@writedocs/generator 0.13.4 → 0.13.5

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 (86) hide show
  1. package/README.md +28 -28
  2. package/astro.config.mjs +645 -645
  3. package/bin/writedocs.js +356 -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 +203 -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 +268 -268
  11. package/src/cli/exit-when-flushed.js +42 -42
  12. package/src/cli/generate-api-pages.js +507 -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 +69 -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 +203 -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 +408 -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.ts +2509 -2509
  48. package/src/lib/config.ts +1316 -1316
  49. package/src/lib/consent.js +108 -108
  50. package/src/lib/content-store-reload-integration.js +101 -101
  51. package/src/lib/icon-data-dev.js +53 -53
  52. package/src/lib/image-size.js +152 -152
  53. package/src/lib/json-schema-descriptions.js +228 -228
  54. package/src/lib/link-check.js +544 -544
  55. package/src/lib/llms-index.ts +90 -90
  56. package/src/lib/mcp-dev-integration.js +65 -65
  57. package/src/lib/mcp-index.ts +102 -102
  58. package/src/lib/mintlify-convert.js +605 -605
  59. package/src/lib/moved-api-pages.js +49 -49
  60. package/src/lib/og-cards.js +33 -33
  61. package/src/lib/og-image.js +235 -235
  62. package/src/lib/openapi-dev-status.js +80 -80
  63. package/src/lib/openapi-reload-integration.js +193 -193
  64. package/src/lib/pages.js +312 -312
  65. package/src/lib/project-files-integration.js +116 -116
  66. package/src/lib/project-files.js +137 -137
  67. package/src/lib/rehype-base-path.js +62 -62
  68. package/src/lib/rehype-image-loading.js +71 -71
  69. package/src/lib/robots-txt.js +21 -21
  70. package/src/lib/search-scope.js +44 -44
  71. package/src/lib/selector-placement.js +50 -50
  72. package/src/lib/seo-tags.js +155 -155
  73. package/src/lib/shiki-code-block.js +7 -1
  74. package/src/lib/site-base.ts +27 -27
  75. package/src/lib/styles-asset-integration.js +291 -291
  76. package/src/lib/wdignore-cases.json +195 -195
  77. package/src/lib/wdignore.js +177 -177
  78. package/src/pages/404.astro +63 -63
  79. package/src/pages/[...slug].astro +1762 -1608
  80. package/src/pages/[...slug].md.ts +93 -93
  81. package/src/pages/llms-full.txt.ts +88 -88
  82. package/src/pages/og/[...slug].png.ts +63 -63
  83. package/src/scripts/mobile-menu.ts +80 -80
  84. package/src/scripts/search.ts +245 -245
  85. package/src/scripts/sidebar-scroll.ts +61 -61
  86. package/src/styles/global.css +40 -40
