UNPKG

@backtrace/browser

Version:
1 lines 79 kB
"use strict";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(s,i){if(null===i)return i;const r=typeof i;if("bigint"===r)return i.toString();if("object"!==r)return i;for(;e.length>0&&e[e.length-1]!==this;)e.pop(),t.pop();return e.includes(i)?`[Circular].${t.filter((e=>!!e)).join(".")}.${s}`:(t.push(s),e.push(i),i)}}class s{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 s=new URL("/post",e);return s.searchParams.append("format","json"),s.searchParams.append("token",t),s.href}static toPlCrashReporterSubmissionUrl(e){return this.changeSubmissionFormat(e,"plcrash")}static toMinidumpSubmissionUrl(e){return this.changeSubmissionFormat(e,"minidump")}static toAttachmentSubmissionUrl(e,t,s){const i=`object=${t}&attachment_name=${s}`;return e.includes("?")?e+"&"+i:e+"?"+i}static findUniverse(e){const t=e.indexOf(this.SUBMIT_PREFIX);if(-1!==t){const s=t+this.SUBMIT_PREFIX.length,i=e.indexOf("/",s);return e.substring(s,i)}const s=e.indexOf(".backtrace.io");if(-1===s)return;let i=e.indexOf("://");-1===i?i=0:i+=3;const r=e.substring(i,s),n=r.indexOf(".");return-1===n?r:r.substring(0,n)}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 s=e.indexOf(this.SUBMIT_PREFIX);if(-1!==s){const i=e.indexOf("?"),r=-1===i?"":e.substring(i),n=e.substring(s+this.SUBMIT_PREFIX.length,-1===i?void 0:i).split("/"),o=3;return n.length<o?e:(n[2]=t,e.substring(0,s+this.SUBMIT_PREFIX.length)+n.join("/")+r)}{const s=new URL(e);return s.searchParams.set("format",t),s.href}}}class i{_requestHandler;_submissionUrl;constructor(e,t){this._requestHandler=t,this._submissionUrl=s.toJsonReportSubmissionUrl(e.url,e.token)}send(e,s,i){const r=JSON.stringify(e,t());return this._requestHandler.postError(this._submissionUrl,r,s,i)}async sendAttachment(t,i,r){return this._requestHandler.postAttachment?await this._requestHandler.postAttachment(s.toAttachmentSubmissionUrl(this._submissionUrl,t,i.name),i,r):e.Unsupported("postAttachment is not implemented")}}class r{static isConnectionError(e){const t=e;return"ETIMEDOUT"===t.code||"ECONNRESET"===t.code||"ECONNABORTED"===t.code}}class n{static generateSummedEventsUrl(e,t,s){const i=this.findSubmissionInformation(t,s);if(i)return this.generateEventsServiceUrl(e,"summed-events",i.universe,i.token)}static generateUniqueEventsUrl(e,t,s){const i=this.findSubmissionInformation(t,s);if(i)return this.generateEventsServiceUrl(e,"unique-events",i.universe,i.token)}static generateEventsServiceUrl(e,t,s,i){return new URL(`/api/${t}/submit?universe=${s}&token=${i}`,e).toString()}static findSubmissionInformation(e,t){const i=s.findUniverse(e);if(i&&(t=t??s.findToken(e)))return{universe:i,token:t}}}class o{_requestHandler;_summedMetricsSubmissionUrl;_uniqueMetricsSubmissionUrl;_requestBacktraceReportSubmission;constructor(e,t){this._requestHandler=t,this._summedMetricsSubmissionUrl=n.generateSummedEventsUrl(e.metrics?.url??"https://events.backtrace.io",e.url,e.token),this._uniqueMetricsSubmissionUrl=n.generateUniqueEventsUrl(e.metrics?.url??"https://events.backtrace.io",e.url,e.token),this._requestBacktraceReportSubmission=e.requestBacktraceReportSubmission??new i({url:e.url},this._requestHandler)}sendReport(e,t,s){return this._requestBacktraceReportSubmission.send(e,t,s)}sendAttachment(e,t,s){return this._requestBacktraceReportSubmission.sendAttachment(e,t,s)}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 s=this._callbacks[e];if(!s||!s.length)return!1;for(const{callback:i,once:r}of[...s]){try{i(...t)}catch{}r&&this.removeCallback(e,i)}return!0}addCallback(e,t){const s=this._callbacks[e];s?s.push(t):this._callbacks[e]=[t]}removeCallback(e,t){const s=this._callbacks[e];if(!s)return;const i=s.findIndex((e=>e.callback===t));-1!==i&&(s.splice(i,1),s.length||delete this._callbacks[e])}}class c{static now(){return Date.now()}static toTimestampInSec(e){return Math.floor(e/1e3)}static convertSecondsToMilliseconds(e){return 1e3*e}}class u{data;attributes;attachments;classifiers=[];annotations={};stackTrace={};message;innerReport=[];timestamp=c.now();skipFrames=0;addStackTrace(e,t,s=""){return this.stackTrace[e]="string"==typeof t?{stack:t,message:s}:t,this}constructor(e,t={},s=[],i={}){this.data=e,this.attributes=t,this.attachments=s,this.skipFrames=i?.skipFrames??0;let r="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"],r="Message",this.skipFrames+=1),this.attributes["error.type"]||(this.attributes["error.type"]=r),this.attributes["error.message"]=this.message,i?.timestamp&&(this.timestamp=i.timestamp),i?.classifiers&&this.classifiers.unshift(...i.classifiers)}generateErrorMessage(e){return"object"==typeof e?JSON.stringify(e,t()):e?.toString()??""}}class d{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 s of e)if("dynamic"===s.type)this._attachmentProviders.push(s);else{const e=s.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 s of this._attachmentProviders){if(e&&s.type!==e)continue;const i=s.get();i&&(Array.isArray(i)?t.push(...i):t.push(i))}return t}}class l{static build(e){const t={annotations:{},attributes:{}};if(!e)return t;for(const s in e){const i=e[s];if(null!=i)switch(typeof i){case"object":t.annotations[s]=i;break;case"bigint":t.attributes[s]=i.toString();break;default:t.attributes[s]=i}else t.attributes[s]=i}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 s of this._attributeProviders){if(e&&s.type!=e)continue;const i=l.build(s.get());t.attributes={...t.attributes,...i.attributes},t.annotations={...t.annotations,...i.annotations}}return t}}class m{_sdkName;_sdkVersion;_sessionId;constructor(e,t,s){this._sdkName=e,this._sdkVersion=t,this._sessionId=s}get type(){return"scoped"}get(){return{"application.session":this._sessionId,"backtrace.agent":this._sdkName,"backtrace.version":this._sdkVersion}}}class b{type;_source;constructor(e){this._source="function"==typeof e?e:()=>e,this.type="function"==typeof e?"dynamic":"scoped"}get(){return this._source()}}function p(e){return e.toString().length}const g=e=>function(e){return JSON.stringify(e).length}(e),f=p,_=p,v=0,w=0,S=e=>e?4:5,y=0,k=4;const x=(e,t)=>{const s=Object.entries(e);let i=0,r=0;for(const[n,o]of s){const s=I(e,n,o,t);0!==s&&(i++,r+=E(n)+s+1)}return 2+Math.max(0,i-1)+r};function E(e){if(null===e)return k+2;if(void 0===e)return 11;switch(typeof e){case"string":return g(e);case"number":return f(e)+2;case"boolean":return S(e)+2;case"symbol":return v;default:return g(e.toString())}}function I(e,t,s,i){if(s&&"object"==typeof s&&"toJSON"in s&&"function"==typeof s.toJSON&&(s=s.toJSON()),null===(s=i?i.call(e,t,s):s))return k;if(void 0===s)return y;if(Array.isArray(s))return function(e,t){const s=e.length-1;let i=0;for(let s=0;s<e.length;s++){const r=e[s];switch(typeof r){case"function":case"symbol":case"undefined":i+=k;break;default:i+=I(e,s.toString(),r,t)}}return 2+s+i}(s,i);switch(typeof s){case"bigint":return _(s);case"boolean":return S(s);case"function":return w;case"number":return f(s);case"object":return x(s,i);case"string":return g(s);case"symbol":return v;case"undefined":return y}return 0}function T(e,t){return I(void 0,"",e,t)}function A(e,t){if(!(t<1/0))return e;if(t<0)return"<removed>";const s=e=>"object"==typeof e&&e?A(e,t-1):e,i={};for(const t in e){const r=e[t];Array.isArray(r)?i[t]=r.map(s):i[t]=s(r)}return i}function M(){const e=(s=t(),function(...e){let t="";for(const i of e)t+="object"==typeof i?JSON.stringify(i,s):i?.toString();return t});var s;try{return require("util").format??e}catch{return e}}var P;exports.BreadcrumbLogLevel=void 0,(P=exports.BreadcrumbLogLevel||(exports.BreadcrumbLogLevel={}))[P.Verbose=1]="Verbose",P[P.Debug=2]="Debug",P[P.Info=4]="Info",P[P.Warning=8]="Warning",P[P.Error=16]="Error";var L;exports.BreadcrumbType=void 0,(L=exports.BreadcrumbType||(exports.BreadcrumbType={}))[L.Manual=1]="Manual",L[L.Log=2]="Log",L[L.Navigation=4]="Navigation",L[L.Http=8]="Http",L[L.System=16]="System",L[L.User=32]="User",L[L.Configuration=64]="Configuration";class B{_events={};_formatter;start(e){(e.breadcrumbsType&exports.BreadcrumbType.Log)===exports.BreadcrumbType.Log&&(this._formatter=M(),this.bindToConsoleMethod("log",exports.BreadcrumbLogLevel.Info,e),this.bindToConsoleMethod("warn",exports.BreadcrumbLogLevel.Warning,e),this.bindToConsoleMethod("error",exports.BreadcrumbLogLevel.Error,e),this.bindToConsoleMethod("debug",exports.BreadcrumbLogLevel.Debug,e),this.bindToConsoleMethod("trace",exports.BreadcrumbLogLevel.Verbose,e))}dispose(){for(const e in this._events){const t=this._events[e];console[e]=t}}bindToConsoleMethod(e,t,s){const i=console[e];console[e]=(...e)=>{i(...e);const r=this._formatter(...e);s.addBreadcrumb(r,t,exports.BreadcrumbType.Log)},this._events[e]=i}}class O{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 s,i;this.capacity=e,this._array=new Array(e),this._headConstraint=(s=0,i=e,function(e){const t=i-s;let r;return e<s?(r=i-(s-e)%t,r===i&&(r=s)):e>=i?(r=s+(e-i)%t,r===i&&(r=s)):r=e,r}),this._lengthConstraint=function(e,t){return function(s){return Math.max(e,Math.min(s,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 R{_limits;get lastBreadcrumbId(){return this._lastBreadcrumbId}name="bt-breadcrumbs-0";_lastBreadcrumbId=c.toTimestampInSec(c.now());_breadcrumbs;_breadcrumbSizes;constructor(e){this._limits=e,this._breadcrumbs=new O(e.maximumBreadcrumbs??100),this._breadcrumbSizes=new O(this._breadcrumbs.capacity)}getAttachments(){return[this]}getAttachmentProviders(){return[{get:()=>this,type:"scoped"}]}static factory({limits:e}){return new R(e)}get(){return JSON.stringify([...this._breadcrumbs],t())}add(e){this._lastBreadcrumbId++;const s=this._lastBreadcrumbId,i={id:s,message:e.message,timestamp:c.now(),type:exports.BreadcrumbType[e.type].toLowerCase(),level:exports.BreadcrumbLogLevel[e.level].toLowerCase()};if(e.attributes&&(i.attributes=e.attributes),this._breadcrumbs.add(i),this._limits.maximumTotalBreadcrumbsSize){const e=T(i,t());this._breadcrumbSizes.add(e);let s=this.totalSize();for(;s>this._limits.maximumTotalBreadcrumbsSize;){this._breadcrumbs.shift();s-=(this._breadcrumbSizes.shift()??0)+1}}return s}totalSize(){let e=0;for(const t of this._breadcrumbSizes)e+=t;return e+Math.max(0,this._breadcrumbSizes.length-1)+2}}const N="breadcrumbs.lastId",U=(e,t)=>!1===e?void 0:void 0!==e?e:t;class C{breadcrumbsType;logLevel;_enabled=!1;_limits;_eventSubscribers=[new B];_interceptor;_storage;constructor(e,t){this._limits={maximumBreadcrumbs:U(e?.maximumBreadcrumbs,100),maximumAttributesDepth:U(e?.maximumAttributesDepth,2),maximumBreadcrumbMessageLength:U(e?.maximumBreadcrumbMessageLength,255),maximumBreadcrumbSize:U(e?.maximumBreadcrumbSize,65536),maximumTotalBreadcrumbsSize:U(e?.maximumTotalBreadcrumbsSize,1048576)},this.breadcrumbsType=e?.eventType??127,this.logLevel=e?.logLevel??31,this._storage=(t?.storage??R.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((()=>({[N]: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,exports.BreadcrumbLogLevel.Verbose,t)}debug(e,t){return this.log(e,exports.BreadcrumbLogLevel.Debug,t)}info(e,t){return this.log(e,exports.BreadcrumbLogLevel.Info,t)}warn(e,t){return this.log(e,exports.BreadcrumbLogLevel.Warning,t)}error(e,t){return this.log(e,exports.BreadcrumbLogLevel.Error,t)}log(e,t,s){return this.addBreadcrumb(e,t,exports.BreadcrumbType.Manual,s)}logReport(e){const t=e.data instanceof Error?exports.BreadcrumbLogLevel.Error:exports.BreadcrumbLogLevel.Warning;return this.addBreadcrumb(e.message,t,exports.BreadcrumbType.System)}addBreadcrumb(e,s,i,r){if(!this._enabled)return!1;let n,o={message:this.prepareBreadcrumbMessage(e),level:s,type:i,attributes:r};if(this._interceptor){const e=this._interceptor(o);if(!e)return!1;o=e}if((this.logLevel&o.level)!==s)return!1;if((this.breadcrumbsType&o.type)!==i)return!1;if(void 0!==this._limits.maximumBreadcrumbMessageLength&&(o.message=o.message.substring(0,this._limits.maximumBreadcrumbMessageLength)),n=void 0!==this._limits.maximumAttributesDepth&&o.attributes?{...o,attributes:A(o.attributes,this._limits.maximumAttributesDepth)}:o,void 0!==this._limits.maximumBreadcrumbSize){if(T(n,t())>this._limits.maximumBreadcrumbSize)return!1}return void 0!==this._storage.add(n)}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 D="unknown",q="anonymous";class F{addressSeparator;get engine(){return"v8"}constructor(e=""){this.addressSeparator=e}convert(e,t){const s=[];let i=e.split("\n");const r=t.split("\n");i=-1!==i[0].indexOf(r[0])?i.slice(r.length):i.slice(1);for(const e of i){const t=e.trim();if(!t)continue;const i=this.parseFrame(t);s.push(i)}return s}parseFrame(e){const t="at ";if(!e.startsWith(t))return{funcName:e,library:D};const s="async ";let i=(e=e.substring(e.indexOf(t)+3)).indexOf(" (");if(-1===i)return e.startsWith(s)&&(e=e.substring(6)),{funcName:q,...this.parseSourceCodeInformation(e)};let r=e.substring(i+2-1,e.length);const n="(<anonymous>)";r.startsWith(n)&&(i+=14,r=r.substring(13)),r=r.startsWith(` ${t}`)?r.substring(4):r.substring(1,r.length-1);let o=e.substring(0,i);return o.startsWith(s)&&(o=o.substring(6)),{funcName:o,...this.parseSourceCodeInformation(r)}}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(":"),s=parseInt(t[t.length-1]),i=parseInt(t[t.length-2]);return{library:t.slice(0,t.length-2).join(":"),column:isNaN(s)?void 0:s,line:isNaN(i)?void 0:i}}extractEvalInformation(e){const t=e.indexOf("("),s=e.indexOf(")");if(-1===t||-1===s||t>s)return{library:D};const i=e.substring(t+1,s);return this.parseSourceCodeInformation(i)}}class H{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 j{_sdkOptions;_stackTraceConverter;_attributeManager;_debugIdProvider;MAIN_THREAD_NAME="main";constructor(e,t,s,i){this._sdkOptions=e,this._stackTraceConverter=t,this._attributeManager=s,this._debugIdProvider=i}build(e){const{annotations:t,attributes:s}=this._attributeManager.get(),i=l.build(e.attributes),{threads:r,detectedDebugIdentifier:n}=this.getThreads(e),o={uuid:H.uuid(),timestamp:c.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:r,annotations:{...t,...i.annotations,...e.annotations},attributes:{...s,...i.attributes}};return n&&(o.symbolication="sourcemap"),o}getThreads(e){const t={};let s=!1;for(const[i,r]of Object.entries(e.stackTrace)){let n;if(Array.isArray(r))n=r;else{const{message:e,stack:t}=r;n=this._stackTraceConverter.convert(t,e)}i===this.MAIN_THREAD_NAME&&e.skipFrames>0&&n.splice(0,e.skipFrames);for(const e of n){const t=this._debugIdProvider.getDebugId(e.library);t&&(s=!0,e.debug_identifier=t)}t[i]={fault:i===this.MAIN_THREAD_NAME,name:i,stack:n}}return{threads:t,detectedDebugIdentifier:s}}}class z extends Error{constructor(e){super(e??"Operation cancelled.")}}const V=($="AbortController","undefined"!=typeof window?window[$]:"undefined"!=typeof global?global[$]:"undefined"!=typeof self?self[$]:void 0);var $;class Q{_listeners={};_events=new a;addEventListener(e,t,s){e in this._listeners||(this._listeners[e]=[]);const i=e=>"object"==typeof t?t.handleEvent.call(this,e):t.call(this,e),{once:r,signal:n}="object"==typeof s?s:{};if(r?this._events.once(e,i):this._events.on(e,i),n){const s=()=>this.removeEventListener(e,t);n.addEventListener(e,s,{once:!0})}this._listeners[e].push({callback:i,listener:t,options:s})}removeEventListener(e,t){if(!(e in this._listeners))return;const s=this._listeners[e],i=s.filter((e=>e.listener===t));for(const t of i){this._events.off(e,t.callback);const i=s.indexOf(t);s.splice(i,1)}}dispatchEvent(e){return this._events.emit(e.type,e),!e.defaultPrevented}}class W extends Q{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 W,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 s=e;if(void 0===s)if("undefined"==typeof document)s=new z("This operation was aborted");else try{s=new DOMException("signal is aborted without reason")}catch(e){s=new z("This operation was aborted")}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};function X(){return V?new V:new J}function G(...e){const t=X();function s(){for(const t of e)t&&t.removeEventListener("abort",i)}function i(){t.abort(),s()}for(const t of e)if(t){if(t.aborted){i();break}t.addEventListener("abort",i)}return t.signal.dispose=s,t.signal}function Y(e){e&&"number"!=typeof e&&e.unref()}"undefined"!=typeof Symbol&&Symbol.toStringTag&&(J.prototype[Symbol.toStringTag]="AbortController",W.prototype[Symbol.toStringTag]="AbortSignal");class Z{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 s of this._records)this._recordBuckets[s.id]===e&&t.push(s);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,s=this._records.findIndex((e=>e.id===t));-1!==s&&(this._records.splice(s,1),delete this._recordBuckets[t])}increaseBucket(e){for(const[t,s]of Object.entries(this._recordBuckets)){if(s<e)continue;const i=s+1;i>=this.bucketCount&&this.remove(t),this._recordBuckets[t]=i}}load(e){for(const t of e)this.add(t)}dropOverLimits(e){const t={...e},s=[];for(let e=this._records.length-1;e>=0;e--){const i=this._records[e];0===t[i.type]?(this.remove(i),s.push(i)):t[i.type]--}return s}}class K extends a{_options;_storageProvider;_requestHandler;_sessionFiles;get enabled(){return this._enabled}_abortController=X();_databaseRecordContext;_storageProviders=[];_recordLimits;_retryInterval;_intervalId;_enabled=!1;constructor(e,t,s,i){super(),this._options=e,this._storageProvider=t,this._requestHandler=s,this._sessionFiles=i,this._databaseRecordContext=new Z(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,s)=>{const i=this.add(t,s);i&&!i.locked&&(i.locked=!0)})),e.on("after-send",((e,t,s,i)=>{const r=this._databaseRecordContext.find((e=>"report"===e.type&&e.data.uuid===t.uuid));r&&(r.locked=!1,"Ok"===i.status&&(this.remove(r),this._sessionFiles?.unlockPreviousSessions(r.id)))})))}add(e,t){if(!this._enabled)return;const s=e.attributes?.["application.session"],i={type:"report",data:e,timestamp:c.now(),id:H.uuid(),locked:!1,attachments:t,sessionId:"string"==typeof s?s:void 0};this.prepareDatabase([i]);return this._storageProvider.add(i)?(this._databaseRecordContext.add(i),this.lockSessionWithRecord(i),this.emit("added",i),i):void 0}addAttachment(e,t,s){if(!this._enabled)return;const i={type:"attachment",timestamp:c.now(),id:H.uuid(),rxid:e,locked:!1,attachment:t,sessionId:s};this.prepareDatabase([i]);return this._storageProvider.add(i)?(this._databaseRecordContext.add(i),this.lockSessionWithRecord(i),this.emit("added",i),i):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=c.now();await this.send(e);const s=this.get().filter((e=>e.timestamp<=t));for(const t of s){if(e?.aborted)return;this.remove(t)}}async send(e){for(let t=0;t<this._databaseRecordContext.bucketCount;t++){const s=[...this._databaseRecordContext.getBucket(t)],i=G(e,this._abortController.signal);try{for(const e of s){if(!this.enabled)return;if(!e.locked)try{e.locked=!0,this.emit("before-send",e);const s="report"===e.type?await this._requestHandler.send(e.data,e.attachments,i):await this._requestHandler.sendAttachment(e.rxid,e.attachment,i);if(this.emit("after-send",e,s),"Ok"===s.status||"Unsupported"===s.status||"Report skipped"===s.status){this.remove(e);continue}return void this._databaseRecordContext.increaseBucket(t)}finally{e.locked=!1}}}finally{i.dispose()}}}prepareDatabase(e){const t={...this._recordLimits};for(const s of e)t[s.type]--;const s=this._databaseRecordContext.dropOverLimits(t);this.remove(s)}async loadReports(){const e=await this._storageProvider.get(),t={attachment:0,report:0},s=[],i=[];for(const r of e)t[r.type]>=this._recordLimits[r.type]?i.push(r):(s.push(r),t[r.type]++);i.length&&this.remove(i),this.prepareDatabase(s),this._databaseRecordContext.load(s);for(const e of s)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("string"!=typeof t)return void this._sessionFiles.lockPreviousSessions(e.id);const s=this._sessionFiles.getSessionWithId(t);s?.lock(e.id)}}function ee(e){return"filePath"in e&&"string"==typeof e.filePath}class te{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 te(e)}static fromJson(e,t){try{const s="string"==typeof e?JSON.parse(e):e;if(!ee(s.attachment))return;if(!t.existsSync(s.attachment.filePath))return;const i=t.createAttachment(s.attachment.filePath,s.attachment.name);return new te({...s,attachment:i})}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(ee))}static fromJson(e,t){try{const s="string"==typeof e?JSON.parse(e):e,i=s.attachments?s.attachments.filter(ee).map((e=>t.createAttachment(e.filePath,e.name))):[];return new se(s,i)}catch{return}}}const ie={fromRecord(e){switch(e.type){case"attachment":return te.fromRecord(e);case"report":return se.fromRecord(e);default:throw new Error("unknown record type")}},fromJson(e,t){try{const s=JSON.parse(e);switch(s.type){case"attachment":return te.fromJson(s,t);case"report":return se.fromJson(s,t);default:return}}catch{return}}};class re{_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 re(e,t.path)}}start(){return!1!==this._enabled}delete(e){const t=this.getRecordPath(e.id);return this.unlinkRecord(t)}add(e){const s=this.getRecordPath(e.id);try{return this._fileSystem.writeFileSync(s,JSON.stringify(ie.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 s of e)try{const e=await this._fileSystem.readFile(s),i=ie.fromJson(e,this._fileSystem);if(!i){await this._fileSystem.unlink(s);continue}t.push(i)}catch{await this._fileSystem.unlink(s)}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 ne{metricGroupName;metricGroupValue;attributes;id=H.uuid();constructor(e,t,s={}){this.metricGroupName=e,this.metricGroupValue=t,this.attributes=s}toJSON(){return{timestamp:c.toTimestampInSec(c.now()),attributes:this.attributes,[this.metricGroupName]:this.metricGroupValue}}}class oe extends ne{constructor(e,t={}){super("metric_group",e,t)}}class ae extends ne{constructor(e){super("unique",["guid"],e)}}class ce{_options;_sessionProvider;_attributeManager;_summedEventsSubmissionQueue;_uniqueEventsSubmissionQueue;get sessionId(){return this._sessionProvider.sessionId}DEFAULT_UPDATE_INTERVAL=c.convertSecondsToMilliseconds(1800);DEFAULT_SERVER_URL="https://events.backtrace.io";metricsHost;_updateInterval;_updateIntervalId;_abortController;constructor(e,t,s,i,r){this._options=e,this._sessionProvider=t,this._attributeManager=s,this._summedEventsSubmissionQueue=i,this._uniqueEventsSubmissionQueue=r,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 s=this.convertAttributes({...this._attributeManager.get().attributes,...l.build(t??{}).attributes});return this._summedEventsSubmissionQueue.add(new oe(e,s)),!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 ae(this.convertAttributes(t))),await this._uniqueEventsSubmissionQueue.send(e)}convertAttributes(e){return Object.keys(e).filter((t=>null!=e[t])).reduce(((t,s)=>(t[s]=e[s]?.toString(),t)),{})}async handleAbort(e){try{return await e(),!0}catch(e){if(e instanceof z)return!1;throw e}}}class ue{static wait(e,t){return new Promise(((s,i)=>{let r;function n(){clearTimeout(r),i(new z)}if(t?.aborted)return n();r=setTimeout((()=>{t?.removeEventListener("abort",n),s()}),e),t?.addEventListener("abort",n)}))}}class de{_submissionUrl;_eventName;_requestHandler;_metricMetadata;maximumEvents;get total(){return this._events.length}get submissionUrl(){return this._submissionUrl}DELAY_BETWEEN_REQUESTS=c.convertSecondsToMilliseconds(10);_events=[];_numberOfDroppedRequests=0;_abortController;MAXIMUM_NUMBER_OF_ATTEMPTS=3;constructor(e,t,s,i,r=50){this._submissionUrl=e,this._eventName=t,this._requestHandler=s,this._metricMetadata=i,this.maximumEvents=r,this._abortController=X()}add(e){this._events.push(e),this.reachedLimit()&&this.send()}async send(e){const t=this._events.splice(0),s=G(e,this._abortController.signal);try{return await this.submit(t,s)}finally{s.dispose()}}dispose(){this._abortController.abort()}async submit(e,s){for(let i=0;i<this.MAXIMUM_NUMBER_OF_ATTEMPTS;i++){if("Ok"===(await this._requestHandler.post(this._submissionUrl,JSON.stringify({...this._metricMetadata,[this._eventName]:e,metadata:{dropped_events:this._numberOfDroppedRequests}},t()),s)).status)return void(this._numberOfDroppedRequests=0);this._numberOfDroppedRequests++,await ue.wait(2**i*this.DELAY_BETWEEN_REQUESTS,s)}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 le{_options;_sessionProvider;_attributeManager;_requestHandler;DEFAULT_UPDATE_INTERVAL=c.convertSecondsToMilliseconds(1800);APPLICATION_VERSION_ATTRIBUTE="application.version";APPLICATION_ATTRIBUTE="application";constructor(e,t,s,i){this._options=e,this._sessionProvider=t,this._attributeManager=s,this._requestHandler=i}build(e,t){const s={...this.optionsWithDefaults(),...this._options.metrics??{}};if(!s.enable)return;const i=this.verifyAttributeSetup();return i&&(e=e??this.createUniqueEventSubmissionQueue(s.metricsSubmissionUrl,i))&&(t=t??this.createSummedEventSubmissionQueue(s.metricsSubmissionUrl,i))?new ce(s,this._sessionProvider,this._attributeManager,t,e):void 0}verifyAttributeSetup(){const{attributes:e}=this._attributeManager.get(),t=e[this.APPLICATION_ATTRIBUTE],s=e[this.APPLICATION_VERSION_ATTRIBUTE];if(t&&s)return{application:t,applicationVersion:s}}createUniqueEventSubmissionQueue(e,t){const s=n.generateUniqueEventsUrl(e,this._options.url,this._options.token);if(s)return new de(s,"unique_events",this._requestHandler,{[this.APPLICATION_ATTRIBUTE]:t.application,appversion:t.applicationVersion},this._options?.metrics?.size)}createSummedEventSubmissionQueue(e,t){const s=n.generateSummedEventsUrl(e,this._options.url,this._options.token);if(s)return new de(s,"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 he{newSession=!0;sessionId=H.uuid();_lastActive=0;get lastActive(){return this._lastActive}afterMetricsSubmission(){this._lastActive=c.now()}shouldSend(){return!0}}class me{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=c.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 be 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(ce)}get breadcrumbs(){return this._modules.get(C)}get database(){return this._modules.get(K)}get attachments(){return this.attachmentManager.get()}get modules(){return this._modules}get sessionFiles(){return this._modules.get(_e)}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 he,this._reportSubmission=e.reportSubmission??new i(this.options,e.requestHandler),this._rateLimitWatcher=new me(this.options.rateLimit),this._requestHandler=e.requestHandler;const t=[new m(this.agent,this.agentVersion,this._sessionProvider.sessionId)];e.attributeProviders&&t.push(...e.attributeProviders),this.options.userAttributes&&t.push(new b(this.options.userAttributes)),this.attributeManager=new h(t),this.attachmentManager=new d,this.options.attachments&&this.attachmentManager.add(...this.options.attachments);const s=e.stackTraceConverter??new F;if(this._dataBuilder=new j(this._sdkOptions,s,this.attributeManager,new ve(s,e.debugIdMapProvider)),!0===this.options?.database?.enable&&e.fileSystem){const t=re.createIfValid(e.fileSystem,this.options.database);if(this.fileSystem){const e=new _e(this.fileSystem,this.options.database.path,this.sessionId,this.options.database.maximumOldSessions??1);this._modules.set(_e,e)}if(t){const e=new K(this.options.database,t,this._reportSubmission,this.sessionFiles);this._modules.set(K,e)}}const r=new le(this.options,this._sessionProvider,this.attributeManager,e.requestHandler).build(e.uniqueMetricsQueue,e.summedMetricsQueue);if(r&&this._modules.set(ce,r),!1!==this.options.breadcrumbs?.enable){const t=new C(this.options?.breadcrumbs,e.breadcrumbsSetup);this._modules.set(C,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,be._instance=this}addAttribute(e){this.attributeManager.add(e)}addAttachment(...e){this.attachmentManager.add(...e)}send(t,s,i=[],r){if(!this._enabled)return Promise.resolve(e.SdkDisabled());if(this._rateLimitWatcher.skipReport())return Promise.resolve(e.OnLimitReached("Client"));const n=this.isReport(t)?void 0:s;r=this.isReport(t)?s:r;const o=this.isReport(t)?t:new u(t,n,[],{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 c=this.generateSubmissionAttachments(o,i);return this.emit("before-send",o,a,c),this._reportSubmission.send(a,c,r).then((e=>(this.emit("after-send",o,a,c,e),e)))}dispose(){this._enabled=!1;for(const e of this._modules.values())e.dispose&&e.dispose();be.destroy()}addModule(e,t){let s;if("function"==typeof e?s=e:(t=e,s=Object.getPrototypeOf(t)),!t)throw new Error("Module implementation is required.");this._modules.set(s,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 u}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 pe{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}}const ge="bt-session",fe=e=>!!e;class _e{_fileSystem;_directory;sessionId;_maxPreviousLockedSessions;timestamp;_lockable;marker;_events=new a;_escapedSessionId;_locks=new Set;_previousSession;_cleared=!1;constructor(e,t,s,i=1,r=Date.now(),n=!0){this._fileSystem=e,this._directory=t,this.sessionId=s,this._maxPreviousLockedSessions=i,this.timestamp=r,this._lockable=n,this._escapedSessionId=this.escapeFileName(s),this.marker=this.getFileName(ge)}initialize(){this.createSessionMarker()}getPreviousSession(){if(this._previousSession)return this._previousSession;const e=this.readDirectoryFiles();if(!e.length)return;const t=e.filter((e=>e.startsWith(ge))).map((e=>this.getFileSession(e))).filter(fe).sort(((e,t)=>t.timestamp-e.timestamp)),s=t.find((e=>e.sessionId===this.sessionId)),i=s?t.filter((({timestamp:e})=>s.timestamp>e))[0]:t[0];return i?this._previousSession=new _e(this._fileSystem,this._directory,i.sessionId,this._maxPreviousLockedSessions-1,i.timestamp,this._maxPreviousLockedSessions>0):void 0}getSessionWithId(e){let t=this;for(;t&&t.sessionId!==e;)t=t.getPreviousSession();return t}getPreviousSessions(e=1/0){const t=[];let s=this.getPreviousSession();for(;s&&e>0;)t.push(s),e--,s=s.getPreviousSession();return t}lockPreviousSessions(e){e=e??H.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.timestamp}`}getSessionFiles(){this.throwIfCleared();return this.readDirectoryFiles().map((e=>this.getFileSession(e))).filter(fe).filter((({sessionId:e})=>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??H.uuid(),this._locks.add(e),e}unlock(e){this._locks.delete(e),0===this._locks.size&&this._events.emit("unlocked")}getFileSession(e){const[t,s]=this.splitByOneChar(e,"_").slice(-2),i=parseInt(s);if(!isNaN(i))return{file:e,escapedSessionId:t,timestamp:i,sessionId: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 s=[];let i=0,r=e.indexOf(t);for(;-1!==r;)e[r+1]===t?r=e.indexOf(t,r+2):(s.push(e.substring(i,r)),i=r+1,r=e.indexOf(t,i));return s.push(e.substring(i)),s}throwIfCleared(){if(this._cleared)throw new Error("This session files are cleared.")}}class ve{_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,s={};for(const[i,r]of Object.entries(e)){const e=this._stackTraceConverter.convert(i,t);if(!e.length)continue;s[e[0].library]=r}return s}}class we{_variable;constructor(e){this._variable=e}getDebugIdMap(){return this._variable._btDebugIds??{}}}const Se={langName:"js",langVersion:navigator.userAgent,agent:"@backtrace/browser",agentVersion:"0.5.0"};function ye(e,t,s,i){return new(s||(s=Promise))((function(r,n){function o(e){try{c(i.next(e))}catch(e){n(e)}}function a(e){try{c(i.throw(e))}catch(e){n(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof s?t:new s((function(e){e(t)}))).then(o,a)}c((i=i.apply(e,t||[])).next())}))}"function"==typeof SuppressedError&&SuppressedError;class ke{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,s,i){return ye(this,void 0,void 0,(function*(){const r=0===s.length?t:this.createFormData(t,s);return this.post(e,r,i)}))}post(t,s,i){return ye(this,void 0,void 0,(function*(){const n=new AbortController,o=setTimeout((()=>n.abort()),this._timeout),a=G(i,n.signal);try{const i=yield fetch(t,{method:"POST",body:s,headers:"string"==typeof s?this.JSON_HEADERS:this.MULTIPART_HEADERS,signal:a});switch(clearInterval(o),i.status){case 200:{const t=yield i.json();return e.Ok(t)}case 401:case 403:return e.OnInvalidToken();case 429:return e.OnLimitReached();default:return e.OnInternalServerError(i.statusText)}}catch(t){return t instanceof Error?"AbortError"===t.name?e.OnNetworkingError("Timeout"):r.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 s=new FormData;if(s.append(this.UPLOAD_FILE_NAME,e),!t||0===t.length)return s;for(const e of t){const t=e.get();t&&s.append(`attachment_${e.name}`,t)}return s}}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=H.uuid(),this._lastActive=0,!window.localStorage)return;const e=this.readLastActiveTimestamp();if(!e||c.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=c.now(),localStorage.setItem(this.SESSION_LAST_ACTIVE,this._lastActive.toString(10))}}xe.PERSISTENCE_INTERVAL=c.convertSecondsToMilliseconds(1800);class Ee{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 Ie="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{},Te={exports:{}};!function(e,t){!function(s,i){var r="function",n="undefin