@writedocs/generator 0.13.4 → 0.13.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +356 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +203 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +268 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +507 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +69 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +203 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +408 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.ts +2509 -2509
  48. package/src/lib/config.ts +1316 -1316
  49. package/src/lib/consent.js +108 -108
  50. package/src/lib/content-store-reload-integration.js +101 -101
  51. package/src/lib/icon-data-dev.js +53 -53
  52. package/src/lib/image-size.js +152 -152
  53. package/src/lib/json-schema-descriptions.js +228 -228
  54. package/src/lib/link-check.js +544 -544
  55. package/src/lib/llms-index.ts +90 -90
  56. package/src/lib/mcp-dev-integration.js +65 -65
  57. package/src/lib/mcp-index.ts +102 -102
  58. package/src/lib/mintlify-convert.js +605 -605
  59. package/src/lib/moved-api-pages.js +49 -49
  60. package/src/lib/og-cards.js +33 -33
  61. package/src/lib/og-image.js +235 -235
  62. package/src/lib/openapi-dev-status.js +80 -80
  63. package/src/lib/openapi-reload-integration.js +193 -193
  64. package/src/lib/pages.js +312 -312
  65. package/src/lib/project-files-integration.js +116 -116
  66. package/src/lib/project-files.js +137 -137
  67. package/src/lib/rehype-base-path.js +62 -62
  68. package/src/lib/rehype-image-loading.js +71 -71
  69. package/src/lib/robots-txt.js +21 -21
  70. package/src/lib/search-scope.js +44 -44
  71. package/src/lib/selector-placement.js +50 -50
  72. package/src/lib/seo-tags.js +155 -155
  73. package/src/lib/shiki-code-block.js +7 -1
  74. package/src/lib/site-base.ts +27 -27
  75. package/src/lib/styles-asset-integration.js +291 -291
  76. package/src/lib/wdignore-cases.json +195 -195
  77. package/src/lib/wdignore.js +177 -177
  78. package/src/pages/404.astro +63 -63
  79. package/src/pages/[...slug].astro +1762 -1608
  80. package/src/pages/[...slug].md.ts +93 -93
  81. package/src/pages/llms-full.txt.ts +88 -88
  82. package/src/pages/og/[...slug].png.ts +63 -63
  83. package/src/scripts/mobile-menu.ts +80 -80
  84. package/src/scripts/search.ts +245 -245
  85. package/src/scripts/sidebar-scroll.ts +61 -61
  86. package/src/styles/global.css +40 -40
