@writedocs/generator 0.13.4 → 0.14.0

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 (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  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 +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -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 +71 -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 +219 -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 +422 -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 +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
package/package.json CHANGED
@@ -1,99 +1,99 @@
1
- {
2
- "name": "@writedocs/generator",
3
- "version": "0.13.4",
4
- "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
- "type": "module",
6
- "bin": {
7
- "writedocs": "./bin/writedocs.js"
8
- },
9
- "exports": {
10
- "./components": "./src/components/index.ts",
11
- "./config-schema": "./src/lib/config-schema.js",
12
- "./writedocs.schema.json": "./writedocs.schema.json",
13
- "./mcp": "./src/mcp/server.js",
14
- "./wdignore": "./src/lib/wdignore.js",
15
- "./wdignore-cases.json": "./src/lib/wdignore-cases.json"
16
- },
17
- "files": [
18
- "bin",
19
- "src",
20
- "astro.config.mjs",
21
- "writedocs.schema.json"
22
- ],
23
- "scripts": {
24
- "dev": "node bin/writedocs.js dev",
25
- "build": "node bin/writedocs.js build",
26
- "init": "node bin/writedocs.js init",
27
- "build:schema": "esbuild src/lib/config-schema.ts --format=esm --target=node22 --outfile=src/lib/config-schema.js",
28
- "prepare": "npm run build:schema && npm run build:json-schema",
29
- "test": "node --test \"scripts/*.test.js\"",
30
- "build:json-schema": "node scripts/build-json-schema.mjs"
31
- },
32
- "keywords": [
33
- "docs",
34
- "documentation",
35
- "static-site-generator",
36
- "mdx",
37
- "astro"
38
- ],
39
- "homepage": "https://github.com/writedocs/writedocs#readme",
40
- "repository": {
41
- "type": "git",
42
- "url": "git+https://github.com/writedocs/writedocs.git"
43
- },
44
- "bugs": {
45
- "url": "https://github.com/writedocs/writedocs/issues"
46
- },
47
- "author": "Gabriel Raeder Gonçalves",
48
- "license": "ISC",
49
- "publishConfig": {
50
- "access": "public"
51
- },
52
- "dependencies": {
53
- "@apidevtools/swagger-parser": "12.1.0",
54
- "@astrojs/markdown-remark": "7.2.4",
55
- "@astrojs/mdx": "7.0.8",
56
- "@astrojs/react": "6.0.2",
57
- "@astrojs/sitemap": "3.7.3",
58
- "@iconify-json/bi": "1.2.7",
59
- "@iconify-json/fa6-brands": "1.2.6",
60
- "@iconify-json/fa6-solid": "1.2.4",
61
- "@iconify-json/heroicons": "1.2.3",
62
- "@iconify-json/ion": "1.2.7",
63
- "@iconify-json/lucide": "1.2.123",
64
- "@iconify-json/mdi": "1.2.3",
65
- "@iconify-json/ri": "1.2.10",
66
- "@iconify-json/simple-icons": "1.2.93",
67
- "@iconify-json/tabler": "1.2.38",
68
- "@mdx-js/mdx": "3.1.1",
69
- "@resvg/resvg-wasm": "2.6.2",
70
- "@shikijs/transformers": "4.4.3",
71
- "@tailwindcss/vite": "4.3.3",
72
- "astro": "7.2.9",
73
- "astro-icon": "1.1.5",
74
- "commander": "15.0.0",
75
- "dotenv": "17.4.2",
76
- "gray-matter": "4.0.3",
77
- "ignore": "7.0.5",
78
- "jsonc-parser": "3.3.1",
79
- "katex": "0.16.47",
80
- "mermaid": "11.16.1",
81
- "pagefind": "1.5.2",
82
- "react": "19.2.8",
83
- "react-dom": "19.2.8",
84
- "rehype-katex": "7.0.1",
85
- "remark-math": "6.0.0",
86
- "rolldown": "1.2.14",
87
- "satori": "0.44.0",
88
- "shiki": "4.4.3",
89
- "tailwindcss": "4.3.3",
90
- "vite": "8.3.4",
91
- "zod": "4.6.7"
92
- },
93
- "engines": {
94
- "node": ">=22.12.0"
95
- },
96
- "devDependencies": {
97
- "esbuild": "0.28.2"
98
- }
99
- }
1
+ {
2
+ "name": "@writedocs/generator",
3
+ "version": "0.14.0",
4
+ "description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
5
+ "type": "module",
6
+ "bin": {
7
+ "writedocs": "./bin/writedocs.js"
8
+ },
9
+ "exports": {
10
+ "./components": "./src/components/index.ts",
11
+ "./config-schema": "./src/lib/config-schema.js",
12
+ "./writedocs.schema.json": "./writedocs.schema.json",
13
+ "./mcp": "./src/mcp/server.js",
14
+ "./wdignore": "./src/lib/wdignore.js",
15
+ "./wdignore-cases.json": "./src/lib/wdignore-cases.json"
16
+ },
17
+ "files": [
18
+ "bin",
19
+ "src",
20
+ "astro.config.mjs",
21
+ "writedocs.schema.json"
22
+ ],
23
+ "scripts": {
24
+ "dev": "node bin/writedocs.js dev",
25
+ "build": "node bin/writedocs.js build",
26
+ "init": "node bin/writedocs.js init",
27
+ "build:schema": "esbuild src/lib/config-schema.ts --format=esm --target=node22 --outfile=src/lib/config-schema.js",
28
+ "prepare": "npm run build:schema && npm run build:json-schema",
29
+ "test": "node --test \"scripts/*.test.js\"",
30
+ "build:json-schema": "node scripts/build-json-schema.mjs"
31
+ },
32
+ "keywords": [
33
+ "docs",
34
+ "documentation",
35
+ "static-site-generator",
36
+ "mdx",
37
+ "astro"
38
+ ],
39
+ "homepage": "https://github.com/writedocs/writedocs#readme",
40
+ "repository": {
41
+ "type": "git",
42
+ "url": "git+https://github.com/writedocs/writedocs.git"
43
+ },
44
+ "bugs": {
45
+ "url": "https://github.com/writedocs/writedocs/issues"
46
+ },
47
+ "author": "Gabriel Raeder Gonçalves",
48
+ "license": "ISC",
49
+ "publishConfig": {
50
+ "access": "public"
51
+ },
52
+ "dependencies": {
53
+ "@apidevtools/swagger-parser": "12.1.0",
54
+ "@astrojs/markdown-remark": "7.2.4",
55
+ "@astrojs/mdx": "7.0.8",
56
+ "@astrojs/react": "6.0.2",
57
+ "@astrojs/sitemap": "3.7.3",
58
+ "@iconify-json/bi": "1.2.7",
59
+ "@iconify-json/fa6-brands": "1.2.6",
60
+ "@iconify-json/fa6-solid": "1.2.4",
61
+ "@iconify-json/heroicons": "1.2.3",
62
+ "@iconify-json/ion": "1.2.7",
63
+ "@iconify-json/lucide": "1.2.123",
64
+ "@iconify-json/mdi": "1.2.3",
65
+ "@iconify-json/ri": "1.2.10",
66
+ "@iconify-json/simple-icons": "1.2.93",
67
+ "@iconify-json/tabler": "1.2.38",
68
+ "@mdx-js/mdx": "3.1.1",
69
+ "@resvg/resvg-wasm": "2.6.2",
70
+ "@shikijs/transformers": "4.4.3",
71
+ "@tailwindcss/vite": "4.3.3",
72
+ "astro": "7.2.9",
73
+ "astro-icon": "1.1.5",
74
+ "commander": "15.0.0",
75
+ "dotenv": "17.4.2",
76
+ "gray-matter": "4.0.3",
77
+ "ignore": "7.0.5",
78
+ "jsonc-parser": "3.3.1",
79
+ "katex": "0.16.47",
80
+ "mermaid": "11.16.1",
81
+ "pagefind": "1.5.2",
82
+ "react": "19.2.8",
83
+ "react-dom": "19.2.8",
84
+ "rehype-katex": "7.0.1",
85
+ "remark-math": "6.0.0",
86
+ "rolldown": "1.2.14",
87
+ "satori": "0.44.0",
88
+ "shiki": "4.4.3",
89
+ "tailwindcss": "4.3.3",
90
+ "vite": "8.3.4",
91
+ "zod": "4.6.7"
92
+ },
93
+ "engines": {
94
+ "node": ">=22.12.0"
95
+ },
96
+ "devDependencies": {
97
+ "esbuild": "0.28.2"
98
+ }
99
+ }
@@ -1,44 +1,44 @@
1
- // Where a build puts the site in dist/ (build.js). Without a basePath, at
2
- // dist/ itself, as always. With one ("/docs", writedocs.json - see
3
- // lib/base-path.js), every file the site serves goes to dist/docs/: a static
4
- // server that serves dist/ at its root answers /docs/... with no rule of its
5
- // own, and a proxy that passes /docs/* on with its path unchanged finds every
6
- // file where its address says.
7
- //
8
- // A few files aren't the site's but its host's, and the host reads them at
9
- // the root of what it serves, so they stay in dist/:
10
- // 404.html the page a host shows for an address it doesn't have
11
- // (Cloudflare Pages, the WriteDocs platform look for it there);
12
- // _redirects the host's redirects - every path in the generated rules
13
- // carries the base (write-redirects-file.js);
14
- // _headers the host's response headers, when the project has one;
15
- // _worker.js, _routes.json, .assetsignore
16
- // the Cloudflare MCP server (write-mcp-files.js), which
17
- // Cloudflare only runs from the root.
18
- import fs from 'node:fs';
19
- import path from 'node:path';
20
-
21
- /** The host's files - kept at the root of dist/, outside the basePath. */
22
- export const ROOT_FILES = ['404.html', '_redirects', '_headers', '_worker.js', '_routes.json', '.assetsignore'];
23
-
24
- /** The folder the site itself goes to: dist/ without a basePath,
25
- * dist/docs/ for "/docs", dist/help/docs/ for "/help/docs". */
26
- export function siteDirFor(distDir, basePath) {
27
- const segments = (basePath ?? '').split('/').filter(Boolean);
28
- return segments.length ? path.join(distDir, ...segments) : distDir;
29
- }
30
-
31
- /** Moves the host's files (ROOT_FILES) a build left in the site's folder up
32
- * to the root of dist/. Nothing to do without a basePath. Returns the names
33
- * moved. */
34
- export function moveRootFiles(siteDir, distDir) {
35
- if (path.resolve(siteDir) === path.resolve(distDir)) return [];
36
- const moved = [];
37
- for (const name of ROOT_FILES) {
38
- const from = path.join(siteDir, name);
39
- if (!fs.existsSync(from)) continue;
40
- fs.renameSync(from, path.join(distDir, name));
41
- moved.push(name);
42
- }
43
- return moved;
44
- }
1
+ // Where a build puts the site in dist/ (build.js). Without a basePath, at
2
+ // dist/ itself, as always. With one ("/docs", writedocs.json - see
3
+ // lib/base-path.js), every file the site serves goes to dist/docs/: a static
4
+ // server that serves dist/ at its root answers /docs/... with no rule of its
5
+ // own, and a proxy that passes /docs/* on with its path unchanged finds every
6
+ // file where its address says.
7
+ //
8
+ // A few files aren't the site's but its host's, and the host reads them at
9
+ // the root of what it serves, so they stay in dist/:
10
+ // 404.html the page a host shows for an address it doesn't have
11
+ // (Cloudflare Pages, the WriteDocs platform look for it there);
12
+ // _redirects the host's redirects - every path in the generated rules
13
+ // carries the base (write-redirects-file.js);
14
+ // _headers the host's response headers, when the project has one;
15
+ // _worker.js, _routes.json, .assetsignore
16
+ // the Cloudflare MCP server (write-mcp-files.js), which
17
+ // Cloudflare only runs from the root.
18
+ import fs from 'node:fs';
19
+ import path from 'node:path';
20
+
21
+ /** The host's files - kept at the root of dist/, outside the basePath. */
22
+ export const ROOT_FILES = ['404.html', '_redirects', '_headers', '_worker.js', '_routes.json', '.assetsignore'];
23
+
24
+ /** The folder the site itself goes to: dist/ without a basePath,
25
+ * dist/docs/ for "/docs", dist/help/docs/ for "/help/docs". */
26
+ export function siteDirFor(distDir, basePath) {
27
+ const segments = (basePath ?? '').split('/').filter(Boolean);
28
+ return segments.length ? path.join(distDir, ...segments) : distDir;
29
+ }
30
+
31
+ /** Moves the host's files (ROOT_FILES) a build left in the site's folder up
32
+ * to the root of dist/. Nothing to do without a basePath. Returns the names
33
+ * moved. */
34
+ export function moveRootFiles(siteDir, distDir) {
35
+ if (path.resolve(siteDir) === path.resolve(distDir)) return [];
36
+ const moved = [];
37
+ for (const name of ROOT_FILES) {
38
+ const from = path.join(siteDir, name);
39
+ if (!fs.existsSync(from)) continue;
40
+ fs.renameSync(from, path.join(distDir, name));
41
+ moved.push(name);
42
+ }
43
+ return moved;
44
+ }
@@ -1,135 +1,135 @@
1
- /**
2
- * `writedocs build` produces the artifact that actually gets deployed, so
3
- * unlike `dev`/`init` it isn't freely runnable by anyone who installs the
4
- * package - it's gated behind a key that a separate service
5
- * (writedocs-key-server, a sibling repo) actually decides the validity of.
6
- *
7
- * This deliberately isn't a local check. An earlier version compared the
8
- * supplied key against an env var set on the same machine
9
- * (WRITEDOCS_BUILD_SECRET) - but since writedocs ships its full source to
10
- * everyone who installs it, anyone could read that check and satisfy it
11
- * with a value they made up themselves. Calling out to a server that
12
- * actually holds the set of issued keys means a key's validity is decided
13
- * by whoever runs that server, not by whoever is running `build`.
14
- *
15
- * See docs/dev/docs/deploy.mdx for how to deploy writedocs-key-server and
16
- * issue keys, and that repo's own README for the service's endpoints.
17
- */
18
- import https from 'node:https';
19
- import { log } from './output.js';
20
-
21
- export const EX_TEMPFAIL = 75;
22
-
23
- /** The authorization servers every `build` asks, in this order. Two only
24
- * while key validation moves to the WriteDocs platform (the first entry);
25
- * the second, writedocs-key-server, goes once every key comes from the
26
- * platform.
27
- *
28
- * Fixed in the code, with no environment override: when the URL came from
29
- * WRITEDOCS_KEY_SERVER_URL, anyone could point it at a 3-line server that
30
- * answers `{ "valid": true }` and build without a key. Tests and CI use a
31
- * real key instead (the WRITEDOCS_API_KEY secret - see
32
- * scripts/smoke-installed-cli.sh). Honest limit: the source ships with the
33
- * package, so someone willing to edit it can still remove this check - it
34
- * raises the bar, it isn't a lock. Real protection is what the platform
35
- * does with the output. */
36
- export const KEY_SERVER_URLS = [
37
- 'https://api.writedocs.io',
38
- 'https://proxy.writechoice.io:8787',
39
- ];
40
-
41
- /** The default transport: POSTs `body` (a JSON string) to `url` and resolves
42
- * with `{ status, text }`, or rejects on a network error or once 10s have
43
- * passed. node:https rather than fetch: on Windows (seen on Node 24.11),
44
- * two fetch calls followed by process.exit abort Node with a libuv
45
- * assertion (src\win\async.c) and exit 127 instead of 1 or 75. `agent:
46
- * false` keeps no connection alive past the answer. */
47
- export function httpsPostJson(url, body) {
48
- return new Promise((resolve, reject) => {
49
- const req = https.request(
50
- url,
51
- {
52
- method: 'POST',
53
- agent: false,
54
- headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
55
- signal: AbortSignal.timeout(10_000),
56
- },
57
- (res) => {
58
- let text = '';
59
- res.setEncoding('utf8');
60
- res.on('data', (chunk) => (text += chunk));
61
- res.on('end', () => resolve({ status: res.statusCode, text }));
62
- res.on('error', reject);
63
- },
64
- );
65
- req.on('error', reject);
66
- req.end(body);
67
- });
68
- }
69
-
70
- /** Asks one server about the key. Never throws; the answer is one of
71
- * 'valid' - a 2xx with `valid: true`.
72
- * 'invalid' - any other 2xx, or a 4xx other than 404: the server
73
- * looked at the key and said no.
74
- * 'unavailable' - network error, timeout, 5xx or 404 (a server that
75
- * doesn't have /v1/validate yet can't judge the key),
76
- * or any other status. `reason` says which.
77
- * `transport` is httpsPostJson unless a test passes a stand-in. */
78
- export async function askKeyServer(serverUrl, key, transport = httpsPostJson) {
79
- let res;
80
- try {
81
- res = await transport(new URL('/v1/validate', serverUrl), JSON.stringify({ key }));
82
- } catch (err) {
83
- return { result: 'unavailable', reason: err.message };
84
- }
85
-
86
- if (res.status >= 200 && res.status < 300) {
87
- let body = null;
88
- try {
89
- body = JSON.parse(res.text);
90
- } catch {}
91
- return body?.valid === true ? { result: 'valid' } : { result: 'invalid', reason: `HTTP ${res.status}` };
92
- }
93
- if (res.status >= 400 && res.status < 500 && res.status !== 404) {
94
- return { result: 'invalid', reason: `HTTP ${res.status}` };
95
- }
96
- return { result: 'unavailable', reason: `HTTP ${res.status}` };
97
- }
98
-
99
- /** `transport` is passed on to askKeyServer - tests only. */
100
- export async function requireBuildKey(providedKey, transport = httpsPostJson) {
101
- if (!providedKey) {
102
- log.error('build requires a valid --key (or WRITEDOCS_API_KEY).');
103
- process.exit(1);
104
- }
105
-
106
- // The exit code is a contract with whoever runs `build` - the WriteDocs
107
- // platform retries on it, never on the message text:
108
- // 1 - the key was not accepted: missing key, or no server said `valid`
109
- // and at least one said no. Trying again with the same key gives
110
- // the same answer.
111
- // 75 - EX_TEMPFAIL (sysexits.h): no server could be asked - each one
112
- // gave a network error, timeout, 5xx or 404. Still fails closed (no
113
- // build happens); it only tells the caller that trying later may
114
- // work.
115
- // The first `valid` wins; a server that says no doesn't stop the next one
116
- // from being asked, since a key may be known to only one of them.
117
- const answers = [];
118
- for (const serverUrl of KEY_SERVER_URLS) {
119
- const answer = await askKeyServer(serverUrl, providedKey, transport);
120
- if (answer.result === 'valid') return;
121
- answers.push({ serverUrl, ...answer });
122
- }
123
-
124
- if (answers.some((a) => a.result === 'invalid')) {
125
- log.error('build requires a valid --key (or WRITEDOCS_API_KEY) - the server rejected this one.');
126
- process.exit(1);
127
- }
128
-
129
- // Every server unavailable. Fails closed, same as a rejection - an
130
- // unreachable authorization server is not treated as "no opinion, let it
131
- // through".
132
- log.error('Could not reach any build authorization server - try again later:');
133
- for (const a of answers) log.line(` ${a.serverUrl}: ${a.reason}`);
134
- process.exit(EX_TEMPFAIL);
135
- }
1
+ /**
2
+ * `writedocs build` produces the artifact that actually gets deployed, so
3
+ * unlike `dev`/`init` it isn't freely runnable by anyone who installs the
4
+ * package - it's gated behind a key that a separate service
5
+ * (writedocs-key-server, a sibling repo) actually decides the validity of.
6
+ *
7
+ * This deliberately isn't a local check. An earlier version compared the
8
+ * supplied key against an env var set on the same machine
9
+ * (WRITEDOCS_BUILD_SECRET) - but since writedocs ships its full source to
10
+ * everyone who installs it, anyone could read that check and satisfy it
11
+ * with a value they made up themselves. Calling out to a server that
12
+ * actually holds the set of issued keys means a key's validity is decided
13
+ * by whoever runs that server, not by whoever is running `build`.
14
+ *
15
+ * See docs/dev/docs/deploy.mdx for how to deploy writedocs-key-server and
16
+ * issue keys, and that repo's own README for the service's endpoints.
17
+ */
18
+ import https from 'node:https';
19
+ import { log } from './output.js';
20
+
21
+ export const EX_TEMPFAIL = 75;
22
+
23
+ /** The authorization servers every `build` asks, in this order. Two only
24
+ * while key validation moves to the WriteDocs platform (the first entry);
25
+ * the second, writedocs-key-server, goes once every key comes from the
26
+ * platform.
27
+ *
28
+ * Fixed in the code, with no environment override: when the URL came from
29
+ * WRITEDOCS_KEY_SERVER_URL, anyone could point it at a 3-line server that
30
+ * answers `{ "valid": true }` and build without a key. Tests and CI use a
31
+ * real key instead (the WRITEDOCS_API_KEY secret - see
32
+ * scripts/smoke-installed-cli.sh). Honest limit: the source ships with the
33
+ * package, so someone willing to edit it can still remove this check - it
34
+ * raises the bar, it isn't a lock. Real protection is what the platform
35
+ * does with the output. */
36
+ export const KEY_SERVER_URLS = [
37
+ 'https://api.writedocs.io',
38
+ 'https://proxy.writechoice.io:8787',
39
+ ];
40
+
41
+ /** The default transport: POSTs `body` (a JSON string) to `url` and resolves
42
+ * with `{ status, text }`, or rejects on a network error or once 10s have
43
+ * passed. node:https rather than fetch: on Windows (seen on Node 24.11),
44
+ * two fetch calls followed by process.exit abort Node with a libuv
45
+ * assertion (src\win\async.c) and exit 127 instead of 1 or 75. `agent:
46
+ * false` keeps no connection alive past the answer. */
47
+ export function httpsPostJson(url, body) {
48
+ return new Promise((resolve, reject) => {
49
+ const req = https.request(
50
+ url,
51
+ {
52
+ method: 'POST',
53
+ agent: false,
54
+ headers: { 'content-type': 'application/json', 'content-length': Buffer.byteLength(body) },
55
+ signal: AbortSignal.timeout(10_000),
56
+ },
57
+ (res) => {
58
+ let text = '';
59
+ res.setEncoding('utf8');
60
+ res.on('data', (chunk) => (text += chunk));
61
+ res.on('end', () => resolve({ status: res.statusCode, text }));
62
+ res.on('error', reject);
63
+ },
64
+ );
65
+ req.on('error', reject);
66
+ req.end(body);
67
+ });
68
+ }
69
+
70
+ /** Asks one server about the key. Never throws; the answer is one of
71
+ * 'valid' - a 2xx with `valid: true`.
72
+ * 'invalid' - any other 2xx, or a 4xx other than 404: the server
73
+ * looked at the key and said no.
74
+ * 'unavailable' - network error, timeout, 5xx or 404 (a server that
75
+ * doesn't have /v1/validate yet can't judge the key),
76
+ * or any other status. `reason` says which.
77
+ * `transport` is httpsPostJson unless a test passes a stand-in. */
78
+ export async function askKeyServer(serverUrl, key, transport = httpsPostJson) {
79
+ let res;
80
+ try {
81
+ res = await transport(new URL('/v1/validate', serverUrl), JSON.stringify({ key }));
82
+ } catch (err) {
83
+ return { result: 'unavailable', reason: err.message };
84
+ }
85
+
86
+ if (res.status >= 200 && res.status < 300) {
87
+ let body = null;
88
+ try {
89
+ body = JSON.parse(res.text);
90
+ } catch {}
91
+ return body?.valid === true ? { result: 'valid' } : { result: 'invalid', reason: `HTTP ${res.status}` };
92
+ }
93
+ if (res.status >= 400 && res.status < 500 && res.status !== 404) {
94
+ return { result: 'invalid', reason: `HTTP ${res.status}` };
95
+ }
96
+ return { result: 'unavailable', reason: `HTTP ${res.status}` };
97
+ }
98
+
99
+ /** `transport` is passed on to askKeyServer - tests only. */
100
+ export async function requireBuildKey(providedKey, transport = httpsPostJson) {
101
+ if (!providedKey) {
102
+ log.error('build requires a valid --key (or WRITEDOCS_API_KEY).');
103
+ process.exit(1);
104
+ }
105
+
106
+ // The exit code is a contract with whoever runs `build` - the WriteDocs
107
+ // platform retries on it, never on the message text:
108
+ // 1 - the key was not accepted: missing key, or no server said `valid`
109
+ // and at least one said no. Trying again with the same key gives
110
+ // the same answer.
111
+ // 75 - EX_TEMPFAIL (sysexits.h): no server could be asked - each one
112
+ // gave a network error, timeout, 5xx or 404. Still fails closed (no
113
+ // build happens); it only tells the caller that trying later may
114
+ // work.
115
+ // The first `valid` wins; a server that says no doesn't stop the next one
116
+ // from being asked, since a key may be known to only one of them.
117
+ const answers = [];
118
+ for (const serverUrl of KEY_SERVER_URLS) {
119
+ const answer = await askKeyServer(serverUrl, providedKey, transport);
120
+ if (answer.result === 'valid') return;
121
+ answers.push({ serverUrl, ...answer });
122
+ }
123
+
124
+ if (answers.some((a) => a.result === 'invalid')) {
125
+ log.error('build requires a valid --key (or WRITEDOCS_API_KEY) - the server rejected this one.');
126
+ process.exit(1);
127
+ }
128
+
129
+ // Every server unavailable. Fails closed, same as a rejection - an
130
+ // unreachable authorization server is not treated as "no opinion, let it
131
+ // through".
132
+ log.error('Could not reach any build authorization server - try again later:');
133
+ for (const a of answers) log.line(` ${a.serverUrl}: ${a.reason}`);
134
+ process.exit(EX_TEMPFAIL);
135
+ }