@writedocs/generator 0.13.4 → 0.14.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 (89) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +359 -356
  4. package/package.json +99 -99
  5. package/src/cli/base-path-layout.js +44 -44
  6. package/src/cli/build-auth.js +135 -135
  7. package/src/cli/build.js +223 -203
  8. package/src/cli/check-built-styles.js +41 -41
  9. package/src/cli/convert.js +124 -124
  10. package/src/cli/dev.js +269 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +509 -507
  13. package/src/cli/og-image-worker.js +20 -20
  14. package/src/cli/og-images.js +70 -70
  15. package/src/cli/page-list-watch.js +71 -69
  16. package/src/cli/run-astro.js +97 -97
  17. package/src/cli/run-pagefind.js +154 -154
  18. package/src/cli/write-mcp-files.js +103 -103
  19. package/src/cli/write-redirects-file.js +158 -158
  20. package/src/components/ApiReferencePanel.astro +1792 -1792
  21. package/src/components/AppIcon.astro +51 -51
  22. package/src/components/Card.astro +193 -193
  23. package/src/components/CodeGroup.astro +63 -39
  24. package/src/components/CopyPageMenu.astro +374 -374
  25. package/src/components/Hint.astro +188 -188
  26. package/src/components/Icon.astro +72 -72
  27. package/src/components/Image.astro +165 -165
  28. package/src/components/Tile.astro +67 -67
  29. package/src/components/Video.astro +137 -137
  30. package/src/content.config.ts +219 -203
  31. package/src/layout/BaseLayout.astro +908 -908
  32. package/src/layout/components/AnalyticsScripts.astro +49 -49
  33. package/src/layout/components/Breadcrumbs.astro +98 -98
  34. package/src/layout/components/ConsentBanner.astro +119 -119
  35. package/src/layout/components/MobileMenu.astro +225 -225
  36. package/src/layout/components/NavTree.astro +422 -408
  37. package/src/layout/components/Sidebar.astro +232 -232
  38. package/src/layout/components/SiteFooter.astro +87 -87
  39. package/src/layout/components/TopBar.astro +386 -386
  40. package/src/layout/styles/base.css +332 -326
  41. package/src/layout/styles/mobile-menu.css +285 -285
  42. package/src/lib/agent-markdown.js +164 -164
  43. package/src/lib/asset-dimensions.js +89 -89
  44. package/src/lib/base-path.js +90 -90
  45. package/src/lib/cli-report.js +22 -22
  46. package/src/lib/code-line-numbers.js +13 -0
  47. package/src/lib/config-schema.js +12 -1
  48. package/src/lib/config-schema.ts +2523 -2509
  49. package/src/lib/config.ts +1331 -1316
  50. package/src/lib/consent.js +108 -108
  51. package/src/lib/content-check.js +4 -1
  52. package/src/lib/content-store-reload-integration.js +101 -101
  53. package/src/lib/drafts.js +186 -0
  54. package/src/lib/icon-data-dev.js +53 -53
  55. package/src/lib/image-size.js +152 -152
  56. package/src/lib/json-schema-descriptions.js +228 -228
  57. package/src/lib/link-check.js +553 -544
  58. package/src/lib/llms-index.ts +90 -90
  59. package/src/lib/mcp-dev-integration.js +65 -65
  60. package/src/lib/mcp-index.ts +102 -102
  61. package/src/lib/mintlify-convert.js +605 -605
  62. package/src/lib/moved-api-pages.js +49 -49
  63. package/src/lib/og-cards.js +33 -33
  64. package/src/lib/og-image.js +235 -235
  65. package/src/lib/openapi-dev-status.js +80 -80
  66. package/src/lib/openapi-reload-integration.js +193 -193
  67. package/src/lib/pages.js +346 -312
  68. package/src/lib/project-files-integration.js +116 -116
  69. package/src/lib/project-files.js +137 -137
  70. package/src/lib/rehype-base-path.js +62 -62
  71. package/src/lib/rehype-image-loading.js +71 -71
  72. package/src/lib/robots-txt.js +21 -21
  73. package/src/lib/search-scope.js +44 -44
  74. package/src/lib/selector-placement.js +50 -50
  75. package/src/lib/seo-tags.js +157 -155
  76. package/src/lib/shiki-code-block.js +7 -1
  77. package/src/lib/site-base.ts +27 -27
  78. package/src/lib/styles-asset-integration.js +291 -291
  79. package/src/lib/wdignore-cases.json +195 -195
  80. package/src/lib/wdignore.js +177 -177
  81. package/src/pages/404.astro +63 -63
  82. package/src/pages/[...slug].astro +1773 -1608
  83. package/src/pages/[...slug].md.ts +93 -93
  84. package/src/pages/llms-full.txt.ts +88 -88
  85. package/src/pages/og/[...slug].png.ts +63 -63
  86. package/src/scripts/mobile-menu.ts +80 -80
  87. package/src/scripts/search.ts +245 -245
  88. package/src/scripts/sidebar-scroll.ts +61 -61
  89. package/src/styles/global.css +40 -40
