Skip to content

Open source alternative to Semrush and Ahrefs

Count words correctly on CJK pages and minified HTML (#1069)

Ben Senescu756538cc55e7
diff --git a/src/server/lib/audit/page-analyzer.test.ts b/src/server/lib/audit/page-analyzer.test.ts
index c8ad71a1..10efbc19 100644
--- a/src/server/lib/audit/page-analyzer.test.ts
+++ b/src/server/lib/audit/page-analyzer.test.ts
@@ -9,7 +9,10 @@ import { analyzeHtml } from "@/server/lib/audit/page-analyzer";
import { normalizeUrl, isSameOrigin } from "@/server/lib/audit/url-utils";
import type { PageAnalysis, PageLink } from "@/server/lib/audit/types";
-/** The previous cheerio implementation, verbatim (minus passthrough fields). */
+/**
+ * The previous cheerio implementation (minus passthrough fields), plus
+ * separators around block elements so minified markup keeps word boundaries.
+ */
function analyzeHtmlWithCheerio(html: string, pageUrl: string): PageAnalysis {
const $ = cheerio.load(html);
@@ -44,6 +47,12 @@ function analyzeHtmlWithCheerio(html: string, pageUrl: string): PageAnalysis {
const bodyClone = $("body").clone();
bodyClone.find("script, style, noscript, svg").remove();
+ bodyClone
+ .find(
+ "address,article,aside,blockquote,br,caption,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,header,hgroup,hr,li,main,nav,ol,p,pre,section,summary,table,td,th,tr,ul",
+ )
+ .before(" ")
+ .after(" ");
const bodyText = bodyClone.text().replace(/\s+/g, " ").trim();
const wordCount = bodyText ? bodyText.split(/\s+/).length : 0;
@@ -208,6 +217,31 @@ describe("analyzeHtml parity with the DOM reference", () => {
});
});
+describe("analyzeHtml word count", () => {
+ const analyzeBody = (body: string) =>
+ analyzeHtml(`<body>${body}</body>`, PAGE_URL, 200, 0);
+
+ it.each([
+ ["paragraphs", "<p>one</p><p>two</p>"],
+ ["table cells", "<table><tr><td>one</td><td>two</td></tr></table>"],
+ ["line breaks", "one<br>two"],
+ ])("keeps word boundaries between %s in minified HTML", (_label, body) => {
+ expect(analyzeBody(body).bodyText).toBe("one two");
+ });
+
+ it("does not split words across inline markup", () => {
+ expect(analyzeBody("<p>Open<strong>SEO</strong></p>").wordCount).toBe(1);
+ });
+
+ it("counts words in scripts written without spaces", () => {
+ expect(
+ analyzeBody("<p>吉隆坡市中心永久地契公寓投资指南</p>").wordCount,
+ ).toBe(8);
+ expect(analyzeBody("<p>東京の不動産投資ガイド</p>").wordCount).toBe(5);
+ expect(analyzeBody("<p>KLCC 公寓指南 2026</p>").wordCount).toBe(4);
+ });
+});
+
describe("analyzeHtml meta names are case-insensitive", () => {
const analyzeHead = (head: string) =>
analyzeHtml(`<head>${head}</head>`, PAGE_URL, 200, 0);
diff --git a/src/server/lib/audit/page-analyzer.ts b/src/server/lib/audit/page-analyzer.ts
index fb50e62d..983a7d83 100644
--- a/src/server/lib/audit/page-analyzer.ts
+++ b/src/server/lib/audit/page-analyzer.ts
@@ -37,6 +37,75 @@ const MAX_EXTRACTED_LINKS = 1_000;
const MAX_EXTRACTED_IMAGES = 1_000;
// Common app entry points. Scripts alone also appear on ordinary HTML pages.
const APP_ROOT_IDS = new Set(["root", "app", "__next", "__nuxt"]);
+/**
+ * Elements a browser renders on their own line. Minified HTML has no
+ * whitespace between them, so `<p>one</p><p>two</p>` would read as "onetwo"
+ * without a separator at their boundaries.
+ */
+const BLOCK_TAGS = new Set([
+ "address",
+ "article",
+ "aside",
+ "blockquote",
+ "br",
+ "caption",
+ "dd",
+ "details",
+ "dialog",
+ "div",
+ "dl",
+ "dt",
+ "fieldset",
+ "figcaption",
+ "figure",
+ "footer",
+ "form",
+ "h1",
+ "h2",
+ "h3",
+ "h4",
+ "h5",
+ "h6",
+ "header",
+ "hgroup",
+ "hr",
+ "li",
+ "main",
+ "nav",
+ "ol",
+ "p",
+ "pre",
+ "section",
+ "summary",
+ "table",
+ "td",
+ "th",
+ "tr",
+ "ul",
+]);
+// Chinese, Japanese, Thai, Lao, Khmer and Burmese are written without spaces
+// between words, so a whitespace split counts a whole paragraph as one word
+// and flags those pages as thin content. Tokens in those scripts get their
+// words from Intl.Segmenter; every other token still counts as one word, so
+// counts for space-separated languages are unchanged.
+const SPACELESS_SCRIPT =
+ /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}\p{Script=Lao}\p{Script=Khmer}\p{Script=Myanmar}]/u;
+const wordSegmenter = new Intl.Segmenter(undefined, { granularity: "word" });
+
+function countWords(text: string): number {
+ let count = 0;
+ for (const token of text.split(/\s+/)) {
+ if (!token) continue;
+ if (!SPACELESS_SCRIPT.test(token)) {
+ count += 1;
+ continue;
+ }
+ for (const segment of wordSegmenter.segment(token)) {
+ if (segment.isWordLike) count += 1;
+ }
+ }
+ return count;
+}
interface OpenAnchor {
href: string;
@@ -89,6 +158,15 @@ export function analyzeHtml(
const bodyParts: string[] = [];
const fallbackParts: string[] = [];
+ const addVisibleText = (text: string) => {
+ if (suppressDepth > 0) return;
+ if (bodyDepth > 0) {
+ bodyParts.push(text);
+ } else if (headDepth === 0) {
+ fallbackParts.push(text);
+ }
+ };
+
const handleMetaTag = (attribs: Record<string, string>) => {
const content = attribs["content"];
// HTML meta names are ASCII case-insensitive: "Description" is valid.
@@ -142,6 +220,7 @@ export function analyzeHtml(
}
if (name === "noscript") noscriptDepth += 1;
if (noscriptDepth > 0) return;
+ if (BLOCK_TAGS.has(name)) addVisibleText(" ");
if (headDepth === 0 && suppressDepth === 0) {
hasAppRoot ||= APP_ROOT_IDS.has(attribs["id"]) || name === "app-root";
}
@@ -214,11 +293,7 @@ export function analyzeHtml(
}
if (openH1) openH1.push(text);
if (openAnchor) openAnchor.text.push(text);
- if (bodyDepth > 0) {
- bodyParts.push(text);
- } else if (headDepth === 0) {
- fallbackParts.push(text);
- }
+ addVisibleText(text);
},
onclosetag(name) {
if (NON_CONTENT_TAGS.has(name) && suppressDepth > 0) {
@@ -229,6 +304,7 @@ export function analyzeHtml(
return;
}
if (noscriptDepth > 0) return;
+ if (BLOCK_TAGS.has(name)) addVisibleText(" ");
if (name === "title" && titleDepth > 0) {
titleDepth -= 1;
if (titleDepth === 0) titleDone = true;
@@ -250,7 +326,7 @@ export function analyzeHtml(
const rawText = (sawBody ? bodyParts : fallbackParts).join("");
const bodyText = rawText.replace(/\s+/g, " ").trim();
- const wordCount = bodyText ? bodyText.split(/\s+/).length : 0;
+ const wordCount = countWords(bodyText);
return {
url: pageUrl,