New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@exceptionless/core

Package Overview
Dependencies
Maintainers
1
Versions
16
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@exceptionless/core - npm Package Compare versions

Comparing version 2.0.0-beta1 to 2.0.0-beta2

19

dist/configuration/Configuration.d.ts

@@ -218,6 +218,11 @@ import { ILastReferenceIdManager } from "../lastReferenceIdManager/ILastReferenceIdManager.js";

set version(version: string);
setUserIdentity(userInfo: UserInfo): void;
setUserIdentity(identity: string): void;
setUserIdentity(identity: string, name: string): void;
/**
* Set the default user identity for all events. If the heartbeat interval is
* greater than 0 (default: 30000ms), heartbeats will be sent after the first
* event submission.
*/
setUserIdentity(userInfo: UserInfo, heartbeatInterval?: number): void;
setUserIdentity(identity: string, heartbeatInterval?: number): void;
setUserIdentity(identity: string, name: string, heartbeatInterval?: number): void;
/**
* Used to identify the client that sent the events to the server.

@@ -227,10 +232,2 @@ */

/**
* Automatically send a heartbeat to keep the session alive.
*/
useSessions(sendHeartbeats?: boolean, heartbeatInterval?: number): void;
/**
* Automatically set a reference id for error events.
*/
useReferenceIds(): void;
/**
* Use localStorage for persisting things like server configuration cache and persisted queue entries (depends on usePersistedQueueStorage).

@@ -237,0 +234,0 @@ */

@@ -5,3 +5,2 @@ import { DefaultLastReferenceIdManager } from "../lastReferenceIdManager/DefaultLastReferenceIdManager.js";

import { HeartbeatPlugin } from "../plugins/default/HeartbeatPlugin.js";
import { ReferenceIdPlugin } from "../plugins/default/ReferenceIdPlugin.js";
import { DefaultEventQueue } from "../queue/DefaultEventQueue.js";

@@ -318,13 +317,5 @@ import { DefaultSubmissionClient } from "../submission/DefaultSubmissionClient.js";

}
let pluginExists = false;
const plugins = this._plugins; // optimization for minifier.
for (const p of plugins) {
if (p.name === plugin.name) {
pluginExists = true;
break;
}
if (!this._plugins.find(f => f.name === plugin.name)) {
this._plugins.push(plugin);
}
if (!pluginExists) {
plugins.push(plugin);
}
}

@@ -367,15 +358,19 @@ /**

}
setUserIdentity(userInfoOrIdentity, name) {
setUserIdentity(userInfoOrIdentity, nameOrHeartbeatInterval, heartbeatInterval = 30000) {
const name = typeof nameOrHeartbeatInterval === "string" ? nameOrHeartbeatInterval : undefined;
const userInfo = typeof userInfoOrIdentity !== "string"
? userInfoOrIdentity
: { identity: userInfoOrIdentity, name };
const shouldRemove = !userInfo ||
(!userInfo.identity && !userInfo.name);
const interval = typeof nameOrHeartbeatInterval === "number" ? nameOrHeartbeatInterval : heartbeatInterval;
const plugin = new HeartbeatPlugin(interval);
const shouldRemove = !userInfo || (!userInfo.identity && !userInfo.name);
if (shouldRemove) {
this.removePlugin(plugin);
delete this.defaultData[KnownEventDataKeys.UserInfo];
}
else {
this.addPlugin(plugin);
this.defaultData[KnownEventDataKeys.UserInfo] = userInfo;
}
this.services.log.info(`user identity: ${shouldRemove ? "null" : userInfo.identity}`);
this.services.log.info(`user identity: ${shouldRemove ? "null" : userInfo.identity} (heartbeat interval: ${interval}ms)`);
}

@@ -386,19 +381,5 @@ /**

get userAgent() {
return "exceptionless-js/2.0.0-beta1";
return "exceptionless-js/2.0.0-beta2";
}
/**
* Automatically send a heartbeat to keep the session alive.
*/
useSessions(sendHeartbeats = true, heartbeatInterval = 30000) {
if (sendHeartbeats) {
this.addPlugin(new HeartbeatPlugin(heartbeatInterval));
}
}
/**
* Automatically set a reference id for error events.
*/
useReferenceIds() {
this.addPlugin(new ReferenceIdPlugin());
}
/**
* Use localStorage for persisting things like server configuration cache and persisted queue entries (depends on usePersistedQueueStorage).

@@ -405,0 +386,0 @@ */

@@ -92,2 +92,5 @@ // src/lastReferenceIdManager/DefaultLastReferenceIdManager.ts

var _a;
if (this._interval <= 0) {
return Promise.resolve();
}
clearInterval(this._intervalId);

@@ -103,190 +106,2 @@ this._intervalId = 0;

