@writedocs/generator 0.10.19 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/astro.config.mjs +32 -8
  2. package/package.json +96 -93
  3. package/src/cli/base-path-layout.js +44 -0
  4. package/src/cli/build.js +177 -168
  5. package/src/cli/check-built-styles.js +41 -33
  6. package/src/cli/dev.js +261 -244
  7. package/src/cli/generate-api-pages.js +9 -5
  8. package/src/cli/page-list-watch.js +69 -66
  9. package/src/cli/run-pagefind.js +154 -148
  10. package/src/cli/write-mcp-files.js +103 -96
  11. package/src/cli/write-redirects-file.js +25 -8
  12. package/src/components/AppIcon.astro +51 -50
  13. package/src/components/Card.astro +193 -192
  14. package/src/components/CopyPageMenu.astro +374 -370
  15. package/src/components/Hint.astro +188 -187
  16. package/src/components/Icon.astro +72 -71
  17. package/src/components/Image.astro +165 -164
  18. package/src/components/Tile.astro +67 -66
  19. package/src/components/Video.astro +137 -136
  20. package/src/layout/BaseLayout.astro +21 -12
  21. package/src/layout/components/AnalyticsScripts.astro +6 -2
  22. package/src/layout/components/Breadcrumbs.astro +98 -97
  23. package/src/layout/components/ConsentBanner.astro +119 -118
  24. package/src/layout/components/MobileMenu.astro +229 -228
  25. package/src/layout/components/NavTree.astro +393 -392
  26. package/src/layout/components/Sidebar.astro +232 -231
  27. package/src/layout/components/SiteFooter.astro +87 -86
  28. package/src/layout/components/TopBar.astro +386 -385
  29. package/src/lib/agent-markdown.js +164 -162
  30. package/src/lib/asset-dimensions.js +89 -0
  31. package/src/lib/base-path.js +90 -0
  32. package/src/lib/config-schema.js +10 -0
  33. package/src/lib/config-schema.ts +17 -0
  34. package/src/lib/config.ts +1314 -1289
  35. package/src/lib/consent.js +108 -102
  36. package/src/lib/image-size.js +152 -140
  37. package/src/lib/json-schema-descriptions.js +1 -0
  38. package/src/lib/link-check.js +42 -4
  39. package/src/lib/llms-index.ts +90 -88
  40. package/src/lib/mcp-dev-integration.js +65 -60
  41. package/src/lib/mcp-index.ts +102 -101
  42. package/src/lib/pages.js +312 -304
  43. package/src/lib/project-files-integration.js +116 -61
  44. package/src/lib/project-files.js +137 -126
  45. package/src/lib/project-ignore.js +46 -0
  46. package/src/lib/rehype-base-path.js +62 -0
  47. package/src/lib/rehype-image-loading.js +71 -71
  48. package/src/lib/robots-txt.js +21 -16
  49. package/src/lib/seo-tags.js +155 -140
  50. package/src/lib/site-base.ts +27 -0
  51. package/src/lib/styles-asset-integration.js +58 -12
  52. package/src/lib/wdignore-cases.json +195 -0
  53. package/src/lib/wdignore.js +177 -0
  54. package/src/pages/404.astro +63 -62
  55. package/src/pages/[...slug].astro +1604 -1597
  56. package/src/pages/[...slug].md.ts +93 -93
  57. package/src/pages/llms-full.txt.ts +88 -86
  58. package/src/scripts/search.ts +241 -237
  59. package/writedocs.schema.json +6 -0
