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

generate-api-reference.ts

1,053 lines32.6 KB

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