Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docusaurus.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,18 @@ module.exports = {
};
},
"docusaurus-tailwindcss-loader",
[
"docusaurus-plugin-llms",
{
docsDir: "versioned_docs/version-4.0.0",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

docsDir is hardcoded to versioned_docs/version-4.0.0 — will need updating when we cut the next docs version, since the buttons show on whatever the latest version is (gated on isLatestVersion).

ignoreFiles: ["**/shared/**"],
generateLLMsTxt: true,
generateLLMsFullTxt: true,
generateMarkdownFiles: true,
preserveDirectoryStructure: false,
excludeImports: true,
},
],
],
themeConfig: {
tableOfContents: {
Expand Down
6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
"write-translations": "docusaurus write-translations",
"wnrite-heading-ids": "docusaurus write-heading-ids",
"format": "prettier --write .",
"prepare": "husky install"
"prepare": "husky install",
"postinstall": "patch-package"
},
"lint-staged": {
"**/*": "prettier --write --ignore-unknown"
Expand Down Expand Up @@ -58,14 +59,17 @@
"@tailwindcss/typography": "^0.5.0",
"autoprefixer": "^10.4.0",
"docusaurus": "^1.14.7",
"docusaurus-plugin-llms": "^0.4.0",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Plugin is ^0.4.0 but the patch is pinned to 0.4.0 — patch-package will fail the install if a 0.4.1 publishes. Consider pinning the exact version.

"docusaurus-tailwindcss-loader": "file:plugins/docusaurus-tailwindcss-loader",
"eslint": "^7.32.0",
"eslint-plugin-react": "^7.23.2",
"husky": "^6.0.0",
"lint-staged": "^11.1.2",
"patch-package": "^8.0.1",
"postcss": "^8.4.4",
"postcss-import": "^14.0.2",
"postcss-preset-env": "^7.4.1",
"postinstall-postinstall": "^2.1.0",
"prettier": "^2.5.1",
"prettier-plugin-tailwindcss": "^0.1.4",
"rimraf": "^6.0.1",
Expand Down
89 changes: 89 additions & 0 deletions patches/docusaurus-plugin-llms+0.4.0.patch
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
diff --git a/node_modules/docusaurus-plugin-llms/lib/utils.js b/node_modules/docusaurus-plugin-llms/lib/utils.js
index ed9850cf..a714772e 100644
--- a/node_modules/docusaurus-plugin-llms/lib/utils.js
+++ b/node_modules/docusaurus-plugin-llms/lib/utils.js
@@ -466,7 +466,7 @@ async function resolvePartialImports(content, filePath, importChain = new Set())
// Pattern 1: import PartialName from './_partial.mdx'
// Pattern 2: import { PartialName } from './_partial.mdx'
// Create a fresh regex for each invocation to avoid lastIndex state leakage
- const createImportRegex = () => /^\s*import\s+(?:(\w+)|{\s*(\w+)\s*})\s+from\s+['"]([^'"]+_[^'"]+\.mdx?)['"];?\s*$/gm;
+ const createImportRegex = () => /^\s*import\s+(?:(\w+)|{\s*(\w+)\s*})\s+from\s+['"]([^'"]+\.mdx?)['"];?\s*$/gm;
const imports = new Map();
// First pass: collect all imports
let match;
@@ -474,10 +474,7 @@ async function resolvePartialImports(content, filePath, importChain = new Set())
while ((match = importRegex.exec(content)) !== null) {
const componentName = match[1] || match[2];
const importPath = match[3];
- // Only process imports for partial files (containing underscore)
- if (importPath.includes('_')) {
- imports.set(componentName, importPath);
- }
+ imports.set(componentName, importPath);
}
// Resolve each partial import
for (const [componentName, importPath] of imports) {
@@ -555,10 +552,63 @@ function cleanMarkdownContent(content, excludeImports = false, removeDuplicateHe
// - import "..."; (side-effect imports)
cleaned = cleaned.replace(/^\s*import\s+.*?;?\s*$/gm, '');
}
+ // Fenced code blocks (```lang ... ```) often contain '<...>' text that looks
+ // exactly like a tag to the regexes below but isn't one -- a placeholder like
+ // `wsl --install -d <Distribution Name>`, or a literal XML sample response
+ // like `<User>...</User>`. None of the tag-stripping rules know about code
+ // fences, so mask every whole fenced block out first and restore it verbatim
+ // once stripping is done, the same way quoted prop strings are masked below.
+ // Fences nested inside list items are indented (e.g. " ```shell"), so the
+ // leading whitespace before the backticks is optional and not part of the
+ // backreference -- only the backtick run itself has to match on both ends.
+ const codeBlocks = [];
+ cleaned = cleaned.replace(/^[ \t]*(`{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$/gm, (block) => {
+ codeBlocks.push(block);
+ return `@@KEPLOY_CODEBLOCK_${codeBlocks.length - 1}@@`;
+ });
// Remove HTML tags, but preserve XML content in code blocks
// We need to be selective to avoid removing XML content from code blocks
// This regex targets common HTML tags while being more conservative about XML
cleaned = cleaned.replace(/<\/?(?:div|span|p|br|hr|img|a|strong|em|b|i|u|h[1-6]|ul|ol|li|table|tr|td|th|thead|tbody)\b[^>]*>/gi, '');
+ // Remove leftover custom (PascalCase) React component tags that MDX imports
+ // resolve at real build time but that this plugin doesn't render. Self-closing
+ // tags carry no readable child text, so they're dropped entirely; paired tags
+ // often wrap real content (e.g. <TabItem>...</TabItem>), so only the tag
+ // markers are stripped and their inner text is preserved. Order matters: the
+ // self-closing pass must run first, or the second regex would partially match it.
+ //
+ // Docs also use <YOUR_INGRESS_HOST>-style ALL_CAPS placeholders for readers to
+ // fill in their own values — these also start with a capital letter, so a real
+ // component name is only treated as such when it contains a lowercase letter
+ // and no underscore (true of every actual component in this codebase, never
+ // true of these placeholders).
+ const isRealComponentName = (name) => /[a-z]/.test(name) && !name.includes('_');
+ // Prop values can legitimately contain '<' or '>' inside quoted strings (e.g.
+ // tools={["Linux kernel >= 5.10"]}), which would otherwise be mistaken for the
Comment on lines +61 to +62

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These two regexes run over the whole document including fenced code, so real code gets stripped. e.g. installation/windows.md: wsl --install -d <Distribution Name>wsl --install -d (~5 files); quickstart/java-spring-boot-xml.md: the <User>...</User> wrapper is removed and the XML sample ends up malformed. This is new — those tags were preserved before (the plugin only stripped a fixed HTML allowlist).
Option: skip fenced code blocks when stripping (mask fences → strip prose → restore).

+ // tag's own boundary. Mask '<'/'>' found inside quoted spans first (escape-aware,
+ // so a backslash-escaped quote like \" doesn't fool it into ending the string
+ // early), run the simple original tag regex, then restore what remains.
+ // The quote-matching alternatives are mutually exclusive at every position
+ // (backslash-led vs not), so there's no ambiguity for the engine to backtrack
+ // over -- this avoids the catastrophic-backtracking trap a naive version of
+ // this fix hit earlier on ordinary prose full of apostrophes (don't, it's).
+ const LT_MASK = '@@KEPLOY_LT@@';
+ const GT_MASK = '@@KEPLOY_GT@@';
+ // Only double-quoted strings need masking: every real prop value in this
+ // codebase that contains '<' or '>' uses double quotes (verified against the
+ // actual docs content). Single quotes are deliberately NOT masked here --
+ // they appear constantly as English contractions (it's, don't, Let's), and
+ // masking them paired each stray apostrophe with whichever one came next in
+ // the document, sometimes many paragraphs later, incorrectly treating
+ // everything in between (including real tags) as "inside a string".
+ const masked = cleaned.replace(/"(?:[^"\\]|\\.)*"/g, (q) => q.split('<').join(LT_MASK).split('>').join(GT_MASK));
+ const stripped = masked
+ .replace(/<([A-Z]\w*)(?:\s+[^<>]*?)?\/>/g, (match, tagName) => isRealComponentName(tagName) ? '' : match)
+ .replace(/<\/?([A-Z]\w*)(?:\s+[^<>]*?)?>/g, (match, tagName) => isRealComponentName(tagName) ? '' : match);
+ cleaned = stripped.split(LT_MASK).join('<').split(GT_MASK).join('>');
+ // Restore fenced code blocks now that tag-stripping is done, so their
+ // original content (placeholders, XML samples, etc.) is left untouched.
+ cleaned = cleaned.replace(/@@KEPLOY_CODEBLOCK_(\d+)@@/g, (_match, index) => codeBlocks[Number(index)]);
// Remove redundant content that just repeats the heading (if requested)
if (removeDuplicateHeadings) {
// Split content into lines and process line by line
82 changes: 82 additions & 0 deletions src/components/MarkdownPageActions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import React, {useEffect, useRef, useState} from "react";
import {Copy, Check, FileText, AlertCircle} from "lucide-react";

/**
* MarkdownPageActions - "Copy page" / "View as Markdown" links, rendered
* directly under the page title (mirrors the docs.sarvam.ai / Mintlify
* pattern: title, then a thin actions row, then a divider, then body).
* Point at the .md twin generated by docusaurus-plugin-llms at build time.
*/
export default function MarkdownPageActions({mdUrl}) {
const [copyState, setCopyState] = useState("idle");
const resetTimeoutRef = useRef(null);

useEffect(() => {
return () => clearTimeout(resetTimeoutRef.current);
}, []);

if (!mdUrl) return null;

const handleCopy = async () => {
clearTimeout(resetTimeoutRef.current);
setCopyState("copying");
try {
const res = await fetch(mdUrl);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
const text = await res.text();
await navigator.clipboard.writeText(text);
setCopyState("copied");
} catch (e) {
setCopyState("error");
} finally {
resetTimeoutRef.current = setTimeout(() => setCopyState("idle"), 2000);
}
};

const copyLabel =
copyState === "copying"
? "Copying…"
: copyState === "copied"
? "Copied"
: copyState === "error"
? "Copy failed"
: "Copy as Markdown";

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

add fixed width to prevent the div from shrinking when changing text


const CopyIcon =
copyState === "copied" ? Check : copyState === "error" ? AlertCircle : Copy;

const copyColorClasses =
copyState === "copied"
? "text-green-600 dark:text-green-500"
: copyState === "error"
? "text-red-600 dark:text-red-500"
: "text-gray-500 dark:text-gray-400";

const linkBase =
"inline-flex items-center gap-1 text-[12px] leading-[1.2] py-[0.2rem] px-2 m-0 " +
"no-underline transition-colors duration-150 hover:text-[#ff914d] " +
"[&>svg]:shrink-0 [&>svg]:opacity-75";

return (
<div className="flex items-center mt-1.5 mb-3 pb-3 border-b border-black/[0.08] dark:border-white/10">
<button
type="button"
className={`${linkBase} pl-0 w-[150px] justify-start whitespace-nowrap bg-transparent border-0 cursor-pointer disabled:cursor-default disabled:opacity-70 ${copyColorClasses}`}
onClick={handleCopy}
disabled={copyState === "copying"}
>
<CopyIcon size={12} strokeWidth={2} aria-hidden="true" />
{copyLabel}
</button>
<a
className={`${linkBase} border-l border-black/[0.12] dark:border-white/[0.14] text-gray-500 dark:text-gray-400`}
href={mdUrl}
target="_blank"
rel="noopener noreferrer"
>
<FileText size={12} strokeWidth={2} aria-hidden="true" />
View as Markdown
</a>
</div>
);
}
22 changes: 18 additions & 4 deletions src/theme/DocItem/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import useBaseUrl from "@docusaurus/useBaseUrl";
import useDocusaurusContext from "@docusaurus/useDocusaurusContext";
import {useDocsVersion} from "@docusaurus/plugin-content-docs/client";
import {KeployCloud} from "@site/src/components/KeployCloud";
import MarkdownPageActions from "@site/src/components/MarkdownPageActions";

export default function DocItem(props) {
const {content: DocContent} = props;
Expand Down Expand Up @@ -126,10 +127,10 @@ export default function DocItem(props) {
const schemaType = schemaTypeFromFrontMatter
? schemaTypeFromFrontMatter
: isApi
? "APIReference"
: isBlog
? "BlogPosting"
: "Article";
? "APIReference"
: isBlog
? "BlogPosting"
: "Article";
const authorList = toPersonList(frontMatter?.author || frontMatter?.authors);
const maintainerList = toPersonList(frontMatter?.maintainer);
const contributorList = toPersonList(frontMatter?.contributor);
Expand Down Expand Up @@ -171,6 +172,18 @@ export default function DocItem(props) {
const isCategoryIndex =
frontMatter?.slug === "index" || /\/category\/|\/index\/?$/.test(permalink);
const suppressArticleSchema = isDocsRoot || isCategoryIndex;
// .md twins are only generated for the current (4.0.0) version's docs
// (docusaurus-plugin-llms docsDir points at versioned_docs/version-4.0.0),
// and only for real doc pages, not root/category-index pages.
const showMarkdownActions = isLatestVersion && !suppressArticleSchema;
// Folder-style permalinks (section landing pages, ending in "/") are
// written by docusaurus-plugin-llms as index.md inside that folder,
// not as <folder>.md -- so the two cases need different URL shapes.
const markdownUrl = showMarkdownActions
? permalink.endsWith("/")
? `${permalink}index.md`
: `${permalink}.md`
: null;

const articleSchema =
pageUrl && title && !suppressArticleSchema
Expand Down Expand Up @@ -306,6 +319,7 @@ export default function DocItem(props) {
<Heading as="h1">{title}</Heading>
</header>
)}
{markdownUrl && <MarkdownPageActions mdUrl={markdownUrl} />}
<MDXContent>
<MDXComponent />
</MDXContent>
Expand Down
Loading
Loading