UNPKG

@backtrace/react

Version:
1 lines 114 kB
class e{message;get result(){return this._result}status="Ok";_result;constructor(e,t){this.message=t,this.isSubmissionResponse(e)?this.status=e:this._result=e}static OnLimitReached(t="Server"){return new e("Limit reached",`${t} report limit reached`)}static SdkDisabled(){return new e("Disabled SDK")}static Unsupported(t){return new e("Unsupported",t)}static ReportSkipped(){return new e("Report skipped")}static OnInternalServerError(t){return new e("Server Error",t)}static OnInvalidToken(){return new e("Invalid token")}static OnUnknownError(t){return new e("Unknown",t)}static OnNetworkingError(t){return new e("Network Error",t)}static Ok(t){return new e(t)}isSubmissionResponse(e){return"string"==typeof e}}function t(){const e=[],t=[];return function(r,n){if(null===n)return n;const i=typeof n;if("bigint"===i)return n.toString();if("object"!==i)return n;for(;e.length>0&&e[e.length-1]!==this;)e.pop(),t.pop();return e.includes(n)?`[Circular].${t.filter((e=>!!e)).join(".")}.${r}`:(t.push(r),e.push(n),n)}}class r{static SUBMIT_PREFIX="submit.backtrace.io/";static toJsonReportSubmissionUrl(e,t){if(!t)return e;if(e.includes(this.SUBMIT_PREFIX))return e;if(-1!==e.indexOf(t))return e;const r=new URL("/post",e);return r.searchParams.append("format","json"),r.searchParams.append("token",t),r.href}static toPlCrashReporterSubmissionUrl(e){return this.changeSubmissionFormat(e,"plcrash")}static toMinidumpSubmissionUrl(e){return this.changeSubmissionFormat(e,"minidump")}static toAttachmentSubmissionUrl(e,t,r){const n=`object=${t}&attachment_name=${r}`;return e.includes("?")?e+"&"+n:e+"?"+n}static findUniverse(e){const t=e.indexOf(this.SUBMIT_PREFIX);if(-1!==t){const r=t+this.SUBMIT_PREFIX.length,n=e.indexOf("/",r);return e.substring(r,n)}const r=e.indexOf(".backtrace.io");if(-1===r)return;let n=e.indexOf("://");-1===n?n=0:n+=3;const i=e.substring(n,r),s=i.indexOf(".");return-1===s?i:i.substring(0,s)}static findToken(e){if(-1!==e.indexOf(this.SUBMIT_PREFIX)){const t=e.split("/");return t[t.length-2]??null}return new URL(e).searchParams.get("token")}static changeSubmissionFormat(e,t){const r=e.indexOf(this.SUBMIT_PREFIX);if(-1!==r){const n=e.indexOf("?"),i=-1===n?"":e.substring(n),s=e.substring(r+this.SUBMIT_PREFIX.length,-1===n?void 0:n).split("/"),o=3;return s.length<o?e:(s[2]=t,e.substring(0,r+this.SUBMIT_PREFIX.length)+s.join("/")+i)}{const r=new URL(e);return r.searchParams.set("format",t),r.href}}}class n{_requestHandler;_submissionUrl;constructor(e,t){this._requestHandler=t,this._submissionUrl=r.toJsonReportSubmissionUrl(e.url,e.token)}send(e,r,n){const i=JSON.stringify(e,t());return this._requestHandler.postError(this._submissionUrl,i,r,n)}async sendAttachment(t,n,i){return this._requestHandler.postAttachment?await this._requestHandler.postAttachment(r.toAttachmentSubmissionUrl(this._submissionUrl,t,n.name),n,i):e.Unsupported("postAttachment is not implemented")}}class i{static isConnectionError(e){const t=e;return"ETIMEDOUT"===t.code||"ECONNRESET"===t.code||"ECONNABORTED"===t.code}}class s{static generateSummedEventsUrl(e,t,r){const n=this.findSubmissionInformation(t,r);if(n)return this.generateEventsServiceUrl(e,"summed-events",n.universe,n.token)}static generateUniqueEventsUrl(e,t,r){const n=this.findSubmissionInformation(t,r);if(n)return this.generateEventsServiceUrl(e,"unique-events",n.universe,n.token)}static generateEventsServiceUrl(e,t,r,n){return new URL(`/api/${t}/submit?universe=${r}&token=${n}`,e).toString()}static findSubmissionInformation(e,t){const n=r.findUniverse(e);if(n&&(t=t??r.findToken(e)))return{universe:n,token:t}}}class o{_requestHandler;_summedMetricsSubmissionUrl;_uniqueMetricsSubmissionUrl;_requestBacktraceReportSubmission;constructor(e,t){this._requestHandler=t,this._summedMetricsSubmissionUrl=s.generateSummedEventsUrl(e.metrics?.url??"https://events.backtrace.io",e.url,e.token),this._uniqueMetricsSubmissionUrl=s.generateUniqueEventsUrl(e.metrics?.url??"https://events.backtrace.io",e.url,e.token),this._requestBacktraceReportSubmission=e.requestBacktraceReportSubmission??new n({url:e.url},this._requestHandler)}sendReport(e,t,r){return this._requestBacktraceReportSubmission.send(e,t,r)}sendAttachment(e,t,r){return this._requestBacktraceReportSubmission.sendAttachment(e,t,r)}sendUniqueMetrics(e,t){if(!this._uniqueMetricsSubmissionUrl)throw new Error("Unique metrics URL is not available.");return this._requestHandler.post(this._uniqueMetricsSubmissionUrl,JSON.stringify(e),t)}sendSummedMetrics(e,t){if(!this._summedMetricsSubmissionUrl)throw new Error("Summed metrics URL is not available.");return this._requestHandler.post(this._summedMetricsSubmissionUrl,JSON.stringify(e),t)}}class a{_callbacks={};on(e,t){return this.addCallback(e,{callback:t}),this}once(e,t){return this.addCallback(e,{callback:t,once:!0}),this}off(e,t){return this.removeCallback(e,t),this}emit(e,...t){const r=this._callbacks[e];if(!r||!r.length)return!1;for(const{callback:n,once:i}of[...r]){try{n(...t)}catch{}i&&this.removeCallback(e,n)}return!0}addCallback(e,t){const r=this._callbacks[e];r?r.push(t):this._callbacks[e]=[t]}removeCallback(e,t){const r=this._callbacks[e];if(!r)return;const n=r.findIndex((e=>e.callback===t));-1!==n&&(r.splice(n,1),r.length||delete this._callbacks[e])}}class u{static now(){return Date.now()}static toTimestampInSec(e){return Math.floor(e/1e3)}static convertSecondsToMilliseconds(e){return 1e3*e}}class c{data;attributes;attachments;classifiers=[];annotations={};stackTrace={};message;innerReport=[];timestamp=u.now();skipFrames=0;addStackTrace(e,t,r=""){return this.stackTrace[e]="string"==typeof t?{stack:t,message:r}:t,this}constructor(e,t={},r=[],n={}){this.data=e,this.attributes=t,this.attachments=r,this.skipFrames=n?.skipFrames??0;let i="Exception";e instanceof Error?(this.message=this.generateErrorMessage(e.message),this.annotations.error={...e,message:this.message,name:e.name,stack:e.stack},this.classifiers=[e.name],this.stackTrace.main={stack:e.stack??"",message:this.message},e.cause&&this.innerReport.push(e.cause)):(this.message=this.generateErrorMessage(e),this.stackTrace.main={stack:(new Error).stack??"",message:this.message},this.classifiers=["Message"],i="Message",this.skipFrames+=1),this.attributes["error.type"]||(this.attributes["error.type"]=i),this.attributes["error.message"]=this.message,n?.timestamp&&(this.timestamp=n.timestamp),n?.classifiers&&this.classifiers.unshift(...n.classifiers)}generateErrorMessage(e){return"object"==typeof e?JSON.stringify(e,t()):e?.toString()??""}}class l{attachmentEvents;_attachmentProviders=[];constructor(){this.attachmentEvents=new a}add(...e){this.addProviders(...e.map((e=>"function"==typeof e?{type:"dynamic",get:e}:{type:"scoped",get:()=>e})))}addProviders(...e){let t=!1;for(const r of e)if("dynamic"===r.type)this._attachmentProviders.push(r);else{const e=r.get();this._attachmentProviders.push({type:"scoped",get:()=>e}),t=!0}t&&this.attachmentEvents.emit("scoped-attachments-updated",this.get("scoped"))}get(e){const t=[];for(const r of this._attachmentProviders){if(e&&r.type!==e)continue;const n=r.get();n&&(Array.isArray(n)?t.push(...n):t.push(n))}return t}}class d{static build(e){const t={annotations:{},attributes:{}};if(!e)return t;for(const r in e){const n=e[r];if(null!=n)switch(typeof n){case"object":t.annotations[r]=n;break;case"bigint":t.attributes[r]=n.toString();break;default:t.attributes[r]=n}else t.attributes[r]=n}return t}}class h{attributeEvents;_attributeProviders=[];constructor(e){this.attributeEvents=new a;for(const t of e)this.addProvider(t)}add(e){"function"==typeof e?this.addProvider({type:"dynamic",get:e}):this.addProvider({type:"scoped",get:()=>e})}addProvider(e){if("dynamic"!==e.type){const t=e.get();this._attributeProviders.push({type:"scoped",get:()=>t}),this.attributeEvents.emit("scoped-attributes-updated",this.get("scoped"))}else this._attributeProviders.push(e)}get(e){const t={annotations:{},attributes:{}};for(const r of this._attributeProviders){if(e&&r.type!=e)continue;const n=d.build(r.get());t.attributes={...t.attributes,...n.attributes},t.annotations={...t.annotations,...n.annotations}}return t}}class p{_sdkName;_sdkVersion;_sessionId;constructor(e,t,r){this._sdkName=e,this._sdkVersion=t,this._sessionId=r}get type(){return"scoped"}get(){return{"application.session":this._sessionId,"backtrace.agent":this._sdkName,"backtrace.version":this._sdkVersion}}}class f{type;_source;constructor(e){this._source="function"==typeof e?e:()=>e,this.type="function"==typeof e?"dynamic":"scoped"}get(){return this._source()}}function m(e){return e.toString().length}const b=e=>function(e){return JSON.stringify(e).length}(e),g=m,v=m,_=0,y=0,w=e=>e?4:5,S=0,k=4;const E=(e,t)=>{const r=Object.entries(e);let n=0,i=0;for(const[s,o]of r){const r=T(e,s,o,t);0!==r&&(n++,i+=I(s)+r+1)}return 2+Math.max(0,n-1)+i};function I(e){if(null===e)return k+2;if(void 0===e)return 11;switch(typeof e){case"string":return b(e);case"number":return g(e)+2;case"boolean":return w(e)+2;case"symbol":return _;default:return b(e.toString())}}function T(e,t,r,n){if(r&&"object"==typeof r&&"toJSON"in r&&"function"==typeof r.toJSON&&(r=r.toJSON()),null===(r=n?n.call(e,t,r):r))return k;if(void 0===r)return S;if(Array.isArray(r))return function(e,t){const r=e.length-1;let n=0;for(let r=0;r<e.length;r++){const i=e[r];switch(typeof i){case"function":case"symbol":case"undefined":n+=k;break;default:n+=T(e,r.toString(),i,t)}}return 2+r+n}(r,n);switch(typeof r){case"bigint":return v(r);case"boolean":return w(r);case"function":return y;case"number":return g(r);case"object":return E(r,n);case"string":return b(r);case"symbol":return _;case"undefined":return S}return 0}function x(e,t){return T(void 0,"",e,t)}function O(e,t){if(!(t<1/0))return e;if(t<0)return"<removed>";const r=e=>"object"==typeof e&&e?O(e,t-1):e,n={};for(const t in e){const i=e[t];Array.isArray(i)?n[t]=i.map(r):n[t]=r(i)}return n}function R(){const e=(r=t(),function(...e){let t="";for(const n of e)t+="object"==typeof n?JSON.stringify(n,r):n?.toString();return t});var r;try{return require("util").format??e}catch{return e}}var P;!function(e){e[e.Verbose=1]="Verbose",e[e.Debug=2]="Debug",e[e.Info=4]="Info",e[e.Warning=8]="Warning",e[e.Error=16]="Error"}(P||(P={}));var C;!function(e){e[e.Manual=1]="Manual",e[e.Log=2]="Log",e[e.Navigation=4]="Navigation",e[e.Http=8]="Http",e[e.System=16]="System",e[e.User=32]="User",e[e.Configuration=64]="Configuration"}(C||(C={}));class A{_events={};_formatter;start(e){(e.breadcrumbsType&C.Log)===C.Log&&(this._formatter=R(),this.bindToConsoleMethod("log",P.Info,e),this.bindToConsoleMethod("warn",P.Warning,e),this.bindToConsoleMethod("error",P.Error,e),this.bindToConsoleMethod("debug",P.Debug,e),this.bindToConsoleMethod("trace",P.Verbose,e))}dispose(){for(const e in this._events){const t=this._events[e];console[e]=t}}bindToConsoleMethod(e,t,r){const n=console[e];console[e]=(...e)=>{n(...e);const i=this._formatter(...e);r.addBreadcrumb(i,t,C.Log)},this._events[e]=n}}class M{capacity;_array;_headConstraint;_lengthConstraint;_head=0;_length=0;get head(){return this._head}set head(e){this._head=this._headConstraint(e)}get length(){return this._length}set length(e){this._length=this._lengthConstraint(e)}get start(){return this._headConstraint(this.head-this.length)}constructor(e,t){var r,n;this.capacity=e,this._array=new Array(e),this._headConstraint=(r=0,n=e,function(e){const t=n-r;let i;return e<r?(i=n-(r-e)%t,i===n&&(i=r)):e>=n?(i=r+(e-n)%t,i===n&&(i=r)):i=e,i}),this._lengthConstraint=function(e,t){return function(r){return Math.max(e,Math.min(r,t))}}(0,e),t&&this.push(...t)}add(e){return this.pushOne(e)}push(...e){for(const t of e)this.pushOne(t);return this.length}pop(){this.head--;const e=this._array[this.head];return this._array[this.head]=void 0,this.length--,e}shift(){const e=this._array[this.start];return this._array[this.start]=void 0,this.length--,e}at(e){return this._array[this.index(e)]}*values(){for(let e=0;e<this.length;e++){const t=this.index(e);yield this._array[t]}}*keys(){for(let e=0;e<this.length;e++)yield e}*entries(){for(let e=0;e<this.length;e++){const t=this.index(e);yield[e,this._array[t]]}}[Symbol.iterator](){return this.values()}pushOne(e){this._array[this.head]=e,this.head++,this.length++}index(e){if(!this.length)return this._headConstraint(e);const t=e%this.length+this.start;return this._headConstraint(t)}}class N{_limits;get lastBreadcrumbId(){return this._lastBreadcrumbId}name="bt-breadcrumbs-0";_lastBreadcrumbId=u.toTimestampInSec(u.now());_breadcrumbs;_breadcrumbSizes;constructor(e){this._limits=e,this._breadcrumbs=new M(e.maximumBreadcrumbs??100),this._breadcrumbSizes=new M(this._breadcrumbs.capacity)}getAttachments(){return[this]}getAttachmentProviders(){return[{get:()=>this,type:"scoped"}]}static factory({limits:e}){return new N(e)}get(){return JSON.stringify([...this._breadcrumbs],t())}add(e){this._lastBreadcrumbId++;const r=this._lastBreadcrumbId,n={id:r,message:e.message,timestamp:u.now(),type:C[e.type].toLowerCase(),level:P[e.level].toLowerCase()};if(e.attributes&&(n.attributes=e.attributes),this._breadcrumbs.add(n),this._limits.maximumTotalBreadcrumbsSize){const e=x(n,t());this._breadcrumbSizes.add(e);let r=this.totalSize();for(;r>this._limits.maximumTotalBreadcrumbsSize;){this._breadcrumbs.shift();r-=(this._breadcrumbSizes.shift()??0)+1}}return r}totalSize(){let e=0;for(const t of this._breadcrumbSizes)e+=t;return e+Math.max(0,this._breadcrumbSizes.length-1)+2}}const U="breadcrumbs.lastId",L=(e,t)=>!1===e?void 0:void 0!==e?e:t;class D{breadcrumbsType;logLevel;_enabled=!1;_limits;_eventSubscribers=[new A];_interceptor;_storage;constructor(e,t){this._limits={maximumBreadcrumbs:L(e?.maximumBreadcrumbs,100),maximumAttributesDepth:L(e?.maximumAttributesDepth,2),maximumBreadcrumbMessageLength:L(e?.maximumBreadcrumbMessageLength,255),maximumBreadcrumbSize:L(e?.maximumBreadcrumbSize,65536),maximumTotalBreadcrumbsSize:L(e?.maximumTotalBreadcrumbsSize,1048576)},this.breadcrumbsType=e?.eventType??127,this.logLevel=e?.logLevel??31,this._storage=(t?.storage??N.factory)({limits:this._limits}),this._interceptor=e?.intercept,t?.subscribers&&this._eventSubscribers.push(...t.subscribers)}addEventSubscriber(e){this._enabled&&e.start(this),this._eventSubscribers.push(e)}setStorage(e){this._storage="function"==typeof e?e({limits:this._limits}):e}dispose(){this._enabled=!1;for(const e of this._eventSubscribers)e.dispose()}bind({client:e,attachmentManager:t}){this._storage.getAttachmentProviders?t.addProviders(...this._storage.getAttachmentProviders()):t.add(...this._storage.getAttachments()),e.addAttribute((()=>({[U]:this._storage.lastBreadcrumbId}))),e.on("before-skip",(e=>this.logReport(e)))}initialize(){if(!this._enabled){for(const e of this._eventSubscribers)e.start(this);this._enabled=!0}}verbose(e,t){return this.log(e,P.Verbose,t)}debug(e,t){return this.log(e,P.Debug,t)}info(e,t){return this.log(e,P.Info,t)}warn(e,t){return this.log(e,P.Warning,t)}error(e,t){return this.log(e,P.Error,t)}log(e,t,r){return this.addBreadcrumb(e,t,C.Manual,r)}logReport(e){const t=e.data instanceof Error?P.Error:P.Warning;return this.addBreadcrumb(e.message,t,C.System)}addBreadcrumb(e,r,n,i){if(!this._enabled)return!1;let s,o={message:this.prepareBreadcrumbMessage(e),level:r,type:n,attributes:i};if(this._interceptor){const e=this._interceptor(o);if(!e)return!1;o=e}if((this.logLevel&o.level)!==r)return!1;if((this.breadcrumbsType&o.type)!==n)return!1;if(void 0!==this._limits.maximumBreadcrumbMessageLength&&(o.message=o.message.substring(0,this._limits.maximumBreadcrumbMessageLength)),s=void 0!==this._limits.maximumAttributesDepth&&o.attributes?{...o,attributes:O(o.attributes,this._limits.maximumAttributesDepth)}:o,void 0!==this._limits.maximumBreadcrumbSize){if(x(s,t())>this._limits.maximumBreadcrumbSize)return!1}return void 0!==this._storage.add(s)}prepareBreadcrumbMessage(e){if(null==e)return"";switch(typeof e){case"string":return e;case"object":return JSON.stringify(e,t());default:return e.toString()}}}const j="unknown",F="anonymous";class B{addressSeparator;get engine(){return"v8"}constructor(e=""){this.addressSeparator=e}convert(e,t){const r=[];let n=e.split("\n");const i=t.split("\n");n=-1!==n[0].indexOf(i[0])?n.slice(i.length):n.slice(1);for(const e of n){const t=e.trim();if(!t)continue;const n=this.parseFrame(t);r.push(n)}return r}parseFrame(e){const t="at ";if(!e.startsWith(t))return{funcName:e,library:j};const r="async ";let n=(e=e.substring(e.indexOf(t)+3)).indexOf(" (");if(-1===n)return e.startsWith(r)&&(e=e.substring(6)),{funcName:F,...this.parseSourceCodeInformation(e)};let i=e.substring(n+2-1,e.length);const s="(<anonymous>)";i.startsWith(s)&&(n+=14,i=i.substring(13)),i=i.startsWith(` ${t}`)?i.substring(4):i.substring(1,i.length-1);let o=e.substring(0,n);return o.startsWith(r)&&(o=o.substring(6)),{funcName:o,...this.parseSourceCodeInformation(i)}}parseSourceCodeInformation(e){if(e.startsWith("eval"))return this.extractEvalInformation(e);this.addressSeparator&&e.startsWith(this.addressSeparator)&&(e=e.substring(this.addressSeparator.length).trimStart());const t=e.split(":"),r=parseInt(t[t.length-1]),n=parseInt(t[t.length-2]);return{library:t.slice(0,t.length-2).join(":"),column:isNaN(r)?void 0:r,line:isNaN(n)?void 0:n}}extractEvalInformation(e){const t=e.indexOf("("),r=e.indexOf(")");if(-1===t||-1===r||t>r)return{library:j};const n=e.substring(t+1,r);return this.parseSourceCodeInformation(n)}}class q{static uuid(){const e=[...new Array(16)].map((()=>Math.floor(256*Math.random())));return e[6]=15&e[6]|64,e[8]=63&e[8]|128,e.slice(0,4).map((e=>e.toString(16).padStart(2,"0"))).join("")+"-"+e.slice(4,6).map((e=>e.toString(16).padStart(2,"0"))).join("")+"-"+e.slice(6,8).map((e=>e.toString(16).padStart(2,"0"))).join("")+"-"+e.slice(8,10).map((e=>e.toString(16).padStart(2,"0"))).join("")+"-"+e.slice(10,16).map((e=>e.toString(16).padStart(2,"0"))).join("")}}class ${_sdkOptions;_stackTraceConverter;_attributeManager;_debugIdProvider;MAIN_THREAD_NAME="main";constructor(e,t,r,n){this._sdkOptions=e,this._stackTraceConverter=t,this._attributeManager=r,this._debugIdProvider=n}build(e){const{annotations:t,attributes:r}=this._attributeManager.get(),n=d.build(e.attributes),{threads:i,detectedDebugIdentifier:s}=this.getThreads(e),o={uuid:q.uuid(),timestamp:u.toTimestampInSec(e.timestamp),agent:this._sdkOptions.agent,agentVersion:this._sdkOptions.agentVersion,lang:this._sdkOptions.langName,langVersion:this._sdkOptions.langVersion,classifiers:e.classifiers,mainThread:this.MAIN_THREAD_NAME,threads:i,annotations:{...t,...n.annotations,...e.annotations},attributes:{...r,...n.attributes}};return s&&(o.symbolication="sourcemap"),o}getThreads(e){const t={};let r=!1;for(const[n,i]of Object.entries(e.stackTrace)){let s;if(Array.isArray(i))s=i;else{const{message:e,stack:t}=i;s=this._stackTraceConverter.convert(t,e)}n===this.MAIN_THREAD_NAME&&e.skipFrames>0&&s.splice(0,e.skipFrames);for(const e of s){const t=this._debugIdProvider.getDebugId(e.library);t&&(r=!0,e.debug_identifier=t)}t[n]={fault:n===this.MAIN_THREAD_NAME,name:n,stack:s}}return{threads:t,detectedDebugIdentifier:r}}}class H extends Error{constructor(e){super(e??"Operation cancelled.")}}const V=(z="AbortController","undefined"!=typeof window?window[z]:"undefined"!=typeof global?global[z]:"undefined"!=typeof self?self[z]:void 0);var z;class W{_listeners={};_events=new a;addEventListener(e,t,r){e in this._listeners||(this._listeners[e]=[]);const n=e=>"object"==typeof t?t.handleEvent.call(this,e):t.call(this,e),{once:i,signal:s}="object"==typeof r?r:{};if(i?this._events.once(e,n):this._events.on(e,n),s){const r=()=>this.removeEventListener(e,t);s.addEventListener(e,r,{once:!0})}this._listeners[e].push({callback:n,listener:t,options:r})}removeEventListener(e,t){if(!(e in this._listeners))return;const r=this._listeners[e],n=r.filter((e=>e.listener===t));for(const t of n){this._events.off(e,t.callback);const n=r.indexOf(t);r.splice(n,1)}}dispatchEvent(e){return this._events.emit(e.type,e),!e.defaultPrevented}}class Q extends W{aborted=!1;onabort=null;reason;constructor(){super(),Object.defineProperty(this,"aborted",{writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(this,"onabort",{writable:!0,configurable:!0,enumerable:!1}),Object.defineProperty(this,"reason",{writable:!0,configurable:!0,enumerable:!1})}toString(){return"[object AbortSignal]"}throwIfAborted(){if(this.aborted)throw this.reason}dispatchEvent(e){return"abort"===e.type&&(this.aborted=!0,"function"==typeof this.onabort&&this.onabort.call(this,e)),super.dispatchEvent(e)}any(e){return G(...e)}}let J=class{signal;constructor(){this.signal=new Q,Object.defineProperty(this,"signal",{configurable:!0,enumerable:!1})}abort(e){let t;try{t=new Event("abort")}catch(e){if("undefined"!=typeof document){const e=document;!e.createEvent&&e.createEventObject?(t=e.createEventObject(),t.type="abort"):(t=document.createEvent("Event"),t.initEvent("abort",!1,!1))}else t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(void 0===r)if("undefined"==typeof document)r=new H("This operation was aborted");else try{r=new DOMException("signal is aborted without reason")}catch(e){r=new H("This operation was aborted")}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};function X(){return V?new V:new J}function G(...e){const t=X();function r(){for(const t of e)t&&t.removeEventListener("abort",n)}function n(){t.abort(),r()}for(const t of e)if(t){if(t.aborted){n();break}t.addEventListener("abort",n)}return t.signal.dispose=r,t.signal}function Y(e){e&&"number"!=typeof e&&e.unref()}"undefined"!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]="AbortController",Q.prototype[Symbol.toStringTag]="AbortSignal");const K="bt-session",Z=e=>!!e;class ee{_fileSystem;_directory;sessionId;_maxPreviousLockedSessions;_lockable;marker;_events=new a;_escapedSessionId;_locks=new Set;_previousSession;_cleared=!1;constructor(e,t,r,n=1,i=!0){this._fileSystem=e,this._directory=t,this.sessionId=r,this._maxPreviousLockedSessions=n,this._lockable=i,this._escapedSessionId=this.escapeFileName(r.id),this.marker=this.getFileName(K)}initialize(){return this.createSessionMarker()}getPreviousSession(){if(this._previousSession)return this._previousSession;const e=this.readDirectoryFiles();if(!e.length)return;const t=e.filter((e=>e.startsWith(K))).map((e=>this.getFileSession(e))).filter(Z).sort(((e,t)=>t.sessionId.timestamp-e.sessionId.timestamp)),r=t.find((e=>this.sessionIdEquals(e.sessionId,this.sessionId))),n=r?t.filter((({sessionId:e})=>r.sessionId.timestamp>e.timestamp))[0]:t[0];return n?this._previousSession=new ee(this._fileSystem,this._directory,n.sessionId,this._maxPreviousLockedSessions-1,this._maxPreviousLockedSessions>0):void 0}getSessionWithId(e){let t=this;for(;t&&this.sessionIdEquals(t.sessionId,e);)t=t.getPreviousSession();return t}getPreviousSessions(e=1/0){const t=[];let r=this.getPreviousSession();for(;r&&e>0;)t.push(r),e--,r=r.getPreviousSession();return t}lockPreviousSessions(e){e=e??q.uuid();for(const t of this.getPreviousSessions(this._maxPreviousLockedSessions))t.lock(e);return e}unlockPreviousSessions(e){for(const t of this.getPreviousSessions(this._maxPreviousLockedSessions))t.unlock(e)}clearPreviousSessions(){for(const e of this.getPreviousSessions())e.clearSession()}getFileName(e){return this.throwIfCleared(),this._directory+"/"+`${this.escapeFileName(e)}_${this._escapedSessionId}_${this.sessionId.timestamp}`}getSessionFiles(){this.throwIfCleared();return this.readDirectoryFiles().map((e=>this.getFileSession(e))).filter(Z).filter((({sessionId:e})=>this.sessionIdEquals(e,this.sessionId))).map((({file:e})=>this._directory+"/"+e))}clearSession(){if(this._locks.size>0)this._events.once("unlocked",(()=>this.clearSession()));else if(!this._cleared)try{const e=this.getSessionFiles();for(const t of e)this._fileSystem.unlinkSync(t)}catch{}finally{this._cleared=!0}}lock(e){if(!this._cleared&&this._lockable)return e=e??q.uuid(),this._locks.add(e),e}unlock(e){this._locks.delete(e),0===this._locks.size&&this._events.emit("unlocked")}getFileSession(e){const[t,r]=this.splitByOneChar(e,"_").slice(-2),n=parseInt(r);if(!isNaN(n))return{file:e,escapedSessionId:t,sessionId:{timestamp:n,id:this.unescapeFileName(t)}}}readDirectoryFiles(){try{return this._fileSystem.readDirSync(this._directory)}catch{return[]}}createSessionMarker(){this._fileSystem.writeFileSync(this.marker,"")}escapeFileName(e){return e.replace(/_/g,"__")}unescapeFileName(e){return e.replace(/__/g,"_")}splitByOneChar(e,t){const r=[];let n=0,i=e.indexOf(t);for(;-1!==i;)e[i+1]===t?i=e.indexOf(t,i+2):(r.push(e.substring(n,i)),n=i+1,i=e.indexOf(t,n));return r.push(e.substring(n)),r}throwIfCleared(){if(this._cleared)throw new Error("This session files are cleared.")}sessionIdEquals(e,t){return e.id===t.id&&e.timestamp===t.timestamp}static isValidSessionId(e){return"object"==typeof e&&!!e&&"id"in e&&"timestamp"in e&&"string"==typeof e.id&&"number"==typeof e.timestamp}}class te{bucketCount;_records;_recordBuckets={};constructor(e=3){this.bucketCount=e,this._records=[],this._recordBuckets={}}find(e){return this._records.find(e)}add(e){void 0===this._recordBuckets[e.id]?(this._records.push(e),this._recordBuckets[e.id]=0):this._recordBuckets[e.id]=0}get(){return this._records.map((e=>({...e})))}getBucket(e){const t=[];for(const r of this._records)this._recordBuckets[r.id]===e&&t.push(r);return t}count(){return this._records.length}countByType(){return this._records.reduce(((e,t)=>(e[t.type]++,e)),{})}remove(e){const t="string"==typeof e?e:e.id,r=this._records.findIndex((e=>e.id===t));-1!==r&&(this._records.splice(r,1),delete this._recordBuckets[t])}increaseBucket(e){for(const[t,r]of Object.entries(this._recordBuckets)){if(r<e)continue;const n=r+1;n>=this.bucketCount&&this.remove(t),this._recordBuckets[t]=n}}load(e){for(const t of e)this.add(t)}dropOverLimits(e){const t={...e},r=[];for(let e=this._records.length-1;e>=0;e--){const n=this._records[e];0===t[n.type]?(this.remove(n),r.push(n)):t[n.type]--}return r}}class re extends a{_options;_storageProvider;_requestHandler;_sessionFiles;get enabled(){return this._enabled}_abortController=X();_databaseRecordContext;_storageProviders=[];_recordLimits;_retryInterval;_intervalId;_enabled=!1;constructor(e,t,r,n){super(),this._options=e,this._storageProvider=t,this._requestHandler=r,this._sessionFiles=n,this._databaseRecordContext=new te(this._options?.maximumRetries),this._recordLimits={report:this._options?.maximumNumberOfRecords??8,attachment:this._options?.maximumNumberOfAttachmentRecords??10},this._retryInterval=this._options?.retryInterval??6e4}initialize(){if(this._enabled)return this._enabled;if(!1===this._options?.enable)return!1;if(!this._storageProvider.start())return!1;const e=this._sessionFiles?.lockPreviousSessions();return this.loadReports().then((()=>{this.setupDatabaseAutoSend()})).finally((()=>e&&this._sessionFiles?.unlockPreviousSessions(e))),this._enabled=!0,!0}bind({client:e}){this._enabled||!1!==this._options?.enable&&(e.on("before-send",((e,t,r)=>{const n=this.add(t,r);n&&!n.locked&&(n.locked=!0)})),e.on("after-send",((e,t,r,n)=>{const i=this._databaseRecordContext.find((e=>"report"===e.type&&e.data.uuid===t.uuid));i&&(i.locked=!1,"Ok"===n.status&&(this.remove(i),this._sessionFiles?.unlockPreviousSessions(i.id)))})))}add(e,t){if(!this._enabled)return;const r={type:"report",data:e,timestamp:u.now(),id:q.uuid(),locked:!1,attachments:t,sessionId:this._sessionFiles?.sessionId};this.prepareDatabase([r]);return this._storageProvider.add(r)?(this._databaseRecordContext.add(r),this.lockSessionWithRecord(r),this.emit("added",r),r):void 0}addAttachment(e,t,r){if(!this._enabled)return;const n={type:"attachment",timestamp:u.now(),id:q.uuid(),rxid:e,locked:!1,attachment:t,sessionId:r};this.prepareDatabase([n]);return this._storageProvider.add(n)?(this._databaseRecordContext.add(n),this.lockSessionWithRecord(n),this.emit("added",n),n):void 0}get(){return this._databaseRecordContext.get()}count(){return this._databaseRecordContext.count()}countByType(){return this._databaseRecordContext.countByType()}dispose(){this._enabled=!1,clearInterval(this._intervalId),this._abortController.abort()}remove(e){if(!this._enabled)return;const t=Array.isArray(e)?e:[e];for(const e of t)this._databaseRecordContext.remove(e),this._storageProvider.delete(e),this._sessionFiles?.unlockPreviousSessions(e.id),this.emit("removed",e)}addStorageProvider(e){if(this._enabled)throw new Error("Cannot add storage provider after the database has been enabled.");this._storageProviders.push(e)}async flush(e){const t=u.now();await this.send(e);const r=this.get().filter((e=>e.timestamp<=t));for(const t of r){if(e?.aborted)return;this.remove(t)}}async send(e){for(let t=0;t<this._databaseRecordContext.bucketCount;t++){const r=[...this._databaseRecordContext.getBucket(t)],n=G(e,this._abortController.signal);try{for(const e of r){if(!this.enabled)return;if(!e.locked)try{e.locked=!0,this.emit("before-send",e);const r="report"===e.type?await this._requestHandler.send(e.data,e.attachments,n):await this._requestHandler.sendAttachment(e.rxid,e.attachment,n);if(this.emit("after-send",e,r),"Ok"===r.status||"Unsupported"===r.status||"Report skipped"===r.status){this.remove(e);continue}return void this._databaseRecordContext.increaseBucket(t)}finally{e.locked=!1}}}finally{n.dispose()}}}prepareDatabase(e){const t={...this._recordLimits};for(const r of e)t[r.type]--;const r=this._databaseRecordContext.dropOverLimits(t);this.remove(r)}async loadReports(){const e=await this._storageProvider.get(),t={attachment:0,report:0},r=[],n=[];for(const i of e)t[i.type]>=this._recordLimits[i.type]?n.push(i):(r.push(i),t[i.type]++);n.length&&this.remove(n),this.prepareDatabase(r),this._databaseRecordContext.load(r);for(const e of r)this.lockSessionWithRecord(e),this.emit("added",e)}async setupDatabaseAutoSend(){if(!this._enabled)return;if(!1===this._options?.autoSend)return;this._intervalId=setInterval((async()=>{await this.send()}),this._retryInterval),Y(this._intervalId),await this.send()}lockSessionWithRecord(e){if(!this._sessionFiles)return;const t=e.sessionId;if(!ee.isValidSessionId(t))return void this._sessionFiles.lockPreviousSessions(e.id);const r=this._sessionFiles.getSessionWithId(t);r?.lock(e.id)}}function ne(e){return"filePath"in e&&"string"==typeof e.filePath}class ie{type="attachment";id;rxid;timestamp;attachment;sessionId;locked;constructor(e){this.attachment=e.attachment,this.id=e.id,this.timestamp=e.timestamp,this.rxid=e.rxid,this.sessionId=e.sessionId,this.locked=!1}static fromRecord(e){return new ie(e)}static fromJson(e,t){try{const r="string"==typeof e?JSON.parse(e):e;if(!ne(r.attachment))return;if(!t.existsSync(r.attachment.filePath))return;const n=t.createAttachment(r.attachment.filePath,r.attachment.name);return new ie({...r,attachment:n})}catch{return}}}class se{attachments;type="report";data;id;timestamp;sessionId;locked;constructor(e,t){this.attachments=t,this.data=e.data,this.id=e.id,this.timestamp=e.timestamp,this.sessionId=e.sessionId,this.locked=!1}static fromRecord(e){return new se(e,e.attachments.filter(ne))}static fromJson(e,t){try{const r="string"==typeof e?JSON.parse(e):e,n=r.attachments?r.attachments.filter(ne).map((e=>t.createAttachment(e.filePath,e.name))):[];return new se(r,n)}catch{return}}}const oe={fromRecord(e){switch(e.type){case"attachment":return ie.fromRecord(e);case"report":return se.fromRecord(e);default:throw new Error("unknown record type")}},fromJson(e,t){try{const r=JSON.parse(e);switch(r.type){case"attachment":return ie.fromJson(r,t);case"report":return se.fromJson(r,t);default:return}}catch{return}}};class ae{_fileSystem;_path;_enabled=!0;RECORD_SUFFIX="-record.json";constructor(e,t){this._fileSystem=e,this._path=t}static createIfValid(e,t){if(t&&t.enable){if(t.enable&&!t.path)throw new Error("Missing mandatory path to the database. Please define the database.path option in the configuration.");return new ae(e,t.path)}}start(){return!1!==this._enabled}delete(e){const t=this.getRecordPath(e.id);return this.unlinkRecord(t)}add(e){const r=this.getRecordPath(e.id);try{return this._fileSystem.writeFileSync(r,JSON.stringify(oe.fromRecord(e),t())),!0}catch{return!1}}async get(){const e=(await this._fileSystem.readDir(this._path)).filter((e=>e.endsWith(this.RECORD_SUFFIX))).map((e=>this._path+"/"+e)),t=[];for(const r of e)try{const e=await this._fileSystem.readFile(r),n=oe.fromJson(e,this._fileSystem);if(!n){await this._fileSystem.unlink(r);continue}t.push(n)}catch{await this._fileSystem.unlink(r)}return t}unlinkRecord(e){if(!this._fileSystem.existsSync(e))return!1;try{return this._fileSystem.unlinkSync(e),!0}catch{return!1}}getRecordPath(e){return this._path+"/"+`${e}${this.RECORD_SUFFIX}`}}class ue{metricGroupName;metricGroupValue;attributes;id=q.uuid();constructor(e,t,r={}){this.metricGroupName=e,this.metricGroupValue=t,this.attributes=r}toJSON(){return{timestamp:u.toTimestampInSec(u.now()),attributes:this.attributes,[this.metricGroupName]:this.metricGroupValue}}}class ce extends ue{constructor(e,t={}){super("metric_group",e,t)}}class le extends ue{constructor(e){super("unique",["guid"],e)}}class de{_options;_sessionProvider;_attributeManager;_summedEventsSubmissionQueue;_uniqueEventsSubmissionQueue;get sessionId(){return this._sessionProvider.sessionId}DEFAULT_UPDATE_INTERVAL=u.convertSecondsToMilliseconds(1800);DEFAULT_SERVER_URL="https://events.backtrace.io";metricsHost;_updateInterval;_updateIntervalId;_abortController;constructor(e,t,r,n,i){this._options=e,this._sessionProvider=t,this._attributeManager=r,this._summedEventsSubmissionQueue=n,this._uniqueEventsSubmissionQueue=i,this.metricsHost=this._options.metricsSubmissionUrl??this.DEFAULT_SERVER_URL,this._updateInterval=this._options.autoSendInterval??this.DEFAULT_UPDATE_INTERVAL,this._abortController=X()}initialize(){this._sessionProvider.newSession&&(this.addSummedEvent("Application Launches"),this.handleAbort((()=>this.send(this._abortController.signal))),0!==this._updateInterval&&(this._updateIntervalId=setInterval((()=>{this.handleAbort((()=>this.send(this._abortController.signal)))}),this._updateInterval),Y(this._updateIntervalId)))}count(){return this._summedEventsSubmissionQueue?.total??0+this._uniqueEventsSubmissionQueue?.total??0}addSummedEvent(e,t={}){if(!e)return!1;const r=this.convertAttributes({...this._attributeManager.get().attributes,...d.build(t??{}).attributes});return this._summedEventsSubmissionQueue.add(new ce(e,r)),!0}async send(e){return!!this._sessionProvider.shouldSend()&&(await Promise.all([this.sendUniqueEvent(e),this._summedEventsSubmissionQueue.send(e)]),this._sessionProvider.afterMetricsSubmission(),!0)}dispose(){this._abortController.abort(),this._updateIntervalId&&clearInterval(this._updateIntervalId),this._uniqueEventsSubmissionQueue.dispose&&this._uniqueEventsSubmissionQueue.dispose(),this._summedEventsSubmissionQueue.dispose&&this._summedEventsSubmissionQueue.dispose()}async sendUniqueEvent(e){const{attributes:t}=this._attributeManager.get();this._uniqueEventsSubmissionQueue.add(new le(this.convertAttributes(t))),await this._uniqueEventsSubmissionQueue.send(e)}convertAttributes(e){return Object.keys(e).filter((t=>null!=e[t])).reduce(((t,r)=>(t[r]=e[r]?.toString(),t)),{})}async handleAbort(e){try{return await e(),!0}catch(e){if(e instanceof H)return!1;throw e}}}class he{static wait(e,t){return new Promise(((r,n)=>{let i;function s(){clearTimeout(i),n(new H)}if(t?.aborted)return s();i=setTimeout((()=>{t?.removeEventListener("abort",s),r()}),e),t?.addEventListener("abort",s)}))}}class pe{_submissionUrl;_eventName;_requestHandler;_metricMetadata;maximumEvents;get total(){return this._events.length}get submissionUrl(){return this._submissionUrl}DELAY_BETWEEN_REQUESTS=u.convertSecondsToMilliseconds(10);_events=[];_numberOfDroppedRequests=0;_abortController;MAXIMUM_NUMBER_OF_ATTEMPTS=3;constructor(e,t,r,n,i=50){this._submissionUrl=e,this._eventName=t,this._requestHandler=r,this._metricMetadata=n,this.maximumEvents=i,this._abortController=X()}add(e){this._events.push(e),this.reachedLimit()&&this.send()}async send(e){const t=this._events.splice(0),r=G(e,this._abortController.signal);try{return await this.submit(t,r)}finally{r.dispose()}}dispose(){this._abortController.abort()}async submit(e,r){for(let n=0;n<this.MAXIMUM_NUMBER_OF_ATTEMPTS;n++){if("Ok"===(await this._requestHandler.post(this._submissionUrl,JSON.stringify({...this._metricMetadata,[this._eventName]:e,metadata:{dropped_events:this._numberOfDroppedRequests}},t()),r)).status)return void(this._numberOfDroppedRequests=0);this._numberOfDroppedRequests++,await he.wait(2**n*this.DELAY_BETWEEN_REQUESTS,r)}this.returnEventsIfPossible(e)}returnEventsIfPossible(e){this.maximumEvents<this._events.length+e.length||this._events.unshift(...e)}reachedLimit(){return this.maximumEvents===this._events.length&&0!==this.maximumEvents}}class fe{_options;_sessionProvider;_attributeManager;_requestHandler;DEFAULT_UPDATE_INTERVAL=u.convertSecondsToMilliseconds(1800);APPLICATION_VERSION_ATTRIBUTE="application.version";APPLICATION_ATTRIBUTE="application";constructor(e,t,r,n){this._options=e,this._sessionProvider=t,this._attributeManager=r,this._requestHandler=n}build(e,t){const r={...this.optionsWithDefaults(),...this._options.metrics??{}};if(!r.enable)return;const n=this.verifyAttributeSetup();return n&&(e=e??this.createUniqueEventSubmissionQueue(r.metricsSubmissionUrl,n))&&(t=t??this.createSummedEventSubmissionQueue(r.metricsSubmissionUrl,n))?new de(r,this._sessionProvider,this._attributeManager,t,e):void 0}verifyAttributeSetup(){const{attributes:e}=this._attributeManager.get(),t=e[this.APPLICATION_ATTRIBUTE],r=e[this.APPLICATION_VERSION_ATTRIBUTE];if(t&&r)return{application:t,applicationVersion:r}}createUniqueEventSubmissionQueue(e,t){const r=s.generateUniqueEventsUrl(e,this._options.url,this._options.token);if(r)return new pe(r,"unique_events",this._requestHandler,{[this.APPLICATION_ATTRIBUTE]:t.application,appversion:t.applicationVersion},this._options?.metrics?.size)}createSummedEventSubmissionQueue(e,t){const r=s.generateSummedEventsUrl(e,this._options.url,this._options.token);if(r)return new pe(r,"summed_events",this._requestHandler,{[this.APPLICATION_ATTRIBUTE]:t.application,appversion:t.applicationVersion},this._options?.metrics?.size)}optionsWithDefaults(){return{enable:!0,autoSendInterval:this.DEFAULT_UPDATE_INTERVAL,metricsSubmissionUrl:"https://events.backtrace.io",size:50}}}class me{newSession=!0;sessionId=q.uuid();_lastActive=0;get lastActive(){return this._lastActive}afterMetricsSubmission(){this._lastActive=u.now()}shouldSend(){return!0}}class be{MAXIMUM_TIME_IN_QUEUE=6e4;_reportPerMin;_watcherEnable;_reportQueue=[];get enabled(){return this._watcherEnable}constructor(e){if(null==e&&(e=0),e<0)throw new Error("ReportPerMinute argument must be greater or equal to zero");this._reportPerMin=e,this._watcherEnable=e>0}skipReport(){const e=u.now();return!!this._watcherEnable&&(this.clear(e),this._reportQueue.length>=this._reportPerMin||(this._reportQueue.push(e),!1))}clear(e){if(0!==this._reportQueue.length&&!(e-this._reportQueue[0]<this.MAXIMUM_TIME_IN_QUEUE))for(let t=this._reportQueue.length;0!=t;t--)if(e-this._reportQueue[t-1]>this.MAXIMUM_TIME_IN_QUEUE)return void(this._reportQueue=this._reportQueue.slice(t))}}class ge extends a{static _instance;get enabled(){return this._enabled}get sessionId(){return this._sessionProvider.sessionId}get agent(){return this._sdkOptions.agent}get agentVersion(){return this._sdkOptions.agentVersion}get attributes(){return this.attributeManager.get().attributes}get annotations(){return this.attributeManager.get().annotations}get metrics(){return this._modules.get(de)}get breadcrumbs(){return this._modules.get(D)}get database(){return this._modules.get(re)}get attachments(){return this.attachmentManager.get()}get modules(){return this._modules}get sessionFiles(){return this._modules.get(ee)}options;attributeManager;attachmentManager;fileSystem;_modules=new Map;_dataBuilder;_reportSubmission;_rateLimitWatcher;_sessionProvider;_sdkOptions;_requestHandler;_enabled=!1;constructor(e){super(),this.options=e.options,this.fileSystem=e.fileSystem,this._sdkOptions=e.sdkOptions,this._sessionProvider=e.sessionProvider??new me,this._reportSubmission=e.reportSubmission??new n(this.options,e.requestHandler),this._rateLimitWatcher=new be(this.options.rateLimit),this._requestHandler=e.requestHandler;const t=[new p(this.agent,this.agentVersion,this._sessionProvider.sessionId)];e.attributeProviders&&t.push(...e.attributeProviders),this.options.userAttributes&&t.push(new f(this.options.userAttributes)),this.attributeManager=new h(t),this.attachmentManager=new l,this.options.attachments&&this.attachmentManager.add(...this.options.attachments);const r=e.stackTraceConverter??new B;if(this._dataBuilder=new $(this._sdkOptions,r,this.attributeManager,new we(r,e.debugIdMapProvider)),!0===this.options?.database?.enable&&e.fileSystem){const t=ae.createIfValid(e.fileSystem,this.options.database);if(this.fileSystem){const e=new ee(this.fileSystem,this.options.database.path,{id:this.sessionId,timestamp:Date.now()},this.options.database.maximumOldSessions??1);this._modules.set(ee,e)}if(t){const e=new re(this.options.database,t,this._reportSubmission,this.sessionFiles);this._modules.set(re,e)}}const i=new fe(this.options,this._sessionProvider,this.attributeManager,e.requestHandler).build(e.uniqueMetricsQueue,e.summedMetricsQueue);if(i&&this._modules.set(de,i),!1!==this.options.breadcrumbs?.enable){const t=new D(this.options?.breadcrumbs,e.breadcrumbsSetup);this._modules.set(D,t)}if(e.modules)for(const t of e.modules)this.addModule(t)}initialize(){if(this.validateAttributes(),this.fileSystem&&this.options.database?.createDatabaseDirectory){if(!this.options.database.path)throw new Error("Missing mandatory path to the database. Please define the database.path option in the configuration.");this.fileSystem.createDirSync(this.options.database?.path)}for(const e of this._modules.values())e.bind&&e.bind(this.getModuleBindData()),e.initialize&&e.initialize();this.sessionFiles?.clearPreviousSessions(),this._enabled=!0,ge._instance=this}addAttribute(e){this.attributeManager.add(e)}addAttachment(...e){this.attachmentManager.add(...e)}send(t,r,n=[],i){if(!this._enabled)return Promise.resolve(e.SdkDisabled());if(this._rateLimitWatcher.skipReport())return Promise.resolve(e.OnLimitReached("Client"));const s=this.isReport(t)?void 0:r;i=this.isReport(t)?r:i;const o=this.isReport(t)?t:new c(t,s,[],{skipFrames:this.skipFrameOnMessage(t)});if(this.emit("before-skip",o),this.options.skipReport&&this.options.skipReport(o))return Promise.resolve(e.ReportSkipped());const a=this.generateSubmissionData(o);if(!a)return Promise.resolve(e.ReportSkipped());const u=this.generateSubmissionAttachments(o,n);return this.emit("before-send",o,a,u),this._reportSubmission.send(a,u,i).then((e=>(this.emit("after-send",o,a,u,e),e)))}dispose(){this._enabled=!1;for(const e of this._modules.values())e.dispose&&e.dispose();ge.destroy()}addModule(e,t){let r;if("function"==typeof e?r=e:(t=e,r=Object.getPrototypeOf(t)),!t)throw new Error("Module implementation is required.");this._modules.set(r,t),this._enabled&&(t.bind&&t.bind(this.getModuleBindData()),t.initialize&&t.initialize())}generateSubmissionData(e){const t=this._dataBuilder.build(e);return this.options.beforeSend?this.options.beforeSend(t):t}generateSubmissionAttachments(e,t){return[...this.attachmentManager.get(),...e.attachments??[],...t??[]]}skipFrameOnMessage(e){return"string"==typeof e?1:0}isReport(e){return e instanceof c}getModuleBindData(){return{client:this,options:this.options,attributeManager:this.attributeManager,attachmentManager:this.attachmentManager,reportSubmission:this._reportSubmission,requestHandler:this._requestHandler,database:this.database,sessionFiles:this.sessionFiles,fileSystem:this.fileSystem}}static destroy(){this._instance=void 0}validateAttributes(){function e(e){if(!e.application||!e["application.version"])return"application and application.version attributes must be defined."}if(!e(this.attributeManager.get("scoped").attributes))return;const t=e(this.attributeManager.get().attributes);if(t)throw new Error(t)}}class ve{clientSetup;constructor(e){this.clientSetup=e}addAttributeProvider(e){return this.clientSetup.attributeProviders?this.clientSetup.attributeProviders.push(e):this.clientSetup.attributeProviders=[e],this}useBreadcrumbSubscriber(e){return this.clientSetup.breadcrumbsSetup||(this.clientSetup.breadcrumbsSetup={}),this.clientSetup.breadcrumbsSetup.subscribers?this.clientSetup.breadcrumbsSetup.subscribers.push(e):this.clientSetup.breadcrumbsSetup.subscribers=[e],this}useBreadcrumbsStorage(e){return this.clientSetup.breadcrumbsSetup||(this.clientSetup.breadcrumbsSetup={}),this.clientSetup.breadcrumbsSetup.storage="function"==typeof e?e:()=>e,this}useSessionProvider(e){return this.clientSetup.sessionProvider=e,this}useRequestHandler(e){return this.clientSetup.requestHandler=e,this}useStackTraceConverter(e){return this.clientSetup.stackTraceConverter=e,this}useFileSystem(e){return this.clientSetup.fileSystem=e,this}useReportSubmission(e){return this.clientSetup.reportSubmission=e,this}useSummedMetricsQueue(e){return this.clientSetup.summedMetricsQueue=e,this}useUniqueMetricsQueue(e){return this.clientSetup.uniqueMetricsQueue=e,this}useModule(e){return this.clientSetup.modules?this.clientSetup.modules.push(e):this.clientSetup.modules=[e],this}}class _e{name;data;constructor(e,t){this.name=e,this.data=t}get(){return this.data}}class ye{name;data;constructor(e,t){this.name=e,this.data=t}get(){return new Blob([this.data.buffer])}}class we{_stackTraceConverter;_debugIdMapProvider;_fileDebugIds;constructor(e,t){this._stackTraceConverter=e,this._debugIdMapProvider=t,this._fileDebugIds=this.loadDebugIds()}getDebugId(e){const t=this._fileDebugIds[e];return t||(this._fileDebugIds=this.loadDebugIds(),this._fileDebugIds[e])}loadDebugIds(){const e=this._debugIdMapProvider?.getDebugIdMap();if(!e)return{};const t=(new Error).message,r={};for(const[n,i]of Object.entries(e)){const e=this._stackTraceConverter.convert(n,t);if(!e.length)continue;r[e[0].library]=i}return r}}class Se{_variable;constructor(e){this._variable=e}getDebugIdMap(){return this._variable._btDebugIds??{}}}const ke={langName:"js",langVersion:navigator.userAgent,agent:"@backtrace/browser",agentVersion:"0.6.0"};function Ee(e,t,r,n){return new(r||(r=Promise))((function(t,i){function s(e){try{a(n.next(e))}catch(e){i(e)}}function o(e){try{a(n.throw(e))}catch(e){i(e)}}function a(e){var n;e.done?t(e.value):(n=e.value,n instanceof r?n:new r((function(e){e(n)}))).then(s,o)}a((n=n.apply(e,[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class Ie{constructor(e){var t;this.UPLOAD_FILE_NAME="upload_file",this.JSON_HEADERS={"Content-type":"application/json","Transfer-Encoding":"chunked"},this.MULTIPART_HEADERS={"Transfer-Encoding":"chunked"},this._timeout=null!==(t=null==e?void 0:e.timeout)&&void 0!==t?t:15e3}postError(e,t,r,n){return Ee(this,0,void 0,(function*(){const i=0===r.length?t:this.createFormData(t,r);return this.post(e,i,n)}))}post(t,r,n){return Ee(this,0,void 0,(function*(){const s=new AbortController,o=setTimeout((()=>s.abort()),this._timeout),a=G(n,s.signal);try{const n=yield fetch(t,{method:"POST",body:r,headers:"string"==typeof r?this.JSON_HEADERS:this.MULTIPART_HEADERS,signal:a});switch(clearInterval(o),n.status){case 200:{const t=yield n.json();return e.Ok(t)}case 401:case 403:return e.OnInvalidToken();case 429:return e.OnLimitReached();default:return e.OnInternalServerError(n.statusText)}}catch(t){return t instanceof Error?"AbortError"===t.name?e.OnNetworkingError("Timeout"):i.isConnectionError(t)?e.OnNetworkingError(t.message):e.OnUnknownError(t.message):e.OnUnknownError(t)}finally{"dispose"in a&&"function"==typeof a.dispose&&a.dispose()}}))}createFormData(e,t){const r=new FormData;if(r.append(this.UPLOAD_FILE_NAME,e),!t||0===t.length)return r;for(const e of t){const t=e.get();t&&r.append(`attachment_${e.name}`,t)}return r}}class Te extends o{constructor(e){var t;super(e,null!==(t=e.requestHandler)&&void 0!==t?t:new Ie(e.requestHandlerOptions))}}class xe{get lastActive(){return this._lastActive}constructor(){if(this.SESSION_LAST_ACTIVE="backtrace-last-active",this.SESSION_GUID="backtrace-guid",this.newSession=!0,this.sessionId=q.uuid(),this._lastActive=0,!window.localStorage)return;const e=this.readLastActiveTimestamp();if(!e||u.now()-e>xe.PERSISTENCE_INTERVAL)return this.updateLastActiveTimestamp(),void localStorage.setItem(this.SESSION_GUID,this.sessionId);this._lastActive=e,this.newSession=!1,this.sessionId=localStorage.getItem(this.SESSION_GUID)}afterMetricsSubmission(){this.updateLastActiveTimestamp()}shouldSend(){return!1===document.hidden}readLastActiveTimestamp(){const e=localStorage.getItem(this.SESSION_LAST_ACTIVE);if(!e)return;const t=parseInt(e,10);return isNaN(t)?void 0:t}updateLastActiveTimestamp(){this._lastActive=u.now(),localStorage.setItem(this.SESSION_LAST_ACTIVE,this._lastActive.toString(10))}}xe.PERSISTENCE_INTERVAL=u.convertSecondsToMilliseconds(1800);class Oe{get type(){return"scoped"}constructor(e){if(this.APPLICATION_ATTRIBUTE="application",this.APPLICATION_VERSION_ATTRIBUTE="application.version",this._application=e.name,this._applicationVersion=e.version,!this._application||!this._applicationVersion)throw new Error("Missing application/application version information!")}get(){return{[this.APPLICATION_ATTRIBUTE]:this._application,[this.APPLICATION_VERSION_ATTRIBUTE]:this._applicationVersion}}}var Re,Pe,Ce="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Ae={exports:{}};Re=Ae,Pe=Ae.exports,function(e,t){var r="function",n="undefined",i="object",s