Skip to content
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

feat(prerender): use ultrahtml to extract links #3068

Merged
merged 6 commits into from
Feb 5, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@
"source-map": "^0.7.4",
"std-env": "^3.8.0",
"ufo": "^1.5.4",
"ultrahtml": "^1.5.3",
"uncrypto": "^0.1.3",
"unctx": "^2.4.1",
"unenv": "^1.10.0",
Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion src/core/prerender/prerender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ export async function prerender(nitro: Nitro) {

// Crawl route links
if (!_route.error && (isImplicitHTML || route.endsWith(".html"))) {
const extractedLinks = extractLinks(
const extractedLinks = await extractLinks(
dataBuff.toString("utf8"),
route,
res,
Expand Down
24 changes: 15 additions & 9 deletions src/core/prerender/utils.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { colors } from "consola/utils";
import type { PrerenderRoute } from "nitropack/types";
import { parseURL } from "ufo";
import { parse as parseHTML, walk } from "ultrahtml";

const allowedExtensions = new Set(["", ".json"]);

const linkParents = new Map<string, Set<string>>();

const LINK_REGEX = /(?<=\s)href=(?!&quot;)["']?([^"'>]+)/g;

const HTML_ENTITIES = {
"&lt;": "<",
"&gt;": ">",
Expand All @@ -23,7 +22,7 @@ function escapeHtml(text: string) {
);
}

export function extractLinks(
export async function extractLinks(
html: string,
from: string,
res: Response,
Expand All @@ -34,12 +33,19 @@ export function extractLinks(

// Extract from any <TAG href=""> to crawl
if (crawlLinks) {
_links.push(
...[...html.matchAll(LINK_REGEX)]
.map((m) => escapeHtml(m[1]))
.filter((m) => !decodeURIComponent(m).startsWith("#"))
.filter((link) => allowedExtensions.has(getExtension(link)))
);
await walk(parseHTML(html), (node) => {
if (!node.attributes?.href) {
return;
}

const link = escapeHtml(node.attributes.href);
if (
!decodeURIComponent(link).startsWith("#") &&
allowedExtensions.has(getExtension(link))
) {
_links.push(link);
}
});
}

// Extract from x-nitro-prerender headers
Expand Down