specra 0.2.2 → 0.2.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (32) hide show
  1. package/config/specra.config.schema.json +9 -14
  2. package/dist/components/docs/Callout.svelte +5 -4
  3. package/dist/components/docs/CodeBlock.svelte +2 -2
  4. package/dist/components/docs/DocLayout.svelte +1 -1
  5. package/dist/components/docs/Header.svelte +73 -3
  6. package/dist/components/docs/Header.svelte.d.ts +11 -0
  7. package/dist/components/docs/MdxLayout.svelte +1 -1
  8. package/dist/components/docs/MobileDocLayout.svelte +3 -15
  9. package/dist/components/docs/Sidebar.svelte +4 -11
  10. package/dist/components/docs/SidebarMenuItems.svelte +1 -3
  11. package/dist/components/docs/Step.svelte +2 -2
  12. package/dist/components/docs/TabGroups.svelte +2 -2
  13. package/dist/components/docs/TableOfContents.svelte +3 -10
  14. package/dist/components/docs/Timeline.svelte +15 -0
  15. package/dist/components/docs/Timeline.svelte.d.ts +7 -0
  16. package/dist/components/docs/TimelineItem.svelte +50 -0
  17. package/dist/components/docs/TimelineItem.svelte.d.ts +10 -0
  18. package/dist/components/docs/VersionBanner.svelte +60 -0
  19. package/dist/components/docs/VersionBanner.svelte.d.ts +10 -0
  20. package/dist/components/docs/VersionSwitcher.svelte +40 -13
  21. package/dist/components/docs/VersionSwitcher.svelte.d.ts +7 -0
  22. package/dist/components/docs/componentTextProps.js +2 -0
  23. package/dist/components/docs/index.d.ts +3 -0
  24. package/dist/components/docs/index.js +3 -0
  25. package/dist/config.d.ts +1 -1
  26. package/dist/config.server.d.ts +28 -1
  27. package/dist/config.server.js +66 -0
  28. package/dist/config.types.d.ts +25 -0
  29. package/dist/mdx-components.js +4 -2
  30. package/dist/mdx.js +325 -42
  31. package/dist/styles/globals.css +71 -0
  32. package/package.json +1 -1
@@ -1,6 +1,13 @@
1
+ interface VersionMeta {
2
+ id: string;
3
+ label: string;
4
+ badge?: string;
5
+ hidden?: boolean;
6
+ }
1
7
  interface Props {
2
8
  currentVersion: string;
3
9
  versions: string[];
10
+ versionsMeta?: VersionMeta[];
4
11
  }
5
12
  declare const VersionSwitcher: import("svelte").Component<Props, {}, "">;
6
13
  type VersionSwitcher = ReturnType<typeof VersionSwitcher>;
@@ -24,6 +24,8 @@ export const COMPONENT_TEXT_PROPS = {
24
24
  CodeBlock: ["filename"],
25
25
  // Step components
26
26
  Step: ["title"],
27
+ // Timeline components
28
+ TimelineItem: ["title", "date"],
27
29
  };