// src/Utils.ts
function getHashCode(source) {
if (!source || source.length === 0) {
return 0;
}
let hash = 0;
for (let index = 0; index < source.length; index++) {
const character = source.charCodeAt(index);
hash = (hash << 5) - hash + character;
hash |= 0;
}
return hash;
}
function getCookies(cookies, exclusions) {
const result = {};
const parts = (cookies || "").split("; ");
for (const part of parts) {
const cookie = part.split("=");
if (!isMatch(cookie[0], exclusions || [])) {
result[cookie[0]] = cookie[1];
}
}
return !isEmpty(result) ? result : null;
}
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1);
}
return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}
function parseVersion(source) {
if (!source) {
return null;
}
const versionRegex = /(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?)/;
const matches = versionRegex.exec(source);
if (matches && matches.length > 0) {
return matches[0];
}
return null;
}
function parseQueryString(query, exclusions) {
if (!query || query.length === 0) {
return {};
}
const pairs = query.split("&");
if (pairs.length === 0) {
return {};
}
const result = {};
for (const pair of pairs) {
const parts = pair.split("=");
if (!exclusions || !isMatch(parts[0], exclusions)) {
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
}
return !isEmpty(result) ? result : {};
}
function randomNumber() {
return Math.floor(Math.random() * 9007199254740992);
}
function isMatch(input, patterns, ignoreCase = true) {
if (typeof input !== "string") {
return false;
}
const trim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
input = (ignoreCase ? input.toLowerCase() : input).replace(trim, "");
return (patterns || []).some((pattern) => {
if (typeof pattern !== "string") {
return false;
}
if (pattern) {
pattern = (ignoreCase ? pattern.toLowerCase() : pattern).replace(trim, "");
}
if (!pattern) {
return input === void 0 || input === null;
}
if (pattern === "*") {
return true;
}
if (input === void 0 || input === null) {
return false;
}
const startsWithWildcard = pattern[0] === "*";
if (startsWithWildcard) {
pattern = pattern.slice(1);
}
const endsWithWildcard = pattern[pattern.length - 1] === "*";
if (endsWithWildcard) {
pattern = pattern.substring(0, pattern.length - 1);
}
if (startsWithWildcard && endsWithWildcard) {
return pattern.length <= input.length && input.indexOf(pattern, 0) !== -1;
}
if (startsWithWildcard) {
return endsWith(input, pattern);
}
if (endsWithWildcard) {
return startsWith(input, pattern);
}
return input === pattern;
});
}
function isEmpty(input) {
if (input === null || input === void 0) {
return true;
}
if (typeof input == "object") {
return Object.keys(input).length === 0;
}
return false;
}
function startsWith(input, prefix) {
return input.substring(0, prefix.length) === prefix;
}
function endsWith(input, suffix) {
return input.indexOf(suffix, input.length - suffix.length) !== -1;
}
function stringify(data, exclusions, maxDepth) {
function stringifyImpl(obj, excludedKeys) {
const cache = [];
return JSON.stringify(obj, (key, value) => {
if (isMatch(key, excludedKeys)) {
return;
}
if (typeof value === "object" && value) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
});
}
if ({}.toString.call(data) === "[object Object]") {
const flattened = {};
for (const prop in data) {
const value = data[prop];
if (value !== data) {
flattened[prop] = value;
}
}
return stringifyImpl(flattened, exclusions || []);
}
if ({}.toString.call(data) === "[object Array]") {
const result = [];
for (let index = 0; index < data.length; index++) {
result[index] = JSON.parse(stringifyImpl(data[index], exclusions || []));
}
return JSON.stringify(result);
}
return stringifyImpl(data, exclusions || []);
}
function toBoolean(input, defaultValue = false) {
if (typeof input === "boolean") {
return input;
}
if (input === null || typeof input !== "number" && typeof input !== "string") {
return defaultValue;
}
switch ((input + "").toLowerCase().trim()) {
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
return false;
}
return defaultValue;
}
// src/plugins/default/ReferenceIdPlugin.ts
var ReferenceIdPlugin = class {
constructor() {
this.priority = 20;
this.name = "ReferenceIdPlugin";
}
run(context) {
if (!context.event.reference_id && context.event.type === "error") {
context.event.reference_id = guid().replace("-", "").substring(0, 10);
}
return Promise.resolve();
}
};
// src/queue/DefaultEventQueue.ts

@@ -660,2 +475,176 @@ var DefaultEventQueue = class {

// src/Utils.ts
function getHashCode(source) {
if (!source || source.length === 0) {
return 0;
}
let hash = 0;
for (let index = 0; index < source.length; index++) {
const character = source.charCodeAt(index);
hash = (hash << 5) - hash + character;
hash |= 0;
}
return hash;
}
function getCookies(cookies, exclusions) {
const result = {};
const parts = (cookies || "").split("; ");
for (const part of parts) {
const cookie = part.split("=");
if (!isMatch(cookie[0], exclusions || [])) {
result[cookie[0]] = cookie[1];
}
}
return !isEmpty(result) ? result : null;
}
function guid() {
function s4() {
return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1);
}
return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();
}
function parseVersion(source) {
if (!source) {
return null;
}
const versionRegex = /(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?)/;
const matches = versionRegex.exec(source);
if (matches && matches.length > 0) {
return matches[0];
}
return null;
}
function parseQueryString(query, exclusions) {
if (!query || query.length === 0) {
return {};
}
const pairs = query.split("&");
if (pairs.length === 0) {
return {};
}
const result = {};
for (const pair of pairs) {
const parts = pair.split("=");
if (!exclusions || !isMatch(parts[0], exclusions)) {
result[decodeURIComponent(parts[0])] = decodeURIComponent(parts[1]);
}
}
return !isEmpty(result) ? result : {};
}
function randomNumber() {
return Math.floor(Math.random() * 9007199254740992);
}
function isMatch(input, patterns, ignoreCase = true) {
if (typeof input !== "string") {
return false;
}
const trim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;
input = (ignoreCase ? input.toLowerCase() : input).replace(trim, "");
return (patterns || []).some((pattern) => {
if (typeof pattern !== "string") {
return false;
}
if (pattern) {
pattern = (ignoreCase ? pattern.toLowerCase() : pattern).replace(trim, "");
}
if (!pattern) {
return input === void 0 || input === null;
}
if (pattern === "*") {
return true;
}
if (input === void 0 || input === null) {
return false;
}
const startsWithWildcard = pattern[0] === "*";
if (startsWithWildcard) {
pattern = pattern.slice(1);
}
const endsWithWildcard = pattern[pattern.length - 1] === "*";
if (endsWithWildcard) {
pattern = pattern.substring(0, pattern.length - 1);
}
if (startsWithWildcard && endsWithWildcard) {
return pattern.length <= input.length && input.indexOf(pattern, 0) !== -1;
}
if (startsWithWildcard) {
return endsWith(input, pattern);
}
if (endsWithWildcard) {
return startsWith(input, pattern);
}
return input === pattern;
});
}
function isEmpty(input) {
if (input === null || input === void 0) {
return true;
}
if (typeof input == "object") {
return Object.keys(input).length === 0;
}
return false;
}
function startsWith(input, prefix) {
return input.substring(0, prefix.length) === prefix;
}
function endsWith(input, suffix) {
return input.indexOf(suffix, input.length - suffix.length) !== -1;
}
function stringify(data, exclusions, maxDepth) {
function stringifyImpl(obj, excludedKeys) {
const cache = [];
return JSON.stringify(obj, (key, value) => {
if (isMatch(key, excludedKeys)) {
return;
}
if (typeof value === "object" && value) {
if (cache.indexOf(value) !== -1) {
return;
}
cache.push(value);
}
return value;
});
}
if ({}.toString.call(data) === "[object Object]") {
const flattened = {};
for (const prop in data) {
const value = data[prop];
if (value !== data) {
flattened[prop] = value;
}
}
return stringifyImpl(flattened, exclusions || []);
}
if ({}.toString.call(data) === "[object Array]") {
const result = [];
for (let index = 0; index < data.length; index++) {
result[index] = JSON.parse(stringifyImpl(data[index], exclusions || []));
}
return JSON.stringify(result);
}
return stringifyImpl(data, exclusions || []);
}
function toBoolean(input, defaultValue = false) {
if (typeof input === "boolean") {
return input;
}
if (input === null || typeof input !== "number" && typeof input !== "string") {
return defaultValue;
}
switch ((input + "").toLowerCase().trim()) {
case "true":
case "yes":
case "1":
return true;
case "false":
case "no":
case "0":
case null:
return false;
}
return defaultValue;
}
// src/storage/InMemoryStorage.ts

@@ -897,13 +886,5 @@ var InMemoryStorage = class {

}
let pluginExists = false;
const plugins = this._plugins;
for (const p of plugins) {
if (p.name === plugin.name) {
pluginExists = true;
break;
}
if (!this._plugins.find((f) => f.name === plugin.name)) {
this._plugins.push(plugin);
}
if (!pluginExists) {
plugins.push(plugin);
}
}

@@ -934,23 +915,20 @@ removePlugin(pluginOrName) {

}
setUserIdentity(userInfoOrIdentity, name) {
setUserIdentity(userInfoOrIdentity, nameOrHeartbeatInterval, heartbeatInterval = 3e4) {
const name = typeof nameOrHeartbeatInterval === "string" ? nameOrHeartbeatInterval : void 0;
const userInfo = typeof userInfoOrIdentity !== "string" ? userInfoOrIdentity : { identity: userInfoOrIdentity, name };
const interval = typeof nameOrHeartbeatInterval === "number" ? nameOrHeartbeatInterval : heartbeatInterval;
const plugin = new HeartbeatPlugin(interval);
const shouldRemove = !userInfo || !userInfo.identity && !userInfo.name;
if (shouldRemove) {
this.removePlugin(plugin);
delete this.defaultData[KnownEventDataKeys.UserInfo];
} else {
this.addPlugin(plugin);
this.defaultData[KnownEventDataKeys.UserInfo] = userInfo;
}
this.services.log.info(`user identity: ${shouldRemove ? "null" : userInfo.identity}`);
this.services.log.info(`user identity: ${shouldRemove ? "null" : userInfo.identity} (heartbeat interval: ${interval}ms)`);
}
get userAgent() {
return "exceptionless-js/2.0.0-beta1";
return "exceptionless-js/2.0.0-beta2";
}
useSessions(sendHeartbeats = true, heartbeatInterval = 3e4) {
if (sendHeartbeats) {
this.addPlugin(new HeartbeatPlugin(heartbeatInterval));
}
}
useReferenceIds() {
this.addPlugin(new ReferenceIdPlugin());
}
useLocalStorage() {

@@ -1190,2 +1168,16 @@ this.services.storage = new LocalStorage();

// src/plugins/default/ReferenceIdPlugin.ts
var ReferenceIdPlugin = class {
constructor() {
this.priority = 20;
this.name = "ReferenceIdPlugin";
}
run(context) {
if (!context.event.reference_id && context.event.type === "error") {
context.event.reference_id = guid().replace("-", "").substring(0, 10);
}
return Promise.resolve();
}
};
// src/plugins/default/SimpleErrorPlugin.ts

@@ -1358,2 +1350,3 @@ var IgnoredErrorProperties = [

config.addPlugin(new SimpleErrorPlugin());
config.addPlugin(new ReferenceIdPlugin());
config.addPlugin(new DuplicateCheckerPlugin());

@@ -1360,0 +1353,0 @@ config.addPlugin(new EventExclusionPlugin());

@@ -1,2 +0,2 @@

var S=class{constructor(){this._lastReferenceId=null}getLast(){return this._lastReferenceId}clearLast(){this._lastReferenceId=null}setLast(e){this._lastReferenceId=e}};var y=class{trace(e){this.log("debug",e)}info(e){this.log("info",e)}warn(e){this.log("warn",e)}error(e){this.log("error",e)}log(e,t){if(console){let i=`Exceptionless:${new Date().toISOString()} [${e}] ${t}`,s=console[e];s?s(i):console.log&&console.log(i)}}};var x=class{trace(e){}info(e){}warn(e){}error(e){}};var u;(function(a){a.Error="@error",a.SimpleError="@simple_error",a.RequestInfo="@request",a.TraceLog="@trace",a.EnvironmentInfo="@environment",a.UserInfo="@user",a.UserDescription="@user_description",a.Version="@version",a.Level="@level",a.SubmissionMethod="@submission_method",a.ManualStackingInfo="@stack"})(u||(u={}));var C=class{constructor(e=3e4){this.priority=100;this.name="HeartbeatPlugin";this._intervalId=0;this._interval=e>=3e4?e:6e4}startup(){return clearInterval(this._intervalId),this._intervalId=0,Promise.resolve()}suspend(){return clearInterval(this._intervalId),this._intervalId=0,Promise.resolve()}run(e){var i;clearInterval(this._intervalId),this._intervalId=0;let t=(i=e.event.data)==null?void 0:i[u.UserInfo];return(t==null?void 0:t.identity)&&(this._intervalId=setInterval(()=>void e.client.submitSessionHeartbeat(t.identity),this._interval)),Promise.resolve()}};function _(r){if(!r||r.length===0)return 0;let e=0;for(let t=0;t<r.length;t++){let i=r.charCodeAt(t);e=(e<<5)-e+i,e|=0}return e}function G(r,e){let t={},i=(r||"").split("; ");for(let s of i){let n=s.split("=");h(n[0],e||[])||(t[n[0]]=n[1])}return d(t)?null:t}function b(){function r(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return r()+r()+"-"+r()+"-"+r()+"-"+r()+"-"+r()+r()+r()}function Z(r){if(!r)return null;let t=/(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?)/.exec(r);return t&&t.length>0?t[0]:null}function X(r,e){if(!r||r.length===0)return{};let t=r.split("&");if(t.length===0)return{};let i={};for(let s of t){let n=s.split("=");(!e||!h(n[0],e))&&(i[decodeURIComponent(n[0])]=decodeURIComponent(n[1]))}return d(i)?{}:i}function Y(){return Math.floor(Math.random()*9007199254740992)}function h(r,e,t=!0){if(typeof r!="string")return!1;let i=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;return r=(t?r.toLowerCase():r).replace(i,""),(e||[]).some(s=>{if(typeof s!="string")return!1;if(s&&(s=(t?s.toLowerCase():s).replace(i,"")),!s)return r==null;if(s==="*")return!0;if(r==null)return!1;let n=s[0]==="*";n&&(s=s.slice(1));let o=s[s.length-1]==="*";return o&&(s=s.substring(0,s.length-1)),n&&o?s.length<=r.length&&r.indexOf(s,0)!==-1:n?W(r,s):o?j(r,s):r===s})}function d(r){return r==null?!0:typeof r=="object"?Object.keys(r).length===0:!1}function j(r,e){return r.substring(0,e.length)===e}function W(r,e){return r.indexOf(e,r.length-e.length)!==-1}function E(r,e,t){function i(s,n){let o=[];return JSON.stringify(s,(l,g)=>{if(!h(l,n)){if(typeof g=="object"&&g){if(o.indexOf(g)!==-1)return;o.push(g)}return g}})}if({}.toString.call(r)==="[object Object]"){let s={};for(let n in r){let o=r[n];o!==r&&(s[n]=o)}return i(s,e||[])}if({}.toString.call(r)==="[object Array]"){let s=[];for(let n=0;n<r.length;n++)s[n]=JSON.parse(i(r[n],e||[]));return JSON.stringify(s)}return i(r,e||[])}function w(r,e=!1){if(typeof r=="boolean")return r;if(r===null||typeof r!="number"&&typeof r!="string")return e;switch((r+"").toLowerCase().trim()){case"true":case"yes":case"1":return!0;case"false":case"no":case"0":case null:return!1}return e}var U=class{constructor(){this.priority=20;this.name="ReferenceIdPlugin"}run(e){return!e.event.reference_id&&e.event.type==="error"&&(e.event.reference_id=b().replace("-","").substring(0,10)),Promise.resolve()}};var R=class{constructor(e,t=250){this.config=e;this.maxItems=t;this._handlers=[];this._processingQueue=!1;this._queueTimerId=0;this.QUEUE_PREFIX="q:";this._lastFileTimestamp=0;this._queue=[];this._loadPersistedEvents=!0}async enqueue(e){let t="The event will not be queued.",i=this.config,s=i.services.log;if(!i.enabled){s.info(`Configuration is disabled. ${t}`);return}if(!i.isValid){s.info(`Invalid Api Key. ${t}`);return}if(this.areQueuedItemsDiscarded()){s.info(`Queue items are currently being discarded. ${t}`);return}let n=await this.enqueueEvent(e),o=`type=${e.type} reference_id=${e.reference_id} source=${e.source} message=${e.message}`;s.info(`Enqueued event: ${n} (${o})`)}async process(){let e="The queue will not be processed",{log:t}=this.config.services;if(!this._processingQueue){if(t.trace("Processing queue..."),!this.config.enabled){t.info(`Configuration is disabled: ${e}`);return}if(!this.config.isValid){t.info(`Invalid Api Key: ${e}`);return}this._processingQueue=!0;try{this._loadPersistedEvents&&(this.config.usePersistedQueueStorage&&await this.loadEvents(),this._loadPersistedEvents=!1);let i=this._queue.slice(0,this.config.submissionBatchSize);if(!i||i.length===0){this._processingQueue=!1;return}t.info(`Sending ${i.length} events to ${this.config.serverUrl}`);let s=i.map(o=>o.event),n=await this.config.services.submissionClient.submitEvents(s);await this.processSubmissionResponse(n,i),await this.eventsPosted(s,n),t.trace("Finished processing queue"),this._processingQueue=!1}catch(i){t.error(`Error processing queue: ${i==null?void 0:i.message}`),await this.suspendProcessing(),this._processingQueue=!1}}}startup(){return this._queueTimerId===0&&(this._queueTimerId=setInterval(()=>void this.onProcessQueue(),1e4)),Promise.resolve()}suspend(){return clearInterval(this._queueTimerId),this._queueTimerId=0,Promise.resolve()}async suspendProcessing(e,t,i){let s=this.config,n=new Date;(!e||e<=0)&&(e=Math.ceil(n.getMinutes()/15)*15-n.getMinutes()),s.services.log.info(`Suspending processing for ${e} minutes.`),this._suspendProcessingUntil=new Date(n.getTime()+e*6e4),t&&(this._discardQueuedItemsUntil=this._suspendProcessingUntil),i&&await this.removeEvents(this._queue)}onEventsPosted(e){e&&this._handlers.push(e)}async eventsPosted(e,t){let i=this._handlers;for(let s of i)try{await s(e,t)}catch(n){this.config.services.log.error(`Error calling onEventsPosted handler: ${n==null?void 0:n.message}`)}}areQueuedItemsDiscarded(){return this._discardQueuedItemsUntil&&this._discardQueuedItemsUntil>new Date||!1}isQueueProcessingSuspended(){return this._suspendProcessingUntil&&this._suspendProcessingUntil>new Date||!1}async onProcessQueue(){!this.isQueueProcessingSuspended()&&!this._processingQueue&&await this.process()}async processSubmissionResponse(e,t){let i="The event will not be submitted",s=this.config,n=s.services.log;if(e.status===202){n.info(`Sent ${t.length} events`),await this.removeEvents(t);return}if(e.status===429||e.rateLimitRemaining===0||e.status===503){n.error("Server returned service unavailable"),await this.suspendProcessing();return}if(e.status===402){n.info("Too many events have been submitted, please upgrade your plan"),await this.suspendProcessing(0,!0,!0);return}if(e.status===401||e.status===403){n.info(`Unable to authenticate, please check your configuration. ${i}`),await this.suspendProcessing(15),await this.removeEvents(t);return}if(e.status===400||e.status===404){n.error(`Error while trying to submit data: ${e.message}`),await this.suspendProcessing(60*4),await this.removeEvents(t);return}if(e.status===413){let o="Event submission discarded for being too large.";s.submissionBatchSize>1?(n.error(`${o} Retrying with smaller batch size.`),s.submissionBatchSize=Math.max(1,Math.round(s.submissionBatchSize/1.5))):(n.error(`${o} ${i}`),await this.removeEvents(t));return}n.error(`Error submitting events: ${e.message||"Please check the network tab for more info."}`),await this.suspendProcessing()}async loadEvents(){if(this.config.usePersistedQueueStorage)try{let e=this.config.services.storage,t=await e.keys();for(let i of t)if(i==null?void 0:i.startsWith(this.QUEUE_PREFIX)){let s=await e.getItem(i);s&&this._queue.push({file:i,event:JSON.parse(s)})}}catch(e){this.config.services.log.error(`Error loading queue items from storage: ${e==null?void 0:e.message}`)}}async enqueueEvent(e){this._lastFileTimestamp=Math.max(Date.now(),this._lastFileTimestamp+1);let t=`${this.QUEUE_PREFIX}${this._lastFileTimestamp}.json`,{storage:i,log:s}=this.config.services,n=this.config.usePersistedQueueStorage;if(this._queue.push({file:t,event:e})>this.maxItems){s.trace("Removing oldest queue entry: maxItems exceeded");let o=this._queue.shift();n&&o&&await i.removeItem(o.file)}if(n)try{await i.setItem(t,JSON.stringify(e))}catch(o){s.error(`Error saving queue item to storage: ${o==null?void 0:o.message}`)}return t}async removeEvents(e){let t=e.map(i=>i.file);if(this.config.usePersistedQueueStorage)for(let i of t)try{await this.config.services.storage.removeItem(i)}catch(s){this.config.services.log.error(`Error removing queue item from storage: ${s==null?void 0:s.message}`)}this._queue=this._queue.filter(i=>!t.includes(i.file))}};var H=class{constructor(e,t){this.settings=e;this.version=t}},M=class{static async applySavedServerSettings(e){if(!(e==null?void 0:e.isValid))return;let t=await this.getSavedServerSettings(e);t&&e.applyServerSettings(t)}static async updateSettings(e){if(!(e==null?void 0:e.enabled)||this._isUpdatingSettings)return;this._isUpdatingSettings=!0;let{log:t}=e.services;try{let i="Unable to update settings";if(!e.isValid){t.error(`${i}: ApiKey is not set`);return}let s=e.settingsVersion;t.trace(`Checking for updated settings from: v${s}`);let n=await e.services.submissionClient.getSettings(s);if(n.status===304){t.trace("Settings are up-to-date");return}if(!(n==null?void 0:n.success)||!n.data){t.warn(`${i}: ${n.message}`);return}e.applyServerSettings(n.data),await e.services.storage.setItem(M.SettingsKey,JSON.stringify(n.data)),t.trace(`Updated settings: v${n.data.version}`)}catch(i){t.error(`Error updating settings: ${i==null?void 0:i.message}`)}finally{this._isUpdatingSettings=!1}}static async getSavedServerSettings(e){try{let t=await e.services.storage.getItem(M.SettingsKey);return t&&JSON.parse(t)||new H({},0)}catch{return new H({},0)}}},m=M;m.SettingsKey="settings",m._isUpdatingSettings=!1;var L=class{constructor(e,t,i,s,n){this.status=e;this.message=t;this.rateLimitRemaining=i;this.settingsVersion=s;this.data=n}get success(){return this.status>=200&&this.status<=299}};var k=class{constructor(e,t=(i=>(i=globalThis.fetch)==null?void 0:i.bind(globalThis))()){this.config=e;this.fetch=t;this.RateLimitRemainingHeader="x-ratelimit-remaining";this.ConfigurationVersionHeader="x-exceptionless-configversion"}getSettings(e){let t=`${this.config.serverUrl}/api/v2/projects/config?v=${e}`;return this.apiFetch(t,{method:"GET"})}async submitEvents(e){let t=`${this.config.serverUrl}/api/v2/events`,i=await this.apiFetch(t,{method:"POST",body:JSON.stringify(e)});return await this.updateSettingsVersion(i.settingsVersion),i}async submitUserDescription(e,t){let i=`${this.config.serverUrl}/api/v2/events/by-ref/${encodeURIComponent(e)}/user-description`,s=await this.apiFetch(i,{method:"POST",body:JSON.stringify(t)});return await this.updateSettingsVersion(s.settingsVersion),s}async submitHeartbeat(e,t){let i=`${this.config.heartbeatServerUrl}/api/v2/events/session/heartbeat?id=${e}&close=${t+""}`;return await this.apiFetch(i,{method:"GET"})}async updateSettingsVersion(e){isNaN(e)?this.config.services.log.error("No config version header was returned."):e>this.config.settingsVersion&&await m.updateSettings(this.config)}async apiFetch(e,t){let i={method:t.method,headers:{Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`,"User-Agent":this.config.userAgent},body:t.body};t.method==="POST"&&this.isHeaders(i.headers)&&(i.headers["Content-Type"]="application/json");let s=await this.fetch(e,i),n=parseInt(s.headers.get(this.RateLimitRemainingHeader)||"",10),o=parseInt(s.headers.get(this.ConfigurationVersionHeader)||"",10),l=await s.text(),g=l&&l.length>0?JSON.parse(l):null;return new L(s.status,s.statusText,n,o,g)}isHeaders(e){return e!==void 0}};var $=class{constructor(){this.items=new Map}length(){return Promise.resolve(this.items.size)}clear(){return this.items.clear(),Promise.resolve()}getItem(e){let t=this.items.get(e);return Promise.resolve(t||null)}async key(e){if(e<0)return Promise.resolve(null);let t=await this.keys();if(e>t.length)return Promise.resolve(null);let i=t[e];return Promise.resolve(i||null)}keys(){return Promise.resolve(Array.from(this.items.keys()))}removeItem(e){return this.items.delete(e),Promise.resolve()}setItem(e,t){return this.items.set(e,t),Promise.resolve()}};var D=class{constructor(e="exceptionless-",t=globalThis.localStorage){this.prefix=e;this.storage=t}length(){return Promise.resolve(this.getKeys().length)}clear(){for(let e of this.getKeys())this.storage.removeItem(this.getKey(e));return Promise.resolve()}getItem(e){return Promise.resolve(this.storage.getItem(this.getKey(e)))}key(e){let t=this.getKeys();return Promise.resolve(e<t.length?t[e]:null)}keys(){return Promise.resolve(this.getKeys())}removeItem(e){return this.storage.removeItem(this.getKey(e)),Promise.resolve()}setItem(e,t){return this.storage.setItem(this.getKey(e),t),Promise.resolve()}getKeys(){return Object.keys(this.storage).filter(e=>e.startsWith(this.prefix)).map(e=>e==null?void 0:e.substr(this.prefix.length))}getKey(e){return this.prefix+e}};var T=class{constructor(){this.defaultTags=[];this.defaultData={};this.enabled=!0;this.submissionBatchSize=50;this.settings={};this.settingsVersion=0;this.apiKey="";this._serverUrl="https://collector.exceptionless.io";this.configServerUrl="https://config.exceptionless.io";this.heartbeatServerUrl="https://heartbeat.exceptionless.io";this._updateSettingsWhenIdleInterval=12e4;this._dataExclusions=[];this._includePrivateInformation=!0;this._includeUserName=!0;this._includeMachineName=!0;this._includeIpAddress=!0;this._includeCookies=!0;this._includePostData=!0;this._includeQueryString=!0;this._userAgentBotPatterns=[];this._plugins=[];this._subscribers=[];this.usePersistedQueueStorage=!1;this.services={lastReferenceIdManager:new S,log:new x,storage:new $,queue:new R(this),submissionClient:new k(this)}}get isValid(){var e;return((e=this.apiKey)==null?void 0:e.length)>=10}get serverUrl(){return this._serverUrl}set serverUrl(e){e&&(this._serverUrl=e,this.configServerUrl=e,this.heartbeatServerUrl=e)}get updateSettingsWhenIdleInterval(){return this._updateSettingsWhenIdleInterval}set updateSettingsWhenIdleInterval(e){typeof e=="number"&&(e<=0?e=-1:e>0&&e<12e4&&(e=12e4),this._updateSettingsWhenIdleInterval=e)}get dataExclusions(){let e=this.settings["@@DataExclusions"];return this._dataExclusions.concat(e&&e.split(",")||[])}addDataExclusions(...e){this._dataExclusions=[...this._dataExclusions,...e]}get includePrivateInformation(){return this._includePrivateInformation}set includePrivateInformation(e){let t=e===!0;this._includePrivateInformation=t,this._includeUserName=t,this._includeMachineName=t,this._includeIpAddress=t,this._includeCookies=t,this._includePostData=t,this._includeQueryString=t}get includeUserName(){return this._includeUserName}set includeUserName(e){this._includeUserName=e===!0}get includeMachineName(){return this._includeMachineName}set includeMachineName(e){this._includeMachineName=e===!0}get includeIpAddress(){return this._includeIpAddress}set includeIpAddress(e){this._includeIpAddress=e===!0}get includeCookies(){return this._includeCookies}set includeCookies(e){this._includeCookies=e===!0}get includePostData(){return this._includePostData}set includePostData(e){this._includePostData=e===!0}get includeQueryString(){return this._includeQueryString}set includeQueryString(e){this._includeQueryString=e===!0}get userAgentBotPatterns(){let e=this.settings["@@UserAgentBotPatterns"];return this._userAgentBotPatterns.concat(e&&e.split(",")||[])}addUserAgentBotPatterns(...e){this._userAgentBotPatterns=[...this._userAgentBotPatterns,...e]}get plugins(){return this._plugins.sort((e,t)=>e==null&&t==null?0:(e==null?void 0:e.priority)==null?-1:(t==null?void 0:t.priority)==null?1:e.priority==t.priority?0:e.priority>t.priority?1:-1)}addPlugin(e,t,i){let s=i?{name:e,priority:t,run:i}:e;if(!s||!(s.startup||s.run)){this.services.log.error("Add plugin failed: startup or run method not defined");return}s.name||(s.name=b()),s.priority||(s.priority=0);let n=!1,o=this._plugins;for(let l of o)if(l.name===s.name){n=!0;break}n||o.push(s)}removePlugin(e){let t=typeof e=="string"?e:e.name||"";if(!t){this.services.log.error("Remove plugin failed: Plugin name not defined");return}let i=this._plugins;for(let s=0;s<i.length;s++)if(i[s].name===t){i.splice(s,1);break}}get version(){return this.defaultData[u.Version]}set version(e){e?this.defaultData[u.Version]=e:delete this.defaultData[u.Version]}setUserIdentity(e,t){let i=typeof e!="string"?e:{identity:e,name:t},s=!i||!i.identity&&!i.name;s?delete this.defaultData[u.UserInfo]:this.defaultData[u.UserInfo]=i,this.services.log.info(`user identity: ${s?"null":i.identity}`)}get userAgent(){return"exceptionless-js/2.0.0-beta1"}useSessions(e=!0,t=3e4){e&&this.addPlugin(new C(t))}useReferenceIds(){this.addPlugin(new U)}useLocalStorage(){this.services.storage=new D}applyServerSettings(e){this.originalSettings||(this.originalSettings=JSON.parse(JSON.stringify(this.settings))),this.services.log.trace(`Applying saved settings: v${e.version}`),this.settings=Object.assign(this.originalSettings,e.settings),this.settingsVersion=e.version,this.notifySubscribers()}useDebugLogger(){this.services.log=new y}subscribeServerSettingsChange(e){e&&this._subscribers.push(e)}notifySubscribers(){for(let e of this._subscribers)try{e(this)}catch(t){this.services.log.error(`Error calling subscribe handler: ${t==null?void 0:t.message}`)}}};var q=class{constructor(){this.priority=10;this.name="ConfigurationDefaultsPlugin"}run(e){let t=e.client.config,i=e.event;t.defaultTags&&(i.tags=[...i.tags||[],...t.defaultTags]);let s=t.defaultData||{};if(s){i.data||(i.data={});for(let n in t.defaultData||{})i.data[n]===void 0&&!d(s[n])&&(i.data[n]=s[n])}return Promise.resolve()}};var Q=class{constructor(e=()=>Date.now(),t=3e4){this.priority=1010;this.name="DuplicateCheckerPlugin";this._mergedEvents=[];this._processedHashCodes=[];this._intervalId=0;this._getCurrentTime=e,this._interval=t}startup(){return clearInterval(this._intervalId),this._intervalId=setInterval(()=>void this.submitEvents(),this._interval),Promise.resolve()}async suspend(){clearInterval(this._intervalId),this._intervalId=0,await this.submitEvents()}run(e){var n;function t(o){let l=0;for(;o;)o.message&&o.message.length&&(l+=l*397^_(o.message)),o.stack_trace&&o.stack_trace.length&&(l+=l*397^_(JSON.stringify(o.stack_trace))),o=o.inner;return l}let i=(n=e.event.data)==null?void 0:n[u.Error],s=t(i);if(s){let o=e.event.count||1,l=this._getCurrentTime(),g=this._mergedEvents.filter(c=>c.hashCode===s)[0];if(g&&(g.incrementCount(o),g.updateDate(e.event.date),e.log.info("Ignoring duplicate event with hash: "+s),e.cancelled=!0),!e.cancelled&&this._processedHashCodes.some(c=>c.hash===s&&c.timestamp>=l-this._interval)&&(e.log.trace("Adding event with hash: "+s),this._mergedEvents.push(new J(s,e,o)),e.cancelled=!0),!e.cancelled)for(e.log.trace(`Enqueueing event with hash: ${s} to cache`),this._processedHashCodes.push({hash:s,timestamp:l});this._processedHashCodes.length>50;)this._processedHashCodes.shift()}return Promise.resolve()}async submitEvents(){var e;for(;this._mergedEvents.length>0;)await((e=this._mergedEvents.shift())==null?void 0:e.resubmit())}},J=class{constructor(e,t,i){this.hashCode=e,this._context=t,this._count=i}incrementCount(e){this._count+=e}async resubmit(){this._context.event.count=this._count,await this._context.client.config.services.queue.enqueue(this._context.event)}updateDate(e){let t=this._context.event;e&&t.date&&e>t.date&&(t.date=e)}};var B=class{constructor(){this.priority=45;this.name="EventExclusionPlugin"}run(e){let t=e.event,i=e.log,s=e.client.config.settings;if(t.type==="log"){let n=this.getMinLogLevel(s,t.source),o=this.getLogLevel(t.data&&t.data[u.Level]);o!==-1&&(o===6||o<n)&&(i.info("Cancelling log event due to minimum log level."),e.cancelled=!0)}else if(t.type==="error"){let n=t.data&&t.data[u.Error];for(;!e.cancelled&&n;)this.getTypeAndSourceSetting(s,t.type,n.type,!0)===!1&&(i.info(`Cancelling error from excluded exception type: ${n.type}`),e.cancelled=!0),n=n.inner}else this.getTypeAndSourceSetting(s,t.type,t.source,!0)===!1&&(i.info(`Cancelling event from excluded type: ${t.type} and source: ${t.source}`),e.cancelled=!0);return Promise.resolve()}getLogLevel(e){switch((e||"").toLowerCase().trim()){case"trace":case"true":case"1":case"yes":return 0;case"debug":return 1;case"info":return 2;case"warn":return 3;case"error":return 4;case"fatal":return 5;case"off":case"false":case"0":case"no":return 6;default:return-1}}getMinLogLevel(e,t){return this.getLogLevel(this.getTypeAndSourceSetting(e,"log",t,"other")+"")}getTypeAndSourceSetting(e={},t,i,s){if(!t)return s;i||(i="");let n=t==="log",o=`@@${t}:`,l=e[o+i];if(l)return n?l:w(l);let g=Object.keys(e).sort((c,I)=>I.length-c.length||c.localeCompare(I));for(let c of g){if(!j(c.toLowerCase(),o))continue;let I=c.substring(o.length);if(h(i,[I]))return n?e[c]:w(e[c])}return s}};var O=["arguments","column","columnNumber","description","fileName","message","name","number","line","lineNumber","opera#sourceloc","sourceId","sourceURL","stack","stackArray","stacktrace"],N=class{constructor(){this.priority=30;this.name="SimpleErrorPlugin"}async run(e){let t=e.eventContext.getException();if(t&&(e.event.type="error",e.event.data&&!e.event.data[u.SimpleError])){let i={type:t.name||"Error",message:t.message,stack_trace:t.stack,data:{}},s=e.client.config.dataExclusions.concat(O),n=JSON.parse(E(t,s));d(n)||(i.data["@ext"]=n),e.event.data[u.SimpleError]=i}return Promise.resolve()}};var A=class{constructor(){this.priority=100;this.name="SubmissionMethodPlugin"}run(e){let t=e.eventContext.getSubmissionMethod();return t&&e.event.data&&(e.event.data[u.SubmissionMethod]=t),Promise.resolve()}};var p;(function(i){i.Exception="@@_Exception",i.IsUnhandledError="@@_IsUnhandledError",i.SubmissionMethod="@@_SubmissionMethod"})(p||(p={}));var f=class{getException(){return this[p.Exception]||null}setException(e){e&&(this[p.Exception]=e)}get hasException(){return!!this[p.Exception]}markAsUnhandledError(){this[p.IsUnhandledError]=!0}get isUnhandledError(){return!!this[p.IsUnhandledError]}getSubmissionMethod(){return this[p.SubmissionMethod]||null}setSubmissionMethod(e){e&&(this[p.SubmissionMethod]=e)}};var P=class{constructor(e){this.client=e}get log(){return this.client.config.services.log}};var F=class{constructor(e,t,i){this.client=e;this.event=t;this.eventContext=i;this.cancelled=!1;this.eventContext||(this.eventContext=new f)}get log(){return this.client.config.services.log}};var v=class{static async startup(e){for(let t of e.client.config.plugins)if(!!t.startup)try{await t.startup(e)}catch(i){e.log.error(`Error running plugin startup"${t.name}": ${i==null?void 0:i.message}`)}}static async suspend(e){for(let t of e.client.config.plugins)if(!!t.suspend)try{await t.suspend(e)}catch(i){e.log.error(`Error running plugin suspend"${t.name}": ${i==null?void 0:i.message}`)}}static async run(e){for(let t of e.client.config.plugins){if(e.cancelled)break;if(!!t.run)try{await t.run(e)}catch(i){e.cancelled=!0,e.log.error(`Error running plugin "${t.name}": ${i==null?void 0:i.message}. Discarding Event.`)}}}static addDefaultPlugins(e){e.addPlugin(new q),e.addPlugin(new N),e.addPlugin(new Q),e.addPlugin(new B),e.addPlugin(new A)}};var V=class{constructor(e,t,i){this._validIdentifierErrorMessage="must contain between 8 and 100 alphanumeric or '-' characters.";this.target=e,this.client=t,this.context=i||new f}setType(e){return e&&(this.target.type=e),this}setSource(e){return e&&(this.target.source=e),this}setReferenceId(e){if(!this.isValidIdentifier(e))throw new Error(`ReferenceId ${this._validIdentifierErrorMessage}`);return this.target.reference_id=e,this}setEventReference(e,t){if(!e)throw new Error("Invalid name");if(!t||!this.isValidIdentifier(t))throw new Error(`Id ${this._validIdentifierErrorMessage}`);return this.setProperty("@ref:"+e,t),this}setMessage(e){return e&&(this.target.message=e),this}setGeo(e,t){if(e<-90||e>90)throw new Error("Must be a valid latitude value between -90.0 and 90.0.");if(t<-180||t>180)throw new Error("Must be a valid longitude value between -180.0 and 180.0.");return this.target.geo=`${e},${t}`,this}setUserIdentity(e,t){let i=typeof e!="string"?e:{identity:e,name:t};return!i||!i.identity&&!i.name?this:(this.setProperty(u.UserInfo,i),this)}setUserDescription(e,t){return e&&t&&this.setProperty(u.UserDescription,{email_address:e,description:t}),this}setManualStackingInfo(e,t){if(e){let i={signature_data:e};t&&(i.title=t),this.setProperty(u.ManualStackingInfo,i)}return this}setManualStackingKey(e,t){if(e){let i={ManualStackingKey:e};this.setManualStackingInfo(i,t)}return this}setValue(e){return e&&(this.target.value=e),this}addTags(...e){return this.target.tags=[...this.target.tags||[],...e],this}setProperty(e,t,i,s){if(!e||t===void 0||t==null)return this;this.target.data||(this.target.data={});let n=JSON.parse(E(t,this.client.config.dataExclusions.concat(s||[]),i));return d(n)||(this.target.data[e]=n),this}markAsCritical(e){return e&&this.addTags("Critical"),this}addRequestInfo(e){return e&&(this.context[u.RequestInfo]=e),this}submit(){return this.client.submitEvent(this.target,this.context)}isValidIdentifier(e){if(!e)return!0;if(e.length<8||e.length>100)return!1;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t),s=i>=48&&i<=57,n=i>=65&&i<=90||i>=97&&i<=122;if(!(s||n)&&!(i===45))return!1}return!0}};var z=class{constructor(e=new T){this.config=e;this._intervalId=0;this._timeoutId=0}async startup(e){e&&(v.addDefaultPlugins(this.config),typeof e=="string"?this.config.apiKey=e:e(this.config),this.config.services.queue.onEventsPosted(()=>Promise.resolve(this.updateSettingsTimer())),await m.applySavedServerSettings(this.config)),this.updateSettingsTimer(!!e),await v.startup(new P(this));let{queue:t}=this.config.services;await t.startup(),this.config.usePersistedQueueStorage&&await t.process()}async suspend(){await v.suspend(new P(this));let{queue:e}=this.config.services;await e.suspend(),await e.process(),this.suspendSettingsTimer()}suspendSettingsTimer(){clearTimeout(this._timeoutId),this._timeoutId=0,clearInterval(this._intervalId),this._intervalId=0}async processQueue(){await this.config.services.queue.process()}updateSettingsTimer(e=!1){this.suspendSettingsTimer();let t=this.config.updateSettingsWhenIdleInterval;if(t>0){let i=t;e&&(i=this.config.settingsVersion>0?15e3:5e3),this.config.services.log.info(`Update settings every ${t}ms (${i||0}ms delay)`);let s=()=>void m.updateSettings(this.config);i<t&&(this._timeoutId=setTimeout(s,i)),this._intervalId=setInterval(s,t)}}createException(e){let t=new f;return t.setException(e),this.createEvent(t).setType("error")}submitException(e){return this.createException(e).submit()}createUnhandledException(e,t){let i=this.createException(e);return i.context.markAsUnhandledError(),i.context.setSubmissionMethod(t||""),i}submitUnhandledException(e,t){return this.createUnhandledException(e,t).submit()}createFeatureUsage(e){return this.createEvent().setType("usage").setSource(e)}submitFeatureUsage(e){return this.createFeatureUsage(e).submit()}createLog(e,t,i){let s=this.createEvent().setType("log");if(i)s=s.setSource(e).setMessage(t).setProperty(u.Level,i);else if(t)s=s.setSource(e).setMessage(t);else{s=s.setMessage(e);try{let n=this.createLog.caller;s=s.setSource(n&&n.caller&&n.caller.name)}catch(n){this.config.services.log.trace("Unable to resolve log source: "+n.message)}}return s}submitLog(e,t,i){return this.createLog(e,t,i).submit()}createNotFound(e){return this.createEvent().setType("404").setSource(e)}submitNotFound(e){return this.createNotFound(e).submit()}createSessionStart(){return this.createEvent().setType("session")}submitSessionStart(){return this.createSessionStart().submit()}async submitSessionEnd(e){e&&this.config.enabled&&this.config.isValid&&(this.config.services.log.info(`Submitting session end: ${e}`),await this.config.services.submissionClient.submitHeartbeat(e,!0))}async submitSessionHeartbeat(e){e&&this.config.enabled&&this.config.isValid&&(this.config.services.log.info(`Submitting session heartbeat: ${e}`),await this.config.services.submissionClient.submitHeartbeat(e,!1))}createEvent(e){return new V({date:new Date},this,e)}async submitEvent(e,t){let i=new F(this,e,t!=null?t:new f);if(!e)return i.cancelled=!0,i;if(!this.config.enabled||!this.config.isValid)return this.config.services.log.info("Event submission is currently disabled."),i.cancelled=!0,i;if(e.data||(e.data={}),(!e.tags||!e.tags.length)&&(e.tags=[]),await v.run(i),i.cancelled)return i;let s=i.event;return(!s.type||s.type.length===0)&&(s.type="log"),s.date||(s.date=new Date),await this.config.services.queue.enqueue(s),s.reference_id&&s.reference_id.length>0&&(i.log.info(`Setting last reference id "${s.reference_id}"`),this.config.services.lastReferenceIdManager.setLast(s.reference_id)),i}async updateUserEmailAndDescription(e,t,i){if(!e||!t||!i||!this.config.enabled||!this.config.isValid)return;let s={email_address:t,description:i},n=await this.config.services.submissionClient.submitUserDescription(e,s);n.success||this.config.services.log.error(`Failed to submit user email and description for event "${e}": ${n.status} ${n.message}`)}getLastReferenceId(){return this.config.services.lastReferenceIdManager.getLast()}};export{T as Configuration,q as ConfigurationDefaultsPlugin,y as ConsoleLog,R as DefaultEventQueue,S as DefaultLastReferenceIdManager,k as DefaultSubmissionClient,Q as DuplicateCheckerPlugin,V as EventBuilder,f as EventContext,B as EventExclusionPlugin,F as EventPluginContext,v as EventPluginManager,z as ExceptionlessClient,C as HeartbeatPlugin,O as IgnoredErrorProperties,$ as InMemoryStorage,u as KnownEventDataKeys,D as LocalStorage,x as NullLog,P as PluginContext,U as ReferenceIdPlugin,L as Response,m as SettingsManager,N as SimpleErrorPlugin,A as SubmissionMethodPlugin,W as endsWith,G as getCookies,_ as getHashCode,b as guid,d as isEmpty,h as isMatch,X as parseQueryString,Z as parseVersion,Y as randomNumber,j as startsWith,E as stringify,w as toBoolean};
var S=class{constructor(){this._lastReferenceId=null}getLast(){return this._lastReferenceId}clearLast(){this._lastReferenceId=null}setLast(e){this._lastReferenceId=e}};var y=class{trace(e){this.log("debug",e)}info(e){this.log("info",e)}warn(e){this.log("warn",e)}error(e){this.log("error",e)}log(e,t){if(console){let i=`Exceptionless:${new Date().toISOString()} [${e}] ${t}`,s=console[e];s?s(i):console.log&&console.log(i)}}};var x=class{trace(e){}info(e){}warn(e){}error(e){}};var u;(function(a){a.Error="@error",a.SimpleError="@simple_error",a.RequestInfo="@request",a.TraceLog="@trace",a.EnvironmentInfo="@environment",a.UserInfo="@user",a.UserDescription="@user_description",a.Version="@version",a.Level="@level",a.SubmissionMethod="@submission_method",a.ManualStackingInfo="@stack"})(u||(u={}));var C=class{constructor(e=3e4){this.priority=100;this.name="HeartbeatPlugin";this._intervalId=0;this._interval=e>=3e4?e:6e4}startup(){return clearInterval(this._intervalId),this._intervalId=0,Promise.resolve()}suspend(){return clearInterval(this._intervalId),this._intervalId=0,Promise.resolve()}run(e){var i;if(this._interval<=0)return Promise.resolve();clearInterval(this._intervalId),this._intervalId=0;let t=(i=e.event.data)==null?void 0:i[u.UserInfo];return(t==null?void 0:t.identity)&&(this._intervalId=setInterval(()=>void e.client.submitSessionHeartbeat(t.identity),this._interval)),Promise.resolve()}};var _=class{constructor(e,t=250){this.config=e;this.maxItems=t;this._handlers=[];this._processingQueue=!1;this._queueTimerId=0;this.QUEUE_PREFIX="q:";this._lastFileTimestamp=0;this._queue=[];this._loadPersistedEvents=!0}async enqueue(e){let t="The event will not be queued.",i=this.config,s=i.services.log;if(!i.enabled){s.info(`Configuration is disabled. ${t}`);return}if(!i.isValid){s.info(`Invalid Api Key. ${t}`);return}if(this.areQueuedItemsDiscarded()){s.info(`Queue items are currently being discarded. ${t}`);return}let n=await this.enqueueEvent(e),o=`type=${e.type} reference_id=${e.reference_id} source=${e.source} message=${e.message}`;s.info(`Enqueued event: ${n} (${o})`)}async process(){let e="The queue will not be processed",{log:t}=this.config.services;if(!this._processingQueue){if(t.trace("Processing queue..."),!this.config.enabled){t.info(`Configuration is disabled: ${e}`);return}if(!this.config.isValid){t.info(`Invalid Api Key: ${e}`);return}this._processingQueue=!0;try{this._loadPersistedEvents&&(this.config.usePersistedQueueStorage&&await this.loadEvents(),this._loadPersistedEvents=!1);let i=this._queue.slice(0,this.config.submissionBatchSize);if(!i||i.length===0){this._processingQueue=!1;return}t.info(`Sending ${i.length} events to ${this.config.serverUrl}`);let s=i.map(o=>o.event),n=await this.config.services.submissionClient.submitEvents(s);await this.processSubmissionResponse(n,i),await this.eventsPosted(s,n),t.trace("Finished processing queue"),this._processingQueue=!1}catch(i){t.error(`Error processing queue: ${i==null?void 0:i.message}`),await this.suspendProcessing(),this._processingQueue=!1}}}startup(){return this._queueTimerId===0&&(this._queueTimerId=setInterval(()=>void this.onProcessQueue(),1e4)),Promise.resolve()}suspend(){return clearInterval(this._queueTimerId),this._queueTimerId=0,Promise.resolve()}async suspendProcessing(e,t,i){let s=this.config,n=new Date;(!e||e<=0)&&(e=Math.ceil(n.getMinutes()/15)*15-n.getMinutes()),s.services.log.info(`Suspending processing for ${e} minutes.`),this._suspendProcessingUntil=new Date(n.getTime()+e*6e4),t&&(this._discardQueuedItemsUntil=this._suspendProcessingUntil),i&&await this.removeEvents(this._queue)}onEventsPosted(e){e&&this._handlers.push(e)}async eventsPosted(e,t){let i=this._handlers;for(let s of i)try{await s(e,t)}catch(n){this.config.services.log.error(`Error calling onEventsPosted handler: ${n==null?void 0:n.message}`)}}areQueuedItemsDiscarded(){return this._discardQueuedItemsUntil&&this._discardQueuedItemsUntil>new Date||!1}isQueueProcessingSuspended(){return this._suspendProcessingUntil&&this._suspendProcessingUntil>new Date||!1}async onProcessQueue(){!this.isQueueProcessingSuspended()&&!this._processingQueue&&await this.process()}async processSubmissionResponse(e,t){let i="The event will not be submitted",s=this.config,n=s.services.log;if(e.status===202){n.info(`Sent ${t.length} events`),await this.removeEvents(t);return}if(e.status===429||e.rateLimitRemaining===0||e.status===503){n.error("Server returned service unavailable"),await this.suspendProcessing();return}if(e.status===402){n.info("Too many events have been submitted, please upgrade your plan"),await this.suspendProcessing(0,!0,!0);return}if(e.status===401||e.status===403){n.info(`Unable to authenticate, please check your configuration. ${i}`),await this.suspendProcessing(15),await this.removeEvents(t);return}if(e.status===400||e.status===404){n.error(`Error while trying to submit data: ${e.message}`),await this.suspendProcessing(60*4),await this.removeEvents(t);return}if(e.status===413){let o="Event submission discarded for being too large.";s.submissionBatchSize>1?(n.error(`${o} Retrying with smaller batch size.`),s.submissionBatchSize=Math.max(1,Math.round(s.submissionBatchSize/1.5))):(n.error(`${o} ${i}`),await this.removeEvents(t));return}n.error(`Error submitting events: ${e.message||"Please check the network tab for more info."}`),await this.suspendProcessing()}async loadEvents(){if(this.config.usePersistedQueueStorage)try{let e=this.config.services.storage,t=await e.keys();for(let i of t)if(i==null?void 0:i.startsWith(this.QUEUE_PREFIX)){let s=await e.getItem(i);s&&this._queue.push({file:i,event:JSON.parse(s)})}}catch(e){this.config.services.log.error(`Error loading queue items from storage: ${e==null?void 0:e.message}`)}}async enqueueEvent(e){this._lastFileTimestamp=Math.max(Date.now(),this._lastFileTimestamp+1);let t=`${this.QUEUE_PREFIX}${this._lastFileTimestamp}.json`,{storage:i,log:s}=this.config.services,n=this.config.usePersistedQueueStorage;if(this._queue.push({file:t,event:e})>this.maxItems){s.trace("Removing oldest queue entry: maxItems exceeded");let o=this._queue.shift();n&&o&&await i.removeItem(o.file)}if(n)try{await i.setItem(t,JSON.stringify(e))}catch(o){s.error(`Error saving queue item to storage: ${o==null?void 0:o.message}`)}return t}async removeEvents(e){let t=e.map(i=>i.file);if(this.config.usePersistedQueueStorage)for(let i of t)try{await this.config.services.storage.removeItem(i)}catch(s){this.config.services.log.error(`Error removing queue item from storage: ${s==null?void 0:s.message}`)}this._queue=this._queue.filter(i=>!t.includes(i.file))}};var H=class{constructor(e,t){this.settings=e;this.version=t}},j=class{static async applySavedServerSettings(e){if(!(e==null?void 0:e.isValid))return;let t=await this.getSavedServerSettings(e);t&&e.applyServerSettings(t)}static async updateSettings(e){if(!(e==null?void 0:e.enabled)||this._isUpdatingSettings)return;this._isUpdatingSettings=!0;let{log:t}=e.services;try{let i="Unable to update settings";if(!e.isValid){t.error(`${i}: ApiKey is not set`);return}let s=e.settingsVersion;t.trace(`Checking for updated settings from: v${s}`);let n=await e.services.submissionClient.getSettings(s);if(n.status===304){t.trace("Settings are up-to-date");return}if(!(n==null?void 0:n.success)||!n.data){t.warn(`${i}: ${n.message}`);return}e.applyServerSettings(n.data),await e.services.storage.setItem(j.SettingsKey,JSON.stringify(n.data)),t.trace(`Updated settings: v${n.data.version}`)}catch(i){t.error(`Error updating settings: ${i==null?void 0:i.message}`)}finally{this._isUpdatingSettings=!1}}static async getSavedServerSettings(e){try{let t=await e.services.storage.getItem(j.SettingsKey);return t&&JSON.parse(t)||new H({},0)}catch{return new H({},0)}}},d=j;d.SettingsKey="settings",d._isUpdatingSettings=!1;var w=class{constructor(e,t,i,s,n){this.status=e;this.message=t;this.rateLimitRemaining=i;this.settingsVersion=s;this.data=n}get success(){return this.status>=200&&this.status<=299}};var U=class{constructor(e,t=(i=>(i=globalThis.fetch)==null?void 0:i.bind(globalThis))()){this.config=e;this.fetch=t;this.RateLimitRemainingHeader="x-ratelimit-remaining";this.ConfigurationVersionHeader="x-exceptionless-configversion"}getSettings(e){let t=`${this.config.serverUrl}/api/v2/projects/config?v=${e}`;return this.apiFetch(t,{method:"GET"})}async submitEvents(e){let t=`${this.config.serverUrl}/api/v2/events`,i=await this.apiFetch(t,{method:"POST",body:JSON.stringify(e)});return await this.updateSettingsVersion(i.settingsVersion),i}async submitUserDescription(e,t){let i=`${this.config.serverUrl}/api/v2/events/by-ref/${encodeURIComponent(e)}/user-description`,s=await this.apiFetch(i,{method:"POST",body:JSON.stringify(t)});return await this.updateSettingsVersion(s.settingsVersion),s}async submitHeartbeat(e,t){let i=`${this.config.heartbeatServerUrl}/api/v2/events/session/heartbeat?id=${e}&close=${t+""}`;return await this.apiFetch(i,{method:"GET"})}async updateSettingsVersion(e){isNaN(e)?this.config.services.log.error("No config version header was returned."):e>this.config.settingsVersion&&await d.updateSettings(this.config)}async apiFetch(e,t){let i={method:t.method,headers:{Accept:"application/json",Authorization:`Bearer ${this.config.apiKey}`,"User-Agent":this.config.userAgent},body:t.body};t.method==="POST"&&this.isHeaders(i.headers)&&(i.headers["Content-Type"]="application/json");let s=await this.fetch(e,i),n=parseInt(s.headers.get(this.RateLimitRemainingHeader)||"",10),o=parseInt(s.headers.get(this.ConfigurationVersionHeader)||"",10),l=await s.text(),g=l&&l.length>0?JSON.parse(l):null;return new w(s.status,s.statusText,n,o,g)}isHeaders(e){return e!==void 0}};function R(r){if(!r||r.length===0)return 0;let e=0;for(let t=0;t<r.length;t++){let i=r.charCodeAt(t);e=(e<<5)-e+i,e|=0}return e}function G(r,e){let t={},i=(r||"").split("; ");for(let s of i){let n=s.split("=");h(n[0],e||[])||(t[n[0]]=n[1])}return m(t)?null:t}function b(){function r(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}return r()+r()+"-"+r()+"-"+r()+"-"+r()+"-"+r()+r()+r()}function Z(r){if(!r)return null;let t=/(v?((\d+)\.(\d+)(\.(\d+))?)(?:-([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?(?:\+([\dA-Za-z-]+(?:\.[\dA-Za-z-]+)*))?)/.exec(r);return t&&t.length>0?t[0]:null}function X(r,e){if(!r||r.length===0)return{};let t=r.split("&");if(t.length===0)return{};let i={};for(let s of t){let n=s.split("=");(!e||!h(n[0],e))&&(i[decodeURIComponent(n[0])]=decodeURIComponent(n[1]))}return m(i)?{}:i}function Y(){return Math.floor(Math.random()*9007199254740992)}function h(r,e,t=!0){if(typeof r!="string")return!1;let i=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g;return r=(t?r.toLowerCase():r).replace(i,""),(e||[]).some(s=>{if(typeof s!="string")return!1;if(s&&(s=(t?s.toLowerCase():s).replace(i,"")),!s)return r==null;if(s==="*")return!0;if(r==null)return!1;let n=s[0]==="*";n&&(s=s.slice(1));let o=s[s.length-1]==="*";return o&&(s=s.substring(0,s.length-1)),n&&o?s.length<=r.length&&r.indexOf(s,0)!==-1:n?W(r,s):o?M(r,s):r===s})}function m(r){return r==null?!0:typeof r=="object"?Object.keys(r).length===0:!1}function M(r,e){return r.substring(0,e.length)===e}function W(r,e){return r.indexOf(e,r.length-e.length)!==-1}function E(r,e,t){function i(s,n){let o=[];return JSON.stringify(s,(l,g)=>{if(!h(l,n)){if(typeof g=="object"&&g){if(o.indexOf(g)!==-1)return;o.push(g)}return g}})}if({}.toString.call(r)==="[object Object]"){let s={};for(let n in r){let o=r[n];o!==r&&(s[n]=o)}return i(s,e||[])}if({}.toString.call(r)==="[object Array]"){let s=[];for(let n=0;n<r.length;n++)s[n]=JSON.parse(i(r[n],e||[]));return JSON.stringify(s)}return i(r,e||[])}function L(r,e=!1){if(typeof r=="boolean")return r;if(r===null||typeof r!="number"&&typeof r!="string")return e;switch((r+"").toLowerCase().trim()){case"true":case"yes":case"1":return!0;case"false":case"no":case"0":case null:return!1}return e}var k=class{constructor(){this.items=new Map}length(){return Promise.resolve(this.items.size)}clear(){return this.items.clear(),Promise.resolve()}getItem(e){let t=this.items.get(e);return Promise.resolve(t||null)}async key(e){if(e<0)return Promise.resolve(null);let t=await this.keys();if(e>t.length)return Promise.resolve(null);let i=t[e];return Promise.resolve(i||null)}keys(){return Promise.resolve(Array.from(this.items.keys()))}removeItem(e){return this.items.delete(e),Promise.resolve()}setItem(e,t){return this.items.set(e,t),Promise.resolve()}};var $=class{constructor(e="exceptionless-",t=globalThis.localStorage){this.prefix=e;this.storage=t}length(){return Promise.resolve(this.getKeys().length)}clear(){for(let e of this.getKeys())this.storage.removeItem(this.getKey(e));return Promise.resolve()}getItem(e){return Promise.resolve(this.storage.getItem(this.getKey(e)))}key(e){let t=this.getKeys();return Promise.resolve(e<t.length?t[e]:null)}keys(){return Promise.resolve(this.getKeys())}removeItem(e){return this.storage.removeItem(this.getKey(e)),Promise.resolve()}setItem(e,t){return this.storage.setItem(this.getKey(e),t),Promise.resolve()}getKeys(){return Object.keys(this.storage).filter(e=>e.startsWith(this.prefix)).map(e=>e==null?void 0:e.substr(this.prefix.length))}getKey(e){return this.prefix+e}};var D=class{constructor(){this.defaultTags=[];this.defaultData={};this.enabled=!0;this.submissionBatchSize=50;this.settings={};this.settingsVersion=0;this.apiKey="";this._serverUrl="https://collector.exceptionless.io";this.configServerUrl="https://config.exceptionless.io";this.heartbeatServerUrl="https://heartbeat.exceptionless.io";this._updateSettingsWhenIdleInterval=12e4;this._dataExclusions=[];this._includePrivateInformation=!0;this._includeUserName=!0;this._includeMachineName=!0;this._includeIpAddress=!0;this._includeCookies=!0;this._includePostData=!0;this._includeQueryString=!0;this._userAgentBotPatterns=[];this._plugins=[];this._subscribers=[];this.usePersistedQueueStorage=!1;this.services={lastReferenceIdManager:new S,log:new x,storage:new k,queue:new _(this),submissionClient:new U(this)}}get isValid(){var e;return((e=this.apiKey)==null?void 0:e.length)>=10}get serverUrl(){return this._serverUrl}set serverUrl(e){e&&(this._serverUrl=e,this.configServerUrl=e,this.heartbeatServerUrl=e)}get updateSettingsWhenIdleInterval(){return this._updateSettingsWhenIdleInterval}set updateSettingsWhenIdleInterval(e){typeof e=="number"&&(e<=0?e=-1:e>0&&e<12e4&&(e=12e4),this._updateSettingsWhenIdleInterval=e)}get dataExclusions(){let e=this.settings["@@DataExclusions"];return this._dataExclusions.concat(e&&e.split(",")||[])}addDataExclusions(...e){this._dataExclusions=[...this._dataExclusions,...e]}get includePrivateInformation(){return this._includePrivateInformation}set includePrivateInformation(e){let t=e===!0;this._includePrivateInformation=t,this._includeUserName=t,this._includeMachineName=t,this._includeIpAddress=t,this._includeCookies=t,this._includePostData=t,this._includeQueryString=t}get includeUserName(){return this._includeUserName}set includeUserName(e){this._includeUserName=e===!0}get includeMachineName(){return this._includeMachineName}set includeMachineName(e){this._includeMachineName=e===!0}get includeIpAddress(){return this._includeIpAddress}set includeIpAddress(e){this._includeIpAddress=e===!0}get includeCookies(){return this._includeCookies}set includeCookies(e){this._includeCookies=e===!0}get includePostData(){return this._includePostData}set includePostData(e){this._includePostData=e===!0}get includeQueryString(){return this._includeQueryString}set includeQueryString(e){this._includeQueryString=e===!0}get userAgentBotPatterns(){let e=this.settings["@@UserAgentBotPatterns"];return this._userAgentBotPatterns.concat(e&&e.split(",")||[])}addUserAgentBotPatterns(...e){this._userAgentBotPatterns=[...this._userAgentBotPatterns,...e]}get plugins(){return this._plugins.sort((e,t)=>e==null&&t==null?0:(e==null?void 0:e.priority)==null?-1:(t==null?void 0:t.priority)==null?1:e.priority==t.priority?0:e.priority>t.priority?1:-1)}addPlugin(e,t,i){let s=i?{name:e,priority:t,run:i}:e;if(!s||!(s.startup||s.run)){this.services.log.error("Add plugin failed: startup or run method not defined");return}s.name||(s.name=b()),s.priority||(s.priority=0),this._plugins.find(n=>n.name===s.name)||this._plugins.push(s)}removePlugin(e){let t=typeof e=="string"?e:e.name||"";if(!t){this.services.log.error("Remove plugin failed: Plugin name not defined");return}let i=this._plugins;for(let s=0;s<i.length;s++)if(i[s].name===t){i.splice(s,1);break}}get version(){return this.defaultData[u.Version]}set version(e){e?this.defaultData[u.Version]=e:delete this.defaultData[u.Version]}setUserIdentity(e,t,i=3e4){let s=typeof t=="string"?t:void 0,n=typeof e!="string"?e:{identity:e,name:s},o=typeof t=="number"?t:i,l=new C(o),g=!n||!n.identity&&!n.name;g?(this.removePlugin(l),delete this.defaultData[u.UserInfo]):(this.addPlugin(l),this.defaultData[u.UserInfo]=n),this.services.log.info(`user identity: ${g?"null":n.identity} (heartbeat interval: ${o}ms)`)}get userAgent(){return"exceptionless-js/2.0.0-beta2"}useLocalStorage(){this.services.storage=new $}applyServerSettings(e){this.originalSettings||(this.originalSettings=JSON.parse(JSON.stringify(this.settings))),this.services.log.trace(`Applying saved settings: v${e.version}`),this.settings=Object.assign(this.originalSettings,e.settings),this.settingsVersion=e.version,this.notifySubscribers()}useDebugLogger(){this.services.log=new y}subscribeServerSettingsChange(e){e&&this._subscribers.push(e)}notifySubscribers(){for(let e of this._subscribers)try{e(this)}catch(t){this.services.log.error(`Error calling subscribe handler: ${t==null?void 0:t.message}`)}}};var T=class{constructor(){this.priority=10;this.name="ConfigurationDefaultsPlugin"}run(e){let t=e.client.config,i=e.event;t.defaultTags&&(i.tags=[...i.tags||[],...t.defaultTags]);let s=t.defaultData||{};if(s){i.data||(i.data={});for(let n in t.defaultData||{})i.data[n]===void 0&&!m(s[n])&&(i.data[n]=s[n])}return Promise.resolve()}};var q=class{constructor(e=()=>Date.now(),t=3e4){this.priority=1010;this.name="DuplicateCheckerPlugin";this._mergedEvents=[];this._processedHashCodes=[];this._intervalId=0;this._getCurrentTime=e,this._interval=t}startup(){return clearInterval(this._intervalId),this._intervalId=setInterval(()=>void this.submitEvents(),this._interval),Promise.resolve()}async suspend(){clearInterval(this._intervalId),this._intervalId=0,await this.submitEvents()}run(e){var n;function t(o){let l=0;for(;o;)o.message&&o.message.length&&(l+=l*397^R(o.message)),o.stack_trace&&o.stack_trace.length&&(l+=l*397^R(JSON.stringify(o.stack_trace))),o=o.inner;return l}let i=(n=e.event.data)==null?void 0:n[u.Error],s=t(i);if(s){let o=e.event.count||1,l=this._getCurrentTime(),g=this._mergedEvents.filter(c=>c.hashCode===s)[0];if(g&&(g.incrementCount(o),g.updateDate(e.event.date),e.log.info("Ignoring duplicate event with hash: "+s),e.cancelled=!0),!e.cancelled&&this._processedHashCodes.some(c=>c.hash===s&&c.timestamp>=l-this._interval)&&(e.log.trace("Adding event with hash: "+s),this._mergedEvents.push(new J(s,e,o)),e.cancelled=!0),!e.cancelled)for(e.log.trace(`Enqueueing event with hash: ${s} to cache`),this._processedHashCodes.push({hash:s,timestamp:l});this._processedHashCodes.length>50;)this._processedHashCodes.shift()}return Promise.resolve()}async submitEvents(){var e;for(;this._mergedEvents.length>0;)await((e=this._mergedEvents.shift())==null?void 0:e.resubmit())}},J=class{constructor(e,t,i){this.hashCode=e,this._context=t,this._count=i}incrementCount(e){this._count+=e}async resubmit(){this._context.event.count=this._count,await this._context.client.config.services.queue.enqueue(this._context.event)}updateDate(e){let t=this._context.event;e&&t.date&&e>t.date&&(t.date=e)}};var Q=class{constructor(){this.priority=45;this.name="EventExclusionPlugin"}run(e){let t=e.event,i=e.log,s=e.client.config.settings;if(t.type==="log"){let n=this.getMinLogLevel(s,t.source),o=this.getLogLevel(t.data&&t.data[u.Level]);o!==-1&&(o===6||o<n)&&(i.info("Cancelling log event due to minimum log level."),e.cancelled=!0)}else if(t.type==="error"){let n=t.data&&t.data[u.Error];for(;!e.cancelled&&n;)this.getTypeAndSourceSetting(s,t.type,n.type,!0)===!1&&(i.info(`Cancelling error from excluded exception type: ${n.type}`),e.cancelled=!0),n=n.inner}else this.getTypeAndSourceSetting(s,t.type,t.source,!0)===!1&&(i.info(`Cancelling event from excluded type: ${t.type} and source: ${t.source}`),e.cancelled=!0);return Promise.resolve()}getLogLevel(e){switch((e||"").toLowerCase().trim()){case"trace":case"true":case"1":case"yes":return 0;case"debug":return 1;case"info":return 2;case"warn":return 3;case"error":return 4;case"fatal":return 5;case"off":case"false":case"0":case"no":return 6;default:return-1}}getMinLogLevel(e,t){return this.getLogLevel(this.getTypeAndSourceSetting(e,"log",t,"other")+"")}getTypeAndSourceSetting(e={},t,i,s){if(!t)return s;i||(i="");let n=t==="log",o=`@@${t}:`,l=e[o+i];if(l)return n?l:L(l);let g=Object.keys(e).sort((c,I)=>I.length-c.length||c.localeCompare(I));for(let c of g){if(!M(c.toLowerCase(),o))continue;let I=c.substring(o.length);if(h(i,[I]))return n?e[c]:L(e[c])}return s}};var B=class{constructor(){this.priority=20;this.name="ReferenceIdPlugin"}run(e){return!e.event.reference_id&&e.event.type==="error"&&(e.event.reference_id=b().replace("-","").substring(0,10)),Promise.resolve()}};var O=["arguments","column","columnNumber","description","fileName","message","name","number","line","lineNumber","opera#sourceloc","sourceId","sourceURL","stack","stackArray","stacktrace"],N=class{constructor(){this.priority=30;this.name="SimpleErrorPlugin"}async run(e){let t=e.eventContext.getException();if(t&&(e.event.type="error",e.event.data&&!e.event.data[u.SimpleError])){let i={type:t.name||"Error",message:t.message,stack_trace:t.stack,data:{}},s=e.client.config.dataExclusions.concat(O),n=JSON.parse(E(t,s));m(n)||(i.data["@ext"]=n),e.event.data[u.SimpleError]=i}return Promise.resolve()}};var A=class{constructor(){this.priority=100;this.name="SubmissionMethodPlugin"}run(e){let t=e.eventContext.getSubmissionMethod();return t&&e.event.data&&(e.event.data[u.SubmissionMethod]=t),Promise.resolve()}};var p;(function(i){i.Exception="@@_Exception",i.IsUnhandledError="@@_IsUnhandledError",i.SubmissionMethod="@@_SubmissionMethod"})(p||(p={}));var f=class{getException(){return this[p.Exception]||null}setException(e){e&&(this[p.Exception]=e)}get hasException(){return!!this[p.Exception]}markAsUnhandledError(){this[p.IsUnhandledError]=!0}get isUnhandledError(){return!!this[p.IsUnhandledError]}getSubmissionMethod(){return this[p.SubmissionMethod]||null}setSubmissionMethod(e){e&&(this[p.SubmissionMethod]=e)}};var P=class{constructor(e){this.client=e}get log(){return this.client.config.services.log}};var F=class{constructor(e,t,i){this.client=e;this.event=t;this.eventContext=i;this.cancelled=!1;this.eventContext||(this.eventContext=new f)}get log(){return this.client.config.services.log}};var v=class{static async startup(e){for(let t of e.client.config.plugins)if(!!t.startup)try{await t.startup(e)}catch(i){e.log.error(`Error running plugin startup"${t.name}": ${i==null?void 0:i.message}`)}}static async suspend(e){for(let t of e.client.config.plugins)if(!!t.suspend)try{await t.suspend(e)}catch(i){e.log.error(`Error running plugin suspend"${t.name}": ${i==null?void 0:i.message}`)}}static async run(e){for(let t of e.client.config.plugins){if(e.cancelled)break;if(!!t.run)try{await t.run(e)}catch(i){e.cancelled=!0,e.log.error(`Error running plugin "${t.name}": ${i==null?void 0:i.message}. Discarding Event.`)}}}static addDefaultPlugins(e){e.addPlugin(new T),e.addPlugin(new N),e.addPlugin(new B),e.addPlugin(new q),e.addPlugin(new Q),e.addPlugin(new A)}};var V=class{constructor(e,t,i){this._validIdentifierErrorMessage="must contain between 8 and 100 alphanumeric or '-' characters.";this.target=e,this.client=t,this.context=i||new f}setType(e){return e&&(this.target.type=e),this}setSource(e){return e&&(this.target.source=e),this}setReferenceId(e){if(!this.isValidIdentifier(e))throw new Error(`ReferenceId ${this._validIdentifierErrorMessage}`);return this.target.reference_id=e,this}setEventReference(e,t){if(!e)throw new Error("Invalid name");if(!t||!this.isValidIdentifier(t))throw new Error(`Id ${this._validIdentifierErrorMessage}`);return this.setProperty("@ref:"+e,t),this}setMessage(e){return e&&(this.target.message=e),this}setGeo(e,t){if(e<-90||e>90)throw new Error("Must be a valid latitude value between -90.0 and 90.0.");if(t<-180||t>180)throw new Error("Must be a valid longitude value between -180.0 and 180.0.");return this.target.geo=`${e},${t}`,this}setUserIdentity(e,t){let i=typeof e!="string"?e:{identity:e,name:t};return!i||!i.identity&&!i.name?this:(this.setProperty(u.UserInfo,i),this)}setUserDescription(e,t){return e&&t&&this.setProperty(u.UserDescription,{email_address:e,description:t}),this}setManualStackingInfo(e,t){if(e){let i={signature_data:e};t&&(i.title=t),this.setProperty(u.ManualStackingInfo,i)}return this}setManualStackingKey(e,t){if(e){let i={ManualStackingKey:e};this.setManualStackingInfo(i,t)}return this}setValue(e){return e&&(this.target.value=e),this}addTags(...e){return this.target.tags=[...this.target.tags||[],...e],this}setProperty(e,t,i,s){if(!e||t===void 0||t==null)return this;this.target.data||(this.target.data={});let n=JSON.parse(E(t,this.client.config.dataExclusions.concat(s||[]),i));return m(n)||(this.target.data[e]=n),this}markAsCritical(e){return e&&this.addTags("Critical"),this}addRequestInfo(e){return e&&(this.context[u.RequestInfo]=e),this}submit(){return this.client.submitEvent(this.target,this.context)}isValidIdentifier(e){if(!e)return!0;if(e.length<8||e.length>100)return!1;for(let t=0;t<e.length;t++){let i=e.charCodeAt(t),s=i>=48&&i<=57,n=i>=65&&i<=90||i>=97&&i<=122;if(!(s||n)&&!(i===45))return!1}return!0}};var z=class{constructor(e=new D){this.config=e;this._intervalId=0;this._timeoutId=0}async startup(e){e&&(v.addDefaultPlugins(this.config),typeof e=="string"?this.config.apiKey=e:e(this.config),this.config.services.queue.onEventsPosted(()=>Promise.resolve(this.updateSettingsTimer())),await d.applySavedServerSettings(this.config)),this.updateSettingsTimer(!!e),await v.startup(new P(this));let{queue:t}=this.config.services;await t.startup(),this.config.usePersistedQueueStorage&&await t.process()}async suspend(){await v.suspend(new P(this));let{queue:e}=this.config.services;await e.suspend(),await e.process(),this.suspendSettingsTimer()}suspendSettingsTimer(){clearTimeout(this._timeoutId),this._timeoutId=0,clearInterval(this._intervalId),this._intervalId=0}async processQueue(){await this.config.services.queue.process()}updateSettingsTimer(e=!1){this.suspendSettingsTimer();let t=this.config.updateSettingsWhenIdleInterval;if(t>0){let i=t;e&&(i=this.config.settingsVersion>0?15e3:5e3),this.config.services.log.info(`Update settings every ${t}ms (${i||0}ms delay)`);let s=()=>void d.updateSettings(this.config);i<t&&(this._timeoutId=setTimeout(s,i)),this._intervalId=setInterval(s,t)}}createException(e){let t=new f;return t.setException(e),this.createEvent(t).setType("error")}submitException(e){return this.createException(e).submit()}createUnhandledException(e,t){let i=this.createException(e);return i.context.markAsUnhandledError(),i.context.setSubmissionMethod(t||""),i}submitUnhandledException(e,t){return this.createUnhandledException(e,t).submit()}createFeatureUsage(e){return this.createEvent().setType("usage").setSource(e)}submitFeatureUsage(e){return this.createFeatureUsage(e).submit()}createLog(e,t,i){let s=this.createEvent().setType("log");if(i)s=s.setSource(e).setMessage(t).setProperty(u.Level,i);else if(t)s=s.setSource(e).setMessage(t);else{s=s.setMessage(e);try{let n=this.createLog.caller;s=s.setSource(n&&n.caller&&n.caller.name)}catch(n){this.config.services.log.trace("Unable to resolve log source: "+n.message)}}return s}submitLog(e,t,i){return this.createLog(e,t,i).submit()}createNotFound(e){return this.createEvent().setType("404").setSource(e)}submitNotFound(e){return this.createNotFound(e).submit()}createSessionStart(){return this.createEvent().setType("session")}submitSessionStart(){return this.createSessionStart().submit()}async submitSessionEnd(e){e&&this.config.enabled&&this.config.isValid&&(this.config.services.log.info(`Submitting session end: ${e}`),await this.config.services.submissionClient.submitHeartbeat(e,!0))}async submitSessionHeartbeat(e){e&&this.config.enabled&&this.config.isValid&&(this.config.services.log.info(`Submitting session heartbeat: ${e}`),await this.config.services.submissionClient.submitHeartbeat(e,!1))}createEvent(e){return new V({date:new Date},this,e)}async submitEvent(e,t){let i=new F(this,e,t!=null?t:new f);if(!e)return i.cancelled=!0,i;if(!this.config.enabled||!this.config.isValid)return this.config.services.log.info("Event submission is currently disabled."),i.cancelled=!0,i;if(e.data||(e.data={}),(!e.tags||!e.tags.length)&&(e.tags=[]),await v.run(i),i.cancelled)return i;let s=i.event;return(!s.type||s.type.length===0)&&(s.type="log"),s.date||(s.date=new Date),await this.config.services.queue.enqueue(s),s.reference_id&&s.reference_id.length>0&&(i.log.info(`Setting last reference id "${s.reference_id}"`),this.config.services.lastReferenceIdManager.setLast(s.reference_id)),i}async updateUserEmailAndDescription(e,t,i){if(!e||!t||!i||!this.config.enabled||!this.config.isValid)return;let s={email_address:t,description:i},n=await this.config.services.submissionClient.submitUserDescription(e,s);n.success||this.config.services.log.error(`Failed to submit user email and description for event "${e}": ${n.status} ${n.message}`)}getLastReferenceId(){return this.config.services.lastReferenceIdManager.getLast()}};export{D as Configuration,T as ConfigurationDefaultsPlugin,y as ConsoleLog,_ as DefaultEventQueue,S as DefaultLastReferenceIdManager,U as DefaultSubmissionClient,q as DuplicateCheckerPlugin,V as EventBuilder,f as EventContext,Q as EventExclusionPlugin,F as EventPluginContext,v as EventPluginManager,z as ExceptionlessClient,C as HeartbeatPlugin,O as IgnoredErrorProperties,k as InMemoryStorage,u as KnownEventDataKeys,$ as LocalStorage,x as NullLog,P as PluginContext,B as ReferenceIdPlugin,w as Response,d as SettingsManager,N as SimpleErrorPlugin,A as SubmissionMethodPlugin,W as endsWith,G as getCookies,R as getHashCode,b as guid,m as isEmpty,h as isMatch,X as parseQueryString,Z as parseVersion,Y as randomNumber,M as startsWith,E as stringify,L as toBoolean};
//# sourceMappingURL=index.bundle.min.js.map

@@ -22,2 +22,5 @@ import { KnownEventDataKeys } from "../../models/Event.js";

var _a;
if (this._interval <= 0) {
return Promise.resolve();
}
clearInterval(this._intervalId);

@@ -24,0 +27,0 @@ this._intervalId = 0;

import { ConfigurationDefaultsPlugin } from "./default/ConfigurationDefaultsPlugin.js";
import { DuplicateCheckerPlugin } from "./default/DuplicateCheckerPlugin.js";
import { EventExclusionPlugin } from "./default/EventExclusionPlugin.js";
import { ReferenceIdPlugin } from "./default/ReferenceIdPlugin.js";
import { SimpleErrorPlugin } from "./default/SimpleErrorPlugin.js";
import { EventExclusionPlugin } from "./default/EventExclusionPlugin.js";
import { SubmissionMethodPlugin } from "./default/SubmissionMethodPlugin.js";

@@ -53,2 +54,3 @@ export class EventPluginManager {

config.addPlugin(new SimpleErrorPlugin());
config.addPlugin(new ReferenceIdPlugin());
config.addPlugin(new DuplicateCheckerPlugin());

@@ -55,0 +57,0 @@ config.addPlugin(new EventExclusionPlugin());

{
"name": "@exceptionless/core",
"version": "2.0.0-beta1",
"version": "2.0.0-beta2",
"description": "JavaScript client for Exceptionless",

@@ -5,0 +5,0 @@ "author": {

@@ -33,3 +33,2 @@ # Exceptionless Client SDK

c.apiKey = "API_KEY_HERE";
c.usePersistedQueueStorage = true;
c.setUserIdentity("12345678", "Blake");

@@ -36,0 +35,0 @@

@@ -8,3 +8,2 @@ import { DefaultLastReferenceIdManager } from "../lastReferenceIdManager/DefaultLastReferenceIdManager.js";

import { HeartbeatPlugin } from "../plugins/default/HeartbeatPlugin.js";
import { ReferenceIdPlugin } from "../plugins/default/ReferenceIdPlugin.js";
import { EventPluginContext } from "../plugins/EventPluginContext.js";

@@ -366,19 +365,10 @@ import { IEventPlugin } from "../plugins/IEventPlugin.js";

*/
public addPlugin(
name: string | undefined,
priority: number,
pluginAction: (context: EventPluginContext) => Promise<void>,
): void;
public addPlugin(
pluginOrName: IEventPlugin | string | undefined,
priority?: number,
pluginAction?: (context: EventPluginContext) => Promise<void>,
): void {
public addPlugin(name: string | undefined, priority: number, pluginAction: (context: EventPluginContext) => Promise<void>): void;
public addPlugin(pluginOrName: IEventPlugin | string | undefined, priority?: number, pluginAction?: (context: EventPluginContext) => Promise<void>): void {
const plugin: IEventPlugin = pluginAction
? { name: pluginOrName as string, priority, run: pluginAction }
: pluginOrName as IEventPlugin;
if (!plugin || !(plugin.startup || plugin.run)) {
this.services.log.error(
"Add plugin failed: startup or run method not defined",
);
this.services.log.error("Add plugin failed: startup or run method not defined");
return;

@@ -395,14 +385,5 @@ }

let pluginExists = false;
const plugins = this._plugins; // optimization for minifier.
for (const p of plugins) {
if (p.name === plugin.name) {
pluginExists = true;
break;
}
if (!this._plugins.find(f => f.name === plugin.name)) {
this._plugins.push(plugin);
}
if (!pluginExists) {
plugins.push(plugin);
}
}

@@ -449,9 +430,12 @@

public setUserIdentity(userInfo: UserInfo): void;
public setUserIdentity(identity: string): void;
public setUserIdentity(identity: string, name: string): void;
public setUserIdentity(
userInfoOrIdentity: UserInfo | string,
name?: string,
): void {
/**
* Set the default user identity for all events. If the heartbeat interval is
* greater than 0 (default: 30000ms), heartbeats will be sent after the first
* event submission.
*/
public setUserIdentity(userInfo: UserInfo, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, heartbeatInterval?: number): void;
public setUserIdentity(identity: string, name: string, heartbeatInterval?: number): void;
public setUserIdentity(userInfoOrIdentity: UserInfo | string, nameOrHeartbeatInterval?: string | number, heartbeatInterval: number = 30000): void {
const name: string | undefined = typeof nameOrHeartbeatInterval === "string" ? nameOrHeartbeatInterval : undefined;
const userInfo: UserInfo = typeof userInfoOrIdentity !== "string"

@@ -461,11 +445,15 @@ ? userInfoOrIdentity

const shouldRemove: boolean = !userInfo ||
(!userInfo.identity && !userInfo.name);
const interval: number = typeof nameOrHeartbeatInterval === "number" ? nameOrHeartbeatInterval : heartbeatInterval;
const plugin = new HeartbeatPlugin(interval);
const shouldRemove: boolean = !userInfo || (!userInfo.identity && !userInfo.name);
if (shouldRemove) {
this.removePlugin(plugin)
delete this.defaultData[KnownEventDataKeys.UserInfo];
} else {
this.addPlugin(plugin)
this.defaultData[KnownEventDataKeys.UserInfo] = userInfo;
}
this.services.log.info(`user identity: ${shouldRemove ? "null" : <string>userInfo.identity}`);
this.services.log.info(`user identity: ${shouldRemove ? "null" : <string>userInfo.identity} (heartbeat interval: ${interval}ms)`);
}

@@ -477,22 +465,6 @@

public get userAgent(): string {
return "exceptionless-js/2.0.0-beta1";
return "exceptionless-js/2.0.0-beta2";
}
/**
* Automatically send a heartbeat to keep the session alive.
*/
public useSessions(sendHeartbeats = true, heartbeatInterval = 30000): void {
if (sendHeartbeats) {
this.addPlugin(new HeartbeatPlugin(heartbeatInterval));
}
}
/**
* Automatically set a reference id for error events.
*/
public useReferenceIds(): void {
this.addPlugin(new ReferenceIdPlugin());
}
/**
* Use localStorage for persisting things like server configuration cache and persisted queue entries (depends on usePersistedQueueStorage).

@@ -499,0 +471,0 @@ */

@@ -30,2 +30,6 @@ import { KnownEventDataKeys } from "../../models/Event.js";

public run(context: EventPluginContext): Promise<void> {
if (this._interval <= 0) {
return Promise.resolve();
}
clearInterval(this._intervalId);

@@ -32,0 +36,0 @@ this._intervalId = 0;

import { Configuration } from "../configuration/Configuration.js";
import { ConfigurationDefaultsPlugin } from "./default/ConfigurationDefaultsPlugin.js";
import { DuplicateCheckerPlugin } from "./default/DuplicateCheckerPlugin.js";
import { EventPluginContext } from "./EventPluginContext.js";
import { EventExclusionPlugin } from "./default/EventExclusionPlugin.js";
import { PluginContext } from "./PluginContext.js";
import { ReferenceIdPlugin } from "./default/ReferenceIdPlugin.js";
import { SimpleErrorPlugin } from "./default/SimpleErrorPlugin.js";
import { EventExclusionPlugin } from "./default/EventExclusionPlugin.js";
import { SubmissionMethodPlugin } from "./default/SubmissionMethodPlugin.js";
import { EventPluginContext } from "./EventPluginContext.js";
import { PluginContext } from "./PluginContext.js";

@@ -61,2 +62,3 @@ export class EventPluginManager {

config.addPlugin(new SimpleErrorPlugin());
config.addPlugin(new ReferenceIdPlugin());
config.addPlugin(new DuplicateCheckerPlugin());

@@ -63,0 +65,0 @@ config.addPlugin(new EventExclusionPlugin());

import { ExceptionlessClient } from "../src/ExceptionlessClient.js";
import { KnownEventDataKeys } from "../src/models/Event.js";
import { ReferenceIdPlugin } from "../src/plugins/default/ReferenceIdPlugin.js";

@@ -20,3 +21,3 @@ describe("ExceptionlessClient", () => {

const numberOfPlugins = client.config.plugins.length;
client.config.useReferenceIds();
client.config.addPlugin(new ReferenceIdPlugin());
expect(client.config.plugins.length).toBe(numberOfPlugins + 1);

@@ -23,0 +24,0 @@

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc