@writedocs/generator 0.10.17 → 0.10.19

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.10.17",
3
+ "version": "0.10.19",
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": {
@@ -42,7 +42,7 @@
42
42
  "bugs": {
43
43
  "url": "https://github.com/writedocs/writedocs/issues"
44
44
  },
45
- "author": "Gabriel Raeder",
45
+ "author": "Gabriel Raeder Gonçalves",
46
46
  "license": "ISC",
47
47
  "publishConfig": {
48
48
  "access": "public"
@@ -64,6 +64,7 @@
64
64
  "@iconify-json/simple-icons": "1.2.93",
65
65
  "@iconify-json/tabler": "1.2.38",
66
66
  "@mdx-js/mdx": "3.1.1",
67
+ "@resvg/resvg-wasm": "2.6.2",
67
68
  "@shikijs/transformers": "4.4.3",
68
69
  "@tailwindcss/vite": "4.3.3",
69
70
  "astro": "7.2.9",
@@ -79,6 +80,7 @@
79
80
  "react-dom": "19.2.8",
80
81
  "rehype-katex": "7.0.1",
81
82
  "remark-math": "6.0.0",
83
+ "satori": "0.44.0",
82
84
  "shiki": "4.4.3",
83
85
  "tailwindcss": "4.3.3",
84
86
  "zod": "4.4.3"
@@ -0,0 +1,93 @@
1
+ Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter) Inter-Italic[opsz,wght].ttf: Copyright 2016 The Inter Project Authors (https://github.com/rsms/inter)
2
+
3
+ This Font Software is licensed under the SIL Open Font License, Version 1.1.
4
+ This license is copied below, and is also available with a FAQ at:
5
+ http://scripts.sil.org/OFL
6
+
7
+
8
+ -----------------------------------------------------------
9
+ SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10
+ -----------------------------------------------------------
11
+
12
+ PREAMBLE
13
+ The goals of the Open Font License (OFL) are to stimulate worldwide
14
+ development of collaborative font projects, to support the font creation
15
+ efforts of academic and linguistic communities, and to provide a free and
16
+ open framework in which fonts may be shared and improved in partnership
17
+ with others.
18
+
19
+ The OFL allows the licensed fonts to be used, studied, modified and
20
+ redistributed freely as long as they are not sold by themselves. The
21
+ fonts, including any derivative works, can be bundled, embedded,
22
+ redistributed and/or sold with any software provided that any reserved
23
+ names are not used by derivative works. The fonts and derivatives,
24
+ however, cannot be released under any other type of license. The
25
+ requirement for fonts to remain under this license does not apply
26
+ to any document created using the fonts or their derivatives.
27
+
28
+ DEFINITIONS
29
+ "Font Software" refers to the set of files released by the Copyright
30
+ Holder(s) under this license and clearly marked as such. This may
31
+ include source files, build scripts and documentation.
32
+
33
+ "Reserved Font Name" refers to any names specified as such after the
34
+ copyright statement(s).
35
+
36
+ "Original Version" refers to the collection of Font Software components as
37
+ distributed by the Copyright Holder(s).
38
+
39
+ "Modified Version" refers to any derivative made by adding to, deleting,
40
+ or substituting -- in part or in whole -- any of the components of the
41
+ Original Version, by changing formats or by porting the Font Software to a
42
+ new environment.
43
+
44
+ "Author" refers to any designer, engineer, programmer, technical
45
+ writer or other person who contributed to the Font Software.
46
+
47
+ PERMISSION & CONDITIONS
48
+ Permission is hereby granted, free of charge, to any person obtaining
49
+ a copy of the Font Software, to use, study, copy, merge, embed, modify,
50
+ redistribute, and sell modified and unmodified copies of the Font
51
+ Software, subject to the following conditions:
52
+
53
+ 1) Neither the Font Software nor any of its individual components,
54
+ in Original or Modified Versions, may be sold by itself.
55
+
56
+ 2) Original or Modified Versions of the Font Software may be bundled,
57
+ redistributed and/or sold with any software, provided that each copy
58
+ contains the above copyright notice and this license. These can be
59
+ included either as stand-alone text files, human-readable headers or
60
+ in the appropriate machine-readable metadata fields within text or
61
+ binary files as long as those fields can be easily viewed by the user.
62
+
63
+ 3) No Modified Version of the Font Software may use the Reserved Font
64
+ Name(s) unless explicit written permission is granted by the corresponding
65
+ Copyright Holder. This restriction only applies to the primary font name as
66
+ presented to the users.
67
+
68
+ 4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69
+ Software shall not be used to promote, endorse or advertise any
70
+ Modified Version, except to acknowledge the contribution(s) of the
71
+ Copyright Holder(s) and the Author(s) or with their explicit written
72
+ permission.
73
+
74
+ 5) The Font Software, modified or unmodified, in part or in whole,
75
+ must be distributed entirely under this license, and must not be
76
+ distributed under any other license. The requirement for fonts to
77
+ remain under this license does not apply to any document created
78
+ using the Font Software.
79
+
80
+ TERMINATION
81
+ This license becomes null and void if any of the above conditions are
82
+ not met.
83
+
84
+ DISCLAIMER
85
+ THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88
+ OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89
+ COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90
+ INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91
+ DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92
+ FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93
+ OTHER DEALINGS IN THE FONT SOFTWARE.
@@ -54,6 +54,8 @@ export function runAstro(command, { packageRoot, contentDir, port, onEvent }) {
54
54
  // fileIdForEntry() can resolve it back into a docs/-relative file id
55
55
  // - see that function for why.
56
56
  WRITEDOCS_PACKAGE_ROOT: packageRoot,
57
+ // 'dev' or 'build' - lib/build-memo.js keeps per-build results only in a build.
58
+ WRITEDOCS_COMMAND: command,
57
59
  ...(port ? { WRITEDOCS_PORT: String(port) } : {}),
58
60
  },
