@sentry/browser 11.0.0-rc.1 → 11.0.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.
Files changed (60) hide show
  1. package/build/npm/cjs/dev/helpers.js +24 -2
  2. package/build/npm/cjs/dev/helpers.js.map +1 -1
  3. package/build/npm/cjs/dev/integrations/globalhandlers.js +2 -1
  4. package/build/npm/cjs/dev/integrations/globalhandlers.js.map +1 -1
  5. package/build/npm/cjs/dev/integrations/httpclient.js +3 -6
  6. package/build/npm/cjs/dev/integrations/httpclient.js.map +1 -1
  7. package/build/npm/cjs/dev/integrations/httpcontext.js +6 -0
  8. package/build/npm/cjs/dev/integrations/httpcontext.js.map +1 -1
  9. package/build/npm/cjs/dev/integrations/spotlight.js +4 -1
  10. package/build/npm/cjs/dev/integrations/spotlight.js.map +1 -1
  11. package/build/npm/cjs/dev/integrations/webWorker.js +73 -19
  12. package/build/npm/cjs/dev/integrations/webWorker.js.map +1 -1
  13. package/build/npm/cjs/prod/helpers.js +24 -2
  14. package/build/npm/cjs/prod/helpers.js.map +1 -1
  15. package/build/npm/cjs/prod/integrations/globalhandlers.js +2 -1
  16. package/build/npm/cjs/prod/integrations/globalhandlers.js.map +1 -1
  17. package/build/npm/cjs/prod/integrations/httpclient.js +3 -6
  18. package/build/npm/cjs/prod/integrations/httpclient.js.map +1 -1
  19. package/build/npm/cjs/prod/integrations/httpcontext.js +6 -0
  20. package/build/npm/cjs/prod/integrations/httpcontext.js.map +1 -1
  21. package/build/npm/cjs/prod/integrations/spotlight.js +4 -1
  22. package/build/npm/cjs/prod/integrations/spotlight.js.map +1 -1
  23. package/build/npm/cjs/prod/integrations/webWorker.js +73 -19
  24. package/build/npm/cjs/prod/integrations/webWorker.js.map +1 -1
  25. package/build/npm/esm/dev/helpers.js +24 -3
  26. package/build/npm/esm/dev/helpers.js.map +1 -1
  27. package/build/npm/esm/dev/integrations/globalhandlers.js +2 -2
  28. package/build/npm/esm/dev/integrations/globalhandlers.js.map +1 -1
  29. package/build/npm/esm/dev/integrations/httpclient.js +3 -6
  30. package/build/npm/esm/dev/integrations/httpclient.js.map +1 -1
  31. package/build/npm/esm/dev/integrations/httpcontext.js +6 -0
  32. package/build/npm/esm/dev/integrations/httpcontext.js.map +1 -1
  33. package/build/npm/esm/dev/integrations/spotlight.js +4 -1
  34. package/build/npm/esm/dev/integrations/spotlight.js.map +1 -1
  35. package/build/npm/esm/dev/integrations/webWorker.js +77 -23
  36. package/build/npm/esm/dev/integrations/webWorker.js.map +1 -1
  37. package/build/npm/esm/dev/package.json +1 -1
  38. package/build/npm/esm/prod/helpers.js +24 -3
  39. package/build/npm/esm/prod/helpers.js.map +1 -1
  40. package/build/npm/esm/prod/integrations/globalhandlers.js +2 -2
  41. package/build/npm/esm/prod/integrations/globalhandlers.js.map +1 -1
  42. package/build/npm/esm/prod/integrations/httpclient.js +3 -6
  43. package/build/npm/esm/prod/integrations/httpclient.js.map +1 -1
  44. package/build/npm/esm/prod/integrations/httpcontext.js +6 -0
  45. package/build/npm/esm/prod/integrations/httpcontext.js.map +1 -1
  46. package/build/npm/esm/prod/integrations/spotlight.js +4 -1
  47. package/build/npm/esm/prod/integrations/spotlight.js.map +1 -1
  48. package/build/npm/esm/prod/integrations/webWorker.js +77 -23
  49. package/build/npm/esm/prod/integrations/webWorker.js.map +1 -1
  50. package/build/npm/esm/prod/package.json +1 -1
  51. package/build/npm/types/helpers.d.ts +10 -2
  52. package/build/npm/types/helpers.d.ts.map +1 -1
  53. package/build/npm/types/integrations/globalhandlers.d.ts +4 -0
  54. package/build/npm/types/integrations/globalhandlers.d.ts.map +1 -1
  55. package/build/npm/types/integrations/httpcontext.d.ts.map +1 -1
  56. package/build/npm/types/integrations/spotlight.d.ts +9 -2
  57. package/build/npm/types/integrations/spotlight.d.ts.map +1 -1
  58. package/build/npm/types/integrations/webWorker.d.ts +5 -4
  59. package/build/npm/types/integrations/webWorker.d.ts.map +1 -1
  60. package/package.json +7 -7
@@ -7,6 +7,7 @@ const helpers = require('../helpers.js');
7
7
  const globalhandlers = require('./globalhandlers.js');
8
8
 
9
9
  const INTEGRATION_NAME = "WebWorker";