@@ -1,108 +1,108 @@
1
- // The analytics integrations' <script> tags (writedocs.json's
2
- // `integrations`), and the consent banner that can hold them back.
3
- //
4
- // Without `integrations.consent`, AnalyticsScripts.astro writes each tag
5
- // into <head> and the browser loads them with the page. With it, no tag is
6
- // written: consentLoaderScript() puts the same list in one small script,
7
- // which adds the tags only once the reader has accepted - on this visit, or
8
- // an earlier one (the answer is kept in localStorage). ConsentBanner.astro
9
- // is the banner; src/scripts/consent.ts wires its buttons.
10
- //
11
- // Plain JavaScript with no Astro import, so scripts/consent.test.js can run
12
- // it directly.
13
-
14
- /** The anchor that opens the banner again, from a link on any page - no
15
- * heading has it. src/scripts/consent.ts listens for it (its own
16
- * SETTINGS_HASH); `writedocs broken-links` (lib/link-check.js) accepts it
17
- * when the banner is on. */
18
- export const CONSENT_SETTINGS_ANCHOR = 'cookie-settings';
19
-
20
- /** localStorage key holding the reader's answer: "granted" or "denied". */
21
- export const CONSENT_STORAGE_KEY = 'wd-consent';
22
-
23
- export const CONSENT_DEFAULTS = {
24
- message: 'We use cookies to understand how this site is used and to improve it.',
25
- acceptLabel: 'Accept',
26
- declineLabel: 'Decline',
27
- policyLabel: 'Privacy policy',
28
- };
29
-
30
- /** `integrations.consent` as the banner's texts - null when it's off
31
- * (absent or false). `true` gives the defaults. */
32
- export function consentOptions(value) {
33
- if (!value) return null;
34
- const given = value === true ? {} : value;
35
- const text = (key) => (typeof given[key] === 'string' && given[key].trim() ? given[key].trim() : CONSENT_DEFAULTS[key]);
36
- return {
37
- message: text('message'),
38
- acceptLabel: text('acceptLabel'),
39
- declineLabel: text('declineLabel'),
40
- policyUrl: typeof given.policyUrl === 'string' && given.policyUrl.trim() ? given.policyUrl.trim() : null,
41
- policyLabel: text('policyLabel'),
42
- };
43
- }
44
-
45
- /** One <script> per entry, in order: `{ src, attrs }` for a file, or
46
- * `{ content }` for code. `attrs` values are strings, or `true` for a
47
- * bare attribute (`async`, `defer`).
48
- *
49
- * Every snippet is the provider's own install snippet - see
50
- * docs/dev/docs/integrations.mdx for where each came from. Config values
51
- * go in through JSON.stringify, so a quote or backslash in one can't break
52
- * out of the generated script. */
53
- export function analyticsTags(integrations = {}) {
54
- const tags = [];
55
- const { ga4, googleTagManager, plausible, fathom, posthog, umami } = integrations;
56
- if (ga4) {
57
- tags.push({ src: `https://www.googletagmanager.com/gtag/js?id=${ga4.measurementId}`, attrs: { async: true } });
58
- tags.push({
59
- content: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',${JSON.stringify(ga4.measurementId)});`,
60
- });
61
- }
62
- if (googleTagManager) {
63
- // Google's own long-stable snippet: pushes the first 'gtm.js' event and
64
- // adds the real gtm.js loader.
65
- tags.push({
66
- content: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer',${JSON.stringify(googleTagManager.containerId)});`,
67
- });
68
- }
69
- if (plausible) tags.push({ src: plausible.src, attrs: { defer: true, 'data-domain': plausible.domain } });
70
- if (fathom) tags.push({ src: 'https://cdn.usefathom.com/script.js', attrs: { 'data-site': fathom.siteId, defer: true } });
71
- if (posthog) {
72
- // PostHog's "array.js" loader, from posthog.com/docs/libraries/js.
73
- // PostHog revises its minified body now and then - fetch it again and
74
- // compare before changing it. `defaults` is their dated configuration
75
- // snapshot; move it on when their docs do.
76
- tags.push({
77
- content: `!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init(${JSON.stringify(posthog.apiKey)},{api_host:${JSON.stringify(posthog.apiHost)},defaults:'2026-05-30'});`,
78
- });
79
- }
80
- if (umami) tags.push({ src: umami.src, attrs: { defer: true, 'data-website-id': umami.websiteId } });
81
- return tags;
82
- }
83
-
84
- /** `scripts.head`/`scripts.body` entries marked `consent: true`, as tags. */
85
- export function scriptTags(entries = []) {
86
- return entries.map((entry) => (entry.src ? { src: entry.src, attrs: {} } : { content: entry.content }));
87
- }
88
-
89
- /** The <head> script that stands in for `tags` when the banner is on. It
90
- * defines `window.wdConsent`:
91
- * get() "granted", "denied" or null (no answer yet)
92
- * set(value) stores the answer; "granted" adds the tags, once. Going
93
- * from "granted" to "denied" reloads the page - scripts
94
- * that already ran can't be taken back any other way.
95
- * and fires a `wd:consent` event on `document` with the answer as `detail`,
96
- * for a site's own scripts. The tags are added on load when the stored
97
- * answer is already "granted". A browser with no localStorage asks again
98
- * on every page, and loads nothing until the reader accepts. */
99
- export function consentLoaderScript(tags) {
100
- // "</script" inside the JSON would end the inline script early.
101
- const list = JSON.stringify(tags).replace(/</g, '\\u003c');
102
- return `(function(){var T=${list},K=${JSON.stringify(CONSENT_STORAGE_KEY)},loaded=false,answer=null;
103
- function read(){try{var v=localStorage.getItem(K);return v==="granted"||v==="denied"?v:null}catch(e){return null}}
104
- function load(){if(loaded)return;loaded=true;T.forEach(function(t){var s=document.createElement("script");s.async=false;for(var k in t.attrs||{}){if(t.attrs[k]===true)s.setAttribute(k,"");else s.setAttribute(k,t.attrs[k])}if(t.src)s.src=t.src;else s.text=t.content;document.head.appendChild(s)})}
105
- answer=read();
106
- window.wdConsent={get:function(){return answer},set:function(v){if(v!=="granted"&&v!=="denied")return;var was=answer;answer=v;try{localStorage.setItem(K,v)}catch(e){}document.dispatchEvent(new CustomEvent("wd:consent",{detail:v}));if(v==="granted")load();else if(was==="granted"&&loaded)location.reload()}};
107
- if(answer==="granted")load();})();`;
108
- }
1
+ // The analytics integrations' <script> tags (writedocs.json's
2
+ // `integrations`), and the consent banner that can hold them back.
3
+ //
4
+ // Without `integrations.consent`, AnalyticsScripts.astro writes each tag
5
+ // into <head> and the browser loads them with the page. With it, no tag is
6
+ // written: consentLoaderScript() puts the same list in one small script,
7
+ // which adds the tags only once the reader has accepted - on this visit, or
8
+ // an earlier one (the answer is kept in localStorage). ConsentBanner.astro
9
+ // is the banner; src/scripts/consent.ts wires its buttons.
10
+ //
11
+ // Plain JavaScript with no Astro import, so scripts/consent.test.js can run
12
+ // it directly.
13
+
14
+ /** The anchor that opens the banner again, from a link on any page - no
15
+ * heading has it. src/scripts/consent.ts listens for it (its own
16
+ * SETTINGS_HASH); `writedocs broken-links` (lib/link-check.js) accepts it
17
+ * when the banner is on. */
18
+ export const CONSENT_SETTINGS_ANCHOR = 'cookie-settings';
19
+
20
+ /** localStorage key holding the reader's answer: "granted" or "denied". */
21
+ export const CONSENT_STORAGE_KEY = 'wd-consent';
22
+
23
+ export const CONSENT_DEFAULTS = {
24
+ message: 'We use cookies to understand how this site is used and to improve it.',
25
+ acceptLabel: 'Accept',
26
+ declineLabel: 'Decline',
27
+ policyLabel: 'Privacy policy',
28
+ };
29
+
30
+ /** `integrations.consent` as the banner's texts - null when it's off
31
+ * (absent or false). `true` gives the defaults. */
32
+ export function consentOptions(value) {
33
+ if (!value) return null;
34
+ const given = value === true ? {} : value;
35
+ const text = (key) => (typeof given[key] === 'string' && given[key].trim() ? given[key].trim() : CONSENT_DEFAULTS[key]);
36
+ return {
37
+ message: text('message'),
38
+ acceptLabel: text('acceptLabel'),
39
+ declineLabel: text('declineLabel'),
40
+ policyUrl: typeof given.policyUrl === 'string' && given.policyUrl.trim() ? given.policyUrl.trim() : null,
41
+ policyLabel: text('policyLabel'),
42
+ };
43
+ }
44
+
45
+ /** One <script> per entry, in order: `{ src, attrs }` for a file, or
46
+ * `{ content }` for code. `attrs` values are strings, or `true` for a
47
+ * bare attribute (`async`, `defer`).
48
+ *
49
+ * Every snippet is the provider's own install snippet - see
50
+ * docs/dev/docs/integrations.mdx for where each came from. Config values
51
+ * go in through JSON.stringify, so a quote or backslash in one can't break
52
+ * out of the generated script. */
53
+ export function analyticsTags(integrations = {}) {
54
+ const tags = [];
55
+ const { ga4, googleTagManager, plausible, fathom, posthog, umami } = integrations;
56
+ if (ga4) {
57
+ tags.push({ src: `https://www.googletagmanager.com/gtag/js?id=${ga4.measurementId}`, attrs: { async: true } });
58
+ tags.push({
59
+ content: `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',${JSON.stringify(ga4.measurementId)});`,
60
+ });
61
+ }
62
+ if (googleTagManager) {
63
+ // Google's own long-stable snippet: pushes the first 'gtm.js' event and
64
+ // adds the real gtm.js loader.
65
+ tags.push({
66
+ content: `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer',${JSON.stringify(googleTagManager.containerId)});`,
67
+ });
68
+ }
69
+ if (plausible) tags.push({ src: plausible.src, attrs: { defer: true, 'data-domain': plausible.domain } });
70
+ if (fathom) tags.push({ src: 'https://cdn.usefathom.com/script.js', attrs: { 'data-site': fathom.siteId, defer: true } });
71
+ if (posthog) {
72
+ // PostHog's "array.js" loader, from posthog.com/docs/libraries/js.
73
+ // PostHog revises its minified body now and then - fetch it again and
74
+ // compare before changing it. `defaults` is their dated configuration
75
+ // snapshot; move it on when their docs do.
76
+ tags.push({
77
+ content: `!function(t,e){var o,n,p,r;e.__SV||(window.posthog=e,e._i=[],e.init=function(i,s,a){function g(t,e){var o=e.split(".");2==o.length&&(t=t[o[0]],e=o[1]),t[e]=function(){t.push([e].concat(Array.prototype.slice.call(arguments,0)))}}(p=t.createElement("script")).type="text/javascript",p.crossOrigin="anonymous",p.async=!0,p.src=s.api_host.replace(".i.posthog.com","-assets.i.posthog.com")+"/static/array.js",(r=t.getElementsByTagName("script")[0]).parentNode.insertBefore(p,r);var u=e;for(void 0!==a?u=e[a]=[]:a="posthog",u.people=u.people||[],u.toString=function(t){var e="posthog";return"posthog"!==a&&(e+="."+a),t||(e+=" (stub)"),e},u.people.toString=function(){return u.toString(1)+".people (stub)"},o="init capture register register_once register_for_session unregister unregister_for_session getFeatureFlag getFeatureFlagResult isFeatureEnabled reloadFeatureFlags updateEarlyAccessFeatureEnrollment getEarlyAccessFeatures on onFeatureFlags onSessionId getSurveys getActiveMatchingSurveys renderSurvey canRenderSurvey getNextSurveyStep identify setPersonProperties group resetGroups setPersonPropertiesForFlags resetPersonPropertiesForFlags setGroupPropertiesForFlags resetGroupPropertiesForFlags reset get_distinct_id getGroups get_session_id get_session_replay_url alias set_config startSessionRecording stopSessionRecording sessionRecordingStarted captureException loadToolbar get_property getSessionProperty createPersonProfile opt_in_capturing opt_out_capturing has_opted_in_capturing has_opted_out_capturing clear_opt_in_out_capturing debug".split(" "),n=0;n<o.length;n++)g(u,o[n]);e._i.push([i,s,a])},e.__SV=1)}(document,window.posthog||[]);posthog.init(${JSON.stringify(posthog.apiKey)},{api_host:${JSON.stringify(posthog.apiHost)},defaults:'2026-05-30'});`,
78
+ });
79
+ }
80
+ if (umami) tags.push({ src: umami.src, attrs: { defer: true, 'data-website-id': umami.websiteId } });
81
+ return tags;
82
+ }
83
+
84
+ /** `scripts.head`/`scripts.body` entries marked `consent: true`, as tags. */
85
+ export function scriptTags(entries = []) {
86
+ return entries.map((entry) => (entry.src ? { src: entry.src, attrs: {} } : { content: entry.content }));
87
+ }
88
+
89
+ /** The <head> script that stands in for `tags` when the banner is on. It
90
+ * defines `window.wdConsent`:
91
+ * get() "granted", "denied" or null (no answer yet)
92
+ * set(value) stores the answer; "granted" adds the tags, once. Going
93
+ * from "granted" to "denied" reloads the page - scripts
94
+ * that already ran can't be taken back any other way.
95
+ * and fires a `wd:consent` event on `document` with the answer as `detail`,
96
+ * for a site's own scripts. The tags are added on load when the stored
97
+ * answer is already "granted". A browser with no localStorage asks again
98
+ * on every page, and loads nothing until the reader accepts. */
99
+ export function consentLoaderScript(tags) {
100
+ // "</script" inside the JSON would end the inline script early.
101
+ const list = JSON.stringify(tags).replace(/</g, '\\u003c');
102
+ return `(function(){var T=${list},K=${JSON.stringify(CONSENT_STORAGE_KEY)},loaded=false,answer=null;
103
+ function read(){try{var v=localStorage.getItem(K);return v==="granted"||v==="denied"?v:null}catch(e){return null}}
104
+ function load(){if(loaded)return;loaded=true;T.forEach(function(t){var s=document.createElement("script");s.async=false;for(var k in t.attrs||{}){if(t.attrs[k]===true)s.setAttribute(k,"");else s.setAttribute(k,t.attrs[k])}if(t.src)s.src=t.src;else s.text=t.content;document.head.appendChild(s)})}
105
+ answer=read();
106
+ window.wdConsent={get:function(){return answer},set:function(v){if(v!=="granted"&&v!=="denied")return;var was=answer;answer=v;try{localStorage.setItem(K,v)}catch(e){}document.dispatchEvent(new CustomEvent("wd:consent",{detail:v}));if(v==="granted")load();else if(was==="granted"&&loaded)location.reload()}};
107
+ if(answer==="granted")load();})();`;
108
+ }
@@ -1,101 +1,101 @@
1
- // `writedocs dev`, installed: Astro's content store changes reach the page.
2
- //
3
- // When a collection entry changes - a page's frontmatter, a generated API
4
- // page added, renamed or removed (lib/openapi-reload-integration.js) - Astro
5
- // writes two files under <packageRoot>/.astro/ and learns that it did from
6
- // Vite's file watcher:
7
- // - data-store.json, the entries: on its change event Astro re-reads it,
8
- // clears the routes getStaticPaths() gave, and reloads the open tab
9
- // (astro/dist/content/vite-plugin-content-virtual-mod.js);
10
- // - content-modules.mjs, the module that renders each entry: an ordinary
11
- // module, which Vite invalidates when it changes - without that, a new
12
- // entry fails to render (UnknownContentCollectionError).
13
- // Vite's watcher ignores everything under node_modules, whatever the config
14
- // says - and an installed writedocs is there
15
- // (<project>/node_modules/@writedocs/generator/.astro/...). So neither event
16
- // came: a title edited in a page's frontmatter, or a new operation's page,
17
- // stayed as it was until the preview restarted. In a checkout of this
18
- // repository the folder isn't under node_modules and Vite sees it by itself.
19
- //
20
- // This watches the two files directly and hands their change events to
21
- // Vite's watcher - the module list first, so the reload Astro sends for the
22
- // store finds it current. lib/openapi-reload-integration.js hands them on
23
- // itself (contentStoreChanged()), at the moment it knows the store is
24
- // complete; the echo of that from the watcher is skipped.
25
- import fs from 'node:fs';
26
- import path from 'node:path';
27
-
28
- /** The files, in the order their change is handed on. */
29
- export const CONTENT_STORE_FILES = ['content-modules.mjs', 'data-store.json'];
30
-
31
- // When contentStoreChanged() last ran - the watcher's own event for the same
32
- // writes comes right after it.
33
- let handedOnAt = 0;
34
- const ECHO_MS = 1000;
35
-
36
- /** Hands Astro the change events of its content store files, as if Vite's
37
- * watcher had seen them - Astro re-reads the store, clears its routes and
38
- * reloads the open tab. For a caller that has just synced the store
39
- * (refreshContent() resolves once both files are written). */
40
- export function contentStoreChanged(server, packageRoot) {
41
- handedOnAt = Date.now();
42
- for (const name of CONTENT_STORE_FILES) {
43
- const file = path.join(packageRoot, '.astro', name);
44
- if (fs.existsSync(file)) server.watcher.emit('change', file);
45
- }
46
- }
47
-
48
- /** Whether Vite's watcher can't see files in `packageRoot` - it's inside a
49
- * node_modules folder. */
50
- export function insideNodeModules(packageRoot) {
51
- return path.resolve(packageRoot).split(/[\\/]/).includes('node_modules');
52
- }
53
-
54
- /** Calls `onChange(files)` - the ones of `names` in `dir` written since the
55
- * last call, in the order of `names` - once a burst of writes settles.
56
- * Astro replaces each file whole (a rename), so the folder is what's
57
- * watched. Returns a function that stops. */
58
- export function watchFiles(dir, names, onChange, { settleMs = 100 } = {}) {
59
- fs.mkdirSync(dir, { recursive: true });
60
- const changed = new Set();
61
- let timer = null;
62
- let watcher;
63
- try {
64
- watcher = fs.watch(dir, (_event, filename) => {
65
- if (!filename || !names.includes(filename)) return;
66
- changed.add(filename);
67
- clearTimeout(timer);
68
- timer = setTimeout(() => {
69
- const files = names.filter((name) => changed.has(name)).map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
70
- changed.clear();
71
- if (files.length) onChange(files);
72
- }, settleMs);
73
- });
74
- watcher.on('error', () => {});
75
- } catch {
76
- return () => {};
77
- }
78
- return () => {
79
- clearTimeout(timer);
80
- watcher.close();
81
- };
82
- }
83
-
84
- export function contentStoreReload({ packageRoot }) {
85
- return {
86
- name: 'writedocs-content-store-reload',
87
- hooks: {
88
- 'astro:server:setup': ({ server }) => {
89
- if (!insideNodeModules(packageRoot)) return;
90
- // The paths exactly as Astro compares them: fileURLToPath() of
91
- // new URL('.astro/<file>', root), root being packageRoot.
92
- const dir = path.join(packageRoot, '.astro');
93
- const stop = watchFiles(dir, CONTENT_STORE_FILES, (files) => {
94
- if (Date.now() - handedOnAt < ECHO_MS) return;
95
- for (const file of files) server.watcher.emit('change', file);
96
- });
97
- server.httpServer?.once('close', stop);
98
- },
99
- },
100
- };
101
- }
1
+ // `writedocs dev`, installed: Astro's content store changes reach the page.
2
+ //
3
+ // When a collection entry changes - a page's frontmatter, a generated API
4
+ // page added, renamed or removed (lib/openapi-reload-integration.js) - Astro
5
+ // writes two files under <packageRoot>/.astro/ and learns that it did from
6
+ // Vite's file watcher:
7
+ // - data-store.json, the entries: on its change event Astro re-reads it,
8
+ // clears the routes getStaticPaths() gave, and reloads the open tab
9
+ // (astro/dist/content/vite-plugin-content-virtual-mod.js);
10
+ // - content-modules.mjs, the module that renders each entry: an ordinary
11
+ // module, which Vite invalidates when it changes - without that, a new
12
+ // entry fails to render (UnknownContentCollectionError).
13
+ // Vite's watcher ignores everything under node_modules, whatever the config
14
+ // says - and an installed writedocs is there
15
+ // (<project>/node_modules/@writedocs/generator/.astro/...). So neither event
16
+ // came: a title edited in a page's frontmatter, or a new operation's page,
17
+ // stayed as it was until the preview restarted. In a checkout of this
18
+ // repository the folder isn't under node_modules and Vite sees it by itself.
19
+ //
20
+ // This watches the two files directly and hands their change events to
21
+ // Vite's watcher - the module list first, so the reload Astro sends for the
22
+ // store finds it current. lib/openapi-reload-integration.js hands them on
23
+ // itself (contentStoreChanged()), at the moment it knows the store is
24
+ // complete; the echo of that from the watcher is skipped.
25
+ import fs from 'node:fs';
26
+ import path from 'node:path';
27
+
28
+ /** The files, in the order their change is handed on. */
29
+ export const CONTENT_STORE_FILES = ['content-modules.mjs', 'data-store.json'];
30
+
31
+ // When contentStoreChanged() last ran - the watcher's own event for the same
32
+ // writes comes right after it.
33
+ let handedOnAt = 0;
34
+ const ECHO_MS = 1000;
35
+
36
+ /** Hands Astro the change events of its content store files, as if Vite's
37
+ * watcher had seen them - Astro re-reads the store, clears its routes and
38
+ * reloads the open tab. For a caller that has just synced the store
39
+ * (refreshContent() resolves once both files are written). */
40
+ export function contentStoreChanged(server, packageRoot) {
41
+ handedOnAt = Date.now();
42
+ for (const name of CONTENT_STORE_FILES) {
43
+ const file = path.join(packageRoot, '.astro', name);
44
+ if (fs.existsSync(file)) server.watcher.emit('change', file);
45
+ }
46
+ }
47
+
48
+ /** Whether Vite's watcher can't see files in `packageRoot` - it's inside a
49
+ * node_modules folder. */
50
+ export function insideNodeModules(packageRoot) {
51
+ return path.resolve(packageRoot).split(/[\\/]/).includes('node_modules');
52
+ }
53
+
54
+ /** Calls `onChange(files)` - the ones of `names` in `dir` written since the
55
+ * last call, in the order of `names` - once a burst of writes settles.
56
+ * Astro replaces each file whole (a rename), so the folder is what's
57
+ * watched. Returns a function that stops. */
58
+ export function watchFiles(dir, names, onChange, { settleMs = 100 } = {}) {
59
+ fs.mkdirSync(dir, { recursive: true });
60
+ const changed = new Set();
61
+ let timer = null;
62
+ let watcher;
63
+ try {
64
+ watcher = fs.watch(dir, (_event, filename) => {
65
+ if (!filename || !names.includes(filename)) return;
66
+ changed.add(filename);
67
+ clearTimeout(timer);
68
+ timer = setTimeout(() => {
69
+ const files = names.filter((name) => changed.has(name)).map((name) => path.join(dir, name)).filter((file) => fs.existsSync(file));
70
+ changed.clear();
71
+ if (files.length) onChange(files);
72
+ }, settleMs);
73
+ });
74
+ watcher.on('error', () => {});
75
+ } catch {
76
+ return () => {};
77
+ }
78
+ return () => {
79
+ clearTimeout(timer);
80
+ watcher.close();
81
+ };
82
+ }
83
+
84
+ export function contentStoreReload({ packageRoot }) {
85
+ return {
86
+ name: 'writedocs-content-store-reload',
87
+ hooks: {
88
+ 'astro:server:setup': ({ server }) => {
89
+ if (!insideNodeModules(packageRoot)) return;
90
+ // The paths exactly as Astro compares them: fileURLToPath() of
91
+ // new URL('.astro/<file>', root), root being packageRoot.
92
+ const dir = path.join(packageRoot, '.astro');
93
+ const stop = watchFiles(dir, CONTENT_STORE_FILES, (files) => {
94
+ if (Date.now() - handedOnAt < ECHO_MS) return;
95
+ for (const file of files) server.watcher.emit('change', file);
96
+ });
97
+ server.httpServer?.once('close', stop);
98
+ },
99
+ },
100
+ };
101
+ }
@@ -1,53 +1,53 @@
1
- // `writedocs dev`: astro-icon's icons reach the page from a file, not through
2
- // Vite's module graph.
3
- //
4
- // In dev, astro-icon's `virtual:astro-icon` module holds every icon of every
5
- // installed @iconify-json collection - `export default {...}` with ~15 MB of
6
- // JSON (a build keeps only the icons pages use). Vite then transforms that
7
- // module for the server, writes a source map for it and inlines it (the 15 MB
8
- // again, in base64), Node reads that map back, and V8 compiles the whole
9
- // thing: ~5 s of the first page of every `writedocs dev`, whatever the site,
10
- // and over 1 GB of memory (measured in WD-312's round 03 - see
11
- // docs/dev/docs/dev-preview.mdx).
12
- //
13
- // So the data astro-icon puts in the module goes to a file instead, and the
14
- // module becomes `export default JSON.parse(readFileSync(<file>))` - the same
15
- // object, the same icons; only the 15 MB stops passing through Vite.
16
- //
17
- // Only in `writedocs dev` (`apply: 'serve'`), and only for the server: a
18
- // build doesn't load this plugin at all. A module that doesn't look the way
19
- // this expects (a new astro-icon) is left as it is - the preview is slower
20
- // again, not broken.
21
- import fs from 'node:fs';
22
- import path from 'node:path';
23
-
24
- const MODULE_ID = '\0virtual:astro-icon';
25
-
26
- /** astro-icon's module - `export default <json>;\nexport const config = <json>` -
27
- * as { data, config } (the two JSON texts), or null for anything else. */
28
- export function splitAstroIconModule(code) {
29
- const match = /^export default (\{[\s\S]*\});\nexport const config = (\{[\s\S]*\})\s*$/.exec(code);
30
- return match ? { data: match[1], config: match[2] } : null;
31
- }
32
-
33
- /** The module that replaces it: the data read from `file`, `config` as it was. */
34
- export function iconDataModule(file, config) {
35
- return `import { readFileSync } from 'node:fs';\nexport default JSON.parse(readFileSync(${JSON.stringify(file)}, 'utf-8'));\nexport const config = ${config};\n`;
36
- }
37
-
38
- /** The Vite plugin; the data goes to `<dir>/astro-icon.json`. */
39
- export function iconDataFromFile(dir) {
40
- return {
41
- name: 'writedocs:astro-icon-data-file',
42
- apply: 'serve',
43
- transform(code, id) {
44
- if (id !== MODULE_ID || this.environment?.config?.consumer === 'client') return null;
45
- const parts = splitAstroIconModule(code);
46
- if (!parts) return null;
47
- const file = path.join(dir, 'astro-icon.json');
48
- fs.mkdirSync(dir, { recursive: true });
49
- fs.writeFileSync(file, parts.data);
50
- return { code: iconDataModule(file, parts.config), map: null };
51
- },
52
- };
53
- }
1
+ // `writedocs dev`: astro-icon's icons reach the page from a file, not through
2
+ // Vite's module graph.
3
+ //
4
+ // In dev, astro-icon's `virtual:astro-icon` module holds every icon of every
5
+ // installed @iconify-json collection - `export default {...}` with ~15 MB of
6
+ // JSON (a build keeps only the icons pages use). Vite then transforms that
7
+ // module for the server, writes a source map for it and inlines it (the 15 MB
8
+ // again, in base64), Node reads that map back, and V8 compiles the whole
9
+ // thing: ~5 s of the first page of every `writedocs dev`, whatever the site,
10
+ // and over 1 GB of memory (measured in WD-312's round 03 - see
11
+ // docs/dev/docs/dev-preview.mdx).
12
+ //
13
+ // So the data astro-icon puts in the module goes to a file instead, and the
14
+ // module becomes `export default JSON.parse(readFileSync(<file>))` - the same
15
+ // object, the same icons; only the 15 MB stops passing through Vite.
16
+ //
17
+ // Only in `writedocs dev` (`apply: 'serve'`), and only for the server: a
18
+ // build doesn't load this plugin at all. A module that doesn't look the way
19
+ // this expects (a new astro-icon) is left as it is - the preview is slower
20
+ // again, not broken.
21
+ import fs from 'node:fs';
22
+ import path from 'node:path';
23
+
24
+ const MODULE_ID = '\0virtual:astro-icon';
25
+
26
+ /** astro-icon's module - `export default <json>;\nexport const config = <json>` -
27
+ * as { data, config } (the two JSON texts), or null for anything else. */
28
+ export function splitAstroIconModule(code) {
29
+ const match = /^export default (\{[\s\S]*\});\nexport const config = (\{[\s\S]*\})\s*$/.exec(code);
30
+ return match ? { data: match[1], config: match[2] } : null;
31
+ }
32
+
33
+ /** The module that replaces it: the data read from `file`, `config` as it was. */
34
+ export function iconDataModule(file, config) {
35
+ return `import { readFileSync } from 'node:fs';\nexport default JSON.parse(readFileSync(${JSON.stringify(file)}, 'utf-8'));\nexport const config = ${config};\n`;
36
+ }
37
+
38
+ /** The Vite plugin; the data goes to `<dir>/astro-icon.json`. */
39
+ export function iconDataFromFile(dir) {
40
+ return {
41
+ name: 'writedocs:astro-icon-data-file',
42
+ apply: 'serve',
43
+ transform(code, id) {
44
+ if (id !== MODULE_ID || this.environment?.config?.consumer === 'client') return null;
45
+ const parts = splitAstroIconModule(code);
46
+ if (!parts) return null;
47
+ const file = path.join(dir, 'astro-icon.json');
48
+ fs.mkdirSync(dir, { recursive: true });
49
+ fs.writeFileSync(file, parts.data);
50
+ return { code: iconDataModule(file, parts.config), map: null };
51
+ },
52
+ };
53
+ }