@writedocs/generator 0.10.18 → 0.10.20

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,164 +1,164 @@
1
- ---
2
- import { extraClasses } from './class-names';
3
- import { imageFileFor, imageSize } from '../lib/image-size.js';
4
- // Block-level (own line, centered) - unlike Hint (inline/text-level),
5
- // this is meant to be dropped in on its own the way Callout/Card are.
6
- //
7
- // src/srcDark render as two separate <img> tags, both always in the
8
- // markup, CSS shows only the one matching the active [data-theme] - the
9
- // exact same dual light/dark-asset pattern base.css's own .wd-logo-light/
10
- // .wd-logo-dark rules already establish for TopBar/MobileMenu/SiteFooter's
11
- // logo (see that comment there) - base.css's own comment on those rules
12
- // spells out exactly why they get to write [data-theme='dark'] .wd-logo-x
13
- // completely unscoped: base.css is a *plain imported* .css file, never run
14
- // through Astro's scoped-CSS compiler at all, unlike this component's own
15
- // <style> block below. [data-theme] lives on <html>, set by BaseLayout's
16
- // anti-FOUC script - nowhere near this component's own template - so
17
- // inside a *scoped* <style> (this one) that ancestor selector has to be
18
- // wrapped in :global() or Astro's compiler appends this component's own
19
- // scope attribute onto it too, requiring <html> to carry that attribute,
20
- // which it never will. .wd-image-light/.wd-image-dark themselves don't
21
- // need :global() - unlike AppIcon-rendered markup (Card/Accordion's own
22
- // icon rules), both <img> tags here are rendered directly by *this*
23
- // component's own template, so they already carry its scope attribute
24
- // normally.
25
- interface Props {
26
- src: string;
27
- srcDark?: string;
28
- // Width at full (unconstrained) viewport width - a raw CSS length or
29
- // percentage string ("80%", "480px", "40rem", ...), passed straight
30
- // through as a custom property with no parsing/validation, the same
31
- // "trust the site author, this is their writedocs.json/content" latitude
32
- // every other pass-through string prop here already gets (Card's
33
- // icon, Callout's title, ...). Applied to the *figure* (see below),
34
- // not the <img> tags directly - an earlier version set it on the img
35
- // instead, which left the figure itself (and, when caption is set,
36
- // its whole bordered card) always full-width regardless of `size`,
37
- // so a size="70%" image ended up sitting inside a card twice as wide
38
- // as it needed to be, with a large empty gap on both sides - caught
39
- // via a real screenshot showing exactly that gap. max-width: 100%
40
- // below is what actually makes this shrink on a narrower viewport
41
- // instead of overflowing it, regardless of which form `size` takes -
42
- // a percentage already scales with its container on its own, but a
43
- // fixed px/rem value doesn't, and needs that separate cap to behave
44
- // the same way.
45
- size?: string;
46
- alt?: string;
47
- // Optional caption shown below the image. Set it and the whole thing
48
- // gains the same bordered/rounded "card" background Frame's own
49
- // caption case uses (border + background + padding, image inset
50
- // inside it) - deliberately conditional on caption being set rather
51
- // than always-on: without a caption this needs to render exactly as
52
- // it always has (a plain image, no chrome), so an existing
53
- // <Image src="..." /> with no caption keeps its current look with
54
- // zero visual change - only opting a page into the card look actually
55
- // opts it in.
56
- caption?: string;
57
- // Opts this image out of the site-wide click-to-zoom lightbox (see
58
- // src/scripts/image-zoom.ts) - rendered as a bare `nozoom` attribute
59
- // on both <img> tags, the same attribute a raw
60
- // `<img nozoom src="..." />` written directly in MDX would carry, so
61
- // lib/image-zoom-rules.js handles both cases identically rather than
62
- // needing to special-case this component.
63
- noZoom?: boolean;
64
- // "lazy" (the default): the browser fetches the image when the reader
65
- // gets near it. "eager": with the page - for an image at the very top.
66
- // The page's first image gets "eager" by itself
67
- // (lib/rehype-image-loading.js).
68
- loading?: "lazy" | "eager";
69
- }
70
- const { src, srcDark, size, alt = "", caption, noZoom, loading = "lazy" } = Astro.props as Props;
71
- // Each file's own pixel size, as width/height: the browser keeps the
72
- // image's place before it arrives, so the text below doesn't jump. The
73
- // CSS below already has height: auto, so the image still scales.
74
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
75
- const sizeOf = (address?: string) => {
76
- const file = address ? imageFileFor(address, contentDir) : null;
77
- return (file && imageSize(file)) || { width: undefined, height: undefined };
78
- };
79
- const light = sizeOf(src);
80
- const dark = sizeOf(srcDark);
81
- const sizeStyle = size ? `--wd-image-size:${size}` : undefined;
82
- ---
83
-
84
- <figure
85
- class:list={["wd-image-figure", caption && "wd-image-figure-framed", srcDark && "wd-image-has-dark", extraClasses(Astro.props)]}
86
- style={sizeStyle}
87
- >
88
- <img src={src} alt={alt} class="wd-image wd-image-light" nozoom={noZoom || undefined} loading={loading} decoding="async" width={light.width} height={light.height} />
89
- {srcDark && <img src={srcDark} alt={alt} class="wd-image wd-image-dark" nozoom={noZoom || undefined} loading={loading} decoding="async" width={dark.width} height={dark.height} />}
90
- {caption && <figcaption class="wd-image-caption">{caption}</figcaption>}
91
- </figure>
92
- <style>
93
- /* width: var(--wd-image-size, 100%) here (not on the img - see the
94
- `size` prop's own comment above) is what makes the *whole figure*,
95
- card background and all, actually match the image's own size
96
- instead of always spanning the full content column. margin: ...
97
- auto only has anything to center once this has a definite width
98
- smaller than its container - at the 100% default it's a no-op,
99
- same as before this prop existed. */
100
- .wd-image-figure {
101
- width: var(--wd-image-size, 100%);
102
- max-width: 100%;
103
- margin: 1.25rem auto;
104
- }
105
- /* Same card language as Frame's own bordered case (border + rounded +
106
- surface background + padding) - deliberately duplicated here rather
107
- than shared, the same way Card/Callout/Accordion each carry their
108
- own near-identical CSS rather than a shared base class; Astro's
109
- scoped <style> blocks are per-component anyway, so there's no
110
- lighter-weight way to share this without introducing a global
111
- stylesheet dependency neither component otherwise needs. Padding
112
- is what creates the "image inset within the card" look - the img's
113
- own width: 100% below resolves against this padded content box,
114
- not the figure's own outer edge.
115
- box-shadow is a deliberate belt-and-suspenders addition on top of
116
- the border - var(--wd-border)/var(--wd-surface) are both very
117
- light, low-contrast tokens by default (see BaseLayout.astro's own
118
- --wd-border/--wd-surface light-mode values), so on a page whose own
119
- background is similarly pale (or, worse, uses the literal same
120
- image asset as its background - confirmed as the actual root cause
121
- of a real earlier "the card is invisible" report), the border alone
122
- can end up nearly imperceptible even though it's genuinely being
123
- applied. A soft shadow gives the card a second, independent visual
124
- cue that doesn't depend on border/surface contrast against
125
- whatever the page happens to look like. */
126
- .wd-image-figure-framed {
127
- border: 1px solid var(--wd-border);
128
- border-radius: 0.75rem;
129
- background: var(--wd-surface);
130
- padding: 0.5rem;
131
- box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
132
- }
133
- .wd-image {
134
- display: block;
135
- width: 100%;
136
- height: auto;
137
- border-radius: 0.75rem;
138
- }
139
- .wd-image-dark {
140
- display: none;
141
- }
142
- /* .wd-image-light only hides in dark mode when a dark variant is
143
- actually there to replace it - .wd-image-has-dark only gets added
144
- to the figure when srcDark is set (see the frontmatter above); with
145
- no srcDark, there's no second <img> in the markup at all, so
146
- unconditionally hiding the light one (an earlier version of this
147
- rule had no such scoping) left dark mode with literally nothing to
148
- show - a real user report caught exactly that: light-only Image
149
- usages went blank in dark mode instead of just keeping the one
150
- image they had, same as base.css's own dual-logo comment already
151
- notes for a site that only configures one logo. */
152
- :global([data-theme="dark"]) .wd-image-figure.wd-image-has-dark .wd-image-light {
153
- display: none;
154
- }
155
- :global([data-theme="dark"]) .wd-image-dark {
156
- display: block;
157
- }
158
- .wd-image-caption {
159
- margin-top: 0.6rem;
160
- text-align: center;
161
- color: var(--wd-text);
162
- font-size: 0.75rem;
163
- }
164
- </style>
1
+ ---
2
+ import { extraClasses } from './class-names';
3
+ import { imageFileFor, imageSize } from '../lib/image-size.js';
4
+ // Block-level (own line, centered) - unlike Hint (inline/text-level),
5
+ // this is meant to be dropped in on its own the way Callout/Card are.
6
+ //
7
+ // src/srcDark render as two separate <img> tags, both always in the
8
+ // markup, CSS shows only the one matching the active [data-theme] - the
9
+ // exact same dual light/dark-asset pattern base.css's own .wd-logo-light/
10
+ // .wd-logo-dark rules already establish for TopBar/MobileMenu/SiteFooter's
11
+ // logo (see that comment there) - base.css's own comment on those rules
12
+ // spells out exactly why they get to write [data-theme='dark'] .wd-logo-x
13
+ // completely unscoped: base.css is a *plain imported* .css file, never run
14
+ // through Astro's scoped-CSS compiler at all, unlike this component's own
15
+ // <style> block below. [data-theme] lives on <html>, set by BaseLayout's
16
+ // anti-FOUC script - nowhere near this component's own template - so
17
+ // inside a *scoped* <style> (this one) that ancestor selector has to be
18
+ // wrapped in :global() or Astro's compiler appends this component's own
19
+ // scope attribute onto it too, requiring <html> to carry that attribute,
20
+ // which it never will. .wd-image-light/.wd-image-dark themselves don't
21
+ // need :global() - unlike AppIcon-rendered markup (Card/Accordion's own
22
+ // icon rules), both <img> tags here are rendered directly by *this*
23
+ // component's own template, so they already carry its scope attribute
24
+ // normally.
25
+ interface Props {
26
+ src: string;
27
+ srcDark?: string;
28
+ // Width at full (unconstrained) viewport width - a raw CSS length or
29
+ // percentage string ("80%", "480px", "40rem", ...), passed straight
30
+ // through as a custom property with no parsing/validation, the same
31
+ // "trust the site author, this is their writedocs.json/content" latitude
32
+ // every other pass-through string prop here already gets (Card's
33
+ // icon, Callout's title, ...). Applied to the *figure* (see below),
34
+ // not the <img> tags directly - an earlier version set it on the img
35
+ // instead, which left the figure itself (and, when caption is set,
36
+ // its whole bordered card) always full-width regardless of `size`,
37
+ // so a size="70%" image ended up sitting inside a card twice as wide
38
+ // as it needed to be, with a large empty gap on both sides - caught
39
+ // via a real screenshot showing exactly that gap. max-width: 100%
40
+ // below is what actually makes this shrink on a narrower viewport
41
+ // instead of overflowing it, regardless of which form `size` takes -
42
+ // a percentage already scales with its container on its own, but a
43
+ // fixed px/rem value doesn't, and needs that separate cap to behave
44
+ // the same way.
45
+ size?: string;
46
+ alt?: string;
47
+ // Optional caption shown below the image. Set it and the whole thing
48
+ // gains the same bordered/rounded "card" background Frame's own
49
+ // caption case uses (border + background + padding, image inset
50
+ // inside it) - deliberately conditional on caption being set rather
51
+ // than always-on: without a caption this needs to render exactly as
52
+ // it always has (a plain image, no chrome), so an existing
53
+ // <Image src="..." /> with no caption keeps its current look with
54
+ // zero visual change - only opting a page into the card look actually
55
+ // opts it in.
56
+ caption?: string;
57
+ // Opts this image out of the site-wide click-to-zoom lightbox (see
58
+ // src/scripts/image-zoom.ts) - rendered as a bare `nozoom` attribute
59
+ // on both <img> tags, the same attribute a raw
60
+ // `<img nozoom src="..." />` written directly in MDX would carry, so
61
+ // lib/image-zoom-rules.js handles both cases identically rather than
62
+ // needing to special-case this component.
63
+ noZoom?: boolean;
64
+ // "lazy" (the default): the browser fetches the image when the reader
65
+ // gets near it. "eager": with the page - for an image at the very top.
66
+ // The page's first image gets "eager" by itself
67
+ // (lib/rehype-image-loading.js).
68
+ loading?: "lazy" | "eager";
69
+ }
70
+ const { src, srcDark, size, alt = "", caption, noZoom, loading = "lazy" } = Astro.props as Props;
71
+ // Each file's own pixel size, as width/height: the browser keeps the
72
+ // image's place before it arrives, so the text below doesn't jump. The
73
+ // CSS below already has height: auto, so the image still scales.
74
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
75
+ const sizeOf = (address?: string) => {
76
+ const file = address ? imageFileFor(address, contentDir) : null;
77
+ return (file && imageSize(file, contentDir)) || { width: undefined, height: undefined };
78
+ };
79
+ const light = sizeOf(src);
80
+ const dark = sizeOf(srcDark);
81
+ const sizeStyle = size ? `--wd-image-size:${size}` : undefined;
82
+ ---
83
+
84
+ <figure
85
+ class:list={["wd-image-figure", caption && "wd-image-figure-framed", srcDark && "wd-image-has-dark", extraClasses(Astro.props)]}
86
+ style={sizeStyle}
87
+ >
88
+ <img src={src} alt={alt} class="wd-image wd-image-light" nozoom={noZoom || undefined} loading={loading} decoding="async" width={light.width} height={light.height} />
89
+ {srcDark && <img src={srcDark} alt={alt} class="wd-image wd-image-dark" nozoom={noZoom || undefined} loading={loading} decoding="async" width={dark.width} height={dark.height} />}
90
+ {caption && <figcaption class="wd-image-caption">{caption}</figcaption>}
91
+ </figure>
92
+ <style>
93
+ /* width: var(--wd-image-size, 100%) here (not on the img - see the
94
+ `size` prop's own comment above) is what makes the *whole figure*,
95
+ card background and all, actually match the image's own size
96
+ instead of always spanning the full content column. margin: ...
97
+ auto only has anything to center once this has a definite width
98
+ smaller than its container - at the 100% default it's a no-op,
99
+ same as before this prop existed. */
100
+ .wd-image-figure {
101
+ width: var(--wd-image-size, 100%);
102
+ max-width: 100%;
103
+ margin: 1.25rem auto;
104
+ }
105
+ /* Same card language as Frame's own bordered case (border + rounded +
106
+ surface background + padding) - deliberately duplicated here rather
107
+ than shared, the same way Card/Callout/Accordion each carry their
108
+ own near-identical CSS rather than a shared base class; Astro's
109
+ scoped <style> blocks are per-component anyway, so there's no
110
+ lighter-weight way to share this without introducing a global
111
+ stylesheet dependency neither component otherwise needs. Padding
112
+ is what creates the "image inset within the card" look - the img's
113
+ own width: 100% below resolves against this padded content box,
114
+ not the figure's own outer edge.
115
+ box-shadow is a deliberate belt-and-suspenders addition on top of
116
+ the border - var(--wd-border)/var(--wd-surface) are both very
117
+ light, low-contrast tokens by default (see BaseLayout.astro's own
118
+ --wd-border/--wd-surface light-mode values), so on a page whose own
119
+ background is similarly pale (or, worse, uses the literal same
120
+ image asset as its background - confirmed as the actual root cause
121
+ of a real earlier "the card is invisible" report), the border alone
122
+ can end up nearly imperceptible even though it's genuinely being
123
+ applied. A soft shadow gives the card a second, independent visual
124
+ cue that doesn't depend on border/surface contrast against
125
+ whatever the page happens to look like. */
126
+ .wd-image-figure-framed {
127
+ border: 1px solid var(--wd-border);
128
+ border-radius: 0.75rem;
129
+ background: var(--wd-surface);
130
+ padding: 0.5rem;
131
+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
132
+ }
133
+ .wd-image {
134
+ display: block;
135
+ width: 100%;
136
+ height: auto;
137
+ border-radius: 0.75rem;
138
+ }
139
+ .wd-image-dark {
140
+ display: none;
141
+ }
142
+ /* .wd-image-light only hides in dark mode when a dark variant is
143
+ actually there to replace it - .wd-image-has-dark only gets added
144
+ to the figure when srcDark is set (see the frontmatter above); with
145
+ no srcDark, there's no second <img> in the markup at all, so
146
+ unconditionally hiding the light one (an earlier version of this
147
+ rule had no such scoping) left dark mode with literally nothing to
148
+ show - a real user report caught exactly that: light-only Image
149
+ usages went blank in dark mode instead of just keeping the one
150
+ image they had, same as base.css's own dual-logo comment already
151
+ notes for a site that only configures one logo. */
152
+ :global([data-theme="dark"]) .wd-image-figure.wd-image-has-dark .wd-image-light {
153
+ display: none;
154
+ }
155
+ :global([data-theme="dark"]) .wd-image-dark {
156
+ display: block;
157
+ }
158
+ .wd-image-caption {
159
+ margin-top: 0.6rem;
160
+ text-align: center;
161
+ color: var(--wd-text);
162
+ font-size: 0.75rem;
163
+ }
164
+ </style>
@@ -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;
@@ -381,10 +382,12 @@ const footerLogoDark = footerLogoConfig
381
382
  // project (root, `docs/`, `snippets/`, `public/`, any subfolder -
