Skip to content
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 .github/workflows/ui-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ jobs:
echo "prerendered pages: $(find apps/loopover-ui/dist/client -name '*.html' | wc -l)"
test -s apps/loopover-ui/dist/client/index.html
test -s apps/loopover-ui/dist/client/404.html
echo "sitemap URLs: $(grep -c '<loc>' apps/loopover-ui/dist/client/sitemap.xml)"

- name: Deploy loopover.ai
if: ${{ github.event_name != 'pull_request' && github.ref == 'refs/heads/main' }}
Expand Down
37 changes: 0 additions & 37 deletions apps/loopover-ui/public/sitemap.xml

This file was deleted.

36 changes: 25 additions & 11 deletions apps/loopover-ui/scripts/prerender-static.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@
// Why a crawl: the app is a TanStack Start SSR build (Nitro, cloudflare-module preset). Nitro's own prerenderer
// renders nothing under @lovable.dev/vite-tanstack-config, and TanStack Start's needs a Node server bundle the
// Cloudflare preset does not produce. So this runs the BUILT Worker in workerd -- several `wrangler dev --local`
// instances, since each renders one request at a time -- and fetches every page from it: the sitemap, every
// docs page in content/docs, every operation in public/openapi.json, and every internal link those pages
// render. A page is written as <path>.html (/ as index.html), which Workers' default html_handling serves at
// <path> with no redirect, and an unknown path's render becomes 404.html for not_found_handling.
// instances, since each renders one request at a time -- and fetches every page from it: every static route in
// src/routes, every docs page in content/docs, every operation in public/openapi.json, and every internal link
// those pages render. A page is written as <path>.html (/ as index.html), which Workers' default html_handling
// serves at <path> with no redirect, and an unknown path's render becomes 404.html for not_found_handling.
//
// sitemap.xml is written from the same crawl (src/lib/sitemap.ts): every rendered page's canonical URL, so the
// sitemap lists exactly the pages the site serves and cannot drift from them.
//
// Any internal link that does not render, or a page that embeds the local origin, fails the run: a link to a
// removed page cannot ship.
Expand All @@ -34,6 +37,8 @@ import {
import { tmpdir } from "node:os";
import { dirname, join, relative, resolve } from "node:path";

import { canonicalUrlOf, sitemapXml } from "../src/lib/sitemap.ts";

const APP_DIR = resolve(import.meta.dirname, "..");
const CLIENT_DIR = join(APP_DIR, "dist/client");
const SERVER_DIR = join(APP_DIR, "dist/server");
Expand Down Expand Up @@ -192,10 +197,6 @@ function seedPaths(): string[] {
.filter(Boolean);
paths.add(`/${segments.join("/")}`);
}
const sitemap = readFileSync(join(APP_DIR, "public/sitemap.xml"), "utf8");
for (const match of sitemap.matchAll(/<loc>\s*([^<\s]+)\s*<\/loc>/g)) {
paths.add(normalize(new URL(match[1]!).pathname) ?? "/");
}
for (const file of readdirSync(join(APP_DIR, "content/docs"))) {
if (file.endsWith(".mdx")) paths.add(`/docs/${file.slice(0, -".mdx".length)}`);
}
Expand Down Expand Up @@ -256,6 +257,7 @@ async function main(): Promise<void> {
process.on("SIGTERM", () => process.exit(143));

const failures: string[] = [];
const sitemapUrls = new Set<string>();
let written = 0;
try {
await Promise.all(servers.map(({ origin, child, log }) => waitReady(origin, child, log)));
Expand Down Expand Up @@ -293,6 +295,12 @@ async function main(): Promise<void> {
failures.push(`unsafe path ${path}`);
return;
}
try {
sitemapUrls.add(canonicalUrlOf(path, html));
} catch (error) {
failures.push(`canonical ${path}: ${(error as Error).message}`);
return;
}
mkdirSync(dirname(join(CLIENT_DIR, file)), { recursive: true });
writeFileSync(join(CLIENT_DIR, file), html);
written += 1;
Expand Down Expand Up @@ -339,8 +347,10 @@ async function main(): Promise<void> {
writeFileSync(join(CLIENT_DIR, "404.html"), notFoundHtml);
}

writeFileSync(join(CLIENT_DIR, "sitemap.xml"), sitemapXml(sitemapUrls));
console.log(
`prerender: ${written} pages written (${seeds.length} seeded, ${seen.size} discovered)`,
`prerender: ${written} pages written (${seeds.length} seeded, ${seen.size} discovered), ` +
`${sitemapUrls.size} canonical URLs in sitemap.xml`,
);
} finally {
stopAll();
Expand All @@ -352,8 +362,12 @@ async function main(): Promise<void> {
for (const line of failures.slice(0, 50)) console.error(` ${line}`);
process.exit(1);
}
if (!existsSync(join(CLIENT_DIR, "index.html")) || !existsSync(join(CLIENT_DIR, "404.html"))) {
console.error("prerender: index.html or 404.html was not written");
if (
!existsSync(join(CLIENT_DIR, "index.html")) ||
!existsSync(join(CLIENT_DIR, "404.html")) ||
!existsSync(join(CLIENT_DIR, "sitemap.xml"))
) {
console.error("prerender: index.html, 404.html or sitemap.xml was not written");
process.exit(1);
}
writeFileSync(GENERATED_CONFIG, `${JSON.stringify(deploy, null, 2)}\n`);
Expand Down
68 changes: 68 additions & 0 deletions apps/loopover-ui/src/lib/sitemap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import { describe, expect, it } from "vitest";

import { canonicalUrlOf, sitemapXml } from "./sitemap";

describe("canonicalUrlOf", () => {
it("takes the URL a page names as canonical, in either attribute order", () => {
expect(
canonicalUrlOf(
"/docs",
'<head><link rel="canonical" href="https://loopover.ai/docs"/></head>',
),
).toBe("https://loopover.ai/docs");
expect(
canonicalUrlOf(
"/api/get-v1-repos",
'<link rel="stylesheet" href="/assets/app.css"><link href="https://loopover.ai/api" rel="canonical"/>',
),
).toBe("https://loopover.ai/api");
});

it("falls back to the page's own loopover.ai URL when it names no canonical", () => {
expect(canonicalUrlOf("/roadmap", '<link rel="icon" href="/favicon.ico">')).toBe(
"https://loopover.ai/roadmap",
);
expect(canonicalUrlOf("/", "<html></html>")).toBe("https://loopover.ai/");
});

it("refuses a canonical on another host, naming the page", () => {
expect(() =>
canonicalUrlOf("/agents", '<link rel="canonical" href="https://www.loopover.ai/agents">'),
).toThrow(/\/agents names https:\/\/www\.loopover\.ai\/agents as canonical/);
});
});

describe("sitemapXml", () => {
it("lists each URL once, sorted, in the sitemap protocol's shape", () => {
expect(
sitemapXml([
"https://loopover.ai/docs",
"https://loopover.ai/",
"https://loopover.ai/api",
"https://loopover.ai/docs",
]),
).toBe(
[
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
" <url><loc>https://loopover.ai/</loc></url>",
" <url><loc>https://loopover.ai/api</loc></url>",
" <url><loc>https://loopover.ai/docs</loc></url>",
"</urlset>",
"",
].join("\n"),
);
});

it("escapes XML metacharacters in a URL", () => {
expect(sitemapXml(["https://loopover.ai/a?b=1&c='d'"])).toContain(
"<loc>https://loopover.ai/a?b=1&amp;c=&apos;d&apos;</loc>",
);
});

it("refuses a URL on another host", () => {
expect(() => sitemapXml(["https://example.com/"])).toThrow(
/sitemap URL https:\/\/example\.com\/ is not on https:\/\/loopover\.ai/,
);
});
});
61 changes: 61 additions & 0 deletions apps/loopover-ui/src/lib/sitemap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// loopover.ai's sitemap.xml, built from the pages the prerender actually rendered (scripts/prerender-static.ts)
// rather than kept by hand: a hand-kept list named 34 of the site's pages and drifted from the rest. Each rendered
// page contributes the URL it names as canonical, so a page that defers to another (every /api/<operation> page
// names /api) is listed once, under the URL search engines are told to index.
//
// The `.ts` extension on the import lets the prerender load this file under plain Node's type stripping.
import { SITE_ORIGIN } from "./canonical.ts";

const LINK_TAG = /<link\b[^>]*>/gi;

function attribute(tag: string, name: string): string | undefined {
const match = tag.match(new RegExp(`\\s${name}="([^"]*)"`, "i"));
return match?.[1]?.replaceAll("&amp;", "&");
}

/** Whether a URL is on loopover.ai: the sitemap lists only this site's pages. */
function onSite(url: string): boolean {
return new URL(url).origin === SITE_ORIGIN;
}

/** A page's canonical URL, or an error naming the page when that URL is on another host. */
function canonicalOnSite(url: string, path: string): string {
if (!onSite(url)) {
throw new Error(`${path} names ${url} as canonical, which is not on ${SITE_ORIGIN}`);
}
return url;
}

/** The URL a rendered page names as canonical, or its own loopover.ai URL when it names none. */
export function canonicalUrlOf(path: string, html: string): string {
for (const tag of html.match(LINK_TAG) ?? []) {
if (attribute(tag, "rel")?.toLowerCase() !== "canonical") continue;
const href = attribute(tag, "href");
if (href) return canonicalOnSite(href, path);
}
return canonicalOnSite(new URL(path, SITE_ORIGIN).toString(), path);
}

function escapeXml(text: string): string {
return text
.replaceAll("&", "&amp;")
.replaceAll("<", "&lt;")
.replaceAll(">", "&gt;")
.replaceAll('"', "&quot;")
.replaceAll("'", "&apos;");
}

/** sitemap.xml for the given loopover.ai URLs: each once, sorted, so a rebuild of the same site is byte-identical. */
export function sitemapXml(urls: Iterable<string>): string {
const unique = [...new Set(urls)].sort();
const foreign = unique.find((url) => !onSite(url));
if (foreign) throw new Error(`sitemap URL ${foreign} is not on ${SITE_ORIGIN}`);
const entries = unique.map((url) => ` <url><loc>${escapeXml(url)}</loc></url>`);
return [
'<?xml version="1.0" encoding="UTF-8"?>',
'<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',
...entries,
"</urlset>",
"",
].join("\n");
}
Loading