import type { eventWithTime, pluginEvent } from './rrweb-types' import { isArray, isNull, isObject, isUndefined } from '@posthog/core' /** Replay events buffered for one session and window, with their estimated sizes. */ export interface SnapshotBuffer { size: number data: any[] sizes: number[] sessionId: string windowId: string } // taken from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value#circular_references export function circularReferenceReplacer() { const ancestors: any[] = [] return function (this: any, _key: string, value: any) { // arrays must be tracked as ancestors too - isObject excludes them, and an // untracked array in the path empties the ancestor stack, so a cycle passing // through an array would be missed and JSON.stringify would throw if (isObject(value) || isArray(value)) { // `this` is the object that value is contained in, // i.e., its direct parent. while (ancestors.length > 0 && ancestors[ancestors.length - 1] !== this) { ancestors.pop() } if (ancestors.includes(value)) { return '[Circular]' } ancestors.push(value) return value } else { return value } } } function estimateStringBytes(data: string): number { return new Blob([data]).size } // an event whose JSON is longer than the engine's maximum string length makes JSON.stringify // throw `RangeError: Invalid string length`. Such an event can never reach the server either - // the request encoder stringifies the whole batch - so estimateSize reports the failure with // this size instead of throwing, and the caller drops that one event. export const UNSTRINGIFIABLE_EVENT_SIZE = -1 export function estimateSize(sizeable: unknown): number { try { const stringifiedData = JSON.stringify(sizeable, circularReferenceReplacer()) return stringifiedData ? estimateStringBytes(stringifiedData) : 0 } catch { return UNSTRINGIFIABLE_EVENT_SIZE } } // Lightweight size estimate for compressed events without allocating a JSON string. // Intentionally loose: does not account for JSON escaping of strings or keys. // This is fine because compressed event strings are base64 gzip output (safe alphabet) // and keys are known-safe identifiers. Used only for buffer threshold checks (~1MB) // and split-buffer decisions (~7MB) where a few bytes of drift don't matter. export function estimateCompressedEventSize(value: unknown): number { if (isNull(value)) { return 4 } if (isUndefined(value)) { return 0 } switch (typeof value) { case 'string': return value.length + 2 case 'number': return String(value).length case 'boolean': return value ? 4 : 5 case 'object': { if (isArray(value)) { let size = 2 for (let i = 0; i < value.length; i++) { if (i > 0) size += 1 const el = value[i] size += isUndefined(el) || isNull(el) ? 4 : estimateCompressedEventSize(el) } return size } const obj = value as Record let size = 2 let first = true for (const key in obj) { if (!Object.prototype.hasOwnProperty.call(obj, key)) continue const val = obj[key] if (isUndefined(val)) continue if (!first) size += 1 first = false size += key.length + 3 + estimateCompressedEventSize(val) } return size } default: return 0 } } export const replacementImageURI = 'data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTYiIGhlaWdodD0iMTYiIHZpZXdCb3g9IjAgMCAxNiAxNiIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHJlY3Qgd2lkdGg9IjE2IiBoZWlnaHQ9IjE2IiBmaWxsPSJibGFjayIvPgo8cGF0aCBkPSJNOCAwSDE2TDAgMTZWOEw4IDBaIiBmaWxsPSIjMkQyRDJEIi8+CjxwYXRoIGQ9Ik0xNiA4VjE2SDhMMTYgOFoiIGZpbGw9IiMyRDJEMkQiLz4KPC9zdmc+Cg==' export const FULL_SNAPSHOT_EVENT_TYPE = 2 export const META_EVENT_TYPE = 4 export const INCREMENTAL_SNAPSHOT_EVENT_TYPE = 3 export const PLUGIN_EVENT_TYPE = 6 export const MUTATION_SOURCE_TYPE = 0 export const MAX_MESSAGE_SIZE = 5000000 // ~5mb /* * Check whether a data payload is nearing 5mb. If it is, it checks the data for * data URIs (the likely culprit for large payloads). If it finds data URIs, it either replaces * it with a generic image (if it's an image) or removes it. * @data {object} the rr-web data object * @returns {object} the rr-web data object with data uris filtered out */ export function ensureMaxMessageSize(data: eventWithTime): { event: eventWithTime; size: number } { let stringifiedData = JSON.stringify(data) // Note: with compression, this limit may be able to be increased // but we're assuming most of the size is from a data uri which // is unlikely to be compressed further let size = estimateStringBytes(stringifiedData) if (size > MAX_MESSAGE_SIZE) { // Regex that matches the pattern for a dataURI with the shape 'data:{mime type}[;{param}[={value}]]*,{data}'. It: // 1) Checks if the pattern starts with 'data:' (potentially, not at the start of the string) // 2) Extracts the mime type of the data uri in the first group (e.g. image/svg+xml) // 3) Allows any number of parameters, e.g. ';base64', ';charset=utf-8;base64' or none // 4) Determines when the data URI ends. It is matched against JSON text, so it must never consume // a " or \ (a quote inside a string is escaped as \", and consuming part of an escape would // produce invalid JSON). It also stops at ), ' and whitespace, which end a URI in css or srcset. const dataURIRegex = /data:([\w/\-.+]+)(?:;[\w\-.+]+(?:=[\w\-.+%]+)?)*,[^)"'\s\\]*/gim const unfilteredStringifiedData = stringifiedData stringifiedData = stringifiedData.replace(dataURIRegex, (_match: string, mimeType: string) => mimeType.toLocaleLowerCase().slice(0, 6) === 'image/' ? replacementImageURI : '' ) if (stringifiedData !== unfilteredStringifiedData) { size = estimateStringBytes(stringifiedData) } } return { event: JSON.parse(stringifiedData), size } } export const CONSOLE_LOG_PLUGIN_NAME = 'rrweb/console@1' // The name of the rr-web plugin that emits console logs // Console logs can be really large. This function truncates large logs // It's a simple function that just truncates long strings. // TODO: Ideally this function would have better handling of objects + lists, // so they could still be rendered in a pretty way after truncation. export function truncateLargeConsoleLogs(_event: eventWithTime) { const event = _event as pluginEvent<{ payload: string[] }> const MAX_STRING_SIZE = 2000 // Maximum number of characters allowed in a string const MAX_STRINGS_PER_LOG = 10 // A log can consist of multiple strings (e.g. consol.log('string1', 'string2')) if ( event && isObject(event) && event.type === PLUGIN_EVENT_TYPE && isObject(event.data) && event.data.plugin === CONSOLE_LOG_PLUGIN_NAME ) { // Note: event.data.payload.payload comes from rr-web, and is an array of strings if (event.data.payload.payload.length > MAX_STRINGS_PER_LOG) { event.data.payload.payload = event.data.payload.payload.slice(0, MAX_STRINGS_PER_LOG) event.data.payload.payload.push('...[truncated]') } const updatedPayload: string[] = [] for (let i = 0; i < event.data.payload.payload.length; i++) { if ( event.data.payload.payload[i] && // Value can be null event.data.payload.payload[i]!.length > MAX_STRING_SIZE ) { updatedPayload.push(event.data.payload.payload[i]!.slice(0, MAX_STRING_SIZE) + '...[truncated]') } else { updatedPayload.push(event.data.payload.payload[i]!) } } event.data.payload.payload = updatedPayload // Return original type return _event } return _event } export const SEVEN_MEGABYTES = 1024 * 1024 * 7 * 0.9 // ~7mb (with some wiggle room) // recursively splits large buffers into smaller ones // uses a pretty high size limit to avoid splitting too much export function splitBuffer(buffer: SnapshotBuffer, sizeLimit: number = SEVEN_MEGABYTES): SnapshotBuffer[] { if (buffer.size >= sizeLimit && buffer.data.length > 1) { const half = Math.floor(buffer.data.length / 2) const firstHalfSizes = buffer.sizes.slice(0, half) const secondHalfSizes = buffer.sizes.slice(half) return [ splitBuffer({ size: firstHalfSizes.reduce((a, b) => a + b, 0), data: buffer.data.slice(0, half), sizes: firstHalfSizes, sessionId: buffer.sessionId, windowId: buffer.windowId, }), splitBuffer({ size: secondHalfSizes.reduce((a, b) => a + b, 0), data: buffer.data.slice(half), sizes: secondHalfSizes, sessionId: buffer.sessionId, windowId: buffer.windowId, }), ].flatMap((x) => x) } else { return [buffer] } }