382
383
  // `dist/`/`node_modules/`/etc. excluded, see findRootAssets() in
383
384
  // lib/pages.js) is auto-loaded on every page, no writedocs.json entry
384
- // needed. Read fresh on every render (not cached at module scope) so an
385
- // edit to one of these files shows up on the next `writedocs dev` page
386
- // load without a server restart - same freshness `loadDocsConfig(contentDir)`
387
- // 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).
388
391
  // Rendered in addition to, not instead of, writedocs.json's own explicit
389
392
  // `scripts` field - that still exists for external/CDN script URLs
390
393
  // (`src`) and inline content that should only load under deliberate
@@ -397,12 +400,12 @@ const rootAssets = findRootAssets(contentDir);
397
400
  // "docs/theme.css") - split and rejoin with nodePath.join rather than
398
401
  // handing the raw string straight to it, so a nested asset resolves
399
402
  // correctly on every OS this might run on, not just POSIX ones.
400
- const rootCssContents = rootAssets.css.map((name) =>
403
+ const rootCssContents = oncePerBuild("root-css-contents", () => rootAssets.css.map((name) =>
401
404
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
402
- );
403
- const rootJsContents = rootAssets.js.map((name) =>
405
+ ));
406
+ const rootJsContents = oncePerBuild("root-js-contents", () => rootAssets.js.map((name) =>
404
407
  fs.readFileSync(nodePath.join(contentDir, ...name.split("/")), "utf-8"),
405
- );
408
+ ));
406
409
  // public/*.css and public/*.js auto-load too, but as <link>/<script src>
