diff --git a/.gitignore b/.gitignore index 2708fdb..eb02267 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,9 @@ node_modules .env _pagefind/ .claude/settings.local.json + +# Generated from content/ at build time +/public/llms.txt +/public/llms-full.txt +/public/.ai-docs-manifest.json +/public/**/*.md diff --git a/README.md b/README.md index dd7c466..8e03c55 100644 --- a/README.md +++ b/README.md @@ -40,3 +40,16 @@ If you have feedback, please open an issue or reach out to [@williamhzo](https:/ ## License All content is © Shape Factory. + +## Documentation for AI tools + +The production build generates `/llms.txt`, `/llms-full.txt`, and Markdown versions of all documentation pages from `content/` and the shared cards and callouts. Each HTML page links to its Markdown alternative. `/llms.txt` groups entry points by task, while `/llms-full.txt` contains the technical documentation corpus. + +```bash +bun run generate:ai-docs +bun run test:ai-docs +``` + +Edit the MDX source or shared components, then regenerate the assets. Do not edit generated Markdown directly. The converter handles the current static MDX patterns and stops on unknown components, unclosed code fences, or unmapped documentation links. Add conversion support and a test when introducing a new MDX component. Fenced code blocks are preserved verbatim. + +Generated files under `public/` are ignored by Git. Both development and production scripts generate them from the existing source before starting Next.js. `.ai-docs-manifest.json` records the generated page paths so deleted pages are removed on regeneration. Each HTML page derives its Markdown alternate from its source file path, which the generator mirrors under `public/`. Titles, summaries, examples, and component text come from the original content; only navigation grouping is configured in the generator. diff --git a/app/[[...mdxPath]]/page.tsx b/app/[[...mdxPath]]/page.tsx index 0df8644..ac9f351 100644 --- a/app/[[...mdxPath]]/page.tsx +++ b/app/[[...mdxPath]]/page.tsx @@ -1,3 +1,4 @@ +import { paths } from '@paths'; import { generateStaticParamsFor, importPage } from 'nextra/pages'; import { useMDXComponents as getMDXComponents } from '../../mdx-components'; @@ -6,7 +7,20 @@ export const generateStaticParams = generateStaticParamsFor('mdxPath'); export async function generateMetadata(props) { const params = await props.params; const { metadata } = await importPage(params.mdxPath); - return metadata; + // Nextra exposes the source file (e.g. content/quick-start/index.mdx); the AI docs + // generator writes its Markdown twin to the same relative path under public/. + const markdown = metadata.filePath?.replace(/^content\//, '/').replace(/\.mdx?$/, '.md'); + if (!markdown) return metadata; + return { + ...metadata, + alternates: { + ...metadata.alternates, + types: { + ...metadata.alternates?.types, + 'text/markdown': paths.canonical + markdown, + }, + }, + }; } const Wrapper = getMDXComponents({}).wrapper; diff --git a/app/layout.tsx b/app/layout.tsx index 77903c8..4fd3507 100644 --- a/app/layout.tsx +++ b/app/layout.tsx @@ -57,7 +57,7 @@ export default async function RootLayout({ children }) { light: '#fff', }} > - {/* Your additional tags should be passed as `children` of `` element */} + diff --git a/next.config.ts b/next.config.ts index aa2f155..c2d57af 100644 --- a/next.config.ts +++ b/next.config.ts @@ -4,6 +4,19 @@ import type { NextConfig } from 'next'; const withNextra = nextra({}); export default withNextra({ + headers: async () => [ + ...['/llms.txt', '/llms-full.txt'].map((source) => ({ + source, + headers: [{ key: 'Content-Type', value: 'text/plain; charset=utf-8' }], + })), + { + source: '/:path*.md', + headers: [ + { key: 'Content-Type', value: 'text/markdown; charset=utf-8' }, + { key: 'Link', value: '; rel="describedby"' }, + ], + }, + ], redirects: () => [ { source: '/building-on-shape/gasback', diff --git a/package.json b/package.json index 5b86e59..2954a92 100644 --- a/package.json +++ b/package.json @@ -1,9 +1,11 @@ { "scripts": { - "dev": "next dev", - "build": "next build", + "dev": "node scripts/generate-ai-docs.mjs && next dev", + "build": "node scripts/generate-ai-docs.mjs && next build", "start": "next start", - "postbuild": "pagefind --site .next/server/app --output-path public/_pagefind" + "postbuild": "pagefind --site .next/server/app --output-path public/_pagefind", + "generate:ai-docs": "node scripts/generate-ai-docs.mjs", + "test:ai-docs": "SHAPE_DOCS_TEST_ROOT=. node --test scripts/generate-ai-docs.test.mjs" }, "dependencies": { "@tailwindcss/postcss": "^4.1.18", diff --git a/public/llms.txt b/public/llms.txt deleted file mode 100644 index e0d3220..0000000 --- a/public/llms.txt +++ /dev/null @@ -1,70 +0,0 @@ -# Shape Network Documentation - -> Shape is a culture-first EVM-compatible L2 built on Ethereum and the Optimism Superchain. It returns 80% of sequencer fees to contract owners via Gasback. Chain ID: 360 (mainnet), 11011 (testnet). Currency: ETH. RPC: https://mainnet.shape.network - -## Getting Started - -- [Introduction](https://docs.shape.network): Overview of Shape, the culture-first L2 for creators and the new NFT economy -- [Wallet Setup](https://docs.shape.network/wallet-setup): Add Shape to your wallet, bridge ETH, mint your Stack -- [Gasback](https://docs.shape.network/gasback): Claim back 80% of L2 sequencer fees users spend interacting with your contracts -- [The Stack](https://docs.shape.network/the-stack): Dynamic NFT reputation system with bronze, silver, gold, and special medals - -## Quick Start - -- [Quick Start](https://docs.shape.network/quick-start): Developer onboarding hub for Shape -- [Connect to Shape](https://docs.shape.network/quick-start/connect-to-shape): Configure viem, wagmi, Foundry, and ethers.js for Shape Mainnet (chain ID 360) and Shape Sepolia (chain ID 11011) -- [Deploy a Contract](https://docs.shape.network/quick-start/deploy-a-contract): Deploy and verify a smart contract on Shape with Foundry - -## Building on Shape - -- [Builder Kit](https://docs.shape.network/building-on-shape/builder-kit): Next.js starter with wallet connect (wagmi), NFT fetching, Shape RPC, and Shadcn UI -- [AI Agents](https://docs.shape.network/building-on-shape/ai): Build AI agents with MCP, Shape MCP server, and Vercel AI SDK -- [Transaction Fees](https://docs.shape.network/building-on-shape/transaction-fees): L1 security fees + L2 execution fees. 80% of L2 fees go back to contract owners via Gasback, 15% to Optimism Collective, 5% to Shape Foundation -- [Differences from Ethereum](https://docs.shape.network/building-on-shape/differences-ethereum-shape): EVM equivalent via OP Stack with minor opcode changes, dual-fee system, faster block times -- [Alchemy API](https://docs.shape.network/building-on-shape/alchemy-api): Full Alchemy tool suite available on Shape -- [Superchain Incentives](https://docs.shape.network/building-on-shape/superchain-incentives): RetroPGF, free contract deployment, gas sponsorship, launch support - -## Technical Reference - -- [Network Information](https://docs.shape.network/technical-details/network-information): Mainnet chain ID 360, RPC https://mainnet.shape.network, explorer https://shapescan.xyz. Testnet chain ID 11011, RPC https://sepolia.shape.network, explorer https://sepolia.shapescan.xyz -- [Contract Addresses](https://docs.shape.network/technical-details/contract-addresses): L1 and L2 contract addresses for mainnet and Sepolia. Gasback contract: 0xf5e602c87d675E978F097503aedE4A766285a08B (mainnet), 0xdF329d59bC797907703F7c198dDA2d770fC45034 (testnet) -- [Run a Node](https://docs.shape.network/technical-details/run-a-node): Run Shape mainnet and Sepolia nodes using op-node with custom rollup.json and genesis.json - -## Onchain Projects - -- [Onchain Compatible](https://docs.shape.network/building-on-shape/onchain-compatible): Collection of interoperable onchain projects on Shape -- [Assembly](https://docs.shape.network/building-on-shape/onchain-compatible/assembly): ERC1155 crafting system built on Otoms. Blueprints, tiers, mutator contracts, fungible and non-fungible items -- [OTOM](https://docs.shape.network/building-on-shape/onchain-compatible/otom): Onchain particle chemistry by Kjetil Golid. Mine otoms, annihilate for energy, react to create molecules - -## Tools - -- [Account Abstraction](https://docs.shape.network/tools/account-abstraction): Alchemy Bundler, Gas Manager, Embedded Accounts, Smart Accounts. Crossmint NFT Checkout and Wallet-as-a-Service -- [Bridges](https://docs.shape.network/tools/bridges): Relay (instant bridging), Superbridge (native bridging), Alchemy bridge. Testnet bridges available for Sepolia -- [Explorers](https://docs.shape.network/tools/explorers): Shapescan (block explorer), Deca (NFT explorer), Zapper (human-readable onchain activity) -- [Data Indexers](https://docs.shape.network/tools/data-indexers): Alchemy NFT/Token/Transfers APIs and Webhooks, Alchemy Subgraphs, Goldsky, Reservoir, SimpleHash -- [Faucets](https://docs.shape.network/tools/faucets): Alchemy and Optimism faucets for Shape Sepolia testnet ETH -- [Node Providers](https://docs.shape.network/tools/node-providers): Alchemy Supernode RPC -- [Oracles - Gelato VRF](https://docs.shape.network/tools/oracles/gelato-vrf): Verifiable randomness using Drand for gaming, DeFi, NFT generation -- [Safes & Asset Security](https://docs.shape.network/tools/safes-asset-security): Safe multisig on Shape, Delegate for hot wallet claim/mint/ownership -- [Sybil Resistance](https://docs.shape.network/tools/sybil-resistance): Gitcoin Passport, Premint allowlists, Crossmint Verifiable Credentials - -## Tutorials - -- [Launch an NFT Collection](https://docs.shape.network/tutorials/mint-nft-collection): Deploy an ERC-721 contract on Shape with Foundry, mint an NFT, verify on Shapescan -- [Register Contract for Gasback (Dashboard)](https://docs.shape.network/tutorials/registering-contract-gasback/dashboard): Step-by-step UI guide to register contracts via the Gasback dashboard -- [Register Contract for Gasback (Programmatic)](https://docs.shape.network/tutorials/registering-contract-gasback/programmatically): Three Solidity approaches to register contracts for Gasback - -## Optional - -- [Shape Website](https://shape.network) -- [Discord](https://discord.com/invite/shape-l2) -- [X / Twitter](https://x.com/shape) -- [GitHub](https://github.com/shape-network) -- [Shape MCP Server](https://github.com/shape-network/mcp-server): MCP server for AI agents to query Gasback, NFT analytics, Stack medals -- [Builder Kit Repo](https://github.com/shape-network/builder-kit): Next.js starter template source code -- [Assembly Repo](https://github.com/shape-network/assembly): Assembly items system source code and contracts -- [OTOM Contracts](https://github.com/shape-network/otom-contracts): OTOM smart contracts source code -- [Gasback Dashboard](https://gasback.shape.network): Register and manage Gasback for your contracts -- [The Stack App](https://stack.shape.network): Mint your Stack and track medals -- [Shapescan](https://shapescan.xyz): Block explorer -- [Deca](https://deca.art): NFT explorer diff --git a/scripts/generate-ai-docs.mjs b/scripts/generate-ai-docs.mjs new file mode 100644 index 0000000..ba32515 --- /dev/null +++ b/scripts/generate-ai-docs.mjs @@ -0,0 +1,298 @@ +import { readFile, readdir, mkdir, writeFile, rm } from 'node:fs/promises'; +import path from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ORIGIN = 'https://docs.shape.network'; +const decode = (text) => + text.replace( + /&(apos|quot|amp|lt|gt|nbsp);/g, + (_, key) => ({ apos: "'", quot: '"', amp: '&', lt: '<', gt: '>', nbsp: ' ' })[key] + ); + +// Protect code before processing MDX: imports and JSX inside examples are content. +export function protectCode(text) { + const saved = []; + const save = (value) => { + saved.push(value); + return `\u0000CODE${saved.length - 1}\u0000`; + }; + let fence; + let block = []; + const lines = []; + for (const line of text.split('\n')) { + const marker = line.match(/^ {0,3}(`{3,}|~{3,})/); + if (!fence && marker) { + fence = marker[1]; + block = [line]; + } else if (fence) { + block.push(line); + if ( + marker && + marker[1][0] === fence[0] && + marker[1].length >= fence.length && + /^ {0,3}(`{3,}|~{3,})\s*$/.test(line) + ) { + lines.push(save(block.join('\n'))); + fence = undefined; + } + } else lines.push(line); + } + if (fence) throw new Error('Unclosed code fence'); + const protectedText = lines.join('\n').replace(/(`+)([^\n]*?)\1/g, save); + return { + text: protectedText, + restore: (value) => value.replace(/\u0000CODE(\d+)\u0000/g, (_, index) => saved[Number(index)]), + }; +} + +function attr(attributes, name, paths) { + const literal = attributes.match(new RegExp(`\\b${name}="([^"]*)"`)); + if (literal) return decode(literal[1]); + const ref = attributes.match(new RegExp(`\\b${name}=\\{paths\\.(\\w+)\\}`)); + if (ref && paths[ref[1]]) return paths[ref[1]]; + throw new Error(`Unsupported or missing ${name}: ${attributes}`); +} + +function renderJsx(text, components, paths) { + text = text.replace(/<([A-Z]\w*)\s*\/>/g, (_, name) => { + if (!(name in components)) throw new Error(`Unsupported component: ${name}`); + return renderJsx(components[name], components, paths); + }); + text = text.replace(//g, (_, attributes) => { + const title = attr(attributes, 'title', paths); + const href = attr(attributes, 'href', paths); + const subtitle = /\bsubtitle=/.test(attributes) + ? `: ${attr(attributes, 'subtitle', paths)}` + : ''; + return `\n- [${title}](${href})${subtitle}\n`; + }); + text = text.replace( + /([\s\S]*?)<\/Link>/g, + (_, attributes, label) => + `[${label.trim().replace(/\s+/g, ' ')}](${attr(attributes, 'href', paths)})` + ); + text = text + .replace(/<\/?Cards>/g, '') + .replace(//g, '\n') + .replace(/\{' '\}/g, ' '); + text = text.replace( + /([\s\S]*?)<\/Callout>/g, + (_, type, body) => + '\n' + + (type === 'warning' ? '> Warning:\n>\n' : '') + + body + .trim() + .split('\n') + .map((line) => '> ' + line.trim()) + .join('\n') + + '\n' + ); + if (/<\/?[A-Za-z][^>]*>/.test(text)) throw new Error('Unconverted JSX/HTML in document'); + return decode(text); +} + +export function convert( + source, + { components = {}, paths = {}, routes = new Map(), route = '/' } = {} +) { + const code = protectCode(source); + let text = code.text.replace(/^---\n[\s\S]*?\n---\n/, ''); + text = text.replace(/^import\s+[\s\S]*?;\s*$/gm, ''); + text = renderJsx(text, components, paths); + text = text.replace(/\]\(([^\s)]+)\)/g, (_, href) => { + if (href.startsWith('#')) return `](${href})`; + const url = new URL(href, ORIGIN + route); + if (url.origin === ORIGIN) { + const markdown = routes.get(url.pathname.replace(/\/$/, '') || '/'); + if (markdown) url.pathname = markdown; + else if (!path.extname(url.pathname)) throw new Error(`Unmapped internal link: ${href}`); + } + return `](${url.href})`; + }); + return ( + code.restore( + text + .replace(/[ \t]+$/gm, '') + .replace(/\n{3,}/g, '\n\n') + .trim() + ) + '\n' + ); +} + +async function walk(directory) { + const result = []; + for (const entry of await readdir(directory, { withFileTypes: true })) { + const full = path.join(directory, entry.name); + if (entry.isDirectory()) result.push(...(await walk(full))); + else if (/\.mdx?$/.test(entry.name)) result.push(full); + } + return result.sort(); +} + +export async function generate(root) { + const content = path.join(root, 'content'); + const publicDir = path.join(root, 'public'); + const pathsSource = await readFile(path.join(root, 'paths.ts'), 'utf8'); + const paths = Object.fromEntries( + [...pathsSource.matchAll(/(\w+):\s*'([^']*)'/g)].map((match) => [match[1], match[2]]) + ); + const components = {}; + for (const name of ['cards.tsx', 'callouts.tsx']) { + const source = await readFile(path.join(root, 'components', name), 'utf8'); + for (const match of source.matchAll( + /export const (\w+)[\s\S]*?return \(([\s\S]*?)\n \);\n};/g + )) + components[match[1]] = match[2]; + } + const records = (await walk(content)).map((file) => { + const relative = path + .relative(content, file) + .replaceAll(path.sep, '/') + .replace(/\.mdx?$/, ''); + const route = '/' + relative.replace(/(^|\/)index$/, ''); + return { file, route: route.replace(/\/$/, '') || '/', markdown: '/' + relative + '.md' }; + }); + const routes = new Map(records.map((record) => [record.route, record.markdown])); + if (routes.size !== records.length) throw new Error('Duplicate content routes'); + const rendered = []; + for (const record of records) { + const source = await readFile(record.file, 'utf8'); + const body = convert(source, { components, paths, routes, route: record.route }); + const title = body.match(/^# (.+)$/m)?.[1]; + if (!title) throw new Error(`Missing title: ${record.file}`); + // Summarise from the lead (between the title and the first section, or the first + // section when there is no lead): its opening paragraph, else the first column of + // an opening table, else a paragraph that does not just introduce an example, + // else the page's section headings. + const [intro, first = ''] = body.slice(body.indexOf('\n') + 1).split(/^## /m); + const lead = (intro.trim() ? intro : first.slice(first.indexOf('\n') + 1)) + .split('\n\n') + .map((block) => block.trim()) + .filter(Boolean); + const isParagraph = (block) => !/^(#|>|-|\*|\d+\.|\||`|~|!\[)/.test(block); + const tableRows = (block) => + block + .split('\n') + .slice(2) + .map((row) => row.split('|')[1]?.trim()) + .filter(Boolean); + const sections = [...body.matchAll(/^## (.+)$/gm)].map((match) => match[1].trim()); + let summary; + if (lead[0] && isParagraph(lead[0])) summary = lead[0].replace(/:$/, '.'); + else if (lead[0]?.startsWith('|') && tableRows(lead[0]).length) + summary = `${title}: ${tableRows(lead[0]).join(', ')}.`; + else summary = lead.find((block) => isParagraph(block) && !block.endsWith(':')); + if (!summary && sections.length) summary = `${title}: ${sections.join(', ')}.`; + let description = (summary || `Documentation for ${title}.`) + .replace(/\[([^\]]+)\]\([^)]*\)/g, '$1') + .replace(/[*`]/g, '') + .replace(/\s+/g, ' ') + .trim(); + if (description.length > 220) + description = description.slice(0, 217).replace(/\s+\S*$/, '') + '...'; + rendered.push({ ...record, title, description, body }); + } + + // Remove only previously generated pages, so deleted source pages cannot linger. + const manifestPath = path.join(publicDir, '.ai-docs-manifest.json'); + let previous = []; + try { + previous = JSON.parse(await readFile(manifestPath, 'utf8')); + } catch (error) { + if (error.code !== 'ENOENT') throw error; + } + for (const relative of previous) { + const target = path.resolve(publicDir, relative); + if (!target.startsWith(path.resolve(publicDir) + path.sep) || !relative.endsWith('.md')) + throw new Error('Invalid generated file manifest'); + await rm(target, { force: true }); + } + await mkdir(publicDir, { recursive: true }); + for (const record of rendered) { + const file = path.join(publicDir, record.markdown); + await mkdir(path.dirname(file), { recursive: true }); + await writeFile(file, record.body); + } + const sections = [ + [ + 'Start Here', + ['/', '/wallet-setup', '/quick-start', '/technical-details/network-information'], + ], + [ + 'Gasback and Fees', + [ + '/gasback', + '/building-on-shape/transaction-fees', + '/tutorials/registering-contract-gasback', + ], + ], + [ + 'Build Applications', + [ + '/quick-start/connect-to-shape', + '/quick-start/deploy-a-contract', + '/building-on-shape/builder-kit', + '/tutorials/mint-nft-collection', + '/building-on-shape/ai', + ], + ], + [ + 'Explore and Operate', + [ + '/the-stack', + '/technical-details/contract-addresses', + '/technical-details/run-a-node', + '/building-on-shape/differences-ethereum-shape', + ], + ], + ]; + const used = new Set(); + const introduction = rendered.find((record) => record.route === '/'); + let index = + `# Shape Documentation\n\n> ${introduction.description}\n\n` + + 'Links below are generated from the existing documentation source. Follow individual pages for details.\n\n'; + for (const [title, entries] of [ + ...sections, + ['Tools and Further Reading', rendered.map((record) => record.route)], + ]) { + const selected = entries.filter((route) => !used.has(route)); + index += `## ${title}\n\n`; + for (const route of selected) { + const record = rendered.find((record) => record.route === route); + if (!record) throw new Error(`Missing curated route: ${route}`); + used.add(route); + index += `- [${record.title}](${ORIGIN}${record.markdown}): ${record.description}\n`; + } + index += '\n'; + } + index += + '## Optional\n\n- [All technical documentation](' + + ORIGIN + + '/llms-full.txt): All generated pages in one file. Use individual pages for narrower questions.\n'; + await writeFile(path.join(publicDir, 'llms.txt'), index); + const full = + '# Shape Technical Documentation\n\nGenerated from the existing documentation source.\n\n' + + rendered + .map( + (record) => + `---\n\nCanonical page: ${ORIGIN}${record.route}\nMarkdown page: ${ORIGIN}${record.markdown}\n\n${record.body}` + ) + .join('\n'); + await writeFile(path.join(publicDir, 'llms-full.txt'), full); + await writeFile( + manifestPath, + JSON.stringify( + rendered.map((record) => record.markdown.slice(1)), + null, + 2 + ) + '\n' + ); + return { pages: rendered.length, bytes: Buffer.byteLength(full) }; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + const result = await generate(path.resolve(process.argv[2] || '.')); + console.log( + `Generated ${result.pages} Markdown pages, llms.txt, and llms-full.txt (${result.bytes} bytes).` + ); +} diff --git a/scripts/generate-ai-docs.test.mjs b/scripts/generate-ai-docs.test.mjs new file mode 100644 index 0000000..56aebb5 --- /dev/null +++ b/scripts/generate-ai-docs.test.mjs @@ -0,0 +1,69 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { convert, generate } from './generate-ai-docs.mjs'; +import { readFile } from 'node:fs/promises'; +import path from 'node:path'; + +test('code examples retain imports, JSX, placeholders, and exports', () => { + const source = + '# Test\n\n```tsx\nimport { x } from "x";\nexport const a = ;\n```\n\nKeep `
` as a placeholder.\n'; + assert.equal(convert(source), source); +}); +test('multiline MDX imports and frontmatter are removed', () => { + const source = '---\ntitle: Test\n---\nimport {\n A, B\n} from "components";\n\n# Test\n'; + assert.equal(convert(source), '# Test\n'); +}); +test('cards keep descriptions and target generated Markdown', () => { + const output = convert('# Test\n', { + routes: new Map([['/next', '/next.md']]), + }); + assert.match(output, /\[Next\]\(https:\/\/docs.shape.network\/next.md\): Details/); +}); +test('component warnings and source-driven links survive', () => { + const output = convert('# Test\n', { + components: { + Warning: + 'Do not register in the constructor. Help', + }, + paths: { help: 'https://example.com/help' }, + }); + assert.match(output, /> Warning:/); + assert.match(output, /Do not register in the constructor/); + assert.match(output, /\[Help\]\(https:\/\/example.com\/help\)/); +}); +test('unsupported components, broken internal links, and broken fences fail loudly', () => { + assert.throws(() => convert('# Test\n'), /Unsupported component/); + assert.throws(() => convert('# Test\n[Lost](/missing)'), /Unmapped internal link/); + assert.throws(() => convert('# Test\n```ts\nbroken'), /Unclosed code fence/); +}); +test('fragment links and HTML entities are preserved correctly', () => { + assert.equal(convert('# Test\n\nIt's [here](#test).\n'), "# Test\n\nIt's [here](#test).\n"); +}); + +// Optional integration test against the actual repository, not fabricated content. +const repo = process.env.SHAPE_DOCS_TEST_ROOT; +if (repo) + test('every source code block is preserved and generation is deterministic', async () => { + const { pages } = await generate(repo); + const manifest = JSON.parse( + await readFile(path.join(repo, 'public/.ai-docs-manifest.json'), 'utf8') + ); + assert.equal(manifest.length, pages); + const files = new Set(manifest); + const originalIndex = await readFile(path.join(repo, 'public/llms.txt'), 'utf8'); + const blocks = (value) => value.match(/^(`{3,}|~{3,})[^\n]*\n[\s\S]*?^\1\s*$/gm) || []; + for (const relative of manifest) { + const output = await readFile(path.join(repo, 'public', relative), 'utf8'); + const source = await readFile( + path.join(repo, 'content', relative.replace(/\.md$/, '.mdx')), + 'utf8' + ); + assert.deepEqual(blocks(output), blocks(source), relative); + for (const match of output.matchAll( + /\]\(https:\/\/docs\.shape\.network\/([^\s)]+\.md)(?:#[^)]*)?\)/g + )) + assert.ok(files.has(match[1]), `${relative}: missing ${match[1]}`); + } + await generate(repo); + assert.equal(await readFile(path.join(repo, 'public/llms.txt'), 'utf8'), originalIndex); + });