59
61
  });
@@ -67,8 +67,10 @@ const SEARCH_PUBLIC = /data-wd-search-public="true"/;
67
67
 
68
68
  /** The site's pages by search space - `{ public, spaces }` - or null when
69
69
  * no page is in a hidden space (the whole site is one index, as ever).
70
- * Only pages Pagefind would index: those with a data-pagefind-body. */
71
- function searchSpaces(siteDir) {
70
+ * Only pages Pagefind would index: those with a data-pagefind-body. A
71
+ * page is `{ rel }`, its path in the site with forward slashes.
72
+ * Exported for scripts/search-spaces.test.js. */
73
+ export function searchSpaces(siteDir) {
72
74
  const publicPages = [];
73
75
  const spaces = new Map();
74
76
  const walk = (dir) => {
@@ -81,7 +83,11 @@ function searchSpaces(siteDir) {
81
83
  if (!entry.name.endsWith('.html')) continue;
82
84
  const content = fs.readFileSync(full, 'utf8');
83
85
  if (!content.includes('data-pagefind-body')) continue;
84
- const page = { rel: path.relative(siteDir, full).split(path.sep).join('/'), content };
86
+ // The page's address only, not its HTML: a page is read again when
87
+ // it's added to an index (indexBySpace()). Keeping every page's
88
+ // content here ran the CLI out of memory on a site with 1.7 GiB of
89
+ // HTML - and most sites have no hidden space, so none of it was used.
90
+ const page = { rel: path.relative(siteDir, full).split(path.sep).join('/') };
85
91
  const space = SPACE.exec(content)?.[1];
86
92
  if (!space) {
87
93
  publicPages.push(page);
@@ -110,7 +116,7 @@ async function indexBySpace(siteDir, packageRoot, groups) {
110
116
  };
111
117
  const write = async (pages, outputPath, what) => {
112
118
  const { index } = check(await pagefind.createIndex({}), what);
113
- for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: page.content }), `${what}: ${page.rel}`);
119
+ for (const page of pages) check(await index.addHTMLFile({ sourcePath: page.rel, content: fs.readFileSync(path.join(siteDir, ...page.rel.split('/')), 'utf8') }), `${what}: ${page.rel}`);
114
120
  check(await index.writeFiles({ outputPath }), what);
115
121
  };
116
122
  try {
@@ -82,6 +82,7 @@ import { htmlDirective } from "../lib/agent-directive.js";
82
82
  import { contextMenuOptions } from "../lib/config";
83
83
  import { jsonLd, serializeJsonLd } from "../lib/json-ld.js";
84
84
  import { consentOptions } from "../lib/consent.js";
85
+ import { oncePerBuild } from "../lib/build-memo.js";
85
86
 
86
87
  interface Props {
87
88
  config: DocsConfig;
@@ -158,6 +159,9 @@ const showTocCol = mode === "default";
158
159
  // link, and the description, robots, Open Graph and Twitter metas, with
159
160
  // `seo.metatags` replacing or adding to them.
160
161
  const siteUrl = resolveSiteUrl(config);
162
+ // The site's logo - the light one, or the dark one when that's all there is -
163
+ // for the organization in the structured data.
164
+ const siteLogo = typeof config.styles.logo === "string" ? config.styles.logo : (config.styles.logo?.light ?? config.styles.logo?.dark);
161
165
  const head = seoHead({
162
166
  title,
163
167
  siteName: config.name,
@@ -170,7 +174,6 @@ const head = seoHead({
170
174
  // hreflang: only on a page search engines index, and only with full URLs.
171
175
  const languageLinks = seo.noindex ? [] : hreflangLinks(siteUrl, alternates);
172
176
  // Structured data - see lib/json-ld.js for what a page gets.
173
- const siteLogo = typeof config.styles.logo === "string" ? config.styles.logo : config.styles.logo?.light;
174
177
  const structuredData = jsonLd({
175
178
  siteUrl,
176
179
  siteName: config.name,
@@ -379,10 +382,12 @@ const footerLogoDark = footerLogoConfig
379
382
  // project (root, `docs/`, `snippets/`, `public/`, any subfolder -
380
383
  // `dist/`/`node_modules/`/etc. excluded, see findRootAssets() in
381
384
  // lib/pages.js) is auto-loaded on every page, no writedocs.json entry
382
- // needed. Read fresh on every render (not cached at module scope) so an
383
- // edit to one of these files shows up on the next `writedocs dev` page
384
- // load without a server restart - same freshness `loadDocsConfig(contentDir)`
385
- // itself already gives writedocs.json edits in [...slug].astro/404.astro.
385
+ // needed. In `writedocs dev` they're read fresh on every render, so an
386
+ // edit to one of these files shows up on the next page load without a
387
+ // server restart - same freshness `loadDocsConfig(contentDir)` itself
388
+ // already gives writedocs.json edits in [...slug].astro/404.astro. In a
389
+ // build, where they can't change, the list and the files are read once
390
+ // for all pages (oncePerBuild(), lib/build-memo.js).
386
391
  // Rendered in addition to, not instead of, writedocs.json's own explicit
387
392
  // `scripts` field - that still exists for external/CDN script URLs
388
393
  // (`src`) and inline content that should only load under deliberate
@@ -395,12 +400,12 @@ const rootAssets = findRootAssets(contentDir);
395
400
  // "docs/theme.css") - split and rejoin with nodePath.join rather than
396
401
  // handing the raw string straight to it, so a nested asset resolves
397
402
  // correctly on every OS this might run on, not just POSIX ones.
398
- const rootCssContents = rootAssets.css.map((name) =>
403
+ const rootCssContents = oncePerBuild("root-css-contents", () => rootAssets.css.map((name) =>
399
404
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
400
- );
401
- const rootJsContents = rootAssets.js.map((name) =>
405
+ ));
406
+ const rootJsContents = oncePerBuild("root-js-contents", () => rootAssets.js.map((name) =>
402
407
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
403
- );
408
+ ));
404
409
  // public/*.css and public/*.js auto-load too, but as <link>/<script src>
405
410
  // pointing at their already-public URL (see findRootAssets()'s own
406
411
  // comment for why - no point inlining a file that's also independently
@@ -0,0 +1,22 @@
1
+ // What is the same for every page of a build, worked out once per build.
2
+ //
3
+ // `writedocs build` renders every page in one process, from files that don't
4
+ // change while it runs. The list of page files, writedocs.json, the lookup
5
+ // tables built from the collections - each page asked for them again, and
6
+ // each of those reads the whole project: with N pages, N x N file reads. A
7
+ // 4,000-page site spent 13 of its 19 minutes there.
8
+ //
9
+ // Only in a build: src/cli/run-astro.js tells the Astro process which command
10
+ // it runs (WRITEDOCS_COMMAND). In `writedocs dev` - and wherever else this is
11
+ // loaded: `writedocs validate`, the tests - compute() runs on every call, as
12
+ // it always did, because there the files do change between two calls.
13
+ //
14
+ // What compute() returns is handed to every caller, so callers must not
15
+ // change it. Plain JavaScript, for scripts/build-memo.test.js.
16
+ const values = new Map();
17
+
18
+ export function oncePerBuild(key, compute) {
19
+ if (process.env.WRITEDOCS_COMMAND !== 'build') return compute();
20
+ if (!values.has(key)) values.set(key, compute());
21
+ return values.get(key);
22
+ }
@@ -337,6 +337,11 @@ const pageSeoFieldsSchema = seoFieldsSchema.extend({
337
337
  jsonLd: z.union([z.record(z.string(), z.unknown()), z.array(z.record(z.string(), z.unknown()))]).optional()
338
338
  }).strict();
339
339
  const siteSeoFieldsSchema = seoFieldsSchema.extend({
340
+ // The link preview picture generated for every page that has no
341
+ // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
342
+ // takes ~25 ms a page, which a site with thousands of pages may prefer
343
+ // to save. Site-wide only - a page opts out by setting its own `ogImage`.
344
+ generatedOgImage: z.boolean().optional(),
340
345
  // Who publishes the site - an Organization block in the home page's
341
346
  // structured data, and the `publisher` of every page (lib/json-ld.js).
342
347
  // Not derived from `name`: a site is called "Acme Docs", the
@@ -679,6 +679,11 @@ export const pageSeoFieldsSchema = seoFieldsSchema
679
679
  // as a whole.
680
680
  export const siteSeoFieldsSchema = seoFieldsSchema
681
681
  .extend({
682
+ // The link preview picture generated for every page that has no
683
+ // `ogImage` (lib/og-image.js). On unless this is `false`: drawing one
684
+ // takes ~25 ms a page, which a site with thousands of pages may prefer
685
+ // to save. Site-wide only - a page opts out by setting its own `ogImage`.
686
+ generatedOgImage: z.boolean().optional(),
682
687
  // Who publishes the site - an Organization block in the home page's
683
688
  // structured data, and the `publisher` of every page (lib/json-ld.js).
684
689
  // Not derived from `name`: a site is called "Acme Docs", the
package/src/lib/config.ts CHANGED
@@ -6,6 +6,7 @@ import { itemPage, childLevel, equivalentItem, resolveLandings as resolveLanding
6
6
  import matter from 'gray-matter';
7
7
  import { writedocsTempDir } from './writedocs-temp-dir.js';
8
8
  import { readableTextOn } from './color.js';
9
+ import { oncePerBuild } from './build-memo.js';
9
10
  import {
10
11
  formatValidationIssues,
11
12
  validateDocsConfig,
@@ -396,6 +397,13 @@ function expandOpenApiInNavigation(navigation: NavigationConfig, contentDir: str
396
397
  }
397
398
 
398
399
  export function loadDocsConfig(contentDir: string): DocsConfig {
400
+ // Read and validated once per build, not once per page (lib/build-memo.js):
401
+ // every caller there gets the same object, so none of them may change it.
402
+ // In `writedocs dev` it's read again on every call, and an edit shows up.
403
+ return oncePerBuild(`config:${contentDir}`, () => readDocsConfig(contentDir));
404
+ }
405
+
406
+ function readDocsConfig(contentDir: string): DocsConfig {
399
407
  const configPath = path.join(contentDir, 'writedocs.json');
400
408
  if (!fs.existsSync(configPath)) {
401
409
  throw new Error(
@@ -168,6 +168,7 @@ export const DESCRIPTIONS = {
168
168
 
169
169
  seo: 'Default metadata for every page. A page\'s own `seo` frontmatter overrides it field by field.',
170
170
  'seo.ogImage': 'Image shown in link previews - a path or a full URL.',
171
+ 'seo.generatedOgImage': 'Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site.',
171
172
  'seo.ogType': 'The og:type of pages. Default "website".',
172
173
  'seo.twitterCard': 'X/Twitter card style. Default "summary_large_image" with an `ogImage`, "summary" without.',
173
174
  'seo.keywords': 'Keywords for the <meta name="keywords"> tag.',
@@ -0,0 +1,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 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
+ }
package/src/lib/pages.js CHANGED
@@ -6,6 +6,7 @@ import fs from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import matter from 'gray-matter';
8
8
  import { readConfigText } from './config-file.js';
9
+ import { oncePerBuild } from './build-memo.js';
9
10
 
10
11
  // Top-level folders of a content directory that are never scanned for
11
12
  // pages - build output, dependencies, and static assets. Any folder whose
@@ -114,10 +115,17 @@ function navigationPageIds(contentDir) {
114
115
  * and [...slug].astro, which needs the identical list to decide whether
115
116
  * calling `getCollection('pages')` is worth doing at all. Also reused by
116
117
  * astro.config.mjs's noindex/sitemap scan and by `writedocs validate`, so
117
- * all of them see exactly the same file set. Synchronous and re-run from
118
- * scratch wherever it's called - cheap enough for a docs site's file
119
- * count. */
118
+ * all of them see exactly the same file set. Synchronous. In a build the
119
+ * project is scanned once and every later call gets that list
120
+ * (lib/build-memo.js) - a page that scanned it again made the build N x N;
121
+ * everywhere else (`writedocs dev`, `validate`) every call scans afresh,
122
+ * so a page added or removed is seen. */
120
123
  export function findAllPages(contentDir) {
124
+ // A copy, so a caller that changes its list doesn't change everyone's.
125
+ return oncePerBuild(`pages:${contentDir}`, () => scanAllPages(contentDir)).slice();
126
+ }
127
+
128
+ function scanAllPages(contentDir) {
121
129
  const results = [];
122
130
  const ignored = readIgnoreFile(contentDir);
123
131
  const listed = navigationPageIds(contentDir);
@@ -232,6 +240,11 @@ export function fileIdForPath(relativePath) {
232
240
  * above - nothing to read, Astro's own static-file serving/copy already
233
241
  * handles those. */
234
242
  export function findRootAssets(contentDir) {
243
+ // Once per build (lib/build-memo.js); on every call in `writedocs dev`.
244
+ return oncePerBuild(`root-assets:${contentDir}`, () => scanRootAssets(contentDir));
245
+ }
246
+
247
+ function scanRootAssets(contentDir) {
235
248
  const css = [];
236
249
  const js = [];
237
250
  function walk(dir, relBase) {
@@ -96,8 +96,11 @@ export function seoHead({ title, siteName, description, siteDescription, seo = {
96
96
  const metaDescription = seo.description?.trim() || description || siteDescription;
97
97
  const canonical = canonicalUrl(siteUrl, path, seo.canonical);
98
98
  const custom = seo.metatags ?? {};
99
+ // The picture in a link preview: the page's or the site's `ogImage` -
100
+ // or, set by [...slug].astro when there is neither, the card generated
101
+ // for the page (lib/og-image.js).
99
102
  const image = seo.ogImage ? absoluteUrl(siteUrl, seo.ogImage) : undefined;
100
- // The large card needs a picture - from `ogImage`, or a tag set by hand.
103
+ // The large card needs a picture - that one, or a tag set by hand.
101
104
  const hasImage = Boolean(image || custom['og:image'] || custom['twitter:image']);
102
105
  const robots = typeof seo.robots === 'string' && seo.robots.trim() ? seo.robots.trim() : seo.noindex ? 'noindex, nofollow' : undefined;
103
106
 
@@ -25,6 +25,7 @@ import {
25
25
  import { writedocsTempDir } from "../lib/writedocs-temp-dir.js";
26
26
  import { parseOpenApiRef } from "../lib/openapi-ref.js";
27
27
  import { languageAlternates } from "../lib/item-pages.js";
28
+ import { wantsGeneratedCard, ogImagePath } from "../lib/og-image.js";
28
29
  import BaseLayout from "../layout/BaseLayout.astro";
29
30
  import Sidebar from "../layout/components/Sidebar.astro";
30
31
  import TableOfContents from "../layout/components/TableOfContents.astro";
@@ -77,6 +78,7 @@ import { selectorPlacements } from "../lib/selector-placement.js";
77
78
  import { spaceOf } from "../lib/hidden-sections.js";
78
79
  import { navigationPageOrder } from "../lib/pages.js";
79
80
  import { folderRedirects } from "../lib/folder-redirects.js";
81
+ import { oncePerBuild } from "../lib/build-memo.js";
80
82
 
81
83
  // A page is hand-written (the `pages` collection, sourced from anywhere
82
84
  // in the project - docs/ has no special status, see findAllPages() in
@@ -370,7 +372,8 @@ const {
370
372
  const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
371
373
  const packageRoot = process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd();
372
374
  const config = loadDocsConfig(contentDir);
373
- const sections = resolveSections(config.navigation);
375
+ // Once per build, like the lookup tables further down.
376
+ const sections = oncePerBuild("slug:sections", () => resolveSections(config.navigation));
374
377
  // Falls back to an empty stand-in section rather than crashing on
375
378
  // `.pages` below - only reachable for a hidden page (see hiddenRoutes in
376
379
  // getStaticPaths above) on a site whose writedocs.json has no navigation
@@ -378,12 +381,17 @@ const sections = resolveSections(config.navigation);
378
381
  // render in the first place.
379
382
  // An item's own page shown inside its item (landingRoutes above): the item's
380
383
  // path, and its own sidebar if it has one.
381
- const landing = landingIndex === undefined ? undefined : resolveLandings(config.navigation)[landingIndex];
384
+ const landing = landingIndex === undefined ? undefined : oncePerBuild("slug:landings", () => resolveLandings(config.navigation))[landingIndex];
382
385
  const activeSection = landing ? { pages: landing.pages, path: landing.path } : sections[sectionIndex] ?? { pages: [], path: [] };
383
386
 
384
387
  const { Content, headings } = await render(entry);
385
388
  const tocHeadings = headings.filter((h) => h.depth === 2 || h.depth === 3);
386
389
 
390
+ // The lookup tables below are the same for every page, so a build makes
391
+ // them once (oncePerBuild(), lib/build-memo.js) - findAllPages() alone reads
392
+ // every page file of the project, and ran here once per page. In
393
+ // `writedocs dev` they're made again on every request, as before.
394
+ const { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId } = await oncePerBuild("slug:lookups", async () => {
387
395
  const hasGeneratedDocs = fs.existsSync(path.join(writedocsTempDir(contentDir), "generated-docs"));
388
396
  const hasPages = findAllPages(contentDir).length > 0;
389
397
  const [pagesEntries, generatedDocsEntries] = await Promise.all([
@@ -418,6 +426,8 @@ for (const e of entries) {
418
426
  methodByFileId.set(fileId, apiRef.method);
419
427
  }
420
428
  }
429
+ return { titleByFileId, navTitleByFileId, entryByFileId, methodByFileId };
430
+ });
421
431
  const titleForSlug = (slug: string) => titleByFileId.get(slug) ?? slug;
422
432
  const navTitleForSlug = (slug: string) => navTitleByFileId.get(slug) ?? slug;
423
433
  const methodForSlug = (slug: string) => methodByFileId.get(slug) ?? null;
@@ -434,7 +444,9 @@ const hrefForSlug = (slug: string) => {
434
444
  // and what every "is this the active page" comparison below needs, since
435
445
  // navTree/globalDropdowns are built from writedocs.json's file-id space.
436
446
  const currentFileId = fileIdForEntry(contentDir, packageRoot, entry);
437
- const navTree = buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug);
447
+ // A section's tree doesn't depend on which of its pages is open (NavTree.astro
448
+ // marks the current one), so it's built once per section in a build.
449
+ const navTree = oncePerBuild(`slug:nav:${landingIndex === undefined ? `s${sectionIndex}` : `l${landingIndex}`}`, () => buildNavTree(activeSection.pages, navTitleForSlug, methodForSlug, navMetaForSlug));
438
450
  // The ancestor sidebar-group trail above the auto <h1> (Breadcrumbs.astro)
439
451
  // - empty for a page sitting at the top level of its Section with no
440
452
  // enclosing group, in which case [...slug].astro below skips rendering
@@ -483,6 +495,9 @@ const globalDropdowns = buildGlobalDropdowns(
483
495
  // than recomputing it, since it already encodes the same
484
496
  // frontmatter-slug-override-aware routing logic.
485
497
  const pageSeo = mergeSeo(config.seo, entry.data.seo);
498
+ // A page with no picture of its own for link previews gets the generated
499
+ // card (lib/og-image.js, served by src/pages/og/[...slug].png.ts).
500
+ if (wantsGeneratedCard(pageSeo, entry.data, config.seo)) pageSeo.ogImage = ogImagePath(normalizeEntryId(entry.id));
486
501
  const currentPath = hrefForSlug(currentFileId);
487
502
  // This page in each language, for hreflang (languageAlternates() in
488
503
  // lib/item-pages.js) - a hidden page belongs to no language level.
@@ -0,0 +1,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, 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
+ };
@@ -757,6 +757,11 @@
757
757
  "description": "Other <meta> tags, name to content - like { \"google-site-verification\": \"...\" }. One with the name of a tag writedocs writes (\"og:image\", \"twitter:image\") replaces it.",
758
758
  "markdownDescription": "Other <meta> tags, name to content - like { \"google-site-verification\": \"...\" }. One with the name of a tag writedocs writes (\"og:image\", \"twitter:image\") replaces it."
759
759
  },
760
+ "generatedOgImage": {
761
+ "type": "boolean",
762
+ "description": "Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site.",
763
+ "markdownDescription": "Whether a page without an `ogImage` gets a link preview image generated at build time. Default true; set false to skip them, which shortens the build of a large site."
764
+ },
760
765
  "organization": {
761
766
  "type": "object",
762
767
  "properties": {