|
| 1 | +import type { ConsoleLevel, Logger } from '@sentry/core'; |
| 2 | +import { DEBUG_BUILD } from './debug-build'; |
| 3 | +import type { NetworkMetaWarning } from './types'; |
| 4 | + |
| 5 | +type ReplayConsoleLevels = Extract<ConsoleLevel, 'info' | 'warn' | 'error' | 'log'>; |
| 6 | +type LoggerMethod = (...args: unknown[]) => void; |
| 7 | +type LoggerConsoleMethods = Record<ReplayConsoleLevels, LoggerMethod>; |
| 8 | + |
| 9 | +interface LoggerConfig { |
| 10 | + captureExceptions: boolean; |
| 11 | + traceInternals: boolean; |
| 12 | +} |
| 13 | + |
| 14 | +// Duplicate from replay-internal |
| 15 | +interface ReplayLogger extends LoggerConsoleMethods { |
| 16 | + /** |
| 17 | + * Calls `logger.info` but saves breadcrumb in the next tick due to race |
| 18 | + * conditions before replay is initialized. |
| 19 | + */ |
| 20 | + infoTick: LoggerMethod; |
| 21 | + /** |
| 22 | + * Captures exceptions (`Error`) if "capture internal exceptions" is enabled |
| 23 | + */ |
| 24 | + exception: LoggerMethod; |
| 25 | + /** |
| 26 | + * Configures the logger with additional debugging behavior |
| 27 | + */ |
| 28 | + setConfig(config: Partial<LoggerConfig>): void; |
| 29 | +} |
| 30 | + |
| 31 | +function _serializeFormData(formData: FormData): string { |
| 32 | + // This is a bit simplified, but gives us a decent estimate |
| 33 | + // This converts e.g. { name: 'Anne Smith', age: 13 } to 'name=Anne+Smith&age=13' |
| 34 | + // @ts-expect-error passing FormData to URLSearchParams actually works |
| 35 | + return new URLSearchParams(formData).toString(); |
| 36 | +} |
| 37 | + |
| 38 | +/** Get the string representation of a body. */ |
| 39 | +export function getBodyString( |
| 40 | + body: unknown, |
| 41 | + logger?: Logger | ReplayLogger, |
| 42 | +): [string | undefined, NetworkMetaWarning?] { |
| 43 | + try { |
| 44 | + if (typeof body === 'string') { |
| 45 | + return [body]; |
| 46 | + } |
| 47 | + |
| 48 | + if (body instanceof URLSearchParams) { |
| 49 | + return [body.toString()]; |
| 50 | + } |
| 51 | + |
| 52 | + if (body instanceof FormData) { |
| 53 | + return [_serializeFormData(body)]; |
| 54 | + } |
| 55 | + |
| 56 | + if (!body) { |
| 57 | + return [undefined]; |
| 58 | + } |
| 59 | + } catch (error) { |
| 60 | + // RelayLogger |
| 61 | + if (DEBUG_BUILD && logger && 'exception' in logger) { |
| 62 | + logger.exception(error, 'Failed to serialize body', body); |
| 63 | + } else if (DEBUG_BUILD && logger) { |
| 64 | + logger.error(error, 'Failed to serialize body', body); |
| 65 | + } |
| 66 | + return [undefined, 'BODY_PARSE_ERROR']; |
| 67 | + } |
| 68 | + |
| 69 | + DEBUG_BUILD && logger?.info('Skipping network body because of body type', body); |
| 70 | + |
| 71 | + return [undefined, 'UNPARSEABLE_BODY_TYPE']; |
| 72 | +} |
0 commit comments