@sentry/core 10.44.0 → 10.45.0
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.
- package/build/cjs/integrations/eventFilters.js +4 -4
- package/build/cjs/integrations/eventFilters.js.map +1 -1
- package/build/cjs/tracing/anthropic-ai/streaming.js +3 -2
- package/build/cjs/tracing/anthropic-ai/streaming.js.map +1 -1
- package/build/cjs/tracing/anthropic-ai/utils.js +24 -1
- package/build/cjs/tracing/anthropic-ai/utils.js.map +1 -1
- package/build/cjs/tracing/google-genai/streaming.js +1 -1
- package/build/cjs/tracing/google-genai/streaming.js.map +1 -1
- package/build/cjs/tracing/langchain/index.js +3 -3
- package/build/cjs/tracing/langchain/index.js.map +1 -1
- package/build/cjs/utils/baggage.js +1 -1
- package/build/cjs/utils/baggage.js.map +1 -1
- package/build/cjs/utils/browser.js +1 -2
- package/build/cjs/utils/browser.js.map +1 -1
- package/build/cjs/utils/envelope.js +8 -9
- package/build/cjs/utils/envelope.js.map +1 -1
- package/build/cjs/utils/object.js +3 -10
- package/build/cjs/utils/object.js.map +1 -1
- package/build/cjs/utils/version.js +1 -1
- package/build/esm/integrations/eventFilters.js +4 -4
- package/build/esm/integrations/eventFilters.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/tracing/anthropic-ai/streaming.js +3 -2
- package/build/esm/tracing/anthropic-ai/streaming.js.map +1 -1
- package/build/esm/tracing/anthropic-ai/utils.js +24 -2
- package/build/esm/tracing/anthropic-ai/utils.js.map +1 -1
- package/build/esm/tracing/google-genai/streaming.js +1 -1
- package/build/esm/tracing/google-genai/streaming.js.map +1 -1
- package/build/esm/tracing/langchain/index.js +3 -3
- package/build/esm/tracing/langchain/index.js.map +1 -1
- package/build/esm/utils/baggage.js +1 -1
- package/build/esm/utils/baggage.js.map +1 -1
- package/build/esm/utils/browser.js +1 -2
- package/build/esm/utils/browser.js.map +1 -1
- package/build/esm/utils/envelope.js +8 -9
- package/build/esm/utils/envelope.js.map +1 -1
- package/build/esm/utils/object.js +3 -10
- package/build/esm/utils/object.js.map +1 -1
- package/build/esm/utils/version.js +1 -1
- package/build/types/tracing/anthropic-ai/streaming.d.ts.map +1 -1
- package/build/types/tracing/anthropic-ai/utils.d.ts +6 -0
- package/build/types/tracing/anthropic-ai/utils.d.ts.map +1 -1
- package/build/types/types-hoist/spanStatus.d.ts +1 -1
- package/build/types/types-hoist/spanStatus.d.ts.map +1 -1
- package/build/types/utils/browser.d.ts.map +1 -1
- package/build/types/utils/envelope.d.ts.map +1 -1
- package/build/types/utils/object.d.ts.map +1 -1
- package/build/types-ts3.8/tracing/anthropic-ai/utils.d.ts +6 -0
- package/build/types-ts3.8/types-hoist/spanStatus.d.ts +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.js","sources":["../../../src/utils/browser.ts"],"sourcesContent":["import { isString } from './is';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\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 */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\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 as SimpleNode;\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: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\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
|
|
1
|
+
{"version":3,"file":"browser.js","sources":["../../../src/utils/browser.ts"],"sourcesContent":["import { isString } from './is';\nimport { GLOBAL_OBJ } from './worldwide';\n\nconst WINDOW = GLOBAL_OBJ as unknown as Window;\n\nconst DEFAULT_MAX_STRING_LENGTH = 80;\n\ntype SimpleNode = {\n parentNode: SimpleNode;\n} | null;\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 */\nexport function htmlTreeAsString(\n elem: unknown,\n options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {},\n): string {\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 as SimpleNode;\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: unknown, keyAttrs?: string[]): string {\n const elem = el as {\n tagName?: string;\n id?: string;\n className?: string;\n getAttribute(key: string): string;\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 for (const k of ['aria-label', 'type', 'name', 'title', 'alt']) {\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 */\nexport function getLocationHref(): string {\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 */\nexport function getComponentName(elem: unknown): string | null {\n // @ts-expect-error WINDOW has HTMLElement\n if (!WINDOW.HTMLElement) {\n return null;\n }\n\n let currentElem = elem as SimpleNode;\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"],"names":["GLOBAL_OBJ","isString"],"mappings":";;;;;AAGA,MAAM,MAAA,GAASA,oBAAA;;AAEf,MAAM,yBAAA,GAA4B,EAAE;;AAMpC;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,gBAAgB;AAChC,EAAE,IAAI;AACN,EAAE,OAAO,GAAiE,EAAE;AAC5E,EAAU;AACV,EAAE,IAAI,CAAC,IAAI,EAAE;AACb,IAAI,OAAO,WAAW;AACtB,EAAE;;AAEF;AACA;AACA;AACA;AACA,EAAE,IAAI;AACN,IAAI,IAAI,WAAA,GAAc,IAAA;AACtB,IAAI,MAAM,mBAAA,GAAsB,CAAC;AACjC,IAAI,MAAM,GAAA,GAAM,EAAE;AAClB,IAAI,IAAI,MAAA,GAAS,CAAC;AAClB,IAAI,IAAI,GAAA,GAAM,CAAC;AACf,IAAI,MAAM,SAAA,GAAY,KAAK;AAC3B,IAAI,MAAM,SAAA,GAAY,SAAS,CAAC,MAAM;AACtC,IAAI,IAAI,OAAO;AACf,IAAI,MAAM,QAAA,GAAW,KAAK,CAAC,OAAO,CAAC,OAAO,CAAA,GAAI,OAAA,GAAU,OAAO,CAAC,QAAQ;AACxE,IAAI,MAAM,eAAA,GAAkB,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,OAAO,KAAK,OAAO,CAAC,eAAe,KAAK,yBAAyB;;AAE7G,IAAI,OAAO,WAAA,IAAe,MAAM,EAAA,GAAK,mBAAmB,EAAE;AAC1D,MAAM,UAAU,oBAAoB,CAAC,WAAW,EAAE,QAAQ,CAAC;AAC3D;AACA;AACA;AACA;AACA,MAAM,IAAI,OAAA,KAAY,MAAA,KAAW,MAAA,G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AAEA,EAAA,OAAA,GAAA,CAAA,IAAA,CAAA,EAAA,CAAA;AACA;;AAEA;AACA;AACA;AACA,SAAA,eAAA,GAAA;AACA,EAAA,IAAA;AACA,IAAA,OAAA,MAAA,CAAA,QAAA,CAAA,QAAA,CAAA,IAAA;AACA,EAAA,CAAA,CAAA,MAAA;AACA,IAAA,OAAA,EAAA;AACA,EAAA;AACA;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA,SAAA,gBAAA,CAAA,IAAA,EAAA;AACA;AACA,EAAA,IAAA,CAAA,MAAA,CAAA,WAAA,EAAA;AACA,IAAA,OAAA,IAAA;AACA,EAAA;;AAEA,EAAA,IAAA,WAAA,GAAA,IAAA;AACA,EAAA,MAAA,mBAAA,GAAA,CAAA;AACA,EAAA,KAAA,IAAA,CAAA,GAAA,CAAA,EAAA,CAAA,GAAA,mBAAA,EAAA,CAAA,EAAA,EAAA;AACA,IAAA,IAAA,CAAA,WAAA,EAAA;AACA,MAAA,OAAA,IAAA;AACA,IAAA;;AAEA,IAAA,IAAA,WAAA,YAAA,WAAA,EAAA;AACA,MAAA,IAAA,WAAA,CAAA,OAAA,CAAA,iBAAA,CAAA,EAAA;AACA,QAAA,OAAA,WAAA,CAAA,OAAA,CAAA,iBAAA,CAAA;AACA,MAAA;AACA,MAAA,IAAA,WAAA,CAAA,OAAA,CAAA,eAAA,CAAA,EAAA;AACA,QAAA,OAAA,WAAA,CAAA,OAAA,CAAA,eAAA,CAAA;AACA,MAAA;AACA,IAAA;;AAEA,IAAA,WAAA,GAAA,WAAA,CAAA,UAAA;AACA,EAAA;;AAEA,EAAA,OAAA,IAAA;AACA;;;;;;"}
|
|
@@ -190,32 +190,31 @@ function createAttachmentEnvelopeItem(attachment) {
|
|
|
190
190
|
];
|
|
191
191
|
}
|
|
192
192
|
|
|
193
|
-
|
|
194
|
-
|
|
193
|
+
// Map of envelope item types to data categories where the category differs from the type.
|
|
194
|
+
// Types that map to themselves (session, attachment, transaction, profile, feedback, span, metric) fall through.
|
|
195
|
+
const DATA_CATEGORY_OVERRIDES = {
|
|
195
196
|
sessions: 'session',
|
|
196
|
-
attachment: 'attachment',
|
|
197
|
-
transaction: 'transaction',
|
|
198
197
|
event: 'error',
|
|
199
198
|
client_report: 'internal',
|
|
200
199
|
user_report: 'default',
|
|
201
|
-
profile: 'profile',
|
|
202
200
|
profile_chunk: 'profile',
|
|
203
201
|
replay_event: 'replay',
|
|
204
202
|
replay_recording: 'replay',
|
|
205
203
|
check_in: 'monitor',
|
|
206
|
-
feedback: 'feedback',
|
|
207
|
-
span: 'span',
|
|
208
204
|
raw_security: 'security',
|
|
209
205
|
log: 'log_item',
|
|
210
|
-
metric: 'metric',
|
|
211
206
|
trace_metric: 'metric',
|
|
212
207
|
};
|
|
213
208
|
|
|
209
|
+
function _isOverriddenType(type) {
|
|
210
|
+
return type in DATA_CATEGORY_OVERRIDES;
|
|
211
|
+
}
|
|
212
|
+
|
|
214
213
|
/**
|
|
215
214
|
* Maps the type of an envelope item to a data category.
|
|
216
215
|
*/
|
|
217
216
|
function envelopeItemTypeToDataCategory(type) {
|
|
218
|
-
return
|
|
217
|
+
return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type;
|
|
219
218
|
}
|
|
220
219
|
|
|
221
220
|
/** Extracts the minimal SDK info from the metadata or an events */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope.js","sources":["../../../src/utils/envelope.ts"],"sourcesContent":["import { getSentryCarrier } from '../carrier';\nimport type { Attachment } from '../types-hoist/attachment';\nimport type { DataCategory } from '../types-hoist/datacategory';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport type {\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n Envelope,\n EnvelopeItemType,\n EventEnvelopeHeaders,\n SpanItem,\n} from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { SdkInfo } from '../types-hoist/sdkinfo';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { GLOBAL_OBJ } from './worldwide';\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 */\nexport function createEnvelope<E extends Envelope>(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\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 */\nexport function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\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 */\nexport function forEachEnvelopeItem<E extends Envelope>(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\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 */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input: string): Uint8Array {\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: Uint8Array): string {\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 */\nexport function serializeEnvelope(envelope: Envelope): string | Uint8Array {\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: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\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: string;\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: Uint8Array[]): Uint8Array {\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 */\nexport function parseEnvelope(env: string | Uint8Array): Envelope {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length: number): Uint8Array {\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<T>(): T {\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))) as T;\n }\n\n const envelopeHeader = readJson<BaseEnvelopeHeaders>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson<BaseEnvelopeItemHeaders>();\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 */\nexport function createSpanEnvelopeItem(spanJson: Partial<SpanJSON>): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(attachment: Attachment): AttachmentItem {\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: Record<EnvelopeItemType, DataCategory> = {\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 */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return ITEM_TYPE_TO_DATA_CATEGORY_MAP[type];\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\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 */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\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"],"names":["carrier","getSentryCarrier","GLOBAL_OBJ","normalize","dsn","dsnToString"],"mappings":";;;;;;;AAqBA;AACA;AACA;AACA;AACA;AACO,SAAS,cAAc,CAAqB,OAAO,EAAQ,KAAK,GAAS,EAAE,EAAK;AACvF,EAAE,OAAO,CAAC,OAAO,EAAE,KAAK,CAAA;AACxB;;AAEA;AACA;AACA;AACA;AACA;AACO,SAAS,iBAAiB,CAAqB,QAAQ,EAAK,OAAO,EAAmB;AAC7F,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,CAAA,GAAI,QAAQ;AACnC,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,EAAE,OAAO,CAAC,CAAA;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,mBAAmB;AACnC,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAW;AACX,EAAE,MAAM,aAAA,GAAgB,QAAQ,CAAC,CAAC,CAAC;;AAEnC,EAAE,KAAK,MAAM,YAAA,IAAgB,aAAa,EAAE;AAC5C,IAAI,MAAM,mBAAmB,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;AACjD,IAAI,MAAM,SAAS,QAAQ,CAAC,YAAY,EAAE,gBAAgB,CAAC;;AAE3D,IAAI,IAAI,MAAM,EAAE;AAChB,MAAM,OAAO,IAAI;AACjB,IAAI;AACJ,EAAE;;AAEF,EAAE,OAAO,KAAK;AACd;;AAEA;AACA;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C7C;;AAEA;AACO,SAAS,+BAA+B,CAAC,eAAe,EAA6C;AAC5G,EAAE,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE;AAC7B,IAAI;AACJ,EAAE;AACF,EAAE,MAAM,EAAE,IAAI,EAAE,SAAQ,GAAI,eAAe,CAAC,GAAG;AAC/C,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAC1B;;AAEA;AACA;AACA;AACA;AACO,SAAS,0BAA0B;AAC1C,EAAE,KAAK;AACP,EAAE,OAAO;AACT,EAAE,MAAM;AACR,EAAEC,KAAG;AACL,EAAwB;AACxB,EAAE,MAAM,sBAAA,GAAyB,KAAK,CAAC,qBAAqB,EAAE,sBAAsB;AACpF,EAAE,OAAO;AACT,IAAI,QAAQ,EAAE,KAAK,CAAC,QAAA;AACpB,IAAI,OAAO,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;AACrC,IAAI,IAAI,OAAA,IAAW,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACpC,IAAI,IAAI,CAAC,CAAC,MAAA,IAAUA,KAAA,IAAO,EAAE,GAAG,EAAEC,eAAW,CAACD,KAAG,CAAA,EAAG,CAAC;AACrD,IAAI,IAAI,sBAAA,IAA0B;AAClC,MAAM,KAAK,EAAE,sBAAsB;AACnC,KAAK,CAAC;AACN,GAAG;AACH;;;;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"envelope.js","sources":["../../../src/utils/envelope.ts"],"sourcesContent":["import { getSentryCarrier } from '../carrier';\nimport type { Attachment } from '../types-hoist/attachment';\nimport type { DataCategory } from '../types-hoist/datacategory';\nimport type { DsnComponents } from '../types-hoist/dsn';\nimport type {\n AttachmentItem,\n BaseEnvelopeHeaders,\n BaseEnvelopeItemHeaders,\n Envelope,\n EnvelopeItemType,\n EventEnvelopeHeaders,\n SpanItem,\n} from '../types-hoist/envelope';\nimport type { Event } from '../types-hoist/event';\nimport type { SdkInfo } from '../types-hoist/sdkinfo';\nimport type { SdkMetadata } from '../types-hoist/sdkmetadata';\nimport type { SpanJSON } from '../types-hoist/span';\nimport { dsnToString } from './dsn';\nimport { normalize } from './normalize';\nimport { GLOBAL_OBJ } from './worldwide';\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 */\nexport function createEnvelope<E extends Envelope>(headers: E[0], items: E[1] = []): E {\n return [headers, items] as E;\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 */\nexport function addItemToEnvelope<E extends Envelope>(envelope: E, newItem: E[1][number]): E {\n const [headers, items] = envelope;\n return [headers, [...items, newItem]] as unknown as E;\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 */\nexport function forEachEnvelopeItem<E extends Envelope>(\n envelope: Envelope,\n callback: (envelopeItem: E[1][number], envelopeItemType: E[1][number][0]['type']) => boolean | void,\n): boolean {\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 */\nexport function envelopeContainsItemType(envelope: Envelope, types: EnvelopeItemType[]): boolean {\n return forEachEnvelopeItem(envelope, (_, type) => types.includes(type));\n}\n\n/**\n * Encode a string to UTF8 array.\n */\nfunction encodeUTF8(input: string): Uint8Array {\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: Uint8Array): string {\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 */\nexport function serializeEnvelope(envelope: Envelope): string | Uint8Array {\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: string | Uint8Array[] = JSON.stringify(envHeaders);\n\n function append(next: string | Uint8Array): void {\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: string;\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: Uint8Array[]): Uint8Array {\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 */\nexport function parseEnvelope(env: string | Uint8Array): Envelope {\n let buffer = typeof env === 'string' ? encodeUTF8(env) : env;\n\n function readBinary(length: number): Uint8Array {\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<T>(): T {\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))) as T;\n }\n\n const envelopeHeader = readJson<BaseEnvelopeHeaders>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const items: [any, any][] = [];\n\n while (buffer.length) {\n const itemHeader = readJson<BaseEnvelopeItemHeaders>();\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 */\nexport function createSpanEnvelopeItem(spanJson: Partial<SpanJSON>): SpanItem {\n const spanHeaders: SpanItem[0] = {\n type: 'span',\n };\n\n return [spanHeaders, spanJson];\n}\n\n/**\n * Creates attachment envelope items\n */\nexport function createAttachmentEnvelopeItem(attachment: Attachment): AttachmentItem {\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\ntype OverriddenItemType = Exclude<EnvelopeItemType, DataCategory>;\n\n// Map of envelope item types to data categories where the category differs from the type.\n// Types that map to themselves (session, attachment, transaction, profile, feedback, span, metric) fall through.\nconst DATA_CATEGORY_OVERRIDES: Record<OverriddenItemType, DataCategory> = {\n sessions: 'session',\n event: 'error',\n client_report: 'internal',\n user_report: 'default',\n profile_chunk: 'profile',\n replay_event: 'replay',\n replay_recording: 'replay',\n check_in: 'monitor',\n raw_security: 'security',\n log: 'log_item',\n trace_metric: 'metric',\n};\n\nfunction _isOverriddenType(type: EnvelopeItemType): type is OverriddenItemType {\n return type in DATA_CATEGORY_OVERRIDES;\n}\n\n/**\n * Maps the type of an envelope item to a data category.\n */\nexport function envelopeItemTypeToDataCategory(type: EnvelopeItemType): DataCategory {\n return _isOverriddenType(type) ? DATA_CATEGORY_OVERRIDES[type] : type;\n}\n\n/** Extracts the minimal SDK info from the metadata or an events */\nexport function getSdkMetadataForEnvelopeHeader(metadataOrEvent?: SdkMetadata | Event): SdkInfo | undefined {\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 */\nexport function createEventEnvelopeHeaders(\n event: Event,\n sdkInfo: SdkInfo | undefined,\n tunnel: string | undefined,\n dsn?: DsnComponents,\n): EventEnvelopeHeaders {\n const dynamicSamplingContext = event.sdkProcessingMetadata?.dynamicSamplingContext;\n return {\n event_id: event.event_id as string,\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"],"names":["carrier","getSentryCarrier","GLOBAL_OBJ","normalize","dsn","dsnToString"],"mappings":";;;;;;;AAqBA;AACA;AACA;AACA;AACA;AACO,SAAS,cAAc,CAAqB,OAAO,EAAQ,KAAK,GAAS,EAAE,EAAK;AACvF,EAAE,OAAO,CAAC,OAAO,EAAE,KAAK,CAAA;AACxB;;AAEA;AACA;AACA;AACA;AACA;AACO,SAAS,iBAAiB,CAAqB,QAAQ,EAAK,OAAO,EAAmB;AAC7F,EAAE,MAAM,CAAC,OAAO,EAAE,KAAK,CAAA,GAAI,QAAQ;AACnC,EAAE,OAAO,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,EAAE,OAAO,CAAC,CAAA;AACtC;;AAEA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,mBAAmB;AACnC,EAAE,QAAQ;AACV,EAAE,QAAQ;AACV,EAAW;AACX,EAAE,MAAM,aAAA,GAAgB,QAAQ,CAAC,CAAC,CAAC;;AAEnC,EAAE,KAAK,MAAM,YAAA,IAAgB,aAAa,EAAE;AAC5C,IAAI,MAAM,mBAAmB,YAAY,CAAC,CAAC,CAAC,CAAC,IAAI;AACjD,IAAI,MAAM,SAAS,QAAQ,CAAC,YAAY,EAAE,gBAAgB,CAAC;;AAE3D,IA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BAAuB,CAAC,IAAI,CAAA,GAAI,IAAI;AACvE;;AAEA;AACO,SAAS,+BAA+B,CAAC,eAAe,EAA6C;AAC5G,EAAE,IAAI,CAAC,eAAe,EAAE,GAAG,EAAE;AAC7B,IAAI;AACJ,EAAE;AACF,EAAE,MAAM,EAAE,IAAI,EAAE,SAAQ,GAAI,eAAe,CAAC,GAAG;AAC/C,EAAE,OAAO,EAAE,IAAI,EAAE,SAAS;AAC1B;;AAEA;AACA;AACA;AACA;AACO,SAAS,0BAA0B;AAC1C,EAAE,KAAK;AACP,EAAE,OAAO;AACT,EAAE,MAAM;AACR,EAAEC,KAAG;AACL,EAAwB;AACxB,EAAE,MAAM,sBAAA,GAAyB,KAAK,CAAC,qBAAqB,EAAE,sBAAsB;AACpF,EAAE,OAAO;AACT,IAAI,QAAQ,EAAE,KAAK,CAAC,QAAA;AACpB,IAAI,OAAO,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;AACrC,IAAI,IAAI,OAAA,IAAW,EAAE,GAAG,EAAE,OAAA,EAAS,CAAC;AACpC,IAAI,IAAI,CAAC,CAAC,MAAA,IAAUA,KAAA,IAAO,EAAE,GAAG,EAAEC,eAAW,CAACD,KAAG,CAAA,EAAG,CAAC;AACrD,IAAI,IAAI,sBAAA,IAA0B;AAClC,MAAM,KAAK,EAAE,sBAAsB;AACnC,KAAK,CAAC;AACN,GAAG;AACH;;;;;;;;;;;;;;"}
|
|
@@ -58,7 +58,7 @@ function addNonEnumerableProperty(obj, name, value) {
|
|
|
58
58
|
try {
|
|
59
59
|
Object.defineProperty(obj, name, {
|
|
60
60
|
// enumerable: false, // the default, so we can save on bundle size by not explicitly setting it
|
|
61
|
-
value
|
|
61
|
+
value,
|
|
62
62
|
writable: true,
|
|
63
63
|
configurable: true,
|
|
64
64
|
});
|
|
@@ -144,16 +144,9 @@ function serializeEventTarget(target) {
|
|
|
144
144
|
/** Filters out all but an object's own properties */
|
|
145
145
|
function getOwnProperties(obj) {
|
|
146
146
|
if (typeof obj === 'object' && obj !== null) {
|
|
147
|
-
|
|
148
|
-
for (const property in obj) {
|
|
149
|
-
if (Object.prototype.hasOwnProperty.call(obj, property)) {
|
|
150
|
-
extractedProps[property] = (obj )[property];
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
return extractedProps;
|
|
154
|
-
} else {
|
|
155
|
-
return {};
|
|
147
|
+
return Object.fromEntries(Object.entries(obj));
|
|
156
148
|
}
|
|
149
|
+
return {};
|
|
157
150
|
}
|
|
158
151
|
|
|
159
152
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"object.js","sources":["../../../src/utils/object.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { htmlTreeAsString } from './browser';\nimport { debug } from './debug-logger';\nimport { isElement, isError, isEvent, isInstanceOf, isPrimitive } from './is';\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 */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\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] as unknown;\n\n if (typeof original !== 'function') {\n return;\n }\n\n const wrapped = replacementFactory(original) as WrappedFunction;\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 */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\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 */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\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\nexport function getOriginalFunction<T extends Function>(func: WrappedFunction<T>): T | undefined {\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 */\nexport function convertToPlainObject<V>(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\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 [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\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: unknown): string {\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: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n const extractedProps: { [key: string]: unknown } = {};\n for (const property in obj) {\n if (Object.prototype.hasOwnProperty.call(obj, property)) {\n extractedProps[property] = (obj as Record<string, unknown>)[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 */\nexport function extractExceptionKeysForMessage(exception: Record<string, unknown>): string {\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 */\nexport function dropUndefinedKeys<T>(inputValue: T): T {\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<unknown, unknown>();\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<T>(inputValue: T, memoizationMap: Map<unknown, unknown>): T {\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 as T;\n }\n\n // handle arrays\n if (Array.isArray(inputValue)) {\n const returnValue: unknown[] = [];\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 as unknown as T;\n }\n\n if (isPojo(inputValue)) {\n const returnValue: { [key: string]: unknown } = {};\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 as T;\n }\n\n // For other object types, return as is\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record<string, unknown> {\n // Plain objects have Object as constructor or no constructor\n const constructor = (input as object).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 */\nexport function objectify(wat: unknown): typeof Object {\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 as any).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"],"names":["DEBUG_BUILD","debug","isError","isEvent","isInstanceOf","isElement","htmlTreeAsString","isPrimitive"],"mappings":";;;;;;;AAAA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,IAAI,CAAC,MAAM,EAA0B,IAAI,EAAU,kBAAkB,EAAiC;AACtH,EAAE,IAAI,EAAE,QAAQ,MAAM,CAAC,EAAE;AACzB,IAAI;AACJ,EAAE;;AAEF;AACA,EAAE,MAAM,QAAA,GAAW,MAAM,CAAC,IAAI,CAAA;;AAE9B,EAAE,IAAI,OAAO,QAAA,KAAa,UAAU,EAAE;AACtC,IAAI;AACJ,EAAE;;AAEF,EAAE,MAAM,OAAA,GAAU,kBAAkB,CAAC,QAAQ,CAAA;;AAE7C;AACA;AACA,EAAE,IAAI,OAAO,OAAA,KAAY,UAAU,EAAE;AACrC,IAAI,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC;AAC1C,EAAE;;AAEF,EAAE,IAAI;AACN,IAAI,MAAM,CAAC,IAAI,CAAA,GAAI,OAAO;AAC1B,EAAE,EAAE,MAAM;AACV,IAAIA,sBAAA,IAAeC,iBAAK,CAAC,GAAG,CAAC,CAAC,0BAA0B,EAAE,IAAI,CAAC,WAAW,CAAC,EAAE,MAAM,CAAC;AACpF,EAAE;AACF;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,wBAAwB,CAAC,GAAG,EAAU,IAAI,EAAU,KAAK,EAAiB;AAC1F,EAAE,IAAI;AACN,IAAI,MAAM,CAAC,cAAc,CAAC,GAAG,EAAE,IAAI,EAAE;AACrC;AACA,MAAM,KAAK,EAAE,KAAK;AAClB,MAAM,QAAQ,EAAE,IAAI;AACpB,MAAM,YAAY,EAAE,IAAI;AACxB,KAAK,CAAC;AACN,EAAE,EAAE,MAAM;AACV,IAAID,sBAAA,IAAeC,iB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AAC,GAAG,CAAC;AACjC,MAAM,IAAI,GAAA,KAAQ,SAAS,EAAE;AAC7B,QAAQ,WAAW,CAAC,GAAG,CAAA,GAAI,kBAAkB,CAAC,GAAG,EAAE,cAAc,CAAC;AAClE,MAAM;AACN,IAAI,CAAC,CAAC;;AAEN,IAAI,OAAO,WAAA;AACX,EAAE;;AAEF;AACA,EAAE,OAAO,UAAU;AACnB;;AAEA,SAAS,MAAM,CAAC,KAAK,EAA6C;AAClE;AACA,EAAE,MAAM,WAAA,GAAc,CAAC,KAAA,GAAiB,WAAW;AACnD,EAAE,OAAO,WAAA,KAAgB,UAAU,WAAA,KAAgB,SAAS;AAC5D;;AAEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,SAAS,CAAC,GAAG,EAA0B;AACvD,EAAE,IAAI,WAAW;AACjB,EAAE,QAAQ,IAAI;AACd;AACA,IAAI,KAAK,GAAA,IAAO,SAAS;AACzB,MAAM,cAAc,IAAI,MAAM,CAAC,GAAG,CAAC;AACnC,MAAM;;AAEN;AACA;AACA;AACA,IAAI,KAAK,OAAO,GAAA,KAAQ,YAAY,OAAO,GAAA,KAAQ,QAAQ;AAC3D,MAAM,WAAA,GAAc,MAAM,CAAC,GAAG,CAAC;AAC/B,MAAM;;AAEN;AACA,IAAI,KAAKC,cAAW,CAAC,GAAG,CAAC;AACzB;AACA,MAAM,WAAA,GAAc,IAAI,CAAC,GAAA,GAAY,WAAW,CAAC,GAAG,CAAC;AACrD,MAAM;;AAEN;AACA,IAAI;AACJ,MAAM,WAAA,GAAc,GAAG;AACvB,MAAM;AACN;AACA,EAAE,OAAO,WAAW;AACpB;;;;;;;;;;;"}
|
|
1
|
+
{"version":3,"file":"object.js","sources":["../../../src/utils/object.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-explicit-any */\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { WrappedFunction } from '../types-hoist/wrappedfunction';\nimport { htmlTreeAsString } from './browser';\nimport { debug } from './debug-logger';\nimport { isElement, isError, isEvent, isInstanceOf, isPrimitive } from './is';\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 */\nexport function fill(source: { [key: string]: any }, name: string, replacementFactory: (...args: any[]) => any): void {\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] as unknown;\n\n if (typeof original !== 'function') {\n return;\n }\n\n const wrapped = replacementFactory(original) as WrappedFunction;\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 */\nexport function addNonEnumerableProperty(obj: object, name: string, value: unknown): void {\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,\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 */\nexport function markFunctionWrapped(wrapped: WrappedFunction, original: WrappedFunction): void {\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\nexport function getOriginalFunction<T extends Function>(func: WrappedFunction<T>): T | undefined {\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 */\nexport function convertToPlainObject<V>(value: V):\n | {\n [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\n }\n | {\n [ownProps: string]: unknown;\n message: string;\n name: string;\n stack?: string;\n }\n | V {\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 [ownProps: string]: unknown;\n type: string;\n target: string;\n currentTarget: string;\n detail?: unknown;\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: unknown): string {\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: unknown): { [key: string]: unknown } {\n if (typeof obj === 'object' && obj !== null) {\n return Object.fromEntries(Object.entries(obj));\n }\n return {};\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 */\nexport function extractExceptionKeysForMessage(exception: Record<string, unknown>): string {\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 */\nexport function dropUndefinedKeys<T>(inputValue: T): T {\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<unknown, unknown>();\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<T>(inputValue: T, memoizationMap: Map<unknown, unknown>): T {\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 as T;\n }\n\n // handle arrays\n if (Array.isArray(inputValue)) {\n const returnValue: unknown[] = [];\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 as unknown as T;\n }\n\n if (isPojo(inputValue)) {\n const returnValue: { [key: string]: unknown } = {};\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 as T;\n }\n\n // For other object types, return as is\n return inputValue;\n}\n\nfunction isPojo(input: unknown): input is Record<string, unknown> {\n // Plain objects have Object as constructor or no constructor\n const constructor = (input as object).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 */\nexport function objectify(wat: unknown): typeof Object {\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 as any).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"],"names":["DEBUG_BUILD","debug","isError","isEvent","isInstanceOf","isElement","htmlTreeAsString","isPrimitive"],"mappings":";;;;;;;AAAA;;AAOA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACO,SAAS,IAAI,CAAC,MAAM,EAA0B,IAAI,EAAU,kBAAkB,EAAiC;AACtH,EAAE,IAAI,EAAE,QAAQ,MAAM,CAAC,EAAE;AACzB,IAAI;AACJ,EAAE;;AAEF;AACA,EAAE,MAAM,QAAA,GAAW,MAAM,CAAC,IAAI,CAAA;;AAE9B,EAAE,IAAI,OAAO,QAAA,KAAa,UAAU,EAAE;AACtC,IAAI;AACJ,EAAE;;AAEF,EAAE,MAAM,OAAA,GAAU,kBAAkB,CAAC,QAAQ,CAAA;;AAE7C;AACA;AACA,EAAE,IAAI,OAAO,OAAA,KAAY,UAAU,EAAE;AACrC,IAAI,mBAAmB,CAAC,OAAO,EAAE,QAAQ,CAAC;AAC1C,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;AACrD,MAAM;;AAEN;AACA,IAAI;AACJ,MAAM,WAAA,GAAc,GAAG;AACvB,MAAM;AACN;AACA,EAAE,OAAO,WAAW;AACpB;;;;;;;;;;;"}
|
|
@@ -2,7 +2,7 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
// This is a magic string replaced by rollup
|
|
4
4
|
|
|
5
|
-
const SDK_VERSION = "10.
|
|
5
|
+
const SDK_VERSION = "10.45.0" ;
|
|
6
6
|
|
|
7
7
|
exports.SDK_VERSION = SDK_VERSION;
|
|
8
8
|
//# sourceMappingURL=version.js.map
|
|
@@ -14,10 +14,10 @@ const DEFAULT_IGNORE_ERRORS = [
|
|
|
14
14
|
/^Cannot redefine property: googletag$/, // This is thrown when google tag manager is used in combination with an ad blocker
|
|
15
15
|
/^Can't find variable: gmo$/, // Error from Google Search App https://issuetracker.google.com/issues/396043331
|
|
16
16
|
/^undefined is not an object \(evaluating 'a\.[A-Z]'\)$/, // Random error that happens but not actionable or noticeable to end-users.
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
17
|
+
/can't redefine non-configurable property "solana"/, // Probably a browser extension or custom browser (Brave) throwing this error
|
|
18
|
+
/vv\(\)\.getRestrictions is not a function/, // Error thrown by GTM, seemingly not affecting end-users
|
|
19
|
+
/Can't find variable: _AutofillCallbackHandler/, // Unactionable error in instagram webview https://developers.facebook.com/community/threads/320013549791141/
|
|
20
|
+
/Object Not Found Matching Id:\d+, MethodName:simulateEvent/, // unactionable error from CEFSharp, a .NET library that embeds chromium in .NET apps
|
|
21
21
|
/^Java exception was raised during method invocation$/, // error from Facebook Mobile browser (https://github.com/getsentry/sentry-javascript/issues/15065)
|
|
22
22
|
];
|
|
23
23
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"eventFilters.js","sources":["../../../src/integrations/eventFilters.ts"],"sourcesContent":["import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getPossibleEventMessages } from '../utils/eventUtils';\nimport { getEventDescription } from '../utils/misc';\nimport { stringMatchesSomePattern } from '../utils/string';\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 */\nexport interface EventFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreTransactions: Array<string | RegExp>;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n}\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 */\nexport const eventFiltersIntegration = defineIntegration((options: Partial<EventFiltersOptions> = {}) => {\n let mergedOptions: Partial<EventFiltersOptions> | undefined;\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 */\nexport const inboundFiltersIntegration = defineIntegration(((options: Partial<EventFiltersOptions> = {}) => {\n return {\n ...eventFiltersIntegration(options),\n name: 'InboundFilters',\n };\n}) satisfies IntegrationFn);\n\nfunction _mergeOptions(\n internalOptions: Partial<EventFiltersOptions> = {},\n clientOptions: Partial<EventFiltersOptions> = {},\n): Partial<EventFiltersOptions> {\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: Event, options: Partial<EventFiltersOptions>): boolean {\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: Event, ignoreErrors?: Array<string | RegExp>): boolean {\n if (!ignoreErrors?.length) {\n return false;\n }\n\n return getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array<string | RegExp>): boolean {\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: Event, denyUrls?: Array<string | RegExp>): boolean {\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: Event, allowUrls?: Array<string | RegExp>): boolean {\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: StackFrame[] = []): string | null {\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: Event): string | null {\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: Event): boolean {\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"],"names":[],"mappings":";;;;;;;AAUA;AACA;AACA,MAAM,wBAAwB;AAC9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AEA,SAAA,kBAAA,CAAA,KAAA,EAAA;AACA,EAAA,IAAA;AACA;AACA;AACA,IAAA,MAAA,aAAA,GAAA,CAAA,IAAA,KAAA,CAAA,SAAA,EAAA,MAAA,IAAA,EAAA,CAAA;AACA,OAAA,OAAA;AACA,OAAA,IAAA,CAAA,KAAA,IAAA,KAAA,CAAA,SAAA,EAAA,SAAA,KAAA,SAAA,IAAA,KAAA,CAAA,UAAA,EAAA,MAAA,EAAA,MAAA,CAAA;AACA,IAAA,MAAA,MAAA,GAAA,aAAA,EAAA,UAAA,EAAA,MAAA;AACA,IAAA,OAAA,MAAA,GAAA,gBAAA,CAAA,MAAA,CAAA,GAAA,IAAA;AACA,EAAA,CAAA,CAAA,MAAA;AACA,IAAA,WAAA,IAAA,KAAA,CAAA,KAAA,CAAA,CAAA,6BAAA,EAAA,mBAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA;AACA,IAAA,OAAA,IAAA;AACA,EAAA;AACA;;AAEA,SAAA,eAAA,CAAA,KAAA,EAAA;AACA;AACA,EAAA,IAAA,CAAA,KAAA,CAAA,SAAA,EAAA,MAAA,EAAA,MAAA,EAAA;AACA,IAAA,OAAA,KAAA;AACA,EAAA;;AAEA,EAAA;AACA;AACA,IAAA,CAAA,KAAA,CAAA,OAAA;AACA;AACA,IAAA,CAAA,KAAA,CAAA,SAAA,CAAA,MAAA,CAAA,IAAA,CAAA,KAAA,IAAA,KAAA,CAAA,UAAA,KAAA,KAAA,CAAA,IAAA,IAAA,KAAA,CAAA,IAAA,KAAA,OAAA,CAAA,IAAA,KAAA,CAAA,KAAA;AACA;AACA;;;;"}
|
|
1
|
+
{"version":3,"file":"eventFilters.js","sources":["../../../src/integrations/eventFilters.ts"],"sourcesContent":["import { DEBUG_BUILD } from '../debug-build';\nimport { defineIntegration } from '../integration';\nimport type { Event } from '../types-hoist/event';\nimport type { IntegrationFn } from '../types-hoist/integration';\nimport type { StackFrame } from '../types-hoist/stackframe';\nimport { debug } from '../utils/debug-logger';\nimport { getPossibleEventMessages } from '../utils/eventUtils';\nimport { getEventDescription } from '../utils/misc';\nimport { stringMatchesSomePattern } from '../utils/string';\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/, // 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 /Object Not Found Matching Id:\\d+, MethodName:simulateEvent/, // 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 */\nexport interface EventFiltersOptions {\n allowUrls: Array<string | RegExp>;\n denyUrls: Array<string | RegExp>;\n ignoreErrors: Array<string | RegExp>;\n ignoreTransactions: Array<string | RegExp>;\n ignoreInternal: boolean;\n disableErrorDefaults: boolean;\n}\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 */\nexport const eventFiltersIntegration = defineIntegration((options: Partial<EventFiltersOptions> = {}) => {\n let mergedOptions: Partial<EventFiltersOptions> | undefined;\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 */\nexport const inboundFiltersIntegration = defineIntegration(((options: Partial<EventFiltersOptions> = {}) => {\n return {\n ...eventFiltersIntegration(options),\n name: 'InboundFilters',\n };\n}) satisfies IntegrationFn);\n\nfunction _mergeOptions(\n internalOptions: Partial<EventFiltersOptions> = {},\n clientOptions: Partial<EventFiltersOptions> = {},\n): Partial<EventFiltersOptions> {\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: Event, options: Partial<EventFiltersOptions>): boolean {\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: Event, ignoreErrors?: Array<string | RegExp>): boolean {\n if (!ignoreErrors?.length) {\n return false;\n }\n\n return getPossibleEventMessages(event).some(message => stringMatchesSomePattern(message, ignoreErrors));\n}\n\nfunction _isIgnoredTransaction(event: Event, ignoreTransactions?: Array<string | RegExp>): boolean {\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: Event, denyUrls?: Array<string | RegExp>): boolean {\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: Event, allowUrls?: Array<string | RegExp>): boolean {\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: StackFrame[] = []): string | null {\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: Event): string | null {\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: Event): boolean {\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"],"names":[],"mappings":";;;;;;;AAUA;AACA;AACA,MAAM,wBAAwB;AAC9B,EAAE,mBAAmB;AACrB,EAAE,+CAA+C;AACjD,EAAE,iEAAiE;AACnE,EAAE,uCAAuC;AACzC,EAAE,4BAA4B;AAC9B,EAAE,wDAAwD;AAC1D,EAAE,mDAAmD;AACrD,EAAE,2CAA2C;AAC7C,EAAE,+CAA+C;AACjD,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AA,KAAA,IAAA,KAAA,CAAA,SAAA,EAAA,SAAA,KAAA,SAAA,IAAA,KAAA,CAAA,UAAA,EAAA,MAAA,EAAA,MAAA,CAAA;AACA,IAAA,MAAA,MAAA,GAAA,aAAA,EAAA,UAAA,EAAA,MAAA;AACA,IAAA,OAAA,MAAA,GAAA,gBAAA,CAAA,MAAA,CAAA,GAAA,IAAA;AACA,EAAA,CAAA,CAAA,MAAA;AACA,IAAA,WAAA,IAAA,KAAA,CAAA,KAAA,CAAA,CAAA,6BAAA,EAAA,mBAAA,CAAA,KAAA,CAAA,CAAA,CAAA,CAAA;AACA,IAAA,OAAA,IAAA;AACA,EAAA;AACA;;AAEA,SAAA,eAAA,CAAA,KAAA,EAAA;AACA;AACA,EAAA,IAAA,CAAA,KAAA,CAAA,SAAA,EAAA,MAAA,EAAA,MAAA,EAAA;AACA,IAAA,OAAA,KAAA;AACA,EAAA;;AAEA,EAAA;AACA;AACA,IAAA,CAAA,KAAA,CAAA,OAAA;AACA;AACA,IAAA,CAAA,KAAA,CAAA,SAAA,CAAA,MAAA,CAAA,IAAA,CAAA,KAAA,IAAA,KAAA,CAAA,UAAA,KAAA,KAAA,CAAA,IAAA,IAAA,KAAA,CAAA,IAAA,KAAA,OAAA,CAAA,IAAA,KAAA,CAAA,KAAA;AACA;AACA;;;;"}
|
package/build/esm/package.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"10.
|
|
1
|
+
{"type":"module","version":"10.45.0","sideEffects":false}
|
|
@@ -2,6 +2,7 @@ import { captureException } from '../../exports.js';
|
|
|
2
2
|
import { SPAN_STATUS_ERROR } from '../spanstatus.js';
|
|
3
3
|
import { 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';
|
|
4
4
|
import { setTokenUsageAttributes } from '../ai/utils.js';
|
|
5
|
+
import { mapAnthropicErrorToStatusMessage } from './utils.js';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* State object used to accumulate information from a stream of Anthropic AI events.
|
|
@@ -21,7 +22,7 @@ function isErrorEvent(event, span) {
|
|
|
21
22
|
// If the event is an error, set the span status and capture the error
|
|
22
23
|
// These error events are not rejected by the API by default, but are sent as metadata of the response
|
|
23
24
|
if (event.type === 'error') {
|
|
24
|
-
span.setStatus({ code: SPAN_STATUS_ERROR, message: event.error?.type
|
|
25
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(event.error?.type) });
|
|
25
26
|
captureException(event.error, {
|
|
26
27
|
mechanism: {
|
|
27
28
|
handled: false,
|
|
@@ -339,7 +340,7 @@ function instrumentMessageStream(
|
|
|
339
340
|
});
|
|
340
341
|
|
|
341
342
|
if (span.isRecording()) {
|
|
342
|
-
span.setStatus({ code: SPAN_STATUS_ERROR, message: '
|
|
343
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
|
|
343
344
|
span.end();
|
|
344
345
|
}
|
|
345
346
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"streaming.js","sources":["../../../../src/tracing/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { setTokenUsageAttributes } from '../ai/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\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: AnthropicAiStreamingEvent, span: Span): boolean {\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: unknown;\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: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\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: StreamingState, span: Span, recordOutputs: boolean): void {\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 */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\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 */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n): R {\n const state: StreamingState = {\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: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, 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: unknown) => {\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"],"names":[],"mappings":";;;;;AAcA;AACA;AACA;;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,CAAC,KAAK,EAA6B,IAAI,EAAiB;AAC7E,EAAE,IAAI,MAAA,IAAU,KAAA,IAAS,OAAO,KAAK,CAAC,IAAA,KAAS,QAAQ,EAAE;AACzD;AACA;AACA,IAAI,IAAI,KAAK,CAAC,IAAA,KAAS,OAAO,EAAE;AAChC,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,KAAK,CAAC,KAAK,EAAE,QAAQ,gBAAA,EAAkB,CAAC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ACtB,QAAQ,IAAI,EAAE,gCAAgC;AAC9C,OAAO;AACP,KAAK,CAAC;;AAEN,IAAI,IAAI,IAAI,CAAC,WAAW,EAAE,EAAE;AAC5B,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,cAAA,EAAgB,CAAC;AAC1E,MAAM,IAAI,CAAC,GAAG,EAAE;AAChB,IAAI;AACJ,EAAE,CAAC,CAAC;;AAEJ,EAAE,OAAO,MAAM;AACf;;;;"}
|
|
1
|
+
{"version":3,"file":"streaming.js","sources":["../../../../src/tracing/anthropic-ai/streaming.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n GEN_AI_RESPONSE_FINISH_REASONS_ATTRIBUTE,\n GEN_AI_RESPONSE_ID_ATTRIBUTE,\n GEN_AI_RESPONSE_MODEL_ATTRIBUTE,\n GEN_AI_RESPONSE_STREAMING_ATTRIBUTE,\n GEN_AI_RESPONSE_TEXT_ATTRIBUTE,\n GEN_AI_RESPONSE_TOOL_CALLS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { setTokenUsageAttributes } from '../ai/utils';\nimport type { AnthropicAiStreamingEvent } from './types';\nimport { mapAnthropicErrorToStatusMessage } from './utils';\n\n/**\n * State object used to accumulate information from a stream of Anthropic AI events.\n */\ninterface StreamingState {\n /** Collected response text fragments (for output recording). */\n responseTexts: string[];\n /** Reasons for finishing the response, as reported by the API. */\n finishReasons: string[];\n /** The response ID. */\n responseId: string;\n /** The model name. */\n responseModel: string;\n /** Number of prompt/input tokens used. */\n promptTokens: number | undefined;\n /** Number of completion/output tokens used. */\n completionTokens: number | undefined;\n /** Number of cache creation input tokens used. */\n cacheCreationInputTokens: number | undefined;\n /** Number of cache read input tokens used. */\n cacheReadInputTokens: number | undefined;\n /** Accumulated tool calls (finalized) */\n toolCalls: Array<Record<string, unknown>>;\n /** In-progress tool call blocks keyed by index */\n activeToolBlocks: Record<\n number,\n {\n id?: string;\n name?: string;\n inputJsonParts: string[];\n }\n >;\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: AnthropicAiStreamingEvent, span: Span): boolean {\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: mapAnthropicErrorToStatusMessage(event.error?.type) });\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n): void {\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: AnthropicAiStreamingEvent, state: StreamingState): void {\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: unknown;\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: AnthropicAiStreamingEvent,\n state: StreamingState,\n recordOutputs: boolean,\n span: Span,\n): void {\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: StreamingState, span: Span, recordOutputs: boolean): void {\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 */\nexport async function* instrumentAsyncIterableStream(\n stream: AsyncIterable<AnthropicAiStreamingEvent>,\n span: Span,\n recordOutputs: boolean,\n): AsyncGenerator<AnthropicAiStreamingEvent, void, unknown> {\n const state: StreamingState = {\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 */\nexport function instrumentMessageStream<R extends { on: (...args: unknown[]) => void }>(\n stream: R,\n span: Span,\n recordOutputs: boolean,\n): R {\n const state: StreamingState = {\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: unknown) => {\n processEvent(event as AnthropicAiStreamingEvent, 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: unknown) => {\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: 'internal_error' });\n span.end();\n }\n });\n\n return stream;\n}\n"],"names":[],"mappings":";;;;;;AAeA;AACA;AACA;;AA+BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AAEA,SAAS,YAAY,CAAC,KAAK,EAA6B,IAAI,EAAiB;AAC7E,EAAE,IAAI,MAAA,IAAU,KAAA,IAAS,OAAO,KAAK,CAAC,IAAA,KAAS,QAAQ,EAAE;AACzD;AACA;AACA,IAAI,IAAI,KAAK,CAAC,IAAA,KAAS,OAAO,EAAE;AAChC,MAAM,IAAI,CAAC,SAAS,CAAC,EAAE,IAAI,EAAE,iBAAiB,EAAE,OAAO,EAAE,gCAAgC,CAAC,KAAK,CAAC,KAAK,EAAE,IAAI,CAAA,EAAG,CAAC;AAC/G,MAAM,gBAAgB,CAAC,KAAK,CAAC,KAAK,EAAE;AACpC,QAAQ,SAAS,EAAE;AACnB,UAAU,OAAO,EAAE,KAAK;AACxB,UAAU,IAAI,EAAE,mCAAmC;AACnD,SAAS;AACT,OAAO,CAAC;AACR,MAAM,OAAO,IAAI;AACjB,IAAI;AACJ,EAAE;AACF,EAAE,OAAO,KAAK;AACd;;AAEA;AACA;AACA;AACA;AACA;;AAEA,SAAS,qBAAqB,CAAC,KAAK,EAA6B,KAAK,EAAwB;AAC9F;AACA;AACA,EAAE,IAAI,KAAK,CAAC,IAAA,KAAS,eAAA,IAAmB,KAAK,CAAC,KAAK,EAAE;AACrD,IAAI,IAAI,eA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PIC_ERROR_TYPE_TO_SPAN_STATUS = {
|
|
39
|
+
invalid_request_error: 'invalid_argument',
|
|
40
|
+
authentication_error: 'unauthenticated',
|
|
41
|
+
permission_error: 'permission_denied',
|
|
42
|
+
not_found_error: 'not_found',
|
|
43
|
+
request_too_large: 'failed_precondition',
|
|
44
|
+
rate_limit_error: 'resource_exhausted',
|
|
45
|
+
api_error: 'internal_error',
|
|
46
|
+
overloaded_error: 'unavailable',
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Map an Anthropic API error type to a SpanStatusType value.
|
|
51
|
+
* @see https://docs.anthropic.com/en/api/errors#error-shapes
|
|
52
|
+
*/
|
|
53
|
+
function mapAnthropicErrorToStatusMessage(errorType) {
|
|
54
|
+
if (!errorType) {
|
|
55
|
+
return 'internal_error';
|
|
56
|
+
}
|
|
57
|
+
return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';
|
|
58
|
+
}
|
|
59
|
+
|
|
38
60
|
/**
|
|
39
61
|
* Capture error information from the response
|
|
40
62
|
* @see https://docs.anthropic.com/en/api/errors#error-shapes
|
|
41
63
|
*/
|
|
42
64
|
function handleResponseError(span, response) {
|
|
43
65
|
if (response.error) {
|
|
44
|
-
span.setStatus({ code: SPAN_STATUS_ERROR, message: response.error.type
|
|
66
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });
|
|
45
67
|
|
|
46
68
|
captureException(response.error, {
|
|
47
69
|
mechanism: {
|
|
@@ -69,5 +91,5 @@ function messagesFromParams(params) {
|
|
|
69
91
|
return [...systemMessages, ...userMessages];
|
|
70
92
|
}
|
|
71
93
|
|
|
72
|
-
export { handleResponseError, messagesFromParams, setMessagesAttribute, shouldInstrument };
|
|
94
|
+
export { handleResponseError, mapAnthropicErrorToStatusMessage, messagesFromParams, setMessagesAttribute, shouldInstrument };
|
|
73
95
|
//# sourceMappingURL=utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"utils.js","sources":["../../../../src/tracing/anthropic-ai/utils.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport {\n GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';\nimport { ANTHROPIC_AI_INSTRUMENTED_METHODS } from './constants';\nimport type { AnthropicAiInstrumentedMethod, AnthropicAiResponse } from './types';\n\n/**\n * Check if a method path should be instrumented\n */\nexport function shouldInstrument(methodPath: string): methodPath is AnthropicAiInstrumentedMethod {\n return ANTHROPIC_AI_INSTRUMENTED_METHODS.includes(methodPath as AnthropicAiInstrumentedMethod);\n}\n\n/**\n * Set the messages and messages original length attributes.\n * Extracts system instructions before truncation.\n */\nexport function setMessagesAttribute(span: Span, messages: unknown): void {\n if (Array.isArray(messages) && messages.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n if (systemInstructions) {\n span.setAttributes({\n [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions,\n });\n }\n\n const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: getTruncatedJsonString(filteredMessages),\n [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n });\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: response.error.type
|
|
1
|
+
{"version":3,"file":"utils.js","sources":["../../../../src/tracing/anthropic-ai/utils.ts"],"sourcesContent":["import { captureException } from '../../exports';\nimport { SPAN_STATUS_ERROR } from '../../tracing';\nimport type { Span } from '../../types-hoist/span';\nimport type { SpanStatusType } from '../../types-hoist/spanStatus';\nimport {\n GEN_AI_INPUT_MESSAGES_ATTRIBUTE,\n GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE,\n GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE,\n} from '../ai/gen-ai-attributes';\nimport { extractSystemInstructions, getTruncatedJsonString } from '../ai/utils';\nimport { ANTHROPIC_AI_INSTRUMENTED_METHODS } from './constants';\nimport type { AnthropicAiInstrumentedMethod, AnthropicAiResponse } from './types';\n\n/**\n * Check if a method path should be instrumented\n */\nexport function shouldInstrument(methodPath: string): methodPath is AnthropicAiInstrumentedMethod {\n return ANTHROPIC_AI_INSTRUMENTED_METHODS.includes(methodPath as AnthropicAiInstrumentedMethod);\n}\n\n/**\n * Set the messages and messages original length attributes.\n * Extracts system instructions before truncation.\n */\nexport function setMessagesAttribute(span: Span, messages: unknown): void {\n if (Array.isArray(messages) && messages.length === 0) {\n return;\n }\n\n const { systemInstructions, filteredMessages } = extractSystemInstructions(messages);\n\n if (systemInstructions) {\n span.setAttributes({\n [GEN_AI_SYSTEM_INSTRUCTIONS_ATTRIBUTE]: systemInstructions,\n });\n }\n\n const filteredLength = Array.isArray(filteredMessages) ? filteredMessages.length : 1;\n span.setAttributes({\n [GEN_AI_INPUT_MESSAGES_ATTRIBUTE]: getTruncatedJsonString(filteredMessages),\n [GEN_AI_INPUT_MESSAGES_ORIGINAL_LENGTH_ATTRIBUTE]: filteredLength,\n });\n}\n\nconst ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS: Record<string, SpanStatusType> = {\n invalid_request_error: 'invalid_argument',\n authentication_error: 'unauthenticated',\n permission_error: 'permission_denied',\n not_found_error: 'not_found',\n request_too_large: 'failed_precondition',\n rate_limit_error: 'resource_exhausted',\n api_error: 'internal_error',\n overloaded_error: 'unavailable',\n};\n\n/**\n * Map an Anthropic API error type to a SpanStatusType value.\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function mapAnthropicErrorToStatusMessage(errorType: string | undefined): SpanStatusType {\n if (!errorType) {\n return 'internal_error';\n }\n return ANTHROPIC_ERROR_TYPE_TO_SPAN_STATUS[errorType] || 'internal_error';\n}\n\n/**\n * Capture error information from the response\n * @see https://docs.anthropic.com/en/api/errors#error-shapes\n */\nexport function handleResponseError(span: Span, response: AnthropicAiResponse): void {\n if (response.error) {\n span.setStatus({ code: SPAN_STATUS_ERROR, message: mapAnthropicErrorToStatusMessage(response.error.type) });\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 */\nexport function messagesFromParams(params: Record<string, unknown>): unknown[] {\n const { system, messages, input } = params;\n\n const systemMessages = typeof system === 'string' ? [{ role: 'system', content: params.system }] : [];\n\n const inputParamMessages = Array.isArray(input) ? input : input != null ? [input] : undefined;\n\n const messagesParamMessages = Array.isArray(messages) ? messages : messages != null ? [messages] : [];\n\n const userMessages = inputParamMessages ?? messagesParamMessages;\n\n return [...systemMessages, ...userMessages];\n}\n"],"names":[],"mappings":";;;;;;AAaA;AACA;AACA;AACO,SAAS,gBAAgB,CAAC,UAAU,EAAuD;AAClG,EAAE,OAAO,iCAAiC,CAAC,QAAQ,CAAC,YAA4C;AAChG;;AAEA;AACA;AACA;AACA;AACO,SAAS,oBAAoB,CAAC,IAAI,EAAQ,QAAQ,EAAiB;AAC1E,EAAE,IAAI,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAA,IAAK,QAAQ,CAAC,MAAA,KAAW,CAAC,EAAE;AACxD,IAAI;AACJ,EAAE;;AAEF,EAAE,MAAM,EAAE,kBAAkB,EAAE,gBAAA,KAAqB,yBAAyB,CAAC,QAAQ,CAAC;;AAEtF,E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AE;AACrC,MAAM,SAAS,EAAE;AACjB,QAAQ,OAAO,EAAE,KAAK;AACtB,QAAQ,IAAI,EAAE,mCAAmC;AACjD,OAAO;AACP,KAAK,CAAC;AACN,EAAE;AACF;;AAEA;AACA;AACA;AACO,SAAS,kBAAkB,CAAC,MAAM,EAAsC;AAC/E,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,KAAA,EAAM,GAAI,MAAM;;AAE5C,EAAE,MAAM,iBAAiB,OAAO,WAAW,QAAA,GAAW,CAAC,EAAE,IAAI,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,CAAC,QAAQ,CAAA,GAAI,EAAE;;AAEvG,EAAE,MAAM,qBAAqB,KAAK,CAAC,OAAO,CAAC,KAAK,CAAA,GAAI,QAAQ,KAAA,IAAS,IAAA,GAAO,CAAC,KAAK,CAAA,GAAI,SAAS;;AAE/F,EAAE,MAAM,wBAAwB,KAAK,CAAC,OAAO,CAAC,QAAQ,CAAA,GAAI,WAAW,QAAA,IAAY,IAAA,GAAO,CAAC,QAAQ,CAAA,GAAI,EAAE;;AAEvG,EAAE,MAAM,YAAA,GAAe,kBAAA,IAAsB,qBAAqB;;AAElE,EAAE,OAAO,CAAC,GAAG,cAAc,EAAE,GAAG,YAAY,CAAC;AAC7C;;;;"}
|
|
@@ -16,7 +16,7 @@ function isErrorChunk(chunk, span) {
|
|
|
16
16
|
const feedback = chunk?.promptFeedback;
|
|
17
17
|
if (feedback?.blockReason) {
|
|
18
18
|
const message = feedback.blockReasonMessage ?? feedback.blockReason;
|
|
19
|
-
span.setStatus({ code: SPAN_STATUS_ERROR, message:
|
|
19
|
+
span.setStatus({ code: SPAN_STATUS_ERROR, message: 'internal_error' });
|
|
20
20
|
captureException(`Content blocked: ${message}`, {
|
|
21
21
|
mechanism: { handled: false, type: 'auto.ai.google_genai' },
|
|
22
22
|
});
|