@writedocs/generator 0.11.0 → 0.11.1
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.
- package/package.json +3 -1
- package/src/cli/astro-output.js +44 -11
- package/src/cli/build.js +177 -177
- package/src/cli/dev.js +261 -261
- package/src/scripts/search.ts +9 -5
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@writedocs/generator",
|
|
3
|
-
"version": "0.11.
|
|
3
|
+
"version": "0.11.1",
|
|
4
4
|
"description": "Static site generator for docs — a writedocs.json + MDX folder in, a static site out.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -83,9 +83,11 @@
|
|
|
83
83
|
"react-dom": "19.2.8",
|
|
84
84
|
"rehype-katex": "7.0.1",
|
|
85
85
|
"remark-math": "6.0.0",
|
|
86
|
+
"rolldown": "1.2.4",
|
|
86
87
|
"satori": "0.44.0",
|
|
87
88
|
"shiki": "4.4.3",
|
|
88
89
|
"tailwindcss": "4.3.3",
|
|
90
|
+
"vite": "8.2.1",
|
|
89
91
|
"zod": "4.4.3"
|
|
90
92
|
},
|
|
91
93
|
"engines": {
|
package/src/cli/astro-output.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
// author should see or noise to hide.
|
|
6
6
|
import fs from 'node:fs';
|
|
7
7
|
import path from 'node:path';
|
|
8
|
+
import { fileURLToPath } from 'node:url';
|
|
8
9
|
|
|
9
10
|
const ANSI = /\x1b\[[0-9;]*m/g;
|
|
10
11
|
export const stripAnsi = (text) => String(text ?? '').replace(ANSI, '');
|
|
@@ -14,7 +15,10 @@ export const stripAnsi = (text) => String(text ?? '').replace(ANSI, '');
|
|
|
14
15
|
const SECTION = /\n\s*(Stack trace|Hint|Error reference|Location|Caused by):/;
|
|
15
16
|
|
|
16
17
|
function absolutePath(file, root) {
|
|
17
|
-
const clean = file.replace(
|
|
18
|
+
const clean = file.replace(/[?#].*$/, '');
|
|
19
|
+
if (clean.startsWith('file:')) {
|
|
20
|
+
try { return fileURLToPath(clean); } catch {}
|
|
21
|
+
}
|
|
18
22
|
return path.resolve(root ?? process.cwd(), clean);
|
|
19
23
|
}
|
|
20
24
|
|
|
@@ -146,19 +150,48 @@ export function requestLog(event) {
|
|
|
146
150
|
return match ? { status: Number(match[1]), url: match[2] } : null;
|
|
147
151
|
}
|
|
148
152
|
|
|
153
|
+
// Warnings that name the author's page but are about code writedocs and
|
|
154
|
+
// Astro generate, so there's nothing for the author to do: newer rolldown
|
|
155
|
+
// versions flag the "use astro:head-inject" directive Astro writes into the
|
|
156
|
+
// wrapper module of every .mdx page (astro/dist/content/
|
|
157
|
+
// vite-plugin-content-assets.js) - one warning per page, on every build.
|
|
158
|
+
const GENERATED_CODE_WARNINGS = [/\[MODULE_LEVEL_DIRECTIVE\][^\n]*"use astro:head-inject"/];
|
|
159
|
+
|
|
160
|
+
const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
161
|
+
|
|
149
162
|
/** An Astro/Vite warning worth showing the author: one about their own
|
|
150
|
-
* files (it names a path inside the project),
|
|
151
|
-
*
|
|
152
|
-
* internals - is about writedocs itself, and stays
|
|
153
|
-
* it).
|
|
154
|
-
|
|
163
|
+
* files (it names a path inside the project), with those paths rewritten
|
|
164
|
+
* relative to the project. Everything else - bundle sizes, dependency
|
|
165
|
+
* optimization, route internals - is about writedocs itself, and stays
|
|
166
|
+
* hidden (--verbose shows it).
|
|
167
|
+
*
|
|
168
|
+
* A path counts only as a whole path that resolves inside contentDir:
|
|
169
|
+
* absolute, or relative to `root` (Astro's working folder, the package
|
|
170
|
+
* root - rolldown names modules that way). Matching contentDir as a bare
|
|
171
|
+
* substring once let a project at /build claim every warning naming
|
|
172
|
+
* ".../build/..." and turned "creator-review/build.mdx" into
|
|
173
|
+
* "creator-review..mdx". */
|
|
174
|
+
export function authorWarning(event, contentDir, { root } = {}) {
|
|
155
175
|
if (event.type !== 'astro-log' || event.level !== 'warn') return null;
|
|
156
176
|
const text = stripAnsi(event.message);
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
177
|
+
if (GENERATED_CODE_WARNINGS.some((pattern) => pattern.test(text))) return null;
|
|
178
|
+
|
|
179
|
+
// A path starts after a space, a quote or a bracket, as contentDir itself
|
|
180
|
+
// (which may hold spaces) or as ./ or ../, and runs to the next of those.
|
|
181
|
+
const variants = [...new Set([contentDir, contentDir.split(path.sep).join('/'), contentDir.split('/').join('\\')])];
|
|
182
|
+
const starts = [...variants.map(escapeRegExp), '\\.\\.?[\\\\/]'].join('|');
|
|
183
|
+
const pathToken = new RegExp(`(?<![^\\s"'\`(\\[<=])(?:file:///?)?(?:${starts})[^\\s"'\`()\\[\\]<>,]*`, 'g');
|
|
184
|
+
|
|
185
|
+
let named = false;
|
|
186
|
+
const out = text.replace(pathToken, (token) => {
|
|
187
|
+
const at = token.match(/(?::\d+){1,2}$/)?.[0] ?? '';
|
|
188
|
+
const file = token.slice(0, token.length - at.length);
|
|
189
|
+
const rel = relativeTo(contentDir, file, root);
|
|
190
|
+
if (rel === null) return token;
|
|
191
|
+
named = true;
|
|
192
|
+
return `${rel || '.'}${at}`;
|
|
193
|
+
});
|
|
194
|
+
return named ? out.trim() : null;
|
|
162
195
|
}
|
|
163
196
|
|
|
164
197
|
/** One event as a plain line, for --verbose. */
|
package/src/cli/build.js
CHANGED
|
@@ -1,177 +1,177 @@
|
|
|
1
|
-
import { canonicalPath } from '../lib/canonical-path.js';
|
|
2
|
-
import fs from 'node:fs';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { runAstro } from './run-astro.js';
|
|
5
|
-
import { runPagefind } from './run-pagefind.js';
|
|
6
|
-
import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
|
|
7
|
-
import { generateApiPages } from './generate-api-pages.js';
|
|
8
|
-
import { writeRedirectsFile } from './write-redirects-file.js';
|
|
9
|
-
import { rewriteRedirectPages } from './rewrite-redirect-pages.js';
|
|
10
|
-
import { readConfigText } from '../lib/config-file.js';
|
|
11
|
-
import { writeMcpFiles } from './write-mcp-files.js';
|
|
12
|
-
import { pagesWithoutStyles } from './check-built-styles.js';
|
|
13
|
-
import { writedocsBuildStagingDir } from '../lib/writedocs-temp-dir.js';
|
|
14
|
-
import { normalizeBasePath } from '../lib/base-path.js';
|
|
15
|
-
import { siteDirFor, moveRootFiles } from './base-path-layout.js';
|
|
16
|
-
import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
|
|
17
|
-
import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
|
|
18
|
-
import { reportApiPages } from './api-pages-output.js';
|
|
19
|
-
|
|
20
|
-
export async function runBuild({ contentDir, packageRoot, verbose = false }) {
|
|
21
|
-
// One spelling of each folder throughout - see lib/canonical-path.js.
|
|
22
|
-
contentDir = canonicalPath(contentDir);
|
|
23
|
-
packageRoot = canonicalPath(packageRoot);
|
|
24
|
-
const started = Date.now();
|
|
25
|
-
preflightCheck(contentDir);
|
|
26
|
-
writableInstallCheck(packageRoot);
|
|
27
|
-
|
|
28
|
-
// Collected while building, printed together at the end - a warning in
|
|
29
|
-
// the middle of a spinner is easy to miss.
|
|
30
|
-
const warnings = [];
|
|
31
|
-
const notes = [];
|
|
32
|
-
const seen = new Set();
|
|
33
|
-
const addWarning = (where, message) => {
|
|
34
|
-
const key = `${where ?? ''}\n${message}`;
|
|
35
|
-
if (seen.has(key)) return;
|
|
36
|
-
seen.add(key);
|
|
37
|
-
warnings.push({ where, message });
|
|
38
|
-
};
|
|
39
|
-
|
|
40
|
-
const api = await generateApiPages({ contentDir });
|
|
41
|
-
sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
|
|
42
|
-
reportApiPages(api);
|
|
43
|
-
api.warnings.forEach((message) => addWarning(null, message));
|
|
44
|
-
|
|
45
|
-
const building = step('Building pages');
|
|
46
|
-
const buildStarted = Date.now();
|
|
47
|
-
let pages = 0;
|
|
48
|
-
let fatal = null;
|
|
49
|
-
const rawTail = [];
|
|
50
|
-
const { exited } = runAstro('build', {
|
|
51
|
-
packageRoot,
|
|
52
|
-
contentDir,
|
|
53
|
-
onEvent(event) {
|
|
54
|
-
if (verbose) {
|
|
55
|
-
const line = verboseLine(event);
|
|
56
|
-
if (line !== null) log.line(color.dim(line));
|
|
57
|
-
}
|
|
58
|
-
if (event.type === 'fatal') {
|
|
59
|
-
fatal = event.error;
|
|
60
|
-
return;
|
|
61
|
-
}
|
|
62
|
-
if (event.type === 'report') {
|
|
63
|
-
if (event.level === 'warn') addWarning(event.where, event.message);
|
|
64
|
-
else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
|
|
65
|
-
return;
|
|
66
|
-
}
|
|
67
|
-
if (event.type === 'raw') {
|
|
68
|
-
rawTail.push(event.line);
|
|
69
|
-
if (rawTail.length > 40) rawTail.shift();
|
|
70
|
-
return;
|
|
71
|
-
}
|
|
72
|
-
const route = builtRoute(event);
|
|
73
|
-
if (route) {
|
|
74
|
-
if (route.endsWith('.html')) pages += 1;
|
|
75
|
-
building.update(`Building pages ${color.dim(`(${pages})`)}`);
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
const warning = authorWarning(event, contentDir);
|
|
79
|
-
if (warning) addWarning(null, warning);
|
|
80
|
-
},
|
|
81
|
-
});
|
|
82
|
-
const code = await exited;
|
|
83
|
-
|
|
84
|
-
if (fatal || code !== 0) {
|
|
85
|
-
building.fail('Build failed');
|
|
86
|
-
if (fatal) {
|
|
87
|
-
const problem = describeError(fatal, contentDir, { root: packageRoot });
|
|
88
|
-
log.line();
|
|
89
|
-
log.line(formatProblems([{ where: problem.where, message: problem.message }]));
|
|
90
|
-
if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
|
|
91
|
-
if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
|
|
92
|
-
} else if (rawTail.length) {
|
|
93
|
-
// No structured error (the worker itself crashed) - show what it printed.
|
|
94
|
-
log.line();
|
|
95
|
-
log.line(color.dim(rawTail.join('\n')));
|
|
96
|
-
}
|
|
97
|
-
log.line();
|
|
98
|
-
log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
|
|
99
|
-
throw new CliExit(1);
|
|
100
|
-
}
|
|
101
|
-
building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
|
|
102
|
-
|
|
103
|
-
const distDir = path.join(contentDir, 'dist');
|
|
104
|
-
// writedocs.json has been through the build's own validation by now.
|
|
105
|
-
const siteConfig = JSON.parse(readConfigText(contentDir));
|
|
106
|
-
// With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
|
|
107
|
-
// host's own files stay at the root of dist/ - see base-path-layout.js.
|
|
108
|
-
// Without one, siteDir is distDir, and every step below is what it was.
|
|
109
|
-
const basePath = normalizeBasePath(siteConfig.basePath);
|
|
110
|
-
const siteDir = siteDirFor(distDir, basePath);
|
|
111
|
-
// Astro just wrote its actual output to writedocsBuildStagingDir()
|
|
112
|
-
// (astro.config.mjs's own `outDir`), not distDir directly - see that
|
|
113
|
-
// function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
|
|
114
|
-
// (unlike the fs.rename() Astro uses internally to get *into* that
|
|
115
|
-
// staging dir in the first place) copies across filesystem boundaries
|
|
116
|
-
// without issue, so this is the one step that actually needs to bridge
|
|
117
|
-
// packageRoot and contentDir potentially living on different devices.
|
|
118
|
-
// distDir is cleared first so a rebuild doesn't leave a stale file
|
|
119
|
-
// behind from a previous build that the new one no longer produces -
|
|
120
|
-
// the same "the output directory reflects exactly this build, nothing
|
|
121
|
-
// older" expectation `astro build` itself already guarantees when
|
|
122
|
-
// writing directly into outDir.
|
|
123
|
-
const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
|
|
124
|
-
fs.rmSync(distDir, { recursive: true, force: true });
|
|
125
|
-
fs.cpSync(stagingDir, siteDir, { recursive: true });
|
|
126
|
-
fs.rmSync(stagingDir, { recursive: true, force: true });
|
|
127
|
-
moveRootFiles(siteDir, distDir);
|
|
128
|
-
// Every page writedocs renders links the site's stylesheet. Builds have
|
|
129
|
-
// come out without it on every page while reporting success (the package
|
|
130
|
-
// folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
|
|
131
|
-
// here, and a build like that stops instead of being deployed unstyled.
|
|
132
|
-
const unstyled = pagesWithoutStyles(distDir, { basePath });
|
|
133
|
-
if (unstyled.length) {
|
|
134
|
-
log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
|
|
135
|
-
log.detail(color.dim('This is a fault in the build, not in your pages. Build again; if it happens again, report it with the output of --verbose.'));
|
|
136
|
-
throw new CliExit(1);
|
|
137
|
-
}
|
|
138
|
-
// Astro's own writedocs.json `redirects` + the automatic "/" redirect only
|
|
139
|
-
// ever produce client-side meta-refresh pages (see write-redirects-file.js)
|
|
140
|
-
// - this turns those into real instant edge redirects on hosts that read
|
|
141
|
-
// a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
|
|
142
|
-
writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
|
|
143
|
-
// Every other host follows Astro's redirect pages - rewritten so the
|
|
144
|
-
// reader never sees one (rewrite-redirect-pages.js).
|
|
145
|
-
rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
|
|
146
|
-
// The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
|
|
147
|
-
// Astro route); this adds the Cloudflare _worker.js that serves it - see
|
|
148
|
-
// write-mcp-files.js for every host.
|
|
149
|
-
const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
|
|
150
|
-
const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
|
|
151
|
-
if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
|
|
152
|
-
if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
|
|
153
|
-
|
|
154
|
-
const indexing = step('Indexing search');
|
|
155
|
-
try {
|
|
156
|
-
await runPagefind(siteDir, { packageRoot });
|
|
157
|
-
} catch (err) {
|
|
158
|
-
indexing.fail('Search indexing failed');
|
|
159
|
-
log.line();
|
|
160
|
-
log.line(color.dim(err.message));
|
|
161
|
-
throw new CliExit(1);
|
|
162
|
-
}
|
|
163
|
-
indexing.succeed('Indexed search');
|
|
164
|
-
|
|
165
|
-
if (warnings.length) {
|
|
166
|
-
log.line();
|
|
167
|
-
log.warn(plural(warnings.length, 'warning'));
|
|
168
|
-
log.line();
|
|
169
|
-
log.line(formatProblems(warnings));
|
|
170
|
-
}
|
|
171
|
-
if (notes.length) {
|
|
172
|
-
log.line();
|
|
173
|
-
notes.forEach((note) => log.info(note));
|
|
174
|
-
}
|
|
175
|
-
log.line();
|
|
176
|
-
log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
|
|
177
|
-
}
|
|
1
|
+
import { canonicalPath } from '../lib/canonical-path.js';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { runAstro } from './run-astro.js';
|
|
5
|
+
import { runPagefind } from './run-pagefind.js';
|
|
6
|
+
import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
|
|
7
|
+
import { generateApiPages } from './generate-api-pages.js';
|
|
8
|
+
import { writeRedirectsFile } from './write-redirects-file.js';
|
|
9
|
+
import { rewriteRedirectPages } from './rewrite-redirect-pages.js';
|
|
10
|
+
import { readConfigText } from '../lib/config-file.js';
|
|
11
|
+
import { writeMcpFiles } from './write-mcp-files.js';
|
|
12
|
+
import { pagesWithoutStyles } from './check-built-styles.js';
|
|
13
|
+
import { writedocsBuildStagingDir } from '../lib/writedocs-temp-dir.js';
|
|
14
|
+
import { normalizeBasePath } from '../lib/base-path.js';
|
|
15
|
+
import { siteDirFor, moveRootFiles } from './base-path-layout.js';
|
|
16
|
+
import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
|
|
17
|
+
import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
|
|
18
|
+
import { reportApiPages } from './api-pages-output.js';
|
|
19
|
+
|
|
20
|
+
export async function runBuild({ contentDir, packageRoot, verbose = false }) {
|
|
21
|
+
// One spelling of each folder throughout - see lib/canonical-path.js.
|
|
22
|
+
contentDir = canonicalPath(contentDir);
|
|
23
|
+
packageRoot = canonicalPath(packageRoot);
|
|
24
|
+
const started = Date.now();
|
|
25
|
+
preflightCheck(contentDir);
|
|
26
|
+
writableInstallCheck(packageRoot);
|
|
27
|
+
|
|
28
|
+
// Collected while building, printed together at the end - a warning in
|
|
29
|
+
// the middle of a spinner is easy to miss.
|
|
30
|
+
const warnings = [];
|
|
31
|
+
const notes = [];
|
|
32
|
+
const seen = new Set();
|
|
33
|
+
const addWarning = (where, message) => {
|
|
34
|
+
const key = `${where ?? ''}\n${message}`;
|
|
35
|
+
if (seen.has(key)) return;
|
|
36
|
+
seen.add(key);
|
|
37
|
+
warnings.push({ where, message });
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
const api = await generateApiPages({ contentDir });
|
|
41
|
+
sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
|
|
42
|
+
reportApiPages(api);
|
|
43
|
+
api.warnings.forEach((message) => addWarning(null, message));
|
|
44
|
+
|
|
45
|
+
const building = step('Building pages');
|
|
46
|
+
const buildStarted = Date.now();
|
|
47
|
+
let pages = 0;
|
|
48
|
+
let fatal = null;
|
|
49
|
+
const rawTail = [];
|
|
50
|
+
const { exited } = runAstro('build', {
|
|
51
|
+
packageRoot,
|
|
52
|
+
contentDir,
|
|
53
|
+
onEvent(event) {
|
|
54
|
+
if (verbose) {
|
|
55
|
+
const line = verboseLine(event);
|
|
56
|
+
if (line !== null) log.line(color.dim(line));
|
|
57
|
+
}
|
|
58
|
+
if (event.type === 'fatal') {
|
|
59
|
+
fatal = event.error;
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
if (event.type === 'report') {
|
|
63
|
+
if (event.level === 'warn') addWarning(event.where, event.message);
|
|
64
|
+
else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (event.type === 'raw') {
|
|
68
|
+
rawTail.push(event.line);
|
|
69
|
+
if (rawTail.length > 40) rawTail.shift();
|
|
70
|
+
return;
|
|
71
|
+
}
|
|
72
|
+
const route = builtRoute(event);
|
|
73
|
+
if (route) {
|
|
74
|
+
if (route.endsWith('.html')) pages += 1;
|
|
75
|
+
building.update(`Building pages ${color.dim(`(${pages})`)}`);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const warning = authorWarning(event, contentDir, { root: packageRoot });
|
|
79
|
+
if (warning) addWarning(null, warning);
|
|
80
|
+
},
|
|
81
|
+
});
|
|
82
|
+
const code = await exited;
|
|
83
|
+
|
|
84
|
+
if (fatal || code !== 0) {
|
|
85
|
+
building.fail('Build failed');
|
|
86
|
+
if (fatal) {
|
|
87
|
+
const problem = describeError(fatal, contentDir, { root: packageRoot });
|
|
88
|
+
log.line();
|
|
89
|
+
log.line(formatProblems([{ where: problem.where, message: problem.message }]));
|
|
90
|
+
if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
|
|
91
|
+
if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
|
|
92
|
+
} else if (rawTail.length) {
|
|
93
|
+
// No structured error (the worker itself crashed) - show what it printed.
|
|
94
|
+
log.line();
|
|
95
|
+
log.line(color.dim(rawTail.join('\n')));
|
|
96
|
+
}
|
|
97
|
+
log.line();
|
|
98
|
+
log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
|
|
99
|
+
throw new CliExit(1);
|
|
100
|
+
}
|
|
101
|
+
building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
|
|
102
|
+
|
|
103
|
+
const distDir = path.join(contentDir, 'dist');
|
|
104
|
+
// writedocs.json has been through the build's own validation by now.
|
|
105
|
+
const siteConfig = JSON.parse(readConfigText(contentDir));
|
|
106
|
+
// With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
|
|
107
|
+
// host's own files stay at the root of dist/ - see base-path-layout.js.
|
|
108
|
+
// Without one, siteDir is distDir, and every step below is what it was.
|
|
109
|
+
const basePath = normalizeBasePath(siteConfig.basePath);
|
|
110
|
+
const siteDir = siteDirFor(distDir, basePath);
|
|
111
|
+
// Astro just wrote its actual output to writedocsBuildStagingDir()
|
|
112
|
+
// (astro.config.mjs's own `outDir`), not distDir directly - see that
|
|
113
|
+
// function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
|
|
114
|
+
// (unlike the fs.rename() Astro uses internally to get *into* that
|
|
115
|
+
// staging dir in the first place) copies across filesystem boundaries
|
|
116
|
+
// without issue, so this is the one step that actually needs to bridge
|
|
117
|
+
// packageRoot and contentDir potentially living on different devices.
|
|
118
|
+
// distDir is cleared first so a rebuild doesn't leave a stale file
|
|
119
|
+
// behind from a previous build that the new one no longer produces -
|
|
120
|
+
// the same "the output directory reflects exactly this build, nothing
|
|
121
|
+
// older" expectation `astro build` itself already guarantees when
|
|
122
|
+
// writing directly into outDir.
|
|
123
|
+
const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
|
|
124
|
+
fs.rmSync(distDir, { recursive: true, force: true });
|
|
125
|
+
fs.cpSync(stagingDir, siteDir, { recursive: true });
|
|
126
|
+
fs.rmSync(stagingDir, { recursive: true, force: true });
|
|
127
|
+
moveRootFiles(siteDir, distDir);
|
|
128
|
+
// Every page writedocs renders links the site's stylesheet. Builds have
|
|
129
|
+
// come out without it on every page while reporting success (the package
|
|
130
|
+
// folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
|
|
131
|
+
// here, and a build like that stops instead of being deployed unstyled.
|
|
132
|
+
const unstyled = pagesWithoutStyles(distDir, { basePath });
|
|
133
|
+
if (unstyled.length) {
|
|
134
|
+
log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
|
|
135
|
+
log.detail(color.dim('This is a fault in the build, not in your pages. Build again; if it happens again, report it with the output of --verbose.'));
|
|
136
|
+
throw new CliExit(1);
|
|
137
|
+
}
|
|
138
|
+
// Astro's own writedocs.json `redirects` + the automatic "/" redirect only
|
|
139
|
+
// ever produce client-side meta-refresh pages (see write-redirects-file.js)
|
|
140
|
+
// - this turns those into real instant edge redirects on hosts that read
|
|
141
|
+
// a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
|
|
142
|
+
writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
|
|
143
|
+
// Every other host follows Astro's redirect pages - rewritten so the
|
|
144
|
+
// reader never sees one (rewrite-redirect-pages.js).
|
|
145
|
+
rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
|
|
146
|
+
// The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
|
|
147
|
+
// Astro route); this adds the Cloudflare _worker.js that serves it - see
|
|
148
|
+
// write-mcp-files.js for every host.
|
|
149
|
+
const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
|
|
150
|
+
const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
|
|
151
|
+
if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
|
|
152
|
+
if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
|
|
153
|
+
|
|
154
|
+
const indexing = step('Indexing search');
|
|
155
|
+
try {
|
|
156
|
+
await runPagefind(siteDir, { packageRoot });
|
|
157
|
+
} catch (err) {
|
|
158
|
+
indexing.fail('Search indexing failed');
|
|
159
|
+
log.line();
|
|
160
|
+
log.line(color.dim(err.message));
|
|
161
|
+
throw new CliExit(1);
|
|
162
|
+
}
|
|
163
|
+
indexing.succeed('Indexed search');
|
|
164
|
+
|
|
165
|
+
if (warnings.length) {
|
|
166
|
+
log.line();
|
|
167
|
+
log.warn(plural(warnings.length, 'warning'));
|
|
168
|
+
log.line();
|
|
169
|
+
log.line(formatProblems(warnings));
|
|
170
|
+
}
|
|
171
|
+
if (notes.length) {
|
|
172
|
+
log.line();
|
|
173
|
+
notes.forEach((note) => log.info(note));
|
|
174
|
+
}
|
|
175
|
+
log.line();
|
|
176
|
+
log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
|
|
177
|
+
}
|
package/src/cli/dev.js
CHANGED
|
@@ -1,261 +1,261 @@
|
|
|
1
|
-
import { canonicalPath } from '../lib/canonical-path.js';
|
|
2
|
-
import { runAstro } from './run-astro.js';
|
|
3
|
-
import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
|
|
4
|
-
import { generateApiPages } from './generate-api-pages.js';
|
|
5
|
-
import { log, step, duration, formatProblems, color, CliExit } from './output.js';
|
|
6
|
-
import { describeError, requestLog, authorWarning, verboseLine, stripAnsi } from './astro-output.js';
|
|
7
|
-
import { reportApiPages } from './api-pages-output.js';
|
|
8
|
-
import { runningPreview, writeLock, removeLock } from './dev-lock.js';
|
|
9
|
-
import { showUpdateNotice } from './update-check.js';
|
|
10
|
-
import { shouldOpenBrowser, openBrowser } from './open-browser.js';
|
|
11
|
-
import { watchPageList } from './page-list-watch.js';
|
|
12
|
-
import { readConfigText } from '../lib/config-file.js';
|
|
13
|
-
import { normalizeBasePath } from '../lib/base-path.js';
|
|
14
|
-
|
|
15
|
-
/** The preview's address for the server's own (`http://localhost:4321/`):
|
|
16
|
-
* under writedocs.json's `basePath` when it has one - the site is served
|
|
17
|
-
* at /docs/ then, and / is Astro's "not here" page. Read when the server
|
|
18
|
-
* is ready, so it follows the file. */
|
|
19
|
-
export function previewAddress(serverUrl, configText) {
|
|
20
|
-
let basePath = '';
|
|
21
|
-
try {
|
|
22
|
-
basePath = normalizeBasePath(JSON.parse(configText).basePath);
|
|
23
|
-
} catch {
|
|
24
|
-
// An unreadable writedocs.json stops the preview elsewhere.
|
|
25
|
-
}
|
|
26
|
-
return basePath ? new URL(`${basePath.slice(1)}/`, serverUrl).href : serverUrl;
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
// The same problem tends to arrive more than once in a row - Vite and
|
|
30
|
-
// Astro each log a failed page, and a page compiles for more than one
|
|
31
|
-
// environment. Within this window, a repeat is dropped.
|
|
32
|
-
const REPEAT_WINDOW_MS = 2000;
|
|
33
|
-
|
|
34
|
-
export async function runDev({ contentDir, packageRoot, port, verbose = false, open = true }) {
|
|
35
|
-
// One spelling of each folder throughout - see lib/canonical-path.js.
|
|
36
|
-
contentDir = canonicalPath(contentDir);
|
|
37
|
-
packageRoot = canonicalPath(packageRoot);
|
|
38
|
-
const started = Date.now();
|
|
39
|
-
preflightCheck(contentDir);
|
|
40
|
-
writableInstallCheck(packageRoot);
|
|
41
|
-
const other = runningPreview(packageRoot);
|
|
42
|
-
if (other) {
|
|
43
|
-
log.error(`Another writedocs preview is already running${other.url ? ` at ${other.url}` : ''}.`);
|
|
44
|
-
log.detail(
|
|
45
|
-
color.dim(
|
|
46
|
-
`It's serving ${other.contentDir}. Stop it first (Ctrl+C in its terminal) - two previews at once overwrite each other's pages.`
|
|
47
|
-
)
|
|
48
|
-
);
|
|
49
|
-
throw new CliExit(1);
|
|
50
|
-
}
|
|
51
|
-
writeLock(packageRoot, { contentDir, url: null });
|
|
52
|
-
process.on('exit', () => removeLock(packageRoot));
|
|
53
|
-
|
|
54
|
-
const api = await generateApiPages({ contentDir });
|
|
55
|
-
sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
|
|
56
|
-
reportApiPages(api);
|
|
57
|
-
api.warnings.forEach((message) => log.warn(message));
|
|
58
|
-
|
|
59
|
-
let starting = step('Starting local preview');
|
|
60
|
-
let ready = false;
|
|
61
|
-
let browserOpened = false;
|
|
62
|
-
// Restarting after pages were added or removed (see the watcher below):
|
|
63
|
-
// when that restart began, and the port to come back on.
|
|
64
|
-
let restartStarted = null;
|
|
65
|
-
let currentPort = port;
|
|
66
|
-
|
|
67
|
-
const lastShown = new Map();
|
|
68
|
-
const once = (key, print) => {
|
|
69
|
-
const now = Date.now();
|
|
70
|
-
if (now - (lastShown.get(key) ?? 0) < REPEAT_WINDOW_MS) return;
|
|
71
|
-
lastShown.set(key, now);
|
|
72
|
-
print();
|
|
73
|
-
};
|
|
74
|
-
const oneLine = (where, message) => (where ? `${color.bold(where)} ${message}` : message);
|
|
75
|
-
|
|
76
|
-
// A failed page is logged twice - Vite's error (message only) and then
|
|
77
|
-
// Astro's (message plus the file). Errors wait a moment so the two can
|
|
78
|
-
// be merged into one line that names the file.
|
|
79
|
-
// When the same page fails again, only the first report of it named the
|
|
80
|
-
// file: later ones point at the MDX compiler instead. The file each
|
|
81
|
-
// error was last seen in is remembered here, by the error itself.
|
|
82
|
-
const pendingErrors = new Map();
|
|
83
|
-
const knownWhere = new Map();
|
|
84
|
-
const showError = (problem) => {
|
|
85
|
-
if (problem.where) knownWhere.set(problem.key, problem.where);
|
|
86
|
-
else if (knownWhere.has(problem.key)) problem = { ...problem, where: knownWhere.get(problem.key) };
|
|
87
|
-
const existing = pendingErrors.get(problem.message);
|
|
88
|
-
if (existing) {
|
|
89
|
-
if (!existing.problem.where && problem.where) existing.problem = problem;
|
|
90
|
-
return;
|
|
91
|
-
}
|
|
92
|
-
const entry = { problem };
|
|
93
|
-
entry.timer = setTimeout(() => {
|
|
94
|
-
pendingErrors.delete(problem.message);
|
|
95
|
-
const { where, message, hint } = entry.problem;
|
|
96
|
-
once(`error\n${where}\n${message}`, () => {
|
|
97
|
-
log.error(oneLine(where, message));
|
|
98
|
-
if (hint) log.detail(color.dim(`Hint: ${hint}`));
|
|
99
|
-
});
|
|
100
|
-
}, 150);
|
|
101
|
-
pendingErrors.set(problem.message, entry);
|
|
102
|
-
};
|
|
103
|
-
|
|
104
|
-
let fatal = null;
|
|
105
|
-
const rawTail = [];
|
|
106
|
-
const onEvent = (event) => {
|
|
107
|
-
if (verbose) {
|
|
108
|
-
const line = verboseLine(event);
|
|
109
|
-
if (line !== null) log.line(color.dim(line));
|
|
110
|
-
}
|
|
111
|
-
switch (event.type) {
|
|
112
|
-
case 'ready': {
|
|
113
|
-
ready = true;
|
|
114
|
-
const [local] = event.urls?.local ?? [];
|
|
115
|
-
const wanted = Number(port ?? 4321);
|
|
116
|
-
const actual = local ? Number(new URL(local).port) : wanted;
|
|
117
|
-
const address = previewAddress(local ?? `http://localhost:${wanted}/`, readConfigText(contentDir));
|
|
118
|
-
writeLock(packageRoot, { contentDir, url: address });
|
|
119
|
-
currentPort = actual;
|
|
120
|
-
// Pages changed while it was starting: restart now that it's up.
|
|
121
|
-
if (restartPending) {
|
|
122
|
-
const change = restartPending;
|
|
123
|
-
restartPending = false;
|
|
124
|
-
setTimeout(() => restartForPages(change), 0);
|
|
125
|
-
}
|
|
126
|
-
// Back after a restart: one line - the open tab reloads by itself.
|
|
127
|
-
if (restartStarted !== null) {
|
|
128
|
-
starting.succeed(`Preview updated ${color.dim(`in ${duration(Date.now() - restartStarted)}`)}`);
|
|
129
|
-
restartStarted = null;
|
|
130
|
-
return;
|
|
131
|
-
}
|
|
132
|
-
starting.succeed(`Preview ready ${color.dim(`in ${duration(Date.now() - started)}`)}`);
|
|
133
|
-
log.line();
|
|
134
|
-
log.line(` ${color.bold('Local:')} ${color.cyan(address)}`);
|
|
135
|
-
if (actual !== wanted) log.line(color.dim(` Port ${wanted} was in use, so the preview is on ${actual}.`));
|
|
136
|
-
log.line();
|
|
137
|
-
log.line(color.dim(' Edit any page and the preview updates. Press Ctrl+C to stop.'));
|
|
138
|
-
log.line();
|
|
139
|
-
// `dev` runs until Ctrl+C - the notice goes under the ready screen,
|
|
140
|
-
// not after the command like everywhere else.
|
|
141
|
-
showUpdateNotice();
|
|
142
|
-
// The preview in the browser, at the address it actually got - once,
|
|
143
|
-
// not again if Astro restarts the server.
|
|
144
|
-
if (!browserOpened && shouldOpenBrowser({ open })) {
|
|
145
|
-
browserOpened = true;
|
|
146
|
-
openBrowser(address);
|
|
147
|
-
}
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
case 'fatal':
|
|
151
|
-
fatal = event.error;
|
|
152
|
-
return;
|
|
153
|
-
case 'report':
|
|
154
|
-
// 'info' notes are about the build (sitemap and the like), not
|
|
155
|
-
// the preview.
|
|
156
|
-
if (event.level === 'warn') once(`warn\n${event.where}\n${event.message}`, () => log.warn(oneLine(event.where, event.message)));
|
|
157
|
-
return;
|
|
158
|
-
case 'raw':
|
|
159
|
-
rawTail.push(event.line);
|
|
160
|
-
if (rawTail.length > 40) rawTail.shift();
|
|
161
|
-
return;
|
|
162
|
-
case 'astro-log': {
|
|
163
|
-
// A page file just deleted: Astro's list of page modules
|
|
164
|
-
// (.astro/content-modules.mjs) still points at it for a moment -
|
|
165
|
-
// "Failed to load url ... Does the file exist?" - until the restart
|
|
166
|
-
// the page-list watcher starts brings in a fresh list. Noise, not a
|
|
167
|
-
// problem in the site. Every other error still shows, and a
|
|
168
|
-
// preview that can't start still reports through 'fatal'.
|
|
169
|
-
if (event.level === 'error' && /content-modules\.mjs/.test(event.message) && /Does the file exist/.test(event.message)) return;
|
|
170
|
-
if (restartStarted !== null && event.level === 'error') return;
|
|
171
|
-
if (event.level === 'error') {
|
|
172
|
-
showError(describeError(stripAnsi(event.message), contentDir, { root: packageRoot }));
|
|
173
|
-
return;
|
|
174
|
-
}
|
|
175
|
-
const request = requestLog(event);
|
|
176
|
-
// A missing page is worth knowing about (a broken link, a typo in
|
|
177
|
-
// the navigation); a missing favicon or source map isn't.
|
|
178
|
-
if (request?.status === 404 && !/\.[a-z0-9]+$/i.test(request.url.split('?')[0])) {
|
|
179
|
-
once(`404\n${request.url}`, () => log.warn(`${color.bold(request.url)} No page at this address (404).`));
|
|
180
|
-
return;
|
|
181
|
-
}
|
|
182
|
-
const warning = authorWarning(event, contentDir);
|
|
183
|
-
if (warning) once(`warn\n${warning}`, () => log.warn(warning));
|
|
184
|
-
return;
|
|
185
|
-
}
|
|
186
|
-
}
|
|
187
|
-
};
|
|
188
|
-
|
|
189
|
-
// Pages added or removed while the preview runs: its page list is read
|
|
190
|
-
// when it starts, so it restarts - on the same port; the open tab
|
|
191
|
-
// reconnects and reloads by itself. Edits to pages and to writedocs.json
|
|
192
|
-
// don't need this (lib/config-reload-integration.js).
|
|
193
|
-
let child = null;
|
|
194
|
-
let restarting = false;
|
|
195
|
-
let restartPending = false;
|
|
196
|
-
const restartForPages = ({ added, removed }) => {
|
|
197
|
-
const what = [
|
|
198
|
-
...added.slice(0, 3).map((file) => `${file} added`),
|
|
199
|
-
...removed.slice(0, 3).map((file) => `${file} removed`),
|
|
200
|
-
];
|
|
201
|
-
const more = added.length + removed.length - what.length;
|
|
202
|
-
log.info(`${what.join(', ')}${more > 0 ? ` and ${more} more` : ''} - restarting the preview so the page list is current.`);
|
|
203
|
-
restarting = true;
|
|
204
|
-
ready = false;
|
|
205
|
-
restartStarted = Date.now();
|
|
206
|
-
starting = step('Restarting the preview');
|
|
207
|
-
child?.kill();
|
|
208
|
-
};
|
|
209
|
-
const pageWatch = watchPageList(contentDir, (change) => {
|
|
210
|
-
if (stopping || restarting) return;
|
|
211
|
-
// Still starting: restart once it's up, not halfway.
|
|
212
|
-
if (!ready) {
|
|
213
|
-
restartPending = change;
|
|
214
|
-
return;
|
|
215
|
-
}
|
|
216
|
-
restartForPages(change);
|
|
217
|
-
});
|
|
218
|
-
|
|
219
|
-
// Ctrl+C: stop the server quietly. (The child gets the same signal from
|
|
220
|
-
// the terminal; killing it here covers the cases where it doesn't.) A
|
|
221
|
-
// second Ctrl+C doesn't wait for it.
|
|
222
|
-
let stopping = false;
|
|
223
|
-
const stop = () => {
|
|
224
|
-
if (stopping) process.exit(130);
|
|
225
|
-
stopping = true;
|
|
226
|
-
pageWatch.close();
|
|
227
|
-
child?.kill();
|
|
228
|
-
};
|
|
229
|
-
process.on('SIGINT', stop);
|
|
230
|
-
process.on('SIGTERM', stop);
|
|
231
|
-
|
|
232
|
-
let code;
|
|
233
|
-
for (;;) {
|
|
234
|
-
fatal = null;
|
|
235
|
-
rawTail.length = 0;
|
|
236
|
-
const run = runAstro('dev', { packageRoot, contentDir, port: currentPort, onEvent });
|
|
237
|
-
child = run.child;
|
|
238
|
-
code = await run.exited;
|
|
239
|
-
if (stopping || !restarting) break;
|
|
240
|
-
restarting = false;
|
|
241
|
-
}
|
|
242
|
-
pageWatch.close();
|
|
243
|
-
if (stopping) {
|
|
244
|
-
if (ready) log.line(color.dim('Preview stopped.'));
|
|
245
|
-
return;
|
|
246
|
-
}
|
|
247
|
-
// The server never stops on its own - getting here is a failure.
|
|
248
|
-
if (!ready) starting.fail('Could not start the local preview');
|
|
249
|
-
else log.error('The local preview stopped unexpectedly.');
|
|
250
|
-
if (fatal) {
|
|
251
|
-
const problem = describeError(fatal, contentDir, { root: packageRoot });
|
|
252
|
-
log.line();
|
|
253
|
-
log.line(formatProblems([{ where: problem.where, message: problem.message }]));
|
|
254
|
-
if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
|
|
255
|
-
if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
|
|
256
|
-
} else if (rawTail.length) {
|
|
257
|
-
log.line();
|
|
258
|
-
log.line(color.dim(rawTail.join('\n')));
|
|
259
|
-
}
|
|
260
|
-
throw new CliExit(code || 1);
|
|
261
|
-
}
|
|
1
|
+
import { canonicalPath } from '../lib/canonical-path.js';
|
|
2
|
+
import { runAstro } from './run-astro.js';
|
|
3
|
+
import { preflightCheck, sameDriveCheck, writableInstallCheck } from './preflight.js';
|
|
4
|
+
import { generateApiPages } from './generate-api-pages.js';
|
|
5
|
+
import { log, step, duration, formatProblems, color, CliExit } from './output.js';
|
|
6
|
+
import { describeError, requestLog, authorWarning, verboseLine, stripAnsi } from './astro-output.js';
|
|
7
|
+
import { reportApiPages } from './api-pages-output.js';
|
|
8
|
+
import { runningPreview, writeLock, removeLock } from './dev-lock.js';
|
|
9
|
+
import { showUpdateNotice } from './update-check.js';
|
|
10
|
+
import { shouldOpenBrowser, openBrowser } from './open-browser.js';
|
|
11
|
+
import { watchPageList } from './page-list-watch.js';
|
|
12
|
+
import { readConfigText } from '../lib/config-file.js';
|
|
13
|
+
import { normalizeBasePath } from '../lib/base-path.js';
|
|
14
|
+
|
|
15
|
+
/** The preview's address for the server's own (`http://localhost:4321/`):
|
|
16
|
+
* under writedocs.json's `basePath` when it has one - the site is served
|
|
17
|
+
* at /docs/ then, and / is Astro's "not here" page. Read when the server
|
|
18
|
+
* is ready, so it follows the file. */
|
|
19
|
+
export function previewAddress(serverUrl, configText) {
|
|
20
|
+
let basePath = '';
|
|
21
|
+
try {
|
|
22
|
+
basePath = normalizeBasePath(JSON.parse(configText).basePath);
|
|
23
|
+
} catch {
|
|
24
|
+
// An unreadable writedocs.json stops the preview elsewhere.
|
|
25
|
+
}
|
|
26
|
+
return basePath ? new URL(`${basePath.slice(1)}/`, serverUrl).href : serverUrl;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// The same problem tends to arrive more than once in a row - Vite and
|
|
30
|
+
// Astro each log a failed page, and a page compiles for more than one
|
|
31
|
+
// environment. Within this window, a repeat is dropped.
|
|
32
|
+
const REPEAT_WINDOW_MS = 2000;
|
|
33
|
+
|
|
34
|
+
export async function runDev({ contentDir, packageRoot, port, verbose = false, open = true }) {
|
|
35
|
+
// One spelling of each folder throughout - see lib/canonical-path.js.
|
|
36
|
+
contentDir = canonicalPath(contentDir);
|
|
37
|
+
packageRoot = canonicalPath(packageRoot);
|
|
38
|
+
const started = Date.now();
|
|
39
|
+
preflightCheck(contentDir);
|
|
40
|
+
writableInstallCheck(packageRoot);
|
|
41
|
+
const other = runningPreview(packageRoot);
|
|
42
|
+
if (other) {
|
|
43
|
+
log.error(`Another writedocs preview is already running${other.url ? ` at ${other.url}` : ''}.`);
|
|
44
|
+
log.detail(
|
|
45
|
+
color.dim(
|
|
46
|
+
`It's serving ${other.contentDir}. Stop it first (Ctrl+C in its terminal) - two previews at once overwrite each other's pages.`
|
|
47
|
+
)
|
|
48
|
+
);
|
|
49
|
+
throw new CliExit(1);
|
|
50
|
+
}
|
|
51
|
+
writeLock(packageRoot, { contentDir, url: null });
|
|
52
|
+
process.on('exit', () => removeLock(packageRoot));
|
|
53
|
+
|
|
54
|
+
const api = await generateApiPages({ contentDir });
|
|
55
|
+
sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
|
|
56
|
+
reportApiPages(api);
|
|
57
|
+
api.warnings.forEach((message) => log.warn(message));
|
|
58
|
+
|
|
59
|
+
let starting = step('Starting local preview');
|
|
60
|
+
let ready = false;
|
|
61
|
+
let browserOpened = false;
|
|
62
|
+
// Restarting after pages were added or removed (see the watcher below):
|
|
63
|
+
// when that restart began, and the port to come back on.
|
|
64
|
+
let restartStarted = null;
|
|
65
|
+
let currentPort = port;
|
|
66
|
+
|
|
67
|
+
const lastShown = new Map();
|
|
68
|
+
const once = (key, print) => {
|
|
69
|
+
const now = Date.now();
|
|
70
|
+
if (now - (lastShown.get(key) ?? 0) < REPEAT_WINDOW_MS) return;
|
|
71
|
+
lastShown.set(key, now);
|
|
72
|
+
print();
|
|
73
|
+
};
|
|
74
|
+
const oneLine = (where, message) => (where ? `${color.bold(where)} ${message}` : message);
|
|
75
|
+
|
|
76
|
+
// A failed page is logged twice - Vite's error (message only) and then
|
|
77
|
+
// Astro's (message plus the file). Errors wait a moment so the two can
|
|
78
|
+
// be merged into one line that names the file.
|
|
79
|
+
// When the same page fails again, only the first report of it named the
|
|
80
|
+
// file: later ones point at the MDX compiler instead. The file each
|
|
81
|
+
// error was last seen in is remembered here, by the error itself.
|
|
82
|
+
const pendingErrors = new Map();
|
|
83
|
+
const knownWhere = new Map();
|
|
84
|
+
const showError = (problem) => {
|
|
85
|
+
if (problem.where) knownWhere.set(problem.key, problem.where);
|
|
86
|
+
else if (knownWhere.has(problem.key)) problem = { ...problem, where: knownWhere.get(problem.key) };
|
|
87
|
+
const existing = pendingErrors.get(problem.message);
|
|
88
|
+
if (existing) {
|
|
89
|
+
if (!existing.problem.where && problem.where) existing.problem = problem;
|
|
90
|
+
return;
|
|
91
|
+
}
|
|
92
|
+
const entry = { problem };
|
|
93
|
+
entry.timer = setTimeout(() => {
|
|
94
|
+
pendingErrors.delete(problem.message);
|
|
95
|
+
const { where, message, hint } = entry.problem;
|
|
96
|
+
once(`error\n${where}\n${message}`, () => {
|
|
97
|
+
log.error(oneLine(where, message));
|
|
98
|
+
if (hint) log.detail(color.dim(`Hint: ${hint}`));
|
|
99
|
+
});
|
|
100
|
+
}, 150);
|
|
101
|
+
pendingErrors.set(problem.message, entry);
|
|
102
|
+
};
|
|
103
|
+
|
|
104
|
+
let fatal = null;
|
|
105
|
+
const rawTail = [];
|
|
106
|
+
const onEvent = (event) => {
|
|
107
|
+
if (verbose) {
|
|
108
|
+
const line = verboseLine(event);
|
|
109
|
+
if (line !== null) log.line(color.dim(line));
|
|
110
|
+
}
|
|
111
|
+
switch (event.type) {
|
|
112
|
+
case 'ready': {
|
|
113
|
+
ready = true;
|
|
114
|
+
const [local] = event.urls?.local ?? [];
|
|
115
|
+
const wanted = Number(port ?? 4321);
|
|
116
|
+
const actual = local ? Number(new URL(local).port) : wanted;
|
|
117
|
+
const address = previewAddress(local ?? `http://localhost:${wanted}/`, readConfigText(contentDir));
|
|
118
|
+
writeLock(packageRoot, { contentDir, url: address });
|
|
119
|
+
currentPort = actual;
|
|
120
|
+
// Pages changed while it was starting: restart now that it's up.
|
|
121
|
+
if (restartPending) {
|
|
122
|
+
const change = restartPending;
|
|
123
|
+
restartPending = false;
|
|
124
|
+
setTimeout(() => restartForPages(change), 0);
|
|
125
|
+
}
|
|
126
|
+
// Back after a restart: one line - the open tab reloads by itself.
|
|
127
|
+
if (restartStarted !== null) {
|
|
128
|
+
starting.succeed(`Preview updated ${color.dim(`in ${duration(Date.now() - restartStarted)}`)}`);
|
|
129
|
+
restartStarted = null;
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
starting.succeed(`Preview ready ${color.dim(`in ${duration(Date.now() - started)}`)}`);
|
|
133
|
+
log.line();
|
|
134
|
+
log.line(` ${color.bold('Local:')} ${color.cyan(address)}`);
|
|
135
|
+
if (actual !== wanted) log.line(color.dim(` Port ${wanted} was in use, so the preview is on ${actual}.`));
|
|
136
|
+
log.line();
|
|
137
|
+
log.line(color.dim(' Edit any page and the preview updates. Press Ctrl+C to stop.'));
|
|
138
|
+
log.line();
|
|
139
|
+
// `dev` runs until Ctrl+C - the notice goes under the ready screen,
|
|
140
|
+
// not after the command like everywhere else.
|
|
141
|
+
showUpdateNotice();
|
|
142
|
+
// The preview in the browser, at the address it actually got - once,
|
|
143
|
+
// not again if Astro restarts the server.
|
|
144
|
+
if (!browserOpened && shouldOpenBrowser({ open })) {
|
|
145
|
+
browserOpened = true;
|
|
146
|
+
openBrowser(address);
|
|
147
|
+
}
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
150
|
+
case 'fatal':
|
|
151
|
+
fatal = event.error;
|
|
152
|
+
return;
|
|
153
|
+
case 'report':
|
|
154
|
+
// 'info' notes are about the build (sitemap and the like), not
|
|
155
|
+
// the preview.
|
|
156
|
+
if (event.level === 'warn') once(`warn\n${event.where}\n${event.message}`, () => log.warn(oneLine(event.where, event.message)));
|
|
157
|
+
return;
|
|
158
|
+
case 'raw':
|
|
159
|
+
rawTail.push(event.line);
|
|
160
|
+
if (rawTail.length > 40) rawTail.shift();
|
|
161
|
+
return;
|
|
162
|
+
case 'astro-log': {
|
|
163
|
+
// A page file just deleted: Astro's list of page modules
|
|
164
|
+
// (.astro/content-modules.mjs) still points at it for a moment -
|
|
165
|
+
// "Failed to load url ... Does the file exist?" - until the restart
|
|
166
|
+
// the page-list watcher starts brings in a fresh list. Noise, not a
|
|
167
|
+
// problem in the site. Every other error still shows, and a
|
|
168
|
+
// preview that can't start still reports through 'fatal'.
|
|
169
|
+
if (event.level === 'error' && /content-modules\.mjs/.test(event.message) && /Does the file exist/.test(event.message)) return;
|
|
170
|
+
if (restartStarted !== null && event.level === 'error') return;
|
|
171
|
+
if (event.level === 'error') {
|
|
172
|
+
showError(describeError(stripAnsi(event.message), contentDir, { root: packageRoot }));
|
|
173
|
+
return;
|
|
174
|
+
}
|
|
175
|
+
const request = requestLog(event);
|
|
176
|
+
// A missing page is worth knowing about (a broken link, a typo in
|
|
177
|
+
// the navigation); a missing favicon or source map isn't.
|
|
178
|
+
if (request?.status === 404 && !/\.[a-z0-9]+$/i.test(request.url.split('?')[0])) {
|
|
179
|
+
once(`404\n${request.url}`, () => log.warn(`${color.bold(request.url)} No page at this address (404).`));
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
const warning = authorWarning(event, contentDir, { root: packageRoot });
|
|
183
|
+
if (warning) once(`warn\n${warning}`, () => log.warn(warning));
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
};
|
|
188
|
+
|
|
189
|
+
// Pages added or removed while the preview runs: its page list is read
|
|
190
|
+
// when it starts, so it restarts - on the same port; the open tab
|
|
191
|
+
// reconnects and reloads by itself. Edits to pages and to writedocs.json
|
|
192
|
+
// don't need this (lib/config-reload-integration.js).
|
|
193
|
+
let child = null;
|
|
194
|
+
let restarting = false;
|
|
195
|
+
let restartPending = false;
|
|
196
|
+
const restartForPages = ({ added, removed }) => {
|
|
197
|
+
const what = [
|
|
198
|
+
...added.slice(0, 3).map((file) => `${file} added`),
|
|
199
|
+
...removed.slice(0, 3).map((file) => `${file} removed`),
|
|
200
|
+
];
|
|
201
|
+
const more = added.length + removed.length - what.length;
|
|
202
|
+
log.info(`${what.join(', ')}${more > 0 ? ` and ${more} more` : ''} - restarting the preview so the page list is current.`);
|
|
203
|
+
restarting = true;
|
|
204
|
+
ready = false;
|
|
205
|
+
restartStarted = Date.now();
|
|
206
|
+
starting = step('Restarting the preview');
|
|
207
|
+
child?.kill();
|
|
208
|
+
};
|
|
209
|
+
const pageWatch = watchPageList(contentDir, (change) => {
|
|
210
|
+
if (stopping || restarting) return;
|
|
211
|
+
// Still starting: restart once it's up, not halfway.
|
|
212
|
+
if (!ready) {
|
|
213
|
+
restartPending = change;
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
restartForPages(change);
|
|
217
|
+
});
|
|
218
|
+
|
|
219
|
+
// Ctrl+C: stop the server quietly. (The child gets the same signal from
|
|
220
|
+
// the terminal; killing it here covers the cases where it doesn't.) A
|
|
221
|
+
// second Ctrl+C doesn't wait for it.
|
|
222
|
+
let stopping = false;
|
|
223
|
+
const stop = () => {
|
|
224
|
+
if (stopping) process.exit(130);
|
|
225
|
+
stopping = true;
|
|
226
|
+
pageWatch.close();
|
|
227
|
+
child?.kill();
|
|
228
|
+
};
|
|
229
|
+
process.on('SIGINT', stop);
|
|
230
|
+
process.on('SIGTERM', stop);
|
|
231
|
+
|
|
232
|
+
let code;
|
|
233
|
+
for (;;) {
|
|
234
|
+
fatal = null;
|
|
235
|
+
rawTail.length = 0;
|
|
236
|
+
const run = runAstro('dev', { packageRoot, contentDir, port: currentPort, onEvent });
|
|
237
|
+
child = run.child;
|
|
238
|
+
code = await run.exited;
|
|
239
|
+
if (stopping || !restarting) break;
|
|
240
|
+
restarting = false;
|
|
241
|
+
}
|
|
242
|
+
pageWatch.close();
|
|
243
|
+
if (stopping) {
|
|
244
|
+
if (ready) log.line(color.dim('Preview stopped.'));
|
|
245
|
+
return;
|
|
246
|
+
}
|
|
247
|
+
// The server never stops on its own - getting here is a failure.
|
|
248
|
+
if (!ready) starting.fail('Could not start the local preview');
|
|
249
|
+
else log.error('The local preview stopped unexpectedly.');
|
|
250
|
+
if (fatal) {
|
|
251
|
+
const problem = describeError(fatal, contentDir, { root: packageRoot });
|
|
252
|
+
log.line();
|
|
253
|
+
log.line(formatProblems([{ where: problem.where, message: problem.message }]));
|
|
254
|
+
if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
|
|
255
|
+
if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
|
|
256
|
+
} else if (rawTail.length) {
|
|
257
|
+
log.line();
|
|
258
|
+
log.line(color.dim(rawTail.join('\n')));
|
|
259
|
+
}
|
|
260
|
+
throw new CliExit(code || 1);
|
|
261
|
+
}
|
package/src/scripts/search.ts
CHANGED
|
@@ -47,10 +47,14 @@ export function initSearch(root: ParentNode) {
|
|
|
47
47
|
// *non-literal* dynamic import specifier - a literal string like
|
|
48
48
|
// '/pagefind/pagefind.js' still gets resolved at transform time
|
|
49
49
|
// regardless of the comment, which crashes `writedocs dev` outright once
|
|
50
|
-
// this file exists in the template.
|
|
51
|
-
//
|
|
52
|
-
//
|
|
53
|
-
//
|
|
50
|
+
// this file exists in the template. A variable alone isn't enough either:
|
|
51
|
+
// rolldown 1.2.15 inlines it and folds `${__WD_BASE__}/pagefind/...` back
|
|
52
|
+
// into a literal, and the build fails with "Can't find
|
|
53
|
+
// /pagefind/pagefind.js". So the specifier is a URL made in the browser -
|
|
54
|
+
// the same address the path resolves to, but nothing a bundler can
|
|
55
|
+
// evaluate - deferring resolution to runtime, where the .catch() below
|
|
56
|
+
// handles "not built yet" gracefully instead. The path itself stays a
|
|
57
|
+
// literal in the bundle (scripts/base-path-dist.js checks it).
|
|
54
58
|
let pagefind: any = null;
|
|
55
59
|
let loadPromise: Promise<any> | null = null;
|
|
56
60
|
function ensurePagefind() {
|
|
@@ -61,7 +65,7 @@ export function initSearch(root: ParentNode) {
|
|
|
61
65
|
// Under writedocs.json's `basePath` ("" or "/docs", astro.config.mjs) -
|
|
62
66
|
// written into the strings so a site without one gets the same code.
|
|
63
67
|
const pagefindUrl = space ? `${__WD_BASE__}/pagefind-spaces/${encodeURIComponent(space)}/pagefind.js` : `${__WD_BASE__}/pagefind/pagefind.js`;
|
|
64
|
-
loadPromise = import(/* @vite-ignore */ pagefindUrl)
|
|
68
|
+
loadPromise = import(/* @vite-ignore */ new URL(pagefindUrl, location.href).href)
|
|
65
69
|
.then((mod: any) => {
|
|
66
70
|
pagefind = mod;
|
|
67
71
|
return mod.init();
|