@writedocs/generator 0.11.1 → 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@writedocs/generator",
3
- "version": "0.11.1",
3
+ "version": "0.12.0",
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": {
package/src/cli/build.js CHANGED
@@ -1,177 +1,203 @@
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
- }
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, writedocsTempDir } from '../lib/writedocs-temp-dir.js';
14
+ import { drawOgImages } from './og-images.js';
15
+ import { normalizeBasePath } from '../lib/base-path.js';
16
+ import { siteDirFor, moveRootFiles } from './base-path-layout.js';
17
+ import { log, step, plural, duration, displayPath, formatProblems, color, CliExit } from './output.js';
18
+ import { describeError, builtRoute, authorWarning, verboseLine } from './astro-output.js';
19
+ import { reportApiPages } from './api-pages-output.js';
20
+
21
+ export async function runBuild({ contentDir, packageRoot, verbose = false }) {
22
+ // One spelling of each folder throughout - see lib/canonical-path.js.
23
+ contentDir = canonicalPath(contentDir);
24
+ packageRoot = canonicalPath(packageRoot);
25
+ const started = Date.now();
26
+ preflightCheck(contentDir);
27
+ writableInstallCheck(packageRoot);
28
+
29
+ // Collected while building, printed together at the end - a warning in
30
+ // the middle of a spinner is easy to miss.
31
+ const warnings = [];
32
+ const notes = [];
33
+ const seen = new Set();
34
+ const addWarning = (where, message) => {
35
+ const key = `${where ?? ''}\n${message}`;
36
+ if (seen.has(key)) return;
37
+ seen.add(key);
38
+ warnings.push({ where, message });
39
+ };
40
+
41
+ const api = await generateApiPages({ contentDir });
42
+ sameDriveCheck(contentDir, packageRoot, { generatedPages: api.groups.length > 0 });
43
+ reportApiPages(api);
44
+ api.warnings.forEach((message) => addWarning(null, message));
45
+
46
+ const building = step('Building pages');
47
+ const buildStarted = Date.now();
48
+ let pages = 0;
49
+ let fatal = null;
50
+ const rawTail = [];
51
+ // The link-preview cards: Astro's og route only writes their list here,
52
+ // and this process draws them after Astro, in parallel (og-images.js).
53
+ // Removed first, so a list from an earlier build is never drawn.
54
+ const ogCardsFile = path.join(writedocsTempDir(contentDir), 'og-cards.json');
55
+ fs.mkdirSync(path.dirname(ogCardsFile), { recursive: true });
56
+ fs.rmSync(ogCardsFile, { force: true });
57
+ const { exited } = runAstro('build', {
58
+ packageRoot,
59
+ contentDir,
60
+ env: { WRITEDOCS_OG_CARDS_FILE: ogCardsFile },
61
+ onEvent(event) {
62
+ if (verbose) {
63
+ const line = verboseLine(event);
64
+ if (line !== null) log.line(color.dim(line));
65
+ }
66
+ if (event.type === 'fatal') {
67
+ fatal = event.error;
68
+ return;
69
+ }
70
+ if (event.type === 'report') {
71
+ if (event.level === 'warn') addWarning(event.where, event.message);
72
+ else if (event.level === 'info' && !notes.includes(event.message)) notes.push(event.message);
73
+ return;
74
+ }
75
+ if (event.type === 'raw') {
76
+ rawTail.push(event.line);
77
+ if (rawTail.length > 40) rawTail.shift();
78
+ return;
79
+ }
80
+ const route = builtRoute(event);
81
+ if (route) {
82
+ if (route.endsWith('.html')) pages += 1;
83
+ building.update(`Building pages ${color.dim(`(${pages})`)}`);
84
+ return;
85
+ }
86
+ const warning = authorWarning(event, contentDir, { root: packageRoot });
87
+ if (warning) addWarning(null, warning);
88
+ },
89
+ });
90
+ const code = await exited;
91
+
92
+ if (fatal || code !== 0) {
93
+ building.fail('Build failed');
94
+ if (fatal) {
95
+ const problem = describeError(fatal, contentDir, { root: packageRoot });
96
+ log.line();
97
+ log.line(formatProblems([{ where: problem.where, message: problem.message }]));
98
+ if (problem.hint) log.line(`\n${color.dim(` Hint: ${problem.hint}`)}`);
99
+ if (verbose && fatal.stack) log.line(`\n${color.dim(fatal.stack)}`);
100
+ } else if (rawTail.length) {
101
+ // No structured error (the worker itself crashed) - show what it printed.
102
+ log.line();
103
+ log.line(color.dim(rawTail.join('\n')));
104
+ }
105
+ log.line();
106
+ log.line(color.dim('Run "writedocs validate" to list every problem in the project at once.'));
107
+ throw new CliExit(1);
108
+ }
109
+ building.succeed(`Built ${plural(pages, 'page')} ${color.dim(`in ${duration(Date.now() - buildStarted)}`)}`);
110
+
111
+ const distDir = path.join(contentDir, 'dist');
112
+ // writedocs.json has been through the build's own validation by now.
113
+ const siteConfig = JSON.parse(readConfigText(contentDir));
114
+ // With a `basePath` ("/docs"), the site goes to dist/docs/ and only the
115
+ // host's own files stay at the root of dist/ - see base-path-layout.js.
116
+ // Without one, siteDir is distDir, and every step below is what it was.
117
+ const basePath = normalizeBasePath(siteConfig.basePath);
118
+ const siteDir = siteDirFor(distDir, basePath);
119
+ // Astro just wrote its actual output to writedocsBuildStagingDir()
120
+ // (astro.config.mjs's own `outDir`), not distDir directly - see that
121
+ // function's own comment (writedocs-temp-dir.js) for why. fs.cpSync
122
+ // (unlike the fs.rename() Astro uses internally to get *into* that
123
+ // staging dir in the first place) copies across filesystem boundaries
124
+ // without issue, so this is the one step that actually needs to bridge
125
+ // packageRoot and contentDir potentially living on different devices.
126
+ // distDir is cleared first so a rebuild doesn't leave a stale file
127
+ // behind from a previous build that the new one no longer produces -
128
+ // the same "the output directory reflects exactly this build, nothing
129
+ // older" expectation `astro build` itself already guarantees when
130
+ // writing directly into outDir.
131
+ const stagingDir = writedocsBuildStagingDir(packageRoot, contentDir);
132
+ // The cards Astro's route listed, into the staging folder's og/ - the
133
+ // same files the route would have made, one thread per CPU (at most 4).
134
+ // Drawn here, before the staging folder replaces dist/: when drawing
135
+ // fails, the build stops with dist/ as it was - no dist/ at all, or the
136
+ // last good build's - the same as when Astro itself fails. Drawn after the
137
+ // copy, a failure left a dist/ with the new pages and none of their cards.
138
+ const drawing = step('Drawing link previews');
139
+ const drawStarted = Date.now();
140
+ try {
141
+ const drawn = await drawOgImages(ogCardsFile, stagingDir);
142
+ if (drawn) drawing.succeed(`Drew ${plural(drawn, 'preview image')} ${color.dim(`in ${duration(Date.now() - drawStarted)}`)}`);
143
+ else drawing.stop();
144
+ } catch (err) {
145
+ drawing.fail('Drawing the link previews failed');
146
+ log.line();
147
+ log.line(color.dim(err.message));
148
+ throw new CliExit(1);
149
+ }
150
+ fs.rmSync(distDir, { recursive: true, force: true });
151
+ fs.cpSync(stagingDir, siteDir, { recursive: true });
152
+ fs.rmSync(stagingDir, { recursive: true, force: true });
153
+ moveRootFiles(siteDir, distDir);
154
+ // Every page writedocs renders links the site's stylesheet. Builds have
155
+ // come out without it on every page while reporting success (the package
156
+ // folder spelled `c:`, fixed in lib/canonical-path.js) - so it's checked
157
+ // here, and a build like that stops instead of being deployed unstyled.
158
+ const unstyled = pagesWithoutStyles(distDir, { basePath });
159
+ if (unstyled.length) {
160
+ log.error(`The build produced ${plural(unstyled.length, 'page')} without the site's styles - for example ${unstyled[0]}.`);
161
+ 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.'));
162
+ throw new CliExit(1);
163
+ }
164
+ // Astro's own writedocs.json `redirects` + the automatic "/" redirect only
165
+ // ever produce client-side meta-refresh pages (see write-redirects-file.js)
166
+ // - this turns those into real instant edge redirects on hosts that read
167
+ // a `_redirects` file (Cloudflare Pages, Netlify), purely additively.
168
+ writeRedirectsFile(siteDir, contentDir, { outDir: distDir, basePath });
169
+ // Every other host follows Astro's redirect pages - rewritten so the
170
+ // reader never sees one (rewrite-redirect-pages.js).
171
+ rewriteRedirectPages(siteDir, { background: siteConfig.styles?.background?.colors });
172
+ // The site's MCP server at /mcp: mcp-index.json is already in dist/ (an
173
+ // Astro route); this adds the Cloudflare _worker.js that serves it - see
174
+ // write-mcp-files.js for every host.
175
+ const { version: writedocsVersion } = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf-8'));
176
+ const mcp = writeMcpFiles(distDir, contentDir, writedocsVersion, { siteDir, basePath });
177
+ if (mcp.written.length) notes.push(`MCP server at ${basePath}/mcp - dist/_worker.js runs it on Cloudflare; mcp-index.json holds the pages.`);
178
+ if (mcp.skipped) addWarning(null, `No _worker.js for the MCP server: ${mcp.skipped}.`);
179
+
180
+ const indexing = step('Indexing search');
181
+ try {
182
+ await runPagefind(siteDir, { packageRoot });
183
+ } catch (err) {
184
+ indexing.fail('Search indexing failed');
185
+ log.line();
186
+ log.line(color.dim(err.message));
187
+ throw new CliExit(1);
188
+ }
189
+ indexing.succeed('Indexed search');
190
+
191
+ if (warnings.length) {
192
+ log.line();
193
+ log.warn(plural(warnings.length, 'warning'));
194
+ log.line();
195
+ log.line(formatProblems(warnings));
196
+ }
197
+ if (notes.length) {
198
+ log.line();
199
+ notes.forEach((note) => log.info(note));
200
+ }
201
+ log.line();
202
+ log.success(`Done in ${duration(Date.now() - started)} ${color.dim('-')} site written to ${color.bold(displayPath(distDir))}`);
203
+ }
@@ -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
+ }