-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
ref(browser): Extract browser-specific normalize code into registerable util
#21172
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
mydea
wants to merge
6
commits into
develop
Choose a base branch
from
fn/move-convertToPlainObject
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| import { addNormalizeUnpacker, isInstanceOf } from '@sentry/core'; | ||
| import { serializeEventTarget } from './object'; | ||
|
|
||
| let unregister: (() => void) | undefined; | ||
|
|
||
| /** | ||
| * Registers a `normalize()` unpacker that extracts the meaningful fields of a DOM | ||
| * `Event` (`type`, `target`, `currentTarget`, optional `detail`) into a plain object | ||
| * before `normalize()` walks it. Element targets are serialized via `htmlTreeAsString` | ||
| * so the user sees a CSS-selector-style path rather than `[object HTMLButtonElement]`. | ||
| * | ||
| * Idempotent — calling more than once is a no-op (the existing registration is reused). | ||
| * | ||
| * Returns the unregister function from `addNormalizeUnpacker` (useful for tests). | ||
| */ | ||
| export function registerDomEventNormalizer(): () => void { | ||
| if (unregister) { | ||
| return unregister; | ||
| } | ||
| unregister = addNormalizeUnpacker(value => { | ||
| if (typeof Event === 'undefined' || !(value instanceof Event)) { | ||
| return undefined; | ||
| } | ||
| const result: Record<string, unknown> = { | ||
| type: value.type, | ||
| target: serializeEventTarget(value.target), | ||
| currentTarget: serializeEventTarget(value.currentTarget), | ||
| ...Object.fromEntries(Object.entries(value)), | ||
| }; | ||
| if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) { | ||
| result.detail = (value as CustomEvent).detail; | ||
| } | ||
| return result; | ||
| }); | ||
|
|
||
| const baseUnregister = unregister; | ||
| return () => { | ||
| baseUnregister(); | ||
| unregister = undefined; | ||
| }; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,124 @@ | ||
| import { isString } from '@sentry/core'; | ||
|
|
||
| const DEFAULT_MAX_STRING_LENGTH = 80; | ||
|
|
||
| type SimpleNode = { | ||
| parentNode: SimpleNode; | ||
| } | null; | ||
|
|
||
| /** | ||
| * Given a child DOM element, returns a query-selector statement describing that | ||
| * and its ancestors | ||
| * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] | ||
| * @returns generated DOM path | ||
| */ | ||
| export function htmlTreeAsString( | ||
| elem: unknown, | ||
| options: string[] | { keyAttrs?: string[]; maxStringLength?: number } = {}, | ||
| ): string { | ||
| if (!elem) { | ||
| return '<unknown>'; | ||
| } | ||
|
|
||
| // try/catch both: | ||
| // - accessing event.target (see getsentry/raven-js#838, #768) | ||
| // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly | ||
| // - can throw an exception in some circumstances. | ||
| try { | ||
| let currentElem = elem as SimpleNode; | ||
| const MAX_TRAVERSE_HEIGHT = 5; | ||
| const out = []; | ||
| let height = 0; | ||
| let len = 0; | ||
| const separator = ' > '; | ||
| const sepLength = separator.length; | ||
| let nextStr; | ||
| const keyAttrs = Array.isArray(options) ? options : options.keyAttrs; | ||
| const maxStringLength = (!Array.isArray(options) && options.maxStringLength) || DEFAULT_MAX_STRING_LENGTH; | ||
|
|
||
| while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { | ||
| nextStr = _htmlElementAsString(currentElem, keyAttrs); | ||
| // bail out if | ||
| // - nextStr is the 'html' element | ||
| // - the length of the string that would be created exceeds maxStringLength | ||
| // (ignore this limit if we are on the first iteration) | ||
| if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= maxStringLength)) { | ||
| break; | ||
| } | ||
|
|
||
| out.push(nextStr); | ||
|
|
||
| len += nextStr.length; | ||
| currentElem = currentElem.parentNode; | ||
| } | ||
|
|
||
| return out.reverse().join(separator); | ||
| } catch { | ||
| return '<unknown>'; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Returns a simple, query-selector representation of a DOM element | ||
| * e.g. [HTMLElement] => input#foo.btn[name=baz] | ||
| * @returns generated DOM path | ||
| */ | ||
| function _htmlElementAsString(el: unknown, keyAttrs?: string[]): string { | ||
| const elem = el as { | ||
| tagName?: string; | ||
| id?: string; | ||
| className?: string; | ||
| getAttribute(key: string): string; | ||
| }; | ||
|
|
||
| const out = []; | ||
|
|
||
| if (!elem?.tagName) { | ||
| return ''; | ||
| } | ||
|
|
||
| if (typeof HTMLElement !== 'undefined') { | ||
| // If using the component name annotation plugin, this value may be available on the DOM node | ||
| if (elem instanceof HTMLElement && elem.dataset) { | ||
| if (elem.dataset['sentryComponent']) { | ||
| return elem.dataset['sentryComponent']; | ||
| } | ||
| if (elem.dataset['sentryElement']) { | ||
| return elem.dataset['sentryElement']; | ||
| } | ||
| } | ||
| } | ||
|
|
||
| out.push(elem.tagName.toLowerCase()); | ||
|
|
||
| // Pairs of attribute keys defined in `serializeAttribute` and their values on element. | ||
| const keyAttrPairs = keyAttrs?.length | ||
| ? keyAttrs.filter(keyAttr => elem.getAttribute(keyAttr)).map(keyAttr => [keyAttr, elem.getAttribute(keyAttr)]) | ||
| : null; | ||
|
|
||
| if (keyAttrPairs?.length) { | ||
| keyAttrPairs.forEach(keyAttrPair => { | ||
| out.push(`[${keyAttrPair[0]}="${keyAttrPair[1]}"]`); | ||
| }); | ||
| } else { | ||
| if (elem.id) { | ||
| out.push(`#${elem.id}`); | ||
| } | ||
|
|
||
| const className = elem.className; | ||
| if (className && isString(className)) { | ||
| const classes = className.split(/\s+/); | ||
| for (const c of classes) { | ||
| out.push(`.${c}`); | ||
| } | ||
| } | ||
| } | ||
| for (const k of ['aria-label', 'type', 'name', 'title', 'alt']) { | ||
| const attr = elem.getAttribute(k); | ||
| if (attr) { | ||
| out.push(`[${k}="${attr}"]`); | ||
| } | ||
| } | ||
|
|
||
| return out.join(''); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,79 @@ | ||
| import { isElement, isEvent, isInstanceOf, convertToPlainObject as originalConvertToPlainObject } from '@sentry/core'; | ||
| import { htmlTreeAsString } from './htmlTreeAsString'; | ||
|
|
||
| /** | ||
| * Transforms any `Error` or `Event` into a plain object with all of their enumerable properties, and some of their | ||
| * non-enumerable properties attached. | ||
| * | ||
| * @param value Initial source that we have to transform in order for it to be usable by the serializer | ||
| * @returns An Event or Error turned into an object - or the value argument itself, when value is neither an Event nor | ||
| * an Error. | ||
| */ | ||
| export function convertToPlainObject<V>(value: V): | ||
| | { | ||
| [ownProps: string]: unknown; | ||
| type: string; | ||
| target: string; | ||
| currentTarget: string; | ||
| detail?: unknown; | ||
| } | ||
| | { | ||
| [ownProps: string]: unknown; | ||
| message: string; | ||
| name: string; | ||
| stack?: string; | ||
| } | ||
| | V { | ||
| if (isEvent(value)) { | ||
| const newObj: { | ||
| [ownProps: string]: unknown; | ||
| type: string; | ||
| target: string; | ||
| currentTarget: string; | ||
| detail?: unknown; | ||
| } = { | ||
| type: value.type, | ||
| target: serializeEventTarget(value.target), | ||
| currentTarget: serializeEventTarget(value.currentTarget), | ||
| ...getOwnProperties(value), | ||
| }; | ||
|
|
||
| if (typeof CustomEvent !== 'undefined' && isInstanceOf(value, CustomEvent)) { | ||
| newObj.detail = value.detail; | ||
| } | ||
|
|
||
| return newObj; | ||
| } | ||
|
|
||
| return originalConvertToPlainObject(value); | ||
| } | ||
|
|
||
| export function serializeEventTarget(target: unknown): string { | ||
| try { | ||
| return isElement(target) ? htmlTreeAsString(target) : Object.prototype.toString.call(target); | ||
| } catch { | ||
| return '<unknown>'; | ||
| } | ||
| } | ||
|
|
||
| function getOwnProperties(obj: unknown): { [key: string]: unknown } { | ||
| if (typeof obj === 'object' && obj !== null) { | ||
| return Object.fromEntries(Object.entries(obj)); | ||
| } | ||
| return {}; | ||
| } | ||
|
|
||
| /** | ||
| * Given any captured exception, extract its keys and create a sorted | ||
| * and truncated list that will be used inside the event message. | ||
| * eg. `Non-error exception captured with keys: foo, bar, baz` | ||
| * | ||
| * The browser variant produces richer output for `Event` exceptions | ||
| * (e.g. extracting `type`, `target`, `currentTarget`). | ||
| */ | ||
| export function extractExceptionKeysForMessage(exception: Record<string, unknown>): string { | ||
| const keys = Object.keys(convertToPlainObject(exception)); | ||
| keys.sort(); | ||
|
|
||
| return !keys[0] ? '[object has no keys]' : keys.join(', '); | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Idempotent unregister breaks re-registration
Medium Severity
When
registerDomEventNormalizer()runs while a registration already exists, it returns the rawaddNormalizeUnpackerteardown instead of the wrapper that clears module state. Calling that teardown removes the unpacker but leaves the moduleunregisterreference set, so later calls hit the idempotent branch and never calladdNormalizeUnpackeragain—DOMEventnormalization stays off until the module reloads.Reviewed by Cursor Bugbot for commit 3ed69bb. Configure here.