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

generate-api-reference.ts

546 lines15.3 KB

1import * as fs from "node:fs/promises";
2import * as path from "node:path";
3​
4import {
5 Node,
6 Project,
7 SyntaxKind,
8 type JSDoc,
9 type SourceFile,
10} from "ts-morph";
11​
12const websiteRoot = path.join(import.meta.dir, "../website");
13​
14const config = {
15 srcRoot: path.join(import.meta.dir, "../packages/alchemy/src"),
16 outRoot: path.join(websiteRoot, "src/content/docs/providers"),
17 tsConfig: path.join(import.meta.dir, "../packages/alchemy/tsconfig.json"),
18 excludeFile(baseName: string): boolean {
19 if (baseName === "index.ts") return true;
20 if (/^[a-z]/.test(baseName)) return true;
21 return false;
22 },
23};
24​
25interface FileEntry {
26 relativePath: string;
27 absolutePath: string;
28 outputPath: string;
30​
31interface ExampleBlock {
32 title: string;
33 body: string;
35​
36interface ExampleSection {
37 title: string;
38 description: string;
39 examples: ExampleBlock[];
41​
42interface PageDoc {
43 title: string;
44 relativePath: string;
45 summary: string;
46 sections: ExampleSection[];
48​
49const normalizeSlashes = (value: string) => value.split(path.sep).join("/");
50​
51async function discoverFiles(): Promise<FileEntry[]> {
52 const entries: FileEntry[] = [];
53​
54 const topLevelEntries = await fs.readdir(config.srcRoot, {
55 withFileTypes: true,
56 });
57 const dirs = topLevelEntries
58 .filter((entry) => entry.isDirectory())
59 .map((entry) => entry.name);
60​
61 for (const dir of dirs) {
62 const dirPath = path.join(config.srcRoot, dir);
63 let files: string[];
64 try {
65 files = (await fs.readdir(dirPath, { recursive: true })) as string[];
66 } catch {
67 continue;
68 }
69​
70 for (const file of files) {
71 const baseName = path.basename(file);
72 if (!baseName.endsWith(".ts") && !baseName.endsWith(".tsx")) continue;
73 if (baseName.endsWith(".d.ts")) continue;
74 if (config.excludeFile(baseName)) continue;
75​
76 const relativePath = path.join(dir, file);
77 const parts = normalizeSlashes(relativePath).split("/");
78 const cloud = parts[0];
79 const service = parts.length >= 3 ? parts[1] : undefined;
80 const resource = path.basename(file, path.extname(file));
81​
82 let outputRelative: string;
83 if (cloud === "Cloudflare") {
84 outputRelative = path.join(cloud, `${resource}.md`);
85 } else if (service) {
86 outputRelative = path.join(cloud, service, `${resource}.md`);
87 } else {
88 outputRelative = path.join(cloud, `${resource}.md`);
89 }
90​
91 entries.push({
92 relativePath,
93 absolutePath: path.join(config.srcRoot, relativePath),
94 outputPath: path.join(config.outRoot, outputRelative),
95 });
96 }
97 }
98​
99 entries.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
100 return entries;
102​
103function getJsDocBlocks(node: Node): JSDoc[] {
104 const getter = (node as Node & { getJsDocs?: () => JSDoc[] }).getJsDocs;
105 return getter ? getter.call(node) : [];
107​
108function cleanDocComment(raw: string): string {
109 return raw
110 .replace(/^\/\*\*?/, "")
111 .replace(/\*\/$/, "")
112 .split("\n")
113 .map((line) => line.replace(/^\s*\*\s?/, ""))
114 .join("\n");
116​
117interface ParsedJSDoc {
118 summary: string;
119 sections: ExampleSection[];
120 hasResourceTag: boolean;
121 hasBindingTag: boolean;
123​
124function parseJSDoc(node: Node): ParsedJSDoc {
125 const docs = getJsDocBlocks(node);
126 if (docs.length === 0) {
127 return {
128 summary: "",
129 sections: [],
130 hasResourceTag: false,
131 hasBindingTag: false,
132 };
133 }
134​
135 const clean = cleanDocComment(docs.map((doc) => doc.getText()).join("\n"));
136 const lines = clean.split("\n");
137​
138 const summaryLines: string[] = [];
139 const sections: ExampleSection[] = [];
140 let hasResourceTag = false;
141 let hasBindingTag = false;
142 let sawTag = false;
143 let currentSection: ExampleSection | undefined;
144 let currentExample: ExampleBlock | undefined;
145​
146 let sectionDescLines: string[] = [];
147 let collectingSectionDesc = false;
148​
149 const flushExample = () => {
150 if (!currentExample) return;
151 currentExample.body = currentExample.body.trim();
152 if (!currentSection) {
153 currentSection = { title: "Examples", description: "", examples: [] };
154 sections.push(currentSection);
155 }
156 currentSection.examples.push(currentExample);
157 currentExample = undefined;
158 };
159​
160 const flushSectionDesc = () => {
161 if (currentSection && sectionDescLines.length > 0) {
162 currentSection.description = sectionDescLines.join("\n").trim();
163 }
164 sectionDescLines = [];
165 collectingSectionDesc = false;
166 };
167​
168 for (const line of lines) {
169 const tag = line.trimEnd().match(/^@(\w+)\s*(.*)$/);
170 if (tag) {
171 sawTag = true;
172 const [, name, rest] = tag;
173 const value = (rest ?? "").trim();
174 switch (name) {
175 case "resource":
176 hasResourceTag = true;
177 break;
178 case "binding":
179 hasBindingTag = true;
180 break;
181 case "section":
182 flushExample();
183 flushSectionDesc();
184 currentSection = {
185 title: value || "Examples",
186 description: "",
187 examples: [],
188 };
189 sections.push(currentSection);
190 collectingSectionDesc = true;
191 break;
192 case "example":
193 flushSectionDesc();
194 flushExample();
195 currentExample = { title: value || "Example", body: "" };
196 break;
197 }
198 continue;
199 }
200​
201 if (!sawTag) {
202 summaryLines.push(line);
203 continue;
204 }
205​
206 if (currentExample) {
207 currentExample.body += `${line}\n`;
208 } else if (collectingSectionDesc) {
209 sectionDescLines.push(line);
210 }
211 }
212​
213 flushSectionDesc();
214 flushExample();
215​
216 return {
217 summary: summaryLines.join("\n").trim(),
218 sections,
219 hasResourceTag,
220 hasBindingTag,
221 };
223​
224function findPrimaryJSDoc(sourceFile: SourceFile): ParsedJSDoc {
225 for (const decl of sourceFile.getVariableDeclarations()) {
226 if (!decl.isExported()) continue;
227 const init = decl.getInitializerIfKind(SyntaxKind.CallExpression);
228 const expr = init?.getExpression().getText();
229 if (expr === "Resource" || expr === "Host" || expr === "Platform") {
230 const stmt = decl.getVariableStatement();
231 if (stmt) {
232 const jsdoc = parseJSDoc(stmt);
233 if (jsdoc.summary || jsdoc.sections.length > 0 || jsdoc.hasResourceTag)
234 return jsdoc;
235 }
236 }
237 }
238​
239 for (const cls of sourceFile.getClasses()) {
240 if (!cls.isExported()) continue;
241 const jsdoc = parseJSDoc(cls);
242 if (
243 jsdoc.hasResourceTag ||
244 jsdoc.hasBindingTag ||
245 jsdoc.sections.length > 0
246 )
247 return jsdoc;
248 if (jsdoc.summary) return jsdoc;
249 }
250​
251 let firstWithSummary: ParsedJSDoc | undefined;
252 for (const stmt of sourceFile.getStatements()) {
253 if (Node.isExportable(stmt) && stmt.isExported()) {
254 const jsdoc = parseJSDoc(stmt);
255 if (
256 jsdoc.hasResourceTag ||
257 jsdoc.hasBindingTag ||
258 jsdoc.sections.length > 0
259 )
260 return jsdoc;
261 if (!firstWithSummary && jsdoc.summary) firstWithSummary = jsdoc;
262 }
263 }
264​
265 if (firstWithSummary) return firstWithSummary;
266​
267 const rawJSDocBlocks = sourceFile.getFullText().match(/\/\*\*[\s\S]*?\*\//g);
268 if (rawJSDocBlocks) {
269 for (const block of rawJSDocBlocks) {
270 if (
271 block.includes("@section") ||
272 block.includes("@resource") ||
273 block.includes("@binding")
274 ) {
275 const clean = cleanDocComment(block);
276 const lines = clean.split("\n");
277 const summaryLines: string[] = [];
278 const sections: ExampleSection[] = [];
279 let hasResourceTag = false;
280 let hasBindingTag = false;
281 let sawTag = false;
282 let currentSection: ExampleSection | undefined;
283 let currentExample: ExampleBlock | undefined;
284 let sectionDescLines: string[] = [];
285 let collectingSectionDesc = false;
286​
287 const flushExample = () => {
288 if (!currentExample) return;
289 currentExample.body = currentExample.body.trim();
290 if (!currentSection) {
291 currentSection = {
292 title: "Examples",
293 description: "",
294 examples: [],
295 };
296 sections.push(currentSection);
297 }
298 currentSection.examples.push(currentExample);
299 currentExample = undefined;
300 };
301​
302 const flushSectionDesc = () => {
303 if (currentSection && sectionDescLines.length > 0) {
304 currentSection.description = sectionDescLines.join("\n").trim();
305 }
306 sectionDescLines = [];
307 collectingSectionDesc = false;
308 };
309​
310 for (const line of lines) {
311 const tag = line.trimEnd().match(/^@(\w+)\s*(.*)$/);
312 if (tag) {
313 sawTag = true;
314 const [, name, rest] = tag;
315 const value = (rest ?? "").trim();
316 switch (name) {
317 case "resource":
318 hasResourceTag = true;
319 break;
320 case "binding":
321 hasBindingTag = true;
322 break;
323 case "section":
324 flushExample();
325 flushSectionDesc();
326 currentSection = {
327 title: value || "Examples",
328 description: "",
329 examples: [],
330 };
331 sections.push(currentSection);
332 collectingSectionDesc = true;
333 break;
334 case "example":
335 flushSectionDesc();
336 flushExample();
337 currentExample = { title: value || "Example", body: "" };
338 break;
339 }
340 continue;
341 }
342 if (!sawTag) {
343 summaryLines.push(line);
344 continue;
345 }
346 if (currentExample) {
347 currentExample.body += `${line}\n`;
348 } else if (collectingSectionDesc) {
349 sectionDescLines.push(line);
350 }
351 }
352 flushSectionDesc();
353 flushExample();
354​
355 const summary = summaryLines.join("\n").trim();
356 if (summary || sections.length > 0) {
357 return { summary, sections, hasResourceTag, hasBindingTag };
358 }
359 }
360 }
361 }
362​
363 return {
364 summary: "",
365 sections: [],
366 hasResourceTag: false,
367 hasBindingTag: false,
368 };
370​
371function isResourceFile(sourceFile: SourceFile): boolean {
372 const fullText = sourceFile.getFullText();
373​
374 if (/^\s*\*\s*@internal\s*$/m.test(fullText)) {
375 const blocks = fullText.match(/\/\*\*[\s\S]*?\*\//g) || [];
376 for (const block of blocks) {
377 if (!/^\s*\*\s*@internal\s*$/m.test(block)) continue;
378 const end = fullText.indexOf(block) + block.length;
379 const after = fullText.slice(end).trimStart();
380 if (after.startsWith("export ")) return false;
381 }
382 }
383​
384 if (fullText.includes("@resource") || fullText.includes("@binding"))
385 return true;
386​
387 const text = sourceFile.getFullText();
388 if (text.includes("Binding.Service<") || text.includes("Binding.Policy<")) {
389 if (
390 !text.includes("= Resource<") &&
391 !text.includes("extends Resource<") &&
392 !text.includes("= Host<") &&
393 !text.includes("extends Host<") &&
394 !text.includes("Platform(")
395 ) {
396 return false;
397 }
398 }
399​
400 for (const decl of sourceFile.getVariableDeclarations()) {
401 if (!decl.isExported()) continue;
402 const init = decl.getInitializerIfKind(SyntaxKind.CallExpression);
403 if (!init) continue;
404 const expr = init.getExpression().getText();
405 if (expr === "Resource" || expr === "Host" || expr === "Platform")
406 return true;
407 const innerCall = init.getExpression();
408 if (Node.isCallExpression(innerCall)) {
409 const innerExpr = innerCall.getExpression().getText();
410 if (innerExpr === "Resource" || innerExpr === "Host") return true;
411 }
412 }
413 for (const iface of sourceFile.getInterfaces()) {
414 if (!iface.isExported()) continue;
415 const hasResourceHeritage = iface
416 .getHeritageClauses()
417 .flatMap((clause) => clause.getTypeNodes())
418 .some((typeNode) => {
419 const expr = typeNode.getExpression().getText();
420 return expr === "Resource" || expr === "Host";
421 });
422 if (hasResourceHeritage) return true;
423 }
424 for (const typeAlias of sourceFile.getTypeAliases()) {
425 if (!typeAlias.isExported()) continue;
426 const typeText = typeAlias.getTypeNode()?.getText() ?? "";
427 if (typeText.startsWith("Resource<") || typeText.startsWith("Host<")) {
428 return true;
429 }
430 }
431 return false;
433​
434function parseFile(sourceFile: SourceFile, relativePath: string): PageDoc {
435 const baseName = path.basename(relativePath, path.extname(relativePath));
436 const primary = findPrimaryJSDoc(sourceFile);
437​
438 return {
439 title: baseName,
440 relativePath,
441 summary: primary.summary,
442 sections: primary.sections,
443 };
445​
446function yamlString(value: string): string {
447 if (/[\n:"{}[\],&*?|>!%@`#]/.test(value) || value.trim() !== value) {
448 return JSON.stringify(value);
449 }
450 return value;
452​
453function firstParagraph(value: string): string {
454 const idx = value.indexOf("\n\n");
455 const para = idx === -1 ? value : value.slice(0, idx);
456 return para.replace(/\s+/g, " ").trim();
458​
459function renderPageBody(doc: PageDoc): string {
460 const parts: string[] = [];
461​
462 if (doc.summary) {
463 parts.push(doc.summary);
464 }
465​
466 for (const section of doc.sections) {
467 const secParts = [`## ${section.title}`];
468 if (section.description) {
469 secParts.push(section.description);
470 }
471 for (const example of section.examples) {
472 if (section.examples.length > 1) {
473 secParts.push(`**${example.title}**`);
474 }
475 secParts.push(example.body);
476 }
477 parts.push(secParts.join("\n\n"));
478 }
479​
480 return parts.join("\n\n");
482​
483function renderPage(doc: PageDoc): string {
484 const sourcePath = `src/${normalizeSlashes(doc.relativePath)}`;
485 const description =
486 firstParagraph(doc.summary) || `API reference for ${doc.title}`;
487 const frontmatter = [
488 "---",
489 `title: ${yamlString(doc.title)}`,
490 `description: ${yamlString(description)}`,
491 "---",
492 ].join("\n");
493​
494 const sourceBlock = `> **Source:** \`${sourcePath}\``;
495 const body = renderPageBody(doc).trim();
496​
497 if (body) {
498 return `${frontmatter}\n\n${sourceBlock}\n\n${body}\n`;
499 }
500 return `${frontmatter}\n\n${sourceBlock}\n`;
502​
503async function main() {
504 const entries = await discoverFiles();
505 console.log(`Discovered ${entries.length} source files.`);
506​
507 const project = new Project({
508 tsConfigFilePath: config.tsConfig,
509 skipFileDependencyResolution: true,
510 });
511​
512 await fs.rm(config.outRoot, { recursive: true, force: true });
513 await fs.mkdir(config.outRoot, { recursive: true });
514​
515 const resourceEntries: FileEntry[] = [];
516 for (const entry of entries) {
517 const sourceFile = project.getSourceFile(entry.absolutePath);
518 if (!sourceFile) {
519 console.warn(` skipped: ${entry.relativePath}`);
520 continue;
521 }
522 if (!isResourceFile(sourceFile)) continue;
523 resourceEntries.push(entry);
524 }
525​
526 console.log(
527 `Filtered to ${resourceEntries.length} documented files (excluded ${entries.length - resourceEntries.length} unannotated files).`,
528 );
529​
530 let written = 0;
531 for (const entry of resourceEntries) {
532 const sourceFile = project.getSourceFile(entry.absolutePath)!;
533 const doc = parseFile(sourceFile, entry.relativePath);
534​
535 await fs.mkdir(path.dirname(entry.outputPath), { recursive: true });
536 await fs.writeFile(entry.outputPath, renderPage(doc), "utf8");
537​
538 written++;
539 }
540​
541 console.log(
542 `Done. Wrote ${written} resource pages to ${normalizeSlashes(path.relative(path.join(import.meta.dir, ".."), config.outRoot))}.`,
543 );
545​
546await main();