forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocs-render.tsx
More file actions
964 lines (891 loc) · 36.6 KB
/
Copy pathdocs-render.tsx
File metadata and controls
964 lines (891 loc) · 36.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
// Shared helpers for rendering MDX docs pages. Pulled out of
// `app/docs/[[...slug]]/page.tsx` so both the classic `/docs/<slug>`
// route and the new `/<framework>/<slug>` catch-all can share the same
// nav-tree builder, snippet inliner, and component map.
//
// Only the pieces that don't depend on the rendered React tree live
// here; the big `components` map still lives alongside the docs page
// for now so it can import client components without circular issues.
import fs from "fs";
import path from "path";
import matter from "gray-matter";
import { resolveWithinDir } from "./safe-fs";
export const CONTENT_DIR = path.join(process.cwd(), "src/content/docs");
export const SNIPPETS_DIR = path.join(CONTENT_DIR, "..", "snippets");
// Re-exported from lib/framework-categories so client components can
// pull the constant without dragging fs through the bundle.
export {
FRAMEWORK_CATEGORY_ORDER,
type FrameworkCategory,
} from "./framework-categories";
// ---------------------------------------------------------------------------
// Nav tree types
// ---------------------------------------------------------------------------
export type NavNode =
| { type: "page"; title: string; slug: string }
| { type: "section"; title: string }
| { type: "group"; title: string; slug: string; children: NavNode[] };
/**
* Extract the frontmatter block (content between leading `---` fences)
* from a raw MDX/Markdown source. Returns empty string when the file
* has no frontmatter. Used to scope frontmatter regexes so we don't
* accidentally match `title:` or `description:` that happen to appear
* inside the MDX body.
*/
function extractFrontmatter(raw: string): string {
// Accept both LF and CRLF line endings so Windows-authored MDX
// doesn't silently bypass frontmatter extraction.
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
return fmMatch?.[1] ?? "";
}
// Escape text for safe interpolation into an HTML attribute/text context.
// Duplicated here (rather than imported from components/snippet.tsx) to
// keep docs-render server-only / framework-free — snippet.tsx is a
// client component and importing it here would pull client code into
// the server bundle. If this ever grows, extract to a shared util.
export function escapeHtml(s: string): string {
return s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """)
.replace(/'/g, "'");
}
// Process-scoped memoization for frequently-called filesystem readers.
// buildNavTree walks the entire content tree on every page render and
// calls readTitle / readMeta O(pages) times per request. Without this
// cache each call reopens and re-parses the file from disk.
//
// Production / build: cache the entire process lifetime — content is
// frozen at deploy time so stale reads aren't possible.
//
// Development: skip the cache so meta.json / frontmatter edits show up
// in the sidebar nav without restarting the dev server. The
// performance hit is acceptable for local dev (the request path
// already does plenty of fs work for MDX rendering).
//
// Memory footprint in production: titles are tiny strings, meta is a
// small JSON object — negligible even with hundreds of docs files.
const isDev = process.env.NODE_ENV === "development";
const titleCache = new Map<string, string | null>();
const metaCache = new Map<
string,
{ title?: string; pages?: string[]; root?: boolean } | null
>();
export function readTitle(filePath: string): string | null {
const cacheKey = path.resolve(filePath);
if (!isDev && titleCache.has(cacheKey)) return titleCache.get(cacheKey)!;
if (!fs.existsSync(filePath)) {
titleCache.set(cacheKey, null);
return null;
}
let raw: string;
try {
raw = fs.readFileSync(filePath, "utf-8");
} catch (err) {
// A single bad file / permission error used to crash the whole
// page render. Log loudly and cache a null so we don't retry on
// every nav build in the same process.
console.error("[docs-render] failed to read", filePath, err);
titleCache.set(cacheKey, null);
return null;
}
// Restrict frontmatter matches to the frontmatter block so we don't
// grab a `title:` line that lives inside an MDX body (e.g. inside a
// code sample or example config). Falls back to the first H1 when no
// frontmatter title is set.
const fm = extractFrontmatter(raw);
const fmMatch = fm.match(/^title:\s*["']?(.+?)["']?\s*$/m);
let title: string | null = null;
if (fmMatch) {
title = fmMatch[1].replace(/["']$/, "");
} else {
const headingMatch = raw.match(/^#\s+(.+)$/m);
if (headingMatch) title = headingMatch[1];
}
titleCache.set(cacheKey, title);
return title;
}
export function readMeta(
dir: string,
): { title?: string; pages?: string[]; root?: boolean } | null {
const metaPath = path.join(dir, "meta.json");
const cacheKey = path.resolve(metaPath);
if (!isDev && metaCache.has(cacheKey)) return metaCache.get(cacheKey)!;
if (!fs.existsSync(metaPath)) {
metaCache.set(cacheKey, null);
return null;
}
try {
const parsed = JSON.parse(fs.readFileSync(metaPath, "utf-8"));
metaCache.set(cacheKey, parsed);
return parsed;
} catch (err) {
// Previously swallowed silently — a malformed meta.json rendered
// as "no nav ordering" with zero signal. Log loudly so authors
// see the offending path and parse error. Cache the null so we
// don't re-parse a bad file on every call.
console.error("[docs-render] failed to parse", metaPath, err);
metaCache.set(cacheKey, null);
return null;
}
}
export function buildNavTree(dir: string, prefix: string = ""): NavNode[] {
const meta = readMeta(dir);
if (!meta) return buildNavTreeFromFilesystem(dir, prefix);
const pages = meta.pages;
if (!pages || !Array.isArray(pages)) {
return buildNavTreeFromFilesystem(dir, prefix);
}
const nodes: NavNode[] = [];
for (const entry of pages) {
const sectionMatch = entry.match(/^---(.+)---$/);
if (sectionMatch) {
nodes.push({ type: "section", title: sectionMatch[1] });
continue;
}
if (entry.startsWith("[")) continue;
const spreadMatch = entry.match(/^\.\.\.(.+)$/);
if (spreadMatch) {
const subDir = path.join(dir, spreadMatch[1]);
const subPrefix = prefix ? `${prefix}/${spreadMatch[1]}` : spreadMatch[1];
if (fs.existsSync(subDir) && fs.statSync(subDir).isDirectory()) {
const subMeta = readMeta(subDir);
if (subMeta?.root) continue;
const subChildren = buildNavTree(subDir, subPrefix);
if (subChildren.length > 0) {
const rawGroupTitle =
subMeta?.title ||
spreadMatch[1].replace(/[()-]/g, " ").replace(/\s+/g, " ").trim();
const groupTitle =
rawGroupTitle.charAt(0).toUpperCase() + rawGroupTitle.slice(1);
// If the previous emitted node is a section header with the
// same title as this group's title, the section header
// already labels this content. Suppress the group title
// (empty string) so the renderer skips rendering it — the
// group still wraps its children for indentation/nesting.
// Without this dedup the sidebar shows "BUILD GENERATIVE UI"
// (section, uppercase) followed immediately by "Build
// Generative UI" (group, regular case) — same text, doubled.
const prev = nodes[nodes.length - 1];
const isDuplicateOfSection =
prev?.type === "section" && prev.title === groupTitle;
nodes.push({
type: "group",
title: isDuplicateOfSection ? "" : groupTitle,
slug: subPrefix,
children: subChildren,
});
}
}
continue;
}
const slug = prefix ? `${prefix}/${entry}` : entry;
const mdxFile = path.join(dir, `${entry}.mdx`);
const indexFile = path.join(dir, entry, "index.mdx");
const subDir = path.join(dir, entry);
if (fs.existsSync(mdxFile)) {
const title =
readTitle(mdxFile) || entry.split("/").pop()!.replace(/-/g, " ");
nodes.push({ type: "page", title, slug });
} else if (fs.existsSync(subDir) && fs.statSync(subDir).isDirectory()) {
const subMeta = readMeta(subDir);
if (subMeta?.root) continue;
const subPrefix = prefix ? `${prefix}/${entry}` : entry;
if (subMeta?.pages) {
const subChildren = buildNavTree(subDir, subPrefix);
const groupTitle = subMeta.title || entry.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug: subPrefix,
children: subChildren,
});
} else if (fs.existsSync(indexFile)) {
const title =
readTitle(indexFile) || subMeta?.title || entry.replace(/-/g, " ");
nodes.push({ type: "page", title, slug: subPrefix });
} else {
const subChildren = buildNavTreeFromFilesystem(subDir, subPrefix);
if (subChildren.length > 0) {
const groupTitle = subMeta?.title || entry.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug: subPrefix,
children: subChildren,
});
}
}
} else if (fs.existsSync(indexFile)) {
const title = readTitle(indexFile) || entry.replace(/-/g, " ");
nodes.push({ type: "page", title, slug });
}
}
return nodes;
}
export function buildNavTreeFromFilesystem(
dir: string,
prefix: string,
): NavNode[] {
if (!fs.existsSync(dir)) return [];
const nodes: NavNode[] = [];
let entries: fs.Dirent[];
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch (err) {
// Permission denied / ENOTDIR / etc. Log and return an empty tree
// rather than crashing every docs page render downstream.
console.error("[docs-render] failed to read dir", dir, err);
return [];
}
for (const entry of entries) {
if (entry.name.startsWith(".") || entry.name === "meta.json") continue;
if (entry.name.startsWith("(")) continue;
const slug = prefix
? `${prefix}/${entry.name.replace(".mdx", "")}`
: entry.name.replace(".mdx", "");
if (entry.isDirectory()) {
const subMeta = readMeta(path.join(dir, entry.name));
if (subMeta?.root) continue;
const subChildren = buildNavTree(path.join(dir, entry.name), slug);
if (subChildren.length > 0) {
const groupTitle = subMeta?.title || entry.name.replace(/-/g, " ");
nodes.push({
type: "group",
title: groupTitle.charAt(0).toUpperCase() + groupTitle.slice(1),
slug,
children: subChildren,
});
}
} else if (entry.name.endsWith(".mdx") && entry.name !== "index.mdx") {
const title =
readTitle(path.join(dir, entry.name)) ||
entry.name.replace(".mdx", "").replace(/-/g, " ");
nodes.push({ type: "page", title, slug });
}
}
return nodes;
}
/**
* Walk `content/docs/integrations/<folder>/` and return NavNodes for
* pages that have NO root equivalent. These are framework-specific
* topics (e.g. Built-in Agent's `copilot-runtime`, LangGraph's `auth`
* and `subgraphs`) that live only in the per-framework tree and need
* their own sidebar entries. Pages that duplicate root files are
* skipped — root wins, and the framework view already renders the
* root MDX with a framework override.
*
* Takes the resolved folder name (not the URL slug). Callers should
* use `getDocsFolder(slug)` from lib/registry to map language/runtime
* variants to their shared folder (e.g. langgraph-python / typescript
* / fastapi → `langgraph/`).
*/
export function buildFrameworkOverridesNav(folder: string): NavNode[] {
const frameworkDir = path.join(CONTENT_DIR, "integrations", folder);
if (!fs.existsSync(frameworkDir)) return [];
const nodes = buildNavTree(frameworkDir, `integrations/${folder}`);
// Drop entries whose equivalent root file exists. Root wins when
// both are present — the per-framework tree is only an escape hatch
// for framework-specific topics, not an alternative rendering.
const prefix = `integrations/${folder}/`;
const filtered: NavNode[] = [];
for (const node of nodes) {
if (node.type === "page") {
// node.slug looks like `integrations/<folder>/<topic>`. Strip
// the prefix to check the root-level equivalent.
const rootSlug = node.slug.replace(prefix, "");
const rootMdx = path.join(CONTENT_DIR, `${rootSlug}.mdx`);
const rootIndex = path.join(CONTENT_DIR, rootSlug, "index.mdx");
if (fs.existsSync(rootMdx) || fs.existsSync(rootIndex)) continue;
// Rewrite the slug so the link points at /<framework>/<topic>,
// which the router resolves via its fallback to the same MDX.
filtered.push({ ...node, slug: rootSlug });
} else if (node.type === "group") {
// Recursively filter children of a group.
const children = node.children
.filter((c) => {
if (c.type !== "page") return true;
const rootSlug = c.slug.replace(prefix, "");
const rootMdx = path.join(CONTENT_DIR, `${rootSlug}.mdx`);
const rootIndex = path.join(CONTENT_DIR, rootSlug, "index.mdx");
return !fs.existsSync(rootMdx) && !fs.existsSync(rootIndex);
})
.map((c) =>
c.type === "page" ? { ...c, slug: c.slug.replace(prefix, "") } : c,
);
if (children.length > 0) {
filtered.push({ ...node, children });
}
}
// Intentionally drop section nodes. Per-framework meta.json files
// tend to mirror the root tree's sections ("Getting Started",
// "Basics", etc.) and flowing them through here would (a) collide
// with root sections of the same name on React keys and (b) double
// up the visual hierarchy — the override block is already wrapped
// in a single `{frameworkName}` section by mergeFrameworkNav.
}
// Flatten empty-title wrapper groups. buildNavTree clears the title on
// a spread-derived group when the preceding section header has the
// same name (so the renderer doesn't double-print "Generative UI").
// After we drop section headers above, those wrappers are left as
// titleless containers that only add an extra indent step around
// their children. Inline the children at the wrapper's level instead.
const flattened: NavNode[] = [];
for (const node of filtered) {
if (node.type === "group" && node.title === "") {
flattened.push(...node.children);
} else {
flattened.push(node);
}
}
return flattened;
}
/**
* Return the list of framework slugs whose `integrations/<folder>/`
* tree contains an MDX file for `slugPath`. Matches either
* `<slug>.mdx` or `<slug>/index.mdx`. Used by the framework-scoped
* router to detect that a topic is available in *some* framework but
* not the one the user is currently viewing, so we can render a
* helpful "not available for <X>" page instead of a bare 404.
*
* Most slugs map 1:1 to their folder, but language/runtime variants
* share one folder (langgraph-python/typescript/fastapi → `langgraph/`,
* ms-agent-dotnet/python → `microsoft-agent-framework/`) and two
* legacy slugs were renamed after the folder existed (google-adk →
* `adk/`, strands → `aws-strands/`). The caller supplies the
* slug→folder resolver so this module stays registry-free.
*/
export function findFrameworksWithPage(
slugPath: string,
integrationSlugs: readonly string[],
slugToFolder: (slug: string) => string,
): string[] {
const matches: string[] = [];
for (const slug of integrationSlugs) {
const folder = slugToFolder(slug);
const mdx = path.join(
CONTENT_DIR,
"integrations",
folder,
`${slugPath}.mdx`,
);
const indexMdx = path.join(
CONTENT_DIR,
"integrations",
folder,
slugPath,
"index.mdx",
);
if (fs.existsSync(mdx) || fs.existsSync(indexMdx)) matches.push(slug);
}
return matches;
}
// ---------------------------------------------------------------------------
// Snippet inlining (same rules as the docs page)
// ---------------------------------------------------------------------------
// Maps `<ComponentName />` MDX references to the relative snippet file
// under SNIPPETS_DIR. Keys are JSX component names (PascalCase) and
// must match EXACTLY what authors write in MDX — they are not
// filesystem paths and are case-sensitive on both sides of the map.
//
// Aliases (same target under multiple keys) are intentional and exist
// because the codebase historically shipped both spellings:
// - `AgUI` / `AGUI` — two legal casings; keep both
// so authors writing either render correctly. Upstream consumers
// reach this via SUBPATH_TO_COMPONENT which uses `AGUI`.
// - `FrontendTools` / `FrontEndToolsImpl` — historical name kept
// for backward compat with existing MDX that still uses
// `<FrontEndToolsImpl />` (confirmed in live docs content). Don't
// collapse these without first rewriting all .mdx references.
//
// Filename casing: `migrate-to-1.10.X.mdx` and `migrate-to-1.8.2.mdx`
// match the on-disk files exactly (uppercase X in 1.10.X), verified
// against src/content/snippets/shared/troubleshooting/.
export const SNIPPET_MAP: Record<string, string> = {
A2UI: "shared/generative-ui/a2ui.mdx",
AgUI: "shared/backend/ag-ui.mdx",
AGUI: "shared/backend/ag-ui.mdx", // alias of AgUI
CodingAgents: "shared/coding-agents.mdx",
CommonIssues: "shared/troubleshooting/common-issues.mdx",
CopilotRuntime: "copilot-runtime.mdx",
CustomAgent: "shared/backend/custom-agent.mdx",
DebugMode: "shared/troubleshooting/debug-mode.mdx",
DisplayOnly: "shared/generative-ui/display-only.mdx",
ErrorDebugging: "shared/troubleshooting/error-debugging.mdx",
FrontendTools: "shared/app-control/frontend-tools.mdx",
FrontEndToolsImpl: "shared/app-control/frontend-tools.mdx", // alias of FrontendTools
GenerativeUISpecsOverview: "shared/generative-ui-specs-overview.mdx",
HeadlessUI: "shared/basics/headless-ui.mdx",
Inspector: "shared/premium/inspector.mdx",
Interactive: "shared/generative-ui/interactive.mdx",
MCPApps: "shared/generative-ui/mcp-apps.mdx",
MCPSetup: "shared/guides/mcp-server-setup.mdx",
MigrateTo1100: "shared/troubleshooting/migrate-to-1.10.X.mdx",
MigrateTo182: "shared/troubleshooting/migrate-to-1.8.2.mdx",
MigrateToV2: "shared/troubleshooting/migrate-to-v2.mdx",
Observability: "shared/premium/observability.mdx",
ObservabilityConnectors:
"shared/troubleshooting/observability-connectors.mdx",
Overview: "shared/premium/overview.mdx",
PrebuiltComponents: "shared/basics/prebuilt-components.mdx",
ProgrammaticControl: "shared/basics/programmatic-control.mdx",
ReasoningMessages:
"shared/guides/custom-look-and-feel/reasoning-messages.mdx",
SelfHosting: "shared/premium/self-hosting.mdx",
Slots: "shared/basics/slots.mdx",
Threads: "shared/threads/threads.mdx",
ToolRendering: "shared/generative-ui/tool-rendering.mdx",
DefaultToolRendering: "shared/guides/default-tool-rendering.mdx",
};
export const SUBPATH_TO_COMPONENT: Record<string, string> = {
"ag-ui": "AGUI",
"coding-agents": "CodingAgents",
"copilot-runtime": "CopilotRuntime",
"custom-look-and-feel/headless-ui": "HeadlessUI",
"custom-look-and-feel/slots": "Slots",
"frontend-tools": "FrontendTools",
"generative-ui/a2ui": "A2UI",
"generative-ui/mcp-apps": "MCPApps",
"generative-ui/tool-rendering": "ToolRendering",
"generative-ui/your-components/display-only": "DisplayOnly",
"generative-ui/your-components/interactive": "Interactive",
inspector: "Inspector",
"prebuilt-components": "PrebuiltComponents",
"programmatic-control": "ProgrammaticControl",
"premium/headless-ui": "HeadlessUI",
"premium/observability": "Observability",
"premium/overview": "Overview",
"troubleshooting/common-issues": "CommonIssues",
"troubleshooting/error-debugging": "ErrorDebugging",
"troubleshooting/migrate-to-1.10.X": "MigrateTo1100",
"troubleshooting/migrate-to-1.8.2": "MigrateTo182",
"troubleshooting/migrate-to-v2": "MigrateToV2",
"troubleshooting/observability-connectors": "ObservabilityConnectors",
};
/**
* Strip leading `import ...` statements from an MDX source WITHOUT
* touching lines inside fenced code blocks. Previously we ran
* `/^import\s+.+$/gm` over the whole source, which mangled real code
* samples like `import os` inside python fences. This implementation
* walks the source line-by-line, tracks fence state with ``` / ~~~,
* and only strips `import` lines that appear at the top of the file
* (before the first non-import, non-blank content line). Import lines
* that appear *later* in the prose are also preserved — the only ones
* we want to remove are MDX's JSX component imports, which always sit
* in the top-of-file block.
*
* Covered by: snippet contents that include a Python/JS code fence
* with an `import` statement must have the `import` preserved in the
* rendered output.
*/
export function stripLeadingImports(source: string): string {
const lines = source.split("\n");
const out: string[] = [];
let inFence = false;
let fenceMarker: string | null = null;
let pastHeader = false;
for (const line of lines) {
// Toggle fence state. Match the opening fence's marker (``` or ~~~)
// so a stray triple-backtick inside a tilde fence (or vice-versa)
// doesn't prematurely close it.
const fenceMatch = line.match(/^\s*(```+|~~~+)/);
if (fenceMatch) {
if (!inFence) {
inFence = true;
// Store the full fence marker (e.g. ``` or ~~~~) rather than
// its first character, so a single stray `\`` inside a ```
// fence doesn't prematurely close the block.
fenceMarker = fenceMatch[1];
} else if (fenceMarker && line.trim().startsWith(fenceMarker)) {
inFence = false;
fenceMarker = null;
}
pastHeader = true; // fences are content
out.push(line);
continue;
}
if (!inFence && !pastHeader) {
if (/^\s*$/.test(line)) {
// Preserve blank lines in the header region for layout.
out.push(line);
continue;
}
if (/^import\s+.+$/.test(line)) {
// Drop this top-of-file MDX import line.
continue;
}
// First real content line flips us out of "header" mode.
pastHeader = true;
}
out.push(line);
}
return out.join("\n");
}
export function inlineSnippets(
content: string,
slugPath: string = "",
seen: Set<string> = new Set(),
): string {
let result = stripLeadingImports(content);
result = result.replace(
/<([A-Z]\w*)\s*(?:components=\{[^}]*\}\s*)?\/>/g,
(match, componentName) => {
let snippetRel = SNIPPET_MAP[componentName];
if (!snippetRel && componentName === "SharedContent" && slugPath) {
// The docs page could live at any of these URL shapes:
// - integrations/<framework>/<subpath> (legacy per-framework docs)
// - unselected/<subpath> (new unselected tree)
// - <subpath> (framework-scoped
// /<framework>/<subpath>,
// which arrives with no
// prefix here)
// Try each shape in order to find a SUBPATH_TO_COMPONENT match.
const candidateSubpaths: string[] = [];
const integrationsMatch = slugPath.match(/^integrations\/[^/]+\/(.+)$/);
if (integrationsMatch) candidateSubpaths.push(integrationsMatch[1]);
if (slugPath.startsWith("unselected/")) {
candidateSubpaths.push(slugPath.slice("unselected/".length));
}
candidateSubpaths.push(slugPath);
for (const sub of candidateSubpaths) {
const resolvedComponent = SUBPATH_TO_COMPONENT[sub];
if (resolvedComponent) {
snippetRel = SNIPPET_MAP[resolvedComponent];
if (snippetRel) break;
}
}
}
if (!snippetRel) {
// Log so docs authors see a clean signal when a <Component />
// reference can't be mapped to a snippet file (previously the
// component just silently rendered nothing).
console.warn(
"[docs-render] snippet missing for component",
componentName,
"from slug",
slugPath || "(none)",
);
return match;
}
// Even though snippetRel comes from the hardcoded SNIPPET_MAP,
// route through resolveWithinDir for defense-in-depth — any
// future addition that builds the relative path from user
// input is guarded by default.
const snippetPath = resolveWithinDir(SNIPPETS_DIR, snippetRel);
if (!snippetPath || !fs.existsSync(snippetPath)) {
console.warn(
"[docs-render] snippet file not found",
snippetRel,
"for component",
componentName,
"from slug",
slugPath || "(none)",
);
return match;
}
// Cycle protection: if this snippet file is already in-flight
// higher up the recursion, emit a warning and stop. Without
// this, a self-referencing or mutually-referencing snippet
// loops until the stack overflows.
if (seen.has(snippetPath)) {
console.warn(
"[docs-render] snippet cycle detected, refusing to re-inline",
snippetPath,
);
return `{/* snippet cycle: ${componentName} */}`;
}
let snippetContent: string;
try {
snippetContent = fs.readFileSync(snippetPath, "utf-8");
} catch (err) {
// Previously a permission error / missing file mid-render
// crashed the entire docs page. Log and leave the original
// <Component /> reference in the rendered output.
console.error("[docs-render] failed to read snippet", snippetPath, err);
return match;
}
snippetContent = snippetContent.replace(/^---[\s\S]*?---\r?\n?/, "");
const nextSeen = new Set(seen);
nextSeen.add(snippetPath);
return inlineSnippets(snippetContent, slugPath, nextSeen);
},
);
return result;
}
// ---------------------------------------------------------------------------
// Markdown tables inside JSX container tags
// ---------------------------------------------------------------------------
// JSX container components whose inner Markdown table bodies should be
// promoted to real HTML tables. Previously only `Accordion` and `Tab`
// were covered, which silently failed for tables inside `Callout`,
// `Card`, `Step`, `Tabs`, etc. Keep this list in rough sync with the
// container-ish entries in mdx-registry.tsx — any JSX component that
// may wrap prose-like MDX bodies belongs here.
const JSX_CONTAINER_TAGS = [
"Accordion",
"Tab",
"Tabs",
"Callout",
"Card",
"Cards",
"Step",
"Steps",
];
// Split a GFM table row into cell values. GFM allows tables WITHOUT
// the outer leading/trailing pipes (e.g. "a | b | c"), so we can't
// unconditionally drop the first and last cells. Instead, drop a
// leading/trailing cell only when it's empty (the artifact of an outer
// pipe); keep genuine first/last cells.
function parseTableRow(line: string): string[] {
const cells = line.split("|").map((cell) => cell.trim());
if (cells.length > 0 && cells[0] === "") cells.shift();
if (cells.length > 0 && cells[cells.length - 1] === "") cells.pop();
return cells;
}
function convertMarkdownTableToHtml(tableLines: string[]): string {
if (tableLines.length < 2) return tableLines.join("\n");
const headers = parseTableRow(tableLines[0]);
const separatorLine = tableLines[1];
// Accept GFM separator lines with or without outer pipes. Must
// contain at least one `|` and otherwise consist of spaces, colons,
// and dashes only.
if (
!/^\s*[|:\- ]*\|[|:\- ]*\s*$/.test(separatorLine) ||
!/\|/.test(separatorLine)
) {
return tableLines.join("\n");
}
const bodyRows = tableLines.slice(2).map(parseTableRow);
// Escape every interpolated cell value. Without this, any MDX table
// cell containing `<script>`, `&`, or other HTML-significant chars
// would inject raw HTML into the rendered page (XSS surface, since
// the output is fed through dangerouslySetInnerHTML-style paths).
// Covered by: docs pages that place untrusted-looking markup inside
// `<Accordion>`/`<Callout>` table cells should render as literal text.
// Emit attribute-free tags so next-mdx-remote parses the result as
// valid JSX. Previously we set inline `style="..."` strings, but MDX
// parses inline HTML as JSX, where `style` must be an object — a
// string crashes the render. Styling comes from the
// `.reference-content table` rules in globals.css.
const headerHtml = headers.map((h) => `<th>${escapeHtml(h)}</th>`).join("");
const bodyHtml = bodyRows
.map(
(row) =>
"<tr>" +
row.map((cell) => `<td>${escapeHtml(cell)}</td>`).join("") +
"</tr>",
)
.join("");
return `<table><thead><tr>${headerHtml}</tr></thead><tbody>${bodyHtml}</tbody></table>`;
}
// A line looks like a table row when it contains at least one pipe
// that separates two non-empty cells OR has the classic leading-pipe
// form. Accepts both GFM variants (with / without outer pipes).
const isTableRow = (s: string): boolean =>
/\S\s*\|\s*\S/.test(s) || /^\s*\|.+/.test(s);
// Separator: at least one pipe, otherwise only spaces, colons, dashes.
const isTableSeparator = (s: string): boolean =>
/\|/.test(s) && /^\s*[|:\- ]+\s*$/.test(s);
export function convertTablesInJSX(content: string): string {
const tagPattern = JSX_CONTAINER_TAGS.join("|");
const regex = new RegExp(
`(<(${tagPattern})[^>]*>)([\\s\\S]*?)(<\\/(?:${tagPattern})>)`,
"g",
);
return content.replace(
regex,
(
match,
openTag: string,
tagName: string,
inner: string,
closeTag: string,
) => {
// Non-greedy `[\s\S]*?` matches through the FIRST close tag of
// any container in the set, so nested same-tag content (e.g.
// `<Card>outer <Card>inner</Card> rest</Card>`) closes at the
// inner `</Card>` and leaves `rest</Card>` stranded. Detect the
// nesting and bail — the outer match is left untouched, which
// renders correctly via MDX's own JSX handling (tables inside
// nested containers simply won't be promoted to HTML tables).
if (new RegExp(`<${tagName}[\\s>]`).test(inner)) {
return match;
}
const lines = inner.split("\n");
const result: string[] = [];
let i = 0;
while (i < lines.length) {
const line = lines[i];
if (isTableRow(line)) {
const tableLines: string[] = [];
while (
i < lines.length &&
(isTableRow(lines[i]) || isTableSeparator(lines[i]))
) {
tableLines.push(lines[i].trim());
i++;
}
if (tableLines.length >= 2 && isTableSeparator(tableLines[1])) {
result.push(convertMarkdownTableToHtml(tableLines));
} else {
result.push(...tableLines);
}
} else {
result.push(line);
i++;
}
}
return openTag + result.join("\n") + closeTag;
},
);
}
// ---------------------------------------------------------------------------
// Framework / cell lookups
// ---------------------------------------------------------------------------
/**
* Return the slugs of integrations that have a demo region tagged for
* the given feature cell. Pure helper — the caller supplies the list of
* candidate integration slugs and the demo-content map so this file
* stays framework-agnostic and free of registry imports.
*
* Shape of `demos`: keys are `"<integrationSlug>::<cell>"`; values are
* opaque demo records (we only check key presence here).
*/
export function findFrameworksWithCell(
cell: string,
integrationSlugs: readonly string[],
demos: Record<string, unknown>,
): string[] {
const matches: string[] = [];
for (const slug of integrationSlugs) {
if (demos[`${slug}::${cell}`]) matches.push(slug);
}
return matches;
}
// ---------------------------------------------------------------------------
// Frontmatter helpers
// ---------------------------------------------------------------------------
export interface DocFrontmatter {
title: string;
description?: string;
defaultFramework?: string;
defaultCell?: string;
hideTOC?: boolean;
}
/**
* Load an MDX file by slug and return its raw source + parsed frontmatter
* metadata for rendering. Returns null when the file doesn't exist.
*/
export function loadDoc(
slugPath: string,
): { source: string; filePath: string; fm: DocFrontmatter } | null {
// Guard against path traversal: slugPath is built from URL segments.
// Without resolveWithinDir, a slug like `../../secrets` would escape
// CONTENT_DIR via path.join and leak arbitrary files on disk.
// Covered by: a request for /docs/..%2F..%2Fpackage must return 404.
const mdxResolved = resolveWithinDir(CONTENT_DIR, `${slugPath}.mdx`);
const indexResolved = resolveWithinDir(
CONTENT_DIR,
path.join(slugPath, "index.mdx"),
);
let filePath: string;
if (mdxResolved && fs.existsSync(mdxResolved)) {
filePath = mdxResolved;
} else if (indexResolved && fs.existsSync(indexResolved)) {
filePath = indexResolved;
} else {
return null;
}
let source: string;
try {
source = fs.readFileSync(filePath, "utf-8");
} catch (err) {
// Can't read the MDX — log and treat as a missing doc so the
// caller renders a 404 rather than crashing the request.
console.error("[docs-render] failed to read", filePath, err);
return null;
}
// Parse frontmatter with gray-matter rather than a hand-rolled
// regex: handles quoted values, folded YAML, multiline descriptions,
// and CRLF line endings correctly. Previously the regex split on
// `^---\n` and missed anything Windows-authored.
let data: Record<string, unknown> = {};
let parsed: { data: Record<string, unknown> } | null = null;
try {
parsed = matter(source);
data = parsed.data ?? {};
} catch (err) {
// Malformed YAML — don't crash the page, just render with an empty
// frontmatter and let the title fall back to the first H1.
console.error("[docs-render] failed to parse frontmatter", filePath, err);
}
const rawTitle = typeof data.title === "string" ? data.title : undefined;
const headingMatch = rawTitle ? null : source.match(/^#\s+(.+)$/m);
const title =
rawTitle ||
headingMatch?.[1] ||
slugPath.split("/").pop()?.replace(/-/g, " ") ||
"Docs";
const description =
typeof data.description === "string" ? data.description : undefined;
const defaultFramework =
typeof data.snippet_framework === "string"
? data.snippet_framework
: undefined;
const defaultCell =
typeof data.snippet_cell === "string" ? data.snippet_cell : undefined;
const hideTOC = data.hideTOC === true;
return {
source,
filePath,
fm: {
title,
description,
defaultFramework,
defaultCell,
hideTOC,
},
};
}
// ---------------------------------------------------------------------------
// Breadcrumbs
// ---------------------------------------------------------------------------
export type Breadcrumb = { label: string; href: string | null };
export function buildBreadcrumbs(
slugPath: string,
opts: { rootLabel: string; rootHref: string | null; slugHrefPrefix: string },
): Breadcrumb[] {
const parts = slugPath.split("/");
const crumbs: Breadcrumb[] = [{ label: opts.rootLabel, href: opts.rootHref }];
for (let i = 0; i < parts.length; i++) {
const partialSlug = parts.slice(0, i + 1).join("/");
const href = `${opts.slugHrefPrefix}/${partialSlug}`;
const isLast = i === parts.length - 1;
// Guard against path traversal on user-supplied slug segments.
// A resolved path that escapes CONTENT_DIR becomes null and we
// fall through to the slug-derived label.
const mdxFile = resolveWithinDir(CONTENT_DIR, `${partialSlug}.mdx`);
const indexFile = resolveWithinDir(
CONTENT_DIR,
path.join(partialSlug, "index.mdx"),
);
const dirResolved = resolveWithinDir(CONTENT_DIR, partialSlug);
const dirMeta = dirResolved ? readMeta(dirResolved) : null;
let label: string | null = null;
if (dirMeta?.title) {
label = dirMeta.title;
} else if (mdxFile && fs.existsSync(mdxFile)) {
label = readTitle(mdxFile);
} else if (indexFile && fs.existsSync(indexFile)) {
label = readTitle(indexFile);
}
if (!label) {
label = parts[i]
.replace(/-/g, " ")
.replace(/\b\w/g, (c) => c.toUpperCase());
}
crumbs.push({ label, href: isLast ? null : href });
}
return crumbs;
}