@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.
@@ -1,168 +1,235 @@
1
- // The picture a link to a page shows when it's shared - generated for every
2
- // page that has none of its own: 1200x630, with the site's logo, the page's
3
- // title and description, and a band of the site's primary color.
4
- //
5
- // Two steps, both without a browser or a system font:
6
- // 1. satori lays the card out (flexbox, text wrapping) and draws every
7
- // letter as a path, from the Inter files in src/assets/fonts/. Because
8
- // the letters are paths, the result looks the same on any machine - a
9
- // build server has no fonts installed to rely on.
10
- // 2. resvg (WebAssembly, so no binary per platform) turns that SVG into a
11
- // PNG. Social networks and chat apps don't show SVG previews.
12
- //
13
- // src/pages/og/[...slug].png.ts serves the result at /og/<page>.png;
14
- // [...slug].astro points a page's og:image there when it has no
15
- // `seo.ogImage`.
16
- //
17
- // Plain JavaScript, for scripts/og-image.test.js.
18
- import fs from 'node:fs';
19
- import path from 'node:path';
20
- import { createRequire } from 'node:module';
21
- import { fileURLToPath } from 'node:url';
22
- import { imageSize } from './image-size.js';
23
- import { plainLine } from './meta-description.js';
24
-
25
- export const OG_WIDTH = 1200;
26
- export const OG_HEIGHT = 630;
27
-
28
- /** Whether a page gets a generated picture: it has none of its own (`seo`
29
- * is the site's with the page's merged over it), search engines index it,
30
- * and it's a page - not a link to somewhere else (`url`) - on a site that
31
- * hasn't turned generated pictures off. */
32
- export function wantsGeneratedCard(seo, data = {}, siteSeo = {}) {
33
- // writedocs.json `"seo": { "generatedOgImage": false }` turns them off
34
- // for the whole site - `siteSeo` is the site's own `seo`, since the merged
35
- // one (mergeSeo()) only carries the fields a page can set.
36
- if (siteSeo?.generatedOgImage === false) return false;
37
- return !seo?.ogImage && !seo?.noindex && !data.url;
38
- }
39
-
40
- /** The address of a page's generated picture: /og/<page id>.png. */
41
- export function ogImagePath(pageId) {
42
- return `/og/${pageId}.png`;
43
- }
44
-
45
- // The font files, by the package's own folder when the CLI says where it is
46
- // (WRITEDOCS_PACKAGE_ROOT, src/cli/run-astro.js): inside a build this module
47
- // is part of a bundle somewhere else, and a path from its own location
48
- // would miss them.
49
- const fontsDir = process.env.WRITEDOCS_PACKAGE_ROOT
50
- ? path.join(process.env.WRITEDOCS_PACKAGE_ROOT, 'src', 'assets', 'fonts')
51
- : path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'fonts');
52
- const fontFile = (name) => fs.readFileSync(path.join(fontsDir, name));
53
-
54
- let fonts = null;
55
- /** Inter, regular and semibold. The extended-Latin files go under a name of
56
- * their own, second in the card's font-family: satori takes a letter from
57
- * the first family that has it, and only one file per family and weight. */
58
- function loadFonts() {
59
- fonts ??= [
60
- { name: 'Inter', weight: 400, style: 'normal', data: fontFile('inter-latin-400-normal.woff') },
61
- { name: 'Inter', weight: 600, style: 'normal', data: fontFile('inter-latin-600-normal.woff') },
62
- { name: 'Inter Ext', weight: 400, style: 'normal', data: fontFile('inter-latin-ext-400-normal.woff') },
63
- { name: 'Inter Ext', weight: 600, style: 'normal', data: fontFile('inter-latin-ext-600-normal.woff') },
64
- ];
65
- return fonts;
66
- }
67
-
68
- // The two renderers are loaded when the first card is drawn, not with this
69
- // module: every page imports it for wantsGeneratedCard(), and most builds of
70
- // a page never draw anything.
71
- let renderer = null;
72
- function loadRenderer() {
73
- renderer ??= (async () => {
74
- const [{ default: satori }, resvg] = await Promise.all([import('satori'), import('@resvg/resvg-wasm')]);
75
- // Once per process: a second initWasm() throws.
76
- await resvg.initWasm(fs.readFileSync(createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm')));
77
- return { satori, Resvg: resvg.Resvg };
78
- })();
79
- return renderer;
80
- }
81
-
82
- const MIME = { '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
83
-
84
- /** The logo file as something the card can draw: a data URI and the size to
85
- * draw it at - `height` tall, as wide as its proportions say, and no wider
86
- * than `maxWidth`. Null for a file that can't be read or measured. */
87
- export function logoForCard(file, height = 64, maxWidth = 520) {
88
- if (!file) return null;
89
- const type = MIME[path.extname(file).toLowerCase()];
90
- const size = type && imageSize(file);
91
- if (!size) return null;
92
- let width = (size.width / size.height) * height;
93
- let drawn = height;
94
- if (width > maxWidth) {
95
- drawn = (maxWidth / width) * height;
96
- width = maxWidth;
97
- }
98
- try {
99
- return { src: `data:${type};base64,${fs.readFileSync(file).toString('base64')}`, width: Math.round(width), height: Math.round(drawn) };
100
- } catch {
101
- return null;
102
- }
103
- }
104
-
105
- const cut = (value, max) => (value.length > max ? `${value.slice(0, max - 1).replace(/\s+\S*$/, '')}…` : value);
106
- const el = (type, style, children, props = {}) => ({ type, props: { style, children, ...props } });
107
-
108
- /** The card as satori's element tree. A long title gets smaller letters
109
- * rather than being cut short; the description is clamped to three lines. */
110
- export function ogCard({ title, description, siteName, primary = '#0029F5', logo = null }) {
111
- const heading = cut(plainLine(title), 110);
112
- const text = description ? cut(plainLine(description), 200) : '';
113
- const titleSize = heading.length > 70 ? 52 : heading.length > 40 ? 62 : 72;
114
- return el(
115
- 'div',
116
- { width: OG_WIDTH, height: OG_HEIGHT, display: 'flex', flexDirection: 'column', backgroundColor: '#ffffff', fontFamily: 'Inter, Inter Ext', color: '#18191d' },
117
- [
118
- el(
119
- 'div',
120
- { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: '72px 80px 0 80px' },
121
- [
122
- // The logo - or, for a site without one (or with one on another
123
- // server, which a build shouldn't wait for), its name.
124
- logo
125
- ? el('img', { width: logo.width, height: logo.height }, undefined, { src: logo.src, width: logo.width, height: logo.height })
126
- : el('div', { display: 'flex', fontSize: 34, fontWeight: 600, color: primary }, siteName),
127
- el(
128
- 'div',
129
- { display: 'flex', flexDirection: 'column', flexGrow: 1, justifyContent: 'center' },
130
- [
131
- el('div', { display: 'flex', fontSize: titleSize, fontWeight: 600, lineHeight: 1.12, letterSpacing: '-0.02em' }, heading),
132
- text ? el('div', { display: 'flex', marginTop: 28, fontSize: 30, lineHeight: 1.4, color: '#404045', lineClamp: 3 }, text) : null,
133
- ].filter(Boolean)
134
- ),
135
- ]
136
- ),
137
- el(
138
- 'div',
139
- { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 80px 44px 80px', fontSize: 24, color: '#6b6b76' },
140
- // With a logo, the name says whose docs these are; without one the
141
- // name is already at the top.
142
- [el('div', { display: 'flex' }, logo ? siteName : '')]
143
- ),
144
- el('div', { display: 'flex', width: OG_WIDTH, height: 14, backgroundColor: primary }, undefined),
145
- ]
146
- );
147
- }
148
-
149
- /** The card as SVG. */
150
- export async function ogImageSvg(options) {
151
- const { satori } = await loadRenderer();
152
- return satori(ogCard(options), { width: OG_WIDTH, height: OG_HEIGHT, fonts: loadFonts() });
153
- }
154
-
155
- /** The card as a PNG: a Buffer, 1200x630. */
156
- export async function ogImagePng(options) {
157
- const svg = await ogImageSvg(options);
158
- const { Resvg } = await loadRenderer();
159
- const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } });
160
- const rendered = resvg.render();
161
- const png = Buffer.from(rendered.asPng());
162
- // Both live in the WebAssembly memory, which nothing collects: freeing
163
- // only the image left the parsed SVG of every card there until the build
164
- // ended, and past ~800 cards each one took three times as long.
165
- rendered.free?.();
166
- resvg.free?.();
167
- return png;
168
- }
1
+ // The picture a link to a page shows when it's shared - generated for every
2
+ // page that has none of its own: 1200x630, with the site's logo, the page's
3
+ // title and description, and a band of the site's primary color.
4
+ //
5
+ // Two steps, both without a browser or a system font:
6
+ // 1. satori lays the card out (flexbox, text wrapping) and draws every
7
+ // letter as a path, from the Inter files in src/assets/fonts/. Because
8
+ // the letters are paths, the result looks the same on any machine - a
9
+ // build server has no fonts installed to rely on.
10
+ // 2. resvg (WebAssembly, so no binary per platform) turns that SVG into
11
+ // pixels, and encodePng() below writes them as a PNG with Node's own
12
+ // zlib. Social networks and chat apps don't show SVG previews.
13
+ //
14
+ // src/pages/og/[...slug].png.ts serves the result at /og/<page>.png;
15
+ // [...slug].astro points a page's og:image there when it has no
16
+ // `seo.ogImage`.
17
+ //
18
+ // Plain JavaScript, for scripts/og-image.test.js.
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+ import zlib from 'node:zlib';
22
+ import { createRequire } from 'node:module';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { imageSize } from './image-size.js';
25
+ import { plainLine } from './meta-description.js';
26
+
27
+ export const OG_WIDTH = 1200;
28
+ export const OG_HEIGHT = 630;
29
+
30
+ /** Whether a page gets a generated picture: it has none of its own (`seo`
31
+ * is the site's with the page's merged over it), search engines index it,
32
+ * and it's a page - not a link to somewhere else (`url`) - on a site that
33
+ * hasn't turned generated pictures off. */
34
+ export function wantsGeneratedCard(seo, data = {}, siteSeo = {}) {
35
+ // writedocs.json `"seo": { "generatedOgImage": false }` turns them off
36
+ // for the whole site - `siteSeo` is the site's own `seo`, since the merged
37
+ // one (mergeSeo()) only carries the fields a page can set.
38
+ if (siteSeo?.generatedOgImage === false) return false;
39
+ return !seo?.ogImage && !seo?.noindex && !data.url;
40
+ }
41
+
42
+ /** The address of a page's generated picture: /og/<page id>.png. */
43
+ export function ogImagePath(pageId) {
44
+ return `/og/${pageId}.png`;
45
+ }
46
+
47
+ // The font files, by the package's own folder when the CLI says where it is
48
+ // (WRITEDOCS_PACKAGE_ROOT, src/cli/run-astro.js): inside a build this module
49
+ // is part of a bundle somewhere else, and a path from its own location
50
+ // would miss them.
51
+ const fontsDir = process.env.WRITEDOCS_PACKAGE_ROOT
52
+ ? path.join(process.env.WRITEDOCS_PACKAGE_ROOT, 'src', 'assets', 'fonts')
53
+ : path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'assets', 'fonts');
54
+ const fontFile = (name) => fs.readFileSync(path.join(fontsDir, name));
55
+
56
+ let fonts = null;
57
+ /** Inter, regular and semibold. The extended-Latin files go under a name of
58
+ * their own, second in the card's font-family: satori takes a letter from
59
+ * the first family that has it, and only one file per family and weight. */
60
+ function loadFonts() {
61
+ fonts ??= [
62
+ { name: 'Inter', weight: 400, style: 'normal', data: fontFile('inter-latin-400-normal.woff') },
63
+ { name: 'Inter', weight: 600, style: 'normal', data: fontFile('inter-latin-600-normal.woff') },
64
+ { name: 'Inter Ext', weight: 400, style: 'normal', data: fontFile('inter-latin-ext-400-normal.woff') },
65
+ { name: 'Inter Ext', weight: 600, style: 'normal', data: fontFile('inter-latin-ext-600-normal.woff') },
66
+ ];
67
+ return fonts;
68
+ }
69
+
70
+ // The two renderers are loaded when the first card is drawn, not with this
71
+ // module: every page imports it for wantsGeneratedCard(), and most builds of
72
+ // a page never draw anything.
73
+ let renderer = null;
74
+ function loadRenderer() {
75
+ renderer ??= (async () => {
76
+ const [{ default: satori }, resvg] = await Promise.all([import('satori'), import('@resvg/resvg-wasm')]);
77
+ // Once per process: a second initWasm() throws.
78
+ await resvg.initWasm(fs.readFileSync(createRequire(import.meta.url).resolve('@resvg/resvg-wasm/index_bg.wasm')));
79
+ return { satori, Resvg: resvg.Resvg };
80
+ })();
81
+ return renderer;
82
+ }
83
+
84
+ const MIME = { '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.gif': 'image/gif', '.webp': 'image/webp' };
85
+
86
+ /** The logo file as something the card can draw: a data URI and the size to
87
+ * draw it at - `height` tall, as wide as its proportions say, and no wider
88
+ * than `maxWidth`. Null for a file that can't be read or measured. */
89
+ export function logoForCard(file, height = 64, maxWidth = 520) {
90
+ if (!file) return null;
91
+ const type = MIME[path.extname(file).toLowerCase()];
92
+ const size = type && imageSize(file);
93
+ if (!size) return null;
94
+ let width = (size.width / size.height) * height;
95
+ let drawn = height;
96
+ if (width > maxWidth) {
97
+ drawn = (maxWidth / width) * height;
98
+ width = maxWidth;
99
+ }
100
+ try {
101
+ return { src: `data:${type};base64,${fs.readFileSync(file).toString('base64')}`, width: Math.round(width), height: Math.round(drawn) };
102
+ } catch {
103
+ return null;
104
+ }
105
+ }
106
+
107
+ const cut = (value, max) => (value.length > max ? `${value.slice(0, max - 1).replace(/\s+\S*$/, '')}…` : value);
108
+ const el = (type, style, children, props = {}) => ({ type, props: { style, children, ...props } });
109
+
110
+ /** The card as satori's element tree. A long title gets smaller letters
111
+ * rather than being cut short; the description is clamped to three lines. */
112
+ export function ogCard({ title, description, siteName, primary = '#0029F5', logo = null }) {
113
+ const heading = cut(plainLine(title), 110);
114
+ const text = description ? cut(plainLine(description), 200) : '';
115
+ const titleSize = heading.length > 70 ? 52 : heading.length > 40 ? 62 : 72;
116
+ return el(
117
+ 'div',
118
+ { width: OG_WIDTH, height: OG_HEIGHT, display: 'flex', flexDirection: 'column', backgroundColor: '#ffffff', fontFamily: 'Inter, Inter Ext', color: '#18191d' },
119
+ [
120
+ el(
121
+ 'div',
122
+ { display: 'flex', flexDirection: 'column', flexGrow: 1, padding: '72px 80px 0 80px' },
123
+ [
124
+ // The logo - or, for a site without one (or with one on another
125
+ // server, which a build shouldn't wait for), its name.
126
+ logo
127
+ ? el('img', { width: logo.width, height: logo.height }, undefined, { src: logo.src, width: logo.width, height: logo.height })
128
+ : el('div', { display: 'flex', fontSize: 34, fontWeight: 600, color: primary }, siteName),
129
+ el(
130
+ 'div',
131
+ { display: 'flex', flexDirection: 'column', flexGrow: 1, justifyContent: 'center' },
132
+ [
133
+ el('div', { display: 'flex', fontSize: titleSize, fontWeight: 600, lineHeight: 1.12, letterSpacing: '-0.02em' }, heading),
134
+ text ? el('div', { display: 'flex', marginTop: 28, fontSize: 30, lineHeight: 1.4, color: '#404045', lineClamp: 3 }, text) : null,
135
+ ].filter(Boolean)
136
+ ),
137
+ ]
138
+ ),
139
+ el(
140
+ 'div',
141
+ { display: 'flex', alignItems: 'center', justifyContent: 'space-between', padding: '0 80px 44px 80px', fontSize: 24, color: '#6b6b76' },
142
+ // With a logo, the name says whose docs these are; without one the
143
+ // name is already at the top.
144
+ [el('div', { display: 'flex' }, logo ? siteName : '')]
145
+ ),
146
+ el('div', { display: 'flex', width: OG_WIDTH, height: 14, backgroundColor: primary }, undefined),
147
+ ]
148
+ );
149
+ }
150
+
151
+ /** The card as SVG. */
152
+ export async function ogImageSvg(options) {
153
+ const { satori } = await loadRenderer();
154
+ return satori(ogCard(options), { width: OG_WIDTH, height: OG_HEIGHT, fonts: loadFonts() });
155
+ }
156
+
157
+ // The PNG is written here, not by resvg's own asPng(): that one compresses
158
+ // in WebAssembly, and it was three quarters of the time a card took (12-25
159
+ // ms of it, against ~1.6 ms for Node's zlib, which is native). The pixels
160
+ // are the same - only the compressed bytes differ.
161
+ //
162
+ // The CRC of each chunk comes from this table rather than zlib.crc32(),
163
+ // which only exists from Node 22.2 / 20.15 - nothing here raises the Node
164
+ // version `engines` asks for.
165
+ const CRC_TABLE = new Int32Array(256);
166
+ for (let n = 0; n < 256; n++) {
167
+ let c = n;
168
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
169
+ CRC_TABLE[n] = c;
170
+ }
171
+ function crc32(bytes) {
172
+ let c = -1;
173
+ for (let i = 0; i < bytes.length; i++) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
174
+ return (c ^ -1) >>> 0;
175
+ }
176
+ function pngChunk(type, data) {
177
+ const chunk = Buffer.alloc(data.length + 12);
178
+ chunk.writeUInt32BE(data.length, 0);
179
+ chunk.write(type, 4, 'latin1');
180
+ data.copy(chunk, 8);
181
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, 8 + data.length)), 8 + data.length);
182
+ return chunk;
183
+ }
184
+
185
+ /** RGBA pixels (8 bits each, `width * height * 4` bytes) as a PNG: RGBA,
186
+ * no interlacing, filter 0 on every row, deflated at level 3 - level 6
187
+ * makes a file a third smaller but takes four times as long, and a card is
188
+ * ~30 KB either way. */
189
+ export function encodePng(width, height, rgba) {
190
+ const header = Buffer.alloc(13);
191
+ header.writeUInt32BE(width, 0);
192
+ header.writeUInt32BE(height, 4);
193
+ header[8] = 8; // bits per channel
194
+ header[9] = 6; // RGBA
195
+ const stride = width * 4;
196
+ const rows = Buffer.alloc((stride + 1) * height);
197
+ for (let y = 0; y < height; y++) {
198
+ // Each row starts with its filter type: 0, none.
199
+ rows.set(rgba.subarray(y * stride, (y + 1) * stride), y * (stride + 1) + 1);
200
+ }
201
+ return Buffer.concat([
202
+ Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
203
+ pngChunk('IHDR', header),
204
+ pngChunk('IDAT', zlib.deflateSync(rows, { level: 3 })),
205
+ pngChunk('IEND', Buffer.alloc(0)),
206
+ ]);
207
+ }
208
+
209
+ /** Whether every pixel is opaque. resvg's pixels are premultiplied by their
210
+ * alpha, and a PNG's aren't: only for opaque pixels are they the same
211
+ * numbers. A card always is - its background is white from edge to edge. */
212
+ function opaque(rgba) {
213
+ for (let i = 3; i < rgba.length; i += 4) if (rgba[i] !== 255) return false;
214
+ return true;
215
+ }
216
+
217
+ /** The card as a PNG: a Buffer, 1200x630. `resvgEncoder` writes it with
218
+ * resvg's own encoder instead, as before encodePng() - for the tests, which
219
+ * check that both give the same picture. */
220
+ export async function ogImagePng(options, { resvgEncoder = false } = {}) {
221
+ const svg = await ogImageSvg(options);
222
+ const { Resvg } = await loadRenderer();
223
+ const resvg = new Resvg(svg, { fitTo: { mode: 'width', value: OG_WIDTH } });
224
+ const rendered = resvg.render();
225
+ const pixels = resvgEncoder ? null : rendered.pixels;
226
+ // A picture with any see-through pixel (which a card never has) goes
227
+ // through resvg's encoder, which converts them.
228
+ const png = pixels && opaque(pixels) ? encodePng(rendered.width, rendered.height, pixels) : Buffer.from(rendered.asPng());
229
+ // Both live in the WebAssembly memory, which nothing collects: freeing
230
+ // only the image left the parsed SVG of every card there until the build
231
+ // ended, and past ~800 cards each one took three times as long.
232
+ rendered.free?.();
233
+ resvg.free?.();
234
+ return png;
235
+ }
@@ -1,64 +1,63 @@
1
- import { getCollection, type CollectionEntry } from 'astro:content';
2
- import fs from 'node:fs';
3
- import path from 'node:path';
4
- import type { APIRoute } from 'astro';
5
- import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
6
- import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
7
- import { ogImagePng, logoForCard, wantsGeneratedCard } from '../../lib/og-image.js';
8
- import { imageFileFor } from '../../lib/image-size.js';
9
-
10
- // /og/<page>.png - the picture a link to a page shows when it's shared, for
11
- // every page with no `seo.ogImage` of its own: the site's logo, the page's
12
- // title and description, the site's primary color (lib/og-image.js).
13
- // [...slug].astro points the page's og:image here under the same condition
14
- // (wantsGeneratedCard()), so a card is only built for a page that uses it -
15
- // a site with `seo.ogImage` in writedocs.json builds none at all, and neither
16
- // does one with `"seo": { "generatedOgImage": false }`.
17
- //
18
- // A static route like [...slug].md.ts next to it: one file per page at build
19
- // time, and built on request in `writedocs dev`.
20
-
21
- type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
22
-
23
- export async function getStaticPaths() {
24
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
25
- const config = loadDocsConfig(contentDir);
26
- const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), 'generated-docs'));
27
- const hasPages = findAllPages(contentDir).length > 0;
28
- const [pagesEntries, generatedDocsEntries] = await Promise.all([
29
- hasPages ? getCollection('pages') : Promise.resolve([]),
30
- hasGeneratedDocs ? getCollection('generatedDocs') : Promise.resolve([]),
31
- ]);
32
- const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
33
-
34
- // The logo is read and encoded once, not once per page.
35
- const logoSetting = config.styles.logo;
36
- const logoPath = typeof logoSetting === 'string' ? logoSetting : (logoSetting?.light ?? logoSetting?.dark);
37
- const logo = logoForCard(logoPath ? imageFileFor(logoPath, contentDir) : null);
38
-
39
- return entries
40
- .filter((entry) => wantsGeneratedCard(mergeSeo(config.seo, entry.data.seo), entry.data, config.seo))
41
- .map((entry) => ({
42
- params: { slug: normalizeEntryId(entry.id) },
43
- props: {
44
- title: entry.data.title,
45
- description: entry.data.seo?.description ?? entry.data.description ?? config.description,
46
- siteName: config.name,
47
- primary: config.styles.colors.primary,
48
- logo,
49
- },
50
- }));
51
- }
52
-
53
- interface Props {
54
- title: string;
55
- description?: string;
56
- siteName: string;
57
- primary: string;
58
- logo: { src: string; width: number; height: number } | null;
59
- }
60
-
61
- export const GET: APIRoute = async ({ props }) => {
62
- const png = await ogImagePng(props as Props);
63
- return new Response(png, { headers: { 'Content-Type': 'image/png' } });
64
- };
1
+ import { getCollection, type CollectionEntry } from 'astro:content';
2
+ import fs from 'node:fs';
3
+ import path from 'node:path';
4
+ import type { APIRoute } from 'astro';
5
+ import { loadDocsConfig, normalizeEntryId, findAllPages, mergeSeo } from '../../lib/config';
6
+ import { writedocsTempDir } from '../../lib/writedocs-temp-dir.js';
7
+ import { ogImagePng } from '../../lib/og-image.js';
8
+ import { ogCardSet, ogCardOptions } from '../../lib/og-cards.js';
9
+
10
+ // /og/<page>.png - the picture a link to a page shows when it's shared, for
11
+ // every page with no `seo.ogImage` of its own: the site's logo, the page's
12
+ // title and description, the site's primary color (lib/og-image.js).
13
+ // Which pages, and what's on each card, is lib/og-cards.js's - the build's
14
+ // own step draws from the same list. [...slug].astro points the page's
15
+ // og:image here under the same condition (wantsGeneratedCard()), so a card is
16
+ // only built for a page that uses it - a site with `seo.ogImage` in
17
+ // writedocs.json builds none at all, and neither does one with
18
+ // `"seo": { "generatedOgImage": false }`.
19
+ //
20
+ // In `writedocs dev`, a static route like [...slug].md.ts next to it, built
21
+ // on request. In `writedocs build` it renders nothing: build.js names a file
22
+ // in WRITEDOCS_OG_CARDS_FILE, the list goes there, and the build draws every
23
+ // card after Astro, in parallel (src/cli/og-images.js) - inside Astro they
24
+ // were drawn one at a time, on one core.
25
+
26
+ type DocsEntry = CollectionEntry<'pages'> | CollectionEntry<'generatedDocs'>;
27
+
28
+ export async function getStaticPaths() {
29
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
30
+ const config = loadDocsConfig(contentDir);
31
+ const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), 'generated-docs'));
32
+ const hasPages = findAllPages(contentDir).length > 0;
33
+ const [pagesEntries, generatedDocsEntries] = await Promise.all([
34
+ hasPages ? getCollection('pages') : Promise.resolve([]),
35
+ hasGeneratedDocs ? getCollection('generatedDocs') : Promise.resolve([]),
36
+ ]);
37
+ const entries: DocsEntry[] = [...pagesEntries, ...generatedDocsEntries];
38
+
39
+ const set = ogCardSet(
40
+ config,
41
+ entries.map((entry) => ({ id: normalizeEntryId(entry.id), data: entry.data, seo: mergeSeo(config.seo, entry.data.seo) })),
42
+ contentDir
43
+ );
44
+ const listFile = process.env.WRITEDOCS_OG_CARDS_FILE;
45
+ if (listFile) {
46
+ fs.writeFileSync(listFile, JSON.stringify(set));
47
+ return [];
48
+ }
49
+ return set.cards.map((card) => ({ params: { slug: card.slug }, props: ogCardOptions(set, card) }));
50
+ }
51
+
52
+ interface Props {
53
+ title: string;
54
+ description?: string;
55
+ siteName: string;
56
+ primary: string;
57
+ logo: { src: string; width: number; height: number } | null;
58
+ }
59
+
60
+ export const GET: APIRoute = async ({ props }) => {
61
+ const png = await ogImagePng(props as Props);
62
+ return new Response(png, { headers: { 'Content-Type': 'image/png' } });
63
+ };