@lowerdeck/queue 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.umd.js","sources":["../../delay/dist/index.module.js","../src/lib/queueRetryError.ts","../../../node_modules/superjson/dist/double-indexed-kv.js","../../../node_modules/superjson/dist/registry.js","../../../node_modules/superjson/dist/class-registry.js","../../../node_modules/superjson/dist/util.js","../../../node_modules/superjson/dist/custom-transformer-registry.js","../../../node_modules/superjson/dist/is.js","../../../node_modules/superjson/dist/pathstringifier.js","../../../node_modules/superjson/dist/transformer.js","../../../node_modules/superjson/dist/accessDeep.js","../../../node_modules/superjson/dist/plainer.js","../../../node_modules/is-what/dist/getType.js","../../../node_modules/is-what/dist/isArray.js","../../../node_modules/copy-anything/dist/index.js","../../../node_modules/is-what/dist/isPlainObject.js","../../../node_modules/superjson/dist/index.js","../src/drivers/bullmq.ts","../src/index.ts","../../memo/dist/index.module.js"],"sourcesContent":["var e=function(e){return new Promise(function(n){return setTimeout(n,e)})};export{e as delay};\n//# sourceMappingURL=index.module.js.map\n","export class QueueRetryError extends Error {\n constructor() {\n super('RETRY');\n }\n}\n","export class DoubleIndexedKV {\n constructor() {\n this.keyToValue = new Map();\n this.valueToKey = new Map();\n }\n set(key, value) {\n this.keyToValue.set(key, value);\n this.valueToKey.set(value, key);\n }\n getByKey(key) {\n return this.keyToValue.get(key);\n }\n getByValue(value) {\n return this.valueToKey.get(value);\n }\n clear() {\n this.keyToValue.clear();\n this.valueToKey.clear();\n }\n}\n//# sourceMappingURL=double-indexed-kv.js.map","import { DoubleIndexedKV } from './double-indexed-kv.js';\nexport class Registry {\n constructor(generateIdentifier) {\n this.generateIdentifier = generateIdentifier;\n this.kv = new DoubleIndexedKV();\n }\n register(value, identifier) {\n if (this.kv.getByValue(value)) {\n return;\n }\n if (!identifier) {\n identifier = this.generateIdentifier(value);\n }\n this.kv.set(identifier, value);\n }\n clear() {\n this.kv.clear();\n }\n getIdentifier(value) {\n return this.kv.getByValue(value);\n }\n getValue(identifier) {\n return this.kv.getByKey(identifier);\n }\n}\n//# sourceMappingURL=registry.js.map","import { Registry } from './registry.js';\nexport class ClassRegistry extends Registry {\n constructor() {\n super(c => c.name);\n this.classToAllowedProps = new Map();\n }\n register(value, options) {\n if (typeof options === 'object') {\n if (options.allowProps) {\n this.classToAllowedProps.set(value, options.allowProps);\n }\n super.register(value, options.identifier);\n }\n else {\n super.register(value, options);\n }\n }\n getAllowedProps(value) {\n return this.classToAllowedProps.get(value);\n }\n}\n//# sourceMappingURL=class-registry.js.map","function valuesOfObj(record) {\n if ('values' in Object) {\n // eslint-disable-next-line es5/no-es6-methods\n return Object.values(record);\n }\n const values = [];\n // eslint-disable-next-line no-restricted-syntax\n for (const key in record) {\n if (record.hasOwnProperty(key)) {\n values.push(record[key]);\n }\n }\n return values;\n}\nexport function find(record, predicate) {\n const values = valuesOfObj(record);\n if ('find' in values) {\n // eslint-disable-next-line es5/no-es6-methods\n return values.find(predicate);\n }\n const valuesNotNever = values;\n for (let i = 0; i < valuesNotNever.length; i++) {\n const value = valuesNotNever[i];\n if (predicate(value)) {\n return value;\n }\n }\n return undefined;\n}\nexport function forEach(record, run) {\n Object.entries(record).forEach(([key, value]) => run(value, key));\n}\nexport function includes(arr, value) {\n return arr.indexOf(value) !== -1;\n}\nexport function findArr(record, predicate) {\n for (let i = 0; i < record.length; i++) {\n const value = record[i];\n if (predicate(value)) {\n return value;\n }\n }\n return undefined;\n}\n//# sourceMappingURL=util.js.map","import { find } from './util.js';\nexport class CustomTransformerRegistry {\n constructor() {\n this.transfomers = {};\n }\n register(transformer) {\n this.transfomers[transformer.name] = transformer;\n }\n findApplicable(v) {\n return find(this.transfomers, transformer => transformer.isApplicable(v));\n }\n findByName(name) {\n return this.transfomers[name];\n }\n}\n//# sourceMappingURL=custom-transformer-registry.js.map","const getType = (payload) => Object.prototype.toString.call(payload).slice(8, -1);\nexport const isUndefined = (payload) => typeof payload === 'undefined';\nexport const isNull = (payload) => payload === null;\nexport const isPlainObject = (payload) => {\n if (typeof payload !== 'object' || payload === null)\n return false;\n if (payload === Object.prototype)\n return false;\n if (Object.getPrototypeOf(payload) === null)\n return true;\n return Object.getPrototypeOf(payload) === Object.prototype;\n};\nexport const isEmptyObject = (payload) => isPlainObject(payload) && Object.keys(payload).length === 0;\nexport const isArray = (payload) => Array.isArray(payload);\nexport const isString = (payload) => typeof payload === 'string';\nexport const isNumber = (payload) => typeof payload === 'number' && !isNaN(payload);\nexport const isBoolean = (payload) => typeof payload === 'boolean';\nexport const isRegExp = (payload) => payload instanceof RegExp;\nexport const isMap = (payload) => payload instanceof Map;\nexport const isSet = (payload) => payload instanceof Set;\nexport const isSymbol = (payload) => getType(payload) === 'Symbol';\nexport const isDate = (payload) => payload instanceof Date && !isNaN(payload.valueOf());\nexport const isError = (payload) => payload instanceof Error;\nexport const isNaNValue = (payload) => typeof payload === 'number' && isNaN(payload);\nexport const isPrimitive = (payload) => isBoolean(payload) ||\n isNull(payload) ||\n isUndefined(payload) ||\n isNumber(payload) ||\n isString(payload) ||\n isSymbol(payload);\nexport const isBigint = (payload) => typeof payload === 'bigint';\nexport const isInfinite = (payload) => payload === Infinity || payload === -Infinity;\nexport const isTypedArray = (payload) => ArrayBuffer.isView(payload) && !(payload instanceof DataView);\nexport const isURL = (payload) => payload instanceof URL;\n//# sourceMappingURL=is.js.map","export const escapeKey = (key) => key.replace(/\\\\/g, '\\\\\\\\').replace(/\\./g, '\\\\.');\nexport const stringifyPath = (path) => path\n .map(String)\n .map(escapeKey)\n .join('.');\nexport const parsePath = (string, legacyPaths) => {\n const result = [];\n let segment = '';\n for (let i = 0; i < string.length; i++) {\n let char = string.charAt(i);\n if (!legacyPaths && char === '\\\\') {\n const escaped = string.charAt(i + 1);\n if (escaped === '\\\\') {\n segment += '\\\\';\n i++;\n continue;\n }\n else if (escaped !== '.') {\n throw Error('invalid path');\n }\n }\n const isEscapedDot = char === '\\\\' && string.charAt(i + 1) === '.';\n if (isEscapedDot) {\n segment += '.';\n i++;\n continue;\n }\n const isEndOfSegment = char === '.';\n if (isEndOfSegment) {\n result.push(segment);\n segment = '';\n continue;\n }\n segment += char;\n }\n const lastSegment = segment;\n result.push(lastSegment);\n return result;\n};\n//# sourceMappingURL=pathstringifier.js.map","import { isBigint, isDate, isInfinite, isMap, isNaNValue, isRegExp, isSet, isUndefined, isSymbol, isArray, isError, isTypedArray, isURL, } from './is.js';\nimport { findArr } from './util.js';\nfunction simpleTransformation(isApplicable, annotation, transform, untransform) {\n return {\n isApplicable,\n annotation,\n transform,\n untransform,\n };\n}\nconst simpleRules = [\n simpleTransformation(isUndefined, 'undefined', () => null, () => undefined),\n simpleTransformation(isBigint, 'bigint', v => v.toString(), v => {\n if (typeof BigInt !== 'undefined') {\n return BigInt(v);\n }\n console.error('Please add a BigInt polyfill.');\n return v;\n }),\n simpleTransformation(isDate, 'Date', v => v.toISOString(), v => new Date(v)),\n simpleTransformation(isError, 'Error', (v, superJson) => {\n const baseError = {\n name: v.name,\n message: v.message,\n };\n if ('cause' in v) {\n baseError.cause = v.cause;\n }\n superJson.allowedErrorProps.forEach(prop => {\n baseError[prop] = v[prop];\n });\n return baseError;\n }, (v, superJson) => {\n const e = new Error(v.message, { cause: v.cause });\n e.name = v.name;\n e.stack = v.stack;\n superJson.allowedErrorProps.forEach(prop => {\n e[prop] = v[prop];\n });\n return e;\n }),\n simpleTransformation(isRegExp, 'regexp', v => '' + v, regex => {\n const body = regex.slice(1, regex.lastIndexOf('/'));\n const flags = regex.slice(regex.lastIndexOf('/') + 1);\n return new RegExp(body, flags);\n }),\n simpleTransformation(isSet, 'set', \n // (sets only exist in es6+)\n // eslint-disable-next-line es5/no-es6-methods\n v => [...v.values()], v => new Set(v)),\n simpleTransformation(isMap, 'map', v => [...v.entries()], v => new Map(v)),\n simpleTransformation((v) => isNaNValue(v) || isInfinite(v), 'number', v => {\n if (isNaNValue(v)) {\n return 'NaN';\n }\n if (v > 0) {\n return 'Infinity';\n }\n else {\n return '-Infinity';\n }\n }, Number),\n simpleTransformation((v) => v === 0 && 1 / v === -Infinity, 'number', () => {\n return '-0';\n }, Number),\n simpleTransformation(isURL, 'URL', v => v.toString(), v => new URL(v)),\n];\nfunction compositeTransformation(isApplicable, annotation, transform, untransform) {\n return {\n isApplicable,\n annotation,\n transform,\n untransform,\n };\n}\nconst symbolRule = compositeTransformation((s, superJson) => {\n if (isSymbol(s)) {\n const isRegistered = !!superJson.symbolRegistry.getIdentifier(s);\n return isRegistered;\n }\n return false;\n}, (s, superJson) => {\n const identifier = superJson.symbolRegistry.getIdentifier(s);\n return ['symbol', identifier];\n}, v => v.description, (_, a, superJson) => {\n const value = superJson.symbolRegistry.getValue(a[1]);\n if (!value) {\n throw new Error('Trying to deserialize unknown symbol');\n }\n return value;\n});\nconst constructorToName = [\n Int8Array,\n Uint8Array,\n Int16Array,\n Uint16Array,\n Int32Array,\n Uint32Array,\n Float32Array,\n Float64Array,\n Uint8ClampedArray,\n].reduce((obj, ctor) => {\n obj[ctor.name] = ctor;\n return obj;\n}, {});\nconst typedArrayRule = compositeTransformation(isTypedArray, v => ['typed-array', v.constructor.name], v => [...v], (v, a) => {\n const ctor = constructorToName[a[1]];\n if (!ctor) {\n throw new Error('Trying to deserialize unknown typed array');\n }\n return new ctor(v);\n});\nexport function isInstanceOfRegisteredClass(potentialClass, superJson) {\n if (potentialClass?.constructor) {\n const isRegistered = !!superJson.classRegistry.getIdentifier(potentialClass.constructor);\n return isRegistered;\n }\n return false;\n}\nconst classRule = compositeTransformation(isInstanceOfRegisteredClass, (clazz, superJson) => {\n const identifier = superJson.classRegistry.getIdentifier(clazz.constructor);\n return ['class', identifier];\n}, (clazz, superJson) => {\n const allowedProps = superJson.classRegistry.getAllowedProps(clazz.constructor);\n if (!allowedProps) {\n return { ...clazz };\n }\n const result = {};\n allowedProps.forEach(prop => {\n result[prop] = clazz[prop];\n });\n return result;\n}, (v, a, superJson) => {\n const clazz = superJson.classRegistry.getValue(a[1]);\n if (!clazz) {\n throw new Error(`Trying to deserialize unknown class '${a[1]}' - check https://github.com/blitz-js/superjson/issues/116#issuecomment-773996564`);\n }\n return Object.assign(Object.create(clazz.prototype), v);\n});\nconst customRule = compositeTransformation((value, superJson) => {\n return !!superJson.customTransformerRegistry.findApplicable(value);\n}, (value, superJson) => {\n const transformer = superJson.customTransformerRegistry.findApplicable(value);\n return ['custom', transformer.name];\n}, (value, superJson) => {\n const transformer = superJson.customTransformerRegistry.findApplicable(value);\n return transformer.serialize(value);\n}, (v, a, superJson) => {\n const transformer = superJson.customTransformerRegistry.findByName(a[1]);\n if (!transformer) {\n throw new Error('Trying to deserialize unknown custom value');\n }\n return transformer.deserialize(v);\n});\nconst compositeRules = [classRule, symbolRule, customRule, typedArrayRule];\nexport const transformValue = (value, superJson) => {\n const applicableCompositeRule = findArr(compositeRules, rule => rule.isApplicable(value, superJson));\n if (applicableCompositeRule) {\n return {\n value: applicableCompositeRule.transform(value, superJson),\n type: applicableCompositeRule.annotation(value, superJson),\n };\n }\n const applicableSimpleRule = findArr(simpleRules, rule => rule.isApplicable(value, superJson));\n if (applicableSimpleRule) {\n return {\n value: applicableSimpleRule.transform(value, superJson),\n type: applicableSimpleRule.annotation,\n };\n }\n return undefined;\n};\nconst simpleRulesByAnnotation = {};\nsimpleRules.forEach(rule => {\n simpleRulesByAnnotation[rule.annotation] = rule;\n});\nexport const untransformValue = (json, type, superJson) => {\n if (isArray(type)) {\n switch (type[0]) {\n case 'symbol':\n return symbolRule.untransform(json, type, superJson);\n case 'class':\n return classRule.untransform(json, type, superJson);\n case 'custom':\n return customRule.untransform(json, type, superJson);\n case 'typed-array':\n return typedArrayRule.untransform(json, type, superJson);\n default:\n throw new Error('Unknown transformation: ' + type);\n }\n }\n else {\n const transformation = simpleRulesByAnnotation[type];\n if (!transformation) {\n throw new Error('Unknown transformation: ' + type);\n }\n return transformation.untransform(json, superJson);\n }\n};\n//# sourceMappingURL=transformer.js.map","import { isMap, isArray, isPlainObject, isSet } from './is.js';\nimport { includes } from './util.js';\nconst getNthKey = (value, n) => {\n if (n > value.size)\n throw new Error('index out of bounds');\n const keys = value.keys();\n while (n > 0) {\n keys.next();\n n--;\n }\n return keys.next().value;\n};\nfunction validatePath(path) {\n if (includes(path, '__proto__')) {\n throw new Error('__proto__ is not allowed as a property');\n }\n if (includes(path, 'prototype')) {\n throw new Error('prototype is not allowed as a property');\n }\n if (includes(path, 'constructor')) {\n throw new Error('constructor is not allowed as a property');\n }\n}\nexport const getDeep = (object, path) => {\n validatePath(path);\n for (let i = 0; i < path.length; i++) {\n const key = path[i];\n if (isSet(object)) {\n object = getNthKey(object, +key);\n }\n else if (isMap(object)) {\n const row = +key;\n const type = +path[++i] === 0 ? 'key' : 'value';\n const keyOfRow = getNthKey(object, row);\n switch (type) {\n case 'key':\n object = keyOfRow;\n break;\n case 'value':\n object = object.get(keyOfRow);\n break;\n }\n }\n else {\n object = object[key];\n }\n }\n return object;\n};\nexport const setDeep = (object, path, mapper) => {\n validatePath(path);\n if (path.length === 0) {\n return mapper(object);\n }\n let parent = object;\n for (let i = 0; i < path.length - 1; i++) {\n const key = path[i];\n if (isArray(parent)) {\n const index = +key;\n parent = parent[index];\n }\n else if (isPlainObject(parent)) {\n parent = parent[key];\n }\n else if (isSet(parent)) {\n const row = +key;\n parent = getNthKey(parent, row);\n }\n else if (isMap(parent)) {\n const isEnd = i === path.length - 2;\n if (isEnd) {\n break;\n }\n const row = +key;\n const type = +path[++i] === 0 ? 'key' : 'value';\n const keyOfRow = getNthKey(parent, row);\n switch (type) {\n case 'key':\n parent = keyOfRow;\n break;\n case 'value':\n parent = parent.get(keyOfRow);\n break;\n }\n }\n }\n const lastKey = path[path.length - 1];\n if (isArray(parent)) {\n parent[+lastKey] = mapper(parent[+lastKey]);\n }\n else if (isPlainObject(parent)) {\n parent[lastKey] = mapper(parent[lastKey]);\n }\n if (isSet(parent)) {\n const oldValue = getNthKey(parent, +lastKey);\n const newValue = mapper(oldValue);\n if (oldValue !== newValue) {\n parent.delete(oldValue);\n parent.add(newValue);\n }\n }\n if (isMap(parent)) {\n const row = +path[path.length - 2];\n const keyToRow = getNthKey(parent, row);\n const type = +lastKey === 0 ? 'key' : 'value';\n switch (type) {\n case 'key': {\n const newKey = mapper(keyToRow);\n parent.set(newKey, parent.get(keyToRow));\n if (newKey !== keyToRow) {\n parent.delete(keyToRow);\n }\n break;\n }\n case 'value': {\n parent.set(keyToRow, mapper(parent.get(keyToRow)));\n break;\n }\n }\n }\n return object;\n};\n//# sourceMappingURL=accessDeep.js.map","import { isArray, isEmptyObject, isError, isMap, isPlainObject, isPrimitive, isSet, } from './is.js';\nimport { escapeKey, stringifyPath } from './pathstringifier.js';\nimport { isInstanceOfRegisteredClass, transformValue, untransformValue, } from './transformer.js';\nimport { includes, forEach } from './util.js';\nimport { parsePath } from './pathstringifier.js';\nimport { getDeep, setDeep } from './accessDeep.js';\nconst enableLegacyPaths = (version) => version < 1;\nfunction traverse(tree, walker, version, origin = []) {\n if (!tree) {\n return;\n }\n const legacyPaths = enableLegacyPaths(version);\n if (!isArray(tree)) {\n forEach(tree, (subtree, key) => traverse(subtree, walker, version, [\n ...origin,\n ...parsePath(key, legacyPaths),\n ]));\n return;\n }\n const [nodeValue, children] = tree;\n if (children) {\n forEach(children, (child, key) => {\n traverse(child, walker, version, [\n ...origin,\n ...parsePath(key, legacyPaths),\n ]);\n });\n }\n walker(nodeValue, origin);\n}\nexport function applyValueAnnotations(plain, annotations, version, superJson) {\n traverse(annotations, (type, path) => {\n plain = setDeep(plain, path, v => untransformValue(v, type, superJson));\n }, version);\n return plain;\n}\nexport function applyReferentialEqualityAnnotations(plain, annotations, version) {\n const legacyPaths = enableLegacyPaths(version);\n function apply(identicalPaths, path) {\n const object = getDeep(plain, parsePath(path, legacyPaths));\n identicalPaths\n .map(path => parsePath(path, legacyPaths))\n .forEach(identicalObjectPath => {\n plain = setDeep(plain, identicalObjectPath, () => object);\n });\n }\n if (isArray(annotations)) {\n const [root, other] = annotations;\n root.forEach(identicalPath => {\n plain = setDeep(plain, parsePath(identicalPath, legacyPaths), () => plain);\n });\n if (other) {\n forEach(other, apply);\n }\n }\n else {\n forEach(annotations, apply);\n }\n return plain;\n}\nconst isDeep = (object, superJson) => isPlainObject(object) ||\n isArray(object) ||\n isMap(object) ||\n isSet(object) ||\n isError(object) ||\n isInstanceOfRegisteredClass(object, superJson);\nfunction addIdentity(object, path, identities) {\n const existingSet = identities.get(object);\n if (existingSet) {\n existingSet.push(path);\n }\n else {\n identities.set(object, [path]);\n }\n}\nexport function generateReferentialEqualityAnnotations(identitites, dedupe) {\n const result = {};\n let rootEqualityPaths = undefined;\n identitites.forEach(paths => {\n if (paths.length <= 1) {\n return;\n }\n // if we're not deduping, all of these objects continue existing.\n // putting the shortest path first makes it easier to parse for humans\n // if we're deduping though, only the first entry will still exist, so we can't do this optimisation.\n if (!dedupe) {\n paths = paths\n .map(path => path.map(String))\n .sort((a, b) => a.length - b.length);\n }\n const [representativePath, ...identicalPaths] = paths;\n if (representativePath.length === 0) {\n rootEqualityPaths = identicalPaths.map(stringifyPath);\n }\n else {\n result[stringifyPath(representativePath)] = identicalPaths.map(stringifyPath);\n }\n });\n if (rootEqualityPaths) {\n if (isEmptyObject(result)) {\n return [rootEqualityPaths];\n }\n else {\n return [rootEqualityPaths, result];\n }\n }\n else {\n return isEmptyObject(result) ? undefined : result;\n }\n}\nexport const walker = (object, identities, superJson, dedupe, path = [], objectsInThisPath = [], seenObjects = new Map()) => {\n const primitive = isPrimitive(object);\n if (!primitive) {\n addIdentity(object, path, identities);\n const seen = seenObjects.get(object);\n if (seen) {\n // short-circuit result if we've seen this object before\n return dedupe\n ? {\n transformedValue: null,\n }\n : seen;\n }\n }\n if (!isDeep(object, superJson)) {\n const transformed = transformValue(object, superJson);\n const result = transformed\n ? {\n transformedValue: transformed.value,\n annotations: [transformed.type],\n }\n : {\n transformedValue: object,\n };\n if (!primitive) {\n seenObjects.set(object, result);\n }\n return result;\n }\n if (includes(objectsInThisPath, object)) {\n // prevent circular references\n return {\n transformedValue: null,\n };\n }\n const transformationResult = transformValue(object, superJson);\n const transformed = transformationResult?.value ?? object;\n const transformedValue = isArray(transformed) ? [] : {};\n const innerAnnotations = {};\n forEach(transformed, (value, index) => {\n if (index === '__proto__' ||\n index === 'constructor' ||\n index === 'prototype') {\n throw new Error(`Detected property ${index}. This is a prototype pollution risk, please remove it from your object.`);\n }\n const recursiveResult = walker(value, identities, superJson, dedupe, [...path, index], [...objectsInThisPath, object], seenObjects);\n transformedValue[index] = recursiveResult.transformedValue;\n if (isArray(recursiveResult.annotations)) {\n innerAnnotations[escapeKey(index)] = recursiveResult.annotations;\n }\n else if (isPlainObject(recursiveResult.annotations)) {\n forEach(recursiveResult.annotations, (tree, key) => {\n innerAnnotations[escapeKey(index) + '.' + key] = tree;\n });\n }\n });\n const result = isEmptyObject(innerAnnotations)\n ? {\n transformedValue,\n annotations: !!transformationResult\n ? [transformationResult.type]\n : undefined,\n }\n : {\n transformedValue,\n annotations: !!transformationResult\n ? [transformationResult.type, innerAnnotations]\n : innerAnnotations,\n };\n if (!primitive) {\n seenObjects.set(object, result);\n }\n return result;\n};\n//# sourceMappingURL=plainer.js.map","/** Returns the object type of the given payload */\nexport function getType(payload) {\n return Object.prototype.toString.call(payload).slice(8, -1);\n}\n","import { getType } from './getType.js';\n/** Returns whether the payload is an array */\nexport function isArray(payload) {\n return getType(payload) === 'Array';\n}\n","import { isArray, isPlainObject } from 'is-what';\nfunction assignProp(carry, key, newVal, originalObject, includeNonenumerable) {\n const propType = {}.propertyIsEnumerable.call(originalObject, key)\n ? 'enumerable'\n : 'nonenumerable';\n if (propType === 'enumerable')\n carry[key] = newVal;\n if (includeNonenumerable && propType === 'nonenumerable') {\n Object.defineProperty(carry, key, {\n value: newVal,\n enumerable: false,\n writable: true,\n configurable: true,\n });\n }\n}\n/**\n * Copy (clone) an object and all its props recursively to get rid of any prop referenced of the\n * original object. Arrays are also cloned, however objects inside arrays are still linked.\n *\n * @param target Target can be anything\n * @param [options={}] See type {@link Options} for more details.\n *\n * - `{ props: ['key1'] }` will only copy the `key1` property. When using this you will need to cast\n * the return type manually (in order to keep the TS implementation in here simple I didn't\n * built a complex auto resolved type for those few cases people want to use this option)\n * - `{ nonenumerable: true }` will copy all non-enumerable properties. Default is `{}`\n *\n * @returns The target with replaced values\n */\nexport function copy(target, options = {}) {\n if (isArray(target)) {\n return target.map((item) => copy(item, options));\n }\n if (!isPlainObject(target)) {\n return target;\n }\n const props = Object.getOwnPropertyNames(target);\n const symbols = Object.getOwnPropertySymbols(target);\n return [...props, ...symbols].reduce((carry, key) => {\n // Skip __proto__ properties to prevent prototype pollution\n if (key === '__proto__')\n return carry;\n if (isArray(options.props) && !options.props.includes(key)) {\n return carry;\n }\n const val = target[key];\n const newVal = copy(val, options);\n assignProp(carry, key, newVal, target, options.nonenumerable);\n return carry;\n }, {});\n}\n","import { getType } from './getType.js';\n/**\n * Returns whether the payload is a plain JavaScript object (excluding special classes or objects\n * with other prototypes)\n */\nexport function isPlainObject(payload) {\n if (getType(payload) !== 'Object')\n return false;\n const prototype = Object.getPrototypeOf(payload);\n return !!prototype && prototype.constructor === Object && prototype === Object.prototype;\n}\n","import { ClassRegistry } from './class-registry.js';\nimport { Registry } from './registry.js';\nimport { CustomTransformerRegistry, } from './custom-transformer-registry.js';\nimport { applyReferentialEqualityAnnotations, applyValueAnnotations, generateReferentialEqualityAnnotations, walker, } from './plainer.js';\nimport { copy } from 'copy-anything';\nclass SuperJSON {\n /**\n * @param dedupeReferentialEqualities If true, SuperJSON will make sure only one instance of referentially equal objects are serialized and the rest are replaced with `null`.\n */\n constructor({ dedupe = false, } = {}) {\n this.classRegistry = new ClassRegistry();\n this.symbolRegistry = new Registry(s => s.description ?? '');\n this.customTransformerRegistry = new CustomTransformerRegistry();\n this.allowedErrorProps = [];\n this.dedupe = dedupe;\n }\n serialize(object) {\n const identities = new Map();\n const output = walker(object, identities, this, this.dedupe);\n const res = {\n json: output.transformedValue,\n };\n if (output.annotations) {\n res.meta = {\n ...res.meta,\n values: output.annotations,\n };\n }\n const equalityAnnotations = generateReferentialEqualityAnnotations(identities, this.dedupe);\n if (equalityAnnotations) {\n res.meta = {\n ...res.meta,\n referentialEqualities: equalityAnnotations,\n };\n }\n if (res.meta)\n res.meta.v = 1;\n return res;\n }\n deserialize(payload, options) {\n const { json, meta } = payload;\n let result = options?.inPlace ? json : copy(json);\n if (meta?.values) {\n result = applyValueAnnotations(result, meta.values, meta.v ?? 0, this);\n }\n if (meta?.referentialEqualities) {\n result = applyReferentialEqualityAnnotations(result, meta.referentialEqualities, meta.v ?? 0);\n }\n return result;\n }\n stringify(object) {\n return JSON.stringify(this.serialize(object));\n }\n parse(string) {\n return this.deserialize(JSON.parse(string), { inPlace: true });\n }\n registerClass(v, options) {\n this.classRegistry.register(v, options);\n }\n registerSymbol(v, identifier) {\n this.symbolRegistry.register(v, identifier);\n }\n registerCustom(transformer, name) {\n this.customTransformerRegistry.register({\n name,\n ...transformer,\n });\n }\n allowErrorProps(...props) {\n this.allowedErrorProps.push(...props);\n }\n}\nSuperJSON.defaultInstance = new SuperJSON();\nSuperJSON.serialize = SuperJSON.defaultInstance.serialize.bind(SuperJSON.defaultInstance);\nSuperJSON.deserialize = SuperJSON.defaultInstance.deserialize.bind(SuperJSON.defaultInstance);\nSuperJSON.stringify = SuperJSON.defaultInstance.stringify.bind(SuperJSON.defaultInstance);\nSuperJSON.parse = SuperJSON.defaultInstance.parse.bind(SuperJSON.defaultInstance);\nSuperJSON.registerClass = SuperJSON.defaultInstance.registerClass.bind(SuperJSON.defaultInstance);\nSuperJSON.registerSymbol = SuperJSON.defaultInstance.registerSymbol.bind(SuperJSON.defaultInstance);\nSuperJSON.registerCustom = SuperJSON.defaultInstance.registerCustom.bind(SuperJSON.defaultInstance);\nSuperJSON.allowErrorProps = SuperJSON.defaultInstance.allowErrorProps.bind(SuperJSON.defaultInstance);\nexport default SuperJSON;\nexport { SuperJSON };\nexport const serialize = SuperJSON.serialize;\nexport const deserialize = SuperJSON.deserialize;\nexport const stringify = SuperJSON.stringify;\nexport const parse = SuperJSON.parse;\nexport const registerClass = SuperJSON.registerClass;\nexport const registerCustom = SuperJSON.registerCustom;\nexport const registerSymbol = SuperJSON.registerSymbol;\nexport const allowErrorProps = SuperJSON.allowErrorProps;\n//# sourceMappingURL=index.js.map","import { delay } from '@lowerdeck/delay';\nimport { memo } from '@lowerdeck/memo';\nimport { parseRedisUrl } from '@lowerdeck/redis';\nimport {\n DeduplicationOptions,\n JobsOptions,\n Queue,\n QueueEvents,\n QueueOptions,\n Worker,\n WorkerOptions\n} from 'bullmq';\nimport { QueueRetryError } from '../lib/queueRetryError';\nimport { IQueue } from '../types';\n\n// @ts-ignore\nimport SuperJson from 'superjson';\n\nlet log = (...any: any[]) => console.log('[QUEUE MANAGER]:', ...any);\n\nlet anyQueueStartedRef = { started: false };\n\nexport interface BullMqQueueOptions {\n delay?: number;\n id?: string;\n deduplication?: DeduplicationOptions;\n}\n\nexport interface BullMqCreateOptions {\n name: string;\n jobOpts?: JobsOptions;\n queueOpts?: Omit<QueueOptions, 'connection'>;\n workerOpts?: Omit<WorkerOptions, 'connection'>;\n redisUrl: string;\n}\n\nexport let createBullMqQueue = <JobData>(\n opts: BullMqCreateOptions\n): IQueue<JobData, BullMqQueueOptions> => {\n let redisOpts = parseRedisUrl(opts.redisUrl);\n\n let queue = new Queue<JobData>(opts.name, {\n ...opts.queueOpts,\n connection: redisOpts,\n defaultJobOptions: {\n removeOnComplete: true,\n removeOnFail: true,\n attempts: 10,\n keepLogs: 10,\n ...opts.jobOpts\n }\n });\n\n let useQueueEvents = memo(() => new QueueEvents(opts.name, { connection: redisOpts }));\n\n return {\n name: opts.name,\n\n add: async (payload, opts) => {\n let job = await queue.add(\n 'j' as any,\n {\n payload: SuperJson.serialize(payload)\n } as any,\n {\n delay: opts?.delay,\n jobId: opts?.id,\n deduplication: opts?.deduplication\n }\n );\n\n return {\n async waitUntilFinished(opts?: { timeout?: number }) {\n let events = useQueueEvents();\n await job.waitUntilFinished(events, opts?.timeout);\n }\n };\n },\n\n addMany: async (payloads, opts) => {\n await queue.addBulk(\n payloads.map(\n payload =>\n ({\n name: 'j',\n data: {\n payload: SuperJson.serialize(payload)\n },\n opts: {\n delay: opts?.delay,\n jobId: opts?.id,\n deduplication: opts?.deduplication\n }\n }) as any\n )\n );\n },\n\n addManyWithOps: async payloads => {\n await queue.addBulk(\n payloads.map(\n payload =>\n ({\n name: 'j',\n data: {\n payload: SuperJson.serialize(payload.data)\n },\n opts: {\n delay: payload.opts?.delay,\n jobId: payload.opts?.id,\n deduplication: payload.opts?.deduplication\n }\n }) as any\n )\n );\n },\n\n process: cb => {\n let staredRef = { started: false };\n\n setTimeout(() => {\n if (anyQueueStartedRef.started && !staredRef.started) {\n log(`Queue ${opts.name} was not started within 10 seconds, this is likely a bug`);\n }\n }, 10000);\n\n return {\n start: async () => {\n log(`Starting queue ${opts.name} using bullmq`);\n staredRef.started = true;\n anyQueueStartedRef.started = true;\n\n let worker = new Worker<JobData>(\n opts.name,\n async job => {\n try {\n let data = job.data as any;\n\n let payload: any;\n\n try {\n payload = SuperJson.deserialize(data.payload);\n } catch (e: any) {\n payload = data.payload;\n }\n\n await cb(payload as any, job);\n } catch (e: any) {\n if (e instanceof QueueRetryError) {\n await delay(1000);\n throw e;\n } else {\n console.error(`[QUEUE ERROR - ${opts.name}]`, e);\n throw e;\n }\n }\n },\n {\n concurrency: 50,\n ...opts.workerOpts,\n connection: redisOpts\n }\n );\n\n return {\n close: () => worker.close()\n };\n }\n };\n }\n };\n};\n","import { BullMqCreateOptions, createBullMqQueue } from './drivers/bullmq';\nimport { IQueueProcessor } from './types';\n\nexport * from './lib/queueRetryError';\nexport * from './types';\n\nlet seenNames = new Set<string>();\n\nexport let createQueue = <JobData>(opts: { driver?: 'bullmq' } & BullMqCreateOptions) => {\n if (!opts.driver) opts.driver = 'bullmq';\n\n if (seenNames.has(opts.name)) {\n throw new Error(`Queue with name ${opts.name} already exists`);\n }\n seenNames.add(opts.name);\n\n if (opts.driver === 'bullmq') {\n return createBullMqQueue<JobData>({\n name: opts.name,\n jobOpts: opts.jobOpts,\n queueOpts: opts.queueOpts,\n workerOpts: opts.workerOpts,\n redisUrl: opts.redisUrl\n });\n }\n\n throw new Error(`Unknown queue driver: ${opts.driver}`);\n};\n\nexport let combineQueueProcessors = (opts: IQueueProcessor[]): IQueueProcessor => {\n return {\n start: async () => {\n let processors = await Promise.all(opts.map(x => x.start()));\n\n return {\n close: async () => {\n await Promise.all(processors.map(x => x?.close?.()));\n }\n };\n }\n };\n};\n\nexport let runQueueProcessors = async (processor: IQueueProcessor[]) => {\n let combined = combineQueueProcessors(processor);\n\n let res = await combined.start();\n\n process.on('SIGINT', async () => {\n await res?.close();\n });\n\n process.on('SIGTERM', async () => {\n await res?.close();\n });\n\n return res;\n};\n","var r=function(r){var n=[];return function(){var t=[].slice.call(arguments),u=n.find(function(r){return r.args.every(function(r,n){return r===t[n]})});if(u)return u.result;var e=r.apply(void 0,t);return n.push({args:t,result:e}),e}};export{r as memo};\n//# sourceMappingURL=index.module.js.map\n"],"names":["QueueRetryError","_Error","call","this","_wrapNativeSuper","Error","DoubleIndexedKV","constructor","keyToValue","Map","valueToKey","set","key","value","getByKey","get","getByValue","clear","Registry","generateIdentifier","kv","register","identifier","getIdentifier","getValue","ClassRegistry","super","c","name","classToAllowedProps","options","allowProps","getAllowedProps","forEach","record","run","Object","entries","includes","arr","indexOf","findArr","predicate","i","length","CustomTransformerRegistry","transfomers","transformer","findApplicable","v","values","hasOwnProperty","push","valuesOfObj","find","valuesNotNever","isApplicable","findByName","isUndefined","payload","isPlainObject","prototype","getPrototypeOf","isEmptyObject","keys","isArray","Array","isMap","isSet","Set","isSymbol","toString","slice","getType","isError","isNaNValue","isNaN","escapeKey","replace","stringifyPath","path","map","String","join","parsePath","string","legacyPaths","result","segment","char","charAt","escaped","simpleTransformation","annotation","transform","untransform","simpleRules","BigInt","console","error","Date","valueOf","toISOString","superJson","baseError","message","cause","allowedErrorProps","prop","e","stack","RegExp","regex","body","lastIndexOf","flags","Infinity","Number","URL","compositeTransformation","symbolRule","s","symbolRegistry","description","_","a","constructorToName","Int8Array","Uint8Array","Int16Array","Uint16Array","Int32Array","Uint32Array","Float32Array","Float64Array","Uint8ClampedArray","reduce","obj","ctor","typedArrayRule","ArrayBuffer","isView","DataView","isInstanceOfRegisteredClass","potentialClass","classRegistry","classRule","clazz","allowedProps","assign","create","customRule","customTransformerRegistry","serialize","deserialize","compositeRules","transformValue","applicableCompositeRule","rule","type","applicableSimpleRule","simpleRulesByAnnotation","getNthKey","n","size","next","validatePath","setDeep","object","mapper","parent","keyOfRow","lastKey","oldValue","newValue","delete","add","keyToRow","newKey","enableLegacyPaths","version","traverse","tree","walker","origin","subtree","nodeValue","children","child","applyValueAnnotations","plain","annotations","json","transformation","untransformValue","identities","dedupe","objectsInThisPath","seenObjects","primitive","isBoolean","isNull","isNumber","isString","existingSet","addIdentity","seen","transformedValue","isDeep","transformed","transformationResult","innerAnnotations","index","recursiveResult","undefined","copy","target","item","getOwnPropertyNames","getOwnPropertySymbols","carry","props","newVal","originalObject","includeNonenumerable","propType","propertyIsEnumerable","defineProperty","enumerable","writable","configurable","assignProp","nonenumerable","SuperJSON","output","res","meta","equalityAnnotations","identitites","rootEqualityPaths","paths","sort","b","representativePath","identicalPaths","generateReferentialEqualityAnnotations","referentialEqualities","inPlace","apply","getDeep","identicalObjectPath","root","other","identicalPath","applyReferentialEqualityAnnotations","stringify","JSON","parse","registerClass","registerSymbol","registerCustom","allowErrorProps","defaultInstance","bind","log","_console","concat","arguments","anyQueueStartedRef","started","seenNames","combineQueueProcessors","opts","start","Promise","resolve","all","x","then","processors","close","reject","driver","has","r","redisOpts","parseRedisUrl","redisUrl","queue","Queue","_extends","queueOpts","connection","defaultJobOptions","removeOnComplete","removeOnFail","attempts","keepLogs","jobOpts","useQueueEvents","QueueEvents","t","u","args","every","SuperJson","delay","jobId","id","deduplication","job","waitUntilFinished","events","timeout","addMany","payloads","addBulk","data","addManyWithOps","_payload$opts","_payload$opts2","_payload$opts3","process","cb","staredRef","setTimeout","worker","Worker","_catch","concurrency","workerOpts","createBullMqQueue","processor","combined","on"],"mappings":"8mDAAW,ICAEA,eAAgBC,SAAAA,GAC3B,SAAAD,IACE,OAAAC,EAAAC,KAAAC,KAAM,UACRA,IAAA,SAAC,SAAAF,KAAAD,yEAAAA,CAAA,CAH0BC,cAG1BG,EAHkCC,QCA9B,MAAMC,EACT,WAAAC,GACIJ,KAAKK,WAAa,IAAIC,IACtBN,KAAKO,WAAa,IAAID,GACzB,CACD,GAAAE,CAAIC,EAAKC,GACLV,KAAKK,WAAWG,IAAIC,EAAKC,GACzBV,KAAKO,WAAWC,IAAIE,EAAOD,EAC9B,CACD,QAAAE,CAASF,GACL,OAAOT,KAAKK,WAAWO,IAAIH,EAC9B,CACD,UAAAI,CAAWH,GACP,OAAOV,KAAKO,WAAWK,IAAIF,EAC9B,CACD,KAAAI,GACId,KAAKK,WAAWS,QAChBd,KAAKO,WAAWO,OACnB,ECjBE,MAAMC,EACT,WAAAX,CAAYY,GACRhB,KAAKgB,mBAAqBA,EAC1BhB,KAAKiB,GAAK,IAAId,CACjB,CACD,QAAAe,CAASR,EAAOS,GACRnB,KAAKiB,GAAGJ,WAAWH,KAGlBS,IACDA,EAAanB,KAAKgB,mBAAmBN,IAEzCV,KAAKiB,GAAGT,IAAIW,EAAYT,GAC3B,CACD,KAAAI,GACId,KAAKiB,GAAGH,OACX,CACD,aAAAM,CAAcV,GACV,OAAOV,KAAKiB,GAAGJ,WAAWH,EAC7B,CACD,QAAAW,CAASF,GACL,OAAOnB,KAAKiB,GAAGN,SAASQ,EAC3B,ECtBE,MAAMG,UAAsBP,EAC/B,WAAAX,GACImB,MAAMC,GAAKA,EAAEC,MACbzB,KAAK0B,oBAAsB,IAAIpB,G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AS1B,EAAK0B,QACdP,UAAWnB,EAAKmB,UAChBuC,WAAY1D,EAAK0D,WACjB3C,SAAUf,EAAKe,WAInB,MAAU,IAAA1R,MAA+B2Q,yBAAAA,EAAKU,OAChD,uBAgBW,SAA4BkD,OACrC,IAAIC,EAAW9D,GAAuB6D,GAAW,OAAA1D,QAAAC,QAEjC0D,EAAS5D,SAAOK,cAA5B3C,GAUJ,OARAuF,QAAQY,GAAG,wBAAqB5D,OAAAA,QAAAC,QACrB,MAAHxC,OAAG,EAAHA,EAAK6C,SAAOF,KACpB,WAAA,EAAA,CAAC,MAAAzK,UAAAqK,QAAAO,OAAA5K,MAEDqN,QAAQY,GAAG,UAAS,WAAA,WAAa5D,QAAAC,QACzBxC,MAAAA,OAAAA,EAAAA,EAAK6C,SAAOF,kBACpB,CAAC,MAAAzK,GAAA,OAAAqK,QAAAO,OAAA5K,EAAA,CAAA,GAEM8H,CAAI,EACb,CAAC,MAAA9H,GAAA,OAAAqK,QAAAO,OAAA5K,EAAA,CAAA"}
1
+ {"version":3,"file":"index.umd.js","sources":["../../error/dist/index.module.js","../../../node_modules/base-x/src/esm/index.js","../../base62/dist/index.module.js","../../../node_modules/nanoid/index.browser.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/rng.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/regex.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/validate.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/stringify.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/v1.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/parse.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/v35.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/md5.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/v3.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/native.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/v4.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/sha1.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/v5.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/nil.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/version.js","../../../node_modules/short-uuid/node_modules/uuid/dist/commonjs-browser/index.js","../../../node_modules/any-base/src/converter.js","../../../node_modules/any-base/index.js","../../../node_modules/short-uuid/index.js","../../../node_modules/snowflake-uuid/dist/index.js","../../id/dist/index.module.js","../../../node_modules/@sentry/core/build/esm/debug-build.js","../../../node_modules/@sentry/core/build/esm/utils/worldwide.js","../../../node_modules/@sentry/core/build/esm/utils/version.js","../../../node_modules/@sentry/core/build/esm/carrier.js","../../../node_modules/@sentry/core/build/esm/utils/debug-logger.js","../../../node_modules/@sentry/core/build/esm/utils/stacktrace.js","../../../node_modules/@sentry/core/build/esm/instrument/handlers.js","../../../node_modules/@sentry/core/build/esm/instrument/globalError.js","../../../node_modules/@sentry/core/build/esm/instrument/globalUnhandledRejection.js","../../../node_modules/@sentry/core/build/esm/utils/is.js","../../../node_modules/@sentry/core/build/esm/utils/browser.js","../../../node_modules/@sentry/core/build/esm/utils/object.js","../../../node_modules/@sentry/core/build/esm/utils/string.js","../../../node_modules/@sentry/core/build/esm/utils/misc.js","../../../node_modules/@sentry/core/build/esm/utils/time.js","../../../node_modules/@sentry/core/build/esm/session.js","../../../node_modules/@sentry/core/build/esm/utils/merge.js","../../../node_modules/@sentry/core/build/esm/utils/propagationContext.js","../../../node_modules/@sentry/core/build/esm/utils/spanOnScope.js","../../../node_modules/@sentry/core/build/esm/scope.js","../../../node_modules/@sentry/core/build/esm/defaultScopes.js","../../../node_modules/@sentry/core/build/esm/asyncContext/stackStrategy.js","../../../node_modules/@sentry/core/build/esm/asyncContext/index.js","../../../node_modules/@sentry/core/build/esm/currentScopes.js","../../../node_modules/@sentry/core/build/esm/semanticAttributes.js","../../../node_modules/@sentry/core/build/esm/tracing/spanstatus.js","../../../node_modules/@sentry/core/build/esm/tracing/utils.js","../../../node_modules/@sentry/core/build/esm/utils/baggage.js","../../../node_modules/@sentry/core/build/esm/utils/dsn.js","../../../node_modules/@sentry/core/build/esm/utils/parseSampleRate.js","../../../node_modules/@sentry/core/build/esm/utils/tracing.js","../../../node_modules/@sentry/core/build/esm/utils/spanUtils.js","../../../node_modules/@sentry/core/build/esm/tracing/errors.js","../../../node_modules/@sentry/core/build/esm/utils/hasSpansEnabled.js","../../../node_modules/@sentry/core/build/esm/utils/should-ignore-span.js","../../../node_modules/@sentry/core/build/esm/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/dynamicSamplingContext.js","../../../node_modules/@sentry/core/build/esm/tracing/sentryNonRecordingSpan.js","../../../node_modules/@sentry/core/build/esm/utils/normalize.js","../../../node_modules/@sentry/core/build/esm/utils/envelope.js","../../../node_modules/@sentry/core/build/esm/envelope.js","../../../node_modules/@sentry/core/build/esm/tracing/logSpans.js","../../../node_modules/@sentry/core/build/esm/tracing/measurement.js","../../../node_modules/@sentry/core/build/esm/tracing/sentrySpan.js","../../../node_modules/@sentry/core/build/esm/utils/handleCallbackErrors.js","../../../node_modules/@sentry/core/build/esm/tracing/sampling.js","../../../node_modules/@sentry/core/build/esm/tracing/trace.js","../../../node_modules/@sentry/core/build/esm/tracing/idleSpan.js","../../../node_modules/@sentry/core/build/esm/utils/syncpromise.js","../../../node_modules/@sentry/core/build/esm/eventProcessors.js","../../../node_modules/@sentry/core/build/esm/utils/applyScopeDataToEvent.js","../../../node_modules/@sentry/core/build/esm/utils/debug-ids.js","../../../node_modules/@sentry/core/build/esm/utils/prepareEvent.js","../../../node_modules/@sentry/core/build/esm/exports.js","../../../node_modules/@sentry/core/build/esm/api.js","../../../node_modules/@sentry/core/build/esm/integration.js","../../../node_modules/@sentry/core/build/esm/attributes.js","../../../node_modules/@sentry/core/build/esm/utils/trace-info.js","../../../node_modules/@sentry/core/build/esm/logs/constants.js","../../../node_modules/@sentry/core/build/esm/logs/internal.js","../../../node_modules/@sentry/core/build/esm/logs/envelope.js","../../../node_modules/@sentry/core/build/esm/metrics/internal.js","../../../node_modules/@sentry/core/build/esm/metrics/envelope.js","../../../node_modules/@sentry/core/build/esm/utils/promisebuffer.js","../../../node_modules/@sentry/core/build/esm/utils/ratelimit.js","../../../node_modules/@sentry/core/build/esm/utils/clientreport.js","../../../node_modules/@sentry/core/build/esm/utils/eventUtils.js","../../../node_modules/@sentry/core/build/esm/client.js","../../../node_modules/@sentry/core/build/esm/transports/base.js","../../../node_modules/@sentry/core/build/esm/utils/transactionEvent.js","../../../node_modules/@sentry/core/build/esm/checkin.js","../../../node_modules/@sentry/core/build/esm/utils/eventbuilder.js","../../../node_modules/@sentry/core/build/esm/server-runtime-client.js","../../../node_modules/@sentry/core/build/esm/sdk.js","../../../node_modules/@sentry/core/build/esm/transports/offline.js","../../../node_modules/@sentry/core/build/esm/transports/multiplexed.js","../../../node_modules/@sentry/core/build/esm/utils/ai/providerSkip.js","../../../node_modules/@sentry/core/build/esm/utils/url.js","../../../node_modules/@sentry/core/build/esm/utils/isSentryRequestUrl.js","../../../node_modules/@sentry/core/build/esm/utils/parameterize.js","../../../node_modules/@sentry/core/build/esm/utils/traceData.js","../../../node_modules/@sentry/core/build/esm/utils/request.js","../../../node_modules/@sentry/core/build/esm/breadcrumbs.js","../../../node_modules/@sentry/core/build/esm/integrations/functiontostring.js","../../../node_modules/@sentry/core/build/esm/integrations/eventFilters.js","../../../node_modules/@sentry/core/build/esm/utils/aggregate-errors.js","../../../node_modules/@sentry/core/build/esm/integrations/linkederrors.js","../../../node_modules/@sentry/core/build/esm/metadata.js","../../../node_modules/@sentry/core/build/esm/integrations/moduleMetadata.js","../../../node_modules/@sentry/core/build/esm/vendor/getIpAddress.js","../../../node_modules/@sentry/core/build/esm/integrations/requestdata.js","../../../node_modules/@sentry/core/build/esm/utils/cookie.js","../../../node_modules/@sentry/core/build/esm/instrument/console.js","../../../node_modules/@sentry/core/build/esm/utils/severity.js","../../../node_modules/@sentry/core/build/esm/integrations/dedupe.js","../../../node_modules/@sentry/core/build/esm/integrations/extraerrordata.js","../../../node_modules/@sentry/core/build/esm/utils/path.js","../../../node_modules/@sentry/core/build/esm/integrations/rewriteframes.js","../../../node_modules/@sentry/core/build/esm/integrations/supabase.js","../../../node_modules/@sentry/core/build/esm/integrations/zoderrors.js","../../../node_modules/@sentry/core/build/esm/integrations/console.js","../../../node_modules/@sentry/core/build/esm/utils/featureFlags.js","../../../node_modules/@sentry/core/build/esm/integrations/featureFlags/growthbook.js","../../../node_modules/@sentry/core/build/esm/profiling.js","../../../node_modules/@sentry/core/build/esm/fetch.js","../../../node_modules/@sentry/core/build/esm/trpc.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/errorCapture.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/handlers.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/attributes.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/piiFiltering.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/validation.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/sessionManagement.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/sessionExtraction.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/correlation.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/methodConfig.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/attributeExtraction.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/spans.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/index.js","../../../node_modules/@sentry/core/build/esm/logs/public-api.js","../../../node_modules/@sentry/core/build/esm/logs/utils.js","../../../node_modules/@sentry/core/build/esm/logs/console-integration.js","../../../node_modules/@sentry/core/build/esm/metrics/public-api.js","../../../node_modules/@sentry/core/build/esm/integrations/consola.js","../../../node_modules/@sentry/core/build/esm/tracing/ai/gen-ai-attributes.js","../../../node_modules/@sentry/core/build/esm/tracing/vercel-ai/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/ai/messageTruncation.js","../../../node_modules/@sentry/core/build/esm/tracing/ai/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/vercel-ai/vercel-ai-attributes.js","../../../node_modules/@sentry/core/build/esm/tracing/vercel-ai/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/vercel-ai/index.js","../../../node_modules/@sentry/core/build/esm/tracing/openai/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/openai/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/openai/streaming.js","../../../node_modules/@sentry/core/build/esm/tracing/openai/index.js","../../../node_modules/@sentry/core/build/esm/tracing/anthropic-ai/streaming.js","../../../node_modules/@sentry/core/build/esm/tracing/anthropic-ai/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/anthropic-ai/index.js","../../../node_modules/@sentry/core/build/esm/tracing/anthropic-ai/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/google-genai/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/google-genai/streaming.js","../../../node_modules/@sentry/core/build/esm/tracing/google-genai/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/google-genai/index.js","../../../node_modules/@sentry/core/build/esm/tracing/langchain/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/langchain/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/langgraph/constants.js","../../../node_modules/@sentry/core/build/esm/tracing/langgraph/utils.js","../../../node_modules/@sentry/core/build/esm/tracing/langgraph/index.js","../../../node_modules/@sentry/core/build/esm/utils/error.js","../../../node_modules/@sentry/core/build/esm/utils/supports.js","../../../node_modules/@sentry/core/build/esm/instrument/fetch.js","../../../node_modules/@sentry/core/build/esm/utils/env.js","../../../node_modules/@sentry/core/build/esm/utils/node.js","../../../node_modules/@sentry/core/build/esm/utils/node-stack-trace.js","../../../node_modules/@sentry/core/build/esm/utils/vercelWaitUntil.js","../../../node_modules/@sentry/core/build/esm/utils/flushIfServerless.js","../../../node_modules/@sentry/core/build/esm/transports/userAgent.js","../../../node_modules/@sentry/core/build/esm/utils/ipAddress.js","../../../node_modules/@sentry/core/build/esm/utils/sdkMetadata.js","../../../node_modules/@sentry/core/build/esm/utils/meta.js","../../../node_modules/@sentry/core/build/esm/utils/debounce.js","../../../node_modules/@sentry/core/build/esm/integrations/captureconsole.js","../../../node_modules/@sentry/core/build/esm/integrations/third-party-errors-filter.js","../../../node_modules/@sentry/core/build/esm/integrations/featureFlags/featureFlagsIntegration.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/transport.js","../../../node_modules/@sentry/core/build/esm/integrations/mcp-server/resultExtraction.js","../../../node_modules/@sentry/core/build/esm/feedback.js","../../../node_modules/@sentry/core/build/esm/tracing/langchain/index.js","../../../node_modules/@sentry/core/build/esm/utils/breadcrumb-log-level.js","../../../node_modules/@sentry/core/build/esm/utils/isBrowser.js","../../../node_modules/@sentry/core/build/esm/utils/exports.js","../../../node_modules/@sentry/core/build/esm/utils/anr.js","../../../node_modules/@sentry/core/build/esm/utils/lru.js","../../../node_modules/@sentry/core/build/esm/vendor/escapeStringForRegex.js","../../sentry/dist/index.module.js","../src/lib/queueRetryError.ts","../src/drivers/bullmq.ts","../src/index.ts","../../execution-context/dist/index.module.js"],"sourcesContent":["import{Cases as e}from\"@lowerdeck/case\";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var r=arguments[t];for(var o in r)({}).hasOwnProperty.call(r,o)&&(e[o]=r[o])}return e},t.apply(null,arguments)}function r(e){return r=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(e){return e.__proto__||Object.getPrototypeOf(e)},r(e)}function o(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch(e){}return(o=function(){return!!e})()}function n(e,t){return n=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(e,t){return e.__proto__=t,e},n(e,t)}function s(e){var t=function(e){if(\"object\"!=typeof e||!e)return e;var t=e[Symbol.toPrimitive];if(void 0!==t){var r=t.call(e,\"string\");if(\"object\"!=typeof r)return r;throw new TypeError(\"@@toPrimitive must return a primitive value.\")}return String(e)}(e);return\"symbol\"==typeof t?t:t+\"\"}function a(e){var t=\"function\"==typeof Map?new Map:void 0;return a=function(e){if(null===e||!function(e){try{return-1!==Function.toString.call(e).indexOf(\"[native code]\")}catch(t){return\"function\"==typeof e}}(e))return e;if(\"function\"!=typeof e)throw new TypeError(\"Super expression must either be null or a function\");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,s)}function s(){return function(e,t,r){if(o())return Reflect.construct.apply(null,arguments);var s=[null];s.push.apply(s,t);var a=new(e.bind.apply(e,s));return r&&n(a,r.prototype),a}(e,arguments,r(this).constructor)}return s.prototype=Object.create(e.prototype,{constructor:{value:s,enumerable:!1,writable:!0,configurable:!0}}),n(s,e)},a(e)}var i=function(e){return Object.assign(function(r){return void 0===r&&(r={}),i(t({},e,r))},{__typename:\"error\",data:e,toResponse:function(){return t({__typename:\"error\",ok:!1},e)}})},u=/*#__PURE__*/function(e){function t(t){var r;return(r=e.call(this,t.data.message)||this).error=void 0,r.__typename=\"ServiceError\",r._parent=null,r.error=t,r}var r,o;o=e,(r=t).prototype=Object.create(o.prototype),r.prototype.constructor=r,n(r,o);var a,u,c=t.prototype;return c.setParent=function(e){return this._parent=e,this},c.toResponse=function(){return this.error.toResponse()},t.fromResponse=function(e){var r=e;return delete r.ok,delete r.__typename,new t(i(r))},a=t,(u=[{key:\"parent\",get:function(){return this._parent}},{key:\"data\",get:function(){return this.error.data}}])&&function(e,t){for(var r=0;r<t.length;r++){var o=t[r];o.enumerable=o.enumerable||!1,o.configurable=!0,\"value\"in o&&(o.writable=!0),Object.defineProperty(e,s(o.key),o)}}(a.prototype,u),Object.defineProperty(a,\"prototype\",{writable:!1}),a}(/*#__PURE__*/a(Error)),c=function(e){return\"ServiceError\"===(null==e?void 0:e.__typename)||\"ErrorRecord\"===(null==e?void 0:e.__typename)},d=function(e){return i(t({status:400,code:\"invalid_data\",message:\"The provided data is invalid.\",hint:\"Make sure the data you are sending follows the specification outlined in the documentation.\"},e))},p=i({status:500,code:\"internal_server_error\",message:\"An internal server error occurred.\"}),l=i({status:400,code:\"bad_request\",message:\"The request is invalid.\"});function f(r,o){var n=\"string\"==typeof r?r:r.entity,s=\"string\"==typeof r?o:r.id;return i(t({status:404,code:\"not_found\",message:\"The requested \"+e.toKebabCase(n)+\" could not be found.\",hint:\"Make sure the resource you are trying to access exists, that you have access to it and that it has not been deleted.\",entity:n,id:null!=s?s:void 0},\"string\"==typeof r?{}:r))}var y=i({status:401,code:\"unauthorized\",message:\"You are not authorized to access this resource.\",hint:\"Make sure you are logged in and have the correct permissions to access this resource.\"}),h=i({status:403,code:\"forbidden\",message:\"You do not have permission to access this resource.\"}),m=i({status:400,code:\"invalid_version\",message:\"The endpoint does not support the requested version.\"}),v=i({status:409,code:\"conflict\",message:\"A similar resource already exists.\"}),g=i({status:410,code:\"gone\",message:\"The requested resource is no longer available.\"}),b=i({status:402,code:\"payment_required\",message:\"Payment is required to access this resource.\"}),_=i({status:412,code:\"precondition_failed\",message:\"The precondition of the request failed.\"}),O=i({status:406,code:\"not_acceptable\",message:\"The requested resource is not acceptable.\"}),w=i({status:501,code:\"not_implemented\",message:\"The requested resource is not implemented.\"}),j=i({status:429,code:\"too_many_requests\",message:\"You have made too many requests in a short period of time.\",hint:\"Please wait a moment and try again.\"}),q=i({status:504,code:\"timeout\",message:\"The request timed out.\"}),P=i({status:405,code:\"method_not_allowed\",message:\"The requested method is not allowed for this resource.\"});export{u as ServiceError,l as badRequestError,v as conflictError,i as createError,h as forbiddenError,g as goneError,p as internalServerError,m as invalidVersion,c as isServiceError,P as methodNotAllowedError,O as notAcceptableError,f as notFoundError,w as notImplementedError,b as paymentRequiredError,_ as preconditionFailedError,q as timeoutError,j as tooManyRequestsError,y as unauthorizedError,d as validationError};\n//# sourceMappingURL=index.module.js.map\n","// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n const BASE_MAP = new Uint8Array(256)\n for (let j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (let i = 0; i < ALPHABET.length; i++) {\n const x = ALPHABET.charAt(i)\n const xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n const BASE = ALPHABET.length\n const LEADER = ALPHABET.charAt(0)\n const FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n const iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n // eslint-disable-next-line no-empty\n if (source instanceof Uint8Array) { } else if (ArrayBuffer.isView(source)) {\n source = new Uint8Array(source.buffer, source.byteOffset, source.byteLength)\n } else if (Array.isArray(source)) {\n source = Uint8Array.from(source)\n }\n if (!(source instanceof Uint8Array)) { throw new TypeError('Expected Uint8Array') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n let zeroes = 0\n let length = 0\n let pbegin = 0\n const pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n const size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n const b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n let carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n let i = 0\n for (let it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n let it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n let str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return new Uint8Array() }\n let psz = 0\n // Skip and count leading '1's.\n let zeroes = 0\n let length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n const size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n const b256 = new Uint8Array(size)\n // Process the characters.\n while (psz < source.length) {\n // Find code of next character\n const charCode = source.charCodeAt(psz)\n // Base map can not be indexed using char code\n if (charCode > 255) { return }\n // Decode character\n let carry = BASE_MAP[charCode]\n // Invalid character\n if (carry === 255) { return }\n let i = 0\n for (let it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip leading zeroes in b256.\n let it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n const vch = new Uint8Array(zeroes + (size - it4))\n let j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n const buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode,\n decodeUnsafe,\n decode\n }\n}\nexport default base\n","import e from\"base-x\";var o=e(\"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"),n={encode:function(e){return o.encode(\"string\"==typeof e?(new TextEncoder).encode(e):e)},decode:function(e){return(new TextDecoder).decode(o.decode(e))},decodeRaw:function(e){return o.decode(e)}};export{n as base62};\n//# sourceMappingURL=index.module.js.map\n","/* @ts-self-types=\"./index.d.ts\" */\nimport { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'\nexport { urlAlphabet } from './url-alphabet/index.js'\nexport let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))\nexport let customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << Math.log2(alphabet.length - 1)) - 1\n let step = -~((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let j = step | 0\n while (j--) {\n id += alphabet[bytes[j] & mask] || ''\n if (id.length >= size) return id\n }\n }\n }\n}\nexport let customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size | 0, random)\nexport let nanoid = (size = 21) => {\n let id = ''\n let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))\n while (size--) {\n id += scopedUrlAlphabet[bytes[size] & 63]\n }\n return id\n}\n","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = rng;\n// Unique ID creation requires a high quality random # generator. In the browser we therefore\n// require the crypto API and do not support built-in fallback to lower quality random number\n// generators (like Math.random()).\nlet getRandomValues;\nconst rnds8 = new Uint8Array(16);\n\nfunction rng() {\n // lazy load so that environments that need to polyfill have a chance to do so\n if (!getRandomValues) {\n // getRandomValues needs to be invoked in a context where \"this\" is a Crypto implementation.\n getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);\n\n if (!getRandomValues) {\n throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');\n }\n }\n\n return getRandomValues(rnds8);\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _regex = _interopRequireDefault(require(\"./regex.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction validate(uuid) {\n return typeof uuid === 'string' && _regex.default.test(uuid);\n}\n\nvar _default = validate;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nexports.unsafeStringify = unsafeStringify;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\n\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\n\nfunction unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n return byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]];\n}\n\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset); // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n\n return uuid;\n}\n\nvar _default = stringify;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\n// **`v1()` - Generate time-based UUID**\n//\n// Inspired by https://github.com/LiosK/UUID.js\n// and http://docs.python.org/library/uuid.html\nlet _nodeId;\n\nlet _clockseq; // Previous uuid creation time\n\n\nlet _lastMSecs = 0;\nlet _lastNSecs = 0; // See https://github.com/uuidjs/uuid for API details\n\nfunction v1(options, buf, offset) {\n let i = buf && offset || 0;\n const b = buf || new Array(16);\n options = options || {};\n let node = options.node || _nodeId;\n let clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; // node and clockseq need to be initialized to random values if they're not\n // specified. We do this lazily to minimize issues related to insufficient\n // system entropy. See #189\n\n if (node == null || clockseq == null) {\n const seedBytes = options.random || (options.rng || _rng.default)();\n\n if (node == null) {\n // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)\n node = _nodeId = [seedBytes[0] | 0x01, seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]];\n }\n\n if (clockseq == null) {\n // Per 4.2.2, randomize (14 bit) clockseq\n clockseq = _clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff;\n }\n } // UUID timestamps are 100 nano-second units since the Gregorian epoch,\n // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so\n // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'\n // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.\n\n\n let msecs = options.msecs !== undefined ? options.msecs : Date.now(); // Per 4.2.1.2, use count of uuid's generated during the current clock\n // cycle to simulate higher resolution clock\n\n let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; // Time since last uuid creation (in msecs)\n\n const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; // Per 4.2.1.2, Bump clockseq on clock regression\n\n if (dt < 0 && options.clockseq === undefined) {\n clockseq = clockseq + 1 & 0x3fff;\n } // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new\n // time interval\n\n\n if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {\n nsecs = 0;\n } // Per 4.2.1.2 Throw error if too many uuids are requested\n\n\n if (nsecs >= 10000) {\n throw new Error(\"uuid.v1(): Can't create more than 10M uuids/sec\");\n }\n\n _lastMSecs = msecs;\n _lastNSecs = nsecs;\n _clockseq = clockseq; // Per 4.1.4 - Convert from unix epoch to Gregorian epoch\n\n msecs += 12219292800000; // `time_low`\n\n const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;\n b[i++] = tl >>> 24 & 0xff;\n b[i++] = tl >>> 16 & 0xff;\n b[i++] = tl >>> 8 & 0xff;\n b[i++] = tl & 0xff; // `time_mid`\n\n const tmh = msecs / 0x100000000 * 10000 & 0xfffffff;\n b[i++] = tmh >>> 8 & 0xff;\n b[i++] = tmh & 0xff; // `time_high_and_version`\n\n b[i++] = tmh >>> 24 & 0xf | 0x10; // include version\n\n b[i++] = tmh >>> 16 & 0xff; // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)\n\n b[i++] = clockseq >>> 8 | 0x80; // `clock_seq_low`\n\n b[i++] = clockseq & 0xff; // `node`\n\n for (let n = 0; n < 6; ++n) {\n b[i + n] = node[n];\n }\n\n return buf || (0, _stringify.unsafeStringify)(b);\n}\n\nvar _default = v1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction parse(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n let v;\n const arr = new Uint8Array(16); // Parse ########-....-....-....-............\n\n arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;\n arr[1] = v >>> 16 & 0xff;\n arr[2] = v >>> 8 & 0xff;\n arr[3] = v & 0xff; // Parse ........-####-....-....-............\n\n arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;\n arr[5] = v & 0xff; // Parse ........-....-####-....-............\n\n arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;\n arr[7] = v & 0xff; // Parse ........-....-....-####-............\n\n arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;\n arr[9] = v & 0xff; // Parse ........-....-....-....-############\n // (Use \"/\" to avoid 32-bit truncation when bit-shifting high-order bytes)\n\n arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;\n arr[11] = v / 0x100000000 & 0xff;\n arr[12] = v >>> 24 & 0xff;\n arr[13] = v >>> 16 & 0xff;\n arr[14] = v >>> 8 & 0xff;\n arr[15] = v & 0xff;\n return arr;\n}\n\nvar _default = parse;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.URL = exports.DNS = void 0;\nexports.default = v35;\n\nvar _stringify = require(\"./stringify.js\");\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction stringToBytes(str) {\n str = unescape(encodeURIComponent(str)); // UTF8 escape\n\n const bytes = [];\n\n for (let i = 0; i < str.length; ++i) {\n bytes.push(str.charCodeAt(i));\n }\n\n return bytes;\n}\n\nconst DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';\nexports.DNS = DNS;\nconst URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';\nexports.URL = URL;\n\nfunction v35(name, version, hashfunc) {\n function generateUUID(value, namespace, buf, offset) {\n var _namespace;\n\n if (typeof value === 'string') {\n value = stringToBytes(value);\n }\n\n if (typeof namespace === 'string') {\n namespace = (0, _parse.default)(namespace);\n }\n\n if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {\n throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');\n } // Compute hash of namespace and value, Per 4.3\n // Future: Use spread syntax when supported on all platforms, e.g. `bytes =\n // hashfunc([...namespace, ... value])`\n\n\n let bytes = new Uint8Array(16 + value.length);\n bytes.set(namespace);\n bytes.set(value, namespace.length);\n bytes = hashfunc(bytes);\n bytes[6] = bytes[6] & 0x0f | version;\n bytes[8] = bytes[8] & 0x3f | 0x80;\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = bytes[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(bytes);\n } // Function#name is not settable on some platforms (#270)\n\n\n try {\n generateUUID.name = name; // eslint-disable-next-line no-empty\n } catch (err) {} // For CommonJS default export support\n\n\n generateUUID.DNS = DNS;\n generateUUID.URL = URL;\n return generateUUID;\n}","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n/*\n * Browser-compatible JavaScript MD5\n *\n * Modification of JavaScript MD5\n * https://github.com/blueimp/JavaScript-MD5\n *\n * Copyright 2011, Sebastian Tschan\n * https://blueimp.net\n *\n * Licensed under the MIT license:\n * https://opensource.org/licenses/MIT\n *\n * Based on\n * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message\n * Digest Algorithm, as defined in RFC 1321.\n * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009\n * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet\n * Distributed under the BSD License\n * See http://pajhome.org.uk/crypt/md5 for more info.\n */\nfunction md5(bytes) {\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = new Uint8Array(msg.length);\n\n for (let i = 0; i < msg.length; ++i) {\n bytes[i] = msg.charCodeAt(i);\n }\n }\n\n return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));\n}\n/*\n * Convert an array of little-endian words to an array of bytes\n */\n\n\nfunction md5ToHexEncodedArray(input) {\n const output = [];\n const length32 = input.length * 32;\n const hexTab = '0123456789abcdef';\n\n for (let i = 0; i < length32; i += 8) {\n const x = input[i >> 5] >>> i % 32 & 0xff;\n const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);\n output.push(hex);\n }\n\n return output;\n}\n/**\n * Calculate output length with padding and bit length\n */\n\n\nfunction getOutputLength(inputLength8) {\n return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;\n}\n/*\n * Calculate the MD5 of an array of little-endian words, and a bit length.\n */\n\n\nfunction wordsToMd5(x, len) {\n /* append padding */\n x[len >> 5] |= 0x80 << len % 32;\n x[getOutputLength(len) - 1] = len;\n let a = 1732584193;\n let b = -271733879;\n let c = -1732584194;\n let d = 271733878;\n\n for (let i = 0; i < x.length; i += 16) {\n const olda = a;\n const oldb = b;\n const oldc = c;\n const oldd = d;\n a = md5ff(a, b, c, d, x[i], 7, -680876936);\n d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);\n c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);\n b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);\n a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);\n d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);\n c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);\n b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);\n a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);\n d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);\n c = md5ff(c, d, a, b, x[i + 10], 17, -42063);\n b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);\n a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);\n d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);\n c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);\n b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);\n a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);\n d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);\n c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);\n b = md5gg(b, c, d, a, x[i], 20, -373897302);\n a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);\n d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);\n c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);\n b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);\n a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);\n d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);\n c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);\n b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);\n a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);\n d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);\n c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);\n b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);\n a = md5hh(a, b, c, d, x[i + 5], 4, -378558);\n d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);\n c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);\n b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);\n a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);\n d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);\n c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);\n b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);\n a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);\n d = md5hh(d, a, b, c, x[i], 11, -358537222);\n c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);\n b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);\n a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);\n d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);\n c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);\n b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);\n a = md5ii(a, b, c, d, x[i], 6, -198630844);\n d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);\n c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);\n b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);\n a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);\n d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);\n c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);\n b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);\n a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);\n d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);\n c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);\n b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);\n a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);\n d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);\n c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);\n b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);\n a = safeAdd(a, olda);\n b = safeAdd(b, oldb);\n c = safeAdd(c, oldc);\n d = safeAdd(d, oldd);\n }\n\n return [a, b, c, d];\n}\n/*\n * Convert an array bytes to an array of little-endian words\n * Characters >255 have their high-byte silently ignored.\n */\n\n\nfunction bytesToWords(input) {\n if (input.length === 0) {\n return [];\n }\n\n const length8 = input.length * 8;\n const output = new Uint32Array(getOutputLength(length8));\n\n for (let i = 0; i < length8; i += 8) {\n output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;\n }\n\n return output;\n}\n/*\n * Add integers, wrapping at 2^32. This uses 16-bit operations internally\n * to work around bugs in some JS interpreters.\n */\n\n\nfunction safeAdd(x, y) {\n const lsw = (x & 0xffff) + (y & 0xffff);\n const msw = (x >> 16) + (y >> 16) + (lsw >> 16);\n return msw << 16 | lsw & 0xffff;\n}\n/*\n * Bitwise rotate a 32-bit number to the left.\n */\n\n\nfunction bitRotateLeft(num, cnt) {\n return num << cnt | num >>> 32 - cnt;\n}\n/*\n * These functions implement the four basic operations the algorithm uses.\n */\n\n\nfunction md5cmn(q, a, b, x, s, t) {\n return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);\n}\n\nfunction md5ff(a, b, c, d, x, s, t) {\n return md5cmn(b & c | ~b & d, a, b, x, s, t);\n}\n\nfunction md5gg(a, b, c, d, x, s, t) {\n return md5cmn(b & d | c & ~d, a, b, x, s, t);\n}\n\nfunction md5hh(a, b, c, d, x, s, t) {\n return md5cmn(b ^ c ^ d, a, b, x, s, t);\n}\n\nfunction md5ii(a, b, c, d, x, s, t) {\n return md5cmn(c ^ (b | ~d), a, b, x, s, t);\n}\n\nvar _default = md5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _md = _interopRequireDefault(require(\"./md5.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v3 = (0, _v.default)('v3', 0x30, _md.default);\nvar _default = v3;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nconst randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);\nvar _default = {\n randomUUID\n};\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _native = _interopRequireDefault(require(\"./native.js\"));\n\nvar _rng = _interopRequireDefault(require(\"./rng.js\"));\n\nvar _stringify = require(\"./stringify.js\");\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction v4(options, buf, offset) {\n if (_native.default.randomUUID && !buf && !options) {\n return _native.default.randomUUID();\n }\n\n options = options || {};\n\n const rnds = options.random || (options.rng || _rng.default)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n\n\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided\n\n if (buf) {\n offset = offset || 0;\n\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n\n return buf;\n }\n\n return (0, _stringify.unsafeStringify)(rnds);\n}\n\nvar _default = v4;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\n// Adapted from Chris Veness' SHA1 code at\n// http://www.movable-type.co.uk/scripts/sha1.html\nfunction f(s, x, y, z) {\n switch (s) {\n case 0:\n return x & y ^ ~x & z;\n\n case 1:\n return x ^ y ^ z;\n\n case 2:\n return x & y ^ x & z ^ y & z;\n\n case 3:\n return x ^ y ^ z;\n }\n}\n\nfunction ROTL(x, n) {\n return x << n | x >>> 32 - n;\n}\n\nfunction sha1(bytes) {\n const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];\n const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];\n\n if (typeof bytes === 'string') {\n const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape\n\n bytes = [];\n\n for (let i = 0; i < msg.length; ++i) {\n bytes.push(msg.charCodeAt(i));\n }\n } else if (!Array.isArray(bytes)) {\n // Convert Array-like to Array\n bytes = Array.prototype.slice.call(bytes);\n }\n\n bytes.push(0x80);\n const l = bytes.length / 4 + 2;\n const N = Math.ceil(l / 16);\n const M = new Array(N);\n\n for (let i = 0; i < N; ++i) {\n const arr = new Uint32Array(16);\n\n for (let j = 0; j < 16; ++j) {\n arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];\n }\n\n M[i] = arr;\n }\n\n M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);\n M[N - 1][14] = Math.floor(M[N - 1][14]);\n M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;\n\n for (let i = 0; i < N; ++i) {\n const W = new Uint32Array(80);\n\n for (let t = 0; t < 16; ++t) {\n W[t] = M[i][t];\n }\n\n for (let t = 16; t < 80; ++t) {\n W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);\n }\n\n let a = H[0];\n let b = H[1];\n let c = H[2];\n let d = H[3];\n let e = H[4];\n\n for (let t = 0; t < 80; ++t) {\n const s = Math.floor(t / 20);\n const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;\n e = d;\n d = c;\n c = ROTL(b, 30) >>> 0;\n b = a;\n a = T;\n }\n\n H[0] = H[0] + a >>> 0;\n H[1] = H[1] + b >>> 0;\n H[2] = H[2] + c >>> 0;\n H[3] = H[3] + d >>> 0;\n H[4] = H[4] + e >>> 0;\n }\n\n return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];\n}\n\nvar _default = sha1;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _v = _interopRequireDefault(require(\"./v35.js\"));\n\nvar _sha = _interopRequireDefault(require(\"./sha1.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nconst v5 = (0, _v.default)('v5', 0x50, _sha.default);\nvar _default = v5;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\nvar _default = '00000000-0000-0000-0000-000000000000';\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nexports.default = void 0;\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }\n\nfunction version(uuid) {\n if (!(0, _validate.default)(uuid)) {\n throw TypeError('Invalid UUID');\n }\n\n return parseInt(uuid.slice(14, 15), 16);\n}\n\nvar _default = version;\nexports.default = _default;","\"use strict\";\n\nObject.defineProperty(exports, \"__esModule\", {\n value: true\n});\nObject.defineProperty(exports, \"NIL\", {\n enumerable: true,\n get: function get() {\n return _nil.default;\n }\n});\nObject.defineProperty(exports, \"parse\", {\n enumerable: true,\n get: function get() {\n return _parse.default;\n }\n});\nObject.defineProperty(exports, \"stringify\", {\n enumerable: true,\n get: function get() {\n return _stringify.default;\n }\n});\nObject.defineProperty(exports, \"v1\", {\n enumerable: true,\n get: function get() {\n return _v.default;\n }\n});\nObject.defineProperty(exports, \"v3\", {\n enumerable: true,\n get: function get() {\n return _v2.default;\n }\n});\nObject.defineProperty(exports, \"v4\", {\n enumerable: true,\n get: function get() {\n return _v3.default;\n }\n});\nObject.defineProperty(exports, \"v5\", {\n enumerable: true,\n get: function get() {\n return _v4.default;\n }\n});\nObject.defineProperty(exports, \"validate\", {\n enumerable: true,\n get: function get() {\n return _validate.default;\n }\n});\nObject.defineProperty(exports, \"version\", {\n enumerable: true,\n get: function get() {\n return _version.default;\n }\n});\n\nvar _v = _interopRequireDefault(require(\"./v1.js\"));\n\nvar _v2 = _interopRequireDefault(require(\"./v3.js\"));\n\nvar _v3 = _interopRequireDefault(require(\"./v4.js\"));\n\nvar _v4 = _interopRequireDefault(require(\"./v5.js\"));\n\nvar _nil = _interopRequireDefault(require(\"./nil.js\"));\n\nvar _version = _interopRequireDefault(require(\"./version.js\"));\n\nvar _validate = _interopRequireDefault(require(\"./validate.js\"));\n\nvar _stringify = _interopRequireDefault(require(\"./stringify.js\"));\n\nvar _parse = _interopRequireDefault(require(\"./parse.js\"));\n\nfunction _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }","'use strict';\n\n/**\n * Converter\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n * @constructor\n */\nfunction Converter(srcAlphabet, dstAlphabet) {\n if (!srcAlphabet || !dstAlphabet || !srcAlphabet.length || !dstAlphabet.length) {\n throw new Error('Bad alphabet');\n }\n this.srcAlphabet = srcAlphabet;\n this.dstAlphabet = dstAlphabet;\n}\n\n/**\n * Convert number from source alphabet to destination alphabet\n *\n * @param {string|Array} number - number represented as a string or array of points\n *\n * @returns {string|Array}\n */\nConverter.prototype.convert = function(number) {\n var i, divide, newlen,\n numberMap = {},\n fromBase = this.srcAlphabet.length,\n toBase = this.dstAlphabet.length,\n length = number.length,\n result = typeof number === 'string' ? '' : [];\n\n if (!this.isValid(number)) {\n throw new Error('Number \"' + number + '\" contains of non-alphabetic digits (' + this.srcAlphabet + ')');\n }\n\n if (this.srcAlphabet === this.dstAlphabet) {\n return number;\n }\n\n for (i = 0; i < length; i++) {\n numberMap[i] = this.srcAlphabet.indexOf(number[i]);\n }\n do {\n divide = 0;\n newlen = 0;\n for (i = 0; i < length; i++) {\n divide = divide * fromBase + numberMap[i];\n if (divide >= toBase) {\n numberMap[newlen++] = parseInt(divide / toBase, 10);\n divide = divide % toBase;\n } else if (newlen > 0) {\n numberMap[newlen++] = 0;\n }\n }\n length = newlen;\n result = this.dstAlphabet.slice(divide, divide + 1).concat(result);\n } while (newlen !== 0);\n\n return result;\n};\n\n/**\n * Valid number with source alphabet\n *\n * @param {number} number\n *\n * @returns {boolean}\n */\nConverter.prototype.isValid = function(number) {\n var i = 0;\n for (; i < number.length; ++i) {\n if (this.srcAlphabet.indexOf(number[i]) === -1) {\n return false;\n }\n }\n return true;\n};\n\nmodule.exports = Converter;","var Converter = require('./src/converter');\n\n/**\n * Function get source and destination alphabet and return convert function\n *\n * @param {string|Array} srcAlphabet\n * @param {string|Array} dstAlphabet\n *\n * @returns {function(number|Array)}\n */\nfunction anyBase(srcAlphabet, dstAlphabet) {\n var converter = new Converter(srcAlphabet, dstAlphabet);\n /**\n * Convert function\n *\n * @param {string|Array} number\n *\n * @return {string|Array} number\n */\n return function (number) {\n return converter.convert(number);\n }\n};\n\nanyBase.BIN = '01';\nanyBase.OCT = '01234567';\nanyBase.DEC = '0123456789';\nanyBase.HEX = '0123456789abcdef';\n\nmodule.exports = anyBase;","/**\n * Created by Samuel on 6/4/2016.\n * Simple wrapper functions to produce shorter UUIDs for cookies, maybe everything?\n */\n\nconst { v4: uuidV4, validate: uuidValidate } = require('uuid');\nconst anyBase = require('any-base');\n\nconst constants = {\n cookieBase90: \"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%&'()*+-./:<=>?@[]^_`{|}~\",\n flickrBase58: '123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ',\n uuid25Base36: '0123456789abcdefghijklmnopqrstuvwxyz',\n};\n\nconst baseOptions = {\n consistentLength: true,\n};\n\n// A default generator, instantiated only if used.\nlet toFlickr;\n\n/**\n * Takes a UUID, strips the dashes, and translates.\n * @param {string} longId\n * @param {function(string):string} translator\n * @param {Object} [paddingParams]\n * @returns {string}\n */\nconst shortenUUID = (longId, translator, paddingParams) => {\n const translated = translator(longId.toLowerCase().replace(/-/g, ''));\n\n if (!paddingParams || !paddingParams.consistentLength) return translated;\n\n return translated.padStart(\n paddingParams.shortIdLength,\n paddingParams.paddingChar,\n );\n};\n\n/**\n * Translate back to hex and turn back into UUID format, with dashes\n * @param {string} shortId\n * @param {function(string)} translator\n * @returns {string}\n */\nconst enlargeUUID = (shortId, translator) => {\n const uu1 = translator(shortId).padStart(32, '0');\n\n // Join the zero padding and the UUID and then slice it up with match\n const m = uu1.match(/(\\w{8})(\\w{4})(\\w{4})(\\w{4})(\\w{12})/);\n\n // Accumulate the matches and join them.\n return [m[1], m[2], m[3], m[4], m[5]].join('-');\n};\n\n/**\n * Calculate length for the shortened ID\n * @param {number} alphabetLength\n * @returns {number}\n */\nconst getShortIdLength = (alphabetLength) => (\n Math.ceil(Math.log(2 ** 128) / Math.log(alphabetLength)));\n\nmodule.exports = (() => {\n /**\n * @param {string} toAlphabet\n * @param {{ consistentLength: boolean }} [options]\n * @returns {{\n * alphabet: string,\n * fromUUID: (function(*): string),\n * generate: (function(): string),\n * maxLength: number,\n * new: (function(): string),\n * toUUID: (function(*): string),\n * uuid: ((function(*, *, *): (*))|*),\n * validate: ((function(*, boolean=false): (boolean))|*)}}\n */\n const makeConvertor = (toAlphabet, options) => {\n // Default to Flickr 58\n const useAlphabet = toAlphabet || constants.flickrBase58;\n\n // Default to baseOptions\n const selectedOptions = { ...baseOptions, ...options };\n\n // Check alphabet for duplicate entries\n if ([...new Set(Array.from(useAlphabet))].length !== useAlphabet.length) {\n throw new Error('The provided Alphabet has duplicate characters resulting in unreliable results');\n }\n\n const shortIdLength = getShortIdLength(useAlphabet.length);\n\n // Padding Params\n const paddingParams = {\n shortIdLength,\n consistentLength: selectedOptions.consistentLength,\n paddingChar: useAlphabet[0],\n };\n\n // UUIDs are in hex, so we translate to and from.\n const fromHex = anyBase(anyBase.HEX, useAlphabet);\n const toHex = anyBase(useAlphabet, anyBase.HEX);\n /**\n * @returns {string} - short id\n */\n const generate = () => shortenUUID(uuidV4(), fromHex, paddingParams);\n\n /**\n * Confirm if string is a valid id. Checks length and alphabet.\n * If the second parameter is true it will translate to standard UUID\n * and check the result for UUID validity.\n * @param {string} shortId - The string to check for validity\n * @param {boolean} [rigorous=false] - If true, also check for a valid UUID\n * @returns {boolean}\n */\n const validate = (shortId, rigorous = false) => {\n if (!shortId || typeof shortId !== 'string') return false;\n const isCorrectLength = selectedOptions.consistentLength\n ? shortId.length === shortIdLength\n : shortId.length <= shortIdLength;\n const onlyAlphabet = shortId.split('').every((letter) => useAlphabet.includes(letter));\n if (rigorous === false) return isCorrectLength && onlyAlphabet;\n return isCorrectLength && onlyAlphabet && uuidValidate(enlargeUUID(shortId, toHex));\n };\n\n const translator = {\n alphabet: useAlphabet,\n fromUUID: (uuid) => shortenUUID(uuid, fromHex, paddingParams),\n maxLength: shortIdLength,\n generate,\n new: generate,\n toUUID: (shortUuid) => enlargeUUID(shortUuid, toHex),\n uuid: uuidV4,\n validate,\n };\n\n Object.freeze(translator);\n\n return translator;\n };\n\n // Expose the constants for other purposes.\n makeConvertor.constants = constants;\n\n // Expose the generic v4 UUID generator for convenience\n makeConvertor.uuid = uuidV4;\n\n // Provide a generic generator\n makeConvertor.generate = () => {\n if (!toFlickr) {\n // Generate on first use;\n toFlickr = makeConvertor(constants.flickrBase58).generate;\n }\n return toFlickr();\n };\n\n return makeConvertor;\n})();\n","'use strict';\nObject.defineProperty(exports, \"__esModule\", { value: true });\nexports.Worker = void 0;\nclass Worker {\n #epoch;\n #workerId;\n #workerIdBits;\n #maxWorkerId;\n #datacenterId;\n #datacenterIdBits;\n #maxDatacenterId;\n #sequence;\n #sequenceBits;\n #workerIdShift;\n #datacenterIdShift;\n #timestampLeftShift;\n #sequenceMask;\n #lastTimestamp = -1n;\n constructor(workerId = 0n, datacenterId = 0n, options) {\n this.#epoch = BigInt(options?.epoch ?? 1609459200000);\n this.#workerId = BigInt(workerId);\n this.#workerIdBits = BigInt(options?.workerIdBits ?? 5);\n this.#maxWorkerId = -1n ^ (-1n << this.#workerIdBits);\n if (this.#workerId < 0 || this.#workerId > this.#maxWorkerId) {\n throw new Error('With ' +\n this.#workerIdBits.toString() +\n \" bits, worker id can't be greater than \" +\n this.#maxWorkerId.toString() +\n ' or less than 0');\n }\n this.#datacenterId = BigInt(datacenterId);\n this.#datacenterIdBits = BigInt(options?.datacenterIdBits ?? 5);\n this.#maxDatacenterId = -1n ^ (-1n << this.#datacenterIdBits);\n if (this.#datacenterId > this.#maxDatacenterId || this.#datacenterId < 0) {\n throw new Error('With ' +\n this.#datacenterIdBits.toString() +\n \" bits, datacenter id can't be greater than \" +\n this.#maxDatacenterId.toString() +\n ' or less than 0');\n }\n this.#sequence = BigInt(options?.sequence ?? 0);\n this.#sequenceBits = BigInt(options?.sequenceBits ?? 12);\n this.#sequenceMask = -1n ^ (-1n << this.#sequenceBits);\n this.#workerIdShift = this.#sequenceBits;\n this.#datacenterIdShift = this.#sequenceBits + this.#workerIdBits;\n this.#timestampLeftShift = this.#sequenceBits + this.#workerIdBits + this.#datacenterIdBits;\n }\n get workerId() {\n return this.#workerId;\n }\n get datacenterId() {\n return this.#datacenterId;\n }\n get currentSequence() {\n return this.#sequence;\n }\n get lastTimestamp() {\n return this.#lastTimestamp;\n }\n nextId() {\n let timestamp = Worker.now();\n if (timestamp < this.#lastTimestamp) {\n throw new Error(\"Clock moved backwards. Can't generate new ID for \" +\n (this.#lastTimestamp - timestamp).toString() +\n 'milliseconds.');\n }\n if (timestamp === this.#lastTimestamp) {\n this.#sequence = (this.#sequence + 1n) & this.#sequenceMask;\n if (this.#sequence === 0n) {\n timestamp = this.tilNextMillis(this.#lastTimestamp);\n }\n }\n else {\n this.#sequence = 0n;\n }\n this.#lastTimestamp = timestamp;\n return (((timestamp - this.#epoch) << this.#timestampLeftShift) |\n (this.#datacenterId << this.#datacenterIdShift) |\n (this.#workerId << this.#workerIdShift) |\n this.#sequence);\n }\n tilNextMillis(lastTimestamp) {\n let timestamp;\n do {\n timestamp = Worker.now();\n } while (timestamp <= lastTimestamp);\n return timestamp;\n }\n static now() {\n return BigInt(Date.now());\n }\n}\nexports.Worker = Worker;\n","import{ServiceError as r,badRequestError as e}from\"@lowerdeck/error\";import{Hash as t}from\"@lowerdeck/hash\";import{customAlphabet as n}from\"nanoid\";import i from\"short-uuid\";import{Worker as o}from\"snowflake-uuid\";var f=i(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\"),u=n(\"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz\",20),s=n(\"0123456789\",6),d=function(){return(new Date).getTime().toString(36).padStart(9,\"0\")},a=new o(0,0,{workerIdBits:12,sequenceBits:12}),c=new Set,h=function(r){if(r.endsWith(\"_\")&&(r=r.slice(0,-1)),c.has(r))throw new Error(\"Prefix \"+r+\" already exists\")},p={sorted:function(r,e){return void 0===e&&(e=22),h(r),{prefix:r,length:e,type:\"sorted\"}},unsorted:function(r,e){return void 0===e&&(e=22),h(r),{prefix:r,length:e,type:\"unsorted\"}},key:function(r,e){return void 0===e&&(e=50),h(r),{prefix:r,length:e,type:\"key\"}}},x=function(r){for(var e in r)r[e].prefix.endsWith(\"_\")||(r[e].prefix=r[e].prefix+\"_\");var n=new Set;for(var i in r){var o=r[i].prefix;if(n.has(o))throw new Error(\"Prefix \"+o+\" already exists\");n.add(o)}var s=function(e){var t=r[e];if(!t)throw new Error(\"Invalid prefix: \"+e);return t};return{generateId:function(r){try{var e=s(r),n=e.length;if(\"sorted\"==e.type){var i=d(),o=n-i.length;return o<10&&(o=10),Promise.resolve(\"\"+e.prefix+i+u(o))}if(\"unsorted\"==e.type)return Promise.resolve(\"\"+e.prefix+u(n));var f=\"\"+e.prefix+u(n);return Promise.resolve(t.sha512(f)).then(function(r){return\"\"+f+r.slice(0,6)})}catch(r){return Promise.reject(r)}},generateIdSync:function(r){var e=s(r),t=e.length;if(\"sorted\"==e.type){var n=d(),i=t-n.length;return i<10&&(i=10),\"\"+e.prefix+n+u(i)}if(\"unsorted\"==e.type)return\"\"+e.prefix+u(t);throw new Error(\"Cannot generate key id synchronously\")},idPrefixes:Object.entries(r).reduce(function(r,e){return r[e[0]]=e[1].prefix,r},{}),normalizeUUID:function(r,e){return\"\"+s(r).prefix+f.fromUUID(e)}}},l=function(t){if(t.endsWith(\"_\")||(t+=\"_\"),c.has(t))throw new Error(\"Prefix \"+t+\" already exists\");return c.add(t),{fromUUID:function(r){return\"\"+t+f.fromUUID(r)},toUUID:function(n){if(!n.startsWith(t))throw new r(e({message:\"ID \"+n+\" does not start with prefix \"+t}));return f.toUUID(n.slice(t.length))}}},v=function(r,e){return void 0===e&&(e=20),r&&!r.endsWith(\"_\")&&(r+=\"_\"),\"\"+r+u(e)},w=function(r){return void 0===r&&(r=20),u(r)},m=function(r,e){void 0===e&&(e=20);var t=d(),n=e-t.length;return n<10&&(n=10),\"\"+r+t+u(n)},y=function(r){return void 0===r&&(r=6),s(r)},g=function(r){return r&&!r.endsWith(\"_\")&&(r+=\"_\"),\"\"+r+a.nextId().toString(36)};export{x as createIdGenerator,l as createUuidTranslator,y as generateCode,v as generateCustomId,m as generateId,w as generatePlainId,g as generateSnowflakeId,d as idTime,p as idType};\n//# sourceMappingURL=index.module.js.map\n","/**\n * This serves as a build time flag that will be true by default, but false in non-debug builds or if users replace `__SENTRY_DEBUG__` in their generated code.\n *\n * ATTENTION: This constant must never cross package boundaries (i.e. be exported) to guarantee that it can be used for tree shaking.\n */\nconst DEBUG_BUILD = (typeof __SENTRY_DEBUG__ === 'undefined' || __SENTRY_DEBUG__);\n\nexport { DEBUG_BUILD };\n//# sourceMappingURL=debug-build.js.map\n","/** Internal global with common properties and Sentry extensions */\n\n/** Get's the global object for the current JavaScript runtime */\nconst GLOBAL_OBJ = globalThis ;\n\nexport { GLOBAL_OBJ };\n//# sourceMappingURL=worldwide.js.map\n","// This is a magic string replaced by rollup\n\nconst SDK_VERSION = \"10.32.1\" ;\n\nexport { SDK_VERSION };\n//# sourceMappingURL=version.js.map\n","import { SDK_VERSION } from './utils/version.js';\nimport { GLOBAL_OBJ } from './utils/worldwide.js';\n\n/**\n * An object that contains globally accessible properties and maintains a scope stack.\n * @hidden\n */\n\n/**\n * Returns the global shim registry.\n *\n * FIXME: This function is problematic, because despite always returning a valid Carrier,\n * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check\n * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there.\n **/\nfunction getMainCarrier() {\n // This ensures a Sentry carrier exists\n getSentryCarrier(GLOBAL_OBJ);\n return GLOBAL_OBJ;\n}\n\n/** Will either get the existing sentry carrier, or create a new one. */\nfunction getSentryCarrier(carrier) {\n const __SENTRY__ = (carrier.__SENTRY__ = carrier.__SENTRY__ || {});\n\n // For now: First SDK that sets the .version property wins\n __SENTRY__.version = __SENTRY__.version || SDK_VERSION;\n\n // Intentionally populating and returning the version of \"this\" SDK instance\n // rather than what's set in .version so that \"this\" SDK always gets its carrier\n return (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n}\n\n/**\n * Returns a global singleton contained in the global `__SENTRY__[]` object.\n *\n * If the singleton doesn't already exist in `__SENTRY__`, it will be created using the given factory\n * function and added to the `__SENTRY__` object.\n *\n * @param name name of the global singleton on __SENTRY__\n * @param creator creator Factory function to create the singleton if it doesn't already exist on `__SENTRY__`\n * @param obj (Optional) The global object on which to look for `__SENTRY__`, if not `GLOBAL_OBJ`'s return value\n * @returns the singleton\n */\nfunction getGlobalSingleton(\n name,\n creator,\n obj = GLOBAL_OBJ,\n) {\n const __SENTRY__ = (obj.__SENTRY__ = obj.__SENTRY__ || {});\n const carrier = (__SENTRY__[SDK_VERSION] = __SENTRY__[SDK_VERSION] || {});\n // Note: We do not want to set `carrier.version` here, as this may be called before any `init` is called, e.g. for the default scopes\n return carrier[name] || (carrier[name] = creator());\n}\n\nexport { getGlobalSingleton, getMainCarrier, getSentryCarrier };\n//# sourceMappingURL=carrier.js.map\n","import { getGlobalSingleton } from '../carrier.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst CONSOLE_LEVELS = [\n 'debug',\n 'info',\n 'warn',\n 'error',\n 'log',\n 'assert',\n 'trace',\n] ;\n\n/** Prefix for logging strings */\nconst PREFIX = 'Sentry Logger ';\n\n/** This may be mutated by the console instrumentation. */\nconst originalConsoleMethods\n\n = {};\n\n/**\n * Temporarily disable sentry console instrumentations.\n *\n * @param callback The function to run against the original `console` messages\n * @returns The results of the callback\n */\nfunction consoleSandbox(callback) {\n if (!('console' in GLOBAL_OBJ)) {\n return callback();\n }\n\n const console = GLOBAL_OBJ.console;\n const wrappedFuncs = {};\n\n const wrappedLevels = Object.keys(originalConsoleMethods) ;\n\n // Restore all wrapped console methods\n wrappedLevels.forEach(level => {\n const originalConsoleMethod = originalConsoleMethods[level];\n wrappedFuncs[level] = console[level] ;\n console[level] = originalConsoleMethod ;\n });\n\n try {\n return callback();\n } finally {\n // Revert restoration to wrapped state\n wrappedLevels.forEach(level => {\n console[level] = wrappedFuncs[level] ;\n });\n }\n}\n\nfunction enable() {\n _getLoggerSettings().enabled = true;\n}\n\nfunction disable() {\n _getLoggerSettings().enabled = false;\n}\n\nfunction isEnabled() {\n return _getLoggerSettings().enabled;\n}\n\nfunction log(...args) {\n _maybeLog('log', ...args);\n}\n\nfunction warn(...args) {\n _maybeLog('warn', ...args);\n}\n\nfunction error(...args) {\n _maybeLog('error', ...args);\n}\n\nfunction _maybeLog(level, ...args) {\n if (!DEBUG_BUILD) {\n return;\n }\n\n if (isEnabled()) {\n consoleSandbox(() => {\n GLOBAL_OBJ.console[level](`${PREFIX}[${level}]:`, ...args);\n });\n }\n}\n\nfunction _getLoggerSettings() {\n if (!DEBUG_BUILD) {\n return { enabled: false };\n }\n\n return getGlobalSingleton('loggerSettings', () => ({ enabled: false }));\n}\n\n/**\n * This is a logger singleton which either logs things or no-ops if logging is not enabled.\n */\nconst debug = {\n /** Enable logging. */\n enable,\n /** Disable logging. */\n disable,\n /** Check if logging is enabled. */\n isEnabled,\n /** Log a message. */\n log,\n /** Log a warning. */\n warn,\n /** Log an error. */\n error,\n} ;\n\nexport { CONSOLE_LEVELS, consoleSandbox, debug, originalConsoleMethods };\n//# sourceMappingURL=debug-logger.js.map\n","const STACKTRACE_FRAME_LIMIT = 50;\nconst UNKNOWN_FUNCTION = '?';\n// Used to sanitize webpack (error: *) wrapped stack errors\nconst WEBPACK_ERROR_REGEXP = /\\(error: (.*)\\)/;\nconst STRIP_FRAME_REGEXP = /captureMessage|captureException/;\n\n/**\n * Creates a stack parser with the supplied line parsers\n *\n * StackFrames are returned in the correct order for Sentry Exception\n * frames and with Sentry SDK internal frames removed from the top and bottom\n *\n */\nfunction createStackParser(...parsers) {\n const sortedParsers = parsers.sort((a, b) => a[0] - b[0]).map(p => p[1]);\n\n return (stack, skipFirstLines = 0, framesToPop = 0) => {\n const frames = [];\n const lines = stack.split('\\n');\n\n for (let i = skipFirstLines; i < lines.length; i++) {\n let line = lines[i] ;\n // Truncate lines over 1kb because many of the regular expressions use\n // backtracking which results in run time that increases exponentially\n // with input size. Huge strings can result in hangs/Denial of Service:\n // https://github.com/getsentry/sentry-javascript/issues/2286\n if (line.length > 1024) {\n line = line.slice(0, 1024);\n }\n\n // https://github.com/getsentry/sentry-javascript/issues/5459\n // Remove webpack (error: *) wrappers\n const cleanedLine = WEBPACK_ERROR_REGEXP.test(line) ? line.replace(WEBPACK_ERROR_REGEXP, '$1') : line;\n\n // https://github.com/getsentry/sentry-javascript/issues/7813\n // Skip Error: lines\n if (cleanedLine.match(/\\S*Error: /)) {\n continue;\n }\n\n for (const parser of sortedParsers) {\n const frame = parser(cleanedLine);\n\n if (frame) {\n frames.push(frame);\n break;\n }\n }\n\n if (frames.length >= STACKTRACE_FRAME_LIMIT + framesToPop) {\n break;\n }\n }\n\n return stripSentryFramesAndReverse(frames.slice(framesToPop));\n };\n}\n\n/**\n * Gets a stack parser implementation from Options.stackParser\n * @see Options\n *\n * If options contains an array of line parsers, it is converted into a parser\n */\nfunction stackParserFromStackParserOptions(stackParser) {\n if (Array.isArray(stackParser)) {\n return createStackParser(...stackParser);\n }\n return stackParser;\n}\n\n/**\n * Removes Sentry frames from the top and bottom of the stack if present and enforces a limit of max number of frames.\n * Assumes stack input is ordered from top to bottom and returns the reverse representation so call site of the\n * function that caused the crash is the last frame in the array.\n * @hidden\n */\nfunction stripSentryFramesAndReverse(stack) {\n if (!stack.length) {\n return [];\n }\n\n const localStack = Array.from(stack);\n\n // If stack starts with one of our API calls, remove it (starts, meaning it's the top of the stack - aka last call)\n if (/sentryWrapped/.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n\n // Reversing in the middle of the procedure allows us to just pop the values off the stack\n localStack.reverse();\n\n // If stack ends with one of our internal API calls, remove it (ends, meaning it's the bottom of the stack - aka top-most call)\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n\n // When using synthetic events, we will have a 2 levels deep stack, as `new Error('Sentry syntheticException')`\n // is produced within the scope itself, making it:\n //\n // Sentry.captureException()\n // scope.captureException()\n //\n // instead of just the top `Sentry` call itself.\n // This forces us to possibly strip an additional frame in the exact same was as above.\n if (STRIP_FRAME_REGEXP.test(getLastStackFrame(localStack).function || '')) {\n localStack.pop();\n }\n }\n\n return localStack.slice(0, STACKTRACE_FRAME_LIMIT).map(frame => ({\n ...frame,\n filename: frame.filename || getLastStackFrame(localStack).filename,\n function: frame.function || UNKNOWN_FUNCTION,\n }));\n}\n\nfunction getLastStackFrame(arr) {\n return arr[arr.length - 1] || {};\n}\n\nconst defaultFunctionName = '<anonymous>';\n\n/**\n * Safely extract function name from itself\n */\nfunction getFunctionName(fn) {\n try {\n if (!fn || typeof fn !== 'function') {\n return defaultFunctionName;\n }\n return fn.name || defaultFunctionName;\n } catch {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n return defaultFunctionName;\n }\n}\n\n/**\n * Get's stack frames from an event without needing to check for undefined properties.\n */\nfunction getFramesFromEvent(event) {\n const exception = event.exception;\n\n if (exception) {\n const frames = [];\n try {\n // @ts-expect-error Object could be undefined\n exception.values.forEach(value => {\n // @ts-expect-error Value could be undefined\n if (value.stacktrace.frames) {\n // @ts-expect-error Value could be undefined\n frames.push(...value.stacktrace.frames);\n }\n });\n return frames;\n } catch {\n return undefined;\n }\n }\n return undefined;\n}\n\n/**\n * Get the internal name of an internal Vue value, to represent it in a stacktrace.\n *\n * @param value The value to get the internal name of.\n */\nfunction getVueInternalName(value) {\n // Check if it's a VNode (has __v_isVNode) or a component instance (has _isVue/__isVue)\n const isVNode = '__v_isVNode' in value && value.__v_isVNode;\n\n return isVNode ? '[VueVNode]' : '[VueViewModel]';\n}\n\nexport { UNKNOWN_FUNCTION, createStackParser, getFramesFromEvent, getFunctionName, getVueInternalName, stackParserFromStackParserOptions, stripSentryFramesAndReverse };\n//# sourceMappingURL=stacktrace.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getFunctionName } from '../utils/stacktrace.js';\n\n// We keep the handlers globally\nconst handlers = {};\nconst instrumented = {};\n\n/** Add a handler function. */\nfunction addHandler(type, handler) {\n handlers[type] = handlers[type] || [];\n handlers[type].push(handler);\n}\n\n/**\n * Reset all instrumentation handlers.\n * This can be used by tests to ensure we have a clean slate of instrumentation handlers.\n */\nfunction resetInstrumentationHandlers() {\n Object.keys(handlers).forEach(key => {\n handlers[key ] = undefined;\n });\n}\n\n/** Maybe run an instrumentation function, unless it was already called. */\nfunction maybeInstrument(type, instrumentFn) {\n if (!instrumented[type]) {\n instrumented[type] = true;\n try {\n instrumentFn();\n } catch (e) {\n DEBUG_BUILD && debug.error(`Error while instrumenting ${type}`, e);\n }\n }\n}\n\n/** Trigger handlers for a given instrumentation type. */\nfunction triggerHandlers(type, data) {\n const typeHandlers = type && handlers[type];\n if (!typeHandlers) {\n return;\n }\n\n for (const handler of typeHandlers) {\n try {\n handler(data);\n } catch (e) {\n DEBUG_BUILD &&\n debug.error(\n `Error while triggering instrumentation handler.\\nType: ${type}\\nName: ${getFunctionName(handler)}\\nError:`,\n e,\n );\n }\n }\n}\n\nexport { addHandler, maybeInstrument, resetInstrumentationHandlers, triggerHandlers };\n//# sourceMappingURL=handlers.js.map\n","import { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnErrorHandler = null;\n\n/**\n * Add an instrumentation handler for when an error is captured by the global error handler.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalErrorInstrumentationHandler(handler) {\n const type = 'error';\n addHandler(type, handler);\n maybeInstrument(type, instrumentError);\n}\n\nfunction instrumentError() {\n _oldOnErrorHandler = GLOBAL_OBJ.onerror;\n\n // Note: The reason we are doing window.onerror instead of window.addEventListener('error')\n // is that we are using this handler in the Loader Script, to handle buffered errors consistently\n GLOBAL_OBJ.onerror = function (\n msg,\n url,\n line,\n column,\n error,\n ) {\n const handlerData = {\n column,\n error,\n line,\n msg,\n url,\n };\n triggerHandlers('error', handlerData);\n\n if (_oldOnErrorHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnErrorHandler.apply(this, arguments);\n }\n\n return false;\n };\n\n GLOBAL_OBJ.onerror.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalErrorInstrumentationHandler };\n//# sourceMappingURL=globalError.js.map\n","import { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\nlet _oldOnUnhandledRejectionHandler = null;\n\n/**\n * Add an instrumentation handler for when an unhandled promise rejection is captured.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addGlobalUnhandledRejectionInstrumentationHandler(\n handler,\n) {\n const type = 'unhandledrejection';\n addHandler(type, handler);\n maybeInstrument(type, instrumentUnhandledRejection);\n}\n\nfunction instrumentUnhandledRejection() {\n _oldOnUnhandledRejectionHandler = GLOBAL_OBJ.onunhandledrejection;\n\n // Note: The reason we are doing window.onunhandledrejection instead of window.addEventListener('unhandledrejection')\n // is that we are using this handler in the Loader Script, to handle buffered rejections consistently\n GLOBAL_OBJ.onunhandledrejection = function (e) {\n const handlerData = e;\n triggerHandlers('unhandledrejection', handlerData);\n\n if (_oldOnUnhandledRejectionHandler) {\n // eslint-disable-next-line prefer-rest-params\n return _oldOnUnhandledRejectionHandler.apply(this, arguments);\n }\n\n return true;\n };\n\n GLOBAL_OBJ.onunhandledrejection.__SENTRY_INSTRUMENTED__ = true;\n}\n\nexport { addGlobalUnhandledRejectionInstrumentationHandler };\n//# sourceMappingURL=globalUnhandledRejection.js.map\n","// eslint-disable-next-line @typescript-eslint/unbound-method\nconst objectToString = Object.prototype.toString;\n\n/**\n * Checks whether given value's type is one of a few Error or Error-like\n * {@link isError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isError(wat) {\n switch (objectToString.call(wat)) {\n case '[object Error]':\n case '[object Exception]':\n case '[object DOMException]':\n case '[object WebAssembly.Exception]':\n return true;\n default:\n return isInstanceOf(wat, Error);\n }\n}\n/**\n * Checks whether given value is an instance of the given built-in class.\n *\n * @param wat The value to be checked\n * @param className\n * @returns A boolean representing the result.\n */\nfunction isBuiltin(wat, className) {\n return objectToString.call(wat) === `[object ${className}]`;\n}\n\n/**\n * Checks whether given value's type is ErrorEvent\n * {@link isErrorEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isErrorEvent(wat) {\n return isBuiltin(wat, 'ErrorEvent');\n}\n\n/**\n * Checks whether given value's type is DOMError\n * {@link isDOMError}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMError(wat) {\n return isBuiltin(wat, 'DOMError');\n}\n\n/**\n * Checks whether given value's type is DOMException\n * {@link isDOMException}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isDOMException(wat) {\n return isBuiltin(wat, 'DOMException');\n}\n\n/**\n * Checks whether given value's type is a string\n * {@link isString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isString(wat) {\n return isBuiltin(wat, 'String');\n}\n\n/**\n * Checks whether given string is parameterized\n * {@link isParameterizedString}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isParameterizedString(wat) {\n return (\n typeof wat === 'object' &&\n wat !== null &&\n '__sentry_template_string__' in wat &&\n '__sentry_template_values__' in wat\n );\n}\n\n/**\n * Checks whether given value is a primitive (undefined, null, number, boolean, string, bigint, symbol)\n * {@link isPrimitive}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPrimitive(wat) {\n return wat === null || isParameterizedString(wat) || (typeof wat !== 'object' && typeof wat !== 'function');\n}\n\n/**\n * Checks whether given value's type is an object literal, or a class instance.\n * {@link isPlainObject}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isPlainObject(wat) {\n return isBuiltin(wat, 'Object');\n}\n\n/**\n * Checks whether given value's type is an Event instance\n * {@link isEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isEvent(wat) {\n return typeof Event !== 'undefined' && isInstanceOf(wat, Event);\n}\n\n/**\n * Checks whether given value's type is an Element instance\n * {@link isElement}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isElement(wat) {\n return typeof Element !== 'undefined' && isInstanceOf(wat, Element);\n}\n\n/**\n * Checks whether given value's type is an regexp\n * {@link isRegExp}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isRegExp(wat) {\n return isBuiltin(wat, 'RegExp');\n}\n\n/**\n * Checks whether given value has a then function.\n * @param wat A value to be checked.\n */\nfunction isThenable(wat) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return Boolean(wat?.then && typeof wat.then === 'function');\n}\n\n/**\n * Checks whether given value's type is a SyntheticEvent\n * {@link isSyntheticEvent}.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isSyntheticEvent(wat) {\n return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat;\n}\n\n/**\n * Checks whether given value's type is an instance of provided constructor.\n * {@link isInstanceOf}.\n *\n * @param wat A value to be checked.\n * @param base A constructor to be used in a check.\n * @returns A boolean representing the result.\n */\n// TODO: fix in v11, convert any to unknown\n// export function isInstanceOf<T>(wat: unknown, base: { new (...args: any[]): T }): wat is T {\nfunction isInstanceOf(wat, base) {\n try {\n return wat instanceof base;\n } catch {\n return false;\n }\n}\n\n/**\n * Checks whether given value's type is a Vue ViewModel or a VNode.\n *\n * @param wat A value to be checked.\n * @returns A boolean representing the result.\n */\nfunction isVueViewModel(wat) {\n // Not using Object.prototype.toString because in Vue 3 it would read the instance's Symbol(Symbol.toStringTag) property.\n // We also need to check for __v_isVNode because Vue 3 component render instances have an internal __v_isVNode property.\n return !!(\n typeof wat === 'object' &&\n wat !== null &&\n ((wat ).__isVue || (wat )._isVue || (wat ).__v_isVNode)\n );\n}\n\n/**\n * Checks whether the given parameter is a Standard Web API Request instance.\n *\n * Returns false if Request is not available in the current runtime.\n */\nfunction isRequest(request) {\n return typeof Request !== 'undefined' && isInstanceOf(request, Request);\n}\n\nexport { isDOMError, isDOMException, isElement, isError, isErrorEvent, isEvent, isInstanceOf, isParameterizedString, isPlainObject, isPrimitive, isRegExp, isRequest, isString, isSyntheticEvent, isThenable, isVueViewModel };\n//# sourceMappingURL=is.js.map\n","import { isString } from './is.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\n/**\n * Given a child DOM element, returns a query-selector statement describing that\n * and its ancestors\n * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction htmlTreeAsString(\n elem,\n options = {},\n) {\n if (!elem) {\n return '<unknown>';\n }\n\n // try/catch both:\n // - accessing event.target (see getsentry/raven-js#838, #768)\n // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly\n // - can throw an exception in some circumstances.\n try {\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n const out = [];\n let height = 0;\n let len = 0;\n const separator = ' > ';\n const sepLength = separator.length;\n let nextStr;\n const keyAttrs = Array.isArray(options) ? options : options.keyAttrs;\n const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH;\n\n while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) {\n nextStr = _htmlElementAsString(currentElem, keyAttrs);\n // bail out if\n // - nextStr is the 'html' element\n // - the length of the string that would be created exceeds maxStringLength\n // (ignore this limit if we are on the first iteration)\n if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) {\n break;\n }\n\n out.push(nextStr);\n\n len += nextStr.length;\n currentElem = currentElem.parentNode;\n }\n\n return out.reverse().join(separator);\n } catch {\n return '<unknown>';\n }\n}\n\n/**\n * Returns a simple, query-selector representation of a DOM element\n * e.g. [HTMLElement] => input#foo.btn[name=baz]\n * @returns generated DOM path\n */\nfunction _htmlElementAsString(el, keyAttrs) {\n const elem = el\n\n;\n\n const out = [];\n\n if (!elem?.tagName) {\n return '';\n }\n\n // @ts-expect-error WINDOW has HTMLElement\n if (WINDOW.HTMLElement) {\n // If using the component name annotation plugin, this value may be available on the DOM node\n if (elem instanceof HTMLElement && elem.dataset) {\n if (elem.dataset['sentryComponent']) {\n return elem.dataset['sentryComponent'];\n }\n if (elem.dataset['sentryElement']) {\n return elem.dataset['sentryElement'];\n }\n }\n }\n\n out.push(elem.tagName.toLowerCase());\n\n // Pairs of attribute keys defined in `serializeAttribute` and their values on element.\n const keyAttrPairs = keyAttrs?.length\n ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)])\n : null;\n\n if (keyAttrPairs?.length) {\n keyAttrPairs.forEach(keyAttrPair => {\n out.push(`[${keyAttrPair[0]}=\"${keyAttrPair[1]}\"]`);\n });\n } else {\n if (elem.id) {\n out.push(`#${elem.id}`);\n }\n\n const className = elem.className;\n if (className && isString(className)) {\n const classes = className.split(/\\s+/);\n for (const c of classes) {\n out.push(`.${c}`);\n }\n }\n }\n const allowedAttrs = ['aria-label', 'type', 'name', 'title', 'alt'];\n for (const k of allowedAttrs) {\n const attr = elem.getAttribute(k);\n if (attr) {\n out.push(`[${k}=\"${attr}\"]`);\n }\n }\n\n return out.join('');\n}\n\n/**\n * A safe form of location.href\n */\nfunction getLocationHref() {\n try {\n return WINDOW.document.location.href;\n } catch {\n return '';\n }\n}\n\n/**\n * Given a DOM element, traverses up the tree until it finds the first ancestor node\n * that has the `data-sentry-component` or `data-sentry-element` attribute with `data-sentry-component` taking\n * precedence. This attribute is added at build-time by projects that have the component name annotation plugin installed.\n *\n * @returns a string representation of the component for the provided DOM element, or `null` if not found\n */\nfunction getComponentName(elem) {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem ;\n const MAX_TRAVERSE_HEIGHT = 5;\n for (let i = 0; i < MAX_TRAVERSE_HEIGHT; i++) {\n if (!currentElem) {\n return null;\n }\n\n if (currentElem instanceof HTMLElement) {\n if (currentElem.dataset['sentryComponent']) {\n return currentElem.dataset['sentryComponent'];\n }\n if (currentElem.dataset['sentryElement']) {\n return currentElem.dataset['sentryElement'];\n }\n }\n\n currentElem = currentElem.parentNode;\n }\n\n return null;\n}\n\nexport { getComponentName, getLocationHref, htmlTreeAsString };\n//# sourceMappingURL=browser.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { htmlTreeAsString } from './browser.js';\nimport { debug } from './debug-logger.js';\nimport { isError, isEvent, isInstanceOf, isPrimitive, isElement } from './is.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/**\n * Replace a method in an object with a wrapped version of itself.\n *\n * If the method on the passed object is not a function, the wrapper will not be applied.\n *\n * @param source An object that contains a method to be wrapped.\n * @param name The name of the method to be wrapped.\n * @param replacementFactory A higher-order function that takes the original version of the given method and returns a\n * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to\n * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, <other\n * args>)` or `origMethod.apply(this, [<other args>])` (rather than being called directly), again to preserve `this`.\n * @returns void\n */\nfunction fill(source, name, replacementFactory) {\n if (!(name in source)) {\n return;\n }\n\n // explicitly casting to unknown because we don't know the type of the method initially at all\n const original = source[name] ;\n\n if (typeof original !== 'function') {\n return;\n }\n\n const wrapped = replacementFactory(original) ;\n\n // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work\n // otherwise it'll throw \"TypeError: Object.defineProperties called on non-object\"\n if (typeof wrapped === 'function') {\n markFunctionWrapped(wrapped, original);\n }\n\n try {\n source[name] = wrapped;\n } catch {\n DEBUG_BUILD && debug.log(`Failed to replace method \"${name}\" in object`, source);\n }\n}\n\n/**\n * Defines a non-enumerable property on the given object.\n *\n * @param obj The object on which to set the property\n * @param name The name of the property to be set\n * @param value The value to which to set the property\n */\nfunction addNonEnumerableProperty(obj, name, value) {\n try {\n Object.defineProperty(obj, name, {\n // enumerable: false, // the default, so we can save on bundle size by not explicitly setting it\n value: value,\n writable: true,\n configurable: true,\n });\n } catch {\n DEBUG_BUILD && debug.log(`Failed to add non-enumerable property \"${name}\" to object`, obj);\n }\n}\n\n/**\n * Remembers the original function on the wrapped function and\n * patches up the prototype.\n *\n * @param wrapped the wrapper function\n * @param original the original function that gets wrapped\n */\nfunction markFunctionWrapped(wrapped, original) {\n try {\n const proto = original.prototype || {};\n wrapped.prototype = original.prototype = proto;\n addNonEnumerableProperty(wrapped, '__sentry_original__', original);\n } catch {} // eslint-disable-line no-empty\n}\n\n/**\n * This extracts the original function if available. See\n * `markFunctionWrapped` for more information.\n *\n * @param func the function to unwrap\n * @returns the unwrapped version of the function if available.\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction getOriginalFunction(func) {\n return func.__sentry_original__;\n}\n\n/**\n * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their\n * non-enumerable properties attached.\n *\n * @param value Initial source that we have to transform in order for it to be usable by the serializer\n * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor\n * an Error.\n */\nfunction convertToPlainObject(value)\n\n {\n if (isError(value)) {\n return {\n message: value.message,\n name: value.name,\n stack: value.stack,\n ...getOwnProperties(value),\n };\n } else if (isEvent(value)) {\n const newObj\n\n = {\n type: value.type,\n target: serializeEventTarget(value.target),\n currentTarget: serializeEventTarget(value.currentTarget),\n ...getOwnProperties(value),\n };\n\n if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) {\n newObj.detail = value.detail;\n }\n\n return newObj;\n } else {\n return value;\n }\n}\n\n/** Creates a string representation of the target of an `Event` object */\nfunction serializeEventTarget(target) {\n try {\n return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target);\n } catch {\n return '<unknown>';\n }\n}\n\n/** Filters out all but an object's own properties */\nfunction getOwnProperties(obj) {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj )[property];\n }\n }\n return extractedProps;\n } else {\n return {};\n }\n}\n\n/**\n * Given any captured exception, extract its keys and create a sorted\n * and truncated list that will be used inside the event message.\n * eg. `Non-error exception captured with keys: foo, bar, baz`\n */\nfunction extractExceptionKeysForMessage(exception) {\n const keys = Object.keys(convertToPlainObject(exception));\n keys.sort();\n\n return !keys[0] ? '[object has no keys]' : keys.join(', ');\n}\n\n/**\n * Given any object, return a new object having removed all fields whose value was `undefined`.\n * Works recursively on objects and arrays.\n *\n * Attention: This function keeps circular references in the returned object.\n *\n * @deprecated This function is no longer used by the SDK and will be removed in a future major version.\n */\nfunction dropUndefinedKeys(inputValue) {\n // This map keeps track of what already visited nodes map to.\n // Our Set - based memoBuilder doesn't work here because we want to the output object to have the same circular\n // references as the input object.\n const memoizationMap = new Map();\n\n // This function just proxies `_dropUndefinedKeys` to keep the `memoBuilder` out of this function's API\n return _dropUndefinedKeys(inputValue, memoizationMap);\n}\n\nfunction _dropUndefinedKeys(inputValue, memoizationMap) {\n // Early return for primitive values\n if (inputValue === null || typeof inputValue !== 'object') {\n return inputValue;\n }\n\n // Check memo map first for all object types\n const memoVal = memoizationMap.get(inputValue);\n if (memoVal !== undefined) {\n return memoVal ;\n }\n\n // handle arrays\n if (Array.isArray(inputValue)) {\n const returnValue = [];\n // Store mapping to handle circular references\n memoizationMap.set(inputValue, returnValue);\n\n inputValue.forEach(value => {\n returnValue.push(_dropUndefinedKeys(value, memoizationMap));\n });\n\n return returnValue ;\n }\n\n if (isPojo(inputValue)) {\n const returnValue = {};\n // Store mapping to handle circular references\n memoizationMap.set(inputValue, returnValue);\n\n const keys = Object.keys(inputValue);\n\n keys.forEach(key => {\n const val = inputValue[key];\n if (val !== undefined) {\n returnValue[key] = _dropUndefinedKeys(val, memoizationMap);\n }\n });\n\n return returnValue ;\n }\n\n // For other object types, return as is\n return inputValue;\n}\n\nfunction isPojo(input) {\n // Plain objects have Object as constructor or no constructor\n const constructor = (input ).constructor;\n return constructor === Object || constructor === undefined;\n}\n\n/**\n * Ensure that something is an object.\n *\n * Turns `undefined` and `null` into `String`s and all other primitives into instances of their respective wrapper\n * classes (String, Boolean, Number, etc.). Acts as the identity function on non-primitives.\n *\n * @param wat The subject of the objectification\n * @returns A version of `wat` which can safely be used with `Object` class methods\n */\nfunction objectify(wat) {\n let objectified;\n switch (true) {\n // this will catch both undefined and null\n case wat == undefined:\n objectified = new String(wat);\n break;\n\n // Though symbols and bigints do have wrapper classes (`Symbol` and `BigInt`, respectively), for whatever reason\n // those classes don't have constructors which can be used with the `new` keyword. We therefore need to cast each as\n // an object in order to wrap it.\n case typeof wat === 'symbol' || typeof wat === 'bigint':\n objectified = Object(wat);\n break;\n\n // this will catch the remaining primitives: `String`, `Number`, and `Boolean`\n case isPrimitive(wat):\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n objectified = new (wat ).constructor(wat);\n break;\n\n // by process of elimination, at this point we know that `wat` must already be an object\n default:\n objectified = wat;\n break;\n }\n return objectified;\n}\n\nexport { addNonEnumerableProperty, convertToPlainObject, dropUndefinedKeys, extractExceptionKeysForMessage, fill, getOriginalFunction, markFunctionWrapped, objectify };\n//# sourceMappingURL=object.js.map\n","import { isString, isRegExp, isVueViewModel } from './is.js';\nimport { getVueInternalName } from './stacktrace.js';\n\n/**\n * Truncates given string to the maximum characters count\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string (0 = unlimited)\n * @returns string Encoded\n */\nfunction truncate(str, max = 0) {\n if (typeof str !== 'string' || max === 0) {\n return str;\n }\n return str.length <= max ? str : `${str.slice(0, max)}...`;\n}\n\n/**\n * This is basically just `trim_line` from\n * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67\n *\n * @param str An object that contains serializable values\n * @param max Maximum number of characters in truncated string\n * @returns string Encoded\n */\nfunction snipLine(line, colno) {\n let newLine = line;\n const lineLength = newLine.length;\n if (lineLength <= 150) {\n return newLine;\n }\n if (colno > lineLength) {\n // eslint-disable-next-line no-param-reassign\n colno = lineLength;\n }\n\n let start = Math.max(colno - 60, 0);\n if (start < 5) {\n start = 0;\n }\n\n let end = Math.min(start + 140, lineLength);\n if (end > lineLength - 5) {\n end = lineLength;\n }\n if (end === lineLength) {\n start = Math.max(end - 140, 0);\n }\n\n newLine = newLine.slice(start, end);\n if (start > 0) {\n newLine = `'{snip} ${newLine}`;\n }\n if (end < lineLength) {\n newLine += ' {snip}';\n }\n\n return newLine;\n}\n\n/**\n * Join values in array\n * @param input array of values to be joined together\n * @param delimiter string to be placed in-between values\n * @returns Joined values\n */\nfunction safeJoin(input, delimiter) {\n if (!Array.isArray(input)) {\n return '';\n }\n\n const output = [];\n // eslint-disable-next-line @typescript-eslint/prefer-for-of\n for (let i = 0; i < input.length; i++) {\n const value = input[i];\n try {\n // This is a hack to fix a Vue3-specific bug that causes an infinite loop of\n // console warnings. This happens when a Vue template is rendered with\n // an undeclared variable, which we try to stringify, ultimately causing\n // Vue to issue another warning which repeats indefinitely.\n // see: https://github.com/getsentry/sentry-javascript/pull/8981\n if (isVueViewModel(value)) {\n output.push(getVueInternalName(value));\n } else {\n output.push(String(value));\n }\n } catch {\n output.push('[value cannot be serialized]');\n }\n }\n\n return output.join(delimiter);\n}\n\n/**\n * Checks if the given value matches a regex or string\n *\n * @param value The string to test\n * @param pattern Either a regex or a string against which `value` will be matched\n * @param requireExactStringMatch If true, `value` must match `pattern` exactly. If false, `value` will match\n * `pattern` if it contains `pattern`. Only applies to string-type patterns.\n */\nfunction isMatchingPattern(\n value,\n pattern,\n requireExactStringMatch = false,\n) {\n if (!isString(value)) {\n return false;\n }\n\n if (isRegExp(pattern)) {\n return pattern.test(value);\n }\n if (isString(pattern)) {\n return requireExactStringMatch ? value === pattern : value.includes(pattern);\n }\n\n return false;\n}\n\n/**\n * Test the given string against an array of strings and regexes. By default, string matching is done on a\n * substring-inclusion basis rather than a strict equality basis\n *\n * @param testString The string to test\n * @param patterns The patterns against which to test the string\n * @param requireExactStringMatch If true, `testString` must match one of the given string patterns exactly in order to\n * count. If false, `testString` will match a string pattern if it contains that pattern.\n * @returns\n */\nfunction stringMatchesSomePattern(\n testString,\n patterns = [],\n requireExactStringMatch = false,\n) {\n return patterns.some(pattern => isMatchingPattern(testString, pattern, requireExactStringMatch));\n}\n\nexport { isMatchingPattern, safeJoin, snipLine, stringMatchesSomePattern, truncate };\n//# sourceMappingURL=string.js.map\n","import { addNonEnumerableProperty } from './object.js';\nimport { snipLine } from './string.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nfunction getCrypto() {\n const gbl = GLOBAL_OBJ ;\n return gbl.crypto || gbl.msCrypto;\n}\n\nlet emptyUuid;\n\nfunction getRandomByte() {\n return Math.random() * 16;\n}\n\n/**\n * UUID4 generator\n * @param crypto Object that provides the crypto API.\n * @returns string Generated UUID4.\n */\nfunction uuid4(crypto = getCrypto()) {\n try {\n if (crypto?.randomUUID) {\n return crypto.randomUUID().replace(/-/g, '');\n }\n } catch {\n // some runtimes can crash invoking crypto\n // https://github.com/getsentry/sentry-javascript/issues/8935\n }\n\n if (!emptyUuid) {\n // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523\n // Concatenating the following numbers as strings results in '10000000100040008000100000000000'\n emptyUuid = ([1e7] ) + 1e3 + 4e3 + 8e3 + 1e11;\n }\n\n return emptyUuid.replace(/[018]/g, c =>\n // eslint-disable-next-line no-bitwise\n ((c ) ^ ((getRandomByte() & 15) >> ((c ) / 4))).toString(16),\n );\n}\n\nfunction getFirstException(event) {\n return event.exception?.values?.[0];\n}\n\n/**\n * Extracts either message or type+value from an event that can be used for user-facing logs\n * @returns event's description\n */\nfunction getEventDescription(event) {\n const { message, event_id: eventId } = event;\n if (message) {\n return message;\n }\n\n const firstException = getFirstException(event);\n if (firstException) {\n if (firstException.type && firstException.value) {\n return `${firstException.type}: ${firstException.value}`;\n }\n return firstException.type || firstException.value || eventId || '<unknown>';\n }\n return eventId || '<unknown>';\n}\n\n/**\n * Adds exception values, type and value to an synthetic Exception.\n * @param event The event to modify.\n * @param value Value of the exception.\n * @param type Type of the exception.\n * @hidden\n */\nfunction addExceptionTypeValue(event, value, type) {\n const exception = (event.exception = event.exception || {});\n const values = (exception.values = exception.values || []);\n const firstException = (values[0] = values[0] || {});\n if (!firstException.value) {\n firstException.value = value || '';\n }\n if (!firstException.type) {\n firstException.type = type || 'Error';\n }\n}\n\n/**\n * Adds exception mechanism data to a given event. Uses defaults if the second parameter is not passed.\n *\n * @param event The event to modify.\n * @param newMechanism Mechanism data to add to the event.\n * @hidden\n */\nfunction addExceptionMechanism(event, newMechanism) {\n const firstException = getFirstException(event);\n if (!firstException) {\n return;\n }\n\n const defaultMechanism = { type: 'generic', handled: true };\n const currentMechanism = firstException.mechanism;\n firstException.mechanism = { ...defaultMechanism, ...currentMechanism, ...newMechanism };\n\n if (newMechanism && 'data' in newMechanism) {\n const mergedData = { ...currentMechanism?.data, ...newMechanism.data };\n firstException.mechanism.data = mergedData;\n }\n}\n\n// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string\nconst SEMVER_REGEXP =\n /^(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?$/;\n\n/**\n * Represents Semantic Versioning object\n */\n\nfunction _parseInt(input) {\n return parseInt(input || '', 10);\n}\n\n/**\n * Parses input into a SemVer interface\n * @param input string representation of a semver version\n */\nfunction parseSemver(input) {\n const match = input.match(SEMVER_REGEXP) || [];\n const major = _parseInt(match[1]);\n const minor = _parseInt(match[2]);\n const patch = _parseInt(match[3]);\n return {\n buildmetadata: match[5],\n major: isNaN(major) ? undefined : major,\n minor: isNaN(minor) ? undefined : minor,\n patch: isNaN(patch) ? undefined : patch,\n prerelease: match[4],\n };\n}\n\n/**\n * This function adds context (pre/post/line) lines to the provided frame\n *\n * @param lines string[] containing all lines\n * @param frame StackFrame that will be mutated\n * @param linesOfContext number of context lines we want to add pre/post\n */\nfunction addContextToFrame(lines, frame, linesOfContext = 5) {\n // When there is no line number in the frame, attaching context is nonsensical and will even break grouping\n if (frame.lineno === undefined) {\n return;\n }\n\n const maxLines = lines.length;\n const sourceLine = Math.max(Math.min(maxLines - 1, frame.lineno - 1), 0);\n\n frame.pre_context = lines\n .slice(Math.max(0, sourceLine - linesOfContext), sourceLine)\n .map((line) => snipLine(line, 0));\n\n // We guard here to ensure this is not larger than the existing number of lines\n const lineIndex = Math.min(maxLines - 1, sourceLine);\n\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n frame.context_line = snipLine(lines[lineIndex], frame.colno || 0);\n\n frame.post_context = lines\n .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext)\n .map((line) => snipLine(line, 0));\n}\n\n/**\n * Checks whether or not we've already captured the given exception (note: not an identical exception - the very object\n * in question), and marks it captured if not.\n *\n * This is useful because it's possible for an error to get captured by more than one mechanism. After we intercept and\n * record an error, we rethrow it (assuming we've intercepted it before it's reached the top-level global handlers), so\n * that we don't interfere with whatever effects the error might have had were the SDK not there. At that point, because\n * the error has been rethrown, it's possible for it to bubble up to some other code we've instrumented. If it's not\n * caught after that, it will bubble all the way up to the global handlers (which of course we also instrument). This\n * function helps us ensure that even if we encounter the same error more than once, we only record it the first time we\n * see it.\n *\n * Note: It will ignore primitives (always return `false` and not mark them as seen), as properties can't be set on\n * them. {@link: Object.objectify} can be used on exceptions to convert any that are primitives into their equivalent\n * object wrapper forms so that this check will always work. However, because we need to flag the exact object which\n * will get rethrown, and because that rethrowing happens outside of the event processing pipeline, the objectification\n * must be done before the exception captured.\n *\n * @param A thrown exception to check or flag as having been seen\n * @returns `true` if the exception has already been captured, `false` if not (with the side effect of marking it seen)\n */\nfunction checkOrSetAlreadyCaught(exception) {\n if (isAlreadyCaptured(exception)) {\n return true;\n }\n\n try {\n // set it this way rather than by assignment so that it's not ennumerable and therefore isn't recorded by the\n // `ExtraErrorData` integration\n addNonEnumerableProperty(exception , '__sentry_captured__', true);\n } catch {\n // `exception` is a primitive, so we can't mark it seen\n }\n\n return false;\n}\n\nfunction isAlreadyCaptured(exception) {\n try {\n return (exception ).__sentry_captured__;\n } catch {} // eslint-disable-line no-empty\n}\n\nexport { addContextToFrame, addExceptionMechanism, addExceptionTypeValue, checkOrSetAlreadyCaught, getEventDescription, parseSemver, uuid4 };\n//# sourceMappingURL=misc.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nconst ONE_SECOND_IN_MS = 1000;\n\n/**\n * A partial definition of the [Performance Web API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Performance}\n * for accessing a high-resolution monotonic clock.\n */\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using the Date API.\n */\nfunction dateTimestampInSeconds() {\n return Date.now() / ONE_SECOND_IN_MS;\n}\n\n/**\n * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not\n * support the API.\n *\n * Wrapping the native API works around differences in behavior from different browsers.\n */\nfunction createUnixTimestampInSecondsFunc() {\n const { performance } = GLOBAL_OBJ ;\n // Some browser and environments don't have a performance or timeOrigin, so we fallback to\n // using Date.now() to compute the starting time.\n if (!performance?.now || !performance.timeOrigin) {\n return dateTimestampInSeconds;\n }\n\n const timeOrigin = performance.timeOrigin;\n\n // performance.now() is a monotonic clock, which means it starts at 0 when the process begins. To get the current\n // wall clock time (actual UNIX timestamp), we need to add the starting time origin and the current time elapsed.\n //\n // TODO: This does not account for the case where the monotonic clock that powers performance.now() drifts from the\n // wall clock time, which causes the returned timestamp to be inaccurate. We should investigate how to detect and\n // correct for this.\n // See: https://github.com/getsentry/sentry-javascript/issues/2590\n // See: https://github.com/mdn/content/issues/4713\n // See: https://dev.to/noamr/when-a-millisecond-is-not-a-millisecond-3h6\n return () => {\n return (timeOrigin + performance.now()) / ONE_SECOND_IN_MS;\n };\n}\n\nlet _cachedTimestampInSeconds;\n\n/**\n * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the\n * availability of the Performance API.\n *\n * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is\n * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The\n * skew can grow to arbitrary amounts like days, weeks or months.\n * See https://github.com/getsentry/sentry-javascript/issues/2590.\n */\nfunction timestampInSeconds() {\n // We store this in a closure so that we don't have to create a new function every time this is called.\n const func = _cachedTimestampInSeconds ?? (_cachedTimestampInSeconds = createUnixTimestampInSecondsFunc());\n return func();\n}\n\n/**\n * Cached result of getBrowserTimeOrigin.\n */\nlet cachedTimeOrigin;\n\n/**\n * Gets the time origin and the mode used to determine it.\n */\nfunction getBrowserTimeOrigin() {\n // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or\n // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin\n // data as reliable if they are within a reasonable threshold of the current time.\n\n const { performance } = GLOBAL_OBJ ;\n if (!performance?.now) {\n return [undefined, 'none'];\n }\n\n const threshold = 3600 * 1000;\n const performanceNow = performance.now();\n const dateNow = Date.now();\n\n // if timeOrigin isn't available set delta to threshold so it isn't used\n const timeOriginDelta = performance.timeOrigin\n ? Math.abs(performance.timeOrigin + performanceNow - dateNow)\n : threshold;\n const timeOriginIsReliable = timeOriginDelta < threshold;\n\n // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin\n // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing.\n // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always\n // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the\n // Date API.\n // eslint-disable-next-line deprecation/deprecation\n const navigationStart = performance.timing?.navigationStart;\n const hasNavigationStart = typeof navigationStart === 'number';\n // if navigationStart isn't available set delta to threshold so it isn't used\n const navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold;\n const navigationStartIsReliable = navigationStartDelta < threshold;\n\n if (timeOriginIsReliable || navigationStartIsReliable) {\n // Use the more reliable time origin\n if (timeOriginDelta <= navigationStartDelta) {\n return [performance.timeOrigin, 'timeOrigin'];\n } else {\n return [navigationStart, 'navigationStart'];\n }\n }\n\n // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date.\n return [dateNow, 'dateNow'];\n}\n\n/**\n * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the\n * performance API is available.\n */\nfunction browserPerformanceTimeOrigin() {\n if (!cachedTimeOrigin) {\n cachedTimeOrigin = getBrowserTimeOrigin();\n }\n\n return cachedTimeOrigin[0];\n}\n\nexport { browserPerformanceTimeOrigin, dateTimestampInSeconds, timestampInSeconds };\n//# sourceMappingURL=time.js.map\n","import { uuid4 } from './utils/misc.js';\nimport { timestampInSeconds } from './utils/time.js';\n\n/**\n * Creates a new `Session` object by setting certain default parameters. If optional @param context\n * is passed, the passed properties are applied to the session object.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns a new `Session` object\n */\nfunction makeSession(context) {\n // Both timestamp and started are in seconds since the UNIX epoch.\n const startingTime = timestampInSeconds();\n\n const session = {\n sid: uuid4(),\n init: true,\n timestamp: startingTime,\n started: startingTime,\n duration: 0,\n status: 'ok',\n errors: 0,\n ignoreDuration: false,\n toJSON: () => sessionToJSON(session),\n };\n\n if (context) {\n updateSession(session, context);\n }\n\n return session;\n}\n\n/**\n * Updates a session object with the properties passed in the context.\n *\n * Note that this function mutates the passed object and returns void.\n * (Had to do this instead of returning a new and updated session because closing and sending a session\n * makes an update to the session after it was passed to the sending logic.\n * @see Client.captureSession )\n *\n * @param session the `Session` to update\n * @param context the `SessionContext` holding the properties that should be updated in @param session\n */\n// eslint-disable-next-line complexity\nfunction updateSession(session, context = {}) {\n if (context.user) {\n if (!session.ipAddress && context.user.ip_address) {\n session.ipAddress = context.user.ip_address;\n }\n\n if (!session.did && !context.did) {\n session.did = context.user.id || context.user.email || context.user.username;\n }\n }\n\n session.timestamp = context.timestamp || timestampInSeconds();\n\n if (context.abnormal_mechanism) {\n session.abnormal_mechanism = context.abnormal_mechanism;\n }\n\n if (context.ignoreDuration) {\n session.ignoreDuration = context.ignoreDuration;\n }\n if (context.sid) {\n // Good enough uuid validation. — Kamil\n session.sid = context.sid.length === 32 ? context.sid : uuid4();\n }\n if (context.init !== undefined) {\n session.init = context.init;\n }\n if (!session.did && context.did) {\n session.did = `${context.did}`;\n }\n if (typeof context.started === 'number') {\n session.started = context.started;\n }\n if (session.ignoreDuration) {\n session.duration = undefined;\n } else if (typeof context.duration === 'number') {\n session.duration = context.duration;\n } else {\n const duration = session.timestamp - session.started;\n session.duration = duration >= 0 ? duration : 0;\n }\n if (context.release) {\n session.release = context.release;\n }\n if (context.environment) {\n session.environment = context.environment;\n }\n if (!session.ipAddress && context.ipAddress) {\n session.ipAddress = context.ipAddress;\n }\n if (!session.userAgent && context.userAgent) {\n session.userAgent = context.userAgent;\n }\n if (typeof context.errors === 'number') {\n session.errors = context.errors;\n }\n if (context.status) {\n session.status = context.status;\n }\n}\n\n/**\n * Closes a session by setting its status and updating the session object with it.\n * Internally calls `updateSession` to update the passed session object.\n *\n * Note that this function mutates the passed session (@see updateSession for explanation).\n *\n * @param session the `Session` object to be closed\n * @param status the `SessionStatus` with which the session was closed. If you don't pass a status,\n * this function will keep the previously set status, unless it was `'ok'` in which case\n * it is changed to `'exited'`.\n */\nfunction closeSession(session, status) {\n let context = {};\n if (status) {\n context = { status };\n } else if (session.status === 'ok') {\n context = { status: 'exited' };\n }\n\n updateSession(session, context);\n}\n\n/**\n * Serializes a passed session object to a JSON object with a slightly different structure.\n * This is necessary because the Sentry backend requires a slightly different schema of a session\n * than the one the JS SDKs use internally.\n *\n * @param session the session to be converted\n *\n * @returns a JSON object of the passed session\n */\nfunction sessionToJSON(session) {\n return {\n sid: `${session.sid}`,\n init: session.init,\n // Make sure that sec is converted to ms for date constructor\n started: new Date(session.started * 1000).toISOString(),\n timestamp: new Date(session.timestamp * 1000).toISOString(),\n status: session.status,\n errors: session.errors,\n did: typeof session.did === 'number' || typeof session.did === 'string' ? `${session.did}` : undefined,\n duration: session.duration,\n abnormal_mechanism: session.abnormal_mechanism,\n attrs: {\n release: session.release,\n environment: session.environment,\n ip_address: session.ipAddress,\n user_agent: session.userAgent,\n },\n };\n}\n\nexport { closeSession, makeSession, updateSession };\n//# sourceMappingURL=session.js.map\n","/**\n * Shallow merge two objects.\n * Does not mutate the passed in objects.\n * Undefined/empty values in the merge object will overwrite existing values.\n *\n * By default, this merges 2 levels deep.\n */\nfunction merge(initialObj, mergeObj, levels = 2) {\n // If the merge value is not an object, or we have no merge levels left,\n // we just set the value to the merge value\n if (!mergeObj || typeof mergeObj !== 'object' || levels <= 0) {\n return mergeObj;\n }\n\n // If the merge object is an empty object, and the initial object is not undefined, we return the initial object\n if (initialObj && Object.keys(mergeObj).length === 0) {\n return initialObj;\n }\n\n // Clone object\n const output = { ...initialObj };\n\n // Merge values into output, resursively\n for (const key in mergeObj) {\n if (Object.prototype.hasOwnProperty.call(mergeObj, key)) {\n output[key] = merge(output[key], mergeObj[key], levels - 1);\n }\n }\n\n return output;\n}\n\nexport { merge };\n//# sourceMappingURL=merge.js.map\n","import { uuid4 } from './misc.js';\n\n/**\n * Generate a random, valid trace ID.\n */\nfunction generateTraceId() {\n return uuid4();\n}\n\n/**\n * Generate a random, valid span ID.\n */\nfunction generateSpanId() {\n return uuid4().substring(16);\n}\n\nexport { generateSpanId, generateTraceId };\n//# sourceMappingURL=propagationContext.js.map\n","import { addNonEnumerableProperty } from './object.js';\n\nconst SCOPE_SPAN_FIELD = '_sentrySpan';\n\n/**\n * Set the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _setSpanForScope(scope, span) {\n if (span) {\n addNonEnumerableProperty(scope , SCOPE_SPAN_FIELD, span);\n } else {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (scope )[SCOPE_SPAN_FIELD];\n }\n}\n\n/**\n * Get the active span for a given scope.\n * NOTE: This should NOT be used directly, but is only used internally by the trace methods.\n */\nfunction _getSpanForScope(scope) {\n return scope[SCOPE_SPAN_FIELD];\n}\n\nexport { _getSpanForScope, _setSpanForScope };\n//# sourceMappingURL=spanOnScope.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { updateSession } from './session.js';\nimport { debug } from './utils/debug-logger.js';\nimport { isPlainObject } from './utils/is.js';\nimport { merge } from './utils/merge.js';\nimport { uuid4 } from './utils/misc.js';\nimport { generateTraceId } from './utils/propagationContext.js';\nimport { _setSpanForScope, _getSpanForScope } from './utils/spanOnScope.js';\nimport { truncate } from './utils/string.js';\nimport { dateTimestampInSeconds } from './utils/time.js';\n\n/**\n * Default value for maximum number of breadcrumbs added to an event.\n */\nconst DEFAULT_MAX_BREADCRUMBS = 100;\n\n/**\n * A context to be used for capturing an event.\n * This can either be a Scope, or a partial ScopeContext,\n * or a callback that receives the current scope and returns a new scope to use.\n */\n\n/**\n * Holds additional event information.\n */\nclass Scope {\n /** Flag if notifying is happening. */\n\n /** Callback for client to receive scope changes. */\n\n /** Callback list that will be called during event processing. */\n\n /** Array of breadcrumbs. */\n\n /** User */\n\n /** Tags */\n\n /** Attributes */\n\n /** Extra */\n\n /** Contexts */\n\n /** Attachments */\n\n /** Propagation Context for distributed tracing */\n\n /**\n * A place to stash data which is needed at some point in the SDK's event processing pipeline but which shouldn't get\n * sent to Sentry\n */\n\n /** Fingerprint */\n\n /** Severity */\n\n /**\n * Transaction Name\n *\n * IMPORTANT: The transaction name on the scope has nothing to do with root spans/transaction objects.\n * It's purpose is to assign a transaction to the scope that's added to non-transaction events.\n */\n\n /** Session */\n\n /** The client on this scope */\n\n /** Contains the last event id of a captured event. */\n\n // NOTE: Any field which gets added here should get added not only to the constructor but also to the `clone` method.\n\n constructor() {\n this._notifyingListeners = false;\n this._scopeListeners = [];\n this._eventProcessors = [];\n this._breadcrumbs = [];\n this._attachments = [];\n this._user = {};\n this._tags = {};\n this._attributes = {};\n this._extra = {};\n this._contexts = {};\n this._sdkProcessingMetadata = {};\n this._propagationContext = {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n /**\n * Clone all data from this scope into a new scope.\n */\n clone() {\n const newScope = new Scope();\n newScope._breadcrumbs = [...this._breadcrumbs];\n newScope._tags = { ...this._tags };\n newScope._attributes = { ...this._attributes };\n newScope._extra = { ...this._extra };\n newScope._contexts = { ...this._contexts };\n if (this._contexts.flags) {\n // We need to copy the `values` array so insertions on a cloned scope\n // won't affect the original array.\n newScope._contexts.flags = {\n values: [...this._contexts.flags.values],\n };\n }\n\n newScope._user = this._user;\n newScope._level = this._level;\n newScope._session = this._session;\n newScope._transactionName = this._transactionName;\n newScope._fingerprint = this._fingerprint;\n newScope._eventProcessors = [...this._eventProcessors];\n newScope._attachments = [...this._attachments];\n newScope._sdkProcessingMetadata = { ...this._sdkProcessingMetadata };\n newScope._propagationContext = { ...this._propagationContext };\n newScope._client = this._client;\n newScope._lastEventId = this._lastEventId;\n\n _setSpanForScope(newScope, _getSpanForScope(this));\n\n return newScope;\n }\n\n /**\n * Update the client assigned to this scope.\n * Note that not every scope will have a client assigned - isolation scopes & the global scope will generally not have a client,\n * as well as manually created scopes.\n */\n setClient(client) {\n this._client = client;\n }\n\n /**\n * Set the ID of the last captured error event.\n * This is generally only captured on the isolation scope.\n */\n setLastEventId(lastEventId) {\n this._lastEventId = lastEventId;\n }\n\n /**\n * Get the client assigned to this scope.\n */\n getClient() {\n return this._client ;\n }\n\n /**\n * Get the ID of the last captured error event.\n * This is generally only available on the isolation scope.\n */\n lastEventId() {\n return this._lastEventId;\n }\n\n /**\n * @inheritDoc\n */\n addScopeListener(callback) {\n this._scopeListeners.push(callback);\n }\n\n /**\n * Add an event processor that will be called before an event is sent.\n */\n addEventProcessor(callback) {\n this._eventProcessors.push(callback);\n return this;\n }\n\n /**\n * Set the user for this scope.\n * Set to `null` to unset the user.\n */\n setUser(user) {\n // If null is passed we want to unset everything, but still define keys,\n // so that later down in the pipeline any existing values are cleared.\n this._user = user || {\n email: undefined,\n id: undefined,\n ip_address: undefined,\n username: undefined,\n };\n\n if (this._session) {\n updateSession(this._session, { user });\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Get the user from this scope.\n */\n getUser() {\n return this._user;\n }\n\n /**\n * Set an object that will be merged into existing tags on the scope,\n * and will be sent as tags data with the event.\n */\n setTags(tags) {\n this._tags = {\n ...this._tags,\n ...tags,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set a single tag that will be sent as tags data with the event.\n */\n setTag(key, value) {\n return this.setTags({ [key]: value });\n }\n\n /**\n * Sets attributes onto the scope.\n *\n * These attributes are currently only applied to logs.\n * In the future, they will also be applied to metrics and spans.\n *\n * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for\n * more complex attribute types. We'll add this support in the future but already specify the wider type to\n * avoid a breaking change in the future.\n *\n * @param newAttributes - The attributes to set on the scope. You can either pass in key-value pairs, or\n * an object with a `value` and an optional `unit` (if applicable to your attribute).\n *\n * @example\n * ```typescript\n * scope.setAttributes({\n * is_admin: true,\n * payment_selection: 'credit_card',\n * render_duration: { value: 'render_duration', unit: 'ms' },\n * });\n * ```\n */\n setAttributes(newAttributes) {\n this._attributes = {\n ...this._attributes,\n ...newAttributes,\n };\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets an attribute onto the scope.\n *\n * These attributes are currently only applied to logs.\n * In the future, they will also be applied to metrics and spans.\n *\n * Important: For now, only strings, numbers and boolean attributes are supported, despite types allowing for\n * more complex attribute types. We'll add this support in the future but already specify the wider type to\n * avoid a breaking change in the future.\n *\n * @param key - The attribute key.\n * @param value - the attribute value. You can either pass in a raw value, or an attribute\n * object with a `value` and an optional `unit` (if applicable to your attribute).\n *\n * @example\n * ```typescript\n * scope.setAttribute('is_admin', true);\n * scope.setAttribute('render_duration', { value: 'render_duration', unit: 'ms' });\n * ```\n */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n setAttribute(\n key,\n value,\n ) {\n return this.setAttributes({ [key]: value });\n }\n\n /**\n * Removes the attribute with the given key from the scope.\n *\n * @param key - The attribute key.\n *\n * @example\n * ```typescript\n * scope.removeAttribute('is_admin');\n * ```\n */\n removeAttribute(key) {\n if (key in this._attributes) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n this._notifyScopeListeners();\n }\n return this;\n }\n\n /**\n * Set an object that will be merged into existing extra on the scope,\n * and will be sent as extra data with the event.\n */\n setExtras(extras) {\n this._extra = {\n ...this._extra,\n ...extras,\n };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set a single key:value extra entry that will be sent as extra data with the event.\n */\n setExtra(key, extra) {\n this._extra = { ...this._extra, [key]: extra };\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the fingerprint on the scope to send with the events.\n * @param {string[]} fingerprint Fingerprint to group events in Sentry.\n */\n setFingerprint(fingerprint) {\n this._fingerprint = fingerprint;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the level on the scope for future events.\n */\n setLevel(level) {\n this._level = level;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets the transaction name on the scope so that the name of e.g. taken server route or\n * the page location is attached to future events.\n *\n * IMPORTANT: Calling this function does NOT change the name of the currently active\n * root span. If you want to change the name of the active root span, use\n * `Sentry.updateSpanName(rootSpan, 'new name')` instead.\n *\n * By default, the SDK updates the scope's transaction name automatically on sensible\n * occasions, such as a page navigation or when handling a new request on the server.\n */\n setTransactionName(name) {\n this._transactionName = name;\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Sets context data with the given name.\n * Data passed as context will be normalized. You can also pass `null` to unset the context.\n * Note that context data will not be merged - calling `setContext` will overwrite an existing context with the same key.\n */\n setContext(key, context) {\n if (context === null) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._contexts[key];\n } else {\n this._contexts[key] = context;\n }\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Set the session for the scope.\n */\n setSession(session) {\n if (!session) {\n delete this._session;\n } else {\n this._session = session;\n }\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Get the session from the scope.\n */\n getSession() {\n return this._session;\n }\n\n /**\n * Updates the scope with provided data. Can work in three variations:\n * - plain object containing updatable attributes\n * - Scope instance that'll extract the attributes from\n * - callback function that'll receive the current scope as an argument and allow for modifications\n */\n update(captureContext) {\n if (!captureContext) {\n return this;\n }\n\n const scopeToMerge = typeof captureContext === 'function' ? captureContext(this) : captureContext;\n\n const scopeInstance =\n scopeToMerge instanceof Scope\n ? scopeToMerge.getScopeData()\n : isPlainObject(scopeToMerge)\n ? (captureContext )\n : undefined;\n\n const {\n tags,\n attributes,\n extra,\n user,\n contexts,\n level,\n fingerprint = [],\n propagationContext,\n } = scopeInstance || {};\n\n this._tags = { ...this._tags, ...tags };\n this._attributes = { ...this._attributes, ...attributes };\n this._extra = { ...this._extra, ...extra };\n this._contexts = { ...this._contexts, ...contexts };\n\n if (user && Object.keys(user).length) {\n this._user = user;\n }\n\n if (level) {\n this._level = level;\n }\n\n if (fingerprint.length) {\n this._fingerprint = fingerprint;\n }\n\n if (propagationContext) {\n this._propagationContext = propagationContext;\n }\n\n return this;\n }\n\n /**\n * Clears the current scope and resets its properties.\n * Note: The client will not be cleared.\n */\n clear() {\n // client is not cleared here on purpose!\n this._breadcrumbs = [];\n this._tags = {};\n this._attributes = {};\n this._extra = {};\n this._user = {};\n this._contexts = {};\n this._level = undefined;\n this._transactionName = undefined;\n this._fingerprint = undefined;\n this._session = undefined;\n _setSpanForScope(this, undefined);\n this._attachments = [];\n this.setPropagationContext({ traceId: generateTraceId(), sampleRand: Math.random() });\n\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Adds a breadcrumb to the scope.\n * By default, the last 100 breadcrumbs are kept.\n */\n addBreadcrumb(breadcrumb, maxBreadcrumbs) {\n const maxCrumbs = typeof maxBreadcrumbs === 'number' ? maxBreadcrumbs : DEFAULT_MAX_BREADCRUMBS;\n\n // No data has been changed, so don't notify scope listeners\n if (maxCrumbs <= 0) {\n return this;\n }\n\n const mergedBreadcrumb = {\n timestamp: dateTimestampInSeconds(),\n ...breadcrumb,\n // Breadcrumb messages can theoretically be infinitely large and they're held in memory so we truncate them not to leak (too much) memory\n message: breadcrumb.message ? truncate(breadcrumb.message, 2048) : breadcrumb.message,\n };\n\n this._breadcrumbs.push(mergedBreadcrumb);\n if (this._breadcrumbs.length > maxCrumbs) {\n this._breadcrumbs = this._breadcrumbs.slice(-maxCrumbs);\n this._client?.recordDroppedEvent('buffer_overflow', 'log_item');\n }\n\n this._notifyScopeListeners();\n\n return this;\n }\n\n /**\n * Get the last breadcrumb of the scope.\n */\n getLastBreadcrumb() {\n return this._breadcrumbs[this._breadcrumbs.length - 1];\n }\n\n /**\n * Clear all breadcrumbs from the scope.\n */\n clearBreadcrumbs() {\n this._breadcrumbs = [];\n this._notifyScopeListeners();\n return this;\n }\n\n /**\n * Add an attachment to the scope.\n */\n addAttachment(attachment) {\n this._attachments.push(attachment);\n return this;\n }\n\n /**\n * Clear all attachments from the scope.\n */\n clearAttachments() {\n this._attachments = [];\n return this;\n }\n\n /**\n * Get the data of this scope, which should be applied to an event during processing.\n */\n getScopeData() {\n return {\n breadcrumbs: this._breadcrumbs,\n attachments: this._attachments,\n contexts: this._contexts,\n tags: this._tags,\n attributes: this._attributes,\n extra: this._extra,\n user: this._user,\n level: this._level,\n fingerprint: this._fingerprint || [],\n eventProcessors: this._eventProcessors,\n propagationContext: this._propagationContext,\n sdkProcessingMetadata: this._sdkProcessingMetadata,\n transactionName: this._transactionName,\n span: _getSpanForScope(this),\n };\n }\n\n /**\n * Add data which will be accessible during event processing but won't get sent to Sentry.\n */\n setSDKProcessingMetadata(newData) {\n this._sdkProcessingMetadata = merge(this._sdkProcessingMetadata, newData, 2);\n return this;\n }\n\n /**\n * Add propagation context to the scope, used for distributed tracing\n */\n setPropagationContext(context) {\n this._propagationContext = context;\n return this;\n }\n\n /**\n * Get propagation context from the scope, used for distributed tracing\n */\n getPropagationContext() {\n return this._propagationContext;\n }\n\n /**\n * Capture an exception for this scope.\n *\n * @returns {string} The id of the captured Sentry event.\n */\n captureException(exception, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.warn('No client configured on scope - will not capture exception!');\n return eventId;\n }\n\n const syntheticException = new Error('Sentry syntheticException');\n\n this._client.captureException(\n exception,\n {\n originalException: exception,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a message for this scope.\n *\n * @returns {string} The id of the captured message.\n */\n captureMessage(message, level, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.warn('No client configured on scope - will not capture message!');\n return eventId;\n }\n\n const syntheticException = hint?.syntheticException ?? new Error(message);\n\n this._client.captureMessage(\n message,\n level,\n {\n originalException: message,\n syntheticException,\n ...hint,\n event_id: eventId,\n },\n this,\n );\n\n return eventId;\n }\n\n /**\n * Capture a Sentry event for this scope.\n *\n * @returns {string} The id of the captured event.\n */\n captureEvent(event, hint) {\n const eventId = hint?.event_id || uuid4();\n\n if (!this._client) {\n DEBUG_BUILD && debug.warn('No client configured on scope - will not capture event!');\n return eventId;\n }\n\n this._client.captureEvent(event, { ...hint, event_id: eventId }, this);\n\n return eventId;\n }\n\n /**\n * This will be called on every set call.\n */\n _notifyScopeListeners() {\n // We need this check for this._notifyingListeners to be able to work on scope during updates\n // If this check is not here we'll produce endless recursion when something is done with the scope\n // during the callback.\n if (!this._notifyingListeners) {\n this._notifyingListeners = true;\n this._scopeListeners.forEach(callback => {\n callback(this);\n });\n this._notifyingListeners = false;\n }\n }\n}\n\nexport { Scope };\n//# sourceMappingURL=scope.js.map\n","import { getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\n\n/** Get the default current scope. */\nfunction getDefaultCurrentScope() {\n return getGlobalSingleton('defaultCurrentScope', () => new Scope());\n}\n\n/** Get the default isolation scope. */\nfunction getDefaultIsolationScope() {\n return getGlobalSingleton('defaultIsolationScope', () => new Scope());\n}\n\nexport { getDefaultCurrentScope, getDefaultIsolationScope };\n//# sourceMappingURL=defaultScopes.js.map\n","import { getDefaultCurrentScope, getDefaultIsolationScope } from '../defaultScopes.js';\nimport { Scope } from '../scope.js';\nimport { isThenable } from '../utils/is.js';\nimport { getMainCarrier, getSentryCarrier } from '../carrier.js';\n\n/**\n * This is an object that holds a stack of scopes.\n */\nclass AsyncContextStack {\n\n constructor(scope, isolationScope) {\n let assignedScope;\n if (!scope) {\n assignedScope = new Scope();\n } else {\n assignedScope = scope;\n }\n\n let assignedIsolationScope;\n if (!isolationScope) {\n assignedIsolationScope = new Scope();\n } else {\n assignedIsolationScope = isolationScope;\n }\n\n // scope stack for domains or the process\n this._stack = [{ scope: assignedScope }];\n this._isolationScope = assignedIsolationScope;\n }\n\n /**\n * Fork a scope for the stack.\n */\n withScope(callback) {\n const scope = this._pushScope();\n\n let maybePromiseResult;\n try {\n maybePromiseResult = callback(scope);\n } catch (e) {\n this._popScope();\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n // @ts-expect-error - isThenable returns the wrong type\n return maybePromiseResult.then(\n res => {\n this._popScope();\n return res;\n },\n e => {\n this._popScope();\n throw e;\n },\n );\n }\n\n this._popScope();\n return maybePromiseResult;\n }\n\n /**\n * Get the client of the stack.\n */\n getClient() {\n return this.getStackTop().client ;\n }\n\n /**\n * Returns the scope of the top stack.\n */\n getScope() {\n return this.getStackTop().scope;\n }\n\n /**\n * Get the isolation scope for the stack.\n */\n getIsolationScope() {\n return this._isolationScope;\n }\n\n /**\n * Returns the topmost scope layer in the order domain > local > process.\n */\n getStackTop() {\n return this._stack[this._stack.length - 1] ;\n }\n\n /**\n * Push a scope to the stack.\n */\n _pushScope() {\n // We want to clone the content of prev scope\n const scope = this.getScope().clone();\n this._stack.push({\n client: this.getClient(),\n scope,\n });\n return scope;\n }\n\n /**\n * Pop a scope from the stack.\n */\n _popScope() {\n if (this._stack.length <= 1) return false;\n return !!this._stack.pop();\n }\n}\n\n/**\n * Get the global async context stack.\n * This will be removed during the v8 cycle and is only here to make migration easier.\n */\nfunction getAsyncContextStack() {\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n\n return (sentry.stack = sentry.stack || new AsyncContextStack(getDefaultCurrentScope(), getDefaultIsolationScope()));\n}\n\nfunction withScope(callback) {\n return getAsyncContextStack().withScope(callback);\n}\n\nfunction withSetScope(scope, callback) {\n const stack = getAsyncContextStack();\n return stack.withScope(() => {\n stack.getStackTop().scope = scope;\n return callback(scope);\n });\n}\n\nfunction withIsolationScope(callback) {\n return getAsyncContextStack().withScope(() => {\n return callback(getAsyncContextStack().getIsolationScope());\n });\n}\n\n/**\n * Get the stack-based async context strategy.\n */\nfunction getStackAsyncContextStrategy() {\n return {\n withIsolationScope,\n withScope,\n withSetScope,\n withSetIsolationScope: (_isolationScope, callback) => {\n return withIsolationScope(callback);\n },\n getCurrentScope: () => getAsyncContextStack().getScope(),\n getIsolationScope: () => getAsyncContextStack().getIsolationScope(),\n };\n}\n\nexport { AsyncContextStack, getStackAsyncContextStrategy };\n//# sourceMappingURL=stackStrategy.js.map\n","import { getMainCarrier, getSentryCarrier } from '../carrier.js';\nimport { getStackAsyncContextStrategy } from './stackStrategy.js';\n\n/**\n * @private Private API with no semver guarantees!\n *\n * Sets the global async context strategy\n */\nfunction setAsyncContextStrategy(strategy) {\n // Get main carrier (global for every environment)\n const registry = getMainCarrier();\n const sentry = getSentryCarrier(registry);\n sentry.acs = strategy;\n}\n\n/**\n * Get the current async context strategy.\n * If none has been setup, the default will be used.\n */\nfunction getAsyncContextStrategy(carrier) {\n const sentry = getSentryCarrier(carrier);\n\n if (sentry.acs) {\n return sentry.acs;\n }\n\n // Otherwise, use the default one (stack)\n return getStackAsyncContextStrategy();\n}\n\nexport { getAsyncContextStrategy, setAsyncContextStrategy };\n//# sourceMappingURL=index.js.map\n","import { getAsyncContextStrategy } from './asyncContext/index.js';\nimport { getMainCarrier, getGlobalSingleton } from './carrier.js';\nimport { Scope } from './scope.js';\nimport { generateSpanId } from './utils/propagationContext.js';\n\n/**\n * Get the currently active scope.\n */\nfunction getCurrentScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getCurrentScope();\n}\n\n/**\n * Get the currently active isolation scope.\n * The isolation scope is active for the current execution context.\n */\nfunction getIsolationScope() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n return acs.getIsolationScope();\n}\n\n/**\n * Get the global scope.\n * This scope is applied to _all_ events.\n */\nfunction getGlobalScope() {\n return getGlobalSingleton('globalScope', () => new Scope());\n}\n\n/**\n * Creates a new scope with and executes the given operation within.\n * The scope is automatically removed once the operation\n * finishes or throws.\n */\n\n/**\n * Either creates a new active scope, or sets the given scope as active scope in the given callback.\n */\nfunction withScope(\n ...rest\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [scope, callback] = rest;\n\n if (!scope) {\n return acs.withScope(callback);\n }\n\n return acs.withSetScope(scope, callback);\n }\n\n return acs.withScope(rest[0]);\n}\n\n/**\n * Attempts to fork the current isolation scope and the current scope based on the current async context strategy. If no\n * async context strategy is set, the isolation scope and the current scope will not be forked (this is currently the\n * case, for example, in the browser).\n *\n * Usage of this function in environments without async context strategy is discouraged and may lead to unexpected behaviour.\n *\n * This function is intended for Sentry SDK and SDK integration development. It is not recommended to be used in \"normal\"\n * applications directly because it comes with pitfalls. Use at your own risk!\n */\n\n/**\n * Either creates a new active isolation scope, or sets the given isolation scope as active scope in the given callback.\n */\nfunction withIsolationScope(\n ...rest\n\n) {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n\n // If a scope is defined, we want to make this the active scope instead of the default one\n if (rest.length === 2) {\n const [isolationScope, callback] = rest;\n\n if (!isolationScope) {\n return acs.withIsolationScope(callback);\n }\n\n return acs.withSetIsolationScope(isolationScope, callback);\n }\n\n return acs.withIsolationScope(rest[0]);\n}\n\n/**\n * Get the currently active client.\n */\nfunction getClient() {\n return getCurrentScope().getClient();\n}\n\n/**\n * Get a trace context for the given scope.\n */\nfunction getTraceContextFromScope(scope) {\n const propagationContext = scope.getPropagationContext();\n\n const { traceId, parentSpanId, propagationSpanId } = propagationContext;\n\n const traceContext = {\n trace_id: traceId,\n span_id: propagationSpanId || generateSpanId(),\n };\n\n if (parentSpanId) {\n traceContext.parent_span_id = parentSpanId;\n }\n\n return traceContext;\n}\n\nexport { getClient, getCurrentScope, getGlobalScope, getIsolationScope, getTraceContextFromScope, withIsolationScope, withScope };\n//# sourceMappingURL=currentScopes.js.map\n","/**\n * Use this attribute to represent the source of a span.\n * Should be one of: custom, url, route, view, component, task, unknown\n *\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SOURCE = 'sentry.source';\n\n/**\n * Attributes that holds the sample rate that was locally applied to a span.\n * If this attribute is not defined, it means that the span inherited a sampling decision.\n *\n * NOTE: Is only defined on root spans.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE = 'sentry.sample_rate';\n\n/**\n * Attribute holding the sample rate of the previous trace.\n * This is used to sample consistently across subsequent traces in the browser SDK.\n *\n * Note: Only defined on root spans, if opted into consistent sampling\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE = 'sentry.previous_trace_sample_rate';\n\n/**\n * Use this attribute to represent the operation of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_OP = 'sentry.op';\n\n/**\n * Use this attribute to represent the origin of a span.\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN = 'sentry.origin';\n\n/** The reason why an idle span finished. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON = 'sentry.idle_span_finish_reason';\n\n/** The unit of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT = 'sentry.measurement_unit';\n\n/** The value of a measurement, which may be stored as a TimedEvent. */\nconst SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE = 'sentry.measurement_value';\n\n/**\n * A custom span name set by users guaranteed to be taken over any automatically\n * inferred name. This attribute is removed before the span is sent.\n *\n * @internal only meant for internal SDK usage\n * @hidden\n */\nconst SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME = 'sentry.custom_span_name';\n\n/**\n * The id of the profile that this span occurred in.\n */\nconst SEMANTIC_ATTRIBUTE_PROFILE_ID = 'sentry.profile_id';\n\nconst SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME = 'sentry.exclusive_time';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_HIT = 'cache.hit';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_KEY = 'cache.key';\n\nconst SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE = 'cache.item_size';\n\n/** TODO: Remove these once we update to latest semantic conventions */\nconst SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD = 'http.request.method';\nconst SEMANTIC_ATTRIBUTE_URL_FULL = 'url.full';\n\n/**\n * A span link attribute to mark the link as a special span link.\n *\n * Known values:\n * - `previous_trace`: The span links to the frontend root span of the previous trace.\n * - `next_trace`: The span links to the frontend root span of the next trace. (Not set by the SDK)\n *\n * Other values may be set as appropriate.\n * @see https://develop.sentry.dev/sdk/telemetry/traces/span-links/#link-types\n */\nconst SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE = 'sentry.link.type';\n\nexport { SEMANTIC_ATTRIBUTE_CACHE_HIT, SEMANTIC_ATTRIBUTE_CACHE_ITEM_SIZE, SEMANTIC_ATTRIBUTE_CACHE_KEY, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_URL_FULL, SEMANTIC_LINK_ATTRIBUTE_LINK_TYPE };\n//# sourceMappingURL=semanticAttributes.js.map\n","const SPAN_STATUS_UNSET = 0;\nconst SPAN_STATUS_OK = 1;\nconst SPAN_STATUS_ERROR = 2;\n\n/**\n * Converts a HTTP status code into a sentry status with a message.\n *\n * @param httpStatus The HTTP response status code.\n * @returns The span status or internal_error.\n */\n// https://develop.sentry.dev/sdk/event-payloads/span/\nfunction getSpanStatusFromHttpCode(httpStatus) {\n if (httpStatus < 400 && httpStatus >= 100) {\n return { code: SPAN_STATUS_OK };\n }\n\n if (httpStatus >= 400 && httpStatus < 500) {\n switch (httpStatus) {\n case 401:\n return { code: SPAN_STATUS_ERROR, message: 'unauthenticated' };\n case 403:\n return { code: SPAN_STATUS_ERROR, message: 'permission_denied' };\n case 404:\n return { code: SPAN_STATUS_ERROR, message: 'not_found' };\n case 409:\n return { code: SPAN_STATUS_ERROR, message: 'already_exists' };\n case 413:\n return { code: SPAN_STATUS_ERROR, message: 'failed_precondition' };\n case 429:\n return { code: SPAN_STATUS_ERROR, message: 'resource_exhausted' };\n case 499:\n return { code: SPAN_STATUS_ERROR, message: 'cancelled' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'invalid_argument' };\n }\n }\n\n if (httpStatus >= 500 && httpStatus < 600) {\n switch (httpStatus) {\n case 501:\n return { code: SPAN_STATUS_ERROR, message: 'unimplemented' };\n case 503:\n return { code: SPAN_STATUS_ERROR, message: 'unavailable' };\n case 504:\n return { code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' };\n default:\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n }\n }\n\n return { code: SPAN_STATUS_ERROR, message: 'internal_error' };\n}\n\n/**\n * Sets the Http status attributes on the current span based on the http code.\n * Additionally, the span's status is updated, depending on the http code.\n */\nfunction setHttpStatus(span, httpStatus) {\n span.setAttribute('http.response.status_code', httpStatus);\n\n const spanStatus = getSpanStatusFromHttpCode(httpStatus);\n if (spanStatus.message !== 'unknown_error') {\n span.setStatus(spanStatus);\n }\n}\n\nexport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, SPAN_STATUS_UNSET, getSpanStatusFromHttpCode, setHttpStatus };\n//# sourceMappingURL=spanstatus.js.map\n","import { addNonEnumerableProperty } from '../utils/object.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\n\nconst SCOPE_ON_START_SPAN_FIELD = '_sentryScope';\nconst ISOLATION_SCOPE_ON_START_SPAN_FIELD = '_sentryIsolationScope';\n\n/** Wrap a scope with a WeakRef if available, falling back to a direct scope. */\nfunction wrapScopeWithWeakRef(scope) {\n try {\n // @ts-expect-error - WeakRef is not available in all environments\n const WeakRefClass = GLOBAL_OBJ.WeakRef;\n if (typeof WeakRefClass === 'function') {\n return new WeakRefClass(scope);\n }\n } catch {\n // WeakRef not available or failed to create\n // We'll fall back to a direct scope\n }\n\n return scope;\n}\n\n/** Try to unwrap a scope from a potential WeakRef wrapper. */\nfunction unwrapScopeFromWeakRef(scopeRef) {\n if (!scopeRef) {\n return undefined;\n }\n\n if (typeof scopeRef === 'object' && 'deref' in scopeRef && typeof scopeRef.deref === 'function') {\n try {\n return scopeRef.deref();\n } catch {\n return undefined;\n }\n }\n\n // Fallback to a direct scope\n return scopeRef ;\n}\n\n/** Store the scope & isolation scope for a span, which can the be used when it is finished. */\nfunction setCapturedScopesOnSpan(span, scope, isolationScope) {\n if (span) {\n addNonEnumerableProperty(span, ISOLATION_SCOPE_ON_START_SPAN_FIELD, wrapScopeWithWeakRef(isolationScope));\n // We don't wrap the scope with a WeakRef here because webkit aggressively garbage collects\n // and scopes are not held in memory for long periods of time.\n addNonEnumerableProperty(span, SCOPE_ON_START_SPAN_FIELD, scope);\n }\n}\n\n/**\n * Grabs the scope and isolation scope off a span that were active when the span was started.\n * If WeakRef was used and scopes have been garbage collected, returns undefined for those scopes.\n */\nfunction getCapturedScopesOnSpan(span) {\n const spanWithScopes = span ;\n\n return {\n scope: spanWithScopes[SCOPE_ON_START_SPAN_FIELD],\n isolationScope: unwrapScopeFromWeakRef(spanWithScopes[ISOLATION_SCOPE_ON_START_SPAN_FIELD]),\n };\n}\n\nexport { getCapturedScopesOnSpan, setCapturedScopesOnSpan };\n//# sourceMappingURL=utils.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isString } from './is.js';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX = 'sentry-';\n\nconst SENTRY_BAGGAGE_KEY_PREFIX_REGEX = /^sentry-/;\n\n/**\n * Max length of a serialized baggage string\n *\n * https://www.w3.org/TR/baggage/#limits\n */\nconst MAX_BAGGAGE_STRING_LENGTH = 8192;\n\n/**\n * Takes a baggage header and turns it into Dynamic Sampling Context, by extracting all the \"sentry-\" prefixed values\n * from it.\n *\n * @param baggageHeader A very bread definition of a baggage header as it might appear in various frameworks.\n * @returns The Dynamic Sampling Context that was found on `baggageHeader`, if there was any, `undefined` otherwise.\n */\nfunction baggageHeaderToDynamicSamplingContext(\n // Very liberal definition of what any incoming header might look like\n baggageHeader,\n) {\n const baggageObject = parseBaggageHeader(baggageHeader);\n\n if (!baggageObject) {\n return undefined;\n }\n\n // Read all \"sentry-\" prefixed values out of the baggage object and put it onto a dynamic sampling context object.\n const dynamicSamplingContext = Object.entries(baggageObject).reduce((acc, [key, value]) => {\n if (key.match(SENTRY_BAGGAGE_KEY_PREFIX_REGEX)) {\n const nonPrefixedKey = key.slice(SENTRY_BAGGAGE_KEY_PREFIX.length);\n acc[nonPrefixedKey] = value;\n }\n return acc;\n }, {});\n\n // Only return a dynamic sampling context object if there are keys in it.\n // A keyless object means there were no sentry values on the header, which means that there is no DSC.\n if (Object.keys(dynamicSamplingContext).length > 0) {\n return dynamicSamplingContext ;\n } else {\n return undefined;\n }\n}\n\n/**\n * Turns a Dynamic Sampling Object into a baggage header by prefixing all the keys on the object with \"sentry-\".\n *\n * @param dynamicSamplingContext The Dynamic Sampling Context to turn into a header. For convenience and compatibility\n * with the `getDynamicSamplingContext` method on the Transaction class ,this argument can also be `undefined`. If it is\n * `undefined` the function will return `undefined`.\n * @returns a baggage header, created from `dynamicSamplingContext`, or `undefined` either if `dynamicSamplingContext`\n * was `undefined`, or if `dynamicSamplingContext` didn't contain any values.\n */\nfunction dynamicSamplingContextToSentryBaggageHeader(\n // this also takes undefined for convenience and bundle size in other places\n dynamicSamplingContext,\n) {\n if (!dynamicSamplingContext) {\n return undefined;\n }\n\n // Prefix all DSC keys with \"sentry-\" and put them into a new object\n const sentryPrefixedDSC = Object.entries(dynamicSamplingContext).reduce(\n (acc, [dscKey, dscValue]) => {\n if (dscValue) {\n acc[`${SENTRY_BAGGAGE_KEY_PREFIX}${dscKey}`] = dscValue;\n }\n return acc;\n },\n {},\n );\n\n return objectToBaggageHeader(sentryPrefixedDSC);\n}\n\n/**\n * Take a baggage header and parse it into an object.\n */\nfunction parseBaggageHeader(\n baggageHeader,\n) {\n if (!baggageHeader || (!isString(baggageHeader) && !Array.isArray(baggageHeader))) {\n return undefined;\n }\n\n if (Array.isArray(baggageHeader)) {\n // Combine all baggage headers into one object containing the baggage values so we can later read the Sentry-DSC-values from it\n return baggageHeader.reduce((acc, curr) => {\n const currBaggageObject = baggageHeaderToObject(curr);\n Object.entries(currBaggageObject).forEach(([key, value]) => {\n acc[key] = value;\n });\n return acc;\n }, {});\n }\n\n return baggageHeaderToObject(baggageHeader);\n}\n\n/**\n * Will parse a baggage header, which is a simple key-value map, into a flat object.\n *\n * @param baggageHeader The baggage header to parse.\n * @returns a flat object containing all the key-value pairs from `baggageHeader`.\n */\nfunction baggageHeaderToObject(baggageHeader) {\n return baggageHeader\n .split(',')\n .map(baggageEntry => {\n const eqIdx = baggageEntry.indexOf('=');\n if (eqIdx === -1) {\n // Likely an invalid entry\n return [];\n }\n const key = baggageEntry.slice(0, eqIdx);\n const value = baggageEntry.slice(eqIdx + 1);\n return [key, value].map(keyOrValue => {\n try {\n return decodeURIComponent(keyOrValue.trim());\n } catch {\n // We ignore errors here, e.g. if the value cannot be URL decoded.\n // This will then be skipped in the next step\n return;\n }\n });\n })\n .reduce((acc, [key, value]) => {\n if (key && value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\n/**\n * Turns a flat object (key-value pairs) into a baggage header, which is also just key-value pairs.\n *\n * @param object The object to turn into a baggage header.\n * @returns a baggage header string, or `undefined` if the object didn't have any values, since an empty baggage header\n * is not spec compliant.\n */\nfunction objectToBaggageHeader(object) {\n if (Object.keys(object).length === 0) {\n // An empty baggage header is not spec compliant: We return undefined.\n return undefined;\n }\n\n return Object.entries(object).reduce((baggageHeader, [objectKey, objectValue], currentIndex) => {\n const baggageEntry = `${encodeURIComponent(objectKey)}=${encodeURIComponent(objectValue)}`;\n const newBaggageHeader = currentIndex === 0 ? baggageEntry : `${baggageHeader},${baggageEntry}`;\n if (newBaggageHeader.length > MAX_BAGGAGE_STRING_LENGTH) {\n DEBUG_BUILD &&\n debug.warn(\n `Not adding key: ${objectKey} with val: ${objectValue} to baggage header due to exceeding baggage size limits.`,\n );\n return baggageHeader;\n } else {\n return newBaggageHeader;\n }\n }, '');\n}\n\nexport { MAX_BAGGAGE_STRING_LENGTH, SENTRY_BAGGAGE_KEY_PREFIX, SENTRY_BAGGAGE_KEY_PREFIX_REGEX, baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader, objectToBaggageHeader, parseBaggageHeader };\n//# sourceMappingURL=baggage.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { consoleSandbox, debug } from './debug-logger.js';\n\n/** Regular expression used to extract org ID from a DSN host. */\nconst ORG_ID_REGEX = /^o(\\d+)\\./;\n\n/** Regular expression used to parse a Dsn. */\nconst DSN_REGEX = /^(?:(\\w+):)\\/\\/(?:(\\w+)(?::(\\w+)?)?@)([\\w.-]+)(?::(\\d+))?\\/(.+)/;\n\nfunction isValidProtocol(protocol) {\n return protocol === 'http' || protocol === 'https';\n}\n\n/**\n * Renders the string representation of this Dsn.\n *\n * By default, this will render the public representation without the password\n * component. To get the deprecated private representation, set `withPassword`\n * to true.\n *\n * @param withPassword When set to true, the password will be included.\n */\nfunction dsnToString(dsn, withPassword = false) {\n const { host, path, pass, port, projectId, protocol, publicKey } = dsn;\n return (\n `${protocol}://${publicKey}${withPassword && pass ? `:${pass}` : ''}` +\n `@${host}${port ? `:${port}` : ''}/${path ? `${path}/` : path}${projectId}`\n );\n}\n\n/**\n * Parses a Dsn from a given string.\n *\n * @param str A Dsn as string\n * @returns Dsn as DsnComponents or undefined if @param str is not a valid DSN string\n */\nfunction dsnFromString(str) {\n const match = DSN_REGEX.exec(str);\n\n if (!match) {\n // This should be logged to the console\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.error(`Invalid Sentry Dsn: ${str}`);\n });\n return undefined;\n }\n\n const [protocol, publicKey, pass = '', host = '', port = '', lastPath = ''] = match.slice(1);\n let path = '';\n let projectId = lastPath;\n\n const split = projectId.split('/');\n if (split.length > 1) {\n path = split.slice(0, -1).join('/');\n projectId = split.pop() ;\n }\n\n if (projectId) {\n const projectMatch = projectId.match(/^\\d+/);\n if (projectMatch) {\n projectId = projectMatch[0];\n }\n }\n\n return dsnFromComponents({ host, pass, path, projectId, port, protocol: protocol , publicKey });\n}\n\nfunction dsnFromComponents(components) {\n return {\n protocol: components.protocol,\n publicKey: components.publicKey || '',\n pass: components.pass || '',\n host: components.host,\n port: components.port || '',\n path: components.path || '',\n projectId: components.projectId,\n };\n}\n\nfunction validateDsn(dsn) {\n if (!DEBUG_BUILD) {\n return true;\n }\n\n const { port, projectId, protocol } = dsn;\n\n const requiredComponents = ['protocol', 'publicKey', 'host', 'projectId'];\n const hasMissingRequiredComponent = requiredComponents.find(component => {\n if (!dsn[component]) {\n debug.error(`Invalid Sentry Dsn: ${component} missing`);\n return true;\n }\n return false;\n });\n\n if (hasMissingRequiredComponent) {\n return false;\n }\n\n if (!projectId.match(/^\\d+$/)) {\n debug.error(`Invalid Sentry Dsn: Invalid projectId ${projectId}`);\n return false;\n }\n\n if (!isValidProtocol(protocol)) {\n debug.error(`Invalid Sentry Dsn: Invalid protocol ${protocol}`);\n return false;\n }\n\n if (port && isNaN(parseInt(port, 10))) {\n debug.error(`Invalid Sentry Dsn: Invalid port ${port}`);\n return false;\n }\n\n return true;\n}\n\n/**\n * Extract the org ID from a DSN host.\n *\n * @param host The host from a DSN\n * @returns The org ID if found, undefined otherwise\n */\nfunction extractOrgIdFromDsnHost(host) {\n const match = host.match(ORG_ID_REGEX);\n\n return match?.[1];\n}\n\n/**\n * Returns the organization ID of the client.\n *\n * The organization ID is extracted from the DSN. If the client options include a `orgId`, this will always take precedence.\n */\nfunction extractOrgIdFromClient(client) {\n const options = client.getOptions();\n\n const { host } = client.getDsn() || {};\n\n let org_id;\n\n if (options.orgId) {\n org_id = String(options.orgId);\n } else if (host) {\n org_id = extractOrgIdFromDsnHost(host);\n }\n\n return org_id;\n}\n\n/**\n * Creates a valid Sentry Dsn object, identifying a Sentry instance and project.\n * @returns a valid DsnComponents object or `undefined` if @param from is an invalid DSN source\n */\nfunction makeDsn(from) {\n const components = typeof from === 'string' ? dsnFromString(from) : dsnFromComponents(from);\n if (!components || !validateDsn(components)) {\n return undefined;\n }\n return components;\n}\n\nexport { dsnFromString, dsnToString, extractOrgIdFromClient, extractOrgIdFromDsnHost, makeDsn };\n//# sourceMappingURL=dsn.js.map\n","/**\n * Parse a sample rate from a given value.\n * This will either return a boolean or number sample rate, if the sample rate is valid (between 0 and 1).\n * If a string is passed, we try to convert it to a number.\n *\n * Any invalid sample rate will return `undefined`.\n */\nfunction parseSampleRate(sampleRate) {\n if (typeof sampleRate === 'boolean') {\n return Number(sampleRate);\n }\n\n const rate = typeof sampleRate === 'string' ? parseFloat(sampleRate) : sampleRate;\n if (typeof rate !== 'number' || isNaN(rate) || rate < 0 || rate > 1) {\n return undefined;\n }\n\n return rate;\n}\n\nexport { parseSampleRate };\n//# sourceMappingURL=parseSampleRate.js.map\n","import { debug } from './debug-logger.js';\nimport { baggageHeaderToDynamicSamplingContext } from './baggage.js';\nimport { extractOrgIdFromClient } from './dsn.js';\nimport { parseSampleRate } from './parseSampleRate.js';\nimport { generateTraceId, generateSpanId } from './propagationContext.js';\n\n// eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor -- RegExp is used for readability here\nconst TRACEPARENT_REGEXP = new RegExp(\n '^[ \\\\t]*' + // whitespace\n '([0-9a-f]{32})?' + // trace_id\n '-?([0-9a-f]{16})?' + // span_id\n '-?([01])?' + // sampled\n '[ \\\\t]*$', // whitespace\n);\n\n/**\n * Extract transaction context data from a `sentry-trace` header.\n *\n * This is terrible naming but the function has nothing to do with the W3C traceparent header.\n * It can only parse the `sentry-trace` header and extract the \"trace parent\" data.\n *\n * @param traceparent Traceparent string\n *\n * @returns Object containing data from the header, or undefined if traceparent string is malformed\n */\nfunction extractTraceparentData(traceparent) {\n if (!traceparent) {\n return undefined;\n }\n\n const matches = traceparent.match(TRACEPARENT_REGEXP);\n if (!matches) {\n return undefined;\n }\n\n let parentSampled;\n if (matches[3] === '1') {\n parentSampled = true;\n } else if (matches[3] === '0') {\n parentSampled = false;\n }\n\n return {\n traceId: matches[1],\n parentSampled,\n parentSpanId: matches[2],\n };\n}\n\n/**\n * Create a propagation context from incoming headers or\n * creates a minimal new one if the headers are undefined.\n */\nfunction propagationContextFromHeaders(\n sentryTrace,\n baggage,\n) {\n const traceparentData = extractTraceparentData(sentryTrace);\n const dynamicSamplingContext = baggageHeaderToDynamicSamplingContext(baggage);\n\n if (!traceparentData?.traceId) {\n return {\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n };\n }\n\n const sampleRand = getSampleRandFromTraceparentAndDsc(traceparentData, dynamicSamplingContext);\n\n // The sample_rand on the DSC needs to be generated based on traceparent + baggage.\n if (dynamicSamplingContext) {\n dynamicSamplingContext.sample_rand = sampleRand.toString();\n }\n\n const { traceId, parentSpanId, parentSampled } = traceparentData;\n\n return {\n traceId,\n parentSpanId,\n sampled: parentSampled,\n dsc: dynamicSamplingContext || {}, // If we have traceparent data but no DSC it means we are not head of trace and we must freeze it\n sampleRand,\n };\n}\n\n/**\n * Create sentry-trace header from span context values.\n */\nfunction generateSentryTraceHeader(\n traceId = generateTraceId(),\n spanId = generateSpanId(),\n sampled,\n) {\n let sampledString = '';\n if (sampled !== undefined) {\n sampledString = sampled ? '-1' : '-0';\n }\n return `${traceId}-${spanId}${sampledString}`;\n}\n\n/**\n * Creates a W3C traceparent header from the given trace and span ids.\n */\nfunction generateTraceparentHeader(\n traceId = generateTraceId(),\n spanId = generateSpanId(),\n sampled,\n) {\n return `00-${traceId}-${spanId}-${sampled ? '01' : '00'}`;\n}\n\n/**\n * Given any combination of an incoming trace, generate a sample rand based on its defined semantics.\n *\n * Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n */\nfunction getSampleRandFromTraceparentAndDsc(\n traceparentData,\n dsc,\n) {\n // When there is an incoming sample rand use it.\n const parsedSampleRand = parseSampleRate(dsc?.sample_rand);\n if (parsedSampleRand !== undefined) {\n return parsedSampleRand;\n }\n\n // Otherwise, if there is an incoming sampling decision + sample rate, generate a sample rand that would lead to the same sampling decision.\n const parsedSampleRate = parseSampleRate(dsc?.sample_rate);\n if (parsedSampleRate && traceparentData?.parentSampled !== undefined) {\n return traceparentData.parentSampled\n ? // Returns a sample rand with positive sampling decision [0, sampleRate)\n Math.random() * parsedSampleRate\n : // Returns a sample rand with negative sampling decision [sampleRate, 1)\n parsedSampleRate + Math.random() * (1 - parsedSampleRate);\n } else {\n // If nothing applies, return a random sample rand.\n return Math.random();\n }\n}\n\n/**\n * Determines whether a new trace should be continued based on the provided baggage org ID and the client's `strictTraceContinuation` option.\n * If the trace should not be continued, a new trace will be started.\n *\n * The result is dependent on the `strictTraceContinuation` option in the client.\n * See https://develop.sentry.dev/sdk/telemetry/traces/#stricttracecontinuation\n */\nfunction shouldContinueTrace(client, baggageOrgId) {\n const clientOrgId = extractOrgIdFromClient(client);\n\n // Case: baggage orgID and Client orgID don't match - always start new trace\n if (baggageOrgId && clientOrgId && baggageOrgId !== clientOrgId) {\n debug.log(\n `Won't continue trace because org IDs don't match (incoming baggage: ${baggageOrgId}, SDK options: ${clientOrgId})`,\n );\n return false;\n }\n\n const strictTraceContinuation = client.getOptions().strictTraceContinuation || false; // default for `strictTraceContinuation` is `false`\n\n if (strictTraceContinuation) {\n // With strict continuation enabled, don't continue trace if:\n // - Baggage has orgID, but Client doesn't have one\n // - Client has orgID, but baggage doesn't have one\n if ((baggageOrgId && !clientOrgId) || (!baggageOrgId && clientOrgId)) {\n debug.log(\n `Starting a new trace because strict trace continuation is enabled but one org ID is missing (incoming baggage: ${baggageOrgId}, Sentry client: ${clientOrgId})`,\n );\n return false;\n }\n }\n\n return true;\n}\n\nexport { TRACEPARENT_REGEXP, extractTraceparentData, generateSentryTraceHeader, generateTraceparentHeader, propagationContextFromHeaders, shouldContinueTrace };\n//# sourceMappingURL=tracing.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getCurrentScope } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { SPAN_STATUS_UNSET, SPAN_STATUS_OK } from '../tracing/spanstatus.js';\nimport { getCapturedScopesOnSpan } from '../tracing/utils.js';\nimport { addNonEnumerableProperty } from './object.js';\nimport { generateSpanId } from './propagationContext.js';\nimport { timestampInSeconds } from './time.js';\nimport { generateSentryTraceHeader, generateTraceparentHeader } from './tracing.js';\nimport { consoleSandbox } from './debug-logger.js';\nimport { _getSpanForScope } from './spanOnScope.js';\n\n// These are aligned with OpenTelemetry trace flags\nconst TRACE_FLAG_NONE = 0x0;\nconst TRACE_FLAG_SAMPLED = 0x1;\n\nlet hasShownSpanDropWarning = false;\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in an event.\n * By default, this will only include trace_id, span_id & parent_span_id.\n * If `includeAllData` is true, it will also include data, op, status & origin.\n */\nfunction spanToTransactionTraceContext(span) {\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n const { data, op, parent_span_id, status, origin, links } = spanToJSON(span);\n\n return {\n parent_span_id,\n span_id,\n trace_id,\n data,\n op,\n status,\n origin,\n links,\n };\n}\n\n/**\n * Convert a span to a trace context, which can be sent as the `trace` context in a non-transaction event.\n */\nfunction spanToTraceContext(span) {\n const { spanId, traceId: trace_id, isRemote } = span.spanContext();\n\n // If the span is remote, we use a random/virtual span as span_id to the trace context,\n // and the remote span as parent_span_id\n const parent_span_id = isRemote ? spanId : spanToJSON(span).parent_span_id;\n const scope = getCapturedScopesOnSpan(span).scope;\n\n const span_id = isRemote ? scope?.getPropagationContext().propagationSpanId || generateSpanId() : spanId;\n\n return {\n parent_span_id,\n span_id,\n trace_id,\n };\n}\n\n/**\n * Convert a Span to a Sentry trace header.\n */\nfunction spanToTraceHeader(span) {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateSentryTraceHeader(traceId, spanId, sampled);\n}\n\n/**\n * Convert a Span to a W3C traceparent header.\n */\nfunction spanToTraceparentHeader(span) {\n const { traceId, spanId } = span.spanContext();\n const sampled = spanIsSampled(span);\n return generateTraceparentHeader(traceId, spanId, sampled);\n}\n\n/**\n * Converts the span links array to a flattened version to be sent within an envelope.\n *\n * If the links array is empty, it returns `undefined` so the empty value can be dropped before it's sent.\n */\nfunction convertSpanLinksForEnvelope(links) {\n if (links && links.length > 0) {\n return links.map(({ context: { spanId, traceId, traceFlags, ...restContext }, attributes }) => ({\n span_id: spanId,\n trace_id: traceId,\n sampled: traceFlags === TRACE_FLAG_SAMPLED,\n attributes,\n ...restContext,\n }));\n } else {\n return undefined;\n }\n}\n\n/**\n * Convert a span time input into a timestamp in seconds.\n */\nfunction spanTimeInputToSeconds(input) {\n if (typeof input === 'number') {\n return ensureTimestampInSeconds(input);\n }\n\n if (Array.isArray(input)) {\n // See {@link HrTime} for the array-based time format\n return input[0] + input[1] / 1e9;\n }\n\n if (input instanceof Date) {\n return ensureTimestampInSeconds(input.getTime());\n }\n\n return timestampInSeconds();\n}\n\n/**\n * Converts a timestamp to second, if it was in milliseconds, or keeps it as second.\n */\nfunction ensureTimestampInSeconds(timestamp) {\n const isMs = timestamp > 9999999999;\n return isMs ? timestamp / 1000 : timestamp;\n}\n\n/**\n * Convert a span to a JSON representation.\n */\n// Note: Because of this, we currently have a circular type dependency (which we opted out of in package.json).\n// This is not avoidable as we need `spanToJSON` in `spanUtils.ts`, which in turn is needed by `span.ts` for backwards compatibility.\n// And `spanToJSON` needs the Span class from `span.ts` to check here.\nfunction spanToJSON(span) {\n if (spanIsSentrySpan(span)) {\n return span.getSpanJSON();\n }\n\n const { spanId: span_id, traceId: trace_id } = span.spanContext();\n\n // Handle a span from @opentelemetry/sdk-base-trace's `Span` class\n if (spanIsOpenTelemetrySdkTraceBaseSpan(span)) {\n const { attributes, startTime, name, endTime, status, links } = span;\n\n // In preparation for the next major of OpenTelemetry, we want to support\n // looking up the parent span id according to the new API\n // In OTel v1, the parent span id is accessed as `parentSpanId`\n // In OTel v2, the parent span id is accessed as `spanId` on the `parentSpanContext`\n const parentSpanId =\n 'parentSpanId' in span\n ? span.parentSpanId\n : 'parentSpanContext' in span\n ? (span.parentSpanContext )?.spanId\n : undefined;\n\n return {\n span_id,\n trace_id,\n data: attributes,\n description: name,\n parent_span_id: parentSpanId,\n start_timestamp: spanTimeInputToSeconds(startTime),\n // This is [0,0] by default in OTEL, in which case we want to interpret this as no end time\n timestamp: spanTimeInputToSeconds(endTime) || undefined,\n status: getStatusMessage(status),\n op: attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n origin: attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,\n links: convertSpanLinksForEnvelope(links),\n };\n }\n\n // Finally, at least we have `spanContext()`....\n // This should not actually happen in reality, but we need to handle it for type safety.\n return {\n span_id,\n trace_id,\n start_timestamp: 0,\n data: {},\n };\n}\n\nfunction spanIsOpenTelemetrySdkTraceBaseSpan(span) {\n const castSpan = span ;\n return !!castSpan.attributes && !!castSpan.startTime && !!castSpan.name && !!castSpan.endTime && !!castSpan.status;\n}\n\n/** Exported only for tests. */\n\n/**\n * Sadly, due to circular dependency checks we cannot actually import the Span class here and check for instanceof.\n * :( So instead we approximate this by checking if it has the `getSpanJSON` method.\n */\nfunction spanIsSentrySpan(span) {\n return typeof (span ).getSpanJSON === 'function';\n}\n\n/**\n * Returns true if a span is sampled.\n * In most cases, you should just use `span.isRecording()` instead.\n * However, this has a slightly different semantic, as it also returns false if the span is finished.\n * So in the case where this distinction is important, use this method.\n */\nfunction spanIsSampled(span) {\n // We align our trace flags with the ones OpenTelemetry use\n // So we also check for sampled the same way they do.\n const { traceFlags } = span.spanContext();\n return traceFlags === TRACE_FLAG_SAMPLED;\n}\n\n/** Get the status message to use for a JSON representation of a span. */\nfunction getStatusMessage(status) {\n if (!status || status.code === SPAN_STATUS_UNSET) {\n return undefined;\n }\n\n if (status.code === SPAN_STATUS_OK) {\n return 'ok';\n }\n\n return status.message || 'internal_error';\n}\n\nconst CHILD_SPANS_FIELD = '_sentryChildSpans';\nconst ROOT_SPAN_FIELD = '_sentryRootSpan';\n\n/**\n * Adds an opaque child span reference to a span.\n */\nfunction addChildSpanToSpan(span, childSpan) {\n // We store the root span reference on the child span\n // We need this for `getRootSpan()` to work\n const rootSpan = span[ROOT_SPAN_FIELD] || span;\n addNonEnumerableProperty(childSpan , ROOT_SPAN_FIELD, rootSpan);\n\n // We store a list of child spans on the parent span\n // We need this for `getSpanDescendants()` to work\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].add(childSpan);\n } else {\n addNonEnumerableProperty(span, CHILD_SPANS_FIELD, new Set([childSpan]));\n }\n}\n\n/** This is only used internally by Idle Spans. */\nfunction removeChildSpanFromSpan(span, childSpan) {\n if (span[CHILD_SPANS_FIELD]) {\n span[CHILD_SPANS_FIELD].delete(childSpan);\n }\n}\n\n/**\n * Returns an array of the given span and all of its descendants.\n */\nfunction getSpanDescendants(span) {\n const resultSet = new Set();\n\n function addSpanChildren(span) {\n // This exit condition is required to not infinitely loop in case of a circular dependency.\n if (resultSet.has(span)) {\n return;\n // We want to ignore unsampled spans (e.g. non recording spans)\n } else if (spanIsSampled(span)) {\n resultSet.add(span);\n const childSpans = span[CHILD_SPANS_FIELD] ? Array.from(span[CHILD_SPANS_FIELD]) : [];\n for (const childSpan of childSpans) {\n addSpanChildren(childSpan);\n }\n }\n }\n\n addSpanChildren(span);\n\n return Array.from(resultSet);\n}\n\n/**\n * Returns the root span of a given span.\n */\nfunction getRootSpan(span) {\n return span[ROOT_SPAN_FIELD] || span;\n}\n\n/**\n * Returns the currently active span.\n */\nfunction getActiveSpan() {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getActiveSpan) {\n return acs.getActiveSpan();\n }\n\n return _getSpanForScope(getCurrentScope());\n}\n\n/**\n * Logs a warning once if `beforeSendSpan` is used to drop spans.\n */\nfunction showSpanDropWarning() {\n if (!hasShownSpanDropWarning) {\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn(\n '[Sentry] Returning null from `beforeSendSpan` is disallowed. To drop certain spans, configure the respective integrations directly or use `ignoreSpans`.',\n );\n });\n hasShownSpanDropWarning = true;\n }\n}\n\n/**\n * Updates the name of the given span and ensures that the span name is not\n * overwritten by the Sentry SDK.\n *\n * Use this function instead of `span.updateName()` if you want to make sure that\n * your name is kept. For some spans, for example root `http.server` spans the\n * Sentry SDK would otherwise overwrite the span name with a high-quality name\n * it infers when the span ends.\n *\n * Use this function in server code or when your span is started on the server\n * and on the client (browser). If you only update a span name on the client,\n * you can also use `span.updateName()` the SDK does not overwrite the name.\n *\n * @param span - The span to update the name of.\n * @param name - The name to set on the span.\n */\nfunction updateSpanName(span, name) {\n span.updateName(name);\n span.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME]: name,\n });\n}\n\nexport { TRACE_FLAG_NONE, TRACE_FLAG_SAMPLED, addChildSpanToSpan, convertSpanLinksForEnvelope, getActiveSpan, getRootSpan, getSpanDescendants, getStatusMessage, removeChildSpanFromSpan, showSpanDropWarning, spanIsSampled, spanTimeInputToSeconds, spanToJSON, spanToTraceContext, spanToTraceHeader, spanToTraceparentHeader, spanToTransactionTraceContext, updateSpanName };\n//# sourceMappingURL=spanUtils.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { addGlobalErrorInstrumentationHandler } from '../instrument/globalError.js';\nimport { addGlobalUnhandledRejectionInstrumentationHandler } from '../instrument/globalUnhandledRejection.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\n\nlet errorsInstrumented = false;\n\n/**\n * Ensure that global errors automatically set the active span status.\n */\nfunction registerSpanErrorInstrumentation() {\n if (errorsInstrumented) {\n return;\n }\n\n /**\n * If an error or unhandled promise occurs, we mark the active root span as failed\n */\n function errorCallback() {\n const activeSpan = getActiveSpan();\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n if (rootSpan) {\n const message = 'internal_error';\n DEBUG_BUILD && debug.log(`[Tracing] Root span: ${message} -> Global error occurred`);\n rootSpan.setStatus({ code: SPAN_STATUS_ERROR, message });\n }\n }\n\n // The function name will be lost when bundling but we need to be able to identify this listener later to maintain the\n // node.js default exit behaviour\n errorCallback.tag = 'sentry_tracingErrorCallback';\n\n errorsInstrumented = true;\n addGlobalErrorInstrumentationHandler(errorCallback);\n addGlobalUnhandledRejectionInstrumentationHandler(errorCallback);\n}\n\nexport { registerSpanErrorInstrumentation };\n//# sourceMappingURL=errors.js.map\n","import { getClient } from '../currentScopes.js';\n\n// Treeshakable guard to remove all code related to tracing\n\n/**\n * Determines if span recording is currently enabled.\n *\n * Spans are recorded when at least one of `tracesSampleRate` and `tracesSampler`\n * is defined in the SDK config. This function does not make any assumption about\n * sampling decisions, it only checks if the SDK is configured to record spans.\n *\n * Important: This function only determines if span recording is enabled. Trace\n * continuation and propagation is separately controlled and not covered by this function.\n * If this function returns `false`, traces can still be propagated (which is what\n * we refer to by \"Tracing without Performance\")\n * @see https://develop.sentry.dev/sdk/telemetry/traces/tracing-without-performance/\n *\n * @param maybeOptions An SDK options object to be passed to this function.\n * If this option is not provided, the function will use the current client's options.\n */\nfunction hasSpansEnabled(\n maybeOptions,\n) {\n if (typeof __SENTRY_TRACING__ === 'boolean' && !__SENTRY_TRACING__) {\n return false;\n }\n\n const options = maybeOptions || getClient()?.getOptions();\n return (\n !!options &&\n // Note: This check is `!= null`, meaning \"nullish\". `0` is not \"nullish\", `undefined` and `null` are. (This comment was brought to you by 15 minutes of questioning life)\n (options.tracesSampleRate != null || !!options.tracesSampler)\n );\n}\n\nexport { hasSpansEnabled };\n//# sourceMappingURL=hasSpansEnabled.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { isMatchingPattern } from './string.js';\n\nfunction logIgnoredSpan(droppedSpan) {\n debug.log(`Ignoring span ${droppedSpan.op} - ${droppedSpan.description} because it matches \\`ignoreSpans\\`.`);\n}\n\n/**\n * Check if a span should be ignored based on the ignoreSpans configuration.\n */\nfunction shouldIgnoreSpan(\n span,\n ignoreSpans,\n) {\n if (!ignoreSpans?.length || !span.description) {\n return false;\n }\n\n for (const pattern of ignoreSpans) {\n if (isStringOrRegExp(pattern)) {\n if (isMatchingPattern(span.description, pattern)) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n continue;\n }\n\n if (!pattern.name && !pattern.op) {\n continue;\n }\n\n const nameMatches = pattern.name ? isMatchingPattern(span.description, pattern.name) : true;\n const opMatches = pattern.op ? span.op && isMatchingPattern(span.op, pattern.op) : true;\n\n // This check here is only correct because we can guarantee that we ran `isMatchingPattern`\n // for at least one of `nameMatches` and `opMatches`. So in contrary to how this looks,\n // not both op and name actually have to match. This is the most efficient way to check\n // for all combinations of name and op patterns.\n if (nameMatches && opMatches) {\n DEBUG_BUILD && logIgnoredSpan(span);\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Takes a list of spans, and a span that was dropped, and re-parents the child spans of the dropped span to the parent of the dropped span, if possible.\n * This mutates the spans array in place!\n */\nfunction reparentChildSpans(spans, dropSpan) {\n const droppedSpanParentId = dropSpan.parent_span_id;\n const droppedSpanId = dropSpan.span_id;\n\n // This should generally not happen, as we do not apply this on root spans\n // but to be safe, we just bail in this case\n if (!droppedSpanParentId) {\n return;\n }\n\n for (const span of spans) {\n if (span.parent_span_id === droppedSpanId) {\n span.parent_span_id = droppedSpanParentId;\n }\n }\n}\n\nfunction isStringOrRegExp(value) {\n return typeof value === 'string' || value instanceof RegExp;\n}\n\nexport { reparentChildSpans, shouldIgnoreSpan };\n//# sourceMappingURL=should-ignore-span.js.map\n","const DEFAULT_ENVIRONMENT = 'production';\n\nexport { DEFAULT_ENVIRONMENT };\n//# sourceMappingURL=constants.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getClient } from '../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext, dynamicSamplingContextToSentryBaggageHeader } from '../utils/baggage.js';\nimport { extractOrgIdFromClient } from '../utils/dsn.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { addNonEnumerableProperty } from '../utils/object.js';\nimport { getRootSpan, spanToJSON, spanIsSampled } from '../utils/spanUtils.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\n/**\n * If you change this value, also update the terser plugin config to\n * avoid minification of the object property!\n */\nconst FROZEN_DSC_FIELD = '_frozenDsc';\n\n/**\n * Freeze the given DSC on the given span.\n */\nfunction freezeDscOnSpan(span, dsc) {\n const spanWithMaybeDsc = span ;\n addNonEnumerableProperty(spanWithMaybeDsc, FROZEN_DSC_FIELD, dsc);\n}\n\n/**\n * Creates a dynamic sampling context from a client.\n *\n * Dispatches the `createDsc` lifecycle hook as a side effect.\n */\nfunction getDynamicSamplingContextFromClient(trace_id, client) {\n const options = client.getOptions();\n\n const { publicKey: public_key } = client.getDsn() || {};\n\n // Instead of conditionally adding non-undefined values, we add them and then remove them if needed\n // otherwise, the order of baggage entries changes, which \"breaks\" a bunch of tests etc.\n const dsc = {\n environment: options.environment || DEFAULT_ENVIRONMENT,\n release: options.release,\n public_key,\n trace_id,\n org_id: extractOrgIdFromClient(client),\n };\n\n client.emit('createDsc', dsc);\n\n return dsc;\n}\n\n/**\n * Get the dynamic sampling context for the currently active scopes.\n */\nfunction getDynamicSamplingContextFromScope(client, scope) {\n const propagationContext = scope.getPropagationContext();\n return propagationContext.dsc || getDynamicSamplingContextFromClient(propagationContext.traceId, client);\n}\n\n/**\n * Creates a dynamic sampling context from a span (and client and scope)\n *\n * @param span the span from which a few values like the root span name and sample rate are extracted.\n *\n * @returns a dynamic sampling context\n */\nfunction getDynamicSamplingContextFromSpan(span) {\n const client = getClient();\n if (!client) {\n return {};\n }\n\n const rootSpan = getRootSpan(span);\n const rootSpanJson = spanToJSON(rootSpan);\n const rootSpanAttributes = rootSpanJson.data;\n const traceState = rootSpan.spanContext().traceState;\n\n // The span sample rate that was locally applied to the root span should also always be applied to the DSC, even if the DSC is frozen.\n // This is so that the downstream traces/services can use parentSampleRate in their `tracesSampler` to make consistent sampling decisions across the entire trace.\n const rootSpanSampleRate =\n traceState?.get('sentry.sample_rate') ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE] ??\n rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE];\n\n function applyLocalSampleRateToDsc(dsc) {\n if (typeof rootSpanSampleRate === 'number' || typeof rootSpanSampleRate === 'string') {\n dsc.sample_rate = `${rootSpanSampleRate}`;\n }\n return dsc;\n }\n\n // For core implementation, we freeze the DSC onto the span as a non-enumerable property\n const frozenDsc = (rootSpan )[FROZEN_DSC_FIELD];\n if (frozenDsc) {\n return applyLocalSampleRateToDsc(frozenDsc);\n }\n\n // For OpenTelemetry, we freeze the DSC on the trace state\n const traceStateDsc = traceState?.get('sentry.dsc');\n\n // If the span has a DSC, we want it to take precedence\n const dscOnTraceState = traceStateDsc && baggageHeaderToDynamicSamplingContext(traceStateDsc);\n\n if (dscOnTraceState) {\n return applyLocalSampleRateToDsc(dscOnTraceState);\n }\n\n // Else, we generate it from the span\n const dsc = getDynamicSamplingContextFromClient(span.spanContext().traceId, client);\n\n // We don't want to have a transaction name in the DSC if the source is \"url\" because URLs might contain PII\n const source = rootSpanAttributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // after JSON conversion, txn.name becomes jsonSpan.description\n const name = rootSpanJson.description;\n if (source !== 'url' && name) {\n dsc.transaction = name;\n }\n\n // How can we even land here with hasSpansEnabled() returning false?\n // Otel creates a Non-recording span in Tracing Without Performance mode when handling incoming requests\n // So we end up with an active span that is not sampled (neither positively nor negatively)\n if (hasSpansEnabled()) {\n dsc.sampled = String(spanIsSampled(rootSpan));\n dsc.sample_rand =\n // In OTEL we store the sample rand on the trace state because we cannot access scopes for NonRecordingSpans\n // The Sentry OTEL SpanSampler takes care of writing the sample rand on the root span\n traceState?.get('sentry.sample_rand') ??\n // On all other platforms we can actually get the scopes from a root span (we use this as a fallback)\n getCapturedScopesOnSpan(rootSpan).scope?.getPropagationContext().sampleRand.toString();\n }\n\n applyLocalSampleRateToDsc(dsc);\n\n client.emit('createDsc', dsc, rootSpan);\n\n return dsc;\n}\n\n/**\n * Convert a Span to a baggage header.\n */\nfunction spanToBaggageHeader(span) {\n const dsc = getDynamicSamplingContextFromSpan(span);\n return dynamicSamplingContextToSentryBaggageHeader(dsc);\n}\n\nexport { freezeDscOnSpan, getDynamicSamplingContextFromClient, getDynamicSamplingContextFromScope, getDynamicSamplingContextFromSpan, spanToBaggageHeader };\n//# sourceMappingURL=dynamicSamplingContext.js.map\n","import { generateTraceId, generateSpanId } from '../utils/propagationContext.js';\nimport { TRACE_FLAG_NONE } from '../utils/spanUtils.js';\n\n/**\n * A Sentry Span that is non-recording, meaning it will not be sent to Sentry.\n */\nclass SentryNonRecordingSpan {\n\n constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n }\n\n /** @inheritdoc */\n spanContext() {\n return {\n spanId: this._spanId,\n traceId: this._traceId,\n traceFlags: TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n end(_timestamp) {}\n\n /** @inheritdoc */\n setAttribute(_key, _value) {\n return this;\n }\n\n /** @inheritdoc */\n setAttributes(_values) {\n return this;\n }\n\n /** @inheritdoc */\n setStatus(_status) {\n return this;\n }\n\n /** @inheritdoc */\n updateName(_name) {\n return this;\n }\n\n /** @inheritdoc */\n isRecording() {\n return false;\n }\n\n /** @inheritdoc */\n addEvent(\n _name,\n _attributesOrStartTime,\n _startTime,\n ) {\n return this;\n }\n\n /** @inheritDoc */\n addLink(_link) {\n return this;\n }\n\n /** @inheritDoc */\n addLinks(_links) {\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n recordException(_exception, _time) {\n // noop\n }\n}\n\nexport { SentryNonRecordingSpan };\n//# sourceMappingURL=sentryNonRecordingSpan.js.map\n","import { isVueViewModel, isSyntheticEvent } from './is.js';\nimport { convertToPlainObject } from './object.js';\nimport { getVueInternalName, getFunctionName } from './stacktrace.js';\n\n/**\n * Recursively normalizes the given object.\n *\n * - Creates a copy to prevent original input mutation\n * - Skips non-enumerable properties\n * - When stringifying, calls `toJSON` if implemented\n * - Removes circular references\n * - Translates non-serializable values (`undefined`/`NaN`/functions) to serializable format\n * - Translates known global objects/classes to a string representations\n * - Takes care of `Error` object serialization\n * - Optionally limits depth of final output\n * - Optionally limits number of properties/elements included in any single object/array\n *\n * @param input The object to be normalized.\n * @param depth The max depth to which to normalize the object. (Anything deeper stringified whole.)\n * @param maxProperties The max number of elements or properties to be included in any single array or\n * object in the normalized output.\n * @returns A normalized version of the object, or `\"**non-serializable**\"` if any errors are thrown during normalization.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction normalize(input, depth = 100, maxProperties = +Infinity) {\n try {\n // since we're at the outermost level, we don't provide a key\n return visit('', input, depth, maxProperties);\n } catch (err) {\n return { ERROR: `**non-serializable** (${err})` };\n }\n}\n\n/** JSDoc */\nfunction normalizeToSize(\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n object,\n // Default Node.js REPL depth\n depth = 3,\n // 100kB, as 200kB is max payload size, so half sounds reasonable\n maxSize = 100 * 1024,\n) {\n const normalized = normalize(object, depth);\n\n if (jsonSize(normalized) > maxSize) {\n return normalizeToSize(object, depth - 1, maxSize);\n }\n\n return normalized ;\n}\n\n/**\n * Visits a node to perform normalization on it\n *\n * @param key The key corresponding to the given node\n * @param value The node to be visited\n * @param depth Optional number indicating the maximum recursion depth\n * @param maxProperties Optional maximum number of properties/elements included in any single object/array\n * @param memo Optional Memo class handling decycling\n */\nfunction visit(\n key,\n value,\n depth = +Infinity,\n maxProperties = +Infinity,\n memo = memoBuilder(),\n) {\n const [memoize, unmemoize] = memo;\n\n // Get the simple cases out of the way first\n if (\n value == null || // this matches null and undefined -> eqeq not eqeqeq\n ['boolean', 'string'].includes(typeof value) ||\n (typeof value === 'number' && Number.isFinite(value))\n ) {\n return value ;\n }\n\n const stringified = stringifyValue(key, value);\n\n // Anything we could potentially dig into more (objects or arrays) will have come back as `\"[object XXXX]\"`.\n // Everything else will have already been serialized, so if we don't see that pattern, we're done.\n if (!stringified.startsWith('[object ')) {\n return stringified;\n }\n\n // From here on, we can assert that `value` is either an object or an array.\n\n // Do not normalize objects that we know have already been normalized. As a general rule, the\n // \"__sentry_skip_normalization__\" property should only be used sparingly and only should only be set on objects that\n // have already been normalized.\n if ((value )['__sentry_skip_normalization__']) {\n return value ;\n }\n\n // We can set `__sentry_override_normalization_depth__` on an object to ensure that from there\n // We keep a certain amount of depth.\n // This should be used sparingly, e.g. we use it for the redux integration to ensure we get a certain amount of state.\n const remainingDepth =\n typeof (value )['__sentry_override_normalization_depth__'] === 'number'\n ? ((value )['__sentry_override_normalization_depth__'] )\n : depth;\n\n // We're also done if we've reached the max depth\n if (remainingDepth === 0) {\n // At this point we know `serialized` is a string of the form `\"[object XXXX]\"`. Clean it up so it's just `\"[XXXX]\"`.\n return stringified.replace('object ', '');\n }\n\n // If we've already visited this branch, bail out, as it's circular reference. If not, note that we're seeing it now.\n if (memoize(value)) {\n return '[Circular ~]';\n }\n\n // If the value has a `toJSON` method, we call it to extract more information\n const valueWithToJSON = value ;\n if (valueWithToJSON && typeof valueWithToJSON.toJSON === 'function') {\n try {\n const jsonValue = valueWithToJSON.toJSON();\n // We need to normalize the return value of `.toJSON()` in case it has circular references\n return visit('', jsonValue, remainingDepth - 1, maxProperties, memo);\n } catch {\n // pass (The built-in `toJSON` failed, but we can still try to do it ourselves)\n }\n }\n\n // At this point we know we either have an object or an array, we haven't seen it before, and we're going to recurse\n // because we haven't yet reached the max depth. Create an accumulator to hold the results of visiting each\n // property/entry, and keep track of the number of items we add to it.\n const normalized = (Array.isArray(value) ? [] : {}) ;\n let numAdded = 0;\n\n // Before we begin, convert`Error` and`Event` instances into plain objects, since some of each of their relevant\n // properties are non-enumerable and otherwise would get missed.\n const visitable = convertToPlainObject(value );\n\n for (const visitKey in visitable) {\n // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration.\n if (!Object.prototype.hasOwnProperty.call(visitable, visitKey)) {\n continue;\n }\n\n if (numAdded >= maxProperties) {\n normalized[visitKey] = '[MaxProperties ~]';\n break;\n }\n\n // Recursively visit all the child nodes\n const visitValue = visitable[visitKey];\n normalized[visitKey] = visit(visitKey, visitValue, remainingDepth - 1, maxProperties, memo);\n\n numAdded++;\n }\n\n // Once we've visited all the branches, remove the parent from memo storage\n unmemoize(value);\n\n // Return accumulated values\n return normalized;\n}\n\n/* eslint-disable complexity */\n/**\n * Stringify the given value. Handles various known special values and types.\n *\n * Not meant to be used on simple primitives which already have a string representation, as it will, for example, turn\n * the number 1231 into \"[Object Number]\", nor on `null`, as it will throw.\n *\n * @param value The value to stringify\n * @returns A stringified representation of the given value\n */\nfunction stringifyValue(\n key,\n // this type is a tiny bit of a cheat, since this function does handle NaN (which is technically a number), but for\n // our internal use, it'll do\n value,\n) {\n try {\n if (key === 'domain' && value && typeof value === 'object' && (value )._events) {\n return '[Domain]';\n }\n\n if (key === 'domainEmitter') {\n return '[DomainEmitter]';\n }\n\n // It's safe to use `global`, `window`, and `document` here in this manner, as we are asserting using `typeof` first\n // which won't throw if they are not present.\n\n if (typeof global !== 'undefined' && value === global) {\n return '[Global]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof window !== 'undefined' && value === window) {\n return '[Window]';\n }\n\n // eslint-disable-next-line no-restricted-globals\n if (typeof document !== 'undefined' && value === document) {\n return '[Document]';\n }\n\n if (isVueViewModel(value)) {\n return getVueInternalName(value);\n }\n\n // React's SyntheticEvent thingy\n if (isSyntheticEvent(value)) {\n return '[SyntheticEvent]';\n }\n\n if (typeof value === 'number' && !Number.isFinite(value)) {\n return `[${value}]`;\n }\n\n if (typeof value === 'function') {\n return `[Function: ${getFunctionName(value)}]`;\n }\n\n if (typeof value === 'symbol') {\n return `[${String(value)}]`;\n }\n\n // stringified BigInts are indistinguishable from regular numbers, so we need to label them to avoid confusion\n if (typeof value === 'bigint') {\n return `[BigInt: ${String(value)}]`;\n }\n\n // Now that we've knocked out all the special cases and the primitives, all we have left are objects. Simply casting\n // them to strings means that instances of classes which haven't defined their `toStringTag` will just come out as\n // `\"[object Object]\"`. If we instead look at the constructor's name (which is the same as the name of the class),\n // we can make sure that only plain objects come out that way.\n const objName = getConstructorName(value);\n\n // Handle HTML Elements\n if (/^HTML(\\w*)Element$/.test(objName)) {\n return `[HTMLElement: ${objName}]`;\n }\n\n return `[object ${objName}]`;\n } catch (err) {\n return `**non-serializable** (${err})`;\n }\n}\n/* eslint-enable complexity */\n\nfunction getConstructorName(value) {\n const prototype = Object.getPrototypeOf(value);\n\n return prototype?.constructor ? prototype.constructor.name : 'null prototype';\n}\n\n/** Calculates bytes size of input string */\nfunction utf8Length(value) {\n // eslint-disable-next-line no-bitwise\n return ~-encodeURI(value).split(/%..|./).length;\n}\n\n/** Calculates bytes size of input object */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction jsonSize(value) {\n return utf8Length(JSON.stringify(value));\n}\n\n/**\n * Normalizes URLs in exceptions and stacktraces to a base path so Sentry can fingerprint\n * across platforms and working directory.\n *\n * @param url The URL to be normalized.\n * @param basePath The application base path.\n * @returns The normalized URL.\n */\nfunction normalizeUrlToBase(url, basePath) {\n const escapedBase = basePath\n // Backslash to forward\n .replace(/\\\\/g, '/')\n // Escape RegExp special characters\n .replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&');\n\n let newUrl = url;\n try {\n newUrl = decodeURI(url);\n } catch {\n // Sometime this breaks\n }\n return (\n newUrl\n .replace(/\\\\/g, '/')\n .replace(/webpack:\\/?/g, '') // Remove intermediate base path\n // eslint-disable-next-line @sentry-internal/sdk/no-regexp-constructor\n .replace(new RegExp(`(file://)?/*${escapedBase}/*`, 'ig'), 'app:///')\n );\n}\n\n/**\n * Helper to decycle json objects\n */\nfunction memoBuilder() {\n const inner = new WeakSet();\n function memoize(obj) {\n if (inner.has(obj)) {\n return true;\n }\n inner.add(obj);\n return false;\n }\n\n function unmemoize(obj) {\n inner.delete(obj);\n }\n return [memoize, unmemoize];\n}\n\nexport { normalize, normalizeToSize, normalizeUrlToBase };\n//# sourceMappingURL=normalize.js.map\n","import { getSentryCarrier } from '../carrier.js';\nimport { dsnToString } from './dsn.js';\nimport { normalize } from './normalize.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Creates an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction createEnvelope(headers, items = []) {\n return [headers, items] ;\n}\n\n/**\n * Add an item to an envelope.\n * Make sure to always explicitly provide the generic to this function\n * so that the envelope types resolve correctly.\n */\nfunction addItemToEnvelope(envelope, newItem) {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] ;\n}\n\n/**\n * Convenience function to loop through the items and item types of an envelope.\n * (This function was mostly created because working with envelope types is painful at the moment)\n *\n * If the callback returns true, the rest of the items will be skipped.\n */\nfunction forEachEnvelopeItem(\n envelope,\n callback,\n) {\n const envelopeItems = envelope[1];\n\n for (const envelopeItem of envelopeItems) {\n const envelopeItemType = envelopeItem[0].type;\n const result = callback(envelopeItem, envelopeItemType);\n\n if (result) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Returns true if the envelope contains any of the given envelope item types\n */\nfunction envelopeContainsItemType(envelope, types) {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.encodePolyfill ? carrier.encodePolyfill(input) : new TextEncoder().encode(input);\n}\n\n/**\n * Decode a UTF8 array to string.\n */\nfunction decodeUTF8(input) {\n const carrier = getSentryCarrier(GLOBAL_OBJ);\n return carrier.decodePolyfill ? carrier.decodePolyfill(input) : new TextDecoder().decode(input);\n}\n\n/**\n * Serializes an envelope.\n */\nfunction serializeEnvelope(envelope) {\n const [envHeaders, items] = envelope;\n // Initially we construct our envelope as a string and only convert to binary chunks if we encounter binary data\n let parts = JSON.stringify(envHeaders);\n\n function append(next) {\n if (typeof parts === 'string') {\n parts = typeof next === 'string' ? parts + next : [encodeUTF8(parts), next];\n } else {\n parts.push(typeof next === 'string' ? encodeUTF8(next) : next);\n }\n }\n\n for (const item of items) {\n const [itemHeaders, payload] = item;\n\n append(`\\n${JSON.stringify(itemHeaders)}\\n`);\n\n if (typeof payload === 'string' || payload instanceof Uint8Array) {\n append(payload);\n } else {\n let stringifiedPayload;\n try {\n stringifiedPayload = JSON.stringify(payload);\n } catch {\n // In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.stringify()` still\n // fails, we try again after normalizing it again with infinite normalization depth. This of course has a\n // performance impact but in this case a performance hit is better than throwing.\n stringifiedPayload = JSON.stringify(normalize(payload));\n }\n append(stringifiedPayload);\n }\n }\n\n return typeof parts === 'string' ? parts : concatBuffers(parts);\n}\n\nfunction concatBuffers(buffers) {\n const totalLength = buffers.reduce((acc, buf) => acc + buf.length, 0);\n\n const merged = new Uint8Array(totalLength);\n let offset = 0;\n for (const buffer of buffers) {\n merged.set(buffer, offset);\n offset += buffer.length;\n }\n\n return merged;\n}\n\n/**\n * Parses an envelope\n */\nfunction parseEnvelope(env) {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length) {\n const bin = buffer.subarray(0, length);\n // Replace the buffer with the remaining data excluding trailing newline\n buffer = buffer.subarray(length + 1);\n return bin;\n }\n\n function readJson() {\n let i = buffer.indexOf(0xa);\n // If we couldn't find a newline, we must have found the end of the buffer\n if (i < 0) {\n i = buffer.length;\n }\n\n return JSON.parse(decodeUTF8(readBinary(i))) ;\n }\n\n const envelopeHeader = readJson();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items = [];\n\n while (buffer.length) {\n const itemHeader = readJson();\n const binaryLength = typeof itemHeader.length === 'number' ? itemHeader.length : undefined;\n\n items.push([itemHeader, binaryLength ? readBinary(binaryLength) : readJson()]);\n }\n\n return [envelopeHeader, items];\n}\n\n/**\n * Creates envelope item for a single span\n */\nfunction createSpanEnvelopeItem(spanJson) {\n const spanHeaders = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nfunction createAttachmentEnvelopeItem(attachment) {\n const buffer = typeof attachment.data === 'string' ? encodeUTF8(attachment.data) : attachment.data;\n\n return [\n {\n type: 'attachment',\n length: buffer.length,\n filename: attachment.filename,\n content_type: attachment.contentType,\n attachment_type: attachment.attachmentType,\n },\n buffer,\n ];\n}\n\nconst ITEM_TYPE_TO_DATA_CATEGORY_MAP = {\n session: 'session',\n sessions: 'session',\n attachment: 'attachment',\n transaction: 'transaction',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile: 'profile',\n profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n feedback: 'feedback',\n span: 'span',\n raw_security: 'security',\n log: 'log_item',\n metric: 'metric',\n trace_metric: 'metric',\n};\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nfunction envelopeItemTypeToDataCategory(type) {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nfunction getSdkMetadataForEnvelopeHeader(metadataOrEvent) {\n if (!metadataOrEvent?.sdk) {\n return;\n }\n const { name, version } = metadataOrEvent.sdk;\n return { name, version };\n}\n\n/**\n * Creates event envelope headers, based on event, sdk info and tunnel\n * Note: This function was extracted from the core package to make it available in Replay\n */\nfunction createEventEnvelopeHeaders(\n event,\n sdkInfo,\n tunnel,\n dsn,\n) {\n const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n return {\n event_id: event.event_id ,\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n ...(dynamicSamplingContext && {\n trace: dynamicSamplingContext,\n }),\n };\n}\n\nexport { addItemToEnvelope, createAttachmentEnvelopeItem, createEnvelope, createEventEnvelopeHeaders, createSpanEnvelopeItem, envelopeContainsItemType, envelopeItemTypeToDataCategory, forEachEnvelopeItem, getSdkMetadataForEnvelopeHeader, parseEnvelope, serializeEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getDynamicSamplingContextFromSpan } from './tracing/dynamicSamplingContext.js';\nimport { dsnToString } from './utils/dsn.js';\nimport { getSdkMetadataForEnvelopeHeader, createEventEnvelopeHeaders, createEnvelope, createSpanEnvelopeItem } from './utils/envelope.js';\nimport { shouldIgnoreSpan } from './utils/should-ignore-span.js';\nimport { spanToJSON, showSpanDropWarning } from './utils/spanUtils.js';\n\n/**\n * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key.\n * Merge with existing data if any.\n *\n * @internal, exported only for testing\n **/\nfunction _enhanceEventWithSdkInfo(event, newSdkInfo) {\n if (!newSdkInfo) {\n return event;\n }\n\n const eventSdkInfo = event.sdk || {};\n\n event.sdk = {\n ...eventSdkInfo,\n name: eventSdkInfo.name || newSdkInfo.name,\n version: eventSdkInfo.version || newSdkInfo.version,\n integrations: [...(event.sdk?.integrations || []), ...(newSdkInfo.integrations || [])],\n packages: [...(event.sdk?.packages || []), ...(newSdkInfo.packages || [])],\n settings:\n event.sdk?.settings || newSdkInfo.settings\n ? {\n ...event.sdk?.settings,\n ...newSdkInfo.settings,\n }\n : undefined,\n };\n\n return event;\n}\n\n/** Creates an envelope from a Session */\nfunction createSessionEnvelope(\n session,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n const envelopeHeaders = {\n sent_at: new Date().toISOString(),\n ...(sdkInfo && { sdk: sdkInfo }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const envelopeItem =\n 'aggregates' in session ? [{ type: 'sessions' }, session] : [{ type: 'session' }, session.toJSON()];\n\n return createEnvelope(envelopeHeaders, [envelopeItem]);\n}\n\n/**\n * Create an Envelope from an event.\n */\nfunction createEventEnvelope(\n event,\n dsn,\n metadata,\n tunnel,\n) {\n const sdkInfo = getSdkMetadataForEnvelopeHeader(metadata);\n\n /*\n Note: Due to TS, event.type may be `replay_event`, theoretically.\n In practice, we never call `createEventEnvelope` with `replay_event` type,\n and we'd have to adjust a looot of types to make this work properly.\n We want to avoid casting this around, as that could lead to bugs (e.g. when we add another type)\n So the safe choice is to really guard against the replay_event type here.\n */\n const eventType = event.type && event.type !== 'replay_event' ? event.type : 'event';\n\n _enhanceEventWithSdkInfo(event, metadata?.sdk);\n\n const envelopeHeaders = createEventEnvelopeHeaders(event, sdkInfo, tunnel, dsn);\n\n // Prevent this data (which, if it exists, was used in earlier steps in the processing pipeline) from being sent to\n // sentry. (Note: Our use of this property comes and goes with whatever we might be debugging, whatever hacks we may\n // have temporarily added, etc. Even if we don't happen to be using it at some point in the future, let's not get rid\n // of this `delete`, lest we miss putting it back in the next time the property is in use.)\n delete event.sdkProcessingMetadata;\n\n const eventItem = [{ type: eventType }, event];\n return createEnvelope(envelopeHeaders, [eventItem]);\n}\n\n/**\n * Create envelope from Span item.\n *\n * Takes an optional client and runs spans through `beforeSendSpan` if available.\n */\nfunction createSpanEnvelope(spans, client) {\n function dscHasRequiredProps(dsc) {\n return !!dsc.trace_id && !!dsc.public_key;\n }\n\n // For the moment we'll obtain the DSC from the first span in the array\n // This might need to be changed if we permit sending multiple spans from\n // different segments in one envelope\n const dsc = getDynamicSamplingContextFromSpan(spans[0]);\n\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n\n const headers = {\n sent_at: new Date().toISOString(),\n ...(dscHasRequiredProps(dsc) && { trace: dsc }),\n ...(!!tunnel && dsn && { dsn: dsnToString(dsn) }),\n };\n\n const { beforeSendSpan, ignoreSpans } = client?.getOptions() || {};\n\n const filteredSpans = ignoreSpans?.length\n ? spans.filter(span => !shouldIgnoreSpan(spanToJSON(span), ignoreSpans))\n : spans;\n const droppedSpans = spans.length - filteredSpans.length;\n\n if (droppedSpans) {\n client?.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n const convertToSpanJSON = beforeSendSpan\n ? (span) => {\n const spanJson = spanToJSON(span);\n const processedSpan = beforeSendSpan(spanJson);\n\n if (!processedSpan) {\n showSpanDropWarning();\n return spanJson;\n }\n\n return processedSpan;\n }\n : spanToJSON;\n\n const items = [];\n for (const span of filteredSpans) {\n const spanJson = convertToSpanJSON(span);\n if (spanJson) {\n items.push(createSpanEnvelopeItem(spanJson));\n }\n }\n\n return createEnvelope(headers, items);\n}\n\nexport { _enhanceEventWithSdkInfo, createEventEnvelope, createSessionEnvelope, createSpanEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { spanToJSON, getRootSpan, spanIsSampled } from '../utils/spanUtils.js';\n\n/**\n * Print a log message for a started span.\n */\nfunction logSpanStart(span) {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >', parent_span_id: parentSpanId } = spanToJSON(span);\n const { spanId } = span.spanContext();\n\n const sampled = spanIsSampled(span);\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const header = `[Tracing] Starting ${sampled ? 'sampled' : 'unsampled'} ${isRootSpan ? 'root ' : ''}span`;\n\n const infoParts = [`op: ${op}`, `name: ${description}`, `ID: ${spanId}`];\n\n if (parentSpanId) {\n infoParts.push(`parent ID: ${parentSpanId}`);\n }\n\n if (!isRootSpan) {\n const { op, description } = spanToJSON(rootSpan);\n infoParts.push(`root ID: ${rootSpan.spanContext().spanId}`);\n if (op) {\n infoParts.push(`root op: ${op}`);\n }\n if (description) {\n infoParts.push(`root description: ${description}`);\n }\n }\n\n debug.log(`${header}\n ${infoParts.join('\\n ')}`);\n}\n\n/**\n * Print a log message for an ended span.\n */\nfunction logSpanEnd(span) {\n if (!DEBUG_BUILD) return;\n\n const { description = '< unknown name >', op = '< unknown op >' } = spanToJSON(span);\n const { spanId } = span.spanContext();\n const rootSpan = getRootSpan(span);\n const isRootSpan = rootSpan === span;\n\n const msg = `[Tracing] Finishing \"${op}\" ${isRootSpan ? 'root ' : ''}span \"${description}\" with ID ${spanId}`;\n debug.log(msg);\n}\n\nexport { logSpanEnd, logSpanStart };\n//# sourceMappingURL=logSpans.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT, SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getActiveSpan, getRootSpan } from '../utils/spanUtils.js';\n\n/**\n * Adds a measurement to the active transaction on the current global scope. You can optionally pass in a different span\n * as the 4th parameter.\n */\nfunction setMeasurement(name, value, unit, activeSpan = getActiveSpan()) {\n const rootSpan = activeSpan && getRootSpan(activeSpan);\n\n if (rootSpan) {\n DEBUG_BUILD && debug.log(`[Measurement] Setting measurement on root span: ${name} = ${value} ${unit}`);\n rootSpan.addEvent(name, {\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE]: value,\n [SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT]: unit ,\n });\n }\n}\n\n/**\n * Convert timed events to measurements.\n */\nfunction timedEventsToMeasurements(events) {\n if (!events || events.length === 0) {\n return undefined;\n }\n\n const measurements = {};\n events.forEach(event => {\n const attributes = event.attributes || {};\n const unit = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT] ;\n const value = attributes[SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE] ;\n\n if (typeof unit === 'string' && typeof value === 'number') {\n measurements[event.name] = { value, unit };\n }\n });\n\n return measurements;\n}\n\nexport { setMeasurement, timedEventsToMeasurements };\n//# sourceMappingURL=measurement.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { createSpanEnvelope } from '../envelope.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID, SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { generateTraceId, generateSpanId } from '../utils/propagationContext.js';\nimport { TRACE_FLAG_SAMPLED, TRACE_FLAG_NONE, spanTimeInputToSeconds, convertSpanLinksForEnvelope, getRootSpan, getStatusMessage, spanToJSON, getSpanDescendants, spanToTransactionTraceContext } from '../utils/spanUtils.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { getDynamicSamplingContextFromSpan } from './dynamicSamplingContext.js';\nimport { logSpanEnd } from './logSpans.js';\nimport { timedEventsToMeasurements } from './measurement.js';\nimport { getCapturedScopesOnSpan } from './utils.js';\n\nconst MAX_SPAN_COUNT = 1000;\n\n/**\n * Span contains all data about a span\n */\nclass SentrySpan {\n\n /** Epoch timestamp in seconds when the span started. */\n\n /** Epoch timestamp in seconds when the span ended. */\n\n /** Internal keeper of the status */\n\n /** The timed events added to this span. */\n\n /** if true, treat span as a standalone span (not part of a transaction) */\n\n /**\n * You should never call the constructor manually, always use `Sentry.startSpan()`\n * or other span methods.\n * @internal\n * @hideconstructor\n * @hidden\n */\n constructor(spanContext = {}) {\n this._traceId = spanContext.traceId || generateTraceId();\n this._spanId = spanContext.spanId || generateSpanId();\n this._startTime = spanContext.startTimestamp || timestampInSeconds();\n this._links = spanContext.links;\n\n this._attributes = {};\n this.setAttributes({\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'manual',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: spanContext.op,\n ...spanContext.attributes,\n });\n\n this._name = spanContext.name;\n\n if (spanContext.parentSpanId) {\n this._parentSpanId = spanContext.parentSpanId;\n }\n // We want to include booleans as well here\n if ('sampled' in spanContext) {\n this._sampled = spanContext.sampled;\n }\n if (spanContext.endTimestamp) {\n this._endTime = spanContext.endTimestamp;\n }\n\n this._events = [];\n\n this._isStandaloneSpan = spanContext.isStandalone;\n\n // If the span is already ended, ensure we finalize the span immediately\n if (this._endTime) {\n this._onSpanEnded();\n }\n }\n\n /** @inheritDoc */\n addLink(link) {\n if (this._links) {\n this._links.push(link);\n } else {\n this._links = [link];\n }\n return this;\n }\n\n /** @inheritDoc */\n addLinks(links) {\n if (this._links) {\n this._links.push(...links);\n } else {\n this._links = links;\n }\n return this;\n }\n\n /**\n * This should generally not be used,\n * but it is needed for being compliant with the OTEL Span interface.\n *\n * @hidden\n * @internal\n */\n recordException(_exception, _time) {\n // noop\n }\n\n /** @inheritdoc */\n spanContext() {\n const { _spanId: spanId, _traceId: traceId, _sampled: sampled } = this;\n return {\n spanId,\n traceId,\n traceFlags: sampled ? TRACE_FLAG_SAMPLED : TRACE_FLAG_NONE,\n };\n }\n\n /** @inheritdoc */\n setAttribute(key, value) {\n if (value === undefined) {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete this._attributes[key];\n } else {\n this._attributes[key] = value;\n }\n\n return this;\n }\n\n /** @inheritdoc */\n setAttributes(attributes) {\n Object.keys(attributes).forEach(key => this.setAttribute(key, attributes[key]));\n return this;\n }\n\n /**\n * This should generally not be used,\n * but we need it for browser tracing where we want to adjust the start time afterwards.\n * USE THIS WITH CAUTION!\n *\n * @hidden\n * @internal\n */\n updateStartTime(timeInput) {\n this._startTime = spanTimeInputToSeconds(timeInput);\n }\n\n /**\n * @inheritDoc\n */\n setStatus(value) {\n this._status = value;\n return this;\n }\n\n /**\n * @inheritDoc\n */\n updateName(name) {\n this._name = name;\n this.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, 'custom');\n return this;\n }\n\n /** @inheritdoc */\n end(endTimestamp) {\n // If already ended, skip\n if (this._endTime) {\n return;\n }\n\n this._endTime = spanTimeInputToSeconds(endTimestamp);\n logSpanEnd(this);\n\n this._onSpanEnded();\n }\n\n /**\n * Get JSON representation of this span.\n *\n * @hidden\n * @internal This method is purely for internal purposes and should not be used outside\n * of SDK code. If you need to get a JSON representation of a span,\n * use `spanToJSON(span)` instead.\n */\n getSpanJSON() {\n return {\n data: this._attributes,\n description: this._name,\n op: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_OP],\n parent_span_id: this._parentSpanId,\n span_id: this._spanId,\n start_timestamp: this._startTime,\n status: getStatusMessage(this._status),\n timestamp: this._endTime,\n trace_id: this._traceId,\n origin: this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN] ,\n profile_id: this._attributes[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: this._attributes[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\n measurements: timedEventsToMeasurements(this._events),\n is_segment: (this._isStandaloneSpan && getRootSpan(this) === this) || undefined,\n segment_id: this._isStandaloneSpan ? getRootSpan(this).spanContext().spanId : undefined,\n links: convertSpanLinksForEnvelope(this._links),\n };\n }\n\n /** @inheritdoc */\n isRecording() {\n return !this._endTime && !!this._sampled;\n }\n\n /**\n * @inheritdoc\n */\n addEvent(\n name,\n attributesOrStartTime,\n startTime,\n ) {\n DEBUG_BUILD && debug.log('[Tracing] Adding an event to span:', name);\n\n const time = isSpanTimeInput(attributesOrStartTime) ? attributesOrStartTime : startTime || timestampInSeconds();\n const attributes = isSpanTimeInput(attributesOrStartTime) ? {} : attributesOrStartTime || {};\n\n const event = {\n name,\n time: spanTimeInputToSeconds(time),\n attributes,\n };\n\n this._events.push(event);\n\n return this;\n }\n\n /**\n * This method should generally not be used,\n * but for now we need a way to publicly check if the `_isStandaloneSpan` flag is set.\n * USE THIS WITH CAUTION!\n * @internal\n * @hidden\n * @experimental\n */\n isStandaloneSpan() {\n return !!this._isStandaloneSpan;\n }\n\n /** Emit `spanEnd` when the span is ended. */\n _onSpanEnded() {\n const client = getClient();\n if (client) {\n client.emit('spanEnd', this);\n }\n\n // A segment span is basically the root span of a local span tree.\n // So for now, this is either what we previously refer to as the root span,\n // or a standalone span.\n const isSegmentSpan = this._isStandaloneSpan || this === getRootSpan(this);\n\n if (!isSegmentSpan) {\n return;\n }\n\n // if this is a standalone span, we send it immediately\n if (this._isStandaloneSpan) {\n if (this._sampled) {\n sendSpanEnvelope(createSpanEnvelope([this], client));\n } else {\n DEBUG_BUILD &&\n debug.log('[Tracing] Discarding standalone span because its trace was not chosen to be sampled.');\n if (client) {\n client.recordDroppedEvent('sample_rate', 'span');\n }\n }\n return;\n }\n\n const transactionEvent = this._convertSpanToTransaction();\n if (transactionEvent) {\n const scope = getCapturedScopesOnSpan(this).scope || getCurrentScope();\n scope.captureEvent(transactionEvent);\n }\n }\n\n /**\n * Finish the transaction & prepare the event to send to Sentry.\n */\n _convertSpanToTransaction() {\n // We can only convert finished spans\n if (!isFullFinishedSpan(spanToJSON(this))) {\n return undefined;\n }\n\n if (!this._name) {\n DEBUG_BUILD && debug.warn('Transaction has no name, falling back to `<unlabeled transaction>`.');\n this._name = '<unlabeled transaction>';\n }\n\n const { scope: capturedSpanScope, isolationScope: capturedSpanIsolationScope } = getCapturedScopesOnSpan(this);\n\n const normalizedRequest = capturedSpanScope?.getScopeData().sdkProcessingMetadata?.normalizedRequest;\n\n if (this._sampled !== true) {\n return undefined;\n }\n\n // The transaction span itself as well as any potential standalone spans should be filtered out\n const finishedSpans = getSpanDescendants(this).filter(span => span !== this && !isStandaloneSpan(span));\n\n const spans = finishedSpans.map(span => spanToJSON(span)).filter(isFullFinishedSpan);\n\n const source = this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE];\n\n // remove internal root span attributes we don't need to send.\n /* eslint-disable @typescript-eslint/no-dynamic-delete */\n delete this._attributes[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n spans.forEach(span => {\n delete span.data[SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME];\n });\n // eslint-enabled-next-line @typescript-eslint/no-dynamic-delete\n\n const transaction = {\n contexts: {\n trace: spanToTransactionTraceContext(this),\n },\n spans:\n // spans.sort() mutates the array, but `spans` is already a copy so we can safely do this here\n // we do not use spans anymore after this point\n spans.length > MAX_SPAN_COUNT\n ? spans.sort((a, b) => a.start_timestamp - b.start_timestamp).slice(0, MAX_SPAN_COUNT)\n : spans,\n start_timestamp: this._startTime,\n timestamp: this._endTime,\n transaction: this._name,\n type: 'transaction',\n sdkProcessingMetadata: {\n capturedSpanScope,\n capturedSpanIsolationScope,\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(this),\n },\n request: normalizedRequest,\n ...(source && {\n transaction_info: {\n source,\n },\n }),\n };\n\n const measurements = timedEventsToMeasurements(this._events);\n const hasMeasurements = measurements && Object.keys(measurements).length;\n\n if (hasMeasurements) {\n DEBUG_BUILD &&\n debug.log(\n '[Measurements] Adding measurements to transaction event',\n JSON.stringify(measurements, undefined, 2),\n );\n transaction.measurements = measurements;\n }\n\n return transaction;\n }\n}\n\nfunction isSpanTimeInput(value) {\n return (value && typeof value === 'number') || value instanceof Date || Array.isArray(value);\n}\n\n// We want to filter out any incomplete SpanJSON objects\nfunction isFullFinishedSpan(input) {\n return !!input.start_timestamp && !!input.timestamp && !!input.span_id && !!input.trace_id;\n}\n\n/** `SentrySpan`s can be sent as a standalone span rather than belonging to a transaction */\nfunction isStandaloneSpan(span) {\n return span instanceof SentrySpan && span.isStandaloneSpan();\n}\n\n/**\n * Sends a `SpanEnvelope`.\n *\n * Note: If the envelope's spans are dropped, e.g. via `beforeSendSpan`,\n * the envelope will not be sent either.\n */\nfunction sendSpanEnvelope(envelope) {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const spanItems = envelope[1];\n if (!spanItems || spanItems.length === 0) {\n client.recordDroppedEvent('before_send', 'span');\n return;\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\nexport { SentrySpan };\n//# sourceMappingURL=sentrySpan.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable */\n// Vendor \"Awaited\" in to be TS 3.8 compatible\n\n/**\n * Wrap a callback function with error handling.\n * If an error is thrown, it will be passed to the `onError` callback and re-thrown.\n *\n * If the return value of the function is a promise, it will be handled with `maybeHandlePromiseRejection`.\n *\n * If an `onFinally` callback is provided, this will be called when the callback has finished\n * - so if it returns a promise, once the promise resolved/rejected,\n * else once the callback has finished executing.\n * The `onFinally` callback will _always_ be called, no matter if an error was thrown or not.\n */\nfunction handleCallbackErrors\n\n(\n fn,\n onError,\n onFinally = () => {},\n onSuccess = () => {},\n) {\n let maybePromiseResult;\n try {\n maybePromiseResult = fn();\n } catch (e) {\n onError(e);\n onFinally();\n throw e;\n }\n\n return maybeHandlePromiseRejection(maybePromiseResult, onError, onFinally, onSuccess);\n}\n\n/**\n * Maybe handle a promise rejection.\n * This expects to be given a value that _may_ be a promise, or any other value.\n * If it is a promise, and it rejects, it will call the `onError` callback.\n * Other than this, it will generally return the given value as-is.\n */\nfunction maybeHandlePromiseRejection(\n value,\n onError,\n onFinally,\n onSuccess,\n) {\n if (isThenable(value)) {\n // @ts-expect-error - the isThenable check returns the \"wrong\" type here\n return value.then(\n res => {\n onFinally();\n onSuccess(res);\n return res;\n },\n e => {\n onError(e);\n onFinally();\n throw e;\n },\n );\n }\n\n onFinally();\n onSuccess(value);\n return value;\n}\n\nexport { handleCallbackErrors };\n//# sourceMappingURL=handleCallbackErrors.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\n\n/**\n * Makes a sampling decision for the given options.\n *\n * Called every time a root span is created. Only root spans which emerge with a `sampled` value of `true` will be\n * sent to Sentry.\n */\nfunction sampleSpan(\n options,\n samplingContext,\n sampleRand,\n) {\n // nothing to do if span recording is not enabled\n if (!hasSpansEnabled(options)) {\n return [false];\n }\n\n let localSampleRateWasApplied = undefined;\n\n // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should\n // work; prefer the hook if so\n let sampleRate;\n if (typeof options.tracesSampler === 'function') {\n sampleRate = options.tracesSampler({\n ...samplingContext,\n inheritOrSampleWith: fallbackSampleRate => {\n // If we have an incoming parent sample rate, we'll just use that one.\n // The sampling decision will be inherited because of the sample_rand that was generated when the trace reached the incoming boundaries of the SDK.\n if (typeof samplingContext.parentSampleRate === 'number') {\n return samplingContext.parentSampleRate;\n }\n\n // Fallback if parent sample rate is not on the incoming trace (e.g. if there is no baggage)\n // This is to provide backwards compatibility if there are incoming traces from older SDKs that don't send a parent sample rate or a sample rand. In these cases we just want to force either a sampling decision on the downstream traces via the sample rate.\n if (typeof samplingContext.parentSampled === 'boolean') {\n return Number(samplingContext.parentSampled);\n }\n\n return fallbackSampleRate;\n },\n });\n localSampleRateWasApplied = true;\n } else if (samplingContext.parentSampled !== undefined) {\n sampleRate = samplingContext.parentSampled;\n } else if (typeof options.tracesSampleRate !== 'undefined') {\n sampleRate = options.tracesSampleRate;\n localSampleRateWasApplied = true;\n }\n\n // Since this is coming from the user (or from a function provided by the user), who knows what we might get.\n // (The only valid values are booleans or numbers between 0 and 1.)\n const parsedSampleRate = parseSampleRate(sampleRate);\n\n if (parsedSampleRate === undefined) {\n DEBUG_BUILD &&\n debug.warn(\n `[Tracing] Discarding root span because of invalid sample rate. Sample rate must be a boolean or a number between 0 and 1. Got ${JSON.stringify(\n sampleRate,\n )} of type ${JSON.stringify(typeof sampleRate)}.`,\n );\n return [false];\n }\n\n // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped\n if (!parsedSampleRate) {\n DEBUG_BUILD &&\n debug.log(\n `[Tracing] Discarding transaction because ${\n typeof options.tracesSampler === 'function'\n ? 'tracesSampler returned 0 or false'\n : 'a negative sampling decision was inherited or tracesSampleRate is set to 0'\n }`,\n );\n return [false, parsedSampleRate, localSampleRateWasApplied];\n }\n\n // We always compare the sample rand for the current execution context against the chosen sample rate.\n // Read more: https://develop.sentry.dev/sdk/telemetry/traces/#propagated-random-value\n const shouldSample = sampleRand < parsedSampleRate;\n\n // if we're not going to keep it, we're done\n if (!shouldSample) {\n DEBUG_BUILD &&\n debug.log(\n `[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = ${Number(\n sampleRate,\n )})`,\n );\n }\n\n return [shouldSample, parsedSampleRate, localSampleRateWasApplied];\n}\n\nexport { sampleSpan };\n//# sourceMappingURL=sampling.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { withScope, getCurrentScope, getClient, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from '../semanticAttributes.js';\nimport { baggageHeaderToDynamicSamplingContext } from '../utils/baggage.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { handleCallbackErrors } from '../utils/handleCallbackErrors.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { parseSampleRate } from '../utils/parseSampleRate.js';\nimport { generateTraceId } from '../utils/propagationContext.js';\nimport { _setSpanForScope, _getSpanForScope } from '../utils/spanOnScope.js';\nimport { spanToJSON, spanTimeInputToSeconds, getRootSpan, addChildSpanToSpan, spanIsSampled } from '../utils/spanUtils.js';\nimport { shouldContinueTrace, propagationContextFromHeaders } from '../utils/tracing.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { logSpanStart } from './logSpans.js';\nimport { sampleSpan } from './sampling.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SentrySpan } from './sentrySpan.js';\nimport { SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { setCapturedScopesOnSpan } from './utils.js';\n\n/* eslint-disable max-lines */\n\n\nconst SUPPRESS_TRACING_KEY = '__SENTRY_SUPPRESS_TRACING__';\n\n/**\n * Wraps a function with a transaction/span and finishes the span after the function is done.\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * If you want to create a span that is not set as active, use {@link startInactiveSpan}.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startSpan(options, callback) {\n const acs = getAcs();\n if (acs.startSpan) {\n return acs.startSpan(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n // We still need to fork a potentially passed scope, as we set the active span on it\n // and we need to ensure that it is cleaned up properly once the span ends.\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n () => callback(activeSpan),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n () => {\n activeSpan.end();\n },\n );\n });\n });\n}\n\n/**\n * Similar to `Sentry.startSpan`. Wraps a function with a transaction/span, but does not finish the span\n * after the function is done automatically. Use `span.end()` to end the span.\n *\n * The created span is the active span and will be used as parent by other spans created inside the function\n * and can be accessed via `Sentry.getActiveSpan()`, as long as the function is executed while the scope is active.\n *\n * You'll always get a span passed to the callback,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startSpanManual(options, callback) {\n const acs = getAcs();\n if (acs.startSpanManual) {\n return acs.startSpanManual(options, callback);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan, scope: customScope } = options;\n\n const customForkedScope = customScope?.clone();\n\n return withScope(customForkedScope, () => {\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = getActiveSpanWrapper(customParentSpan);\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n const activeSpan = shouldSkipSpan\n ? new SentryNonRecordingSpan()\n : createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n\n _setSpanForScope(scope, activeSpan);\n\n return handleCallbackErrors(\n // We pass the `finish` function to the callback, so the user can finish the span manually\n // this is mainly here for historic purposes because previously, we instructed users to call\n // `finish` instead of `span.end()` to also clean up the scope. Nowadays, calling `span.end()`\n // or `finish` has the same effect and we simply leave it here to avoid breaking user code.\n () => callback(activeSpan, () => activeSpan.end()),\n () => {\n // Only update the span status if it hasn't been changed yet, and the span is not yet finished\n const { status } = spanToJSON(activeSpan);\n if (activeSpan.isRecording() && (!status || status === 'ok')) {\n activeSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n },\n );\n });\n });\n}\n\n/**\n * Creates a span. This span is not set as active, so will not get automatic instrumentation spans\n * as children or be able to be accessed via `Sentry.getActiveSpan()`.\n *\n * If you want to create a span that is set as active, use {@link startSpan}.\n *\n * This function will always return a span,\n * it may just be a non-recording span if the span is not sampled or if tracing is disabled.\n */\nfunction startInactiveSpan(options) {\n const acs = getAcs();\n if (acs.startInactiveSpan) {\n return acs.startInactiveSpan(options);\n }\n\n const spanArguments = parseSentrySpanArguments(options);\n const { forceTransaction, parentSpan: customParentSpan } = options;\n\n // If `options.scope` is defined, we use this as as a wrapper,\n // If `options.parentSpan` is defined, we want to wrap the callback in `withActiveSpan`\n const wrapper = options.scope\n ? (callback) => withScope(options.scope, callback)\n : customParentSpan !== undefined\n ? (callback) => withActiveSpan(customParentSpan, callback)\n : (callback) => callback();\n\n return wrapper(() => {\n const scope = getCurrentScope();\n const parentSpan = getParentSpan(scope, customParentSpan);\n\n const shouldSkipSpan = options.onlyIfParent && !parentSpan;\n\n if (shouldSkipSpan) {\n return new SentryNonRecordingSpan();\n }\n\n return createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n });\n });\n}\n\n/**\n * Continue a trace from `sentry-trace` and `baggage` values.\n * These values can be obtained from incoming request headers, or in the browser from `<meta name=\"sentry-trace\">`\n * and `<meta name=\"baggage\">` HTML tags.\n *\n * Spans started with `startSpan`, `startSpanManual` and `startInactiveSpan`, within the callback will automatically\n * be attached to the incoming trace.\n */\nconst continueTrace = (\n options\n\n,\n callback,\n) => {\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.continueTrace) {\n return acs.continueTrace(options, callback);\n }\n\n const { sentryTrace, baggage } = options;\n\n const client = getClient();\n const incomingDsc = baggageHeaderToDynamicSamplingContext(baggage);\n if (client && !shouldContinueTrace(client, incomingDsc?.org_id)) {\n return startNewTrace(callback);\n }\n\n return withScope(scope => {\n const propagationContext = propagationContextFromHeaders(sentryTrace, baggage);\n scope.setPropagationContext(propagationContext);\n _setSpanForScope(scope, undefined);\n return callback();\n });\n};\n\n/**\n * Forks the current scope and sets the provided span as active span in the context of the provided callback. Can be\n * passed `null` to start an entirely new span tree.\n *\n * @param span Spans started in the context of the provided callback will be children of this span. If `null` is passed,\n * spans started within the callback will not be attached to a parent span.\n * @param callback Execution context in which the provided span will be active. Is passed the newly forked scope.\n * @returns the value returned from the provided callback function.\n */\nfunction withActiveSpan(span, callback) {\n const acs = getAcs();\n if (acs.withActiveSpan) {\n return acs.withActiveSpan(span, callback);\n }\n\n return withScope(scope => {\n _setSpanForScope(scope, span || undefined);\n return callback(scope);\n });\n}\n\n/** Suppress tracing in the given callback, ensuring no spans are generated inside of it. */\nfunction suppressTracing(callback) {\n const acs = getAcs();\n\n if (acs.suppressTracing) {\n return acs.suppressTracing(callback);\n }\n\n return withScope(scope => {\n // Note: We do not wait for the callback to finish before we reset the metadata\n // the reason for this is that otherwise, in the browser this can lead to very weird behavior\n // as there is only a single top scope, if the callback takes longer to finish,\n // other, unrelated spans may also be suppressed, which we do not want\n // so instead, we only suppress tracing synchronoysly in the browser\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: true });\n const res = callback();\n scope.setSDKProcessingMetadata({ [SUPPRESS_TRACING_KEY]: undefined });\n return res;\n });\n}\n\n/**\n * Starts a new trace for the duration of the provided callback. Spans started within the\n * callback will be part of the new trace instead of a potentially previously started trace.\n *\n * Important: Only use this function if you want to override the default trace lifetime and\n * propagation mechanism of the SDK for the duration and scope of the provided callback.\n * The newly created trace will also be the root of a new distributed trace, for example if\n * you make http requests within the callback.\n * This function might be useful if the operation you want to instrument should not be part\n * of a potentially ongoing trace.\n *\n * Default behavior:\n * - Server-side: A new trace is started for each incoming request.\n * - Browser: A new trace is started for each page our route. Navigating to a new route\n * or page will automatically create a new trace.\n */\nfunction startNewTrace(callback) {\n return withScope(scope => {\n scope.setPropagationContext({\n traceId: generateTraceId(),\n sampleRand: Math.random(),\n });\n DEBUG_BUILD && debug.log(`Starting a new trace with id ${scope.getPropagationContext().traceId}`);\n return withActiveSpan(null, callback);\n });\n}\n\nfunction createChildOrRootSpan({\n parentSpan,\n spanArguments,\n forceTransaction,\n scope,\n}\n\n) {\n if (!hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n // If this is a root span, we ensure to freeze a DSC\n // So we can have at least partial data here\n if (forceTransaction || !parentSpan) {\n const dsc = {\n sampled: 'false',\n sample_rate: '0',\n transaction: spanArguments.name,\n ...getDynamicSamplingContextFromSpan(span),\n } ;\n freezeDscOnSpan(span, dsc);\n }\n\n return span;\n }\n\n const isolationScope = getIsolationScope();\n\n let span;\n if (parentSpan && !forceTransaction) {\n span = _startChildSpan(parentSpan, scope, spanArguments);\n addChildSpanToSpan(parentSpan, span);\n } else if (parentSpan) {\n // If we forced a transaction but have a parent span, make sure to continue from the parent span, not the scope\n const dsc = getDynamicSamplingContextFromSpan(parentSpan);\n const { traceId, spanId: parentSpanId } = parentSpan.spanContext();\n const parentSampled = spanIsSampled(parentSpan);\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n freezeDscOnSpan(span, dsc);\n } else {\n const {\n traceId,\n dsc,\n parentSpanId,\n sampled: parentSampled,\n } = {\n ...isolationScope.getPropagationContext(),\n ...scope.getPropagationContext(),\n };\n\n span = _startRootSpan(\n {\n traceId,\n parentSpanId,\n ...spanArguments,\n },\n scope,\n parentSampled,\n );\n\n if (dsc) {\n freezeDscOnSpan(span, dsc);\n }\n }\n\n logSpanStart(span);\n\n setCapturedScopesOnSpan(span, scope, isolationScope);\n\n return span;\n}\n\n/**\n * This converts StartSpanOptions to SentrySpanArguments.\n * For the most part (for now) we accept the same options,\n * but some of them need to be transformed.\n */\nfunction parseSentrySpanArguments(options) {\n const exp = options.experimental || {};\n const initialCtx = {\n isStandalone: exp.standalone,\n ...options,\n };\n\n if (options.startTime) {\n const ctx = { ...initialCtx };\n ctx.startTimestamp = spanTimeInputToSeconds(options.startTime);\n delete ctx.startTime;\n return ctx;\n }\n\n return initialCtx;\n}\n\nfunction getAcs() {\n const carrier = getMainCarrier();\n return getAsyncContextStrategy(carrier);\n}\n\nfunction _startRootSpan(spanArguments, scope, parentSampled) {\n const client = getClient();\n const options = client?.getOptions() || {};\n\n const { name = '' } = spanArguments;\n\n const mutableSpanSamplingData = { spanAttributes: { ...spanArguments.attributes }, spanName: name, parentSampled };\n\n // we don't care about the decision for the moment; this is just a placeholder\n client?.emit('beforeSampling', mutableSpanSamplingData, { decision: false });\n\n // If hook consumers override the parentSampled flag, we will use that value instead of the actual one\n const finalParentSampled = mutableSpanSamplingData.parentSampled ?? parentSampled;\n const finalAttributes = mutableSpanSamplingData.spanAttributes;\n\n const currentPropagationContext = scope.getPropagationContext();\n const [sampled, sampleRate, localSampleRateWasApplied] = scope.getScopeData().sdkProcessingMetadata[\n SUPPRESS_TRACING_KEY\n ]\n ? [false]\n : sampleSpan(\n options,\n {\n name,\n parentSampled: finalParentSampled,\n attributes: finalAttributes,\n parentSampleRate: parseSampleRate(currentPropagationContext.dsc?.sample_rate),\n },\n currentPropagationContext.sampleRand,\n );\n\n const rootSpan = new SentrySpan({\n ...spanArguments,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'custom',\n [SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE]:\n sampleRate !== undefined && localSampleRateWasApplied ? sampleRate : undefined,\n ...finalAttributes,\n },\n sampled,\n });\n\n if (!sampled && client) {\n DEBUG_BUILD && debug.log('[Tracing] Discarding root span because its trace was not chosen to be sampled.');\n client.recordDroppedEvent('sample_rate', 'transaction');\n }\n\n if (client) {\n client.emit('spanStart', rootSpan);\n }\n\n return rootSpan;\n}\n\n/**\n * Creates a new `Span` while setting the current `Span.id` as `parentSpanId`.\n * This inherits the sampling decision from the parent span.\n */\nfunction _startChildSpan(parentSpan, scope, spanArguments) {\n const { spanId, traceId } = parentSpan.spanContext();\n const sampled = scope.getScopeData().sdkProcessingMetadata[SUPPRESS_TRACING_KEY] ? false : spanIsSampled(parentSpan);\n\n const childSpan = sampled\n ? new SentrySpan({\n ...spanArguments,\n parentSpanId: spanId,\n traceId,\n sampled,\n })\n : new SentryNonRecordingSpan({ traceId });\n\n addChildSpanToSpan(parentSpan, childSpan);\n\n const client = getClient();\n if (client) {\n client.emit('spanStart', childSpan);\n // If it has an endTimestamp, it's already ended\n if (spanArguments.endTimestamp) {\n client.emit('spanEnd', childSpan);\n }\n }\n\n return childSpan;\n}\n\nfunction getParentSpan(scope, customParentSpan) {\n // always use the passed in span directly\n if (customParentSpan) {\n return customParentSpan ;\n }\n\n // This is different from `undefined` as it means the user explicitly wants no parent span\n if (customParentSpan === null) {\n return undefined;\n }\n\n const span = _getSpanForScope(scope) ;\n\n if (!span) {\n return undefined;\n }\n\n const client = getClient();\n const options = client ? client.getOptions() : {};\n if (options.parentSpanIsAlwaysRootSpan) {\n return getRootSpan(span) ;\n }\n\n return span;\n}\n\nfunction getActiveSpanWrapper(parentSpan) {\n return parentSpan !== undefined\n ? (callback) => {\n return withActiveSpan(parentSpan, callback);\n }\n : (callback) => callback();\n}\n\nexport { continueTrace, startInactiveSpan, startNewTrace, startSpan, startSpanManual, suppressTracing, withActiveSpan };\n//# sourceMappingURL=trace.js.map\n","import { getClient, getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { hasSpansEnabled } from '../utils/hasSpansEnabled.js';\nimport { shouldIgnoreSpan } from '../utils/should-ignore-span.js';\nimport { _setSpanForScope } from '../utils/spanOnScope.js';\nimport { getActiveSpan, spanTimeInputToSeconds, getSpanDescendants, spanToJSON, removeChildSpanFromSpan } from '../utils/spanUtils.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { getDynamicSamplingContextFromSpan, freezeDscOnSpan } from './dynamicSamplingContext.js';\nimport { SentryNonRecordingSpan } from './sentryNonRecordingSpan.js';\nimport { SentrySpan } from './sentrySpan.js';\nimport { SPAN_STATUS_OK, SPAN_STATUS_ERROR } from './spanstatus.js';\nimport { startInactiveSpan } from './trace.js';\n\nconst TRACING_DEFAULTS = {\n idleTimeout: 1000,\n finalTimeout: 30000,\n childSpanTimeout: 15000,\n};\n\nconst FINISH_REASON_HEARTBEAT_FAILED = 'heartbeatFailed';\nconst FINISH_REASON_IDLE_TIMEOUT = 'idleTimeout';\nconst FINISH_REASON_FINAL_TIMEOUT = 'finalTimeout';\nconst FINISH_REASON_EXTERNAL_FINISH = 'externalFinish';\n\n/**\n * An idle span is a span that automatically finishes. It does this by tracking child spans as activities.\n * An idle span is always the active span.\n */\nfunction startIdleSpan(startSpanOptions, options = {}) {\n // Activities store a list of active spans\n const activities = new Map();\n\n // We should not use heartbeat if we finished a span\n let _finished = false;\n\n // Timer that tracks idleTimeout\n let _idleTimeoutID;\n\n // The reason why the span was finished\n let _finishReason = FINISH_REASON_EXTERNAL_FINISH;\n\n let _autoFinishAllowed = !options.disableAutoFinish;\n\n const _cleanupHooks = [];\n\n const {\n idleTimeout = TRACING_DEFAULTS.idleTimeout,\n finalTimeout = TRACING_DEFAULTS.finalTimeout,\n childSpanTimeout = TRACING_DEFAULTS.childSpanTimeout,\n beforeSpanEnd,\n trimIdleSpanEndTimestamp = true,\n } = options;\n\n const client = getClient();\n\n if (!client || !hasSpansEnabled()) {\n const span = new SentryNonRecordingSpan();\n\n const dsc = {\n sample_rate: '0',\n sampled: 'false',\n ...getDynamicSamplingContextFromSpan(span),\n } ;\n freezeDscOnSpan(span, dsc);\n\n return span;\n }\n\n const scope = getCurrentScope();\n const previousActiveSpan = getActiveSpan();\n const span = _startIdleSpan(startSpanOptions);\n\n // We patch span.end to ensure we can run some things before the span is ended\n // eslint-disable-next-line @typescript-eslint/unbound-method\n span.end = new Proxy(span.end, {\n apply(target, thisArg, args) {\n if (beforeSpanEnd) {\n beforeSpanEnd(span);\n }\n\n // If the span is non-recording, nothing more to do here...\n // This is the case if tracing is enabled but this specific span was not sampled\n if (thisArg instanceof SentryNonRecordingSpan) {\n return;\n }\n\n // Just ensuring that this keeps working, even if we ever have more arguments here\n const [definedEndTimestamp, ...rest] = args;\n const timestamp = definedEndTimestamp || timestampInSeconds();\n const spanEndTimestamp = spanTimeInputToSeconds(timestamp);\n\n // Ensure we end with the last span timestamp, if possible\n const spans = getSpanDescendants(span).filter(child => child !== span);\n\n const spanJson = spanToJSON(span);\n\n // If we have no spans, we just end, nothing else to do here\n // Likewise, if users explicitly ended the span, we simply end the span without timestamp adjustment\n if (!spans.length || !trimIdleSpanEndTimestamp) {\n onIdleSpanEnded(spanEndTimestamp);\n return Reflect.apply(target, thisArg, [spanEndTimestamp, ...rest]);\n }\n\n const ignoreSpans = client.getOptions().ignoreSpans;\n\n const latestSpanEndTimestamp = spans?.reduce((acc, current) => {\n const currentSpanJson = spanToJSON(current);\n if (!currentSpanJson.timestamp) {\n return acc;\n }\n // Ignored spans will get dropped later (in the client) but since we already adjust\n // the idle span end timestamp here, we can already take to-be-ignored spans out of\n // the calculation here.\n if (ignoreSpans && shouldIgnoreSpan(currentSpanJson, ignoreSpans)) {\n return acc;\n }\n return acc ? Math.max(acc, currentSpanJson.timestamp) : currentSpanJson.timestamp;\n }, undefined);\n\n // In reality this should always exist here, but type-wise it may be undefined...\n const spanStartTimestamp = spanJson.start_timestamp;\n\n // The final endTimestamp should:\n // * Never be before the span start timestamp\n // * Be the latestSpanEndTimestamp, if there is one, and it is smaller than the passed span end timestamp\n // * Otherwise be the passed end timestamp\n // Final timestamp can never be after finalTimeout\n const endTimestamp = Math.min(\n spanStartTimestamp ? spanStartTimestamp + finalTimeout / 1000 : Infinity,\n Math.max(spanStartTimestamp || -Infinity, Math.min(spanEndTimestamp, latestSpanEndTimestamp || Infinity)),\n );\n\n onIdleSpanEnded(endTimestamp);\n return Reflect.apply(target, thisArg, [endTimestamp, ...rest]);\n },\n });\n\n /**\n * Cancels the existing idle timeout, if there is one.\n */\n function _cancelIdleTimeout() {\n if (_idleTimeoutID) {\n clearTimeout(_idleTimeoutID);\n _idleTimeoutID = undefined;\n }\n }\n\n /**\n * Restarts idle timeout, if there is no running idle timeout it will start one.\n */\n function _restartIdleTimeout(endTimestamp) {\n _cancelIdleTimeout();\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && activities.size === 0 && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_IDLE_TIMEOUT;\n span.end(endTimestamp);\n }\n }, idleTimeout);\n }\n\n /**\n * Restarts child span timeout, if there is none running it will start one.\n */\n function _restartChildSpanTimeout(endTimestamp) {\n _idleTimeoutID = setTimeout(() => {\n if (!_finished && _autoFinishAllowed) {\n _finishReason = FINISH_REASON_HEARTBEAT_FAILED;\n span.end(endTimestamp);\n }\n }, childSpanTimeout);\n }\n\n /**\n * Start tracking a specific activity.\n * @param spanId The span id that represents the activity\n */\n function _pushActivity(spanId) {\n _cancelIdleTimeout();\n activities.set(spanId, true);\n\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartChildSpanTimeout(endTimestamp + childSpanTimeout / 1000);\n }\n\n /**\n * Remove an activity from usage\n * @param spanId The span id that represents the activity\n */\n function _popActivity(spanId) {\n if (activities.has(spanId)) {\n activities.delete(spanId);\n }\n\n if (activities.size === 0) {\n const endTimestamp = timestampInSeconds();\n // We need to add the timeout here to have the real endtimestamp of the idle span\n // Remember timestampInSeconds is in seconds, timeout is in ms\n _restartIdleTimeout(endTimestamp + idleTimeout / 1000);\n }\n }\n\n function onIdleSpanEnded(endTimestamp) {\n _finished = true;\n activities.clear();\n\n _cleanupHooks.forEach(cleanup => cleanup());\n\n _setSpanForScope(scope, previousActiveSpan);\n\n const spanJSON = spanToJSON(span);\n\n const { start_timestamp: startTimestamp } = spanJSON;\n // This should never happen, but to make TS happy...\n if (!startTimestamp) {\n return;\n }\n\n const attributes = spanJSON.data;\n if (!attributes[SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON]) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON, _finishReason);\n }\n\n // Set span status to 'ok' if it hasn't been explicitly set to an error status\n const currentStatus = spanJSON.status;\n if (!currentStatus || currentStatus === 'unknown') {\n span.setStatus({ code: SPAN_STATUS_OK });\n }\n\n debug.log(`[Tracing] Idle span \"${spanJSON.op}\" finished`);\n\n const childSpans = getSpanDescendants(span).filter(child => child !== span);\n\n let discardedSpans = 0;\n childSpans.forEach(childSpan => {\n // We cancel all pending spans with status \"cancelled\" to indicate the idle span was finished early\n if (childSpan.isRecording()) {\n childSpan.setStatus({ code: SPAN_STATUS_ERROR, message: 'cancelled' });\n childSpan.end(endTimestamp);\n DEBUG_BUILD &&\n debug.log('[Tracing] Cancelling span since span ended early', JSON.stringify(childSpan, undefined, 2));\n }\n\n const childSpanJSON = spanToJSON(childSpan);\n const { timestamp: childEndTimestamp = 0, start_timestamp: childStartTimestamp = 0 } = childSpanJSON;\n\n const spanStartedBeforeIdleSpanEnd = childStartTimestamp <= endTimestamp;\n\n // Add a delta with idle timeout so that we prevent false positives\n const timeoutWithMarginOfError = (finalTimeout + idleTimeout) / 1000;\n const spanEndedBeforeFinalTimeout = childEndTimestamp - childStartTimestamp <= timeoutWithMarginOfError;\n\n if (DEBUG_BUILD) {\n const stringifiedSpan = JSON.stringify(childSpan, undefined, 2);\n if (!spanStartedBeforeIdleSpanEnd) {\n debug.log('[Tracing] Discarding span since it happened after idle span was finished', stringifiedSpan);\n } else if (!spanEndedBeforeFinalTimeout) {\n debug.log('[Tracing] Discarding span since it finished after idle span final timeout', stringifiedSpan);\n }\n }\n\n if (!spanEndedBeforeFinalTimeout || !spanStartedBeforeIdleSpanEnd) {\n removeChildSpanFromSpan(span, childSpan);\n discardedSpans++;\n }\n });\n\n if (discardedSpans > 0) {\n span.setAttribute('sentry.idle_span_discarded_spans', discardedSpans);\n }\n }\n\n _cleanupHooks.push(\n client.on('spanStart', startedSpan => {\n // If we already finished the idle span,\n // or if this is the idle span itself being started,\n // or if the started span has already been closed,\n // we don't care about it for activity\n if (\n _finished ||\n startedSpan === span ||\n !!spanToJSON(startedSpan).timestamp ||\n (startedSpan instanceof SentrySpan && startedSpan.isStandaloneSpan())\n ) {\n return;\n }\n\n const allSpans = getSpanDescendants(span);\n\n // If the span that was just started is a child of the idle span, we should track it\n if (allSpans.includes(startedSpan)) {\n _pushActivity(startedSpan.spanContext().spanId);\n }\n }),\n );\n\n _cleanupHooks.push(\n client.on('spanEnd', endedSpan => {\n if (_finished) {\n return;\n }\n\n _popActivity(endedSpan.spanContext().spanId);\n }),\n );\n\n _cleanupHooks.push(\n client.on('idleSpanEnableAutoFinish', spanToAllowAutoFinish => {\n if (spanToAllowAutoFinish === span) {\n _autoFinishAllowed = true;\n _restartIdleTimeout();\n\n if (activities.size) {\n _restartChildSpanTimeout();\n }\n }\n }),\n );\n\n // We only start the initial idle timeout if we are not delaying the auto finish\n if (!options.disableAutoFinish) {\n _restartIdleTimeout();\n }\n\n setTimeout(() => {\n if (!_finished) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'deadline_exceeded' });\n _finishReason = FINISH_REASON_FINAL_TIMEOUT;\n span.end();\n }\n }, finalTimeout);\n\n return span;\n}\n\nfunction _startIdleSpan(options) {\n const span = startInactiveSpan(options);\n\n _setSpanForScope(getCurrentScope(), span);\n\n DEBUG_BUILD && debug.log('[Tracing] Started span is an idle span');\n\n return span;\n}\n\nexport { TRACING_DEFAULTS, startIdleSpan };\n//# sourceMappingURL=idleSpan.js.map\n","import { isThenable } from './is.js';\n\n/* eslint-disable @typescript-eslint/no-explicit-any */\n\n/** SyncPromise internal states */\nconst STATE_PENDING = 0;\nconst STATE_RESOLVED = 1;\nconst STATE_REJECTED = 2;\n\n/**\n * Creates a resolved sync promise.\n *\n * @param value the value to resolve the promise with\n * @returns the resolved sync promise\n */\nfunction resolvedSyncPromise(value) {\n return new SyncPromise(resolve => {\n resolve(value);\n });\n}\n\n/**\n * Creates a rejected sync promise.\n *\n * @param value the value to reject the promise with\n * @returns the rejected sync promise\n */\nfunction rejectedSyncPromise(reason) {\n return new SyncPromise((_, reject) => {\n reject(reason);\n });\n}\n\n/**\n * Thenable class that behaves like a Promise and follows it's interface\n * but is not async internally\n */\nclass SyncPromise {\n\n constructor(executor) {\n this._state = STATE_PENDING;\n this._handlers = [];\n\n this._runExecutor(executor);\n }\n\n /** @inheritdoc */\n then(\n onfulfilled,\n onrejected,\n ) {\n return new SyncPromise((resolve, reject) => {\n this._handlers.push([\n false,\n result => {\n if (!onfulfilled) {\n // TODO: ¯\\_(ツ)_/¯\n // TODO: FIXME\n resolve(result );\n } else {\n try {\n resolve(onfulfilled(result));\n } catch (e) {\n reject(e);\n }\n }\n },\n reason => {\n if (!onrejected) {\n reject(reason);\n } else {\n try {\n resolve(onrejected(reason));\n } catch (e) {\n reject(e);\n }\n }\n },\n ]);\n this._executeHandlers();\n });\n }\n\n /** @inheritdoc */\n catch(\n onrejected,\n ) {\n return this.then(val => val, onrejected);\n }\n\n /** @inheritdoc */\n finally(onfinally) {\n return new SyncPromise((resolve, reject) => {\n let val;\n let isRejected;\n\n return this.then(\n value => {\n isRejected = false;\n val = value;\n if (onfinally) {\n onfinally();\n }\n },\n reason => {\n isRejected = true;\n val = reason;\n if (onfinally) {\n onfinally();\n }\n },\n ).then(() => {\n if (isRejected) {\n reject(val);\n return;\n }\n\n resolve(val );\n });\n });\n }\n\n /** Excute the resolve/reject handlers. */\n _executeHandlers() {\n if (this._state === STATE_PENDING) {\n return;\n }\n\n const cachedHandlers = this._handlers.slice();\n this._handlers = [];\n\n cachedHandlers.forEach(handler => {\n if (handler[0]) {\n return;\n }\n\n if (this._state === STATE_RESOLVED) {\n handler[1](this._value );\n }\n\n if (this._state === STATE_REJECTED) {\n handler[2](this._value);\n }\n\n handler[0] = true;\n });\n }\n\n /** Run the executor for the SyncPromise. */\n _runExecutor(executor) {\n const setResult = (state, value) => {\n if (this._state !== STATE_PENDING) {\n return;\n }\n\n if (isThenable(value)) {\n void (value ).then(resolve, reject);\n return;\n }\n\n this._state = state;\n this._value = value;\n\n this._executeHandlers();\n };\n\n const resolve = (value) => {\n setResult(STATE_RESOLVED, value);\n };\n\n const reject = (reason) => {\n setResult(STATE_REJECTED, reason);\n };\n\n try {\n executor(resolve, reject);\n } catch (e) {\n reject(e);\n }\n }\n}\n\nexport { SyncPromise, rejectedSyncPromise, resolvedSyncPromise };\n//# sourceMappingURL=syncpromise.js.map\n","import { DEBUG_BUILD } from './debug-build.js';\nimport { debug } from './utils/debug-logger.js';\nimport { isThenable } from './utils/is.js';\nimport { resolvedSyncPromise, rejectedSyncPromise } from './utils/syncpromise.js';\n\n/**\n * Process an array of event processors, returning the processed event (or `null` if the event was dropped).\n */\nfunction notifyEventProcessors(\n processors,\n event,\n hint,\n index = 0,\n) {\n try {\n const result = _notifyEventProcessors(event, hint, processors, index);\n return isThenable(result) ? result : resolvedSyncPromise(result);\n } catch (error) {\n return rejectedSyncPromise(error);\n }\n}\n\nfunction _notifyEventProcessors(\n event,\n hint,\n processors,\n index,\n) {\n const processor = processors[index];\n\n if (!event || !processor) {\n return event;\n }\n\n const result = processor({ ...event }, hint);\n\n DEBUG_BUILD && result === null && debug.log(`Event processor \"${processor.id || '?'}\" dropped event`);\n\n if (isThenable(result)) {\n return result.then(final => _notifyEventProcessors(final, hint, processors, index + 1));\n }\n\n return _notifyEventProcessors(result, hint, processors, index + 1);\n}\n\nexport { notifyEventProcessors };\n//# sourceMappingURL=eventProcessors.js.map\n","import { getDynamicSamplingContextFromSpan } from '../tracing/dynamicSamplingContext.js';\nimport { merge } from './merge.js';\nimport { spanToTraceContext, getRootSpan, spanToJSON } from './spanUtils.js';\n\n/**\n * Applies data from the scope to the event and runs all event processors on it.\n */\nfunction applyScopeDataToEvent(event, data) {\n const { fingerprint, span, breadcrumbs, sdkProcessingMetadata } = data;\n\n // Apply general data\n applyDataToEvent(event, data);\n\n // We want to set the trace context for normal events only if there isn't already\n // a trace context on the event. There is a product feature in place where we link\n // errors with transaction and it relies on that.\n if (span) {\n applySpanToEvent(event, span);\n }\n\n applyFingerprintToEvent(event, fingerprint);\n applyBreadcrumbsToEvent(event, breadcrumbs);\n applySdkMetadataToEvent(event, sdkProcessingMetadata);\n}\n\n/** Merge data of two scopes together. */\nfunction mergeScopeData(data, mergeData) {\n const {\n extra,\n tags,\n attributes,\n user,\n contexts,\n level,\n sdkProcessingMetadata,\n breadcrumbs,\n fingerprint,\n eventProcessors,\n attachments,\n propagationContext,\n transactionName,\n span,\n } = mergeData;\n\n mergeAndOverwriteScopeData(data, 'extra', extra);\n mergeAndOverwriteScopeData(data, 'tags', tags);\n mergeAndOverwriteScopeData(data, 'attributes', attributes);\n mergeAndOverwriteScopeData(data, 'user', user);\n mergeAndOverwriteScopeData(data, 'contexts', contexts);\n\n data.sdkProcessingMetadata = merge(data.sdkProcessingMetadata, sdkProcessingMetadata, 2);\n\n if (level) {\n data.level = level;\n }\n\n if (transactionName) {\n data.transactionName = transactionName;\n }\n\n if (span) {\n data.span = span;\n }\n\n if (breadcrumbs.length) {\n data.breadcrumbs = [...data.breadcrumbs, ...breadcrumbs];\n }\n\n if (fingerprint.length) {\n data.fingerprint = [...data.fingerprint, ...fingerprint];\n }\n\n if (eventProcessors.length) {\n data.eventProcessors = [...data.eventProcessors, ...eventProcessors];\n }\n\n if (attachments.length) {\n data.attachments = [...data.attachments, ...attachments];\n }\n\n data.propagationContext = { ...data.propagationContext, ...propagationContext };\n}\n\n/**\n * Merges certain scope data. Undefined values will overwrite any existing values.\n * Exported only for tests.\n */\nfunction mergeAndOverwriteScopeData\n\n(data, prop, mergeVal) {\n data[prop] = merge(data[prop], mergeVal, 1);\n}\n\nfunction applyDataToEvent(event, data) {\n const { extra, tags, user, contexts, level, transactionName } = data;\n\n if (Object.keys(extra).length) {\n event.extra = { ...extra, ...event.extra };\n }\n\n if (Object.keys(tags).length) {\n event.tags = { ...tags, ...event.tags };\n }\n\n if (Object.keys(user).length) {\n event.user = { ...user, ...event.user };\n }\n\n if (Object.keys(contexts).length) {\n event.contexts = { ...contexts, ...event.contexts };\n }\n\n if (level) {\n event.level = level;\n }\n\n // transaction events get their `transaction` from the root span name\n if (transactionName && event.type !== 'transaction') {\n event.transaction = transactionName;\n }\n}\n\nfunction applyBreadcrumbsToEvent(event, breadcrumbs) {\n const mergedBreadcrumbs = [...(event.breadcrumbs || []), ...breadcrumbs];\n event.breadcrumbs = mergedBreadcrumbs.length ? mergedBreadcrumbs : undefined;\n}\n\nfunction applySdkMetadataToEvent(event, sdkProcessingMetadata) {\n event.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n ...sdkProcessingMetadata,\n };\n}\n\nfunction applySpanToEvent(event, span) {\n event.contexts = {\n trace: spanToTraceContext(span),\n ...event.contexts,\n };\n\n event.sdkProcessingMetadata = {\n dynamicSamplingContext: getDynamicSamplingContextFromSpan(span),\n ...event.sdkProcessingMetadata,\n };\n\n const rootSpan = getRootSpan(span);\n const transactionName = spanToJSON(rootSpan).description;\n if (transactionName && !event.transaction && event.type === 'transaction') {\n event.transaction = transactionName;\n }\n}\n\n/**\n * Applies fingerprint from the scope to the event if there's one,\n * uses message if there's one instead or get rid of empty fingerprint\n */\nfunction applyFingerprintToEvent(event, fingerprint) {\n // Make sure it's an array first and we actually have something in place\n event.fingerprint = event.fingerprint\n ? Array.isArray(event.fingerprint)\n ? event.fingerprint\n : [event.fingerprint]\n : [];\n\n // If we have something on the scope, then merge it with event\n if (fingerprint) {\n event.fingerprint = event.fingerprint.concat(fingerprint);\n }\n\n // If we have no data at all, remove empty array default\n if (!event.fingerprint.length) {\n delete event.fingerprint;\n }\n}\n\nexport { applyScopeDataToEvent, mergeAndOverwriteScopeData, mergeScopeData };\n//# sourceMappingURL=applyScopeDataToEvent.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\nlet parsedStackResults;\nlet lastSentryKeysCount;\nlet lastNativeKeysCount;\nlet cachedFilenameDebugIds;\n\n/**\n * Returns a map of filenames to debug identifiers.\n * Supports both proprietary _sentryDebugIds and native _debugIds (e.g., from Vercel) formats.\n */\nfunction getFilenameToDebugIdMap(stackParser) {\n const sentryDebugIdMap = GLOBAL_OBJ._sentryDebugIds;\n const nativeDebugIdMap = GLOBAL_OBJ._debugIds;\n\n if (!sentryDebugIdMap && !nativeDebugIdMap) {\n return {};\n }\n\n const sentryDebugIdKeys = sentryDebugIdMap ? Object.keys(sentryDebugIdMap) : [];\n const nativeDebugIdKeys = nativeDebugIdMap ? Object.keys(nativeDebugIdMap) : [];\n\n // If the count of registered globals hasn't changed since the last call, we\n // can just return the cached result.\n if (\n cachedFilenameDebugIds &&\n sentryDebugIdKeys.length === lastSentryKeysCount &&\n nativeDebugIdKeys.length === lastNativeKeysCount\n ) {\n return cachedFilenameDebugIds;\n }\n\n lastSentryKeysCount = sentryDebugIdKeys.length;\n lastNativeKeysCount = nativeDebugIdKeys.length;\n\n // Build a map of filename -> debug_id from both sources\n cachedFilenameDebugIds = {};\n\n if (!parsedStackResults) {\n parsedStackResults = {};\n }\n\n const processDebugIds = (debugIdKeys, debugIdMap) => {\n for (const key of debugIdKeys) {\n const debugId = debugIdMap[key];\n const result = parsedStackResults?.[key];\n\n if (result && cachedFilenameDebugIds && debugId) {\n // Use cached filename but update with current debug ID\n cachedFilenameDebugIds[result[0]] = debugId;\n // Update cached result with new debug ID\n if (parsedStackResults) {\n parsedStackResults[key] = [result[0], debugId];\n }\n } else if (debugId) {\n const parsedStack = stackParser(key);\n\n for (let i = parsedStack.length - 1; i >= 0; i--) {\n const stackFrame = parsedStack[i];\n const filename = stackFrame?.filename;\n\n if (filename && cachedFilenameDebugIds && parsedStackResults) {\n cachedFilenameDebugIds[filename] = debugId;\n parsedStackResults[key] = [filename, debugId];\n break;\n }\n }\n }\n }\n };\n\n if (sentryDebugIdMap) {\n processDebugIds(sentryDebugIdKeys, sentryDebugIdMap);\n }\n\n // Native _debugIds will override _sentryDebugIds if same file\n if (nativeDebugIdMap) {\n processDebugIds(nativeDebugIdKeys, nativeDebugIdMap);\n }\n\n return cachedFilenameDebugIds;\n}\n\n/**\n * Returns a list of debug images for the given resources.\n */\nfunction getDebugImagesForResources(\n stackParser,\n resource_paths,\n) {\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n if (!filenameDebugIdMap) {\n return [];\n }\n\n const images = [];\n for (const path of resource_paths) {\n if (path && filenameDebugIdMap[path]) {\n images.push({\n type: 'sourcemap',\n code_file: path,\n debug_id: filenameDebugIdMap[path],\n });\n }\n }\n\n return images;\n}\n\nexport { getDebugImagesForResources, getFilenameToDebugIdMap };\n//# sourceMappingURL=debug-ids.js.map\n","import { DEFAULT_ENVIRONMENT } from '../constants.js';\nimport { getGlobalScope } from '../currentScopes.js';\nimport { notifyEventProcessors } from '../eventProcessors.js';\nimport { Scope } from '../scope.js';\nimport { mergeScopeData, applyScopeDataToEvent } from './applyScopeDataToEvent.js';\nimport { getFilenameToDebugIdMap } from './debug-ids.js';\nimport { uuid4, addExceptionMechanism } from './misc.js';\nimport { normalize } from './normalize.js';\nimport { truncate } from './string.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * This type makes sure that we get either a CaptureContext, OR an EventHint.\n * It does not allow mixing them, which could lead to unexpected outcomes, e.g. this is disallowed:\n * { user: { id: '123' }, mechanism: { handled: false } }\n */\n\n/**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param scope A scope containing event metadata.\n * @returns A new event with more information.\n * @hidden\n */\nfunction prepareEvent(\n options,\n event,\n hint,\n scope,\n client,\n isolationScope,\n) {\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = options;\n const prepared = {\n ...event,\n event_id: event.event_id || hint.event_id || uuid4(),\n timestamp: event.timestamp || dateTimestampInSeconds(),\n };\n const integrations = hint.integrations || options.integrations.map(i => i.name);\n\n applyClientOptions(prepared, options);\n applyIntegrationsMetadata(prepared, integrations);\n\n if (client) {\n client.emit('applyFrameMetadata', event);\n }\n\n // Only put debug IDs onto frames for error events.\n if (event.type === undefined) {\n applyDebugIds(prepared, options.stackParser);\n }\n\n // If we have scope given to us, use it as the base for further modifications.\n // This allows us to prevent unnecessary copying of data if `captureContext` is not provided.\n const finalScope = getFinalScope(scope, hint.captureContext);\n\n if (hint.mechanism) {\n addExceptionMechanism(prepared, hint.mechanism);\n }\n\n const clientEventProcessors = client ? client.getEventProcessors() : [];\n\n // This should be the last thing called, since we want that\n // {@link Scope.addEventProcessor} gets the finished prepared event.\n // Merge scope data together\n const data = getGlobalScope().getScopeData();\n\n if (isolationScope) {\n const isolationData = isolationScope.getScopeData();\n mergeScopeData(data, isolationData);\n }\n\n if (finalScope) {\n const finalScopeData = finalScope.getScopeData();\n mergeScopeData(data, finalScopeData);\n }\n\n const attachments = [...(hint.attachments || []), ...data.attachments];\n if (attachments.length) {\n hint.attachments = attachments;\n }\n\n applyScopeDataToEvent(prepared, data);\n\n const eventProcessors = [\n ...clientEventProcessors,\n // Run scope event processors _after_ all other processors\n ...data.eventProcessors,\n ];\n\n const result = notifyEventProcessors(eventProcessors, prepared, hint);\n\n return result.then(evt => {\n if (evt) {\n // We apply the debug_meta field only after all event processors have ran, so that if any event processors modified\n // file names (e.g.the RewriteFrames integration) the filename -> debug ID relationship isn't destroyed.\n // This should not cause any PII issues, since we're only moving data that is already on the event and not adding\n // any new data\n applyDebugMeta(evt);\n }\n\n if (typeof normalizeDepth === 'number' && normalizeDepth > 0) {\n return normalizeEvent(evt, normalizeDepth, normalizeMaxBreadth);\n }\n return evt;\n });\n}\n\n/**\n * Enhances event using the client configuration.\n * It takes care of all \"static\" values like environment, release and `dist`,\n * as well as truncating overly long values.\n *\n * Only exported for tests.\n *\n * @param event event instance to be enhanced\n */\nfunction applyClientOptions(event, options) {\n const { environment, release, dist, maxValueLength } = options;\n\n // empty strings do not make sense for environment, release, and dist\n // so we handle them the same as if they were not provided\n event.environment = event.environment || environment || DEFAULT_ENVIRONMENT;\n\n if (!event.release && release) {\n event.release = release;\n }\n\n if (!event.dist && dist) {\n event.dist = dist;\n }\n\n const request = event.request;\n if (request?.url && maxValueLength) {\n request.url = truncate(request.url, maxValueLength);\n }\n\n if (maxValueLength) {\n event.exception?.values?.forEach(exception => {\n if (exception.value) {\n // Truncates error messages\n exception.value = truncate(exception.value, maxValueLength);\n }\n });\n }\n}\n\n/**\n * Puts debug IDs into the stack frames of an error event.\n */\nfunction applyDebugIds(event, stackParser) {\n // Build a map of filename -> debug_id\n const filenameDebugIdMap = getFilenameToDebugIdMap(stackParser);\n\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (frame.filename) {\n frame.debug_id = filenameDebugIdMap[frame.filename];\n }\n });\n });\n}\n\n/**\n * Moves debug IDs from the stack frames of an error event into the debug_meta field.\n */\nfunction applyDebugMeta(event) {\n // Extract debug IDs and filenames from the stack frames on the event.\n const filenameDebugIdMap = {};\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (frame.debug_id) {\n if (frame.abs_path) {\n filenameDebugIdMap[frame.abs_path] = frame.debug_id;\n } else if (frame.filename) {\n filenameDebugIdMap[frame.filename] = frame.debug_id;\n }\n delete frame.debug_id;\n }\n });\n });\n\n if (Object.keys(filenameDebugIdMap).length === 0) {\n return;\n }\n\n // Fill debug_meta information\n event.debug_meta = event.debug_meta || {};\n event.debug_meta.images = event.debug_meta.images || [];\n const images = event.debug_meta.images;\n Object.entries(filenameDebugIdMap).forEach(([filename, debug_id]) => {\n images.push({\n type: 'sourcemap',\n code_file: filename,\n debug_id,\n });\n });\n}\n\n/**\n * This function adds all used integrations to the SDK info in the event.\n * @param event The event that will be filled with all integrations.\n */\nfunction applyIntegrationsMetadata(event, integrationNames) {\n if (integrationNames.length > 0) {\n event.sdk = event.sdk || {};\n event.sdk.integrations = [...(event.sdk.integrations || []), ...integrationNames];\n }\n}\n\n/**\n * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization.\n * Normalized keys:\n * - `breadcrumbs.data`\n * - `user`\n * - `contexts`\n * - `extra`\n * @param event Event\n * @returns Normalized event\n */\nfunction normalizeEvent(event, depth, maxBreadth) {\n if (!event) {\n return null;\n }\n\n const normalized = {\n ...event,\n ...(event.breadcrumbs && {\n breadcrumbs: event.breadcrumbs.map(b => ({\n ...b,\n ...(b.data && {\n data: normalize(b.data, depth, maxBreadth),\n }),\n })),\n }),\n ...(event.user && {\n user: normalize(event.user, depth, maxBreadth),\n }),\n ...(event.contexts && {\n contexts: normalize(event.contexts, depth, maxBreadth),\n }),\n ...(event.extra && {\n extra: normalize(event.extra, depth, maxBreadth),\n }),\n };\n\n // event.contexts.trace stores information about a Transaction. Similarly,\n // event.spans[] stores information about child Spans. Given that a\n // Transaction is conceptually a Span, normalization should apply to both\n // Transactions and Spans consistently.\n // For now the decision is to skip normalization of Transactions and Spans,\n // so this block overwrites the normalized event to add back the original\n // Transaction information prior to normalization.\n if (event.contexts?.trace && normalized.contexts) {\n normalized.contexts.trace = event.contexts.trace;\n\n // event.contexts.trace.data may contain circular/dangerous data so we need to normalize it\n if (event.contexts.trace.data) {\n normalized.contexts.trace.data = normalize(event.contexts.trace.data, depth, maxBreadth);\n }\n }\n\n // event.spans[].data may contain circular/dangerous data so we need to normalize it\n if (event.spans) {\n normalized.spans = event.spans.map(span => {\n return {\n ...span,\n ...(span.data && {\n data: normalize(span.data, depth, maxBreadth),\n }),\n };\n });\n }\n\n // event.contexts.flags (FeatureFlagContext) stores context for our feature\n // flag integrations. It has a greater nesting depth than our other typed\n // Contexts, so we re-normalize with a fixed depth of 3 here. We do not want\n // to skip this in case of conflicting, user-provided context.\n if (event.contexts?.flags && normalized.contexts) {\n normalized.contexts.flags = normalize(event.contexts.flags, 3, maxBreadth);\n }\n\n return normalized;\n}\n\nfunction getFinalScope(scope, captureContext) {\n if (!captureContext) {\n return scope;\n }\n\n const finalScope = scope ? scope.clone() : new Scope();\n finalScope.update(captureContext);\n return finalScope;\n}\n\n/**\n * Parse either an `EventHint` directly, or convert a `CaptureContext` to an `EventHint`.\n * This is used to allow to update method signatures that used to accept a `CaptureContext` but should now accept an `EventHint`.\n */\nfunction parseEventHintOrCaptureContext(\n hint,\n) {\n if (!hint) {\n return undefined;\n }\n\n // If you pass a Scope or `() => Scope` as CaptureContext, we just return this as captureContext\n if (hintIsScopeOrFunction(hint)) {\n return { captureContext: hint };\n }\n\n if (hintIsScopeContext(hint)) {\n return {\n captureContext: hint,\n };\n }\n\n return hint;\n}\n\nfunction hintIsScopeOrFunction(hint) {\n return hint instanceof Scope || typeof hint === 'function';\n}\n\nconst captureContextKeys = [\n 'user',\n 'level',\n 'extra',\n 'contexts',\n 'tags',\n 'fingerprint',\n 'propagationContext',\n] ;\n\nfunction hintIsScopeContext(hint) {\n return Object.keys(hint).some(key => captureContextKeys.includes(key ));\n}\n\nexport { applyClientOptions, applyDebugIds, applyDebugMeta, parseEventHintOrCaptureContext, prepareEvent };\n//# sourceMappingURL=prepareEvent.js.map\n","import { getCurrentScope, getClient, withIsolationScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { makeSession, updateSession, closeSession } from './session.js';\nimport { startNewTrace } from './tracing/trace.js';\nimport { debug } from './utils/debug-logger.js';\nimport { isThenable } from './utils/is.js';\nimport { uuid4 } from './utils/misc.js';\nimport { parseEventHintOrCaptureContext } from './utils/prepareEvent.js';\nimport { timestampInSeconds } from './utils/time.js';\nimport { GLOBAL_OBJ } from './utils/worldwide.js';\n\n/**\n * Captures an exception event and sends it to Sentry.\n *\n * @param exception The exception to capture.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured Sentry event.\n */\nfunction captureException(exception, hint) {\n return getCurrentScope().captureException(exception, parseEventHintOrCaptureContext(hint));\n}\n\n/**\n * Captures a message event and sends it to Sentry.\n *\n * @param message The message to send to Sentry.\n * @param captureContext Define the level of the message or pass in additional data to attach to the message.\n * @returns the id of the captured message.\n */\nfunction captureMessage(message, captureContext) {\n // This is necessary to provide explicit scopes upgrade, without changing the original\n // arity of the `captureMessage(message, level)` method.\n const level = typeof captureContext === 'string' ? captureContext : undefined;\n const hint = typeof captureContext !== 'string' ? { captureContext } : undefined;\n return getCurrentScope().captureMessage(message, level, hint);\n}\n\n/**\n * Captures a manually created event and sends it to Sentry.\n *\n * @param event The event to send to Sentry.\n * @param hint Optional additional data to attach to the Sentry event.\n * @returns the id of the captured event.\n */\nfunction captureEvent(event, hint) {\n return getCurrentScope().captureEvent(event, hint);\n}\n\n/**\n * Sets context data with the given name.\n * @param name of the context\n * @param context Any kind of data. This data will be normalized.\n */\nfunction setContext(name, context) {\n getIsolationScope().setContext(name, context);\n}\n\n/**\n * Set an object that will be merged sent as extra data with the event.\n * @param extras Extras object to merge into current context.\n */\nfunction setExtras(extras) {\n getIsolationScope().setExtras(extras);\n}\n\n/**\n * Set key:value that will be sent as extra data with the event.\n * @param key String of extra\n * @param extra Any kind of data. This data will be normalized.\n */\nfunction setExtra(key, extra) {\n getIsolationScope().setExtra(key, extra);\n}\n\n/**\n * Set an object that will be merged sent as tags data with the event.\n * @param tags Tags context object to merge into current context.\n */\nfunction setTags(tags) {\n getIsolationScope().setTags(tags);\n}\n\n/**\n * Set key:value that will be sent as tags data with the event.\n *\n * Can also be used to unset a tag, by passing `undefined`.\n *\n * @param key String key of tag\n * @param value Value of tag\n */\nfunction setTag(key, value) {\n getIsolationScope().setTag(key, value);\n}\n\n/**\n * Updates user context information for future events.\n *\n * @param user User context object to be set in the current context. Pass `null` to unset the user.\n */\nfunction setUser(user) {\n getIsolationScope().setUser(user);\n}\n\n/**\n * The last error event id of the isolation scope.\n *\n * Warning: This function really returns the last recorded error event id on the current\n * isolation scope. If you call this function after handling a certain error and another error\n * is captured in between, the last one is returned instead of the one you might expect.\n * Also, ids of events that were never sent to Sentry (for example because\n * they were dropped in `beforeSend`) could be returned.\n *\n * @returns The last event id of the isolation scope.\n */\nfunction lastEventId() {\n return getIsolationScope().lastEventId();\n}\n\n/**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction captureCheckIn(checkIn, upsertMonitorConfig) {\n const scope = getCurrentScope();\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('Cannot capture check-in. No client defined.');\n } else if (!client.captureCheckIn) {\n DEBUG_BUILD && debug.warn('Cannot capture check-in. Client does not support sending check-ins.');\n } else {\n return client.captureCheckIn(checkIn, upsertMonitorConfig, scope);\n }\n\n return uuid4();\n}\n\n/**\n * Wraps a callback with a cron monitor check in. The check in will be sent to Sentry when the callback finishes.\n *\n * @param monitorSlug The distinct slug of the monitor.\n * @param callback Callback to be monitored\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\nfunction withMonitor(\n monitorSlug,\n callback,\n upsertMonitorConfig,\n) {\n function runCallback() {\n const checkInId = captureCheckIn({ monitorSlug, status: 'in_progress' }, upsertMonitorConfig);\n const now = timestampInSeconds();\n\n function finishCheckIn(status) {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - now });\n }\n // Default behavior without isolateTrace\n let maybePromiseResult;\n try {\n maybePromiseResult = callback();\n } catch (e) {\n finishCheckIn('error');\n throw e;\n }\n\n if (isThenable(maybePromiseResult)) {\n return maybePromiseResult.then(\n r => {\n finishCheckIn('ok');\n return r;\n },\n e => {\n finishCheckIn('error');\n throw e;\n },\n ) ;\n }\n finishCheckIn('ok');\n\n return maybePromiseResult;\n }\n\n return withIsolationScope(() => (upsertMonitorConfig?.isolateTrace ? startNewTrace(runCallback) : runCallback()));\n}\n\n/**\n * Call `flush()` on the current client, if there is one. See {@link Client.flush}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause\n * the client to wait until all events are sent before resolving the promise.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function flush(timeout) {\n const client = getClient();\n if (client) {\n return client.flush(timeout);\n }\n DEBUG_BUILD && debug.warn('Cannot flush events. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Call `close()` on the current client, if there is one. See {@link Client.close}.\n *\n * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this\n * parameter will cause the client to wait until all events are sent before disabling itself.\n * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it\n * doesn't (or if there's no client defined).\n */\nasync function close(timeout) {\n const client = getClient();\n if (client) {\n return client.close(timeout);\n }\n DEBUG_BUILD && debug.warn('Cannot flush events and disable SDK. No client defined.');\n return Promise.resolve(false);\n}\n\n/**\n * Returns true if Sentry has been properly initialized.\n */\nfunction isInitialized() {\n return !!getClient();\n}\n\n/** If the SDK is initialized & enabled. */\nfunction isEnabled() {\n const client = getClient();\n return client?.getOptions().enabled !== false && !!client?.getTransport();\n}\n\n/**\n * Add an event processor.\n * This will be added to the current isolation scope, ensuring any event that is processed in the current execution\n * context will have the processor applied.\n */\nfunction addEventProcessor(callback) {\n getIsolationScope().addEventProcessor(callback);\n}\n\n/**\n * Start a session on the current isolation scope.\n *\n * @param context (optional) additional properties to be applied to the returned session object\n *\n * @returns the new active session\n */\nfunction startSession(context) {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n // Will fetch userAgent if called from browser sdk\n const { userAgent } = GLOBAL_OBJ.navigator || {};\n\n const session = makeSession({\n user: currentScope.getUser() || isolationScope.getUser(),\n ...(userAgent && { userAgent }),\n ...context,\n });\n\n // End existing session if there's one\n const currentSession = isolationScope.getSession();\n if (currentSession?.status === 'ok') {\n updateSession(currentSession, { status: 'exited' });\n }\n\n endSession();\n\n // Afterwards we set the new session on the scope\n isolationScope.setSession(session);\n\n return session;\n}\n\n/**\n * End the session on the current isolation scope.\n */\nfunction endSession() {\n const isolationScope = getIsolationScope();\n const currentScope = getCurrentScope();\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (session) {\n closeSession(session);\n }\n _sendSessionUpdate();\n\n // the session is over; take it off of the scope\n isolationScope.setSession();\n}\n\n/**\n * Sends the current Session on the scope\n */\nfunction _sendSessionUpdate() {\n const isolationScope = getIsolationScope();\n const client = getClient();\n const session = isolationScope.getSession();\n if (session && client) {\n client.captureSession(session);\n }\n}\n\n/**\n * Sends the current session on the scope to Sentry\n *\n * @param end If set the session will be marked as exited and removed from the scope.\n * Defaults to `false`.\n */\nfunction captureSession(end = false) {\n // both send the update and pull the session from the scope\n if (end) {\n endSession();\n return;\n }\n\n // only send the update\n _sendSessionUpdate();\n}\n\nexport { addEventProcessor, captureCheckIn, captureEvent, captureException, captureMessage, captureSession, close, endSession, flush, isEnabled, isInitialized, lastEventId, setContext, setExtra, setExtras, setTag, setTags, setUser, startSession, withMonitor };\n//# sourceMappingURL=exports.js.map\n","import { makeDsn, dsnToString } from './utils/dsn.js';\n\nconst SENTRY_API_VERSION = '7';\n\n/** Returns the prefix to construct Sentry ingestion API endpoints. */\nfunction getBaseApiEndpoint(dsn) {\n const protocol = dsn.protocol ? `${dsn.protocol}:` : '';\n const port = dsn.port ? `:${dsn.port}` : '';\n return `${protocol}//${dsn.host}${port}${dsn.path ? `/${dsn.path}` : ''}/api/`;\n}\n\n/** Returns the ingest API endpoint for target. */\nfunction _getIngestEndpoint(dsn) {\n return `${getBaseApiEndpoint(dsn)}${dsn.projectId}/envelope/`;\n}\n\n/** Returns a URL-encoded string with auth config suitable for a query string. */\nfunction _encodedAuth(dsn, sdkInfo) {\n const params = {\n sentry_version: SENTRY_API_VERSION,\n };\n\n if (dsn.publicKey) {\n // We send only the minimum set of required information. See\n // https://github.com/getsentry/sentry-javascript/issues/2572.\n params.sentry_key = dsn.publicKey;\n }\n\n if (sdkInfo) {\n params.sentry_client = `${sdkInfo.name}/${sdkInfo.version}`;\n }\n\n return new URLSearchParams(params).toString();\n}\n\n/**\n * Returns the envelope endpoint URL with auth in the query string.\n *\n * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests.\n */\nfunction getEnvelopeEndpointWithUrlEncodedAuth(dsn, tunnel, sdkInfo) {\n return tunnel ? tunnel : `${_getIngestEndpoint(dsn)}?${_encodedAuth(dsn, sdkInfo)}`;\n}\n\n/** Returns the url to the report dialog endpoint. */\nfunction getReportDialogEndpoint(dsnLike, dialogOptions) {\n const dsn = makeDsn(dsnLike);\n if (!dsn) {\n return '';\n }\n\n const endpoint = `${getBaseApiEndpoint(dsn)}embed/error-page/`;\n\n let encodedOptions = `dsn=${dsnToString(dsn)}`;\n for (const key in dialogOptions) {\n if (key === 'dsn') {\n continue;\n }\n\n if (key === 'onClose') {\n continue;\n }\n\n if (key === 'user') {\n const user = dialogOptions.user;\n if (!user) {\n continue;\n }\n if (user.name) {\n encodedOptions += `&name=${encodeURIComponent(user.name)}`;\n }\n if (user.email) {\n encodedOptions += `&email=${encodeURIComponent(user.email)}`;\n }\n } else {\n encodedOptions += `&${encodeURIComponent(key)}=${encodeURIComponent(dialogOptions[key] )}`;\n }\n }\n\n return `${endpoint}?${encodedOptions}`;\n}\n\nexport { getEnvelopeEndpointWithUrlEncodedAuth, getReportDialogEndpoint };\n//# sourceMappingURL=api.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { debug } from './utils/debug-logger.js';\n\nconst installedIntegrations = [];\n\n/** Map of integrations assigned to a client */\n\n/**\n * Remove duplicates from the given array, preferring the last instance of any duplicate. Not guaranteed to\n * preserve the order of integrations in the array.\n *\n * @private\n */\nfunction filterDuplicates(integrations) {\n const integrationsByName = {};\n\n integrations.forEach((currentInstance) => {\n const { name } = currentInstance;\n\n const existingInstance = integrationsByName[name];\n\n // We want integrations later in the array to overwrite earlier ones of the same type, except that we never want a\n // default instance to overwrite an existing user instance\n if (existingInstance && !existingInstance.isDefaultInstance && currentInstance.isDefaultInstance) {\n return;\n }\n\n integrationsByName[name] = currentInstance;\n });\n\n return Object.values(integrationsByName);\n}\n\n/** Gets integrations to install */\nfunction getIntegrationsToSetup(\n options,\n) {\n const defaultIntegrations = options.defaultIntegrations || [];\n const userIntegrations = options.integrations;\n\n // We flag default instances, so that later we can tell them apart from any user-created instances of the same class\n defaultIntegrations.forEach((integration) => {\n integration.isDefaultInstance = true;\n });\n\n let integrations;\n\n if (Array.isArray(userIntegrations)) {\n integrations = [...defaultIntegrations, ...userIntegrations];\n } else if (typeof userIntegrations === 'function') {\n const resolvedUserIntegrations = userIntegrations(defaultIntegrations);\n integrations = Array.isArray(resolvedUserIntegrations) ? resolvedUserIntegrations : [resolvedUserIntegrations];\n } else {\n integrations = defaultIntegrations;\n }\n\n return filterDuplicates(integrations);\n}\n\n/**\n * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default\n * integrations are added unless they were already provided before.\n * @param integrations array of integration instances\n * @param withDefault should enable default integrations\n */\nfunction setupIntegrations(client, integrations) {\n const integrationIndex = {};\n\n integrations.forEach((integration) => {\n // guard against empty provided integrations\n if (integration) {\n setupIntegration(client, integration, integrationIndex);\n }\n });\n\n return integrationIndex;\n}\n\n/**\n * Execute the `afterAllSetup` hooks of the given integrations.\n */\nfunction afterSetupIntegrations(client, integrations) {\n for (const integration of integrations) {\n // guard against empty provided integrations\n if (integration?.afterAllSetup) {\n integration.afterAllSetup(client);\n }\n }\n}\n\n/** Setup a single integration. */\nfunction setupIntegration(client, integration, integrationIndex) {\n if (integrationIndex[integration.name]) {\n DEBUG_BUILD && debug.log(`Integration skipped because it was already installed: ${integration.name}`);\n return;\n }\n integrationIndex[integration.name] = integration;\n\n // `setupOnce` is only called the first time\n if (!installedIntegrations.includes(integration.name) && typeof integration.setupOnce === 'function') {\n integration.setupOnce();\n installedIntegrations.push(integration.name);\n }\n\n // `setup` is run for each client\n if (integration.setup && typeof integration.setup === 'function') {\n integration.setup(client);\n }\n\n if (typeof integration.preprocessEvent === 'function') {\n const callback = integration.preprocessEvent.bind(integration) ;\n client.on('preprocessEvent', (event, hint) => callback(event, hint, client));\n }\n\n if (typeof integration.processEvent === 'function') {\n const callback = integration.processEvent.bind(integration) ;\n\n const processor = Object.assign((event, hint) => callback(event, hint, client), {\n id: integration.name,\n });\n\n client.addEventProcessor(processor);\n }\n\n DEBUG_BUILD && debug.log(`Integration installed: ${integration.name}`);\n}\n\n/** Add an integration to the current scope's client. */\nfunction addIntegration(integration) {\n const client = getClient();\n\n if (!client) {\n DEBUG_BUILD && debug.warn(`Cannot add integration \"${integration.name}\" because no SDK Client is available.`);\n return;\n }\n\n client.addIntegration(integration);\n}\n\n/**\n * Define an integration function that can be used to create an integration instance.\n * Note that this by design hides the implementation details of the integration, as they are considered internal.\n */\nfunction defineIntegration(fn) {\n return fn;\n}\n\nexport { addIntegration, afterSetupIntegrations, defineIntegration, getIntegrationsToSetup, installedIntegrations, setupIntegration, setupIntegrations };\n//# sourceMappingURL=integration.js.map\n","/**\n * Type-guard: The attribute object has the shape the official attribute object (value, type, unit).\n * https://develop.sentry.dev/sdk/telemetry/scopes/#setting-attributes\n */\nfunction isAttributeObject(maybeObj) {\n return (\n typeof maybeObj === 'object' &&\n maybeObj != null &&\n !Array.isArray(maybeObj) &&\n Object.keys(maybeObj).includes('value')\n );\n}\n\n/**\n * Converts an attribute value to a typed attribute value.\n *\n * For now, we intentionally only support primitive values and attribute objects with primitive values.\n * If @param useFallback is true, we stringify non-primitive values to a string attribute value. Otherwise\n * we return `undefined` for unsupported values.\n *\n * @param value - The value of the passed attribute.\n * @param useFallback - If true, unsupported values will be stringified to a string attribute value.\n * Defaults to false. In this case, `undefined` is returned for unsupported values.\n * @returns The typed attribute.\n */\nfunction attributeValueToTypedAttributeValue(\n rawValue,\n useFallback,\n) {\n const { value, unit } = isAttributeObject(rawValue) ? rawValue : { value: rawValue, unit: undefined };\n const attributeValue = getTypedAttributeValue(value);\n const checkedUnit = unit && typeof unit === 'string' ? { unit } : {};\n if (attributeValue) {\n return { ...attributeValue, ...checkedUnit };\n }\n\n if (!useFallback) {\n return;\n }\n\n // Fallback: stringify the value\n // TODO(v11): be smarter here and use String constructor if stringify fails\n // (this is a breaking change for already existing attribute values)\n let stringValue = '';\n try {\n stringValue = JSON.stringify(value) ?? '';\n } catch {\n // Do nothing\n }\n return {\n value: stringValue,\n type: 'string',\n ...checkedUnit,\n };\n}\n\n/**\n * Serializes raw attributes to typed attributes as expected in our envelopes.\n *\n * @param attributes The raw attributes to serialize.\n * @param fallback If true, unsupported values will be stringified to a string attribute value.\n * Defaults to false. In this case, `undefined` is returned for unsupported values.\n *\n * @returns The serialized attributes.\n */\nfunction serializeAttributes(attributes, fallback = false) {\n const serializedAttributes = {};\n for (const [key, value] of Object.entries(attributes)) {\n const typedValue = attributeValueToTypedAttributeValue(value, fallback);\n if (typedValue) {\n serializedAttributes[key] = typedValue;\n }\n }\n return serializedAttributes;\n}\n\n/**\n * NOTE: We intentionally do not return anything for non-primitive values:\n * - array support will come in the future but if we stringify arrays now,\n * sending arrays (unstringified) later will be a subtle breaking change.\n * - Objects are not supported yet and product support is still TBD.\n * - We still keep the type signature for TypedAttributeValue wider to avoid a\n * breaking change once we add support for non-primitive values.\n * - Once we go back to supporting arrays and stringifying all other values,\n * we already implemented the serialization logic here:\n * https://github.com/getsentry/sentry-javascript/pull/18165\n */\nfunction getTypedAttributeValue(value) {\n const primitiveType =\n typeof value === 'string'\n ? 'string'\n : typeof value === 'boolean'\n ? 'boolean'\n : typeof value === 'number' && !Number.isNaN(value)\n ? Number.isInteger(value)\n ? 'integer'\n : 'double'\n : null;\n if (primitiveType) {\n // @ts-expect-error - TS complains because {@link TypedAttributeValue} is strictly typed to\n // avoid setting the wrong `type` on the attribute value.\n // In this case, getPrimitiveType already does the check but TS doesn't know that.\n // The \"clean\" alternative is to return an object per `typeof value` case\n // but that would require more bundle size\n // Therefore, we ignore it.\n return { value, type: primitiveType };\n }\n}\n\nexport { attributeValueToTypedAttributeValue, isAttributeObject, serializeAttributes };\n//# sourceMappingURL=attributes.js.map\n","import { withScope, getTraceContextFromScope } from '../currentScopes.js';\nimport { getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromScope } from '../tracing/dynamicSamplingContext.js';\nimport { getActiveSpan, spanToTraceContext } from './spanUtils.js';\n\n/** Extract trace information from scope */\nfunction _getTraceInfoFromScope(\n client,\n scope,\n) {\n if (!scope) {\n return [undefined, undefined];\n }\n\n return withScope(scope, () => {\n const span = getActiveSpan();\n const traceContext = span ? spanToTraceContext(span) : getTraceContextFromScope(scope);\n const dynamicSamplingContext = span\n ? getDynamicSamplingContextFromSpan(span)\n : getDynamicSamplingContextFromScope(client, scope);\n return [dynamicSamplingContext, traceContext];\n });\n}\n\nexport { _getTraceInfoFromScope };\n//# sourceMappingURL=trace-info.js.map\n","/**\n * Maps a log severity level to a log severity number.\n *\n * @see LogSeverityLevel\n */\nconst SEVERITY_TEXT_TO_SEVERITY_NUMBER = {\n trace: 1,\n debug: 5,\n info: 9,\n warn: 13,\n error: 17,\n fatal: 21,\n};\n\nexport { SEVERITY_TEXT_TO_SEVERITY_NUMBER };\n//# sourceMappingURL=constants.js.map\n","import { serializeAttributes } from '../attributes.js';\nimport { getGlobalSingleton } from '../carrier.js';\nimport { getCurrentScope, getClient, getGlobalScope, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { mergeScopeData } from '../utils/applyScopeDataToEvent.js';\nimport { debug, consoleSandbox } from '../utils/debug-logger.js';\nimport { isParameterizedString } from '../utils/is.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { SEVERITY_TEXT_TO_SEVERITY_NUMBER } from './constants.js';\nimport { createLogEnvelope } from './envelope.js';\n\nconst MAX_LOG_BUFFER_SIZE = 100;\n\n/**\n * Sets a log attribute if the value exists and the attribute key is not already present.\n *\n * @param logAttributes - The log attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setLogAttribute(\n logAttributes,\n key,\n value,\n setEvenIfPresent = true,\n) {\n if (value && (!logAttributes[key] || setEvenIfPresent)) {\n logAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized log event and adds it to the log buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedLog - The serialized log event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureSerializedLog(client, serializedLog) {\n const bufferMap = _getBufferMap();\n const logBuffer = _INTERNAL_getLogBuffer(client);\n\n if (logBuffer === undefined) {\n bufferMap.set(client, [serializedLog]);\n } else {\n if (logBuffer.length >= MAX_LOG_BUFFER_SIZE) {\n _INTERNAL_flushLogsBuffer(client, logBuffer);\n bufferMap.set(client, [serializedLog]);\n } else {\n bufferMap.set(client, [...logBuffer, serializedLog]);\n }\n }\n}\n\n/**\n * Captures a log event and sends it to Sentry.\n *\n * @param log - The log event to capture.\n * @param scope - A scope. Uses the current scope if not provided.\n * @param client - A client. Uses the current client if not provided.\n * @param captureSerializedLog - A function to capture the serialized log.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureLog(\n beforeLog,\n currentScope = getCurrentScope(),\n captureSerializedLog = _INTERNAL_captureSerializedLog,\n) {\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture log.');\n return;\n }\n\n const { release, environment, enableLogs = false, beforeSendLog } = client.getOptions();\n if (!enableLogs) {\n DEBUG_BUILD && debug.warn('logging option not enabled, log will not be captured.');\n return;\n }\n\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n\n const processedLogAttributes = {\n ...beforeLog.attributes,\n };\n\n const {\n user: { id, email, username },\n attributes: scopeAttributes = {},\n } = getMergedScopeData(currentScope);\n\n setLogAttribute(processedLogAttributes, 'user.id', id, false);\n setLogAttribute(processedLogAttributes, 'user.email', email, false);\n setLogAttribute(processedLogAttributes, 'user.name', username, false);\n\n setLogAttribute(processedLogAttributes, 'sentry.release', release);\n setLogAttribute(processedLogAttributes, 'sentry.environment', environment);\n\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setLogAttribute(processedLogAttributes, 'sentry.sdk.name', name);\n setLogAttribute(processedLogAttributes, 'sentry.sdk.version', version);\n\n const replay = client.getIntegrationByName\n\n('Replay');\n\n const replayId = replay?.getReplayId(true);\n setLogAttribute(processedLogAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n // We send this so we can identify cases where the replayId is attached but the replay itself might not have been sent to Sentry\n setLogAttribute(processedLogAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n const beforeLogMessage = beforeLog.message;\n if (isParameterizedString(beforeLogMessage)) {\n const { __sentry_template_string__, __sentry_template_values__ = [] } = beforeLogMessage;\n if (__sentry_template_values__?.length) {\n processedLogAttributes['sentry.message.template'] = __sentry_template_string__;\n }\n __sentry_template_values__.forEach((param, index) => {\n processedLogAttributes[`sentry.message.parameter.${index}`] = param;\n });\n }\n\n const span = _getSpanForScope(currentScope);\n // Add the parent span ID to the log attributes for trace context\n setLogAttribute(processedLogAttributes, 'sentry.trace.parent_span_id', span?.spanContext().spanId);\n\n const processedLog = { ...beforeLog, attributes: processedLogAttributes };\n\n client.emit('beforeCaptureLog', processedLog);\n\n // We need to wrap this in `consoleSandbox` to avoid recursive calls to `beforeSendLog`\n const log = beforeSendLog ? consoleSandbox(() => beforeSendLog(processedLog)) : processedLog;\n if (!log) {\n client.recordDroppedEvent('before_send', 'log_item', 1);\n DEBUG_BUILD && debug.warn('beforeSendLog returned null, log will not be captured.');\n return;\n }\n\n const { level, message, attributes: logAttributes = {}, severityNumber } = log;\n\n const serializedLog = {\n timestamp: timestampInSeconds(),\n level,\n body: message,\n trace_id: traceContext?.trace_id,\n severity_number: severityNumber ?? SEVERITY_TEXT_TO_SEVERITY_NUMBER[level],\n attributes: {\n ...serializeAttributes(scopeAttributes),\n ...serializeAttributes(logAttributes, true),\n },\n };\n\n captureSerializedLog(client, serializedLog);\n\n client.emit('afterCaptureLog', log);\n}\n\n/**\n * Flushes the logs buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeLogBuffer - A log buffer. Uses the log buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_flushLogsBuffer(client, maybeLogBuffer) {\n const logBuffer = maybeLogBuffer ?? _INTERNAL_getLogBuffer(client) ?? [];\n if (logBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createLogEnvelope(logBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the log buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushLogs');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the log buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the log buffer for.\n * @returns The log buffer for the given client.\n */\nfunction _INTERNAL_getLogBuffer(client) {\n return _getBufferMap().get(client);\n}\n\n/**\n * Get the scope data for the current scope after merging with the\n * global scope and isolation scope.\n *\n * @param currentScope - The current scope.\n * @returns The scope data.\n */\nfunction getMergedScopeData(currentScope) {\n const scopeData = getGlobalScope().getScopeData();\n mergeScopeData(scopeData, getIsolationScope().getScopeData());\n mergeScopeData(scopeData, currentScope.getScopeData());\n return scopeData;\n}\n\nfunction _getBufferMap() {\n // The reference to the Client <> LogBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToLogBufferMap', () => new WeakMap());\n}\n\nexport { _INTERNAL_captureLog, _INTERNAL_captureSerializedLog, _INTERNAL_flushLogsBuffer, _INTERNAL_getLogBuffer };\n//# sourceMappingURL=internal.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\n\n/**\n * Creates a log container envelope item for a list of logs.\n *\n * @param items - The logs to include in the envelope.\n * @returns The created log container envelope item.\n */\nfunction createLogContainerEnvelopeItem(items) {\n return [\n {\n type: 'log',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.log+json',\n },\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of logs.\n *\n * Logs from multiple traces can be included in the same envelope.\n *\n * @param logs - The logs to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nfunction createLogEnvelope(\n logs,\n metadata,\n tunnel,\n dsn,\n) {\n const headers = {};\n\n if (metadata?.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n return createEnvelope(headers, [createLogContainerEnvelopeItem(logs)]);\n}\n\nexport { createLogContainerEnvelopeItem, createLogEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { getGlobalSingleton } from '../carrier.js';\nimport { getCurrentScope, getClient, getGlobalScope, getIsolationScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { mergeScopeData } from '../utils/applyScopeDataToEvent.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { _getSpanForScope } from '../utils/spanOnScope.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { _getTraceInfoFromScope } from '../utils/trace-info.js';\nimport { createMetricEnvelope } from './envelope.js';\n\nconst MAX_METRIC_BUFFER_SIZE = 1000;\n\n/**\n * Converts a metric attribute to a serialized metric attribute.\n *\n * @param value - The value of the metric attribute.\n * @returns The serialized metric attribute.\n */\nfunction metricAttributeToSerializedMetricAttribute(value) {\n switch (typeof value) {\n case 'number':\n if (Number.isInteger(value)) {\n return {\n value,\n type: 'integer',\n };\n }\n return {\n value,\n type: 'double',\n };\n case 'boolean':\n return {\n value,\n type: 'boolean',\n };\n case 'string':\n return {\n value,\n type: 'string',\n };\n default: {\n let stringValue = '';\n try {\n stringValue = JSON.stringify(value) ?? '';\n } catch {\n // Do nothing\n }\n return {\n value: stringValue,\n type: 'string',\n };\n }\n }\n}\n\n/**\n * Sets a metric attribute if the value exists and the attribute key is not already present.\n *\n * @param metricAttributes - The metric attributes object to modify.\n * @param key - The attribute key to set.\n * @param value - The value to set (only sets if truthy and key not present).\n * @param setEvenIfPresent - Whether to set the attribute if it is present. Defaults to true.\n */\nfunction setMetricAttribute(\n metricAttributes,\n key,\n value,\n setEvenIfPresent = true,\n) {\n if (value && (setEvenIfPresent || !(key in metricAttributes))) {\n metricAttributes[key] = value;\n }\n}\n\n/**\n * Captures a serialized metric event and adds it to the metric buffer for the given client.\n *\n * @param client - A client. Uses the current client if not provided.\n * @param serializedMetric - The serialized metric event to capture.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureSerializedMetric(client, serializedMetric) {\n const bufferMap = _getBufferMap();\n const metricBuffer = _INTERNAL_getMetricBuffer(client);\n\n if (metricBuffer === undefined) {\n bufferMap.set(client, [serializedMetric]);\n } else {\n if (metricBuffer.length >= MAX_METRIC_BUFFER_SIZE) {\n _INTERNAL_flushMetricsBuffer(client, metricBuffer);\n bufferMap.set(client, [serializedMetric]);\n } else {\n bufferMap.set(client, [...metricBuffer, serializedMetric]);\n }\n }\n}\n\n/**\n * Options for capturing a metric internally.\n */\n\n/**\n * Enriches metric with all contextual attributes (user, SDK metadata, replay, etc.)\n */\nfunction _enrichMetricAttributes(beforeMetric, client, currentScope) {\n const { release, environment } = client.getOptions();\n\n const processedMetricAttributes = {\n ...beforeMetric.attributes,\n };\n\n // Add user attributes\n const {\n user: { id, email, username },\n } = getMergedScopeData(currentScope);\n setMetricAttribute(processedMetricAttributes, 'user.id', id, false);\n setMetricAttribute(processedMetricAttributes, 'user.email', email, false);\n setMetricAttribute(processedMetricAttributes, 'user.name', username, false);\n\n // Add Sentry metadata\n setMetricAttribute(processedMetricAttributes, 'sentry.release', release);\n setMetricAttribute(processedMetricAttributes, 'sentry.environment', environment);\n\n // Add SDK metadata\n const { name, version } = client.getSdkMetadata()?.sdk ?? {};\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.name', name);\n setMetricAttribute(processedMetricAttributes, 'sentry.sdk.version', version);\n\n // Add replay metadata\n const replay = client.getIntegrationByName\n\n('Replay');\n\n const replayId = replay?.getReplayId(true);\n setMetricAttribute(processedMetricAttributes, 'sentry.replay_id', replayId);\n\n if (replayId && replay?.getRecordingMode() === 'buffer') {\n setMetricAttribute(processedMetricAttributes, 'sentry._internal.replay_is_buffering', true);\n }\n\n return {\n ...beforeMetric,\n attributes: processedMetricAttributes,\n };\n}\n\n/**\n * Creates a serialized metric ready to be sent to Sentry.\n */\nfunction _buildSerializedMetric(metric, client, currentScope) {\n // Serialize attributes\n const serializedAttributes = {};\n for (const key in metric.attributes) {\n if (metric.attributes[key] !== undefined) {\n serializedAttributes[key] = metricAttributeToSerializedMetricAttribute(metric.attributes[key]);\n }\n }\n\n // Get trace context\n const [, traceContext] = _getTraceInfoFromScope(client, currentScope);\n const span = _getSpanForScope(currentScope);\n const traceId = span ? span.spanContext().traceId : traceContext?.trace_id;\n const spanId = span ? span.spanContext().spanId : undefined;\n\n return {\n timestamp: timestampInSeconds(),\n trace_id: traceId ?? '',\n span_id: spanId,\n name: metric.name,\n type: metric.type,\n unit: metric.unit,\n value: metric.value,\n attributes: serializedAttributes,\n };\n}\n\n/**\n * Captures a metric event and sends it to Sentry.\n *\n * @param metric - The metric event to capture.\n * @param options - Options for capturing the metric.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_captureMetric(beforeMetric, options) {\n const currentScope = options?.scope ?? getCurrentScope();\n const captureSerializedMetric = options?.captureSerializedMetric ?? _INTERNAL_captureSerializedMetric;\n const client = currentScope?.getClient() ?? getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No client available to capture metric.');\n return;\n }\n\n const { _experiments, enableMetrics, beforeSendMetric } = client.getOptions();\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const metricsEnabled = enableMetrics ?? _experiments?.enableMetrics ?? true;\n\n if (!metricsEnabled) {\n DEBUG_BUILD && debug.warn('metrics option not enabled, metric will not be captured.');\n return;\n }\n\n // Enrich metric with contextual attributes\n const enrichedMetric = _enrichMetricAttributes(beforeMetric, client, currentScope);\n\n client.emit('processMetric', enrichedMetric);\n\n // todo(v11): Remove the experimental `beforeSendMetric`\n // eslint-disable-next-line deprecation/deprecation\n const beforeSendCallback = beforeSendMetric || _experiments?.beforeSendMetric;\n const processedMetric = beforeSendCallback ? beforeSendCallback(enrichedMetric) : enrichedMetric;\n\n if (!processedMetric) {\n DEBUG_BUILD && debug.log('`beforeSendMetric` returned `null`, will not send metric.');\n return;\n }\n\n const serializedMetric = _buildSerializedMetric(processedMetric, client, currentScope);\n\n DEBUG_BUILD && debug.log('[Metric]', serializedMetric);\n\n captureSerializedMetric(client, serializedMetric);\n\n client.emit('afterCaptureMetric', processedMetric);\n}\n\n/**\n * Flushes the metrics buffer to Sentry.\n *\n * @param client - A client.\n * @param maybeMetricBuffer - A metric buffer. Uses the metric buffer for the given client if not provided.\n *\n * @experimental This method will experience breaking changes. This is not yet part of\n * the stable Sentry SDK API and can be changed or removed without warning.\n */\nfunction _INTERNAL_flushMetricsBuffer(client, maybeMetricBuffer) {\n const metricBuffer = maybeMetricBuffer ?? _INTERNAL_getMetricBuffer(client) ?? [];\n if (metricBuffer.length === 0) {\n return;\n }\n\n const clientOptions = client.getOptions();\n const envelope = createMetricEnvelope(metricBuffer, clientOptions._metadata, clientOptions.tunnel, client.getDsn());\n\n // Clear the metric buffer after envelopes have been constructed.\n _getBufferMap().set(client, []);\n\n client.emit('flushMetrics');\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n client.sendEnvelope(envelope);\n}\n\n/**\n * Returns the metric buffer for a given client.\n *\n * Exported for testing purposes.\n *\n * @param client - The client to get the metric buffer for.\n * @returns The metric buffer for the given client.\n */\nfunction _INTERNAL_getMetricBuffer(client) {\n return _getBufferMap().get(client);\n}\n\n/**\n * Get the scope data for the current scope after merging with the\n * global scope and isolation scope.\n *\n * @param currentScope - The current scope.\n * @returns The scope data.\n */\nfunction getMergedScopeData(currentScope) {\n const scopeData = getGlobalScope().getScopeData();\n mergeScopeData(scopeData, getIsolationScope().getScopeData());\n mergeScopeData(scopeData, currentScope.getScopeData());\n return scopeData;\n}\n\nfunction _getBufferMap() {\n // The reference to the Client <> MetricBuffer map is stored on the carrier to ensure it's always the same\n return getGlobalSingleton('clientToMetricBufferMap', () => new WeakMap());\n}\n\nexport { _INTERNAL_captureMetric, _INTERNAL_captureSerializedMetric, _INTERNAL_flushMetricsBuffer, _INTERNAL_getMetricBuffer, metricAttributeToSerializedMetricAttribute };\n//# sourceMappingURL=internal.js.map\n","import { dsnToString } from '../utils/dsn.js';\nimport { createEnvelope } from '../utils/envelope.js';\n\n/**\n * Creates a metric container envelope item for a list of metrics.\n *\n * @param items - The metrics to include in the envelope.\n * @returns The created metric container envelope item.\n */\nfunction createMetricContainerEnvelopeItem(items) {\n return [\n {\n type: 'trace_metric',\n item_count: items.length,\n content_type: 'application/vnd.sentry.items.trace-metric+json',\n } ,\n {\n items,\n },\n ];\n}\n\n/**\n * Creates an envelope for a list of metrics.\n *\n * Metrics from multiple traces can be included in the same envelope.\n *\n * @param metrics - The metrics to include in the envelope.\n * @param metadata - The metadata to include in the envelope.\n * @param tunnel - The tunnel to include in the envelope.\n * @param dsn - The DSN to include in the envelope.\n * @returns The created envelope.\n */\nfunction createMetricEnvelope(\n metrics,\n metadata,\n tunnel,\n dsn,\n) {\n const headers = {};\n\n if (metadata?.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n return createEnvelope(headers, [createMetricContainerEnvelopeItem(metrics)]);\n}\n\nexport { createMetricContainerEnvelopeItem, createMetricEnvelope };\n//# sourceMappingURL=envelope.js.map\n","import { resolvedSyncPromise, rejectedSyncPromise } from './syncpromise.js';\n\nconst SENTRY_BUFFER_FULL_ERROR = Symbol.for('SentryBufferFullError');\n\n/**\n * Creates an new PromiseBuffer object with the specified limit\n * @param limit max number of promises that can be stored in the buffer\n */\nfunction makePromiseBuffer(limit = 100) {\n const buffer = new Set();\n\n function isReady() {\n return buffer.size < limit;\n }\n\n /**\n * Remove a promise from the queue.\n *\n * @param task Can be any PromiseLike<T>\n * @returns Removed promise.\n */\n function remove(task) {\n buffer.delete(task);\n }\n\n /**\n * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment.\n *\n * @param taskProducer A function producing any PromiseLike<T>; In previous versions this used to be `task:\n * PromiseLike<T>`, but under that model, Promises were instantly created on the call-site and their executor\n * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By\n * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer\n * limit check.\n * @returns The original promise.\n */\n function add(taskProducer) {\n if (!isReady()) {\n return rejectedSyncPromise(SENTRY_BUFFER_FULL_ERROR);\n }\n\n // start the task and add its promise to the queue\n const task = taskProducer();\n buffer.add(task);\n void task.then(\n () => remove(task),\n () => remove(task),\n );\n return task;\n }\n\n /**\n * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or\n * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and\n * `false` otherwise\n */\n function drain(timeout) {\n if (!buffer.size) {\n return resolvedSyncPromise(true);\n }\n\n // We want to resolve even if one of the promises rejects\n const drainPromise = Promise.allSettled(Array.from(buffer)).then(() => true);\n\n if (!timeout) {\n return drainPromise;\n }\n\n const promises = [drainPromise, new Promise(resolve => setTimeout(() => resolve(false), timeout))];\n\n // Promise.race will resolve to the first promise that resolves or rejects\n // So if the drainPromise resolves, the timeout promise will be ignored\n return Promise.race(promises);\n }\n\n return {\n get $() {\n return Array.from(buffer);\n },\n add,\n drain,\n };\n}\n\nexport { SENTRY_BUFFER_FULL_ERROR, makePromiseBuffer };\n//# sourceMappingURL=promisebuffer.js.map\n","// Intentionally keeping the key broad, as we don't know for sure what rate limit headers get returned from backend\n\nconst DEFAULT_RETRY_AFTER = 60 * 1000; // 60 seconds\n\n/**\n * Extracts Retry-After value from the request header or returns default value\n * @param header string representation of 'Retry-After' header\n * @param now current unix timestamp\n *\n */\nfunction parseRetryAfterHeader(header, now = Date.now()) {\n const headerDelay = parseInt(`${header}`, 10);\n if (!isNaN(headerDelay)) {\n return headerDelay * 1000;\n }\n\n const headerDate = Date.parse(`${header}`);\n if (!isNaN(headerDate)) {\n return headerDate - now;\n }\n\n return DEFAULT_RETRY_AFTER;\n}\n\n/**\n * Gets the time that the given category is disabled until for rate limiting.\n * In case no category-specific limit is set but a general rate limit across all categories is active,\n * that time is returned.\n *\n * @return the time in ms that the category is disabled until or 0 if there's no active rate limit.\n */\nfunction disabledUntil(limits, dataCategory) {\n return limits[dataCategory] || limits.all || 0;\n}\n\n/**\n * Checks if a category is rate limited\n */\nfunction isRateLimited(limits, dataCategory, now = Date.now()) {\n return disabledUntil(limits, dataCategory) > now;\n}\n\n/**\n * Update ratelimits from incoming headers.\n *\n * @return the updated RateLimits object.\n */\nfunction updateRateLimits(\n limits,\n { statusCode, headers },\n now = Date.now(),\n) {\n const updatedRateLimits = {\n ...limits,\n };\n\n // \"The name is case-insensitive.\"\n // https://developer.mozilla.org/en-US/docs/Web/API/Headers/get\n const rateLimitHeader = headers?.['x-sentry-rate-limits'];\n const retryAfterHeader = headers?.['retry-after'];\n\n if (rateLimitHeader) {\n /**\n * rate limit headers are of the form\n * <header>,<header>,..\n * where each <header> is of the form\n * <retry_after>: <categories>: <scope>: <reason_code>: <namespaces>\n * where\n * <retry_after> is a delay in seconds\n * <categories> is the event type(s) (error, transaction, etc) being rate limited and is of the form\n * <category>;<category>;...\n * <scope> is what's being limited (org, project, or key) - ignored by SDK\n * <reason_code> is an arbitrary string like \"org_quota\" - ignored by SDK\n * <namespaces> Semicolon-separated list of metric namespace identifiers. Defines which namespace(s) will be affected.\n * Only present if rate limit applies to the metric_bucket data category.\n */\n for (const limit of rateLimitHeader.trim().split(',')) {\n const [retryAfter, categories, , , namespaces] = limit.split(':', 5) ;\n const headerDelay = parseInt(retryAfter, 10);\n const delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default\n if (!categories) {\n updatedRateLimits.all = now + delay;\n } else {\n for (const category of categories.split(';')) {\n if (category === 'metric_bucket') {\n // namespaces will be present when category === 'metric_bucket'\n if (!namespaces || namespaces.split(';').includes('custom')) {\n updatedRateLimits[category] = now + delay;\n }\n } else {\n updatedRateLimits[category] = now + delay;\n }\n }\n }\n }\n } else if (retryAfterHeader) {\n updatedRateLimits.all = now + parseRetryAfterHeader(retryAfterHeader, now);\n } else if (statusCode === 429) {\n updatedRateLimits.all = now + 60 * 1000;\n }\n\n return updatedRateLimits;\n}\n\nexport { DEFAULT_RETRY_AFTER, disabledUntil, isRateLimited, parseRetryAfterHeader, updateRateLimits };\n//# sourceMappingURL=ratelimit.js.map\n","import { createEnvelope } from './envelope.js';\nimport { dateTimestampInSeconds } from './time.js';\n\n/**\n * Creates client report envelope\n * @param discarded_events An array of discard events\n * @param dsn A DSN that can be set on the header. Optional.\n */\nfunction createClientReportEnvelope(\n discarded_events,\n dsn,\n timestamp,\n) {\n const clientReportItem = [\n { type: 'client_report' },\n {\n timestamp: timestamp || dateTimestampInSeconds(),\n discarded_events,\n },\n ];\n return createEnvelope(dsn ? { dsn } : {}, [clientReportItem]);\n}\n\nexport { createClientReportEnvelope };\n//# sourceMappingURL=clientreport.js.map\n","/**\n * Get a list of possible event messages from a Sentry event.\n */\nfunction getPossibleEventMessages(event) {\n const possibleMessages = [];\n\n if (event.message) {\n possibleMessages.push(event.message);\n }\n\n try {\n // @ts-expect-error Try catching to save bundle size\n const lastException = event.exception.values[event.exception.values.length - 1];\n if (lastException?.value) {\n possibleMessages.push(lastException.value);\n if (lastException.type) {\n possibleMessages.push(`${lastException.type}: ${lastException.value}`);\n }\n }\n } catch {\n // ignore errors here\n }\n\n return possibleMessages;\n}\n\nexport { getPossibleEventMessages };\n//# sourceMappingURL=eventUtils.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from './api.js';\nimport { DEFAULT_ENVIRONMENT } from './constants.js';\nimport { getTraceContextFromScope, getCurrentScope, getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { createEventEnvelope, createSessionEnvelope } from './envelope.js';\nimport { setupIntegration, afterSetupIntegrations, setupIntegrations } from './integration.js';\nimport { _INTERNAL_flushLogsBuffer } from './logs/internal.js';\nimport { _INTERNAL_flushMetricsBuffer } from './metrics/internal.js';\nimport { updateSession } from './session.js';\nimport { getDynamicSamplingContextFromScope } from './tracing/dynamicSamplingContext.js';\nimport { DEFAULT_TRANSPORT_BUFFER_SIZE } from './transports/base.js';\nimport { createClientReportEnvelope } from './utils/clientreport.js';\nimport { debug } from './utils/debug-logger.js';\nimport { makeDsn, dsnToString } from './utils/dsn.js';\nimport { addItemToEnvelope, createAttachmentEnvelopeItem } from './utils/envelope.js';\nimport { getPossibleEventMessages } from './utils/eventUtils.js';\nimport { isParameterizedString, isPrimitive, isThenable, isPlainObject } from './utils/is.js';\nimport { merge } from './utils/merge.js';\nimport { uuid4, checkOrSetAlreadyCaught } from './utils/misc.js';\nimport { parseSampleRate } from './utils/parseSampleRate.js';\nimport { prepareEvent } from './utils/prepareEvent.js';\nimport { makePromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from './utils/promisebuffer.js';\nimport { shouldIgnoreSpan, reparentChildSpans } from './utils/should-ignore-span.js';\nimport { showSpanDropWarning } from './utils/spanUtils.js';\nimport { rejectedSyncPromise } from './utils/syncpromise.js';\nimport { convertTransactionEventToSpanJson, convertSpanJsonToTransactionEvent } from './utils/transactionEvent.js';\n\n/* eslint-disable max-lines */\n\nconst ALREADY_SEEN_ERROR = \"Not capturing exception because it's already been captured.\";\nconst MISSING_RELEASE_FOR_SESSION_ERROR = 'Discarded session because of missing or non-string release';\n\nconst INTERNAL_ERROR_SYMBOL = Symbol.for('SentryInternalError');\nconst DO_NOT_SEND_EVENT_SYMBOL = Symbol.for('SentryDoNotSendEventError');\n\n// Default interval for flushing logs and metrics (5 seconds)\nconst DEFAULT_FLUSH_INTERVAL = 5000;\n\nfunction _makeInternalError(message) {\n return {\n message,\n [INTERNAL_ERROR_SYMBOL]: true,\n };\n}\n\nfunction _makeDoNotSendEventError(message) {\n return {\n message,\n [DO_NOT_SEND_EVENT_SYMBOL]: true,\n };\n}\n\nfunction _isInternalError(error) {\n return !!error && typeof error === 'object' && INTERNAL_ERROR_SYMBOL in error;\n}\n\nfunction _isDoNotSendEventError(error) {\n return !!error && typeof error === 'object' && DO_NOT_SEND_EVENT_SYMBOL in error;\n}\n\n/**\n * Sets up weight-based flushing for logs or metrics.\n * This helper function encapsulates the common pattern of:\n * 1. Tracking accumulated weight of items\n * 2. Flushing when weight exceeds threshold (800KB)\n * 3. Flushing after timeout period from the first item\n *\n * Uses closure variables to track weight and timeout state.\n */\nfunction setupWeightBasedFlushing\n\n(\n client,\n afterCaptureHook,\n flushHook,\n estimateSizeFn,\n flushFn,\n) {\n // Track weight and timeout in closure variables\n let weight = 0;\n let flushTimeout;\n let isTimerActive = false;\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(flushHook, () => {\n weight = 0;\n clearTimeout(flushTimeout);\n isTimerActive = false;\n });\n\n // @ts-expect-error - TypeScript can't narrow generic hook types to match specific overloads, but we know this is type-safe\n client.on(afterCaptureHook, (item) => {\n weight += estimateSizeFn(item);\n\n // We flush the buffer if it exceeds 0.8 MB\n // The weight is a rough estimate, so we flush way before the payload gets too big.\n if (weight >= 800000) {\n flushFn(client);\n } else if (!isTimerActive) {\n // Only start timer if one isn't already running.\n // This prevents flushing being delayed by items that arrive close to the timeout limit\n // and thus resetting the flushing timeout and delaying items being flushed.\n isTimerActive = true;\n flushTimeout = setTimeout(() => {\n flushFn(client);\n // Note: isTimerActive is reset by the flushHook handler above, not here,\n // to avoid race conditions when new items arrive during the flush.\n }, DEFAULT_FLUSH_INTERVAL);\n }\n });\n\n client.on('flush', () => {\n flushFn(client);\n });\n}\n\n/**\n * Base implementation for all JavaScript SDK clients.\n *\n * Call the constructor with the corresponding options\n * specific to the client subclass. To access these options later, use\n * {@link Client.getOptions}.\n *\n * If a Dsn is specified in the options, it will be parsed and stored. Use\n * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is\n * invalid, the constructor will throw a {@link SentryException}. Note that\n * without a valid Dsn, the SDK will not send any events to Sentry.\n *\n * Before sending an event, it is passed through\n * {@link Client._prepareEvent} to add SDK information and scope data\n * (breadcrumbs and context). To add more custom information, override this\n * method and extend the resulting prepared event.\n *\n * To issue automatically created events (e.g. via instrumentation), use\n * {@link Client.captureEvent}. It will prepare the event and pass it through\n * the callback lifecycle. To issue auto-breadcrumbs, use\n * {@link Client.addBreadcrumb}.\n *\n * @example\n * class NodeClient extends Client<NodeOptions> {\n * public constructor(options: NodeOptions) {\n * super(options);\n * }\n *\n * // ...\n * }\n */\nclass Client {\n /** Options passed to the SDK. */\n\n /** The client Dsn, if specified in options. Without this Dsn, the SDK will be disabled. */\n\n /** Array of set up integrations. */\n\n /** Number of calls being processed */\n\n /** Holds flushable */\n\n // eslint-disable-next-line @typescript-eslint/ban-types\n\n /**\n * Initializes this client instance.\n *\n * @param options Options for the client.\n */\n constructor(options) {\n this._options = options;\n this._integrations = {};\n this._numProcessing = 0;\n this._outcomes = {};\n this._hooks = {};\n this._eventProcessors = [];\n this._promiseBuffer = makePromiseBuffer(options.transportOptions?.bufferSize ?? DEFAULT_TRANSPORT_BUFFER_SIZE);\n\n if (options.dsn) {\n this._dsn = makeDsn(options.dsn);\n } else {\n DEBUG_BUILD && debug.warn('No DSN provided, client will not send events.');\n }\n\n if (this._dsn) {\n const url = getEnvelopeEndpointWithUrlEncodedAuth(\n this._dsn,\n options.tunnel,\n options._metadata ? options._metadata.sdk : undefined,\n );\n this._transport = options.transport({\n tunnel: this._options.tunnel,\n recordDroppedEvent: this.recordDroppedEvent.bind(this),\n ...options.transportOptions,\n url,\n });\n }\n\n // Backfill enableLogs option from _experiments.enableLogs\n // TODO(v11): Remove or change default value\n // eslint-disable-next-line deprecation/deprecation\n this._options.enableLogs = this._options.enableLogs ?? this._options._experiments?.enableLogs;\n\n // Setup log flushing with weight and timeout tracking\n if (this._options.enableLogs) {\n setupWeightBasedFlushing(this, 'afterCaptureLog', 'flushLogs', estimateLogSizeInBytes, _INTERNAL_flushLogsBuffer);\n }\n\n // todo(v11): Remove the experimental flag\n // eslint-disable-next-line deprecation/deprecation\n const enableMetrics = this._options.enableMetrics ?? this._options._experiments?.enableMetrics ?? true;\n\n // Setup metric flushing with weight and timeout tracking\n if (enableMetrics) {\n setupWeightBasedFlushing(\n this,\n 'afterCaptureMetric',\n 'flushMetrics',\n estimateMetricSizeInBytes,\n _INTERNAL_flushMetricsBuffer,\n );\n }\n }\n\n /**\n * Captures an exception event and sends it to Sentry.\n *\n * Unlike `captureException` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureException(exception, hint, scope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (checkOrSetAlreadyCaught(exception)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n this._process(\n () =>\n this.eventFromException(exception, hintWithEventId)\n .then(event => this._captureEvent(event, hintWithEventId, scope))\n .then(res => res),\n 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a message event and sends it to Sentry.\n *\n * Unlike `captureMessage` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureMessage(\n message,\n level,\n hint,\n currentScope,\n ) {\n const hintWithEventId = {\n event_id: uuid4(),\n ...hint,\n };\n\n const eventMessage = isParameterizedString(message) ? message : String(message);\n const isMessage = isPrimitive(message);\n const promisedEvent = isMessage\n ? this.eventFromMessage(eventMessage, level, hintWithEventId)\n : this.eventFromException(message, hintWithEventId);\n\n this._process(\n () => promisedEvent.then(event => this._captureEvent(event, hintWithEventId, currentScope)),\n isMessage ? 'unknown' : 'error',\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a manually created event and sends it to Sentry.\n *\n * Unlike `captureEvent` exported from every SDK, this method requires that you pass it the current scope.\n */\n captureEvent(event, hint, currentScope) {\n const eventId = uuid4();\n\n // ensure we haven't captured this very object before\n if (hint?.originalException && checkOrSetAlreadyCaught(hint.originalException)) {\n DEBUG_BUILD && debug.log(ALREADY_SEEN_ERROR);\n return eventId;\n }\n\n const hintWithEventId = {\n event_id: eventId,\n ...hint,\n };\n\n const sdkProcessingMetadata = event.sdkProcessingMetadata || {};\n const capturedSpanScope = sdkProcessingMetadata.capturedSpanScope;\n const capturedSpanIsolationScope = sdkProcessingMetadata.capturedSpanIsolationScope;\n const dataCategory = getDataCategoryByType(event.type);\n\n this._process(\n () => this._captureEvent(event, hintWithEventId, capturedSpanScope || currentScope, capturedSpanIsolationScope),\n dataCategory,\n );\n\n return hintWithEventId.event_id;\n }\n\n /**\n * Captures a session.\n */\n captureSession(session) {\n this.sendSession(session);\n // After sending, we set init false to indicate it's not the first occurrence\n updateSession(session, { init: false });\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry. This method is not available on all clients.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n * @param scope An optional scope containing event metadata.\n * @returns A string representing the id of the check in.\n */\n\n /**\n * Get the current Dsn.\n */\n getDsn() {\n return this._dsn;\n }\n\n /**\n * Get the current options.\n */\n getOptions() {\n return this._options;\n }\n\n /**\n * Get the SDK metadata.\n * @see SdkMetadata\n */\n getSdkMetadata() {\n return this._options._metadata;\n }\n\n /**\n * Returns the transport that is used by the client.\n * Please note that the transport gets lazy initialized so it will only be there once the first event has been sent.\n */\n getTransport() {\n return this._transport;\n }\n\n /**\n * Wait for all events to be sent or the timeout to expire, whichever comes first.\n *\n * @param timeout Maximum time in ms the client should wait for events to be flushed. Omitting this parameter will\n * cause the client to wait until all events are sent before resolving the promise.\n * @returns A promise that will resolve with `true` if all events are sent before the timeout, or `false` if there are\n * still events in the queue when the timeout is reached.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async flush(timeout) {\n const transport = this._transport;\n if (!transport) {\n return true;\n }\n\n this.emit('flush');\n\n const clientFinished = await this._isClientDoneProcessing(timeout);\n const transportFlushed = await transport.flush(timeout);\n\n return clientFinished && transportFlushed;\n }\n\n /**\n * Flush the event queue and set the client to `enabled = false`. See {@link Client.flush}.\n *\n * @param {number} timeout Maximum time in ms the client should wait before shutting down. Omitting this parameter will cause\n * the client to wait until all events are sent before disabling itself.\n * @returns {Promise<boolean>} A promise which resolves to `true` if the flush completes successfully before the timeout, or `false` if\n * it doesn't.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async close(timeout) {\n const result = await this.flush(timeout);\n this.getOptions().enabled = false;\n this.emit('close');\n return result;\n }\n\n /**\n * Get all installed event processors.\n */\n getEventProcessors() {\n return this._eventProcessors;\n }\n\n /**\n * Adds an event processor that applies to any event processed by this client.\n */\n addEventProcessor(eventProcessor) {\n this._eventProcessors.push(eventProcessor);\n }\n\n /**\n * Initialize this client.\n * Call this after the client was set on a scope.\n */\n init() {\n if (\n this._isEnabled() ||\n // Force integrations to be setup even if no DSN was set when we have\n // Spotlight enabled. This is particularly important for browser as we\n // don't support the `spotlight` option there and rely on the users\n // adding the `spotlightBrowserIntegration()` to their integrations which\n // wouldn't get initialized with the check below when there's no DSN set.\n this._options.integrations.some(({ name }) => name.startsWith('Spotlight'))\n ) {\n this._setupIntegrations();\n }\n }\n\n /**\n * Gets an installed integration by its name.\n *\n * @returns {Integration|undefined} The installed integration or `undefined` if no integration with that `name` was installed.\n */\n getIntegrationByName(integrationName) {\n return this._integrations[integrationName] ;\n }\n\n /**\n * Add an integration to the client.\n * This can be used to e.g. lazy load integrations.\n * In most cases, this should not be necessary,\n * and you're better off just passing the integrations via `integrations: []` at initialization time.\n * However, if you find the need to conditionally load & add an integration, you can use `addIntegration` to do so.\n */\n addIntegration(integration) {\n const isAlreadyInstalled = this._integrations[integration.name];\n\n // This hook takes care of only installing if not already installed\n setupIntegration(this, integration, this._integrations);\n // Here we need to check manually to make sure to not run this multiple times\n if (!isAlreadyInstalled) {\n afterSetupIntegrations(this, [integration]);\n }\n }\n\n /**\n * Send a fully prepared event to Sentry.\n */\n sendEvent(event, hint = {}) {\n this.emit('beforeSendEvent', event, hint);\n\n let env = createEventEnvelope(event, this._dsn, this._options._metadata, this._options.tunnel);\n\n for (const attachment of hint.attachments || []) {\n env = addItemToEnvelope(env, createAttachmentEnvelopeItem(attachment));\n }\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env).then(sendResponse => this.emit('afterSendEvent', event, sendResponse));\n }\n\n /**\n * Send a session or session aggregrates to Sentry.\n */\n sendSession(session) {\n // Backfill release and environment on session\n const { release: clientReleaseOption, environment: clientEnvironmentOption = DEFAULT_ENVIRONMENT } = this._options;\n if ('aggregates' in session) {\n const sessionAttrs = session.attrs || {};\n if (!sessionAttrs.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n sessionAttrs.release = sessionAttrs.release || clientReleaseOption;\n sessionAttrs.environment = sessionAttrs.environment || clientEnvironmentOption;\n session.attrs = sessionAttrs;\n } else {\n if (!session.release && !clientReleaseOption) {\n DEBUG_BUILD && debug.warn(MISSING_RELEASE_FOR_SESSION_ERROR);\n return;\n }\n session.release = session.release || clientReleaseOption;\n session.environment = session.environment || clientEnvironmentOption;\n }\n\n this.emit('beforeSendSession', session);\n\n const env = createSessionEnvelope(session, this._dsn, this._options._metadata, this._options.tunnel);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(env);\n }\n\n /**\n * Record on the client that an event got dropped (ie, an event that will not be sent to Sentry).\n */\n recordDroppedEvent(reason, category, count = 1) {\n if (this._options.sendClientReports) {\n // We want to track each category (error, transaction, session, replay_event) separately\n // but still keep the distinction between different type of outcomes.\n // We could use nested maps, but it's much easier to read and type this way.\n // A correct type for map-based implementation if we want to go that route\n // would be `Partial<Record<SentryRequestType, Partial<Record<Outcome, number>>>>`\n // With typescript 4.1 we could even use template literal types\n const key = `${reason}:${category}`;\n DEBUG_BUILD && debug.log(`Recording outcome: \"${key}\"${count > 1 ? ` (${count} times)` : ''}`);\n this._outcomes[key] = (this._outcomes[key] || 0) + count;\n }\n }\n\n /* eslint-disable @typescript-eslint/unified-signatures */\n /**\n * Register a callback for whenever a span is started.\n * Receives the span as argument.\n * @returns {() => void} A function that, when executed, removes the registered callback.\n */\n\n /**\n * Register a hook on this client.\n */\n on(hook, callback) {\n const hookCallbacks = (this._hooks[hook] = this._hooks[hook] || new Set());\n\n // Wrap the callback in a function so that registering the same callback instance multiple\n // times results in the callback being called multiple times.\n // @ts-expect-error - The `callback` type is correct and must be a function due to the\n // individual, specific overloads of this function.\n // eslint-disable-next-line @typescript-eslint/ban-types\n const uniqueCallback = (...args) => callback(...args);\n\n hookCallbacks.add(uniqueCallback);\n\n // This function returns a callback execution handler that, when invoked,\n // deregisters a callback. This is crucial for managing instances where callbacks\n // need to be unregistered to prevent self-referencing in callback closures,\n // ensuring proper garbage collection.\n return () => {\n hookCallbacks.delete(uniqueCallback);\n };\n }\n\n /** Fire a hook whenever a span starts. */\n\n /**\n * Emit a hook that was previously registered via `on()`.\n */\n emit(hook, ...rest) {\n const callbacks = this._hooks[hook];\n if (callbacks) {\n callbacks.forEach(callback => callback(...rest));\n }\n }\n\n /**\n * Send an envelope to Sentry.\n */\n // @ts-expect-error - PromiseLike is a subset of Promise\n async sendEnvelope(envelope) {\n this.emit('beforeEnvelope', envelope);\n\n if (this._isEnabled() && this._transport) {\n try {\n return await this._transport.send(envelope);\n } catch (reason) {\n DEBUG_BUILD && debug.error('Error while sending envelope:', reason);\n return {};\n }\n }\n\n DEBUG_BUILD && debug.error('Transport disabled');\n return {};\n }\n\n /* eslint-enable @typescript-eslint/unified-signatures */\n\n /** Setup integrations for this client. */\n _setupIntegrations() {\n const { integrations } = this._options;\n this._integrations = setupIntegrations(this, integrations);\n afterSetupIntegrations(this, integrations);\n }\n\n /** Updates existing session based on the provided event */\n _updateSessionFromEvent(session, event) {\n // initially, set `crashed` based on the event level and update from exceptions if there are any later on\n let crashed = event.level === 'fatal';\n let errored = false;\n const exceptions = event.exception?.values;\n\n if (exceptions) {\n errored = true;\n // reset crashed to false if there are exceptions, to ensure `mechanism.handled` is respected.\n crashed = false;\n\n for (const ex of exceptions) {\n if (ex.mechanism?.handled === false) {\n crashed = true;\n break;\n }\n }\n }\n\n // A session is updated and that session update is sent in only one of the two following scenarios:\n // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update\n // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update\n const sessionNonTerminal = session.status === 'ok';\n const shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed);\n\n if (shouldUpdateAndSend) {\n updateSession(session, {\n ...(crashed && { status: 'crashed' }),\n errors: session.errors || Number(errored || crashed),\n });\n this.captureSession(session);\n }\n }\n\n /**\n * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying\n * \"no\" (resolving to `false`) in order to give the client a chance to potentially finish first.\n *\n * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not\n * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to\n * `true`.\n * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and\n * `false` otherwise\n */\n async _isClientDoneProcessing(timeout) {\n let ticked = 0;\n\n // if no timeout is provided, we wait \"forever\" until everything is processed\n while (!timeout || ticked < timeout) {\n await new Promise(resolve => setTimeout(resolve, 1));\n\n if (!this._numProcessing) {\n return true;\n }\n ticked++;\n }\n\n return false;\n }\n\n /** Determines whether this SDK is enabled and a transport is present. */\n _isEnabled() {\n return this.getOptions().enabled !== false && this._transport !== undefined;\n }\n\n /**\n * Adds common information to events.\n *\n * The information includes release and environment from `options`,\n * breadcrumbs and context (extra, tags and user) from the scope.\n *\n * Information that is already present in the event is never overwritten. For\n * nested objects, such as the context, keys are merged.\n *\n * @param event The original event.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A new event with more information.\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const integrations = Object.keys(this._integrations);\n if (!hint.integrations && integrations?.length) {\n hint.integrations = integrations;\n }\n\n this.emit('preprocessEvent', event, hint);\n\n if (!event.type) {\n isolationScope.setLastEventId(event.event_id || hint.event_id);\n }\n\n return prepareEvent(options, event, hint, currentScope, this, isolationScope).then(evt => {\n if (evt === null) {\n return evt;\n }\n\n this.emit('postprocessEvent', evt, hint);\n\n evt.contexts = {\n trace: getTraceContextFromScope(currentScope),\n ...evt.contexts,\n };\n\n const dynamicSamplingContext = getDynamicSamplingContextFromScope(this, currentScope);\n\n evt.sdkProcessingMetadata = {\n dynamicSamplingContext,\n ...evt.sdkProcessingMetadata,\n };\n\n return evt;\n });\n }\n\n /**\n * Processes the event and logs an error in case of rejection\n * @param event\n * @param hint\n * @param scope\n */\n _captureEvent(\n event,\n hint = {},\n currentScope = getCurrentScope(),\n isolationScope = getIsolationScope(),\n ) {\n if (DEBUG_BUILD && isErrorEvent(event)) {\n debug.log(`Captured error event \\`${getPossibleEventMessages(event)[0] || '<unknown>'}\\``);\n }\n\n return this._processEvent(event, hint, currentScope, isolationScope).then(\n finalEvent => {\n return finalEvent.event_id;\n },\n reason => {\n if (DEBUG_BUILD) {\n if (_isDoNotSendEventError(reason)) {\n debug.log(reason.message);\n } else if (_isInternalError(reason)) {\n debug.warn(reason.message);\n } else {\n debug.warn(reason);\n }\n }\n return undefined;\n },\n );\n }\n\n /**\n * Processes an event (either error or message) and sends it to Sentry.\n *\n * This also adds breadcrumbs and context information to the event. However,\n * platform specific meta data (such as the User's IP address) must be added\n * by the SDK implementor.\n *\n *\n * @param event The event to send to Sentry.\n * @param hint May contain additional information about the original exception.\n * @param currentScope A scope containing event metadata.\n * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send.\n */\n _processEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n const options = this.getOptions();\n const { sampleRate } = options;\n\n const isTransaction = isTransactionEvent(event);\n const isError = isErrorEvent(event);\n const eventType = event.type || 'error';\n const beforeSendLabel = `before send for type \\`${eventType}\\``;\n\n // 1.0 === 100% events are sent\n // 0.0 === 0% events are sent\n // Sampling for transaction happens somewhere else\n const parsedSampleRate = typeof sampleRate === 'undefined' ? undefined : parseSampleRate(sampleRate);\n if (isError && typeof parsedSampleRate === 'number' && Math.random() > parsedSampleRate) {\n this.recordDroppedEvent('sample_rate', 'error');\n return rejectedSyncPromise(\n _makeDoNotSendEventError(\n `Discarding event because it's not included in the random sample (sampling rate = ${sampleRate})`,\n ),\n );\n }\n\n const dataCategory = getDataCategoryByType(event.type);\n\n return this._prepareEvent(event, hint, currentScope, isolationScope)\n .then(prepared => {\n if (prepared === null) {\n this.recordDroppedEvent('event_processor', dataCategory);\n throw _makeDoNotSendEventError('An event processor returned `null`, will not send event.');\n }\n\n const isInternalException = hint.data && (hint.data ).__sentry__ === true;\n if (isInternalException) {\n return prepared;\n }\n\n const result = processBeforeSend(this, options, prepared, hint);\n return _validateBeforeSendResult(result, beforeSendLabel);\n })\n .then(processedEvent => {\n if (processedEvent === null) {\n this.recordDroppedEvent('before_send', dataCategory);\n if (isTransaction) {\n const spans = event.spans || [];\n // the transaction itself counts as one span, plus all the child spans that are added\n const spanCount = 1 + spans.length;\n this.recordDroppedEvent('before_send', 'span', spanCount);\n }\n throw _makeDoNotSendEventError(`${beforeSendLabel} returned \\`null\\`, will not send event.`);\n }\n\n const session = currentScope.getSession() || isolationScope.getSession();\n if (isError && session) {\n this._updateSessionFromEvent(session, processedEvent);\n }\n\n if (isTransaction) {\n const spanCountBefore = processedEvent.sdkProcessingMetadata?.spanCountBeforeProcessing || 0;\n const spanCountAfter = processedEvent.spans ? processedEvent.spans.length : 0;\n\n const droppedSpanCount = spanCountBefore - spanCountAfter;\n if (droppedSpanCount > 0) {\n this.recordDroppedEvent('before_send', 'span', droppedSpanCount);\n }\n }\n\n // None of the Sentry built event processor will update transaction name,\n // so if the transaction name has been changed by an event processor, we know\n // it has to come from custom event processor added by a user\n const transactionInfo = processedEvent.transaction_info;\n if (isTransaction && transactionInfo && processedEvent.transaction !== event.transaction) {\n const source = 'custom';\n processedEvent.transaction_info = {\n ...transactionInfo,\n source,\n };\n }\n\n this.sendEvent(processedEvent, hint);\n return processedEvent;\n })\n .then(null, reason => {\n if (_isDoNotSendEventError(reason) || _isInternalError(reason)) {\n throw reason;\n }\n\n this.captureException(reason, {\n mechanism: {\n handled: false,\n type: 'internal',\n },\n data: {\n __sentry__: true,\n },\n originalException: reason,\n });\n throw _makeInternalError(\n `Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\\nReason: ${reason}`,\n );\n });\n }\n\n /**\n * Occupies the client with processing and event\n */\n _process(taskProducer, dataCategory) {\n this._numProcessing++;\n\n void this._promiseBuffer.add(taskProducer).then(\n value => {\n this._numProcessing--;\n return value;\n },\n reason => {\n this._numProcessing--;\n\n if (reason === SENTRY_BUFFER_FULL_ERROR) {\n this.recordDroppedEvent('queue_overflow', dataCategory);\n }\n\n return reason;\n },\n );\n }\n\n /**\n * Clears outcomes on this client and returns them.\n */\n _clearOutcomes() {\n const outcomes = this._outcomes;\n this._outcomes = {};\n return Object.entries(outcomes).map(([key, quantity]) => {\n const [reason, category] = key.split(':') ;\n return {\n reason,\n category,\n quantity,\n };\n });\n }\n\n /**\n * Sends client reports as an envelope.\n */\n _flushOutcomes() {\n DEBUG_BUILD && debug.log('Flushing outcomes...');\n\n const outcomes = this._clearOutcomes();\n\n if (outcomes.length === 0) {\n DEBUG_BUILD && debug.log('No outcomes to send');\n return;\n }\n\n // This is really the only place where we want to check for a DSN and only send outcomes then\n if (!this._dsn) {\n DEBUG_BUILD && debug.log('No dsn provided, will not send outcomes');\n return;\n }\n\n DEBUG_BUILD && debug.log('Sending outcomes:', outcomes);\n\n const envelope = createClientReportEnvelope(outcomes, this._options.tunnel && dsnToString(this._dsn));\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n }\n\n /**\n * Creates an {@link Event} from all inputs to `captureException` and non-primitive inputs to `captureMessage`.\n */\n\n}\n\nfunction getDataCategoryByType(type) {\n return type === 'replay_event' ? 'replay' : type || 'error';\n}\n\n/**\n * Verifies that return value of configured `beforeSend` or `beforeSendTransaction` is of expected type, and returns the value if so.\n */\nfunction _validateBeforeSendResult(\n beforeSendResult,\n beforeSendLabel,\n) {\n const invalidValueError = `${beforeSendLabel} must return \\`null\\` or a valid event.`;\n if (isThenable(beforeSendResult)) {\n return beforeSendResult.then(\n event => {\n if (!isPlainObject(event) && event !== null) {\n throw _makeInternalError(invalidValueError);\n }\n return event;\n },\n e => {\n throw _makeInternalError(`${beforeSendLabel} rejected with ${e}`);\n },\n );\n } else if (!isPlainObject(beforeSendResult) && beforeSendResult !== null) {\n throw _makeInternalError(invalidValueError);\n }\n return beforeSendResult;\n}\n\n/**\n * Process the matching `beforeSendXXX` callback.\n */\nfunction processBeforeSend(\n client,\n options,\n event,\n hint,\n) {\n const { beforeSend, beforeSendTransaction, beforeSendSpan, ignoreSpans } = options;\n let processedEvent = event;\n\n if (isErrorEvent(processedEvent) && beforeSend) {\n return beforeSend(processedEvent, hint);\n }\n\n if (isTransactionEvent(processedEvent)) {\n // Avoid processing if we don't have to\n if (beforeSendSpan || ignoreSpans) {\n // 1. Process root span\n const rootSpanJson = convertTransactionEventToSpanJson(processedEvent);\n\n // 1.1 If the root span should be ignored, drop the whole transaction\n if (ignoreSpans?.length && shouldIgnoreSpan(rootSpanJson, ignoreSpans)) {\n // dropping the whole transaction!\n return null;\n }\n\n // 1.2 If a `beforeSendSpan` callback is defined, process the root span\n if (beforeSendSpan) {\n const processedRootSpanJson = beforeSendSpan(rootSpanJson);\n if (!processedRootSpanJson) {\n showSpanDropWarning();\n } else {\n // update event with processed root span values\n processedEvent = merge(event, convertSpanJsonToTransactionEvent(processedRootSpanJson));\n }\n }\n\n // 2. Process child spans\n if (processedEvent.spans) {\n const processedSpans = [];\n\n const initialSpans = processedEvent.spans;\n\n for (const span of initialSpans) {\n // 2.a If the child span should be ignored, reparent it to the root span\n if (ignoreSpans?.length && shouldIgnoreSpan(span, ignoreSpans)) {\n reparentChildSpans(initialSpans, span);\n continue;\n }\n\n // 2.b If a `beforeSendSpan` callback is defined, process the child span\n if (beforeSendSpan) {\n const processedSpan = beforeSendSpan(span);\n if (!processedSpan) {\n showSpanDropWarning();\n processedSpans.push(span);\n } else {\n processedSpans.push(processedSpan);\n }\n } else {\n processedSpans.push(span);\n }\n }\n\n const droppedSpans = processedEvent.spans.length - processedSpans.length;\n if (droppedSpans) {\n client.recordDroppedEvent('before_send', 'span', droppedSpans);\n }\n\n processedEvent.spans = processedSpans;\n }\n }\n\n if (beforeSendTransaction) {\n if (processedEvent.spans) {\n // We store the # of spans before processing in SDK metadata,\n // so we can compare it afterwards to determine how many spans were dropped\n const spanCountBefore = processedEvent.spans.length;\n processedEvent.sdkProcessingMetadata = {\n ...event.sdkProcessingMetadata,\n spanCountBeforeProcessing: spanCountBefore,\n };\n }\n return beforeSendTransaction(processedEvent , hint);\n }\n }\n\n return processedEvent;\n}\n\nfunction isErrorEvent(event) {\n return event.type === undefined;\n}\n\nfunction isTransactionEvent(event) {\n return event.type === 'transaction';\n}\n\n/**\n * Estimate the size of a metric in bytes.\n *\n * @param metric - The metric to estimate the size of.\n * @returns The estimated size of the metric in bytes.\n */\nfunction estimateMetricSizeInBytes(metric) {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (metric.name) {\n weight += metric.name.length * 2;\n }\n\n // Add weight for number\n weight += 8;\n\n return weight + estimateAttributesSizeInBytes(metric.attributes);\n}\n\n/**\n * Estimate the size of a log in bytes.\n *\n * @param log - The log to estimate the size of.\n * @returns The estimated size of the log in bytes.\n */\nfunction estimateLogSizeInBytes(log) {\n let weight = 0;\n\n // Estimate byte size of 2 bytes per character. This is a rough estimate JS strings are stored as UTF-16.\n if (log.message) {\n weight += log.message.length * 2;\n }\n\n return weight + estimateAttributesSizeInBytes(log.attributes);\n}\n\n/**\n * Estimate the size of attributes in bytes.\n *\n * @param attributes - The attributes object to estimate the size of.\n * @returns The estimated size of the attributes in bytes.\n */\nfunction estimateAttributesSizeInBytes(attributes) {\n if (!attributes) {\n return 0;\n }\n\n let weight = 0;\n\n Object.values(attributes).forEach(value => {\n if (Array.isArray(value)) {\n weight += value.length * estimatePrimitiveSizeInBytes(value[0]);\n } else if (isPrimitive(value)) {\n weight += estimatePrimitiveSizeInBytes(value);\n } else {\n // For objects values, we estimate the size of the object as 100 bytes\n weight += 100;\n }\n });\n\n return weight;\n}\n\nfunction estimatePrimitiveSizeInBytes(value) {\n if (typeof value === 'string') {\n return value.length * 2;\n } else if (typeof value === 'number') {\n return 8;\n } else if (typeof value === 'boolean') {\n return 4;\n }\n\n return 0;\n}\n\nexport { Client };\n//# sourceMappingURL=client.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { forEachEnvelopeItem, envelopeItemTypeToDataCategory, createEnvelope, serializeEnvelope } from '../utils/envelope.js';\nimport { makePromiseBuffer, SENTRY_BUFFER_FULL_ERROR } from '../utils/promisebuffer.js';\nimport { isRateLimited, updateRateLimits } from '../utils/ratelimit.js';\n\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 64;\n\n/**\n * Creates an instance of a Sentry `Transport`\n *\n * @param options\n * @param makeRequest\n */\nfunction createTransport(\n options,\n makeRequest,\n buffer = makePromiseBuffer(\n options.bufferSize || DEFAULT_TRANSPORT_BUFFER_SIZE,\n ),\n) {\n let rateLimits = {};\n const flush = (timeout) => buffer.drain(timeout);\n\n function send(envelope) {\n const filteredEnvelopeItems = [];\n\n // Drop rate limited items from envelope\n forEachEnvelopeItem(envelope, (item, type) => {\n const dataCategory = envelopeItemTypeToDataCategory(type);\n if (isRateLimited(rateLimits, dataCategory)) {\n options.recordDroppedEvent('ratelimit_backoff', dataCategory);\n } else {\n filteredEnvelopeItems.push(item);\n }\n });\n\n // Skip sending if envelope is empty after filtering out rate limited events\n if (filteredEnvelopeItems.length === 0) {\n return Promise.resolve({});\n }\n\n const filteredEnvelope = createEnvelope(envelope[0], filteredEnvelopeItems );\n\n // Creates client report for each item in an envelope\n const recordEnvelopeLoss = (reason) => {\n forEachEnvelopeItem(filteredEnvelope, (item, type) => {\n options.recordDroppedEvent(reason, envelopeItemTypeToDataCategory(type));\n });\n };\n\n const requestTask = () =>\n makeRequest({ body: serializeEnvelope(filteredEnvelope) }).then(\n response => {\n // We don't want to throw on NOK responses, but we want to at least log them\n if (response.statusCode !== undefined && (response.statusCode < 200 || response.statusCode >= 300)) {\n DEBUG_BUILD && debug.warn(`Sentry responded with status code ${response.statusCode} to sent event.`);\n }\n\n rateLimits = updateRateLimits(rateLimits, response);\n return response;\n },\n error => {\n recordEnvelopeLoss('network_error');\n DEBUG_BUILD && debug.error('Encountered error running transport request:', error);\n throw error;\n },\n );\n\n return buffer.add(requestTask).then(\n result => result,\n error => {\n if (error === SENTRY_BUFFER_FULL_ERROR) {\n DEBUG_BUILD && debug.error('Skipped sending event because buffer is full.');\n recordEnvelopeLoss('queue_overflow');\n return Promise.resolve({});\n } else {\n throw error;\n }\n },\n );\n }\n\n return {\n send,\n flush,\n };\n}\n\nexport { DEFAULT_TRANSPORT_BUFFER_SIZE, createTransport };\n//# sourceMappingURL=base.js.map\n","import { SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME, SEMANTIC_ATTRIBUTE_PROFILE_ID } from '../semanticAttributes.js';\n\n/**\n * Converts a transaction event to a span JSON object.\n */\nfunction convertTransactionEventToSpanJson(event) {\n const { trace_id, parent_span_id, span_id, status, origin, data, op } = event.contexts?.trace ?? {};\n\n return {\n data: data ?? {},\n description: event.transaction,\n op,\n parent_span_id,\n span_id: span_id ?? '',\n start_timestamp: event.start_timestamp ?? 0,\n status,\n timestamp: event.timestamp,\n trace_id: trace_id ?? '',\n origin,\n profile_id: data?.[SEMANTIC_ATTRIBUTE_PROFILE_ID] ,\n exclusive_time: data?.[SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME] ,\n measurements: event.measurements,\n is_segment: true,\n };\n}\n\n/**\n * Converts a span JSON object to a transaction event.\n */\nfunction convertSpanJsonToTransactionEvent(span) {\n return {\n type: 'transaction',\n timestamp: span.timestamp,\n start_timestamp: span.start_timestamp,\n transaction: span.description,\n contexts: {\n trace: {\n trace_id: span.trace_id,\n span_id: span.span_id,\n parent_span_id: span.parent_span_id,\n op: span.op,\n status: span.status,\n origin: span.origin,\n data: {\n ...span.data,\n ...(span.profile_id && { [SEMANTIC_ATTRIBUTE_PROFILE_ID]: span.profile_id }),\n ...(span.exclusive_time && { [SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME]: span.exclusive_time }),\n },\n },\n },\n measurements: span.measurements,\n };\n}\n\nexport { convertSpanJsonToTransactionEvent, convertTransactionEventToSpanJson };\n//# sourceMappingURL=transactionEvent.js.map\n","import { dsnToString } from './utils/dsn.js';\nimport { createEnvelope } from './utils/envelope.js';\n\n/**\n * Create envelope from check in item.\n */\nfunction createCheckInEnvelope(\n checkIn,\n dynamicSamplingContext,\n metadata,\n tunnel,\n dsn,\n) {\n const headers = {\n sent_at: new Date().toISOString(),\n };\n\n if (metadata?.sdk) {\n headers.sdk = {\n name: metadata.sdk.name,\n version: metadata.sdk.version,\n };\n }\n\n if (!!tunnel && !!dsn) {\n headers.dsn = dsnToString(dsn);\n }\n\n if (dynamicSamplingContext) {\n headers.trace = dynamicSamplingContext ;\n }\n\n const item = createCheckInEnvelopeItem(checkIn);\n return createEnvelope(headers, [item]);\n}\n\nfunction createCheckInEnvelopeItem(checkIn) {\n const checkInHeaders = {\n type: 'check_in',\n };\n return [checkInHeaders, checkIn];\n}\n\nexport { createCheckInEnvelope };\n//# sourceMappingURL=checkin.js.map\n","import { isParameterizedString, isError, isPlainObject, isErrorEvent } from './is.js';\nimport { addExceptionMechanism, addExceptionTypeValue } from './misc.js';\nimport { normalizeToSize } from './normalize.js';\nimport { extractExceptionKeysForMessage } from './object.js';\n\n/**\n * Extracts stack frames from the error.stack string\n */\nfunction parseStackFrames(stackParser, error) {\n return stackParser(error.stack || '', 1);\n}\n\n/**\n * Extracts stack frames from the error and builds a Sentry Exception\n */\nfunction exceptionFromError(stackParser, error) {\n const exception = {\n type: error.name || error.constructor.name,\n value: error.message,\n };\n\n const frames = parseStackFrames(stackParser, error);\n if (frames.length) {\n exception.stacktrace = { frames };\n }\n\n return exception;\n}\n\n/** If a plain object has a property that is an `Error`, return this error. */\nfunction getErrorPropertyFromObject(obj) {\n for (const prop in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n const value = obj[prop];\n if (value instanceof Error) {\n return value;\n }\n }\n }\n\n return undefined;\n}\n\nfunction getMessageForObject(exception) {\n if ('name' in exception && typeof exception.name === 'string') {\n let message = `'${exception.name}' captured as exception`;\n\n if ('message' in exception && typeof exception.message === 'string') {\n message += ` with message '${exception.message}'`;\n }\n\n return message;\n } else if ('message' in exception && typeof exception.message === 'string') {\n return exception.message;\n }\n\n const keys = extractExceptionKeysForMessage(exception);\n\n // Some ErrorEvent instances do not have an `error` property, which is why they are not handled before\n // We still want to try to get a decent message for these cases\n if (isErrorEvent(exception)) {\n return `Event \\`ErrorEvent\\` captured as exception with message \\`${exception.message}\\``;\n }\n\n const className = getObjectClassName(exception);\n\n return `${\n className && className !== 'Object' ? `'${className}'` : 'Object'\n } captured as exception with keys: ${keys}`;\n}\n\nfunction getObjectClassName(obj) {\n try {\n const prototype = Object.getPrototypeOf(obj);\n return prototype ? prototype.constructor.name : undefined;\n } catch {\n // ignore errors here\n }\n}\n\nfunction getException(\n client,\n mechanism,\n exception,\n hint,\n) {\n if (isError(exception)) {\n return [exception, undefined];\n }\n\n // Mutate this!\n mechanism.synthetic = true;\n\n if (isPlainObject(exception)) {\n const normalizeDepth = client?.getOptions().normalizeDepth;\n const extras = { ['__serialized__']: normalizeToSize(exception, normalizeDepth) };\n\n const errorFromProp = getErrorPropertyFromObject(exception);\n if (errorFromProp) {\n return [errorFromProp, extras];\n }\n\n const message = getMessageForObject(exception);\n const ex = hint?.syntheticException || new Error(message);\n ex.message = message;\n\n return [ex, extras];\n }\n\n // This handles when someone does: `throw \"something awesome\";`\n // We use synthesized Error here so we can extract a (rough) stack trace.\n const ex = hint?.syntheticException || new Error(exception );\n ex.message = `${exception}`;\n\n return [ex, undefined];\n}\n\n/**\n * Builds and Event from a Exception\n * @hidden\n */\nfunction eventFromUnknownInput(\n client,\n stackParser,\n exception,\n hint,\n) {\n const providedMechanism = hint?.data && (hint.data ).mechanism;\n const mechanism = providedMechanism || {\n handled: true,\n type: 'generic',\n };\n\n const [ex, extras] = getException(client, mechanism, exception, hint);\n\n const event = {\n exception: {\n values: [exceptionFromError(stackParser, ex)],\n },\n };\n\n if (extras) {\n event.extra = extras;\n }\n\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, mechanism);\n\n return {\n ...event,\n event_id: hint?.event_id,\n };\n}\n\n/**\n * Builds and Event from a Message\n * @hidden\n */\nfunction eventFromMessage(\n stackParser,\n message,\n level = 'info',\n hint,\n attachStacktrace,\n) {\n const event = {\n event_id: hint?.event_id,\n level,\n };\n\n if (attachStacktrace && hint?.syntheticException) {\n const frames = parseStackFrames(stackParser, hint.syntheticException);\n if (frames.length) {\n event.exception = {\n values: [\n {\n value: message,\n stacktrace: { frames },\n },\n ],\n };\n addExceptionMechanism(event, { synthetic: true });\n }\n }\n\n if (isParameterizedString(message)) {\n const { __sentry_template_string__, __sentry_template_values__ } = message;\n\n event.logentry = {\n message: __sentry_template_string__,\n params: __sentry_template_values__,\n };\n return event;\n }\n\n event.message = message;\n return event;\n}\n\nexport { eventFromMessage, eventFromUnknownInput, exceptionFromError, parseStackFrames };\n//# sourceMappingURL=eventbuilder.js.map\n","import { createCheckInEnvelope } from './checkin.js';\nimport { Client } from './client.js';\nimport { getIsolationScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { registerSpanErrorInstrumentation } from './tracing/errors.js';\nimport { debug } from './utils/debug-logger.js';\nimport { uuid4 } from './utils/misc.js';\nimport { addUserAgentToTransportHeaders } from './transports/userAgent.js';\nimport { eventFromUnknownInput, eventFromMessage } from './utils/eventbuilder.js';\nimport { resolvedSyncPromise } from './utils/syncpromise.js';\nimport { _getTraceInfoFromScope } from './utils/trace-info.js';\n\n/**\n * The Sentry Server Runtime Client SDK.\n */\nclass ServerRuntimeClient\n\n extends Client {\n /**\n * Creates a new Edge SDK instance.\n * @param options Configuration options for this SDK.\n */\n constructor(options) {\n // Server clients always support tracing\n registerSpanErrorInstrumentation();\n\n addUserAgentToTransportHeaders(options);\n\n super(options);\n\n this._setUpMetricsProcessing();\n }\n\n /**\n * @inheritDoc\n */\n eventFromException(exception, hint) {\n const event = eventFromUnknownInput(this, this._options.stackParser, exception, hint);\n event.level = 'error';\n\n return resolvedSyncPromise(event);\n }\n\n /**\n * @inheritDoc\n */\n eventFromMessage(\n message,\n level = 'info',\n hint,\n ) {\n return resolvedSyncPromise(\n eventFromMessage(this._options.stackParser, message, level, hint, this._options.attachStacktrace),\n );\n }\n\n /**\n * @inheritDoc\n */\n captureException(exception, hint, scope) {\n setCurrentRequestSessionErroredOrCrashed(hint);\n return super.captureException(exception, hint, scope);\n }\n\n /**\n * @inheritDoc\n */\n captureEvent(event, hint, scope) {\n // If the event is of type Exception, then a request session should be captured\n const isException = !event.type && event.exception?.values && event.exception.values.length > 0;\n if (isException) {\n setCurrentRequestSessionErroredOrCrashed(hint);\n }\n\n return super.captureEvent(event, hint, scope);\n }\n\n /**\n * Create a cron monitor check in and send it to Sentry.\n *\n * @param checkIn An object that describes a check in.\n * @param upsertMonitorConfig An optional object that describes a monitor config. Use this if you want\n * to create a monitor automatically when sending a check in.\n */\n captureCheckIn(checkIn, monitorConfig, scope) {\n const id = 'checkInId' in checkIn && checkIn.checkInId ? checkIn.checkInId : uuid4();\n if (!this._isEnabled()) {\n DEBUG_BUILD && debug.warn('SDK not enabled, will not capture check-in.');\n return id;\n }\n\n const options = this.getOptions();\n const { release, environment, tunnel } = options;\n\n const serializedCheckIn = {\n check_in_id: id,\n monitor_slug: checkIn.monitorSlug,\n status: checkIn.status,\n release,\n environment,\n };\n\n if ('duration' in checkIn) {\n serializedCheckIn.duration = checkIn.duration;\n }\n\n if (monitorConfig) {\n serializedCheckIn.monitor_config = {\n schedule: monitorConfig.schedule,\n checkin_margin: monitorConfig.checkinMargin,\n max_runtime: monitorConfig.maxRuntime,\n timezone: monitorConfig.timezone,\n failure_issue_threshold: monitorConfig.failureIssueThreshold,\n recovery_threshold: monitorConfig.recoveryThreshold,\n };\n }\n\n const [dynamicSamplingContext, traceContext] = _getTraceInfoFromScope(this, scope);\n if (traceContext) {\n serializedCheckIn.contexts = {\n trace: traceContext,\n };\n }\n\n const envelope = createCheckInEnvelope(\n serializedCheckIn,\n dynamicSamplingContext,\n this.getSdkMetadata(),\n tunnel,\n this.getDsn(),\n );\n\n DEBUG_BUILD && debug.log('Sending checkin:', checkIn.monitorSlug, checkIn.status);\n\n // sendEnvelope should not throw\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n this.sendEnvelope(envelope);\n\n return id;\n }\n\n /**\n * @inheritDoc\n */\n _prepareEvent(\n event,\n hint,\n currentScope,\n isolationScope,\n ) {\n if (this._options.platform) {\n event.platform = event.platform || this._options.platform;\n }\n\n if (this._options.runtime) {\n event.contexts = {\n ...event.contexts,\n runtime: event.contexts?.runtime || this._options.runtime,\n };\n }\n\n if (this._options.serverName) {\n event.server_name = event.server_name || this._options.serverName;\n }\n\n return super._prepareEvent(event, hint, currentScope, isolationScope);\n }\n\n /**\n * Process a server-side metric before it is captured.\n */\n _setUpMetricsProcessing() {\n this.on('processMetric', metric => {\n if (this._options.serverName) {\n metric.attributes = {\n 'server.address': this._options.serverName,\n ...metric.attributes,\n };\n }\n });\n }\n}\n\nfunction setCurrentRequestSessionErroredOrCrashed(eventHint) {\n const requestSession = getIsolationScope().getScopeData().sdkProcessingMetadata.requestSession;\n if (requestSession) {\n // We mutate instead of doing `setSdkProcessingMetadata` because the http integration stores away a particular\n // isolationScope. If that isolation scope is forked, setting the processing metadata here will not mutate the\n // original isolation scope that the http integration stored away.\n const isHandledException = eventHint?.mechanism?.handled ?? true;\n // A request session can go from \"errored\" -> \"crashed\" but not \"crashed\" -> \"errored\".\n // Crashed (unhandled exception) is worse than errored (handled exception).\n if (isHandledException && requestSession.status !== 'crashed') {\n requestSession.status = 'errored';\n } else if (!isHandledException) {\n requestSession.status = 'crashed';\n }\n }\n}\n\nexport { ServerRuntimeClient };\n//# sourceMappingURL=server-runtime-client.js.map\n","import { getCurrentScope } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { debug, consoleSandbox } from './utils/debug-logger.js';\n\n/** A class object that can instantiate Client objects. */\n\n/**\n * Internal function to create a new SDK client instance. The client is\n * installed and then bound to the current scope.\n *\n * @param clientClass The client class to instantiate.\n * @param options Options to pass to the client.\n */\nfunction initAndBind(\n clientClass,\n options,\n) {\n if (options.debug === true) {\n if (DEBUG_BUILD) {\n debug.enable();\n } else {\n // use `console.warn` rather than `debug.warn` since by non-debug bundles have all `debug.x` statements stripped\n consoleSandbox(() => {\n // eslint-disable-next-line no-console\n console.warn('[Sentry] Cannot initialize SDK with `debug` option using a non-debug bundle.');\n });\n }\n }\n const scope = getCurrentScope();\n scope.update(options.initialScope);\n\n const client = new clientClass(options);\n setCurrentClient(client);\n client.init();\n return client;\n}\n\n/**\n * Make the given client the current client.\n */\nfunction setCurrentClient(client) {\n getCurrentScope().setClient(client);\n}\n\nexport { initAndBind, setCurrentClient };\n//# sourceMappingURL=sdk.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { envelopeContainsItemType } from '../utils/envelope.js';\nimport { parseRetryAfterHeader } from '../utils/ratelimit.js';\n\nconst MIN_DELAY = 100; // 100 ms\nconst START_DELAY = 5000; // 5 seconds\nconst MAX_DELAY = 3.6e6; // 1 hour\n\n/**\n * Wraps a transport and stores and retries events when they fail to send.\n *\n * @param createTransport The transport to wrap.\n */\nfunction makeOfflineTransport(\n createTransport,\n) {\n function log(...args) {\n DEBUG_BUILD && debug.log('[Offline]:', ...args);\n }\n\n return options => {\n const transport = createTransport(options);\n\n if (!options.createStore) {\n throw new Error('No `createStore` function was provided');\n }\n\n const store = options.createStore(options);\n\n let retryDelay = START_DELAY;\n let flushTimer;\n\n function shouldQueue(env, error, retryDelay) {\n // We want to drop client reports because they can be generated when we retry sending events while offline.\n if (envelopeContainsItemType(env, ['client_report'])) {\n return false;\n }\n\n if (options.shouldStore) {\n return options.shouldStore(env, error, retryDelay);\n }\n\n return true;\n }\n\n function flushIn(delay) {\n if (flushTimer) {\n clearTimeout(flushTimer );\n }\n\n flushTimer = setTimeout(async () => {\n flushTimer = undefined;\n\n const found = await store.shift();\n if (found) {\n log('Attempting to send previously queued event');\n\n // We should to update the sent_at timestamp to the current time.\n found[0].sent_at = new Date().toISOString();\n\n void send(found, true).catch(e => {\n log('Failed to retry sending', e);\n });\n }\n }, delay) ;\n\n // We need to unref the timer in node.js, otherwise the node process never exit.\n if (typeof flushTimer !== 'number' && flushTimer.unref) {\n flushTimer.unref();\n }\n }\n\n function flushWithBackOff() {\n if (flushTimer) {\n return;\n }\n\n flushIn(retryDelay);\n\n retryDelay = Math.min(retryDelay * 2, MAX_DELAY);\n }\n\n async function send(envelope, isRetry = false) {\n // We queue all replay envelopes to avoid multiple replay envelopes being sent at the same time. If one fails, we\n // need to retry them in order.\n if (!isRetry && envelopeContainsItemType(envelope, ['replay_event', 'replay_recording'])) {\n await store.push(envelope);\n flushIn(MIN_DELAY);\n return {};\n }\n\n try {\n if (options.shouldSend && (await options.shouldSend(envelope)) === false) {\n throw new Error('Envelope not sent because `shouldSend` callback returned false');\n }\n\n const result = await transport.send(envelope);\n\n let delay = MIN_DELAY;\n\n if (result) {\n // If there's a retry-after header, use that as the next delay.\n if (result.headers?.['retry-after']) {\n delay = parseRetryAfterHeader(result.headers['retry-after']);\n } else if (result.headers?.['x-sentry-rate-limits']) {\n delay = 60000; // 60 seconds\n } // If we have a server error, return now so we don't flush the queue.\n else if ((result.statusCode || 0) >= 400) {\n return result;\n }\n }\n\n flushIn(delay);\n retryDelay = START_DELAY;\n return result;\n } catch (e) {\n if (await shouldQueue(envelope, e , retryDelay)) {\n // If this envelope was a retry, we want to add it to the front of the queue so it's retried again first.\n if (isRetry) {\n await store.unshift(envelope);\n } else {\n await store.push(envelope);\n }\n flushWithBackOff();\n log('Error sending. Event queued.', e );\n return {};\n } else {\n throw e;\n }\n }\n }\n\n if (options.flushAtStartup) {\n flushWithBackOff();\n }\n\n return {\n send,\n flush: timeout => {\n // If there's no timeout, we should attempt to flush the offline queue.\n if (timeout === undefined) {\n retryDelay = START_DELAY;\n flushIn(MIN_DELAY);\n }\n\n return transport.flush(timeout);\n },\n };\n };\n}\n\nexport { MIN_DELAY, START_DELAY, makeOfflineTransport };\n//# sourceMappingURL=offline.js.map\n","import { getEnvelopeEndpointWithUrlEncodedAuth } from '../api.js';\nimport { dsnFromString } from '../utils/dsn.js';\nimport { createEnvelope, forEachEnvelopeItem } from '../utils/envelope.js';\n\n/**\n * Key used in event.extra to provide routing information for the multiplexed transport.\n * Should contain an array of `{ dsn: string, release?: string }` objects.\n */\nconst MULTIPLEXED_TRANSPORT_EXTRA_KEY = 'MULTIPLEXED_TRANSPORT_EXTRA_KEY';\n\n/**\n * Gets an event from an envelope.\n *\n * This is only exported for use in the tests\n */\nfunction eventFromEnvelope(env, types) {\n let event;\n\n forEachEnvelopeItem(env, (item, type) => {\n if (types.includes(type)) {\n event = Array.isArray(item) ? (item )[1] : undefined;\n }\n // bail out if we found an event\n return !!event;\n });\n\n return event;\n}\n\n/**\n * Creates a transport that overrides the release on all events.\n */\nfunction makeOverrideReleaseTransport(\n createTransport,\n release,\n) {\n return options => {\n const transport = createTransport(options);\n\n return {\n ...transport,\n send: async (envelope) => {\n const event = eventFromEnvelope(envelope, ['event', 'transaction', 'profile', 'replay_event']);\n\n if (event) {\n event.release = release;\n }\n return transport.send(envelope);\n },\n };\n };\n}\n\n/** Overrides the DSN in the envelope header */\nfunction overrideDsn(envelope, dsn) {\n return createEnvelope(\n dsn\n ? {\n ...envelope[0],\n dsn,\n }\n : envelope[0],\n envelope[1],\n );\n}\n\n/**\n * Creates a transport that can send events to different DSNs depending on the envelope contents.\n *\n * If no matcher is provided, the transport will look for routing information in\n * `event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY]`, which should contain\n * an array of `{ dsn: string, release?: string }` objects.\n */\nfunction makeMultiplexedTransport(\n createTransport,\n matcher,\n) {\n return options => {\n const fallbackTransport = createTransport(options);\n const otherTransports = new Map();\n\n // Use provided matcher or default to simple multiplexed transport behavior\n const actualMatcher =\n matcher ||\n (args => {\n const event = args.getEvent();\n if (\n event?.extra?.[MULTIPLEXED_TRANSPORT_EXTRA_KEY] &&\n Array.isArray(event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY])\n ) {\n return event.extra[MULTIPLEXED_TRANSPORT_EXTRA_KEY];\n }\n return [];\n });\n\n function getTransport(dsn, release) {\n // We create a transport for every unique dsn/release combination as there may be code from multiple releases in\n // use at the same time\n const key = release ? `${dsn}:${release}` : dsn;\n\n let transport = otherTransports.get(key);\n\n if (!transport) {\n const validatedDsn = dsnFromString(dsn);\n if (!validatedDsn) {\n return undefined;\n }\n const url = getEnvelopeEndpointWithUrlEncodedAuth(validatedDsn, options.tunnel);\n\n transport = release\n ? makeOverrideReleaseTransport(createTransport, release)({ ...options, url })\n : createTransport({ ...options, url });\n\n otherTransports.set(key, transport);\n }\n\n return [dsn, transport];\n }\n\n async function send(envelope) {\n function getEvent(types) {\n const eventTypes = types?.length ? types : ['event'];\n return eventFromEnvelope(envelope, eventTypes);\n }\n\n const transports = actualMatcher({ envelope, getEvent })\n .map(result => {\n if (typeof result === 'string') {\n return getTransport(result, undefined);\n } else {\n return getTransport(result.dsn, result.release);\n }\n })\n .filter((t) => !!t);\n\n // If we have no transports to send to, use the fallback transport\n // Don't override the DSN in the header for the fallback transport. '' is falsy\n const transportsWithFallback = transports.length ? transports : [['', fallbackTransport]];\n\n const results = (await Promise.all(\n transportsWithFallback.map(([dsn, transport]) => transport.send(overrideDsn(envelope, dsn))),\n )) ;\n\n return results[0];\n }\n\n async function flush(timeout) {\n const allTransports = [...otherTransports.values(), fallbackTransport];\n const results = await Promise.all(allTransports.map(transport => transport.flush(timeout)));\n return results.every(r => r);\n }\n\n return {\n send,\n flush,\n };\n };\n}\n\nexport { MULTIPLEXED_TRANSPORT_EXTRA_KEY, eventFromEnvelope, makeMultiplexedTransport };\n//# sourceMappingURL=multiplexed.js.map\n","import { DEBUG_BUILD } from '../../debug-build.js';\nimport { debug } from '../debug-logger.js';\n\n/**\n * Registry tracking which AI provider modules should skip instrumentation wrapping.\n *\n * This prevents duplicate spans when a higher-level integration (like LangChain)\n * already instruments AI providers at a higher abstraction level.\n */\nconst SKIPPED_AI_PROVIDERS = new Set();\n\n/**\n * Mark AI provider modules to skip instrumentation wrapping.\n *\n * This prevents duplicate spans when a higher-level integration (like LangChain)\n * already instruments AI providers at a higher abstraction level.\n *\n * @internal\n * @param modules - Array of npm module names to skip (e.g., '@anthropic-ai/sdk', 'openai')\n *\n * @example\n * ```typescript\n * // In LangChain integration\n * _INTERNAL_skipAiProviderWrapping(['@anthropic-ai/sdk', 'openai', '@google/generative-ai']);\n * ```\n */\nfunction _INTERNAL_skipAiProviderWrapping(modules) {\n modules.forEach(module => {\n SKIPPED_AI_PROVIDERS.add(module);\n DEBUG_BUILD && debug.log(`AI provider \"${module}\" wrapping will be skipped`);\n });\n}\n\n/**\n * Check if an AI provider module should skip instrumentation wrapping.\n *\n * @internal\n * @param module - The npm module name (e.g., '@anthropic-ai/sdk', 'openai')\n * @returns true if wrapping should be skipped\n *\n * @example\n * ```typescript\n * // In AI provider instrumentation\n * if (_INTERNAL_shouldSkipAiProviderWrapping('@anthropic-ai/sdk')) {\n * return Reflect.construct(Original, args); // Don't instrument\n * }\n * ```\n */\nfunction _INTERNAL_shouldSkipAiProviderWrapping(module) {\n return SKIPPED_AI_PROVIDERS.has(module);\n}\n\n/**\n * Clear all AI provider skip registrations.\n *\n * This is automatically called at the start of Sentry.init() to ensure a clean state\n * between different client initializations.\n *\n * @internal\n */\nfunction _INTERNAL_clearAiProviderSkips() {\n SKIPPED_AI_PROVIDERS.clear();\n DEBUG_BUILD && debug.log('Cleared AI provider skip registrations');\n}\n\nexport { _INTERNAL_clearAiProviderSkips, _INTERNAL_shouldSkipAiProviderWrapping, _INTERNAL_skipAiProviderWrapping };\n//# sourceMappingURL=providerSkip.js.map\n","import { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD, SEMANTIC_ATTRIBUTE_URL_FULL, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes.js';\n\n// Curious about `thismessage:/`? See: https://www.rfc-editor.org/rfc/rfc2557.html\n// > When the methods above do not yield an absolute URI, a base URL\n// > of \"thismessage:/\" MUST be employed. This base URL has been\n// > defined for the sole purpose of resolving relative references\n// > within a multipart/related structure when no other base URI is\n// > specified.\n//\n// We need to provide a base URL to `parseStringToURLObject` because the fetch API gives us a\n// relative URL sometimes.\n//\n// This is the only case where we need to provide a base URL to `parseStringToURLObject`\n// because the relative URL is not valid on its own.\nconst DEFAULT_BASE_URL = 'thismessage:/';\n\n/**\n * Checks if the URL object is relative\n *\n * @param url - The URL object to check\n * @returns True if the URL object is relative, false otherwise\n */\nfunction isURLObjectRelative(url) {\n return 'isRelative' in url;\n}\n\n/**\n * Parses string to a URL object\n *\n * @param url - The URL to parse\n * @returns The parsed URL object or undefined if the URL is invalid\n */\nfunction parseStringToURLObject(url, urlBase) {\n const isRelative = url.indexOf('://') <= 0 && url.indexOf('//') !== 0;\n const base = urlBase ?? (isRelative ? DEFAULT_BASE_URL : undefined);\n try {\n // Use `canParse` to short-circuit the URL constructor if it's not a valid URL\n // This is faster than trying to construct the URL and catching the error\n // Node 20+, Chrome 120+, Firefox 115+, Safari 17+\n if ('canParse' in URL && !(URL ).canParse(url, base)) {\n return undefined;\n }\n\n const fullUrlObject = new URL(url, base);\n if (isRelative) {\n // Because we used a fake base URL, we need to return a relative URL object.\n // We cannot return anything about the origin, host, etc. because it will refer to the fake base URL.\n return {\n isRelative,\n pathname: fullUrlObject.pathname,\n search: fullUrlObject.search,\n hash: fullUrlObject.hash,\n };\n }\n return fullUrlObject;\n } catch {\n // empty body\n }\n\n return undefined;\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlStringFromUrlObject(url) {\n if (isURLObjectRelative(url)) {\n return url.pathname;\n }\n\n const newUrl = new URL(url);\n newUrl.search = '';\n newUrl.hash = '';\n if (['80', '443'].includes(newUrl.port)) {\n newUrl.port = '';\n }\n if (newUrl.password) {\n newUrl.password = '%filtered%';\n }\n if (newUrl.username) {\n newUrl.username = '%filtered%';\n }\n\n return newUrl.toString();\n}\n\nfunction getHttpSpanNameFromUrlObject(\n urlObject,\n kind,\n request,\n routeName,\n) {\n const method = request?.method?.toUpperCase() ?? 'GET';\n const route = routeName\n ? routeName\n : urlObject\n ? kind === 'client'\n ? getSanitizedUrlStringFromUrlObject(urlObject)\n : urlObject.pathname\n : '/';\n\n return `${method} ${route}`;\n}\n\n/**\n * Takes a parsed URL object and returns a set of attributes for the span\n * that represents the HTTP request for that url. This is used for both server\n * and client http spans.\n *\n * Follows https://opentelemetry.io/docs/specs/semconv/http/.\n *\n * @param urlObject - see {@link parseStringToURLObject}\n * @param kind - The type of HTTP operation (server or client)\n * @param spanOrigin - The origin of the span\n * @param request - The request object, see {@link PartialRequest}\n * @param routeName - The name of the route, must be low cardinality\n * @returns The span name and attributes for the HTTP operation\n */\nfunction getHttpSpanDetailsFromUrlObject(\n urlObject,\n kind,\n spanOrigin,\n request,\n routeName,\n) {\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'url',\n };\n\n if (routeName) {\n // This is based on https://opentelemetry.io/docs/specs/semconv/http/http-spans/#name\n attributes[kind === 'server' ? 'http.route' : 'url.template'] = routeName;\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n\n if (request?.method) {\n attributes[SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD] = request.method.toUpperCase();\n }\n\n if (urlObject) {\n if (urlObject.search) {\n attributes['url.query'] = urlObject.search;\n }\n if (urlObject.hash) {\n attributes['url.fragment'] = urlObject.hash;\n }\n if (urlObject.pathname) {\n attributes['url.path'] = urlObject.pathname;\n if (urlObject.pathname === '/') {\n attributes[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE] = 'route';\n }\n }\n\n if (!isURLObjectRelative(urlObject)) {\n attributes[SEMANTIC_ATTRIBUTE_URL_FULL] = urlObject.href;\n if (urlObject.port) {\n attributes['url.port'] = urlObject.port;\n }\n if (urlObject.protocol) {\n attributes['url.scheme'] = urlObject.protocol;\n }\n if (urlObject.hostname) {\n attributes[kind === 'server' ? 'server.address' : 'url.domain'] = urlObject.hostname;\n }\n }\n }\n\n return [getHttpSpanNameFromUrlObject(urlObject, kind, request, routeName), attributes];\n}\n\n/**\n * Parses string form of URL into an object\n * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B\n * // intentionally using regex and not <a/> href parsing trick because React Native and other\n * // environments where DOM might not be available\n * @returns parsed URL object\n */\nfunction parseUrl(url) {\n if (!url) {\n return {};\n }\n\n const match = url.match(/^(([^:/?#]+):)?(\\/\\/([^/?#]*))?([^?#]*)(\\?([^#]*))?(#(.*))?$/);\n\n if (!match) {\n return {};\n }\n\n // coerce to undefined values to empty string so we don't get 'undefined'\n const query = match[6] || '';\n const fragment = match[8] || '';\n return {\n host: match[4],\n path: match[5],\n protocol: match[2],\n search: query,\n hash: fragment,\n relative: match[5] + query + fragment, // everything minus origin\n };\n}\n\n/**\n * Strip the query string and fragment off of a given URL or path (if present)\n *\n * @param urlPath Full URL or path, including possible query string and/or fragment\n * @returns URL or path without query string or fragment\n */\nfunction stripUrlQueryAndFragment(urlPath) {\n return (urlPath.split(/[?#]/, 1) )[0];\n}\n\n/**\n * Takes a URL object and returns a sanitized string which is safe to use as span name\n * see: https://develop.sentry.dev/sdk/data-handling/#structuring-data\n */\nfunction getSanitizedUrlString(url) {\n const { protocol, host, path } = url;\n\n const filteredHost =\n host\n // Always filter out authority\n ?.replace(/^.*@/, '[filtered]:[filtered]@')\n // Don't show standard :80 (http) and :443 (https) ports to reduce the noise\n // TODO: Use new URL global if it exists\n .replace(/(:80)$/, '')\n .replace(/(:443)$/, '') || '';\n\n return `${protocol ? `${protocol}://` : ''}${filteredHost}${path}`;\n}\n\nexport { getHttpSpanDetailsFromUrlObject, getSanitizedUrlString, getSanitizedUrlStringFromUrlObject, isURLObjectRelative, parseStringToURLObject, parseUrl, stripUrlQueryAndFragment };\n//# sourceMappingURL=url.js.map\n","import { parseStringToURLObject, isURLObjectRelative } from './url.js';\n\n/**\n * Checks whether given url points to Sentry server\n *\n * @param url url to verify\n */\nfunction isSentryRequestUrl(url, client) {\n const dsn = client?.getDsn();\n const tunnel = client?.getOptions().tunnel;\n return checkDsn(url, dsn) || checkTunnel(url, tunnel);\n}\n\nfunction checkTunnel(url, tunnel) {\n if (!tunnel) {\n return false;\n }\n\n return removeTrailingSlash(url) === removeTrailingSlash(tunnel);\n}\n\nfunction checkDsn(url, dsn) {\n // Requests to Sentry's ingest endpoint must have a `sentry_key` in the query string\n // This is equivalent to the public_key which is required in the DSN\n // see https://develop.sentry.dev/sdk/overview/#parsing-the-dsn\n // Therefore, a request to the same host and with a `sentry_key` in the query string\n // can be considered a request to the ingest endpoint.\n const urlParts = parseStringToURLObject(url);\n if (!urlParts || isURLObjectRelative(urlParts)) {\n return false;\n }\n\n return dsn ? urlParts.host.includes(dsn.host) && /(^|&|\\?)sentry_key=/.test(urlParts.search) : false;\n}\n\nfunction removeTrailingSlash(str) {\n return str[str.length - 1] === '/' ? str.slice(0, -1) : str;\n}\n\nexport { isSentryRequestUrl };\n//# sourceMappingURL=isSentryRequestUrl.js.map\n","/**\n * Tagged template function which returns parameterized representation of the message\n * For example: parameterize`This is a log statement with ${x} and ${y} params`, would return:\n * \"__sentry_template_string__\": 'This is a log statement with %s and %s params',\n * \"__sentry_template_values__\": ['first', 'second']\n *\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n *\n * @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.\n */\nfunction parameterize(strings, ...values) {\n const formatted = new String(String.raw(strings, ...values)) ;\n formatted.__sentry_template_string__ = strings.join('\\x00').replace(/%/g, '%%').replace(/\\0/g, '%s');\n formatted.__sentry_template_values__ = values;\n return formatted;\n}\n\n/**\n * Tagged template function which returns parameterized representation of the message.\n *\n * @param strings An array of string values splitted between expressions\n * @param values Expressions extracted from template string\n * @returns A `ParameterizedString` object that can be passed into `captureMessage` or Sentry.logger.X methods.\n */\nconst fmt = parameterize;\n\nexport { fmt, parameterize };\n//# sourceMappingURL=parameterize.js.map\n","import { getAsyncContextStrategy } from '../asyncContext/index.js';\nimport { getMainCarrier } from '../carrier.js';\nimport { getClient, getCurrentScope } from '../currentScopes.js';\nimport { isEnabled } from '../exports.js';\nimport { debug } from './debug-logger.js';\nimport { getActiveSpan, spanToTraceHeader, spanToTraceparentHeader } from './spanUtils.js';\nimport { getDynamicSamplingContextFromSpan, getDynamicSamplingContextFromScope } from '../tracing/dynamicSamplingContext.js';\nimport { dynamicSamplingContextToSentryBaggageHeader } from './baggage.js';\nimport { TRACEPARENT_REGEXP, generateSentryTraceHeader, generateTraceparentHeader } from './tracing.js';\n\n/**\n * Extracts trace propagation data from the current span or from the client's scope (via transaction or propagation\n * context) and serializes it to `sentry-trace` and `baggage` values. These values can be used to propagate\n * a trace via our tracing Http headers or Html `<meta>` tags.\n *\n * This function also applies some validation to the generated sentry-trace and baggage values to ensure that\n * only valid strings are returned.\n *\n * If (@param options.propagateTraceparent) is `true`, the function will also generate a `traceparent` value,\n * following the W3C traceparent header format.\n *\n * @returns an object with the tracing data values. The object keys are the name of the tracing key to be used as header\n * or meta tag name.\n */\nfunction getTraceData(\n options = {},\n) {\n const client = options.client || getClient();\n if (!isEnabled() || !client) {\n return {};\n }\n\n const carrier = getMainCarrier();\n const acs = getAsyncContextStrategy(carrier);\n if (acs.getTraceData) {\n return acs.getTraceData(options);\n }\n\n const scope = options.scope || getCurrentScope();\n const span = options.span || getActiveSpan();\n const sentryTrace = span ? spanToTraceHeader(span) : scopeToTraceHeader(scope);\n const dsc = span ? getDynamicSamplingContextFromSpan(span) : getDynamicSamplingContextFromScope(client, scope);\n const baggage = dynamicSamplingContextToSentryBaggageHeader(dsc);\n\n const isValidSentryTraceHeader = TRACEPARENT_REGEXP.test(sentryTrace);\n if (!isValidSentryTraceHeader) {\n debug.warn('Invalid sentry-trace data. Cannot generate trace data');\n return {};\n }\n\n const traceData = {\n 'sentry-trace': sentryTrace,\n baggage,\n };\n\n if (options.propagateTraceparent) {\n traceData.traceparent = span ? spanToTraceparentHeader(span) : scopeToTraceparentHeader(scope);\n }\n\n return traceData;\n}\n\n/**\n * Get a sentry-trace header value for the given scope.\n */\nfunction scopeToTraceHeader(scope) {\n const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n return generateSentryTraceHeader(traceId, propagationSpanId, sampled);\n}\n\nfunction scopeToTraceparentHeader(scope) {\n const { traceId, sampled, propagationSpanId } = scope.getPropagationContext();\n return generateTraceparentHeader(traceId, propagationSpanId, sampled);\n}\n\nexport { getTraceData };\n//# sourceMappingURL=traceData.js.map\n","/**\n * Transforms a `Headers` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into a simple key-value dict.\n * The header keys will be lower case: e.g. A \"Content-Type\" header will be stored as \"content-type\".\n */\nfunction winterCGHeadersToDict(winterCGHeaders) {\n const headers = {};\n try {\n winterCGHeaders.forEach((value, key) => {\n if (typeof value === 'string') {\n // We check that value is a string even though it might be redundant to make sure prototype pollution is not possible.\n headers[key] = value;\n }\n });\n } catch {\n // just return the empty headers\n }\n\n return headers;\n}\n\n/**\n * Convert common request headers to a simple dictionary.\n */\nfunction headersToDict(reqHeaders) {\n const headers = Object.create(null);\n\n try {\n Object.entries(reqHeaders).forEach(([key, value]) => {\n if (typeof value === 'string') {\n headers[key] = value;\n }\n });\n } catch {\n // just return the empty headers\n }\n\n return headers;\n}\n\n/**\n * Converts a `Request` object that implements the `Web Fetch API` (https://developer.mozilla.org/en-US/docs/Web/API/Headers) into the format that the `RequestData` integration understands.\n */\nfunction winterCGRequestToRequestData(req) {\n const headers = winterCGHeadersToDict(req.headers);\n\n return {\n method: req.method,\n url: req.url,\n query_string: extractQueryParamsFromUrl(req.url),\n headers,\n // TODO: Can we extract body data from the request?\n };\n}\n\n/**\n * Convert a HTTP request object to RequestEventData to be passed as normalizedRequest.\n * Instead of allowing `PolymorphicRequest` to be passed,\n * we want to be more specific and generally require a http.IncomingMessage-like object.\n */\nfunction httpRequestToRequestData(request\n\n) {\n const headers = request.headers || {};\n\n // Check for x-forwarded-host first, then fall back to host header\n const forwardedHost = typeof headers['x-forwarded-host'] === 'string' ? headers['x-forwarded-host'] : undefined;\n const host = forwardedHost || (typeof headers.host === 'string' ? headers.host : undefined);\n\n // Check for x-forwarded-proto first, then fall back to existing protocol detection\n const forwardedProto = typeof headers['x-forwarded-proto'] === 'string' ? headers['x-forwarded-proto'] : undefined;\n const protocol = forwardedProto || request.protocol || (request.socket?.encrypted ? 'https' : 'http');\n\n const url = request.url || '';\n\n const absoluteUrl = getAbsoluteUrl({\n url,\n host,\n protocol,\n });\n\n // This is non-standard, but may be sometimes set\n // It may be overwritten later by our own body handling\n const data = (request ).body || undefined;\n\n // This is non-standard, but may be set on e.g. Next.js or Express requests\n const cookies = (request ).cookies;\n\n return {\n url: absoluteUrl,\n method: request.method,\n query_string: extractQueryParamsFromUrl(url),\n headers: headersToDict(headers),\n cookies,\n data,\n };\n}\n\nfunction getAbsoluteUrl({\n url,\n protocol,\n host,\n}\n\n) {\n if (url?.startsWith('http')) {\n return url;\n }\n\n if (url && host) {\n return `${protocol}://${host}${url}`;\n }\n\n return undefined;\n}\n\nconst SENSITIVE_HEADER_SNIPPETS = [\n 'auth',\n 'token',\n 'secret',\n 'session', // for the user_session cookie\n 'password',\n 'passwd',\n 'pwd',\n 'key',\n 'jwt',\n 'bearer',\n 'sso',\n 'saml',\n 'csrf',\n 'xsrf',\n 'credentials',\n // Always treat cookie headers as sensitive in case individual key-value cookie pairs cannot properly be extracted\n 'set-cookie',\n 'cookie',\n];\n\nconst PII_HEADER_SNIPPETS = ['x-forwarded-', '-user'];\n\n/**\n * Converts incoming HTTP request headers to OpenTelemetry span attributes following semantic conventions.\n * Header names are converted to the format: http.request.header.<key>\n * where <key> is the header name in lowercase with dashes converted to underscores.\n *\n * @see https://opentelemetry.io/docs/specs/semconv/registry/attributes/http/#http-request-header\n */\nfunction httpHeadersToSpanAttributes(\n headers,\n sendDefaultPii = false,\n) {\n const spanAttributes = {};\n\n try {\n Object.entries(headers).forEach(([key, value]) => {\n if (value == null) {\n return;\n }\n\n const lowerCasedHeaderKey = key.toLowerCase();\n const isCookieHeader = lowerCasedHeaderKey === 'cookie' || lowerCasedHeaderKey === 'set-cookie';\n\n if (isCookieHeader && typeof value === 'string' && value !== '') {\n // Set-Cookie: single cookie with attributes (\"name=value; HttpOnly; Secure\")\n // Cookie: multiple cookies separated by \"; \" (\"cookie1=value1; cookie2=value2\")\n const isSetCookie = lowerCasedHeaderKey === 'set-cookie';\n const semicolonIndex = value.indexOf(';');\n const cookieString = isSetCookie && semicolonIndex !== -1 ? value.substring(0, semicolonIndex) : value;\n const cookies = isSetCookie ? [cookieString] : cookieString.split('; ');\n\n for (const cookie of cookies) {\n // Split only at the first '=' to preserve '=' characters in cookie values\n const equalSignIndex = cookie.indexOf('=');\n const cookieKey = equalSignIndex !== -1 ? cookie.substring(0, equalSignIndex) : cookie;\n const cookieValue = equalSignIndex !== -1 ? cookie.substring(equalSignIndex + 1) : '';\n\n const lowerCasedCookieKey = cookieKey.toLowerCase();\n\n addSpanAttribute(spanAttributes, lowerCasedHeaderKey, lowerCasedCookieKey, cookieValue, sendDefaultPii);\n }\n } else {\n addSpanAttribute(spanAttributes, lowerCasedHeaderKey, '', value, sendDefaultPii);\n }\n });\n } catch {\n // Return empty object if there's an error\n }\n\n return spanAttributes;\n}\n\nfunction normalizeAttributeKey(key) {\n return key.replace(/-/g, '_');\n}\n\nfunction addSpanAttribute(\n spanAttributes,\n headerKey,\n cookieKey,\n value,\n sendPii,\n) {\n const normalizedKey = cookieKey\n ? `http.request.header.${normalizeAttributeKey(headerKey)}.${normalizeAttributeKey(cookieKey)}`\n : `http.request.header.${normalizeAttributeKey(headerKey)}`;\n\n const headerValue = handleHttpHeader(cookieKey || headerKey, value, sendPii);\n if (headerValue !== undefined) {\n spanAttributes[normalizedKey] = headerValue;\n }\n}\n\nfunction handleHttpHeader(\n lowerCasedKey,\n value,\n sendPii,\n) {\n const isSensitive = sendPii\n ? SENSITIVE_HEADER_SNIPPETS.some(snippet => lowerCasedKey.includes(snippet))\n : [...PII_HEADER_SNIPPETS, ...SENSITIVE_HEADER_SNIPPETS].some(snippet => lowerCasedKey.includes(snippet));\n\n if (isSensitive) {\n return '[Filtered]';\n } else if (Array.isArray(value)) {\n return value.map(v => (v != null ? String(v) : v)).join(';');\n } else if (typeof value === 'string') {\n return value;\n }\n\n return undefined;\n}\n\n/** Extract the query params from an URL. */\nfunction extractQueryParamsFromUrl(url) {\n // url is path and query string\n if (!url) {\n return;\n }\n\n try {\n // The `URL` constructor can't handle internal URLs of the form `/some/path/here`, so stick a dummy protocol and\n // hostname as the base. Since the point here is just to grab the query string, it doesn't matter what we use.\n const queryParams = new URL(url, 'http://s.io').search.slice(1);\n return queryParams.length ? queryParams : undefined;\n } catch {\n return undefined;\n }\n}\n\nexport { extractQueryParamsFromUrl, headersToDict, httpHeadersToSpanAttributes, httpRequestToRequestData, winterCGHeadersToDict, winterCGRequestToRequestData };\n//# sourceMappingURL=request.js.map\n","import { getClient, getIsolationScope } from './currentScopes.js';\nimport { consoleSandbox } from './utils/debug-logger.js';\nimport { dateTimestampInSeconds } from './utils/time.js';\n\n/**\n * Default maximum number of breadcrumbs added to an event. Can be overwritten\n * with {@link Options.maxBreadcrumbs}.\n */\nconst DEFAULT_BREADCRUMBS = 100;\n\n/**\n * Records a new breadcrumb which will be attached to future events.\n *\n * Breadcrumbs will be added to subsequent events to provide more context on\n * user's actions prior to an error or crash.\n */\nfunction addBreadcrumb(breadcrumb, hint) {\n const client = getClient();\n const isolationScope = getIsolationScope();\n\n if (!client) return;\n\n const { beforeBreadcrumb = null, maxBreadcrumbs = DEFAULT_BREADCRUMBS } = client.getOptions();\n\n if (maxBreadcrumbs <= 0) return;\n\n const timestamp = dateTimestampInSeconds();\n const mergedBreadcrumb = { timestamp, ...breadcrumb };\n const finalBreadcrumb = beforeBreadcrumb\n ? consoleSandbox(() => beforeBreadcrumb(mergedBreadcrumb, hint))\n : mergedBreadcrumb;\n\n if (finalBreadcrumb === null) return;\n\n if (client.emit) {\n client.emit('beforeAddBreadcrumb', finalBreadcrumb, hint);\n }\n\n isolationScope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs);\n}\n\nexport { addBreadcrumb };\n//# sourceMappingURL=breadcrumbs.js.map\n","import { getClient } from '../currentScopes.js';\nimport { defineIntegration } from '../integration.js';\nimport { getOriginalFunction } from '../utils/object.js';\n\nlet originalFunctionToString;\n\nconst INTEGRATION_NAME = 'FunctionToString';\n\nconst SETUP_CLIENTS = new WeakMap();\n\nconst _functionToStringIntegration = (() => {\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n originalFunctionToString = Function.prototype.toString;\n\n // intrinsics (like Function.prototype) might be immutable in some environments\n // e.g. Node with --frozen-intrinsics, XS (an embedded JavaScript engine) or SES (a JavaScript proposal)\n try {\n Function.prototype.toString = function ( ...args) {\n const originalFunction = getOriginalFunction(this);\n const context =\n SETUP_CLIENTS.has(getClient() ) && originalFunction !== undefined ? originalFunction : this;\n return originalFunctionToString.apply(context, args);\n };\n } catch {\n // ignore errors here, just don't patch this\n }\n },\n setup(client) {\n SETUP_CLIENTS.set(client, true);\n },\n };\n}) ;\n\n/**\n * Patch toString calls to return proper name for wrapped functions.\n *\n * ```js\n * Sentry.init({\n * integrations: [\n * functionToStringIntegration(),\n * ],\n * });\n * ```\n */\nconst functionToStringIntegration = defineIntegration(_functionToStringIntegration);\n\nexport { functionToStringIntegration };\n//# sourceMappingURL=functiontostring.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getPossibleEventMessages } from '../utils/eventUtils.js';\nimport { getEventDescription } from '../utils/misc.js';\nimport { stringMatchesSomePattern } from '../utils/string.js';\n\n// \"Script error.\" is hard coded into browsers for errors that it can't read.\n// this is the result of a script being pulled in from an external domain and CORS.\nconst DEFAULT_IGNORE_ERRORS = [\n /^Script error\\.?$/,\n /^Javascript error: Script error\\.? on line 0$/,\n /^ResizeObserver loop completed with undelivered notifications.$/, // The browser logs this when a ResizeObserver handler takes a bit longer. Usually this is not an actual issue though. It indicates slowness.\n /^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker\n /^Can't find variable: gmo$/, // Error from Google Search App https://issuetracker.google.com/issues/396043331\n /^undefined is not an object \\(evaluating 'a\\.[A-Z]'\\)$/, // Random error that happens but not actionable or noticeable to end-users.\n 'can\\'t redefine non-configurable property \"solana\"', // Probably a browser extension or custom browser (Brave) throwing this error\n \"vv().getRestrictions is not a function. (In 'vv().getRestrictions(1,a)', 'vv().getRestrictions' is undefined)\", // Error thrown by GTM, seemingly not affecting end-users\n \"Can't find variable: _AutofillCallbackHandler\", // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/\n /^Non-Error promise rejection captured with value: Object Not Found Matching Id:\\d+, MethodName:simulateEvent, ParamCount:\\d+$/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps\n /^Java exception was raised during method invocation$/, // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065)\n];\n\n/** Options for the EventFilters integration */\n\nconst INTEGRATION_NAME = 'EventFilters';\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n */\nconst eventFiltersIntegration = defineIntegration((options = {}) => {\n let mergedOptions;\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n },\n processEvent(event, _hint, client) {\n if (!mergedOptions) {\n const clientOptions = client.getOptions();\n mergedOptions = _mergeOptions(options, clientOptions);\n }\n return _shouldDropEvent(event, mergedOptions) ? null : event;\n },\n };\n});\n\n/**\n * An integration that filters out events (errors and transactions) based on:\n *\n * - (Errors) A curated list of known low-value or irrelevant errors (see {@link DEFAULT_IGNORE_ERRORS})\n * - (Errors) A list of error messages or urls/filenames passed in via\n * - Top level Sentry.init options (`ignoreErrors`, `denyUrls`, `allowUrls`)\n * - The same options passed to the integration directly via @param options\n * - (Transactions/Spans) A list of root span (transaction) names passed in via\n * - Top level Sentry.init option (`ignoreTransactions`)\n * - The same option passed to the integration directly via @param options\n *\n * Events filtered by this integration will not be sent to Sentry.\n *\n * @deprecated this integration was renamed and will be removed in a future major version.\n * Use `eventFiltersIntegration` instead.\n */\nconst inboundFiltersIntegration = defineIntegration(((options = {}) => {\n return {\n ...eventFiltersIntegration(options),\n name: 'InboundFilters',\n };\n}) );\n\nfunction _mergeOptions(\n internalOptions = {},\n clientOptions = {},\n) {\n return {\n allowUrls: [...(internalOptions.allowUrls || []), ...(clientOptions.allowUrls || [])],\n denyUrls: [...(internalOptions.denyUrls || []), ...(clientOptions.denyUrls || [])],\n ignoreErrors: [\n ...(internalOptions.ignoreErrors || []),\n ...(clientOptions.ignoreErrors || []),\n ...(internalOptions.disableErrorDefaults ? [] : DEFAULT_IGNORE_ERRORS),\n ],\n ignoreTransactions: [...(internalOptions.ignoreTransactions || []), ...(clientOptions.ignoreTransactions || [])],\n };\n}\n\nfunction _shouldDropEvent(event, options) {\n if (!event.type) {\n // Filter errors\n if (_isIgnoredError(event, options.ignoreErrors)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreErrors\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n if (_isUselessError(event)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to not having an error message, error type or stacktrace.\\nEvent: ${getEventDescription(\n event,\n )}`,\n );\n return true;\n }\n if (_isDeniedUrl(event, options.denyUrls)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`denyUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n if (!_isAllowedUrl(event, options.allowUrls)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to not being matched by \\`allowUrls\\` option.\\nEvent: ${getEventDescription(\n event,\n )}.\\nUrl: ${_getEventFilterUrl(event)}`,\n );\n return true;\n }\n } else if (event.type === 'transaction') {\n // Filter transactions\n\n if (_isIgnoredTransaction(event, options.ignoreTransactions)) {\n DEBUG_BUILD &&\n debug.warn(\n `Event dropped due to being matched by \\`ignoreTransactions\\` option.\\nEvent: ${getEventDescription(event)}`,\n );\n return true;\n }\n }\n return false;\n}\n\nfunction _isIgnoredError(event, ignoreErrors) {\n if (!ignoreErrors?.length) {\n return false;\n }\n\n return getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event, ignoreTransactions) {\n if (!ignoreTransactions?.length) {\n return false;\n }\n\n const name = event.transaction;\n return name ? stringMatchesSomePattern(name, ignoreTransactions) : false;\n}\n\nfunction _isDeniedUrl(event, denyUrls) {\n if (!denyUrls?.length) {\n return false;\n }\n const url = _getEventFilterUrl(event);\n return !url ? false : stringMatchesSomePattern(url, denyUrls);\n}\n\nfunction _isAllowedUrl(event, allowUrls) {\n if (!allowUrls?.length) {\n return true;\n }\n const url = _getEventFilterUrl(event);\n return !url ? true : stringMatchesSomePattern(url, allowUrls);\n}\n\nfunction _getLastValidUrl(frames = []) {\n for (let i = frames.length - 1; i >= 0; i--) {\n const frame = frames[i];\n\n if (frame && frame.filename !== '<anonymous>' && frame.filename !== '[native code]') {\n return frame.filename || null;\n }\n }\n\n return null;\n}\n\nfunction _getEventFilterUrl(event) {\n try {\n // If there are linked exceptions or exception aggregates we only want to match against the top frame of the \"root\" (the main exception)\n // The root always comes last in linked exceptions\n const rootException = [...(event.exception?.values ?? [])]\n .reverse()\n .find(value => value.mechanism?.parent_id === undefined && value.stacktrace?.frames?.length);\n const frames = rootException?.stacktrace?.frames;\n return frames ? _getLastValidUrl(frames) : null;\n } catch {\n DEBUG_BUILD && debug.error(`Cannot extract url for event ${getEventDescription(event)}`);\n return null;\n }\n}\n\nfunction _isUselessError(event) {\n // We only want to consider events for dropping that actually have recorded exception values.\n if (!event.exception?.values?.length) {\n return false;\n }\n\n return (\n // No top-level message\n !event.message &&\n // There are no exception values that have a stacktrace, a non-generic-Error type or value\n !event.exception.values.some(value => value.stacktrace || (value.type && value.type !== 'Error') || value.value)\n );\n}\n\nexport { eventFiltersIntegration, inboundFiltersIntegration };\n//# sourceMappingURL=eventFilters.js.map\n","import { isInstanceOf } from './is.js';\n\n/**\n * Creates exceptions inside `event.exception.values` for errors that are nested on properties based on the `key` parameter.\n */\nfunction applyAggregateErrorsToEvent(\n exceptionFromErrorImplementation,\n parser,\n key,\n limit,\n event,\n hint,\n) {\n if (!event.exception?.values || !hint || !isInstanceOf(hint.originalException, Error)) {\n return;\n }\n\n // Generally speaking the last item in `event.exception.values` is the exception originating from the original Error\n const originalException =\n event.exception.values.length > 0 ? event.exception.values[event.exception.values.length - 1] : undefined;\n\n // We only create exception grouping if there is an exception in the event.\n if (originalException) {\n event.exception.values = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n hint.originalException ,\n key,\n event.exception.values,\n originalException,\n 0,\n );\n }\n}\n\nfunction aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error,\n key,\n prevExceptions,\n exception,\n exceptionId,\n) {\n if (prevExceptions.length >= limit + 1) {\n return prevExceptions;\n }\n\n let newExceptions = [...prevExceptions];\n\n // Recursively call this function in order to walk down a chain of errors\n if (isInstanceOf(error[key], Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, error[key] );\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, key, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n error[key] ,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n\n // This will create exception grouping for AggregateErrors\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/AggregateError\n if (Array.isArray(error.errors)) {\n error.errors.forEach((childError, i) => {\n if (isInstanceOf(childError, Error)) {\n applyExceptionGroupFieldsForParentException(exception, exceptionId);\n const newException = exceptionFromErrorImplementation(parser, childError );\n const newExceptionId = newExceptions.length;\n applyExceptionGroupFieldsForChildException(newException, `errors[${i}]`, newExceptionId, exceptionId);\n newExceptions = aggregateExceptionsFromError(\n exceptionFromErrorImplementation,\n parser,\n limit,\n childError ,\n key,\n [newException, ...newExceptions],\n newException,\n newExceptionId,\n );\n }\n });\n }\n\n return newExceptions;\n}\n\nfunction applyExceptionGroupFieldsForParentException(exception, exceptionId) {\n exception.mechanism = {\n handled: true,\n type: 'auto.core.linked_errors',\n ...exception.mechanism,\n ...(exception.type === 'AggregateError' && { is_exception_group: true }),\n exception_id: exceptionId,\n };\n}\n\nfunction applyExceptionGroupFieldsForChildException(\n exception,\n source,\n exceptionId,\n parentId,\n) {\n exception.mechanism = {\n handled: true,\n ...exception.mechanism,\n type: 'chained',\n source,\n exception_id: exceptionId,\n parent_id: parentId,\n };\n}\n\nexport { applyAggregateErrorsToEvent };\n//# sourceMappingURL=aggregate-errors.js.map\n","import { defineIntegration } from '../integration.js';\nimport { applyAggregateErrorsToEvent } from '../utils/aggregate-errors.js';\nimport { exceptionFromError } from '../utils/eventbuilder.js';\n\nconst DEFAULT_KEY = 'cause';\nconst DEFAULT_LIMIT = 5;\n\nconst INTEGRATION_NAME = 'LinkedErrors';\n\nconst _linkedErrorsIntegration = ((options = {}) => {\n const limit = options.limit || DEFAULT_LIMIT;\n const key = options.key || DEFAULT_KEY;\n\n return {\n name: INTEGRATION_NAME,\n preprocessEvent(event, hint, client) {\n const options = client.getOptions();\n\n applyAggregateErrorsToEvent(exceptionFromError, options.stackParser, key, limit, event, hint);\n },\n };\n}) ;\n\nconst linkedErrorsIntegration = defineIntegration(_linkedErrorsIntegration);\n\nexport { linkedErrorsIntegration };\n//# sourceMappingURL=linkederrors.js.map\n","import { GLOBAL_OBJ } from './utils/worldwide.js';\n\n/** Keys are source filename/url, values are metadata objects. */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst filenameMetadataMap = new Map();\n/** Set of stack strings that have already been parsed. */\nconst parsedStacks = new Set();\n\nfunction ensureMetadataStacksAreParsed(parser) {\n if (!GLOBAL_OBJ._sentryModuleMetadata) {\n return;\n }\n\n for (const stack of Object.keys(GLOBAL_OBJ._sentryModuleMetadata)) {\n const metadata = GLOBAL_OBJ._sentryModuleMetadata[stack];\n\n if (parsedStacks.has(stack)) {\n continue;\n }\n\n // Ensure this stack doesn't get parsed again\n parsedStacks.add(stack);\n\n const frames = parser(stack);\n\n // Go through the frames starting from the top of the stack and find the first one with a filename\n for (const frame of frames.reverse()) {\n if (frame.filename) {\n // Save the metadata for this filename\n filenameMetadataMap.set(frame.filename, metadata);\n break;\n }\n }\n }\n}\n\n/**\n * Retrieve metadata for a specific JavaScript file URL.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getMetadataForUrl(parser, filename) {\n ensureMetadataStacksAreParsed(parser);\n return filenameMetadataMap.get(filename);\n}\n\n/**\n * Adds metadata to stack frames.\n *\n * Metadata is injected by the Sentry bundler plugins using the `_experiments.moduleMetadata` config option.\n */\nfunction addMetadataToStackFrames(parser, event) {\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n if (!frame.filename || frame.module_metadata) {\n return;\n }\n\n const metadata = getMetadataForUrl(parser, frame.filename);\n\n if (metadata) {\n frame.module_metadata = metadata;\n }\n });\n });\n}\n\n/**\n * Strips metadata from stack frames.\n */\nfunction stripMetadataFromStackFrames(event) {\n event.exception?.values?.forEach(exception => {\n exception.stacktrace?.frames?.forEach(frame => {\n delete frame.module_metadata;\n });\n });\n}\n\nexport { addMetadataToStackFrames, getMetadataForUrl, stripMetadataFromStackFrames };\n//# sourceMappingURL=metadata.js.map\n","import { defineIntegration } from '../integration.js';\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata.js';\nimport { forEachEnvelopeItem } from '../utils/envelope.js';\n\n/**\n * Adds module metadata to stack frames.\n *\n * Metadata can be injected by the Sentry bundler plugins using the `moduleMetadata` config option.\n *\n * When this integration is added, the metadata passed to the bundler plugin is added to the stack frames of all events\n * under the `module_metadata` property. This can be used to help in tagging or routing of events from different teams\n * our sources\n */\nconst moduleMetadataIntegration = defineIntegration(() => {\n return {\n name: 'ModuleMetadata',\n setup(client) {\n // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n client.on('beforeEnvelope', envelope => {\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type === 'event') {\n const event = Array.isArray(item) ? (item )[1] : undefined;\n\n if (event) {\n stripMetadataFromStackFrames(event);\n item[1] = event;\n }\n }\n });\n });\n\n client.on('applyFrameMetadata', event => {\n // Only apply stack frame metadata to error events\n if (event.type) {\n return;\n }\n\n const stackParser = client.getOptions().stackParser;\n addMetadataToStackFrames(stackParser, event);\n });\n },\n };\n});\n\nexport { moduleMetadataIntegration };\n//# sourceMappingURL=moduleMetadata.js.map\n","// Vendored / modified from @sergiodxa/remix-utils\n\n// https://github.com/sergiodxa/remix-utils/blob/02af80e12829a53696bfa8f3c2363975cf59f55e/src/server/get-client-ip-address.ts\n// MIT License\n\n// Copyright (c) 2021 Sergio Xalambrí\n\n// Permission is hereby granted, free of charge, to any person obtaining a copy\n// of this software and associated documentation files (the \"Software\"), to deal\n// in the Software without restriction, including without limitation the rights\n// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n// copies of the Software, and to permit persons to whom the Software is\n// furnished to do so, subject to the following conditions:\n\n// The above copyright notice and this permission notice shall be included in all\n// copies or substantial portions of the Software.\n\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n// SOFTWARE.\n\n// The headers to check, in priority order\nconst ipHeaderNames = [\n 'X-Client-IP',\n 'X-Forwarded-For',\n 'Fly-Client-IP',\n 'CF-Connecting-IP',\n 'Fastly-Client-Ip',\n 'True-Client-Ip',\n 'X-Real-IP',\n 'X-Cluster-Client-IP',\n 'X-Forwarded',\n 'Forwarded-For',\n 'Forwarded',\n 'X-Vercel-Forwarded-For',\n];\n\n/**\n * Get the IP address of the client sending a request.\n *\n * It receives a Request headers object and use it to get the\n * IP address from one of the following headers in order.\n *\n * If the IP address is valid, it will be returned. Otherwise, null will be\n * returned.\n *\n * If the header values contains more than one IP address, the first valid one\n * will be returned.\n */\nfunction getClientIPAddress(headers) {\n // This will end up being Array<string | string[] | undefined | null> because of the various possible values a header\n // can take\n const headerValues = ipHeaderNames.map((headerName) => {\n const rawValue = headers[headerName];\n const value = Array.isArray(rawValue) ? rawValue.join(';') : rawValue;\n\n if (headerName === 'Forwarded') {\n return parseForwardedHeader(value);\n }\n\n return value?.split(',').map((v) => v.trim());\n });\n\n // Flatten the array and filter out any falsy entries\n const flattenedHeaderValues = headerValues.reduce((acc, val) => {\n if (!val) {\n return acc;\n }\n\n return acc.concat(val);\n }, []);\n\n // Find the first value which is a valid IP address, if any\n const ipAddress = flattenedHeaderValues.find(ip => ip !== null && isIP(ip));\n\n return ipAddress || null;\n}\n\nfunction parseForwardedHeader(value) {\n if (!value) {\n return null;\n }\n\n for (const part of value.split(';')) {\n if (part.startsWith('for=')) {\n return part.slice(4);\n }\n }\n\n return null;\n}\n\n//\n/**\n * Custom method instead of importing this from `net` package, as this only exists in node\n * Accepts:\n * 127.0.0.1\n * 192.168.1.1\n * 192.168.1.255\n * 255.255.255.255\n * 10.1.1.1\n * 0.0.0.0\n * 2b01:cb19:8350:ed00:d0dd:fa5b:de31:8be5\n *\n * Rejects:\n * 1.1.1.01\n * 30.168.1.255.1\n * 127.1\n * 192.168.1.256\n * -1.2.3.4\n * 1.1.1.1.\n * 3...3\n * 192.168.1.099\n */\nfunction isIP(str) {\n const regex =\n /(?:^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$)|(?:^(?:(?:[a-fA-F\\d]{1,4}:){7}(?:[a-fA-F\\d]{1,4}|:)|(?:[a-fA-F\\d]{1,4}:){6}(?:(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}|:[a-fA-F\\d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$)/;\n return regex.test(str);\n}\n\nexport { getClientIPAddress, ipHeaderNames };\n//# sourceMappingURL=getIpAddress.js.map\n","import { defineIntegration } from '../integration.js';\nimport { parseCookie } from '../utils/cookie.js';\nimport { getClientIPAddress, ipHeaderNames } from '../vendor/getIpAddress.js';\n\n// TODO(v11): Change defaults based on `sendDefaultPii`\nconst DEFAULT_INCLUDE = {\n cookies: true,\n data: true,\n headers: true,\n query_string: true,\n url: true,\n};\n\nconst INTEGRATION_NAME = 'RequestData';\n\nconst _requestDataIntegration = ((options = {}) => {\n const include = {\n ...DEFAULT_INCLUDE,\n ...options.include,\n };\n\n return {\n name: INTEGRATION_NAME,\n processEvent(event, _hint, client) {\n const { sdkProcessingMetadata = {} } = event;\n const { normalizedRequest, ipAddress } = sdkProcessingMetadata;\n\n const includeWithDefaultPiiApplied = {\n ...include,\n ip: include.ip ?? client.getOptions().sendDefaultPii,\n };\n\n if (normalizedRequest) {\n addNormalizedRequestDataToEvent(event, normalizedRequest, { ipAddress }, includeWithDefaultPiiApplied);\n }\n\n return event;\n },\n };\n}) ;\n\n/**\n * Add data about a request to an event. Primarily for use in Node-based SDKs, but included in `@sentry/core`\n * so it can be used in cross-platform SDKs like `@sentry/nextjs`.\n */\nconst requestDataIntegration = defineIntegration(_requestDataIntegration);\n\n/**\n * Add already normalized request data to an event.\n * This mutates the passed in event.\n */\nfunction addNormalizedRequestDataToEvent(\n event,\n req,\n // Data that should not go into `event.request` but is somehow related to requests\n additionalData,\n include,\n) {\n event.request = {\n ...event.request,\n ...extractNormalizedRequestData(req, include),\n };\n\n if (include.ip) {\n const ip = (req.headers && getClientIPAddress(req.headers)) || additionalData.ipAddress;\n if (ip) {\n event.user = {\n ...event.user,\n ip_address: ip,\n };\n }\n }\n}\n\nfunction extractNormalizedRequestData(\n normalizedRequest,\n include,\n) {\n const requestData = {};\n const headers = { ...normalizedRequest.headers };\n\n if (include.headers) {\n requestData.headers = headers;\n\n // Remove the Cookie header in case cookie data should not be included in the event\n if (!include.cookies) {\n delete (headers ).cookie;\n }\n\n // Remove IP headers in case IP data should not be included in the event\n if (!include.ip) {\n ipHeaderNames.forEach(ipHeaderName => {\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete (headers )[ipHeaderName];\n });\n }\n }\n\n requestData.method = normalizedRequest.method;\n\n if (include.url) {\n requestData.url = normalizedRequest.url;\n }\n\n if (include.cookies) {\n const cookies = normalizedRequest.cookies || (headers?.cookie ? parseCookie(headers.cookie) : undefined);\n requestData.cookies = cookies || {};\n }\n\n if (include.query_string) {\n requestData.query_string = normalizedRequest.query_string;\n }\n\n if (include.data) {\n requestData.data = normalizedRequest.data;\n }\n\n return requestData;\n}\n\nexport { requestDataIntegration };\n//# sourceMappingURL=requestdata.js.map\n","/**\n * This code was originally copied from the 'cookie` module at v0.5.0 and was simplified for our use case.\n * https://github.com/jshttp/cookie/blob/a0c84147aab6266bdb3996cf4062e93907c0b0fc/index.js\n * It had the following license:\n *\n * (The MIT License)\n *\n * Copyright (c) 2012-2014 Roman Shtylman <shtylman@gmail.com>\n * Copyright (c) 2015 Douglas Christopher Wilson <doug@somethingdoug.com>\n *\n * Permission is hereby granted, free of charge, to any person obtaining\n * a copy of this software and associated documentation files (the\n * 'Software'), to deal in the Software without restriction, including\n * without limitation the rights to use, copy, modify, merge, publish,\n * distribute, sublicense, and/or sell copies of the Software, and to\n * permit persons to whom the Software is furnished to do so, subject to\n * the following conditions:\n *\n * The above copyright notice and this permission notice shall be\n * included in all copies or substantial portions of the Software.\n *\n * THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,\n * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.\n * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\n * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n */\n\n/**\n * Parses a cookie string\n */\nfunction parseCookie(str) {\n const obj = {};\n let index = 0;\n\n while (index < str.length) {\n const eqIdx = str.indexOf('=', index);\n\n // no more cookie pairs\n if (eqIdx === -1) {\n break;\n }\n\n let endIdx = str.indexOf(';', index);\n\n if (endIdx === -1) {\n endIdx = str.length;\n } else if (endIdx < eqIdx) {\n // backtrack on prior semicolon\n index = str.lastIndexOf(';', eqIdx - 1) + 1;\n continue;\n }\n\n const key = str.slice(index, eqIdx).trim();\n\n // only assign once\n if (undefined === obj[key]) {\n let val = str.slice(eqIdx + 1, endIdx).trim();\n\n // quoted values\n if (val.charCodeAt(0) === 0x22) {\n val = val.slice(1, -1);\n }\n\n try {\n obj[key] = val.indexOf('%') !== -1 ? decodeURIComponent(val) : val;\n } catch {\n obj[key] = val;\n }\n }\n\n index = endIdx + 1;\n }\n\n return obj;\n}\n\nexport { parseCookie };\n//# sourceMappingURL=cookie.js.map\n","import { CONSOLE_LEVELS, originalConsoleMethods } from '../utils/debug-logger.js';\nimport { fill } from '../utils/object.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a console.xxx method is called.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addConsoleInstrumentationHandler(handler) {\n const type = 'console';\n addHandler(type, handler);\n maybeInstrument(type, instrumentConsole);\n}\n\nfunction instrumentConsole() {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n CONSOLE_LEVELS.forEach(function (level) {\n if (!(level in GLOBAL_OBJ.console)) {\n return;\n }\n\n fill(GLOBAL_OBJ.console, level, function (originalConsoleMethod) {\n originalConsoleMethods[level] = originalConsoleMethod;\n\n return function (...args) {\n const handlerData = { args, level };\n triggerHandlers('console', handlerData);\n\n const log = originalConsoleMethods[level];\n log?.apply(GLOBAL_OBJ.console, args);\n };\n });\n });\n}\n\nexport { addConsoleInstrumentationHandler };\n//# sourceMappingURL=console.js.map\n","/**\n * Converts a string-based level into a `SeverityLevel`, normalizing it along the way.\n *\n * @param level String representation of desired `SeverityLevel`.\n * @returns The `SeverityLevel` corresponding to the given string, or 'log' if the string isn't a valid level.\n */\nfunction severityLevelFromString(level) {\n return (\n level === 'warn' ? 'warning' : ['fatal', 'error', 'warning', 'log', 'info', 'debug'].includes(level) ? level : 'log'\n ) ;\n}\n\nexport { severityLevelFromString };\n//# sourceMappingURL=severity.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { getFramesFromEvent } from '../utils/stacktrace.js';\n\nconst INTEGRATION_NAME = 'Dedupe';\n\nconst _dedupeIntegration = (() => {\n let previousEvent;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(currentEvent) {\n // We want to ignore any non-error type events, e.g. transactions or replays\n // These should never be deduped, and also not be compared against as _previousEvent.\n if (currentEvent.type) {\n return currentEvent;\n }\n\n // Juuust in case something goes wrong\n try {\n if (_shouldDropEvent(currentEvent, previousEvent)) {\n DEBUG_BUILD && debug.warn('Event dropped due to being a duplicate of previously captured event.');\n return null;\n }\n } catch {} // eslint-disable-line no-empty\n\n return (previousEvent = currentEvent);\n },\n };\n}) ;\n\n/**\n * Deduplication filter.\n */\nconst dedupeIntegration = defineIntegration(_dedupeIntegration);\n\n/** only exported for tests. */\nfunction _shouldDropEvent(currentEvent, previousEvent) {\n if (!previousEvent) {\n return false;\n }\n\n if (_isSameMessageEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n if (_isSameExceptionEvent(currentEvent, previousEvent)) {\n return true;\n }\n\n return false;\n}\n\nfunction _isSameMessageEvent(currentEvent, previousEvent) {\n const currentMessage = currentEvent.message;\n const previousMessage = previousEvent.message;\n\n // If neither event has a message property, they were both exceptions, so bail out\n if (!currentMessage && !previousMessage) {\n return false;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentMessage && !previousMessage) || (!currentMessage && previousMessage)) {\n return false;\n }\n\n if (currentMessage !== previousMessage) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameExceptionEvent(currentEvent, previousEvent) {\n const previousException = _getExceptionFromEvent(previousEvent);\n const currentException = _getExceptionFromEvent(currentEvent);\n\n if (!previousException || !currentException) {\n return false;\n }\n\n if (previousException.type !== currentException.type || previousException.value !== currentException.value) {\n return false;\n }\n\n if (!_isSameFingerprint(currentEvent, previousEvent)) {\n return false;\n }\n\n if (!_isSameStacktrace(currentEvent, previousEvent)) {\n return false;\n }\n\n return true;\n}\n\nfunction _isSameStacktrace(currentEvent, previousEvent) {\n let currentFrames = getFramesFromEvent(currentEvent);\n let previousFrames = getFramesFromEvent(previousEvent);\n\n // If neither event has a stacktrace, they are assumed to be the same\n if (!currentFrames && !previousFrames) {\n return true;\n }\n\n // If only one event has a stacktrace, but not the other one, they are not the same\n if ((currentFrames && !previousFrames) || (!currentFrames && previousFrames)) {\n return false;\n }\n\n currentFrames = currentFrames ;\n previousFrames = previousFrames ;\n\n // If number of frames differ, they are not the same\n if (previousFrames.length !== currentFrames.length) {\n return false;\n }\n\n // Otherwise, compare the two\n for (let i = 0; i < previousFrames.length; i++) {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameA = previousFrames[i];\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const frameB = currentFrames[i];\n\n if (\n frameA.filename !== frameB.filename ||\n frameA.lineno !== frameB.lineno ||\n frameA.colno !== frameB.colno ||\n frameA.function !== frameB.function\n ) {\n return false;\n }\n }\n\n return true;\n}\n\nfunction _isSameFingerprint(currentEvent, previousEvent) {\n let currentFingerprint = currentEvent.fingerprint;\n let previousFingerprint = previousEvent.fingerprint;\n\n // If neither event has a fingerprint, they are assumed to be the same\n if (!currentFingerprint && !previousFingerprint) {\n return true;\n }\n\n // If only one event has a fingerprint, but not the other one, they are not the same\n if ((currentFingerprint && !previousFingerprint) || (!currentFingerprint && previousFingerprint)) {\n return false;\n }\n\n currentFingerprint = currentFingerprint ;\n previousFingerprint = previousFingerprint ;\n\n // Otherwise, compare the two\n try {\n return !!(currentFingerprint.join('') === previousFingerprint.join(''));\n } catch {\n return false;\n }\n}\n\nfunction _getExceptionFromEvent(event) {\n return event.exception?.values?.[0];\n}\n\nexport { _shouldDropEvent, dedupeIntegration };\n//# sourceMappingURL=dedupe.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { defineIntegration } from '../integration.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { isError, isPlainObject } from '../utils/is.js';\nimport { normalize } from '../utils/normalize.js';\nimport { addNonEnumerableProperty } from '../utils/object.js';\nimport { truncate } from '../utils/string.js';\n\nconst INTEGRATION_NAME = 'ExtraErrorData';\n\n/**\n * Extract additional data for from original exceptions.\n */\nconst _extraErrorDataIntegration = ((options = {}) => {\n const { depth = 3, captureErrorCause = true } = options;\n return {\n name: INTEGRATION_NAME,\n processEvent(event, hint, client) {\n const { maxValueLength } = client.getOptions();\n return _enhanceEventWithErrorData(event, hint, depth, captureErrorCause, maxValueLength);\n },\n };\n}) ;\n\nconst extraErrorDataIntegration = defineIntegration(_extraErrorDataIntegration);\n\nfunction _enhanceEventWithErrorData(\n event,\n hint = {},\n depth,\n captureErrorCause,\n maxValueLength,\n) {\n if (!hint.originalException || !isError(hint.originalException)) {\n return event;\n }\n const exceptionName = (hint.originalException ).name || hint.originalException.constructor.name;\n\n const errorData = _extractErrorData(hint.originalException , captureErrorCause, maxValueLength);\n\n if (errorData) {\n const contexts = {\n ...event.contexts,\n };\n\n const normalizedErrorData = normalize(errorData, depth);\n\n if (isPlainObject(normalizedErrorData)) {\n // We mark the error data as \"already normalized\" here, because we don't want other normalization procedures to\n // potentially truncate the data we just already normalized, with a certain depth setting.\n addNonEnumerableProperty(normalizedErrorData, '__sentry_skip_normalization__', true);\n contexts[exceptionName] = normalizedErrorData;\n }\n\n return {\n ...event,\n contexts,\n };\n }\n\n return event;\n}\n\n/**\n * Extract extra information from the Error object\n */\nfunction _extractErrorData(\n error,\n captureErrorCause,\n maxValueLength,\n) {\n // We are trying to enhance already existing event, so no harm done if it won't succeed\n try {\n const nativeKeys = [\n 'name',\n 'message',\n 'stack',\n 'line',\n 'column',\n 'fileName',\n 'lineNumber',\n 'columnNumber',\n 'toJSON',\n ];\n\n const extraErrorInfo = {};\n\n // We want only enumerable properties, thus `getOwnPropertyNames` is redundant here, as we filter keys anyway.\n for (const key of Object.keys(error)) {\n if (nativeKeys.indexOf(key) !== -1) {\n continue;\n }\n const value = error[key];\n extraErrorInfo[key] =\n isError(value) || typeof value === 'string'\n ? maxValueLength\n ? truncate(`${value}`, maxValueLength)\n : `${value}`\n : value;\n }\n\n // Error.cause is a standard property that is non enumerable, we therefore need to access it separately.\n // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause\n if (captureErrorCause && error.cause !== undefined) {\n if (isError(error.cause)) {\n const errorName = error.cause.name || error.cause.constructor.name;\n extraErrorInfo.cause = { [errorName]: _extractErrorData(error.cause , false, maxValueLength) };\n } else {\n extraErrorInfo.cause = error.cause;\n }\n }\n\n // Check if someone attached `toJSON` method to grab even more properties (eg. axios is doing that)\n if (typeof error.toJSON === 'function') {\n const serializedError = error.toJSON() ;\n\n for (const key of Object.keys(serializedError)) {\n const value = serializedError[key];\n extraErrorInfo[key] = isError(value) ? value.toString() : value;\n }\n }\n\n return extraErrorInfo;\n } catch (oO) {\n DEBUG_BUILD && debug.error('Unable to extract extra data from the Error object:', oO);\n }\n\n return null;\n}\n\nexport { extraErrorDataIntegration };\n//# sourceMappingURL=extraerrordata.js.map\n","// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript\n// https://github.com/calvinmetcalf/rollup-plugin-node-builtins/blob/63ab8aacd013767445ca299e468d9a60a95328d7/src/es6/path.js\n//\n// Copyright Joyent, Inc.and other Node contributors.\n//\n// Permission is hereby granted, free of charge, to any person obtaining a\n// copy of this software and associated documentation files (the\n// \"Software\"), to deal in the Software without restriction, including\n// without limitation the rights to use, copy, modify, merge, publish,\n// distribute, sublicense, and/or sell copies of the Software, and to permit\n// persons to whom the Software is furnished to do so, subject to the\n// following conditions:\n//\n// The above copyright notice and this permission notice shall be included\n// in all copies or substantial portions of the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n// USE OR OTHER DEALINGS IN THE SOFTWARE.\n\n/** JSDoc */\nfunction normalizeArray(parts, allowAboveRoot) {\n // if the path tries to go above the root, `up` ends up > 0\n let up = 0;\n for (let i = parts.length - 1; i >= 0; i--) {\n const last = parts[i];\n if (last === '.') {\n parts.splice(i, 1);\n } else if (last === '..') {\n parts.splice(i, 1);\n up++;\n } else if (up) {\n parts.splice(i, 1);\n up--;\n }\n }\n\n // if the path is allowed to go above the root, restore leading ..s\n if (allowAboveRoot) {\n for (; up--; up) {\n parts.unshift('..');\n }\n }\n\n return parts;\n}\n\n// Split a filename into [root, dir, basename, ext], unix version\n// 'root' is just a slash, or nothing.\nconst splitPathRe = /^(\\S+:\\\\|\\/?)([\\s\\S]*?)((?:\\.{1,2}|[^/\\\\]+?|)(\\.[^./\\\\]*|))(?:[/\\\\]*)$/;\n/** JSDoc */\nfunction splitPath(filename) {\n // Truncate files names greater than 1024 characters to avoid regex dos\n // https://github.com/getsentry/sentry-javascript/pull/8737#discussion_r1285719172\n const truncated = filename.length > 1024 ? `<truncated>${filename.slice(-1024)}` : filename;\n const parts = splitPathRe.exec(truncated);\n return parts ? parts.slice(1) : [];\n}\n\n// path.resolve([from ...], to)\n// posix version\n/** JSDoc */\nfunction resolve(...args) {\n let resolvedPath = '';\n let resolvedAbsolute = false;\n\n for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {\n const path = i >= 0 ? args[i] : '/';\n\n // Skip empty entries\n if (!path) {\n continue;\n }\n\n resolvedPath = `${path}/${resolvedPath}`;\n resolvedAbsolute = path.charAt(0) === '/';\n }\n\n // At this point the path should be resolved to a full absolute path, but\n // handle relative paths to be safe (might happen when process.cwd() fails)\n\n // Normalize the path\n resolvedPath = normalizeArray(\n resolvedPath.split('/').filter(p => !!p),\n !resolvedAbsolute,\n ).join('/');\n\n return (resolvedAbsolute ? '/' : '') + resolvedPath || '.';\n}\n\n/** JSDoc */\nfunction trim(arr) {\n let start = 0;\n for (; start < arr.length; start++) {\n if (arr[start] !== '') {\n break;\n }\n }\n\n let end = arr.length - 1;\n for (; end >= 0; end--) {\n if (arr[end] !== '') {\n break;\n }\n }\n\n if (start > end) {\n return [];\n }\n return arr.slice(start, end - start + 1);\n}\n\n// path.relative(from, to)\n// posix version\n/** JSDoc */\nfunction relative(from, to) {\n /* eslint-disable no-param-reassign */\n from = resolve(from).slice(1);\n to = resolve(to).slice(1);\n /* eslint-enable no-param-reassign */\n\n const fromParts = trim(from.split('/'));\n const toParts = trim(to.split('/'));\n\n const length = Math.min(fromParts.length, toParts.length);\n let samePartsLength = length;\n for (let i = 0; i < length; i++) {\n if (fromParts[i] !== toParts[i]) {\n samePartsLength = i;\n break;\n }\n }\n\n let outputParts = [];\n for (let i = samePartsLength; i < fromParts.length; i++) {\n outputParts.push('..');\n }\n\n outputParts = outputParts.concat(toParts.slice(samePartsLength));\n\n return outputParts.join('/');\n}\n\n// path.normalize(path)\n// posix version\n/** JSDoc */\nfunction normalizePath(path) {\n const isPathAbsolute = isAbsolute(path);\n const trailingSlash = path.slice(-1) === '/';\n\n // Normalize the path\n let normalizedPath = normalizeArray(\n path.split('/').filter(p => !!p),\n !isPathAbsolute,\n ).join('/');\n\n if (!normalizedPath && !isPathAbsolute) {\n normalizedPath = '.';\n }\n if (normalizedPath && trailingSlash) {\n normalizedPath += '/';\n }\n\n return (isPathAbsolute ? '/' : '') + normalizedPath;\n}\n\n// posix version\n/** JSDoc */\nfunction isAbsolute(path) {\n return path.charAt(0) === '/';\n}\n\n// posix version\n/** JSDoc */\nfunction join(...args) {\n return normalizePath(args.join('/'));\n}\n\n/** JSDoc */\nfunction dirname(path) {\n const result = splitPath(path);\n const root = result[0] || '';\n let dir = result[1];\n\n if (!root && !dir) {\n // No dirname whatsoever\n return '.';\n }\n\n if (dir) {\n // It has a dirname, strip trailing slash\n dir = dir.slice(0, dir.length - 1);\n }\n\n return root + dir;\n}\n\n/** JSDoc */\nfunction basename(path, ext) {\n let f = splitPath(path)[2] || '';\n if (ext && f.slice(ext.length * -1) === ext) {\n f = f.slice(0, f.length - ext.length);\n }\n return f;\n}\n\nexport { basename, dirname, isAbsolute, join, normalizePath, relative, resolve };\n//# sourceMappingURL=path.js.map\n","import { defineIntegration } from '../integration.js';\nimport { relative, basename } from '../utils/path.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\n\nconst INTEGRATION_NAME = 'RewriteFrames';\n\n/**\n * Rewrite event frames paths.\n */\nconst rewriteFramesIntegration = defineIntegration((options = {}) => {\n const root = options.root;\n const prefix = options.prefix || 'app:///';\n\n const isBrowser = 'window' in GLOBAL_OBJ && !!GLOBAL_OBJ.window;\n\n const iteratee = options.iteratee || generateIteratee({ isBrowser, root, prefix });\n\n /** Process an exception event. */\n function _processExceptionsEvent(event) {\n try {\n return {\n ...event,\n exception: {\n ...event.exception,\n // The check for this is performed inside `process` call itself, safe to skip here\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n values: event.exception.values.map(value => ({\n ...value,\n ...(value.stacktrace && { stacktrace: _processStacktrace(value.stacktrace) }),\n })),\n },\n };\n } catch {\n return event;\n }\n }\n\n /** Process a stack trace. */\n function _processStacktrace(stacktrace) {\n return {\n ...stacktrace,\n frames: stacktrace?.frames?.map(f => iteratee(f)),\n };\n }\n\n return {\n name: INTEGRATION_NAME,\n processEvent(originalEvent) {\n let processedEvent = originalEvent;\n\n if (originalEvent.exception && Array.isArray(originalEvent.exception.values)) {\n processedEvent = _processExceptionsEvent(processedEvent);\n }\n\n return processedEvent;\n },\n };\n});\n\n/**\n * Exported only for tests.\n */\nfunction generateIteratee({\n isBrowser,\n root,\n prefix,\n}\n\n) {\n return (frame) => {\n if (!frame.filename) {\n return frame;\n }\n\n // Determine if this is a Windows frame by checking for a Windows-style prefix such as `C:\\`\n const isWindowsFrame =\n /^[a-zA-Z]:\\\\/.test(frame.filename) ||\n // or the presence of a backslash without a forward slash (which are not allowed on Windows)\n (frame.filename.includes('\\\\') && !frame.filename.includes('/'));\n\n // Check if the frame filename begins with `/`\n const startsWithSlash = /^\\//.test(frame.filename);\n\n if (isBrowser) {\n if (root) {\n const oldFilename = frame.filename;\n if (oldFilename.indexOf(root) === 0) {\n frame.filename = oldFilename.replace(root, prefix);\n }\n }\n } else {\n if (isWindowsFrame || startsWithSlash) {\n const filename = isWindowsFrame\n ? frame.filename\n .replace(/^[a-zA-Z]:/, '') // remove Windows-style prefix\n .replace(/\\\\/g, '/') // replace all `\\\\` instances with `/`\n : frame.filename;\n const base = root ? relative(root, filename) : basename(filename);\n frame.filename = `${prefix}${base}`;\n }\n }\n\n return frame;\n };\n}\n\nexport { generateIteratee, rewriteFramesIntegration };\n//# sourceMappingURL=rewriteframes.js.map\n","import { addBreadcrumb } from '../breadcrumbs.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { captureException } from '../exports.js';\nimport { defineIntegration } from '../integration.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes.js';\nimport { debug } from '../utils/debug-logger.js';\nimport { addExceptionMechanism } from '../utils/misc.js';\nimport { isPlainObject } from '../utils/is.js';\nimport { SPAN_STATUS_ERROR, SPAN_STATUS_OK, setHttpStatus } from '../tracing/spanstatus.js';\nimport { startSpan } from '../tracing/trace.js';\n\n// Based on Kamil Ogórek's work on:\n// https://github.com/supabase-community/sentry-integration-js\n\n\nconst AUTH_OPERATIONS_TO_INSTRUMENT = [\n 'reauthenticate',\n 'signInAnonymously',\n 'signInWithOAuth',\n 'signInWithIdToken',\n 'signInWithOtp',\n 'signInWithPassword',\n 'signInWithSSO',\n 'signOut',\n 'signUp',\n 'verifyOtp',\n];\n\nconst AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT = [\n 'createUser',\n 'deleteUser',\n 'listUsers',\n 'getUserById',\n 'updateUserById',\n 'inviteUserByEmail',\n];\n\nconst FILTER_MAPPINGS = {\n eq: 'eq',\n neq: 'neq',\n gt: 'gt',\n gte: 'gte',\n lt: 'lt',\n lte: 'lte',\n like: 'like',\n 'like(all)': 'likeAllOf',\n 'like(any)': 'likeAnyOf',\n ilike: 'ilike',\n 'ilike(all)': 'ilikeAllOf',\n 'ilike(any)': 'ilikeAnyOf',\n is: 'is',\n in: 'in',\n cs: 'contains',\n cd: 'containedBy',\n sr: 'rangeGt',\n nxl: 'rangeGte',\n sl: 'rangeLt',\n nxr: 'rangeLte',\n adj: 'rangeAdjacent',\n ov: 'overlaps',\n fts: '',\n plfts: 'plain',\n phfts: 'phrase',\n wfts: 'websearch',\n not: 'not',\n};\n\nconst DB_OPERATIONS_TO_INSTRUMENT = ['select', 'insert', 'upsert', 'update', 'delete'];\n\nfunction markAsInstrumented(fn) {\n try {\n (fn ).__SENTRY_INSTRUMENTED__ = true;\n } catch {\n // ignore errors here\n }\n}\n\nfunction isInstrumented(fn) {\n try {\n return (fn ).__SENTRY_INSTRUMENTED__;\n } catch {\n return false;\n }\n}\n\n/**\n * Extracts the database operation type from the HTTP method and headers\n * @param method - The HTTP method of the request\n * @param headers - The request headers\n * @returns The database operation type ('select', 'insert', 'upsert', 'update', or 'delete')\n */\nfunction extractOperation(method, headers = {}) {\n switch (method) {\n case 'GET': {\n return 'select';\n }\n case 'POST': {\n if (headers['Prefer']?.includes('resolution=')) {\n return 'upsert';\n } else {\n return 'insert';\n }\n }\n case 'PATCH': {\n return 'update';\n }\n case 'DELETE': {\n return 'delete';\n }\n default: {\n return '<unknown-op>';\n }\n }\n}\n\n/**\n * Translates Supabase filter parameters into readable method names for tracing\n * @param key - The filter key from the URL search parameters\n * @param query - The filter value from the URL search parameters\n * @returns A string representation of the filter as a method call\n */\nfunction translateFiltersIntoMethods(key, query) {\n if (query === '' || query === '*') {\n return 'select(*)';\n }\n\n if (key === 'select') {\n return `select(${query})`;\n }\n\n if (key === 'or' || key.endsWith('.or')) {\n return `${key}${query}`;\n }\n\n const [filter, ...value] = query.split('.');\n\n let method;\n // Handle optional `configPart` of the filter\n if (filter?.startsWith('fts')) {\n method = 'textSearch';\n } else if (filter?.startsWith('plfts')) {\n method = 'textSearch[plain]';\n } else if (filter?.startsWith('phfts')) {\n method = 'textSearch[phrase]';\n } else if (filter?.startsWith('wfts')) {\n method = 'textSearch[websearch]';\n } else {\n method = (filter && FILTER_MAPPINGS[filter ]) || 'filter';\n }\n\n return `${method}(${key}, ${value.join('.')})`;\n}\n\nfunction instrumentAuthOperation(operation, isAdmin = false) {\n return new Proxy(operation, {\n apply(target, thisArg, argumentsList) {\n return startSpan(\n {\n name: `auth ${isAdmin ? '(admin) ' : ''}${operation.name}`,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.supabase',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db',\n 'db.system': 'postgresql',\n 'db.operation': `auth.${isAdmin ? 'admin.' : ''}${operation.name}`,\n },\n },\n span => {\n return Reflect.apply(target, thisArg, argumentsList)\n .then((res) => {\n if (res && typeof res === 'object' && 'error' in res && res.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n\n captureException(res.error, {\n mechanism: {\n handled: false,\n type: 'auto.db.supabase.auth',\n },\n });\n } else {\n span.setStatus({ code: SPAN_STATUS_OK });\n }\n\n span.end();\n return res;\n })\n .catch((err) => {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n span.end();\n\n captureException(err, {\n mechanism: {\n handled: false,\n type: 'auto.db.supabase.auth',\n },\n });\n\n throw err;\n })\n .then(...argumentsList);\n },\n );\n },\n });\n}\n\nfunction instrumentSupabaseAuthClient(supabaseClientInstance) {\n const auth = supabaseClientInstance.auth;\n\n if (!auth || isInstrumented(supabaseClientInstance.auth)) {\n return;\n }\n\n for (const operation of AUTH_OPERATIONS_TO_INSTRUMENT) {\n const authOperation = auth[operation];\n\n if (!authOperation) {\n continue;\n }\n\n if (typeof supabaseClientInstance.auth[operation] === 'function') {\n supabaseClientInstance.auth[operation] = instrumentAuthOperation(authOperation);\n }\n }\n\n for (const operation of AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT) {\n const authOperation = auth.admin[operation];\n\n if (!authOperation) {\n continue;\n }\n\n if (typeof supabaseClientInstance.auth.admin[operation] === 'function') {\n supabaseClientInstance.auth.admin[operation] = instrumentAuthOperation(authOperation, true);\n }\n }\n\n markAsInstrumented(supabaseClientInstance.auth);\n}\n\nfunction instrumentSupabaseClientConstructor(SupabaseClient) {\n if (isInstrumented((SupabaseClient ).prototype.from)) {\n return;\n }\n\n (SupabaseClient ).prototype.from = new Proxy(\n (SupabaseClient ).prototype.from,\n {\n apply(target, thisArg, argumentsList) {\n const rv = Reflect.apply(target, thisArg, argumentsList);\n const PostgRESTQueryBuilder = (rv ).constructor;\n\n instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder );\n\n return rv;\n },\n },\n );\n\n markAsInstrumented((SupabaseClient ).prototype.from);\n}\n\nfunction instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder) {\n if (isInstrumented((PostgRESTFilterBuilder.prototype ).then)) {\n return;\n }\n\n (PostgRESTFilterBuilder.prototype ).then = new Proxy(\n (PostgRESTFilterBuilder.prototype ).then,\n {\n apply(target, thisArg, argumentsList) {\n const operations = DB_OPERATIONS_TO_INSTRUMENT;\n const typedThis = thisArg ;\n const operation = extractOperation(typedThis.method, typedThis.headers);\n\n if (!operations.includes(operation)) {\n return Reflect.apply(target, thisArg, argumentsList);\n }\n\n if (!typedThis?.url?.pathname || typeof typedThis.url.pathname !== 'string') {\n return Reflect.apply(target, thisArg, argumentsList);\n }\n\n const pathParts = typedThis.url.pathname.split('/');\n const table = pathParts.length > 0 ? pathParts[pathParts.length - 1] : '';\n\n const queryItems = [];\n for (const [key, value] of typedThis.url.searchParams.entries()) {\n // It's possible to have multiple entries for the same key, eg. `id=eq.7&id=eq.3`,\n // so we need to use array instead of object to collect them.\n queryItems.push(translateFiltersIntoMethods(key, value));\n }\n const body = Object.create(null);\n if (isPlainObject(typedThis.body)) {\n for (const [key, value] of Object.entries(typedThis.body)) {\n body[key] = value;\n }\n }\n\n // Adding operation to the beginning of the description if it's not a `select` operation\n // For example, it can be an `insert` or `update` operation but the query can be `select(...)`\n // For `select` operations, we don't need repeat it in the description\n const description = `${operation === 'select' ? '' : `${operation}${body ? '(...) ' : ''}`}${queryItems.join(\n ' ',\n )} from(${table})`;\n\n const attributes = {\n 'db.table': table,\n 'db.schema': typedThis.schema,\n 'db.url': typedThis.url.origin,\n 'db.sdk': typedThis.headers['X-Client-Info'],\n 'db.system': 'postgresql',\n 'db.operation': operation,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.supabase',\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'db',\n };\n\n if (queryItems.length) {\n attributes['db.query'] = queryItems;\n }\n\n if (Object.keys(body).length) {\n attributes['db.body'] = body;\n }\n\n return startSpan(\n {\n name: description,\n attributes,\n },\n span => {\n return (Reflect.apply(target, thisArg, []) )\n .then(\n (res) => {\n if (span) {\n if (res && typeof res === 'object' && 'status' in res) {\n setHttpStatus(span, res.status || 500);\n }\n span.end();\n }\n\n if (res.error) {\n const err = new Error(res.error.message) ;\n if (res.error.code) {\n err.code = res.error.code;\n }\n if (res.error.details) {\n err.details = res.error.details;\n }\n\n const supabaseContext = {};\n if (queryItems.length) {\n supabaseContext.query = queryItems;\n }\n if (Object.keys(body).length) {\n supabaseContext.body = body;\n }\n\n captureException(err, scope => {\n scope.addEventProcessor(e => {\n addExceptionMechanism(e, {\n handled: false,\n type: 'auto.db.supabase.postgres',\n });\n\n return e;\n });\n\n scope.setContext('supabase', supabaseContext);\n\n return scope;\n });\n }\n\n const breadcrumb = {\n type: 'supabase',\n category: `db.${operation}`,\n message: description,\n };\n\n const data = {};\n\n if (queryItems.length) {\n data.query = queryItems;\n }\n\n if (Object.keys(body).length) {\n data.body = body;\n }\n\n if (Object.keys(data).length) {\n breadcrumb.data = data;\n }\n\n addBreadcrumb(breadcrumb);\n\n return res;\n },\n (err) => {\n // TODO: shouldn't we capture this error?\n if (span) {\n setHttpStatus(span, 500);\n span.end();\n }\n throw err;\n },\n )\n .then(...argumentsList);\n },\n );\n },\n },\n );\n\n markAsInstrumented((PostgRESTFilterBuilder.prototype ).then);\n}\n\nfunction instrumentPostgRESTQueryBuilder(PostgRESTQueryBuilder) {\n // We need to wrap _all_ operations despite them sharing the same `PostgRESTFilterBuilder`\n // constructor, as we don't know which method will be called first, and we don't want to miss any calls.\n for (const operation of DB_OPERATIONS_TO_INSTRUMENT) {\n if (isInstrumented((PostgRESTQueryBuilder.prototype )[operation])) {\n continue;\n }\n\n (PostgRESTQueryBuilder.prototype )[operation ] = new Proxy(\n (PostgRESTQueryBuilder.prototype )[operation ],\n {\n apply(target, thisArg, argumentsList) {\n const rv = Reflect.apply(target, thisArg, argumentsList);\n const PostgRESTFilterBuilder = (rv ).constructor;\n\n DEBUG_BUILD && debug.log(`Instrumenting ${operation} operation's PostgRESTFilterBuilder`);\n\n instrumentPostgRESTFilterBuilder(PostgRESTFilterBuilder);\n\n return rv;\n },\n },\n );\n\n markAsInstrumented((PostgRESTQueryBuilder.prototype )[operation]);\n }\n}\n\nconst instrumentSupabaseClient = (supabaseClient) => {\n if (!supabaseClient) {\n DEBUG_BUILD && debug.warn('Supabase integration was not installed because no Supabase client was provided.');\n return;\n }\n const SupabaseClientConstructor =\n supabaseClient.constructor === Function ? supabaseClient : supabaseClient.constructor;\n\n instrumentSupabaseClientConstructor(SupabaseClientConstructor);\n instrumentSupabaseAuthClient(supabaseClient );\n};\n\nconst INTEGRATION_NAME = 'Supabase';\n\nconst _supabaseIntegration = ((supabaseClient) => {\n return {\n setupOnce() {\n instrumentSupabaseClient(supabaseClient);\n },\n name: INTEGRATION_NAME,\n };\n}) ;\n\nconst supabaseIntegration = defineIntegration((options) => {\n return _supabaseIntegration(options.supabaseClient);\n}) ;\n\nexport { DB_OPERATIONS_TO_INSTRUMENT, FILTER_MAPPINGS, extractOperation, instrumentSupabaseClient, supabaseIntegration, translateFiltersIntoMethods };\n//# sourceMappingURL=supabase.js.map\n","import { defineIntegration } from '../integration.js';\nimport { isError } from '../utils/is.js';\nimport { truncate } from '../utils/string.js';\n\nconst DEFAULT_LIMIT = 10;\nconst INTEGRATION_NAME = 'ZodErrors';\n\n/**\n * Simplified ZodIssue type definition\n */\n\nfunction originalExceptionIsZodError(originalException) {\n return (\n isError(originalException) &&\n originalException.name === 'ZodError' &&\n Array.isArray((originalException ).issues)\n );\n}\n\n/**\n * Formats child objects or arrays to a string\n * that is preserved when sent to Sentry.\n *\n * Without this, we end up with something like this in Sentry:\n *\n * [\n * [Object],\n * [Object],\n * [Object],\n * [Object]\n * ]\n */\nfunction flattenIssue(issue) {\n return {\n ...issue,\n path: 'path' in issue && Array.isArray(issue.path) ? issue.path.join('.') : undefined,\n keys: 'keys' in issue ? JSON.stringify(issue.keys) : undefined,\n unionErrors: 'unionErrors' in issue ? JSON.stringify(issue.unionErrors) : undefined,\n };\n}\n\n/**\n * Takes ZodError issue path array and returns a flattened version as a string.\n * This makes it easier to display paths within a Sentry error message.\n *\n * Array indexes are normalized to reduce duplicate entries\n *\n * @param path ZodError issue path\n * @returns flattened path\n *\n * @example\n * flattenIssuePath([0, 'foo', 1, 'bar']) // -> '<array>.foo.<array>.bar'\n */\nfunction flattenIssuePath(path) {\n return path\n .map(p => {\n if (typeof p === 'number') {\n return '<array>';\n } else {\n return p;\n }\n })\n .join('.');\n}\n\n/**\n * Zod error message is a stringified version of ZodError.issues\n * This doesn't display well in the Sentry UI. Replace it with something shorter.\n */\nfunction formatIssueMessage(zodError) {\n const errorKeyMap = new Set();\n for (const iss of zodError.issues) {\n const issuePath = flattenIssuePath(iss.path);\n if (issuePath.length > 0) {\n errorKeyMap.add(issuePath);\n }\n }\n\n const errorKeys = Array.from(errorKeyMap);\n if (errorKeys.length === 0) {\n // If there are no keys, then we're likely validating the root\n // variable rather than a key within an object. This attempts\n // to extract what type it was that failed to validate.\n // For example, z.string().parse(123) would return \"string\" here.\n let rootExpectedType = 'variable';\n if (zodError.issues.length > 0) {\n const iss = zodError.issues[0];\n if (iss !== undefined && 'expected' in iss && typeof iss.expected === 'string') {\n rootExpectedType = iss.expected;\n }\n }\n return `Failed to validate ${rootExpectedType}`;\n }\n return `Failed to validate keys: ${truncate(errorKeys.join(', '), 100)}`;\n}\n\n/**\n * Applies ZodError issues to an event extra and replaces the error message\n */\nfunction applyZodErrorsToEvent(\n limit,\n saveZodIssuesAsAttachment = false,\n event,\n hint,\n) {\n if (\n !event.exception?.values ||\n !hint.originalException ||\n !originalExceptionIsZodError(hint.originalException) ||\n hint.originalException.issues.length === 0\n ) {\n return event;\n }\n\n try {\n const issuesToFlatten = saveZodIssuesAsAttachment\n ? hint.originalException.issues\n : hint.originalException.issues.slice(0, limit);\n const flattenedIssues = issuesToFlatten.map(flattenIssue);\n\n if (saveZodIssuesAsAttachment) {\n // Sometimes having the full error details can be helpful.\n // Attachments have much higher limits, so we can include the full list of issues.\n if (!Array.isArray(hint.attachments)) {\n hint.attachments = [];\n }\n hint.attachments.push({\n filename: 'zod_issues.json',\n data: JSON.stringify({\n issues: flattenedIssues,\n }),\n });\n }\n\n return {\n ...event,\n exception: {\n ...event.exception,\n values: [\n {\n ...event.exception.values[0],\n value: formatIssueMessage(hint.originalException),\n },\n ...event.exception.values.slice(1),\n ],\n },\n extra: {\n ...event.extra,\n 'zoderror.issues': flattenedIssues.slice(0, limit),\n },\n };\n } catch (e) {\n // Hopefully we never throw errors here, but record it\n // with the event just in case.\n return {\n ...event,\n extra: {\n ...event.extra,\n 'zoderrors sentry integration parse error': {\n message: 'an exception was thrown while processing ZodError within applyZodErrorsToEvent()',\n error: e instanceof Error ? `${e.name}: ${e.message}\\n${e.stack}` : 'unknown',\n },\n },\n };\n }\n}\n\nconst _zodErrorsIntegration = ((options = {}) => {\n const limit = options.limit ?? DEFAULT_LIMIT;\n\n return {\n name: INTEGRATION_NAME,\n processEvent(originalEvent, hint) {\n const processedEvent = applyZodErrorsToEvent(limit, options.saveZodIssuesAsAttachment, originalEvent, hint);\n return processedEvent;\n },\n };\n}) ;\n\n/**\n * Sentry integration to process Zod errors, making them easier to work with in Sentry.\n */\nconst zodErrorsIntegration = defineIntegration(_zodErrorsIntegration);\n\nexport { applyZodErrorsToEvent, flattenIssue, flattenIssuePath, formatIssueMessage, zodErrorsIntegration };\n//# sourceMappingURL=zoderrors.js.map\n","import { addBreadcrumb } from '../breadcrumbs.js';\nimport { getClient } from '../currentScopes.js';\nimport { addConsoleInstrumentationHandler } from '../instrument/console.js';\nimport { defineIntegration } from '../integration.js';\nimport { CONSOLE_LEVELS } from '../utils/debug-logger.js';\nimport { severityLevelFromString } from '../utils/severity.js';\nimport { safeJoin } from '../utils/string.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\n\nconst INTEGRATION_NAME = 'Console';\n\n/**\n * Captures calls to the `console` API as breadcrumbs in Sentry.\n *\n * By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,\n * `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which\n * levels are captured.\n *\n * @example\n *\n * ```js\n * Sentry.init({\n * integrations: [Sentry.consoleIntegration({ levels: ['error', 'warn'] })],\n * });\n * ```\n */\nconst consoleIntegration = defineIntegration((options = {}) => {\n const levels = new Set(options.levels || CONSOLE_LEVELS);\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.has(level)) {\n return;\n }\n\n addConsoleBreadcrumb(level, args);\n });\n },\n };\n});\n\n/**\n * Capture a console breadcrumb.\n *\n * Exported just for tests.\n */\nfunction addConsoleBreadcrumb(level, args) {\n const breadcrumb = {\n category: 'console',\n data: {\n arguments: args,\n logger: 'console',\n },\n level: severityLevelFromString(level),\n message: formatConsoleArgs(args),\n };\n\n if (level === 'assert') {\n if (args[0] === false) {\n const assertionArgs = args.slice(1);\n breadcrumb.message =\n assertionArgs.length > 0 ? `Assertion failed: ${formatConsoleArgs(assertionArgs)}` : 'Assertion failed';\n breadcrumb.data.arguments = assertionArgs;\n } else {\n // Don't capture a breadcrumb for passed assertions\n return;\n }\n }\n\n addBreadcrumb(breadcrumb, {\n input: args,\n level,\n });\n}\n\nfunction formatConsoleArgs(values) {\n return 'util' in GLOBAL_OBJ && typeof (GLOBAL_OBJ ).util.format === 'function'\n ? (GLOBAL_OBJ ).util.format(...values)\n : safeJoin(values, ' ');\n}\n\nexport { addConsoleBreadcrumb, consoleIntegration };\n//# sourceMappingURL=console.js.map\n","import { getCurrentScope } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { getActiveSpan, spanToJSON } from './spanUtils.js';\n\n/**\n * Ordered LRU cache for storing feature flags in the scope context. The name\n * of each flag in the buffer is unique, and the output of getAll() is ordered\n * from oldest to newest.\n */\n\n/**\n * Max size of the LRU flag buffer stored in Sentry scope and event contexts.\n */\nconst _INTERNAL_FLAG_BUFFER_SIZE = 100;\n\n/**\n * Max number of flag evaluations to record per span.\n */\nconst _INTERNAL_MAX_FLAGS_PER_SPAN = 10;\n\nconst SPAN_FLAG_ATTRIBUTE_PREFIX = 'flag.evaluation.';\n\n/**\n * Copies feature flags that are in current scope context to the event context\n */\nfunction _INTERNAL_copyFlagsFromScopeToEvent(event) {\n const scope = getCurrentScope();\n const flagContext = scope.getScopeData().contexts.flags;\n const flagBuffer = flagContext ? flagContext.values : [];\n\n if (!flagBuffer.length) {\n return event;\n }\n\n if (event.contexts === undefined) {\n event.contexts = {};\n }\n event.contexts.flags = { values: [...flagBuffer] };\n return event;\n}\n\n/**\n * Inserts a flag into the current scope's context while maintaining ordered LRU properties.\n * Not thread-safe. After inserting:\n * - The flag buffer is sorted in order of recency, with the newest evaluation at the end.\n * - The names in the buffer are always unique.\n * - The length of the buffer never exceeds `maxSize`.\n *\n * @param name Name of the feature flag to insert.\n * @param value Value of the feature flag.\n * @param maxSize Max number of flags the buffer should store. Default value should always be used in production.\n */\nfunction _INTERNAL_insertFlagToScope(\n name,\n value,\n maxSize = _INTERNAL_FLAG_BUFFER_SIZE,\n) {\n const scopeContexts = getCurrentScope().getScopeData().contexts;\n if (!scopeContexts.flags) {\n scopeContexts.flags = { values: [] };\n }\n const flags = scopeContexts.flags.values;\n _INTERNAL_insertToFlagBuffer(flags, name, value, maxSize);\n}\n\n/**\n * Exported for tests only. Currently only accepts boolean values (otherwise no-op).\n * Inserts a flag into a FeatureFlag array while maintaining the following properties:\n * - Flags are sorted in order of recency, with the newest evaluation at the end.\n * - The flag names are always unique.\n * - The length of the array never exceeds `maxSize`.\n *\n * @param flags The buffer to insert the flag into.\n * @param name Name of the feature flag to insert.\n * @param value Value of the feature flag.\n * @param maxSize Max number of flags the buffer should store. Default value should always be used in production.\n */\nfunction _INTERNAL_insertToFlagBuffer(\n flags,\n name,\n value,\n maxSize,\n) {\n if (typeof value !== 'boolean') {\n return;\n }\n\n if (flags.length > maxSize) {\n DEBUG_BUILD && debug.error(`[Feature Flags] insertToFlagBuffer called on a buffer larger than maxSize=${maxSize}`);\n return;\n }\n\n // Check if the flag is already in the buffer - O(n)\n const index = flags.findIndex(f => f.flag === name);\n\n if (index !== -1) {\n // The flag was found, remove it from its current position - O(n)\n flags.splice(index, 1);\n }\n\n if (flags.length === maxSize) {\n // If at capacity, pop the earliest flag - O(n)\n flags.shift();\n }\n\n // Push the flag to the end - O(1)\n flags.push({\n flag: name,\n result: value,\n });\n}\n\n/**\n * Records a feature flag evaluation for the active span. This is a no-op for non-boolean values.\n * The flag and its value is stored in span attributes with the `flag.evaluation` prefix. Once the\n * unique flags for a span reaches maxFlagsPerSpan, subsequent flags are dropped.\n *\n * @param name Name of the feature flag.\n * @param value Value of the feature flag. Non-boolean values are ignored.\n * @param maxFlagsPerSpan Max number of flags a buffer should store. Default value should always be used in production.\n */\nfunction _INTERNAL_addFeatureFlagToActiveSpan(\n name,\n value,\n maxFlagsPerSpan = _INTERNAL_MAX_FLAGS_PER_SPAN,\n) {\n if (typeof value !== 'boolean') {\n return;\n }\n\n const span = getActiveSpan();\n if (!span) {\n return;\n }\n\n const attributes = spanToJSON(span).data;\n\n // If the flag already exists, always update it\n if (`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}` in attributes) {\n span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);\n return;\n }\n\n // Else, add the flag to the span if we have not reached the max number of flags\n const numOfAddedFlags = Object.keys(attributes).filter(key => key.startsWith(SPAN_FLAG_ATTRIBUTE_PREFIX)).length;\n if (numOfAddedFlags < maxFlagsPerSpan) {\n span.setAttribute(`${SPAN_FLAG_ATTRIBUTE_PREFIX}${name}`, value);\n }\n}\n\nexport { _INTERNAL_FLAG_BUFFER_SIZE, _INTERNAL_MAX_FLAGS_PER_SPAN, _INTERNAL_addFeatureFlagToActiveSpan, _INTERNAL_copyFlagsFromScopeToEvent, _INTERNAL_insertFlagToScope, _INTERNAL_insertToFlagBuffer };\n//# sourceMappingURL=featureFlags.js.map\n","import { defineIntegration } from '../../integration.js';\nimport { _INTERNAL_copyFlagsFromScopeToEvent, _INTERNAL_insertFlagToScope, _INTERNAL_addFeatureFlagToActiveSpan } from '../../utils/featureFlags.js';\nimport { fill } from '../../utils/object.js';\n\n/**\n * Sentry integration for capturing feature flag evaluations from GrowthBook.\n *\n * Only boolean results are captured at this time.\n *\n * @example\n * ```typescript\n * import { GrowthBook } from '@growthbook/growthbook';\n * import * as Sentry from '@sentry/browser'; // or '@sentry/node'\n *\n * Sentry.init({\n * dsn: 'your-dsn',\n * integrations: [\n * Sentry.growthbookIntegration({ growthbookClass: GrowthBook })\n * ]\n * });\n * ```\n */\nconst growthbookIntegration = defineIntegration(\n ({ growthbookClass }) => {\n return {\n name: 'GrowthBook',\n\n setupOnce() {\n const proto = growthbookClass.prototype ;\n\n // Type guard and wrap isOn\n if (typeof proto.isOn === 'function') {\n fill(proto, 'isOn', _wrapAndCaptureBooleanResult);\n }\n\n // Type guard and wrap getFeatureValue\n if (typeof proto.getFeatureValue === 'function') {\n fill(proto, 'getFeatureValue', _wrapAndCaptureBooleanResult);\n }\n },\n\n processEvent(event, _hint, _client) {\n return _INTERNAL_copyFlagsFromScopeToEvent(event);\n },\n };\n },\n);\n\nfunction _wrapAndCaptureBooleanResult(\n original,\n) {\n return function ( ...args) {\n const flagName = args[0];\n const result = original.apply(this, args);\n\n if (typeof flagName === 'string' && typeof result === 'boolean') {\n _INTERNAL_insertFlagToScope(flagName, result);\n _INTERNAL_addFeatureFlagToActiveSpan(flagName, result);\n }\n\n return result;\n };\n}\n\nexport { growthbookIntegration };\n//# sourceMappingURL=growthbook.js.map\n","import { getClient } from './currentScopes.js';\nimport { DEBUG_BUILD } from './debug-build.js';\nimport { debug } from './utils/debug-logger.js';\n\nfunction isProfilingIntegrationWithProfiler(\n integration,\n) {\n return (\n !!integration &&\n typeof integration['_profiler'] !== 'undefined' &&\n typeof integration['_profiler']['start'] === 'function' &&\n typeof integration['_profiler']['stop'] === 'function'\n );\n}\n/**\n * Starts the Sentry continuous profiler.\n * This mode is exclusive with the transaction profiler and will only work if the profilesSampleRate is set to a falsy value.\n * In continuous profiling mode, the profiler will keep reporting profile chunks to Sentry until it is stopped, which allows for continuous profiling of the application.\n */\nfunction startProfiler() {\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No Sentry client available, profiling is not started');\n return;\n }\n\n const integration = client.getIntegrationByName('ProfilingIntegration');\n\n if (!integration) {\n DEBUG_BUILD && debug.warn('ProfilingIntegration is not available');\n return;\n }\n\n if (!isProfilingIntegrationWithProfiler(integration)) {\n DEBUG_BUILD && debug.warn('Profiler is not available on profiling integration.');\n return;\n }\n\n integration._profiler.start();\n}\n\n/**\n * Stops the Sentry continuous profiler.\n * Calls to stop will stop the profiler and flush the currently collected profile data to Sentry.\n */\nfunction stopProfiler() {\n const client = getClient();\n if (!client) {\n DEBUG_BUILD && debug.warn('No Sentry client available, profiling is not started');\n return;\n }\n\n const integration = client.getIntegrationByName('ProfilingIntegration');\n if (!integration) {\n DEBUG_BUILD && debug.warn('ProfilingIntegration is not available');\n return;\n }\n\n if (!isProfilingIntegrationWithProfiler(integration)) {\n DEBUG_BUILD && debug.warn('Profiler is not available on profiling integration.');\n return;\n }\n\n integration._profiler.stop();\n}\n\n/**\n * Profiler namespace for controlling the profiler in 'manual' mode.\n *\n * Requires the `nodeProfilingIntegration` from the `@sentry/profiling-node` package.\n */\nconst profiler = {\n startProfiler,\n stopProfiler,\n};\n\nexport { profiler };\n//# sourceMappingURL=profiling.js.map\n","import { getClient } from './currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from './semanticAttributes.js';\nimport { getActiveSpan } from './utils/spanUtils.js';\nimport { setHttpStatus, SPAN_STATUS_ERROR } from './tracing/spanstatus.js';\nimport { isRequest, isInstanceOf } from './utils/is.js';\nimport { hasSpansEnabled } from './utils/hasSpansEnabled.js';\nimport { SENTRY_BAGGAGE_KEY_PREFIX } from './utils/baggage.js';\nimport { SentryNonRecordingSpan } from './tracing/sentryNonRecordingSpan.js';\nimport { startInactiveSpan } from './tracing/trace.js';\nimport { getTraceData } from './utils/traceData.js';\nimport { parseStringToURLObject, getSanitizedUrlStringFromUrlObject, isURLObjectRelative } from './utils/url.js';\n\n/**\n * Create and track fetch request spans for usage in combination with `addFetchInstrumentationHandler`.\n *\n * @returns Span if a span was created, otherwise void.\n */\nfunction instrumentFetchRequest(\n handlerData,\n shouldCreateSpan,\n shouldAttachHeaders,\n spans,\n spanOriginOrOptions,\n) {\n if (!handlerData.fetchData) {\n return undefined;\n }\n\n const { method, url } = handlerData.fetchData;\n\n const shouldCreateSpanResult = hasSpansEnabled() && shouldCreateSpan(url);\n\n if (handlerData.endTimestamp && shouldCreateSpanResult) {\n const spanId = handlerData.fetchData.__span;\n if (!spanId) return;\n\n const span = spans[spanId];\n if (span) {\n endSpan(span, handlerData);\n\n _callOnRequestSpanEnd(span, handlerData, spanOriginOrOptions);\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete spans[spanId];\n }\n return undefined;\n }\n\n // Backwards-compatible with the old signature. Needed to introduce the combined optional parameter\n // to avoid API breakage for anyone calling this function with the optional spanOrigin parameter\n // TODO (v11): remove this backwards-compatible code and only accept the options parameter\n const { spanOrigin = 'auto.http.browser', propagateTraceparent = false } =\n typeof spanOriginOrOptions === 'object' ? spanOriginOrOptions : { spanOrigin: spanOriginOrOptions };\n\n const hasParent = !!getActiveSpan();\n\n const span =\n shouldCreateSpanResult && hasParent\n ? startInactiveSpan(getSpanStartOptions(url, method, spanOrigin))\n : new SentryNonRecordingSpan();\n\n handlerData.fetchData.__span = span.spanContext().spanId;\n spans[span.spanContext().spanId] = span;\n\n if (shouldAttachHeaders(handlerData.fetchData.url)) {\n const request = handlerData.args[0];\n\n const options = handlerData.args[1] || {};\n\n const headers = _addTracingHeadersToFetchRequest(\n request,\n options,\n // If performance is disabled (TWP) or there's no active root span (pageload/navigation/interaction),\n // we do not want to use the span as base for the trace headers,\n // which means that the headers will be generated from the scope and the sampling decision is deferred\n hasSpansEnabled() && hasParent ? span : undefined,\n propagateTraceparent,\n );\n if (headers) {\n // Ensure this is actually set, if no options have been passed previously\n handlerData.args[1] = options;\n options.headers = headers;\n }\n }\n\n const client = getClient();\n\n if (client) {\n const fetchHint = {\n input: handlerData.args,\n response: handlerData.response,\n startTimestamp: handlerData.startTimestamp,\n endTimestamp: handlerData.endTimestamp,\n } ;\n\n client.emit('beforeOutgoingRequestSpan', span, fetchHint);\n }\n\n return span;\n}\n\n/**\n * Calls the onRequestSpanEnd callback if it is defined.\n */\nfunction _callOnRequestSpanEnd(\n span,\n handlerData,\n spanOriginOrOptions,\n) {\n const onRequestSpanEnd =\n typeof spanOriginOrOptions === 'object' && spanOriginOrOptions !== null\n ? spanOriginOrOptions.onRequestSpanEnd\n : undefined;\n\n onRequestSpanEnd?.(span, {\n headers: handlerData.response?.headers,\n error: handlerData.error,\n });\n}\n\n/**\n * Adds sentry-trace and baggage headers to the various forms of fetch headers.\n * exported only for testing purposes\n *\n * When we determine if we should add a baggage header, there are 3 cases:\n * 1. No previous baggage header -> add baggage\n * 2. Previous baggage header has no sentry baggage values -> add our baggage\n * 3. Previous baggage header has sentry baggage values -> do nothing (might have been added manually by users)\n */\n// eslint-disable-next-line complexity -- yup it's this complicated :(\nfunction _addTracingHeadersToFetchRequest(\n request,\n fetchOptionsObj\n\n,\n span,\n propagateTraceparent,\n) {\n const traceHeaders = getTraceData({ span, propagateTraceparent });\n const sentryTrace = traceHeaders['sentry-trace'];\n const baggage = traceHeaders.baggage;\n const traceparent = traceHeaders.traceparent;\n\n // Nothing to do, when we return undefined here, the original headers will be used\n if (!sentryTrace) {\n return undefined;\n }\n\n const originalHeaders = fetchOptionsObj.headers || (isRequest(request) ? request.headers : undefined);\n\n if (!originalHeaders) {\n return { ...traceHeaders };\n } else if (isHeaders(originalHeaders)) {\n const newHeaders = new Headers(originalHeaders);\n\n // We don't want to override manually added sentry headers\n if (!newHeaders.get('sentry-trace')) {\n newHeaders.set('sentry-trace', sentryTrace);\n }\n\n if (propagateTraceparent && traceparent && !newHeaders.get('traceparent')) {\n newHeaders.set('traceparent', traceparent);\n }\n\n if (baggage) {\n const prevBaggageHeader = newHeaders.get('baggage');\n\n if (!prevBaggageHeader) {\n newHeaders.set('baggage', baggage);\n } else if (!baggageHeaderHasSentryBaggageValues(prevBaggageHeader)) {\n newHeaders.set('baggage', `${prevBaggageHeader},${baggage}`);\n }\n }\n\n return newHeaders;\n } else if (Array.isArray(originalHeaders)) {\n const newHeaders = [...originalHeaders];\n\n if (!originalHeaders.find(header => header[0] === 'sentry-trace')) {\n newHeaders.push(['sentry-trace', sentryTrace]);\n }\n\n if (propagateTraceparent && traceparent && !originalHeaders.find(header => header[0] === 'traceparent')) {\n newHeaders.push(['traceparent', traceparent]);\n }\n\n const prevBaggageHeaderWithSentryValues = originalHeaders.find(\n header => header[0] === 'baggage' && baggageHeaderHasSentryBaggageValues(header[1]),\n );\n\n if (baggage && !prevBaggageHeaderWithSentryValues) {\n // If there are multiple entries with the same key, the browser will merge the values into a single request header.\n // Its therefore safe to simply push a \"baggage\" entry, even though there might already be another baggage header.\n newHeaders.push(['baggage', baggage]);\n }\n\n return newHeaders ;\n } else {\n const existingSentryTraceHeader = 'sentry-trace' in originalHeaders ? originalHeaders['sentry-trace'] : undefined;\n const existingTraceparentHeader = 'traceparent' in originalHeaders ? originalHeaders.traceparent : undefined;\n const existingBaggageHeader = 'baggage' in originalHeaders ? originalHeaders.baggage : undefined;\n\n const newBaggageHeaders = existingBaggageHeader\n ? Array.isArray(existingBaggageHeader)\n ? [...existingBaggageHeader]\n : [existingBaggageHeader]\n : [];\n\n const prevBaggageHeaderWithSentryValues =\n existingBaggageHeader &&\n (Array.isArray(existingBaggageHeader)\n ? existingBaggageHeader.find(headerItem => baggageHeaderHasSentryBaggageValues(headerItem))\n : baggageHeaderHasSentryBaggageValues(existingBaggageHeader));\n\n if (baggage && !prevBaggageHeaderWithSentryValues) {\n newBaggageHeaders.push(baggage);\n }\n\n const newHeaders\n\n = {\n ...originalHeaders,\n 'sentry-trace': (existingSentryTraceHeader ) ?? sentryTrace,\n baggage: newBaggageHeaders.length > 0 ? newBaggageHeaders.join(',') : undefined,\n };\n\n if (propagateTraceparent && traceparent && !existingTraceparentHeader) {\n newHeaders.traceparent = traceparent;\n }\n\n return newHeaders;\n }\n}\n\nfunction endSpan(span, handlerData) {\n if (handlerData.response) {\n setHttpStatus(span, handlerData.response.status);\n\n const contentLength = handlerData.response?.headers?.get('content-length');\n\n if (contentLength) {\n const contentLengthNum = parseInt(contentLength);\n if (contentLengthNum > 0) {\n span.setAttribute('http.response_content_length', contentLengthNum);\n }\n }\n } else if (handlerData.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n }\n span.end();\n}\n\nfunction baggageHeaderHasSentryBaggageValues(baggageHeader) {\n return baggageHeader.split(',').some(baggageEntry => baggageEntry.trim().startsWith(SENTRY_BAGGAGE_KEY_PREFIX));\n}\n\nfunction isHeaders(headers) {\n return typeof Headers !== 'undefined' && isInstanceOf(headers, Headers);\n}\n\nfunction getSpanStartOptions(\n url,\n method,\n spanOrigin,\n) {\n const parsedUrl = parseStringToURLObject(url);\n return {\n name: parsedUrl ? `${method} ${getSanitizedUrlStringFromUrlObject(parsedUrl)}` : method,\n attributes: getFetchSpanAttributes(url, parsedUrl, method, spanOrigin),\n };\n}\n\nfunction getFetchSpanAttributes(\n url,\n parsedUrl,\n method,\n spanOrigin,\n) {\n const attributes = {\n url,\n type: 'fetch',\n 'http.method': method,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: spanOrigin,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'http.client',\n };\n if (parsedUrl) {\n if (!isURLObjectRelative(parsedUrl)) {\n attributes['http.url'] = parsedUrl.href;\n attributes['server.address'] = parsedUrl.host;\n }\n if (parsedUrl.search) {\n attributes['http.query'] = parsedUrl.search;\n }\n if (parsedUrl.hash) {\n attributes['http.fragment'] = parsedUrl.hash;\n }\n }\n return attributes;\n}\n\nexport { _addTracingHeadersToFetchRequest, _callOnRequestSpanEnd, instrumentFetchRequest };\n//# sourceMappingURL=fetch.js.map\n","import { getClient, withIsolationScope } from './currentScopes.js';\nimport { captureException } from './exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE } from './semanticAttributes.js';\nimport { addNonEnumerableProperty } from './utils/object.js';\nimport { normalize } from './utils/normalize.js';\nimport { startSpanManual } from './tracing/trace.js';\n\nconst trpcCaptureContext = { mechanism: { handled: false, type: 'auto.rpc.trpc.middleware' } };\n\nfunction captureIfError(nextResult) {\n // TODO: Set span status based on what TRPCError was encountered\n if (\n typeof nextResult === 'object' &&\n nextResult !== null &&\n 'ok' in nextResult &&\n !nextResult.ok &&\n 'error' in nextResult\n ) {\n captureException(nextResult.error, trpcCaptureContext);\n }\n}\n\n/**\n * Sentry tRPC middleware that captures errors and creates spans for tRPC procedures.\n */\nfunction trpcMiddleware(options = {}) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n return async function (opts) {\n const { path, type, next, rawInput, getRawInput } = opts;\n\n const client = getClient();\n const clientOptions = client?.getOptions();\n\n const trpcContext = {\n procedure_path: path,\n procedure_type: type,\n };\n\n addNonEnumerableProperty(\n trpcContext,\n '__sentry_override_normalization_depth__',\n 1 + // 1 for context.input + the normal normalization depth\n (clientOptions?.normalizeDepth ?? 5), // 5 is a sane depth\n );\n\n if (options.attachRpcInput !== undefined ? options.attachRpcInput : clientOptions?.sendDefaultPii) {\n if (rawInput !== undefined) {\n trpcContext.input = normalize(rawInput);\n }\n\n if (getRawInput !== undefined && typeof getRawInput === 'function') {\n try {\n const rawRes = await getRawInput();\n\n trpcContext.input = normalize(rawRes);\n } catch {\n // noop\n }\n }\n }\n\n return withIsolationScope(scope => {\n scope.setContext('trpc', trpcContext);\n return startSpanManual(\n {\n name: `trpc/${path}`,\n op: 'rpc.server',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'route',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.rpc.trpc',\n },\n forceTransaction: !!options.forceTransaction,\n },\n async span => {\n try {\n const nextResult = await next();\n captureIfError(nextResult);\n span.end();\n return nextResult;\n } catch (e) {\n captureException(e, trpcCaptureContext);\n span.end();\n throw e;\n }\n },\n ) ;\n });\n };\n}\n\nexport { trpcMiddleware };\n//# sourceMappingURL=trpc.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { captureException } from '../../exports.js';\nimport { getActiveSpan } from '../../utils/spanUtils.js';\nimport { SPAN_STATUS_ERROR } from '../../tracing/spanstatus.js';\n\n/**\n * Safe error capture utilities for MCP server instrumentation\n *\n * Ensures error reporting never interferes with MCP server operation.\n * All capture operations are wrapped in try-catch to prevent side effects.\n */\n\n\n/**\n * Captures an error without affecting MCP server operation.\n *\n * The active span already contains all MCP context (method, tool, arguments, etc.)\n * @param error - Error to capture\n * @param errorType - Classification of error type for filtering\n * @param extraData - Additional context data to include\n */\nfunction captureError(error, errorType, extraData) {\n try {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const activeSpan = getActiveSpan();\n if (activeSpan?.isRecording()) {\n activeSpan.setStatus({\n code: SPAN_STATUS_ERROR,\n message: 'internal_error',\n });\n }\n\n captureException(error, {\n mechanism: {\n type: 'auto.ai.mcp_server',\n handled: false,\n data: {\n error_type: errorType || 'handler_execution',\n ...extraData,\n },\n },\n });\n } catch {\n // noop\n }\n}\n\nexport { captureError };\n//# sourceMappingURL=errorCapture.js.map\n","import { DEBUG_BUILD } from '../../debug-build.js';\nimport { debug } from '../../utils/debug-logger.js';\nimport { fill } from '../../utils/object.js';\nimport { captureError } from './errorCapture.js';\n\n/**\n * Handler method wrapping for MCP server instrumentation\n *\n * Provides automatic error capture and span correlation for tool, resource,\n * and prompt handlers.\n */\n\n\n/**\n * Generic function to wrap MCP server method handlers\n * @internal\n * @param serverInstance - MCP server instance\n * @param methodName - Method name to wrap (tool, resource, prompt)\n */\nfunction wrapMethodHandler(serverInstance, methodName) {\n fill(serverInstance, methodName, originalMethod => {\n return function ( name, ...args) {\n const handler = args[args.length - 1];\n\n if (typeof handler !== 'function') {\n return (originalMethod ).call(this, name, ...args);\n }\n\n const wrappedHandler = createWrappedHandler(handler , methodName, name);\n return (originalMethod ).call(this, name, ...args.slice(0, -1), wrappedHandler);\n };\n });\n}\n\n/**\n * Creates a wrapped handler with span correlation and error capture\n * @internal\n * @param originalHandler - Original handler function\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n * @returns Wrapped handler function\n */\nfunction createWrappedHandler(originalHandler, methodName, handlerName) {\n return function ( ...handlerArgs) {\n try {\n return createErrorCapturingHandler.call(this, originalHandler, methodName, handlerName, handlerArgs);\n } catch (error) {\n DEBUG_BUILD && debug.warn('MCP handler wrapping failed:', error);\n return originalHandler.apply(this, handlerArgs);\n }\n };\n}\n\n/**\n * Creates an error-capturing wrapper for handler execution\n * @internal\n * @param originalHandler - Original handler function\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n * @param handlerArgs - Handler arguments\n * @param extraHandlerData - Additional handler context\n * @returns Handler execution result\n */\nfunction createErrorCapturingHandler(\n\n originalHandler,\n methodName,\n handlerName,\n handlerArgs,\n) {\n try {\n const result = originalHandler.apply(this, handlerArgs);\n\n if (result && typeof result === 'object' && typeof (result ).then === 'function') {\n return Promise.resolve(result).catch(error => {\n captureHandlerError(error, methodName, handlerName);\n throw error;\n });\n }\n\n return result;\n } catch (error) {\n captureHandlerError(error , methodName, handlerName);\n throw error;\n }\n}\n\n/**\n * Captures handler execution errors based on handler type\n * @internal\n * @param error - Error to capture\n * @param methodName - MCP method name\n * @param handlerName - Handler identifier\n */\nfunction captureHandlerError(error, methodName, handlerName) {\n try {\n const extraData = {};\n\n if (methodName === 'tool') {\n extraData.tool_name = handlerName;\n\n if (\n error.name === 'ProtocolValidationError' ||\n error.message.includes('validation') ||\n error.message.includes('protocol')\n ) {\n captureError(error, 'validation', extraData);\n } else if (\n error.name === 'ServerTimeoutError' ||\n error.message.includes('timed out') ||\n error.message.includes('timeout')\n ) {\n captureError(error, 'timeout', extraData);\n } else {\n captureError(error, 'tool_execution', extraData);\n }\n } else if (methodName === 'resource') {\n extraData.resource_uri = handlerName;\n captureError(error, 'resource_execution', extraData);\n } else if (methodName === 'prompt') {\n extraData.prompt_name = handlerName;\n captureError(error, 'prompt_execution', extraData);\n }\n } catch (captureErr) {\n // noop\n }\n}\n\n/**\n * Wraps tool handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nfunction wrapToolHandlers(serverInstance) {\n wrapMethodHandler(serverInstance, 'tool');\n}\n\n/**\n * Wraps resource handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nfunction wrapResourceHandlers(serverInstance) {\n wrapMethodHandler(serverInstance, 'resource');\n}\n\n/**\n * Wraps prompt handlers to associate them with request spans\n * @param serverInstance - MCP server instance\n */\nfunction wrapPromptHandlers(serverInstance) {\n wrapMethodHandler(serverInstance, 'prompt');\n}\n\n/**\n * Wraps all MCP handler types (tool, resource, prompt) for span correlation\n * @param serverInstance - MCP server instance\n */\nfunction wrapAllMCPHandlers(serverInstance) {\n wrapToolHandlers(serverInstance);\n wrapResourceHandlers(serverInstance);\n wrapPromptHandlers(serverInstance);\n}\n\nexport { wrapAllMCPHandlers, wrapPromptHandlers, wrapResourceHandlers, wrapToolHandlers };\n//# sourceMappingURL=handlers.js.map\n","/**\n * Essential MCP attribute constants for Sentry instrumentation\n *\n * Based on OpenTelemetry MCP semantic conventions\n * @see https://github.com/open-telemetry/semantic-conventions/blob/3097fb0af5b9492b0e3f55dc5f6c21a3dc2be8df/docs/gen-ai/mcp.md\n */\n\n// =============================================================================\n// CORE MCP ATTRIBUTES\n// =============================================================================\n\n/** The name of the request or notification method */\nconst MCP_METHOD_NAME_ATTRIBUTE = 'mcp.method.name';\n\n/** JSON-RPC request identifier for the request. Unique within the MCP session. */\nconst MCP_REQUEST_ID_ATTRIBUTE = 'mcp.request.id';\n\n/** Identifies the MCP session */\nconst MCP_SESSION_ID_ATTRIBUTE = 'mcp.session.id';\n\n/** Transport method used for MCP communication */\nconst MCP_TRANSPORT_ATTRIBUTE = 'mcp.transport';\n\n// =============================================================================\n// SERVER ATTRIBUTES\n// =============================================================================\n\n/** Name of the MCP server application */\nconst MCP_SERVER_NAME_ATTRIBUTE = 'mcp.server.name';\n\n/** Display title of the MCP server application */\nconst MCP_SERVER_TITLE_ATTRIBUTE = 'mcp.server.title';\n\n/** Version of the MCP server application */\nconst MCP_SERVER_VERSION_ATTRIBUTE = 'mcp.server.version';\n\n/** MCP protocol version used in the session */\nconst MCP_PROTOCOL_VERSION_ATTRIBUTE = 'mcp.protocol.version';\n\n// =============================================================================\n// METHOD-SPECIFIC ATTRIBUTES\n// =============================================================================\n\n/** Name of the tool being called */\nconst MCP_TOOL_NAME_ATTRIBUTE = 'mcp.tool.name';\n\n/** The resource URI being accessed */\nconst MCP_RESOURCE_URI_ATTRIBUTE = 'mcp.resource.uri';\n\n/** Name of the prompt template */\nconst MCP_PROMPT_NAME_ATTRIBUTE = 'mcp.prompt.name';\n\n// =============================================================================\n// TOOL RESULT ATTRIBUTES\n// =============================================================================\n\n/** Whether a tool execution resulted in an error */\nconst MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE = 'mcp.tool.result.is_error';\n\n/** Number of content items in the tool result */\nconst MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE = 'mcp.tool.result.content_count';\n\n/** Serialized content of the tool result */\nconst MCP_TOOL_RESULT_CONTENT_ATTRIBUTE = 'mcp.tool.result.content';\n\n/** Prefix for tool result attributes that contain sensitive content */\nconst MCP_TOOL_RESULT_PREFIX = 'mcp.tool.result';\n\n// =============================================================================\n// PROMPT RESULT ATTRIBUTES\n// =============================================================================\n\n/** Description of the prompt result */\nconst MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE = 'mcp.prompt.result.description';\n\n/** Number of messages in the prompt result */\nconst MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE = 'mcp.prompt.result.message_count';\n\n/** Content of the message in the prompt result (for single message results) */\nconst MCP_PROMPT_RESULT_MESSAGE_CONTENT_ATTRIBUTE = 'mcp.prompt.result.message_content';\n\n/** Prefix for prompt result attributes that contain sensitive content */\nconst MCP_PROMPT_RESULT_PREFIX = 'mcp.prompt.result';\n\n// =============================================================================\n// REQUEST ARGUMENT ATTRIBUTES\n// =============================================================================\n\n/** Prefix for MCP request argument prefix for each argument */\nconst MCP_REQUEST_ARGUMENT = 'mcp.request.argument';\n\n// =============================================================================\n// LOGGING ATTRIBUTES\n// =============================================================================\n\n/** Log level for MCP logging operations */\nconst MCP_LOGGING_LEVEL_ATTRIBUTE = 'mcp.logging.level';\n\n/** Logger name for MCP logging operations */\nconst MCP_LOGGING_LOGGER_ATTRIBUTE = 'mcp.logging.logger';\n\n/** Data type of the logged message */\nconst MCP_LOGGING_DATA_TYPE_ATTRIBUTE = 'mcp.logging.data_type';\n\n/** Log message content */\nconst MCP_LOGGING_MESSAGE_ATTRIBUTE = 'mcp.logging.message';\n\n// =============================================================================\n// NETWORK ATTRIBUTES (OpenTelemetry Standard)\n// =============================================================================\n\n/** OSI transport layer protocol */\nconst NETWORK_TRANSPORT_ATTRIBUTE = 'network.transport';\n\n/** The version of JSON RPC protocol used */\nconst NETWORK_PROTOCOL_VERSION_ATTRIBUTE = 'network.protocol.version';\n\n/** Client address - domain name if available without reverse DNS lookup; otherwise, IP address or Unix domain socket name */\nconst CLIENT_ADDRESS_ATTRIBUTE = 'client.address';\n\n/** Client port number */\nconst CLIENT_PORT_ATTRIBUTE = 'client.port';\n\n// =============================================================================\n// SENTRY-SPECIFIC MCP ATTRIBUTE VALUES\n// =============================================================================\n\n/** Sentry operation value for MCP server spans */\nconst MCP_SERVER_OP_VALUE = 'mcp.server';\n\n/**\n * Sentry operation value for client-to-server notifications\n * Following OpenTelemetry MCP semantic conventions\n */\nconst MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE = 'mcp.notification.client_to_server';\n\n/**\n * Sentry operation value for server-to-client notifications\n * Following OpenTelemetry MCP semantic conventions\n */\nconst MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE = 'mcp.notification.server_to_client';\n\n/** Sentry origin value for MCP function spans */\nconst MCP_FUNCTION_ORIGIN_VALUE = 'auto.function.mcp_server';\n\n/** Sentry origin value for MCP notification spans */\nconst MCP_NOTIFICATION_ORIGIN_VALUE = 'auto.mcp.notification';\n\n/** Sentry source value for MCP route spans */\nconst MCP_ROUTE_SOURCE_VALUE = 'route';\n\nexport { CLIENT_ADDRESS_ATTRIBUTE, CLIENT_PORT_ATTRIBUTE, MCP_FUNCTION_ORIGIN_VALUE, MCP_LOGGING_DATA_TYPE_ATTRIBUTE, MCP_LOGGING_LEVEL_ATTRIBUTE, MCP_LOGGING_LOGGER_ATTRIBUTE, MCP_LOGGING_MESSAGE_ATTRIBUTE, MCP_METHOD_NAME_ATTRIBUTE, MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE, MCP_NOTIFICATION_ORIGIN_VALUE, MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE, MCP_PROMPT_NAME_ATTRIBUTE, MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE, MCP_PROMPT_RESULT_MESSAGE_CONTENT_ATTRIBUTE, MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE, MCP_PROMPT_RESULT_PREFIX, MCP_PROTOCOL_VERSION_ATTRIBUTE, MCP_REQUEST_ARGUMENT, MCP_REQUEST_ID_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE, MCP_ROUTE_SOURCE_VALUE, MCP_SERVER_NAME_ATTRIBUTE, MCP_SERVER_OP_VALUE, MCP_SERVER_TITLE_ATTRIBUTE, MCP_SERVER_VERSION_ATTRIBUTE, MCP_SESSION_ID_ATTRIBUTE, MCP_TOOL_NAME_ATTRIBUTE, MCP_TOOL_RESULT_CONTENT_ATTRIBUTE, MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE, MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE, MCP_TOOL_RESULT_PREFIX, MCP_TRANSPORT_ATTRIBUTE, NETWORK_PROTOCOL_VERSION_ATTRIBUTE, NETWORK_TRANSPORT_ATTRIBUTE };\n//# sourceMappingURL=attributes.js.map\n","import { MCP_REQUEST_ARGUMENT, MCP_TOOL_RESULT_PREFIX, MCP_PROMPT_RESULT_PREFIX, CLIENT_ADDRESS_ATTRIBUTE, CLIENT_PORT_ATTRIBUTE, MCP_LOGGING_MESSAGE_ATTRIBUTE, MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE, MCP_PROMPT_RESULT_MESSAGE_CONTENT_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE, MCP_TOOL_RESULT_CONTENT_ATTRIBUTE } from './attributes.js';\n\n/**\n * PII attributes that should be removed when sendDefaultPii is false\n * @internal\n */\nconst PII_ATTRIBUTES = new Set([\n CLIENT_ADDRESS_ATTRIBUTE,\n CLIENT_PORT_ATTRIBUTE,\n MCP_LOGGING_MESSAGE_ATTRIBUTE,\n MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE,\n MCP_PROMPT_RESULT_MESSAGE_CONTENT_ATTRIBUTE,\n MCP_RESOURCE_URI_ATTRIBUTE,\n MCP_TOOL_RESULT_CONTENT_ATTRIBUTE,\n]);\n\n/**\n * Checks if an attribute key should be considered PII.\n *\n * Returns true for:\n * - Explicit PII attributes (client.address, client.port, mcp.logging.message, etc.)\n * - All request arguments (mcp.request.argument.*)\n * - Tool and prompt result content (mcp.tool.result.*, mcp.prompt.result.*) except metadata\n *\n * Preserves metadata attributes ending with _count, _error, or .is_error as they don't contain sensitive data.\n *\n * @param key - Attribute key to evaluate\n * @returns true if the attribute should be filtered out (is PII), false if it should be preserved\n * @internal\n */\nfunction isPiiAttribute(key) {\n if (PII_ATTRIBUTES.has(key)) {\n return true;\n }\n\n if (key.startsWith(`${MCP_REQUEST_ARGUMENT}.`)) {\n return true;\n }\n\n if (key.startsWith(`${MCP_TOOL_RESULT_PREFIX}.`) || key.startsWith(`${MCP_PROMPT_RESULT_PREFIX}.`)) {\n if (!key.endsWith('_count') && !key.endsWith('_error') && !key.endsWith('.is_error')) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Removes PII attributes from span data when sendDefaultPii is false\n * @param spanData - Raw span attributes\n * @param sendDefaultPii - Whether to include PII data\n * @returns Filtered span attributes\n */\nfunction filterMcpPiiFromSpanData(\n spanData,\n sendDefaultPii,\n) {\n if (sendDefaultPii) {\n return spanData ;\n }\n\n return Object.entries(spanData).reduce(\n (acc, [key, value]) => {\n if (!isPiiAttribute(key)) {\n acc[key] = value ;\n }\n return acc;\n },\n {} ,\n );\n}\n\nexport { filterMcpPiiFromSpanData };\n//# sourceMappingURL=piiFiltering.js.map\n","import { DEBUG_BUILD } from '../../debug-build.js';\nimport { debug } from '../../utils/debug-logger.js';\n\n/**\n * Message validation functions for MCP server instrumentation\n *\n * Provides JSON-RPC 2.0 message type validation and MCP server instance validation.\n */\n\n\n/**\n * Validates if a message is a JSON-RPC request\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC request\n */\nfunction isJsonRpcRequest(message) {\n return (\n typeof message === 'object' &&\n message !== null &&\n 'jsonrpc' in message &&\n (message ).jsonrpc === '2.0' &&\n 'method' in message &&\n 'id' in message\n );\n}\n\n/**\n * Validates if a message is a JSON-RPC notification\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC notification\n */\nfunction isJsonRpcNotification(message) {\n return (\n typeof message === 'object' &&\n message !== null &&\n 'jsonrpc' in message &&\n (message ).jsonrpc === '2.0' &&\n 'method' in message &&\n !('id' in message)\n );\n}\n\n/**\n * Validates if a message is a JSON-RPC response\n * @param message - Message to validate\n * @returns True if message is a JSON-RPC response\n */\nfunction isJsonRpcResponse(message) {\n return (\n typeof message === 'object' &&\n message !== null &&\n 'jsonrpc' in message &&\n (message ).jsonrpc === '2.0' &&\n 'id' in message &&\n ('result' in message || 'error' in message)\n );\n}\n\n/**\n * Validates MCP server instance with type checking\n * @param instance - Object to validate as MCP server instance\n * @returns True if instance has required MCP server methods\n */\nfunction validateMcpServerInstance(instance) {\n if (\n typeof instance === 'object' &&\n instance !== null &&\n 'resource' in instance &&\n 'tool' in instance &&\n 'prompt' in instance &&\n 'connect' in instance\n ) {\n return true;\n }\n DEBUG_BUILD && debug.warn('Did not patch MCP server. Interface is incompatible.');\n return false;\n}\n\n/**\n * Check if the item is a valid content item\n * @param item - The item to check\n * @returns True if the item is a valid content item, false otherwise\n */\nfunction isValidContentItem(item) {\n return item != null && typeof item === 'object';\n}\n\nexport { isJsonRpcNotification, isJsonRpcRequest, isJsonRpcResponse, isValidContentItem, validateMcpServerInstance };\n//# sourceMappingURL=validation.js.map\n","/**\n * Transport-scoped session data storage (only for transports with sessionId)\n * @internal Maps transport instances to session-level data\n */\nconst transportToSessionData = new WeakMap();\n\n/**\n * Stores session data for a transport with sessionId\n * @param transport - MCP transport instance\n * @param sessionData - Session data to store\n */\nfunction storeSessionDataForTransport(transport, sessionData) {\n if (transport.sessionId) {\n transportToSessionData.set(transport, sessionData);\n }\n}\n\n/**\n * Updates session data for a transport with sessionId (merges with existing data)\n * @param transport - MCP transport instance\n * @param partialSessionData - Partial session data to merge with existing data\n */\nfunction updateSessionDataForTransport(transport, partialSessionData) {\n if (transport.sessionId) {\n const existingData = transportToSessionData.get(transport) || {};\n transportToSessionData.set(transport, { ...existingData, ...partialSessionData });\n }\n}\n\n/**\n * Retrieves client information for a transport\n * @param transport - MCP transport instance\n * @returns Client information if available\n */\nfunction getClientInfoForTransport(transport) {\n return transportToSessionData.get(transport)?.clientInfo;\n}\n\n/**\n * Retrieves protocol version for a transport\n * @param transport - MCP transport instance\n * @returns Protocol version if available\n */\nfunction getProtocolVersionForTransport(transport) {\n return transportToSessionData.get(transport)?.protocolVersion;\n}\n\n/**\n * Retrieves full session data for a transport\n * @param transport - MCP transport instance\n * @returns Complete session data if available\n */\nfunction getSessionDataForTransport(transport) {\n return transportToSessionData.get(transport);\n}\n\n/**\n * Cleans up session data for a specific transport (when that transport closes)\n * @param transport - MCP transport instance\n */\nfunction cleanupSessionDataForTransport(transport) {\n transportToSessionData.delete(transport);\n}\n\nexport { cleanupSessionDataForTransport, getClientInfoForTransport, getProtocolVersionForTransport, getSessionDataForTransport, storeSessionDataForTransport, updateSessionDataForTransport };\n//# sourceMappingURL=sessionManagement.js.map\n","import { MCP_PROTOCOL_VERSION_ATTRIBUTE, CLIENT_PORT_ATTRIBUTE, CLIENT_ADDRESS_ATTRIBUTE, MCP_SESSION_ID_ATTRIBUTE, NETWORK_PROTOCOL_VERSION_ATTRIBUTE, NETWORK_TRANSPORT_ATTRIBUTE, MCP_TRANSPORT_ATTRIBUTE, MCP_SERVER_NAME_ATTRIBUTE, MCP_SERVER_TITLE_ATTRIBUTE, MCP_SERVER_VERSION_ATTRIBUTE } from './attributes.js';\nimport { getProtocolVersionForTransport, getClientInfoForTransport, getSessionDataForTransport } from './sessionManagement.js';\nimport { isValidContentItem } from './validation.js';\n\n/**\n * Session and party info extraction functions for MCP server instrumentation\n *\n * Handles extraction of client/server info and session data from MCP messages.\n */\n\n\n/**\n * Extracts and validates PartyInfo from an unknown object\n * @param obj - Unknown object that might contain party info\n * @returns Validated PartyInfo object with only string properties\n */\nfunction extractPartyInfo(obj) {\n const partyInfo = {};\n\n if (isValidContentItem(obj)) {\n if (typeof obj.name === 'string') {\n partyInfo.name = obj.name;\n }\n if (typeof obj.title === 'string') {\n partyInfo.title = obj.title;\n }\n if (typeof obj.version === 'string') {\n partyInfo.version = obj.version;\n }\n }\n\n return partyInfo;\n}\n\n/**\n * Extracts session data from \"initialize\" requests\n * @param request - JSON-RPC \"initialize\" request containing client info and protocol version\n * @returns Session data extracted from request parameters including protocol version and client info\n */\nfunction extractSessionDataFromInitializeRequest(request) {\n const sessionData = {};\n if (isValidContentItem(request.params)) {\n if (typeof request.params.protocolVersion === 'string') {\n sessionData.protocolVersion = request.params.protocolVersion;\n }\n if (request.params.clientInfo) {\n sessionData.clientInfo = extractPartyInfo(request.params.clientInfo);\n }\n }\n return sessionData;\n}\n\n/**\n * Extracts session data from \"initialize\" response\n * @param result - \"initialize\" response result containing server info and protocol version\n * @returns Partial session data extracted from response including protocol version and server info\n */\nfunction extractSessionDataFromInitializeResponse(result) {\n const sessionData = {};\n if (isValidContentItem(result)) {\n if (typeof result.protocolVersion === 'string') {\n sessionData.protocolVersion = result.protocolVersion;\n }\n if (result.serverInfo) {\n sessionData.serverInfo = extractPartyInfo(result.serverInfo);\n }\n }\n return sessionData;\n}\n\n/**\n * Build client attributes from stored client info\n * @param transport - MCP transport instance\n * @returns Client attributes for span instrumentation\n */\nfunction getClientAttributes(transport) {\n const clientInfo = getClientInfoForTransport(transport);\n const attributes = {};\n\n if (clientInfo?.name) {\n attributes['mcp.client.name'] = clientInfo.name;\n }\n if (clientInfo?.title) {\n attributes['mcp.client.title'] = clientInfo.title;\n }\n if (clientInfo?.version) {\n attributes['mcp.client.version'] = clientInfo.version;\n }\n\n return attributes;\n}\n\n/**\n * Build client attributes from PartyInfo directly\n * @param clientInfo - Client party info\n * @returns Client attributes for span instrumentation\n */\nfunction buildClientAttributesFromInfo(clientInfo) {\n const attributes = {};\n\n if (clientInfo?.name) {\n attributes['mcp.client.name'] = clientInfo.name;\n }\n if (clientInfo?.title) {\n attributes['mcp.client.title'] = clientInfo.title;\n }\n if (clientInfo?.version) {\n attributes['mcp.client.version'] = clientInfo.version;\n }\n\n return attributes;\n}\n\n/**\n * Build server attributes from stored server info\n * @param transport - MCP transport instance\n * @returns Server attributes for span instrumentation\n */\nfunction getServerAttributes(transport) {\n const serverInfo = getSessionDataForTransport(transport)?.serverInfo;\n const attributes = {};\n\n if (serverInfo?.name) {\n attributes[MCP_SERVER_NAME_ATTRIBUTE] = serverInfo.name;\n }\n if (serverInfo?.title) {\n attributes[MCP_SERVER_TITLE_ATTRIBUTE] = serverInfo.title;\n }\n if (serverInfo?.version) {\n attributes[MCP_SERVER_VERSION_ATTRIBUTE] = serverInfo.version;\n }\n\n return attributes;\n}\n\n/**\n * Build server attributes from PartyInfo directly\n * @param serverInfo - Server party info\n * @returns Server attributes for span instrumentation\n */\nfunction buildServerAttributesFromInfo(serverInfo) {\n const attributes = {};\n\n if (serverInfo?.name) {\n attributes[MCP_SERVER_NAME_ATTRIBUTE] = serverInfo.name;\n }\n if (serverInfo?.title) {\n attributes[MCP_SERVER_TITLE_ATTRIBUTE] = serverInfo.title;\n }\n if (serverInfo?.version) {\n attributes[MCP_SERVER_VERSION_ATTRIBUTE] = serverInfo.version;\n }\n\n return attributes;\n}\n\n/**\n * Extracts client connection info from extra handler data\n * @param extra - Extra handler data containing connection info\n * @returns Client address and port information\n */\nfunction extractClientInfo(extra)\n\n {\n return {\n address:\n extra?.requestInfo?.remoteAddress ||\n extra?.clientAddress ||\n extra?.request?.ip ||\n extra?.request?.connection?.remoteAddress,\n port: extra?.requestInfo?.remotePort || extra?.clientPort || extra?.request?.connection?.remotePort,\n };\n}\n\n/**\n * Extracts transport types based on transport constructor name\n * @param transport - MCP transport instance\n * @returns Transport type mapping for span attributes\n */\nfunction getTransportTypes(transport) {\n if (!transport?.constructor) {\n return { mcpTransport: 'unknown', networkTransport: 'unknown' };\n }\n const transportName = typeof transport.constructor?.name === 'string' ? transport.constructor.name : 'unknown';\n let networkTransport = 'unknown';\n\n const lowerTransportName = transportName.toLowerCase();\n if (lowerTransportName.includes('stdio')) {\n networkTransport = 'pipe';\n } else if (lowerTransportName.includes('http') || lowerTransportName.includes('sse')) {\n networkTransport = 'tcp';\n }\n\n return {\n mcpTransport: transportName,\n networkTransport,\n };\n}\n\n/**\n * Build transport and network attributes\n * @param transport - MCP transport instance\n * @param extra - Optional extra handler data\n * @returns Transport attributes for span instrumentation\n * @note sessionId may be undefined during initial setup - session should be established by client during initialize flow\n */\nfunction buildTransportAttributes(\n transport,\n extra,\n) {\n const sessionId = transport && 'sessionId' in transport ? transport.sessionId : undefined;\n const clientInfo = extra ? extractClientInfo(extra) : {};\n const { mcpTransport, networkTransport } = getTransportTypes(transport);\n const clientAttributes = getClientAttributes(transport);\n const serverAttributes = getServerAttributes(transport);\n const protocolVersion = getProtocolVersionForTransport(transport);\n\n const attributes = {\n ...(sessionId && { [MCP_SESSION_ID_ATTRIBUTE]: sessionId }),\n ...(clientInfo.address && { [CLIENT_ADDRESS_ATTRIBUTE]: clientInfo.address }),\n ...(clientInfo.port && { [CLIENT_PORT_ATTRIBUTE]: clientInfo.port }),\n [MCP_TRANSPORT_ATTRIBUTE]: mcpTransport,\n [NETWORK_TRANSPORT_ATTRIBUTE]: networkTransport,\n [NETWORK_PROTOCOL_VERSION_ATTRIBUTE]: '2.0',\n ...(protocolVersion && { [MCP_PROTOCOL_VERSION_ATTRIBUTE]: protocolVersion }),\n ...clientAttributes,\n ...serverAttributes,\n };\n\n return attributes;\n}\n\nexport { buildClientAttributesFromInfo, buildServerAttributesFromInfo, buildTransportAttributes, extractClientInfo, extractSessionDataFromInitializeRequest, extractSessionDataFromInitializeResponse, getClientAttributes, getServerAttributes, getTransportTypes };\n//# sourceMappingURL=sessionExtraction.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { SPAN_STATUS_ERROR } from '../../tracing/spanstatus.js';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes.js';\nimport { filterMcpPiiFromSpanData } from './piiFiltering.js';\nimport { extractToolResultAttributes, extractPromptResultAttributes } from './resultExtraction.js';\nimport { extractSessionDataFromInitializeResponse, buildServerAttributesFromInfo } from './sessionExtraction.js';\n\n/**\n * Request-span correlation system for MCP server instrumentation\n *\n * Handles mapping requestId to span data for correlation with handler execution.\n * Uses WeakMap to scope correlation maps per transport instance, preventing\n * request ID collisions between different MCP sessions.\n */\n\n\n/**\n * Transport-scoped correlation system that prevents collisions between different MCP sessions\n * @internal Each transport instance gets its own correlation map, eliminating request ID conflicts\n */\nconst transportToSpanMap = new WeakMap();\n\n/**\n * Gets or creates the span map for a specific transport instance\n * @internal\n * @param transport - MCP transport instance\n * @returns Span map for the transport\n */\nfunction getOrCreateSpanMap(transport) {\n let spanMap = transportToSpanMap.get(transport);\n if (!spanMap) {\n spanMap = new Map();\n transportToSpanMap.set(transport, spanMap);\n }\n return spanMap;\n}\n\n/**\n * Stores span context for later correlation with handler execution\n * @param transport - MCP transport instance\n * @param requestId - Request identifier\n * @param span - Active span to correlate\n * @param method - MCP method name\n */\nfunction storeSpanForRequest(transport, requestId, span, method) {\n const spanMap = getOrCreateSpanMap(transport);\n spanMap.set(requestId, {\n span,\n method,\n startTime: Date.now(),\n });\n}\n\n/**\n * Completes span with results and cleans up correlation\n * @param transport - MCP transport instance\n * @param requestId - Request identifier\n * @param result - Execution result for attribute extraction\n */\nfunction completeSpanWithResults(transport, requestId, result) {\n const spanMap = getOrCreateSpanMap(transport);\n const spanData = spanMap.get(requestId);\n if (spanData) {\n const { span, method } = spanData;\n\n if (method === 'initialize') {\n const sessionData = extractSessionDataFromInitializeResponse(result);\n const serverAttributes = buildServerAttributesFromInfo(sessionData.serverInfo);\n\n const initAttributes = {\n ...serverAttributes,\n };\n if (sessionData.protocolVersion) {\n initAttributes[MCP_PROTOCOL_VERSION_ATTRIBUTE] = sessionData.protocolVersion;\n }\n\n span.setAttributes(initAttributes);\n } else if (method === 'tools/call') {\n const rawToolAttributes = extractToolResultAttributes(result);\n const client = getClient();\n const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n const toolAttributes = filterMcpPiiFromSpanData(rawToolAttributes, sendDefaultPii);\n\n span.setAttributes(toolAttributes);\n } else if (method === 'prompts/get') {\n const rawPromptAttributes = extractPromptResultAttributes(result);\n const client = getClient();\n const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n const promptAttributes = filterMcpPiiFromSpanData(rawPromptAttributes, sendDefaultPii);\n\n span.setAttributes(promptAttributes);\n }\n\n span.end();\n spanMap.delete(requestId);\n }\n}\n\n/**\n * Cleans up pending spans for a specific transport (when that transport closes)\n * @param transport - MCP transport instance\n */\nfunction cleanupPendingSpansForTransport(transport) {\n const spanMap = transportToSpanMap.get(transport);\n if (spanMap) {\n for (const [, spanData] of spanMap) {\n spanData.span.setStatus({\n code: SPAN_STATUS_ERROR,\n message: 'cancelled',\n });\n spanData.span.end();\n }\n spanMap.clear();\n }\n}\n\nexport { cleanupPendingSpansForTransport, completeSpanWithResults, storeSpanForRequest };\n//# sourceMappingURL=correlation.js.map\n","import { MCP_PROMPT_NAME_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE, MCP_TOOL_NAME_ATTRIBUTE, MCP_REQUEST_ARGUMENT } from './attributes.js';\n\n/**\n * Method configuration and request processing for MCP server instrumentation\n */\n\n\n/**\n * Configuration for MCP methods to extract targets and arguments\n * @internal Maps method names to their extraction configuration\n */\nconst METHOD_CONFIGS = {\n 'tools/call': {\n targetField: 'name',\n targetAttribute: MCP_TOOL_NAME_ATTRIBUTE,\n captureArguments: true,\n argumentsField: 'arguments',\n },\n 'resources/read': {\n targetField: 'uri',\n targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n captureUri: true,\n },\n 'resources/subscribe': {\n targetField: 'uri',\n targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n },\n 'resources/unsubscribe': {\n targetField: 'uri',\n targetAttribute: MCP_RESOURCE_URI_ATTRIBUTE,\n },\n 'prompts/get': {\n targetField: 'name',\n targetAttribute: MCP_PROMPT_NAME_ATTRIBUTE,\n captureName: true,\n captureArguments: true,\n argumentsField: 'arguments',\n },\n};\n\n/**\n * Extracts target info from method and params based on method type\n * @param method - MCP method name\n * @param params - Method parameters\n * @returns Target name and attributes for span instrumentation\n */\nfunction extractTargetInfo(\n method,\n params,\n)\n\n {\n const config = METHOD_CONFIGS[method];\n if (!config) {\n return { attributes: {} };\n }\n\n const target =\n config.targetField && typeof params?.[config.targetField] === 'string'\n ? (params[config.targetField] )\n : undefined;\n\n return {\n target,\n attributes: target && config.targetAttribute ? { [config.targetAttribute]: target } : {},\n };\n}\n\n/**\n * Extracts request arguments based on method type\n * @param method - MCP method name\n * @param params - Method parameters\n * @returns Arguments as span attributes with mcp.request.argument prefix\n */\nfunction getRequestArguments(method, params) {\n const args = {};\n const config = METHOD_CONFIGS[method];\n\n if (!config) {\n return args;\n }\n\n if (config.captureArguments && config.argumentsField && params?.[config.argumentsField]) {\n const argumentsObj = params[config.argumentsField];\n if (typeof argumentsObj === 'object' && argumentsObj !== null) {\n for (const [key, value] of Object.entries(argumentsObj )) {\n args[`${MCP_REQUEST_ARGUMENT}.${key.toLowerCase()}`] = JSON.stringify(value);\n }\n }\n }\n\n if (config.captureUri && params?.uri) {\n args[`${MCP_REQUEST_ARGUMENT}.uri`] = JSON.stringify(params.uri);\n }\n\n if (config.captureName && params?.name) {\n args[`${MCP_REQUEST_ARGUMENT}.name`] = JSON.stringify(params.name);\n }\n\n return args;\n}\n\nexport { extractTargetInfo, getRequestArguments };\n//# sourceMappingURL=methodConfig.js.map\n","import { parseStringToURLObject, isURLObjectRelative } from '../../utils/url.js';\nimport { MCP_REQUEST_ID_ATTRIBUTE, MCP_RESOURCE_URI_ATTRIBUTE, MCP_LOGGING_LEVEL_ATTRIBUTE, MCP_LOGGING_LOGGER_ATTRIBUTE, MCP_LOGGING_DATA_TYPE_ATTRIBUTE, MCP_LOGGING_MESSAGE_ATTRIBUTE } from './attributes.js';\nimport { extractTargetInfo, getRequestArguments } from './methodConfig.js';\n\n/**\n * Core attribute extraction and building functions for MCP server instrumentation\n */\n\n\n/**\n * Extracts additional attributes for specific notification types\n * @param method - Notification method name\n * @param params - Notification parameters\n * @returns Method-specific attributes for span instrumentation\n */\nfunction getNotificationAttributes(\n method,\n params,\n) {\n const attributes = {};\n\n switch (method) {\n case 'notifications/cancelled':\n if (params?.requestId) {\n attributes['mcp.cancelled.request_id'] = String(params.requestId);\n }\n if (params?.reason) {\n attributes['mcp.cancelled.reason'] = String(params.reason);\n }\n break;\n\n case 'notifications/message':\n if (params?.level) {\n attributes[MCP_LOGGING_LEVEL_ATTRIBUTE] = String(params.level);\n }\n if (params?.logger) {\n attributes[MCP_LOGGING_LOGGER_ATTRIBUTE] = String(params.logger);\n }\n if (params?.data !== undefined) {\n attributes[MCP_LOGGING_DATA_TYPE_ATTRIBUTE] = typeof params.data;\n if (typeof params.data === 'string') {\n attributes[MCP_LOGGING_MESSAGE_ATTRIBUTE] = params.data;\n } else {\n attributes[MCP_LOGGING_MESSAGE_ATTRIBUTE] = JSON.stringify(params.data);\n }\n }\n break;\n\n case 'notifications/progress':\n if (params?.progressToken) {\n attributes['mcp.progress.token'] = String(params.progressToken);\n }\n if (typeof params?.progress === 'number') {\n attributes['mcp.progress.current'] = params.progress;\n }\n if (typeof params?.total === 'number') {\n attributes['mcp.progress.total'] = params.total;\n if (typeof params?.progress === 'number') {\n attributes['mcp.progress.percentage'] = (params.progress / params.total) * 100;\n }\n }\n if (params?.message) {\n attributes['mcp.progress.message'] = String(params.message);\n }\n break;\n\n case 'notifications/resources/updated':\n if (params?.uri) {\n attributes[MCP_RESOURCE_URI_ATTRIBUTE] = String(params.uri);\n const urlObject = parseStringToURLObject(String(params.uri));\n if (urlObject && !isURLObjectRelative(urlObject)) {\n attributes['mcp.resource.protocol'] = urlObject.protocol.replace(':', '');\n }\n }\n break;\n\n case 'notifications/initialized':\n attributes['mcp.lifecycle.phase'] = 'initialization_complete';\n attributes['mcp.protocol.ready'] = 1;\n break;\n }\n\n return attributes;\n}\n\n/**\n * Build type-specific attributes based on message type\n * @param type - Span type (request or notification)\n * @param message - JSON-RPC message\n * @param params - Optional parameters for attribute extraction\n * @returns Type-specific attributes for span instrumentation\n */\nfunction buildTypeSpecificAttributes(\n type,\n message,\n params,\n) {\n if (type === 'request') {\n const request = message ;\n const targetInfo = extractTargetInfo(request.method, params || {});\n\n return {\n ...(request.id !== undefined && { [MCP_REQUEST_ID_ATTRIBUTE]: String(request.id) }),\n ...targetInfo.attributes,\n ...getRequestArguments(request.method, params || {}),\n };\n }\n\n return getNotificationAttributes(message.method, params || {});\n}\n\nexport { buildTypeSpecificAttributes, getNotificationAttributes };\n//# sourceMappingURL=attributeExtraction.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP } from '../../semanticAttributes.js';\nimport { startSpan } from '../../tracing/trace.js';\nimport { buildTypeSpecificAttributes } from './attributeExtraction.js';\nimport { MCP_SERVER_OP_VALUE, MCP_METHOD_NAME_ATTRIBUTE, MCP_ROUTE_SOURCE_VALUE, MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE, MCP_NOTIFICATION_ORIGIN_VALUE, MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE, MCP_FUNCTION_ORIGIN_VALUE } from './attributes.js';\nimport { extractTargetInfo } from './methodConfig.js';\nimport { filterMcpPiiFromSpanData } from './piiFiltering.js';\nimport { buildTransportAttributes } from './sessionExtraction.js';\n\n/**\n * Span creation and management functions for MCP server instrumentation\n *\n * Provides unified span creation following OpenTelemetry MCP semantic conventions and our opinitionated take on MCP.\n * Handles both request and notification spans with attribute extraction.\n */\n\n\n/**\n * Creates a span name based on the method and target\n * @internal\n * @param method - MCP method name\n * @param target - Optional target identifier\n * @returns Formatted span name\n */\nfunction createSpanName(method, target) {\n return target ? `${method} ${target}` : method;\n}\n\n/**\n * Build Sentry-specific attributes based on span type\n * @internal\n * @param type - Span type configuration\n * @returns Sentry-specific attributes\n */\nfunction buildSentryAttributes(type) {\n let op;\n let origin;\n\n switch (type) {\n case 'request':\n op = MCP_SERVER_OP_VALUE;\n origin = MCP_FUNCTION_ORIGIN_VALUE;\n break;\n case 'notification-incoming':\n op = MCP_NOTIFICATION_CLIENT_TO_SERVER_OP_VALUE;\n origin = MCP_NOTIFICATION_ORIGIN_VALUE;\n break;\n case 'notification-outgoing':\n op = MCP_NOTIFICATION_SERVER_TO_CLIENT_OP_VALUE;\n origin = MCP_NOTIFICATION_ORIGIN_VALUE;\n break;\n }\n\n return {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: op,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n [SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: MCP_ROUTE_SOURCE_VALUE,\n };\n}\n\n/**\n * Unified builder for creating MCP spans\n * @internal\n * @param config - Span configuration\n * @returns Created span\n */\nfunction createMcpSpan(config) {\n const { type, message, transport, extra, callback } = config;\n const { method } = message;\n const params = message.params;\n\n // Determine span name based on type and OTEL conventions\n let spanName;\n if (type === 'request') {\n const targetInfo = extractTargetInfo(method, params || {});\n spanName = createSpanName(method, targetInfo.target);\n } else {\n // For notifications, use method name directly per OpenTelemetry conventions\n spanName = method;\n }\n\n const rawAttributes = {\n ...buildTransportAttributes(transport, extra),\n [MCP_METHOD_NAME_ATTRIBUTE]: method,\n ...buildTypeSpecificAttributes(type, message, params),\n ...buildSentryAttributes(type),\n };\n\n const client = getClient();\n const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n const attributes = filterMcpPiiFromSpanData(rawAttributes, sendDefaultPii) ;\n\n return startSpan(\n {\n name: spanName,\n forceTransaction: true,\n attributes,\n },\n callback,\n );\n}\n\n/**\n * Creates a span for incoming MCP notifications\n * @param jsonRpcMessage - Notification message\n * @param transport - MCP transport instance\n * @param extra - Extra handler data\n * @param callback - Span execution callback\n * @returns Span execution result\n */\nfunction createMcpNotificationSpan(\n jsonRpcMessage,\n transport,\n extra,\n callback,\n) {\n return createMcpSpan({\n type: 'notification-incoming',\n message: jsonRpcMessage,\n transport,\n extra,\n callback,\n });\n}\n\n/**\n * Creates a span for outgoing MCP notifications\n * @param jsonRpcMessage - Notification message\n * @param transport - MCP transport instance\n * @param callback - Span execution callback\n * @returns Span execution result\n */\nfunction createMcpOutgoingNotificationSpan(\n jsonRpcMessage,\n transport,\n callback,\n) {\n return createMcpSpan({\n type: 'notification-outgoing',\n message: jsonRpcMessage,\n transport,\n callback,\n });\n}\n\n/**\n * Builds span configuration for MCP server requests\n * @param jsonRpcMessage - Request message\n * @param transport - MCP transport instance\n * @param extra - Optional extra handler data\n * @returns Span configuration object\n */\nfunction buildMcpServerSpanConfig(\n jsonRpcMessage,\n transport,\n extra,\n)\n\n {\n const { method } = jsonRpcMessage;\n const params = jsonRpcMessage.params;\n\n const targetInfo = extractTargetInfo(method, params || {});\n const spanName = createSpanName(method, targetInfo.target);\n\n const rawAttributes = {\n ...buildTransportAttributes(transport, extra),\n [MCP_METHOD_NAME_ATTRIBUTE]: method,\n ...buildTypeSpecificAttributes('request', jsonRpcMessage, params),\n ...buildSentryAttributes('request'),\n };\n\n const client = getClient();\n const sendDefaultPii = Boolean(client?.getOptions().sendDefaultPii);\n const attributes = filterMcpPiiFromSpanData(rawAttributes, sendDefaultPii) ;\n\n return {\n name: spanName,\n op: MCP_SERVER_OP_VALUE,\n forceTransaction: true,\n attributes,\n };\n}\n\nexport { buildMcpServerSpanConfig, createMcpNotificationSpan, createMcpOutgoingNotificationSpan };\n//# sourceMappingURL=spans.js.map\n","import { fill } from '../../utils/object.js';\nimport { wrapAllMCPHandlers } from './handlers.js';\nimport { wrapTransportOnMessage, wrapTransportSend, wrapTransportOnClose, wrapTransportError } from './transport.js';\nimport { validateMcpServerInstance } from './validation.js';\n\n/**\n * Tracks wrapped MCP server instances to prevent double-wrapping\n * @internal\n */\nconst wrappedMcpServerInstances = new WeakSet();\n\n/**\n * Wraps a MCP Server instance from the `@modelcontextprotocol/sdk` package with Sentry instrumentation.\n *\n * Compatible with versions `^1.9.0` of the `@modelcontextprotocol/sdk` package.\n * Automatically instruments transport methods and handler functions for comprehensive monitoring.\n *\n * @example\n * ```typescript\n * import * as Sentry from '@sentry/core';\n * import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';\n * import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';\n *\n * const server = Sentry.wrapMcpServerWithSentry(\n * new McpServer({ name: \"my-server\", version: \"1.0.0\" })\n * );\n *\n * const transport = new StreamableHTTPServerTransport();\n * await server.connect(transport);\n * ```\n *\n * @param mcpServerInstance - MCP server instance to instrument\n * @returns Instrumented server instance (same reference)\n */\nfunction wrapMcpServerWithSentry(mcpServerInstance) {\n if (wrappedMcpServerInstances.has(mcpServerInstance)) {\n return mcpServerInstance;\n }\n\n if (!validateMcpServerInstance(mcpServerInstance)) {\n return mcpServerInstance;\n }\n\n const serverInstance = mcpServerInstance ;\n\n fill(serverInstance, 'connect', originalConnect => {\n return async function ( transport, ...restArgs) {\n const result = await (originalConnect ).call(\n this,\n transport,\n ...restArgs,\n );\n\n wrapTransportOnMessage(transport);\n wrapTransportSend(transport);\n wrapTransportOnClose(transport);\n wrapTransportError(transport);\n\n return result;\n };\n });\n\n wrapAllMCPHandlers(serverInstance);\n\n wrappedMcpServerInstances.add(mcpServerInstance);\n return mcpServerInstance;\n}\n\nexport { wrapMcpServerWithSentry };\n//# sourceMappingURL=index.js.map\n","import { _INTERNAL_captureLog } from './internal.js';\nexport { fmt } from '../utils/parameterize.js';\n\n/**\n * Capture a log with the given level.\n *\n * @param level - The level of the log.\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., userId: 100.\n * @param scope - The scope to capture the log with.\n * @param severityNumber - The severity number of the log.\n */\nfunction captureLog(\n level,\n message,\n attributes,\n scope,\n severityNumber,\n) {\n _INTERNAL_captureLog({ level, message, attributes, severityNumber }, scope);\n}\n\n/**\n * Additional metadata to capture the log with.\n */\n\n/**\n * @summary Capture a log with the `trace` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { userId: 100, route: '/dashboard' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.trace('User clicked submit button', {\n * buttonId: 'submit-form',\n * formId: 'user-profile',\n * timestamp: Date.now()\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.trace(Sentry.logger.fmt`User ${user} navigated to ${page}`, {\n * userId: '123',\n * sessionId: 'abc-xyz'\n * });\n * ```\n */\nfunction trace(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('trace', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `debug` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { component: 'Header', state: 'loading' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.debug('Component mounted', {\n * component: 'UserProfile',\n * props: { userId: 123 },\n * renderTime: 150\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.debug(Sentry.logger.fmt`API request to ${endpoint} failed`, {\n * statusCode: 404,\n * requestId: 'req-123',\n * duration: 250\n * });\n * ```\n */\nfunction debug(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('debug', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `info` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { feature: 'checkout', status: 'completed' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.info('User completed checkout', {\n * orderId: 'order-123',\n * amount: 99.99,\n * paymentMethod: 'credit_card'\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.info(Sentry.logger.fmt`User ${user} updated profile picture`, {\n * userId: 'user-123',\n * imageSize: '2.5MB',\n * timestamp: Date.now()\n * });\n * ```\n */\nfunction info(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('info', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `warn` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { browser: 'Chrome', version: '91.0' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.warn('Browser compatibility issue detected', {\n * browser: 'Safari',\n * version: '14.0',\n * feature: 'WebRTC',\n * fallback: 'enabled'\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.warn(Sentry.logger.fmt`API endpoint ${endpoint} is deprecated`, {\n * recommendedEndpoint: '/api/v2/users',\n * sunsetDate: '2024-12-31',\n * clientVersion: '1.2.3'\n * });\n * ```\n */\nfunction warn(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('warn', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `error` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { error: 'NetworkError', url: '/api/data' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.error('Failed to load user data', {\n * error: 'NetworkError',\n * url: '/api/users/123',\n * statusCode: 500,\n * retryCount: 3\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.error(Sentry.logger.fmt`Payment processing failed for order ${orderId}`, {\n * error: 'InsufficientFunds',\n * amount: 100.00,\n * currency: 'USD',\n * userId: 'user-456'\n * });\n * ```\n */\nfunction error(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('error', message, attributes, scope);\n}\n\n/**\n * @summary Capture a log with the `fatal` level. Requires the `enableLogs` option to be enabled.\n *\n * @param message - The message to log.\n * @param attributes - Arbitrary structured data that stores information about the log - e.g., { appState: 'corrupted', sessionId: 'abc-123' }.\n * @param metadata - additional metadata to capture the log with.\n *\n * @example\n *\n * ```\n * Sentry.logger.fatal('Application state corrupted', {\n * lastKnownState: 'authenticated',\n * sessionId: 'session-123',\n * timestamp: Date.now(),\n * recoveryAttempted: true\n * });\n * ```\n *\n * @example With template strings\n *\n * ```\n * Sentry.logger.fatal(Sentry.logger.fmt`Critical system failure in ${service}`, {\n * service: 'payment-processor',\n * errorCode: 'CRITICAL_FAILURE',\n * affectedUsers: 150,\n * timestamp: Date.now()\n * });\n * ```\n */\nfunction fatal(\n message,\n attributes,\n { scope } = {},\n) {\n captureLog('fatal', message, attributes, scope);\n}\n\nexport { debug, error, fatal, info, trace, warn };\n//# sourceMappingURL=public-api.js.map\n","import { isPrimitive } from '../utils/is.js';\nimport { normalize } from '../utils/normalize.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\n\n/**\n * Formats the given values into a string.\n *\n * @param values - The values to format.\n * @param normalizeDepth - The depth to normalize the values.\n * @param normalizeMaxBreadth - The max breadth to normalize the values.\n * @returns The formatted string.\n */\nfunction formatConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) {\n return 'util' in GLOBAL_OBJ && typeof (GLOBAL_OBJ ).util.format === 'function'\n ? (GLOBAL_OBJ ).util.format(...values)\n : safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth);\n}\n\n/**\n * Joins the given values into a string.\n *\n * @param values - The values to join.\n * @param normalizeDepth - The depth to normalize the values.\n * @param normalizeMaxBreadth - The max breadth to normalize the values.\n * @returns The joined string.\n */\nfunction safeJoinConsoleArgs(values, normalizeDepth, normalizeMaxBreadth) {\n return values\n .map(value =>\n isPrimitive(value) ? String(value) : JSON.stringify(normalize(value, normalizeDepth, normalizeMaxBreadth)),\n )\n .join(' ');\n}\n\n/**\n * Checks if a string contains console substitution patterns like %s, %d, %i, %f, %o, %O, %c.\n *\n * @param str - The string to check\n * @returns true if the string contains console substitution patterns\n */\nfunction hasConsoleSubstitutions(str) {\n // Match console substitution patterns: %s, %d, %i, %f, %o, %O, %c\n return /%[sdifocO]/.test(str);\n}\n\n/**\n * Creates template attributes for multiple console arguments.\n *\n * @param args - The console arguments\n * @returns An object with template and parameter attributes\n */\nfunction createConsoleTemplateAttributes(firstArg, followingArgs) {\n const attributes = {};\n\n // Create template with placeholders for each argument\n const template = new Array(followingArgs.length).fill('{}').join(' ');\n attributes['sentry.message.template'] = `${firstArg} ${template}`;\n\n // Add each argument as a parameter\n followingArgs.forEach((arg, index) => {\n attributes[`sentry.message.parameter.${index}`] = arg;\n });\n\n return attributes;\n}\n\nexport { createConsoleTemplateAttributes, formatConsoleArgs, hasConsoleSubstitutions, safeJoinConsoleArgs };\n//# sourceMappingURL=utils.js.map\n","import { getClient } from '../currentScopes.js';\nimport { DEBUG_BUILD } from '../debug-build.js';\nimport { addConsoleInstrumentationHandler } from '../instrument/console.js';\nimport { defineIntegration } from '../integration.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../semanticAttributes.js';\nimport { CONSOLE_LEVELS, debug } from '../utils/debug-logger.js';\nimport { _INTERNAL_captureLog } from './internal.js';\nimport { formatConsoleArgs, hasConsoleSubstitutions, createConsoleTemplateAttributes } from './utils.js';\n\nconst INTEGRATION_NAME = 'ConsoleLogs';\n\nconst DEFAULT_ATTRIBUTES = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.log.console',\n};\n\nconst _consoleLoggingIntegration = ((options = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n const { enableLogs, normalizeDepth = 3, normalizeMaxBreadth = 1000 } = client.getOptions();\n if (!enableLogs) {\n DEBUG_BUILD && debug.warn('`enableLogs` is not enabled, ConsoleLogs integration disabled');\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n const firstArg = args[0];\n const followingArgs = args.slice(1);\n\n if (level === 'assert') {\n if (!firstArg) {\n const assertionMessage =\n followingArgs.length > 0\n ? `Assertion failed: ${formatConsoleArgs(followingArgs, normalizeDepth, normalizeMaxBreadth)}`\n : 'Assertion failed';\n _INTERNAL_captureLog({ level: 'error', message: assertionMessage, attributes: DEFAULT_ATTRIBUTES });\n }\n return;\n }\n\n const isLevelLog = level === 'log';\n\n const shouldGenerateTemplate =\n args.length > 1 && typeof args[0] === 'string' && !hasConsoleSubstitutions(args[0]);\n const attributes = {\n ...DEFAULT_ATTRIBUTES,\n ...(shouldGenerateTemplate ? createConsoleTemplateAttributes(firstArg, followingArgs) : {}),\n };\n\n _INTERNAL_captureLog({\n level: isLevelLog ? 'info' : level,\n message: formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth),\n severityNumber: isLevelLog ? 10 : undefined,\n attributes,\n });\n });\n },\n };\n}) ;\n\n/**\n * Captures calls to the `console` API as logs in Sentry. Requires the `enableLogs` option to be enabled.\n *\n * @experimental This feature is experimental and may be changed or removed in future versions.\n *\n * By default the integration instruments `console.debug`, `console.info`, `console.warn`, `console.error`,\n * `console.log`, `console.trace`, and `console.assert`. You can use the `levels` option to customize which\n * levels are captured.\n *\n * @example\n *\n * ```ts\n * import * as Sentry from '@sentry/browser';\n *\n * Sentry.init({\n * enableLogs: true,\n * integrations: [Sentry.consoleLoggingIntegration({ levels: ['error', 'warn'] })],\n * });\n * ```\n */\nconst consoleLoggingIntegration = defineIntegration(_consoleLoggingIntegration);\n\nexport { consoleLoggingIntegration };\n//# sourceMappingURL=console-integration.js.map\n","import { _INTERNAL_captureMetric } from './internal.js';\n\n/**\n * Options for capturing a metric.\n */\n\n/**\n * Capture a metric with the given type, name, and value.\n *\n * @param type - The type of the metric.\n * @param name - The name of the metric.\n * @param value - The value of the metric.\n * @param options - Options for capturing the metric.\n */\nfunction captureMetric(type, name, value, options) {\n _INTERNAL_captureMetric(\n { type, name, value, unit: options?.unit, attributes: options?.attributes },\n { scope: options?.scope },\n );\n}\n\n/**\n * @summary Increment a counter metric. Requires the `_experiments.enableMetrics` option to be enabled.\n *\n * @param name - The name of the counter metric.\n * @param value - The value to increment by (defaults to 1).\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.count('api.requests', 1, {\n * attributes: {\n * endpoint: '/api/users',\n * method: 'GET',\n * status: 200\n * }\n * });\n * ```\n *\n * @example With custom value\n *\n * ```\n * Sentry.metrics.count('items.processed', 5, {\n * attributes: {\n * processor: 'batch-processor',\n * queue: 'high-priority'\n * }\n * });\n * ```\n */\nfunction count(name, value = 1, options) {\n captureMetric('counter', name, value, options);\n}\n\n/**\n * @summary Set a gauge metric to a specific value. Requires the `_experiments.enableMetrics` option to be enabled.\n *\n * @param name - The name of the gauge metric.\n * @param value - The current value of the gauge.\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.gauge('memory.usage', 1024, {\n * unit: 'megabyte',\n * attributes: {\n * process: 'web-server',\n * region: 'us-east-1'\n * }\n * });\n * ```\n *\n * @example Without unit\n *\n * ```\n * Sentry.metrics.gauge('active.connections', 42, {\n * attributes: {\n * server: 'api-1',\n * protocol: 'websocket'\n * }\n * });\n * ```\n */\nfunction gauge(name, value, options) {\n captureMetric('gauge', name, value, options);\n}\n\n/**\n * @summary Record a value in a distribution metric. Requires the `_experiments.enableMetrics` option to be enabled.\n *\n * @param name - The name of the distribution metric.\n * @param value - The value to record in the distribution.\n * @param options - Options for capturing the metric.\n *\n * @example\n *\n * ```\n * Sentry.metrics.distribution('task.duration', 500, {\n * unit: 'millisecond',\n * attributes: {\n * task: 'data-processing',\n * priority: 'high'\n * }\n * });\n * ```\n *\n * @example Without unit\n *\n * ```\n * Sentry.metrics.distribution('batch.size', 100, {\n * attributes: {\n * processor: 'batch-1',\n * type: 'async'\n * }\n * });\n * ```\n */\nfunction distribution(name, value, options) {\n captureMetric('distribution', name, value, options);\n}\n\nexport { count, distribution, gauge };\n//# sourceMappingURL=public-api.js.map\n","import { getClient } from '../currentScopes.js';\nimport { _INTERNAL_captureLog } from '../logs/internal.js';\nimport { formatConsoleArgs } from '../logs/utils.js';\n\n/**\n * Options for the Sentry Consola reporter.\n */\n\nconst DEFAULT_CAPTURED_LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'fatal'];\n\n/**\n * Creates a new Sentry reporter for Consola that forwards logs to Sentry. Requires the `enableLogs` option to be enabled.\n *\n * **Note: This integration supports Consola v3.x only.** The reporter interface and log object structure\n * may differ in other versions of Consola.\n *\n * @param options - Configuration options for the reporter.\n * @returns A Consola reporter that can be added to consola instances.\n *\n * @example\n * ```ts\n * import * as Sentry from '@sentry/node';\n * import { consola } from 'consola';\n *\n * Sentry.init({\n * enableLogs: true,\n * });\n *\n * const sentryReporter = Sentry.createConsolaReporter({\n * // Optional: filter levels to capture\n * levels: ['error', 'warn', 'info'],\n * });\n *\n * consola.addReporter(sentryReporter);\n *\n * // Now consola logs will be captured by Sentry\n * consola.info('This will be sent to Sentry');\n * consola.error('This error will also be sent to Sentry');\n * ```\n */\nfunction createConsolaReporter(options = {}) {\n const levels = new Set(options.levels ?? DEFAULT_CAPTURED_LEVELS);\n const providedClient = options.client;\n\n return {\n log(logObj) {\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n const { type, level, message: consolaMessage, args, tag, date: _date, ...attributes } = logObj;\n\n // Get client - use provided client or current client\n const client = providedClient || getClient();\n if (!client) {\n return;\n }\n\n // Determine the log severity level\n const logSeverityLevel = getLogSeverityLevel(type, level);\n\n // Early exit if this level should not be captured\n if (!levels.has(logSeverityLevel)) {\n return;\n }\n\n const { normalizeDepth = 3, normalizeMaxBreadth = 1000 } = client.getOptions();\n\n // Format the log message using the same approach as consola's basic reporter\n const messageParts = [];\n if (consolaMessage) {\n messageParts.push(consolaMessage);\n }\n if (args && args.length > 0) {\n messageParts.push(formatConsoleArgs(args, normalizeDepth, normalizeMaxBreadth));\n }\n const message = messageParts.join(' ');\n\n // Build attributes\n attributes['sentry.origin'] = 'auto.log.consola';\n\n if (tag) {\n attributes['consola.tag'] = tag;\n }\n\n if (type) {\n attributes['consola.type'] = type;\n }\n\n // Only add level if it's a valid number (not null/undefined)\n if (level != null && typeof level === 'number') {\n attributes['consola.level'] = level;\n }\n\n _INTERNAL_captureLog({\n level: logSeverityLevel,\n message,\n attributes,\n });\n },\n };\n}\n\n// Mapping from consola log types to Sentry log severity levels\nconst CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP = {\n // Consola built-in types\n silent: 'trace',\n fatal: 'fatal',\n error: 'error',\n warn: 'warn',\n log: 'info',\n info: 'info',\n success: 'info',\n fail: 'error',\n ready: 'info',\n start: 'info',\n box: 'info',\n debug: 'debug',\n trace: 'trace',\n verbose: 'debug',\n // Custom types that might exist\n critical: 'fatal',\n notice: 'info',\n};\n\n// Mapping from consola log levels (numbers) to Sentry log severity levels\nconst CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP = {\n 0: 'fatal', // Fatal and Error\n 1: 'warn', // Warnings\n 2: 'info', // Normal logs\n 3: 'info', // Informational logs, success, fail, ready, start, ...\n 4: 'debug', // Debug logs\n 5: 'trace', // Trace logs\n};\n\n/**\n * Determines the log severity level from Consola type and level.\n *\n * @param type - The Consola log type (e.g., 'error', 'warn', 'info')\n * @param level - The Consola numeric log level (0-5) or null for some types like 'verbose'\n * @returns The corresponding Sentry log severity level\n */\nfunction getLogSeverityLevel(type, level) {\n // Handle special case for verbose logs (level can be null with infinite level in Consola)\n if (type === 'verbose') {\n return 'debug';\n }\n\n // Handle silent logs - these should be at trace level\n if (type === 'silent') {\n return 'trace';\n }\n\n // First try to map by type (more specific)\n if (type) {\n const mappedLevel = CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP[type];\n if (mappedLevel) {\n return mappedLevel;\n }\n }\n\n // Fallback to level mapping (handle null level)\n if (typeof level === 'number') {\n const mappedLevel = CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP[level];\n if (mappedLevel) {\n return mappedLevel;\n }\n }\n\n // Default fallback\n return 'info';\n}\n\nexport { createConsolaReporter };\n//# sourceMappingURL=consola.js.map\n","/**\n * OpenAI Integration Telemetry Attributes\n * Based on OpenTelemetry Semantic Conventions for Generative AI\n * @see https://opentelemetry.io/docs/specs/semconv/gen-ai/\n */\n\n// =============================================================================\n// OPENTELEMETRY SEMANTIC CONVENTIONS FOR GENAI\n// =============================================================================\n\n/**\n * The input messages sent to the model\n */\nconst GEN_AI_PROMPT_ATTRIBUTE = 'gen_ai.prompt';\n\n/**\n * The Generative AI system being used\n * For OpenAI, this should always be \"openai\"\n */\nconst GEN_AI_SYSTEM_ATTRIBUTE = 'gen_ai.system';\n\n/**\n * The name of the model as requested\n * Examples: \"gpt-4\", \"gpt-3.5-turbo\"\n */\nconst GEN_AI_REQUEST_MODEL_ATTRIBUTE = 'gen_ai.request.model';\n\n/**\n * Whether streaming was enabled for the request\n */\nconst GEN_AI_REQUEST_STREAM_ATTRIBUTE = 'gen_ai.request.stream';\n\n/**\n * The temperature setting for the model request\n */\nconst GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE = 'gen_ai.request.temperature';\n\n/**\n * The maximum number of tokens requested\n */\nconst GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE = 'gen_ai.request.max_tokens';\n\n/**\n * The frequency penalty setting for the model request\n */\nconst GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE = 'gen_ai.request.frequency_penalty';\n\n/**\n * The presence penalty setting for the model request\n */\nconst GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE = 'gen_ai.request.presence_penalty';\n\n/**\n * The top_p (nucleus sampling) setting for the model request\n */\nconst GEN_AI_REQUEST_TOP_P_ATTRIBUTE = 'gen_ai.request.top_p';\n\n/**\n * The top_k setting for the model request\n */\nconst GEN_AI_REQUEST_TOP_K_ATTRIBUTE = 'gen_ai.request.top_k';\n\n/**\n * The encoding format for the model request\n */\nconst GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE = 'gen_ai.request.encoding_format';\n\n/**\n * The dimensions for the model request\n */\nconst GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE = 'gen_ai.request.dimensions';\n\n/**\n * Array of reasons why the model stopped generating tokens\n */\nconst GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE = 'gen_ai.response.finish_reasons';\n\n/**\n * The name of the model that generated the response\n */\nconst GEN_AI_RESPONSE_MODEL_ATTRIBUTE = 'gen_ai.response.model';\n\n/**\n * The unique identifier for the response\n */\nconst GEN_AI_RESPONSE_ID_ATTRIBUTE = 'gen_ai.response.id';\n\n/**\n * The reason why the model stopped generating tokens\n */\nconst GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE = 'gen_ai.response.stop_reason';\n\n/**\n * The number of tokens used in the prompt\n */\nconst GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.input_tokens';\n\n/**\n * The number of tokens used in the response\n */\nconst GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.output_tokens';\n\n/**\n * The total number of tokens used (input + output)\n */\nconst GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE = 'gen_ai.usage.total_tokens';\n\n/**\n * The operation name\n */\nconst GEN_AI_OPERATION_NAME_ATTRIBUTE = 'gen_ai.operation.name';\n\n/**\n * The prompt messages\n * Only recorded when recordInputs is enabled\n */\nconst GEN_AI_REQUEST_MESSAGES_ATTRIBUTE = 'gen_ai.request.messages';\n\n/**\n * The response text\n * Only recorded when recordOutputs is enabled\n */\nconst GEN_AI_RESPONSE_TEXT_ATTRIBUTE = 'gen_ai.response.text';\n\n/**\n * The available tools from incoming request\n * Only recorded when recordInputs is enabled\n */\nconst GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE = 'gen_ai.request.available_tools';\n\n/**\n * Whether the response is a streaming response\n */\nconst GEN_AI_RESPONSE_STREAMING_ATTRIBUTE = 'gen_ai.response.streaming';\n\n/**\n * The tool calls from the response\n * Only recorded when recordOutputs is enabled\n */\nconst GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'gen_ai.response.tool_calls';\n\n/**\n * The agent name\n */\nconst GEN_AI_AGENT_NAME_ATTRIBUTE = 'gen_ai.agent.name';\n\n/**\n * The pipeline name\n */\nconst GEN_AI_PIPELINE_NAME_ATTRIBUTE = 'gen_ai.pipeline.name';\n\n/**\n * The number of cache creation input tokens used\n */\nconst GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_creation_input_tokens';\n\n/**\n * The number of cache read input tokens used\n */\nconst GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE = 'gen_ai.usage.cache_read_input_tokens';\n\n/**\n * The number of cache write input tokens used\n */\nconst GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE = 'gen_ai.usage.input_tokens.cache_write';\n\n/**\n * The number of cached input tokens that were used\n */\nconst GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE = 'gen_ai.usage.input_tokens.cached';\n\n/**\n * The span operation name for invoking an agent\n */\nconst GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE = 'gen_ai.invoke_agent';\n\n// =============================================================================\n// OPENAI-SPECIFIC ATTRIBUTES\n// =============================================================================\n\n/**\n * The response ID from OpenAI\n */\nconst OPENAI_RESPONSE_ID_ATTRIBUTE = 'openai.response.id';\n\n/**\n * The response model from OpenAI\n */\nconst OPENAI_RESPONSE_MODEL_ATTRIBUTE = 'openai.response.model';\n\n/**\n * The response timestamp from OpenAI (ISO string)\n */\nconst OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'openai.response.timestamp';\n\n/**\n * The number of completion tokens used\n */\nconst OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = 'openai.usage.completion_tokens';\n\n/**\n * The number of prompt tokens used\n */\nconst OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE = 'openai.usage.prompt_tokens';\n\n// =============================================================================\n// OPENAI OPERATIONS\n// =============================================================================\n\n/**\n * OpenAI API operations\n */\nconst OPENAI_OPERATIONS = {\n CHAT: 'chat',\n RESPONSES: 'responses',\n EMBEDDINGS: 'embeddings',\n} ;\n\n// =============================================================================\n// ANTHROPIC AI OPERATIONS\n// =============================================================================\n\n/**\n * The response timestamp from Anthropic AI (ISO string)\n */\nconst ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE = 'anthropic.response.timestamp';\n\nexport { ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE, GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, OPENAI_OPERATIONS, OPENAI_RESPONSE_ID_ATTRIBUTE, OPENAI_RESPONSE_MODEL_ATTRIBUTE, OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE };\n//# sourceMappingURL=gen-ai-attributes.js.map\n","// Global Map to track tool call IDs to their corresponding spans\n// This allows us to capture tool errors and link them to the correct span\nconst toolCallSpanMap = new Map();\n\nexport { toolCallSpanMap };\n//# sourceMappingURL=constants.js.map\n","/**\n * Default maximum size in bytes for GenAI messages.\n * Messages exceeding this limit will be truncated.\n */\nconst DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT = 20000;\n\n/**\n * Message format used by OpenAI and Anthropic APIs.\n */\n\n/**\n * Calculate the UTF-8 byte length of a string.\n */\nconst utf8Bytes = (text) => {\n return new TextEncoder().encode(text).length;\n};\n\n/**\n * Calculate the UTF-8 byte length of a value's JSON representation.\n */\nconst jsonBytes = (value) => {\n return utf8Bytes(JSON.stringify(value));\n};\n\n/**\n * Truncate a string to fit within maxBytes when encoded as UTF-8.\n * Uses binary search for efficiency with multi-byte characters.\n *\n * @param text - The string to truncate\n * @param maxBytes - Maximum byte length (UTF-8 encoded)\n * @returns Truncated string that fits within maxBytes\n */\nfunction truncateTextByBytes(text, maxBytes) {\n if (utf8Bytes(text) <= maxBytes) {\n return text;\n }\n\n let low = 0;\n let high = text.length;\n let bestFit = '';\n\n while (low <= high) {\n const mid = Math.floor((low + high) / 2);\n const candidate = text.slice(0, mid);\n const byteSize = utf8Bytes(candidate);\n\n if (byteSize <= maxBytes) {\n bestFit = candidate;\n low = mid + 1;\n } else {\n high = mid - 1;\n }\n }\n\n return bestFit;\n}\n\n/**\n * Extract text content from a Google GenAI message part.\n * Parts are either plain strings or objects with a text property.\n *\n * @returns The text content\n */\nfunction getPartText(part) {\n if (typeof part === 'string') {\n return part;\n }\n if ('text' in part) return part.text;\n return '';\n}\n\n/**\n * Create a new part with updated text content while preserving the original structure.\n *\n * @param part - Original part (string or object)\n * @param text - New text content\n * @returns New part with updated text\n */\nfunction withPartText(part, text) {\n if (typeof part === 'string') {\n return text;\n }\n return { ...part, text };\n}\n\n/**\n * Check if a message has the OpenAI/Anthropic content format.\n */\nfunction isContentMessage(message) {\n return (\n message !== null &&\n typeof message === 'object' &&\n 'content' in message &&\n typeof (message ).content === 'string'\n );\n}\n\n/**\n * Check if a message has the OpenAI/Anthropic content array format.\n */\nfunction isContentArrayMessage(message) {\n return message !== null && typeof message === 'object' && 'content' in message && Array.isArray(message.content);\n}\n\n/**\n * Check if a content part is an OpenAI/Anthropic media source\n */\nfunction isContentMedia(part) {\n if (!part || typeof part !== 'object') return false;\n\n return (\n isContentMediaSource(part) ||\n hasInlineData(part) ||\n ('media_type' in part && typeof part.media_type === 'string' && 'data' in part) ||\n ('image_url' in part && typeof part.image_url === 'string' && part.image_url.startsWith('data:')) ||\n ('type' in part && (part.type === 'blob' || part.type === 'base64')) ||\n 'b64_json' in part ||\n ('type' in part && 'result' in part && part.type === 'image_generation') ||\n ('uri' in part && typeof part.uri === 'string' && part.uri.startsWith('data:'))\n );\n}\nfunction isContentMediaSource(part) {\n return 'type' in part && typeof part.type === 'string' && 'source' in part && isContentMedia(part.source);\n}\nfunction hasInlineData(part) {\n return (\n 'inlineData' in part &&\n !!part.inlineData &&\n typeof part.inlineData === 'object' &&\n 'data' in part.inlineData &&\n typeof part.inlineData.data === 'string'\n );\n}\n\n/**\n * Check if a message has the Google GenAI parts format.\n */\nfunction isPartsMessage(message) {\n return (\n message !== null &&\n typeof message === 'object' &&\n 'parts' in message &&\n Array.isArray((message ).parts) &&\n (message ).parts.length > 0\n );\n}\n\n/**\n * Truncate a message with `content: string` format (OpenAI/Anthropic).\n *\n * @param message - Message with content property\n * @param maxBytes - Maximum byte limit\n * @returns Array with truncated message, or empty array if it doesn't fit\n */\nfunction truncateContentMessage(message, maxBytes) {\n // Calculate overhead (message structure without content)\n const emptyMessage = { ...message, content: '' };\n const overhead = jsonBytes(emptyMessage);\n const availableForContent = maxBytes - overhead;\n\n if (availableForContent <= 0) {\n return [];\n }\n\n const truncatedContent = truncateTextByBytes(message.content, availableForContent);\n return [{ ...message, content: truncatedContent }];\n}\n\n/**\n * Truncate a message with `parts: [...]` format (Google GenAI).\n * Keeps as many complete parts as possible, only truncating the first part if needed.\n *\n * @param message - Message with parts array\n * @param maxBytes - Maximum byte limit\n * @returns Array with truncated message, or empty array if it doesn't fit\n */\nfunction truncatePartsMessage(message, maxBytes) {\n const { parts } = message;\n\n // Calculate overhead by creating empty text parts\n const emptyParts = parts.map(part => withPartText(part, ''));\n const overhead = jsonBytes({ ...message, parts: emptyParts });\n let remainingBytes = maxBytes - overhead;\n\n if (remainingBytes <= 0) {\n return [];\n }\n\n // Include parts until we run out of space\n const includedParts = [];\n\n for (const part of parts) {\n const text = getPartText(part);\n const textSize = utf8Bytes(text);\n\n if (textSize <= remainingBytes) {\n // Part fits: include it as-is\n includedParts.push(part);\n remainingBytes -= textSize;\n } else if (includedParts.length === 0) {\n // First part doesn't fit: truncate it\n const truncated = truncateTextByBytes(text, remainingBytes);\n if (truncated) {\n includedParts.push(withPartText(part, truncated));\n }\n break;\n } else {\n // Subsequent part doesn't fit: stop here\n break;\n }\n }\n\n /* c8 ignore start\n * for type safety only, algorithm guarantees SOME text included */\n if (includedParts.length <= 0) {\n return [];\n } else {\n /* c8 ignore stop */\n return [{ ...message, parts: includedParts }];\n }\n}\n\n/**\n * Truncate a single message to fit within maxBytes.\n *\n * Supports two message formats:\n * - OpenAI/Anthropic: `{ ..., content: string }`\n * - Google GenAI: `{ ..., parts: Array<string | {text: string} | non-text> }`\n *\n * @param message - The message to truncate\n * @param maxBytes - Maximum byte limit for the message\n * @returns Array containing the truncated message, or empty array if truncation fails\n */\nfunction truncateSingleMessage(message, maxBytes) {\n /* c8 ignore start - unreachable */\n if (!message || typeof message !== 'object') {\n return [];\n }\n /* c8 ignore stop */\n\n if (isContentMessage(message)) {\n return truncateContentMessage(message, maxBytes);\n }\n\n if (isPartsMessage(message)) {\n return truncatePartsMessage(message, maxBytes);\n }\n\n // Unknown message format: cannot truncate safely\n return [];\n}\n\nconst REMOVED_STRING = '[Filtered]';\n\nconst MEDIA_FIELDS = ['image_url', 'data', 'content', 'b64_json', 'result', 'uri'] ;\n\nfunction stripInlineMediaFromSingleMessage(part) {\n const strip = { ...part };\n if (isContentMedia(strip.source)) {\n strip.source = stripInlineMediaFromSingleMessage(strip.source);\n }\n // google genai inline data blob objects\n if (hasInlineData(part)) {\n strip.inlineData = { ...part.inlineData, data: REMOVED_STRING };\n }\n for (const field of MEDIA_FIELDS) {\n if (typeof strip[field] === 'string') strip[field] = REMOVED_STRING;\n }\n return strip;\n}\n\n/**\n * Strip the inline media from message arrays.\n *\n * This returns a stripped message. We do NOT want to mutate the data in place,\n * because of course we still want the actual API/client to handle the media.\n */\nfunction stripInlineMediaFromMessages(messages) {\n const stripped = messages.map(message => {\n let newMessage = undefined;\n if (!!message && typeof message === 'object') {\n if (isContentArrayMessage(message)) {\n newMessage = {\n ...message,\n content: stripInlineMediaFromMessages(message.content),\n };\n } else if ('content' in message && isContentMedia(message.content)) {\n newMessage = {\n ...message,\n content: stripInlineMediaFromSingleMessage(message.content),\n };\n }\n if (isPartsMessage(message)) {\n newMessage = {\n // might have to strip content AND parts\n ...(newMessage ?? message),\n parts: stripInlineMediaFromMessages(message.parts),\n };\n }\n if (isContentMedia(newMessage)) {\n newMessage = stripInlineMediaFromSingleMessage(newMessage);\n } else if (isContentMedia(message)) {\n newMessage = stripInlineMediaFromSingleMessage(message);\n }\n }\n return newMessage ?? message;\n });\n return stripped;\n}\n\n/**\n * Truncate an array of messages to fit within a byte limit.\n *\n * Strategy:\n * - Keeps the newest messages (from the end of the array)\n * - Uses O(n) algorithm: precompute sizes once, then find largest suffix under budget\n * - If no complete messages fit, attempts to truncate the newest single message\n *\n * @param messages - Array of messages to truncate\n * @param maxBytes - Maximum total byte limit for all messages\n * @returns Truncated array of messages\n *\n * @example\n * ```ts\n * const messages = [msg1, msg2, msg3, msg4]; // newest is msg4\n * const truncated = truncateMessagesByBytes(messages, 10000);\n * // Returns [msg3, msg4] if they fit, or [msg4] if only it fits, etc.\n * ```\n */\nfunction truncateMessagesByBytes(messages, maxBytes) {\n // Early return for empty or invalid input\n if (!Array.isArray(messages) || messages.length === 0) {\n return messages;\n }\n\n // strip inline media first. This will often get us below the threshold,\n // while preserving human-readable information about messages sent.\n const stripped = stripInlineMediaFromMessages(messages);\n\n // Fast path: if all messages fit, return as-is\n const totalBytes = jsonBytes(stripped);\n if (totalBytes <= maxBytes) {\n return stripped;\n }\n\n // Precompute each message's JSON size once for efficiency\n const messageSizes = stripped.map(jsonBytes);\n\n // Find the largest suffix (newest messages) that fits within the budget\n let bytesUsed = 0;\n let startIndex = stripped.length; // Index where the kept suffix starts\n\n for (let i = stripped.length - 1; i >= 0; i--) {\n const messageSize = messageSizes[i];\n\n if (messageSize && bytesUsed + messageSize > maxBytes) {\n // Adding this message would exceed the budget\n break;\n }\n\n if (messageSize) {\n bytesUsed += messageSize;\n }\n startIndex = i;\n }\n\n // If no complete messages fit, try truncating just the newest message\n if (startIndex === stripped.length) {\n // we're truncating down to one message, so all others dropped.\n const newestMessage = stripped[stripped.length - 1];\n return truncateSingleMessage(newestMessage, maxBytes);\n }\n\n // Return the suffix that fits\n return stripped.slice(startIndex);\n}\n\n/**\n * Truncate GenAI messages using the default byte limit.\n *\n * Convenience wrapper around `truncateMessagesByBytes` with the default limit.\n *\n * @param messages - Array of messages to truncate\n * @returns Truncated array of messages\n */\nfunction truncateGenAiMessages(messages) {\n return truncateMessagesByBytes(messages, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT);\n}\n\n/**\n * Truncate GenAI string input using the default byte limit.\n *\n * @param input - The string to truncate\n * @returns Truncated string\n */\nfunction truncateGenAiStringInput(input) {\n return truncateTextByBytes(input, DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT);\n}\n\nexport { DEFAULT_GEN_AI_MESSAGES_BYTE_LIMIT, truncateGenAiMessages, truncateGenAiStringInput };\n//# sourceMappingURL=messageTruncation.js.map\n","import { GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE } from './gen-ai-attributes.js';\nimport { truncateGenAiStringInput, truncateGenAiMessages } from './messageTruncation.js';\n\n/**\n * Maps AI method paths to Sentry operation name\n */\nfunction getFinalOperationName(methodPath) {\n if (methodPath.includes('messages')) {\n return 'messages';\n }\n if (methodPath.includes('completions')) {\n return 'completions';\n }\n if (methodPath.includes('models')) {\n return 'models';\n }\n if (methodPath.includes('chat')) {\n return 'chat';\n }\n return methodPath.split('.').pop() || 'unknown';\n}\n\n/**\n * Get the span operation for AI methods\n * Following Sentry's convention: \"gen_ai.{operation_name}\"\n */\nfunction getSpanOperation(methodPath) {\n return `gen_ai.${getFinalOperationName(methodPath)}`;\n}\n\n/**\n * Build method path from current traversal\n */\nfunction buildMethodPath(currentPath, prop) {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param cachedInputTokens - The number of cached input tokens\n * @param cachedOutputTokens - The number of cached output tokens\n */\nfunction setTokenUsageAttributes(\n span,\n promptTokens,\n completionTokens,\n cachedInputTokens,\n cachedOutputTokens,\n) {\n if (promptTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n });\n }\n if (completionTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n });\n }\n if (\n promptTokens !== undefined ||\n completionTokens !== undefined ||\n cachedInputTokens !== undefined ||\n cachedOutputTokens !== undefined\n ) {\n /**\n * Total input tokens in a request is the summation of `input_tokens`,\n * `cache_creation_input_tokens`, and `cache_read_input_tokens`.\n */\n const totalTokens =\n (promptTokens ?? 0) + (completionTokens ?? 0) + (cachedInputTokens ?? 0) + (cachedOutputTokens ?? 0);\n\n span.setAttributes({\n [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n });\n }\n}\n\n/**\n * Get the truncated JSON string for a string or array of strings.\n *\n * @param value - The string or array of strings to truncate\n * @returns The truncated JSON string\n */\nfunction getTruncatedJsonString(value) {\n if (typeof value === 'string') {\n // Some values are already JSON strings, so we don't need to duplicate the JSON parsing\n return truncateGenAiStringInput(value);\n }\n if (Array.isArray(value)) {\n // truncateGenAiMessages returns an array of strings, so we need to stringify it\n const truncatedMessages = truncateGenAiMessages(value);\n return JSON.stringify(truncatedMessages);\n }\n // value is an object, so we need to stringify it\n return JSON.stringify(value);\n}\n\nexport { buildMethodPath, getFinalOperationName, getSpanOperation, getTruncatedJsonString, setTokenUsageAttributes };\n//# sourceMappingURL=utils.js.map\n","/* eslint-disable max-lines */\n/**\n * AI SDK Telemetry Attributes\n * Based on https://ai-sdk.dev/docs/ai-sdk-core/telemetry#collected-data\n */\n\n// =============================================================================\n// COMMON ATTRIBUTES\n// =============================================================================\n\n/**\n * Common attribute for operation name across all functions and spans\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#collected-data\n */\nconst OPERATION_NAME_ATTRIBUTE = 'operation.name';\n\n// =============================================================================\n// SHARED ATTRIBUTES\n// =============================================================================\n\n/**\n * `generateText` function - `ai.generateText` span\n * `streamText` function - `ai.streamText` span\n *\n * The prompt that was used when calling the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamtext-function\n */\nconst AI_PROMPT_ATTRIBUTE = 'ai.prompt';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The JSON schema version of the schema that was passed into the function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nconst AI_SCHEMA_ATTRIBUTE = 'ai.schema';\n\n/**\n * `generateObject` function - `ai.generateObject` span\n * `streamObject` function - `ai.streamObject` span\n *\n * The object that was generated (stringified JSON)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generateobject-function\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#streamobject-function\n */\nconst AI_RESPONSE_OBJECT_ATTRIBUTE = 'ai.response.object';\n\n// =============================================================================\n// GENERATETEXT FUNCTION - UNIQUE ATTRIBUTES\n// =============================================================================\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The text that was generated\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nconst AI_RESPONSE_TEXT_ATTRIBUTE = 'ai.response.text';\n\n/**\n * `generateText` function - `ai.generateText` span\n *\n * The tool calls that were made as part of the generation (stringified JSON)\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nconst AI_RESPONSE_TOOL_CALLS_ATTRIBUTE = 'ai.response.toolCalls';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * The messages that were passed into the provider\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nconst AI_PROMPT_MESSAGES_ATTRIBUTE = 'ai.prompt.messages';\n\n/**\n * `generateText` function - `ai.generateText.doGenerate` span\n *\n * Array of stringified tool definitions\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#generatetext-function\n */\nconst AI_PROMPT_TOOLS_ATTRIBUTE = 'ai.prompt.tools';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The id of the model\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_MODEL_ID_ATTRIBUTE = 'ai.model.id';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * Provider specific metadata returned with the generation response\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE = 'ai.response.providerMetadata';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of cached input tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE = 'ai.usage.cachedInputTokens';\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The functionId that was set through `telemetry.functionId`\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE = 'ai.telemetry.functionId';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of completion tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE = 'ai.usage.completionTokens';\n\n/**\n * Basic LLM span information\n * Multiple spans\n *\n * The number of prompt tokens that were used\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#basic-llm-span-information\n */\nconst AI_USAGE_PROMPT_TOKENS_ATTRIBUTE = 'ai.usage.promptTokens';\n\n// =============================================================================\n// TOOL CALL SPANS\n// =============================================================================\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The name of the tool\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nconst AI_TOOL_CALL_NAME_ATTRIBUTE = 'ai.toolCall.name';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The id of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nconst AI_TOOL_CALL_ID_ATTRIBUTE = 'ai.toolCall.id';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The parameters of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nconst AI_TOOL_CALL_ARGS_ATTRIBUTE = 'ai.toolCall.args';\n\n/**\n * Tool call spans\n * `ai.toolCall` span\n *\n * The result of the tool call\n * @see https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n */\nconst AI_TOOL_CALL_RESULT_ATTRIBUTE = 'ai.toolCall.result';\n\n// =============================================================================\n// PROVIDER METADATA\n// =============================================================================\n\n/**\n * OpenAI Provider Metadata\n * @see https://ai-sdk.dev/providers/ai-sdk-providers/openai\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/openai/src/openai-chat-language-model.ts#L397-L416\n * @see https://github.com/vercel/ai/blob/65e042afde6aad4da9d7a62526ece839eb34f9a5/packages/openai/src/responses/openai-responses-language-model.ts#L377C7-L384\n */\n\nexport { AI_MODEL_ID_ATTRIBUTE, AI_PROMPT_ATTRIBUTE, AI_PROMPT_MESSAGES_ATTRIBUTE, AI_PROMPT_TOOLS_ATTRIBUTE, AI_RESPONSE_OBJECT_ATTRIBUTE, AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE, AI_RESPONSE_TEXT_ATTRIBUTE, AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, AI_SCHEMA_ATTRIBUTE, AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE, AI_TOOL_CALL_ARGS_ATTRIBUTE, AI_TOOL_CALL_ID_ATTRIBUTE, AI_TOOL_CALL_NAME_ATTRIBUTE, AI_TOOL_CALL_RESULT_ATTRIBUTE, AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE, AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, AI_USAGE_PROMPT_TOKENS_ATTRIBUTE, OPERATION_NAME_ATTRIBUTE };\n//# sourceMappingURL=vercel-ai-attributes.js.map\n","import { GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { getTruncatedJsonString } from '../ai/utils.js';\nimport { toolCallSpanMap } from './constants.js';\nimport { AI_PROMPT_ATTRIBUTE, AI_PROMPT_MESSAGES_ATTRIBUTE } from './vercel-ai-attributes.js';\n\n/**\n * Accumulates token data from a span to its parent in the token accumulator map.\n * This function extracts token usage from the current span and adds it to the\n * accumulated totals for its parent span.\n */\nfunction accumulateTokensForParent(span, tokenAccumulator) {\n const parentSpanId = span.parent_span_id;\n if (!parentSpanId) {\n return;\n }\n\n const inputTokens = span.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];\n const outputTokens = span.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE];\n\n if (typeof inputTokens === 'number' || typeof outputTokens === 'number') {\n const existing = tokenAccumulator.get(parentSpanId) || { inputTokens: 0, outputTokens: 0 };\n\n if (typeof inputTokens === 'number') {\n existing.inputTokens += inputTokens;\n }\n if (typeof outputTokens === 'number') {\n existing.outputTokens += outputTokens;\n }\n\n tokenAccumulator.set(parentSpanId, existing);\n }\n}\n\n/**\n * Applies accumulated token data to the `gen_ai.invoke_agent` span.\n * Only immediate children of the `gen_ai.invoke_agent` span are considered,\n * since aggregation will automatically occur for each parent span.\n */\nfunction applyAccumulatedTokens(\n spanOrTrace,\n tokenAccumulator,\n) {\n const accumulated = tokenAccumulator.get(spanOrTrace.span_id);\n if (!accumulated || !spanOrTrace.data) {\n return;\n }\n\n if (accumulated.inputTokens > 0) {\n spanOrTrace.data[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = accumulated.inputTokens;\n }\n if (accumulated.outputTokens > 0) {\n spanOrTrace.data[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = accumulated.outputTokens;\n }\n if (accumulated.inputTokens > 0 || accumulated.outputTokens > 0) {\n spanOrTrace.data['gen_ai.usage.total_tokens'] = accumulated.inputTokens + accumulated.outputTokens;\n }\n}\n\n/**\n * Get the span associated with a tool call ID\n */\nfunction _INTERNAL_getSpanForToolCallId(toolCallId) {\n return toolCallSpanMap.get(toolCallId);\n}\n\n/**\n * Clean up the span mapping for a tool call ID\n */\nfunction _INTERNAL_cleanupToolCallSpan(toolCallId) {\n toolCallSpanMap.delete(toolCallId);\n}\n\n/**\n * Convert an array of tool strings to a JSON string\n */\nfunction convertAvailableToolsToJsonString(tools) {\n const toolObjects = tools.map(tool => {\n if (typeof tool === 'string') {\n try {\n return JSON.parse(tool);\n } catch {\n return tool;\n }\n }\n return tool;\n });\n return JSON.stringify(toolObjects);\n}\n\n/**\n * Convert the prompt string to messages array\n */\nfunction convertPromptToMessages(prompt) {\n try {\n const p = JSON.parse(prompt);\n if (!!p && typeof p === 'object') {\n const { prompt, system } = p;\n if (typeof prompt === 'string' || typeof system === 'string') {\n const messages = [];\n if (typeof system === 'string') {\n messages.push({ role: 'system', content: system });\n }\n if (typeof prompt === 'string') {\n messages.push({ role: 'user', content: prompt });\n }\n return messages;\n }\n }\n // eslint-disable-next-line no-empty\n } catch {}\n return [];\n}\n\n/**\n * Generate a request.messages JSON array from the prompt field in the\n * invoke_agent op\n */\nfunction requestMessagesFromPrompt(span, attributes) {\n if (attributes[AI_PROMPT_ATTRIBUTE]) {\n const truncatedPrompt = getTruncatedJsonString(attributes[AI_PROMPT_ATTRIBUTE] );\n span.setAttribute('gen_ai.prompt', truncatedPrompt);\n }\n const prompt = attributes[AI_PROMPT_ATTRIBUTE];\n if (\n typeof prompt === 'string' &&\n !attributes[GEN_AI_REQUEST_MESSAGES_ATTRIBUTE] &&\n !attributes[AI_PROMPT_MESSAGES_ATTRIBUTE]\n ) {\n const messages = convertPromptToMessages(prompt);\n if (messages.length) span.setAttribute(GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, getTruncatedJsonString(messages));\n }\n}\n\nexport { _INTERNAL_cleanupToolCallSpan, _INTERNAL_getSpanForToolCallId, accumulateTokensForParent, applyAccumulatedTokens, convertAvailableToolsToJsonString, convertPromptToMessages, requestMessagesFromPrompt };\n//# sourceMappingURL=utils.js.map\n","import { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { spanToJSON } from '../../utils/spanUtils.js';\nimport { GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { toolCallSpanMap } from './constants.js';\nimport { accumulateTokensForParent, applyAccumulatedTokens, requestMessagesFromPrompt, convertAvailableToolsToJsonString } from './utils.js';\nimport { AI_TOOL_CALL_NAME_ATTRIBUTE, AI_TOOL_CALL_ID_ATTRIBUTE, AI_MODEL_ID_ATTRIBUTE, AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE, AI_PROMPT_TOOLS_ATTRIBUTE, AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE, AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, AI_USAGE_PROMPT_TOKENS_ATTRIBUTE, AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE, OPERATION_NAME_ATTRIBUTE, AI_PROMPT_MESSAGES_ATTRIBUTE, AI_RESPONSE_TEXT_ATTRIBUTE, AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, AI_RESPONSE_OBJECT_ATTRIBUTE, AI_TOOL_CALL_ARGS_ATTRIBUTE, AI_TOOL_CALL_RESULT_ATTRIBUTE, AI_SCHEMA_ATTRIBUTE } from './vercel-ai-attributes.js';\n\nfunction addOriginToSpan(span, origin) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, origin);\n}\n\n/**\n * Post-process spans emitted by the Vercel AI SDK.\n * This is supposed to be used in `client.on('spanStart', ...)\n */\nfunction onVercelAiSpanStart(span) {\n const { data: attributes, description: name } = spanToJSON(span);\n\n if (!name) {\n return;\n }\n\n // Tool call spans\n // https://ai-sdk.dev/docs/ai-sdk-core/telemetry#tool-call-spans\n if (attributes[AI_TOOL_CALL_NAME_ATTRIBUTE] && attributes[AI_TOOL_CALL_ID_ATTRIBUTE] && name === 'ai.toolCall') {\n processToolCallSpan(span, attributes);\n return;\n }\n\n // The AI model ID must be defined for generate, stream, and embed spans.\n // The provider is optional and may not always be present.\n const aiModelId = attributes[AI_MODEL_ID_ATTRIBUTE];\n if (typeof aiModelId !== 'string' || !aiModelId) {\n return;\n }\n\n processGenerateSpan(span, name, attributes);\n}\n\nfunction vercelAiEventProcessor(event) {\n if (event.type === 'transaction' && event.spans) {\n // Map to accumulate token data by parent span ID\n const tokenAccumulator = new Map();\n\n // First pass: process all spans and accumulate token data\n for (const span of event.spans) {\n processEndedVercelAiSpan(span);\n\n // Accumulate token data for parent spans\n accumulateTokensForParent(span, tokenAccumulator);\n }\n\n // Second pass: apply accumulated token data to parent spans\n for (const span of event.spans) {\n if (span.op !== 'gen_ai.invoke_agent') {\n continue;\n }\n\n applyAccumulatedTokens(span, tokenAccumulator);\n }\n\n // Also apply to root when it is the invoke_agent pipeline\n const trace = event.contexts?.trace;\n if (trace && trace.op === 'gen_ai.invoke_agent') {\n applyAccumulatedTokens(trace, tokenAccumulator);\n }\n }\n\n return event;\n}\n/**\n * Post-process spans emitted by the Vercel AI SDK.\n */\nfunction processEndedVercelAiSpan(span) {\n const { data: attributes, origin } = span;\n\n if (origin !== 'auto.vercelai.otel') {\n return;\n }\n\n renameAttributeKey(attributes, AI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE);\n renameAttributeKey(attributes, AI_USAGE_PROMPT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE);\n renameAttributeKey(attributes, AI_USAGE_CACHED_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE);\n\n // Input tokens is the sum of prompt tokens and cached input tokens\n if (\n typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === 'number' &&\n typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE] === 'number'\n ) {\n attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] =\n attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] + attributes[GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE];\n }\n\n if (\n typeof attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] === 'number' &&\n typeof attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] === 'number'\n ) {\n attributes['gen_ai.usage.total_tokens'] =\n attributes[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] + attributes[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE];\n }\n\n // Convert the available tools array to a JSON string\n if (attributes[AI_PROMPT_TOOLS_ATTRIBUTE] && Array.isArray(attributes[AI_PROMPT_TOOLS_ATTRIBUTE])) {\n attributes[AI_PROMPT_TOOLS_ATTRIBUTE] = convertAvailableToolsToJsonString(\n attributes[AI_PROMPT_TOOLS_ATTRIBUTE] ,\n );\n }\n\n // Rename AI SDK attributes to standardized gen_ai attributes\n renameAttributeKey(attributes, OPERATION_NAME_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE);\n renameAttributeKey(attributes, AI_PROMPT_MESSAGES_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE);\n renameAttributeKey(attributes, AI_RESPONSE_TEXT_ATTRIBUTE, 'gen_ai.response.text');\n renameAttributeKey(attributes, AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, 'gen_ai.response.tool_calls');\n renameAttributeKey(attributes, AI_RESPONSE_OBJECT_ATTRIBUTE, 'gen_ai.response.object');\n renameAttributeKey(attributes, AI_PROMPT_TOOLS_ATTRIBUTE, 'gen_ai.request.available_tools');\n\n renameAttributeKey(attributes, AI_TOOL_CALL_ARGS_ATTRIBUTE, 'gen_ai.tool.input');\n renameAttributeKey(attributes, AI_TOOL_CALL_RESULT_ATTRIBUTE, 'gen_ai.tool.output');\n\n renameAttributeKey(attributes, AI_SCHEMA_ATTRIBUTE, 'gen_ai.request.schema');\n renameAttributeKey(attributes, AI_MODEL_ID_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE);\n\n addProviderMetadataToAttributes(attributes);\n\n // Change attributes namespaced with `ai.X` to `vercel.ai.X`\n for (const key of Object.keys(attributes)) {\n if (key.startsWith('ai.')) {\n renameAttributeKey(attributes, key, `vercel.${key}`);\n }\n }\n}\n\n/**\n * Renames an attribute key in the provided attributes object if the old key exists.\n * This function safely handles null and undefined values.\n */\nfunction renameAttributeKey(attributes, oldKey, newKey) {\n if (attributes[oldKey] != null) {\n attributes[newKey] = attributes[oldKey];\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete attributes[oldKey];\n }\n}\n\nfunction processToolCallSpan(span, attributes) {\n addOriginToSpan(span, 'auto.vercelai.otel');\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.execute_tool');\n renameAttributeKey(attributes, AI_TOOL_CALL_NAME_ATTRIBUTE, 'gen_ai.tool.name');\n renameAttributeKey(attributes, AI_TOOL_CALL_ID_ATTRIBUTE, 'gen_ai.tool.call.id');\n\n // Store the span in our global map using the tool call ID\n // This allows us to capture tool errors and link them to the correct span\n const toolCallId = attributes['gen_ai.tool.call.id'];\n\n if (typeof toolCallId === 'string') {\n toolCallSpanMap.set(toolCallId, span);\n }\n\n // https://opentelemetry.io/docs/specs/semconv/registry/attributes/gen-ai/#gen-ai-tool-type\n if (!attributes['gen_ai.tool.type']) {\n span.setAttribute('gen_ai.tool.type', 'function');\n }\n const toolName = attributes['gen_ai.tool.name'];\n if (toolName) {\n span.updateName(`execute_tool ${toolName}`);\n }\n}\n\nfunction processGenerateSpan(span, name, attributes) {\n addOriginToSpan(span, 'auto.vercelai.otel');\n\n const nameWthoutAi = name.replace('ai.', '');\n span.setAttribute('ai.pipeline.name', nameWthoutAi);\n span.updateName(nameWthoutAi);\n\n // If a telemetry name is set and the span represents a pipeline, use it as the operation name.\n // This name can be set at the request level by adding `experimental_telemetry.functionId`.\n const functionId = attributes[AI_TELEMETRY_FUNCTION_ID_ATTRIBUTE];\n if (functionId && typeof functionId === 'string') {\n span.updateName(`${nameWthoutAi} ${functionId}`);\n span.setAttribute('gen_ai.function_id', functionId);\n }\n\n requestMessagesFromPrompt(span, attributes);\n\n if (attributes[AI_MODEL_ID_ATTRIBUTE] && !attributes[GEN_AI_RESPONSE_MODEL_ATTRIBUTE]) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, attributes[AI_MODEL_ID_ATTRIBUTE]);\n }\n span.setAttribute('ai.streaming', name.includes('stream'));\n\n // Generate Spans\n if (name === 'ai.generateText') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.generateText.doGenerate') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.generate_text');\n span.updateName(`generate_text ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name === 'ai.streamText') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.streamText.doStream') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.stream_text');\n span.updateName(`stream_text ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name === 'ai.generateObject') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.generateObject.doGenerate') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.generate_object');\n span.updateName(`generate_object ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name === 'ai.streamObject') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.streamObject.doStream') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.stream_object');\n span.updateName(`stream_object ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name === 'ai.embed') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.embed.doEmbed') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.embed');\n span.updateName(`embed ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name === 'ai.embedMany') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.invoke_agent');\n return;\n }\n\n if (name === 'ai.embedMany.doEmbed') {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'gen_ai.embed_many');\n span.updateName(`embed_many ${attributes[AI_MODEL_ID_ATTRIBUTE]}`);\n return;\n }\n\n if (name.startsWith('ai.stream')) {\n span.setAttribute(SEMANTIC_ATTRIBUTE_SENTRY_OP, 'ai.run');\n return;\n }\n}\n\n/**\n * Add event processors to the given client to process Vercel AI spans.\n */\nfunction addVercelAiProcessors(client) {\n client.on('spanStart', onVercelAiSpanStart);\n // Note: We cannot do this on `spanEnd`, because the span cannot be mutated anymore at this point\n client.addEventProcessor(Object.assign(vercelAiEventProcessor, { id: 'VercelAiEventProcessor' }));\n}\n\nfunction addProviderMetadataToAttributes(attributes) {\n const providerMetadata = attributes[AI_RESPONSE_PROVIDER_METADATA_ATTRIBUTE] ;\n if (providerMetadata) {\n try {\n const providerMetadataObject = JSON.parse(providerMetadata) ;\n if (providerMetadataObject.openai) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n providerMetadataObject.openai.cachedPromptTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.reasoning',\n providerMetadataObject.openai.reasoningTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_accepted',\n providerMetadataObject.openai.acceptedPredictionTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.output_tokens.prediction_rejected',\n providerMetadataObject.openai.rejectedPredictionTokens,\n );\n setAttributeIfDefined(attributes, 'gen_ai.conversation.id', providerMetadataObject.openai.responseId);\n }\n\n if (providerMetadataObject.anthropic) {\n const cachedInputTokens =\n providerMetadataObject.anthropic.usage?.cache_read_input_tokens ??\n providerMetadataObject.anthropic.cacheReadInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE, cachedInputTokens);\n\n const cacheWriteInputTokens =\n providerMetadataObject.anthropic.usage?.cache_creation_input_tokens ??\n providerMetadataObject.anthropic.cacheCreationInputTokens;\n setAttributeIfDefined(attributes, GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE, cacheWriteInputTokens);\n }\n\n if (providerMetadataObject.bedrock?.usage) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n providerMetadataObject.bedrock.usage.cacheReadInputTokens,\n );\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE,\n providerMetadataObject.bedrock.usage.cacheWriteInputTokens,\n );\n }\n\n if (providerMetadataObject.deepseek) {\n setAttributeIfDefined(\n attributes,\n GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE,\n providerMetadataObject.deepseek.promptCacheHitTokens,\n );\n setAttributeIfDefined(\n attributes,\n 'gen_ai.usage.input_tokens.cache_miss',\n providerMetadataObject.deepseek.promptCacheMissTokens,\n );\n }\n } catch {\n // Ignore\n }\n }\n}\n\n/**\n * Sets an attribute only if the value is not null or undefined.\n */\nfunction setAttributeIfDefined(attributes, key, value) {\n if (value != null) {\n attributes[key] = value;\n }\n}\n\nexport { addVercelAiProcessors };\n//# sourceMappingURL=index.js.map\n","const OPENAI_INTEGRATION_NAME = 'OpenAI';\n\n// https://platform.openai.com/docs/quickstart?api-mode=responses\n// https://platform.openai.com/docs/quickstart?api-mode=chat\nconst INSTRUMENTED_METHODS = ['responses.create', 'chat.completions.create', 'embeddings.create'] ;\nconst RESPONSES_TOOL_CALL_EVENT_TYPES = [\n 'response.output_item.added',\n 'response.function_call_arguments.delta',\n 'response.function_call_arguments.done',\n 'response.output_item.done',\n] ;\nconst RESPONSE_EVENT_TYPES = [\n 'response.created',\n 'response.in_progress',\n 'response.failed',\n 'response.completed',\n 'response.incomplete',\n 'response.queued',\n 'response.output_text.delta',\n ...RESPONSES_TOOL_CALL_EVENT_TYPES,\n] ;\n\nexport { INSTRUMENTED_METHODS, OPENAI_INTEGRATION_NAME, RESPONSES_TOOL_CALL_EVENT_TYPES, RESPONSE_EVENT_TYPES };\n//# sourceMappingURL=constants.js.map\n","import { OPENAI_OPERATIONS, GEN_AI_RESPONSE_ID_ATTRIBUTE, OPENAI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, OPENAI_RESPONSE_MODEL_ATTRIBUTE, OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { INSTRUMENTED_METHODS } from './constants.js';\n\n/**\n * Maps OpenAI method paths to Sentry operation names\n */\nfunction getOperationName(methodPath) {\n if (methodPath.includes('chat.completions')) {\n return OPENAI_OPERATIONS.CHAT;\n }\n if (methodPath.includes('responses')) {\n return OPENAI_OPERATIONS.RESPONSES;\n }\n if (methodPath.includes('embeddings')) {\n return OPENAI_OPERATIONS.EMBEDDINGS;\n }\n return methodPath.split('.').pop() || 'unknown';\n}\n\n/**\n * Get the span operation for OpenAI methods\n * Following Sentry's convention: \"gen_ai.{operation_name}\"\n */\nfunction getSpanOperation(methodPath) {\n return `gen_ai.${getOperationName(methodPath)}`;\n}\n\n/**\n * Check if a method path should be instrumented\n */\nfunction shouldInstrument(methodPath) {\n return INSTRUMENTED_METHODS.includes(methodPath );\n}\n\n/**\n * Build method path from current traversal\n */\nfunction buildMethodPath(currentPath, prop) {\n return currentPath ? `${currentPath}.${prop}` : prop;\n}\n\n/**\n * Check if response is a Chat Completion object\n */\nfunction isChatCompletionResponse(response) {\n return (\n response !== null &&\n typeof response === 'object' &&\n 'object' in response &&\n (response ).object === 'chat.completion'\n );\n}\n\n/**\n * Check if response is a Responses API object\n */\nfunction isResponsesApiResponse(response) {\n return (\n response !== null &&\n typeof response === 'object' &&\n 'object' in response &&\n (response ).object === 'response'\n );\n}\n\n/**\n * Check if response is an Embeddings API object\n */\nfunction isEmbeddingsResponse(response) {\n if (response === null || typeof response !== 'object' || !('object' in response)) {\n return false;\n }\n const responseObject = response ;\n return (\n responseObject.object === 'list' &&\n typeof responseObject.model === 'string' &&\n responseObject.model.toLowerCase().includes('embedding')\n );\n}\n\n/**\n * Check if streaming event is from the Responses API\n */\nfunction isResponsesApiStreamEvent(event) {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'type' in event &&\n typeof (event ).type === 'string' &&\n ((event ).type ).startsWith('response.')\n );\n}\n\n/**\n * Check if streaming event is a chat completion chunk\n */\nfunction isChatCompletionChunk(event) {\n return (\n event !== null &&\n typeof event === 'object' &&\n 'object' in event &&\n (event ).object === 'chat.completion.chunk'\n );\n}\n\n/**\n * Add attributes for Chat Completion responses\n */\nfunction addChatCompletionAttributes(\n span,\n response,\n recordOutputs,\n) {\n setCommonResponseAttributes(span, response.id, response.model, response.created);\n if (response.usage) {\n setTokenUsageAttributes(\n span,\n response.usage.prompt_tokens,\n response.usage.completion_tokens,\n response.usage.total_tokens,\n );\n }\n if (Array.isArray(response.choices)) {\n const finishReasons = response.choices\n .map(choice => choice.finish_reason)\n .filter((reason) => reason !== null);\n if (finishReasons.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(finishReasons),\n });\n }\n\n // Extract tool calls from all choices (only if recordOutputs is true)\n if (recordOutputs) {\n const toolCalls = response.choices\n .map(choice => choice.message?.tool_calls)\n .filter(calls => Array.isArray(calls) && calls.length > 0)\n .flat();\n\n if (toolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls),\n });\n }\n }\n }\n}\n\n/**\n * Add attributes for Responses API responses\n */\nfunction addResponsesApiAttributes(span, response, recordOutputs) {\n setCommonResponseAttributes(span, response.id, response.model, response.created_at);\n if (response.status) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify([response.status]),\n });\n }\n if (response.usage) {\n setTokenUsageAttributes(\n span,\n response.usage.input_tokens,\n response.usage.output_tokens,\n response.usage.total_tokens,\n );\n }\n\n // Extract function calls from output (only if recordOutputs is true)\n if (recordOutputs) {\n const responseWithOutput = response ;\n if (Array.isArray(responseWithOutput.output) && responseWithOutput.output.length > 0) {\n // Filter for function_call type objects in the output array\n const functionCalls = responseWithOutput.output.filter(\n (item) =>\n typeof item === 'object' && item !== null && (item ).type === 'function_call',\n );\n\n if (functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls),\n });\n }\n }\n }\n}\n\n/**\n * Add attributes for Embeddings API responses\n */\nfunction addEmbeddingsAttributes(span, response) {\n span.setAttributes({\n [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n });\n\n if (response.usage) {\n setTokenUsageAttributes(span, response.usage.prompt_tokens, undefined, response.usage.total_tokens);\n }\n}\n\n/**\n * Set token usage attributes\n * @param span - The span to add attributes to\n * @param promptTokens - The number of prompt tokens\n * @param completionTokens - The number of completion tokens\n * @param totalTokens - The number of total tokens\n */\nfunction setTokenUsageAttributes(\n span,\n promptTokens,\n completionTokens,\n totalTokens,\n) {\n if (promptTokens !== undefined) {\n span.setAttributes({\n [OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE]: promptTokens,\n [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: promptTokens,\n });\n }\n if (completionTokens !== undefined) {\n span.setAttributes({\n [OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE]: completionTokens,\n [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: completionTokens,\n });\n }\n if (totalTokens !== undefined) {\n span.setAttributes({\n [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: totalTokens,\n });\n }\n}\n\n/**\n * Set common response attributes\n * @param span - The span to add attributes to\n * @param id - The response id\n * @param model - The response model\n * @param timestamp - The response timestamp\n */\nfunction setCommonResponseAttributes(span, id, model, timestamp) {\n span.setAttributes({\n [OPENAI_RESPONSE_ID_ATTRIBUTE]: id,\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: id,\n });\n span.setAttributes({\n [OPENAI_RESPONSE_MODEL_ATTRIBUTE]: model,\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: model,\n });\n span.setAttributes({\n [OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(timestamp * 1000).toISOString(),\n });\n}\n\nexport { addChatCompletionAttributes, addEmbeddingsAttributes, addResponsesApiAttributes, buildMethodPath, getOperationName, getSpanOperation, isChatCompletionChunk, isChatCompletionResponse, isEmbeddingsResponse, isResponsesApiResponse, isResponsesApiStreamEvent, setCommonResponseAttributes, setTokenUsageAttributes, shouldInstrument };\n//# sourceMappingURL=utils.js.map\n","import { captureException } from '../../exports.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { RESPONSE_EVENT_TYPES } from './constants.js';\nimport { isChatCompletionChunk, isResponsesApiStreamEvent, setCommonResponseAttributes, setTokenUsageAttributes } from './utils.js';\n\n/**\n * State object used to accumulate information from a stream of OpenAI events/chunks.\n */\n\n/**\n * Processes tool calls from a chat completion chunk delta.\n * Follows the pattern: accumulate by index, then convert to array at the end.\n *\n * @param toolCalls - Array of tool calls from the delta.\n * @param state - The current streaming state to update.\n *\n * @see https://platform.openai.com/docs/guides/function-calling#streaming\n */\nfunction processChatCompletionToolCalls(toolCalls, state) {\n for (const toolCall of toolCalls) {\n const index = toolCall.index;\n if (index === undefined || !toolCall.function) continue;\n\n // Initialize tool call if this is the first chunk for this index\n if (!(index in state.chatCompletionToolCalls)) {\n state.chatCompletionToolCalls[index] = {\n ...toolCall,\n function: {\n name: toolCall.function.name,\n arguments: toolCall.function.arguments || '',\n },\n };\n } else {\n // Accumulate function arguments from subsequent chunks\n const existingToolCall = state.chatCompletionToolCalls[index];\n if (toolCall.function.arguments && existingToolCall?.function) {\n existingToolCall.function.arguments += toolCall.function.arguments;\n }\n }\n }\n}\n\n/**\n * Processes a single OpenAI ChatCompletionChunk event, updating the streaming state.\n *\n * @param chunk - The ChatCompletionChunk event to process.\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n */\nfunction processChatCompletionChunk(chunk, state, recordOutputs) {\n state.responseId = chunk.id ?? state.responseId;\n state.responseModel = chunk.model ?? state.responseModel;\n state.responseTimestamp = chunk.created ?? state.responseTimestamp;\n\n if (chunk.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = chunk.usage.prompt_tokens;\n state.completionTokens = chunk.usage.completion_tokens;\n state.totalTokens = chunk.usage.total_tokens;\n }\n\n for (const choice of chunk.choices ?? []) {\n if (recordOutputs) {\n if (choice.delta?.content) {\n state.responseTexts.push(choice.delta.content);\n }\n\n // Handle tool calls from delta\n if (choice.delta?.tool_calls) {\n processChatCompletionToolCalls(choice.delta.tool_calls, state);\n }\n }\n if (choice.finish_reason) {\n state.finishReasons.push(choice.finish_reason);\n }\n }\n}\n\n/**\n * Processes a single OpenAI Responses API streaming event, updating the streaming state and span.\n *\n * @param streamEvent - The event to process (may be an error or unknown object).\n * @param state - The current streaming state to update.\n * @param recordOutputs - Whether to record output text fragments.\n * @param span - The span to update with error status if needed.\n */\nfunction processResponsesApiEvent(\n streamEvent,\n state,\n recordOutputs,\n span,\n) {\n if (!(streamEvent && typeof streamEvent === 'object')) {\n state.eventTypes.push('unknown:non-object');\n return;\n }\n if (streamEvent instanceof Error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(streamEvent, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream-response',\n },\n });\n return;\n }\n\n if (!('type' in streamEvent)) return;\n const event = streamEvent ;\n\n if (!RESPONSE_EVENT_TYPES.includes(event.type)) {\n state.eventTypes.push(event.type);\n return;\n }\n\n // Handle output text delta\n if (recordOutputs) {\n // Handle tool call events for Responses API\n if (event.type === 'response.output_item.done' && 'item' in event) {\n state.responsesApiToolCalls.push(event.item);\n }\n\n if (event.type === 'response.output_text.delta' && 'delta' in event && event.delta) {\n state.responseTexts.push(event.delta);\n return;\n }\n }\n\n if ('response' in event) {\n const { response } = event ;\n state.responseId = response.id ?? state.responseId;\n state.responseModel = response.model ?? state.responseModel;\n state.responseTimestamp = response.created_at ?? state.responseTimestamp;\n\n if (response.usage) {\n // For stream responses, the input tokens remain constant across all events in the stream.\n // Output tokens, however, are only finalized in the last event.\n // Since we can't guarantee that the last event will include usage data or even be a typed event,\n // we update the output token values on every event that includes them.\n // This ensures that output token usage is always set, even if the final event lacks it.\n state.promptTokens = response.usage.input_tokens;\n state.completionTokens = response.usage.output_tokens;\n state.totalTokens = response.usage.total_tokens;\n }\n\n if (response.status) {\n state.finishReasons.push(response.status);\n }\n\n if (recordOutputs && response.output_text) {\n state.responseTexts.push(response.output_text);\n }\n }\n}\n\n/**\n * Instruments a stream of OpenAI events, updating the provided span with relevant attributes and\n * optionally recording output text. This function yields each event from the input stream as it is processed.\n *\n * @template T - The type of events in the stream.\n * @param stream - The async iterable stream of events to instrument.\n * @param span - The span to add attributes to and to finish at the end of the stream.\n * @param recordOutputs - Whether to record output text fragments in the span.\n * @returns An async generator yielding each event from the input stream.\n */\nasync function* instrumentStream(\n stream,\n span,\n recordOutputs,\n) {\n const state = {\n eventTypes: [],\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n responseTimestamp: 0,\n promptTokens: undefined,\n completionTokens: undefined,\n totalTokens: undefined,\n chatCompletionToolCalls: {},\n responsesApiToolCalls: [],\n };\n\n try {\n for await (const event of stream) {\n if (isChatCompletionChunk(event)) {\n processChatCompletionChunk(event , state, recordOutputs);\n } else if (isResponsesApiStreamEvent(event)) {\n processResponsesApiEvent(event , state, recordOutputs, span);\n }\n yield event;\n }\n } finally {\n setCommonResponseAttributes(span, state.responseId, state.responseModel, state.responseTimestamp);\n setTokenUsageAttributes(span, state.promptTokens, state.completionTokens, state.totalTokens);\n\n span.setAttributes({\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n });\n\n if (state.finishReasons.length) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n });\n }\n\n if (recordOutputs && state.responseTexts.length) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n });\n }\n\n // Set tool calls attribute if any were accumulated\n const chatCompletionToolCallsArray = Object.values(state.chatCompletionToolCalls);\n const allToolCalls = [...chatCompletionToolCallsArray, ...state.responsesApiToolCalls];\n\n if (allToolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(allToolCalls),\n });\n }\n\n span.end();\n }\n}\n\nexport { instrumentStream };\n//# sourceMappingURL=streaming.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { captureException } from '../../exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { startSpanManual, startSpan } from '../trace.js';\nimport { GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE, GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { getTruncatedJsonString } from '../ai/utils.js';\nimport { instrumentStream } from './streaming.js';\nimport { shouldInstrument, getOperationName, getSpanOperation, isChatCompletionResponse, addChatCompletionAttributes, isResponsesApiResponse, addResponsesApiAttributes, isEmbeddingsResponse, addEmbeddingsAttributes, buildMethodPath } from './utils.js';\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args, methodPath) {\n const attributes = {\n [GEN_AI_SYSTEM_ATTRIBUTE]: 'openai',\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getOperationName(methodPath),\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.openai',\n };\n\n // Chat completion API accepts web_search_options and tools as parameters\n // we append web search options to the available tools to capture all tool calls\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] ;\n\n const tools = Array.isArray(params.tools) ? params.tools : [];\n const hasWebSearchOptions = params.web_search_options && typeof params.web_search_options === 'object';\n const webSearchOptions = hasWebSearchOptions\n ? [{ type: 'web_search_options', ...(params.web_search_options ) }]\n : [];\n\n const availableTools = [...tools, ...webSearchOptions];\n\n if (availableTools.length > 0) {\n attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(availableTools);\n }\n }\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] ;\n\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n if ('frequency_penalty' in params)\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n if ('presence_penalty' in params) attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = params.presence_penalty;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('encoding_format' in params) attributes[GEN_AI_REQUEST_ENCODING_FORMAT_ATTRIBUTE] = params.encoding_format;\n if ('dimensions' in params) attributes[GEN_AI_REQUEST_DIMENSIONS_ATTRIBUTE] = params.dimensions;\n } else {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n }\n\n return attributes;\n}\n\n/**\n * Add response attributes to spans\n * This currently supports both Chat Completion and Responses API responses\n */\nfunction addResponseAttributes(span, result, recordOutputs) {\n if (!result || typeof result !== 'object') return;\n\n const response = result ;\n\n if (isChatCompletionResponse(response)) {\n addChatCompletionAttributes(span, response, recordOutputs);\n if (recordOutputs && response.choices?.length) {\n const responseTexts = response.choices.map(choice => choice.message?.content || '');\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(responseTexts) });\n }\n } else if (isResponsesApiResponse(response)) {\n addResponsesApiAttributes(span, response, recordOutputs);\n if (recordOutputs && response.output_text) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.output_text });\n }\n } else if (isEmbeddingsResponse(response)) {\n addEmbeddingsAttributes(span, response);\n }\n}\n\n// Extract and record AI request inputs, if present. This is intentionally separate from response attributes.\nfunction addRequestAttributes(span, params) {\n if ('messages' in params) {\n const truncatedMessages = getTruncatedJsonString(params.messages);\n span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedMessages });\n }\n if ('input' in params) {\n const truncatedInput = getTruncatedJsonString(params.input);\n span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedInput });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod(\n originalMethod,\n methodPath,\n context,\n options,\n) {\n return async function instrumentedMethod(...args) {\n const requestAttributes = extractRequestAttributes(args, methodPath);\n const model = (requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ) || 'unknown';\n const operationName = getOperationName(methodPath);\n\n const params = args[0] ;\n const isStreamRequested = params && typeof params === 'object' && params.stream === true;\n\n if (isStreamRequested) {\n // For streaming responses, use manual span management to properly handle the async generator lifecycle\n return startSpanManual(\n {\n name: `${operationName} ${model} stream-response`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes ,\n },\n async (span) => {\n try {\n if (options.recordInputs && params) {\n addRequestAttributes(span, params);\n }\n\n const result = await originalMethod.apply(context, args);\n\n return instrumentStream(\n result ,\n span,\n options.recordOutputs ?? false,\n ) ;\n } catch (error) {\n // For streaming requests that fail before stream creation, we still want to record\n // them as streaming requests but end the span gracefully\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai.stream',\n data: {\n function: methodPath,\n },\n },\n });\n span.end();\n throw error;\n }\n },\n );\n } else {\n // Non-streaming responses\n return startSpan(\n {\n name: `${operationName} ${model}`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes ,\n },\n async (span) => {\n try {\n if (options.recordInputs && params) {\n addRequestAttributes(span, params);\n }\n\n const result = await originalMethod.apply(context, args);\n addResponseAttributes(span, result, options.recordOutputs);\n return result;\n } catch (error) {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.openai',\n data: {\n function: methodPath,\n },\n },\n });\n throw error;\n }\n },\n );\n }\n };\n}\n\n/**\n * Create a deep proxy for OpenAI client instrumentation\n */\nfunction createDeepProxy(target, currentPath = '', options) {\n return new Proxy(target, {\n get(obj, prop) {\n const value = (obj )[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n if (typeof value === 'function' && shouldInstrument(methodPath)) {\n return instrumentMethod(value , methodPath, obj, options);\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n // which is required for accessing private class fields (e.g. #baseURL) in OpenAI SDK v5.\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) ;\n}\n\n/**\n * Instrument an OpenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n */\nfunction instrumentOpenAiClient(client, options) {\n const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n\n const _options = {\n recordInputs: sendDefaultPii,\n recordOutputs: sendDefaultPii,\n ...options,\n };\n\n return createDeepProxy(client, '', _options);\n}\n\nexport { instrumentOpenAiClient };\n//# sourceMappingURL=index.js.map\n","import { captureException } from '../../exports.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { setTokenUsageAttributes } from '../ai/utils.js';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\n\n/**\n * Checks if an event is an error event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n * @returns Whether an error occurred\n */\n\nfunction isErrorEvent(event, span) {\n if ('type' in event && typeof event.type === 'string') {\n // If the event is an error, set the span status and capture the error\n // These error events are not rejected by the API by default, but are sent as metadata of the response\n if (event.type === 'error') {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: event.error?.type ?? 'internal_error' });\n captureException(event.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n return true;\n }\n }\n return false;\n}\n\n/**\n * Processes the message metadata of an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n */\n\nfunction handleMessageMetadata(event, state) {\n // The token counts shown in the usage field of the message_delta event are cumulative.\n // @see https://docs.anthropic.com/en/docs/build-with-claude/streaming#event-types\n if (event.type === 'message_delta' && event.usage) {\n if ('output_tokens' in event.usage && typeof event.usage.output_tokens === 'number') {\n state.completionTokens = event.usage.output_tokens;\n }\n }\n\n if (event.message) {\n const message = event.message;\n\n if (message.id) state.responseId = message.id;\n if (message.model) state.responseModel = message.model;\n if (message.stop_reason) state.finishReasons.push(message.stop_reason);\n\n if (message.usage) {\n if (typeof message.usage.input_tokens === 'number') state.promptTokens = message.usage.input_tokens;\n if (typeof message.usage.cache_creation_input_tokens === 'number')\n state.cacheCreationInputTokens = message.usage.cache_creation_input_tokens;\n if (typeof message.usage.cache_read_input_tokens === 'number')\n state.cacheReadInputTokens = message.usage.cache_read_input_tokens;\n }\n }\n}\n\n/**\n * Handle start of a content block (e.g., tool_use)\n */\nfunction handleContentBlockStart(event, state) {\n if (event.type !== 'content_block_start' || typeof event.index !== 'number' || !event.content_block) return;\n if (event.content_block.type === 'tool_use' || event.content_block.type === 'server_tool_use') {\n state.activeToolBlocks[event.index] = {\n id: event.content_block.id,\n name: event.content_block.name,\n inputJsonParts: [],\n };\n }\n}\n\n/**\n * Handle deltas of a content block, including input_json_delta for tool_use\n */\nfunction handleContentBlockDelta(\n event,\n state,\n recordOutputs,\n) {\n if (event.type !== 'content_block_delta' || !event.delta) return;\n\n // Accumulate tool_use input JSON deltas only when we have an index and an active tool block\n if (\n typeof event.index === 'number' &&\n 'partial_json' in event.delta &&\n typeof event.delta.partial_json === 'string'\n ) {\n const active = state.activeToolBlocks[event.index];\n if (active) {\n active.inputJsonParts.push(event.delta.partial_json);\n }\n }\n\n // Accumulate streamed response text regardless of index\n if (recordOutputs && typeof event.delta.text === 'string') {\n state.responseTexts.push(event.delta.text);\n }\n}\n\n/**\n * Handle stop of a content block; finalize tool_use entries\n */\nfunction handleContentBlockStop(event, state) {\n if (event.type !== 'content_block_stop' || typeof event.index !== 'number') return;\n\n const active = state.activeToolBlocks[event.index];\n if (!active) return;\n\n const raw = active.inputJsonParts.join('');\n let parsedInput;\n\n try {\n parsedInput = raw ? JSON.parse(raw) : {};\n } catch {\n parsedInput = { __unparsed: raw };\n }\n\n state.toolCalls.push({\n type: 'tool_use',\n id: active.id,\n name: active.name,\n input: parsedInput,\n });\n\n // eslint-disable-next-line @typescript-eslint/no-dynamic-delete\n delete state.activeToolBlocks[event.index];\n}\n\n/**\n * Processes an event\n * @param event - The event to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processEvent(\n event,\n state,\n recordOutputs,\n span,\n) {\n if (!(event && typeof event === 'object')) {\n return;\n }\n\n const isError = isErrorEvent(event, span);\n if (isError) return;\n\n handleMessageMetadata(event, state);\n\n // Tool call events are sent via 3 separate events:\n // - content_block_start (start of the tool call)\n // - content_block_delta (delta aka input of the tool call)\n // - content_block_stop (end of the tool call)\n // We need to handle them all to capture the full tool call.\n handleContentBlockStart(event, state);\n handleContentBlockDelta(event, state, recordOutputs);\n handleContentBlockStop(event, state);\n}\n\n/**\n * Finalizes span attributes when stream processing completes\n */\nfunction finalizeStreamSpan(state, span, recordOutputs) {\n if (!span.isRecording()) {\n return;\n }\n\n // Set common response attributes if available\n if (state.responseId) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n });\n }\n if (state.responseModel) {\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n });\n }\n\n setTokenUsageAttributes(\n span,\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n );\n\n span.setAttributes({\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n });\n\n if (state.finishReasons.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n });\n }\n\n if (recordOutputs && state.responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n });\n }\n\n // Set tool calls if any were captured\n if (recordOutputs && state.toolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n });\n }\n\n span.end();\n}\n\n/**\n * Instruments an async iterable stream of Anthropic events, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each event from the input stream unchanged.\n */\nasync function* instrumentAsyncIterableStream(\n stream,\n span,\n recordOutputs,\n) {\n const state = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n try {\n for await (const event of stream) {\n processEvent(event, state, recordOutputs, span);\n yield event;\n }\n } finally {\n // Set common response attributes if available\n if (state.responseId) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: state.responseId,\n });\n }\n if (state.responseModel) {\n span.setAttributes({\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: state.responseModel,\n });\n }\n\n setTokenUsageAttributes(\n span,\n state.promptTokens,\n state.completionTokens,\n state.cacheCreationInputTokens,\n state.cacheReadInputTokens,\n );\n\n span.setAttributes({\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n });\n\n if (state.finishReasons.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE]: JSON.stringify(state.finishReasons),\n });\n }\n\n if (recordOutputs && state.responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: state.responseTexts.join(''),\n });\n }\n\n // Set tool calls if any were captured\n if (recordOutputs && state.toolCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(state.toolCalls),\n });\n }\n\n span.end();\n }\n}\n\n/**\n * Instruments a MessageStream by registering event handlers and preserving the original stream API.\n */\nfunction instrumentMessageStream(\n stream,\n span,\n recordOutputs,\n) {\n const state = {\n responseTexts: [],\n finishReasons: [],\n responseId: '',\n responseModel: '',\n promptTokens: undefined,\n completionTokens: undefined,\n cacheCreationInputTokens: undefined,\n cacheReadInputTokens: undefined,\n toolCalls: [],\n activeToolBlocks: {},\n };\n\n stream.on('streamEvent', (event) => {\n processEvent(event , state, recordOutputs, span);\n });\n\n // The event fired when a message is done being streamed by the API. Corresponds to the message_stop SSE event.\n // @see https://github.com/anthropics/anthropic-sdk-typescript/blob/d3be31f5a4e6ebb4c0a2f65dbb8f381ae73a9166/helpers.md?plain=1#L42-L44\n stream.on('message', () => {\n finalizeStreamSpan(state, span, recordOutputs);\n });\n\n stream.on('error', (error) => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.stream_error',\n },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'stream_error' });\n span.end();\n }\n });\n\n return stream;\n}\n\nexport { instrumentAsyncIterableStream, instrumentMessageStream };\n//# sourceMappingURL=streaming.js.map\n","const ANTHROPIC_AI_INTEGRATION_NAME = 'Anthropic_AI';\n\n// https://docs.anthropic.com/en/api/messages\n// https://docs.anthropic.com/en/api/models-list\nconst ANTHROPIC_AI_INSTRUMENTED_METHODS = [\n 'messages.create',\n 'messages.stream',\n 'messages.countTokens',\n 'models.get',\n 'completions.create',\n 'models.retrieve',\n 'beta.messages.create',\n] ;\n\nexport { ANTHROPIC_AI_INSTRUMENTED_METHODS, ANTHROPIC_AI_INTEGRATION_NAME };\n//# sourceMappingURL=constants.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { captureException } from '../../exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { startSpan, startSpanManual } from '../trace.js';\nimport { handleCallbackErrors } from '../../utils/handleCallbackErrors.js';\nimport { GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_PROMPT_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { getFinalOperationName, getSpanOperation, getTruncatedJsonString, setTokenUsageAttributes, buildMethodPath } from '../ai/utils.js';\nimport { instrumentAsyncIterableStream, instrumentMessageStream } from './streaming.js';\nimport { shouldInstrument, messagesFromParams, handleResponseError } from './utils.js';\n\n/**\n * Extract request attributes from method arguments\n */\nfunction extractRequestAttributes(args, methodPath) {\n const attributes = {\n [GEN_AI_SYSTEM_ATTRIBUTE]: 'anthropic',\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath),\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.anthropic',\n };\n\n if (args.length > 0 && typeof args[0] === 'object' && args[0] !== null) {\n const params = args[0] ;\n if (params.tools && Array.isArray(params.tools)) {\n attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(params.tools);\n }\n\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = params.model ?? 'unknown';\n if ('temperature' in params) attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = params.temperature;\n if ('top_p' in params) attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = params.top_p;\n if ('stream' in params) attributes[GEN_AI_REQUEST_STREAM_ATTRIBUTE] = params.stream;\n if ('top_k' in params) attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = params.top_k;\n if ('frequency_penalty' in params)\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = params.frequency_penalty;\n if ('max_tokens' in params) attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = params.max_tokens;\n } else {\n if (methodPath === 'models.retrieve' || methodPath === 'models.get') {\n // models.retrieve(model-id) and models.get(model-id)\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = args[0];\n } else {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = 'unknown';\n }\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n */\nfunction addPrivateRequestAttributes(span, params) {\n const messages = messagesFromParams(params);\n if (messages.length) {\n const truncatedMessages = getTruncatedJsonString(messages);\n span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedMessages });\n }\n\n if ('input' in params) {\n const truncatedInput = getTruncatedJsonString(params.input);\n span.setAttributes({ [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: truncatedInput });\n }\n\n if ('prompt' in params) {\n span.setAttributes({ [GEN_AI_PROMPT_ATTRIBUTE]: JSON.stringify(params.prompt) });\n }\n}\n\n/**\n * Add content attributes when recordOutputs is enabled\n */\nfunction addContentAttributes(span, response) {\n // Messages.create\n if ('content' in response) {\n if (Array.isArray(response.content)) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.content\n .map((item) => item.text)\n .filter(text => !!text)\n .join(''),\n });\n\n const toolCalls = [];\n\n for (const item of response.content) {\n if (item.type === 'tool_use' || item.type === 'server_tool_use') {\n toolCalls.push(item);\n }\n }\n if (toolCalls.length > 0) {\n span.setAttributes({ [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(toolCalls) });\n }\n }\n }\n // Completions.create\n if ('completion' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: response.completion });\n }\n // Models.countTokens\n if ('input_tokens' in response) {\n span.setAttributes({ [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: JSON.stringify(response.input_tokens) });\n }\n}\n\n/**\n * Add basic metadata attributes from the response\n */\nfunction addMetadataAttributes(span, response) {\n if ('id' in response && 'model' in response) {\n span.setAttributes({\n [GEN_AI_RESPONSE_ID_ATTRIBUTE]: response.id,\n [GEN_AI_RESPONSE_MODEL_ATTRIBUTE]: response.model,\n });\n\n if ('created' in response && typeof response.created === 'number') {\n span.setAttributes({\n [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created * 1000).toISOString(),\n });\n }\n if ('created_at' in response && typeof response.created_at === 'number') {\n span.setAttributes({\n [ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE]: new Date(response.created_at * 1000).toISOString(),\n });\n }\n\n if ('usage' in response && response.usage) {\n setTokenUsageAttributes(\n span,\n response.usage.input_tokens,\n response.usage.output_tokens,\n response.usage.cache_creation_input_tokens,\n response.usage.cache_read_input_tokens,\n );\n }\n }\n}\n\n/**\n * Add response attributes to spans\n */\nfunction addResponseAttributes(span, response, recordOutputs) {\n if (!response || typeof response !== 'object') return;\n\n // capture error, do not add attributes if error (they shouldn't exist)\n if ('type' in response && response.type === 'error') {\n handleResponseError(span, response);\n return;\n }\n\n // Private response attributes that are only recorded if recordOutputs is true.\n if (recordOutputs) {\n addContentAttributes(span, response);\n }\n\n // Add basic metadata attributes\n addMetadataAttributes(span, response);\n}\n\n/**\n * Handle common error catching and reporting for streaming requests\n */\nfunction handleStreamingError(error, span, methodPath) {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.ai.anthropic', data: { function: methodPath } },\n });\n\n if (span.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n span.end();\n }\n throw error;\n}\n\n/**\n * Handle streaming cases with common logic\n */\nfunction handleStreamingRequest(\n originalMethod,\n target,\n context,\n args,\n requestAttributes,\n operationName,\n methodPath,\n params,\n options,\n isStreamRequested,\n isStreamingMethod,\n) {\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n const spanConfig = {\n name: `${operationName} ${model} stream-response`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes ,\n };\n\n // messages.stream() always returns a sync MessageStream, even with stream: true param\n if (isStreamRequested && !isStreamingMethod) {\n return startSpanManual(spanConfig, async span => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n const result = await originalMethod.apply(context, args);\n return instrumentAsyncIterableStream(\n result ,\n span,\n options.recordOutputs ?? false,\n ) ;\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n });\n } else {\n return startSpanManual(spanConfig, span => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n const messageStream = target.apply(context, args);\n return instrumentMessageStream(messageStream, span, options.recordOutputs ?? false);\n } catch (error) {\n return handleStreamingError(error, span, methodPath);\n }\n });\n }\n}\n\n/**\n * Instrument a method with Sentry spans\n * Following Sentry AI Agents Manual Instrumentation conventions\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod(\n originalMethod,\n methodPath,\n context,\n options,\n) {\n return new Proxy(originalMethod, {\n apply(target, thisArg, args) {\n const requestAttributes = extractRequestAttributes(args, methodPath);\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n const operationName = getFinalOperationName(methodPath);\n\n const params = typeof args[0] === 'object' ? (args[0] ) : undefined;\n const isStreamRequested = Boolean(params?.stream);\n const isStreamingMethod = methodPath === 'messages.stream';\n\n if (isStreamRequested || isStreamingMethod) {\n return handleStreamingRequest(\n originalMethod,\n target,\n context,\n args,\n requestAttributes,\n operationName,\n methodPath,\n params,\n options,\n isStreamRequested,\n isStreamingMethod,\n );\n }\n\n return startSpan(\n {\n name: `${operationName} ${model}`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes ,\n },\n span => {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return handleCallbackErrors(\n () => target.apply(context, args),\n error => {\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic',\n data: {\n function: methodPath,\n },\n },\n });\n },\n () => {},\n result => addResponseAttributes(span, result , options.recordOutputs),\n );\n },\n );\n },\n }) ;\n}\n\n/**\n * Create a deep proxy for Anthropic AI client instrumentation\n */\nfunction createDeepProxy(target, currentPath = '', options) {\n return new Proxy(target, {\n get(obj, prop) {\n const value = (obj )[prop];\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n if (typeof value === 'function' && shouldInstrument(methodPath)) {\n return instrumentMethod(value , methodPath, obj, options);\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context,\n return value.bind(obj);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n }) ;\n}\n\n/**\n * Instrument an Anthropic AI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends object\n * @param client - The Anthropic AI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n */\nfunction instrumentAnthropicAiClient(anthropicAiClient, options) {\n const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n\n const _options = {\n recordInputs: sendDefaultPii,\n recordOutputs: sendDefaultPii,\n ...options,\n };\n return createDeepProxy(anthropicAiClient, '', _options);\n}\n\nexport { instrumentAnthropicAiClient };\n//# sourceMappingURL=index.js.map\n","import { captureException } from '../../exports.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { ANTHROPIC_AI_INSTRUMENTED_METHODS } from './constants.js';\n\n/**\n * Check if a method path should be instrumented\n */\nfunction shouldInstrument(methodPath) {\n return ANTHROPIC_AI_INSTRUMENTED_METHODS.includes(methodPath );\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nfunction handleResponseError(span, response) {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: response.error.type || 'internal_error' });\n\n captureException(response.error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.anthropic.anthropic_error',\n },\n });\n }\n}\n\n/**\n * Include the system prompt in the messages list, if available\n */\nfunction messagesFromParams(params) {\n const { system, messages } = params;\n\n const systemMessages = typeof system === 'string' ? [{ role: 'system', content: params.system }] : [];\n\n const userMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n return [...systemMessages, ...userMessages];\n}\n\nexport { handleResponseError, messagesFromParams, shouldInstrument };\n//# sourceMappingURL=utils.js.map\n","const GOOGLE_GENAI_INTEGRATION_NAME = 'Google_GenAI';\n\n// https://ai.google.dev/api/rest/v1/models/generateContent\n// https://ai.google.dev/api/rest/v1/chats/sendMessage\n// https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html#generatecontentstream\n// https://googleapis.github.io/js-genai/release_docs/classes/chats.Chat.html#sendmessagestream\nconst GOOGLE_GENAI_INSTRUMENTED_METHODS = [\n 'models.generateContent',\n 'models.generateContentStream',\n 'chats.create',\n 'sendMessage',\n 'sendMessageStream',\n] ;\n\n// Constants for internal use\nconst GOOGLE_GENAI_SYSTEM_NAME = 'google_genai';\nconst CHATS_CREATE_METHOD = 'chats.create';\nconst CHAT_PATH = 'chat';\n\nexport { CHATS_CREATE_METHOD, CHAT_PATH, GOOGLE_GENAI_INSTRUMENTED_METHODS, GOOGLE_GENAI_INTEGRATION_NAME, GOOGLE_GENAI_SYSTEM_NAME };\n//# sourceMappingURL=constants.js.map\n","import { captureException } from '../../exports.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { GEN_AI_RESPONSE_STREAMING_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\n\n/**\n * State object used to accumulate information from a stream of Google GenAI events.\n */\n\n/**\n * Checks if a response chunk contains an error\n * @param chunk - The response chunk to check\n * @param span - The span to update if error is found\n * @returns Whether an error occurred\n */\nfunction isErrorChunk(chunk, span) {\n const feedback = chunk?.promptFeedback;\n if (feedback?.blockReason) {\n const message = feedback.blockReasonMessage ?? feedback.blockReason;\n span.setStatus({ code: SPAN_STATUS_ERROR, message: `Content blocked: ${message}` });\n captureException(`Content blocked: ${message}`, {\n mechanism: { handled: false, type: 'auto.ai.google_genai' },\n });\n return true;\n }\n return false;\n}\n\n/**\n * Processes response metadata from a chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n */\nfunction handleResponseMetadata(chunk, state) {\n if (typeof chunk.responseId === 'string') state.responseId = chunk.responseId;\n if (typeof chunk.modelVersion === 'string') state.responseModel = chunk.modelVersion;\n\n const usage = chunk.usageMetadata;\n if (usage) {\n if (typeof usage.promptTokenCount === 'number') state.promptTokens = usage.promptTokenCount;\n if (typeof usage.candidatesTokenCount === 'number') state.completionTokens = usage.candidatesTokenCount;\n if (typeof usage.totalTokenCount === 'number') state.totalTokens = usage.totalTokenCount;\n }\n}\n\n/**\n * Processes candidate content from a response chunk\n * @param chunk - The response chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n */\nfunction handleCandidateContent(chunk, state, recordOutputs) {\n if (Array.isArray(chunk.functionCalls)) {\n state.toolCalls.push(...chunk.functionCalls);\n }\n\n for (const candidate of chunk.candidates ?? []) {\n if (candidate?.finishReason && !state.finishReasons.includes(candidate.finishReason)) {\n state.finishReasons.push(candidate.finishReason);\n }\n\n for (const part of candidate?.content?.parts ?? []) {\n if (recordOutputs && part.text) state.responseTexts.push(part.text);\n if (part.functionCall) {\n state.toolCalls.push({\n type: 'function',\n id: part.functionCall.id,\n name: part.functionCall.name,\n arguments: part.functionCall.args,\n });\n }\n }\n }\n}\n\n/**\n * Processes a single chunk from the Google GenAI stream\n * @param chunk - The chunk to process\n * @param state - The state of the streaming process\n * @param recordOutputs - Whether to record outputs\n * @param span - The span to update\n */\nfunction processChunk(chunk, state, recordOutputs, span) {\n if (!chunk || isErrorChunk(chunk, span)) return;\n handleResponseMetadata(chunk, state);\n handleCandidateContent(chunk, state, recordOutputs);\n}\n\n/**\n * Instruments an async iterable stream of Google GenAI response chunks, updates the span with\n * streaming attributes and (optionally) the aggregated output text, and yields\n * each chunk from the input stream unchanged.\n */\nasync function* instrumentStream(\n stream,\n span,\n recordOutputs,\n) {\n const state = {\n responseTexts: [],\n finishReasons: [],\n toolCalls: [],\n };\n\n try {\n for await (const chunk of stream) {\n processChunk(chunk, state, recordOutputs, span);\n yield chunk;\n }\n } finally {\n const attrs = {\n [GEN_AI_RESPONSE_STREAMING_ATTRIBUTE]: true,\n };\n\n if (state.responseId) attrs[GEN_AI_RESPONSE_ID_ATTRIBUTE] = state.responseId;\n if (state.responseModel) attrs[GEN_AI_RESPONSE_MODEL_ATTRIBUTE] = state.responseModel;\n if (state.promptTokens !== undefined) attrs[GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE] = state.promptTokens;\n if (state.completionTokens !== undefined) attrs[GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE] = state.completionTokens;\n if (state.totalTokens !== undefined) attrs[GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE] = state.totalTokens;\n\n if (state.finishReasons.length) {\n attrs[GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE] = JSON.stringify(state.finishReasons);\n }\n if (recordOutputs && state.responseTexts.length) {\n attrs[GEN_AI_RESPONSE_TEXT_ATTRIBUTE] = state.responseTexts.join('');\n }\n if (recordOutputs && state.toolCalls.length) {\n attrs[GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE] = JSON.stringify(state.toolCalls);\n }\n\n span.setAttributes(attrs);\n span.end();\n }\n}\n\nexport { instrumentStream };\n//# sourceMappingURL=streaming.js.map\n","import { GOOGLE_GENAI_INSTRUMENTED_METHODS } from './constants.js';\n\n/**\n * Check if a method path should be instrumented\n */\nfunction shouldInstrument(methodPath) {\n // Check for exact matches first (like 'models.generateContent')\n if (GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodPath )) {\n return true;\n }\n\n // Check for method name matches (like 'sendMessage' from chat instances)\n const methodName = methodPath.split('.').pop();\n return GOOGLE_GENAI_INSTRUMENTED_METHODS.includes(methodName );\n}\n\n/**\n * Check if a method is a streaming method\n */\nfunction isStreamingMethod(methodPath) {\n return methodPath.includes('Stream');\n}\n\n// Copied from https://googleapis.github.io/js-genai/release_docs/index.html\n\n/**\n *\n */\nfunction contentUnionToMessages(content, role = 'user') {\n if (typeof content === 'string') {\n return [{ role, content }];\n }\n if (Array.isArray(content)) {\n return content.flatMap(content => contentUnionToMessages(content, role));\n }\n if (typeof content !== 'object' || !content) return [];\n if ('role' in content && typeof content.role === 'string') {\n return [content ];\n }\n if ('parts' in content) {\n return [{ ...content, role } ];\n }\n return [{ role, content }];\n}\n\nexport { contentUnionToMessages, isStreamingMethod, shouldInstrument };\n//# sourceMappingURL=utils.js.map\n","import { getClient } from '../../currentScopes.js';\nimport { captureException } from '../../exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { startSpanManual, startSpan } from '../trace.js';\nimport { handleCallbackErrors } from '../../utils/handleCallbackErrors.js';\nimport { GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_TOP_K_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { truncateGenAiMessages } from '../ai/messageTruncation.js';\nimport { buildMethodPath, getFinalOperationName, getSpanOperation } from '../ai/utils.js';\nimport { CHATS_CREATE_METHOD, CHAT_PATH, GOOGLE_GENAI_SYSTEM_NAME } from './constants.js';\nimport { instrumentStream } from './streaming.js';\nimport { shouldInstrument, isStreamingMethod, contentUnionToMessages } from './utils.js';\n\n/**\n * Extract model from parameters or chat context object\n * For chat instances, the model is available on the chat object as 'model' (older versions) or 'modelVersion' (newer versions)\n */\nfunction extractModel(params, context) {\n if ('model' in params && typeof params.model === 'string') {\n return params.model;\n }\n\n // Try to get model from chat context object (chat instance has model property)\n if (context && typeof context === 'object') {\n const contextObj = context ;\n\n // Check for 'model' property (older versions, and streaming)\n if ('model' in contextObj && typeof contextObj.model === 'string') {\n return contextObj.model;\n }\n\n // Check for 'modelVersion' property (newer versions)\n if ('modelVersion' in contextObj && typeof contextObj.modelVersion === 'string') {\n return contextObj.modelVersion;\n }\n }\n\n return 'unknown';\n}\n\n/**\n * Extract generation config parameters\n */\nfunction extractConfigAttributes(config) {\n const attributes = {};\n\n if ('temperature' in config && typeof config.temperature === 'number') {\n attributes[GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE] = config.temperature;\n }\n if ('topP' in config && typeof config.topP === 'number') {\n attributes[GEN_AI_REQUEST_TOP_P_ATTRIBUTE] = config.topP;\n }\n if ('topK' in config && typeof config.topK === 'number') {\n attributes[GEN_AI_REQUEST_TOP_K_ATTRIBUTE] = config.topK;\n }\n if ('maxOutputTokens' in config && typeof config.maxOutputTokens === 'number') {\n attributes[GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE] = config.maxOutputTokens;\n }\n if ('frequencyPenalty' in config && typeof config.frequencyPenalty === 'number') {\n attributes[GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE] = config.frequencyPenalty;\n }\n if ('presencePenalty' in config && typeof config.presencePenalty === 'number') {\n attributes[GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE] = config.presencePenalty;\n }\n\n return attributes;\n}\n\n/**\n * Extract request attributes from method arguments\n * Builds the base attributes for span creation including system info, model, and config\n */\nfunction extractRequestAttributes(\n methodPath,\n params,\n context,\n) {\n const attributes = {\n [GEN_AI_SYSTEM_ATTRIBUTE]: GOOGLE_GENAI_SYSTEM_NAME,\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: getFinalOperationName(methodPath),\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.google_genai',\n };\n\n if (params) {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel(params, context);\n\n // Extract generation config parameters\n if ('config' in params && typeof params.config === 'object' && params.config) {\n const config = params.config ;\n Object.assign(attributes, extractConfigAttributes(config));\n\n // Extract available tools from config\n if ('tools' in config && Array.isArray(config.tools)) {\n const functionDeclarations = config.tools.flatMap(\n (tool) => tool.functionDeclarations,\n );\n attributes[GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE] = JSON.stringify(functionDeclarations);\n }\n }\n } else {\n attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] = extractModel({}, context);\n }\n\n return attributes;\n}\n\n/**\n * Add private request attributes to spans.\n * This is only recorded if recordInputs is true.\n * Handles different parameter formats for different Google GenAI methods.\n */\nfunction addPrivateRequestAttributes(span, params) {\n const messages = [];\n\n // config.systemInstruction: ContentUnion\n if (\n 'config' in params &&\n params.config &&\n typeof params.config === 'object' &&\n 'systemInstruction' in params.config &&\n params.config.systemInstruction\n ) {\n messages.push(...contentUnionToMessages(params.config.systemInstruction , 'system'));\n }\n\n // For chats.create: history contains the conversation history\n if ('history' in params) {\n messages.push(...contentUnionToMessages(params.history , 'user'));\n }\n\n // For models.generateContent: ContentListUnion\n if ('contents' in params) {\n messages.push(...contentUnionToMessages(params.contents , 'user'));\n }\n\n // For chat.sendMessage: message can be PartListUnion\n if ('message' in params) {\n messages.push(...contentUnionToMessages(params.message , 'user'));\n }\n\n if (messages.length) {\n span.setAttributes({\n [GEN_AI_REQUEST_MESSAGES_ATTRIBUTE]: JSON.stringify(truncateGenAiMessages(messages)),\n });\n }\n}\n\n/**\n * Add response attributes from the Google GenAI response\n * @see https://github.com/googleapis/js-genai/blob/v1.19.0/src/types.ts#L2313\n */\nfunction addResponseAttributes(span, response, recordOutputs) {\n if (!response || typeof response !== 'object') return;\n\n if (response.modelVersion) {\n span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, response.modelVersion);\n }\n\n // Add usage metadata if present\n if (response.usageMetadata && typeof response.usageMetadata === 'object') {\n const usage = response.usageMetadata;\n if (typeof usage.promptTokenCount === 'number') {\n span.setAttributes({\n [GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE]: usage.promptTokenCount,\n });\n }\n if (typeof usage.candidatesTokenCount === 'number') {\n span.setAttributes({\n [GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE]: usage.candidatesTokenCount,\n });\n }\n if (typeof usage.totalTokenCount === 'number') {\n span.setAttributes({\n [GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE]: usage.totalTokenCount,\n });\n }\n }\n\n // Add response text if recordOutputs is enabled\n if (recordOutputs && Array.isArray(response.candidates) && response.candidates.length > 0) {\n const responseTexts = response.candidates\n .map((candidate) => {\n if (candidate.content?.parts && Array.isArray(candidate.content.parts)) {\n return candidate.content.parts\n .map((part) => (typeof part.text === 'string' ? part.text : ''))\n .filter((text) => text.length > 0)\n .join('');\n }\n return '';\n })\n .filter((text) => text.length > 0);\n\n if (responseTexts.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TEXT_ATTRIBUTE]: responseTexts.join(''),\n });\n }\n }\n\n // Add tool calls if recordOutputs is enabled\n if (recordOutputs && response.functionCalls) {\n const functionCalls = response.functionCalls;\n if (Array.isArray(functionCalls) && functionCalls.length > 0) {\n span.setAttributes({\n [GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE]: JSON.stringify(functionCalls),\n });\n }\n }\n}\n\n/**\n * Instrument any async or synchronous genai method with Sentry spans\n * Handles operations like models.generateContent and chat.sendMessage and chats.create\n * @see https://docs.sentry.io/platforms/javascript/guides/node/tracing/instrumentation/ai-agents-module/#manual-instrumentation\n */\nfunction instrumentMethod(\n originalMethod,\n methodPath,\n context,\n options,\n) {\n const isSyncCreate = methodPath === CHATS_CREATE_METHOD;\n\n return new Proxy(originalMethod, {\n apply(target, _, args) {\n const params = args[0] ;\n const requestAttributes = extractRequestAttributes(methodPath, params, context);\n const model = requestAttributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE] ?? 'unknown';\n const operationName = getFinalOperationName(methodPath);\n\n // Check if this is a streaming method\n if (isStreamingMethod(methodPath)) {\n // Use startSpanManual for streaming methods to control span lifecycle\n return startSpanManual(\n {\n name: `${operationName} ${model} stream-response`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes,\n },\n async (span) => {\n try {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n const stream = await target.apply(context, args);\n return instrumentStream(stream, span, Boolean(options.recordOutputs)) ;\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.google_genai',\n data: { function: methodPath },\n },\n });\n span.end();\n throw error;\n }\n },\n );\n }\n // Single span for both sync and async operations\n return startSpan(\n {\n name: isSyncCreate ? `${operationName} ${model} create` : `${operationName} ${model}`,\n op: getSpanOperation(methodPath),\n attributes: requestAttributes,\n },\n (span) => {\n if (options.recordInputs && params) {\n addPrivateRequestAttributes(span, params);\n }\n\n return handleCallbackErrors(\n () => target.apply(context, args),\n error => {\n captureException(error, {\n mechanism: { handled: false, type: 'auto.ai.google_genai', data: { function: methodPath } },\n });\n },\n () => {},\n result => {\n // Only add response attributes for content-producing methods, not for chats.create\n if (!isSyncCreate) {\n addResponseAttributes(span, result, options.recordOutputs);\n }\n },\n );\n },\n );\n },\n }) ;\n}\n\n/**\n * Create a deep proxy for Google GenAI client instrumentation\n * Recursively instruments methods and handles special cases like chats.create\n */\nfunction createDeepProxy(target, currentPath = '', options) {\n return new Proxy(target, {\n get: (t, prop, receiver) => {\n const value = Reflect.get(t, prop, receiver);\n const methodPath = buildMethodPath(currentPath, String(prop));\n\n if (typeof value === 'function' && shouldInstrument(methodPath)) {\n // Special case: chats.create is synchronous but needs both instrumentation AND result proxying\n if (methodPath === CHATS_CREATE_METHOD) {\n const instrumentedMethod = instrumentMethod(value , methodPath, t, options);\n return function instrumentedAndProxiedCreate(...args) {\n const result = instrumentedMethod(...args);\n // If the result is an object (like a chat instance), proxy it too\n if (result && typeof result === 'object') {\n return createDeepProxy(result, CHAT_PATH, options);\n }\n return result;\n };\n }\n\n return instrumentMethod(value , methodPath, t, options);\n }\n\n if (typeof value === 'function') {\n // Bind non-instrumented functions to preserve the original `this` context\n return value.bind(t);\n }\n\n if (value && typeof value === 'object') {\n return createDeepProxy(value, methodPath, options);\n }\n\n return value;\n },\n });\n}\n\n/**\n * Instrument a Google GenAI client with Sentry tracing\n * Can be used across Node.js, Cloudflare Workers, and Vercel Edge\n *\n * @template T - The type of the client that extends client object\n * @param client - The Google GenAI client to instrument\n * @param options - Optional configuration for recording inputs and outputs\n * @returns The instrumented client with the same type as the input\n *\n * @example\n * ```typescript\n * import { GoogleGenAI } from '@google/genai';\n * import { instrumentGoogleGenAIClient } from '@sentry/core';\n *\n * const genAI = new GoogleGenAI({ apiKey: process.env.GOOGLE_GENAI_API_KEY });\n * const instrumentedClient = instrumentGoogleGenAIClient(genAI);\n *\n * // Now both chats.create and sendMessage will be instrumented\n * const chat = instrumentedClient.chats.create({ model: 'gemini-1.5-pro' });\n * const response = await chat.sendMessage({ message: 'Hello' });\n * ```\n */\nfunction instrumentGoogleGenAIClient(client, options) {\n const sendDefaultPii = Boolean(getClient()?.getOptions().sendDefaultPii);\n\n const _options = {\n recordInputs: sendDefaultPii,\n recordOutputs: sendDefaultPii,\n ...options,\n };\n return createDeepProxy(client, '', _options);\n}\n\nexport { extractModel, instrumentGoogleGenAIClient };\n//# sourceMappingURL=index.js.map\n","const LANGCHAIN_INTEGRATION_NAME = 'LangChain';\nconst LANGCHAIN_ORIGIN = 'auto.ai.langchain';\n\nconst ROLE_MAP = {\n human: 'user',\n ai: 'assistant',\n assistant: 'assistant',\n system: 'system',\n function: 'function',\n tool: 'tool',\n};\n\nexport { LANGCHAIN_INTEGRATION_NAME, LANGCHAIN_ORIGIN, ROLE_MAP };\n//# sourceMappingURL=constants.js.map\n","import { SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_SYSTEM_ATTRIBUTE, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, GEN_AI_REQUEST_STREAM_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_ID_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { truncateGenAiMessages } from '../ai/messageTruncation.js';\nimport { LANGCHAIN_ORIGIN, ROLE_MAP } from './constants.js';\n\n/**\n * Assigns an attribute only when the value is neither `undefined` nor `null`.\n *\n * We keep this tiny helper because call sites are repetitive and easy to miswrite.\n * It also preserves falsy-but-valid values like `0` and `\"\"`.\n */\nconst setIfDefined = (target, key, value) => {\n if (value != null) target[key] = value ;\n};\n\n/**\n * Like `setIfDefined`, but converts the value with `Number()` and skips only when the\n * result is `NaN`. This ensures numeric 0 makes it through (unlike truthy checks).\n */\nconst setNumberIfDefined = (target, key, value) => {\n const n = Number(value);\n if (!Number.isNaN(n)) target[key] = n;\n};\n\n/**\n * Converts a value to a string. Avoids double-quoted JSON strings where a plain\n * string is desired, but still handles objects/arrays safely.\n */\nfunction asString(v) {\n if (typeof v === 'string') return v;\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n\n/**\n * Normalizes a single role token to our canonical set.\n *\n * @param role Incoming role value (free-form, any casing)\n * @returns Canonical role: 'user' | 'assistant' | 'system' | 'function' | 'tool' | <passthrough>\n */\nfunction normalizeMessageRole(role) {\n const normalized = role.toLowerCase();\n return ROLE_MAP[normalized] ?? normalized;\n}\n\n/**\n * Infers a role from a LangChain message constructor name.\n *\n * Checks for substrings like \"System\", \"Human\", \"AI\", etc.\n */\nfunction normalizeRoleNameFromCtor(name) {\n if (name.includes('System')) return 'system';\n if (name.includes('Human')) return 'user';\n if (name.includes('AI') || name.includes('Assistant')) return 'assistant';\n if (name.includes('Function')) return 'function';\n if (name.includes('Tool')) return 'tool';\n return 'user';\n}\n\n/**\n * Returns invocation params from a LangChain `tags` object.\n *\n * LangChain often passes runtime parameters (model, temperature, etc.) via the\n * `tags.invocation_params` bag. If `tags` is an array (LangChain sometimes uses\n * string tags), we return `undefined`.\n *\n * @param tags LangChain tags (string[] or record)\n * @returns The `invocation_params` object, if present\n */\nfunction getInvocationParams(tags) {\n if (!tags || Array.isArray(tags)) return undefined;\n return tags.invocation_params ;\n}\n\n/**\n * Normalizes a heterogeneous set of LangChain messages to `{ role, content }`.\n *\n * Why so many branches? LangChain messages can arrive in several shapes:\n * - Message classes with `_getType()` (most reliable)\n * - Classes with meaningful constructor names (e.g. `SystemMessage`)\n * - Plain objects with `type`, or `{ role, content }`\n * - Serialized format with `{ lc: 1, id: [...], kwargs: { content } }`\n * We preserve the prioritization to minimize behavioral drift.\n *\n * @param messages Mixed LangChain messages\n * @returns Array of normalized `{ role, content }`\n */\nfunction normalizeLangChainMessages(messages) {\n return messages.map(message => {\n // 1) Prefer _getType() when present\n const maybeGetType = (message )._getType;\n if (typeof maybeGetType === 'function') {\n const messageType = maybeGetType.call(message);\n return {\n role: normalizeMessageRole(messageType),\n content: asString(message.content),\n };\n }\n\n // 2) Then try constructor name (SystemMessage / HumanMessage / ...)\n const ctor = (message ).constructor?.name;\n if (ctor) {\n return {\n role: normalizeMessageRole(normalizeRoleNameFromCtor(ctor)),\n content: asString(message.content),\n };\n }\n\n // 3) Then objects with `type`\n if (message.type) {\n const role = String(message.type).toLowerCase();\n return {\n role: normalizeMessageRole(role),\n content: asString(message.content),\n };\n }\n\n // 4) Then objects with `{ role, content }`\n if (message.role) {\n return {\n role: normalizeMessageRole(String(message.role)),\n content: asString(message.content),\n };\n }\n\n // 5) Serialized LangChain format (lc: 1)\n if (message.lc === 1 && message.kwargs) {\n const id = message.id;\n const messageType = Array.isArray(id) && id.length > 0 ? id[id.length - 1] : '';\n const role = typeof messageType === 'string' ? normalizeRoleNameFromCtor(messageType) : 'user';\n\n return {\n role: normalizeMessageRole(role),\n content: asString(message.kwargs?.content),\n };\n }\n\n // 6) Fallback: treat as user text\n return {\n role: 'user',\n content: asString(message.content),\n };\n });\n}\n\n/**\n * Extracts request attributes common to both LLM and ChatModel invocations.\n *\n * Source precedence:\n * 1) `invocationParams` (highest)\n * 2) `langSmithMetadata`\n *\n * Numeric values are set even when 0 (e.g. `temperature: 0`), but skipped if `NaN`.\n */\nfunction extractCommonRequestAttributes(\n serialized,\n invocationParams,\n langSmithMetadata,\n) {\n const attrs = {};\n\n // Get kwargs if available (from constructor type)\n const kwargs = 'kwargs' in serialized ? serialized.kwargs : undefined;\n\n const temperature = invocationParams?.temperature ?? langSmithMetadata?.ls_temperature ?? kwargs?.temperature;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE, temperature);\n\n const maxTokens = invocationParams?.max_tokens ?? langSmithMetadata?.ls_max_tokens ?? kwargs?.max_tokens;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE, maxTokens);\n\n const topP = invocationParams?.top_p ?? kwargs?.top_p;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_TOP_P_ATTRIBUTE, topP);\n\n const frequencyPenalty = invocationParams?.frequency_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE, frequencyPenalty);\n\n const presencePenalty = invocationParams?.presence_penalty;\n setNumberIfDefined(attrs, GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE, presencePenalty);\n\n // LangChain uses `stream`. We only set the attribute if the key actually exists\n // (some callbacks report `false` even on streamed requests, this stems from LangChain's callback handler).\n if (invocationParams && 'stream' in invocationParams) {\n setIfDefined(attrs, GEN_AI_REQUEST_STREAM_ATTRIBUTE, Boolean(invocationParams.stream));\n }\n\n return attrs;\n}\n\n/**\n * Small helper to assemble boilerplate attributes shared by both request extractors.\n */\nfunction baseRequestAttributes(\n system,\n modelName,\n operation,\n serialized,\n invocationParams,\n langSmithMetadata,\n) {\n return {\n [GEN_AI_SYSTEM_ATTRIBUTE]: asString(system ?? 'langchain'),\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: operation,\n [GEN_AI_REQUEST_MODEL_ATTRIBUTE]: asString(modelName),\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n ...extractCommonRequestAttributes(serialized, invocationParams, langSmithMetadata),\n };\n}\n\n/**\n * Extracts attributes for plain LLM invocations (string prompts).\n *\n * - Operation is tagged as `pipeline` to distinguish from chat-style invocations.\n * - When `recordInputs` is true, string prompts are wrapped into `{role:\"user\"}`\n * messages to align with the chat schema used elsewhere.\n */\nfunction extractLLMRequestAttributes(\n llm,\n prompts,\n recordInputs,\n invocationParams,\n langSmithMetadata,\n) {\n const system = langSmithMetadata?.ls_provider;\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, 'pipeline', llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(prompts) && prompts.length > 0) {\n const messages = prompts.map(p => ({ role: 'user', content: p }));\n setIfDefined(attrs, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, asString(messages));\n }\n\n return attrs;\n}\n\n/**\n * Extracts attributes for ChatModel invocations (array-of-arrays of messages).\n *\n * - Operation is tagged as `chat`.\n * - We flatten LangChain's `LangChainMessage[][]` and normalize shapes into a\n * consistent `{ role, content }` array when `recordInputs` is true.\n * - Provider system value falls back to `serialized.id?.[2]`.\n */\nfunction extractChatModelRequestAttributes(\n llm,\n langChainMessages,\n recordInputs,\n invocationParams,\n langSmithMetadata,\n) {\n const system = langSmithMetadata?.ls_provider ?? llm.id?.[2];\n const modelName = invocationParams?.model ?? langSmithMetadata?.ls_model_name ?? 'unknown';\n\n const attrs = baseRequestAttributes(system, modelName, 'chat', llm, invocationParams, langSmithMetadata);\n\n if (recordInputs && Array.isArray(langChainMessages) && langChainMessages.length > 0) {\n const normalized = normalizeLangChainMessages(langChainMessages.flat());\n const truncated = truncateGenAiMessages(normalized);\n setIfDefined(attrs, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, asString(truncated));\n }\n\n return attrs;\n}\n\n/**\n * Scans generations for Anthropic-style `tool_use` items and records them.\n *\n * LangChain represents some provider messages (e.g., Anthropic) with a `message.content`\n * array that may include objects `{ type: 'tool_use', ... }`. We collect and attach\n * them as a JSON array on `gen_ai.response.tool_calls` for downstream consumers.\n */\nfunction addToolCallsAttributes(generations, attrs) {\n const toolCalls = [];\n const flatGenerations = generations.flat();\n\n for (const gen of flatGenerations) {\n const content = gen.message?.content;\n if (Array.isArray(content)) {\n for (const item of content) {\n const t = item ;\n if (t.type === 'tool_use') toolCalls.push(t);\n }\n }\n }\n\n if (toolCalls.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, asString(toolCalls));\n }\n}\n\n/**\n * Adds token usage attributes, supporting both OpenAI (`tokenUsage`) and Anthropic (`usage`) formats.\n * - Preserve zero values (0 tokens) by avoiding truthy checks.\n * - Compute a total for Anthropic when not explicitly provided.\n * - Include cache token metrics when present.\n */\nfunction addTokenUsageAttributes(\n llmOutput,\n attrs,\n) {\n if (!llmOutput) return;\n\n const tokenUsage = llmOutput.tokenUsage\n\n;\n const anthropicUsage = llmOutput.usage\n\n;\n\n if (tokenUsage) {\n setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, tokenUsage.promptTokens);\n setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, tokenUsage.completionTokens);\n setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, tokenUsage.totalTokens);\n } else if (anthropicUsage) {\n setNumberIfDefined(attrs, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.input_tokens);\n setNumberIfDefined(attrs, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, anthropicUsage.output_tokens);\n\n // Compute total when not provided by the provider.\n const input = Number(anthropicUsage.input_tokens);\n const output = Number(anthropicUsage.output_tokens);\n const total = (Number.isNaN(input) ? 0 : input) + (Number.isNaN(output) ? 0 : output);\n if (total > 0) setNumberIfDefined(attrs, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, total);\n\n // Extra Anthropic cache metrics (present only when caching is enabled)\n if (anthropicUsage.cache_creation_input_tokens !== undefined)\n setNumberIfDefined(\n attrs,\n GEN_AI_USAGE_CACHE_CREATION_INPUT_TOKENS_ATTRIBUTE,\n anthropicUsage.cache_creation_input_tokens,\n );\n if (anthropicUsage.cache_read_input_tokens !== undefined)\n setNumberIfDefined(attrs, GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS_ATTRIBUTE, anthropicUsage.cache_read_input_tokens);\n }\n}\n\n/**\n * Extracts response-related attributes based on a `LangChainLLMResult`.\n *\n * - Records finish reasons when present on generations (e.g., OpenAI)\n * - When `recordOutputs` is true, captures textual response content and any\n * tool calls.\n * - Also propagates model name (`model_name` or `model`), response `id`, and\n * `stop_reason` (for providers that use it).\n */\nfunction extractLlmResponseAttributes(\n llmResult,\n recordOutputs,\n) {\n if (!llmResult) return;\n\n const attrs = {};\n\n if (Array.isArray(llmResult.generations)) {\n const finishReasons = llmResult.generations\n .flat()\n .map(g => {\n // v1 uses generationInfo.finish_reason\n if (g.generationInfo?.finish_reason) {\n return g.generationInfo.finish_reason;\n }\n // v0.3+ uses generation_info.finish_reason\n if (g.generation_info?.finish_reason) {\n return g.generation_info.finish_reason;\n }\n return null;\n })\n .filter((r) => typeof r === 'string');\n\n if (finishReasons.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, asString(finishReasons));\n }\n\n // Tool calls metadata (names, IDs) are not PII, so capture them regardless of recordOutputs\n addToolCallsAttributes(llmResult.generations , attrs);\n\n if (recordOutputs) {\n const texts = llmResult.generations\n .flat()\n .map(gen => gen.text ?? gen.message?.content)\n .filter(t => typeof t === 'string');\n\n if (texts.length > 0) {\n setIfDefined(attrs, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, asString(texts));\n }\n }\n }\n\n addTokenUsageAttributes(llmResult.llmOutput, attrs);\n\n const llmOutput = llmResult.llmOutput;\n\n // Extract from v1 generations structure if available\n const firstGeneration = llmResult.generations?.[0]?.[0];\n const v1Message = firstGeneration?.message;\n\n // Provider model identifier: `model_name` (OpenAI-style) or `model` (others)\n // v1 stores this in message.response_metadata.model_name\n const modelName = llmOutput?.model_name ?? llmOutput?.model ?? v1Message?.response_metadata?.model_name;\n if (modelName) setIfDefined(attrs, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, modelName);\n\n // Response ID: v1 stores this in message.id\n const responseId = llmOutput?.id ?? v1Message?.id;\n if (responseId) {\n setIfDefined(attrs, GEN_AI_RESPONSE_ID_ATTRIBUTE, responseId);\n }\n\n // Stop reason: v1 stores this in message.response_metadata.finish_reason\n const stopReason = llmOutput?.stop_reason ?? v1Message?.response_metadata?.finish_reason;\n if (stopReason) {\n setIfDefined(attrs, GEN_AI_RESPONSE_STOP_REASON_ATTRIBUTE, asString(stopReason));\n }\n\n return attrs;\n}\n\nexport { extractChatModelRequestAttributes, extractLLMRequestAttributes, extractLlmResponseAttributes, getInvocationParams, normalizeLangChainMessages };\n//# sourceMappingURL=utils.js.map\n","const LANGGRAPH_INTEGRATION_NAME = 'LangGraph';\nconst LANGGRAPH_ORIGIN = 'auto.ai.langgraph';\n\nexport { LANGGRAPH_INTEGRATION_NAME, LANGGRAPH_ORIGIN };\n//# sourceMappingURL=constants.js.map\n","import { GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, GEN_AI_RESPONSE_TEXT_ATTRIBUTE, GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, GEN_AI_RESPONSE_MODEL_ATTRIBUTE, GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { normalizeLangChainMessages } from '../langchain/utils.js';\n\n/**\n * Extract tool calls from messages\n */\nfunction extractToolCalls(messages) {\n if (!messages || messages.length === 0) {\n return null;\n }\n\n const toolCalls = [];\n\n for (const message of messages) {\n if (message && typeof message === 'object') {\n const msgToolCalls = message.tool_calls;\n if (msgToolCalls && Array.isArray(msgToolCalls)) {\n toolCalls.push(...msgToolCalls);\n }\n }\n }\n\n return toolCalls.length > 0 ? toolCalls : null;\n}\n\n/**\n * Extract token usage from a message's usage_metadata or response_metadata\n * Returns token counts without setting span attributes\n */\nfunction extractTokenUsageFromMessage(message)\n\n {\n const msg = message ;\n let inputTokens = 0;\n let outputTokens = 0;\n let totalTokens = 0;\n\n // Extract from usage_metadata (newer format)\n if (msg.usage_metadata && typeof msg.usage_metadata === 'object') {\n const usage = msg.usage_metadata ;\n if (typeof usage.input_tokens === 'number') {\n inputTokens = usage.input_tokens;\n }\n if (typeof usage.output_tokens === 'number') {\n outputTokens = usage.output_tokens;\n }\n if (typeof usage.total_tokens === 'number') {\n totalTokens = usage.total_tokens;\n }\n return { inputTokens, outputTokens, totalTokens };\n }\n\n // Fallback: Extract from response_metadata.tokenUsage\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata ;\n if (metadata.tokenUsage && typeof metadata.tokenUsage === 'object') {\n const tokenUsage = metadata.tokenUsage ;\n if (typeof tokenUsage.promptTokens === 'number') {\n inputTokens = tokenUsage.promptTokens;\n }\n if (typeof tokenUsage.completionTokens === 'number') {\n outputTokens = tokenUsage.completionTokens;\n }\n if (typeof tokenUsage.totalTokens === 'number') {\n totalTokens = tokenUsage.totalTokens;\n }\n }\n }\n\n return { inputTokens, outputTokens, totalTokens };\n}\n\n/**\n * Extract model and finish reason from a message's response_metadata\n */\nfunction extractModelMetadata(span, message) {\n const msg = message ;\n\n if (msg.response_metadata && typeof msg.response_metadata === 'object') {\n const metadata = msg.response_metadata ;\n\n if (metadata.model_name && typeof metadata.model_name === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_MODEL_ATTRIBUTE, metadata.model_name);\n }\n\n if (metadata.finish_reason && typeof metadata.finish_reason === 'string') {\n span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE, [metadata.finish_reason]);\n }\n }\n}\n\n/**\n * Extract tools from compiled graph structure\n *\n * Tools are stored in: compiledGraph.builder.nodes.tools.runnable.tools\n */\nfunction extractToolsFromCompiledGraph(compiledGraph) {\n if (!compiledGraph.builder?.nodes?.tools?.runnable?.tools) {\n return null;\n }\n\n const tools = compiledGraph.builder?.nodes?.tools?.runnable?.tools;\n\n if (!tools || !Array.isArray(tools) || tools.length === 0) {\n return null;\n }\n\n // Extract name, description, and schema from each tool's lc_kwargs\n return tools.map((tool) => ({\n name: tool.lc_kwargs?.name,\n description: tool.lc_kwargs?.description,\n schema: tool.lc_kwargs?.schema,\n }));\n}\n\n/**\n * Set response attributes on the span\n */\nfunction setResponseAttributes(span, inputMessages, result) {\n // Extract messages from result\n const resultObj = result ;\n const outputMessages = resultObj?.messages;\n\n if (!outputMessages || !Array.isArray(outputMessages)) {\n return;\n }\n\n // Get new messages (delta between input and output)\n const inputCount = inputMessages?.length ?? 0;\n const newMessages = outputMessages.length > inputCount ? outputMessages.slice(inputCount) : [];\n\n if (newMessages.length === 0) {\n return;\n }\n\n // Extract and set tool calls from new messages BEFORE normalization\n // (normalization strips tool_calls, so we need to extract them first)\n const toolCalls = extractToolCalls(newMessages );\n if (toolCalls) {\n span.setAttribute(GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE, JSON.stringify(toolCalls));\n }\n\n // Normalize the new messages\n const normalizedNewMessages = normalizeLangChainMessages(newMessages);\n span.setAttribute(GEN_AI_RESPONSE_TEXT_ATTRIBUTE, JSON.stringify(normalizedNewMessages));\n\n // Accumulate token usage across all messages\n let totalInputTokens = 0;\n let totalOutputTokens = 0;\n let totalTokens = 0;\n\n // Extract metadata from messages\n for (const message of newMessages) {\n // Accumulate token usage\n const tokens = extractTokenUsageFromMessage(message);\n totalInputTokens += tokens.inputTokens;\n totalOutputTokens += tokens.outputTokens;\n totalTokens += tokens.totalTokens;\n\n // Extract model metadata (last message's metadata wins for model/finish_reason)\n extractModelMetadata(span, message);\n }\n\n // Set accumulated token usage on span\n if (totalInputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE, totalInputTokens);\n }\n if (totalOutputTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE, totalOutputTokens);\n }\n if (totalTokens > 0) {\n span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE, totalTokens);\n }\n}\n\nexport { extractModelMetadata, extractTokenUsageFromMessage, extractToolCalls, extractToolsFromCompiledGraph, setResponseAttributes };\n//# sourceMappingURL=utils.js.map\n","import { captureException } from '../../exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { startSpan } from '../trace.js';\nimport { GEN_AI_AGENT_NAME_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE, GEN_AI_PIPELINE_NAME_ATTRIBUTE, GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { truncateGenAiMessages } from '../ai/messageTruncation.js';\nimport { normalizeLangChainMessages } from '../langchain/utils.js';\nimport { LANGGRAPH_ORIGIN } from './constants.js';\nimport { extractToolsFromCompiledGraph, setResponseAttributes } from './utils.js';\n\n/**\n * Instruments StateGraph's compile method to create spans for agent creation and invocation\n *\n * Wraps the compile() method to:\n * - Create a `gen_ai.create_agent` span when compile() is called\n * - Automatically wrap the invoke() method on the returned compiled graph with a `gen_ai.invoke_agent` span\n *\n */\nfunction instrumentStateGraphCompile(\n originalCompile,\n options,\n) {\n return new Proxy(originalCompile, {\n apply(target, thisArg, args) {\n return startSpan(\n {\n op: 'gen_ai.create_agent',\n name: 'create_agent',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.create_agent',\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'create_agent',\n },\n },\n span => {\n try {\n const compiledGraph = Reflect.apply(target, thisArg, args);\n const compileOptions = args.length > 0 ? (args[0] ) : {};\n\n // Extract graph name\n if (compileOptions?.name && typeof compileOptions.name === 'string') {\n span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, compileOptions.name);\n span.updateName(`create_agent ${compileOptions.name}`);\n }\n\n // Instrument agent invoke method on the compiled graph\n const originalInvoke = compiledGraph.invoke;\n if (originalInvoke && typeof originalInvoke === 'function') {\n compiledGraph.invoke = instrumentCompiledGraphInvoke(\n originalInvoke.bind(compiledGraph) ,\n compiledGraph,\n compileOptions,\n options,\n ) ;\n }\n\n return compiledGraph;\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.langgraph.error',\n },\n });\n throw error;\n }\n },\n );\n },\n }) ;\n}\n\n/**\n * Instruments CompiledGraph's invoke method to create spans for agent invocation\n *\n * Creates a `gen_ai.invoke_agent` span when invoke() is called\n */\nfunction instrumentCompiledGraphInvoke(\n originalInvoke,\n graphInstance,\n compileOptions,\n options,\n) {\n return new Proxy(originalInvoke, {\n apply(target, thisArg, args) {\n return startSpan(\n {\n op: 'gen_ai.invoke_agent',\n name: 'invoke_agent',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGGRAPH_ORIGIN,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: GEN_AI_INVOKE_AGENT_OPERATION_ATTRIBUTE,\n [GEN_AI_OPERATION_NAME_ATTRIBUTE]: 'invoke_agent',\n },\n },\n async span => {\n try {\n const graphName = compileOptions?.name;\n\n if (graphName && typeof graphName === 'string') {\n span.setAttribute(GEN_AI_PIPELINE_NAME_ATTRIBUTE, graphName);\n span.setAttribute(GEN_AI_AGENT_NAME_ATTRIBUTE, graphName);\n span.updateName(`invoke_agent ${graphName}`);\n }\n\n // Extract available tools from the graph instance\n const tools = extractToolsFromCompiledGraph(graphInstance);\n if (tools) {\n span.setAttribute(GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE, JSON.stringify(tools));\n }\n\n // Parse input messages\n const recordInputs = options.recordInputs;\n const recordOutputs = options.recordOutputs;\n const inputMessages =\n args.length > 0 ? ((args[0] ).messages ?? []) : [];\n\n if (inputMessages && recordInputs) {\n const normalizedMessages = normalizeLangChainMessages(inputMessages);\n const truncatedMessages = truncateGenAiMessages(normalizedMessages);\n span.setAttribute(GEN_AI_REQUEST_MESSAGES_ATTRIBUTE, JSON.stringify(truncatedMessages));\n }\n\n // Call original invoke\n const result = await Reflect.apply(target, thisArg, args);\n\n // Set response attributes\n if (recordOutputs) {\n setResponseAttributes(span, inputMessages ?? null, result);\n }\n\n return result;\n } catch (error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });\n captureException(error, {\n mechanism: {\n handled: false,\n type: 'auto.ai.langgraph.error',\n },\n });\n throw error;\n }\n },\n );\n },\n }) ;\n}\n\n/**\n * Directly instruments a StateGraph instance to add tracing spans\n *\n * This function can be used to manually instrument LangGraph StateGraph instances\n * in environments where automatic instrumentation is not available or desired.\n *\n * @param stateGraph - The StateGraph instance to instrument\n * @param options - Optional configuration for recording inputs/outputs\n *\n * @example\n * ```typescript\n * import { instrumentLangGraph } from '@sentry/cloudflare';\n * import { StateGraph } from '@langchain/langgraph';\n *\n * const graph = new StateGraph(MessagesAnnotation)\n * .addNode('agent', mockLlm)\n * .addEdge(START, 'agent')\n * .addEdge('agent', END);\n *\n * instrumentLangGraph(graph, { recordInputs: true, recordOutputs: true });\n * const compiled = graph.compile({ name: 'my_agent' });\n * ```\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction instrumentLangGraph(\n stateGraph,\n options,\n) {\n const _options = options || {};\n\n stateGraph.compile = instrumentStateGraphCompile(stateGraph.compile.bind(stateGraph), _options);\n\n return stateGraph;\n}\n\nexport { instrumentLangGraph, instrumentStateGraphCompile };\n//# sourceMappingURL=index.js.map\n","/**\n * An error emitted by Sentry SDKs and related utilities.\n * @deprecated This class is no longer used and will be removed in a future version. Use `Error` instead.\n */\nclass SentryError extends Error {\n\n constructor(\n message,\n logLevel = 'warn',\n ) {\n super(message);this.message = message;\n this.logLevel = logLevel;\n }\n}\n\nexport { SentryError };\n//# sourceMappingURL=error.js.map\n","import { DEBUG_BUILD } from '../debug-build.js';\nimport { debug } from './debug-logger.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nconst WINDOW = GLOBAL_OBJ ;\n\n/**\n * Tells whether current environment supports ErrorEvent objects\n * {@link supportsErrorEvent}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsErrorEvent() {\n try {\n new ErrorEvent('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMError objects\n * {@link supportsDOMError}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMError() {\n try {\n // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError':\n // 1 argument required, but only 0 present.\n // @ts-expect-error It really needs 1 argument, not 0.\n new DOMError('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports DOMException objects\n * {@link supportsDOMException}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsDOMException() {\n try {\n new DOMException('');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Tells whether current environment supports History API\n * {@link supportsHistory}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsHistory() {\n return 'history' in WINDOW && !!WINDOW.history;\n}\n\n/**\n * Tells whether current environment supports Fetch API\n * {@link supportsFetch}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nconst supportsFetch = _isFetchSupported;\n\nfunction _isFetchSupported() {\n if (!('fetch' in WINDOW)) {\n return false;\n }\n\n try {\n new Headers();\n // Deno requires a valid URL so '' cannot be used as an argument\n new Request('data:,');\n new Response();\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * isNative checks if the given function is a native implementation\n */\n// eslint-disable-next-line @typescript-eslint/ban-types\nfunction isNativeFunction(func) {\n return func && /^function\\s+\\w+\\(\\)\\s+\\{\\s+\\[native code\\]\\s+\\}$/.test(func.toString());\n}\n\n/**\n * Tells whether current environment supports Fetch API natively\n * {@link supportsNativeFetch}.\n *\n * @returns true if `window.fetch` is natively implemented, false otherwise\n */\nfunction supportsNativeFetch() {\n if (typeof EdgeRuntime === 'string') {\n return true;\n }\n\n if (!_isFetchSupported()) {\n return false;\n }\n\n // Fast path to avoid DOM I/O\n // eslint-disable-next-line @typescript-eslint/unbound-method\n if (isNativeFunction(WINDOW.fetch)) {\n return true;\n }\n\n // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension)\n // so create a \"pure\" iframe to see if that has native fetch\n let result = false;\n const doc = WINDOW.document;\n // eslint-disable-next-line deprecation/deprecation\n if (doc && typeof (doc.createElement ) === 'function') {\n try {\n const sandbox = doc.createElement('iframe');\n sandbox.hidden = true;\n doc.head.appendChild(sandbox);\n if (sandbox.contentWindow?.fetch) {\n // eslint-disable-next-line @typescript-eslint/unbound-method\n result = isNativeFunction(sandbox.contentWindow.fetch);\n }\n doc.head.removeChild(sandbox);\n } catch (err) {\n DEBUG_BUILD && debug.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err);\n }\n }\n\n return result;\n}\n\n/**\n * Tells whether current environment supports ReportingObserver API\n * {@link supportsReportingObserver}.\n *\n * @returns Answer to the given question.\n */\nfunction supportsReportingObserver() {\n return 'ReportingObserver' in WINDOW;\n}\n\n/**\n * Tells whether current environment supports Referrer Policy API\n * {@link supportsReferrerPolicy}.\n *\n * @returns Answer to the given question.\n * @deprecated This is no longer used and will be removed in a future major version.\n */\nfunction supportsReferrerPolicy() {\n // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default'\n // (see https://caniuse.com/#feat=referrer-policy),\n // it doesn't. And it throws an exception instead of ignoring this parameter...\n // REF: https://github.com/getsentry/raven-js/issues/1233\n\n if (!_isFetchSupported()) {\n return false;\n }\n\n try {\n new Request('_', {\n referrerPolicy: 'origin' ,\n });\n return true;\n } catch {\n return false;\n }\n}\n\nexport { isNativeFunction, supportsDOMError, supportsDOMException, supportsErrorEvent, supportsFetch, supportsHistory, supportsNativeFetch, supportsReferrerPolicy, supportsReportingObserver };\n//# sourceMappingURL=supports.js.map\n","import { isError, isRequest } from '../utils/is.js';\nimport { fill, addNonEnumerableProperty } from '../utils/object.js';\nimport { supportsNativeFetch } from '../utils/supports.js';\nimport { timestampInSeconds } from '../utils/time.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\nimport { addHandler, maybeInstrument, triggerHandlers } from './handlers.js';\n\n/**\n * Add an instrumentation handler for when a fetch request happens.\n * The handler function is called once when the request starts and once when it ends,\n * which can be identified by checking if it has an `endTimestamp`.\n *\n * Use at your own risk, this might break without changelog notice, only used internally.\n * @hidden\n */\nfunction addFetchInstrumentationHandler(\n handler,\n skipNativeFetchCheck,\n) {\n const type = 'fetch';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(undefined, skipNativeFetchCheck));\n}\n\n/**\n * Add an instrumentation handler for long-lived fetch requests, like consuming server-sent events (SSE) via fetch.\n * The handler will resolve the request body and emit the actual `endTimestamp`, so that the\n * span can be updated accordingly.\n *\n * Only used internally\n * @hidden\n */\nfunction addFetchEndInstrumentationHandler(handler) {\n const type = 'fetch-body-resolved';\n addHandler(type, handler);\n maybeInstrument(type, () => instrumentFetch(streamHandler));\n}\n\nfunction instrumentFetch(onFetchResolved, skipNativeFetchCheck = false) {\n if (skipNativeFetchCheck && !supportsNativeFetch()) {\n return;\n }\n\n fill(GLOBAL_OBJ, 'fetch', function (originalFetch) {\n return function (...args) {\n // We capture the error right here and not in the Promise error callback because Safari (and probably other\n // browsers too) will wipe the stack trace up to this point, only leaving us with this file which is useless.\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n const virtualError = new Error();\n\n const { method, url } = parseFetchArgs(args);\n const handlerData = {\n args,\n fetchData: {\n method,\n url,\n },\n startTimestamp: timestampInSeconds() * 1000,\n // // Adding the error to be able to fingerprint the failed fetch event in HttpClient instrumentation\n virtualError,\n headers: getHeadersFromFetchArgs(args),\n };\n\n // if there is no callback, fetch is instrumented directly\n if (!onFetchResolved) {\n triggerHandlers('fetch', {\n ...handlerData,\n });\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return originalFetch.apply(GLOBAL_OBJ, args).then(\n async (response) => {\n if (onFetchResolved) {\n onFetchResolved(response);\n } else {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n }\n\n return response;\n },\n (error) => {\n triggerHandlers('fetch', {\n ...handlerData,\n endTimestamp: timestampInSeconds() * 1000,\n error,\n });\n\n if (isError(error) && error.stack === undefined) {\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the error, that was caused by your fetch call did not\n // have a stack trace, so the SDK backfilled the stack trace so\n // you can see which fetch call failed.\n error.stack = virtualError.stack;\n addNonEnumerableProperty(error, 'framesToPop', 1);\n }\n\n // We enhance the not-so-helpful \"Failed to fetch\" error messages with the host\n // Possible messages we handle here:\n // * \"Failed to fetch\" (chromium)\n // * \"Load failed\" (webkit)\n // * \"NetworkError when attempting to fetch resource.\" (firefox)\n if (\n error instanceof TypeError &&\n (error.message === 'Failed to fetch' ||\n error.message === 'Load failed' ||\n error.message === 'NetworkError when attempting to fetch resource.')\n ) {\n try {\n const url = new URL(handlerData.fetchData.url);\n error.message = `${error.message} (${url.host})`;\n } catch {\n // ignore it if errors happen here\n }\n }\n\n // NOTE: If you are a Sentry user, and you are seeing this stack frame,\n // it means the sentry.javascript SDK caught an error invoking your application code.\n // This is expected behavior and NOT indicative of a bug with sentry.javascript.\n throw error;\n },\n );\n };\n });\n}\n\nasync function resolveResponse(res, onFinishedResolving) {\n if (res?.body) {\n const body = res.body;\n const responseReader = body.getReader();\n\n // Define a maximum duration after which we just cancel\n const maxFetchDurationTimeout = setTimeout(\n () => {\n body.cancel().then(null, () => {\n // noop\n });\n },\n 90 * 1000, // 90s\n );\n\n let readingActive = true;\n while (readingActive) {\n let chunkTimeout;\n try {\n // abort reading if read op takes more than 5s\n chunkTimeout = setTimeout(() => {\n body.cancel().then(null, () => {\n // noop on error\n });\n }, 5000);\n\n // This .read() call will reject/throw when we abort due to timeouts through `body.cancel()`\n const { done } = await responseReader.read();\n\n clearTimeout(chunkTimeout);\n\n if (done) {\n onFinishedResolving();\n readingActive = false;\n }\n } catch {\n readingActive = false;\n } finally {\n clearTimeout(chunkTimeout);\n }\n }\n\n clearTimeout(maxFetchDurationTimeout);\n\n responseReader.releaseLock();\n body.cancel().then(null, () => {\n // noop on error\n });\n }\n}\n\nfunction streamHandler(response) {\n // clone response for awaiting stream\n let clonedResponseForResolving;\n try {\n clonedResponseForResolving = response.clone();\n } catch {\n return;\n }\n\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n resolveResponse(clonedResponseForResolving, () => {\n triggerHandlers('fetch-body-resolved', {\n endTimestamp: timestampInSeconds() * 1000,\n response,\n });\n });\n}\n\nfunction hasProp(obj, prop) {\n return !!obj && typeof obj === 'object' && !!(obj )[prop];\n}\n\nfunction getUrlFromResource(resource) {\n if (typeof resource === 'string') {\n return resource;\n }\n\n if (!resource) {\n return '';\n }\n\n if (hasProp(resource, 'url')) {\n return resource.url;\n }\n\n if (resource.toString) {\n return resource.toString();\n }\n\n return '';\n}\n\n/**\n * Parses the fetch arguments to find the used Http method and the url of the request.\n * Exported for tests only.\n */\nfunction parseFetchArgs(fetchArgs) {\n if (fetchArgs.length === 0) {\n return { method: 'GET', url: '' };\n }\n\n if (fetchArgs.length === 2) {\n const [resource, options] = fetchArgs ;\n\n return {\n url: getUrlFromResource(resource),\n method: hasProp(options, 'method')\n ? String(options.method).toUpperCase()\n : // Request object as first argument\n isRequest(resource) && hasProp(resource, 'method')\n ? String(resource.method).toUpperCase()\n : 'GET',\n };\n }\n\n const arg = fetchArgs[0];\n return {\n url: getUrlFromResource(arg ),\n method: hasProp(arg, 'method') ? String(arg.method).toUpperCase() : 'GET',\n };\n}\n\nfunction getHeadersFromFetchArgs(fetchArgs) {\n const [requestArgument, optionsArgument] = fetchArgs;\n\n try {\n if (\n typeof optionsArgument === 'object' &&\n optionsArgument !== null &&\n 'headers' in optionsArgument &&\n optionsArgument.headers\n ) {\n return new Headers(optionsArgument.headers );\n }\n\n if (isRequest(requestArgument)) {\n return new Headers(requestArgument.headers);\n }\n } catch {\n // noop\n }\n\n return;\n}\n\nexport { addFetchEndInstrumentationHandler, addFetchInstrumentationHandler, parseFetchArgs };\n//# sourceMappingURL=fetch.js.map\n","/*\n * This module exists for optimizations in the build process through rollup and terser. We define some global\n * constants, which can be overridden during build. By guarding certain pieces of code with functions that return these\n * constants, we can control whether or not they appear in the final bundle. (Any code guarded by a false condition will\n * never run, and will hence be dropped during treeshaking.) The two primary uses for this are stripping out calls to\n * `debug` and preventing node-related code from appearing in browser bundles.\n *\n * Attention:\n * This file should not be used to define constants/flags that are intended to be used for tree-shaking conducted by\n * users. These flags should live in their respective packages, as we identified user tooling (specifically webpack)\n * having issues tree-shaking these constants across package boundaries.\n * An example for this is the __SENTRY_DEBUG__ constant. It is declared in each package individually because we want\n * users to be able to shake away expressions that it guards.\n */\n\n/**\n * Figures out if we're building a browser bundle.\n *\n * @returns true if this is a browser bundle build.\n */\nfunction isBrowserBundle() {\n return typeof __SENTRY_BROWSER_BUNDLE__ !== 'undefined' && !!__SENTRY_BROWSER_BUNDLE__;\n}\n\n/**\n * Get source of SDK.\n */\nfunction getSDKSource() {\n // This comment is used to identify this line in the CDN bundle build step and replace this with \"return 'cdn';\"\n /* __SENTRY_SDK_SOURCE__ */ return 'npm';\n}\n\nexport { getSDKSource, isBrowserBundle };\n//# sourceMappingURL=env.js.map\n","import { isBrowserBundle } from './env.js';\n\n/**\n * NOTE: In order to avoid circular dependencies, if you add a function to this module and it needs to print something,\n * you must either a) use `console.log` rather than the `debug` singleton, or b) put your function elsewhere.\n */\n\n\n/**\n * Checks whether we're in the Node.js or Browser environment\n *\n * @returns Answer to given question\n */\nfunction isNodeEnv() {\n // explicitly check for browser bundles as those can be optimized statically\n // by terser/rollup.\n return (\n !isBrowserBundle() &&\n Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'\n );\n}\n\n/**\n * Requires a module which is protected against bundler minification.\n *\n * @param request The module path to resolve\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction dynamicRequire(mod, request) {\n // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n return mod.require(request);\n}\n\n/**\n * Helper for dynamically loading module that should work with linked dependencies.\n * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))`\n * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during\n * build time. `require.resolve` is also not available in any other way, so we cannot create,\n * a fake helper like we do with `dynamicRequire`.\n *\n * We always prefer to use local package, thus the value is not returned early from each `try/catch` block.\n * That is to mimic the behavior of `require.resolve` exactly.\n *\n * @param moduleName module name to require\n * @param existingModule module to use for requiring\n * @returns possibly required module\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction loadModule(moduleName, existingModule = module) {\n let mod;\n\n try {\n mod = dynamicRequire(existingModule, moduleName);\n } catch {\n // no-empty\n }\n\n if (!mod) {\n try {\n const { cwd } = dynamicRequire(existingModule, 'process');\n mod = dynamicRequire(existingModule, `${cwd()}/node_modules/${moduleName}`) ;\n } catch {\n // no-empty\n }\n }\n\n return mod;\n}\n\nexport { isNodeEnv, loadModule };\n//# sourceMappingURL=node.js.map\n","import { UNKNOWN_FUNCTION } from './stacktrace.js';\n\n/**\n * Does this filename look like it's part of the app code?\n */\nfunction filenameIsInApp(filename, isNative = false) {\n const isInternal =\n isNative ||\n (filename &&\n // It's not internal if it's an absolute linux path\n !filename.startsWith('/') &&\n // It's not internal if it's an absolute windows path\n !filename.match(/^[A-Z]:/) &&\n // It's not internal if the path is starting with a dot\n !filename.startsWith('.') &&\n // 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\n !filename.match(/^[a-zA-Z]([a-zA-Z0-9.\\-+])*:\\/\\//)); // Schema from: https://stackoverflow.com/a/3641782\n\n // in_app is all that's not an internal Node function or a module within node_modules\n // note that isNative appears to return true even for node core libraries\n // see https://github.com/getsentry/raven-node/issues/176\n\n return !isInternal && filename !== undefined && !filename.includes('node_modules/');\n}\n\n/** Node Stack line parser */\nfunction node(getModule) {\n const FILENAME_MATCH = /^\\s*[-]{4,}$/;\n const FULL_MATCH = /at (?:async )?(?:(.+?)\\s+\\()?(?:(.+):(\\d+):(\\d+)?|([^)]+))\\)?/;\n const DATA_URI_MATCH = /at (?:async )?(.+?) \\(data:(.*?),/;\n\n // eslint-disable-next-line complexity\n return (line) => {\n const dataUriMatch = line.match(DATA_URI_MATCH);\n if (dataUriMatch) {\n return {\n filename: `<data:${dataUriMatch[2]}>`,\n function: dataUriMatch[1],\n };\n }\n\n const lineMatch = line.match(FULL_MATCH);\n\n if (lineMatch) {\n let object;\n let method;\n let functionName;\n let typeName;\n let methodName;\n\n if (lineMatch[1]) {\n functionName = lineMatch[1];\n\n let methodStart = functionName.lastIndexOf('.');\n if (functionName[methodStart - 1] === '.') {\n methodStart--;\n }\n\n if (methodStart > 0) {\n object = functionName.slice(0, methodStart);\n method = functionName.slice(methodStart + 1);\n const objectEnd = object.indexOf('.Module');\n if (objectEnd > 0) {\n functionName = functionName.slice(objectEnd + 1);\n object = object.slice(0, objectEnd);\n }\n }\n typeName = undefined;\n }\n\n if (method) {\n typeName = object;\n methodName = method;\n }\n\n if (method === '<anonymous>') {\n methodName = undefined;\n functionName = undefined;\n }\n\n if (functionName === undefined) {\n methodName = methodName || UNKNOWN_FUNCTION;\n functionName = typeName ? `${typeName}.${methodName}` : methodName;\n }\n\n let filename = lineMatch[2]?.startsWith('file://') ? lineMatch[2].slice(7) : lineMatch[2];\n const isNative = lineMatch[5] === 'native';\n\n // If it's a Windows path, trim the leading slash so that `/C:/foo` becomes `C:/foo`\n if (filename?.match(/\\/[A-Z]:/)) {\n filename = filename.slice(1);\n }\n\n if (!filename && lineMatch[5] && !isNative) {\n filename = lineMatch[5];\n }\n\n return {\n filename: filename ? decodeURI(filename) : undefined,\n module: getModule ? getModule(filename) : undefined,\n function: functionName,\n lineno: _parseIntOrUndefined(lineMatch[3]),\n colno: _parseIntOrUndefined(lineMatch[4]),\n in_app: filenameIsInApp(filename || '', isNative),\n };\n }\n\n if (line.match(FILENAME_MATCH)) {\n return {\n filename: line,\n };\n }\n\n return undefined;\n };\n}\n\n/**\n * Node.js stack line parser\n *\n * This is in @sentry/core so it can be used from the Electron SDK in the browser for when `nodeIntegration == true`.\n * This allows it to be used without referencing or importing any node specific code which causes bundlers to complain\n */\nfunction nodeStackLineParser(getModule) {\n return [90, node(getModule)];\n}\n\nfunction _parseIntOrUndefined(input) {\n return parseInt(input || '', 10) || undefined;\n}\n\nexport { filenameIsInApp, node, nodeStackLineParser };\n//# sourceMappingURL=node-stack-trace.js.map\n","import { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Function that delays closing of a Vercel lambda until the provided promise is resolved.\n *\n * Vendored from https://www.npmjs.com/package/@vercel/functions\n */\nfunction vercelWaitUntil(task) {\n const vercelRequestContextGlobal =\n // @ts-expect-error This is not typed\n GLOBAL_OBJ[Symbol.for('@vercel/request-context')];\n\n const ctx = vercelRequestContextGlobal?.get?.();\n\n if (ctx?.waitUntil) {\n ctx.waitUntil(task);\n }\n}\n\nexport { vercelWaitUntil };\n//# sourceMappingURL=vercelWaitUntil.js.map\n","import { flush } from '../exports.js';\nimport { debug } from './debug-logger.js';\nimport { vercelWaitUntil } from './vercelWaitUntil.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\nasync function flushWithTimeout(timeout) {\n try {\n debug.log('Flushing events...');\n await flush(timeout);\n debug.log('Done flushing events');\n } catch (e) {\n debug.log('Error while flushing events:\\n', e);\n }\n}\n\n/**\n * Flushes the event queue with a timeout in serverless environments to ensure that events are sent to Sentry before the\n * serverless function execution ends.\n *\n * The function is async, but in environments that support a `waitUntil` mechanism, it will run synchronously.\n *\n * This function is aware of the following serverless platforms:\n * - Cloudflare: If a Cloudflare context is provided, it will use `ctx.waitUntil()` to flush events (keeps the `this` context of `ctx`).\n * If a `cloudflareWaitUntil` function is provided, it will use that to flush events (looses the `this` context of `ctx`).\n * - Vercel: It detects the Vercel environment and uses Vercel's `waitUntil` function.\n * - Other Serverless (AWS Lambda, Google Cloud, etc.): It detects the environment via environment variables\n * and uses a regular `await flush()`.\n *\n * @internal This function is supposed for internal Sentry SDK usage only.\n * @hidden\n */\nasync function flushIfServerless(\n params\n\n = {},\n) {\n const { timeout = 2000 } = params;\n\n if ('cloudflareWaitUntil' in params && typeof params?.cloudflareWaitUntil === 'function') {\n params.cloudflareWaitUntil(flushWithTimeout(timeout));\n return;\n }\n\n if ('cloudflareCtx' in params && typeof params.cloudflareCtx?.waitUntil === 'function') {\n params.cloudflareCtx.waitUntil(flushWithTimeout(timeout));\n return;\n }\n\n // @ts-expect-error This is not typed\n if (GLOBAL_OBJ[Symbol.for('@vercel/request-context')]) {\n // Vercel has a waitUntil equivalent that works without execution context\n vercelWaitUntil(flushWithTimeout(timeout));\n return;\n }\n\n if (typeof process === 'undefined') {\n return;\n }\n\n const isServerless =\n !!process.env.FUNCTIONS_WORKER_RUNTIME || // Azure Functions\n !!process.env.LAMBDA_TASK_ROOT || // AWS Lambda\n !!process.env.K_SERVICE || // Google Cloud Run\n !!process.env.CF_PAGES || // Cloudflare Pages\n !!process.env.VERCEL ||\n !!process.env.NETLIFY;\n\n if (isServerless) {\n // Use regular flush for environments without a generic waitUntil mechanism\n await flushWithTimeout(timeout);\n }\n}\n\nexport { flushIfServerless };\n//# sourceMappingURL=flushIfServerless.js.map\n","/**\n * Takes the SDK metadata and adds the user-agent header to the transport options.\n * This ensures that the SDK sends the user-agent header with SDK name and version to\n * all requests made by the transport.\n *\n * @see https://develop.sentry.dev/sdk/overview/#user-agent\n */\nfunction addUserAgentToTransportHeaders(options) {\n const sdkMetadata = options._metadata?.sdk;\n const sdkUserAgent =\n sdkMetadata?.name && sdkMetadata?.version ? `${sdkMetadata?.name}/${sdkMetadata?.version}` : undefined;\n\n options.transportOptions = {\n ...options.transportOptions,\n headers: {\n ...(sdkUserAgent && { 'user-agent': sdkUserAgent }),\n ...options.transportOptions?.headers,\n },\n };\n}\n\nexport { addUserAgentToTransportHeaders };\n//# sourceMappingURL=userAgent.js.map\n","// By default, we want to infer the IP address, unless this is explicitly set to `null`\n// We do this after all other processing is done\n// If `ip_address` is explicitly set to `null` or a value, we leave it as is\n\n/**\n * @internal\n * @deprecated -- set ip inferral via via SDK metadata options on client instead.\n */\nfunction addAutoIpAddressToUser(objWithMaybeUser) {\n if (objWithMaybeUser.user?.ip_address === undefined) {\n objWithMaybeUser.user = {\n ...objWithMaybeUser.user,\n ip_address: '{{auto}}',\n };\n }\n}\n\n/**\n * @internal\n */\nfunction addAutoIpAddressToSession(session) {\n if ('aggregates' in session) {\n if (session.attrs?.['ip_address'] === undefined) {\n session.attrs = {\n ...session.attrs,\n ip_address: '{{auto}}',\n };\n }\n } else {\n if (session.ipAddress === undefined) {\n session.ipAddress = '{{auto}}';\n }\n }\n}\n\nexport { addAutoIpAddressToSession, addAutoIpAddressToUser };\n//# sourceMappingURL=ipAddress.js.map\n","import { SDK_VERSION } from './version.js';\n\n/**\n * A builder for the SDK metadata in the options for the SDK initialization.\n *\n * Note: This function is identical to `buildMetadata` in Remix and NextJS and SvelteKit.\n * We don't extract it for bundle size reasons.\n * @see https://github.com/getsentry/sentry-javascript/pull/7404\n * @see https://github.com/getsentry/sentry-javascript/pull/4196\n *\n * If you make changes to this function consider updating the others as well.\n *\n * @param options SDK options object that gets mutated\n * @param names list of package names\n */\nfunction applySdkMetadata(options, name, names = [name], source = 'npm') {\n const metadata = options._metadata || {};\n\n if (!metadata.sdk) {\n metadata.sdk = {\n name: `sentry.javascript.${name}`,\n packages: names.map(name => ({\n name: `${source}:@sentry/${name}`,\n version: SDK_VERSION,\n })),\n version: SDK_VERSION,\n };\n }\n\n options._metadata = metadata;\n}\n\nexport { applySdkMetadata };\n//# sourceMappingURL=sdkMetadata.js.map\n","import { getTraceData } from './traceData.js';\n\n/**\n * Returns a string of meta tags that represent the current trace data.\n *\n * You can use this to propagate a trace from your server-side rendered Html to the browser.\n * This function returns up to two meta tags, `sentry-trace` and `baggage`, depending on the\n * current trace data state.\n *\n * @example\n * Usage example:\n *\n * ```js\n * function renderHtml() {\n * return `\n * <head>\n * ${getTraceMetaTags()}\n * </head>\n * `;\n * }\n * ```\n *\n */\nfunction getTraceMetaTags(traceData) {\n return Object.entries(traceData || getTraceData())\n .map(([key, value]) => `<meta name=\"${key}\" content=\"${value}\"/>`)\n .join('\\n');\n}\n\nexport { getTraceMetaTags };\n//# sourceMappingURL=meta.js.map\n","/**\n * Heavily simplified debounce function based on lodash.debounce.\n *\n * This function takes a callback function (@param fun) and delays its invocation\n * by @param wait milliseconds. Optionally, a maxWait can be specified in @param options,\n * which ensures that the callback is invoked at least once after the specified max. wait time.\n *\n * @param func the function whose invocation is to be debounced\n * @param wait the minimum time until the function is invoked after it was called once\n * @param options the options object, which can contain the `maxWait` property\n *\n * @returns the debounced version of the function, which needs to be called at least once to start the\n * debouncing process. Subsequent calls will reset the debouncing timer and, in case @paramfunc\n * was already invoked in the meantime, return @param func's return value.\n * The debounced function has two additional properties:\n * - `flush`: Invokes the debounced function immediately and returns its return value\n * - `cancel`: Cancels the debouncing process and resets the debouncing timer\n */\nfunction debounce(func, wait, options) {\n let callbackReturnValue;\n\n let timerId;\n let maxTimerId;\n\n const maxWait = options?.maxWait ? Math.max(options.maxWait, wait) : 0;\n const setTimeoutImpl = options?.setTimeoutImpl || setTimeout;\n\n function invokeFunc() {\n cancelTimers();\n callbackReturnValue = func();\n return callbackReturnValue;\n }\n\n function cancelTimers() {\n timerId !== undefined && clearTimeout(timerId);\n maxTimerId !== undefined && clearTimeout(maxTimerId);\n timerId = maxTimerId = undefined;\n }\n\n function flush() {\n if (timerId !== undefined || maxTimerId !== undefined) {\n return invokeFunc();\n }\n return callbackReturnValue;\n }\n\n function debounced() {\n if (timerId) {\n clearTimeout(timerId);\n }\n timerId = setTimeoutImpl(invokeFunc, wait);\n\n if (maxWait && maxTimerId === undefined) {\n maxTimerId = setTimeoutImpl(invokeFunc, maxWait);\n }\n\n return callbackReturnValue;\n }\n\n debounced.cancel = cancelTimers;\n debounced.flush = flush;\n return debounced;\n}\n\nexport { debounce };\n//# sourceMappingURL=debounce.js.map\n","import { getClient, withScope } from '../currentScopes.js';\nimport { captureException } from '../exports.js';\nimport { addConsoleInstrumentationHandler } from '../instrument/console.js';\nimport { defineIntegration } from '../integration.js';\nimport { CONSOLE_LEVELS } from '../utils/debug-logger.js';\nimport { addExceptionMechanism } from '../utils/misc.js';\nimport { severityLevelFromString } from '../utils/severity.js';\nimport { safeJoin } from '../utils/string.js';\nimport { GLOBAL_OBJ } from '../utils/worldwide.js';\n\nconst INTEGRATION_NAME = 'CaptureConsole';\n\nconst _captureConsoleIntegration = ((options = {}) => {\n const levels = options.levels || CONSOLE_LEVELS;\n const handled = options.handled ?? true;\n\n return {\n name: INTEGRATION_NAME,\n setup(client) {\n if (!('console' in GLOBAL_OBJ)) {\n return;\n }\n\n addConsoleInstrumentationHandler(({ args, level }) => {\n if (getClient() !== client || !levels.includes(level)) {\n return;\n }\n\n consoleHandler(args, level, handled);\n });\n },\n };\n}) ;\n\n/**\n * Send Console API calls as Sentry Events.\n */\nconst captureConsoleIntegration = defineIntegration(_captureConsoleIntegration);\n\nfunction consoleHandler(args, level, handled) {\n const severityLevel = severityLevelFromString(level);\n\n /*\n We create this error here already to attach a stack trace to captured messages,\n if users set `attachStackTrace` to `true` in Sentry.init.\n We do this here already because we want to minimize the number of Sentry SDK stack frames\n within the error. Technically, Client.captureMessage will also do it but this happens several\n stack frames deeper.\n */\n const syntheticException = new Error();\n\n const captureContext = {\n level: severityLevelFromString(level),\n extra: {\n arguments: args,\n },\n };\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n event.logger = 'console';\n\n addExceptionMechanism(event, {\n handled,\n type: 'auto.core.capture_console',\n });\n\n return event;\n });\n\n if (level === 'assert') {\n if (!args[0]) {\n const message = `Assertion failed: ${safeJoin(args.slice(1), ' ') || 'console.assert'}`;\n scope.setExtra('arguments', args.slice(1));\n scope.captureMessage(message, severityLevel, { captureContext, syntheticException });\n }\n return;\n }\n\n const error = args.find(arg => arg instanceof Error);\n if (error) {\n captureException(error, captureContext);\n return;\n }\n\n const message = safeJoin(args, ' ');\n scope.captureMessage(message, severityLevel, { captureContext, syntheticException });\n });\n}\n\nexport { captureConsoleIntegration };\n//# sourceMappingURL=captureconsole.js.map\n","import { defineIntegration } from '../integration.js';\nimport { addMetadataToStackFrames, stripMetadataFromStackFrames } from '../metadata.js';\nimport { forEachEnvelopeItem } from '../utils/envelope.js';\nimport { getFramesFromEvent } from '../utils/stacktrace.js';\n\n/**\n * This integration allows you to filter out, or tag error events that do not come from user code marked with a bundle key via the Sentry bundler plugins.\n */\nconst thirdPartyErrorFilterIntegration = defineIntegration((options) => {\n return {\n name: 'ThirdPartyErrorsFilter',\n setup(client) {\n // We need to strip metadata from stack frames before sending them to Sentry since these are client side only.\n client.on('beforeEnvelope', envelope => {\n forEachEnvelopeItem(envelope, (item, type) => {\n if (type === 'event') {\n const event = Array.isArray(item) ? (item )[1] : undefined;\n\n if (event) {\n stripMetadataFromStackFrames(event);\n item[1] = event;\n }\n }\n });\n });\n\n client.on('applyFrameMetadata', event => {\n // Only apply stack frame metadata to error events\n if (event.type) {\n return;\n }\n\n const stackParser = client.getOptions().stackParser;\n addMetadataToStackFrames(stackParser, event);\n });\n },\n\n processEvent(event) {\n const frameKeys = getBundleKeysForAllFramesWithFilenames(event);\n\n if (frameKeys) {\n const arrayMethod =\n options.behaviour === 'drop-error-if-contains-third-party-frames' ||\n options.behaviour === 'apply-tag-if-contains-third-party-frames'\n ? 'some'\n : 'every';\n\n const behaviourApplies = frameKeys[arrayMethod](keys => !keys.some(key => options.filterKeys.includes(key)));\n\n if (behaviourApplies) {\n const shouldDrop =\n options.behaviour === 'drop-error-if-contains-third-party-frames' ||\n options.behaviour === 'drop-error-if-exclusively-contains-third-party-frames';\n if (shouldDrop) {\n return null;\n } else {\n event.tags = {\n ...event.tags,\n third_party_code: true,\n };\n }\n }\n }\n\n return event;\n },\n };\n});\n\nfunction getBundleKeysForAllFramesWithFilenames(event) {\n const frames = getFramesFromEvent(event);\n\n if (!frames) {\n return undefined;\n }\n\n return (\n frames\n // Exclude frames without a filename or without lineno and colno,\n // since these are likely native code or built-ins\n .filter(frame => !!frame.filename && (frame.lineno ?? frame.colno) != null)\n .map(frame => {\n if (frame.module_metadata) {\n return Object.keys(frame.module_metadata)\n .filter(key => key.startsWith(BUNDLER_PLUGIN_APP_KEY_PREFIX))\n .map(key => key.slice(BUNDLER_PLUGIN_APP_KEY_PREFIX.length));\n }\n return [];\n })\n );\n}\n\nconst BUNDLER_PLUGIN_APP_KEY_PREFIX = '_sentryBundlerPluginAppKey:';\n\nexport { thirdPartyErrorFilterIntegration };\n//# sourceMappingURL=third-party-errors-filter.js.map\n","import { defineIntegration } from '../../integration.js';\nimport { _INTERNAL_insertFlagToScope, _INTERNAL_addFeatureFlagToActiveSpan, _INTERNAL_copyFlagsFromScopeToEvent } from '../../utils/featureFlags.js';\n\n/**\n * Sentry integration for buffering feature flag evaluations manually with an API, and\n * capturing them on error events and spans.\n *\n * See the [feature flag documentation](https://develop.sentry.dev/sdk/expected-features/#feature-flags) for more information.\n *\n * @example\n * ```\n * import * as Sentry from '@sentry/browser';\n * import { type FeatureFlagsIntegration } from '@sentry/browser';\n *\n * // Setup\n * Sentry.init(..., integrations: [Sentry.featureFlagsIntegration()])\n *\n * // Verify\n * const flagsIntegration = Sentry.getClient()?.getIntegrationByName<FeatureFlagsIntegration>('FeatureFlags');\n * if (flagsIntegration) {\n * flagsIntegration.addFeatureFlag('my-flag', true);\n * } else {\n * // check your setup\n * }\n * Sentry.captureException(Exception('broke')); // 'my-flag' should be captured to this Sentry event.\n * ```\n */\nconst featureFlagsIntegration = defineIntegration(() => {\n return {\n name: 'FeatureFlags',\n\n processEvent(event, _hint, _client) {\n return _INTERNAL_copyFlagsFromScopeToEvent(event);\n },\n\n addFeatureFlag(name, value) {\n _INTERNAL_insertFlagToScope(name, value);\n _INTERNAL_addFeatureFlagToActiveSpan(name, value);\n },\n };\n}) ;\n\nexport { featureFlagsIntegration };\n//# sourceMappingURL=featureFlagsIntegration.js.map\n","import { getIsolationScope, withIsolationScope } from '../../currentScopes.js';\nimport { fill } from '../../utils/object.js';\nimport { startInactiveSpan, withActiveSpan } from '../../tracing/trace.js';\nimport { MCP_PROTOCOL_VERSION_ATTRIBUTE } from './attributes.js';\nimport { storeSpanForRequest, completeSpanWithResults, cleanupPendingSpansForTransport } from './correlation.js';\nimport { captureError } from './errorCapture.js';\nimport { extractSessionDataFromInitializeRequest, buildClientAttributesFromInfo, extractSessionDataFromInitializeResponse } from './sessionExtraction.js';\nimport { storeSessionDataForTransport, updateSessionDataForTransport, cleanupSessionDataForTransport } from './sessionManagement.js';\nimport { buildMcpServerSpanConfig, createMcpNotificationSpan, createMcpOutgoingNotificationSpan } from './spans.js';\nimport { isJsonRpcRequest, isJsonRpcNotification, isJsonRpcResponse, isValidContentItem } from './validation.js';\n\n/**\n * Transport layer instrumentation for MCP server\n *\n * Handles message interception and response correlation.\n * @see https://modelcontextprotocol.io/specification/2025-06-18/basic/transports\n */\n\n\n/**\n * Wraps transport.onmessage to create spans for incoming messages.\n * For \"initialize\" requests, extracts and stores client info and protocol version\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n */\nfunction wrapTransportOnMessage(transport) {\n if (transport.onmessage) {\n fill(transport, 'onmessage', originalOnMessage => {\n return function ( message, extra) {\n if (isJsonRpcRequest(message)) {\n const isInitialize = message.method === 'initialize';\n let initSessionData;\n\n if (isInitialize) {\n try {\n initSessionData = extractSessionDataFromInitializeRequest(message);\n storeSessionDataForTransport(this, initSessionData);\n } catch {\n // noop\n }\n }\n\n const isolationScope = getIsolationScope().clone();\n\n return withIsolationScope(isolationScope, () => {\n const spanConfig = buildMcpServerSpanConfig(message, this, extra );\n const span = startInactiveSpan(spanConfig);\n\n // For initialize requests, add client info directly to span (works even for stateless transports)\n if (isInitialize && initSessionData) {\n span.setAttributes({\n ...buildClientAttributesFromInfo(initSessionData.clientInfo),\n ...(initSessionData.protocolVersion && {\n [MCP_PROTOCOL_VERSION_ATTRIBUTE]: initSessionData.protocolVersion,\n }),\n });\n }\n\n storeSpanForRequest(this, message.id, span, message.method);\n\n return withActiveSpan(span, () => {\n return (originalOnMessage ).call(this, message, extra);\n });\n });\n }\n\n if (isJsonRpcNotification(message)) {\n return createMcpNotificationSpan(message, this, extra , () => {\n return (originalOnMessage ).call(this, message, extra);\n });\n }\n\n return (originalOnMessage ).call(this, message, extra);\n };\n });\n }\n}\n\n/**\n * Wraps transport.send to handle outgoing messages and response correlation.\n * For \"initialize\" responses, extracts and stores protocol version and server info\n * in the session data for the transport.\n * @param transport - MCP transport instance to wrap\n */\nfunction wrapTransportSend(transport) {\n if (transport.send) {\n fill(transport, 'send', originalSend => {\n return async function ( ...args) {\n const [message] = args;\n\n if (isJsonRpcNotification(message)) {\n return createMcpOutgoingNotificationSpan(message, this, () => {\n return (originalSend ).call(this, ...args);\n });\n }\n\n if (isJsonRpcResponse(message)) {\n if (message.id !== null && message.id !== undefined) {\n if (message.error) {\n captureJsonRpcErrorResponse(message.error);\n }\n\n if (isValidContentItem(message.result)) {\n if (message.result.protocolVersion || message.result.serverInfo) {\n try {\n const serverData = extractSessionDataFromInitializeResponse(message.result);\n updateSessionDataForTransport(this, serverData);\n } catch {\n // noop\n }\n }\n }\n\n completeSpanWithResults(this, message.id, message.result);\n }\n }\n\n return (originalSend ).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport.onclose to clean up pending spans for this transport only\n * @param transport - MCP transport instance to wrap\n */\nfunction wrapTransportOnClose(transport) {\n if (transport.onclose) {\n fill(transport, 'onclose', originalOnClose => {\n return function ( ...args) {\n cleanupPendingSpansForTransport(this);\n cleanupSessionDataForTransport(this);\n return (originalOnClose ).call(this, ...args);\n };\n });\n }\n}\n\n/**\n * Wraps transport error handlers to capture connection errors\n * @param transport - MCP transport instance to wrap\n */\nfunction wrapTransportError(transport) {\n if (transport.onerror) {\n fill(transport, 'onerror', (originalOnError) => {\n return function ( error) {\n captureTransportError(error);\n return originalOnError.call(this, error);\n };\n });\n }\n}\n\n/**\n * Captures JSON-RPC error responses for server-side errors.\n * @see https://www.jsonrpc.org/specification#error_object\n * @internal\n * @param errorResponse - JSON-RPC error response\n */\nfunction captureJsonRpcErrorResponse(errorResponse) {\n try {\n if (errorResponse && typeof errorResponse === 'object' && 'code' in errorResponse && 'message' in errorResponse) {\n const jsonRpcError = errorResponse ;\n\n const isServerError =\n jsonRpcError.code === -32603 || (jsonRpcError.code >= -32099 && jsonRpcError.code <= -32000);\n\n if (isServerError) {\n const error = new Error(jsonRpcError.message);\n error.name = `JsonRpcError_${jsonRpcError.code}`;\n\n captureError(error, 'protocol');\n }\n }\n } catch {\n // noop\n }\n}\n\n/**\n * Captures transport connection errors\n * @internal\n * @param error - Transport error\n */\nfunction captureTransportError(error) {\n try {\n captureError(error, 'transport');\n } catch {\n // noop\n }\n}\n\nexport { wrapTransportError, wrapTransportOnClose, wrapTransportOnMessage, wrapTransportSend };\n//# sourceMappingURL=transport.js.map\n","import { MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE, MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE, MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE, MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE } from './attributes.js';\nimport { isValidContentItem } from './validation.js';\n\n/**\n * Result extraction functions for MCP server instrumentation\n *\n * Handles extraction of attributes from tool and prompt execution results.\n */\n\n\n/**\n * Build attributes for tool result content items\n * @param content - Array of content items from tool result\n * @returns Attributes extracted from each content item including type, text, mime type, URI, and resource info\n */\nfunction buildAllContentItemAttributes(content) {\n const attributes = {\n [MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE]: content.length,\n };\n\n for (const [i, item] of content.entries()) {\n if (!isValidContentItem(item)) {\n continue;\n }\n\n const prefix = content.length === 1 ? 'mcp.tool.result' : `mcp.tool.result.${i}`;\n\n const safeSet = (key, value) => {\n if (typeof value === 'string') {\n attributes[`${prefix}.${key}`] = value;\n }\n };\n\n safeSet('content_type', item.type);\n safeSet('mime_type', item.mimeType);\n safeSet('uri', item.uri);\n safeSet('name', item.name);\n\n if (typeof item.text === 'string') {\n attributes[`${prefix}.content`] = item.text;\n }\n\n if (typeof item.data === 'string') {\n attributes[`${prefix}.data_size`] = item.data.length;\n }\n\n const resource = item.resource;\n if (isValidContentItem(resource)) {\n safeSet('resource_uri', resource.uri);\n safeSet('resource_mime_type', resource.mimeType);\n }\n }\n\n return attributes;\n}\n\n/**\n * Extract tool result attributes for span instrumentation\n * @param result - Tool execution result\n * @returns Attributes extracted from tool result content\n */\nfunction extractToolResultAttributes(result) {\n if (!isValidContentItem(result)) {\n return {};\n }\n\n const attributes = Array.isArray(result.content) ? buildAllContentItemAttributes(result.content) : {};\n\n if (typeof result.isError === 'boolean') {\n attributes[MCP_TOOL_RESULT_IS_ERROR_ATTRIBUTE] = result.isError;\n }\n\n return attributes;\n}\n\n/**\n * Extract prompt result attributes for span instrumentation\n * @param result - Prompt execution result\n * @returns Attributes extracted from prompt result\n */\nfunction extractPromptResultAttributes(result) {\n const attributes = {};\n if (!isValidContentItem(result)) {\n return attributes;\n }\n\n if (typeof result.description === 'string') {\n attributes[MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE] = result.description;\n }\n\n if (Array.isArray(result.messages)) {\n attributes[MCP_PROMPT_RESULT_MESSAGE_COUNT_ATTRIBUTE] = result.messages.length;\n\n const messages = result.messages;\n for (const [i, message] of messages.entries()) {\n if (!isValidContentItem(message)) {\n continue;\n }\n\n const prefix = messages.length === 1 ? 'mcp.prompt.result' : `mcp.prompt.result.${i}`;\n\n const safeSet = (key, value) => {\n if (typeof value === 'string') {\n const attrName = messages.length === 1 ? `${prefix}.message_${key}` : `${prefix}.${key}`;\n attributes[attrName] = value;\n }\n };\n\n safeSet('role', message.role);\n\n if (isValidContentItem(message.content)) {\n const content = message.content;\n if (typeof content.text === 'string') {\n const attrName = messages.length === 1 ? `${prefix}.message_content` : `${prefix}.content`;\n attributes[attrName] = content.text;\n }\n }\n }\n }\n\n return attributes;\n}\n\nexport { extractPromptResultAttributes, extractToolResultAttributes };\n//# sourceMappingURL=resultExtraction.js.map\n","import { getCurrentScope, getClient } from './currentScopes.js';\n\n/**\n * Send user feedback to Sentry.\n */\nfunction captureFeedback(\n params,\n hint = {},\n scope = getCurrentScope(),\n) {\n const { message, name, email, url, source, associatedEventId, tags } = params;\n\n const feedbackEvent = {\n contexts: {\n feedback: {\n contact_email: email,\n name,\n message,\n url,\n source,\n associated_event_id: associatedEventId,\n },\n },\n type: 'feedback',\n level: 'info',\n tags,\n };\n\n const client = scope?.getClient() || getClient();\n\n if (client) {\n client.emit('beforeSendFeedback', feedbackEvent, hint);\n }\n\n const eventId = scope.captureEvent(feedbackEvent, hint);\n\n return eventId;\n}\n\nexport { captureFeedback };\n//# sourceMappingURL=feedback.js.map\n","import { captureException } from '../../exports.js';\nimport { SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '../../semanticAttributes.js';\nimport { SPAN_STATUS_ERROR } from '../spanstatus.js';\nimport { startSpanManual } from '../trace.js';\nimport { GEN_AI_REQUEST_MODEL_ATTRIBUTE, GEN_AI_OPERATION_NAME_ATTRIBUTE } from '../ai/gen-ai-attributes.js';\nimport { LANGCHAIN_ORIGIN } from './constants.js';\nimport { extractLlmResponseAttributes, getInvocationParams, extractChatModelRequestAttributes, extractLLMRequestAttributes } from './utils.js';\n\n/**\n * Creates a Sentry callback handler for LangChain\n * Returns a plain object that LangChain will call via duck-typing\n *\n * This is a stateful handler that tracks spans across multiple LangChain executions.\n */\nfunction createLangChainCallbackHandler(options = {}) {\n const recordInputs = options.recordInputs ?? false;\n const recordOutputs = options.recordOutputs ?? false;\n\n // Internal state - single instance tracks all spans\n const spanMap = new Map();\n\n /**\n * Exit a span and clean up\n */\n const exitSpan = (runId) => {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n span.end();\n spanMap.delete(runId);\n }\n };\n\n /**\n * Handler for LLM Start\n * This handler will be called by LangChain's callback handler when an LLM event is detected.\n */\n const handler = {\n // Required LangChain BaseCallbackHandler properties\n lc_serializable: false,\n lc_namespace: ['langchain_core', 'callbacks', 'sentry'],\n lc_secrets: undefined,\n lc_attributes: undefined,\n lc_aliases: undefined,\n lc_serializable_keys: undefined,\n lc_id: ['langchain_core', 'callbacks', 'sentry'],\n lc_kwargs: {},\n name: 'SentryCallbackHandler',\n\n // BaseCallbackHandlerInput boolean flags\n ignoreLLM: false,\n ignoreChain: false,\n ignoreAgent: false,\n ignoreRetriever: false,\n ignoreCustomEvent: false,\n raiseError: false,\n awaitHandlers: true,\n\n handleLLMStart(\n llm,\n prompts,\n runId,\n _parentRunId,\n _extraParams,\n tags,\n metadata,\n _runName,\n ) {\n const invocationParams = getInvocationParams(tags);\n const attributes = extractLLMRequestAttributes(\n llm ,\n prompts,\n recordInputs,\n invocationParams,\n metadata,\n );\n const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE];\n const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE];\n\n startSpanManual(\n {\n name: `${operationName} ${modelName}`,\n op: 'gen_ai.pipeline',\n attributes: {\n ...attributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.pipeline',\n },\n },\n span => {\n spanMap.set(runId, span);\n return span;\n },\n );\n },\n\n // Chat Model Start Handler\n handleChatModelStart(\n llm,\n messages,\n runId,\n _parentRunId,\n _extraParams,\n tags,\n metadata,\n _runName,\n ) {\n const invocationParams = getInvocationParams(tags);\n const attributes = extractChatModelRequestAttributes(\n llm ,\n messages ,\n recordInputs,\n invocationParams,\n metadata,\n );\n const modelName = attributes[GEN_AI_REQUEST_MODEL_ATTRIBUTE];\n const operationName = attributes[GEN_AI_OPERATION_NAME_ATTRIBUTE];\n\n startSpanManual(\n {\n name: `${operationName} ${modelName}`,\n op: 'gen_ai.chat',\n attributes: {\n ...attributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.chat',\n },\n },\n span => {\n spanMap.set(runId, span);\n return span;\n },\n );\n },\n\n // LLM End Handler - note: handleLLMEnd with capital LLM (used by both LLMs and chat models!)\n handleLLMEnd(\n output,\n runId,\n _parentRunId,\n _tags,\n _extraParams,\n ) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n const attributes = extractLlmResponseAttributes(output , recordOutputs);\n if (attributes) {\n span.setAttributes(attributes);\n }\n exitSpan(runId);\n }\n },\n\n // LLM Error Handler - note: handleLLMError with capital LLM\n handleLLMError(error, runId) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'llm_error' });\n exitSpan(runId);\n }\n\n captureException(error, {\n mechanism: {\n handled: false,\n type: `${LANGCHAIN_ORIGIN}.llm_error_handler`,\n },\n });\n },\n\n // Chain Start Handler\n handleChainStart(chain, inputs, runId, _parentRunId) {\n const chainName = chain.name || 'unknown_chain';\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.ai.langchain',\n 'langchain.chain.name': chainName,\n };\n\n // Add inputs if recordInputs is enabled\n if (recordInputs) {\n attributes['langchain.chain.inputs'] = JSON.stringify(inputs);\n }\n\n startSpanManual(\n {\n name: `chain ${chainName}`,\n op: 'gen_ai.invoke_agent',\n attributes: {\n ...attributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.invoke_agent',\n },\n },\n span => {\n spanMap.set(runId, span);\n return span;\n },\n );\n },\n\n // Chain End Handler\n handleChainEnd(outputs, runId) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n // Add outputs if recordOutputs is enabled\n if (recordOutputs) {\n span.setAttributes({\n 'langchain.chain.outputs': JSON.stringify(outputs),\n });\n }\n exitSpan(runId);\n }\n },\n\n // Chain Error Handler\n handleChainError(error, runId) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'chain_error' });\n exitSpan(runId);\n }\n\n captureException(error, {\n mechanism: {\n handled: false,\n type: `${LANGCHAIN_ORIGIN}.chain_error_handler`,\n },\n });\n },\n\n // Tool Start Handler\n handleToolStart(tool, input, runId, _parentRunId) {\n const toolName = tool.name || 'unknown_tool';\n const attributes = {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: LANGCHAIN_ORIGIN,\n 'gen_ai.tool.name': toolName,\n };\n\n // Add input if recordInputs is enabled\n if (recordInputs) {\n attributes['gen_ai.tool.input'] = input;\n }\n\n startSpanManual(\n {\n name: `execute_tool ${toolName}`,\n op: 'gen_ai.execute_tool',\n attributes: {\n ...attributes,\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'gen_ai.execute_tool',\n },\n },\n span => {\n spanMap.set(runId, span);\n return span;\n },\n );\n },\n\n // Tool End Handler\n handleToolEnd(output, runId) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n // Add output if recordOutputs is enabled\n if (recordOutputs) {\n span.setAttributes({\n 'gen_ai.tool.output': JSON.stringify(output),\n });\n }\n exitSpan(runId);\n }\n },\n\n // Tool Error Handler\n handleToolError(error, runId) {\n const span = spanMap.get(runId);\n if (span?.isRecording()) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: 'tool_error' });\n exitSpan(runId);\n }\n\n captureException(error, {\n mechanism: {\n handled: false,\n type: `${LANGCHAIN_ORIGIN}.tool_error_handler`,\n },\n });\n },\n\n // LangChain BaseCallbackHandler required methods\n copy() {\n return handler;\n },\n\n toJSON() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n\n toJSONNotImplemented() {\n return {\n lc: 1,\n type: 'not_implemented',\n id: handler.lc_id,\n };\n },\n };\n\n return handler;\n}\n\nexport { createLangChainCallbackHandler };\n//# sourceMappingURL=index.js.map\n","/**\n * Determine a breadcrumb's log level (only `warning` or `error`) based on an HTTP status code.\n */\nfunction getBreadcrumbLogLevelFromHttpStatusCode(statusCode) {\n // NOTE: undefined defaults to 'info' in Sentry\n if (statusCode === undefined) {\n return undefined;\n } else if (statusCode >= 400 && statusCode < 500) {\n return 'warning';\n } else if (statusCode >= 500) {\n return 'error';\n } else {\n return undefined;\n }\n}\n\nexport { getBreadcrumbLogLevelFromHttpStatusCode };\n//# sourceMappingURL=breadcrumb-log-level.js.map\n","import { isNodeEnv } from './node.js';\nimport { GLOBAL_OBJ } from './worldwide.js';\n\n/**\n * Returns true if we are in the browser.\n */\nfunction isBrowser() {\n // eslint-disable-next-line no-restricted-globals\n return typeof window !== 'undefined' && (!isNodeEnv() || isElectronNodeRenderer());\n}\n\n// Electron renderers with nodeIntegration enabled are detected as Node.js so we specifically test for them\nfunction isElectronNodeRenderer() {\n const process = (GLOBAL_OBJ ).process;\n return process?.type === 'renderer';\n}\n\nexport { isBrowser };\n//# sourceMappingURL=isBrowser.js.map\n","/**\n * Replaces constructor functions in module exports, handling read-only properties,\n * and both default and named exports by wrapping them with the constructor.\n *\n * @param exports The module exports object to modify\n * @param exportName The name of the export to replace (e.g., 'GoogleGenAI', 'Anthropic', 'OpenAI')\n * @param wrappedConstructor The wrapped constructor function to replace the original with\n * @returns void\n */\nfunction replaceExports(\n exports,\n exportName,\n wrappedConstructor,\n) {\n const original = exports[exportName];\n\n if (typeof original !== 'function') {\n return;\n }\n\n // Replace the named export - handle read-only properties\n try {\n exports[exportName] = wrappedConstructor;\n } catch (error) {\n // If direct assignment fails, override the property descriptor\n Object.defineProperty(exports, exportName, {\n value: wrappedConstructor,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n\n // Replace the default export if it points to the original constructor\n if (exports.default === original) {\n try {\n exports.default = wrappedConstructor;\n } catch (error) {\n Object.defineProperty(exports, 'default', {\n value: wrappedConstructor,\n writable: true,\n configurable: true,\n enumerable: true,\n });\n }\n }\n}\n\nexport { replaceExports };\n//# sourceMappingURL=exports.js.map\n","import { filenameIsInApp } from './node-stack-trace.js';\nimport { UNKNOWN_FUNCTION } from './stacktrace.js';\n\n/**\n * A node.js watchdog timer\n * @param pollInterval The interval that we expect to get polled at\n * @param anrThreshold The threshold for when we consider ANR\n * @param callback The callback to call for ANR\n * @returns An object with `poll` and `enabled` functions {@link WatchdogReturn}\n */\nfunction watchdogTimer(\n createTimer,\n pollInterval,\n anrThreshold,\n callback,\n) {\n const timer = createTimer();\n let triggered = false;\n let enabled = true;\n\n setInterval(() => {\n const diffMs = timer.getTimeMs();\n\n if (triggered === false && diffMs > pollInterval + anrThreshold) {\n triggered = true;\n if (enabled) {\n callback();\n }\n }\n\n if (diffMs < pollInterval + anrThreshold) {\n triggered = false;\n }\n }, 20);\n\n return {\n poll: () => {\n timer.reset();\n },\n enabled: (state) => {\n enabled = state;\n },\n };\n}\n\n// types copied from inspector.d.ts\n\n/**\n * Converts Debugger.CallFrame to Sentry StackFrame\n */\nfunction callFrameToStackFrame(\n frame,\n url,\n getModuleFromFilename,\n) {\n const filename = url ? url.replace(/^file:\\/\\//, '') : undefined;\n\n // CallFrame row/col are 0 based, whereas StackFrame are 1 based\n const colno = frame.location.columnNumber ? frame.location.columnNumber + 1 : undefined;\n const lineno = frame.location.lineNumber ? frame.location.lineNumber + 1 : undefined;\n\n return {\n filename,\n module: getModuleFromFilename(filename),\n function: frame.functionName || UNKNOWN_FUNCTION,\n colno,\n lineno,\n in_app: filename ? filenameIsInApp(filename) : undefined,\n };\n}\n\nexport { callFrameToStackFrame, watchdogTimer };\n//# sourceMappingURL=anr.js.map\n","/** A simple Least Recently Used map */\nclass LRUMap {\n\n constructor( _maxSize) {this._maxSize = _maxSize;\n this._cache = new Map();\n }\n\n /** Get the current size of the cache */\n get size() {\n return this._cache.size;\n }\n\n /** Get an entry or undefined if it was not in the cache. Re-inserts to update the recently used order */\n get(key) {\n const value = this._cache.get(key);\n if (value === undefined) {\n return undefined;\n }\n // Remove and re-insert to update the order\n this._cache.delete(key);\n this._cache.set(key, value);\n return value;\n }\n\n /** Insert an entry and evict an older entry if we've reached maxSize */\n set(key, value) {\n if (this._cache.size >= this._maxSize) {\n // keys() returns an iterator in insertion order so keys().next() gives us the oldest key\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const nextKey = this._cache.keys().next().value;\n this._cache.delete(nextKey);\n }\n this._cache.set(key, value);\n }\n\n /** Remove an entry and return the entry if it was in the cache */\n remove(key) {\n const value = this._cache.get(key);\n if (value) {\n this._cache.delete(key);\n }\n return value;\n }\n\n /** Clear all entries */\n clear() {\n this._cache.clear();\n }\n\n /** Get all the keys */\n keys() {\n return Array.from(this._cache.keys());\n }\n\n /** Get all the values */\n values() {\n const values = [];\n this._cache.forEach(value => values.push(value));\n return values;\n }\n}\n\nexport { LRUMap };\n//# sourceMappingURL=lru.js.map\n","// Based on https://github.com/sindresorhus/escape-string-regexp but with modifications to:\n// a) reduce the size by skipping the runtime type - checking\n// b) ensure it gets down - compiled for old versions of Node(the published package only supports Node 14+).\n//\n// MIT License\n//\n// Copyright (c) Sindre Sorhus <sindresorhus@gmail.com> (https://sindresorhus.com)\n//\n// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated\n// documentation files(the \"Software\"), to deal in the Software without restriction, including without limitation\n// the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and\n// to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n//\n// The above copyright notice and this permission notice shall be included in all copies or substantial portions of\n// the Software.\n//\n// THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO\n// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE\n// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,\n// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n// IN THE SOFTWARE.\n\n/**\n * Given a string, escape characters which have meaning in the regex grammar, such that the result is safe to feed to\n * `new RegExp()`.\n *\n * @param regexString The string to escape\n * @returns An version of the string with all special regex characters escaped\n */\nfunction escapeStringForRegex(regexString) {\n // escape the hyphen separately so we can also replace it with a unicode literal hyphen, to avoid the problems\n // discussed in https://github.com/sindresorhus/escape-string-regexp/issues/20.\n return regexString.replace(/[|\\\\{}()[\\]^$+*?.]/g, '\\\\$&').replace(/-/g, '\\\\x2d');\n}\n\nexport { escapeStringForRegex };\n//# sourceMappingURL=escapeStringForRegex.js.map\n","import*as r from\"@sentry/core\";var n={current:r},t=function(r){n.current=r},e=function(){return n.current};export{e as getSentry,t as setSentry};\n//# sourceMappingURL=index.module.js.map\n","export class QueueRetryError extends Error {\n constructor() {\n super('RETRY');\n }\n}\n","import { delay } from '@lowerdeck/delay';\nimport {\n createExecutionContext,\n ExecutionContext,\n provideExecutionContext,\n withExecutionContextOptional\n} from '@lowerdeck/execution-context';\nimport { generateSnowflakeId } from '@lowerdeck/id';\nimport { memo } from '@lowerdeck/memo';\nimport { parseRedisUrl } from '@lowerdeck/redis';\nimport { getSentry } from '@lowerdeck/sentry';\nimport {\n DeduplicationOptions,\n JobsOptions,\n Queue,\n QueueEvents,\n QueueOptions,\n Worker,\n WorkerOptions\n} from 'bullmq';\nimport { QueueRetryError } from '../lib/queueRetryError';\nimport { IQueue } from '../types';\n\n// @ts-ignore\nimport SuperJson from 'superjson';\n\nlet Sentry = getSentry();\n\nlet log = (...any: any[]) => console.log('[QUEUE MANAGER]:', ...any);\n\nlet anyQueueStartedRef = { started: false };\n\nexport interface BullMqQueueOptions {\n delay?: number;\n id?: string;\n deduplication?: DeduplicationOptions;\n}\n\nexport interface BullMqCreateOptions {\n name: string;\n jobOpts?: JobsOptions;\n queueOpts?: Omit<QueueOptions, 'connection'>;\n workerOpts?: Omit<WorkerOptions, 'connection'>;\n redisUrl: string;\n}\n\nexport let createBullMqQueue = <JobData>(\n opts: BullMqCreateOptions\n): IQueue<JobData, BullMqQueueOptions> => {\n let redisOpts = parseRedisUrl(opts.redisUrl);\n\n let queue = new Queue<JobData>(opts.name, {\n ...opts.queueOpts,\n connection: redisOpts,\n defaultJobOptions: {\n removeOnComplete: true,\n removeOnFail: true,\n attempts: 10,\n keepLogs: 10,\n ...opts.jobOpts\n }\n });\n\n let useQueueEvents = memo(() => new QueueEvents(opts.name, { connection: redisOpts }));\n\n return {\n name: opts.name,\n\n add: async (payload, opts) => {\n let job = await withExecutionContextOptional(\n async ctx =>\n await queue.add(\n 'j' as any,\n {\n payload: SuperJson.serialize(payload),\n $$execution_context$$: ctx\n } as any,\n {\n delay: opts?.delay,\n jobId: opts?.id,\n deduplication: opts?.deduplication\n }\n )\n );\n\n return {\n async waitUntilFinished(opts?: { timeout?: number }) {\n let events = useQueueEvents();\n await job.waitUntilFinished(events, opts?.timeout);\n }\n };\n },\n\n addMany: async (payloads, opts) => {\n await withExecutionContextOptional(async ctx => {\n await queue.addBulk(\n payloads.map(\n payload =>\n ({\n name: 'j',\n data: {\n payload: SuperJson.serialize(payload),\n $$execution_context$$: ctx\n },\n opts: {\n delay: opts?.delay,\n jobId: opts?.id,\n deduplication: opts?.deduplication\n }\n }) as any\n )\n );\n });\n },\n\n addManyWithOps: async payloads => {\n await withExecutionContextOptional(async ctx => {\n await queue.addBulk(\n payloads.map(\n payload =>\n ({\n name: 'j',\n data: {\n payload: SuperJson.serialize(payload.data),\n $$execution_context$$: ctx\n },\n opts: {\n delay: payload.opts?.delay,\n jobId: payload.opts?.id,\n deduplication: payload.opts?.deduplication\n }\n }) as any\n )\n );\n });\n },\n\n process: cb => {\n let staredRef = { started: false };\n\n setTimeout(() => {\n if (anyQueueStartedRef.started && !staredRef.started) {\n log(`Queue ${opts.name} was not started within 10 seconds, this is likely a bug`);\n }\n }, 10000);\n\n return {\n start: async () => {\n log(`Starting queue ${opts.name} using bullmq`);\n staredRef.started = true;\n anyQueueStartedRef.started = true;\n\n let worker = new Worker<JobData>(\n opts.name,\n async job => {\n try {\n let data = job.data as any;\n\n let payload: any;\n\n try {\n payload = SuperJson.deserialize(data.payload);\n } catch (e: any) {\n payload = data.payload;\n }\n\n let parentExecutionContext = (data as any)\n .$$execution_context$$ as ExecutionContext;\n while (\n parentExecutionContext &&\n parentExecutionContext.type == 'job' &&\n parentExecutionContext.parent\n )\n parentExecutionContext = parentExecutionContext.parent;\n\n await provideExecutionContext(\n createExecutionContext({\n type: 'job',\n contextId: job.id ?? generateSnowflakeId(),\n queue: opts.name,\n parent: parentExecutionContext\n }),\n () => cb(payload as any, job)\n );\n } catch (e: any) {\n if (e instanceof QueueRetryError) {\n await delay(1000);\n throw e;\n } else {\n Sentry.captureException(e);\n console.error(e);\n throw e;\n }\n }\n },\n {\n concurrency: 50,\n ...opts.workerOpts,\n connection: redisOpts\n }\n );\n\n return {\n close: () => worker.close()\n };\n }\n };\n }\n };\n};\n","import { BullMqCreateOptions, createBullMqQueue } from './drivers/bullmq';\nimport { IQueueProcessor } from './types';\n\nexport * from './lib/queueRetryError';\nexport * from './types';\n\nlet seenNames = new Set<string>();\n\nexport let createQueue = <JobData>(opts: { driver?: 'bullmq' } & BullMqCreateOptions) => {\n if (!opts.driver) opts.driver = 'bullmq';\n\n if (seenNames.has(opts.name)) {\n throw new Error(`Queue with name ${opts.name} already exists`);\n }\n seenNames.add(opts.name);\n\n return createBullMqQueue<JobData>({\n name: opts.name,\n redisUrl: opts.redisUrl,\n\n jobOpts: opts.jobOpts,\n queueOpts: opts.queueOpts,\n workerOpts: opts.workerOpts\n });\n};\n\nexport let combineQueueProcessors = (opts: IQueueProcessor[]): IQueueProcessor => {\n return {\n start: async () => {\n let processors = await Promise.all(opts.map(x => x.start()));\n\n return {\n close: async () => {\n await Promise.all(processors.map(x => x?.close?.()));\n }\n };\n }\n };\n};\n\nexport let runQueueProcessors = async (processor: IQueueProcessor[]) => {\n let combined = combineQueueProcessors(processor);\n\n let res = await combined.start();\n\n process.on('SIGINT', async () => {\n await res?.close();\n });\n\n process.on('SIGTERM', async () => {\n await res?.close();\n });\n\n return res;\n};\n","import{generateId as r}from\"@lowerdeck/id\";import{getSentry as t}from\"@lowerdeck/sentry\";import{AsyncLocalStorage as e}from\"async_hooks\";var o=function(t){return t.contextId||(t.contextId=r(\"ctx_\")),t},n=t(),c=new e,i=function(r){try{var t=c.getStore();if(!t)throw new Error(\"No execution context found\");return Promise.resolve(r(t.context))}catch(r){return Promise.reject(r)}},u=function(r){try{var t,e=c.getStore();return Promise.resolve(r(null!=(t=null==e?void 0:e.context)?t:null))}catch(r){return Promise.reject(r)}},f=function(r){try{var t=c.getStore();if(!t)throw new Error(\"No execution context found\");if(!t.afterHooks)throw new Error(\"After hooks not enabled for this execution context\");return t.afterHooks.push(r),Promise.resolve()}catch(r){return Promise.reject(r)}},s=function(r,t){try{var e=[];return n.setContext(\"executionContext\",r),Promise.resolve(c.run({context:r,afterHooks:e},function(){try{return Promise.resolve(t())}catch(r){return Promise.reject(r)}})).then(function(t){for(var o=0,c=e;o<c.length;o++)(0,c[o])().catch(function(t){n.captureException(t),console.error(\"Error in after hook\",{err:t,context:r})});return t})}catch(r){return Promise.reject(r)}},a=function(r){c.enterWith({context:r})},x=function(r){var t=h();return Object.assign(t,r),t},h=function(){var r=c.getStore();if(!r)throw new Error(\"No execution context found\");return r.context};export{f as addAfterHook,o as createExecutionContext,c as ctxStorage,h as getExecutionContext,s as provideExecutionContext,a as setExecutionContextSync,x as updateExecutionContext,i as withExecutionContext,u as withExecutionContextOptional};\n//# sourceMappingURL=index.module.js.map\n"],"names":["t","Object","assign","bind","e","arguments","length","r","o","hasOwnProperty","call","apply","i","__typename","data","toResponse","ok","ALPHABET","BASE_MAP","Uint8Array","j","x","charAt","xc","charCodeAt","TypeError","Math","log","base","getRandomValues","random","bytes","crypto","customAlphabet","alphabet","size","defaultSize","getRandom","mask","log2","step","id","customRandom","rnds8","Error","defineProperty","exports","value","default","obj","_regex","require$$0","__esModule","uuid","test","unsafeStringify","_validate","byteToHex","push","toString","slice","arr","offset","_rng","_nodeId","_clockseq","_lastMSecs","_lastNSecs","options","buf","b","Array","node","clockseq","undefined","seedBytes","rng","msecs","Date","now","nsecs","dt","tl","tmh","n","_stringify","v","parseInt","URL","DNS","name","version","hashfunc","generateUUID","namespace","_namespace","str","unescape","encodeURIComponent","stringToBytes","_parse","set","err","getOutputLength","inputLength8","safeAdd","y","lsw","md5cmn","q","a","s","num","cnt","md5ff","c","d","md5gg","md5hh","md5ii","msg","input","output","length32","hexTab","hex","md5ToHexEncodedArray","len","olda","oldb","oldc","oldd","wordsToMd5","length8","Uint32Array","bytesToWords","_v","_interopRequireDefault","_md","require$$1","v3","randomUUID","_native","rnds","f","z","ROTL","K","H","isArray","prototype","N","ceil","M","pow","floor","W","T","_sha","v5","enumerable","get","_nil","_v2","_v3","_v4","_version","require$$2","require$$3","require$$4","require$$5","require$$6","require$$7","require$$8","Converter","srcAlphabet","dstAlphabet","this","convert","number","divide","newlen","numberMap","fromBase","toBase","result","isValid","indexOf","concat","converter","anyBase","BIN","OCT","DEC","HEX","anyBase_1","v4","uuidV4","validate","uuidValidate","constants","cookieBase90","flickrBase58","uuid25Base36","baseOptions","consistentLength","toFlickr","shortenUUID","longId","translator","paddingParams","translated","toLowerCase","replace","padStart","shortIdLength","paddingChar","enlargeUUID","shortId","m","match","join","shortUuid","makeConvertor","toAlphabet","useAlphabet","selectedOptions","Set","from","alphabetLength","fromHex","toHex","generate","fromUUID","maxLength","new","toUUID","rigorous","isCorrectLength","onlyAlphabet","split","every","letter","includes","freeze","Worker","epoch","workerId","workerIdBits","maxWorkerId","datacenterId","datacenterIdBits","maxDatacenterId","sequence","sequenceBits","workerIdShift","datacenterIdShift","timestampLeftShift","sequenceMask","lastTimestamp","constructor","BigInt","currentSequence","nextId","timestamp","tilNextMillis","u","g","endsWith","DEBUG_BUILD","__SENTRY_DEBUG__","GLOBAL_OBJ","globalThis","SDK_VERSION","getMainCarrier","getSentryCarrier","carrier","__SENTRY__","getGlobalSingleton","creator","CONSOLE_LEVELS","originalConsoleMethods","consoleSandbox","callback","console","wrappedFuncs","wrappedLevels","keys","forEach","level","originalConsoleMethod","isEnabled","_getLoggerSettings","enabled","_maybeLog","args","debug","enable","disable","warn","error","UNKNOWN_FUNCTION","WEBPACK_ERROR_REGEXP","STRIP_FRAME_REGEXP","createStackParser","parsers","sortedParsers","sort","map","p","stack","skipFirstLines","framesToPop","frames","lines","line","cleanedLine","parser","frame","stripSentryFramesAndReverse","localStack","getLastStackFrame","function","pop","reverse","filename","defaultFunctionName","getFunctionName","fn","getFramesFromEvent","event","exception","values","stacktrace","getVueInternalName","__v_isVNode","handlers","instrumented","addHandler","type","handler","maybeInstrument","instrumentFn","triggerHandlers","typeHandlers","_oldOnErrorHandler","addGlobalErrorInstrumentationHandler","instrumentError","onerror","url","column","__SENTRY_INSTRUMENTED__","_oldOnUnhandledRejectionHandler","addGlobalUnhandledRejectionInstrumentationHandler","instrumentUnhandledRejection","onunhandledrejection","objectToString","isError","wat","isInstanceOf","isBuiltin","className","isErrorEvent","isString","isParameterizedString","isPrimitive","isPlainObject","isEvent","Event","isElement","Element","isRegExp","isThenable","Boolean","then","isSyntheticEvent","isVueViewModel","__isVue","_isVue","isRequest","request","Request","WINDOW","htmlTreeAsString","elem","currentElem","MAX_TRAVERSE_HEIGHT","out","height","separator","sepLength","nextStr","keyAttrs","maxStringLength","_htmlElementAsString","parentNode","el","tagName","HTMLElement","dataset","keyAttrPairs","filter","keyAttr","getAttribute","keyAttrPair","classes","allowedAttrs","k","attr","fill","source","replacementFactory","original","wrapped","markFunctionWrapped","addNonEnumerableProperty","writable","configurable","getOriginalFunction","func","__sentry_original__","convertToPlainObject","message","getOwnProperties","newObj","target","serializeEventTarget","currentTarget","CustomEvent","detail","extractedProps","property","extractExceptionKeysForMessage","_dropUndefinedKeys","inputValue","memoizationMap","memoVal","returnValue","isPojo","key","val","truncate","max","snipLine","colno","newLine","lineLength","start","end","min","safeJoin","delimiter","String","isMatchingPattern","pattern","requireExactStringMatch","stringMatchesSomePattern","testString","patterns","some","emptyUuid","uuid4","msCrypto","getCrypto","getFirstException","getEventDescription","event_id","eventId","firstException","addExceptionTypeValue","addExceptionMechanism","newMechanism","currentMechanism","mechanism","handled","mergedData","SEMVER_REGEXP","_parseInt","checkOrSetAlreadyCaught","__sentry_captured__","isAlreadyCaptured","dateTimestampInSeconds","_cachedTimestampInSeconds","cachedTimeOrigin","timestampInSeconds","performance","timeOrigin","createUnixTimestampInSecondsFunc","makeSession","context","startingTime","session","sid","init","started","duration","status","errors","ignoreDuration","toJSON","toISOString","did","abnormal_mechanism","attrs","release","environment","ip_address","ipAddress","user_agent","userAgent","sessionToJSON","updateSession","user","email","username","closeSession","merge","initialObj","mergeObj","levels","generateTraceId","generateSpanId","substring","SCOPE_SPAN_FIELD","_setSpanForScope","scope","span","_getSpanForScope","Scope","_notifyingListeners","_scopeListeners","_eventProcessors","_breadcrumbs","_attachments","_user","_tags","_attributes","_extra","_contexts","_sdkProcessingMetadata","_propagationContext","traceId","sampleRand","clone","newScope","flags","_level","_session","_transactionName","_fingerprint","_client","_lastEventId","setClient","client","setLastEventId","lastEventId","getClient","addScopeListener","addEventProcessor","setUser","_notifyScopeListeners","getUser","setTags","tags","setTag","setAttributes","newAttributes","setAttribute","removeAttribute","setExtras","extras","setExtra","extra","setFingerprint","fingerprint","setLevel","setTransactionName","setContext","setSession","getSession","update","captureContext","scopeToMerge","scopeInstance","getScopeData","attributes","contexts","propagationContext","clear","setPropagationContext","addBreadcrumb","breadcrumb","maxBreadcrumbs","maxCrumbs","mergedBreadcrumb","recordDroppedEvent","getLastBreadcrumb","clearBreadcrumbs","addAttachment","attachment","clearAttachments","breadcrumbs","attachments","eventProcessors","sdkProcessingMetadata","transactionName","setSDKProcessingMetadata","newData","getPropagationContext","captureException","hint","syntheticException","originalException","captureMessage","captureEvent","getDefaultCurrentScope","getDefaultIsolationScope","AsyncContextStack","isolationScope","assignedScope","assignedIsolationScope","_stack","_isolationScope","withScope","_pushScope","maybePromiseResult","_popScope","res","getStackTop","getScope","getIsolationScope","getAsyncContextStack","sentry","withSetScope","withIsolationScope","getAsyncContextStrategy","acs","withSetIsolationScope","getCurrentScope","getGlobalScope","rest","getTraceContextFromScope","parentSpanId","propagationSpanId","traceContext","trace_id","span_id","parent_span_id","SEMANTIC_ATTRIBUTE_SENTRY_SOURCE","SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_PREVIOUS_TRACE_SAMPLE_RATE","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","SEMANTIC_ATTRIBUTE_SENTRY_IDLE_SPAN_FINISH_REASON","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_UNIT","SEMANTIC_ATTRIBUTE_SENTRY_MEASUREMENT_VALUE","SEMANTIC_ATTRIBUTE_SENTRY_CUSTOM_SPAN_NAME","SEMANTIC_ATTRIBUTE_PROFILE_ID","SEMANTIC_ATTRIBUTE_EXCLUSIVE_TIME","SEMANTIC_ATTRIBUTE_HTTP_REQUEST_METHOD","SEMANTIC_ATTRIBUTE_URL_FULL","getSpanStatusFromHttpCode","httpStatus","code","setHttpStatus","spanStatus","setStatus","SCOPE_ON_START_SPAN_FIELD","ISOLATION_SCOPE_ON_START_SPAN_FIELD","unwrapScopeFromWeakRef","scopeRef","deref","setCapturedScopesOnSpan","WeakRefClass","WeakRef","wrapScopeWithWeakRef","getCapturedScopesOnSpan","SENTRY_BAGGAGE_KEY_PREFIX","SENTRY_BAGGAGE_KEY_PREFIX_REGEX","baggageHeaderToDynamicSamplingContext","baggageHeader","baggageObject","parseBaggageHeader","dynamicSamplingContext","entries","reduce","acc","dynamicSamplingContextToSentryBaggageHeader","objectToBaggageHeader","dscKey","dscValue","curr","currBaggageObject","baggageHeaderToObject","baggageEntry","eqIdx","keyOrValue","decodeURIComponent","trim","object","objectKey","objectValue","currentIndex","newBaggageHeader","ORG_ID_REGEX","DSN_REGEX","dsnToString","dsn","withPassword","host","path","pass","port","projectId","protocol","publicKey","dsnFromString","exec","lastPath","projectMatch","dsnFromComponents","components","extractOrgIdFromClient","getOptions","getDsn","org_id","orgId","extractOrgIdFromDsnHost","makeDsn","find","component","isValidProtocol","isNaN","validateDsn","parseSampleRate","sampleRate","Number","rate","parseFloat","TRACEPARENT_REGEXP","RegExp","extractTraceparentData","traceparent","matches","parentSampled","propagationContextFromHeaders","sentryTrace","baggage","traceparentData","dsc","parsedSampleRand","sample_rand","parsedSampleRate","sample_rate","getSampleRandFromTraceparentAndDsc","sampled","generateSentryTraceHeader","spanId","sampledString","generateTraceparentHeader","shouldContinueTrace","baggageOrgId","clientOrgId","strictTraceContinuation","hasShownSpanDropWarning","spanToTransactionTraceContext","spanContext","op","origin","links","spanToJSON","spanToTraceContext","isRemote","spanToTraceHeader","spanIsSampled","convertSpanLinksForEnvelope","traceFlags","restContext","spanTimeInputToSeconds","ensureTimestampInSeconds","getTime","getSpanJSON","spanIsSentrySpan","startTime","endTime","spanIsOpenTelemetrySdkTraceBaseSpan","description","start_timestamp","getStatusMessage","CHILD_SPANS_FIELD","ROOT_SPAN_FIELD","addChildSpanToSpan","childSpan","add","getSpanDescendants","resultSet","addSpanChildren","has","childSpans","getRootSpan","getActiveSpan","showSpanDropWarning","errorsInstrumented","registerSpanErrorInstrumentation","errorCallback","activeSpan","rootSpan","tag","hasSpansEnabled","maybeOptions","__SENTRY_TRACING__","tracesSampleRate","tracesSampler","logIgnoredSpan","droppedSpan","shouldIgnoreSpan","ignoreSpans","isStringOrRegExp","nameMatches","opMatches","reparentChildSpans","spans","dropSpan","droppedSpanParentId","droppedSpanId","DEFAULT_ENVIRONMENT","FROZEN_DSC_FIELD","freezeDscOnSpan","getDynamicSamplingContextFromClient","public_key","emit","getDynamicSamplingContextFromScope","getDynamicSamplingContextFromSpan","rootSpanJson","rootSpanAttributes","traceState","rootSpanSampleRate","applyLocalSampleRateToDsc","frozenDsc","traceStateDsc","dscOnTraceState","transaction","SentryNonRecordingSpan","_traceId","_spanId","_timestamp","_key","_value","_values","_status","updateName","_name","isRecording","addEvent","_attributesOrStartTime","_startTime","addLink","_link","addLinks","_links","recordException","_exception","_time","normalize","depth","maxProperties","visit","ERROR","normalizeToSize","maxSize","normalized","JSON","stringify","encodeURI","memo","inner","WeakSet","delete","memoBuilder","memoize","unmemoize","isFinite","stringified","_events","global","window","document","objName","getPrototypeOf","getConstructorName","stringifyValue","startsWith","remainingDepth","valueWithToJSON","numAdded","visitable","visitKey","createEnvelope","headers","items","addItemToEnvelope","envelope","newItem","forEachEnvelopeItem","envelopeItems","envelopeItem","envelopeContainsItemType","types","_","encodeUTF8","encodePolyfill","TextEncoder","encode","serializeEnvelope","envHeaders","parts","append","next","item","itemHeaders","payload","stringifiedPayload","buffers","totalLength","merged","buffer","concatBuffers","createSpanEnvelopeItem","spanJson","createAttachmentEnvelopeItem","content_type","contentType","attachment_type","attachmentType","ITEM_TYPE_TO_DATA_CATEGORY_MAP","sessions","client_report","user_report","profile","profile_chunk","replay_event","replay_recording","check_in","feedback","raw_security","metric","trace_metric","envelopeItemTypeToDataCategory","getSdkMetadataForEnvelopeHeader","metadataOrEvent","sdk","createEventEnvelopeHeaders","sdkInfo","tunnel","sent_at","trace","createSessionEnvelope","metadata","createEventEnvelope","eventType","newSdkInfo","eventSdkInfo","integrations","packages","settings","_enhanceEventWithSdkInfo","envelopeHeaders","createSpanEnvelope","dscHasRequiredProps","beforeSendSpan","filteredSpans","droppedSpans","convertToSpanJSON","logSpanStart","isRootSpan","header","infoParts","logSpanEnd","timedEventsToMeasurements","events","measurements","unit","SentrySpan","startTimestamp","_parentSpanId","_sampled","endTimestamp","_endTime","_isStandaloneSpan","isStandalone","_onSpanEnded","link","updateStartTime","timeInput","profile_id","exclusive_time","is_segment","segment_id","attributesOrStartTime","time","isSpanTimeInput","isStandaloneSpan","spanItems","sendEnvelope","sendSpanEnvelope","transactionEvent","_convertSpanToTransaction","isFullFinishedSpan","capturedSpanScope","capturedSpanIsolationScope","normalizedRequest","transaction_info","handleCallbackErrors","onError","onFinally","onSuccess","maybeHandlePromiseRejection","sampleSpan","samplingContext","localSampleRateWasApplied","inheritOrSampleWith","fallbackSampleRate","parentSampleRate","shouldSample","SUPPRESS_TRACING_KEY","startSpan","getAcs","spanArguments","parseSentrySpanArguments","forceTransaction","parentSpan","customParentSpan","customScope","customForkedScope","getActiveSpanWrapper","wrapper","getParentSpan","onlyIfParent","createChildOrRootSpan","startSpanManual","startInactiveSpan","withActiveSpan","startNewTrace","_startChildSpan","_startRootSpan","initialCtx","experimental","standalone","ctx","mutableSpanSamplingData","spanAttributes","spanName","decision","finalParentSampled","finalAttributes","currentPropagationContext","parentSpanIsAlwaysRootSpan","TRACING_DEFAULTS","idleTimeout","finalTimeout","childSpanTimeout","resolvedSyncPromise","SyncPromise","resolve","rejectedSyncPromise","reason","reject","executor","_state","_handlers","_runExecutor","onfulfilled","onrejected","_executeHandlers","onfinally","isRejected","cachedHandlers","setResult","state","notifyEventProcessors","processors","index","_notifyEventProcessors","processor","final","applyScopeDataToEvent","applyDataToEvent","applySpanToEvent","applyFingerprintToEvent","mergedBreadcrumbs","applyBreadcrumbsToEvent","applySdkMetadataToEvent","mergeScopeData","mergeData","mergeAndOverwriteScopeData","prop","mergeVal","parsedStackResults","lastSentryKeysCount","lastNativeKeysCount","cachedFilenameDebugIds","getFilenameToDebugIdMap","stackParser","sentryDebugIdMap","_sentryDebugIds","nativeDebugIdMap","_debugIds","sentryDebugIdKeys","nativeDebugIdKeys","processDebugIds","debugIdKeys","debugIdMap","debugId","parsedStack","stackFrame","prepareEvent","normalizeDepth","normalizeMaxBreadth","prepared","dist","maxValueLength","applyClientOptions","integrationNames","applyIntegrationsMetadata","filenameDebugIdMap","debug_id","applyDebugIds","finalScope","getFinalScope","clientEventProcessors","getEventProcessors","evt","abs_path","debug_meta","images","code_file","applyDebugMeta","maxBreadth","normalizeEvent","captureContextKeys","hintIsScopeOrFunction","hintIsScopeContext","parseEventHintOrCaptureContext","captureCheckIn","checkIn","upsertMonitorConfig","async","flush","timeout","Promise","getTransport","endSession","_sendSessionUpdate","captureSession","getBaseApiEndpoint","getEnvelopeEndpointWithUrlEncodedAuth","_getIngestEndpoint","params","sentry_version","sentry_key","sentry_client","URLSearchParams","_encodedAuth","installedIntegrations","afterSetupIntegrations","integration","afterAllSetup","setupIntegration","integrationIndex","setupOnce","setup","preprocessEvent","on","processEvent","attributeValueToTypedAttributeValue","rawValue","useFallback","maybeObj","attributeValue","primitiveType","isInteger","getTypedAttributeValue","checkedUnit","stringValue","serializeAttributes","fallback","serializedAttributes","typedValue","_getTraceInfoFromScope","SEVERITY_TEXT_TO_SEVERITY_NUMBER","info","fatal","setLogAttribute","logAttributes","setEvenIfPresent","_INTERNAL_captureSerializedLog","serializedLog","bufferMap","_getBufferMap","logBuffer","_INTERNAL_getLogBuffer","_INTERNAL_flushLogsBuffer","_INTERNAL_captureLog","beforeLog","currentScope","captureSerializedLog","enableLogs","beforeSendLog","processedLogAttributes","scopeAttributes","scopeData","getMergedScopeData","getSdkMetadata","replay","getIntegrationByName","replayId","getReplayId","getRecordingMode","beforeLogMessage","__sentry_template_string__","__sentry_template_values__","param","processedLog","severityNumber","body","severity_number","maybeLogBuffer","clientOptions","logs","item_count","createLogEnvelope","_metadata","WeakMap","metricAttributeToSerializedMetricAttribute","setMetricAttribute","metricAttributes","_INTERNAL_captureSerializedMetric","serializedMetric","metricBuffer","_INTERNAL_getMetricBuffer","_INTERNAL_flushMetricsBuffer","_INTERNAL_captureMetric","beforeMetric","captureSerializedMetric","_experiments","enableMetrics","beforeSendMetric","enrichedMetric","processedMetricAttributes","_enrichMetricAttributes","beforeSendCallback","processedMetric","_buildSerializedMetric","maybeMetricBuffer","metrics","createMetricEnvelope","SENTRY_BUFFER_FULL_ERROR","Symbol","for","makePromiseBuffer","limit","remove","task","$","taskProducer","drain","drainPromise","allSettled","promises","setTimeout","race","parseRetryAfterHeader","headerDelay","headerDate","parse","disabledUntil","limits","dataCategory","all","isRateLimited","updateRateLimits","statusCode","updatedRateLimits","rateLimitHeader","retryAfterHeader","retryAfter","categories","namespaces","delay","category","createClientReportEnvelope","discarded_events","getPossibleEventMessages","possibleMessages","lastException","ALREADY_SEEN_ERROR","MISSING_RELEASE_FOR_SESSION_ERROR","INTERNAL_ERROR_SYMBOL","DO_NOT_SEND_EVENT_SYMBOL","_makeInternalError","_makeDoNotSendEventError","_isInternalError","_isDoNotSendEventError","setupWeightBasedFlushing","afterCaptureHook","flushHook","estimateSizeFn","flushFn","flushTimeout","weight","isTimerActive","clearTimeout","Client","_options","_integrations","_numProcessing","_outcomes","_hooks","_promiseBuffer","transportOptions","bufferSize","_dsn","_transport","transport","estimateLogSizeInBytes","estimateMetricSizeInBytes","hintWithEventId","_process","eventFromException","_captureEvent","eventMessage","isMessage","promisedEvent","eventFromMessage","getDataCategoryByType","sendSession","clientFinished","_isClientDoneProcessing","transportFlushed","close","eventProcessor","_isEnabled","_setupIntegrations","integrationName","addIntegration","isAlreadyInstalled","sendEvent","env","sendResponse","clientReleaseOption","clientEnvironmentOption","sessionAttrs","count","sendClientReports","hook","hookCallbacks","uniqueCallback","callbacks","send","setupIntegrations","_updateSessionFromEvent","crashed","errored","exceptions","ex","sessionNonTerminal","ticked","_prepareEvent","_processEvent","finalEvent","isTransaction","isTransactionEvent","beforeSendLabel","__sentry__","beforeSend","beforeSendTransaction","processedEvent","convertTransactionEventToSpanJson","processedRootSpanJson","processedSpans","initialSpans","processedSpan","spanCountBeforeProcessing","processBeforeSend","beforeSendResult","invalidValueError","_validateBeforeSendResult","droppedSpanCount","transactionInfo","_clearOutcomes","outcomes","quantity","_flushOutcomes","estimateAttributesSizeInBytes","estimatePrimitiveSizeInBytes","createCheckInEnvelope","createCheckInEnvelopeItem","parseStackFrames","exceptionFromError","eventFromUnknownInput","synthetic","__serialized__","errorFromProp","getErrorPropertyFromObject","getObjectClassName","getMessageForObject","getException","attachStacktrace","logentry","setCurrentRequestSessionErroredOrCrashed","eventHint","requestSession","isHandledException","setCurrentClient","START_DELAY","MULTIPLEXED_TRANSPORT_EXTRA_KEY","eventFromEnvelope","SKIPPED_AI_PROVIDERS","isURLObjectRelative","parseStringToURLObject","urlBase","isRelative","canParse","fullUrlObject","pathname","search","hash","getSanitizedUrlStringFromUrlObject","newUrl","password","getHttpSpanNameFromUrlObject","urlObject","kind","routeName","method","toUpperCase","removeTrailingSlash","parameterize","strings","formatted","raw","fmt","getTraceData","scopeToTraceHeader","traceData","propagateTraceparent","spanToTraceparentHeader","scopeToTraceparentHeader","winterCGHeadersToDict","winterCGHeaders","headersToDict","reqHeaders","create","SENSITIVE_HEADER_SNIPPETS","PII_HEADER_SNIPPETS","normalizeAttributeKey","addSpanAttribute","headerKey","cookieKey","sendPii","normalizedKey","headerValue","lowerCasedKey","snippet","handleHttpHeader","extractQueryParamsFromUrl","queryParams","DEFAULT_BREADCRUMBS","beforeBreadcrumb","finalBreadcrumb","originalFunctionToString","SETUP_CLIENTS","DEFAULT_IGNORE_ERRORS","eventFiltersIntegration","mergedOptions","_mergeOptions","_hint","ignoreTransactions","_isIgnoredTransaction","ignoreErrors","_isIgnoredError","_isUselessError","denyUrls","_getEventFilterUrl","_isDeniedUrl","allowUrls","_isAllowedUrl","_shouldDropEvent","internalOptions","disableErrorDefaults","rootException","parent_id","_getLastValidUrl","applyAggregateErrorsToEvent","exceptionFromErrorImplementation","aggregateExceptionsFromError","prevExceptions","exceptionId","newExceptions","applyExceptionGroupFieldsForParentException","newException","newExceptionId","applyExceptionGroupFieldsForChildException","childError","is_exception_group","exception_id","parentId","filenameMetadataMap","Map","parsedStacks","addMetadataToStackFrames","module_metadata","_sentryModuleMetadata","ensureMetadataStacksAreParsed","getMetadataForUrl","stripMetadataFromStackFrames","ipHeaderNames","DEFAULT_INCLUDE","cookies","query_string","extractNormalizedRequestData","include","requestData","cookie","ip","ipHeaderName","endIdx","lastIndexOf","parseCookie","addConsoleInstrumentationHandler","instrumentConsole","severityLevelFromString","_isSameStacktrace","currentEvent","previousEvent","currentFrames","previousFrames","frameA","frameB","lineno","_isSameFingerprint","currentFingerprint","previousFingerprint","_getExceptionFromEvent","_extractErrorData","captureErrorCause","nativeKeys","extraErrorInfo","cause","errorName","serializedError","oO","normalizeArray","allowAboveRoot","up","last","splice","unshift","splitPathRe","splitPath","truncated","resolvedPath","resolvedAbsolute","relative","to","fromParts","toParts","samePartsLength","outputParts","normalizePath","isPathAbsolute","isAbsolute","trailingSlash","normalizedPath","basename","ext","AUTH_OPERATIONS_TO_INSTRUMENT","AUTH_ADMIN_OPERATIONS_TO_INSTRUMENT","FILTER_MAPPINGS","eq","neq","gt","gte","lt","lte","like","ilike","is","in","cs","cd","sr","nxl","sl","nxr","adj","ov","fts","plfts","phfts","wfts","not","DB_OPERATIONS_TO_INSTRUMENT","markAsInstrumented","isInstrumented","translateFiltersIntoMethods","query","instrumentAuthOperation","operation","isAdmin","Proxy","thisArg","argumentsList","Reflect","catch","instrumentPostgRESTFilterBuilder","PostgRESTFilterBuilder","operations","typedThis","extractOperation","pathParts","table","queryItems","searchParams","schema","details","supabaseContext","instrumentSupabaseClient","supabaseClient","SupabaseClient","Function","rv","PostgRESTQueryBuilder","instrumentPostgRESTQueryBuilder","supabaseClientInstance","auth","authOperation","admin","instrumentSupabaseAuthClient","flattenIssue","issue","unionErrors","flattenIssuePath","formatIssueMessage","zodError","errorKeyMap","iss","issues","issuePath","errorKeys","rootExpectedType","expected","formatConsoleArgs","util","format","SPAN_FLAG_ATTRIBUTE_PREFIX","_INTERNAL_copyFlagsFromScopeToEvent","flagContext","flagBuffer","_INTERNAL_insertFlagToScope","scopeContexts","findIndex","flag","shift","_INTERNAL_insertToFlagBuffer","_INTERNAL_addFeatureFlagToActiveSpan","maxFlagsPerSpan","_wrapAndCaptureBooleanResult","flagName","isProfilingIntegrationWithProfiler","profiler","startProfiler","_profiler","stopProfiler","stop","baggageHeaderHasSentryBaggageValues","getFetchSpanAttributes","parsedUrl","spanOrigin","href","trpcCaptureContext","captureError","errorType","extraData","error_type","wrapMethodHandler","serverInstance","methodName","originalMethod","wrappedHandler","originalHandler","handlerName","handlerArgs","createErrorCapturingHandler","createWrappedHandler","captureHandlerError","tool_name","resource_uri","prompt_name","captureErr","MCP_METHOD_NAME_ATTRIBUTE","MCP_REQUEST_ID_ATTRIBUTE","MCP_SESSION_ID_ATTRIBUTE","MCP_TRANSPORT_ATTRIBUTE","MCP_SERVER_NAME_ATTRIBUTE","MCP_SERVER_TITLE_ATTRIBUTE","MCP_SERVER_VERSION_ATTRIBUTE","MCP_PROTOCOL_VERSION_ATTRIBUTE","MCP_RESOURCE_URI_ATTRIBUTE","MCP_TOOL_RESULT_CONTENT_COUNT_ATTRIBUTE","MCP_PROMPT_RESULT_DESCRIPTION_ATTRIBUTE","MCP_REQUEST_ARGUMENT","MCP_LOGGING_MESSAGE_ATTRIBUTE","NETWORK_TRANSPORT_ATTRIBUTE","NETWORK_PROTOCOL_VERSION_ATTRIBUTE","CLIENT_ADDRESS_ATTRIBUTE","CLIENT_PORT_ATTRIBUTE","MCP_SERVER_OP_VALUE","MCP_NOTIFICATION_ORIGIN_VALUE","PII_ATTRIBUTES","filterMcpPiiFromSpanData","spanData","sendDefaultPii","isPiiAttribute","isJsonRpcNotification","jsonrpc","isValidContentItem","transportToSessionData","extractPartyInfo","partyInfo","title","extractSessionDataFromInitializeResponse","sessionData","protocolVersion","serverInfo","buildClientAttributesFromInfo","clientInfo","buildTransportAttributes","sessionId","address","requestInfo","remoteAddress","clientAddress","connection","remotePort","clientPort","extractClientInfo","mcpTransport","networkTransport","transportName","lowerTransportName","getTransportTypes","clientAttributes","getClientInfoForTransport","getClientAttributes","serverAttributes","getSessionDataForTransport","getServerAttributes","getProtocolVersionForTransport","transportToSpanMap","getOrCreateSpanMap","spanMap","METHOD_CONFIGS","targetField","targetAttribute","captureArguments","argumentsField","captureUri","captureName","extractTargetInfo","config","getRequestArguments","argumentsObj","uri","buildTypeSpecificAttributes","targetInfo","requestId","logger","progressToken","progress","total","getNotificationAttributes","createSpanName","buildSentryAttributes","createMcpSpan","rawAttributes","wrappedMcpServerInstances","captureLog","safeJoinConsoleArgs","createConsoleTemplateAttributes","firstArg","followingArgs","template","arg","DEFAULT_ATTRIBUTES","captureMetric","DEFAULT_CAPTURED_LEVELS","CONSOLA_TYPE_TO_LOG_SEVERITY_LEVEL_MAP","silent","success","fail","ready","box","verbose","critical","notice","CONSOLA_LEVEL_TO_LOG_SEVERITY_LEVEL_MAP","GEN_AI_PROMPT_ATTRIBUTE","GEN_AI_SYSTEM_ATTRIBUTE","GEN_AI_REQUEST_MODEL_ATTRIBUTE","GEN_AI_REQUEST_STREAM_ATTRIBUTE","GEN_AI_REQUEST_TEMPERATURE_ATTRIBUTE","GEN_AI_REQUEST_MAX_TOKENS_ATTRIBUTE","GEN_AI_REQUEST_FREQUENCY_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_PRESENCE_PENALTY_ATTRIBUTE","GEN_AI_REQUEST_TOP_P_ATTRIBUTE","GEN_AI_REQUEST_TOP_K_ATTRIBUTE","GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE","GEN_AI_RESPONSE_MODEL_ATTRIBUTE","GEN_AI_RESPONSE_ID_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_OUTPUT_TOKENS_ATTRIBUTE","GEN_AI_USAGE_TOTAL_TOKENS_ATTRIBUTE","GEN_AI_OPERATION_NAME_ATTRIBUTE","GEN_AI_REQUEST_MESSAGES_ATTRIBUTE","GEN_AI_RESPONSE_TEXT_ATTRIBUTE","GEN_AI_REQUEST_AVAILABLE_TOOLS_ATTRIBUTE","GEN_AI_RESPONSE_STREAMING_ATTRIBUTE","GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE","GEN_AI_AGENT_NAME_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_CACHE_WRITE_ATTRIBUTE","GEN_AI_USAGE_INPUT_TOKENS_CACHED_ATTRIBUTE","OPENAI_RESPONSE_ID_ATTRIBUTE","OPENAI_RESPONSE_MODEL_ATTRIBUTE","OPENAI_RESPONSE_TIMESTAMP_ATTRIBUTE","OPENAI_USAGE_COMPLETION_TOKENS_ATTRIBUTE","OPENAI_USAGE_PROMPT_TOKENS_ATTRIBUTE","ANTHROPIC_AI_RESPONSE_TIMESTAMP_ATTRIBUTE","toolCallSpanMap","utf8Bytes","text","jsonBytes","truncateTextByBytes","maxBytes","low","high","bestFit","mid","candidate","getPartText","part","withPartText","isContentMedia","isContentMediaSource","hasInlineData","media_type","image_url","inlineData","isPartsMessage","REMOVED_STRING","MEDIA_FIELDS","stripInlineMediaFromSingleMessage","strip","field","stripInlineMediaFromMessages","messages","newMessage","content","isContentArrayMessage","truncateGenAiMessages","stripped","messageSizes","bytesUsed","startIndex","messageSize","isContentMessage","emptyMessage","availableForContent","truncatedContent","truncateContentMessage","emptyParts","remainingBytes","includedParts","textSize","truncatePartsMessage","truncateMessagesByBytes","getFinalOperationName","methodPath","getSpanOperation","buildMethodPath","currentPath","setTokenUsageAttributes","promptTokens","completionTokens","cachedInputTokens","cachedOutputTokens","totalTokens","getTruncatedJsonString","truncatedMessages","AI_PROMPT_ATTRIBUTE","AI_PROMPT_MESSAGES_ATTRIBUTE","AI_PROMPT_TOOLS_ATTRIBUTE","AI_MODEL_ID_ATTRIBUTE","AI_TOOL_CALL_NAME_ATTRIBUTE","AI_TOOL_CALL_ID_ATTRIBUTE","accumulateTokensForParent","tokenAccumulator","inputTokens","outputTokens","existing","applyAccumulatedTokens","spanOrTrace","accumulated","addOriginToSpan","onVercelAiSpanStart","renameAttributeKey","toolCallId","toolName","processToolCallSpan","aiModelId","nameWthoutAi","functionId","truncatedPrompt","prompt","system","role","convertPromptToMessages","requestMessagesFromPrompt","processGenerateSpan","vercelAiEventProcessor","processEndedVercelAiSpan","tools","toolObjects","tool","convertAvailableToolsToJsonString","providerMetadata","providerMetadataObject","openai","setAttributeIfDefined","cachedPromptTokens","reasoningTokens","acceptedPredictionTokens","rejectedPredictionTokens","responseId","anthropic","usage","cache_read_input_tokens","cacheReadInputTokens","cache_creation_input_tokens","cacheCreationInputTokens","bedrock","cacheWriteInputTokens","deepseek","promptCacheHitTokens","promptCacheMissTokens","addProviderMetadataToAttributes","oldKey","newKey","INSTRUMENTED_METHODS","RESPONSE_EVENT_TYPES","getOperationName","isResponsesApiStreamEvent","isChatCompletionChunk","setCommonResponseAttributes","model","processChatCompletionToolCalls","toolCalls","toolCall","chatCompletionToolCalls","existingToolCall","processChatCompletionChunk","chunk","recordOutputs","responseModel","responseTimestamp","created","prompt_tokens","completion_tokens","total_tokens","choice","choices","delta","responseTexts","tool_calls","finish_reason","finishReasons","processResponsesApiEvent","streamEvent","eventTypes","responsesApiToolCalls","response","created_at","input_tokens","output_tokens","output_text","addRequestAttributes","truncatedInput","createDeepProxy","shouldInstrument","requestAttributes","availableTools","web_search_options","temperature","top_p","frequency_penalty","presence_penalty","stream","encoding_format","dimensions","extractRequestAttributes","operationName","recordInputs","allToolCalls","instrumentStream","isChatCompletionResponse","calls","flat","addChatCompletionAttributes","isResponsesApiResponse","isEmbeddingsResponse","addEmbeddingsAttributes","responseWithOutput","functionCalls","addResponsesApiAttributes","addResponseAttributes","instrumentMethod","stop_reason","handleMessageMetadata","content_block","activeToolBlocks","inputJsonParts","handleContentBlockStart","partial_json","active","handleContentBlockDelta","parsedInput","__unparsed","handleContentBlockStop","ANTHROPIC_AI_INSTRUMENTED_METHODS","addPrivateRequestAttributes","messagesFromParams","handleStreamingError","top_k","max_tokens","isStreamRequested","isStreamingMethod","instrumentAsyncIterableStream","finalizeStreamSpan","instrumentMessageStream","handleStreamingRequest","handleResponseError","completion","addContentAttributes","addMetadataAttributes","GOOGLE_GENAI_INSTRUMENTED_METHODS","CHATS_CREATE_METHOD","processChunk","promptFeedback","blockReason","blockReasonMessage","isErrorChunk","modelVersion","usageMetadata","promptTokenCount","candidatesTokenCount","totalTokenCount","handleResponseMetadata","candidates","finishReason","functionCall","handleCandidateContent","contentUnionToMessages","flatMap","extractModel","systemInstruction","history","contents","isSyncCreate","topP","topK","maxOutputTokens","frequencyPenalty","presencePenalty","extractConfigAttributes","functionDeclarations","receiver","instrumentedMethod","LANGCHAIN_ORIGIN","ROLE_MAP","human","ai","assistant","setIfDefined","setNumberIfDefined","asString","normalizeMessageRole","normalizeRoleNameFromCtor","getInvocationParams","invocation_params","normalizeLangChainMessages","maybeGetType","_getType","ctor","lc","kwargs","messageType","extractCommonRequestAttributes","serialized","invocationParams","langSmithMetadata","ls_temperature","ls_max_tokens","baseRequestAttributes","modelName","LANGGRAPH_ORIGIN","extractTokenUsageFromMessage","usage_metadata","response_metadata","tokenUsage","extractModelMetadata","model_name","instrumentStateGraphCompile","originalCompile","compiledGraph","compileOptions","originalInvoke","invoke","graphInstance","graphName","builder","nodes","runnable","lc_kwargs","extractToolsFromCompiledGraph","inputMessages","resultObj","outputMessages","inputCount","newMessages","msgToolCalls","extractToolCalls","normalizedNewMessages","totalInputTokens","totalOutputTokens","tokens","setResponseAttributes","instrumentCompiledGraphInvoke","SentryError","logLevel","super","supportsFetch","_isFetchSupported","Headers","Response","isNativeFunction","supportsNativeFetch","EdgeRuntime","fetch","doc","sandbox","createElement","hidden","head","appendChild","contentWindow","removeChild","instrumentFetch","onFetchResolved","skipNativeFetchCheck","originalFetch","virtualError","fetchArgs","resource","getUrlFromResource","hasProp","parseFetchArgs","handlerData","fetchData","getHeadersFromFetchArgs","streamHandler","clonedResponseForResolving","onFinishedResolving","responseReader","getReader","maxFetchDurationTimeout","cancel","readingActive","chunkTimeout","done","read","releaseLock","resolveResponse","requestArgument","optionsArgument","isBrowserBundle","__SENTRY_BROWSER_BUNDLE__","isNodeEnv","process","dynamicRequire","mod","require","filenameIsInApp","isNative","getModule","FILENAME_MATCH","FULL_MATCH","DATA_URI_MATCH","dataUriMatch","lineMatch","functionName","typeName","methodStart","objectEnd","decodeURI","module","_parseIntOrUndefined","in_app","vercelWaitUntil","vercelRequestContextGlobal","waitUntil","flushWithTimeout","startSpanOptions","activities","_idleTimeoutID","_finished","_finishReason","_autoFinishAllowed","disableAutoFinish","_cleanupHooks","beforeSpanEnd","trimIdleSpanEndTimestamp","previousActiveSpan","_startIdleSpan","_cancelIdleTimeout","_restartIdleTimeout","_restartChildSpanTimeout","onIdleSpanEnded","cleanup","spanJSON","currentStatus","child","discardedSpans","childSpanJSON","childEndTimestamp","childStartTimestamp","spanStartedBeforeIdleSpanEnd","spanEndedBeforeFinalTimeout","stringifiedSpan","removeChildSpanFromSpan","definedEndTimestamp","spanEndTimestamp","latestSpanEndTimestamp","current","currentSpanJson","spanStartTimestamp","Infinity","startedSpan","endedSpan","spanToAllowAutoFinish","continueTrace","incomingDsc","suppressTracing","navigator","currentSession","monitorSlug","runCallback","checkInId","finishCheckIn","isolateTrace","strategy","dsnLike","dialogOptions","endpoint","encodedOptions","sdkMetadata","sdkUserAgent","addUserAgentToTransportHeaders","_setUpMetricsProcessing","monitorConfig","serializedCheckIn","check_in_id","monitor_slug","monitor_config","schedule","checkin_margin","checkinMargin","max_runtime","maxRuntime","timezone","failure_issue_threshold","failureIssueThreshold","recovery_threshold","recoveryThreshold","platform","runtime","serverName","server_name","clientClass","initialScope","makeRequest","rateLimits","filteredEnvelopeItems","filteredEnvelope","recordEnvelopeLoss","createTransport","createStore","store","flushTimer","retryDelay","flushIn","found","unref","flushWithBackOff","isRetry","shouldSend","shouldStore","shouldQueue","flushAtStartup","matcher","fallbackTransport","otherTransports","actualMatcher","getEvent","validatedDsn","makeOverrideReleaseTransport","transports","transportsWithFallback","overrideDsn","allTransports","defaultIntegrations","userIntegrations","isDefaultInstance","resolvedUserIntegrations","integrationsByName","currentInstance","existingInstance","filterDuplicates","modules","urlParts","checkDsn","checkTunnel","objWithMaybeUser","names","wait","callbackReturnValue","timerId","maxTimerId","maxWait","setTimeoutImpl","invokeFunc","cancelTimers","debounced","lowerCasedHeaderKey","isSetCookie","semicolonIndex","cookieString","equalSignIndex","cookieValue","lowerCasedCookieKey","absoluteUrl","getAbsoluteUrl","socket","encrypted","req","originalFunction","includeWithDefaultPiiApplied","additionalData","headerName","parseForwardedHeader","getClientIPAddress","addNormalizedRequestDataToEvent","severityLevel","consoleHandler","currentMessage","previousMessage","_isSameMessageEvent","previousException","currentException","_isSameExceptionEvent","exceptionName","errorData","normalizedErrorData","_enhanceEventWithErrorData","iteratee","isBrowser","root","prefix","isWindowsFrame","startsWithSlash","oldFilename","generateIteratee","originalEvent","_processExceptionsEvent","saveZodIssuesAsAttachment","flattenedIssues","applyZodErrorsToEvent","frameKeys","BUNDLER_PLUGIN_APP_KEY_PREFIX","getBundleKeysForAllFramesWithFilenames","behaviour","filterKeys","third_party_code","assertionArgs","addConsoleBreadcrumb","addFeatureFlag","growthbookClass","proto","isOn","getFeatureValue","shouldCreateSpan","shouldAttachHeaders","spanOriginOrOptions","shouldCreateSpanResult","__span","contentLength","contentLengthNum","endSpan","onRequestSpanEnd","_callOnRequestSpanEnd","hasParent","getSpanStartOptions","fetchOptionsObj","traceHeaders","originalHeaders","isHeaders","newHeaders","prevBaggageHeader","prevBaggageHeaderWithSentryValues","existingSentryTraceHeader","existingTraceparentHeader","existingBaggageHeader","newBaggageHeaders","headerItem","_addTracingHeadersToFetchRequest","opts","rawInput","getRawInput","trpcContext","procedure_path","procedure_type","attachRpcInput","rawRes","nextResult","captureIfError","mcpServerInstance","instance","originalConnect","restArgs","onmessage","originalOnMessage","isJsonRpcRequest","isInitialize","initSessionData","extractSessionDataFromInitializeRequest","storeSessionDataForTransport","spanConfig","jsonRpcMessage","buildMcpServerSpanConfig","storeSpanForRequest","createMcpNotificationSpan","wrapTransportOnMessage","originalSend","createMcpOutgoingNotificationSpan","isJsonRpcResponse","errorResponse","jsonRpcError","captureJsonRpcErrorResponse","partialSessionData","existingData","updateSessionDataForTransport","initAttributes","buildServerAttributesFromInfo","rawToolAttributes","safeSet","mimeType","buildAllContentItemAttributes","extractToolResultAttributes","toolAttributes","rawPromptAttributes","extractPromptResultAttributes","promptAttributes","completeSpanWithResults","wrapTransportSend","onclose","originalOnClose","cleanupPendingSpansForTransport","cleanupSessionDataForTransport","wrapTransportOnClose","originalOnError","captureTransportError","wrapTransportError","wrapToolHandlers","wrapResourceHandlers","wrapPromptHandlers","wrapAllMCPHandlers","associatedEventId","feedbackEvent","contact_email","associated_event_id","isLevelLog","shouldGenerateTemplate","providedClient","logObj","consolaMessage","date","_date","logSeverityLevel","mappedLevel","getLogSeverityLevel","messageParts","anthropicAiClient","exitSpan","runId","lc_serializable","lc_namespace","lc_secrets","lc_attributes","lc_aliases","lc_serializable_keys","lc_id","ignoreLLM","ignoreChain","ignoreAgent","ignoreRetriever","ignoreCustomEvent","raiseError","awaitHandlers","handleLLMStart","llm","prompts","_parentRunId","_extraParams","_runName","ls_provider","ls_model_name","extractLLMRequestAttributes","handleChatModelStart","langChainMessages","extractChatModelRequestAttributes","handleLLMEnd","llmResult","generations","generationInfo","generation_info","flatGenerations","gen","addToolCallsAttributes","texts","llmOutput","anthropicUsage","addTokenUsageAttributes","firstGeneration","v1Message","stopReason","extractLlmResponseAttributes","handleLLMError","handleChainStart","chain","inputs","chainName","handleChainEnd","outputs","handleChainError","handleToolStart","handleToolEnd","handleToolError","copy","toJSONNotImplemented","stateGraph","compile","location","isElectronNodeRenderer","linesOfContext","maxLines","sourceLine","pre_context","lineIndex","context_line","post_context","major","minor","patch","buildmetadata","prerelease","moduleName","existingModule","cwd","basePath","escapedBase","objectified","dir","exportName","wrappedConstructor","DOMError","DOMException","ErrorEvent","referrerPolicy","threshold","performanceNow","dateNow","timeOriginDelta","abs","timeOriginIsReliable","navigationStart","timing","navigationStartDelta","getBrowserTimeOrigin","readBinary","bin","subarray","readJson","decodePolyfill","TextDecoder","decode","decodeUTF8","envelopeHeader","itemHeader","binaryLength","hostname","fragment","urlPath","getModuleFromFilename","columnNumber","lineNumber","createTimer","pollInterval","anrThreshold","timer","triggered","setInterval","diffMs","getTimeMs","poll","reset","_maxSize","_cache","nextKey","cloudflareWaitUntil","cloudflareCtx","FUNCTIONS_WORKER_RUNTIME","LAMBDA_TASK_ROOT","K_SERVICE","CF_PAGES","VERCEL","NETLIFY","resource_paths","regexString","QueueRetryError","_Error","_inheritsLoose","_wrapNativeSuper","Sentry","getSentry","_console","anyQueueStartedRef","seenNames","combineQueueProcessors","driver","redisOpts","parseRedisUrl","redisUrl","queue","Queue","_extends","queueOpts","defaultJobOptions","removeOnComplete","removeOnFail","attempts","keepLogs","jobOpts","useQueueEvents","QueueEvents","withExecutionContextOptional","SuperJson","serialize","$$execution_context$$","jobId","deduplication","job","waitUntilFinished","addMany","payloads","addBulk","addManyWithOps","_payload$opts","_payload$opts2","_payload$opts3","cb","staredRef","worker","_job$id","deserialize","parentExecutionContext","parent","provideExecutionContext","contextId","createExecutionContext","generateSnowflakeId","_catch","concurrency","workerOpts","createBullMqQueue","combined"],"mappings":"i6DAgBW,SAAAA,IAAA,OAAAA,EAAAC,OAAAC,OAAAD,OAAAC,OAAAC,OAAA,SAAAC,GAAA,IAAA,IAAAJ,EAAA,EAAAA,EAAAK,UAAAC,OAAAN,IAAA,CAAA,IAAAO,EAAAF,UAAAL,GAAA,IAAA,IAAAQ,KAAAD,GAAA,CAAA,GAAAE,eAAAC,KAAAH,EAAAC,KAAAJ,EAAAI,GAAAD,EAAAC,GAAA,CAAA,OAAAJ,CAAA,EAAAJ,EAAAW,MAAA,KAAAN,UAAA,mvCAAA,IAAAO,EAAc,SACvBR,GAEA,OAAOH,OAAOC,OACZ,SAACK,GACC,YAAA,IADDA,IAAAA,EAA8C,IAC7CK,EAAWZ,EACNI,CAAAA,EAAAA,EACAG,GACH,EACJ,CACEM,WAAY,QACZC,KAAAV,EACAW,WAAY,WAAF,OAAAf,EAAW,CAAAa,WAAY,QAAkBG,IAAI,GAAmBZ,EAAI,GAGpF,y3CC1BA,SAAea,GAEb,MAAMC,EAAW,IAAIC,WAAW,KAChC,IAAK,IAAIC,EAAI,EAAGA,EAAIF,EAASZ,OAAQc,IACnCF,EAASE,GAAK,IAEhB,IAAK,IAAIR,EAAI,EAAGA,EAAIK,GAAiBL,IAAK,CACxC,MAAMS,EAAIJ,EAASK,OAAOV,GACpBW,EAAKF,EAAEG,WAAW,GACxB,GAAqB,MAAjBN,EAASK,GAAe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