@@ -1,61 +1,116 @@
1
- // Two build steps around the files a project publishes as they are (see
2
- // lib/project-files.js for which):
3
- //
4
- // publishProjectFiles() - copies each one into the build output at its own
5
- // path. Never over a file that's already there: a page the build
6
- // rendered, or the same address in public/, wins. It has to come before
7
- // the sitemap integration in astro.config.mjs's `integrations`, so a
8
- // project's own sitemap.xml is in place when singleSitemapFile() decides
9
- // whether to write the generated one there.
10
- // generatedRobotsTxt() - writes robots.txt when the project didn't bring
11
- // one (lib/robots-txt.js). After the sitemap integration, so it can name
12
- // the sitemap file the build ended up with.
13
- //
14
- // `writedocs dev` serves the same files straight from the project
15
- // (lib/styles-asset-integration.js); it has no generated robots.txt.
16
- import fs from 'node:fs';
17
- import path from 'node:path';
18
- import { fileURLToPath } from 'node:url';
19
- import { findPublishedFiles, readSpecPaths } from './project-files.js';
20
- import { robotsTxt } from './robots-txt.js';
21
- import { isNoindex } from './seo-tags.js';
22
- import { report } from './cli-report.js';
23
-
24
- export function publishProjectFiles(contentDir) {
25
- return {
26
- name: 'writedocs-publish-project-files',
27
- hooks: {
28
- 'astro:build:done': ({ dir }) => {
29
- const outDir = fileURLToPath(dir);
30
- let copied = 0;
31
- for (const rel of findPublishedFiles(contentDir, { specs: readSpecPaths(contentDir) })) {
32
- const segments = rel.split('/');
33
- const outPath = path.join(outDir, ...segments);
34
- if (fs.existsSync(outPath)) continue;
35
- fs.mkdirSync(path.dirname(outPath), { recursive: true });
36
- fs.copyFileSync(path.join(contentDir, ...segments), outPath);
37
- copied += 1;
38
- }
39
- report('debug', `Published ${copied} project file(s) as they are.`);
40
- },
41
- },
42
- };
43
- }
44
-
45
- export function generatedRobotsTxt({ siteUrl, seo }) {
46
- return {
47
- name: 'writedocs-robots-txt',
48
- hooks: {
49
- 'astro:build:done': ({ dir }) => {
50
- const outDir = fileURLToPath(dir);
51
- const target = path.join(outDir, 'robots.txt');
52
- if (fs.existsSync(target)) {
53
- report('debug', 'The project has its own robots.txt - kept as it is.');
54
- return;
55
- }
56
- const sitemap = ['sitemap.xml', 'sitemap-index.xml'].find((name) => fs.existsSync(path.join(outDir, name))) ?? null;
57
- fs.writeFileSync(target, robotsTxt({ siteUrl, sitemap, noindex: isNoindex(seo) }));
58
- },
59
- },
60
- };
61
- }
1
+ // Three build steps around the files a project publishes as they are (see
2
+ // lib/project-files.js for which):
3
+ //
4
+ // removeIgnoredPublicFiles() - Astro copies public/ whole into the build
5
+ // output. This takes out again the files in it that the project's ignore
6
+ // rules leave out (lib/wdignore.js): a key or a .env put there by
7
+ // mistake, or anything the project's `.wdignore` names. Part of
8
+ // publishProjectFiles()'s hook, before it copies anything.
9
+ // publishProjectFiles() - copies each one into the build output at its own
10
+ // path. Never over a file that's already there: a page the build
11
+ // rendered, or the same address in public/, wins. It has to come before
12
+ // the sitemap integration in astro.config.mjs's `integrations`, so a
13
+ // project's own sitemap.xml is in place when singleSitemapFile() decides
14
+ // whether to write the generated one there.
15
+ // generatedRobotsTxt() - writes robots.txt when the project didn't bring
16
+ // one (lib/robots-txt.js). After the sitemap integration, so it can name
17
+ // the sitemap file the build ended up with.
18
+ //
19
+ // `writedocs dev` serves the same files straight from the project
20
+ // (lib/styles-asset-integration.js); it has no generated robots.txt.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+ import { fileURLToPath } from 'node:url';
24
+ import { findPublishedFiles, readSpecPaths } from './project-files.js';
25
+ import { projectIgnore } from './project-ignore.js';
26
+ import { robotsTxt } from './robots-txt.js';
27
+ import { isNoindex } from './seo-tags.js';
28
+ import { report } from './cli-report.js';
29
+
30
+ /** Every file under `dir`, as POSIX paths from it. */
31
+ function listFiles(dir, relBase = '') {
32
+ let entries;
33
+ try {
34
+ entries = fs.readdirSync(dir, { withFileTypes: true });
35
+ } catch {
36
+ return [];
37
+ }
38
+ const found = [];
39
+ for (const entry of entries) {
40
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
41
+ if (entry.isDirectory()) found.push(...listFiles(path.join(dir, entry.name), rel));
42
+ else if (entry.isFile()) found.push(rel);
43
+ }
44
+ return found;
45
+ }
46
+
47
+ /** Removes from the build output the files of public/ that the project's
48
+ * ignore rules leave out, and the folders that empties. Only a file that's
49
+ * still the copy of the one in public/ is removed - a page the build
50
+ * rendered at the same address stays. Returns the removed paths (POSIX,
51
+ * from the output's root). */
52
+ export function removeIgnoredPublicFiles(contentDir, outDir, rules = projectIgnore(contentDir)) {
53
+ const publicDir = path.join(contentDir, 'public');
54
+ const removed = [];
55
+ for (const rel of listFiles(publicDir)) {
56
+ if (!rules.ignores(`public/${rel}`)) continue;
57
+ const segments = rel.split('/');
58
+ const outPath = path.join(outDir, ...segments);
59
+ try {
60
+ if (!fs.readFileSync(outPath).equals(fs.readFileSync(path.join(publicDir, ...segments)))) continue;
61
+ fs.unlinkSync(outPath);
62
+ } catch {
63
+ continue; // not in the output
64
+ }
65
+ removed.push(rel);
66
+ for (let depth = segments.length - 1; depth > 0; depth--) {
67
+ try {
68
+ fs.rmdirSync(path.join(outDir, ...segments.slice(0, depth))); // fails unless empty
69
+ } catch {
70
+ break;
71
+ }
72
+ }
73
+ }
74
+ return removed;
75
+ }
76
+
77
+ export function publishProjectFiles(contentDir) {
78
+ return {
79
+ name: 'writedocs-publish-project-files',
80
+ hooks: {
81
+ 'astro:build:done': ({ dir }) => {
82
+ const outDir = fileURLToPath(dir);
83
+ const removed = removeIgnoredPublicFiles(contentDir, outDir);
84
+ if (removed.length) report('debug', `Left out ${removed.length} file(s) of public/ that the ignore rules name.`);
85
+ let copied = 0;
86
+ for (const rel of findPublishedFiles(contentDir, { specs: readSpecPaths(contentDir) })) {
87
+ const segments = rel.split('/');
88
+ const outPath = path.join(outDir, ...segments);
89
+ if (fs.existsSync(outPath)) continue;
90
+ fs.mkdirSync(path.dirname(outPath), { recursive: true });
91
+ fs.copyFileSync(path.join(contentDir, ...segments), outPath);
92
+ copied += 1;
93
+ }
94
+ report('debug', `Published ${copied} project file(s) as they are.`);
95
+ },
96
+ },
97
+ };
98
+ }
99
+
100
+ export function generatedRobotsTxt({ siteUrl, seo, basePath = '' }) {
101
+ return {
102
+ name: 'writedocs-robots-txt',
103
+ hooks: {
104
+ 'astro:build:done': ({ dir }) => {
105
+ const outDir = fileURLToPath(dir);
106
+ const target = path.join(outDir, 'robots.txt');
107
+ if (fs.existsSync(target)) {
108
+ report('debug', 'The project has its own robots.txt - kept as it is.');
109
+ return;
110
+ }
111
+ const sitemap = ['sitemap.xml', 'sitemap-index.xml'].find((name) => fs.existsSync(path.join(outDir, name))) ?? null;
112
+ fs.writeFileSync(target, robotsTxt({ siteUrl, sitemap, noindex: isNoindex(seo), basePath }));
113
+ },
114
+ },
115
+ };
116
+ }
@@ -1,126 +1,137 @@
1
- // Which of a project's files are published as they are, at their own path:
2
- // `robots.txt` at the project root is served at /robots.txt,
3
- // `files/terms.pdf` at /files/terms.pdf - with no `public/` folder to
4
- // create. (A `public/` folder still works, and wins over a file of the same
5
- // address outside it.)
6
- //
7
- // A file is published when its extension is in PUBLISHED_EXTENSIONS and it
8
- // isn't part of how the site is built: writedocs.json and other tooling
9
- // files, an OpenAPI spec the site reads, anything in a dot-folder,
10
- // `node_modules/` or `dist/`. Pages (.md/.mdx), snippets (.jsx/.tsx) and
11
- // the project's .css/.js (loaded into every page - findRootAssets(),
12
- // lib/pages.js) are never published as files: their extensions aren't here.
13
- //
14
- // Used by the build (lib/project-files-integration.js copies them into the
15
- // output), `writedocs dev` (lib/styles-asset-integration.js serves them),
16
- // and `writedocs broken-links` (a link to one isn't broken).
17
- //
18
- // Plain JavaScript with no config.ts import, so scripts/project-files.test.js
19
- // can run it directly.
20
- import fs from 'node:fs';
21
- import path from 'node:path';
22
- import { EXCLUDED_TOP_LEVEL_DIRS } from './pages.js';
23
- import { writedocsTempDir } from './writedocs-temp-dir.js';
24
-
25
- /** Extension -> content type, for every kind of file that's published. */
26
- export const PUBLISHED_TYPES = {
27
- // Images and fonts.
28
- '.svg': 'image/svg+xml',
29
- '.png': 'image/png',
30
- '.jpg': 'image/jpeg',
31
- '.jpeg': 'image/jpeg',
32
- '.gif': 'image/gif',
33
- '.webp': 'image/webp',
34
- '.avif': 'image/avif',
35
- '.ico': 'image/x-icon',
36
- '.woff': 'font/woff',
37
- '.woff2': 'font/woff2',
38
- '.ttf': 'font/ttf',
39
- '.otf': 'font/otf',
40
- // Text and data.
41
- '.txt': 'text/plain; charset=utf-8',
42
- '.xml': 'application/xml',
43
- '.json': 'application/json',
44
- '.csv': 'text/csv; charset=utf-8',
45
- '.webmanifest': 'application/manifest+json',
46
- // Downloads and media.
47
- '.pdf': 'application/pdf',
48
- '.zip': 'application/zip',
49
- '.mp4': 'video/mp4',
50
- '.webm': 'video/webm',
51
- '.mov': 'video/quicktime',
52
- '.mp3': 'audio/mpeg',
53
- '.wav': 'audio/wav',
54
- '.ogg': 'audio/ogg',
55
- };
56
-
57
- /** Files at the project root that configure the site or its tooling. */
58
- const ROOT_CONFIG_FILES = new Set([
59
- 'writedocs.json',
60
- 'docs.json',
61
- 'mint.json',
62
- 'config.json',
63
- 'package.json',
64
- 'package-lock.json',
65
- 'tsconfig.json',
66
- 'jsconfig.json',
67
- 'composer.json',
68
- 'vercel.json',
69
- 'netlify.json',
70
- 'wrangler.json',
71
- // Read by the build, which serves them itself (src/pages/llms*.ts).
72
- 'llms.txt',
73
- 'llms-full.txt',
74
- ]);
75
-
76
- /** Whether the file at `rel` (a POSIX path from the project root) is
77
- * published. `specs` holds the OpenAPI specs the site reads, as paths of
78
- * the same form. */
79
- export function isPublishedFile(rel, { specs = new Set() } = {}) {
80
- const parts = rel.split('/');
81
- if (parts.some((part) => part === '' || part === '.' || part === '..' || part.startsWith('.'))) return false;
82
- if (EXCLUDED_TOP_LEVEL_DIRS.has(parts[0])) return false;
83
- const name = parts[parts.length - 1].toLowerCase();
84
- if (!Object.prototype.hasOwnProperty.call(PUBLISHED_TYPES, path.posix.extname(name))) return false;
85
- if (parts.length === 1 && ROOT_CONFIG_FILES.has(name)) return false;
86
- if (specs.has(rel)) return false;
87
- return true;
88
- }
89
-
90
- /** Every published file in the project, as POSIX paths from its root,
91
- * sorted. */
92
- export function findPublishedFiles(contentDir, options = {}) {
93
- const found = [];
94
- const walk = (dir, relBase) => {
95
- let entries;
96
- try {
97
- entries = fs.readdirSync(dir, { withFileTypes: true });
98
- } catch {
99
- return;
100
- }
101
- for (const entry of entries) {
102
- if (entry.name.startsWith('.')) continue;
103
- const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
104
- if (entry.isDirectory()) {
105
- if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
106
- walk(path.join(dir, entry.name), rel);
107
- } else if (entry.isFile() && isPublishedFile(rel, options)) {
108
- found.push(rel);
109
- }
110
- }
111
- };
112
- walk(contentDir, '');
113
- return found.sort();
114
- }
115
-
116
- /** The OpenAPI specs the site reads: generateApiPages() (src/cli/
117
- * generate-api-pages.js) lists them before each build and preview. An
118
- * empty set when it hasn't run. */
119
- export function readSpecPaths(contentDir) {
120
- try {
121
- const list = JSON.parse(fs.readFileSync(path.join(writedocsTempDir(contentDir), 'openapi', 'specs.json'), 'utf-8'));
122
- return new Set(Array.isArray(list) ? list : []);
123
- } catch {
124
- return new Set();
125
- }
126
- }
1
+ // Which of a project's files are published as they are, at their own path:
2
+ // `robots.txt` at the project root is served at /robots.txt,
3
+ // `files/terms.pdf` at /files/terms.pdf - with no `public/` folder to
4
+ // create. (A `public/` folder still works, and wins over a file of the same
5
+ // address outside it.)
6
+ //
7
+ // A file is published when its extension is in PUBLISHED_TYPES, it isn't
8
+ // what the site is built from (writedocs.json, llms.txt, an OpenAPI spec the
9
+ // site reads) and the project's ignore rules don't leave it out
10
+ // (lib/wdignore.js: the default exclusions - dot-files and dot-folders,
11
+ // package.json, node_modules/, keys, databases ... - plus the project's own
12
+ // `.wdignore`). Pages (.md/.mdx), snippets (.jsx/.tsx) and the project's
13
+ // .css/.js (loaded into every page - findRootAssets(), lib/pages.js) are
14
+ // never published as files: their extensions aren't here.
15
+ //
16
+ // A `.wdignore` line starting with `!` can bring back a default exclusion
17
+ // (`!.well-known/`), and the file is then published - if its extension is
18
+ // in PUBLISHED_TYPES. It can't bring back what LOCKED_PATTERNS names, nor
19
+ // the folders in EXCLUDED_TOP_LEVEL_DIRS, which the build itself owns.
20
+ //
21
+ // Used by the build (lib/project-files-integration.js copies them into the
22
+ // output), `writedocs dev` (lib/styles-asset-integration.js serves them),
23
+ // and `writedocs broken-links` (a link to one isn't broken).
24
+ //
25
+ // Plain JavaScript with no config.ts import, so scripts/project-files.test.js
26
+ // can run it directly.
27
+ import fs from 'node:fs';
28
+ import path from 'node:path';
29
+ import { EXCLUDED_TOP_LEVEL_DIRS } from './pages.js';
30
+ import { writedocsTempDir } from './writedocs-temp-dir.js';
31
+ import { createWdignore } from './wdignore.js';
32
+ import { projectIgnore } from './project-ignore.js';
33
+
34
+ /** Extension -> content type, for every kind of file that's published. */
35
+ export const PUBLISHED_TYPES = {
36
+ // Images and fonts.
37
+ '.svg': 'image/svg+xml',
38
+ '.png': 'image/png',
39
+ '.jpg': 'image/jpeg',
40
+ '.jpeg': 'image/jpeg',
41
+ '.gif': 'image/gif',
42
+ '.webp': 'image/webp',
43
+ '.avif': 'image/avif',
44
+ '.ico': 'image/x-icon',
45
+ '.woff': 'font/woff',
46
+ '.woff2': 'font/woff2',
47
+ '.ttf': 'font/ttf',
48
+ '.otf': 'font/otf',
49
+ // Text and data.
50
+ '.txt': 'text/plain; charset=utf-8',
51
+ '.xml': 'application/xml',
52
+ '.json': 'application/json',
53
+ '.csv': 'text/csv; charset=utf-8',
54
+ '.webmanifest': 'application/manifest+json',
55
+ // Downloads and media.
56
+ '.pdf': 'application/pdf',
57
+ '.zip': 'application/zip',
58
+ '.mp4': 'video/mp4',
59
+ '.webm': 'video/webm',
60
+ '.mov': 'video/quicktime',
61
+ '.mp3': 'audio/mpeg',
62
+ '.wav': 'audio/wav',
63
+ '.ogg': 'audio/ogg',
64
+ };
65
+
66
+ /** Files at the project root that the site is built from: read by the
67
+ * build, never published, and not something `.wdignore` decides (tooling
68
+ * files - package.json, tsconfig.json ... - are default exclusions there). */
69
+ const ROOT_CONFIG_FILES = new Set([
70
+ 'writedocs.json',
71
+ 'docs.json',
72
+ 'mint.json',
73
+ 'config.json',
74
+ // Read by the build, which serves them itself (src/pages/llms*.ts).
75
+ 'llms.txt',
76
+ 'llms-full.txt',
77
+ ]);
78
+
79
+ /** The rules of a project with no `.wdignore`. */
80
+ const DEFAULT_RULES = createWdignore('');
81
+
82
+ /** Whether the file at `rel` (a POSIX path from the project root) is
83
+ * published. `specs` holds the OpenAPI specs the site reads, as paths of
84
+ * the same form; `rules` the project's ignore rules (projectIgnore(),
85
+ * lib/project-ignore.js) - the default exclusions alone when not given. */
86
+ export function isPublishedFile(rel, { specs = new Set(), rules = DEFAULT_RULES } = {}) {
87
+ const parts = rel.split('/');
88
+ if (parts.some((part) => part === '' || part === '.' || part === '..')) return false;
89
+ if (EXCLUDED_TOP_LEVEL_DIRS.has(parts[0])) return false;
90
+ const name = parts[parts.length - 1].toLowerCase();
91
+ if (!Object.prototype.hasOwnProperty.call(PUBLISHED_TYPES, path.posix.extname(name))) return false;
92
+ if (parts.length === 1 && ROOT_CONFIG_FILES.has(name)) return false;
93
+ if (specs.has(rel)) return false;
94
+ if (rules.ignores(rel)) return false;
95
+ return true;
96
+ }
97
+
98
+ /** Every published file in the project, as POSIX paths from its root,
99
+ * sorted. Reads the project's `.wdignore` unless `options.rules` is given. */
100
+ export function findPublishedFiles(contentDir, options = {}) {
101
+ const rules = options.rules ?? projectIgnore(contentDir);
102
+ const found = [];
103
+ const walk = (dir, relBase) => {
104
+ let entries;
105
+ try {
106
+ entries = fs.readdirSync(dir, { withFileTypes: true });
107
+ } catch {
108
+ return;
109
+ }
110
+ for (const entry of entries) {
111
+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;
112
+ if (entry.isDirectory()) {
113
+ if (relBase === '' && EXCLUDED_TOP_LEVEL_DIRS.has(entry.name)) continue;
114
+ // Nothing inside an ignored folder can be brought back (the
115
+ // .gitignore rule), so there's no need to look in it.
116
+ if (rules.ignores(rel, true)) continue;
117
+ walk(path.join(dir, entry.name), rel);
118
+ } else if (entry.isFile() && isPublishedFile(rel, { ...options, rules })) {
119
+ found.push(rel);
120
+ }
121
+ }
122
+ };
123
+ walk(contentDir, '');
124
+ return found.sort();
125
+ }
126
+
127
+ /** The OpenAPI specs the site reads: generateApiPages() (src/cli/
128
+ * generate-api-pages.js) lists them before each build and preview. An
129
+ * empty set when it hasn't run. */
130
+ export function readSpecPaths(contentDir) {
131
+ try {
132
+ const list = JSON.parse(fs.readFileSync(path.join(writedocsTempDir(contentDir), 'openapi', 'specs.json'), 'utf-8'));
133
+ return new Set(Array.isArray(list) ? list : []);
134
+ } catch {
135
+ return new Set();
136
+ }
137
+ }
@@ -0,0 +1,46 @@
1
+ // The ignore rules of one project, read from disk: lib/wdignore.js (the
2
+ // rules themselves, with no file access - the WriteDocs platform uses that
3
+ // module as it is) plus the project's `.wdignore`.
4
+ //
5
+ // Everything that decides what a project publishes or reads as content asks
6
+ // here: published files (lib/project-files.js), pages and the project's
7
+ // CSS/JS (lib/pages.js), images and fonts a page names
8
+ // (lib/styles-asset-integration.js, lib/image-size.js) and
9
+ // `writedocs broken-links` (lib/link-check.js).
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { createWdignore, WDIGNORE_FILE } from './wdignore.js';
13
+
14
+ // Per project, built again only when `.wdignore` changes - `writedocs dev`
15
+ // keeps running while it's edited.
16
+ const loaded = new Map();
17
+
18
+ /** The rules for the project at `contentDir`: `{ ignores(relPath,
19
+ * isDirectory), isLocked(relPath, isDirectory) }` - see createWdignore(). */
20
+ export function projectIgnore(contentDir) {
21
+ const file = path.join(contentDir, WDIGNORE_FILE);
22
+ let stamp = 'none';
23
+ try {
24
+ const stat = fs.statSync(file);
25
+ if (stat.isFile()) stamp = `${stat.mtimeMs}:${stat.size}`;
26
+ } catch {}
27
+ const known = loaded.get(contentDir);
28
+ if (known?.stamp === stamp) return known.rules;
29
+ let text = '';
30
+ if (stamp !== 'none') {
31
+ try {
32
+ text = fs.readFileSync(file, 'utf8');
33
+ } catch {}
34
+ }
35
+ const rules = createWdignore(text);
36
+ loaded.set(contentDir, { stamp, rules });
37
+ return rules;
38
+ }
39
+
40
+ /** Whether the file at `absolute` is left out of the project at
41
+ * `contentDir`. A file outside the project is. */
42
+ export function isIgnoredFile(absolute, contentDir) {
43
+ const relative = path.relative(path.resolve(contentDir), path.resolve(absolute));
44
+ if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) return true;
45
+ return projectIgnore(contentDir).ignores(relative.split(path.sep).join('/'));
46
+ }
@@ -0,0 +1,62 @@
1
+ // writedocs.json's `basePath` in a page's own content: a link or a picture
2
+ // written from the site's root - `[a](/guides/a)`, `![x](/images/x.png)`,
3
+ // `<a href="/guides/a">`, `<img src="/images/x.png">` - gets the base in
4
+ // front (`/docs/guides/a`), so the author keeps writing site addresses
5
+ // whether or not the site is served under a path. A relative address, a full
6
+ // URL, `#anchor` and `mailto:` stay as written (lib/base-path.js).
7
+ //
8
+ // What it changes: Markdown's own elements (hast `element`), raw HTML in a
9
+ // .md page (`raw`), and HTML tags written in MDX (`mdxJsx*` with a lowercase
10
+ // name) - their href, src, srcset, poster and action. Not a component's
11
+ // props (`<Card href="/a">`): a component writes its own addresses, with
12
+ // siteHref() (lib/site-base.ts), so prefixing here too would give them the
13
+ // base twice. Not a value written as an expression (`href={link}`), which
14
+ // isn't known until the page runs.
15
+ //
16
+ // Runs last among the rehype plugins (astro.config.mjs): rehypeImageLoading
17
+ // reads an image's file by its site address before this changes it.
18
+ import { withBase, srcsetWithBase } from './base-path.js';
19
+
20
+ /** hast property names (camelCase) of the attributes that hold an address. */
21
+ const HAST_URL_PROPERTIES = ['href', 'src', 'poster', 'action', 'formAction'];
22
+ /** The same attributes as written in HTML/JSX. */
23
+ const JSX_URL_ATTRIBUTES = new Set(['href', 'src', 'poster', 'action', 'formAction', 'formaction']);
24
+ const JSX_SRCSET_ATTRIBUTES = new Set(['srcSet', 'srcset']);
25
+
26
+ const isJsx = (node) => node.type === 'mdxJsxFlowElement' || node.type === 'mdxJsxTextElement';
27
+ /** An HTML tag (`a`, `img`), not a component (`Card`, `Tree.Folder`). */
28
+ const isHtmlTag = (name) => typeof name === 'string' && /^[a-z][a-z0-9-]*$/.test(name);
29
+
30
+ /** A raw HTML string with the base in front of each site address in an
31
+ * href, src, poster or action attribute. */
32
+ export function rawHtmlWithBase(base, html) {
33
+ if (!base) return html;
34
+ return html.replace(/(\s(?:href|src|poster|action)\s*=\s*["'])(\/(?!\/))/gi, `$1${base}$2`);
35
+ }
36
+
37
+ export function rehypeBasePath({ base = '' } = {}) {
38
+ return (tree) => {
39
+ if (!base) return;
40
+ const visit = (node) => {
41
+ if (node.type === 'element' && node.properties) {
42
+ const p = node.properties;
43
+ for (const name of HAST_URL_PROPERTIES) {
44
+ if (typeof p[name] === 'string') p[name] = withBase(base, p[name]);
45
+ }
46
+ if (typeof p.srcSet === 'string') p.srcSet = srcsetWithBase(base, p.srcSet);
47
+ // hast keeps srcset as a list of its comma-separated candidates.
48
+ else if (Array.isArray(p.srcSet)) p.srcSet = p.srcSet.map((candidate) => srcsetWithBase(base, candidate));
49
+ } else if (node.type === 'raw' && typeof node.value === 'string') {
50
+ node.value = rawHtmlWithBase(base, node.value);
51
+ } else if (isJsx(node) && isHtmlTag(node.name)) {
52
+ for (const attribute of node.attributes ?? []) {
53
+ if (attribute.type !== 'mdxJsxAttribute' || typeof attribute.value !== 'string') continue;
54
+ if (JSX_URL_ATTRIBUTES.has(attribute.name)) attribute.value = withBase(base, attribute.value);
55
+ else if (JSX_SRCSET_ATTRIBUTES.has(attribute.name)) attribute.value = srcsetWithBase(base, attribute.value);
56
+ }
57
+ }
58
+ if (Array.isArray(node.children)) node.children.forEach(visit);
59
+ };
60
+ visit(tree);
61
+ };
62
+ }