@writedocs/generator 0.11.0 → 0.12.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.
- package/package.json +3 -1
- package/src/cli/astro-output.js +44 -11
- package/src/cli/build.js +28 -2
- package/src/cli/dev.js +261 -261
- package/src/cli/og-image-worker.js +20 -0
- package/src/cli/og-images.js +70 -0
- package/src/cli/run-astro.js +97 -93
- package/src/components/ApiReferencePanel.astro +1792 -1792
- package/src/layout/BaseLayout.astro +1 -3
- package/src/layout/components/MobileMenu.astro +9 -13
- package/src/layout/components/NavTree.astro +21 -6
- package/src/layout/components/Sidebar.astro +4 -4
- package/src/layout/styles/base.css +326 -327
- package/src/layout/styles/mobile-menu.css +285 -285
- package/src/lib/og-cards.js +33 -0
- package/src/lib/og-image.js +235 -168
- package/src/pages/og/[...slug].png.ts +63 -64
- package/src/scripts/mobile-menu.ts +80 -55
- package/src/scripts/search.ts +9 -5
- package/src/scripts/sidebar-scroll.ts +61 -65
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
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// One of og-images.js's threads: asks for a card, draws it into the site's
|
|
2
|
+
// og/ folder, asks for the next - until it's sent null.
|
|
3
|
+
import fs from 'node:fs';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { parentPort, workerData } from 'node:worker_threads';
|
|
6
|
+
import { ogImagePng, ogImagePath } from '../lib/og-image.js';
|
|
7
|
+
import { ogCardOptions } from '../lib/og-cards.js';
|
|
8
|
+
|
|
9
|
+
const { shared, siteDir } = workerData;
|
|
10
|
+
parentPort.on('message', async (card) => {
|
|
11
|
+
if (card === null) {
|
|
12
|
+
parentPort.close();
|
|
13
|
+
return;
|
|
14
|
+
}
|
|
15
|
+
const file = path.join(siteDir, ...ogImagePath(card.slug).split('/').filter(Boolean));
|
|
16
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
17
|
+
fs.writeFileSync(file, await ogImagePng(ogCardOptions(shared, card)));
|
|
18
|
+
parentPort.postMessage('drawn');
|
|
19
|
+
});
|
|
20
|
+
parentPort.postMessage('ready');
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// `writedocs build`'s link-preview cards (lib/og-cards.js), drawn after
|
|
2
|
+
// Astro, in worker threads - one per CPU this process may use
|
|
3
|
+
// (os.availableParallelism(), which follows a container's CPU limit), and
|
|
4
|
+
// at most MAX_THREADS (ogThreads()).
|
|
5
|
+
//
|
|
6
|
+
// Inside Astro they were one route among the others (src/pages/og/
|
|
7
|
+
// [...slug].png.ts), and Astro renders its routes one at a time on one core:
|
|
8
|
+
// on a site with 800 OpenAPI operations, the 800 cards were a third of the
|
|
9
|
+
// build. The route still decides nothing here - it writes the list of cards
|
|
10
|
+
// to the file it's given (WRITEDOCS_OG_CARDS_FILE, set by build.js) and
|
|
11
|
+
// renders none; each thread draws a card with the same ogImagePng() call the
|
|
12
|
+
// route makes in `writedocs dev`, so the files are the same, byte for byte.
|
|
13
|
+
//
|
|
14
|
+
// Each thread holds its own resvg, satori and fonts, ~110 MB: the threads
|
|
15
|
+
// start after Astro has exited, so that isn't on top of its peak.
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import os from 'node:os';
|
|
18
|
+
import { Worker } from 'node:worker_threads';
|
|
19
|
+
|
|
20
|
+
/** No more threads than this, however many CPUs a machine shows: a CI host
|
|
21
|
+
* can show dozens without a quota, and dozens of threads would be gigabytes.
|
|
22
|
+
* The platform's container has 4 CPUs; 800 cards take ~3.5 s there. */
|
|
23
|
+
export const MAX_THREADS = 4;
|
|
24
|
+
|
|
25
|
+
/** How many threads draw the cards, for `available` CPUs. */
|
|
26
|
+
export function ogThreads(available = os.availableParallelism()) {
|
|
27
|
+
return Math.max(1, Math.min(available, MAX_THREADS));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** Draws every card in `listFile` into `siteDir`/og/ - the site's root
|
|
31
|
+
* folder: build.js passes the staging folder, before it replaces dist/.
|
|
32
|
+
* Returns how many.
|
|
33
|
+
* The list is removed afterwards, drawn or not: it's only this build's, and
|
|
34
|
+
* it holds the logo, base64-encoded - no reason to leave it in the temp
|
|
35
|
+
* folder. */
|
|
36
|
+
export async function drawOgImages(listFile, siteDir, { threads = ogThreads() } = {}) {
|
|
37
|
+
try {
|
|
38
|
+
return await drawEach(listFile, siteDir, threads);
|
|
39
|
+
} finally {
|
|
40
|
+
fs.rmSync(listFile, { force: true });
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function drawEach(listFile, siteDir, threads) {
|
|
45
|
+
// No file: the route never ran - a site with no pages to give a card.
|
|
46
|
+
if (!fs.existsSync(listFile)) return 0;
|
|
47
|
+
const { cards, ...shared } = JSON.parse(fs.readFileSync(listFile, 'utf8'));
|
|
48
|
+
if (!cards.length) return 0;
|
|
49
|
+
let next = 0;
|
|
50
|
+
const workers = [];
|
|
51
|
+
try {
|
|
52
|
+
await Promise.all(
|
|
53
|
+
Array.from({ length: Math.min(threads, cards.length) }, () => {
|
|
54
|
+
const worker = new Worker(new URL('./og-image-worker.js', import.meta.url), { workerData: { shared, siteDir } });
|
|
55
|
+
workers.push(worker);
|
|
56
|
+
return new Promise((resolve, reject) => {
|
|
57
|
+
// A card at a time, to whichever thread is free: a long title or a
|
|
58
|
+
// logo makes one slower than another.
|
|
59
|
+
worker.on('message', () => worker.postMessage(next < cards.length ? cards[next++] : null));
|
|
60
|
+
worker.on('error', reject);
|
|
61
|
+
worker.on('exit', (code) => (code === 0 ? resolve() : reject(new Error(`A thread drawing the link previews stopped (exit code ${code}).`))));
|
|
62
|
+
});
|
|
63
|
+
})
|
|
64
|
+
);
|
|
65
|
+
} finally {
|
|
66
|
+
// One thread failing stops the others.
|
|
67
|
+
await Promise.all(workers.map((worker) => worker.terminate()));
|
|
68
|
+
}
|
|
69
|
+
return cards.length;
|
|
70
|
+
}
|