10
+ const MAX_FORWARDED_ERRORS = 20;
10
11
  const webWorkerIntegration = core.defineIntegration(({ worker }) => ({
11
12
  name: INTEGRATION_NAME,
12
13
  setupOnce: () => {
@@ -15,6 +16,16 @@ const webWorkerIntegration = core.defineIntegration(({ worker }) => ({
15
16
  addWorker: (worker2) => listenForSentryMessages(worker2)
16
17
  }));
17
18
  function listenForSentryMessages(worker) {
19
+ const forwardedErrors = [];
20
+ worker.addEventListener("error", ({ message, filename, lineno, colno }) => {
21
+ const index = forwardedErrors.findIndex(
22
+ (e) => e.message === message && e.url === filename && e.lineno === lineno && e.colno === colno
23
+ );
24
+ if (index !== -1) {
25
+ forwardedErrors.splice(0, index + 1);
26
+ helpers.ignoreNextOnErrorMatching({ msg: message, url: filename, line: lineno, column: colno });
27
+ }
28
+ });
18
29
  worker.addEventListener("message", (event) => {
19
30
  if (isSentryMessage(event.data)) {
20
31
  event.stopImmediatePropagation();
@@ -46,27 +57,40 @@ function listenForSentryMessages(worker) {
46
57
  ];
47
58
  }
48
59
  if (event.data._sentryWorkerError) {
49
- debugBuild.DEBUG_BUILD && core.debug.log("Sentry worker rejection message received", event.data._sentryWorkerError);
50
- handleForwardedWorkerRejection(event.data._sentryWorkerError);
60
+ debugBuild.DEBUG_BUILD && core.debug.log("Sentry worker error message received", event.data._sentryWorkerError);
61
+ const { kind, message, url, lineno, colno } = event.data._sentryWorkerError;
62
+ if (kind === "error") {
63
+ if (forwardedErrors.push({ message, url, lineno, colno }) > MAX_FORWARDED_ERRORS) {
64
+ forwardedErrors.shift();
65
+ }
66
+ }
67
+ handleForwardedWorkerError(event.data._sentryWorkerError);
51
68
  }
52
69
  }
53
70
  });
54
71
  }
55
- function handleForwardedWorkerRejection(workerError) {
72
+ function handleForwardedWorkerError(workerError) {
73
+ const { reason, kind, name, filename, url, lineno, colno, plainError } = workerError;
74
+ const isUnhandledRejection = kind !== "error";
75
+ const error = plainError && core.isPlainObject(reason) ? errorFromPlain(reason) : reason;
76
+ if (name && core.isError(error) && error.name !== name) {
77
+ core.addNonEnumerableProperty(error, "name", name);
78
+ }
56
79
  const client = core.getClient();
57
80
  if (!client) {
58
81
  return;
59
82
  }
60
- const stackParser = client.getOptions().stackParser;
61
- const attachStacktrace = client.getOptions().attachStacktrace;
62
- const error = workerError.reason;
63
- const event = core.isPrimitive(error) ? globalhandlers._eventFromRejectionWithPrimitive(error) : eventbuilder.eventFromUnknownInput(stackParser, error, void 0, attachStacktrace, true);
83
+ const { stackParser, attachStacktrace } = client.getOptions();
84
+ const event = isUnhandledRejection && core.isPrimitive(error) ? globalhandlers._eventFromRejectionWithPrimitive(error) : eventbuilder.eventFromUnknownInput(stackParser, error, void 0, attachStacktrace, isUnhandledRejection);
85
+ if (!isUnhandledRejection) {
86
+ globalhandlers._enhanceEventWithInitialFrame(event, url || filename, lineno, colno);
87
+ }
64
88
  event.level = "error";
65
- if (workerError.filename) {
89
+ if (filename) {
66
90
  event.contexts = {
67
91
  ...event.contexts,
68
92
  worker: {
69
- filename: workerError.filename
93
+ filename
70
94
  }
71
95
  };
72
96
  }
@@ -74,30 +98,60 @@ function handleForwardedWorkerRejection(workerError) {
74
98
  originalException: error,
75
99
  mechanism: {
76
100
  handled: false,
77
- type: "auto.browser.web_worker.onunhandledrejection"
101
+ type: isUnhandledRejection ? "auto.browser.web_worker.onunhandledrejection" : "auto.browser.web_worker.onerror"
78
102
  }
79
103
  });
80
- debugBuild.DEBUG_BUILD && core.debug.log("Captured worker unhandled rejection", error);
104
+ debugBuild.DEBUG_BUILD && core.debug.log(`Captured worker ${isUnhandledRejection ? "unhandled rejection" : "error"}`, error);
81
105
  }
82
106
  function registerWebWorker({ self }) {
107
+ Error.stackTraceLimit = 50;
83
108
  self.postMessage({
84
109
  _sentryMessage: true,
85
110
  _sentryDebugIds: self._sentryDebugIds ?? void 0,
86
111
  _sentryModuleMetadata: self._sentryModuleMetadata ?? void 0
87
112
  });
113
+ const forward = (serializedError) => {
114
+ const { reason } = serializedError;
115
+ debugBuild.DEBUG_BUILD && core.debug.log(`[Sentry Worker] Forwarding ${serializedError.kind} to parent`, serializedError);
116
+ postSerializedWorkerError(self, {
117
+ ...serializedError,
118
+ filename: self.location?.href,
119
+ name: core.isError(reason) ? eventbuilder.extractType(reason) : void 0
120
+ });
121
+ };
122
+ self.addEventListener("error", (event) => {
123
+ const { error, message, filename, lineno, colno } = event;
124
+ forward({ kind: "error", reason: error ?? message, message, url: filename, lineno, colno });
125
+ });
88
126
  self.addEventListener("unhandledrejection", (event) => {
89
- const reason = globalhandlers._getUnhandledRejectionError(event);
90
- const serializedError = {
91
- reason,
92
- filename: self.location?.href
93
- };
127
+ forward({ kind: "unhandledrejection", reason: globalhandlers._getUnhandledRejectionError(event) });
128
+ });
129
+ debugBuild.DEBUG_BUILD && core.debug.log("[Sentry Worker] Registered worker with error and unhandled rejection handling");
130
+ }
131
+ function postSerializedWorkerError(self, serializedError) {
132
+ try {
94
133
  self.postMessage({
95
134
  _sentryMessage: true,
96
135
  _sentryWorkerError: serializedError
97
136
  });
98
- debugBuild.DEBUG_BUILD && core.debug.log("[Sentry Worker] Forwarding unhandled rejection to parent", serializedError);
99
- });
100
- debugBuild.DEBUG_BUILD && core.debug.log("[Sentry Worker] Registered worker with unhandled rejection handling");
137
+ return;
138
+ } catch {
139
+ }
140
+ const { reason } = serializedError;
141
+ const plainError = core.isError(reason);
142
+ const plainReason = plainError ? { message: eventbuilder.extractMessage(reason), stack: reason.stack } : core.normalize(reason);
143
+ try {
144
+ self.postMessage({
145
+ _sentryMessage: true,
146
+ _sentryWorkerError: { ...serializedError, reason: plainReason, plainError }
147
+ });
148
+ } catch {
149
+ }
150
+ }
151
+ function errorFromPlain(plain) {
152
+ const error = new Error(String(plain.message));
153
+ error.stack = typeof plain.stack === "string" ? plain.stack : void 0;
154
+ return error;
101
155
  }
102
156
  function isSentryMessage(eventData) {
103
157
  if (!core.isPlainObject(eventData) || eventData._sentryMessage !== true) {
@@ -1 +1 @@
1
- {"version":3,"file":"webWorker.js","sources":["../../../../../src/integrations/webWorker.ts"],"sourcesContent":["import type { DebugImage, Integration, IntegrationFn } from '@sentry/core';\nimport { captureEvent, debug, defineIntegration, getClient, isPlainObject, isPrimitive } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { WINDOW } from '../helpers';\nimport { _eventFromRejectionWithPrimitive, _getUnhandledRejectionError } from './globalhandlers';\n\nexport const INTEGRATION_NAME = 'WebWorker' as const;\n\ninterface WebWorkerMessage {\n _sentryMessage: boolean;\n _sentryDebugIds?: Record<string, string>;\n _sentryModuleMetadata?: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n _sentryWorkerError?: SerializedWorkerError;\n _sentryWasmImages?: Array<DebugImage>;\n}\n\ninterface SerializedWorkerError {\n reason: unknown;\n filename?: string;\n}\n\ninterface WebWorkerIntegrationOptions {\n worker: Worker | Array<Worker>;\n}\n\ninterface WebWorkerIntegration extends Integration {\n addWorker: (worker: Worker) => void;\n}\n\n/**\n * Use this integration to set up Sentry with web workers.\n *\n * IMPORTANT: This integration must be added **before** you start listening to\n * any messages from the worker. Otherwise, your message handlers will receive\n * messages from the Sentry SDK which you need to ignore.\n *\n * This integration only has an effect, if you call `Sentry.registerWebWorker(self)`\n * from within the worker(s) you're adding to the integration.\n *\n * Given that you want to initialize the SDK as early as possible, you most likely\n * want to add this integration **after** initializing the SDK:\n *\n * @example:\n * ```ts filename={main.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // some time earlier:\n * Sentry.init(...)\n *\n * // 1. Initialize the worker\n * const worker = new Worker(new URL('./worker.ts', import.meta.url));\n *\n * // 2. Add the integration\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker });\n * Sentry.addIntegration(webWorkerIntegration);\n *\n * // 3. Register message listeners on the worker\n * worker.addEventListener('message', event => {\n * // ...\n * });\n * ```\n *\n * If you initialize multiple workers at the same time, you can also pass an array of workers\n * to the integration:\n *\n * ```ts filename={main.js}\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker: [worker1, worker2] });\n * Sentry.addIntegration(webWorkerIntegration);\n * ```\n *\n * If you have any additional workers that you initialize at a later point,\n * you can add them to the integration as follows:\n *\n * ```ts filename={main.js}\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker: worker1 });\n * Sentry.addIntegration(webWorkerIntegration);\n *\n * // sometime later:\n * webWorkerIntegration.addWorker(worker2);\n * ```\n *\n * Of course, you can also directly add the integration in Sentry.init:\n * ```ts filename={main.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // 1. Initialize the worker\n * const worker = new Worker(new URL('./worker.ts', import.meta.url));\n *\n * // 2. Initialize the SDK\n * Sentry.init({\n * integrations: [Sentry.webWorkerIntegration({ worker })]\n * });\n *\n * // 3. Register message listeners on the worker\n * worker.addEventListener('message', event => {\n * // ...\n * });\n * ```\n *\n * @param options {WebWorkerIntegrationOptions} Integration options:\n * - `worker`: The worker instance.\n */\nexport const webWorkerIntegration = defineIntegration(({ worker }: WebWorkerIntegrationOptions) => ({\n name: INTEGRATION_NAME,\n setupOnce: () => {\n (Array.isArray(worker) ? worker : [worker]).forEach(w => listenForSentryMessages(w));\n },\n addWorker: (worker: Worker) => listenForSentryMessages(worker),\n})) as IntegrationFn<WebWorkerIntegration>;\n\nfunction listenForSentryMessages(worker: Worker): void {\n worker.addEventListener('message', event => {\n if (isSentryMessage(event.data)) {\n event.stopImmediatePropagation(); // other listeners should not receive this message\n\n // Handle debug IDs\n if (event.data._sentryDebugIds) {\n DEBUG_BUILD && debug.log('Sentry debugId web worker message received', event.data);\n WINDOW._sentryDebugIds = {\n ...event.data._sentryDebugIds,\n // debugIds of the main thread have precedence over the worker's in case of a collision.\n ...WINDOW._sentryDebugIds,\n };\n }\n\n // Handle module metadata\n if (event.data._sentryModuleMetadata) {\n DEBUG_BUILD && debug.log('Sentry module metadata web worker message received', event.data);\n // Merge worker's raw metadata into the global object\n // It will be parsed lazily when needed by getMetadataForUrl\n WINDOW._sentryModuleMetadata = {\n ...event.data._sentryModuleMetadata,\n // Module metadata of the main thread have precedence over the worker's in case of a collision.\n ...WINDOW._sentryModuleMetadata,\n };\n }\n\n // Handle WASM images from worker\n if (event.data._sentryWasmImages) {\n DEBUG_BUILD && debug.log('Sentry WASM images web worker message received', event.data);\n const existingImages =\n (WINDOW as typeof WINDOW & { _sentryWasmImages?: Array<DebugImage> })._sentryWasmImages || [];\n const newImages = event.data._sentryWasmImages.filter(\n (newImg: unknown) =>\n isPlainObject(newImg) &&\n typeof newImg.code_file === 'string' &&\n !existingImages.some(existing => existing.code_file === newImg.code_file),\n );\n (WINDOW as typeof WINDOW & { _sentryWasmImages?: Array<DebugImage> })._sentryWasmImages = [\n ...existingImages,\n ...newImages,\n ];\n }\n\n // Handle unhandled rejections forwarded from worker\n if (event.data._sentryWorkerError) {\n DEBUG_BUILD && debug.log('Sentry worker rejection message received', event.data._sentryWorkerError);\n handleForwardedWorkerRejection(event.data._sentryWorkerError);\n }\n }\n });\n}\n\nfunction handleForwardedWorkerRejection(workerError: SerializedWorkerError): void {\n const client = getClient();\n if (!client) {\n return;\n }\n\n const stackParser = client.getOptions().stackParser;\n const attachStacktrace = client.getOptions().attachStacktrace;\n\n const error = workerError.reason;\n\n // Follow same pattern as globalHandlers for unhandledrejection\n // Handle both primitives and errors the same way\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n // Add worker-specific context\n if (workerError.filename) {\n event.contexts = {\n ...event.contexts,\n worker: {\n filename: workerError.filename,\n },\n };\n }\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.web_worker.onunhandledrejection',\n },\n });\n\n DEBUG_BUILD && debug.log('Captured worker unhandled rejection', error);\n}\n\n/**\n * Minimal interface for DedicatedWorkerGlobalScope, only requiring the postMessage method.\n * (which is the only thing we need from the worker's global object)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope\n *\n * We can't use the actual type because it breaks everyone who doesn't have {\"lib\": [\"WebWorker\"]}\n * but uses {\"skipLibCheck\": true} in their tsconfig.json.\n */\ninterface MinimalDedicatedWorkerGlobalScope {\n postMessage: (message: unknown) => void;\n addEventListener: (type: string, listener: (event: unknown) => void) => void;\n location?: { href?: string };\n}\n\ninterface RegisterWebWorkerOptions {\n self: MinimalDedicatedWorkerGlobalScope & {\n _sentryDebugIds?: Record<string, string>;\n _sentryModuleMetadata?: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n}\n\n/**\n * Use this function to register the worker with the Sentry SDK.\n *\n * This function will:\n * - Send debug IDs to the parent thread\n * - Send module metadata to the parent thread (for thirdPartyErrorFilterIntegration)\n * - Set up a handler for unhandled rejections in the worker\n * - Forward unhandled rejections to the parent thread for capture\n *\n * Note: Synchronous errors in workers are already captured by globalHandlers.\n * This only handles unhandled promise rejections which don't bubble to the parent.\n *\n * @example\n * ```ts filename={worker.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // Do this as early as possible in your worker.\n * Sentry.registerWebWorker({ self });\n *\n * // continue setting up your worker\n * self.postMessage(...)\n * ```\n * @param options {RegisterWebWorkerOptions} Integration options:\n * - `self`: The worker instance you're calling this function from (self).\n */\nexport function registerWebWorker({ self }: RegisterWebWorkerOptions): void {\n // Send debug IDs and raw module metadata to parent thread\n // The metadata will be parsed lazily on the main thread when needed\n self.postMessage({\n _sentryMessage: true,\n _sentryDebugIds: self._sentryDebugIds ?? undefined,\n _sentryModuleMetadata: self._sentryModuleMetadata ?? undefined,\n });\n\n // Set up unhandledrejection handler inside the worker\n // Following the same pattern as globalHandlers\n // unhandled rejections don't bubble to the parent thread, so we need to handle them here\n self.addEventListener('unhandledrejection', (event: unknown) => {\n const reason = _getUnhandledRejectionError(event);\n\n // Forward the raw reason to parent thread\n // The parent will handle primitives vs errors the same way globalHandlers does\n const serializedError: SerializedWorkerError = {\n reason: reason,\n filename: self.location?.href,\n };\n\n // Forward to parent thread\n self.postMessage({\n _sentryMessage: true,\n _sentryWorkerError: serializedError,\n });\n\n DEBUG_BUILD && debug.log('[Sentry Worker] Forwarding unhandled rejection to parent', serializedError);\n });\n\n DEBUG_BUILD && debug.log('[Sentry Worker] Registered worker with unhandled rejection handling');\n}\n\nfunction isSentryMessage(eventData: unknown): eventData is WebWorkerMessage {\n if (!isPlainObject(eventData) || eventData._sentryMessage !== true) {\n return false;\n }\n\n // Must have at least one of: debug IDs, module metadata, worker error, or WASM images\n const hasDebugIds = '_sentryDebugIds' in eventData;\n const hasModuleMetadata = '_sentryModuleMetadata' in eventData;\n const hasWorkerError = '_sentryWorkerError' in eventData;\n const hasWasmImages = '_sentryWasmImages' in eventData;\n\n if (!hasDebugIds && !hasModuleMetadata && !hasWorkerError && !hasWasmImages) {\n return false;\n }\n\n // Validate debug IDs if present\n if (hasDebugIds && !(isPlainObject(eventData._sentryDebugIds) || eventData._sentryDebugIds === undefined)) {\n return false;\n }\n\n // Validate module metadata if present\n if (\n hasModuleMetadata &&\n !(isPlainObject(eventData._sentryModuleMetadata) || eventData._sentryModuleMetadata === undefined)\n ) {\n return false;\n }\n\n // Validate worker error if present\n if (hasWorkerError && !isPlainObject(eventData._sentryWorkerError)) {\n return false;\n }\n\n // Validate WASM images if present\n if (\n hasWasmImages &&\n (!Array.isArray(eventData._sentryWasmImages) ||\n !eventData._sentryWasmImages.every(\n (img: unknown) => isPlainObject(img) && typeof (img as { code_file?: unknown }).code_file === 'string',\n ))\n ) {\n return false;\n }\n\n return true;\n}\n"],"names":["defineIntegration","worker","DEBUG_BUILD","debug","WINDOW","isPlainObject","getClient","isPrimitive","_eventFromRejectionWithPrimitive","eventFromUnknownInput","captureEvent","_getUnhandledRej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AAO,IAAA;AACT;;;;;;"}
1
+ {"version":3,"file":"webWorker.js","sources":["../../../../../src/integrations/webWorker.ts"],"sourcesContent":["import type { DebugImage, Integration, IntegrationFn } from '@sentry/core';\nimport {\n addNonEnumerableProperty,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n isError,\n isPlainObject,\n isPrimitive,\n normalize,\n} from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { eventFromUnknownInput, extractMessage, extractType } from '../eventbuilder';\nimport { ignoreNextOnErrorMatching, WINDOW } from '../helpers';\nimport {\n _enhanceEventWithInitialFrame,\n _eventFromRejectionWithPrimitive,\n _getUnhandledRejectionError,\n} from './globalhandlers';\n\nexport const INTEGRATION_NAME = 'WebWorker' as const;\n\nconst MAX_FORWARDED_ERRORS = 20;\n\ninterface WebWorkerMessage {\n _sentryMessage: boolean;\n _sentryDebugIds?: Record<string, string>;\n _sentryModuleMetadata?: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n _sentryWorkerError?: SerializedWorkerError;\n _sentryWasmImages?: Array<DebugImage>;\n}\n\ntype WorkerErrorKind = 'error' | 'unhandledrejection';\n\ninterface SerializedWorkerError {\n reason: unknown;\n filename?: string;\n /** Absent on workers registered by an SDK version that only forwarded rejections. */\n kind?: WorkerErrorKind;\n /** Structured clone resets any name outside the built-in set to `Error`. */\n name?: string;\n /** The `ErrorEvent` message, matched against the copy that bubbles to `window.onerror`. */\n message?: string;\n /** Script the error was thrown in, which can differ from the worker script. */\n url?: string;\n lineno?: number;\n colno?: number;\n /** Set when `reason` is a plain `{ message, stack }` copy of an error that did not clone. */\n plainError?: boolean;\n}\n\ninterface WebWorkerIntegrationOptions {\n worker: Worker | Array<Worker>;\n}\n\ninterface WebWorkerIntegration extends Integration {\n addWorker: (worker: Worker) => void;\n}\n\n/**\n * Use this integration to set up Sentry with web workers.\n *\n * IMPORTANT: This integration must be added **before** you start listening to\n * any messages from the worker. Otherwise, your message handlers will receive\n * messages from the Sentry SDK which you need to ignore.\n *\n * This integration only has an effect, if you call `Sentry.registerWebWorker(self)`\n * from within the worker(s) you're adding to the integration.\n *\n * Given that you want to initialize the SDK as early as possible, you most likely\n * want to add this integration **after** initializing the SDK:\n *\n * @example:\n * ```ts filename={main.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // some time earlier:\n * Sentry.init(...)\n *\n * // 1. Initialize the worker\n * const worker = new Worker(new URL('./worker.ts', import.meta.url));\n *\n * // 2. Add the integration\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker });\n * Sentry.addIntegration(webWorkerIntegration);\n *\n * // 3. Register message listeners on the worker\n * worker.addEventListener('message', event => {\n * // ...\n * });\n * ```\n *\n * If you initialize multiple workers at the same time, you can also pass an array of workers\n * to the integration:\n *\n * ```ts filename={main.js}\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker: [worker1, worker2] });\n * Sentry.addIntegration(webWorkerIntegration);\n * ```\n *\n * If you have any additional workers that you initialize at a later point,\n * you can add them to the integration as follows:\n *\n * ```ts filename={main.js}\n * const webWorkerIntegration = Sentry.webWorkerIntegration({ worker: worker1 });\n * Sentry.addIntegration(webWorkerIntegration);\n *\n * // sometime later:\n * webWorkerIntegration.addWorker(worker2);\n * ```\n *\n * Of course, you can also directly add the integration in Sentry.init:\n * ```ts filename={main.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // 1. Initialize the worker\n * const worker = new Worker(new URL('./worker.ts', import.meta.url));\n *\n * // 2. Initialize the SDK\n * Sentry.init({\n * integrations: [Sentry.webWorkerIntegration({ worker })]\n * });\n *\n * // 3. Register message listeners on the worker\n * worker.addEventListener('message', event => {\n * // ...\n * });\n * ```\n *\n * @param options {WebWorkerIntegrationOptions} Integration options:\n * - `worker`: The worker instance.\n */\nexport const webWorkerIntegration = defineIntegration(({ worker }: WebWorkerIntegrationOptions) => ({\n name: INTEGRATION_NAME,\n setupOnce: () => {\n (Array.isArray(worker) ? worker : [worker]).forEach(w => listenForSentryMessages(w));\n },\n addWorker: (worker: Worker) => listenForSentryMessages(worker),\n})) as IntegrationFn<WebWorkerIntegration>;\n\nfunction listenForSentryMessages(worker: Worker): void {\n // Forwarded errors whose message-only copy has yet to bubble to the page.\n const forwardedErrors: Array<Pick<SerializedWorkerError, 'message' | 'url' | 'lineno' | 'colno'>> = [];\n\n // The bubbled copy fires `error` on the worker object and then `window.onerror` in the same task, after the\n // forward arrived. Skipping only copies of errors we actually received means a missing forward can at worst\n // cause a duplicate, never a lost error.\n worker.addEventListener('error', ({ message, filename, lineno, colno }) => {\n const index = forwardedErrors.findIndex(\n e => e.message === message && e.url === filename && e.lineno === lineno && e.colno === colno,\n );\n if (index !== -1) {\n // Earlier entries were cancelled inside the worker and will never bubble.\n forwardedErrors.splice(0, index + 1);\n ignoreNextOnErrorMatching({ msg: message, url: filename, line: lineno, column: colno });\n }\n });\n\n worker.addEventListener('message', event => {\n if (isSentryMessage(event.data)) {\n event.stopImmediatePropagation(); // other listeners should not receive this message\n\n // Handle debug IDs\n if (event.data._sentryDebugIds) {\n DEBUG_BUILD && debug.log('Sentry debugId web worker message received', event.data);\n WINDOW._sentryDebugIds = {\n ...event.data._sentryDebugIds,\n // debugIds of the main thread have precedence over the worker's in case of a collision.\n ...WINDOW._sentryDebugIds,\n };\n }\n\n // Handle module metadata\n if (event.data._sentryModuleMetadata) {\n DEBUG_BUILD && debug.log('Sentry module metadata web worker message received', event.data);\n // Merge worker's raw metadata into the global object\n // It will be parsed lazily when needed by getMetadataForUrl\n WINDOW._sentryModuleMetadata = {\n ...event.data._sentryModuleMetadata,\n // Module metadata of the main thread have precedence over the worker's in case of a collision.\n ...WINDOW._sentryModuleMetadata,\n };\n }\n\n // Handle WASM images from worker\n if (event.data._sentryWasmImages) {\n DEBUG_BUILD && debug.log('Sentry WASM images web worker message received', event.data);\n const existingImages =\n (WINDOW as typeof WINDOW & { _sentryWasmImages?: Array<DebugImage> })._sentryWasmImages || [];\n const newImages = event.data._sentryWasmImages.filter(\n (newImg: unknown) =>\n isPlainObject(newImg) &&\n typeof newImg.code_file === 'string' &&\n !existingImages.some(existing => existing.code_file === newImg.code_file),\n );\n (WINDOW as typeof WINDOW & { _sentryWasmImages?: Array<DebugImage> })._sentryWasmImages = [\n ...existingImages,\n ...newImages,\n ];\n }\n\n // Handle errors and unhandled rejections forwarded from worker\n if (event.data._sentryWorkerError) {\n DEBUG_BUILD && debug.log('Sentry worker error message received', event.data._sentryWorkerError);\n const { kind, message, url, lineno, colno } = event.data._sentryWorkerError;\n if (kind === 'error') {\n // Bounded because a worker that cancels its own errors never bubbles them.\n if (forwardedErrors.push({ message, url, lineno, colno }) > MAX_FORWARDED_ERRORS) {\n forwardedErrors.shift();\n }\n }\n handleForwardedWorkerError(event.data._sentryWorkerError);\n }\n }\n });\n}\n\nfunction handleForwardedWorkerError(workerError: SerializedWorkerError): void {\n const { reason, kind, name, filename, url, lineno, colno, plainError } = workerError;\n // Older workers only ever forwarded rejections and send no `kind`.\n const isUnhandledRejection = kind !== 'error';\n\n const error = plainError && isPlainObject(reason) ? errorFromPlain(reason) : reason;\n\n if (name && isError(error) && error.name !== name) {\n addNonEnumerableProperty(error, 'name', name);\n }\n\n const client = getClient();\n if (!client) {\n return;\n }\n\n const { stackParser, attachStacktrace } = client.getOptions();\n\n // Follow same pattern as globalHandlers for each source.\n // A thrown primitive is not a rejection, so the rejection-specific wording must not apply to it.\n const event =\n isUnhandledRejection && isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, isUnhandledRejection);\n\n if (!isUnhandledRejection) {\n // An ErrorEvent reports an unknown script as an empty string.\n _enhanceEventWithInitialFrame(event, url || filename, lineno, colno);\n }\n\n event.level = 'error';\n\n // Add worker-specific context\n if (filename) {\n event.contexts = {\n ...event.contexts,\n worker: {\n filename,\n },\n };\n }\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: isUnhandledRejection ? 'auto.browser.web_worker.onunhandledrejection' : 'auto.browser.web_worker.onerror',\n },\n });\n\n DEBUG_BUILD && debug.log(`Captured worker ${isUnhandledRejection ? 'unhandled rejection' : 'error'}`, error);\n}\n\n/**\n * Minimal interface for DedicatedWorkerGlobalScope, only requiring the postMessage method.\n * (which is the only thing we need from the worker's global object)\n *\n * @see https://developer.mozilla.org/en-US/docs/Web/API/DedicatedWorkerGlobalScope\n *\n * We can't use the actual type because it breaks everyone who doesn't have {\"lib\": [\"WebWorker\"]}\n * but uses {\"skipLibCheck\": true} in their tsconfig.json.\n */\ninterface MinimalDedicatedWorkerGlobalScope {\n postMessage: (message: unknown) => void;\n addEventListener: (type: string, listener: (event: unknown) => void) => void;\n location?: { href?: string };\n}\n\ninterface RegisterWebWorkerOptions {\n self: MinimalDedicatedWorkerGlobalScope & {\n _sentryDebugIds?: Record<string, string>;\n _sentryModuleMetadata?: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any\n };\n}\n\n/**\n * Use this function to register the worker with the Sentry SDK.\n *\n * This function will:\n * - Send debug IDs to the parent thread\n * - Send module metadata to the parent thread (for thirdPartyErrorFilterIntegration)\n * - Set up handlers for uncaught errors and unhandled rejections in the worker\n * - Forward both to the parent thread for capture\n *\n * Note: uncaught errors do bubble to the parent, but the propagated `ErrorEvent` carries\n * no `error` object, so globalHandlers can only build an event from the message string.\n * Forwarding them here preserves the real stack, which matters most for wasm frames.\n *\n * @example\n * ```ts filename={worker.js}\n * import * as Sentry from '@sentry/<your-sdk>';\n *\n * // Do this as early as possible in your worker.\n * Sentry.registerWebWorker({ self });\n *\n * // continue setting up your worker\n * self.postMessage(...)\n * ```\n * @param options {RegisterWebWorkerOptions} Integration options:\n * - `self`: The worker instance you're calling this function from (self).\n */\nexport function registerWebWorker({ self }: RegisterWebWorkerOptions): void {\n // Mirrors globalHandlersIntegration. The worker has no client of its own, so without this\n // V8's default of 10 truncates stacks before this code forwards them.\n Error.stackTraceLimit = 50;\n\n // Send debug IDs and raw module metadata to parent thread\n // The metadata will be parsed lazily on the main thread when needed\n self.postMessage({\n _sentryMessage: true,\n _sentryDebugIds: self._sentryDebugIds ?? undefined,\n _sentryModuleMetadata: self._sentryModuleMetadata ?? undefined,\n });\n\n const forward = (serializedError: Omit<SerializedWorkerError, 'filename' | 'name'>): void => {\n const { reason } = serializedError;\n\n DEBUG_BUILD && debug.log(`[Sentry Worker] Forwarding ${serializedError.kind} to parent`, serializedError);\n\n postSerializedWorkerError(self, {\n ...serializedError,\n filename: self.location?.href,\n name: isError(reason) ? extractType(reason) : undefined,\n });\n };\n\n // Uncaught errors bubble to the parent, but the propagated ErrorEvent\n // carries no error object. Forwarding the object keeps the real stack.\n self.addEventListener('error', (event: unknown) => {\n const { error, message, filename, lineno, colno } = event as {\n error?: unknown;\n message?: string;\n filename?: string;\n lineno?: number;\n colno?: number;\n };\n\n forward({ kind: 'error', reason: error ?? message, message, url: filename, lineno, colno });\n });\n\n // Unhandled rejections do not bubble to the parent thread at all.\n self.addEventListener('unhandledrejection', (event: unknown) => {\n forward({ kind: 'unhandledrejection', reason: _getUnhandledRejectionError(event) });\n });\n\n DEBUG_BUILD && debug.log('[Sentry Worker] Registered worker with error and unhandled rejection handling');\n}\n\n/**\n * `postMessage` structured-clones the reason. A `DataCloneError` must never\n * escape the worker's own error handler, so the forward is retried with\n * plain data that clones in every browser, including ones that cannot clone\n * `Error` at all.\n */\nfunction postSerializedWorkerError(\n self: MinimalDedicatedWorkerGlobalScope,\n serializedError: SerializedWorkerError,\n): void {\n try {\n self.postMessage({\n _sentryMessage: true,\n _sentryWorkerError: serializedError,\n });\n return;\n } catch {\n // Not cloneable, fall through and send plain data instead.\n }\n\n const { reason } = serializedError;\n const plainError = isError(reason);\n const plainReason = plainError ? { message: extractMessage(reason), stack: reason.stack } : normalize(reason);\n\n try {\n self.postMessage({\n _sentryMessage: true,\n _sentryWorkerError: { ...serializedError, reason: plainReason, plainError },\n });\n } catch {\n // Dropping the forward is better than throwing out of the worker's error handler.\n }\n}\n\nfunction errorFromPlain(plain: Record<string, unknown>): Error {\n const error = new Error(String(plain.message));\n error.stack = typeof plain.stack === 'string' ? plain.stack : undefined;\n return error;\n}\n\nfunction isSentryMessage(eventData: unknown): eventData is WebWorkerMessage {\n if (!isPlainObject(eventData) || eventData._sentryMessage !== true) {\n return false;\n }\n\n // Must have at least one of: debug IDs, module metadata, worker error, or WASM images\n const hasDebugIds = '_sentryDebugIds' in eventData;\n const hasModuleMetadata = '_sentryModuleMetadata' in eventData;\n const hasWorkerError = '_sentryWorkerError' in eventData;\n const hasWasmImages = '_sentryWasmImages' in eventData;\n\n if (!hasDebugIds && !hasModuleMetadata && !hasWorkerError && !hasWasmImages) {\n return false;\n }\n\n // Validate debug IDs if present\n if (hasDebugIds && !(isPlainObject(eventData._sentryDebugIds) || eventData._sentryDebugIds === undefined)) {\n return false;\n }\n\n // Validate module metadata if present\n if (\n hasModuleMetadata &&\n !(isPlainObject(eventData._sentryModuleMetadata) || eventData._sentryModuleMetadata === undefined)\n ) {\n return false;\n }\n\n // Validate worker error if present\n if (hasWorkerError && !isPlainObject(eventData._sentryWorkerError)) {\n return false;\n }\n\n // Validate WASM images if present\n if (\n hasWasmImages &&\n (!Array.isArray(eventData._sentryWasmImages) ||\n !eventData._sentryWasmImages.every(\n (img: unknown) => isPlainObject(img) && typeof (img as { code_file?: unknown }).code_file === 'string',\n ))\n ) {\n return false;\n }\n\n return true;\n}\n"],"names":["defineIntegration","worker","ignoreNextOnErrorMatching","DEBUG_BUILD","debug","WINDOW","isPlainObject","isError","addNonEnumerableProperty","getClient","isPrimitive","_eventFromRejectionWithPrimitive","eventFromUnknownInput","_enhanceEventWithInitialFrame","captureEvent","extractType","_getUnhandledRejectionError","extractMessage","normalize"],"mappings":";;;;;;;;AAqBO,MAAM,gBAAA,GAAmB;AAEhC,MAAM,oBAAA,GAAuB,EAAA;AA8GtB,MAAM,oBAAA,GAAuBA,sBAAA,CAAkB,CAAC,EAAE,QAAO,MAAoC;AAAA,EAClG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kB,CAACA,kBAAA,CAAc,SAAA,CAAU,kBAAkB,CAAA,EAAG;AAClE,IAAA,OAAO,KAAA;AAAA,EACT;AAGA,EAAA,IACE,aAAA,KACC,CAAC,KAAA,CAAM,OAAA,CAAQ,UAAU,iBAAiB,CAAA,IACzC,CAAC,SAAA,CAAU,iBAAA,CAAkB,KAAA;AAAA,IAC3B,CAAC,GAAA,KAAiBA,kBAAA,CAAc,GAAG,CAAA,IAAK,OAAQ,IAAgC,SAAA,KAAc;AAAA,GAChG,CAAA,EACF;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,OAAO,IAAA;AACT;;;;;;"}
@@ -3,8 +3,29 @@ import { getLocationHref } from '@sentry/browser-utils';
3
3
 
4
4
  const WINDOW = GLOBAL_OBJ;
5
5
  let ignoreOnError = 0;
6
- function shouldIgnoreOnError() {
7
- return ignoreOnError > 0;
6
+ const ignoredErrorReports = [];
7
+ function shouldIgnoreOnError(data) {
8
+ if (ignoreOnError > 0) {
9
+ return true;
10
+ }
11
+ const index = data ? ignoredErrorReports.findIndex((report) => isSameErrorReport(report, data)) : -1;
12
+ if (index === -1) {
13
+ return false;
14
+ }
15
+ ignoredErrorReports.splice(index, 1);
16
+ return true;
17
+ }
18
+ function ignoreNextOnErrorMatching(report) {
19
+ ignoredErrorReports.push(report);
20
+ setTimeout(() => {
21
+ const index = ignoredErrorReports.indexOf(report);
22
+ if (index !== -1) {
23
+ ignoredErrorReports.splice(index, 1);
24
+ }
25
+ });
26
+ }
27
+ function isSameErrorReport(a, b) {
28
+ return a.msg === b.msg && a.url === b.url && a.line === b.line && a.column === b.column;
8
29
  }
9
30
  function ignoreNextOnError() {
10
31
  ignoreOnError++;
@@ -99,5 +120,5 @@ function getHttpRequestData() {
99
120
  return request;
100
121
  }
101
122
 
102
- export { WINDOW, getHttpRequestData, ignoreNextOnError, shouldIgnoreOnError, wrap };
123
+ export { WINDOW, getHttpRequestData, ignoreNextOnError, ignoreNextOnErrorMatching, shouldIgnoreOnError, wrap };
103
124
  //# sourceMappingURL=helpers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"helpers.js","sources":["../../../../src/helpers.ts"],"sourcesContent":["import type { Mechanism, WrappedFunction } from '@sentry/core';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n captureException,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n withScope,\n} from '@sentry/core';\nimport { getLocationHref } from '@sentry/browser-utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(): boolean {\n return ignoreOnError > 0;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype WrappableFunction = Function;\n\nexport function wrap<T extends WrappableFunction>(\n fn: T,\n options?: {\n mechanism?: Mechanism;\n },\n): WrappedFunction<T>;\nexport function wrap<NonFunction>(\n fn: NonFunction,\n options?: {\n mechanism?: Mechanism;\n },\n): NonFunction;\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap<T extends WrappableFunction, NonFunction>(\n fn: T | NonFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n): NonFunction | WrappedFunction<T> {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n function isFunction(fn: T | NonFunction): fn is T {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\n return fn;\n }\n\n try {\n // If we're dealing with a function that was previously wrapped, return the original wrapper.\n // Check via hasOwnProperty so a `__sentry_wrapped__` inherited from a wrapped `Function.prototype`\n // is not mistaken for a real wrapper.\n const hasOwnWrapper = Object.prototype.hasOwnProperty.call(fn, '__sentry_wrapped__');\n if (hasOwnWrapper) {\n const wrapper = (fn as WrappedFunction<T>).__sentry_wrapped__;\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function (this: unknown, ...args: unknown[]): unknown {\n // Track depth on GLOBAL_OBJ so the thirdPartyErrorFilterIntegration (in @sentry/core) can detect\n // that processEvent is running inside a sentryWrapped call, even with minified/bundled code.\n GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) + 1;\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n // no need to add a mechanism here, we already add it via an event processor above\n captureException(ex);\n });\n\n throw ex;\n } finally {\n GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) - 1;\n }\n } as unknown as WrappedFunction<T>;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property as keyof T] = fn[property as keyof T];\n }\n }\n } catch {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name')!;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n } catch {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\n/**\n * Get HTTP request data from the current page.\n */\nexport function getHttpRequestData(): { url: string; headers: Record<string, string> } {\n // grab as much info as exists and add it to the event\n const url = getLocationHref();\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = {\n url,\n headers,\n };\n\n return request;\n}\n"],"names":["fn"],"mappings":";;;AAaO,MAAM,MAAA,GAAS;AAEtB,IAAI,aAAA,GAAwB,CAAA;AAKrB,SAAS,mBAAA,GAA+B;AAC7C,EAAA,OAAO,aAAA,GAAgB,CAAA;AACzB;AAKO,SAAS,iBAAA,GAA0B;AAExC,EAAA,aAAA,EAAA;AACA,EAAA,UAAA,CAAW,MAAM;AACf,IAAA,aAAA,EAAA;AAAA,EACF,CAAC,CAAA;AACH;AA0BO,SAAS,IAAA,CACd,EAAA,EACA,OAAA,GA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,kBAAA,GAAuE;AAErF,EAAA,MAAM,MAAM,eAAA,EAAgB;AAC5B,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAA,CAAO,YAAY,EAAC;AACzC,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAA,CAAO,aAAa,EAAC;AAE3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,GAAI,QAAA,IAAY,EAAE,OAAA,EAAS,QAAA,EAAS;AAAA,IACpC,GAAI,SAAA,IAAa,EAAE,YAAA,EAAc,SAAA;AAAU,GAC7C;AACA,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,GAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
1
+ {"version":3,"file":"helpers.js","sources":["../../../../src/helpers.ts"],"sourcesContent":["import type { HandlerDataError, Mechanism, WrappedFunction } from '@sentry/core';\nimport {\n addExceptionMechanism,\n addExceptionTypeValue,\n addNonEnumerableProperty,\n captureException,\n getOriginalFunction,\n GLOBAL_OBJ,\n markFunctionWrapped,\n withScope,\n} from '@sentry/core';\nimport { getLocationHref } from '@sentry/browser-utils';\n\nexport const WINDOW = GLOBAL_OBJ as typeof GLOBAL_OBJ & Window;\n\nlet ignoreOnError: number = 0;\n\ntype ErrorReport = Pick<HandlerDataError, 'msg' | 'url' | 'line' | 'column'>;\n\nconst ignoredErrorReports: ErrorReport[] = [];\n\n/**\n * @hidden\n */\nexport function shouldIgnoreOnError(data?: HandlerDataError): boolean {\n if (ignoreOnError > 0) {\n return true;\n }\n\n const index = data ? ignoredErrorReports.findIndex(report => isSameErrorReport(report, data)) : -1;\n if (index === -1) {\n return false;\n }\n\n ignoredErrorReports.splice(index, 1);\n return true;\n}\n\n/**\n * Skips the next `onerror` report that matches `report`, once. A report that\n * never arrives is forgotten after the current task.\n *\n * @hidden\n */\nexport function ignoreNextOnErrorMatching(report: ErrorReport): void {\n ignoredErrorReports.push(report);\n setTimeout(() => {\n const index = ignoredErrorReports.indexOf(report);\n if (index !== -1) {\n ignoredErrorReports.splice(index, 1);\n }\n });\n}\n\nfunction isSameErrorReport(a: ErrorReport, b: ErrorReport): boolean {\n return a.msg === b.msg && a.url === b.url && a.line === b.line && a.column === b.column;\n}\n\n/**\n * @hidden\n */\nexport function ignoreNextOnError(): void {\n // onerror should trigger before setTimeout\n ignoreOnError++;\n setTimeout(() => {\n ignoreOnError--;\n });\n}\n\n// eslint-disable-next-line @typescript-eslint/ban-types\ntype WrappableFunction = Function;\n\nexport function wrap<T extends WrappableFunction>(\n fn: T,\n options?: {\n mechanism?: Mechanism;\n },\n): WrappedFunction<T>;\nexport function wrap<NonFunction>(\n fn: NonFunction,\n options?: {\n mechanism?: Mechanism;\n },\n): NonFunction;\n/**\n * Instruments the given function and sends an event to Sentry every time the\n * function throws an exception.\n *\n * @param fn A function to wrap. It is generally safe to pass an unbound function, because the returned wrapper always\n * has a correct `this` context.\n * @returns The wrapped function.\n * @hidden\n */\nexport function wrap<T extends WrappableFunction, NonFunction>(\n fn: T | NonFunction,\n options: {\n mechanism?: Mechanism;\n } = {},\n): NonFunction | WrappedFunction<T> {\n // for future readers what this does is wrap a function and then create\n // a bi-directional wrapping between them.\n //\n // example: wrapped = wrap(original);\n // original.__sentry_wrapped__ -> wrapped\n // wrapped.__sentry_original__ -> original\n\n function isFunction(fn: T | NonFunction): fn is T {\n return typeof fn === 'function';\n }\n\n if (!isFunction(fn)) {\n return fn;\n }\n\n try {\n // If we're dealing with a function that was previously wrapped, return the original wrapper.\n // Check via hasOwnProperty so a `__sentry_wrapped__` inherited from a wrapped `Function.prototype`\n // is not mistaken for a real wrapper.\n const hasOwnWrapper = Object.prototype.hasOwnProperty.call(fn, '__sentry_wrapped__');\n if (hasOwnWrapper) {\n const wrapper = (fn as WrappedFunction<T>).__sentry_wrapped__;\n if (typeof wrapper === 'function') {\n return wrapper;\n } else {\n // If we find that the `__sentry_wrapped__` function is not a function at the time of accessing it, it means\n // that something messed with it. In that case we want to return the originally passed function.\n return fn;\n }\n }\n\n // We don't wanna wrap it twice\n if (getOriginalFunction(fn)) {\n return fn;\n }\n } catch {\n // Just accessing custom props in some Selenium environments\n // can cause a \"Permission denied\" exception (see raven-js#495).\n // Bail on wrapping and return the function as-is (defers to window.onerror).\n return fn;\n }\n\n // Wrap the function itself\n // It is important that `sentryWrapped` is not an arrow function to preserve the context of `this`\n const sentryWrapped = function (this: unknown, ...args: unknown[]): unknown {\n // Track depth on GLOBAL_OBJ so the thirdPartyErrorFilterIntegration (in @sentry/core) can detect\n // that processEvent is running inside a sentryWrapped call, even with minified/bundled code.\n GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) + 1;\n try {\n // Also wrap arguments that are themselves functions\n const wrappedArguments = args.map(arg => wrap(arg, options));\n\n // Attempt to invoke user-land function\n // NOTE: If you are a Sentry user, and you are seeing this stack frame, it\n // means the sentry.javascript SDK caught an error invoking your application code. This\n // is expected behavior and NOT indicative of a bug with sentry.javascript.\n return fn.apply(this, wrappedArguments);\n } catch (ex) {\n ignoreNextOnError();\n\n withScope(scope => {\n scope.addEventProcessor(event => {\n if (options.mechanism) {\n addExceptionTypeValue(event, undefined, undefined);\n addExceptionMechanism(event, options.mechanism);\n }\n\n event.extra = {\n ...event.extra,\n arguments: args,\n };\n\n return event;\n });\n\n // no need to add a mechanism here, we already add it via an event processor above\n captureException(ex);\n });\n\n throw ex;\n } finally {\n GLOBAL_OBJ._sentryWrappedDepth = (GLOBAL_OBJ._sentryWrappedDepth || 0) - 1;\n }\n } as unknown as WrappedFunction<T>;\n\n // Wrap the wrapped function in a proxy, to ensure any other properties of the original function remain available\n try {\n for (const property in fn) {\n if (Object.prototype.hasOwnProperty.call(fn, property)) {\n sentryWrapped[property as keyof T] = fn[property as keyof T];\n }\n }\n } catch {\n // Accessing some objects may throw\n // ref: https://github.com/getsentry/sentry-javascript/issues/1168\n }\n\n // Signal that this function has been wrapped/filled already\n // for both debugging and to prevent it to being wrapped/filled twice\n markFunctionWrapped(sentryWrapped, fn);\n\n addNonEnumerableProperty(fn, '__sentry_wrapped__', sentryWrapped);\n\n // Restore original function name (not all browsers allow that)\n try {\n // eslint-disable-next-line @typescript-eslint/no-non-null-assertion\n const descriptor = Object.getOwnPropertyDescriptor(sentryWrapped, 'name')!;\n if (descriptor.configurable) {\n Object.defineProperty(sentryWrapped, 'name', {\n get(): string {\n return fn.name;\n },\n });\n }\n } catch {\n // This may throw if e.g. the descriptor does not exist, or a browser does not allow redefining `name`.\n // to save some bytes we simply try-catch this\n }\n\n return sentryWrapped;\n}\n\n/**\n * Get HTTP request data from the current page.\n */\nexport function getHttpRequestData(): { url: string; headers: Record<string, string> } {\n // grab as much info as exists and add it to the event\n const url = getLocationHref();\n const { referrer } = WINDOW.document || {};\n const { userAgent } = WINDOW.navigator || {};\n\n const headers = {\n ...(referrer && { Referer: referrer }),\n ...(userAgent && { 'User-Agent': userAgent }),\n };\n const request = {\n url,\n headers,\n };\n\n return request;\n}\n"],"names":["fn"],"mappings":";;;AAaO,MAAM,MAAA,GAAS;AAEtB,IAAI,aAAA,GAAwB,CAAA;AAI5B,MAAM,sBAAqC,EAAC;AAKrC,SAAS,oBAAoB,IAAA,EAAkC;AACpE,EAAA,IAAI,gBAAgB,CAAA,EAAG;AACrB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,KAAA,GAAQ,OAAO,mBAAA,CAAoB,SAAA,CAAU,YAAU,iBAAA,CAAkB,MAAA,EAAQ,IAAI,CAAC,CAAA,GAAI,EAAA;AAChG,EAAA,IAAI,UAAU,EAAA,EAAI;AAChB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,mBAAA,CAAoB,MAAA,CAAO,OAAO,CAAC,CAAA;AACnC,EAAA,OAAO,IAAA;AACT;AAQO,SAAS,0BAA0B,MAAA,EAA2B;AACnE,EAAA,mBAAA,CAAoB,KAAK,MAAM,CAAA;AAC/B,EAAA,UAAA,CAAW,MAAM;AACf,IAAA,M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ACtD,QAAA,aAAA,CAAc,QAAmB,CAAA,GAAI,EAAA,CAAG,QAAmB,CAAA;AAAA,MAC7D;AAAA,IACF;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAGR;AAIA,EAAA,mBAAA,CAAoB,eAAe,EAAE,CAAA;AAErC,EAAA,wBAAA,CAAyB,EAAA,EAAI,sBAAsB,aAAa,CAAA;AAGhE,EAAA,IAAI;AAEF,IAAA,MAAM,UAAA,GAAa,MAAA,CAAO,wBAAA,CAAyB,aAAA,EAAe,MAAM,CAAA;AACxE,IAAA,IAAI,WAAW,YAAA,EAAc;AAC3B,MAAA,MAAA,CAAO,cAAA,CAAe,eAAe,MAAA,EAAQ;AAAA,QAC3C,GAAA,GAAc;AACZ,UAAA,OAAO,EAAA,CAAG,IAAA;AAAA,QACZ;AAAA,OACD,CAAA;AAAA,IACH;AAAA,EACF,CAAA,CAAA,MAAQ;AAAA,EAGR;AAEA,EAAA,OAAO,aAAA;AACT;AAKO,SAAS,kBAAA,GAAuE;AAErF,EAAA,MAAM,MAAM,eAAA,EAAgB;AAC5B,EAAA,MAAM,EAAE,QAAA,EAAS,GAAI,MAAA,CAAO,YAAY,EAAC;AACzC,EAAA,MAAM,EAAE,SAAA,EAAU,GAAI,MAAA,CAAO,aAAa,EAAC;AAE3C,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,GAAI,QAAA,IAAY,EAAE,OAAA,EAAS,QAAA,EAAS;AAAA,IACpC,GAAI,SAAA,IAAa,EAAE,YAAA,EAAc,SAAA;AAAU,GAC7C;AACA,EAAA,MAAM,OAAA,GAAU;AAAA,IACd,GAAA;AAAA,IACA;AAAA,GACF;AAEA,EAAA,OAAO,OAAA;AACT;;;;"}
@@ -32,7 +32,7 @@ const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);
32
32
  function _installGlobalOnErrorHandler(client) {
33
33
  addGlobalErrorInstrumentationHandler((data) => {
34
34
  const { stackParser, attachStacktrace } = getOptions();
35
- if (getClient() !== client || shouldIgnoreOnError()) {
35
+ if (getClient() !== client || shouldIgnoreOnError(data)) {
36
36
  return;
37
37
  }
38
38
  const { msg, url, line, column, error } = data;
@@ -136,5 +136,5 @@ function getFilenameFromUrl(url) {
136
136
  return url;
137
137
  }
138
138
 
139
- export { _eventFromRejectionWithPrimitive, _getUnhandledRejectionError, globalHandlersIntegration };
139
+ export { _enhanceEventWithInitialFrame, _eventFromRejectionWithPrimitive, _getUnhandledRejectionError, globalHandlersIntegration };
140
140
  //# sourceMappingURL=globalhandlers.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"globalhandlers.js","sources":["../../../../../src/integrations/globalhandlers.ts"],"sourcesContent":["import type { Client, Event, IntegrationFn, Primitive, StackParser } from '@sentry/core';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n isPrimitive,\n isString,\n stripDataUrlContent,\n UNKNOWN_FUNCTION,\n} from '@sentry/core';\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getLocationHref } from '@sentry/browser-utils';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record<GlobalHandlersIntegrationsOptionKeys, boolean>;\n\nconst INTEGRATION_NAME = 'GlobalHandlers' as const;\n\nconst _globalHandlersIntegration = ((options: Partial<GlobalHandlersIntegrations> = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event = _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onunhandledrejection',\n },\n });\n });\n}\n\n/**\n *\n */\nexport function _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n type ErrorWithReason = { reason: unknown };\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in (error as ErrorWithReason)) {\n return (error as ErrorWithReason).reason;\n }\n\n type CustomEventWithDetail = { detail: { reason: unknown } };\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error as CustomEventWithDetail) && 'reason' in (error as CustomEventWithDetail).detail) {\n return (error as CustomEventWithDetail).detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nexport function _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\nfunction _enhanceEventWithInitialFrame(\n event: Event,\n url: string | undefined,\n lineno: number | undefined,\n colno: number | undefined,\n): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n lineno,\n filename: getFilenameFromUrl(url) ?? getLocationHref(),\n function: UNKNOWN_FUNCTION,\n in_app: true,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && debug.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient<BrowserClient>();\n const options = client?.getOptions() || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nfunction getFilenameFromUrl(url: string | undefined): string | undefined {\n if (!isString(url) || url.length === 0) {\n return undefined;\n }\n\n // Strip data URL content to avoid long base64 strings in stack frames\n // (e.g. when initializing a Worker with a base64 encoded script)\n // Don't include data prefix for filenames as it's not useful for stack traces\n // Wrap with < > to indicate it's a placeholder\n if (url.startsWith('data:')) {\n return `<${stripDataUrlContent(url, false)}>`;\n }\n\n return url;\n}\n"],"names":[],"mappings":";;;;;;AAuBA,MAAM,gBAAA,GAAmB,gBAAA;AAEzB,MAAM,0BAAA,IAA8B,CAAC,OAAA,GAA+C,EAAC,KAAM;AACzF,EAAA,MAAM,QAAA,GAAW;AAAA,IACf,OAAA,EAAS,IAAA;AAAA,IACT,oBAAA,EAAsB,IAAA;AAAA,IACtB,GAAG;AAAA,GACL;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,KAAA,CAAM,eAAA,GAAkB,EAAA;AAAA,IAC1B,CAAA;AAAA,IACA,MAAM,MAAA,EAAQ;AACZ,MAAA,IAAI,SAAS,OAAA,EAAS;AACpB,QAAA,4BAAA,CAA6B,MAAM,CAAA;AACnC,QAAA,gBAAA,CAAiB,SAAS,CAAA;AAAA,MAC5B;AACA,MAAA,IAAI,SAAS,oBAAA,EAAsB;AACjC,QAAA,yCAAA,CAA0C,MAAM,CAAA;AAChD,QAAA,gBAAA,CAAiB,sBAAsB,CAAA;AAAA,MACzC;AAAA,IACF;AAAA,GACF;AACF,CAAA,CAAA;AAEO,MAAM,yBAAA,GAA4B,kBAAkB,0BAA0B;AAErF,SAAS,6BAA6B,MAAA,EAAsB;AAC1D,EAAA,oCAAA,CAAqC,CAAA,IAAA,KAAQ;AAC3C,IAAA,MAAM,EAAE,WAAA,EAAa,gBAAA,EAAiB,GAAI,UAAA,EAAW;AAErD,IAAA,IAAI,SAAA,EAAU,KAAM,MAAA,IAAU,mBAAA,EAAoB,EAAG;AACnD,MAAA;AAAA,IACF;AAEA,IAAA,MAAM,EAAE,GAAA,EAAK,GAAA,EAAK,IAAA,EAAM,MAAA,EAAQ,OAAM,GAAI,IAAA;AAE1C,IAAA,MAAM,KAAA,GAAQ,6BAAA;AAAA,MACZ,sBAAsB,WAAA,EAAa,KAAA,IAAS,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EAAA,OAAO,KAAA;AACT;AAEA,SAAS,iBAAiB,IAAA,EAAoB;AAC5C,EAAA,WAAA,IAAe,KAAA,CAAM,GAAA,CAAI,CAAA,yBAAA,EAA4B,IAAI,CAAA,CAAE,CAAA;AAC7D;AAEA,SAAS,UAAA,GAAuE;AAC9E,EAAA,MAAM,SAAS,SAAA,EAAyB;AACxC,EAAA,MAAM,OAAA,GAAU,MAAA,EAAQ,UAAA,EAAW,IAAK;AAAA,IACtC,WAAA,EAAa,MAAM,EAAC;AAAA,IACpB,gBAAA,EAAkB;AAAA,GACpB;AACA,EAAA,OAAO,OAAA;AACT;AAEA,SAAS,mBAAmB,GAAA,EAA6C;AACvE,EAAA,IAAI,CAAC,QAAA,CAAS,GAAG,CAAA,IAAK,GAAA,CAAI,WAAW,CAAA,EAAG;AACtC,IAAA,OAAO,MAAA;AAAA,EACT;AAMA,EAAA,IAAI,GAAA,CAAI,UAAA,CAAW,OAAO,CAAA,EAAG;AAC3B,IAAA,OAAO,CAAA,CAAA,EAAI,mBAAA,CAAoB,GAAA,EAAK,KAAK,CAAC,CAAA,CAAA,CAAA;AAAA,EAC5C;AAEA,EAAA,OAAO,GAAA;AACT;;;;"}
1
+ {"version":3,"file":"globalhandlers.js","sources":["../../../../../src/integrations/globalhandlers.ts"],"sourcesContent":["import type { Client, Event, IntegrationFn, Primitive, StackParser } from '@sentry/core';\nimport {\n addGlobalErrorInstrumentationHandler,\n addGlobalUnhandledRejectionInstrumentationHandler,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n isPrimitive,\n isString,\n stripDataUrlContent,\n UNKNOWN_FUNCTION,\n} from '@sentry/core';\nimport type { BrowserClient } from '../client';\nimport { DEBUG_BUILD } from '../debug-build';\nimport { getLocationHref } from '@sentry/browser-utils';\nimport { eventFromUnknownInput } from '../eventbuilder';\nimport { shouldIgnoreOnError } from '../helpers';\n\ntype GlobalHandlersIntegrationsOptionKeys = 'onerror' | 'onunhandledrejection';\n\ntype GlobalHandlersIntegrations = Record<GlobalHandlersIntegrationsOptionKeys, boolean>;\n\nconst INTEGRATION_NAME = 'GlobalHandlers' as const;\n\nconst _globalHandlersIntegration = ((options: Partial<GlobalHandlersIntegrations> = {}) => {\n const _options = {\n onerror: true,\n onunhandledrejection: true,\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setupOnce() {\n Error.stackTraceLimit = 50;\n },\n setup(client) {\n if (_options.onerror) {\n _installGlobalOnErrorHandler(client);\n globalHandlerLog('onerror');\n }\n if (_options.onunhandledrejection) {\n _installGlobalOnUnhandledRejectionHandler(client);\n globalHandlerLog('onunhandledrejection');\n }\n },\n };\n}) satisfies IntegrationFn;\n\nexport const globalHandlersIntegration = defineIntegration(_globalHandlersIntegration);\n\nfunction _installGlobalOnErrorHandler(client: Client): void {\n addGlobalErrorInstrumentationHandler(data => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError(data)) {\n return;\n }\n\n const { msg, url, line, column, error } = data;\n\n const event = _enhanceEventWithInitialFrame(\n eventFromUnknownInput(stackParser, error || msg, undefined, attachStacktrace, false),\n url,\n line,\n column,\n );\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onerror',\n },\n });\n });\n}\n\nfunction _installGlobalOnUnhandledRejectionHandler(client: Client): void {\n addGlobalUnhandledRejectionInstrumentationHandler(e => {\n const { stackParser, attachStacktrace } = getOptions();\n\n if (getClient() !== client || shouldIgnoreOnError()) {\n return;\n }\n\n const error = _getUnhandledRejectionError(e);\n\n const event = isPrimitive(error)\n ? _eventFromRejectionWithPrimitive(error)\n : eventFromUnknownInput(stackParser, error, undefined, attachStacktrace, true);\n\n event.level = 'error';\n\n captureEvent(event, {\n originalException: error,\n mechanism: {\n handled: false,\n type: 'auto.browser.global_handlers.onunhandledrejection',\n },\n });\n });\n}\n\n/**\n *\n */\nexport function _getUnhandledRejectionError(error: unknown): unknown {\n if (isPrimitive(error)) {\n return error;\n }\n\n // dig the object of the rejection out of known event types\n try {\n type ErrorWithReason = { reason: unknown };\n // PromiseRejectionEvents store the object of the rejection under 'reason'\n // see https://developer.mozilla.org/en-US/docs/Web/API/PromiseRejectionEvent\n if ('reason' in (error as ErrorWithReason)) {\n return (error as ErrorWithReason).reason;\n }\n\n type CustomEventWithDetail = { detail: { reason: unknown } };\n // something, somewhere, (likely a browser extension) effectively casts PromiseRejectionEvents\n // to CustomEvents, moving the `promise` and `reason` attributes of the PRE into\n // the CustomEvent's `detail` attribute, since they're not part of CustomEvent's spec\n // see https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent and\n // https://github.com/getsentry/sentry-javascript/issues/2380\n if ('detail' in (error as CustomEventWithDetail) && 'reason' in (error as CustomEventWithDetail).detail) {\n return (error as CustomEventWithDetail).detail.reason;\n }\n } catch {} // eslint-disable-line no-empty\n\n return error;\n}\n\n/**\n * Create an event from a promise rejection where the `reason` is a primitive.\n *\n * @param reason: The `reason` property of the promise rejection\n * @returns An Event object with an appropriate `exception` value\n */\nexport function _eventFromRejectionWithPrimitive(reason: Primitive): Event {\n return {\n exception: {\n values: [\n {\n type: 'UnhandledRejection',\n // String() is needed because the Primitive type includes symbols (which can't be automatically stringified)\n value: `Non-Error promise rejection captured with value: ${String(reason)}`,\n },\n ],\n },\n };\n}\n\n/**\n * Adds a frame built from the error location when the event has none.\n */\nexport function _enhanceEventWithInitialFrame(\n event: Event,\n url: string | undefined,\n lineno: number | undefined,\n colno: number | undefined,\n): Event {\n // event.exception\n const e = (event.exception = event.exception || {});\n // event.exception.values\n const ev = (e.values = e.values || []);\n // event.exception.values[0]\n const ev0 = (ev[0] = ev[0] || {});\n // event.exception.values[0].stacktrace\n const ev0s = (ev0.stacktrace = ev0.stacktrace || {});\n // event.exception.values[0].stacktrace.frames\n const ev0sf = (ev0s.frames = ev0s.frames || []);\n\n if (ev0sf.length === 0) {\n ev0sf.push({\n colno,\n lineno,\n filename: getFilenameFromUrl(url) ?? getLocationHref(),\n function: UNKNOWN_FUNCTION,\n in_app: true,\n });\n }\n\n return event;\n}\n\nfunction globalHandlerLog(type: string): void {\n DEBUG_BUILD && debug.log(`Global Handler attached: ${type}`);\n}\n\nfunction getOptions(): { stackParser: StackParser; attachStacktrace?: boolean } {\n const client = getClient<BrowserClient>();\n const options = client?.getOptions() || {\n stackParser: () => [],\n attachStacktrace: false,\n };\n return options;\n}\n\nfunction getFilenameFromUrl(url: string | undefined): string | undefined {\n if (!isString(url) || url.length === 0) {\n return undefined;\n }\n\n // Strip data URL content to avoid long base64 strings in stack frames\n // (e.g. when initializing a Worker with a base64 encoded script)\n // Don't include data prefix for filenames as it's not useful for stack traces\n // Wrap with < > to indicate it's a placeholder\n if (url.startsWith('data:')) {\n return `<${stripDataUrlContent(url, false)}>`;\n }\n\n return url;\n}\n"],"names":[],"mappings":";;;;;;AAuBA,MAAM,gBAAA,GAAmB,gBAAA;AAEzB,MAAM,0BAAA,IAA8B,CAAC,OAAA,GAA+C,EAAC,KAAM;AACzF,EAAA,MAAM,QAAA,GAAW;AAAA,IACf,OAAA,EAAS,IAAA;AAAA,IACT,oBAAA,EAAsB,IAAA;AAAA,IACtB,GAAG;AAAA,GACL;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,SAAA,GAAY;AACV,MAAA,KAAA,CAAM,eAAA,GAAkB,EAAA;AAAA,IAC1B,CAAA;AAAA,IACA,MAAM,MAAA,EAAQ;AACZ,MAAA,IAAI,SAAS,OAAA,EAAS;AACpB,QAAA,4BAAA,CAA6B,MAAM,CAAA;AACnC,QAAA,gBAAA,CAAiB,SAAS,CAAA;AAAA,MAC5B;AACA,MAAA,IAAI,SAAS,oBAAA,EAAsB;AACjC,QAAA,yCAAA,CAA0C,MAAM,CAAA;AAChD,QAAA,gBAAA,CAAiB,sBAAsB,CAAA;AAAA,MACzC;AAAA,IACF;AAAA,GACF;AACF,CAAA,CAAA;AAEO,MAAM,yBAAA,GAA4B,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, requestInit, erro
32
32
  if (dc.cookies !== false) {
33
33
  const reqCookieStr = request.headers.get("Cookie") || void 0;
34
34
  if (reqCookieStr) {
35
- const filtered = _INTERNAL_filterCookies(reqCookieStr, dc.cookies);
36
- requestCookies = typeof filtered === "string" ? { cookie: filtered } : filtered;
35
+ requestCookies = _INTERNAL_filterCookies(reqCookieStr, dc.cookies, "cookie");
37
36
  }
38
37
  const resCookieStr = response.headers.get("Set-Cookie") || void 0;
39
38
  if (resCookieStr) {
40
- const filtered = _INTERNAL_filterCookies(resCookieStr, dc.cookies);
41
- responseCookies = typeof filtered === "string" ? { "set-cookie": filtered } : filtered;
39
+ responseCookies = _INTERNAL_filterCookies(resCookieStr, dc.cookies, "set-cookie");
42
40
  }
43
41
  }
44
42
  const event = _createEvent({
@@ -63,8 +61,7 @@ function _xhrResponseHandler(options, xhr, method, headers, error) {
63
61
  try {
64
62
  const cookieString = xhr.getResponseHeader("Set-Cookie") || xhr.getResponseHeader("set-cookie") || void 0;
65
63
  if (cookieString) {
66
- const filtered = _INTERNAL_filterCookies(cookieString, dc.cookies);
67
- responseCookies = typeof filtered === "string" ? { "set-cookie": filtered } : filtered;
64
+ responseCookies = _INTERNAL_filterCookies(cookieString, dc.cookies, "set-cookie");
68
65
  }
69
66
  } catch {
70
67
  }
@@ -1 +1 @@
1
- {"version":3,"file":"httpclient.js","sources":["../../../../../src/integrations/httpclient.ts"],"sourcesContent":["import type { Client, Event as SentryEvent, IntegrationFn } from '@sentry/core';\nimport {\n _INTERNAL_filterCookies,\n _INTERNAL_filterKeyValueData,\n addExceptionMechanism,\n addFetchInstrumentationHandler,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n GLOBAL_OBJ,\n isSentryRequestUrl,\n} from '@sentry/core';\nimport type { SentryWrappedXMLHttpRequest } from '@sentry/browser-utils';\nimport { addXhrInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport type HttpStatusCodeRange = [number, number] | number;\nexport type HttpRequestTarget = string | RegExp;\n\nconst INTEGRATION_NAME = 'HttpClient' as const;\n\ninterface HttpClientOptions {\n /**\n * HTTP status codes that should be considered failed.\n * This array can contain tuples of `[begin, end]` (both inclusive),\n * single status codes, or a combinations of both\n *\n * Example: [[500, 505], 507]\n * Default: [[500, 599]]\n */\n failedRequestStatusCodes: HttpStatusCodeRange[];\n\n /**\n * Targets to track for failed requests.\n * This array can contain strings or regular expressions.\n *\n * Example: ['http://localhost', /api\\/.*\\/]\n * Default: [/.*\\/]\n */\n failedRequestTargets: HttpRequestTarget[];\n}\n\nconst _httpClientIntegration = ((options: Partial<HttpClientOptions> = {}) => {\n const _options: HttpClientOptions = {\n failedRequestStatusCodes: [[500, 599]],\n failedRequestTargets: [/.*/],\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client): void {\n _wrapFetch(client, _options);\n _wrapXHR(client, _options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Create events for failed client side HTTP requests.\n */\nexport const httpClientIntegration = defineIntegration(_httpClientIntegration);\n\n/**\n * Interceptor function for fetch requests\n *\n * @param requestInfo The Fetch API request info\n * @param response The Fetch API response\n * @param requestInit The request init object\n */\nfunction _fetchResponseHandler(\n options: HttpClientOptions,\n requestInfo: RequestInfo,\n response: Response,\n requestInit?: RequestInit,\n error?: unknown,\n): void {\n if (_shouldCaptureResponse(options, response.status, response.url)) {\n const request = _getRequest(requestInfo, requestInit);\n\n let requestHeaders, responseHeaders, requestCookies, responseCookies;\n\n const dc = _getDataCollectionSettings();\n\n if (dc.requestHeaders !== false) {\n requestHeaders = _INTERNAL_filterKeyValueData(_extractFetchHeaders(request.headers), dc.requestHeaders);\n }\n if (dc.responseHeaders !== false) {\n responseHeaders = _INTERNAL_filterKeyValueData(_extractFetchHeaders(response.headers), dc.responseHeaders);\n }\n if (dc.cookies !== false) {\n const reqCookieStr = request.headers.get('Cookie') || undefined;\n if (reqCookieStr) {\n const filtered = _INTERNAL_filterCookies(reqCookieStr, dc.cookies);\n requestCookies = typeof filtered === 'string' ? { cookie: filtered } : filtered;\n }\n const resCookieStr = response.headers.get('Set-Cookie') || undefined;\n if (resCookieStr) {\n const filtered = _INTERNAL_filterCookies(resCookieStr, dc.cookies);\n responseCookies = typeof filtered === 'string' ? { 'set-cookie': filtered } : filtered;\n }\n }\n\n const event = _createEvent({\n url: request.url,\n method: request.method,\n status: response.status,\n requestHeaders,\n responseHeaders,\n requestCookies,\n responseCookies,\n error,\n type: 'fetch',\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Interceptor function for XHR requests\n *\n * @param xhr The XHR request\n * @param method The HTTP method\n * @param headers The HTTP headers\n */\nfunction _xhrResponseHandler(\n options: HttpClientOptions,\n xhr: XMLHttpRequest,\n method: string,\n headers: Record<string, string>,\n error?: unknown,\n): void {\n if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) {\n let requestHeaders, responseCookies, responseHeaders;\n\n const dc = _getDataCollectionSettings();\n\n if (dc.cookies !== false) {\n try {\n const cookieString = xhr.getResponseHeader('Set-Cookie') || xhr.getResponseHeader('set-cookie') || undefined;\n if (cookieString) {\n const filtered = _INTERNAL_filterCookies(cookieString, dc.cookies);\n responseCookies = typeof filtered === 'string' ? { 'set-cookie': filtered } : filtered;\n }\n } catch {\n // ignore it if parsing fails\n }\n }\n\n if (dc.responseHeaders !== false) {\n try {\n responseHeaders = _INTERNAL_filterKeyValueData(_getXHRResponseHeaders(xhr), dc.responseHeaders);\n } catch {\n // ignore it if parsing fails\n }\n }\n\n if (dc.requestHeaders !== false) {\n requestHeaders = _INTERNAL_filterKeyValueData(headers, dc.requestHeaders);\n }\n\n const event = _createEvent({\n url: xhr.responseURL,\n method,\n status: xhr.status,\n requestHeaders,\n // Can't access request cookies from XHR\n responseHeaders,\n responseCookies,\n error,\n type: 'xhr',\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Extracts response size from `Content-Length` header when possible\n *\n * @param headers\n * @returns The response size in bytes or undefined\n */\nfunction _getResponseSizeFromHeaders(headers?: Record<string, string>): number | undefined {\n if (headers) {\n const contentLength = headers['Content-Length'] || headers['content-length'];\n\n if (contentLength) {\n return parseInt(contentLength, 10);\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts the headers as an object from the given Fetch API request or response object\n *\n * @param headers The headers to extract\n * @returns The extracted headers as an object\n */\nfunction _extractFetchHeaders(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n\n headers.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n\n/**\n * Extracts the response headers as an object from the given XHR object\n *\n * @param xhr The XHR object to extract the response headers from\n * @returns The response headers as an object\n */\nfunction _getXHRResponseHeaders(xhr: XMLHttpRequest): Record<string, string> {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record<string, string>, line: string) => {\n const [key, value] = line.split(': ');\n if (key && value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\n/**\n * Checks if the given target url is in the given list of targets\n *\n * @param target The target url to check\n * @returns true if the target url is in the given list of targets, false otherwise\n */\nfunction _isInGivenRequestTargets(\n failedRequestTargets: HttpClientOptions['failedRequestTargets'],\n target: string,\n): boolean {\n return failedRequestTargets.some((givenRequestTarget: HttpRequestTarget) => {\n if (typeof givenRequestTarget === 'string') {\n return target.includes(givenRequestTarget);\n }\n\n return givenRequestTarget.test(target);\n });\n}\n\n/**\n * Checks if the given status code is in the given range\n *\n * @param status The status code to check\n * @returns true if the status code is in the given range, false otherwise\n */\nfunction _isInGivenStatusRanges(\n failedRequestStatusCodes: HttpClientOptions['failedRequestStatusCodes'],\n status: number,\n): boolean {\n return failedRequestStatusCodes.some((range: HttpStatusCodeRange) => {\n if (typeof range === 'number') {\n return range === status;\n }\n\n return status >= range[0] && status <= range[1];\n });\n}\n\n/**\n * Wraps `fetch` function to capture request and response data\n */\nfunction _wrapFetch(client: Client, options: HttpClientOptions): void {\n addFetchInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const { response, args, error, virtualError } = handlerData;\n const [requestInfo, requestInit] = args as [RequestInfo, RequestInit | undefined];\n\n if (!response) {\n return;\n }\n\n _fetchResponseHandler(options, requestInfo, response as Response, requestInit, error || virtualError);\n });\n}\n\n/**\n * Wraps XMLHttpRequest to capture request and response data\n */\nfunction _wrapXHR(client: Client, options: HttpClientOptions): void {\n if (!('XMLHttpRequest' in GLOBAL_OBJ)) {\n return;\n }\n\n addXhrInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const { error, virtualError } = handlerData;\n\n const xhr = handlerData.xhr as SentryWrappedXMLHttpRequest & XMLHttpRequest;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return;\n }\n\n const { method, request_headers: headers } = sentryXhrData;\n\n try {\n _xhrResponseHandler(options, xhr, method, headers, error || virtualError);\n } catch (e) {\n DEBUG_BUILD && debug.warn('Error while extracting response event form XHR response', e);\n }\n });\n}\n\n/**\n * Checks whether to capture given response as an event\n *\n * @param status response status code\n * @param url response url\n */\nfunction _shouldCaptureResponse(options: HttpClientOptions, status: number, url: string): boolean {\n return (\n _isInGivenStatusRanges(options.failedRequestStatusCodes, status) &&\n _isInGivenRequestTargets(options.failedRequestTargets, url) &&\n !isSentryRequestUrl(url, getClient())\n );\n}\n\n/**\n * Creates a synthetic Sentry event from given response data\n *\n * @param data response data\n * @returns event\n */\nfunction _createEvent(data: {\n url: string;\n method: string;\n status: number;\n type: 'fetch' | 'xhr';\n responseHeaders?: Record<string, string>;\n responseCookies?: Record<string, string>;\n requestHeaders?: Record<string, string>;\n requestCookies?: Record<string, string>;\n error?: unknown;\n}): SentryEvent {\n const client = getClient();\n const virtualStackTrace = client && data.error && data.error instanceof Error ? data.error.stack : undefined;\n // Remove the first frame from the stack as it's the HttpClient call\n const stack = virtualStackTrace && client ? client.getOptions().stackParser(virtualStackTrace, 0, 1) : undefined;\n const message = `HTTP Client Error with status code: ${data.status}`;\n\n const event: SentryEvent = {\n message,\n exception: {\n values: [\n {\n type: 'Error',\n value: message,\n stacktrace: stack ? { frames: stack } : undefined,\n },\n ],\n },\n request: {\n url: data.url,\n method: data.method,\n headers: data.requestHeaders,\n cookies: data.requestCookies,\n },\n contexts: {\n response: {\n status_code: data.status,\n headers: data.responseHeaders,\n cookies: data.responseCookies,\n body_size: _getResponseSizeFromHeaders(data.responseHeaders),\n },\n },\n };\n\n addExceptionMechanism(event, {\n type: `auto.http.client.${data.type}`,\n handled: false,\n });\n\n return event;\n}\n\nfunction _getRequest(requestInfo: RequestInfo, requestInit?: RequestInit): Request {\n if (!requestInit && requestInfo instanceof Request) {\n return requestInfo;\n }\n\n // If both are set, we try to construct a new Request with the given arguments\n // However, if e.g. the original request has a `body`, this will throw an error because it was already accessed\n // In this case, as a fallback, we just use the original request - using both is rather an edge case\n if (requestInfo instanceof Request && requestInfo.bodyUsed) {\n return requestInfo;\n }\n\n return new Request(requestInfo, requestInit);\n}\n\nfunction _getDataCollectionSettings() {\n const client = getClient();\n if (!client) {\n return { cookies: false, requestHeaders: false, responseHeaders: false };\n }\n\n const { cookies, httpHeaders } = client.getDataCollectionOptions();\n return { cookies, requestHeaders: httpHeaders.request, responseHeaders: httpHeaders.response };\n}\n"],"names":[],"mappings":";;;;AAoBA,MAAM,gBAAA,GAAmB,YAAA;AAuBzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAsC,EAAC,KAAM;AAC5E,EAAA,MAAM,QAAA,GAA8B;AAAA,IAClC,wBAAA,EAA0B,CAAC,CAAC,GAAA,EAAK,GAAG,CAAC,CAAA;AAAA,IACrC,oBAAA,EAAsB,CAAC,IAAI,CAAA;AAAA,IAC3B,GAAG;AAAA,GACL;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAc;AAClB,MAAA,UAAA,CAAW,QAAQ,QAAQ,CAAA;AAC3B,M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EAAoB,IAAA,CAAK,IAAI,CAAA,CAAA;AAAA,IACnC,OAAA,EAAS;AAAA,GACV,CAAA;AAED,EAAA,OAAO,KAAA;AACT;AAEA,SAAS,WAAA,CAAY,aAA0B,WAAA,EAAoC;AACjF,EAAA,IAAI,CAAC,WAAA,IAAe,WAAA,YAAuB,OAAA,EAAS;AAClD,IAAA,OAAO,WAAA;AAAA,EACT;AAKA,EAAA,IAAI,WAAA,YAAuB,OAAA,IAAW,WAAA,CAAY,QAAA,EAAU;AAC1D,IAAA,OAAO,WAAA;AAAA,EACT;AAEA,EAAA,OAAO,IAAI,OAAA,CAAQ,WAAA,EAAa,WAAW,CAAA;AAC7C;AAEA,SAAS,0BAAA,GAA6B;AACpC,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAO,cAAA,EAAgB,KAAA,EAAO,iBAAiB,KAAA,EAAM;AAAA,EACzE;AAEA,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAY,GAAI,OAAO,wBAAA,EAAyB;AACjE,EAAA,OAAO,EAAE,OAAA,EAAS,cAAA,EAAgB,YAAY,OAAA,EAAS,eAAA,EAAiB,YAAY,QAAA,EAAS;AAC/F;;;;"}
1
+ {"version":3,"file":"httpclient.js","sources":["../../../../../src/integrations/httpclient.ts"],"sourcesContent":["import type { Client, Event as SentryEvent, IntegrationFn } from '@sentry/core';\nimport {\n _INTERNAL_filterCookies,\n _INTERNAL_filterKeyValueData,\n addExceptionMechanism,\n addFetchInstrumentationHandler,\n captureEvent,\n debug,\n defineIntegration,\n getClient,\n GLOBAL_OBJ,\n isSentryRequestUrl,\n} from '@sentry/core';\nimport type { SentryWrappedXMLHttpRequest } from '@sentry/browser-utils';\nimport { addXhrInstrumentationHandler, SENTRY_XHR_DATA_KEY } from '@sentry/browser-utils';\nimport { DEBUG_BUILD } from '../debug-build';\n\nexport type HttpStatusCodeRange = [number, number] | number;\nexport type HttpRequestTarget = string | RegExp;\n\nconst INTEGRATION_NAME = 'HttpClient' as const;\n\ninterface HttpClientOptions {\n /**\n * HTTP status codes that should be considered failed.\n * This array can contain tuples of `[begin, end]` (both inclusive),\n * single status codes, or a combinations of both\n *\n * Example: [[500, 505], 507]\n * Default: [[500, 599]]\n */\n failedRequestStatusCodes: HttpStatusCodeRange[];\n\n /**\n * Targets to track for failed requests.\n * This array can contain strings or regular expressions.\n *\n * Example: ['http://localhost', /api\\/.*\\/]\n * Default: [/.*\\/]\n */\n failedRequestTargets: HttpRequestTarget[];\n}\n\nconst _httpClientIntegration = ((options: Partial<HttpClientOptions> = {}) => {\n const _options: HttpClientOptions = {\n failedRequestStatusCodes: [[500, 599]],\n failedRequestTargets: [/.*/],\n ...options,\n };\n\n return {\n name: INTEGRATION_NAME,\n setup(client): void {\n _wrapFetch(client, _options);\n _wrapXHR(client, _options);\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Create events for failed client side HTTP requests.\n */\nexport const httpClientIntegration = defineIntegration(_httpClientIntegration);\n\n/**\n * Interceptor function for fetch requests\n *\n * @param requestInfo The Fetch API request info\n * @param response The Fetch API response\n * @param requestInit The request init object\n */\nfunction _fetchResponseHandler(\n options: HttpClientOptions,\n requestInfo: RequestInfo,\n response: Response,\n requestInit?: RequestInit,\n error?: unknown,\n): void {\n if (_shouldCaptureResponse(options, response.status, response.url)) {\n const request = _getRequest(requestInfo, requestInit);\n\n let requestHeaders, responseHeaders, requestCookies, responseCookies;\n\n const dc = _getDataCollectionSettings();\n\n if (dc.requestHeaders !== false) {\n requestHeaders = _INTERNAL_filterKeyValueData(_extractFetchHeaders(request.headers), dc.requestHeaders);\n }\n if (dc.responseHeaders !== false) {\n responseHeaders = _INTERNAL_filterKeyValueData(_extractFetchHeaders(response.headers), dc.responseHeaders);\n }\n if (dc.cookies !== false) {\n const reqCookieStr = request.headers.get('Cookie') || undefined;\n if (reqCookieStr) {\n requestCookies = _INTERNAL_filterCookies(reqCookieStr, dc.cookies, 'cookie');\n }\n const resCookieStr = response.headers.get('Set-Cookie') || undefined;\n if (resCookieStr) {\n responseCookies = _INTERNAL_filterCookies(resCookieStr, dc.cookies, 'set-cookie');\n }\n }\n\n const event = _createEvent({\n url: request.url,\n method: request.method,\n status: response.status,\n requestHeaders,\n responseHeaders,\n requestCookies,\n responseCookies,\n error,\n type: 'fetch',\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Interceptor function for XHR requests\n *\n * @param xhr The XHR request\n * @param method The HTTP method\n * @param headers The HTTP headers\n */\nfunction _xhrResponseHandler(\n options: HttpClientOptions,\n xhr: XMLHttpRequest,\n method: string,\n headers: Record<string, string>,\n error?: unknown,\n): void {\n if (_shouldCaptureResponse(options, xhr.status, xhr.responseURL)) {\n let requestHeaders, responseCookies, responseHeaders;\n\n const dc = _getDataCollectionSettings();\n\n if (dc.cookies !== false) {\n try {\n const cookieString = xhr.getResponseHeader('Set-Cookie') || xhr.getResponseHeader('set-cookie') || undefined;\n if (cookieString) {\n responseCookies = _INTERNAL_filterCookies(cookieString, dc.cookies, 'set-cookie');\n }\n } catch {\n // ignore it if parsing fails\n }\n }\n\n if (dc.responseHeaders !== false) {\n try {\n responseHeaders = _INTERNAL_filterKeyValueData(_getXHRResponseHeaders(xhr), dc.responseHeaders);\n } catch {\n // ignore it if parsing fails\n }\n }\n\n if (dc.requestHeaders !== false) {\n requestHeaders = _INTERNAL_filterKeyValueData(headers, dc.requestHeaders);\n }\n\n const event = _createEvent({\n url: xhr.responseURL,\n method,\n status: xhr.status,\n requestHeaders,\n // Can't access request cookies from XHR\n responseHeaders,\n responseCookies,\n error,\n type: 'xhr',\n });\n\n captureEvent(event);\n }\n}\n\n/**\n * Extracts response size from `Content-Length` header when possible\n *\n * @param headers\n * @returns The response size in bytes or undefined\n */\nfunction _getResponseSizeFromHeaders(headers?: Record<string, string>): number | undefined {\n if (headers) {\n const contentLength = headers['Content-Length'] || headers['content-length'];\n\n if (contentLength) {\n return parseInt(contentLength, 10);\n }\n }\n\n return undefined;\n}\n\n/**\n * Extracts the headers as an object from the given Fetch API request or response object\n *\n * @param headers The headers to extract\n * @returns The extracted headers as an object\n */\nfunction _extractFetchHeaders(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {};\n\n headers.forEach((value, key) => {\n result[key] = value;\n });\n\n return result;\n}\n\n/**\n * Extracts the response headers as an object from the given XHR object\n *\n * @param xhr The XHR object to extract the response headers from\n * @returns The response headers as an object\n */\nfunction _getXHRResponseHeaders(xhr: XMLHttpRequest): Record<string, string> {\n const headers = xhr.getAllResponseHeaders();\n\n if (!headers) {\n return {};\n }\n\n return headers.split('\\r\\n').reduce((acc: Record<string, string>, line: string) => {\n const [key, value] = line.split(': ');\n if (key && value) {\n acc[key] = value;\n }\n return acc;\n }, {});\n}\n\n/**\n * Checks if the given target url is in the given list of targets\n *\n * @param target The target url to check\n * @returns true if the target url is in the given list of targets, false otherwise\n */\nfunction _isInGivenRequestTargets(\n failedRequestTargets: HttpClientOptions['failedRequestTargets'],\n target: string,\n): boolean {\n return failedRequestTargets.some((givenRequestTarget: HttpRequestTarget) => {\n if (typeof givenRequestTarget === 'string') {\n return target.includes(givenRequestTarget);\n }\n\n return givenRequestTarget.test(target);\n });\n}\n\n/**\n * Checks if the given status code is in the given range\n *\n * @param status The status code to check\n * @returns true if the status code is in the given range, false otherwise\n */\nfunction _isInGivenStatusRanges(\n failedRequestStatusCodes: HttpClientOptions['failedRequestStatusCodes'],\n status: number,\n): boolean {\n return failedRequestStatusCodes.some((range: HttpStatusCodeRange) => {\n if (typeof range === 'number') {\n return range === status;\n }\n\n return status >= range[0] && status <= range[1];\n });\n}\n\n/**\n * Wraps `fetch` function to capture request and response data\n */\nfunction _wrapFetch(client: Client, options: HttpClientOptions): void {\n addFetchInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const { response, args, error, virtualError } = handlerData;\n const [requestInfo, requestInit] = args as [RequestInfo, RequestInit | undefined];\n\n if (!response) {\n return;\n }\n\n _fetchResponseHandler(options, requestInfo, response as Response, requestInit, error || virtualError);\n });\n}\n\n/**\n * Wraps XMLHttpRequest to capture request and response data\n */\nfunction _wrapXHR(client: Client, options: HttpClientOptions): void {\n if (!('XMLHttpRequest' in GLOBAL_OBJ)) {\n return;\n }\n\n addXhrInstrumentationHandler(handlerData => {\n if (getClient() !== client) {\n return;\n }\n\n const { error, virtualError } = handlerData;\n\n const xhr = handlerData.xhr as SentryWrappedXMLHttpRequest & XMLHttpRequest;\n\n const sentryXhrData = xhr[SENTRY_XHR_DATA_KEY];\n\n if (!sentryXhrData) {\n return;\n }\n\n const { method, request_headers: headers } = sentryXhrData;\n\n try {\n _xhrResponseHandler(options, xhr, method, headers, error || virtualError);\n } catch (e) {\n DEBUG_BUILD && debug.warn('Error while extracting response event form XHR response', e);\n }\n });\n}\n\n/**\n * Checks whether to capture given response as an event\n *\n * @param status response status code\n * @param url response url\n */\nfunction _shouldCaptureResponse(options: HttpClientOptions, status: number, url: string): boolean {\n return (\n _isInGivenStatusRanges(options.failedRequestStatusCodes, status) &&\n _isInGivenRequestTargets(options.failedRequestTargets, url) &&\n !isSentryRequestUrl(url, getClient())\n );\n}\n\n/**\n * Creates a synthetic Sentry event from given response data\n *\n * @param data response data\n * @returns event\n */\nfunction _createEvent(data: {\n url: string;\n method: string;\n status: number;\n type: 'fetch' | 'xhr';\n responseHeaders?: Record<string, string>;\n responseCookies?: Record<string, string>;\n requestHeaders?: Record<string, string>;\n requestCookies?: Record<string, string>;\n error?: unknown;\n}): SentryEvent {\n const client = getClient();\n const virtualStackTrace = client && data.error && data.error instanceof Error ? data.error.stack : undefined;\n // Remove the first frame from the stack as it's the HttpClient call\n const stack = virtualStackTrace && client ? client.getOptions().stackParser(virtualStackTrace, 0, 1) : undefined;\n const message = `HTTP Client Error with status code: ${data.status}`;\n\n const event: SentryEvent = {\n message,\n exception: {\n values: [\n {\n type: 'Error',\n value: message,\n stacktrace: stack ? { frames: stack } : undefined,\n },\n ],\n },\n request: {\n url: data.url,\n method: data.method,\n headers: data.requestHeaders,\n cookies: data.requestCookies,\n },\n contexts: {\n response: {\n status_code: data.status,\n headers: data.responseHeaders,\n cookies: data.responseCookies,\n body_size: _getResponseSizeFromHeaders(data.responseHeaders),\n },\n },\n };\n\n addExceptionMechanism(event, {\n type: `auto.http.client.${data.type}`,\n handled: false,\n });\n\n return event;\n}\n\nfunction _getRequest(requestInfo: RequestInfo, requestInit?: RequestInit): Request {\n if (!requestInit && requestInfo instanceof Request) {\n return requestInfo;\n }\n\n // If both are set, we try to construct a new Request with the given arguments\n // However, if e.g. the original request has a `body`, this will throw an error because it was already accessed\n // In this case, as a fallback, we just use the original request - using both is rather an edge case\n if (requestInfo instanceof Request && requestInfo.bodyUsed) {\n return requestInfo;\n }\n\n return new Request(requestInfo, requestInit);\n}\n\nfunction _getDataCollectionSettings() {\n const client = getClient();\n if (!client) {\n return { cookies: false, requestHeaders: false, responseHeaders: false };\n }\n\n const { cookies, httpHeaders } = client.getDataCollectionOptions();\n return { cookies, requestHeaders: httpHeaders.request, responseHeaders: httpHeaders.response };\n}\n"],"names":[],"mappings":";;;;AAoBA,MAAM,gBAAA,GAAmB,YAAA;AAuBzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAsC,EAAC,KAAM;AAC5E,EAAA,MAAM,QAAA,GAA8B;AAAA,IAClC,wBAAA,EAA0B,CAAC,CAAC,GAAA,EAAK,GAAG,CAAC,CAAA;AAAA,IACrC,oBAAA,EAAsB,CAAC,IAAI,CAAA;AAAA,IAC3B,GAAG;AAAA,GACL;AAEA,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,MAAM,MAAA,EAAc;AAClB,MAAA,UAAA,CAAW,QAAQ,QAAQ,CAAA;AAC3B,MAAA,QAAA,CAAS,QAAQ,QAAQ,CAAA;AAAA,IAC3B;AAAA,GACF;AACF,CAAA,CAAA;AAKO,MAAM,qBAAA,GAAwB,kBAAk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OAAO,IAAI,OAAA,CAAQ,WAAA,EAAa,WAAW,CAAA;AAC7C;AAEA,SAAS,0BAAA,GAA6B;AACpC,EAAA,MAAM,SAAS,SAAA,EAAU;AACzB,EAAA,IAAI,CAAC,MAAA,EAAQ;AACX,IAAA,OAAO,EAAE,OAAA,EAAS,KAAA,EAAO,cAAA,EAAgB,KAAA,EAAO,iBAAiB,KAAA,EAAM;AAAA,EACzE;AAEA,EAAA,MAAM,EAAE,OAAA,EAAS,WAAA,EAAY,GAAI,OAAO,wBAAA,EAAyB;AACjE,EAAA,OAAO,EAAE,OAAA,EAAS,cAAA,EAAgB,YAAY,OAAA,EAAS,eAAA,EAAiB,YAAY,QAAA,EAAS;AAC/F;;;;"}
@@ -33,10 +33,16 @@ const httpContextIntegration = defineIntegration(() => {
33
33
  client.getDataCollectionOptions().httpHeaders.request
34
34
  );
35
35
  const referer = headers["Referer"];
36
+ const { hostname, protocol } = WINDOW.location || {};
36
37
  safeSetSpanJSONAttributes(span, {
37
38
  // This attribute is used by the "Filter out events from legacy browsers and crawlers" features on the Sentry backend.
38
39
  // Therefore, it's set on every span.
39
40
  [USER_AGENT_ORIGINAL]: headers["User-Agent"],
41
+ // Likewise for the "Filter out localhost events" feature. Deliberately inlined rather than
42
+ // sharing the server-side helper, which costs bundle size for request headers and IPs that
43
+ // don't exist here. Mirrors Relay's localhost filter (relay-filter/src/localhost.rs).
44
+ "sentry.is_localhost": protocol === "file:" || hostname === "localhost" || hostname === "127.0.0.1" || // `location.hostname` keeps the brackets for IPv6 hosts, so this is `[::1]`, not `::1`.
45
+ hostname === "[::1]" || !!hostname?.endsWith(".localhost"),
40
46
  // These attributes, we only need on the segment span (analogous to the `request` context for events)
41
47
  ...span.is_segment && {
42
48
  // Coerce empty string to undefined so the helper's nullish check drops it,
@@ -1 +1 @@
1
- {"version":3,"file":"httpcontext.js","sources":["../../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { _INTERNAL_filterKeyValueData, defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { HTTP_REQUEST_HEADER_KEY_BASE, SENTRY_OP, URL_FULL, USER_AGENT_ORIGINAL } from '@sentry/conventions/attributes';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext' as const,\n preprocessEvent(event, _hint, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const { url, headers: collectedHeaders } = getHttpRequestData();\n\n // We only filter the headers we collected ourselves, so headers the user set are left alone. Going by key\n // means we also catch these headers when `browserTracingIntegration` already put them on the event.\n const behavior = client.getDataCollectionOptions().httpHeaders.request;\n const userHeaders = Object.entries(event.request?.headers ?? {}).filter(([key]) => !(key in collectedHeaders));\n\n const headers = {\n ..._INTERNAL_filterKeyValueData(collectedHeaders, behavior),\n ...Object.fromEntries(userHeaders),\n };\n\n event.request = {\n // The URL isn't gated by `dataCollection`, same as on the server.\n url,\n ...event.request,\n ...(Object.keys(headers).length > 0 ? { headers } : { headers: undefined }),\n };\n },\n\n processSpan(span, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n\n // `httpHeadersToSpanAttributes` would also work here, but its cookie and array handling never runs for these\n // two headers and costs every browser bundle ~400B gzip.\n const headers = _INTERNAL_filterKeyValueData(\n reqData.headers,\n client.getDataCollectionOptions().httpHeaders.request,\n );\n const referer = headers['Referer'];\n\n safeSetSpanJSONAttributes(span, {\n // This attribute is used by the \"Filter out events from legacy browsers and crawlers\" features on the Sentry backend.\n // Therefore, it's set on every span.\n [USER_AGENT_ORIGINAL]: headers['User-Agent'],\n\n // These attributes, we only need on the segment span (analogous to the `request` context for events)\n ...(span.is_segment && {\n // Coerce empty string to undefined so the helper's nullish check drops it,\n // rather than writing an empty `url.full` attribute onto the span.\n [URL_FULL]: span.attributes?.[SENTRY_OP] !== 'http.client' ? filterCollectedUrl(reqData.url) : undefined,\n [`${HTTP_REQUEST_HEADER_KEY_BASE}.referer`]: referer ? [referer] : undefined,\n }),\n });\n },\n };\n});\n"],"names":[],"mappings":";;;;AASO,MAAM,sBAAA,GAAyB,kBAAkB,MAAM;AAC5D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,eAAA,CAAgB,KAAA,EAAO,KAAA,EAAO,MAAA,EAAQ;AAEpC,MAAA,IAAI,CAAC,OAAO,SAAA,IAAa,CAAC,OAAO,QAAA,IAAY,CAAC,OAAO,QAAA,EAAU;AAC7D,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,gBAAA,KAAqB,kBAAA,EAAmB;AAI9D,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,wBAAA,EAAyB,CAAE,WAAA,CAAY,OAAA;AAC/D,MAAA,MAAM,cAAc,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,OAAA,EAAS,WAAW,EAAE,CAAA,CAAE,MAAA,CAAO,CAAC,CAAC,GAAG,CAAA,KAAM,EAAE,OAAO,gBAAA,CAAiB,CAAA;AAE7G,MAAA,MAAM,OAAA,GAAU;AAAA,QACd,GAAG,4BAAA,CAA6B,gBAAA,EAAkB,QAAQ,CAAA;AAAA,QAC1D,GAAG,MAAA,CAAO,WAAA,CAAY,WAAW;AAAA,OACnC;AAEA,MAAA,KAAA,CAAM,OAAA,GAAU;AAAA;AAAA,QAEd,GAAA;AAAA,QACA,GAAG,KAAA,CAAM,OAAA;AAAA,QACT,GAAI,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,GAAS,CAAA,GAAI,EAAE,OAAA,EAAQ,GAAI,EAAE,OAAA,EAAS,MAAA;AAAU,OAC3E;AAAA,IACF,CAAA;AAAA,IAEA,WAAA,CAAY,MAAM,MAAA,EAAQ;AAExB,MAAA,IAAI,CAAC,OAAO,SAAA,IAAa,CAAC,OAAO,QAAA,IAAY,CAAC,OAAO,QAAA,EAAU;AAC7D,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,UAAU,kBAAA,EAAmB;AAInC,MAAA,MAAM,OAAA,GAAU,4BAAA;AAAA,QACd,OAAA,CAAQ,OAAA;AAAA,QACR,MAAA,CAAO,wBAAA,EAAyB,CAAE,WAAA,CAAY;AAAA,OAChD;AACA,MAAA,MAAM,OAAA,GAAU,QAAQ,SAAS,CAAA;AAEjC,MAAA,yBAAA,CAA0B,IAAA,EAAM;AAAA;AAAA;AAAA,QAG9B,CAAC,mBAAmB,GAAG,OAAA,CAAQ,YAAY,CAAA;AAAA;AAAA,QAG3C,GAAI,KAAK,UAAA,IAAc;AAAA;AAAA;AAAA,UAGrB,CAAC,QAAQ,GAAG,IAAA,CAAK,UAAA,GAAa,SAAS,CAAA,KAAM,aAAA,GAAgB,kBAAA,CAAmB,OAAA,CAAQ,GAAG,CAAA,GAAI,MAAA;AAAA,UAC/F,CAAC,GAAG,4BAA4B,CAAA,QAAA,CAAU,GAAG,OAAA,GAAU,CAAC,OAAO,CAAA,GAAI;AAAA;AACrE,OACD,CAAA;AAAA,IACH;AAAA,GACF;AACF,CAAC;;;;"}
1
+ {"version":3,"file":"httpcontext.js","sources":["../../../../../src/integrations/httpcontext.ts"],"sourcesContent":["import { _INTERNAL_filterKeyValueData, defineIntegration, safeSetSpanJSONAttributes } from '@sentry/core';\nimport { getHttpRequestData, WINDOW } from '../helpers';\nimport { filterCollectedUrl } from '@sentry/core';\nimport { HTTP_REQUEST_HEADER_KEY_BASE, SENTRY_OP, URL_FULL, USER_AGENT_ORIGINAL } from '@sentry/conventions/attributes';\n\n/**\n * Collects information about HTTP request headers and\n * attaches them to the event.\n */\nexport const httpContextIntegration = defineIntegration(() => {\n return {\n name: 'HttpContext' as const,\n preprocessEvent(event, _hint, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const { url, headers: collectedHeaders } = getHttpRequestData();\n\n // We only filter the headers we collected ourselves, so headers the user set are left alone. Going by key\n // means we also catch these headers when `browserTracingIntegration` already put them on the event.\n const behavior = client.getDataCollectionOptions().httpHeaders.request;\n const userHeaders = Object.entries(event.request?.headers ?? {}).filter(([key]) => !(key in collectedHeaders));\n\n const headers = {\n ..._INTERNAL_filterKeyValueData(collectedHeaders, behavior),\n ...Object.fromEntries(userHeaders),\n };\n\n event.request = {\n // The URL isn't gated by `dataCollection`, same as on the server.\n url,\n ...event.request,\n ...(Object.keys(headers).length > 0 ? { headers } : { headers: undefined }),\n };\n },\n\n processSpan(span, client) {\n // if none of the information we want exists, don't bother\n if (!WINDOW.navigator && !WINDOW.location && !WINDOW.document) {\n return;\n }\n\n const reqData = getHttpRequestData();\n\n // `httpHeadersToSpanAttributes` would also work here, but its cookie and array handling never runs for these\n // two headers and costs every browser bundle ~400B gzip.\n const headers = _INTERNAL_filterKeyValueData(\n reqData.headers,\n client.getDataCollectionOptions().httpHeaders.request,\n );\n const referer = headers['Referer'];\n const { hostname, protocol } = WINDOW.location || {};\n\n safeSetSpanJSONAttributes(span, {\n // This attribute is used by the \"Filter out events from legacy browsers and crawlers\" features on the Sentry backend.\n // Therefore, it's set on every span.\n [USER_AGENT_ORIGINAL]: headers['User-Agent'],\n\n // Likewise for the \"Filter out localhost events\" feature. Deliberately inlined rather than\n // sharing the server-side helper, which costs bundle size for request headers and IPs that\n // don't exist here. Mirrors Relay's localhost filter (relay-filter/src/localhost.rs).\n 'sentry.is_localhost':\n protocol === 'file:' ||\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n // `location.hostname` keeps the brackets for IPv6 hosts, so this is `[::1]`, not `::1`.\n hostname === '[::1]' ||\n !!hostname?.endsWith('.localhost'),\n\n // These attributes, we only need on the segment span (analogous to the `request` context for events)\n ...(span.is_segment && {\n // Coerce empty string to undefined so the helper's nullish check drops it,\n // rather than writing an empty `url.full` attribute onto the span.\n [URL_FULL]: span.attributes?.[SENTRY_OP] !== 'http.client' ? filterCollectedUrl(reqData.url) : undefined,\n [`${HTTP_REQUEST_HEADER_KEY_BASE}.referer`]: referer ? [referer] : undefined,\n }),\n });\n },\n };\n});\n"],"names":[],"mappings":";;;;AASO,MAAM,sBAAA,GAAyB,kBAAkB,MAAM;AAC5D,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,aAAA;AAAA,IACN,eAAA,CAAgB,KAAA,EAAO,KAAA,EAAO,MAAA,EAAQ;AAEpC,MAAA,IAAI,CAAC,OAAO,SAAA,IAAa,CAAC,OAAO,QAAA,IAAY,CAAC,OAAO,QAAA,EAAU;AAC7D,QAAA;AAAA,MACF;AAEA,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,gBAAA,KAAqB,kBAAA,EAAmB;AAI9D,MAAA,MAAM,QAAA,GAAW,MAAA,CAAO,wBAAA,EAAyB,CAAE,WAAA,CAAY,OAAA;AAC/D,MAAA,MAAM,cAAc,MAAA,CAAO,OAAA,CAAQ,KAAA,CAAM,OAAA,EAAS,WAAW,EAAE,CAAA,CAAE,MAAA,CAAO,CAAC,CAAC,GAAG,CAAA,KAAM,EAAE,OAAO,gBAAA,CAAiB,CAAA;AAE7G,MAAA,MAAM,OAAA,GAAU;AAAA,QACd,GAAG,4BAAA,CAA6B,gBAAA,EAAkB,QAAQ,CAAA;AAAA,QAC1D,GAAG,MAAA,CAAO,WAAA,CAAY,WAAW;AAAA,OACnC;AAEA,MAAA,KAAA,CAAM,OAAA,GAAU;AAAA;AAAA,QAEd,GAAA;AAAA,QACA,GAAG,KAAA,CAAM,OAAA;AAAA,QACT,GAAI,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,GAAS,CAAA,GAAI,EAAE,OAAA,EAAQ,GAAI,EAAE,OAAA,EAAS,MAAA;AAAU,OAC3E;AAAA,IACF,CAAA;AAAA,IAEA,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GNORE_SPANS = [{ op: UI_INTERACTION_CLICK, name: "#sentry-spotlight" }];
7
+ const SPOTLIGHT_IGNORE_SPANS = [
8
+ { op: UI_INTERACTION_CLICK, name: "#sentry-spotlight" },
9
+ { op: UI_INTERACTION_CLICK, attributes: { "browser.web_vital.inp.target": "#sentry-spotlight" } }
10
+ ];
8
11
  const _spotlightIntegration = ((options = {}) => {
9
12
  const sidecarUrl = options.sidecarUrl || "http://localhost:8969/stream";
10
13
  return {