Changed the type of the "node" in hooks to be as specific as possible #1031
+280
−152
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.
Fixes #1029.
Prior to the TypeScript type declarations being provided by this package, the
@types/dompurify
package defined all hooks as taking anElement
as the first parameter. That was incorrect because some hooks can be given aNode
orDocumentFragment
. When the type declarations were moved into this repository, the hook's first parameter type was changed toNode
. This change was overzealous because some hooks are guaranteed to only be given anElement
orDocumentFragment
.To account for those hooks, this pull request adds two additional hook types -
ElementHook
andDocumentFragmentHook
(plusHook
has been renamed toNodeHook
to disambiguate it).currentNode
beforeSanitizeElements
Node
afterSanitizeElements
Node
beforeSanitizeShadowDOM
DocumentFragment
uponSanitizeShadowNode
Node
afterSanitizeShadowDOM
DocumentFragment
beforeSanitizeAttributes
Element
afterSanitizeAttributes
Element
uponSanitizeElement
Node
uponSanitizeAttribute
Element
To make this as type-safe as possible internally, I've changed the hooks to be stored in an object with properties named after each hook rather than just in an object that keys a string to an array of functions. The
_executeHooks
function now takes in the array of hooks to execute rather than the name of the hook. This allows the "node" and "data" parameters for the hook to have type-checking applied at compile time to ensure that, for example, you don't call_executeHooks
with aNode
when the hooks you are executing require anElement
.