@writedocs/generator 0.10.14 → 0.10.15

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,116 +1,125 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
- import { readConfigText } from '../lib/config-file.js';
4
-
5
- // Astro's own `output: 'static'` redirects (both writedocs.json's `redirects`
6
- // feature and the automatic "/" -> first-nav-page redirect in
7
- // [...slug].astro) are never real server/edge redirects - with no adapter
8
- // installed, Astro can only ever emit a client-side
9
- // `<meta http-equiv="refresh">` page (see redirectSchema's own comment in
10
- // lib/config.ts for why `permanent`/status-code isn't even offered as a
11
- // config option). That page is a real, working redirect, but it's a flash
12
- // of unstyled content before the browser honors the meta-refresh - visibly
13
- // bad on a deployed site, and exactly what a reader lands on for a second
14
- // or more depending on network/host latency.
15
- //
16
- // Cloudflare Pages and Netlify both read a `_redirects` file at the root
17
- // of the deployed output and turn each line into a real edge-level
18
- // redirect - no page ever renders, no flash. This step generates that file
19
- // as a purely additive improvement: hosts that honor `_redirects` get an
20
- // instant real redirect, and every other static host (S3, GitHub Pages,
21
- // etc.) falls back to the meta-refresh page Astro already generates, which
22
- // keeps working exactly as before. Neither this file nor its absence ever
23
- // changes what Astro itself builds.
24
- // `contentDir` rather than a pre-loaded config object: this runs from
25
- // build.js, invoked by plain `node`, not through Astro/Vite's TS
26
- // transform - loadDocsConfig() (lib/config.ts) can't be imported here the
27
- // way astro.config.mjs and every .astro file import it. writedocs.json has
28
- // already been through preflightCheck() (valid JSON) and Astro's own
29
- // loadDocsConfig() call inside astro.config.mjs (schema-valid, or the
30
- // build above would already have failed) by the time this runs, so a
31
- // second, un-validated JSON.parse() here is safe - this only ever reads
32
- // the one `redirects` array back out, nothing that needs zod's defaults
33
- // or transforms.
34
- export function writeRedirectsFile(distDir, contentDir) {
35
- const writedocsJson = JSON.parse(readConfigText(contentDir));
36
- const redirects = writedocsJson.redirects ?? [];
37
- const lines = [];
38
-
39
- // writedocs.json's own `redirects` array - one line per entry, always 301
40
- // (there's nowhere else in this project to source a status code from;
41
- // see redirectSchema's comment in lib/config.ts on why the schema itself
42
- // has no field for one - a redirect a site author deliberately
43
- // configured is safe to treat as permanent).
44
- for (const { source, destination } of redirects) {
45
- lines.push(`${source} ${destination} 301`);
46
- }
47
-
48
- // The automatic root "/" redirect (see the `rootRedirect` block in
49
- // [...slug].astro's getStaticPaths()) isn't reachable from here without
50
- // re-deriving the same first-nav-page resolution Astro already did -
51
- // instead, read it straight back out of the meta-refresh tag in the
52
- // already-built dist/index.html. If writedocs.json already defines its own
53
- // `/` redirect above, that one wins (first match wins in `_redirects`,
54
- // and it's already listed first) - skip the automatic one entirely
55
- // rather than emit a second, unreachable rule for the same path.
56
- const hasExplicitRootRedirect = redirects.some((r) => r.source === '/');
57
- const indexHtmlPath = path.join(distDir, 'index.html');
58
- if (!hasExplicitRootRedirect && fs.existsSync(indexHtmlPath)) {
59
- const html = fs.readFileSync(indexHtmlPath, 'utf8');
60
- const match = html.match(/<meta http-equiv="refresh" content="\d+;\s*url=([^"]+)"/i);
61
- // 302, not 301: see [...slug].astro - a browser keeps a 301 for good,
62
- // and "/" stops redirecting once the site gets a home page.
63
- if (match) lines.push(`/ ${match[1]} 302`);
64
- }
65
-
66
- // Folder addresses redirecting to the first page under them
67
- // (lib/folder-redirects.js). Read back from the built pages like "/"
68
- // above: Astro writes a temporary (302) redirect's page with a 2-second
69
- // refresh and a permanent one's with 0 - writedocs.json's own redirects
70
- // and `url` pages are permanent, so the 2-second ones are exactly the
71
- // automatic folder redirects. (Read before rewrite-redirect-pages.js makes
72
- // every redirect page go at once.)
73
- for (const { url, target } of temporaryRedirectPages(distDir)) {
74
- lines.push(`${url} ${target} 302`, `${url.replace(/\/$/, '')} ${target} 302`);
75
- }
76
-
77
- if (lines.length === 0) return;
78
-
79
- const generated = [
80
- '# Generated by writedocs (see src/cli/write-redirects-file.js).',
81
- '# Gives Cloudflare Pages / Netlify a real edge redirect for the same',
82
- "# paths Astro's own static-mode <meta http-equiv=\"refresh\"> pages",
83
- '# already cover - other static hosts keep using those pages as-is.',
84
- ...lines,
85
- '',
86
- ].join('\n');
87
-
88
- const redirectsPath = path.join(distDir, '_redirects');
89
- // A hand-written public/_redirects is already copied into dist by Astro
90
- // by this point - preserve it (and its priority: first match wins) by
91
- // appending after it rather than overwriting.
92
- const existing = fs.existsSync(redirectsPath) ? fs.readFileSync(redirectsPath, 'utf8').replace(/\s*$/, '\n\n') : '';
93
- fs.writeFileSync(redirectsPath, existing + generated);
94
- }
95
-
96
- /** Astro's pages for temporary redirects below the site's root, as
97
- * `{ url: "/docs/creator/", target }`. */
98
- function temporaryRedirectPages(distDir) {
99
- const found = [];
100
- const walk = (dir) => {
101
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
102
- const full = path.join(dir, entry.name);
103
- if (entry.isDirectory()) {
104
- if (!['_astro', 'pagefind', 'pagefind-spaces'].includes(entry.name)) walk(full);
105
- continue;
106
- }
107
- if (entry.name !== 'index.html' || dir === distDir) continue;
108
- const html = fs.readFileSync(full, 'utf8');
109
- if (!html.includes('<title>Redirecting to:')) continue;
110
- const match = html.match(/<meta http-equiv="refresh" content="2;\s*url=([^"]+)"/i);
111
- if (match) found.push({ url: `/${path.relative(distDir, dir).split(path.sep).join('/')}/`, target: match[1] });
112
- }
113
- };
114
- walk(distDir);
115
- return found.sort((a, b) => a.url.localeCompare(b.url));
116
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readConfigText } from '../lib/config-file.js';
4
+ import { readMovedApiPages } from '../lib/moved-api-pages.js';
5
+
6
+ // Astro's own `output: 'static'` redirects (both writedocs.json's `redirects`
7
+ // feature and the automatic "/" -> first-nav-page redirect in
8
+ // [...slug].astro) are never real server/edge redirects - with no adapter
9
+ // installed, Astro can only ever emit a client-side
10
+ // `<meta http-equiv="refresh">` page (see redirectSchema's own comment in
11
+ // lib/config.ts for why `permanent`/status-code isn't even offered as a
12
+ // config option). That page is a real, working redirect, but it's a flash
13
+ // of unstyled content before the browser honors the meta-refresh - visibly
14
+ // bad on a deployed site, and exactly what a reader lands on for a second
15
+ // or more depending on network/host latency.
16
+ //
17
+ // Cloudflare Pages and Netlify both read a `_redirects` file at the root
18
+ // of the deployed output and turn each line into a real edge-level
19
+ // redirect - no page ever renders, no flash. This step generates that file
20
+ // as a purely additive improvement: hosts that honor `_redirects` get an
21
+ // instant real redirect, and every other static host (S3, GitHub Pages,
22
+ // etc.) falls back to the meta-refresh page Astro already generates, which
23
+ // keeps working exactly as before. Neither this file nor its absence ever
24
+ // changes what Astro itself builds.
25
+ // `contentDir` rather than a pre-loaded config object: this runs from
26
+ // build.js, invoked by plain `node`, not through Astro/Vite's TS
27
+ // transform - loadDocsConfig() (lib/config.ts) can't be imported here the
28
+ // way astro.config.mjs and every .astro file import it. writedocs.json has
29
+ // already been through preflightCheck() (valid JSON) and Astro's own
30
+ // loadDocsConfig() call inside astro.config.mjs (schema-valid, or the
31
+ // build above would already have failed) by the time this runs, so a
32
+ // second, un-validated JSON.parse() here is safe - this only ever reads
33
+ // the one `redirects` array back out, nothing that needs zod's defaults
34
+ // or transforms.
35
+ export function writeRedirectsFile(distDir, contentDir) {
36
+ const writedocsJson = JSON.parse(readConfigText(contentDir));
37
+ const redirects = writedocsJson.redirects ?? [];
38
+ const lines = [];
39
+
40
+ // writedocs.json's own `redirects` array - one line per entry, always 301
41
+ // (there's nowhere else in this project to source a status code from;
42
+ // see redirectSchema's comment in lib/config.ts on why the schema itself
43
+ // has no field for one - a redirect a site author deliberately
44
+ // configured is safe to treat as permanent).
45
+ for (const { source, destination } of redirects) {
46
+ lines.push(`${source} ${destination} 301`);
47
+ }
48
+ // Generated API pages that changed address (lib/moved-api-pages.js) -
49
+ // after the site's own, which win for the same address (first match).
50
+ // With and without the trailing slash: `_redirects` matches the path
51
+ // as requested.
52
+ for (const { source, destination } of readMovedApiPages(contentDir)) {
53
+ if (redirects.some((r) => r.source.replace(/\/+$/, '') === source)) continue;
54
+ lines.push(`${source} ${destination} 301`, `${source}/ ${destination} 301`);
55
+ }
56
+
57
+ // The automatic root "/" redirect (see the `rootRedirect` block in
58
+ // [...slug].astro's getStaticPaths()) isn't reachable from here without
59
+ // re-deriving the same first-nav-page resolution Astro already did -
60
+ // instead, read it straight back out of the meta-refresh tag in the
61
+ // already-built dist/index.html. If writedocs.json already defines its own
62
+ // `/` redirect above, that one wins (first match wins in `_redirects`,
63
+ // and it's already listed first) - skip the automatic one entirely
64
+ // rather than emit a second, unreachable rule for the same path.
65
+ const hasExplicitRootRedirect = redirects.some((r) => r.source === '/');
66
+ const indexHtmlPath = path.join(distDir, 'index.html');
67
+ if (!hasExplicitRootRedirect && fs.existsSync(indexHtmlPath)) {
68
+ const html = fs.readFileSync(indexHtmlPath, 'utf8');
69
+ const match = html.match(/<meta http-equiv="refresh" content="\d+;\s*url=([^"]+)"/i);
70
+ // 302, not 301: see [...slug].astro - a browser keeps a 301 for good,
71
+ // and "/" stops redirecting once the site gets a home page.
72
+ if (match) lines.push(`/ ${match[1]} 302`);
73
+ }
74
+
75
+ // Folder addresses redirecting to the first page under them
76
+ // (lib/folder-redirects.js). Read back from the built pages like "/"
77
+ // above: Astro writes a temporary (302) redirect's page with a 2-second
78
+ // refresh and a permanent one's with 0 - writedocs.json's own redirects
79
+ // and `url` pages are permanent, so the 2-second ones are exactly the
80
+ // automatic folder redirects. (Read before rewrite-redirect-pages.js makes
81
+ // every redirect page go at once.)
82
+ for (const { url, target } of temporaryRedirectPages(distDir)) {
83
+ lines.push(`${url} ${target} 302`, `${url.replace(/\/$/, '')} ${target} 302`);
84
+ }
85
+
86
+ if (lines.length === 0) return;
87
+
88
+ const generated = [
89
+ '# Generated by writedocs (see src/cli/write-redirects-file.js).',
90
+ '# Gives Cloudflare Pages / Netlify a real edge redirect for the same',
91
+ "# paths Astro's own static-mode <meta http-equiv=\"refresh\"> pages",
92
+ '# already cover - other static hosts keep using those pages as-is.',
93
+ ...lines,
94
+ '',
95
+ ].join('\n');
96
+
97
+ const redirectsPath = path.join(distDir, '_redirects');
98
+ // A hand-written public/_redirects is already copied into dist by Astro
99
+ // by this point - preserve it (and its priority: first match wins) by
100
+ // appending after it rather than overwriting.
101
+ const existing = fs.existsSync(redirectsPath) ? fs.readFileSync(redirectsPath, 'utf8').replace(/\s*$/, '\n\n') : '';
102
+ fs.writeFileSync(redirectsPath, existing + generated);
103
+ }
104
+
105
+ /** Astro's pages for temporary redirects below the site's root, as
106
+ * `{ url: "/docs/creator/", target }`. */
107
+ function temporaryRedirectPages(distDir) {
108
+ const found = [];
109
+ const walk = (dir) => {
110
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
111
+ const full = path.join(dir, entry.name);
112
+ if (entry.isDirectory()) {
113
+ if (!['_astro', 'pagefind', 'pagefind-spaces'].includes(entry.name)) walk(full);
114
+ continue;
115
+ }
116
+ if (entry.name !== 'index.html' || dir === distDir) continue;
117
+ const html = fs.readFileSync(full, 'utf8');
118
+ if (!html.includes('<title>Redirecting to:')) continue;
119
+ const match = html.match(/<meta http-equiv="refresh" content="2;\s*url=([^"]+)"/i);
120
+ if (match) found.push({ url: `/${path.relative(distDir, dir).split(path.sep).join('/')}/`, target: match[1] });
121
+ }
122
+ };
123
+ walk(distDir);
124
+ return found.sort((a, b) => a.url.localeCompare(b.url));
125
+ }
@@ -1,5 +1,6 @@
1
1
  ---
