@exceptionless/node
Version:
JavaScript client for Exceptionless
1,565 lines (1,550 loc) • 115 kB
JavaScript
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
}) : x)(function(x) {
if (typeof require !== "undefined")
return require.apply(this, arguments);
throw Error('Dynamic require of "' + x + '" is not supported');
});
var __commonJS = (cb, mod) => function __require2() {
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// ../../node_modules/imurmurhash/imurmurhash.js
var require_imurmurhash = __commonJS({
"../../node_modules/imurmurhash/imurmurhash.js"(exports, module) {
(function() {
var cache;
function MurmurHash3(key, seed) {
var m = this instanceof MurmurHash3 ? this : cache;
m.reset(seed);
if (typeof key === "string" && key.length > 0) {
m.hash(key);
}
if (m !== this) {
return m;
}
}
;
MurmurHash3.prototype.hash = function(key) {
var h1, k1, i, top, len;
len = key.length;
this.len += len;
k1 = this.k1;
i = 0;
switch (this.rem) {
case 0:
k1 ^= len > i ? key.charCodeAt(i++) & 65535 : 0;
case 1:
k1 ^= len > i ? (key.charCodeAt(i++) & 65535) << 8 : 0;
case 2:
k1 ^= len > i ? (key.charCodeAt(i++) & 65535) << 16 : 0;
case 3:
k1 ^= len > i ? (key.charCodeAt(i) & 255) << 24 : 0;
k1 ^= len > i ? (key.charCodeAt(i++) & 65280) >> 8 : 0;
}
this.rem = len + this.rem & 3;
len -= this.rem;
if (len > 0) {
h1 = this.h1;
while (1) {
k1 = k1 * 11601 + (k1 & 65535) * 3432906752 & 4294967295;
k1 = k1 << 15 | k1 >>> 17;
k1 = k1 * 13715 + (k1 & 65535) * 461832192 & 4294967295;
h1 ^= k1;
h1 = h1 << 13 | h1 >>> 19;
h1 = h1 * 5 + 3864292196 & 4294967295;
if (i >= len) {
break;
}
k1 = key.charCodeAt(i++) & 65535 ^ (key.charCodeAt(i++) & 65535) << 8 ^ (key.charCodeAt(i++) & 65535) << 16;
top = key.charCodeAt(i++);
k1 ^= (top & 255) << 24 ^ (top & 65280) >> 8;
}
k1 = 0;
switch (this.rem) {
case 3:
k1 ^= (key.charCodeAt(i + 2) & 65535) << 16;
case 2:
k1 ^= (key.charCodeAt(i + 1) & 65535) << 8;
case 1:
k1 ^= key.charCodeAt(i) & 65535;
}
this.h1 = h1;
}
this.k1 = k1;
return this;
};
MurmurHash3.prototype.result = function() {
var k1, h1;
k1 = this.k1;
h1 = this.h1;
if (k1 > 0) {
k1 = k1 * 11601 + (k1 & 65535) * 3432906752 & 4294967295;
k1 = k1 << 15 | k1 >>> 17;
k1 = k1 * 13715 + (k1 & 65535) * 461832192 & 4294967295;
h1 ^= k1;
}
h1 ^= this.len;
h1 ^= h1 >>> 16;
h1 = h1 * 51819 + (h1 & 65535) * 2246770688 & 4294967295;
h1 ^= h1 >>> 13;
h1 = h1 * 44597 + (h1 & 65535) * 3266445312 & 4294967295;
h1 ^= h1 >>> 16;
return h1 >>> 0;
};
MurmurHash3.prototype.reset = function(seed) {
this.h1 = typeof seed === "number" ? seed : 0;
this.rem = this.k1 = this.len = 0;
return this;
};
cache = new MurmurHash3();
if (typeof module != "undefined") {
module.exports = MurmurHash3;
} else {
this.MurmurHash3 = MurmurHash3;
}
})();
}
});
// ../../node_modules/node-localstorage/node_modules/signal-exit/dist/cjs/signals.js
var require_signals = __commonJS({
"../../node_modules/node-localstorage/node_modules/signal-exit/dist/cjs/signals.js"(exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.signals = void 0;
exports.signals = [];
exports.signals.push("SIGHUP", "SIGINT", "SIGTERM");
if (process.platform !== "win32") {
exports.signals.push(
"SIGALRM",
"SIGABRT",
"SIGVTALRM",
"SIGXCPU",
"SIGXFSZ",
"SIGUSR2",
"SIGTRAP",
"SIGSYS",
"SIGQUIT",
"SIGIOT"
// should detect profiler and enable/disable accordingly.
// see #21
// 'SIGPROF'
);
}
if (process.platform === "linux") {
exports.signals.push("SIGIO", "SIGPOLL", "SIGPWR", "SIGSTKFLT");
}
}
});
// ../../node_modules/node-localstorage/node_modules/signal-exit/dist/cjs/index.js
var require_cjs = __commonJS({
"../../node_modules/node-localstorage/node_modules/signal-exit/dist/cjs/index.js"(exports) {
"use strict";
var _a;
Object.defineProperty(exports, "__esModule", { value: true });
exports.unload = exports.load = exports.onExit = exports.signals = void 0;
var signals_js_1 = require_signals();
Object.defineProperty(exports, "signals", { enumerable: true, get: function() {
return signals_js_1.signals;
} });
var processOk = (process3) => !!process3 && typeof process3 === "object" && typeof process3.removeListener === "function" && typeof process3.emit === "function" && typeof process3.reallyExit === "function" && typeof process3.listeners === "function" && typeof process3.kill === "function" && typeof process3.pid === "number" && typeof process3.on === "function";
var kExitEmitter = Symbol.for("signal-exit emitter");
var global = globalThis;
var ObjectDefineProperty = Object.defineProperty.bind(Object);
var Emitter = class {
emitted = {
afterExit: false,
exit: false
};
listeners = {
afterExit: [],
exit: []
};
count = 0;
id = Math.random();
constructor() {
if (global[kExitEmitter]) {
return global[kExitEmitter];
}
ObjectDefineProperty(global, kExitEmitter, {
value: this,
writable: false,
enumerable: false,
configurable: false
});
}
on(ev, fn) {
this.listeners[ev].push(fn);
}
removeListener(ev, fn) {
const list = this.listeners[ev];
const i = list.indexOf(fn);
if (i === -1) {
return;
}
if (i === 0 && list.length === 1) {
list.length = 0;
} else {
list.splice(i, 1);
}
}
emit(ev, code, signal) {
if (this.emitted[ev]) {
return false;
}
this.emitted[ev] = true;
let ret = false;
for (const fn of this.listeners[ev]) {
ret = fn(code, signal) === true || ret;
}
if (ev === "exit") {
ret = this.emit("afterExit", code, signal) || ret;
}
return ret;
}
};
var SignalExitBase = class {
};
var signalExitWrap = (handler) => {
return {
onExit(cb, opts) {
return handler.onExit(cb, opts);
},
load() {
return handler.load();
},
unload() {
return handler.unload();
}
};
};
var SignalExitFallback = class extends SignalExitBase {
onExit() {
return () => {
};
}
load() {
}
unload() {
}
};
var SignalExit = class extends SignalExitBase {
// "SIGHUP" throws an `ENOSYS` error on Windows,
// so use a supported signal instead
/* c8 ignore start */
#hupSig = process2.platform === "win32" ? "SIGINT" : "SIGHUP";
/* c8 ignore stop */
#emitter = new Emitter();
#process;
#originalProcessEmit;
#originalProcessReallyExit;
#sigListeners = {};
#loaded = false;
constructor(process3) {
super();
this.#process = process3;
this.#sigListeners = {};
for (const sig of signals_js_1.signals) {
this.#sigListeners[sig] = () => {
const listeners = this.#process.listeners(sig);
let { count } = this.#emitter;
const p = process3;
if (typeof p.__signal_exit_emitter__ === "object" && typeof p.__signal_exit_emitter__.count === "number") {
count += p.__signal_exit_emitter__.count;
}
if (listeners.length === count) {
this.unload();
const ret = this.#emitter.emit("exit", null, sig);
const s = sig === "SIGHUP" ? this.#hupSig : sig;
if (!ret)
process3.kill(process3.pid, s);
}
};
}
this.#originalProcessReallyExit = process3.reallyExit;
this.#originalProcessEmit = process3.emit;
}
onExit(cb, opts) {
if (!processOk(this.#process)) {
return () => {
};
}
if (this.#loaded === false) {
this.load();
}
const ev = opts?.alwaysLast ? "afterExit" : "exit";
this.#emitter.on(ev, cb);
return () => {
this.#emitter.removeListener(ev, cb);
if (this.#emitter.listeners["exit"].length === 0 && this.#emitter.listeners["afterExit"].length === 0) {
this.unload();
}
};
}
load() {
if (this.#loaded) {
return;
}
this.#loaded = true;
this.#emitter.count += 1;
for (const sig of signals_js_1.signals) {
try {
const fn = this.#sigListeners[sig];
if (fn)
this.#process.on(sig, fn);
} catch (_) {
}
}
this.#process.emit = (ev, ...a) => {
return this.#processEmit(ev, ...a);
};
this.#process.reallyExit = (code) => {
return this.#processReallyExit(code);
};
}
unload() {
if (!this.#loaded) {
return;
}
this.#loaded = false;
signals_js_1.signals.forEach((sig) => {
const listener = this.#sigListeners[sig];
if (!listener) {
throw new Error("Listener not defined for signal: " + sig);
}
try {
this.#process.removeListener(sig, listener);
} catch (_) {
}
});
this.#process.emit = this.#originalProcessEmit;
this.#process.reallyExit = this.#originalProcessReallyExit;
this.#emitter.count -= 1;
}
#processReallyExit(code) {
if (!processOk(this.#process)) {
return 0;
}
this.#process.exitCode = code || 0;
this.#emitter.emit("exit", this.#process.exitCode, null);
return this.#originalProcessReallyExit.call(this.#process, this.#process.exitCode);
}
#processEmit(ev, ...args) {
const og = this.#originalProcessEmit;
if (ev === "exit" && processOk(this.#process)) {
if (typeof args[0] === "number") {
this.#process.exitCode = args[0];
}
const ret = og.call(this.#process, ev, ...args);
this.#emitter.emit("exit", this.#process.exitCode, null);
return ret;
} else {
return og.call(this.#process, ev, ...args);
}
}
};
var process2 = globalThis.process;
_a = signalExitWrap(processOk(process2) ? new SignalExit(process2) : new SignalExitFallback()), /**
* Called when the process is exiting, whether via signal, explicit
* exit, or running out of stuff to do.
*
* If the global process object is not suitable for instrumentation,
* then this will be a no-op.
*
* Returns a function that may be used to unload signal-exit.
*/
exports.onExit = _a.onExit, /**
* Load the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
exports.load = _a.load, /**
* Unload the listeners. Likely you never need to call this, unless
* doing a rather deep integration with signal-exit functionality.
* Mostly exposed for the benefit of testing.
*
* @internal
*/
exports.unload = _a.unload;
}
});
// ../../node_modules/node-localstorage/node_modules/write-file-atomic/lib/index.js
var require_lib = __commonJS({
"../../node_modules/node-localstorage/node_modules/write-file-atomic/lib/index.js"(exports, module) {
"use strict";
module.exports = writeFile;
module.exports.sync = writeFileSync;
module.exports._getTmpname = getTmpname;
module.exports._cleanupOnExit = cleanupOnExit;
var fs = __require("fs");
var MurmurHash3 = require_imurmurhash();
var { onExit } = require_cjs();
var path = __require("path");
var { promisify } = __require("util");
var activeFiles = {};
var threadId = function getId() {
try {
const workerThreads = __require("worker_threads");
return workerThreads.threadId;
} catch (e) {
return 0;
}
}();
var invocations = 0;
function getTmpname(filename) {
return filename + "." + MurmurHash3(__filename).hash(String(process.pid)).hash(String(threadId)).hash(String(++invocations)).result();
}
function cleanupOnExit(tmpfile) {
return () => {
try {
fs.unlinkSync(typeof tmpfile === "function" ? tmpfile() : tmpfile);
} catch {
}
};
}
function serializeActiveFile(absoluteName) {
return new Promise((resolve) => {
if (!activeFiles[absoluteName]) {
activeFiles[absoluteName] = [];
}
activeFiles[absoluteName].push(resolve);
if (activeFiles[absoluteName].length === 1) {
resolve();
}
});
}
function isChownErrOk(err) {
if (err.code === "ENOSYS") {
return true;
}
const nonroot = !process.getuid || process.getuid() !== 0;
if (nonroot) {
if (err.code === "EINVAL" || err.code === "EPERM") {
return true;
}
}
return false;
}
async function writeFileAsync(filename, data, options = {}) {
if (typeof options === "string") {
options = { encoding: options };
}
let fd;
let tmpfile;
const removeOnExitHandler = onExit(cleanupOnExit(() => tmpfile));
const absoluteName = path.resolve(filename);
try {
await serializeActiveFile(absoluteName);
const truename = await promisify(fs.realpath)(filename).catch(() => filename);
tmpfile = getTmpname(truename);
if (!options.mode || !options.chown) {
const stats = await promisify(fs.stat)(truename).catch(() => {
});
if (stats) {
if (options.mode == null) {
options.mode = stats.mode;
}
if (options.chown == null && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid };
}
}
}
fd = await promisify(fs.open)(tmpfile, "w", options.mode);
if (options.tmpfileCreated) {
await options.tmpfileCreated(tmpfile);
}
if (ArrayBuffer.isView(data)) {
await promisify(fs.write)(fd, data, 0, data.length, 0);
} else if (data != null) {
await promisify(fs.write)(fd, String(data), 0, String(options.encoding || "utf8"));
}
if (options.fsync !== false) {
await promisify(fs.fsync)(fd);
}
await promisify(fs.close)(fd);
fd = null;
if (options.chown) {
await promisify(fs.chown)(tmpfile, options.chown.uid, options.chown.gid).catch((err) => {
if (!isChownErrOk(err)) {
throw err;
}
});
}
if (options.mode) {
await promisify(fs.chmod)(tmpfile, options.mode).catch((err) => {
if (!isChownErrOk(err)) {
throw err;
}
});
}
await promisify(fs.rename)(tmpfile, truename);
} finally {
if (fd) {
await promisify(fs.close)(fd).catch(
/* istanbul ignore next */
() => {
}
);
}
removeOnExitHandler();
await promisify(fs.unlink)(tmpfile).catch(() => {
});
activeFiles[absoluteName].shift();
if (activeFiles[absoluteName].length > 0) {
activeFiles[absoluteName][0]();
} else {
delete activeFiles[absoluteName];
}
}
}
async function writeFile(filename, data, options, callback) {
if (options instanceof Function) {
callback = options;
options = {};
}
const promise = writeFileAsync(filename, data, options);
if (callback) {
try {
const result = await promise;
return callback(result);
} catch (err) {
return callback(err);
}
}
return promise;
}
function writeFileSync(filename, data, options) {
if (typeof options === "string") {
options = { encoding: options };
} else if (!options) {
options = {};
}
try {
filename = fs.realpathSync(filename);
} catch (ex) {
}
const tmpfile = getTmpname(filename);
if (!options.mode || !options.chown) {
try {
const stats = fs.statSync(filename);
options = Object.assign({}, options);
if (!options.mode) {
options.mode = stats.mode;
}
if (!options.chown && process.getuid) {
options.chown = { uid: stats.uid, gid: stats.gid };
}
} catch (ex) {
}
}
let fd;
const cleanup = cleanupOnExit(tmpfile);
const removeOnExitHandler = onExit(cleanup);
let threw = true;
try {
fd = fs.openSync(tmpfile, "w", options.mode || 438);
if (options.tmpfileCreated) {
options.tmpfileCreated(tmpfile);
}
if (ArrayBuffer.isView(data)) {
fs.writeSync(fd, data, 0, data.length, 0);
} else if (data != null) {
fs.writeSync(fd, String(data), 0, String(options.encoding || "utf8"));
}
if (options.fsync !== false) {
fs.fsyncSync(fd);
}
fs.closeSync(fd);
fd = null;
if (options.chown) {
try {
fs.chownSync(tmpfile, options.chown.uid, options.chown.gid);
} catch (err) {
if (!isChownErrOk(err)) {
throw err;
}
}
}
if (options.mode) {
try {
fs.chmodSync(tmpfile, options.mode);
} catch (err) {
if (!isChownErrOk(err)) {
throw err;
}
}
}
fs.renameSync(tmpfile, filename);
threw = false;
} finally {
if (fd) {
try {
fs.closeSync(fd);
} catch (ex) {
}
}
removeOnExitHandler();
if (threw) {
cleanup();
}
}
}
}
});
// ../../node_modules/node-localstorage/LocalStorage.js
var require_LocalStorage = __commonJS({
"../../node_modules/node-localstorage/LocalStorage.js"(exports) {
(function() {
var JSONStorage, KEY_FOR_EMPTY_STRING, LocalStorage2, MetaKey, QUOTA_EXCEEDED_ERR, StorageEvent, _emptyDirectory, _escapeKey, _rm, createMap, events, fs, path, writeSync;
path = __require("path");
fs = __require("fs");
events = __require("events");
writeSync = require_lib().sync;
KEY_FOR_EMPTY_STRING = "---.EMPTY_STRING.---";
_emptyDirectory = function(target) {
var i, len, p, ref, results;
ref = fs.readdirSync(target);
results = [];
for (i = 0, len = ref.length; i < len; i++) {
p = ref[i];
results.push(_rm(path.join(target, p)));
}
return results;
};
_rm = function(target) {
if (fs.statSync(target).isDirectory()) {
_emptyDirectory(target);
return fs.rmdirSync(target);
} else {
return fs.unlinkSync(target);
}
};
_escapeKey = function(key) {
var newKey;
if (key === "") {
newKey = KEY_FOR_EMPTY_STRING;
} else {
newKey = `${key}`;
}
return newKey;
};
QUOTA_EXCEEDED_ERR = class QUOTA_EXCEEDED_ERR extends Error {
constructor(message = "Unknown error.") {
super();
this.message = message;
if (Error.captureStackTrace != null) {
Error.captureStackTrace(this, this.constructor);
}
this.name = this.constructor.name;
}
toString() {
return `${this.name}: ${this.message}`;
}
};
StorageEvent = class StorageEvent {
constructor(key1, oldValue1, newValue1, url, storageArea = "localStorage") {
this.key = key1;
this.oldValue = oldValue1;
this.newValue = newValue1;
this.url = url;
this.storageArea = storageArea;
}
};
MetaKey = class MetaKey2 {
// MetaKey contains key and size
constructor(key1, index1) {
this.key = key1;
this.index = index1;
if (!(this instanceof MetaKey2)) {
return new MetaKey2(this.key, this.index);
}
}
};
createMap = function() {
var Map2;
Map2 = function() {
};
Map2.prototype = /* @__PURE__ */ Object.create(null);
return new Map2();
};
LocalStorage2 = function() {
var instanceMap;
class LocalStorage3 extends events.EventEmitter {
constructor(_location, quota = 5 * 1024 * 1024) {
var handler;
super();
this._location = _location;
this.quota = quota;
if (!(this instanceof LocalStorage3)) {
return new LocalStorage3(this._location, this.quota);
}
this._location = path.resolve(this._location);
if (instanceMap[this._location] != null) {
return instanceMap[this._location];
}
this.length = 0;
this._bytesInUse = 0;
this._keys = [];
this._metaKeyMap = createMap();
this._eventUrl = "pid:" + process.pid;
this._init();
this._QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR;
if (typeof Proxy !== "undefined" && Proxy !== null) {
handler = {
set: (receiver, key, value) => {
if (this[key] != null) {
this[key] = value;
} else {
this.setItem(key, value);
}
return true;
},
get: (receiver, key) => {
if (this[key] != null) {
return this[key];
} else {
return this.getItem(key);
}
},
ownKeys: (target) => {
return this._keys.map(function(k) {
if (k === KEY_FOR_EMPTY_STRING) {
return "";
} else {
return k;
}
});
},
getOwnPropertyDescriptor: (target, key) => {
return {
value: this[key],
enumerable: true,
configurable: true
};
}
};
instanceMap[this._location] = new Proxy(this, handler);
return instanceMap[this._location];
}
instanceMap[this._location] = this;
return instanceMap[this._location];
}
_init() {
var e, stat;
try {
stat = fs.statSync(this._location);
if (stat != null && !stat.isDirectory()) {
throw new Error(`A file exists at the location '${this._location}' when trying to create/open localStorage`);
}
this._sync();
} catch (error) {
e = error;
if (e.code !== "ENOENT") {
throw e;
}
try {
fs.mkdirSync(this._location, {
recursive: true
});
} catch (error2) {
e = error2;
if (e.code !== "EEXIST") {
throw e;
}
}
}
}
_sync() {
var _MetaKey, _decodedKey, _keys, i, index, k, len, stat;
this._bytesInUse = 0;
this.length = 0;
_keys = fs.readdirSync(this._location);
for (index = i = 0, len = _keys.length; i < len; index = ++i) {
k = _keys[index];
_decodedKey = decodeURIComponent(k);
this._keys.push(_decodedKey);
_MetaKey = new MetaKey(k, index);
this._metaKeyMap[_decodedKey] = _MetaKey;
stat = this._getStat(k);
if ((stat != null ? stat.size : void 0) != null) {
_MetaKey.size = stat.size;
this._bytesInUse += stat.size;
}
}
return this.length = _keys.length;
}
setItem(key, value) {
var encodedKey, evnt, existsBeforeSet, filename, hasListeners, metaKey, oldLength, oldValue, valueString, valueStringLength;
hasListeners = this.listenerCount("storage");
oldValue = null;
if (hasListeners) {
oldValue = this.getItem(key);
}
key = _escapeKey(key);
encodedKey = encodeURIComponent(key).replace(/[!'()]/g, escape).replace(/\*/g, "%2A");
filename = path.join(this._location, encodedKey);
valueString = `${value}`;
valueStringLength = valueString.length;
metaKey = this._metaKeyMap[key];
existsBeforeSet = !!metaKey;
if (existsBeforeSet) {
oldLength = metaKey.size;
} else {
oldLength = 0;
}
if (this._bytesInUse - oldLength + valueStringLength > this.quota) {
throw new QUOTA_EXCEEDED_ERR();
}
writeSync(filename, valueString, {
encoding: "utf8"
});
if (!existsBeforeSet) {
metaKey = new MetaKey(encodedKey, this._keys.push(key) - 1);
metaKey.size = valueStringLength;
this._metaKeyMap[key] = metaKey;
this.length += 1;
this._bytesInUse += valueStringLength;
}
if (hasListeners) {
evnt = new StorageEvent(key, oldValue, value, this._eventUrl);
return this.emit("storage", evnt);
}
}
getItem(key) {
var filename, metaKey;
key = _escapeKey(key);
metaKey = this._metaKeyMap[key];
if (!!metaKey) {
filename = path.join(this._location, metaKey.key);
return fs.readFileSync(filename, "utf8");
} else {
return null;
}
}
_getStat(key) {
var filename;
key = _escapeKey(key);
filename = path.join(this._location, encodeURIComponent(key));
try {
return fs.statSync(filename);
} catch (error) {
return null;
}
}
removeItem(key) {
var evnt, filename, hasListeners, k, meta, metaKey, oldValue, ref, v;
key = _escapeKey(key);
metaKey = this._metaKeyMap[key];
if (!!metaKey) {
hasListeners = this.listenerCount("storage");
oldValue = null;
if (hasListeners) {
oldValue = this.getItem(key);
}
delete this._metaKeyMap[key];
this.length -= 1;
this._bytesInUse -= metaKey.size;
filename = path.join(this._location, metaKey.key);
this._keys.splice(metaKey.index, 1);
ref = this._metaKeyMap;
for (k in ref) {
v = ref[k];
meta = this._metaKeyMap[k];
if (meta.index > metaKey.index) {
meta.index -= 1;
}
}
_rm(filename);
if (hasListeners) {
evnt = new StorageEvent(key, oldValue, null, this._eventUrl);
return this.emit("storage", evnt);
}
}
}
key(n) {
var rawKey;
rawKey = this._keys[n];
if (rawKey === KEY_FOR_EMPTY_STRING) {
return "";
} else {
return rawKey;
}
}
clear() {
var evnt;
_emptyDirectory(this._location);
this._metaKeyMap = createMap();
this._keys = [];
this.length = 0;
this._bytesInUse = 0;
if (this.listenerCount("storage")) {
evnt = new StorageEvent(null, null, null, this._eventUrl);
return this.emit("storage", evnt);
}
}
_getBytesInUse() {
return this._bytesInUse;
}
_deleteLocation() {
delete instanceMap[this._location];
_rm(this._location);
this._metaKeyMap = {};
this._keys = [];
this.length = 0;
return this._bytesInUse = 0;
}
}
;
instanceMap = {};
return LocalStorage3;
}.call(this);
JSONStorage = class JSONStorage extends LocalStorage2 {
setItem(key, value) {
var newValue;
newValue = JSON.stringify(value);
return super.setItem(key, newValue);
}
getItem(key) {
return JSON.parse(super.getItem(key));
}
};
exports.LocalStorage = LocalStorage2;
exports.JSONStorage = JSONStorage;
exports.QUOTA_EXCEEDED_ERR = QUOTA_EXCEEDED_ERR;
}).call(exports);
}
});
// ../core/dist/lastReferenceIdManager/DefaultLastReferenceIdManager.js
var DefaultLastReferenceIdManager = class {
/**
* Gets the last event's reference id that was submitted to the server.
*/
_lastReferenceId = null;
/**
* Gets the last event's reference id that was submitted to the server.
*/
getLast() {
return this._lastReferenceId;
}
/**
* Clears the last event's reference id.
*/
clearLast() {
this._lastReferenceId = null;
}
/**
* Sets the last event's reference id.
*/
setLast(eventId) {
this._lastReferenceId = eventId;
}
};
// ../core/dist/logging/ConsoleLog.js
var ConsoleLog = class {
trace(message) {
this.log("debug", message);
}
info(message) {
this.log("info", message);
}
warn(message) {
this.log("warn", message);
}
error(message) {
this.log("error", message);
}
log(level, message) {
if (console) {
const msg = `Exceptionless:${(/* @__PURE__ */ new Date()).toISOString()} [${level}] ${message}`;
const logFn = console[level];
if (logFn) {
logFn(msg);
} else if (console["log"]) {
console["log"](msg);
}
}
}
};
// ../core/dist/logging/NullLog.js
var NullLog = class {
trace(_) {
}
info(_) {
}
warn(_) {
}
error(_) {
}
};
// ../core/dist/models/Event.js
var KnownEventDataKeys;
(function(KnownEventDataKeys2) {
KnownEventDataKeys2["Error"] = "@error";
KnownEventDataKeys2["SimpleError"] = "@simple_error";
KnownEventDataKeys2["RequestInfo"] = "@request";
KnownEventDataKeys2["TraceLog"] = "@trace";
KnownEventDataKeys2["EnvironmentInfo"] = "@environment";
KnownEventDataKeys2["UserInfo"] = "@user";
KnownEventDataKeys2["UserDescription"] = "@user_description";
KnownEventDataKeys2["Version"] = "@version";
KnownEventDataKeys2["Level"] = "@level";
KnownEventDataKeys2["SubmissionMethod"] = "@submission_method";
KnownEventDataKeys2["ManualStackingInfo"] = "@stack";
})(KnownEventDataKeys || (KnownEventDataKeys = {}));
// ../core/dist/Utils.js
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") {
if (Array.isArray(input)) {
return input.length === 0;
}
if (input instanceof Date) {
return false;
}
return Object.getOwnPropertyNames(input).length === 0;
}
if (typeof input === "string") {
const trimmedInput = input.trim();
return trimmedInput.length === 0 || trimmedInput === "{}" || trimmedInput === "[]";
}
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 prune(value, depth = 10) {
function isUnsupportedType(value2) {
if (value2 === null || value2 === void 0) {
return false;
}
switch (typeof value2) {
case "function":
return true;
case "object":
switch (Object.prototype.toString.call(value2)) {
case "[object AsyncGenerator]":
case "[object Generator]":
case "[object ArrayBuffer]":
case "[object Buffer]":
case "[object DataView]":
case "[object Promise]":
case "[object WeakMap]":
case "[object WeakSet]":
return true;
}
if ("writeBigInt64LE" in value2) {
return true;
}
break;
}
return false;
}
function normalizeValue(value2) {
function hasToJSONFunction(value3) {
return value3 !== null && typeof value3 === "object" && typeof value3.toJSON === "function";
}
if (typeof value2 === "bigint") {
return `${value2.toString()}n`;
}
if (typeof value2 === "object") {
if (Array.isArray(value2)) {
return value2;
}
if (value2 instanceof Date) {
return value2;
}
if (value2 instanceof Map) {
const result = {};
for (const [key, val] of value2) {
result[key] = val;
}
return result;
}
if (value2 instanceof RegExp) {
return value2.toString();
}
if (value2 instanceof Set) {
return Array.from(value2);
}
const TypedArray = Object.getPrototypeOf(Uint8Array);
if (value2 instanceof TypedArray) {
return Array.from(value2);
}
if (hasToJSONFunction(value2)) {
return normalizeValue(value2.toJSON());
}
return value2;
}
if (typeof value2 === "symbol") {
return value2.description;
}
return value2;
}
function pruneImpl(value2, maxDepth, currentDepth = 10, seen = /* @__PURE__ */ new WeakSet(), parentIsArray = false) {
if (value2 === null || value2 === void 0) {
return value2;
}
if (currentDepth > maxDepth) {
return void 0;
}
if (isUnsupportedType(value2)) {
return void 0;
}
const normalizedValue = normalizeValue(value2);
if (typeof normalizedValue === "object") {
if (currentDepth == maxDepth) {
return void 0;
}
if (Array.isArray(normalizedValue)) {
const depth2 = parentIsArray ? currentDepth + 1 : currentDepth;
return normalizedValue.map((e) => pruneImpl(e, maxDepth, depth2, seen, true));
}
if (normalizedValue instanceof Date) {
return normalizedValue;
}
if (Object.prototype.toString.call(normalizedValue) === "[object Object]") {
if (seen.has(normalizedValue)) {
return void 0;
}
seen.add(normalizedValue);
}
const keys = /* @__PURE__ */ new Set([...Object.getOwnPropertyNames(normalizedValue), ...Object.getOwnPropertySymbols(normalizedValue)]);
for (const key in normalizedValue) {
keys.add(key);
}
const result = {};
for (const key of keys) {
const normalizedKey = normalizeValue(key);
const objectValue = normalizedValue[key];
result[normalizedKey] = pruneImpl(objectValue, maxDepth, currentDepth + 1, seen);
}
return result;
}
return normalizedValue;
}
if (depth < 0) {
return void 0;
}
return pruneImpl(value, depth, 0);
}
function stringify(data, exclusions, maxDepth = 10) {
function stringifyImpl(obj, excludedKeys) {
return JSON.stringify(obj, (key, value) => {
if (isMatch(key, excludedKeys)) {
return;
}
return value;
});
}
if (data === void 0) {
return data;
}
const prunedData = prune(data, maxDepth);
return stringifyImpl(prunedData, 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;
}
function toError(errorOrMessage, defaultMessage = "Unknown Error") {
if (errorOrMessage === null || errorOrMessage === void 0) {
const error2 = new Error(defaultMessage);
error2.stack = void 0;
return error2;
}
if (errorOrMessage instanceof Error) {
return errorOrMessage;
}
if (typeof errorOrMessage === "string") {
const error2 = new Error(errorOrMessage);
error2.stack = void 0;
return error2;
}
const error = new Error(stringify(errorOrMessage) || defaultMessage);
error.stack = void 0;
return error;
}
function allowProcessToExitWithoutWaitingForTimerOrInterval(timeoutOrIntervalId) {
if (typeof timeoutOrIntervalId === "object" && "unref" in timeoutOrIntervalId) {
timeoutOrIntervalId.unref();
}
}
// ../core/dist/plugins/default/HeartbeatPlugin.js
var HeartbeatPlugin = class {
priority = 100;
name = "HeartbeatPlugin";
_interval;
_intervalId;
constructor(heartbeatInterval = 6e4) {
this._interval = heartbeatInterval >= 3e4 ? heartbeatInterval : 6e4;
}
startup() {
clearInterval(this._intervalId);
this._intervalId = void 0;
return Promise.resolve();
}
suspend() {
clearInterval(this._intervalId);
this._intervalId = void 0;
return Promise.resolve();
}
run(context) {
if (this._interval <= 0) {
return Promise.resolve();
}
clearInterval(this._intervalId);
this._intervalId = void 0;
const { config } = context.client;
if (!config.currentSessionIdentifier) {
const user = context.event.data?.[KnownEventDataKeys.UserInfo];
if (!user?.identity) {
return Promise.resolve();
}
config.currentSessionIdentifier = user.identity;
}
if (config.currentSessionIdentifier) {
this._intervalId = setInterval(() => void context.client.submitSessionHeartbeat(config.currentSessionIdentifier), this._interval);
allowProcessToExitWithoutWaitingForTimerOrInterval(this._intervalId);
}
return Promise.resolve();
}
};
// ../core/dist/plugins/default/SessionIdManagementPlugin.js
var SessionIdManagementPlugin = class {
priority = 25;
name = "SessionIdManagementPlugin";
run(context) {
const ev = context.event;
const isSessionStart = ev.type === "session";
const { config } = context.client;
if (isSessionStart || !config.currentSessionIdentifier) {
config.currentSessionIdentifier = guid().replaceAll("-", "");
}
if (isSessionStart) {
ev.reference_id = config.currentSessionIdentifier;
} else {
if (!ev.data) {
ev.data = {};
}
ev.data["@ref:session"] = config.currentSessionIdentifier;
}
return Promise.resolve();
}
};
// ../core/dist/plugins/default/ConfigurationDefaultsPlugin.js
var ConfigurationDefaultsPlugin = class {
priority = 10;
name = "ConfigurationDefaultsPlugin";
run(context) {
const { dataExclusions, defaultData, defaultTags } = context.client.config;
const ev = context.event;
if (defaultTags) {
ev.tags = [...ev.tags || [], ...defaultTags];
}
if (defaultData) {
if (!ev.data) {
ev.data = {};
}
for (const key in defaultData) {
if (ev.data[key] !== void 0 || isEmpty(defaultData[key])) {
continue;
}
const data = stringify(defaultData[key], dataExclusions);
if (!isEmpty(data)) {
ev.data[key] = JSON.parse(data);
}
}
}
return Promise.resolve();
}
};
// ../core/dist/plugins/default/DuplicateCheckerPlugin.js
var DuplicateCheckerPlugin = class {
priority = 1010;
name = "DuplicateCheckerPlugin";
_mergedEvents = [];
_processedHashCodes = [];
_getCurrentTime;
_intervalId;
_interval;
constructor(getCurrentTime = () => Date.now(), interval = 3e4) {
this._getCurrentTime = getCurrentTime;
this._interval = interval;
}
startup() {
clearInterval(this._intervalId);
this._intervalId = setInterval(() => void this.submitEvents(), this._interval);
allowProcessToExitWithoutWaitingForTimerOrInterval(this._intervalId);
return Promise.resolve();
}
async suspend() {
clearInterval(this._intervalId);
this._intervalId = void 0;
await this.submitEvents();
}
run(context) {
function calculateHashCode(error2) {
let hash = 0;
while (error2) {
if (error2.message && error2.message.length) {
hash += hash * 397 ^ getHashCode(error2.message);
}
if (error2.stack_trace && error2.stack_trace.length) {
hash += hash * 397 ^ getHashCode(JSON.stringify(error2.stack_trace));
}
error2 = error2.inner;
}
return hash;
}
const error = context.event.data?.[KnownEventDataKeys.Error];
const hashCode = calculateHashCode(error);
if (hashCode) {
const count = context.event.count || 1;
const now = this._getCurrentTime();
const merged = this._mergedEvents.filter((s) => s.hashCode === hashCode)[0];
if (merged) {
merged.incrementCount(count);
merged.updateDate(context.event.date);
context.log.info("Ignoring duplicate event with hash: " + hashCode);
context.cancelled = true;
}
if (!context.cancelled && this._processedHashCodes.some((h) => h.hash === hashCode && h.timestamp >= now - this._interval)) {
context.log.trace("Adding event with hash: " + hashCode);
this._mergedEvents.push(new MergedEvent(hashCode, context, count));
context.cancelled = true;
}
if (!context.cancelled) {
context.log.trace(`Enqueueing event with hash: ${hashCode} to cache`);
this._processedHashCodes.push({ hash: hashCode, timestamp: now });
while (this._processedHashCodes.length > 50) {
this._processedHashCodes.shift();
}
}
}
return Promise.resolve();
}
async submitEvents() {
while (this._mergedEvents.length > 0) {
await this._mergedEvents.shift()?.resubmit();
}
}
};
var MergedEvent = class {
hashCode;
_count;
_context;
constructor(hashCode, context, count) {
this.hashCode = hashCode;
this._context = context;
this._count = count;
}
incrementCount(count) {
this._count += count;
}
async resubmit() {
this._context.event.count = this._count;
await this._context.client.config.services.queue.enqueue(this._context.event);
}
updateDate(date) {
const ev = this._context.event;
if (date && ev.date && date > ev.date) {
ev.date = date;
}
}
};
// ../core/dist/plugins/default/EventExclusionPlugin.js
var EventExclusionPlugin = class {
priority = 45;
name = "EventExclusionPlugin";
run(context) {
const ev = context.event;
const log = context.log;
const settings = context.client.config.settings;
if (ev.type === "log") {
const minLogLevel = this.getMinLogLevel(settings, ev.source);
const logLevel = this.getLogLevel(ev.data && ev.data[KnownEventDataKeys.Level]);
if (logLevel !== -1 && (logLevel === 6 || logLevel < minLogLevel)) {
log.info("Cancelling log event due to minimum log level.");
context.cancelled = true;
}
} else if (ev.type === "error") {
let error = ev.data && ev.data[KnownEventDataKeys.Error];
while (!context.cancelled && error) {
if (this.getTypeAndSourceSetting(settings, ev.type, error.type, true) === false) {
log.info(`Cancelling error from excluded exception type: ${error.type}`);
context.cancelled = true;
}
error = error.inner;
}
} else if (this.getTypeAndSourceSetting(settings, ev.type, ev.source, true) === false) {
log.info(`Cancelling event from excluded type: ${ev.type} and source: ${ev.source}`);
context.cancelled = true;
}
return Promise.resolve();
}
getLogLevel(level) {
switch ((level || "").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