28
30
  export function extractComponentPropsText(mdx) {
29
31
  return mdx.replace(/<([A-Z][\w]*)\b([^/>]*)\/>/g, (_, component, props) => {
@@ -46,9 +46,12 @@ export { default as Steps } from './Steps.svelte';
46
46
  export { default as Tab } from './Tab.svelte';
47
47
  export { default as TabGroups } from './TabGroups.svelte';
48
48
  export { default as TableOfContents } from './TableOfContents.svelte';
49
+ export { default as Timeline } from './Timeline.svelte';
50
+ export { default as TimelineItem } from './TimelineItem.svelte';
49
51
  export { default as Tabs } from './Tabs.svelte';
50
52
  export { default as ThemeToggle } from './ThemeToggle.svelte';
51
53
  export { default as Tooltip } from './Tooltip.svelte';
54
+ export { default as VersionBanner } from './VersionBanner.svelte';
52
55
  export { default as VersionSwitcher } from './VersionSwitcher.svelte';
53
56
  export { default as Video } from './Video.svelte';
54
57
  export { ApiEndpoint, ApiParams, ApiResponse, ApiResponseDisplay, ApiPlayground, ApiReference, } from './api/index.js';
@@ -47,9 +47,12 @@ export { default as Steps } from './Steps.svelte';
47
47
  export { default as Tab } from './Tab.svelte';
48
48
  export { default as TabGroups } from './TabGroups.svelte';
49
49
  export { default as TableOfContents } from './TableOfContents.svelte';
50
+ export { default as Timeline } from './Timeline.svelte';
51
+ export { default as TimelineItem } from './TimelineItem.svelte';
50
52
  export { default as Tabs } from './Tabs.svelte';
51
53
  export { default as ThemeToggle } from './ThemeToggle.svelte';
52
54
  export { default as Tooltip } from './Tooltip.svelte';
55
+ export { default as VersionBanner } from './VersionBanner.svelte';
53
56
  export { default as VersionSwitcher } from './VersionSwitcher.svelte';
54
57
  export { default as Video } from './Video.svelte';
55
58
  // API components
package/dist/config.d.ts CHANGED
@@ -4,5 +4,5 @@
4
4
  * The actual config loading happens on the server and is passed as props
5
5
  */
6
6
  export { defaultConfig } from "./config.types";
7
- export type { SpecraConfig } from "./config.types";
7
+ export type { SpecraConfig, VersionConfig, BannerConfig } from "./config.types";
8
8
  export { getConfig, getConfigValue, loadConfig, processContentWithEnv, replaceEnvVariables, validateConfig, reloadConfig, } from "./config.server";
@@ -1,4 +1,4 @@
1
- import type { SpecraConfig } from "./config.types";
1
+ import type { SpecraConfig, VersionConfig } from "./config.types";
2
2
  /**
3
3
  * Load and parse the Specra configuration file
4
4
  * Falls back to default configuration if file doesn't exist or is invalid
@@ -41,6 +41,33 @@ export declare function getConfig(): SpecraConfig;
41
41
  * Reload the configuration (useful for development) (SERVER ONLY)
42
42
  */
43
43
  export declare function reloadConfig(userConfig: Partial<SpecraConfig>): SpecraConfig;
44
+ export declare function loadVersionConfig(version: string): VersionConfig | null;
45
+ /**
46
+ * Get the effective config for a specific version.
47
+ * Merges global config with per-version overrides from _version_.json.
48
+ * If no _version_.json exists, returns the global config unchanged.
49
+ */
50
+ export declare function getEffectiveConfig(version: string): SpecraConfig;
51
+ /**
52
+ * Version metadata for display in the version switcher.
53
+ */
54
+ export interface VersionMeta {
55
+ /** Directory name (e.g., "v1.0.0") — used for routing */
56
+ id: string;
57
+ /** Display label (e.g., "v1.0 (Stable)") — defaults to id */
58
+ label: string;
59
+ /** Short badge text (e.g., "Beta", "LTS") */
60
+ badge?: string;
61
+ /** Whether this version is hidden from the switcher */
62
+ hidden?: boolean;
63
+ /** Version-level banner */
64
+ banner?: import("./config.types").BannerConfig;
65
+ }
66
+ /**
67
+ * Get metadata for all versions, enriched with _version_.json data.
68
+ * Hidden versions are included but marked — the UI decides whether to show them.
69
+ */
70
+ export declare function getVersionsMeta(versions: string[]): VersionMeta[];
44
71
  /**
45
72
  * Export the loaded config as default (SERVER ONLY)
46
73
  */
@@ -1,3 +1,5 @@
1
+ import fs from "fs";
2
+ import path from "path";
1
3
  import { defaultConfig } from "./config.types";
2
4
  /**
3
5
  * Deep merge two objects
@@ -143,6 +145,70 @@ export function reloadConfig(userConfig) {
143
145
  configInstance = loadConfig(userConfig);
144
146
  return configInstance;
145
147
  }
148
+ /**
149
+ * Load per-version configuration from docs/{version}/_version_.json.
150
+ * Returns null if the file doesn't exist or is invalid.
151
+ */
152
+ const versionConfigCache = new Map();
153
+ const VCFG_TTL = process.env.NODE_ENV === 'development' ? 5000 : 60000;
154
+ export function loadVersionConfig(version) {
155
+ const cached = versionConfigCache.get(version);
156
+ if (cached && Date.now() - cached.timestamp < VCFG_TTL) {
157
+ return cached.data;
158
+ }
159
+ try {
160
+ const versionConfigPath = path.join(process.cwd(), "docs", version, "_version_.json");
161
+ if (!fs.existsSync(versionConfigPath)) {
162
+ versionConfigCache.set(version, { data: null, timestamp: Date.now() });
163
+ return null;
164
+ }
165
+ const content = fs.readFileSync(versionConfigPath, "utf8");
166
+ const data = JSON.parse(content);
167
+ versionConfigCache.set(version, { data, timestamp: Date.now() });
168
+ return data;
169
+ }
170
+ catch (error) {
171
+ console.error(`Error loading _version_.json for ${version}:`, error);
172
+ versionConfigCache.set(version, { data: null, timestamp: Date.now() });
173
+ return null;
174
+ }
175
+ }
176
+ /**
177
+ * Get the effective config for a specific version.
178
+ * Merges global config with per-version overrides from _version_.json.
179
+ * If no _version_.json exists, returns the global config unchanged.
180
+ */
181
+ export function getEffectiveConfig(version) {
182
+ const globalConfig = getConfig();
183
+ const versionConfig = loadVersionConfig(version);
184
+ if (!versionConfig) {
185
+ return globalConfig;
186
+ }
187
+ const effective = { ...globalConfig };
188
+ if (versionConfig.tabGroups !== undefined) {
189
+ effective.navigation = {
190
+ ...effective.navigation,
191
+ tabGroups: versionConfig.tabGroups,
192
+ };
193
+ }
194
+ return effective;
195
+ }
196
+ /**
197
+ * Get metadata for all versions, enriched with _version_.json data.
198
+ * Hidden versions are included but marked — the UI decides whether to show them.
199
+ */
200
+ export function getVersionsMeta(versions) {
201
+ return versions.map(id => {
202
+ const versionConfig = loadVersionConfig(id);
203
+ return {
204
+ id,
205
+ label: versionConfig?.label || id,
206
+ badge: versionConfig?.badge,
207
+ hidden: versionConfig?.hidden,
208
+ banner: versionConfig?.banner,
209
+ };
210
+ });
211
+ }
146
212
  /**
147
213
  * Export the loaded config as default (SERVER ONLY)
148
214
  */
@@ -59,6 +59,31 @@ export interface TabGroup {
59
59
  /** Optional icon name (lucide-react icon) */
60
60
  icon?: string;
61
61
  }
62
+ /**
63
+ * Banner configuration for version-level or site-level banners.
64
+ */
65
+ export interface BannerConfig {
66
+ /** Banner message text. Supports markdown links like [text](/url). */
67
+ text: string;
68
+ /** Banner style: info, warning, error, success */
69
+ type?: 'info' | 'warning' | 'error' | 'success';
70
+ }
71
+ /**
72
+ * Per-version configuration that can override global config settings.
73
+ * Loaded from docs/{version}/_version_.json
74
+ */
75
+ export interface VersionConfig {
76
+ /** Display label for this version (e.g., "v1.0 (Stable)"). Defaults to directory name. */
77
+ label?: string;
78
+ /** Hide this version from the version switcher. Useful for unreleased versions. */
79
+ hidden?: boolean;
80
+ /** Short badge text shown next to the version (e.g., "Beta", "LTS", "Deprecated"). */
81
+ badge?: string;
82
+ /** Banner shown at the top of every page in this version. Overrides global banner. */
83
+ banner?: BannerConfig;
84
+ /** Override tab groups for this version. Empty array = no tabs. */
85
+ tabGroups?: TabGroup[];
86
+ }
62
87
  /**
63
88
  * Navigation and sidebar configuration
64
89
  */
@@ -13,9 +13,9 @@
13
13
  * <Callout type="info">This is a callout</Callout>
14
14
  * ```
15
15
  */
16
- import { Callout, Accordion, AccordionItem, Tabs, Tab, Image, Video, Card, CardGrid, ImageCard, ImageCardGrid, Steps, Step, Icon, Mermaid, Math, Columns, Column, DocBadge, Tooltip, Frame, CodeBlock, ApiEndpoint, ApiParams, ApiResponse, ApiPlayground, ApiReference, } from './components/docs';
16
+ import { Callout, Accordion, AccordionItem, Tabs, Tab, Image, Video, Card, CardGrid, ImageCard, ImageCardGrid, Steps, Step, Icon, Mermaid, Math, Columns, Column, DocBadge, Tooltip, Frame, CodeBlock, Timeline, TimelineItem, ApiEndpoint, ApiParams, ApiResponse, ApiPlayground, ApiReference, } from './components/docs';
17
17
  // Re-export all MDX-usable components
18
- export { Callout, Accordion, AccordionItem, Tabs, Tab, Image, Video, Card, CardGrid, ImageCard, ImageCardGrid, Steps, Step, Icon, Mermaid, Math, Columns, Column, DocBadge, Tooltip, Frame, CodeBlock, ApiEndpoint, ApiParams, ApiResponse, ApiPlayground, ApiReference, };
18
+ export { Callout, Accordion, AccordionItem, Tabs, Tab, Image, Video, Card, CardGrid, ImageCard, ImageCardGrid, Steps, Step, Icon, Mermaid, Math, Columns, Column, DocBadge, Tooltip, Frame, CodeBlock, Timeline, TimelineItem, ApiEndpoint, ApiParams, ApiResponse, ApiPlayground, ApiReference, };
19
19
  /**
20
20
  * Component map for passing to layout components that render MDX content.
21
21
  */
@@ -43,6 +43,8 @@ export const mdxComponents = {
43
43
  Tooltip,
44
44
  Frame,
45
45
  CodeBlock,
46
+ Timeline,
47
+ TimelineItem,
46
48
  ApiEndpoint,
47
49
  ApiParams,
48
50
  ApiResponse,
package/dist/mdx.js CHANGED
@@ -81,28 +81,34 @@ const PROP_NAME_MAP = {
81
81
  * span={2} → span="__jsx:2"
82
82
  * variant="success" → (unchanged, already a string)
83
83
  */
84
- function preprocessJsxExpressions(markdown) {
85
- // Split markdown into fenced code blocks and non-code segments.
86
- // Only process JSX expressions in non-code segments to avoid corrupting code examples.
87
- // Matches ```` ``` ```` or ```` ```` ```` fenced blocks (3+ backticks or tildes).
84
+ /**
85
+ * Split markdown into fenced code blocks and non-code segments.
86
+ * Code blocks are preserved as-is; only non-code segments should be
87
+ * processed by JSX/component preprocessing functions.
88
+ * Matches 3+ backticks or tildes as fence markers.
89
+ */
90
+ function splitByCodeFences(markdown) {
88
91
  const fencedCodeRegex = /(^|\n)((`{3,}|~{3,}).*\n[\s\S]*?\n\3\s*(?:\n|$))/g;
89
92
  const segments = [];
90
93
  let lastIndex = 0;
91
94
  let match;
92
95
  while ((match = fencedCodeRegex.exec(markdown)) !== null) {
93
96
  const codeStart = match.index + (match[1]?.length || 0);
94
- // Add the non-code segment before this code block
95
97
  if (codeStart > lastIndex) {
96
98
  segments.push({ text: markdown.slice(lastIndex, codeStart), isCode: false });
97
99
  }
98
- // Add the code block as-is
99
100
  segments.push({ text: match[2], isCode: true });
100
101
  lastIndex = match.index + match[0].length;
101
102
  }
102
- // Add remaining non-code segment
103
103
  if (lastIndex < markdown.length) {
104
104
  segments.push({ text: markdown.slice(lastIndex), isCode: false });
105
105
  }
106
+ return segments;
107
+ }
108
+ function preprocessJsxExpressions(markdown) {
109
+ // Split markdown into fenced code blocks and non-code segments.
110
+ // Only process JSX expressions in non-code segments to avoid corrupting code examples.
111
+ const segments = splitByCodeFences(markdown);
106
112
  // Build a pattern that matches known component tag names (case-insensitive for safety)
107
113
  const allNames = [...new Set([
108
114
  ...Object.values(COMPONENT_TAG_MAP),
@@ -425,9 +431,7 @@ function extractCodeBlockProps(node) {
425
431
  // Extract language from className like ['language-javascript']
426
432
  const classNames = codeChild.properties?.className || [];
427
433
  const langClass = classNames.find((c) => typeof c === 'string' && c.startsWith('language-'));
428
- if (!langClass)
429
- return null;
430
- const language = langClass.replace('language-', '');
434
+ const language = langClass ? langClass.replace('language-', '') : 'txt';
431
435
  // Extract text content from the code element
432
436
  const code = extractTextContent(codeChild).replace(/\n$/, '');
433
437
  // Check for filename in data attributes (e.g. from remark-code-meta)
@@ -463,6 +467,7 @@ function childrenContainMarkdownText(children) {
463
467
  /\[.*\]\(/.test(text) || // links
464
468
  /(?:^|\n)\s*[-*+]\s/.test(child.value) || // unordered lists
465
469
  /(?:^|\n)\s*\d+\.\s/.test(child.value) || // ordered lists
470
+ /(?:^|\n)\s*(`{3,}|~{3,})/.test(child.value) || // fenced code blocks
466
471
  (text.length > 10 && /\n/.test(text.trim())) // multi-line text content (paragraphs)
467
472
  ) {
468
473
  return true;
@@ -493,9 +498,72 @@ function dedent(text) {
493
498
  // Strip the common indent from all lines
494
499
  return lines.map(line => line.slice(minIndent)).join('\n');
495
500
  }
501
+ /**
502
+ * Check if a text buffer currently has an unclosed fenced code block.
503
+ * Returns the fence marker (e.g. "```") if inside a code fence, or null otherwise.
504
+ */
505
+ function getOpenCodeFence(text) {
506
+ const lines = text.split('\n');
507
+ let openFence = null;
508
+ for (const line of lines) {
509
+ if (openFence) {
510
+ // Check if this line closes the fence (same or more chars of same type)
511
+ const trimmed = line.trim();
512
+ if (trimmed.startsWith(openFence) && /^(`{3,}|~{3,})\s*$/.test(trimmed)) {
513
+ openFence = null;
514
+ }
515
+ }
516
+ else {
517
+ // Check if this line opens a fence
518
+ const fenceMatch = line.match(/^(`{3,}|~{3,})/);
519
+ if (fenceMatch) {
520
+ openFence = fenceMatch[1];
521
+ }
522
+ }
523
+ }
524
+ return openFence;
525
+ }
526
+ /**
527
+ * Serialize a hast element back to its original tag text representation.
528
+ * Used to reconstruct component/element tags as plain text when they
529
+ * appear inside fenced code blocks (where they should be code, not components).
530
+ */
531
+ function hastElementToText(node) {
532
+ const tagName = node.tagName || 'div';
533
+ // Restore PascalCase for known components
534
+ const displayName = COMPONENT_TAG_MAP[tagName] || tagName;
535
+ const props = node.properties || {};
536
+ const attrs = Object.entries(props)
537
+ .filter(([key]) => key !== 'className' || props[key]?.length > 0)
538
+ .map(([key, value]) => {
539
+ if (value === true || value === '')
540
+ return key;
541
+ if (typeof value === 'string' && value.startsWith('__jsx:')) {
542
+ // Restore JSX expression syntax
543
+ const expr = value.slice(6).replace(/&quot;/g, '"').replace(/&#10;/g, '\n');
544
+ return `${key}={${expr}}`;
545
+ }
546
+ return `${key}="${value}"`;
547
+ })
548
+ .join(' ');
549
+ const openTag = attrs ? `<${displayName} ${attrs}>` : `<${displayName}>`;
550
+ const childText = (node.children || []).map((c) => {
551
+ if (c.type === 'text')
552
+ return c.value || '';
553
+ if (c.type === 'element')
554
+ return hastElementToText(c);
555
+ return '';
556
+ }).join('');
557
+ return `${openTag}${childText}</${displayName}>`;
558
+ }
496
559
  /**
497
560
  * Extract raw text from hast children, preserving component tags as placeholders.
498
561
  * Returns the markdown text and a map of placeholders to component MdxNodes.
562
+ *
563
+ * Tracks open code fences in the text buffer: if the buffer contains an unclosed
564
+ * fenced code block (e.g. ``` opened but not closed), subsequent component/element
565
+ * children are serialized back to text instead of being processed as real components.
566
+ * This prevents component tags inside code examples from rendering as live components.
499
567
  */
500
568
  async function processComponentChildren(children) {
501
569
  // Separate text runs from component/element children.
@@ -530,42 +598,52 @@ async function processComponentChildren(children) {
530
598
  if (child.type === 'text') {
531
599
  textBuffer += child.value || '';
532
600
  }
533
- else if (isComponentElement(child)) {
534
- await flushTextBuffer();
535
- const componentName = COMPONENT_TAG_MAP[child.tagName];
536
- const props = convertProps(child.properties || {});
537
- const childNodes = child.children && child.children.length > 0
538
- ? await processSmartChildren(child.children)
539
- : [];
540
- result.push({
541
- type: 'component',
542
- name: componentName,
543
- props,
544
- children: childNodes,
545
- });
546
- }
547
- else if (child.type === 'element') {
548
- // Regular HTML element inside a component — flush text first, then serialize
549
- await flushTextBuffer();
550
- const codeBlockProps = extractCodeBlockProps(child);
551
- if (codeBlockProps) {
601
+ else if (isComponentElement(child) || child.type === 'element') {
602
+ // Check if we're inside an unclosed code fence in the text buffer.
603
+ // If so, this element is part of a code example — serialize it back
604
+ // to text rather than processing it as a real component.
605
+ const openFence = getOpenCodeFence(textBuffer);
606
+ if (openFence) {
607
+ // We're inside a code fence — serialize this element as text
608
+ textBuffer += hastElementToText(child);
609
+ }
610
+ else if (isComponentElement(child)) {
611
+ await flushTextBuffer();
612
+ const componentName = COMPONENT_TAG_MAP[child.tagName];
613
+ const props = convertProps(child.properties || {});
614
+ const childNodes = child.children && child.children.length > 0
615
+ ? await processSmartChildren(child.children)
616
+ : [];
552
617
  result.push({
553
618
  type: 'component',
554
- name: 'CodeBlock',
555
- props: codeBlockProps,
556
- children: [],
619
+ name: componentName,
620
+ props,
621
+ children: childNodes,
557
622
  });
558
623
  }
559
- else if (hasNestedComponent(child)) {
560
- const openTag = toHtml({ ...child, children: [] }).replace(/<\/[^>]+>$/, '');
561
- result.push({ type: 'html', content: openTag });
562
- result.push(...await processSmartChildren(child.children));
563
- result.push({ type: 'html', content: `</${child.tagName}>` });
564
- }
565
624
  else {
566
- const html = toHtml(child).trim();
567
- if (html) {
568
- result.push({ type: 'html', content: html });
625
+ // Regular HTML element inside a component — flush text first, then serialize
626
+ await flushTextBuffer();
627
+ const codeBlockProps = extractCodeBlockProps(child);
628
+ if (codeBlockProps) {
629
+ result.push({
630
+ type: 'component',
631
+ name: 'CodeBlock',
632
+ props: codeBlockProps,
633
+ children: [],
634
+ });
635
+ }
636
+ else if (hasNestedComponent(child)) {
637
+ const openTag = toHtml({ ...child, children: [] }).replace(/<\/[^>]+>$/, '');
638
+ result.push({ type: 'html', content: openTag });
639
+ result.push(...await processSmartChildren(child.children));
640
+ result.push({ type: 'html', content: `</${child.tagName}>` });
641
+ }
642
+ else {
643
+ const html = toHtml(child).trim();
644
+ if (html) {
645
+ result.push({ type: 'html', content: html });
646
+ }
569
647
  }
570
648
  }
571
649
  }
@@ -672,9 +750,214 @@ function hasNestedComponent(node) {
672
750
  * Runs the same remark/rehype pipeline but produces an AST
673
751
  * instead of a stringified HTML output.
674
752
  */
753
+ /**
754
+ * Dedent content inside component tags before remark processing.
755
+ * In CommonMark, 4+ spaces of indentation create code blocks.
756
+ * When users indent content inside component tags (e.g. <Tabs> inside <Step>),
757
+ * the inherited indentation causes remark to misinterpret child tags and
758
+ * markdown as indented code blocks. This strips common leading indentation
759
+ * from the content between known component open/close tags.
760
+ *
761
+ * Only processes the outermost component tags (those not nested inside another
762
+ * known component). Inner components are handled naturally since their parent's
763
+ * dedent removes the shared indentation.
764
+ */
765
+ /**
766
+ * Identify which lines in a text block are inside fenced code blocks.
767
+ * Returns a Set of line indices (0-based) that are inside code fences.
768
+ */
769
+ function getCodeFenceLineIndices(lines) {
770
+ const indices = new Set();
771
+ let openFence = null;
772
+ let openIndex = -1;
773
+ for (let i = 0; i < lines.length; i++) {
774
+ const line = lines[i];
775
+ if (openFence) {
776
+ indices.add(i);
777
+ const trimmed = line.trim();
778
+ if (trimmed.startsWith(openFence) && new RegExp(`^${openFence[0]}{${openFence.length},}\\s*$`).test(trimmed)) {
779
+ openFence = null;
780
+ }
781
+ }
782
+ else {
783
+ const fenceMatch = line.match(/^(\s*)(`{3,}|~{3,})/);
784
+ if (fenceMatch) {
785
+ openFence = fenceMatch[2];
786
+ openIndex = i;
787
+ indices.add(i);
788
+ }
789
+ }
790
+ }
791
+ return indices;
792
+ }
793
+ function dedentComponentChildren(markdown) {
794
+ // Build a single regex that matches any known component opening tag
795
+ const allNames = [...new Set([
796
+ ...Object.values(COMPONENT_TAG_MAP),
797
+ ...Object.keys(COMPONENT_TAG_MAP),
798
+ ])];
799
+ const namesPattern = allNames.join('|');
800
+ // Find outermost component blocks and dedent their entire content
801
+ // (including nested component tags) so remark doesn't misinterpret indentation.
802
+ const openTagRegex = new RegExp(`(<(?:${namesPattern})(?:\\s[^>]*)?>)(\\n)`, 'gi');
803
+ let result = '';
804
+ let lastIndex = 0;
805
+ let match;
806
+ openTagRegex.lastIndex = 0;
807
+ while ((match = openTagRegex.exec(markdown)) !== null) {
808
+ // Skip if this tag is nested inside a previously processed block
809
+ if (match.index < lastIndex)
810
+ continue;
811
+ const tagName = match[1].match(/<(\w+)/)?.[1];
812
+ if (!tagName)
813
+ continue;
814
+ const contentStart = match.index + match[0].length;
815
+ // Find the matching closing tag, handling nesting of the SAME tag
816
+ const closeTagRegex = new RegExp(`</${tagName}\\s*>`, 'gi');
817
+ const openNestRegex = new RegExp(`<${tagName}(?:\\s[^>]*)?>`, 'gi');
818
+ closeTagRegex.lastIndex = contentStart;
819
+ openNestRegex.lastIndex = contentStart;
820
+ let depth = 1;
821
+ let closeMatch = null;
822
+ while (depth > 0 && (closeMatch = closeTagRegex.exec(markdown)) !== null) {
823
+ // Count any nested opens of the same tag before this close
824
+ while (true) {
825
+ const nested = openNestRegex.exec(markdown);
826
+ if (!nested || nested.index >= closeMatch.index) {
827
+ openNestRegex.lastIndex = closeMatch.index + closeMatch[0].length;
828
+ break;
829
+ }
830
+ depth++;
831
+ }
832
+ depth--;
833
+ }
834
+ if (!closeMatch)
835
+ continue;
836
+ const contentEnd = closeMatch.index;
837
+ const innerContent = markdown.slice(contentStart, contentEnd);
838
+ // Find minimum indentation of non-empty lines that are NOT inside code fences.
839
+ // Lines inside code fences (including fence markers and their content) are
840
+ // excluded so that code at indent 0 doesn't prevent dedenting of component content.
841
+ const lines = innerContent.split('\n');
842
+ const codeFenceLines = getCodeFenceLineIndices(lines);
843
+ let minIndent = Infinity;
844
+ for (let i = 0; i < lines.length; i++) {
845
+ if (codeFenceLines.has(i))
846
+ continue;
847
+ const line = lines[i];
848
+ if (line.trim().length === 0)
849
+ continue;
850
+ const indent = line.match(/^(\s*)/)?.[1].length ?? 0;
851
+ if (indent > 0 && indent < minIndent)
852
+ minIndent = indent;
853
+ }
854
+ if (minIndent > 0 && minIndent !== Infinity) {
855
+ // Dedent non-code-fence lines by the common indent.
856
+ // Code fence lines are left as-is to preserve their content.
857
+ const dedented = lines.map((line, i) => {
858
+ if (codeFenceLines.has(i))
859
+ return line;
860
+ if (line.trim().length === 0)
861
+ return line;
862
+ return line.slice(Math.min(minIndent, line.match(/^(\s*)/)?.[1].length ?? 0));
863
+ }).join('\n');
864
+ result += markdown.slice(lastIndex, contentStart) + dedented;
865
+ lastIndex = contentEnd;
866
+ // Advance past this entire component block
867
+ openTagRegex.lastIndex = closeMatch.index + closeMatch[0].length;
868
+ }
869
+ }
870
+ if (lastIndex > 0) {
871
+ result += markdown.slice(lastIndex);
872
+ markdown = result;
873
+ // Re-run to handle inner components that were previously skipped
874
+ // (e.g. <Step> inside <Steps> now has reduced indentation that needs further dedenting)
875
+ return dedentComponentChildren(markdown);
876
+ }
877
+ return markdown;
878
+ }
879
+ /**
880
+ * Collapse blank lines inside component blocks so remark-parse treats the
881
+ * entire component (from opening to closing tag) as a single HTML block.
882
+ *
883
+ * In CommonMark, a blank line inside an HTML block (type 6) ends the block.
884
+ * This causes remark to split component content into separate blocks, and
885
+ * plain text between child components becomes a `<p>` element that disrupts
886
+ * parse5's handling of unknown element nesting (siblings become children).
887
+ *
888
+ * By removing blank lines inside component blocks, the entire component tree
889
+ * stays as one HTML block that parse5 can parse correctly.
890
+ */
891
+ function ensureComponentBlockIntegrity(markdown) {
892
+ const allNames = [...new Set([
893
+ ...Object.values(COMPONENT_TAG_MAP),
894
+ ...Object.keys(COMPONENT_TAG_MAP),
895
+ ])];
896
+ const namesPattern = allNames.join('|');
897
+ // Find outermost component blocks and collapse blank lines within them
898
+ const openTagRegex = new RegExp(`^(\\s*<(?:${namesPattern})(?:\\s[^>]*)?>)\\s*$`, 'gim');
899
+ let result = '';
900
+ let lastIndex = 0;
901
+ let match;
902
+ openTagRegex.lastIndex = 0;
903
+ while ((match = openTagRegex.exec(markdown)) !== null) {
904
+ // Skip if inside a previously processed block
905
+ if (match.index < lastIndex)
906
+ continue;
907
+ const tagName = match[1].match(/<(\w+)/)?.[1];
908
+ if (!tagName)
909
+ continue;
910
+ const blockStart = match.index;
911
+ // Find matching closing tag, handling nesting
912
+ const closeTagRegex = new RegExp(`</${tagName}\\s*>`, 'gi');
913
+ const openNestRegex = new RegExp(`<${tagName}(?:\\s[^>]*)?>`, 'gi');
914
+ closeTagRegex.lastIndex = match.index + match[0].length;
915
+ openNestRegex.lastIndex = match.index + match[0].length;
916
+ let depth = 1;
917
+ let closeMatch = null;
918
+ while (depth > 0 && (closeMatch = closeTagRegex.exec(markdown)) !== null) {
919
+ while (true) {
920
+ const nested = openNestRegex.exec(markdown);
921
+ if (!nested || nested.index >= closeMatch.index) {
922
+ openNestRegex.lastIndex = closeMatch.index + closeMatch[0].length;
923
+ break;
924
+ }
925
+ depth++;
926
+ }
927
+ depth--;
928
+ }
929
+ if (!closeMatch)
930
+ continue;
931
+ const blockEnd = closeMatch.index + closeMatch[0].length;
932
+ const block = markdown.slice(blockStart, blockEnd);
933
+ // Replace blank/whitespace-only lines (outside code fences) with HTML
934
+ // comments so remark doesn't end the HTML block at those points.
935
+ // In CommonMark, a blank line inside an HTML type-6 block ends the block.
936
+ // An HTML comment on the line prevents this while being invisible in output.
937
+ // Replace ALL blank/whitespace-only lines with HTML comments — even inside
938
+ // code fences. The code fence content is raw text inside the HTML block and
939
+ // will be re-processed by processComponentChildren through the markdown
940
+ // pipeline, which restores proper code formatting.
941
+ const collapsed = block.replace(/^\s*$/gm, '<!-- -->');
942
+ result += markdown.slice(lastIndex, blockStart) + collapsed;
943
+ lastIndex = blockEnd;
944
+ openTagRegex.lastIndex = blockEnd;
945
+ }
946
+ if (lastIndex > 0) {
947
+ result += markdown.slice(lastIndex);
948
+ return result;
949
+ }
950
+ return markdown;
951
+ }
675
952
  async function processMarkdownToMdxNodes(markdown) {
676
953
  // Pre-process JSX expression attributes into HTML-safe string attributes
677
954
  const preprocessed = preprocessJsxExpressions(markdown);
955
+ // Dedent content inside component tags so that indented children
956
+ // (e.g. <Tabs> inside <Step>) don't get treated as code blocks
957
+ // by remark-parse (4+ spaces = indented code in CommonMark).
958
+ const dedented = dedentComponentChildren(preprocessed);
959
+ // Ensure component block integrity in the markdown
960
+ const normalized = ensureComponentBlockIntegrity(dedented);
678
961
  const processor = unified()
679
962
  .use(remarkParse)
680
963
  .use(remarkGfm)
@@ -683,7 +966,7 @@ async function processMarkdownToMdxNodes(markdown) {
683
966
  .use(rehypeRaw)
684
967
  .use(rehypeSlug)
685
968
  .use(rehypeKatex);
686
- const mdast = processor.parse(preprocessed);
969
+ const mdast = processor.parse(normalized);
687
970
  const hast = await processor.run(mdast);
688
971
  // The hast root has children - process them into MdxNodes
689
972
  const children = hast.children || [];