Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

generate-api-reference.ts

1,113 lines35.3 KB

1import * as fs from "node:fs/promises";
2import * as path from "node:path";
3​
4import * as ts from "typescript-api/unstable/ast";
5import type { Node, SourceFile } from "typescript-api/unstable/ast";
6import { createSyntaxProject } from "./typescript-source.ts";
7​
8const websiteRoot = path.join(import.meta.dir, "../website");
9​
10interface SourceRoot {
11 /** Directory scanned for documented source files. */
12 srcRoot: string;
13 /**
14 * Synthetic provider name for flat single-provider packages (their files
15 * sit directly at `srcRoot`); empty for the alchemy package, whose
16 * top-level directories ARE the providers.
17 */
18 providerPrefix: string;
19 /** Display prefix for the page's `Source:` line. */
20 sourceDisplayPrefix: string;
22​
23const config = {
24 outRoot: path.join(websiteRoot, "src/content/docs/providers"),
25 roots: [
26 {
27 srcRoot: path.join(import.meta.dir, "../packages/alchemy/src"),
28 providerPrefix: "",
29 sourceDisplayPrefix: "src",
30 },
31 {
32 srcRoot: path.join(import.meta.dir, "../packages/better-auth/src"),
33 providerPrefix: "BetterAuth",
34 sourceDisplayPrefix: "packages/better-auth/src",
35 },
36 ] satisfies SourceRoot[],
37};
38​
39interface FileEntry {
40 /** Output-relative path (provider-prefixed for flat packages). */
41 relativePath: string;
42 absolutePath: string;
43 /** Display path for the page's `Source:` blockquote. */
44 sourceDisplay: string;
46​
47interface ExampleBlock {
48 title: string;
49 body: string;
51​
52interface ExampleSection {
53 title: string;
54 description: string;
55 examples: ExampleBlock[];
57​
58interface PageDoc {
59 title: string;
60 /** Display path for the `Source:` blockquote. */
61 sourceDisplay: string;
62 summary: string;
63 sections: ExampleSection[];
64 /** True for `@layer` pages — renders the Layer metadata line. */
65 isLayer: boolean;
66 /** Service tags the Layer provides (`@provides`). */
67 provides: string[];
68 /** Optional peer dependencies (`@peer`). */
69 peers: string[];
71​
72const normalizeSlashes = (value: string) => value.split(path.sep).join("/");
73​
74const isSourceFile = (baseName: string) =>
75 (baseName.endsWith(".ts") || baseName.endsWith(".tsx")) &&
76 !baseName.endsWith(".d.ts") &&
77 baseName !== "index.ts";
78​
79async function discoverFiles(root: SourceRoot): Promise<FileEntry[]> {
80 const entries: FileEntry[] = [];
81​
82 // Flat single-provider packages: every file under srcRoot belongs to the
83 // synthetic provider directory.
84 if (root.providerPrefix) {
85 const files = (await fs.readdir(root.srcRoot, {
86 recursive: true,
87 })) as string[];
88 for (const file of files) {
89 if (!isSourceFile(path.basename(file))) continue;
90 entries.push({
91 relativePath: path.join(root.providerPrefix, file),
92 absolutePath: path.join(root.srcRoot, file),
93 sourceDisplay: `${root.sourceDisplayPrefix}/${normalizeSlashes(file)}`,
94 });
95 }
96 entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
97 return entries;
98 }
99​
100 const topLevelEntries = await fs.readdir(root.srcRoot, {
101 withFileTypes: true,
102 });
103 const dirs = topLevelEntries
104 .filter((entry) => entry.isDirectory())
105 .map((entry) => entry.name);
106​
107 for (const dir of dirs) {
108 const dirPath = path.join(root.srcRoot, dir);
109 let files: string[];
110 try {
111 files = (await fs.readdir(dirPath, { recursive: true })) as string[];
112 } catch {
113 continue;
114 }
115​
116 for (const file of files) {
117 if (!isSourceFile(path.basename(file))) continue;
118​
119 const relativePath = path.join(dir, file);
120 entries.push({
121 relativePath,
122 absolutePath: path.join(root.srcRoot, relativePath),
123 sourceDisplay: `${root.sourceDisplayPrefix}/${normalizeSlashes(relativePath)}`,
124 });
125 }
126 }
127​
128 entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
129 return entries;
131​
132function getJsDocText(node: Node): string {
133 return node.jsDoc?.map((doc) => doc.getText()).join("\n") ?? "";
135​
136function cleanDocComment(raw: string): string {
137 return raw
138 .replace(/^\/\*\*?/, "")
139 .replace(/\*\/$/, "")
140 .split("\n")
141 .map((line) => line.replace(/^\s*\*\s?/, ""))
142 .join("\n");
144​
145interface ParsedJSDoc {
146 summary: string;
147 sections: ExampleSection[];
148 hasResourceTag: boolean;
149 hasBindingTag: boolean;
150 /** `@layer` — a Layer factory providing a Context service. */
151 hasLayerTag: boolean;
152 /** `@provides <Service.Tag>` — service tags the Layer satisfies. */
153 provides: string[];
154 /** `@peer <package>` — optional peer dependencies the Layer needs. */
155 peers: string[];
156 category: string;
157 product: string;
159​
160function parseJSDoc(node: Node): ParsedJSDoc {
161 const raw = getJsDocText(node);
162 if (!raw) {
163 return {
164 summary: "",
165 sections: [],
166 hasResourceTag: false,
167 hasBindingTag: false,
168 hasLayerTag: false,
169 provides: [],
170 peers: [],
171 category: "",
172 product: "",
173 };
174 }
175​
176 const lines = cleanDocComment(raw).split("\n");
177​
178 const summaryLines: string[] = [];
179 const sections: ExampleSection[] = [];
180 const provides: string[] = [];
181 const peers: string[] = [];
182 let hasResourceTag = false;
183 let hasBindingTag = false;
184 let hasLayerTag = false;
185 let category = "";
186 let product = "";
187 let sawTag = false;
188 let currentSection: ExampleSection | undefined;
189 let currentExample: ExampleBlock | undefined;
190​
191 let sectionDescLines: string[] = [];
192 let collectingSectionDesc = false;
193 let insideFence = false;
194​
195 const flushExample = () => {
196 if (!currentExample) return;
197 currentExample.body = currentExample.body.trim();
198 if (!currentSection) {
199 currentSection = { title: "Examples", description: "", examples: [] };
200 sections.push(currentSection);
201 }
202 currentSection.examples.push(currentExample);
203 currentExample = undefined;
204 };
205​
206 const flushSectionDesc = () => {
207 if (currentSection && sectionDescLines.length > 0) {
208 currentSection.description = sectionDescLines.join("\n").trim();
209 }
210 sectionDescLines = [];
211 collectingSectionDesc = false;
212 };
213​
214 for (const line of lines) {
215 // Track fenced code blocks so an `@`-prefixed line inside an example
216 // (e.g. a decorator) is never mistaken for a JSDoc tag.
217 if (line.trim().startsWith("```")) {
218 insideFence = !insideFence;
219 }
220​
221 const proseHeading = insideFence
222 ? null
223 : line.trim().match(/^###\s+(.+?)\s+<!-- api-prose -->$/);
224 if (proseHeading) {
225 if (!sawTag) summaryLines.push(`### ${proseHeading[1]!.trim()}`);
226 continue;
227 }
228​
229 const section = insideFence ? null : line.trim().match(/^###\s+(.+)$/);
230 if (section) {
231 sawTag = true;
232 flushExample();
233 flushSectionDesc();
234 currentSection = {
235 title: section[1]!.trim(),
236 description: "",
237 examples: [],
238 };
239 sections.push(currentSection);
240 collectingSectionDesc = true;
241 continue;
242 }
243​
244 const example = insideFence
245 ? null
246 : line.trim().match(/^\*\*Example:\*\*\s*(.*)$/);
247 if (example) {
248 sawTag = true;
249 flushSectionDesc();
250 flushExample();
251 currentExample = {
252 title: example[1]!.trim() || "Example",
253 body: "",
254 };
255 continue;
256 }
257​
258 const tag = insideFence ? null : line.trim().match(/^@(\w+)\s*(.*)$/);
259 if (tag) {
260 sawTag = true;
261 const [, name, rest] = tag;
262 const value = (rest ?? "").trim();
263 switch (name) {
264 case "resource":
265 hasResourceTag = true;
266 break;
267 case "binding":
268 hasBindingTag = true;
269 break;
270 case "layer":
271 hasLayerTag = true;
272 break;
273 case "provides":
274 if (value) provides.push(value);
275 break;
276 case "peer":
277 if (value) peers.push(value);
278 break;
279 case "category":
280 case "group":
281 if (value) category = value;
282 break;
283 case "product":
284 case "label":
285 if (value) product = value;
286 break;
287 case "section":
288 flushExample();
289 flushSectionDesc();
290 currentSection = {
291 title: value || "Examples",
292 description: "",
293 examples: [],
294 };
295 sections.push(currentSection);
296 collectingSectionDesc = true;
297 break;
298 case "example":
299 flushSectionDesc();
300 flushExample();
301 currentExample = { title: value || "Example", body: "" };
302 break;
303 }
304 continue;
305 }
306​
307 if (!sawTag) {
308 summaryLines.push(line);
309 continue;
310 }
311​
312 if (currentExample) {
313 currentExample.body += `${line}\n`;
314 } else if (collectingSectionDesc) {
315 sectionDescLines.push(line);
316 }
317 }
318​
319 flushSectionDesc();
320 flushExample();
321​
322 return {
323 summary: summaryLines.join("\n").trim(),
324 sections,
325 hasResourceTag,
326 hasBindingTag,
327 hasLayerTag,
328 provides,
329 peers,
330 category,
331 product,
332 };
334​
335function declName(node: Node): string {
336 if (ts.isVariableStatement(node)) {
337 return node.declarationList.declarations[0]?.name.getText() ?? "";
338 }
339 if (
340 ts.isClassDeclaration(node) ||
341 ts.isInterfaceDeclaration(node) ||
342 ts.isTypeAliasDeclaration(node)
343 ) {
344 return node.name?.getText() ?? "";
345 }
346 return "";
348​
349interface Primary {
350 name: string;
351 doc: ParsedJSDoc;
352 category: string;
353 product: string;
355​
356const hasContent = (doc: ParsedJSDoc) =>
357 Boolean(doc.summary) || doc.sections.length > 0;
358​
359/**
360 * Map a public export name back to its local declaration name when a file
361 * re-exports under an alias, e.g. `export { VpcLinkResource as VpcLink }`
362 * lets us find the documented `VpcLinkResource` const from the tagged
363 * `VpcLink` interface.
364 */
365export function exportedNames(sourceFile: SourceFile): string[] {
366 const names = new Set<string>();
367 const addBinding = (name: ts.BindingName): void => {
368 if (ts.isIdentifier(name)) names.add(name.text);
369 else
370 for (const element of name.elements) {
371 if (ts.isBindingElement(element) && element.name)
372 addBinding(element.name);
373 }
374 };
375 for (const statement of sourceFile.statements) {
376 if (ts.isExportDeclaration(statement)) {
377 if (statement.exportClause && ts.isNamedExports(statement.exportClause)) {
378 for (const spec of statement.exportClause.elements)
379 names.add(spec.name.text);
380 } else if (
381 statement.exportClause &&
382 ts.isNamespaceExport(statement.exportClause)
383 ) {
384 names.add(statement.exportClause.name.text);
385 }
386 } else if (ts.isExportAssignment(statement)) {
387 if (!statement.isExportEquals) names.add("default");
388 } else if (
389 (ts.isVariableStatement(statement) ||
390 ts.isClassDeclaration(statement) ||
391 ts.isFunctionDeclaration(statement) ||
392 ts.isInterfaceDeclaration(statement) ||
393 ts.isTypeAliasDeclaration(statement) ||
394 ts.isEnumDeclaration(statement) ||
395 ts.isModuleDeclaration(statement) ||
396 ts.isImportEqualsDeclaration(statement)) &&
397 statement.modifierFlags & ts.ModifierFlags.Export
398 ) {
399 if (statement.modifierFlags & ts.ModifierFlags.Default)
400 names.add("default");
401 else if (ts.isVariableStatement(statement)) {
402 for (const declaration of statement.declarationList.declarations)
403 addBinding(declaration.name);
404 } else if (
405 ts.isClassDeclaration(statement) ||
406 ts.isFunctionDeclaration(statement) ||
407 ts.isInterfaceDeclaration(statement) ||
408 ts.isTypeAliasDeclaration(statement) ||
409 ts.isEnumDeclaration(statement) ||
410 ts.isModuleDeclaration(statement) ||
411 ts.isImportEqualsDeclaration(statement)
412 ) {
413 if (statement.name) names.add(statement.name.text);
414 }
415 }
416 }
417 return [...names];
419​
420function localNameForExport(
421 sourceFile: SourceFile,
422 publicName: string,
423): string | undefined {
424 for (const ed of sourceFile.statements.filter(ts.isExportDeclaration)) {
425 if (ed.moduleSpecifier) continue;
426 for (const spec of ed.exportClause && ts.isNamedExports(ed.exportClause)
427 ? ed.exportClause.elements
428 : []) {
429 if (spec.name.text === publicName) {
430 return (spec.propertyName ?? spec.name).text;
431 }
432 }
433 }
434 return undefined;
436​
437/**
438 * The page for a file is owned by the single exported declaration tagged
439 * `@resource` or `@binding`, and named after it. Authors sometimes write the
440 * docs (summary/@section/@example) on a sibling declaration of the same name
441 * (an `interface X` paired with `const X`) or on an internal const that is
442 * re-exported under the tagged name (the ApiGateway `XResource as X` pattern).
443 * When the tagged declaration itself has no content, pull it from that related
444 * declaration so the page isn't dropped as empty.
445 */
446export function findTaggedPrimary(sourceFile: SourceFile): Primary | undefined {
447 const candidates: Node[] = [
448 ...sourceFile.statements
449 .filter(ts.isVariableStatement)
450 .filter((s) => Boolean(s.modifierFlags & ts.ModifierFlags.Export)),
451 ...sourceFile.statements
452 .filter(ts.isClassDeclaration)
453 .filter((c) => Boolean(c.modifierFlags & ts.ModifierFlags.Export)),
454 ...sourceFile.statements
455 .filter(ts.isInterfaceDeclaration)
456 .filter((i) => Boolean(i.modifierFlags & ts.ModifierFlags.Export)),
457 ];
458​
459 for (const node of candidates) {
460 const doc = parseJSDoc(node);
461 if (!doc.hasResourceTag && !doc.hasBindingTag && !doc.hasLayerTag) {
462 continue;
463 }
464 const name = declName(node);
465 if (!name) continue;
466 const category = doc.category;
467 const product = doc.product;
468 if (hasContent(doc)) return { name, doc, category, product };
469​
470 // Tagged declaration has no prose — look for the related declaration that
471 // carries the docs (same name, or re-exported under this name).
472 const localName = localNameForExport(sourceFile, name);
473 const related: Node[] = [
474 ...sourceFile.statements.filter(ts.isVariableStatement),
475 ...sourceFile.statements.filter(ts.isClassDeclaration),
476 ...sourceFile.statements.filter(ts.isInterfaceDeclaration),
477 ...sourceFile.statements.filter(ts.isTypeAliasDeclaration),
478 ].filter((d) => {
479 if (d === node) return false;
480 const dn = declName(d);
481 return dn === name || (localName !== undefined && dn === localName);
482 });
483​
484 let best: ParsedJSDoc | undefined;
485 for (const d of related) {
486 const pd = parseJSDoc(d);
487 if (pd.sections.length > 0) {
488 best = pd;
489 break;
490 }
491 if (!best && pd.summary) best = pd;
492 }
493 // Borrowed prose keeps the TAGGED declaration's kind + metadata.
494 const merged: ParsedJSDoc = {
495 ...(best ?? doc),
496 hasResourceTag: doc.hasResourceTag,
497 hasBindingTag: doc.hasBindingTag,
498 hasLayerTag: doc.hasLayerTag,
499 provides: doc.provides,
500 peers: doc.peers,
501 };
502 return { name, doc: merged, category, product };
503 }
504 return undefined;
506​
507const LINK_TAG_RE = /\{@link\s+([^}]+)\}/g;
508​
509/** Split a `{@link ...}` tag's inner text into target + optional label. */
510function parseLinkTag(inner: string): { target: string; label?: string } {
511 const trimmed = inner.trim();
512 const pipe = trimmed.indexOf("|");
513 if (pipe !== -1) {
514 return {
515 target: trimmed.slice(0, pipe).trim(),
516 label: trimmed.slice(pipe + 1).trim() || undefined,
517 };
518 }
519 const space = trimmed.search(/\s/);
520 if (space !== -1) {
521 return {
522 target: trimmed.slice(0, space).trim(),
523 label: trimmed.slice(space + 1).trim() || undefined,
524 };
525 }
526 return { target: trimmed };
528​
529/**
530 * Reduce a typedoc-style `import("./Secrets.ts").Secrets` target to the bare
531 * symbol name — resolution (same-directory first) and display both want the
532 * name, not the module expression.
533 */
534function normalizeLinkTarget(target: string): string {
535 const match = target.match(/^import\((["'])[^"']+\1\)\.(.+)$/);
536 return match ? match[2] : target;
538​
539/** Resolves a `{@link}` symbol target to a generated page URL, if any. */
540type LinkResolver = (target: string) => string | undefined;
541​
542/**
543 * Build a per-page resolver factory. A symbol resolves to another generated
544 * page preferring (in order): a same-directory page named after it, a
545 * same-directory page whose source file exports it (an access-level service
546 * like `ReadNamespace` documented on its `ReadWriteNamespace` page), a unique
547 * name match within the same provider, a unique exporter within the same
548 * provider, then a unique global name match. Member suffixes
549 * (`Cluster#capacityProviders`), provider-qualified names (`Cloudflare.Worker`)
550 * and `FooProps` interfaces resolve to the base resource's page.
551 */
552function makeLinkResolverFactory(
553 pages: PageEntry[],
554): (fromDir: string) => LinkResolver {
555 const byName = new Map<string, PageEntry[]>();
556 const byExport = new Map<string, PageEntry[]>();
557 for (const p of pages) {
558 if (!byName.has(p.resource)) byName.set(p.resource, []);
559 byName.get(p.resource)!.push(p);
560 for (const name of p.exports) {
561 if (!byExport.has(name)) byExport.set(name, []);
562 byExport.get(name)!.push(p);
563 }
564 }
565 const providers = new Set(pages.map((p) => p.provider));
566​
567 return (fromDir: string) => {
568 const fromProvider = fromDir.split("/")[0] ?? "";
569​
570 const lookup = (name: string, provider?: string): PageEntry | undefined => {
571 const scope = (list: PageEntry[] | undefined) =>
572 (list ?? []).filter((c) => !provider || c.provider === provider);
573 const named = scope(byName.get(name));
574 const exporting = scope(byExport.get(name));
575​
576 const sameDirNamed = named.filter((c) => c.dir === fromDir);
577 if (sameDirNamed.length === 1) return sameDirNamed[0];
578 const sameDirExporting = exporting.filter((c) => c.dir === fromDir);
579 if (sameDirExporting.length === 1) return sameDirExporting[0];
580 const providerNamed = named.filter((c) => c.provider === fromProvider);
581 if (providerNamed.length === 1) return providerNamed[0];
582 const providerExporting = exporting.filter(
583 (c) => c.provider === fromProvider,
584 );
585 if (providerExporting.length === 1) return providerExporting[0];
586 if (named.length === 1) return named[0];
587 return undefined;
588 };
589​
590 return (target: string) => {
591 // Strip a `#member` suffix — the link lands on the owning resource page.
592 const base = target.split("#")[0];
593​
594 const attempts: { name: string; provider?: string }[] = [{ name: base }];
595 if (base.includes(".")) {
596 const segments = base.split(".");
597 const first = segments[0];
598 const last = segments[segments.length - 1];
599 if (providers.has(first)) {
600 // Provider-qualified: `Cloudflare.Worker`, `Cloudflare.KV.Namespace`.
601 attempts.push({ name: last, provider: first });
602 } else {
603 // Member access on a symbol: `KeyPairProps.publicKeyMaterial`.
604 attempts.push({ name: first });
605 if (first.endsWith("Props")) {
606 attempts.push({ name: first.slice(0, -"Props".length) });
607 }
608 }
609 } else if (base.endsWith("Props")) {
610 attempts.push({ name: base.slice(0, -"Props".length) });
611 }
612​
613 for (const attempt of attempts) {
614 const found = lookup(attempt.name, attempt.provider);
615 if (found) return found.link;
616 }
617 return undefined;
618 };
619 };
621​
622const isUrl = (target: string) => /^https?:\/\//.test(target);
623​
624/**
625 * Replace `{@link ...}` tags with markdown links, skipping fenced code
626 * blocks. Symbols that don't resolve to a generated page render as inline
627 * code (or their label) instead of leaking the raw tag.
628 */
629/** Symbol targets that didn't resolve to a page, for the end-of-run summary. */
630const unresolvedLinkTargets = new Map<string, number>();
631​
632function linkifyMarkdown(markdown: string, resolve: LinkResolver): string {
633 const replaceTags = (chunk: string) =>
634 chunk.replace(LINK_TAG_RE, (_, inner: string) => {
635 // A tag wrapped across source lines carries the line break in its
636 // label — collapse it so the markdown link stays intact.
637 const parsed = parseLinkTag(inner.replace(/\s+/g, " "));
638 const label = parsed.label;
639 if (isUrl(parsed.target)) {
640 return `[${label ?? parsed.target}](${parsed.target})`;
641 }
642 const target = normalizeLinkTarget(parsed.target);
643 const url = resolve(target);
644 if (!url) {
645 unresolvedLinkTargets.set(
646 target,
647 (unresolvedLinkTargets.get(target) ?? 0) + 1,
648 );
649 }
650 const text = label ?? `\`${target}\``;
651 return url ? `[${text}](${url})` : text;
652 });
653​
654 // Apply across contiguous non-fence chunks (a `{@link}` may span lines);
655 // leave fenced code blocks untouched.
656 const out: string[] = [];
657 let chunk: string[] = [];
658 let insideFence = false;
659 const flushChunk = () => {
660 if (chunk.length > 0) {
661 out.push(replaceTags(chunk.join("\n")));
662 chunk = [];
663 }
664 };
665 for (const line of markdown.split("\n")) {
666 if (line.trim().startsWith("```")) {
667 if (!insideFence) flushChunk();
668 insideFence = !insideFence;
669 out.push(line);
670 continue;
671 }
672 if (insideFence) {
673 out.push(line);
674 } else {
675 chunk.push(line);
676 }
677 }
678 flushChunk();
679 return out.join("\n");
681​
682/** Reduce `{@link ...}` tags to plain text for frontmatter descriptions. */
683function stripLinkTags(text: string): string {
684 return text.replace(LINK_TAG_RE, (_, inner: string) => {
685 const { target, label } = parseLinkTag(inner.replace(/\s+/g, " "));
686 return (label ?? normalizeLinkTarget(target)).replace(/`/g, "");
687 });
689​
690function yamlString(value: string): string {
691 if (/[\n:"{}[\],&*?|>!%@`#]/.test(value) || value.trim() !== value) {
692 return JSON.stringify(value);
693 }
694 return value;
696​
697function firstParagraph(value: string): string {
698 const idx = value.indexOf("\n\n");
699 const para = idx === -1 ? value : value.slice(0, idx);
700 return para.replace(/\s+/g, " ").trim();
702​
703function renderPageBody(doc: PageDoc): string {
704 const parts: string[] = [];
705​
706 if (doc.summary) {
707 parts.push(doc.summary);
708 }
709​
710 for (const section of doc.sections) {
711 const secParts = [`## ${section.title}`];
712 if (section.description) {
713 secParts.push(section.description);
714 }
715 for (const example of section.examples) {
716 if (section.examples.length > 1) {
717 secParts.push(`**${example.title}**`);
718 }
719 secParts.push(example.body);
720 }
721 parts.push(secParts.join("\n\n"));
722 }
723​
724 return parts.join("\n\n");
726​
727function renderPage(doc: PageDoc, resolve: LinkResolver): string {
728 const description =
729 stripLinkTags(firstParagraph(doc.summary)) ||
730 `API reference for ${doc.title}`;
731 const frontmatter = [
732 "---",
733 `title: ${yamlString(doc.title)}`,
734 `description: ${yamlString(description)}`,
735 // Generated reference pages are ~4k near-identical one-paragraph +
736 // one-snippet stubs (92% of the site). Indexed as separate documents
737 // they read as programmatic thin content, dilute crawl budget, and are
738 // what surfaces as "random" search results instead of the hub and
739 // guide pages. Keep them navigable and crawlable (`follow`) but out of
740 // search indexes; the sitemap integration drops any page carrying this
741 // meta. Revisit once pages are consolidated per service / carry real
742 // prose — this is the only line to change.
743 "head:",
744 " - tag: meta",
745 " attrs:",
746 " name: robots",
747 ' content: "noindex, follow"',
748 "---",
749 ].join("\n");
750​
751 const headerLines = [`> **Source:** \`${doc.sourceDisplay}\``];
752 if (doc.isLayer) {
753 const meta = ["**Kind:** Layer"];
754 if (doc.provides.length > 0) {
755 meta.push(
756 `**Provides:** ${doc.provides.map((tag) => `\`${tag}\``).join(", ")}`,
757 );
758 }
759 if (doc.peers.length > 0) {
760 meta.push(
761 `**Peer dependencies:** ${doc.peers
762 .map((peer) => `\`${peer}\``)
763 .join(", ")}`,
764 );
765 }
766 headerLines.push(`> ${meta.join(" · ")}`);
767 }
768 const sourceBlock = headerLines.join("\n");
769 const body = linkifyMarkdown(renderPageBody(doc).trim(), resolve);
770​
771 if (body) {
772 return `${frontmatter}\n\n${sourceBlock}\n\n${body}\n`;
773 }
774 return `${frontmatter}\n\n${sourceBlock}\n`;
776​
777/** Providers shown first in the sidebar; the rest follow alphabetically. */
778const PROVIDER_ORDER = ["AWS", "Cloudflare"];
779​
780/**
781 * Uncategorized providers with at most this many pages render as a flat
782 * resource list instead of per-service folders (see buildProvidersSidebar).
783 */
784const FLAT_PROVIDER_MAX_PAGES = 16;
785​
786interface SidebarLeaf {
787 label: string;
788 link: string;
790interface SidebarGroup {
791 label: string;
792 collapsed: true;
793 items: SidebarItem[];
795type SidebarItem = SidebarLeaf | SidebarGroup;
796​
797interface PageEntry {
798 provider: string;
799 service: string;
800 resource: string;
801 category: string;
802 product: string;
803 link: string;
804 /** Source directory relative to srcRoot (slash-normalized), e.g. `Cloudflare/KV`. */
805 dir: string;
806 /** All names the page's source file exports — `{@link}` targets documented on this page. */
807 exports: string[];
809​
810const byLabel = (a: { label: string }, b: { label: string }) =>
811 a.label.localeCompare(b.label);
812​
813function orderedKeys(keys: string[], order: string[]): string[] {
814 const ranked = keys.filter((k) => order.includes(k));
815 ranked.sort((a, b) => order.indexOf(a) - order.indexOf(b));
816 const rest = keys.filter((k) => !order.includes(k)).sort();
817 return [...ranked, ...rest];
819​
820/**
821 * Build sidebar items for one set of pages sharing a provider+category:
822 * every product is its own collapsible folder containing its resource
823 * pages, mirroring how Cloudflare's API reference gives each product its
824 * own section — even single-page products like D1 or Organization — so
825 * the grouping is uniform.
826 *
827 * Grouping is by resolved product LABEL (`@product`, falling back to the
828 * service dir name), not by directory: two directories declaring the same
829 * product merge into one group instead of rendering duplicate siblings.
830 *
831 * A group that would hold exactly one page named the same as the group
832 * (a flat provider dir where the label falls back to the resource name,
833 * e.g. "Certificate > Certificate") carries no information — collapse it
834 * to a plain leaf. Genuine single-page products keep their folder (the
835 * label differs, e.g. Cloudflare's "D1 > Database").
836 */
837function buildServiceItems(pages: PageEntry[]): SidebarItem[] {
838 const byLabelKey = new Map<string, PageEntry[]>();
839 for (const p of pages) {
840 const key = p.product || p.service || p.resource;
841 if (!byLabelKey.has(key)) byLabelKey.set(key, []);
842 byLabelKey.get(key)!.push(p);
843 }
844 const items: SidebarItem[] = [];
845 for (const [label, productPages] of byLabelKey) {
846 if (productPages.length === 1 && productPages[0].resource === label) {
847 items.push({ label, link: productPages[0].link });
848 continue;
849 }
850 items.push({
851 label,
852 collapsed: true,
853 items: productPages
854 .map((p) => ({ label: p.resource, link: p.link }))
855 .sort(byLabel),
856 });
857 }
858 return items.sort(byLabel);
860​
861function buildProvidersSidebar(entries: PageEntry[]): SidebarItem[] {
862 const byProvider = new Map<string, PageEntry[]>();
863 for (const e of entries) {
864 if (!byProvider.has(e.provider)) byProvider.set(e.provider, []);
865 byProvider.get(e.provider)!.push(e);
866 }
867​
868 const providers: SidebarGroup[] = [];
869 for (const provider of orderedKeys([...byProvider.keys()], PROVIDER_ORDER)) {
870 const pages = byProvider.get(provider)!;
871​
872 // `@category` is per-file; a documented file that omits it must not fall
873 // out of its service's category and render a duplicate service group at
874 // the provider root. Inherit the category any sibling page of the same
875 // service dir declares.
876 const categoryByService = new Map<string, string>();
877 for (const p of pages) {
878 if (p.service && p.category && !categoryByService.has(p.service)) {
879 categoryByService.set(p.service, p.category);
880 }
881 }
882​
883 const categorized = new Map<string, PageEntry[]>();
884 const uncategorized: PageEntry[] = [];
885 for (const p of pages) {
886 const category = p.category || categoryByService.get(p.service) || "";
887 if (category) {
888 if (!categorized.has(category)) categorized.set(category, []);
889 categorized.get(category)!.push(p);
890 } else {
891 uncategorized.push(p);
892 }
893 }
894​
895 const items: SidebarItem[] = [];
896 for (const cat of [...categorized.keys()].sort((a, b) =>
897 a.localeCompare(b),
898 )) {
899 items.push({
900 label: cat,
901 collapsed: true,
902 items: buildServiceItems(categorized.get(cat)!),
903 });
904 }
905 if (categorized.size === 0 && pages.length <= FLAT_PROVIDER_MAX_PAGES) {
906 // Small uncategorized providers (Neon, Planetscale, Axiom, GitHub, …)
907 // render as a flat resource list — per-service folders around one or
908 // two pages ("Branch > Branch") are redundant nesting, and prefixed
909 // resource names (MySQLBranch/PostgresBranch) already carry the
910 // grouping information.
911 items.push(
912 ...uncategorized
913 .map((p) => ({ label: p.resource, link: p.link }))
914 .sort(byLabel),
915 );
916 } else {
917 // Pages without a category fall back to service grouping directly under
918 // the provider (this is how AWS renders until it gets categorized).
919 items.push(...buildServiceItems(uncategorized));
920 }
921​
922 providers.push({ label: provider, collapsed: true, items });
923 }
924​
925 assertNoDuplicateSiblings(providers, []);
926 return providers;
928​
929/**
930 * Duplicate sibling labels are always a tagging bug (e.g. two products
931 * resolving to the same name in one category) and render as confusing
932 * twin sections — fail the generation instead of shipping them.
933 */
934function assertNoDuplicateSiblings(items: SidebarItem[], path: string[]) {
935 const seen = new Map<string, number>();
936 for (const item of items) {
937 seen.set(item.label, (seen.get(item.label) ?? 0) + 1);
938 }
939 const dups = [...seen.entries()].filter(([, n]) => n > 1);
940 if (dups.length > 0) {
941 throw new Error(
942 `Duplicate sidebar sibling label(s) under "${path.join(" > ") || "(root)"}": ${dups
943 .map(([label, n]) => `"${label}" ×${n}`)
944 .join(", ")} — fix the @product/@category tags on the offending files.`,
945 );
946 }
947 for (const item of items) {
948 if ("items" in item) {
949 assertNoDuplicateSiblings(item.items, [...path, item.label]);
950 }
951 }
953​
954async function main() {
955 await fs.rm(config.outRoot, { recursive: true, force: true });
956 await fs.mkdir(config.outRoot, { recursive: true });
957​
958 const seen = new Map<string, string>();
959 const pageEntries: PageEntry[] = [];
960 const pending: { outputRelative: string; doc: PageDoc }[] = [];
961 let written = 0;
962 let skipped = 0;
963​
964 for (const root of config.roots) {
965 const entries = await discoverFiles(root);
966 console.log(
967 `Discovered ${entries.length} source files in ${normalizeSlashes(
968 path.relative(path.join(import.meta.dir, ".."), root.srcRoot),
969 )}.`,
970 );
971​
972 await using syntax = await createSyntaxProject(
973 entries.map((entry) => entry.absolutePath),
974 );
975​
976 for (const entry of entries) {
977 const sourceFile = await syntax.project.program.getSourceFile(
978 entry.absolutePath,
979 );
980 if (!sourceFile) {
981 throw new Error(`Missing source file ${entry.absolutePath}`);
982 }
983​
984 const primary = findTaggedPrimary(sourceFile);
985 if (!primary) {
986 skipped++;
987 continue;
988 }
989​
990 // Only emit a page when there's actual documented content; a bare
991 // frontmatter + source link stub is noise.
992 if (!primary.doc.summary && primary.doc.sections.length === 0) {
993 skipped++;
994 continue;
995 }
996​
997 // Mirror the source directory structure; name the page after the
998 // tagged declaration (e.g. Cloudflare.AI.Search/AiSearchInstance.md).
999 const relDir = path.dirname(entry.relativePath);
1000 const outputRelative = path.join(relDir, `${primary.name}.md`);
1001​
1002 const existing = seen.get(outputRelative);
1003 if (existing) {
1004 console.warn(
1005 ` collision: ${outputRelative} from ${entry.relativePath} (already from ${existing})`,
1006 );
1008 seen.set(outputRelative, entry.relativePath);
1009​
1010 const doc: PageDoc = {
1011 title: primary.name,
1012 sourceDisplay: entry.sourceDisplay,
1013 summary: primary.doc.summary,
1014 sections: primary.doc.sections,
1015 isLayer: primary.doc.hasLayerTag,
1016 provides: primary.doc.provides,
1017 peers: primary.doc.peers,
1018 };
1019 pending.push({ outputRelative, doc });
1020​
1021 const exportNames = exportedNames(sourceFile);
1022​
1023 const segments = normalizeSlashes(outputRelative).split("/");
1024 pageEntries.push({
1025 provider: segments[0] ?? "",
1026 service: segments.length > 2 ? segments[1] : "",
1027 resource: primary.name,
1028 category: primary.category,
1029 product: primary.product,
1030 link: `/providers/${normalizeSlashes(outputRelative)
1031 .replace(/\.md$/, "")
1032 .toLowerCase()}`,
1033 dir: normalizeSlashes(relDir),
1034 exports: exportNames,
1035 });
1038​
1039 // Second pass: render with `{@link}` resolution — the full page set must be
1040 // known before symbol targets can resolve to their pages.
1041 const resolverFor = makeLinkResolverFactory(pageEntries);
1042 for (const page of pending) {
1043 const resolve = resolverFor(
1044 normalizeSlashes(path.dirname(page.outputRelative)),
1045 );
1046 const outputPath = path.join(config.outRoot, page.outputRelative);
1047 await fs.mkdir(path.dirname(outputPath), { recursive: true });
1048 await fs.writeFile(outputPath, renderPage(page.doc, resolve), "utf8");
1049 written++;
1051​
1052 const sidebar = buildProvidersSidebar(pageEntries);
1053​
1054 // Landing page for the Reference tab (/providers): a provider directory.
1055 // Each provider's reference belongs to its docs hub — the directory just
1056 // routes there (or into the tree, for providers without a hub). The
1057 // ProviderDirectory component reads the generated sidebar for counts.
1058 // Regenerated with the rest of the tree on every run.
1059 const referenceIndex = [
1060 "---",
1061 "title: API Reference",
1062 "description: Every provider alchemy can manage — pick a provider to open its docs hub and resource reference.",
1063 "---",
1064 "",
1065 'import ProviderDirectory from "../../../components/ProviderDirectory.astro";',
1066 "",
1067 "Every resource alchemy can manage, documented from the source JSDoc and",
1068 "organized by provider. A provider's reference lives in its docs hub —",
1069 "pick one below, or search with `⌘K`.",
1070 "",
1071 "<ProviderDirectory />",
1072 "",
1073 ].join("\n");
1074 await fs.rm(path.join(config.outRoot, "index.md"), { force: true });
1075 await fs.writeFile(
1076 path.join(config.outRoot, "index.mdx"),
1077 referenceIndex,
1078 "utf8",
1079 );
1080​
1081 const sidebarPath = path.join(
1082 websiteRoot,
1083 "src/generated/providers-sidebar.json",
1084 );
1085 await fs.mkdir(path.dirname(sidebarPath), { recursive: true });
1086 await fs.writeFile(
1087 sidebarPath,
1088 `${JSON.stringify(sidebar, null, 2)}\n`,
1089 "utf8",
1090 );
1091​
1092 console.log(
1093 `Done. Wrote ${written} resource pages (skipped ${skipped} untagged) to ${normalizeSlashes(
1094 path.relative(path.join(import.meta.dir, ".."), config.outRoot),
1095 )}.`,
1096 );
1097 if (unresolvedLinkTargets.size > 0) {
1098 const list = [...unresolvedLinkTargets.entries()]
1099 .sort((a, b) => b[1] - a[1])
1100 .map(([target, n]) => (n > 1 ? `${target} ×${n}` : target))
1101 .join(", ");
1102 console.log(
1103 `{@link} targets without a page (rendered as inline code): ${list}`,
1104 );
1106 console.log(
1107 `Wrote provider sidebar to ${normalizeSlashes(
1108 path.relative(path.join(import.meta.dir, ".."), sidebarPath),
1109 )}.`,
1110 );
1112​
1113if (import.meta.main) await main();