@writedocs/generator 0.13.3 → 0.13.5

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 (87) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +43 -12
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +203 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +1 -1
  10. package/src/cli/dev.js +268 -268
  11. package/src/cli/exit-when-flushed.js +4 -0
  12. package/src/cli/generate-api-pages.js +507 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +69 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +203 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +408 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +414 -75
  48. package/src/lib/config-schema.ts +2509 -1905
  49. package/src/lib/config.ts +1316 -1314
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-store-reload-integration.js +101 -101
  52. package/src/lib/icon-data-dev.js +53 -53
  53. package/src/lib/image-size.js +152 -152
  54. package/src/lib/json-schema-descriptions.js +228 -228
  55. package/src/lib/link-check.js +544 -544
  56. package/src/lib/llms-index.ts +90 -90
  57. package/src/lib/mcp-dev-integration.js +65 -65
  58. package/src/lib/mcp-index.ts +102 -102
  59. package/src/lib/mintlify-convert.js +605 -605
  60. package/src/lib/moved-api-pages.js +49 -49
  61. package/src/lib/og-cards.js +33 -33
  62. package/src/lib/og-image.js +235 -235
  63. package/src/lib/openapi-dev-status.js +80 -80
  64. package/src/lib/openapi-reload-integration.js +193 -193
  65. package/src/lib/pages.js +312 -312
  66. package/src/lib/project-files-integration.js +116 -116
  67. package/src/lib/project-files.js +137 -137
  68. package/src/lib/rehype-base-path.js +62 -62
  69. package/src/lib/rehype-image-loading.js +71 -71
  70. package/src/lib/robots-txt.js +21 -21
  71. package/src/lib/search-scope.js +44 -44
  72. package/src/lib/selector-placement.js +50 -50
  73. package/src/lib/seo-tags.js +155 -155
  74. package/src/lib/shiki-code-block.js +7 -1
  75. package/src/lib/site-base.ts +27 -27
  76. package/src/lib/styles-asset-integration.js +291 -291
  77. package/src/lib/wdignore-cases.json +195 -195
  78. package/src/lib/wdignore.js +177 -177
  79. package/src/pages/404.astro +63 -63
  80. package/src/pages/[...slug].astro +1762 -1608
  81. package/src/pages/[...slug].md.ts +93 -93
  82. package/src/pages/llms-full.txt.ts +88 -88
  83. package/src/pages/og/[...slug].png.ts +63 -63
  84. package/src/scripts/mobile-menu.ts +80 -80
  85. package/src/scripts/search.ts +245 -245
  86. package/src/scripts/sidebar-scroll.ts +61 -61
  87. package/src/styles/global.css +40 -40
