Skip to content
Open
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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"@astrojs/rss": "4.0.18",
"@astrojs/sitemap": "3.7.3",
"@base-ui/react": "1.5.0",
"@cloudflare/nimbus-docs": "0.7.1",
"@cloudflare/vitest-pool-workers": "0.16.15",
"@cloudflare/workers-types": "4.20260615.1",
"@docsearch/css": "3.9.0",
Expand Down Expand Up @@ -112,7 +113,6 @@
"mermaid": "11.15.0",
"micromark-extension-mdxjs": "3.0.0",
"nanostores": "1.3.0",
"@cloudflare/nimbus-docs": "^0.6.1",
"node-html-parser": "7.1.0",
"openapi-types": "12.1.3",
"parse-duration": "2.1.6",
Expand Down
14 changes: 9 additions & 5 deletions pnpm-lock.yaml

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

8 changes: 8 additions & 0 deletions pnpm-workspace.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,14 @@ minimumReleaseAgeExclude:
# natively (nimbus-docs pulls markdown-satteri 0.3.4, @astrojs/mdx@7 peers
# ^0.3.1), so the old allowedVersions override is obsolete and has been removed.

# Resolve @cloudflare/nimbus-docs from the public npm tarball. It is published to
# public npm, but a machine-global .npmrc rule routes the whole @cloudflare scope
# to the internal registry gateway (which does not mirror it). Pinning the tarball
# URL here bypasses that routing for this one package, leaving the scope rule (and
# every other @cloudflare/* dependency) untouched. Bump this URL on each release.
overrides:
"@cloudflare/nimbus-docs": "https://registry.npmjs.org/@cloudflare/nimbus-docs/-/nimbus-docs-0.7.1.tgz"

# Prevent transitive dependencies from using exotic sources (git repos, direct tarball URLs).
# Only direct dependencies may use exotic sources.
blockExoticSubdeps: true
Expand Down
28 changes: 26 additions & 2 deletions src/pages/[...slug].astro
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,24 @@ import { config } from "virtual:nimbus/config";
import { docsSidebarTransform, getCfBreadcrumbs } from "../util/sidebar";
import { components } from "../mdx-components";
import { getOgImage } from "~/util/og";
import {
pageHasRuntimeHeadings,
scrapeRenderedHeadings,
} from "../util/rendered-toc";

const NOINDEX_PRODUCTS = ["email-security"];

export const prerender = true;
export const getStaticPaths = getDocsStaticPaths;

const { entry, Content, headings } = await getDocsPageProps(Astro);
const { entry, Content, headings } = await getDocsPageProps(Astro, {
partialHeadings: {
resolvePartialId: ({ file, product }) => {
if (!file) return undefined;
return product ? `${product}/${file}` : file;
},
},
});

const currentSlug = Astro.url.pathname.replace(/\/$/, "") || "/";
const sectionSegment = currentSlug.split("/").filter(Boolean)[0];
Expand Down Expand Up @@ -66,7 +77,20 @@ const editUrl = await getEditUrl(entry);
// Frontmatter wins; git is the fallback.
const lastUpdated = entry.data.lastUpdated ?? (await getLastUpdated(entry));
const tocConfig = entry.data.tableOfContents;
const tocHeadings = headings.filter((h) => h.slug !== "footnote-label");
// Runtime (set:html) headings are missing from compile-time `headings`.
let tocSource = headings;
if (
tocOn &&
tocConfig !== false &&
(await pageHasRuntimeHeadings(entry.body ?? ""))
) {
try {
tocSource = await scrapeRenderedHeadings(Content, components);
} catch (err) {
console.error(`[toc] rendered-heading scrape failed for ${entry.id}:`, err);
}
}
const tocHeadings = tocSource.filter((h) => h.slug !== "footnote-label");
const toc =
tocOn && tocConfig !== false ? getTOC(tocHeadings, tocConfig) : false;
const markdownPath = `/${entry.id}/index.md`;
Expand Down
76 changes: 76 additions & 0 deletions src/util/rendered-toc.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
import { getCollection } from "astro:content";
import { experimental_AstroContainer as AstroContainer } from "astro/container";
import { loadRenderers } from "astro:container";
import { getContainerRenderer as getMdxRenderer } from "@astrojs/mdx";
import { getContainerRenderer as getReactRenderer } from "@astrojs/react";
import { getHeadingsFromHtml, type Heading } from "@cloudflare/nimbus-docs";
import type { AstroComponentFactory } from "astro/runtime/server/index.js";

// AnchorHeading emits its <h*> at runtime via set:html, so those headings are
// absent from compile-time `render().headings`. Pages using it (directly or
// through a partial) must read headings from rendered HTML instead.
const RENDER_MARKER = "AnchorHeading";

function resolvePartialId(file?: string, product?: string): string | undefined {
if (!file) return undefined;
return product ? `${product}/${file}` : file;
}

function renderRefs(body: string): string[] {
const ids: string[] = [];
for (const match of body.matchAll(/<Render\b[^>]*>/g)) {
const tag = match[0];
const file = /\bfile=["']([^"']+)["']/.exec(tag)?.[1];
const product = /\bproduct=["']([^"']+)["']/.exec(tag)?.[1];
const id = resolvePartialId(file, product);
if (id) ids.push(id);
}
return ids;
}

let dynamicPartials: Promise<Set<string>> | undefined;
async function computeDynamicPartials(): Promise<Set<string>> {
const bodies = new Map<string, string>();
for (const partial of await getCollection("partials")) {
bodies.set(partial.id, partial.body ?? "");
}

const dynamic = new Set<string>();
for (const [id, body] of bodies) {
if (body.includes(RENDER_MARKER)) dynamic.add(id);
}
let changed = true;
while (changed) {
changed = false;
for (const [id, body] of bodies) {
if (dynamic.has(id)) continue;
if (renderRefs(body).some((ref) => dynamic.has(ref))) {
dynamic.add(id);
changed = true;
}
}
}
return dynamic;
}

export async function pageHasRuntimeHeadings(body: string): Promise<boolean> {
if (!body) return false;
if (body.includes(RENDER_MARKER)) return true;
const dynamic = await (dynamicPartials ??= computeDynamicPartials());
return renderRefs(body).some((ref) => dynamic.has(ref));
}

let containerPromise: Promise<AstroContainer> | undefined;
export async function scrapeRenderedHeadings(
Content: AstroComponentFactory,
components: Record<string, unknown>,
): Promise<Heading[]> {
containerPromise ??= loadRenderers([
getMdxRenderer(),
getReactRenderer(),
]).then((renderers) => AstroContainer.create({ renderers }));
const html = await (
await containerPromise
).renderToString(Content, { props: { components } });
return getHeadingsFromHtml(html);
}