@@ -1,49 +1,49 @@
1
- // Generated API pages whose address changed between writedocs versions, as
2
- // redirects from the old address to the new one - so links to a published
3
- // site keep working after an update.
4
- //
5
- // One case so far: an operation with no tag used to be served under
6
- // "<path>/untagged/<operation>/" and is now at "<path>/<operation>/".
7
- // generateApiPages() (src/cli/generate-api-pages.js) works the list out
8
- // from the specs and writes it; astro.config.mjs adds it to the site's
9
- // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
- // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
- // counts the old addresses as existing.
12
- //
13
- // Plain JavaScript: read by code that runs under plain Node.
14
- import fs from 'node:fs';
15
- import path from 'node:path';
16
- import { writedocsTempDir } from './writedocs-temp-dir.js';
17
-
18
- /** Where generateApiPages() writes the list (JSON), when anything moved. */
19
- export const movedApiPagesFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'moved.json');
20
-
21
- /** `[{ source: "/api/untagged/get-pets", destination: "/api/get-pets/" }]` -
22
- * empty when nothing moved, or generateApiPages() hasn't run. */
23
- export function readMovedApiPages(contentDir) {
24
- try {
25
- const list = JSON.parse(fs.readFileSync(movedApiPagesFile(contentDir), 'utf-8'));
26
- return Array.isArray(list) ? list.filter((r) => typeof r?.source === 'string' && typeof r?.destination === 'string') : [];
27
- } catch {
28
- return [];
29
- }
30
- }
31
-
32
- /** The redirects for one spec's untagged operations. `moved` is
33
- * `[{ oldSlug, newSlug }]` in the spec's order; `taken` holds every slug a
34
- * page is served at (an operation tagged "untagged" still lives under
35
- * that folder - its address isn't a redirect's to take). The folder's own
36
- * address, which used to lead to its first page, goes to that page's new
37
- * address. */
38
- export function untaggedRedirects(pathPrefix, moved, taken) {
39
- const redirects = [];
40
- const free = (slug) => !taken.has(slug);
41
- for (const { oldSlug, newSlug } of moved) {
42
- if (free(oldSlug)) redirects.push({ source: `/${oldSlug}`, destination: `/${newSlug}/` });
43
- }
44
- const folder = `${pathPrefix}/untagged`;
45
- if (moved.length && free(folder) && ![...taken].some((slug) => slug.startsWith(`${folder}/`))) {
46
- redirects.push({ source: `/${folder}`, destination: `/${moved[0].newSlug}/` });
47
- }
48
- return redirects;
49
- }
1
+ // Generated API pages whose address changed between writedocs versions, as
2
+ // redirects from the old address to the new one - so links to a published
3
+ // site keep working after an update.
4
+ //
5
+ // One case so far: an operation with no tag used to be served under
6
+ // "<path>/untagged/<operation>/" and is now at "<path>/<operation>/".
7
+ // generateApiPages() (src/cli/generate-api-pages.js) works the list out
8
+ // from the specs and writes it; astro.config.mjs adds it to the site's
9
+ // redirects (the redirect pages), src/cli/write-redirects-file.js to
10
+ // `_redirects` (real 301s on hosts that read it), and lib/link-check.js
11
+ // counts the old addresses as existing.
12
+ //
13
+ // Plain JavaScript: read by code that runs under plain Node.
14
+ import fs from 'node:fs';
15
+ import path from 'node:path';
16
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
17
+
18
+ /** Where generateApiPages() writes the list (JSON), when anything moved. */
19
+ export const movedApiPagesFile = (contentDir) => path.join(writedocsTempDir(contentDir), 'openapi', 'moved.json');
20
+
21
+ /** `[{ source: "/api/untagged/get-pets", destination: "/api/get-pets/" }]` -
22
+ * empty when nothing moved, or generateApiPages() hasn't run. */
23
+ export function readMovedApiPages(contentDir) {
24
+ try {
25
+ const list = JSON.parse(fs.readFileSync(movedApiPagesFile(contentDir), 'utf-8'));
26
+ return Array.isArray(list) ? list.filter((r) => typeof r?.source === 'string' && typeof r?.destination === 'string') : [];
27
+ } catch {
28
+ return [];
29
+ }
30
+ }
31
+
32
+ /** The redirects for one spec's untagged operations. `moved` is
33
+ * `[{ oldSlug, newSlug }]` in the spec's order; `taken` holds every slug a
34
+ * page is served at (an operation tagged "untagged" still lives under
35
+ * that folder - its address isn't a redirect's to take). The folder's own
36
+ * address, which used to lead to its first page, goes to that page's new
37
+ * address. */
38
+ export function untaggedRedirects(pathPrefix, moved, taken) {
39
+ const redirects = [];
40
+ const free = (slug) => !taken.has(slug);
41
+ for (const { oldSlug, newSlug } of moved) {
42
+ if (free(oldSlug)) redirects.push({ source: `/${oldSlug}`, destination: `/${newSlug}/` });
43
+ }
44
+ const folder = `${pathPrefix}/untagged`;
45
+ if (moved.length && free(folder) && ![...taken].some((slug) => slug.startsWith(`${folder}/`))) {
46
+ redirects.push({ source: `/${folder}`, destination: `/${moved[0].newSlug}/` });
47
+ }
48
+ return redirects;
49
+ }
@@ -1,33 +1,33 @@
1
- // The link-preview cards a site gets (lib/og-image.js draws one), decided in
2
- // one place for both places that draw them: src/pages/og/[...slug].png.ts,
3
- // on request in `writedocs dev`, and the build's own step after Astro
4
- // (src/cli/og-images.js), which draws them all in parallel. Which pages get
5
- // one, and what's on it - the title, the description, the logo, the color -
6
- // and where it goes: /og/<page id>.png (ogImagePath() in lib/og-image.js).
7
- //
8
- // Plain JavaScript, for scripts/og-images.test.js and the build's threads.
9
- import { imageFileFor } from './image-size.js';
10
- import { logoForCard, wantsGeneratedCard } from './og-image.js';
11
-
12
- /** The cards of a site. `pages` is every page as { id, data, seo }: the
13
- * collection entry's normalized id (normalizeEntryId() in lib/config.ts),
14
- * its frontmatter, and the site's `seo` with the page's merged over it
15
- * (mergeSeo()). What every card shares is said once - the logo is read and
16
- * encoded once, not once per page. */
17
- export function ogCardSet(config, pages, contentDir) {
18
- const logoSetting = config.styles.logo;
19
- const logoPath = typeof logoSetting === 'string' ? logoSetting : (logoSetting?.light ?? logoSetting?.dark);
20
- return {
21
- siteName: config.name,
22
- primary: config.styles.colors.primary,
23
- logo: logoForCard(logoPath ? imageFileFor(logoPath, contentDir) : null),
24
- cards: pages
25
- .filter(({ data, seo }) => wantsGeneratedCard(seo, data, config.seo))
26
- .map(({ id, data }) => ({ slug: id, title: data.title, description: data.seo?.description ?? data.description ?? config.description })),
27
- };
28
- }
29
-
30
- /** What ogImagePng() draws for one card of a set. */
31
- export function ogCardOptions(set, card) {
32
- return { title: card.title, description: card.description, siteName: set.siteName, primary: set.primary, logo: set.logo };
33
- }
1
+ // The link-preview cards a site gets (lib/og-image.js draws one), decided in
2
+ // one place for both places that draw them: src/pages/og/[...slug].png.ts,
3
+ // on request in `writedocs dev`, and the build's own step after Astro
4
+ // (src/cli/og-images.js), which draws them all in parallel. Which pages get
5
+ // one, and what's on it - the title, the description, the logo, the color -
6
+ // and where it goes: /og/<page id>.png (ogImagePath() in lib/og-image.js).
7
+ //
8
+ // Plain JavaScript, for scripts/og-images.test.js and the build's threads.
9
+ import { imageFileFor } from './image-size.js';
10
+ import { logoForCard, wantsGeneratedCard } from './og-image.js';
11
+
12
+ /** The cards of a site. `pages` is every page as { id, data, seo }: the
13
+ * collection entry's normalized id (normalizeEntryId() in lib/config.ts),
14
+ * its frontmatter, and the site's `seo` with the page's merged over it
15
+ * (mergeSeo()). What every card shares is said once - the logo is read and
16
+ * encoded once, not once per page. */
17
+ export function ogCardSet(config, pages, contentDir) {
18
+ const logoSetting = config.styles.logo;
19
+ const logoPath = typeof logoSetting === 'string' ? logoSetting : (logoSetting?.light ?? logoSetting?.dark);
20
+ return {
21
+ siteName: config.name,
22
+ primary: config.styles.colors.primary,
23
+ logo: logoForCard(logoPath ? imageFileFor(logoPath, contentDir) : null),
24
+ cards: pages
25
+ .filter(({ data, seo }) => wantsGeneratedCard(seo, data, config.seo))
26
+ .map(({ id, data }) => ({ slug: id, title: data.title, description: data.seo?.description ?? data.description ?? config.description })),
27
+ };
28
+ }
29
+
30
+ /** What ogImagePng() draws for one card of a set. */
31
+ export function ogCardOptions(set, card) {
32
+ return { title: card.title, description: card.description, siteName: set.siteName, primary: set.primary, logo: set.logo };
33
+ }
@@ -1,235 +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
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
+ // 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
+ }