407
410
  // pointing at their already-public URL (see findRootAssets()'s own
408
411
  // comment for why - no point inlining a file that's also independently
@@ -0,0 +1,89 @@
1
+ // Image sizes handed to the build in a file, so it doesn't open the images.
2
+ //
3
+ // The WriteDocs platform builds a project with its images swapped for small
4
+ // placeholder files (it puts the real ones back after the build), so the
5
+ // build can't read a width and a height from them. It writes this file
6
+ // instead:
7
+ //
8
+ // <project>/.writedocs/asset-dimensions.json
9
+ // {
10
+ // "images/hero.png": { "width": 1200, "height": 630 },
11
+ // "public/images/logo.svg": { "width": 120, "height": 32 }
12
+ // }
13
+ //
14
+ // THIS FORMAT IS A CONTRACT with the platform:
15
+ // - one JSON object; each key is a file's path from the project root -
16
+ // where the file really is, so a file in public/ starts with "public/" -
17
+ // with forward slashes, no leading slash, spelled exactly as on disk;
18
+ // - each value is an object with `width` and `height`, both whole numbers
19
+ // greater than zero (pixels). Other fields in it are ignored.
20
+ // - A path that's listed is never opened to be measured. A path that isn't
21
+ // listed is read from its file, as when there's no such file at all.
22
+ // - An entry that isn't valid is skipped and the image is read; a file
23
+ // that isn't valid JSON, or isn't an object, counts as absent. Nothing
24
+ // here can fail a build.
25
+ //
26
+ // `.writedocs/` is never published (EXCLUDED_TOP_LEVEL_DIRS, lib/pages.js).
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+
30
+ /** Where the file is, from the project root. */
31
+ export const ASSET_DIMENSIONS_FILE = '.writedocs/asset-dimensions.json';
32
+
33
+ const isSize = (n) => Number.isSafeInteger(n) && n > 0;
34
+
35
+ /** The valid entries of the file's text, as a Map of path -> `{ width,
36
+ * height }`. Empty for text that isn't a JSON object. */
37
+ export function parseAssetDimensions(text) {
38
+ const sizes = new Map();
39
+ let data;
40
+ try {
41
+ data = JSON.parse(String(text).replace(/^/, ''));
42
+ } catch {
43
+ return sizes;
44
+ }
45
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return sizes;
46
+ for (const [key, value] of Object.entries(data)) {
47
+ if (!value || typeof value !== 'object' || Array.isArray(value)) continue;
48
+ if (!isSize(value.width) || !isSize(value.height)) continue;
49
+ sizes.set(key, { width: value.width, height: value.height });
50
+ }
51
+ return sizes;
52
+ }
53
+
54
+ // Per project, parsed again only when the file changes - `writedocs dev`
55
+ // keeps running while it's edited.
56
+ const loaded = new Map();
57
+
58
+ function dimensionsFor(contentDir) {
59
+ const file = path.join(contentDir, ...ASSET_DIMENSIONS_FILE.split('/'));
60
+ let stamp;
61
+ try {
62
+ const stat = fs.statSync(file);
63
+ stamp = `${stat.mtimeMs}:${stat.size}`;
64
+ } catch {
65
+ loaded.delete(contentDir);
66
+ return null;
67
+ }
68
+ const known = loaded.get(contentDir);
69
+ if (known?.stamp === stamp) return known.sizes;
70
+ let sizes;
71
+ try {
72
+ sizes = parseAssetDimensions(fs.readFileSync(file, 'utf8'));
73
+ } catch {
74
+ sizes = new Map();
75
+ }
76
+ loaded.set(contentDir, { stamp, sizes });
77
+ return sizes;
78
+ }
79
+
80
+ /** `{ width, height }` for the image file at `file` (an absolute path) when
81
+ * the project's asset-dimensions.json lists it, else null. */
82
+ export function providedImageSize(file, contentDir) {
83
+ if (!file || !contentDir) return null;
84
+ const sizes = dimensionsFor(contentDir);
85
+ if (!sizes || sizes.size === 0) return null;
86
+ const relative = path.relative(contentDir, file);
87
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return null;
88
+ return sizes.get(relative.split(path.sep).join('/')) ?? null;
89
+ }
@@ -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(