2
2
  import { extraClasses } from './class-names';
3
+ import { imageFileFor, imageSize } from '../lib/image-size.js';
3
4
  // Block-level (own line, centered) - unlike Hint (inline/text-level),
4
5
  // this is meant to be dropped in on its own the way Callout/Card are.
5
6
  //
@@ -60,8 +61,23 @@ interface Props {
60
61
  // lib/image-zoom-rules.js handles both cases identically rather than
61
62
  // needing to special-case this component.
62
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";
63
69
  }
64
- const { src, srcDark, size, alt = "", caption, noZoom } = Astro.props as Props;
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);
65
81
  const sizeStyle = size ? `--wd-image-size:${size}` : undefined;
66
82
  ---
67
83
 
@@ -69,8 +85,8 @@ const sizeStyle = size ? `--wd-image-size:${size}` : undefined;
69
85
  class:list={["wd-image-figure", caption && "wd-image-figure-framed", srcDark && "wd-image-has-dark", extraClasses(Astro.props)]}
70
86
  style={sizeStyle}
71
87
  >
72
- <img src={src} alt={alt} class="wd-image wd-image-light" nozoom={noZoom || undefined} />
73
- {srcDark && <img src={srcDark} alt={alt} class="wd-image wd-image-dark" nozoom={noZoom || undefined} />}
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} />}
74
90
  {caption && <figcaption class="wd-image-caption">{caption}</figcaption>}
75
91
  </figure>
76
92
  <style>