@@ -1,154 +1,154 @@
1
- import path from 'node:path';
2
- import fs from 'node:fs';
3
- import { spawn } from 'node:child_process';
4
- import { pathToFileURL } from 'node:url';
5
-
6
- /**
7
- * Locates the installed pagefind package by walking up node_modules
8
- * directories from packageRoot - the same lookup algorithm Node itself
9
- * uses for bare-specifier resolution, just done by hand with fs instead
10
- * of require.resolve()/import.meta.resolve(). This is necessary (rather
11
- * than a require.resolve()-based lookup) because pagefind's own
12
- * package.json declares an "exports" map with only a "." entry scoped to
13
- * the "import" condition: require.resolve('pagefind/package.json') is
14
- * blocked outright (exports doesn't list a package.json subpath at all),
15
- * and require.resolve('pagefind') also fails under CJS require() semantics
16
- * (no "require"/"default" condition for it to satisfy).
17
- * import.meta.resolve() would sidestep both, but needs Node 20.6+ -
18
- * newer than this package's documented minimum (20.3.0, see engines in
19
- * package.json). Walking node_modules ourselves avoids all of this - we
20
- * only need pagefind's package.json (for its "bin" field) and the CLI
21
- * script path, both plain file reads that "exports" doesn't restrict at
22
- * all (only module *resolution* is subject to it).
23
- */
24
- function findPagefindDir(startDir) {
25
- let dir = startDir;
26
- while (true) {
27
- const candidate = path.join(dir, 'node_modules', 'pagefind');
28
- if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
29
- const parent = path.dirname(dir);
30
- if (parent === dir) {
31
- throw new Error(`Could not find "pagefind" in any node_modules directory above ${startDir}`);
32
- }
33
- dir = parent;
34
- }
35
- }
36
-
37
- function resolvePagefindBin(packageRoot) {
38
- const dir = findPagefindDir(packageRoot);
39
- const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
40
- return path.join(dir, pkg.bin);
41
- }
42
-
43
- /**
44
- * Indexes a built static site with Pagefind, writing the search bundle
45
- * into <siteDir>/pagefind. Run as a postbuild step, after astro build has
46
- * already produced the final HTML - Pagefind crawls that HTML directly
47
- * rather than hooking into the Astro/Vite build pipeline, so search stays
48
- * decoupled from whatever templating produced the pages. Only indexes
49
- * elements carrying `data-pagefind-body` (see [...slug].astro's
50
- * `.wd-article`) - without that scoping, Pagefind falls back to indexing
51
- * every page's entire <body>, polluting every result with sidebar/topbar
52
- * chrome text repeated on every page.
53
- *
54
- * Pagefind's output is captured, not printed: the CLI prints its own step
55
- * line, and Pagefind's text only when it fails (in the rejected Error).
56
- *
57
- * With a `basePath` ("/docs"), `siteDir` is dist/docs/ and nothing here
58
- * changes: the index keeps each page's address in the site ("/a/"), and
59
- * Pagefind's script puts the folder its bundle is served from in front of a
60
- * result (/docs/pagefind/ -> "/docs/a/"). Adding the base here too gave
61
- * results with it twice.
62
- */
63
- export async function runPagefind(siteDir, { packageRoot }) {
64
- const groups = searchSpaces(siteDir);
65
- if (groups) return indexBySpace(siteDir, packageRoot, groups);
66
- return indexWholeSite(siteDir, packageRoot);
67
- }
68
-
69
- // Pages under a hidden navigation item name their search space in their
70
- // markup ([...slug].astro, lib/hidden-sections.js).
71
- const SPACE = /data-wd-search-space="([^"]+)"/;
72
- const SEARCH_PUBLIC = /data-wd-search-public="true"/;
73
-
74
- /** The site's pages by search space - `{ public, spaces }` - or null when
75
- * no page is in a hidden space (the whole site is one index, as ever).
76
- * Only pages Pagefind would index: those with a data-pagefind-body. A
77
- * page is `{ rel }`, its path in the site with forward slashes.
78
- * Exported for scripts/search-spaces.test.js. */
79
- export function searchSpaces(siteDir) {
80
- const publicPages = [];
81
- const spaces = new Map();
82
- const walk = (dir) => {
83
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
84
- const full = path.join(dir, entry.name);
85
- if (entry.isDirectory()) {
86
- if (!['_astro', 'pagefind', 'pagefind-spaces'].includes(entry.name)) walk(full);
87
- continue;
88
- }
89
- if (!entry.name.endsWith('.html')) continue;
90
- const content = fs.readFileSync(full, 'utf8');
91
- if (!content.includes('data-pagefind-body')) continue;
92
- // The page's address only, not its HTML: a page is read again when
93
- // it's added to an index (indexBySpace()). Keeping every page's
94
- // content here ran the CLI out of memory on a site with 1.7 GiB of
95
- // HTML - and most sites have no hidden space, so none of it was used.
96
- const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
97
- const space = SPACE.exec(content)?.[1];
98
- if (!space) {
99
- publicPages.push(page);
100
- continue;
101
- }
102
- const group = spaces.get(space) ?? { searchPublic: false, pages: [] };
103
- group.searchPublic ||= SEARCH_PUBLIC.test(content);
104
- group.pages.push(page);
105
- spaces.set(space, group);
106
- }
107
- };
108
- walk(siteDir);
109
- return spaces.size ? { public: publicPages, spaces } : null;
110
- }
111
-
112
- /** One index for the public pages (dist/pagefind/) and one per hidden
113
- * space (dist/pagefind-spaces/<id>/) - so the public search never finds a
114
- * hidden page, and a hidden space's search finds only its own pages, plus
115
- * the public ones when it sets `searchPublic`. src/scripts/search.ts loads
116
- * the index of the page's space. */
117
- async function indexBySpace(siteDir, packageRoot, groups) {
118
- const pagefind = await import(pathToFileURL(path.join(findPagefindDir(packageRoot), 'lib', 'index.js')).href);
119
- const check = (result, what) => {
120
- if (result.errors?.length) throw new Error(`pagefind (${what}): ${result.errors.join('; ')}`);
121
- return result;
122
- };
123
- const write = async (pages, outputPath, what) => {
124
- const { index } = check(await pagefind.createIndex({}), what);
125
- for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8') }), `${what}: ${page.rel}`);
126
- check(await index.writeFiles({ outputPath }), what);
127
- };
128
- try {
129
- await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
130
- for (const [id, space] of groups.spaces) {
131
- const pages = space.searchPublic ? [...space.pages, ...groups.public] : space.pages;
132
- await write(pages, path.join(siteDir, 'pagefind-spaces', id), `hidden space ${id}`);
133
- }
134
- } finally {
135
- await pagefind.close();
136
- }
137
- }
138
-
139
- function indexWholeSite(siteDir, packageRoot) {
140
- const bin = resolvePagefindBin(packageRoot);
141
- return new Promise((resolve, reject) => {
142
- const child = spawn(process.execPath, [bin, '--site', siteDir, '--quiet'], {
143
- stdio: ['ignore', 'pipe', 'pipe'],
144
- });
145
- let output = '';
146
- child.stdout.on('data', (d) => (output += d));
147
- child.stderr.on('data', (d) => (output += d));
148
- child.on('close', (code) => {
149
- if (code === 0) resolve();
150
- else reject(new Error(`pagefind exited with code ${code}${output.trim() ? `:\n${output.trim()}` : ''}`));
151
- });
152
- child.on('error', reject);
153
- });
154
- }
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { spawn } from 'node:child_process';
4
+ import { pathToFileURL } from 'node:url';
5
+
6
+ /**
7
+ * Locates the installed pagefind package by walking up node_modules
8
+ * directories from packageRoot - the same lookup algorithm Node itself
9
+ * uses for bare-specifier resolution, just done by hand with fs instead
10
+ * of require.resolve()/import.meta.resolve(). This is necessary (rather
11
+ * than a require.resolve()-based lookup) because pagefind's own
12
+ * package.json declares an "exports" map with only a "." entry scoped to
13
+ * the "import" condition: require.resolve('pagefind/package.json') is
14
+ * blocked outright (exports doesn't list a package.json subpath at all),
15
+ * and require.resolve('pagefind') also fails under CJS require() semantics
16
+ * (no "require"/"default" condition for it to satisfy).
17
+ * import.meta.resolve() would sidestep both, but needs Node 20.6+ -
18
+ * newer than this package's documented minimum (20.3.0, see engines in
19
+ * package.json). Walking node_modules ourselves avoids all of this - we
20
+ * only need pagefind's package.json (for its "bin" field) and the CLI
21
+ * script path, both plain file reads that "exports" doesn't restrict at
22
+ * all (only module *resolution* is subject to it).
23
+ */
24
+ function findPagefindDir(startDir) {
25
+ let dir = startDir;
26
+ while (true) {
27
+ const candidate = path.join(dir, 'node_modules', 'pagefind');
28
+ if (fs.existsSync(path.join(candidate, 'package.json'))) return candidate;
29
+ const parent = path.dirname(dir);
30
+ if (parent === dir) {
31
+ throw new Error(`Could not find "pagefind" in any node_modules directory above ${startDir}`);
32
+ }
33
+ dir = parent;
34
+ }
35
+ }
36
+
37
+ function resolvePagefindBin(packageRoot) {
38
+ const dir = findPagefindDir(packageRoot);
39
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8'));
40
+ return path.join(dir, pkg.bin);
41
+ }
42
+
43
+ /**
44
+ * Indexes a built static site with Pagefind, writing the search bundle
45
+ * into <siteDir>/pagefind. Run as a postbuild step, after astro build has
46
+ * already produced the final HTML - Pagefind crawls that HTML directly
47
+ * rather than hooking into the Astro/Vite build pipeline, so search stays
48
+ * decoupled from whatever templating produced the pages. Only indexes
49
+ * elements carrying `data-pagefind-body` (see [...slug].astro's
50
+ * `.wd-article`) - without that scoping, Pagefind falls back to indexing
51
+ * every page's entire <body>, polluting every result with sidebar/topbar
52
+ * chrome text repeated on every page.
53
+ *
54
+ * Pagefind's output is captured, not printed: the CLI prints its own step
55
+ * line, and Pagefind's text only when it fails (in the rejected Error).
56
+ *
57
+ * With a `basePath` ("/docs"), `siteDir` is dist/docs/ and nothing here
58
+ * changes: the index keeps each page's address in the site ("/a/"), and
59
+ * Pagefind's script puts the folder its bundle is served from in front of a
60
+ * result (/docs/pagefind/ -> "/docs/a/"). Adding the base here too gave
61
+ * results with it twice.
62
+ */
63
+ export async function runPagefind(siteDir, { packageRoot }) {
64
+ const groups = searchSpaces(siteDir);
65
+ if (groups) return indexBySpace(siteDir, packageRoot, groups);
66
+ return indexWholeSite(siteDir, packageRoot);
67
+ }
68
+
69
+ // Pages under a hidden navigation item name their search space in their
70
+ // markup ([...slug].astro, lib/hidden-sections.js).
71
+ const SPACE = /data-wd-search-space="([^"]+)"/;
72
+ const SEARCH_PUBLIC = /data-wd-search-public="true"/;
73
+
74
+ /** The site's pages by search space - `{ public, spaces }` - or null when
75
+ * no page is in a hidden space (the whole site is one index, as ever).
76
+ * Only pages Pagefind would index: those with a data-pagefind-body. A
77
+ * page is `{ rel }`, its path in the site with forward slashes.
78
+ * Exported for scripts/search-spaces.test.js. */
79
+ export function searchSpaces(siteDir) {
80
+ const publicPages = [];
81
+ const spaces = new Map();
82
+ const walk = (dir) => {
83
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
84
+ const full = path.join(dir, entry.name);
85
+ if (entry.isDirectory()) {
86
+ if (!['_astro', 'pagefind', 'pagefind-spaces'].includes(entry.name)) walk(full);
87
+ continue;
88
+ }
89
+ if (!entry.name.endsWith('.html')) continue;
90
+ const content = fs.readFileSync(full, 'utf8');
91
+ if (!content.includes('data-pagefind-body')) continue;
92
+ // The page's address only, not its HTML: a page is read again when
93
+ // it's added to an index (indexBySpace()). Keeping every page's
94
+ // content here ran the CLI out of memory on a site with 1.7 GiB of
95
+ // HTML - and most sites have no hidden space, so none of it was used.
96
+ const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
97
+ const space = SPACE.exec(content)?.[1];
98
+ if (!space) {
99
+ publicPages.push(page);
100
+ continue;
101
+ }
102
+ const group = spaces.get(space) ?? { searchPublic: false, pages: [] };
103
+ group.searchPublic ||= SEARCH_PUBLIC.test(content);
104
+ group.pages.push(page);
105
+ spaces.set(space, group);
106
+ }
107
+ };
108
+ walk(siteDir);
109
+ return spaces.size ? { public: publicPages, spaces } : null;
110
+ }
111
+
112
+ /** One index for the public pages (dist/pagefind/) and one per hidden
113
+ * space (dist/pagefind-spaces/<id>/) - so the public search never finds a
114
+ * hidden page, and a hidden space's search finds only its own pages, plus
115
+ * the public ones when it sets `searchPublic`. src/scripts/search.ts loads
116
+ * the index of the page's space. */
117
+ async function indexBySpace(siteDir, packageRoot, groups) {
118
+ const pagefind = await import(pathToFileURL(path.join(findPagefindDir(packageRoot), 'lib', 'index.js')).href);
119
+ const check = (result, what) => {
120
+ if (result.errors?.length) throw new Error(`pagefind (${what}): ${result.errors.join('; ')}`);
121
+ return result;
122
+ };
123
+ const write = async (pages, outputPath, what) => {
124
+ const { index } = check(await pagefind.createIndex({}), what);
125
+ for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8') }), `${what}: ${page.rel}`);
126
+ check(await index.writeFiles({ outputPath }), what);
127
+ };
128
+ try {
129
+ await write(groups.public, path.join(siteDir, 'pagefind'), 'public pages');
130
+ for (const [id, space] of groups.spaces) {
131
+ const pages = space.searchPublic ? [...space.pages, ...groups.public] : space.pages;
132
+ await write(pages, path.join(siteDir, 'pagefind-spaces', id), `hidden space ${id}`);
133
+ }
134
+ } finally {
135
+ await pagefind.close();
136
+ }
137
+ }
138
+
139
+ function indexWholeSite(siteDir, packageRoot) {
140
+ const bin = resolvePagefindBin(packageRoot);
141
+ return new Promise((resolve, reject) => {
142
+ const child = spawn(process.execPath, [bin, '--site', siteDir, '--quiet'], {
143
+ stdio: ['ignore', 'pipe', 'pipe'],
144
+ });
145
+ let output = '';
146
+ child.stdout.on('data', (d) => (output += d));
147
+ child.stderr.on('data', (d) => (output += d));
148
+ child.on('close', (code) => {
149
+ if (code === 0) resolve();
150
+ else reject(new Error(`pagefind exited with code ${code}${output.trim() ? `:\n${output.trim()}` : ''}`));
151
+ });
152
+ child.on('error', reject);
153
+ });
154
+ }
@@ -1,103 +1,103 @@
1
- // After `writedocs build`: the files that make dist/ serve the site's MCP
2
- // server at /mcp on Cloudflare, with no setup of the host's own - next to
3
- // mcp-index.json, which the build itself writes (src/pages/[mcpIndex].json.ts).
4
- //
5
- // _worker.js the MCP server (src/mcp/server.js, inlined - no imports)
6
- // plus a small fetch handler: /mcp goes to the server,
7
- // everything else to the static files (env.ASSETS).
8
- // - Cloudflare Pages runs it on its own ("advanced mode").
9
- // - Cloudflare Workers with static assets: point `main` at
10
- // dist/_worker.js, assets at dist/ with an ASSETS binding.
11
- // _routes.json Pages: only /mcp runs the worker; every other path stays a
12
- // plain static file (and `_redirects` keeps applying).
13
- // .assetsignore Workers: don't publish _worker.js / _routes.json as files.
14
- //
15
- // Anywhere else - Netlify, Vercel, the WriteDocs platform's serving Worker -
16
- // import handleMcpHttp from `@writedocs/generator/mcp` and give it
17
- // mcp-index.json; a purely static host (GitHub Pages, S3) can't run /mcp.
18
- //
19
- // A project that brings its own _worker.js or _routes.json (in public/), or a
20
- // Pages `functions/` folder (which Pages ignores once a _worker.js exists),
21
- // keeps them: the worker isn't written, and the build says so.
22
- //
23
- // With a `basePath` ("/docs"), the site is in dist/docs/ (base-path-layout.js)
24
- // and so is mcp-index.json; these three files stay at the root of dist/, where
25
- // Cloudflare reads them, and the server answers at /docs/mcp.
26
- import fs from 'node:fs';
27
- import path from 'node:path';
28
- import { fileURLToPath } from 'node:url';
29
-
30
- const SERVER_SOURCE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'mcp', 'server.js');
31
- const IGNORED_BY_WORKERS = ['_worker.js', '_routes.json'];
32
-
33
- /** The `_worker.js` source: server.js without its `export`s, and the fetch
34
- * handler. `version` is the writedocs version, reported by the server;
35
- * `basePath` the site's base ("" or "/docs" - only `[a-z0-9_/-]`, safe in a
36
- * string literal), in front of /mcp and /mcp-index.json. */
37
- export function mcpWorkerSource(version, basePath = '') {
38
- const server = fs.readFileSync(SERVER_SOURCE, 'utf-8').replace(/^export (?=(?:const|let|async function|function) )/gm, '');
39
- return `// Generated by writedocs ${version} - the site's MCP server at ${basePath}/mcp.
40
- // Cloudflare Pages runs this file on its own; on Cloudflare Workers, use it as
41
- // \`main\` with dist/ as the static assets (binding ASSETS). See
42
- // https://github.com/writedocs/writedocs (src/cli/write-mcp-files.js).
43
-
44
- ${server}
45
- const WRITEDOCS_VERSION = ${JSON.stringify(version)};
46
-
47
- // The page index, read once per isolate from the site's own static files.
48
- let indexPromise = null;
49
- function loadIndex(request, env) {
50
- if (!indexPromise) {
51
- indexPromise = env.ASSETS.fetch(new URL('${basePath}/mcp-index.json', request.url))
52
- .then((res) => {
53
- if (!res.ok) throw new Error('mcp-index.json: HTTP ' + res.status);
54
- return res.json();
55
- })
56
- .catch((err) => {
57
- indexPromise = null;
58
- throw err;
59
- });
60
- }
61
- return indexPromise;
62
- }
63
-
64
- export default {
65
- async fetch(request, env) {
66
- const { pathname } = new URL(request.url);
67
- if (pathname === '${basePath}/mcp' || pathname === '${basePath}/mcp/') {
68
- return handleMcpHttp(request, { loadIndex: () => loadIndex(request, env), version: WRITEDOCS_VERSION });
69
- }
70
- return env.ASSETS.fetch(request);
71
- },
72
- };
73
- `;
74
- }
75
-
76
- /** Writes the files into `distDir`. Returns { written: [names], skipped:
77
- * reason or null } - nothing at all when there's no mcp-index.json
78
- * (writedocs.json `"mcp": false`). `siteDir` is where the site itself is
79
- * (dist/docs/ with a `basePath`). */
80
- export function writeMcpFiles(distDir, contentDir, version, { siteDir = distDir, basePath = '' } = {}) {
81
- if (!fs.existsSync(path.join(siteDir, 'mcp-index.json'))) return { written: [], skipped: null };
82
-
83
- const own = ['_worker.js', '_routes.json'].filter((name) => fs.existsSync(path.join(distDir, name)));
84
- if (own.length) {
85
- return { written: [], skipped: `the project has its own ${own.join(' and ')} - /mcp needs its handler added there (see @writedocs/generator/mcp)` };
86
- }
87
- if (fs.existsSync(path.join(contentDir, 'functions'))) {
88
- return { written: [], skipped: 'the project has a Cloudflare Pages functions/ folder, which a _worker.js would switch off - add /mcp there with @writedocs/generator/mcp' };
89
- }
90
-
91
- fs.writeFileSync(path.join(distDir, '_worker.js'), mcpWorkerSource(version, basePath));
92
- fs.writeFileSync(path.join(distDir, '_routes.json'), JSON.stringify({ version: 1, include: [`${basePath}/mcp`, `${basePath}/mcp/`], exclude: [] }, null, 2) + '\n');
93
-
94
- const ignorePath = path.join(distDir, '.assetsignore');
95
- const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, 'utf-8') : '';
96
- const lines = existing.split(/\r?\n/).map((l) => l.trim());
97
- const missing = IGNORED_BY_WORKERS.filter((name) => !lines.includes(name));
98
- if (missing.length) {
99
- const prefix = existing && !existing.endsWith('\n') ? `${existing}\n` : existing;
100
- fs.writeFileSync(ignorePath, `${prefix}${missing.join('\n')}\n`);
101
- }
102
- return { written: ['_worker.js', '_routes.json', '.assetsignore'], skipped: null };
103
- }
1
+ // After `writedocs build`: the files that make dist/ serve the site's MCP
2
+ // server at /mcp on Cloudflare, with no setup of the host's own - next to
3
+ // mcp-index.json, which the build itself writes (src/pages/[mcpIndex].json.ts).
4
+ //
5
+ // _worker.js the MCP server (src/mcp/server.js, inlined - no imports)
6
+ // plus a small fetch handler: /mcp goes to the server,
7
+ // everything else to the static files (env.ASSETS).
8
+ // - Cloudflare Pages runs it on its own ("advanced mode").
9
+ // - Cloudflare Workers with static assets: point `main` at
10
+ // dist/_worker.js, assets at dist/ with an ASSETS binding.
11
+ // _routes.json Pages: only /mcp runs the worker; every other path stays a
12
+ // plain static file (and `_redirects` keeps applying).
13
+ // .assetsignore Workers: don't publish _worker.js / _routes.json as files.
14
+ //
15
+ // Anywhere else - Netlify, Vercel, the WriteDocs platform's serving Worker -
16
+ // import handleMcpHttp from `@writedocs/generator/mcp` and give it
17
+ // mcp-index.json; a purely static host (GitHub Pages, S3) can't run /mcp.
18
+ //
19
+ // A project that brings its own _worker.js or _routes.json (in public/), or a
20
+ // Pages `functions/` folder (which Pages ignores once a _worker.js exists),
21
+ // keeps them: the worker isn't written, and the build says so.
22
+ //
23
+ // With a `basePath` ("/docs"), the site is in dist/docs/ (base-path-layout.js)
24
+ // and so is mcp-index.json; these three files stay at the root of dist/, where
25
+ // Cloudflare reads them, and the server answers at /docs/mcp.
26
+ import fs from 'node:fs';
27
+ import path from 'node:path';
28
+ import { fileURLToPath } from 'node:url';
29
+
30
+ const SERVER_SOURCE = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'mcp', 'server.js');
31
+ const IGNORED_BY_WORKERS = ['_worker.js', '_routes.json'];
32
+
33
+ /** The `_worker.js` source: server.js without its `export`s, and the fetch
34
+ * handler. `version` is the writedocs version, reported by the server;
35
+ * `basePath` the site's base ("" or "/docs" - only `[a-z0-9_/-]`, safe in a
36
+ * string literal), in front of /mcp and /mcp-index.json. */
37
+ export function mcpWorkerSource(version, basePath = '') {
38
+ const server = fs.readFileSync(SERVER_SOURCE, 'utf-8').replace(/^export (?=(?:const|let|async function|function) )/gm, '');
39
+ return `// Generated by writedocs ${version} - the site's MCP server at ${basePath}/mcp.
40
+ // Cloudflare Pages runs this file on its own; on Cloudflare Workers, use it as
41
+ // \`main\` with dist/ as the static assets (binding ASSETS). See
42
+ // https://github.com/writedocs/writedocs (src/cli/write-mcp-files.js).
43
+
44
+ ${server}
45
+ const WRITEDOCS_VERSION = ${JSON.stringify(version)};
46
+
47
+ // The page index, read once per isolate from the site's own static files.
48
+ let indexPromise = null;
49
+ function loadIndex(request, env) {
50
+ if (!indexPromise) {
51
+ indexPromise = env.ASSETS.fetch(new URL('${basePath}/mcp-index.json', request.url))
52
+ .then((res) => {
53
+ if (!res.ok) throw new Error('mcp-index.json: HTTP ' + res.status);
54
+ return res.json();
55
+ })
56
+ .catch((err) => {
57
+ indexPromise = null;
58
+ throw err;
59
+ });
60
+ }
61
+ return indexPromise;
62
+ }
63
+
64
+ export default {
65
+ async fetch(request, env) {
66
+ const { pathname } = new URL(request.url);
67
+ if (pathname === '${basePath}/mcp' || pathname === '${basePath}/mcp/') {
68
+ return handleMcpHttp(request, { loadIndex: () => loadIndex(request, env), version: WRITEDOCS_VERSION });
69
+ }
70
+ return env.ASSETS.fetch(request);
71
+ },
72
+ };
73
+ `;
74
+ }
75
+
76
+ /** Writes the files into `distDir`. Returns { written: [names], skipped:
77
+ * reason or null } - nothing at all when there's no mcp-index.json
78
+ * (writedocs.json `"mcp": false`). `siteDir` is where the site itself is
79
+ * (dist/docs/ with a `basePath`). */
80
+ export function writeMcpFiles(distDir, contentDir, version, { siteDir = distDir, basePath = '' } = {}) {
81
+ if (!fs.existsSync(path.join(siteDir, 'mcp-index.json'))) return { written: [], skipped: null };
82
+
83
+ const own = ['_worker.js', '_routes.json'].filter((name) => fs.existsSync(path.join(distDir, name)));
84
+ if (own.length) {
85
+ return { written: [], skipped: `the project has its own ${own.join(' and ')} - /mcp needs its handler added there (see @writedocs/generator/mcp)` };
86
+ }
87
+ if (fs.existsSync(path.join(contentDir, 'functions'))) {
88
+ return { written: [], skipped: 'the project has a Cloudflare Pages functions/ folder, which a _worker.js would switch off - add /mcp there with @writedocs/generator/mcp' };
89
+ }
90
+
91
+ fs.writeFileSync(path.join(distDir, '_worker.js'), mcpWorkerSource(version, basePath));
92
+ fs.writeFileSync(path.join(distDir, '_routes.json'), JSON.stringify({ version: 1, include: [`${basePath}/mcp`, `${basePath}/mcp/`], exclude: [] }, null, 2) + '\n');
93
+
94
+ const ignorePath = path.join(distDir, '.assetsignore');
95
+ const existing = fs.existsSync(ignorePath) ? fs.readFileSync(ignorePath, 'utf-8') : '';
96
+ const lines = existing.split(/\r?\n/).map((l) => l.trim());
97
+ const missing = IGNORED_BY_WORKERS.filter((name) => !lines.includes(name));
98
+ if (missing.length) {
99
+ const prefix = existing && !existing.endsWith('\n') ? `${existing}\n` : existing;
100
+ fs.writeFileSync(ignorePath, `${prefix}${missing.join('\n')}\n`);
101
+ }
102
+ return { written: ['_worker.js', '_routes.json', '.assetsignore'], skipped: null };
103
+ }