From 5c23514fca9871c7bae7c75267ef65daf6cbd96c Mon Sep 17 00:00:00 2001 From: Filip Slatinac Date: Wed, 1 Apr 2026 12:00:00 +0800 Subject: [PATCH] replacing invalid tag names by div (#22) --- src/snapshot.ts | 21 ++++++++++++++++++--- test/__snapshots__/integration.ts.snap | 18 ++++++++++++++++++ test/html/invalid-tagname.html | 15 +++++++++++++++ test/html/with-relative-res.html | 4 ++++ 4 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 test/html/invalid-tagname.html diff --git a/src/snapshot.ts b/src/snapshot.ts index 58891587..8c8233e1 100644 --- a/src/snapshot.ts +++ b/src/snapshot.ts @@ -8,11 +8,25 @@ import { } from './types'; let _id = 1; +const symbolAndNumberRegex = RegExp('[^a-z]'); function genId(): number { return _id++; } +function getValidTagName(tagName: string): string { + const processedTagName = tagName.toLowerCase().trim(); + + if (symbolAndNumberRegex.test(processedTagName)) { + // if the tag name is odd and we cannot extract + // anything from the string, then we return a + // generic div + return 'div'; + } + + return processedTagName; +} + function getCssRulesString(s: CSSStyleSheet): string | null { try { const rules = s.rules || s.cssRules; @@ -174,7 +188,7 @@ function serializeNode( } }); } - const tagName = (n as HTMLElement).tagName.toLowerCase(); + const tagName = getValidTagName((n as HTMLElement).tagName); let attributes: attributes = {}; for (const { name, value } of Array.from((n as HTMLElement).attributes)) { attributes[name] = transformAttribute(doc, name, value); @@ -205,8 +219,9 @@ function serializeNode( '' ).trim().length ) { - const cssText = getCssRulesString((n as HTMLStyleElement) - .sheet as CSSStyleSheet); + const cssText = getCssRulesString( + (n as HTMLStyleElement).sheet as CSSStyleSheet, + ); if (cssText) { attributes._cssText = absoluteToStylesheet(cssText, location.href); } diff --git a/test/__snapshots__/integration.ts.snap b/test/__snapshots__/integration.ts.snap index e5b4fc73..f04f33ad 100644 --- a/test/__snapshots__/integration.ts.snap +++ b/test/__snapshots__/integration.ts.snap @@ -172,6 +172,20 @@ exports[`[html file]: invalid-attribute.html 1`] = ` " `; +exports[`[html file]: invalid-tagname.html 1`] = ` +" + + + + Document + + +
Hello
+
Hello
+
Hello
+
" +`; + exports[`[html file]: picture.html 1`] = ` " @@ -190,6 +204,10 @@ exports[`[html file]: with-relative-res.html 1`] = ` +
Hello
+
Hello
+
Hello
+
\\"\\" \\"\\" \\"\\" diff --git a/test/html/invalid-tagname.html b/test/html/invalid-tagname.html new file mode 100644 index 00000000..4d9183df --- /dev/null +++ b/test/html/invalid-tagname.html @@ -0,0 +1,15 @@ + + + + + + + Document + + + Hello + Hello + Hello + + + \ No newline at end of file diff --git a/test/html/with-relative-res.html b/test/html/with-relative-res.html index f8cd16dc..7505d5a3 100644 --- a/test/html/with-relative-res.html +++ b/test/html/with-relative-res.html @@ -8,6 +8,10 @@ + Hello + Hello + Hello +