diff --git a/src/lib/utils/index.js b/src/lib/utils/index.js
index 7d51472..b5b4c33 100644
--- a/src/lib/utils/index.js
+++ b/src/lib/utils/index.js
@@ -100,6 +100,90 @@ export function buildWordSlug(id) {
return id.split(".")[0];
}
+/**
+ * Get a plain-text excerpt from the first non-code paragraph of Markdown
+ * @param {string} body
+ * @returns {string}
+ */
+export function getExcerpt(body = "") {
+ const firstParagraph = body
+ .split(/\r?\n\s*\r?\n/)
+ .find(
+ (paragraph) => paragraph.trim() && !paragraph.trim().startsWith("```"),
+ );
+ const normalized = (firstParagraph ?? "")
+ .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
+ .replace(/`([^`]+)`/g, "$1")
+ .replace(/[*_>#]/g, "")
+ .replace(/\s+/g, " ")
+ .trim();
+
+ if (normalized.length <= 320) return normalized;
+
+ return `${normalized.slice(0, 317).trimEnd()}...`;
+}
+
+/**
+ * Extract a short, deduplicated keyword list from a word title and definition
+ * @todo Consider adding more sophisticated keyword extraction logic - this can help improve the relevance of extracted keywords
+ * @param {string} title
+ * @param {string} body
+ * @returns {string[]}
+ */
+export function getKeywords(title = "", body = "") {
+ const stopWords = new Set([
+ "about",
+ "after",
+ "also",
+ "and",
+ "are",
+ "as",
+ "at",
+ "be",
+ "by",
+ "for",
+ "from",
+ "has",
+ "have",
+ "into",
+ "is",
+ "it",
+ "its",
+ "of",
+ "on",
+ "or",
+ "that",
+ "the",
+ "their",
+ "this",
+ "to",
+ "using",
+ "was",
+ "were",
+ "which",
+ "with",
+ ]);
+ const normalizedTitle = title.trim().toLowerCase();
+ const keywords = normalizedTitle ? [normalizedTitle] : [];
+ const seen = new Set(keywords);
+ const words =
+ `${title} ${getExcerpt(body)}`.match(/[\p{L}\p{N}+#.-]+/gu) ?? [];
+
+ for (const word of words) {
+ const keyword = word.replace(/^[.-]+|[.-]+$/g, "").toLowerCase();
+ if (keyword.length < 3 || stopWords.has(keyword) || seen.has(keyword)) {
+ continue;
+ }
+
+ keywords.push(keyword);
+ seen.add(keyword);
+
+ if (keywords.length === 12) break;
+ }
+
+ return keywords;
+}
+
/**
* Get branch name from branch ref
* @param {string} branchRef
diff --git a/src/pages/api/open-graph/[...slug].png.js b/src/pages/api/open-graph/[...slug].png.js
index 4cdc2cf..8913d63 100644
--- a/src/pages/api/open-graph/[...slug].png.js
+++ b/src/pages/api/open-graph/[...slug].png.js
@@ -4,6 +4,7 @@ import { Resvg } from "@resvg/resvg-js";
import fs from "node:fs";
import path from "node:path";
import { getCollection } from "astro:content";
+import { getExcerpt } from "../../../lib/utils/index.js";
export const prerender = true;
@@ -76,22 +77,6 @@ function truncate(text, limit) {
return `${normalized.slice(0, limit - 3).trimEnd()}...`;
}
-function getExcerpt(body = "") {
- const firstParagraph = body
- .split(/\r?\n\s*\r?\n/)
- .find(
- (paragraph) => paragraph.trim() && !paragraph.trim().startsWith("```"),
- );
-
- return truncate(
- (firstParagraph ?? "")
- .replace(/\[([^\]]+)\]\([^)]+\)/g, "$1")
- .replace(/`([^`]+)`/g, "$1")
- .replace(/[*_>#]/g, ""),
- 320,
- );
-}
-
/**
* Generate a share image for a dictionary entry.
* @param {import("astro").APIContext} context
diff --git a/tests/unit/utils/index.test.js b/tests/unit/utils/index.test.js
index c89c2fb..eeb5472 100644
--- a/tests/unit/utils/index.test.js
+++ b/tests/unit/utils/index.test.js
@@ -10,6 +10,8 @@ import {
buildStatsUrl,
buildWordPathname,
buildWordSlug,
+ getExcerpt,
+ getKeywords,
toggleMarkdownListPrefix,
continueMarkdownListOnEnter,
toggleMarkdownWrap,
@@ -438,3 +440,41 @@ describe("buildWordSlug", () => {
expect(buildWordSlug("")).toBe("");
});
});
+
+describe("getExcerpt", () => {
+ it("extracts and simplifies the first non-code paragraph", () => {
+ expect(
+ getExcerpt(
+ "```js\nignored()\n```\n\n**QUIC** uses [`UDP`](https://example.com) and `TLS`.\n\nA second paragraph.",
+ ),
+ ).toBe("QUIC uses UDP and TLS.");
+ });
+
+ it("truncates excerpts to 320 characters", () => {
+ expect(getExcerpt("a".repeat(321))).toBe(`${"a".repeat(317)}...`);
+ });
+
+ it("returns an empty string when no paragraph is available", () => {
+ expect(getExcerpt()).toBe("");
+ });
+});
+
+describe("getKeywords", () => {
+ it("extracts unique terms from the title and first definition paragraph", () => {
+ expect(
+ getKeywords("QUIC", "QUIC is a fast protocol using UDP and TCP."),
+ ).toEqual(["quic", "fast", "protocol", "udp", "tcp"]);
+ });
+
+ it("keeps a title keyword when the definition is empty", () => {
+ expect(getKeywords("C", "")).toEqual(["c"]);
+ });
+
+ it("limits the list to twelve keywords", () => {
+ const body = Array.from({ length: 20 }, (_, index) => `term${index}`).join(
+ " ",
+ );
+
+ expect(getKeywords("Example", body)).toHaveLength(12);
+ });
+});