diff --git a/docs/CLAUDE.md b/docs/CLAUDE.md index 77d87164b..cd63c62f8 100644 --- a/docs/CLAUDE.md +++ b/docs/CLAUDE.md @@ -24,6 +24,14 @@ The build runs `docusaurus-plugin-llms` (configured in `docusaurus.config.js`), - `/llms.txt` (curated index) and `/llms-full.txt` (full concatenation) - a per-page `.md` twin for every doc page (so `llms.txt` links resolve) +The plugin reads **source** markdown and has no transform hook, so MDX tab JSX would land +verbatim in those artifacts. `scripts/flatten-llms-tabs.mjs` runs after `docusaurus build` +(chained in the `build` script — it can't be a plugin, since core runs every `postBuild` under +`Promise.all`) and flattens it: `` collapses to the pnpm +command, `` linearizes to `####` headings keeping every `TabItem` body. It never touches +code — fenced _or_ inline — because `docs/api/components/tabs.md` documents bestax-bulma's own +``/``. Covered by `scripts/flatten-llms-tabs.test.mjs` (`pnpm test`). + Consequences: moving/renaming/deleting a doc page changes the published LLM index that AI agents consume — treat URL changes like API changes. The canonical AI entrypoint is the LLMs guide (`docs/guides/llms/` → https://bestax.io/docs/guides/llms) — don't add new competing diff --git a/docs/package.json b/docs/package.json index b08dd6ff7..0b8e9deb0 100644 --- a/docs/package.json +++ b/docs/package.json @@ -6,7 +6,8 @@ "docusaurus": "docusaurus", "docs": "docusaurus start", "start": "docusaurus start", - "build": "docusaurus build", + "build": "docusaurus build && node scripts/flatten-llms-tabs.mjs", + "test": "node --test \"scripts/*.test.mjs\"", "swizzle": "docusaurus swizzle", "deploy": "docusaurus deploy", "clear": "docusaurus clear", diff --git a/docs/scripts/flatten-llms-tabs.mjs b/docs/scripts/flatten-llms-tabs.mjs new file mode 100644 index 000000000..c4d96ca36 --- /dev/null +++ b/docs/scripts/flatten-llms-tabs.mjs @@ -0,0 +1,237 @@ +#!/usr/bin/env node +/** + * Flatten MDX tab JSX in the generated LLM artifacts. + * + * `docusaurus-plugin-llms` reads the *source* markdown, not the rendered HTML, + * and its only cleanup (`cleanMarkdownContent`) strips a fixed allowlist of + * plain HTML tags. `` / `` are not in that list and its options + * expose no transform hook, so tab JSX lands verbatim in llms.txt, + * llms-full.txt and every per-page .md twin. + * + * This runs after `docusaurus build` and rewrites those artifacts only — the + * HTML site is untouched. It cannot be a Docusaurus plugin: core runs every + * plugin's `postBuild` under `Promise.all`, so a sibling plugin would race + * docusaurus-plugin-llms nondeterministically. + * + * Two transforms, because there are two kinds of tabs: + * + * 1. `` — four *equivalent* commands. + * Collapse to a single fenced pnpm block. What an agent copies out of + * llms.txt has to match what a reader sees on the default tab, and pnpm is + * the default tab. + * + * 2. `` / `` — *complementary* content (the skills + * pages tab between ProfileCard.tsx, _profilecard.scss and Usage). Keep + * every body and promote the label to a heading. Keeping only the first + * tab here would silently delete documentation. + * + * Both transforms run only outside code — see `outsideCode` for why that is not + * optional. + */ +import { readFile, writeFile, readdir } from 'node:fs/promises'; +import path from 'node:path'; +import { pathToFileURL } from 'node:url'; + +/** Heading level that a flattened `` is promoted to. */ +const TAB_HEADING = '####'; + +/** Sentinel wrapping masked code so a placeholder can never occur in prose. */ +const NUL = String.fromCharCode(0); + +/** + * `command` is authored in pnpm's verb vocabulary (`add`, `create`, `dlx`), so + * this is a passthrough. The npm/yarn/bun translations live in the React + * component; duplicating them here would be a second source of truth. + */ +const toPnpm = command => `pnpm ${command}`.replace(/\s+/g, ' ').trim(); + +/** + * Quoted `command` only. A braced template — command={`add foo`} — is not + * supported on purpose: its backticks are indistinguishable from an inline code + * span, and code masking has to run first (see `outsideCode`), so the attribute + * would be masked before this ever saw it. Author the prop as a plain string. + */ +function flattenPackageManagerTabs(src) { + return src.replace( + /]*?\bcommand=(?:"([^"]*)"|'([^']*)')[^>]*?\/>/g, + (_match, dq, sq) => '```bash\n' + toPnpm((dq ?? sq).trim()) + '\n```' + ); +} + +function attrLabel(attrs) { + for (const key of ['label', 'value']) { + const m = attrs.match(new RegExp(`\\b${key}=(?:"([^"]*)"|'([^']*)')`)); + if (m) return m[1] ?? m[2] ?? ''; + } + return ''; +} + +function flattenGenericTabs(src) { + // `])`, never ``, which + // is bestax-bulma's own Tabs component as documented in docs/api/components. + return src.replace(/])[^>]*>([\s\S]*?)<\/Tabs>/g, (_m, inner) => { + const items = [ + ...inner.matchAll(/]*)>([\s\S]*?)<\/TabItem>/g), + ]; + if (items.length === 0) return inner.trim(); + return items + .map(([, attrs, body]) => { + const label = attrLabel(attrs); + const text = body.trim(); + return label ? `${TAB_HEADING} ${label}\n\n${text}` : text; + }) + .join('\n\n'); + }); +} + +/** + * Apply `fn` only outside code — fenced blocks *and* inline spans. + * + * Both exclusions are load-bearing: `docs/api/components/tabs.md` documents + * bestax-bulma's own `` / `` inside tsx fences, and the + * migration guides mention the Tabs component inline in prose. Neither is a + * Docusaurus theme tab and neither may be rewritten. + * + * Mask rather than split: a `` block *wraps* fenced code, so the document + * has to stay contiguous for `…` to match across it. + */ +/** + * Mask fenced code blocks, per CommonMark rather than by regex. + * + * A regex can't do this: fences are variable-length and come in two characters, + * and the closing fence only has to be *at least* as long as the opening one. + * `docs/api/helpers/theme.md` and `docs/tutorial-basics/markdown-features.mdx` + * both wrap ``` examples in ```` fences, so mis-pairing is not hypothetical. + */ +function maskFences(src, hold) { + const out = []; + let open = null; + let buf = []; + + for (const line of src.split('\n')) { + const fence = line.match(/^ {0,3}(`{3,}|~{3,})(.*)$/); + + if (!open) { + // A backtick fence's info string may not itself contain a backtick. + const validOpen = + fence && !(fence[1][0] === '`' && fence[2].includes('`')); + if (validOpen) { + open = { char: fence[1][0], len: fence[1].length }; + buf = [line]; + } else { + out.push(line); + } + continue; + } + + buf.push(line); + const close = line.match(/^ {0,3}(`{3,}|~{3,})[ \t]*$/); + if (close && close[1][0] === open.char && close[1].length >= open.len) { + out.push(hold(buf.join('\n'))); + open = null; + buf = []; + } + } + + // An unterminated fence runs to end of document (CommonMark). Mask it: never + // mutate content we can't confidently parse. + if (open) out.push(hold(buf.join('\n'))); + + return out.join('\n'); +} + +/** + * Apply `fn` only outside code — fenced blocks *and* inline spans. + * + * Both exclusions are load-bearing: `docs/api/components/tabs.md` documents + * bestax-bulma's own `` / `` inside tsx fences, and the + * migration guides mention the Tabs component inline in prose. Neither is a + * Docusaurus theme tab and neither may be rewritten. + * + * Mask rather than split: a `` block *wraps* fenced code, so the document + * has to stay contiguous for `…` to match across it. + * + * Inline spans are matched single-line only. CommonMark allows one to wrap, but + * an unpaired backtick in prose would then swallow the rest of the document — + * the failure mode of guessing wrong here is much worse than the miss. + */ +function outsideCode(src, fn) { + const held = []; + const hold = chunk => { + held.push(chunk); + return NUL + (held.length - 1) + NUL; + }; + + const masked = maskFences(src, hold).replace( + /(`+)(?:(?!\1)[^\n])*?\1/g, + hold + ); + + const restore = new RegExp(NUL + '(\\d+)' + NUL, 'g'); + return fn(masked).replace(restore, (_m, i) => held[Number(i)]); +} + +/** + * Rewrite one artifact's contents. Idempotent. + * + * Every rewrite happens inside `outsideCode` — including the import and blank + * line cleanup. Running those after restoration would reach into fenced code and + * strip `import Tabs …` lines out of examples, or collapse deliberate blank + * lines in a code block. + */ +export function transform(src) { + return outsideCode(src, chunk => + flattenGenericTabs(flattenPackageManagerTabs(chunk)) + .replace(/^[ \t]*import\s+(?:Tabs|TabItem|PackageManagerTabs)\b.*$/gm, '') + .replace(/\n{3,}/g, '\n\n') + ); +} + +/** + * Cheap prefilter for `main`. Matches the imports too — `transform` strips + * orphaned tab imports, so an artifact carrying only those still has work to do. + */ +export const NEEDS_FLATTENING = + / { + console.error(`flatten-llms-tabs: ${error.message}`); + process.exitCode = 1; + }); +} diff --git a/docs/scripts/flatten-llms-tabs.test.mjs b/docs/scripts/flatten-llms-tabs.test.mjs new file mode 100644 index 000000000..3c6d51f00 --- /dev/null +++ b/docs/scripts/flatten-llms-tabs.test.mjs @@ -0,0 +1,265 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { + transform, + isLlmArtifact, + NEEDS_FLATTENING, +} from './flatten-llms-tabs.mjs'; + +const fence = (lang, body) => '```' + lang + '\n' + body + '\n```'; + +test('PackageManagerTabs collapses to a single pnpm block', () => { + const out = transform( + '' + ); + assert.equal(out.trim(), fence('bash', 'pnpm add @allxsmith/bestax-bulma')); +}); + +test('PackageManagerTabs passes the pnpm verb vocabulary through', () => { + for (const [command, expected] of [ + ['create bestax@latest my-app', 'pnpm create bestax@latest my-app'], + [ + 'dlx create-next-app@latest my-app', + 'pnpm dlx create-next-app@latest my-app', + ], + ['add -D typescript', 'pnpm add -D typescript'], + ['install', 'pnpm install'], + ]) { + const out = transform(``); + assert.equal(out.trim(), fence('bash', expected)); + } +}); + +test('PackageManagerTabs accepts a single-quoted command', () => { + assert.match( + transform(""), + /pnpm add foo/ + ); +}); + +test('a braced-template command is left alone, by design', () => { + // Its backticks are indistinguishable from an inline code span, and masking + // has to run first. Authors use a plain string; this asserts we fail loudly + // (untouched JSX in the artifact) rather than silently mangling it. + const src = ''; + assert.equal(transform(src), src); +}); + +test('generic Tabs keep every body and promote labels to headings', () => { + const src = [ + '', + '', + '', + fence('tsx', 'const x = 1;'), + '', + '', + '', + '', + fence('tsx', 'const y = 2;'), + '', + '', + '', + ].join('\n'); + + const out = transform(src); + + // Complementary content — dropping non-first tabs would delete documentation. + assert.match(out, /^#### ProfileCard\.tsx$/m); + assert.match(out, /^#### Usage$/m); + assert.match(out, /const x = 1;/); + assert.match(out, /const y = 2;/); + assert.doesNotMatch(out, / { + const src = '\n\n\nbody\n\n\n'; + assert.match(transform(src), /^#### scss$/m); +}); + +test("bestax-bulma's own Tabs component survives inside fences", () => { + // Regression: `', + ' Home', + '', + ].join('\n') + ), + ].join('\n'); + + assert.equal(transform(src), src); +}); + +test('Tabs mentioned in inline code spans in prose survive', () => { + const src = + 'You can use helper props with `` and its subcomponents.\n\n' + + 'The legacy `` API is preserved, and `` now provides context.'; + + assert.equal(transform(src), src); +}); + +test('a fenced Tabs example is not flattened by a later real Tabs block', () => { + const src = [ + fence('mdx', '\nx\n'), + '', + '', + 'real body', + '', + ].join('\n'); + + const out = transform(src); + + assert.match( + out, + /```mdx\n\nx<\/TabItem>\n<\/Tabs>\n```/ + ); + assert.match(out, /^#### Real$/m); + assert.match(out, /real body/); +}); + +test('orphaned tab imports are dropped', () => { + const src = [ + "import Tabs from '@theme/Tabs';", + "import TabItem from '@theme/TabItem';", + "import PackageManagerTabs from '@site/src/components/PackageManagerTabs';", + "import { ExampleMeta } from '@site/src/components/SkillExamples';", + '', + '# Title', + ].join('\n'); + + const out = transform(src); + + assert.doesNotMatch(out, /@theme\/Tabs|@theme\/TabItem|PackageManagerTabs/); + // Unrelated imports are left alone — the llms plugin owns that stripping. + assert.match(out, /ExampleMeta/); +}); + +test('transform is idempotent', () => { + const src = [ + '', + '', + '', + '', + '', + fence('ts', 'const a = 1;'), + '', + '', + '', + '', + 'Prose about `` stays put.', + ].join('\n'); + + const once = transform(src); + assert.equal(transform(once), once); +}); + +test('content is never lost to placeholder collisions', () => { + // Masked code is NUL-delimited, so digit runs in prose cannot be mistaken + // for a placeholder on restore. + const src = 'Release 5 8 0 shipped.\n\n' + fence('bash', 'pnpm add foo'); + assert.equal(transform(src), src); +}); + +test('a longer fence wrapping shorter fences is masked as one block', () => { + // Real shape: docs/api/helpers/theme.md and tutorial-basics/markdown-features + // wrap ``` examples in ```` fences. Mis-pairing here shifts every mask + // boundary after it in llms-full.txt. + const src = [ + '````md', + '```tsx', + '', + 'not a real tab', + '', + '```', + '````', + '', + '', + 'real body', + '', + ].join('\n'); + + const out = transform(src); + + assert.match(out, /````md\n```tsx\n\n/); + assert.match(out, /^#### Real$/m); + assert.doesNotMatch(out, /#### Nope/); +}); + +test('tilde fences are masked', () => { + const src = [ + '~~~tsx', + '', + 'y', + '', + '~~~', + ].join('\n'); + assert.equal(transform(src), src); +}); + +test('a tilde fence is not closed by a backtick fence', () => { + const src = [ + '~~~md', + '```', + 'still inside the tilde fence', + '```', + '~~~', + ].join('\n'); + assert.equal(transform(src), src); +}); + +test('an indented fence (up to 3 spaces) still opens a block', () => { + const src = [' ```tsx', ' x', ' ```'].join('\n'); + assert.equal(transform(src), src); +}); + +test('imports inside a fenced example are preserved', () => { + // Regression: the cleanup used to run after code was restored, so a fenced + // example demonstrating the import lost the line. + const src = [ + 'Import it first:', + '', + fence( + 'tsx', + "import Tabs from '@theme/Tabs';\n\nexport default function Demo() {}" + ), + ].join('\n'); + + assert.equal(transform(src), src); +}); + +test('deliberate blank lines inside a fence are preserved', () => { + const src = [ + '', + '', + fence('ts', 'const a = 1;\n\n\nconst b = 2;'), + ].join('\n'); + + const out = transform(src); + + assert.match(out, /const a = 1;\n\n\nconst b = 2;/); + assert.match(out, /pnpm add foo/); +}); + +test('an unterminated fence is masked rather than rewritten', () => { + const src = ['```tsx', '', 'y'].join('\n'); + assert.equal(transform(src), src); +}); + +test('NEEDS_FLATTENING matches import-only artifacts', () => { + assert.equal(NEEDS_FLATTENING.test("import Tabs from '@theme/Tabs';"), true); + assert.equal(NEEDS_FLATTENING.test(''), true); + assert.equal(NEEDS_FLATTENING.test('# Just a heading'), false); +}); + +test('isLlmArtifact selects .md twins and llms*.txt only', () => { + assert.equal(isLlmArtifact('build/docs/guides/intro.md'), true); + assert.equal(isLlmArtifact('build/llms.txt'), true); + assert.equal(isLlmArtifact('build/llms-full.txt'), true); + assert.equal(isLlmArtifact('build/robots.txt'), false); + assert.equal(isLlmArtifact('build/assets/js/main.js'), false); + assert.equal(isLlmArtifact('build/index.html'), false); +});