@cloudflare/vite-plugin
Version:
Cloudflare plugin for Vite
1,648 lines (1,617 loc) • 148 kB
JavaScript
// ../workers-shared/utils/tracing.ts
function mockJaegerBindingSpan() {
return {
addLogs: () => {
},
setTags: () => {
},
end: () => {
},
isRecording: true
};
}
function mockJaegerBinding() {
return {
enterSpan: (_, span, ...args) => {
return span(mockJaegerBindingSpan(), ...args);
},
getSpanContext: () => ({
traceId: "test-trace",
spanId: "test-span",
parentSpanId: "test-parent-span",
traceFlags: 0
}),
runWithSpanContext: (_, callback, ...args) => {
return callback(...args);
},
traceId: "test-trace",
spanId: "test-span",
parentSpanId: "test-parent-span",
cfTraceIdHeader: "test-trace:test-span:0"
};
}
// ../workers-shared/asset-worker/src/utils/rules-engine.ts
var ESCAPE_REGEX_CHARACTERS = /[-/\\^$*+?.()|[\]{}]/g;
var escapeRegex = (str) => {
return str.replace(ESCAPE_REGEX_CHARACTERS, "\\$&");
};
var generateGlobOnlyRuleRegExp = (rule) => {
rule = rule.split("*").map(escapeRegex).join(".*");
rule = "^" + rule + "$";
return RegExp(rule);
};
var generateStaticRoutingRuleMatcher = (rules) => ({ request }) => {
const { pathname } = new URL(request.url);
for (const rule of rules) {
try {
const regExp = generateGlobOnlyRuleRegExp(rule);
if (regExp.test(pathname)) {
return true;
}
} catch {
}
}
return false;
};
// ../workers-shared/utils/performance.ts
var PerformanceTimer = class {
performanceTimer;
constructor(performanceTimer) {
this.performanceTimer = performanceTimer;
}
now() {
if (this.performanceTimer) {
return this.performanceTimer.timeOrigin + this.performanceTimer.now();
}
return Date.now();
}
};
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/is.js
var objectToString = Object.prototype.toString;
function isError(wat) {
switch (objectToString.call(wat)) {
case "[object Error]":
case "[object Exception]":
case "[object DOMException]":
return true;
default:
return isInstanceOf(wat, Error);
}
}
function isBuiltin(wat, className) {
return objectToString.call(wat) === `[object ${className}]`;
}
function isErrorEvent(wat) {
return isBuiltin(wat, "ErrorEvent");
}
function isString(wat) {
return isBuiltin(wat, "String");
}
function isParameterizedString(wat) {
return typeof wat === "object" && wat !== null && "__sentry_template_string__" in wat && "__sentry_template_values__" in wat;
}
function isPrimitive(wat) {
return wat === null || isParameterizedString(wat) || typeof wat !== "object" && typeof wat !== "function";
}
function isPlainObject(wat) {
return isBuiltin(wat, "Object");
}
function isEvent(wat) {
return typeof Event !== "undefined" && isInstanceOf(wat, Event);
}
function isElement(wat) {
return typeof Element !== "undefined" && isInstanceOf(wat, Element);
}
function isThenable(wat) {
return Boolean(wat && wat.then && typeof wat.then === "function");
}
function isSyntheticEvent(wat) {
return isPlainObject(wat) && "nativeEvent" in wat && "preventDefault" in wat && "stopPropagation" in wat;
}
function isInstanceOf(wat, base) {
try {
return wat instanceof base;
} catch (_e) {
return false;
}
}
function isVueViewModel(wat) {
return !!(typeof wat === "object" && wat !== null && (wat.__isVue || wat._isVue));
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/string.js
function truncate(str, max = 0) {
if (typeof str !== "string" || max === 0) {
return str;
}
return str.length <= max ? str : `${str.slice(0, max)}...`;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/version.js
var SDK_VERSION = "8.9.2";
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/worldwide.js
var GLOBAL_OBJ = globalThis;
function getGlobalSingleton(name, creator, obj) {
const gbl = obj || GLOBAL_OBJ;
const __SENTRY__ = gbl.__SENTRY__ = gbl.__SENTRY__ || {};
const versionedCarrier = __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
return versionedCarrier[name] || (versionedCarrier[name] = creator());
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/browser.js
var WINDOW = GLOBAL_OBJ;
var DEFAULT_MAX_STRING_LENGTH = 80;
function htmlTreeAsString(elem, options = {}) {
if (!elem) {
return "<unknown>";
}
try {
let currentElem = elem;
const MAX_TRAVERSE_HEIGHT = 5;
const out = [];
let height = 0;
let len = 0;
const separator = " > ";
const sepLength = separator.length;
let nextStr;
const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;
const maxStringLength = !Array.isArray(options) && options.maxStringLength || DEFAULT_MAX_STRING_LENGTH;
while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {
nextStr = _htmlElementAsString(currentElem, keyAttrs);
if (nextStr === "html" || height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength) {
break;
}
out.push(nextStr);
len += nextStr.length;
currentElem = currentElem.parentNode;
}
return out.reverse().join(separator);
} catch (_oO) {
return "<unknown>";
}
}
function _htmlElementAsString(el, keyAttrs) {
const elem = el;
const out = [];
let className;
let classes;
let key;
let attr;
let i;
if (!elem || !elem.tagName) {
return "";
}
if (WINDOW.HTMLElement) {
if (elem instanceof HTMLElement && elem.dataset) {
if (elem.dataset["sentryComponent"]) {
return elem.dataset["sentryComponent"];
}
if (elem.dataset["sentryElement"]) {
return elem.dataset["sentryElement"];
}
}
}
out.push(elem.tagName.toLowerCase());
const keyAttrPairs = keyAttrs && keyAttrs.length ? keyAttrs.filter((keyAttr) => elem.getAttribute(keyAttr)).map((keyAttr) => [keyAttr, elem.getAttribute(keyAttr)]) : null;
if (keyAttrPairs && keyAttrPairs.length) {
keyAttrPairs.forEach((keyAttrPair) => {
out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`);
});
} else {
if (elem.id) {
out.push(`#${elem.id}`);
}
className = elem.className;
if (className && isString(className)) {
classes = className.split(/\s+/);
for (i = 0; i < classes.length; i++) {
out.push(`.${classes[i]}`);
}
}
}
const allowedAttrs = ["aria-label", "type", "name", "title", "alt"];
for (i = 0; i < allowedAttrs.length; i++) {
key = allowedAttrs[i];
attr = elem.getAttribute(key);
if (attr) {
out.push(`[${key}="${attr}"]`);
}
}
return out.join("");
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/debug-build.js
var DEBUG_BUILD = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/logger.js
var PREFIX = "Sentry Logger ";
var CONSOLE_LEVELS = [
"debug",
"info",
"warn",
"error",
"log",
"assert",
"trace"
];
var originalConsoleMethods = {};
function consoleSandbox(callback) {
if (!("console" in GLOBAL_OBJ)) {
return callback();
}
const console2 = GLOBAL_OBJ.console;
const wrappedFuncs = {};
const wrappedLevels = Object.keys(originalConsoleMethods);
wrappedLevels.forEach((level) => {
const originalConsoleMethod = originalConsoleMethods[level];
wrappedFuncs[level] = console2[level];
console2[level] = originalConsoleMethod;
});
try {
return callback();
} finally {
wrappedLevels.forEach((level) => {
console2[level] = wrappedFuncs[level];
});
}
}
function makeLogger() {
let enabled = false;
const logger2 = {
enable: () => {
enabled = true;
},
disable: () => {
enabled = false;
},
isEnabled: () => enabled
};
if (DEBUG_BUILD) {
CONSOLE_LEVELS.forEach((name) => {
logger2[name] = (...args) => {
if (enabled) {
consoleSandbox(() => {
GLOBAL_OBJ.console[name](`${PREFIX}[${name}]:`, ...args);
});
}
};
});
} else {
CONSOLE_LEVELS.forEach((name) => {
logger2[name] = () => void 0;
});
}
return logger2;
}
var logger = makeLogger();
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/dsn.js
var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+)?)?@)([\w.-]+)(?::(\d+))?\/(.+)/;
function isValidProtocol(protocol) {
return protocol === "http" || protocol === "https";
}
function dsnToString(dsn, withPassword = false) {
const { host, path, pass, port, projectId, protocol, publicKey } = dsn;
return `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ""}@${host}${port ? `:${port}` : ""}/${path ? `${path}/` : path}${projectId}`;
}
function dsnFromString(str) {
const match = DSN_REGEX.exec(str);
if (!match) {
consoleSandbox(() => {
console.error(`Invalid Sentry Dsn: ${str}`);
});
return void 0;
}
const [protocol, publicKey, pass = "", host, port = "", lastPath] = match.slice(1);
let path = "";
let projectId = lastPath;
const split = projectId.split("/");
if (split.length > 1) {
path = split.slice(0, -1).join("/");
projectId = split.pop();
}
if (projectId) {
const projectMatch = projectId.match(/^\d+/);
if (projectMatch) {
projectId = projectMatch[0];
}
}
return dsnFromComponents({ host, pass, path, projectId, port, protocol, publicKey });
}
function dsnFromComponents(components) {
return {
protocol: components.protocol,
publicKey: components.publicKey || "",
pass: components.pass || "",
host: components.host,
port: components.port || "",
path: components.path || "",
projectId: components.projectId
};
}
function validateDsn(dsn) {
if (!DEBUG_BUILD) {
return true;
}
const { port, projectId, protocol } = dsn;
const requiredComponents = ["protocol", "publicKey", "host", "projectId"];
const hasMissingRequiredComponent = requiredComponents.find((component) => {
if (!dsn[component]) {
logger.error(`Invalid Sentry Dsn: ${component} missing`);
return true;
}
return false;
});
if (hasMissingRequiredComponent) {
return false;
}
if (!projectId.match(/^\d+$/)) {
logger.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);
return false;
}
if (!isValidProtocol(protocol)) {
logger.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);
return false;
}
if (port && isNaN(parseInt(port, 10))) {
logger.error(`Invalid Sentry Dsn: Invalid port ${port}`);
return false;
}
return true;
}
function makeDsn(from) {
const components = typeof from === "string" ? dsnFromString(from) : dsnFromComponents(from);
if (!components || !validateDsn(components)) {
return void 0;
}
return components;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/error.js
var SentryError = class extends Error {
/** Display name of this error instance. */
constructor(message, logLevel = "warn") {
super(message);
this.message = message;
this.name = new.target.prototype.constructor.name;
Object.setPrototypeOf(this, new.target.prototype);
this.logLevel = logLevel;
}
};
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/object.js
function addNonEnumerableProperty(obj, name, value) {
try {
Object.defineProperty(obj, name, {
// enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
value,
writable: true,
configurable: true
});
} catch (o_O) {
DEBUG_BUILD && logger.log(`Failed to add non-enumerable property "${name}" to object`, obj);
}
}
function urlEncode(object) {
return Object.keys(object).map((key) => `${encodeURIComponent(key)}=${encodeURIComponent(object[key])}`).join("&");
}
function convertToPlainObject(value) {
if (isError(value)) {
return {
message: value.message,
name: value.name,
stack: value.stack,
...getOwnProperties(value)
};
} else if (isEvent(value)) {
const newObj = {
type: value.type,
target: serializeEventTarget(value.target),
currentTarget: serializeEventTarget(value.currentTarget),
...getOwnProperties(value)
};
if (typeof CustomEvent !== "undefined" && isInstanceOf(value, CustomEvent)) {
newObj.detail = value.detail;
}
return newObj;
} else {
return value;
}
}
function serializeEventTarget(target) {
try {
return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);
} catch (_oO) {
return "<unknown>";
}
}
function getOwnProperties(obj) {
if (typeof obj === "object" && obj !== null) {
const extractedProps = {};
for (const property in obj) {
if (Object.prototype.hasOwnProperty.call(obj, property)) {
extractedProps[property] = obj[property];
}
}
return extractedProps;
} else {
return {};
}
}
function extractExceptionKeysForMessage(exception, maxLength = 40) {
const keys = Object.keys(convertToPlainObject(exception));
keys.sort();
if (!keys.length) {
return "[object has no keys]";
}
if (keys[0].length >= maxLength) {
return truncate(keys[0], maxLength);
}
for (let includedKeys = keys.length; includedKeys > 0; includedKeys--) {
const serialized = keys.slice(0, includedKeys).join(", ");
if (serialized.length > maxLength) {
continue;
}
if (includedKeys === keys.length) {
return serialized;
}
return truncate(serialized, maxLength);
}
return "";
}
function dropUndefinedKeys(inputValue) {
const memoizationMap = /* @__PURE__ */ new Map();
return _dropUndefinedKeys(inputValue, memoizationMap);
}
function _dropUndefinedKeys(inputValue, memoizationMap) {
if (isPojo(inputValue)) {
const memoVal = memoizationMap.get(inputValue);
if (memoVal !== void 0) {
return memoVal;
}
const returnValue = {};
memoizationMap.set(inputValue, returnValue);
for (const key of Object.keys(inputValue)) {
if (typeof inputValue[key] !== "undefined") {
returnValue[key] = _dropUndefinedKeys(inputValue[key], memoizationMap);
}
}
return returnValue;
}
if (Array.isArray(inputValue)) {
const memoVal = memoizationMap.get(inputValue);
if (memoVal !== void 0) {
return memoVal;
}
const returnValue = [];
memoizationMap.set(inputValue, returnValue);
inputValue.forEach((item) => {
returnValue.push(_dropUndefinedKeys(item, memoizationMap));
});
return returnValue;
}
return inputValue;
}
function isPojo(input) {
if (!isPlainObject(input)) {
return false;
}
try {
const name = Object.getPrototypeOf(input).constructor.name;
return !name || name === "Object";
} catch (e) {
return true;
}
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/stacktrace.js
var STACKTRACE_FRAME_LIMIT = 50;
var UNKNOWN_FUNCTION = "?";
var WEBPACK_ERROR_REGEXP = /\(error: (.*)\)/;
var STRIP_FRAME_REGEXP = /captureMessage|captureException/;
function createStackParser(...parsers) {
const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map((p) => p[1]);
return (stack, skipFirstLines = 0, framesToPop = 0) => {
const frames = [];
const lines = stack.split("\n");
for (let i = skipFirstLines; i < lines.length; i++) {
const line = lines[i];
if (line.length > 1024) {
continue;
}
const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, "$1") : line;
if (cleanedLine.match(/\S*Error: /)) {
continue;
}
for (const parser of sortedParsers) {
const frame = parser(cleanedLine);
if (frame) {
frames.push(frame);
break;
}
}
if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {
break;
}
}
return stripSentryFramesAndReverse(frames.slice(framesToPop));
};
}
function stackParserFromStackParserOptions(stackParser) {
if (Array.isArray(stackParser)) {
return createStackParser(...stackParser);
}
return stackParser;
}
function stripSentryFramesAndReverse(stack) {
if (!stack.length) {
return [];
}
const localStack = Array.from(stack);
if (/sentryWrapped/.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
}
localStack.reverse();
if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
if (STRIP_FRAME_REGEXP.test(localStack[localStack.length - 1].function || "")) {
localStack.pop();
}
}
return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map((frame) => ({
...frame,
filename: frame.filename || localStack[localStack.length - 1].filename,
function: frame.function || UNKNOWN_FUNCTION
}));
}
var defaultFunctionName = "<anonymous>";
function getFunctionName(fn) {
try {
if (!fn || typeof fn !== "function") {
return defaultFunctionName;
}
return fn.name || defaultFunctionName;
} catch (e) {
return defaultFunctionName;
}
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/handlers.js
var handlers = {};
var instrumented = {};
function addHandler(type, handler2) {
handlers[type] = handlers[type] || [];
handlers[type].push(handler2);
}
function maybeInstrument(type, instrumentFn) {
if (!instrumented[type]) {
instrumentFn();
instrumented[type] = true;
}
}
function triggerHandlers(type, data) {
const typeHandlers = type && handlers[type];
if (!typeHandlers) {
return;
}
for (const handler2 of typeHandlers) {
try {
handler2(data);
} catch (e) {
DEBUG_BUILD && logger.error(
`Error while triggering instrumentation handler.
Type: ${type}
Name: ${getFunctionName(handler2)}
Error:`,
e
);
}
}
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/time.js
var ONE_SECOND_IN_MS = 1e3;
function dateTimestampInSeconds() {
return Date.now() / ONE_SECOND_IN_MS;
}
function createUnixTimestampInSecondsFunc() {
const { performance } = GLOBAL_OBJ;
if (!performance || !performance.now) {
return dateTimestampInSeconds;
}
const approxStartingTimeOrigin = Date.now() - performance.now();
const timeOrigin = performance.timeOrigin == void 0 ? approxStartingTimeOrigin : performance.timeOrigin;
return () => {
return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;
};
}
var timestampInSeconds = createUnixTimestampInSecondsFunc();
var _browserPerformanceTimeOriginMode;
var browserPerformanceTimeOrigin = (() => {
const { performance } = GLOBAL_OBJ;
if (!performance || !performance.now) {
_browserPerformanceTimeOriginMode = "none";
return void 0;
}
const threshold = 3600 * 1e3;
const performanceNow = performance.now();
const dateNow = Date.now();
const timeOriginDelta = performance.timeOrigin ? Math.abs(performance.timeOrigin + performanceNow - dateNow) : threshold;
const timeOriginIsReliable = timeOriginDelta < threshold;
const navigationStart = performance.timing && performance.timing.navigationStart;
const hasNavigationStart = typeof navigationStart === "number";
const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;
const navigationStartIsReliable = navigationStartDelta < threshold;
if (timeOriginIsReliable || navigationStartIsReliable) {
if (timeOriginDelta <= navigationStartDelta) {
_browserPerformanceTimeOriginMode = "timeOrigin";
return performance.timeOrigin;
} else {
_browserPerformanceTimeOriginMode = "navigationStart";
return navigationStart;
}
}
_browserPerformanceTimeOriginMode = "dateNow";
return dateNow;
})();
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/globalError.js
var _oldOnErrorHandler = null;
function addGlobalErrorInstrumentationHandler(handler2) {
const type = "error";
addHandler(type, handler2);
maybeInstrument(type, instrumentError);
}
function instrumentError() {
_oldOnErrorHandler = GLOBAL_OBJ.onerror;
GLOBAL_OBJ.onerror = function(msg, url, line, column, error) {
const handlerData = {
column,
error,
line,
msg,
url
};
triggerHandlers("error", handlerData);
if (_oldOnErrorHandler && !_oldOnErrorHandler.__SENTRY_LOADER__) {
return _oldOnErrorHandler.apply(this, arguments);
}
return false;
};
GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/instrument/globalUnhandledRejection.js
var _oldOnUnhandledRejectionHandler = null;
function addGlobalUnhandledRejectionInstrumentationHandler(handler2) {
const type = "unhandledrejection";
addHandler(type, handler2);
maybeInstrument(type, instrumentUnhandledRejection);
}
function instrumentUnhandledRejection() {
_oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;
GLOBAL_OBJ.onunhandledrejection = function(e) {
const handlerData = e;
triggerHandlers("unhandledrejection", handlerData);
if (_oldOnUnhandledRejectionHandler && !_oldOnUnhandledRejectionHandler.__SENTRY_LOADER__) {
return _oldOnUnhandledRejectionHandler.apply(this, arguments);
}
return true;
};
GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/memo.js
function memoBuilder() {
const hasWeakSet = typeof WeakSet === "function";
const inner = hasWeakSet ? /* @__PURE__ */ new WeakSet() : [];
function memoize(obj) {
if (hasWeakSet) {
if (inner.has(obj)) {
return true;
}
inner.add(obj);
return false;
}
for (let i = 0; i < inner.length; i++) {
const value = inner[i];
if (value === obj) {
return true;
}
}
inner.push(obj);
return false;
}
function unmemoize(obj) {
if (hasWeakSet) {
inner.delete(obj);
} else {
for (let i = 0; i < inner.length; i++) {
if (inner[i] === obj) {
inner.splice(i, 1);
break;
}
}
}
}
return [memoize, unmemoize];
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/misc.js
function uuid4() {
const gbl = GLOBAL_OBJ;
const crypto = gbl.crypto || gbl.msCrypto;
let getRandomByte = () => Math.random() * 16;
try {
if (crypto && crypto.randomUUID) {
return crypto.randomUUID().replace(/-/g, "");
}
if (crypto && crypto.getRandomValues) {
getRandomByte = () => {
const typedArray = new Uint8Array(1);
crypto.getRandomValues(typedArray);
return typedArray[0];
};
}
} catch (_) {
}
return ("10000000100040008000" + 1e11).replace(
/[018]/g,
(c) => (
// eslint-disable-next-line no-bitwise
(c ^ (getRandomByte() & 15) >> c / 4).toString(16)
)
);
}
function getFirstException(event) {
return event.exception && event.exception.values ? event.exception.values[0] : void 0;
}
function addExceptionTypeValue(event, value, type) {
const exception = event.exception = event.exception || {};
const values = exception.values = exception.values || [];
const firstException = values[0] = values[0] || {};
if (!firstException.value) {
firstException.value = value || "";
}
if (!firstException.type) {
firstException.type = type || "Error";
}
}
function addExceptionMechanism(event, newMechanism) {
const firstException = getFirstException(event);
if (!firstException) {
return;
}
const defaultMechanism = { type: "generic", handled: true };
const currentMechanism = firstException.mechanism;
firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };
if (newMechanism && "data" in newMechanism) {
const mergedData = { ...currentMechanism && currentMechanism.data, ...newMechanism.data };
firstException.mechanism.data = mergedData;
}
}
function checkOrSetAlreadyCaught(exception) {
if (exception && exception.__sentry_captured__) {
return true;
}
try {
addNonEnumerableProperty(exception, "__sentry_captured__", true);
} catch (err) {
}
return false;
}
function arrayify(maybeArray) {
return Array.isArray(maybeArray) ? maybeArray : [maybeArray];
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/normalize.js
function normalize(input, depth = 100, maxProperties = Infinity) {
try {
return visit("", input, depth, maxProperties);
} catch (err) {
return { ERROR: `**non-serializable** (${err})` };
}
}
function normalizeToSize(object, depth = 3, maxSize = 100 * 1024) {
const normalized = normalize(object, depth);
if (jsonSize(normalized) > maxSize) {
return normalizeToSize(object, depth - 1, maxSize);
}
return normalized;
}
function visit(key, value, depth = Infinity, maxProperties = Infinity, memo = memoBuilder()) {
const [memoize, unmemoize] = memo;
if (value == null || // this matches null and undefined -> eqeq not eqeqeq
["number", "boolean", "string"].includes(typeof value) && !Number.isNaN(value)) {
return value;
}
const stringified = stringifyValue(key, value);
if (!stringified.startsWith("[object ")) {
return stringified;
}
if (value["__sentry_skip_normalization__"]) {
return value;
}
const remainingDepth = typeof value["__sentry_override_normalization_depth__"] === "number" ? value["__sentry_override_normalization_depth__"] : depth;
if (remainingDepth === 0) {
return stringified.replace("object ", "");
}
if (memoize(value)) {
return "[Circular ~]";
}
const valueWithToJSON = value;
if (valueWithToJSON && typeof valueWithToJSON.toJSON === "function") {
try {
const jsonValue = valueWithToJSON.toJSON();
return visit("", jsonValue, remainingDepth - 1, maxProperties, memo);
} catch (err) {
}
}
const normalized = Array.isArray(value) ? [] : {};
let numAdded = 0;
const visitable = convertToPlainObject(value);
for (const visitKey in visitable) {
if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {
continue;
}
if (numAdded >= maxProperties) {
normalized[visitKey] = "[MaxProperties ~]";
break;
}
const visitValue = visitable[visitKey];
normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);
numAdded++;
}
unmemoize(value);
return normalized;
}
function stringifyValue(key, value) {
try {
if (key === "domain" && value && typeof value === "object" && value._events) {
return "[Domain]";
}
if (key === "domainEmitter") {
return "[DomainEmitter]";
}
if (typeof global !== "undefined" && value === global) {
return "[Global]";
}
if (typeof window !== "undefined" && value === window) {
return "[Window]";
}
if (typeof document !== "undefined" && value === document) {
return "[Document]";
}
if (isVueViewModel(value)) {
return "[VueViewModel]";
}
if (isSyntheticEvent(value)) {
return "[SyntheticEvent]";
}
if (typeof value === "number" && value !== value) {
return "[NaN]";
}
if (typeof value === "function") {
return `[Function: ${getFunctionName(value)}]`;
}
if (typeof value === "symbol") {
return `[${String(value)}]`;
}
if (typeof value === "bigint") {
return `[BigInt: ${String(value)}]`;
}
const objName = getConstructorName(value);
if (/^HTML(\w*)Element$/.test(objName)) {
return `[HTMLElement: ${objName}]`;
}
return `[object ${objName}]`;
} catch (err) {
return `**non-serializable** (${err})`;
}
}
function getConstructorName(value) {
const prototype = Object.getPrototypeOf(value);
return prototype ? prototype.constructor.name : "null prototype";
}
function utf8Length(value) {
return ~-encodeURI(value).split(/%..|./).length;
}
function jsonSize(value) {
return utf8Length(JSON.stringify(value));
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/path.js
function normalizeArray(parts, allowAboveRoot) {
let up = 0;
for (let i = parts.length - 1; i >= 0; i--) {
const last = parts[i];
if (last === ".") {
parts.splice(i, 1);
} else if (last === "..") {
parts.splice(i, 1);
up++;
} else if (up) {
parts.splice(i, 1);
up--;
}
}
if (allowAboveRoot) {
for (; up--; up) {
parts.unshift("..");
}
}
return parts;
}
var splitPathRe = /^(\S+:\\|\/?)([\s\S]*?)((?:\.{1,2}|[^/\\]+?|)(\.[^./\\]*|))(?:[/\\]*)$/;
function splitPath(filename) {
const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;
const parts = splitPathRe.exec(truncated);
return parts ? parts.slice(1) : [];
}
function resolve(...args) {
let resolvedPath = "";
let resolvedAbsolute = false;
for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
const path = i >= 0 ? args[i] : "/";
if (!path) {
continue;
}
resolvedPath = `${path}/${resolvedPath}`;
resolvedAbsolute = path.charAt(0) === "/";
}
resolvedPath = normalizeArray(
resolvedPath.split("/").filter((p) => !!p),
!resolvedAbsolute
).join("/");
return (resolvedAbsolute ? "/" : "") + resolvedPath || ".";
}
function trim(arr) {
let start = 0;
for (; start < arr.length; start++) {
if (arr[start] !== "") {
break;
}
}
let end = arr.length - 1;
for (; end >= 0; end--) {
if (arr[end] !== "") {
break;
}
}
if (start > end) {
return [];
}
return arr.slice(start, end - start + 1);
}
function relative(from, to) {
from = resolve(from).slice(1);
to = resolve(to).slice(1);
const fromParts = trim(from.split("/"));
const toParts = trim(to.split("/"));
const length = Math.min(fromParts.length, toParts.length);
let samePartsLength = length;
for (let i = 0; i < length; i++) {
if (fromParts[i] !== toParts[i]) {
samePartsLength = i;
break;
}
}
let outputParts = [];
for (let i = samePartsLength; i < fromParts.length; i++) {
outputParts.push("..");
}
outputParts = outputParts.concat(toParts.slice(samePartsLength));
return outputParts.join("/");
}
function basename(path, ext) {
let f = splitPath(path)[2];
if (ext && f.slice(ext.length * -1) === ext) {
f = f.slice(0, f.length - ext.length);
}
return f;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/syncpromise.js
var States;
(function(States2) {
const PENDING = 0;
States2[States2["PENDING"] = PENDING] = "PENDING";
const RESOLVED = 1;
States2[States2["RESOLVED"] = RESOLVED] = "RESOLVED";
const REJECTED = 2;
States2[States2["REJECTED"] = REJECTED] = "REJECTED";
})(States || (States = {}));
function resolvedSyncPromise(value) {
return new SyncPromise((resolve2) => {
resolve2(value);
});
}
function rejectedSyncPromise(reason) {
return new SyncPromise((_, reject) => {
reject(reason);
});
}
var SyncPromise = class _SyncPromise {
constructor(executor) {
_SyncPromise.prototype.__init.call(this);
_SyncPromise.prototype.__init2.call(this);
_SyncPromise.prototype.__init3.call(this);
_SyncPromise.prototype.__init4.call(this);
this._state = States.PENDING;
this._handlers = [];
try {
executor(this._resolve, this._reject);
} catch (e) {
this._reject(e);
}
}
/** JSDoc */
then(onfulfilled, onrejected) {
return new _SyncPromise((resolve2, reject) => {
this._handlers.push([
false,
(result) => {
if (!onfulfilled) {
resolve2(result);
} else {
try {
resolve2(onfulfilled(result));
} catch (e) {
reject(e);
}
}
},
(reason) => {
if (!onrejected) {
reject(reason);
} else {
try {
resolve2(onrejected(reason));
} catch (e) {
reject(e);
}
}
}
]);
this._executeHandlers();
});
}
/** JSDoc */
catch(onrejected) {
return this.then((val) => val, onrejected);
}
/** JSDoc */
finally(onfinally) {
return new _SyncPromise((resolve2, reject) => {
let val;
let isRejected;
return this.then(
(value) => {
isRejected = false;
val = value;
if (onfinally) {
onfinally();
}
},
(reason) => {
isRejected = true;
val = reason;
if (onfinally) {
onfinally();
}
}
).then(() => {
if (isRejected) {
reject(val);
return;
}
resolve2(val);
});
});
}
/** JSDoc */
__init() {
this._resolve = (value) => {
this._setResult(States.RESOLVED, value);
};
}
/** JSDoc */
__init2() {
this._reject = (reason) => {
this._setResult(States.REJECTED, reason);
};
}
/** JSDoc */
__init3() {
this._setResult = (state, value) => {
if (this._state !== States.PENDING) {
return;
}
if (isThenable(value)) {
void value.then(this._resolve, this._reject);
return;
}
this._state = state;
this._value = value;
this._executeHandlers();
};
}
/** JSDoc */
__init4() {
this._executeHandlers = () => {
if (this._state === States.PENDING) {
return;
}
const cachedHandlers = this._handlers.slice();
this._handlers = [];
cachedHandlers.forEach((handler2) => {
if (handler2[0]) {
return;
}
if (this._state === States.RESOLVED) {
handler2[1](this._value);
}
if (this._state === States.REJECTED) {
handler2[2](this._value);
}
handler2[0] = true;
});
};
}
};
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/promisebuffer.js
function makePromiseBuffer(limit) {
const buffer = [];
function isReady() {
return limit === void 0 || buffer.length < limit;
}
function remove(task) {
return buffer.splice(buffer.indexOf(task), 1)[0];
}
function add(taskProducer) {
if (!isReady()) {
return rejectedSyncPromise(new SentryError("Not adding Promise because buffer limit was reached."));
}
const task = taskProducer();
if (buffer.indexOf(task) === -1) {
buffer.push(task);
}
void task.then(() => remove(task)).then(
null,
() => remove(task).then(null, () => {
})
);
return task;
}
function drain(timeout) {
return new SyncPromise((resolve2, reject) => {
let counter = buffer.length;
if (!counter) {
return resolve2(true);
}
const capturedSetTimeout = setTimeout(() => {
if (timeout && timeout > 0) {
resolve2(false);
}
}, timeout);
buffer.forEach((item) => {
void resolvedSyncPromise(item).then(() => {
if (!--counter) {
clearTimeout(capturedSetTimeout);
resolve2(true);
}
}, reject);
});
});
}
return {
$: buffer,
add,
drain
};
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/node-stack-trace.js
function filenameIsInApp(filename, isNative = false) {
const isInternal = isNative || filename && // It's not internal if it's an absolute linux path
!filename.startsWith("/") && // It's not internal if it's an absolute windows path
!filename.match(/^[A-Z]:/) && // It's not internal if the path is starting with a dot
!filename.startsWith(".") && // It's not internal if the frame has a protocol. In node, this is usually the case if the file got pre-processed with a bundler like webpack
!filename.match(/^[a-zA-Z]([a-zA-Z0-9.\-+])*:\/\//);
return !isInternal && filename !== void 0 && !filename.includes("node_modules/");
}
function node(getModule2) {
const FILENAME_MATCH = /^\s*[-]{4,}$/;
const FULL_MATCH = /at (?:async )?(?:(.+?)\s+\()?(?:(.+):(\d+):(\d+)?|([^)]+))\)?/;
return (line) => {
const lineMatch = line.match(FULL_MATCH);
if (lineMatch) {
let object;
let method;
let functionName;
let typeName;
let methodName;
if (lineMatch[1]) {
functionName = lineMatch[1];
let methodStart = functionName.lastIndexOf(".");
if (functionName[methodStart - 1] === ".") {
methodStart--;
}
if (methodStart > 0) {
object = functionName.slice(0, methodStart);
method = functionName.slice(methodStart + 1);
const objectEnd = object.indexOf(".Module");
if (objectEnd > 0) {
functionName = functionName.slice(objectEnd + 1);
object = object.slice(0, objectEnd);
}
}
typeName = void 0;
}
if (method) {
typeName = object;
methodName = method;
}
if (method === "<anonymous>") {
methodName = void 0;
functionName = void 0;
}
if (functionName === void 0) {
methodName = methodName || UNKNOWN_FUNCTION;
functionName = typeName ? `${typeName}.${methodName}` : methodName;
}
let filename = lineMatch[2] && lineMatch[2].startsWith("file://") ? lineMatch[2].slice(7) : lineMatch[2];
const isNative = lineMatch[5] === "native";
if (filename && filename.match(/\/[A-Z]:/)) {
filename = filename.slice(1);
}
if (!filename && lineMatch[5] && !isNative) {
filename = lineMatch[5];
}
return {
filename,
module: getModule2 ? getModule2(filename) : void 0,
function: functionName,
lineno: parseInt(lineMatch[3], 10) || void 0,
colno: parseInt(lineMatch[4], 10) || void 0,
in_app: filenameIsInApp(filename, isNative)
};
}
if (line.match(FILENAME_MATCH)) {
return {
filename: line
};
}
return void 0;
};
}
function nodeStackLineParser(getModule2) {
return [90, node(getModule2)];
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/envelope.js
function createEnvelope(headers, items = []) {
return [headers, items];
}
function addItemToEnvelope(envelope, newItem) {
const [headers, items] = envelope;
return [headers, [...items, newItem]];
}
function forEachEnvelopeItem(envelope, callback) {
const envelopeItems = envelope[1];
for (const envelopeItem of envelopeItems) {
const envelopeItemType = envelopeItem[0].type;
const result = callback(envelopeItem, envelopeItemType);
if (result) {
return true;
}
}
return false;
}
function encodeUTF8(input) {
return GLOBAL_OBJ.__SENTRY__ && GLOBAL_OBJ.__SENTRY__.encodePolyfill ? GLOBAL_OBJ.__SENTRY__.encodePolyfill(input) : new TextEncoder().encode(input);
}
function serializeEnvelope(envelope) {
const [envHeaders, items] = envelope;
let parts = JSON.stringify(envHeaders);
function append(next) {
if (typeof parts === "string") {
parts = typeof next === "string" ? parts + next : [encodeUTF8(parts), next];
} else {
parts.push(typeof next === "string" ? encodeUTF8(next) : next);
}
}
for (const item of items) {
const [itemHeaders, payload] = item;
append(`
${JSON.stringify(itemHeaders)}
`);
if (typeof payload === "string" || payload instanceof Uint8Array) {
append(payload);
} else {
let stringifiedPayload;
try {
stringifiedPayload = JSON.stringify(payload);
} catch (e) {
stringifiedPayload = JSON.stringify(normalize(payload));
}
append(stringifiedPayload);
}
}
return typeof parts === "string" ? parts : concatBuffers(parts);
}
function concatBuffers(buffers) {
const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);
const merged = new Uint8Array(totalLength);
let offset = 0;
for (const buffer of buffers) {
merged.set(buffer, offset);
offset += buffer.length;
}
return merged;
}
function createAttachmentEnvelopeItem(attachment) {
const buffer = typeof attachment.data === "string" ? encodeUTF8(attachment.data) : attachment.data;
return [
dropUndefinedKeys({
type: "attachment",
length: buffer.length,
filename: attachment.filename,
content_type: attachment.contentType,
attachment_type: attachment.attachmentType
}),
buffer
];
}
var ITEM_TYPE_TO_DATA_CATEGORY_MAP = {
session: "session",
sessions: "session",
attachment: "attachment",
transaction: "transaction",
event: "error",
client_report: "internal",
user_report: "default",
profile: "profile",
profile_chunk: "profile",
replay_event: "replay",
replay_recording: "replay",
check_in: "monitor",
feedback: "feedback",
span: "span",
statsd: "metric_bucket"
};
function envelopeItemTypeToDataCategory(type) {
return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];
}
function getSdkMetadataForEnvelopeHeader(metadataOrEvent) {
if (!metadataOrEvent || !metadataOrEvent.sdk) {
return;
}
const { name, version } = metadataOrEvent.sdk;
return { name, version };
}
function createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn) {
const dynamicSamplingContext = event.sdkProcessingMetadata && event.sdkProcessingMetadata.dynamicSamplingContext;
return {
event_id: event.event_id,
sent_at: (/* @__PURE__ */ new Date()).toISOString(),
...sdkInfo && { sdk: sdkInfo },
...!!tunnel && dsn && { dsn: dsnToString(dsn) },
...dynamicSamplingContext && {
trace: dropUndefinedKeys({ ...dynamicSamplingContext })
}
};
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/ratelimit.js
var DEFAULT_RETRY_AFTER = 60 * 1e3;
function parseRetryAfterHeader(header, now = Date.now()) {
const headerDelay = parseInt(`${header}`, 10);
if (!isNaN(headerDelay)) {
return headerDelay * 1e3;
}
const headerDate = Date.parse(`${header}`);
if (!isNaN(headerDate)) {
return headerDate - now;
}
return DEFAULT_RETRY_AFTER;
}
function disabledUntil(limits, dataCategory) {
return limits[dataCategory] || limits.all || 0;
}
function isRateLimited(limits, dataCategory, now = Date.now()) {
return disabledUntil(limits, dataCategory) > now;
}
function updateRateLimits(limits, { statusCode, headers }, now = Date.now()) {
const updatedRateLimits = {
...limits
};
const rateLimitHeader = headers && headers["x-sentry-rate-limits"];
const retryAfterHeader = headers && headers["retry-after"];
if (rateLimitHeader) {
for (const limit of rateLimitHeader.trim().split(",")) {
const [retryAfter, categories, , , namespaces] = limit.split(":", 5);
const headerDelay = parseInt(retryAfter, 10);
const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1e3;
if (!categories) {
updatedRateLimits.all = now + delay;
} else {
for (const category of categories.split(";")) {
if (category === "metric_bucket") {
if (!namespaces || namespaces.split(";").includes("custom")) {
updatedRateLimits[category] = now + delay;
}
} else {
updatedRateLimits[category] = now + delay;
}
}
}
}
} else if (retryAfterHeader) {
updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);
} else if (statusCode === 429) {
updatedRateLimits.all = now + 60 * 1e3;
}
return updatedRateLimits;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/eventbuilder.js
function parseStackFrames(stackParser, error) {
return stackParser(error.stack || "", 1);
}
function exceptionFromError(stackParser, error) {
const exception = {
type: error.name || error.constructor.name,
value: error.message
};
const frames = parseStackFrames(stackParser, error);
if (frames.length) {
exception.stacktrace = { frames };
}
return exception;
}
function getErrorPropertyFromObject(obj) {
for (const prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
const value = obj[prop];
if (value instanceof Error) {
return value;
}
}
}
return void 0;
}
function getMessageForObject(exception) {
if ("name" in exception && typeof exception.name === "string") {
let message = `'${exception.name}' captured as exception`;
if ("message" in exception && typeof exception.message === "string") {
message += ` with message '${exception.message}'`;
}
return message;
} else if ("message" in exception && typeof exception.message === "string") {
return exception.message;
}
const keys = extractExceptionKeysForMessage(exception);
if (isErrorEvent(exception)) {
return `Event \`ErrorEvent\` captured as exception with message \`${exception.message}\``;
}
const className = getObjectClassName(exception);
return `${className && className !== "Object" ? `'${className}'` : "Object"} captured as exception with keys: ${keys}`;
}
function getObjectClassName(obj) {
try {
const prototype = Object.getPrototypeOf(obj);
return prototype ? prototype.constructor.name : void 0;
} catch (e) {
}
}
function getException(client, mechanism, exception, hint) {
if (isError(exception)) {
return [exception, void 0];
}
mechanism.synthetic = true;
if (isPlainObject(exception)) {
const normalizeDepth = client && client.getOptions().normalizeDepth;
const extras = { ["__serialized__"]: normalizeToSize(exception, normalizeDepth) };
const errorFromProp = getErrorPropertyFromObject(exception);
if (errorFromProp) {
return [errorFromProp, extras];
}
const message = getMessageForObject(exception);
const ex2 = hint && hint.syntheticException || new Error(message);
ex2.message = message;
return [ex2, extras];
}
const ex = hint && hint.syntheticException || new Error(exception);
ex.message = `${exception}`;
return [ex, void 0];
}
function eventFromUnknownInput(client, stackParser, exception, hint) {
const providedMechanism = hint && hint.data && hint.data.mechanism;
const mechanism = providedMechanism || {
handled: true,
type: "generic"
};
const [ex, extras] = getException(client, mechanism, exception, hint);
const event = {
exception: {
values: [exceptionFromError(stackParser, ex)]
}
};
if (extras) {
event.extra = extras;
}
addExceptionTypeValue(event, void 0, void 0);
addExceptionMechanism(event, mechanism);
return {
...event,
event_id: hint && hint.event_id
};
}
function eventFromMessage(stackParser, message, level = "info", hint, attachStacktrace) {
const event = {
event_id: hint && hint.event_id,
level
};
if (attachStacktrace && hint && hint.syntheticException) {
const frames = parseStackFrames(stackParser, hint.syntheticException);
if (frames.length) {
event.exception = {
values: [
{
value: message,
stacktrace: { frames }
}
]
};
}
}
if (isParameterizedString(message)) {
const { __sentry_template_string__, __sentry_template_values__ } = message;
event.logentry = {
message: __sentry_template_string__,
params: __sentry_template_values__
};
return event;
}
event.message = message;
return event;
}
// ../../node_modules/.pnpm/@sentry+utils@8.9.2/node_modules/@sentry/utils/esm/propagationContext.js
function generatePropagationContext() {
return {
traceId: uuid4(),
spanId: uuid4().substring(16)
};
}
// ../../node_modules/.pnpm/@sentry+core@8.9.2/node_modules/@sentry/core/esm/debug-build.js
var DEBUG_BUILD2 = typeof __SENTRY_DEBUG__ === "undefined" || __SENTRY_DEBUG__;
// ../../node_modules/.pnpm/@sentry+core@8.9.2/node_modules/@sentry/core/esm/carrier.js
function getMainCarrier() {
getSentryCarrier(GLOBAL_OBJ);
return GLOBAL_OBJ;
}
function getSentryCarrier(carrier) {
const __SENTRY__ = carrier.__SENTRY__ = carrier.__SENTRY__ || {};
__SENTRY__.version = __SENTRY__.version || SDK_VERSION;
return __SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {};
}
// ../../node_modules/.pnpm/@sentry+core@8.9.2/node_modules/@sentry/core/esm/session.js
function updateSession(session, context = {}) {
if (context.user) {
if (!session.ipAddress && context.user.ip_address) {
session.ipAddress = context.user.ip_address;
}
if (!session.did && !context.did) {
session.did = context.user.id || context.user.email || context.user.username;
}
}
session.timestamp = context.timestamp || timestampInSeconds();
if (context.abnormal_mechanism) {
session.abnormal_mechanism = context.abnormal_mechanism;
}
if (context.ignoreDuration) {
session.ignoreDuration = context.ignoreDuration;
}
if (context.sid) {
session.sid = context.sid.length === 32 ? context.sid : uuid4();
}
if (context.init !== void 0) {
session.init = context.init;
}
if (!session.did && context.did) {
session.did = `${context.did}`;
}
if (typeof context.started === "number") {
session.started = context.started;
}
if (session.ignoreDuration) {
session.duration = void 0;
} else if (typeof context.duration === "number") {
session.duration = context.duration;
} else {
const duration = session.timestamp - session.started;
session.duration = duration >= 0 ? duration : 0;
}
if (context.release) {
session.release = context.release;
}
if (contex