@@ -1,203 +1,219 @@
1
- import { defineCollection } from 'astro:content';
2
- import { glob } from 'astro/loaders';
3
- import type { Loader } from 'astro/loaders';
4
- import fs from 'node:fs';
5
- import path from 'node:path';
6
- import { fileURLToPath, pathToFileURL } from 'node:url';
7
- import { pageFrontmatterSchema, findAllPages } from './lib/config';
8
- import { titleFromPath } from './lib/pages.js';
9
- import { writedocsTempDir } from './lib/writedocs-temp-dir.js';
10
-
11
- const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
12
-
13
- // Astro's glob loader resolves `base` via `new URL(base, root)`. On Windows,
14
- // a raw path string like "C:\foo\docs" gets misparsed by the WHATWG URL
15
- // parser (the drive letter "C:" looks like a URL scheme), which breaks
16
- // downstream `fileURLToPath` calls. Passing an explicit file:// URL sidesteps
17
- // that entirely and works the same on every platform.
18
- //
19
- // Auto-generated OpenAPI stub pages (see generate-api-pages.js) live under
20
- // writedocsTempDir() - an OS-temp-directory location keyed off contentDir,
21
- // not anywhere inside the content directory itself - so they never show up
22
- // mixed in with a site's own hand-written pages, and writedocs never writes
23
- // generated files into a person's own project folder. The same location is
24
- // also where build-time manifests/caches live - see writedocs-temp-dir.js's
25
- // own doc comment. A separate collection (rather than a second base folder
26
- // glued onto `pages` somehow) because Astro's loader API has no supported
27
- // way to point one collection's glob() at two base directories sharing a
28
- // single store without each call's own "delete anything I didn't just see"
29
- // cleanup wiping out the other's entries - [...slug].astro merges both
30
- // collections' entries back into one list at query time instead, which
31
- // sidesteps that entirely.
32
- const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
33
- const generatedDocsBase = pathToFileURL(generatedDocsDir + path.sep);
34
-
35
- // Page frontmatter - defined in lib/config-schema.ts as
36
- // pageFrontmatterSchema, next to writedocs.json's own schema, so
37
- // `writedocs validate` checks every page against exactly the schema the
38
- // build uses (that file compiles to the plain JS validate loads).
39
- const docsSchema = pageFrontmatterSchema;
40
-
41
- /** Wraps another loader so it's skipped entirely - no filesystem scan, no
42
- * "directory doesn't exist"/"no files found" warning - when its own base
43
- * directory doesn't exist yet. Astro requires every collection declared
44
- * in this file to have a loader, but most sites have no OpenAPI groups
45
- * at all (generate-api-pages.js only ever creates a generated-docs/
46
- * directory under writedocsTempDir() when at least one exists), so without this
47
- * the `generatedDocs` collection below would print a spurious warning on
48
- * every single build/dev run for the common case of a site with no
49
- * OpenAPI pages.
50
- *
51
- * Without a watcher, in `writedocs dev` too: the collection is synced when
52
- * the preview starts and then only when lib/openapi-reload-integration.js
53
- * asks (refreshContent()), after writing the pages of an edited spec - in
54
- * the order that keeps the navigation and the pages in step. A watcher of
55
- * its own would sync each page file as it's written, at its own moment
56
- * (and each refresh would add another set of its listeners). */
57
- function skipIfMissing(inner: Loader): Loader {
58
- return {
59
- name: inner.name,
60
- load: async (context) => {
61
- if (!fs.existsSync(generatedDocsBase)) return;
62
- // Left empty: the last spec taken out of writedocs.json while
63
- // `writedocs dev` runs (the folder stays then). glob() would only warn
64
- // about no files and keep the pages it had.
65
- if (!fs.readdirSync(generatedDocsBase, { recursive: true }).some((file) => /\.mdx?$/i.test(String(file)))) {
66
- for (const id of context.store.keys()) context.store.delete(id);
67
- return;
68
- }
69
- return inner.load({ ...withTitleFallback(context), watcher: undefined });
70
- },
71
- };
72
- }
73
-
74
- // A page with no `title` in its frontmatter gets one from its file name,
75
- // before the schema (which requires `title`) sees it - Mintlify's rule, so
76
- // a migrated page that relied on it builds with the same title. See
77
- // titleFromPath() in lib/pages.js; `writedocs validate` applies the same
78
- // default (lib/content-check.js).
79
- type LoaderContext = Parameters<Loader['load']>[0];
80
- function withTitleFallback(context: LoaderContext): LoaderContext {
81
- return {
82
- ...context,
83
- parseData: (props) =>
84
- context.parseData({
85
- ...props,
86
- data:
87
- typeof props.data?.title === 'string'
88
- ? props.data
89
- : { ...props.data, title: titleFromPath(props.filePath ?? props.id) },
90
- }),
91
- };
92
- }
93
-
94
- const generatedDocs = defineCollection({
95
- loader: skipIfMissing(glob({ pattern: '**/*.{md,mdx}', base: generatedDocsBase })),
96
- schema: docsSchema,
97
- });
98
-
99
- // Every hand-written page in the project, wherever it lives - see
100
- // findAllPages() in lib/config.ts for the exact discovery rule (any
101
- // .md/.mdx file with a frontmatter block, the usual build/dependency
102
- // directories excluded - docs/ has no special status, it's scanned like
103
- // any other folder). A single collection covering the whole content
104
- // directory works here (unlike generatedDocs, which needs its own
105
- // separate collection - see that const's own comment) because there's
106
- // only one base to worry about: the content root itself.
107
- //
108
- // The literal file list (rather than a `**/*.{md,mdx}` pattern) is what
109
- // actually implements the frontmatter-based filter: glob()'s `pattern`
110
- // option takes glob patterns, not a predicate function, so the predicate
111
- // has to run first, here, to produce the list glob() then just matches
112
- // literally. Astro's own default id computation, scoped to this same
113
- // content-root base, is what gives a page under docs/ its "docs/..."
114
- // file id and a page at the root its bare file id - see
115
- // fileIdForEntry()'s own comment in lib/config.ts for the one place that
116
- // id computation needs to be independently recovered (once a page's
117
- // frontmatter `slug` has overridden `entry.id` itself).
118
- const contentRootBase = pathToFileURL(contentDir + path.sep);
119
-
120
- /** Wraps astro's own glob() loader so pages are re-discovered live during
121
- * `astro dev`, not just once when this module first evaluates.
122
- *
123
- * The naive approach - `glob({ pattern: findAllPages(contentDir), base })`,
124
- * computed once at module load, as this used to be - works fine for the
125
- * *first* load, but astro's glob loader's own dev-mode watcher only ever
126
- * matches entries against whatever literal pattern list it was constructed
127
- * with (see matchesGlob() in astro's glob.js, called from its `watcher.on(
128
- * 'add', ...)` handler): a file created after that list was computed can
129
- * never match it, so it silently never becomes a page until the dev server
130
- * is restarted and this module re-evaluates findAllPages() from scratch.
131
- * That's the exact bug this wrapper fixes.
132
- *
133
- * A plain wildcard pattern (`**\/*.{md,mdx}`) doesn't work as a substitute,
134
- * either: whether a given .md/.mdx file counts as a page at all depends on
135
- * its *content* (does it have a frontmatter block? - see findAllPages()'s
136
- * own doc comment, this is what lets e.g. snippets/ partials with no
137
- * frontmatter coexist in the content dir without becoming pages
138
- * themselves), not just its path, and glob()'s `pattern` option only does
139
- * path matching - it can't express that filter. Something has to re-run
140
- * findAllPages() itself, content and all, whenever the file set changes.
141
- *
142
- * So: this re-invokes astro's own glob() loader - reusing all of its real
143
- * parsing/rendering/digest-based caching logic rather than reimplementing
144
- * any of that - with a freshly recomputed literal file list every time
145
- * something relevant changes on disk, instead of once. The inner loader's
146
- * own watcher wiring is deliberately skipped each time (`watcher` is
147
- * stripped from the context passed to it) - this loader keeps exactly one
148
- * watcher subscription of its own instead, covering every case uniformly
149
- * (a new page file appearing, one being deleted, frontmatter being added
150
- * to or removed from an existing file, ordinary content edits) rather than
151
- * relying on the inner loader's add/change/unlink handlers, which - as
152
- * above - are only ever bound to whatever the pattern looked like at the
153
- * moment they were registered. */
154
- function livePages(dir: string, base: URL): Loader {
155
- return {
156
- name: 'writedocs-live-pages',
157
- load: async (context) => {
158
- const { watcher, store, logger } = context;
159
-
160
- async function resync() {
161
- const files = findAllPages(dir);
162
- if (files.length === 0) {
163
- // Mirrors the old skipIfEmpty() wrapper: skip calling the inner
164
- // loader entirely (rather than passing it an empty/impossible
165
- // pattern) so astro doesn't print its own "no files found"
166
- // warning for a freshly-scaffolded project with no content yet -
167
- // but still clear out any previously-synced entries, in case a
168
- // page's last file was just deleted mid dev-session rather than
169
- // this being the initial load of an empty project.
170
- for (const id of store.keys()) store.delete(id);
171
- return;
172
- }
173
- await glob({ pattern: files, base }).load({ ...withTitleFallback(context), watcher: undefined });
174
- }
175
-
176
- await resync();
177
- if (!watcher) return; // no watcher outside `astro dev` (e.g. `astro build`)
178
-
179
- watcher.add(fileURLToPath(base));
180
- let pending: ReturnType<typeof setTimeout> | undefined;
181
- const scheduleResync = (changedPath: string) => {
182
- if (!/\.mdx?$/i.test(changedPath)) return;
183
- clearTimeout(pending);
184
- // Debounced: an editor's "save" can fire several fs events in
185
- // quick succession (e.g. atomic-write = unlink+add), and adding
186
- // several files at once shouldn't trigger a resync per file.
187
- pending = setTimeout(() => {
188
- resync().catch((err) => logger.error(`Failed to reload pages: ${err.message}`));
189
- }, 100);
190
- };
191
- watcher.on('add', scheduleResync);
192
- watcher.on('unlink', scheduleResync);
193
- watcher.on('change', scheduleResync);
194
- },
195
- };
196
- }
197
-
198
- const pages = defineCollection({
199
- loader: livePages(contentDir, contentRootBase),
200
- schema: docsSchema,
201
- });
202
-
203
- export const collections = { pages, generatedDocs };
1
+ import { defineCollection } from 'astro:content';
2
+ import { glob } from 'astro/loaders';
3
+ import type { Loader } from 'astro/loaders';
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { createHash } from 'node:crypto';
7
+ import { fileURLToPath, pathToFileURL } from 'node:url';
8
+ import { pageFrontmatterSchema, findAllPages } from './lib/config';
9
+ import { titleFromPath } from './lib/pages.js';
10
+ import { writedocsTempDir } from './lib/writedocs-temp-dir.js';
11
+
12
+ const contentDir = process.env.WRITEDOCS_CONTENT_DIR || process.cwd();
13
+
14
+ // Astro's glob loader resolves `base` via `new URL(base, root)`. On Windows,
15
+ // a raw path string like "C:\foo\docs" gets misparsed by the WHATWG URL
16
+ // parser (the drive letter "C:" looks like a URL scheme), which breaks
17
+ // downstream `fileURLToPath` calls. Passing an explicit file:// URL sidesteps
18
+ // that entirely and works the same on every platform.
19
+ //
20
+ // Auto-generated OpenAPI stub pages (see generate-api-pages.js) live under
21
+ // writedocsTempDir() - an OS-temp-directory location keyed off contentDir,
22
+ // not anywhere inside the content directory itself - so they never show up
23
+ // mixed in with a site's own hand-written pages, and writedocs never writes
24
+ // generated files into a person's own project folder. The same location is
25
+ // also where build-time manifests/caches live - see writedocs-temp-dir.js's
26
+ // own doc comment. A separate collection (rather than a second base folder
27
+ // glued onto `pages` somehow) because Astro's loader API has no supported
28
+ // way to point one collection's glob() at two base directories sharing a
29
+ // single store without each call's own "delete anything I didn't just see"
30
+ // cleanup wiping out the other's entries - [...slug].astro merges both
31
+ // collections' entries back into one list at query time instead, which
32
+ // sidesteps that entirely.
33
+ const generatedDocsDir = path.join(writedocsTempDir(contentDir), 'generated-docs');
34
+ const generatedDocsBase = pathToFileURL(generatedDocsDir + path.sep);
35
+
36
+ // Page frontmatter - defined in lib/config-schema.ts as
37
+ // pageFrontmatterSchema, next to writedocs.json's own schema, so
38
+ // `writedocs validate` checks every page against exactly the schema the
39
+ // build uses (that file compiles to the plain JS validate loads).
40
+ const docsSchema = pageFrontmatterSchema;
41
+
42
+ /** Wraps another loader so it's skipped entirely - no filesystem scan, no
43
+ * "directory doesn't exist"/"no files found" warning - when its own base
44
+ * directory doesn't exist yet. Astro requires every collection declared
45
+ * in this file to have a loader, but most sites have no OpenAPI groups
46
+ * at all (generate-api-pages.js only ever creates a generated-docs/
47
+ * directory under writedocsTempDir() when at least one exists), so without this
48
+ * the `generatedDocs` collection below would print a spurious warning on
49
+ * every single build/dev run for the common case of a site with no
50
+ * OpenAPI pages.
51
+ *
52
+ * Without a watcher, in `writedocs dev` too: the collection is synced when
53
+ * the preview starts and then only when lib/openapi-reload-integration.js
54
+ * asks (refreshContent()), after writing the pages of an edited spec - in
55
+ * the order that keeps the navigation and the pages in step. A watcher of
56
+ * its own would sync each page file as it's written, at its own moment
57
+ * (and each refresh would add another set of its listeners). */
58
+ function skipIfMissing(inner: Loader): Loader {
59
+ return {
60
+ name: inner.name,
61
+ load: async (context) => {
62
+ if (!fs.existsSync(generatedDocsBase)) return;
63
+ // Left empty: the last spec taken out of writedocs.json while
64
+ // `writedocs dev` runs (the folder stays then). glob() would only warn
65
+ // about no files and keep the pages it had.
66
+ if (!fs.readdirSync(generatedDocsBase, { recursive: true }).some((file) => /\.mdx?$/i.test(String(file)))) {
67
+ for (const id of context.store.keys()) context.store.delete(id);
68
+ return;
69
+ }
70
+ return inner.load({ ...withTitleFallback(context), watcher: undefined });
71
+ },
72
+ };
73
+ }
74
+
75
+ // A page with no `title` in its frontmatter gets one from its file name,
76
+ // before the schema (which requires `title`) sees it - Mintlify's rule, so
77
+ // a migrated page that relied on it builds with the same title. See
78
+ // titleFromPath() in lib/pages.js; `writedocs validate` applies the same
79
+ // default (lib/content-check.js).
80
+ //
81
+ // And each page's digest - what Astro's content store, kept between runs in
82
+ // writedocsTempDir()'s cache/, compares to reuse a page's data instead of
83
+ // parsing it again - also covers the frontmatter schema (config-schema.ts).
84
+ // With the file's text alone, a page that hadn't changed kept the data an
85
+ // earlier writedocs parsed: after an upgrade that added `draft`, a draft
86
+ // page came back without it - no strip in `writedocs dev`, and not noindex
87
+ // in `build --drafts`. Astro clears the store only when content.config.ts's
88
+ // own text, the Astro config or Astro's version changes.
89
+ const schemaDigest = createHash('sha256')
90
+ .update(fs.readFileSync(path.join(process.env.WRITEDOCS_PACKAGE_ROOT || process.cwd(), 'src', 'lib', 'config-schema.ts')))
91
+ .digest('hex')
92
+ .slice(0, 16);
93
+
94
+ type LoaderContext = Parameters<Loader['load']>[0];
95
+ function withTitleFallback(context: LoaderContext): LoaderContext {
96
+ return {
97
+ ...context,
98
+ generateDigest: (data) => context.generateDigest(typeof data === 'string' ? `${schemaDigest}\n${data}` : data),
99
+ parseData: (props) =>
100
+ context.parseData({
101
+ ...props,
102
+ data:
103
+ typeof props.data?.title === 'string'
104
+ ? props.data
105
+ : { ...props.data, title: titleFromPath(props.filePath ?? props.id) },
106
+ }),
107
+ };
108
+ }
109
+
110
+ const generatedDocs = defineCollection({
111
+ loader: skipIfMissing(glob({ pattern: '**/*.{md,mdx}', base: generatedDocsBase })),
112
+ schema: docsSchema,
113
+ });
114
+
115
+ // Every hand-written page in the project, wherever it lives - see
116
+ // findAllPages() in lib/config.ts for the exact discovery rule (any
117
+ // .md/.mdx file with a frontmatter block, the usual build/dependency
118
+ // directories excluded - docs/ has no special status, it's scanned like
119
+ // any other folder). A single collection covering the whole content
120
+ // directory works here (unlike generatedDocs, which needs its own
121
+ // separate collection - see that const's own comment) because there's
122
+ // only one base to worry about: the content root itself.
123
+ //
124
+ // The literal file list (rather than a `**/*.{md,mdx}` pattern) is what
125
+ // actually implements the frontmatter-based filter: glob()'s `pattern`
126
+ // option takes glob patterns, not a predicate function, so the predicate
127
+ // has to run first, here, to produce the list glob() then just matches
128
+ // literally. Astro's own default id computation, scoped to this same
129
+ // content-root base, is what gives a page under docs/ its "docs/..."
130
+ // file id and a page at the root its bare file id - see
131
+ // fileIdForEntry()'s own comment in lib/config.ts for the one place that
132
+ // id computation needs to be independently recovered (once a page's
133
+ // frontmatter `slug` has overridden `entry.id` itself).
134
+ const contentRootBase = pathToFileURL(contentDir + path.sep);
135
+
136
+ /** Wraps astro's own glob() loader so pages are re-discovered live during
137
+ * `astro dev`, not just once when this module first evaluates.
138
+ *
139
+ * The naive approach - `glob({ pattern: findAllPages(contentDir), base })`,
140
+ * computed once at module load, as this used to be - works fine for the
141
+ * *first* load, but astro's glob loader's own dev-mode watcher only ever
142
+ * matches entries against whatever literal pattern list it was constructed
143
+ * with (see matchesGlob() in astro's glob.js, called from its `watcher.on(
144
+ * 'add', ...)` handler): a file created after that list was computed can
145
+ * never match it, so it silently never becomes a page until the dev server
146
+ * is restarted and this module re-evaluates findAllPages() from scratch.
147
+ * That's the exact bug this wrapper fixes.
148
+ *
149
+ * A plain wildcard pattern (`**\/*.{md,mdx}`) doesn't work as a substitute,
150
+ * either: whether a given .md/.mdx file counts as a page at all depends on
151
+ * its *content* (does it have a frontmatter block? - see findAllPages()'s
152
+ * own doc comment, this is what lets e.g. snippets/ partials with no
153
+ * frontmatter coexist in the content dir without becoming pages
154
+ * themselves), not just its path, and glob()'s `pattern` option only does
155
+ * path matching - it can't express that filter. Something has to re-run
156
+ * findAllPages() itself, content and all, whenever the file set changes.
157
+ *
158
+ * So: this re-invokes astro's own glob() loader - reusing all of its real
159
+ * parsing/rendering/digest-based caching logic rather than reimplementing
160
+ * any of that - with a freshly recomputed literal file list every time
161
+ * something relevant changes on disk, instead of once. The inner loader's
162
+ * own watcher wiring is deliberately skipped each time (`watcher` is
163
+ * stripped from the context passed to it) - this loader keeps exactly one
164
+ * watcher subscription of its own instead, covering every case uniformly
165
+ * (a new page file appearing, one being deleted, frontmatter being added
166
+ * to or removed from an existing file, ordinary content edits) rather than
167
+ * relying on the inner loader's add/change/unlink handlers, which - as
168
+ * above - are only ever bound to whatever the pattern looked like at the
169
+ * moment they were registered. */
170
+ function livePages(dir: string, base: URL): Loader {
171
+ return {
172
+ name: 'writedocs-live-pages',
173
+ load: async (context) => {
174
+ const { watcher, store, logger } = context;
175
+
176
+ async function resync() {
177
+ const files = findAllPages(dir);
178
+ if (files.length === 0) {
179
+ // Mirrors the old skipIfEmpty() wrapper: skip calling the inner
180
+ // loader entirely (rather than passing it an empty/impossible
181
+ // pattern) so astro doesn't print its own "no files found"
182
+ // warning for a freshly-scaffolded project with no content yet -
183
+ // but still clear out any previously-synced entries, in case a
184
+ // page's last file was just deleted mid dev-session rather than
185
+ // this being the initial load of an empty project.
186
+ for (const id of store.keys()) store.delete(id);
187
+ return;
188
+ }
189
+ await glob({ pattern: files, base }).load({ ...withTitleFallback(context), watcher: undefined });
190
+ }
191
+
192
+ await resync();
193
+ if (!watcher) return; // no watcher outside `astro dev` (e.g. `astro build`)
194
+
195
+ watcher.add(fileURLToPath(base));
196
+ let pending: ReturnType<typeof setTimeout> | undefined;
197
+ const scheduleResync = (changedPath: string) => {
198
+ if (!/\.mdx?$/i.test(changedPath)) return;
199
+ clearTimeout(pending);
200
+ // Debounced: an editor's "save" can fire several fs events in
201
+ // quick succession (e.g. atomic-write = unlink+add), and adding
202
+ // several files at once shouldn't trigger a resync per file.
203
+ pending = setTimeout(() => {
204
+ resync().catch((err) => logger.error(`Failed to reload pages: ${err.message}`));
205
+ }, 100);
206
+ };
207
+ watcher.on('add', scheduleResync);
208
+ watcher.on('unlink', scheduleResync);
209
+ watcher.on('change', scheduleResync);
210
+ },
211
+ };
212
+ }
213
+
214
+ const pages = defineCollection({
215
+ loader: livePages(contentDir, contentRootBase),
216
+ schema: docsSchema,
217
+ });
218
+
219
+ export const collections = { pages, generatedDocs };