@writedocs/generator 0.10.14 → 0.10.16

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 (48) hide show
  1. package/astro.config.mjs +610 -572
  2. package/package.json +1 -1
  3. package/src/cli/generate-api-pages.js +418 -384
  4. package/src/cli/write-redirects-file.js +141 -116
  5. package/src/components/Accordion.astro +2 -1
  6. package/src/components/Callout.astro +1 -1
  7. package/src/components/CopyPageMenu.astro +1 -1
  8. package/src/components/Image.astro +19 -3
  9. package/src/components/Parameter.astro +11 -6
  10. package/src/components/Visibility.astro +11 -1
  11. package/src/layout/BaseLayout.astro +896 -831
  12. package/src/layout/components/AnalyticsScripts.astro +45 -77
  13. package/src/layout/components/Breadcrumbs.astro +1 -1
  14. package/src/layout/components/ConsentBanner.astro +118 -0
  15. package/src/layout/components/MobileMenu.astro +3 -2
  16. package/src/layout/components/Sidebar.astro +2 -2
  17. package/src/layout/components/SiteFooter.astro +3 -2
  18. package/src/layout/components/TopBar.astro +3 -2
  19. package/src/layout/styles/base.css +30 -0
  20. package/src/lib/agent-directive.js +47 -0
  21. package/src/lib/agent-markdown.js +22 -2
  22. package/src/lib/components-to-markdown.js +297 -0
  23. package/src/lib/config-schema.js +97 -10
  24. package/src/lib/config-schema.ts +1882 -1768
  25. package/src/lib/consent.js +102 -0
  26. package/src/lib/font-fallback.js +79 -0
  27. package/src/lib/image-size.js +140 -0
  28. package/src/lib/item-pages.js +63 -0
  29. package/src/lib/json-ld.js +127 -0
  30. package/src/lib/json-schema-descriptions.js +226 -212
  31. package/src/lib/last-modified.js +52 -0
  32. package/src/lib/link-check.js +506 -500
  33. package/src/lib/mcp-index.ts +1 -1
  34. package/src/lib/meta-description.js +41 -0
  35. package/src/lib/mintlify-convert.js +605 -603
  36. package/src/lib/moved-api-pages.js +54 -0
  37. package/src/lib/openapi-markdown.ts +16 -6
  38. package/src/lib/project-files-integration.js +61 -0
  39. package/src/lib/project-files.js +126 -0
  40. package/src/lib/rehype-image-loading.js +71 -0
  41. package/src/lib/robots-txt.js +16 -0
  42. package/src/lib/seo-tags.js +137 -0
  43. package/src/lib/styles-asset-integration.js +21 -3
  44. package/src/pages/[...slug].astro +22 -3
  45. package/src/pages/[...slug].md.ts +15 -5
  46. package/src/pages/llms-full.txt.ts +1 -1
  47. package/src/scripts/consent.ts +62 -0
  48. package/writedocs.schema.json +100 -0
@@ -1,77 +1,45 @@
1
- ---
2
- // writedocs.json's `integrations` (integrationsSchema in lib/config.ts) - the
3
- // six analytics providers. Each provider's inline-JS half (the ones that
4
- // need one; Fathom/Plausible/Umami are pure <script src> tags with data-*
5
- // attributes, rendered directly in the template below with no inline half
6
- // to build here) is assembled as a plain string, interpolating the site's
7
- // own config values via JSON.stringify (not raw string interpolation) so
8
- // a value containing a quote or backslash can never break out of the
9
- // generated script.
10
- //
11
- // Rendered by BaseLayout.astro in <head>, right after the meta tags and
12
- // before even the theme-detection script - the usual placement every one
13
- // of these providers' own install instructions ask for, so pageview
14
- // timing is captured as close to actual page load as it can be. Every
15
- // snippet below was sourced from that provider's own current official
16
- // docs (fetched directly, not recalled from training data) while building
17
- // this feature - see docs/dev/docs/integrations.mdx for links and dates.
18
- // Every provider field is optional and independent - a site can turn on
19
- // any subset (including all of them at once, for a migration period) or
20
- // none.
21
- //
22
- // AskAiWidget.astro is the seventh integration (DocsBot) - kept as its
23
- // own separate component rather than folded in here, since it renders at
24
- // the *end* of <body>, not in <head> (it's a UI widget, not a pageview
25
- // beacon - see that component's own comment).
26
- //
27
- // Split out of BaseLayout.astro, which had grown to ~2200 lines covering
28
- // several unrelated concerns in one file - see that component's own
29
- // comment for the fuller rationale.
30
- import type { DocsConfig } from '../../lib/config';
31
-
32
- interface Props {
33
- config: DocsConfig;
34
- }
35
- const { config } = Astro.props as Props;
36
-
37
- // Google Tag Manager's snippet is copied verbatim from Google's own
38
- // long-stable install snippet (unchanged in substance for years) - the
39
- // self-invoking function that pushes the initial 'gtm.js' event and
40
- // injects the real gtm.js loader script.
41
- const gtmScript = config.integrations.googleTagManager
42
- ? `(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(config.integrations.googleTagManager.containerId)});`
43
- : null;
44
- // GA4's own gtag.js config call - paired with the separate `<script
45
- // async src="...gtag/js?id=...">` loader tag rendered directly below,
46
- // both gated on the same config.integrations.ga4 check.
47
- const ga4ConfigScript = config.integrations.ga4
48
- ? `window.dataLayer=window.dataLayer||[];function gtag(){dataLayer.push(arguments);}gtag('js',new Date());gtag('config',${JSON.stringify(config.integrations.ga4.measurementId)});`
49
- : null;
50
- // PostHog's own "array.js" bootstrap loader - copied verbatim from
51
- // posthog.com/docs/libraries/js (fetched directly while building this
52
- // feature, not recalled from training data - PostHog revises this
53
- // snippet's minified body occasionally, so re-fetch and diff before
54
- // assuming it's still current if this ever needs touching again). The
55
- // `defaults` date is PostHog's own versioned configuration-snapshot pin
56
- // (their docs describe it as "a date... for a configuration snapshot used
57
- // as defaults") - current as of the fetch above; bump it if PostHog's own
58
- // docs have moved on to a newer one.
59
- const posthogScript = config.integrations.posthog
60
- ? `!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(config.integrations.posthog.apiKey)},{api_host:${JSON.stringify(config.integrations.posthog.apiHost)},defaults:'2026-05-30'});`
61
- : null;
62
- ---
63
- {config.integrations.ga4 && (
64
- <script is:inline async src={`https://www.googletagmanager.com/gtag/js?id=${config.integrations.ga4.measurementId}`}></script>
65
- )}
66
- {ga4ConfigScript && <script is:inline set:html={ga4ConfigScript} />}
67
- {gtmScript && <script is:inline set:html={gtmScript} />}
68
- {config.integrations.plausible && (
69
- <script is:inline defer data-domain={config.integrations.plausible.domain} src={config.integrations.plausible.src}></script>
70
- )}
71
- {config.integrations.fathom && (
72
- <script is:inline src="https://cdn.usefathom.com/script.js" data-site={config.integrations.fathom.siteId} defer></script>
73
- )}
74
- {posthogScript && <script is:inline set:html={posthogScript} />}
75
- {config.integrations.umami && (
76
- <script is:inline defer src={config.integrations.umami.src} data-website-id={config.integrations.umami.websiteId}></script>
77
- )}
1
+ ---
2
+ // writedocs.json's `integrations` - the six analytics providers. The tags
3
+ // themselves are built by analyticsTags() in lib/consent.js (each one the
4
+ // provider's own install snippet - see docs/dev/docs/integrations.mdx for
5
+ // links and dates); this component decides how they reach the page:
6
+ //
7
+ // - no `integrations.consent`: one <script> tag each, loaded with the page.
8
+ // - with it: no tag at all, only consentLoaderScript() - which adds them
9
+ // once the reader has accepted, now or on an earlier visit. `scripts`
10
+ // entries marked `consent: true` (gatedScripts) wait the same way.
11
+ //
12
+ // Rendered by BaseLayout.astro in <head>, right after the meta tags and
13
+ // before even the theme-detection script - the usual placement every one
14
+ // of these providers' own install instructions ask for, so pageview timing
15
+ // is captured as close to actual page load as it can be. Every provider
16
+ // field is optional and independent - a site can turn on any subset
17
+ // (including all of them at once, for a migration period) or none.
18
+ //
19
+ // AskAiWidget.astro is the seventh integration (DocsBot) - its own
20
+ // component, since it renders at the *end* of <body>, not in <head> (it's a
21
+ // UI widget, not a pageview beacon - see that component's own comment), and
22
+ // it doesn't wait for consent.
23
+ import type { DocsConfig } from '../../lib/config';
24
+ import { analyticsTags, scriptTags, consentLoaderScript } from '../../lib/consent.js';
25
+
26
+ interface Props {
27
+ config: DocsConfig;
28
+ // consentOptions() of `integrations.consent` - null when the banner is off.
29
+ consent?: object | null;
30
+ // `scripts` entries with `consent: true`. Empty when the banner is off:
31
+ // BaseLayout renders them as ordinary scripts then.
32
+ gatedScripts?: { src?: string; content?: string }[];
33
+ }
34
+ const { config, consent = null, gatedScripts = [] } = Astro.props as Props;
35
+
36
+ const tags = analyticsTags(config.integrations);
37
+ const loader = consent ? consentLoaderScript([...tags, ...scriptTags(gatedScripts)]) : null;
38
+ ---
39
+ {loader ? (
40
+ <script is:inline set:html={loader} />
41
+ ) : (
42
+ tags.map((tag) =>
43
+ tag.src ? <script is:inline src={tag.src} {...tag.attrs}></script> : <script is:inline set:html={tag.content} />,
44
+ )
45
+ )}
@@ -32,7 +32,7 @@ interface Props {
32
32
 
33
33
  const { items } = Astro.props as Props;
34
34
  ---
35
- <nav class="wd-breadcrumbs" aria-label="Breadcrumb" data-pagefind-ignore>
35
+ <nav class="wd-breadcrumbs" aria-label="Breadcrumb" data-pagefind-ignore data-markdown-ignore>
36
36
  <ol class="wd-breadcrumb-list">
37
37
  <li class="wd-breadcrumb-item">
38
38
  <a href="/" class="wd-breadcrumb-home" aria-label="Home">
@@ -0,0 +1,118 @@
1
+ ---
2
+ // writedocs.json's `integrations.consent` - the banner that asks before the
3
+ // analytics integrations load. It's in the page hidden; src/scripts/
4
+ // consent.ts shows it when the reader hasn't answered yet (window.wdConsent,
5
+ // defined in <head> by consentLoaderScript() in lib/consent.js), and again
6
+ // when they follow a link to #cookie-settings.
7
+ //
8
+ // A strip along the bottom of the window rather than a dialog: the page
9
+ // stays readable and usable while it's there, so focus isn't trapped and
10
+ // nothing is covered that can't be scrolled into view (consent.ts pads the
11
+ // page's end by the banner's height).
12
+ interface Props {
13
+ consent: {
14
+ message: string;
15
+ acceptLabel: string;
16
+ declineLabel: string;
17
+ policyUrl: string | null;
18
+ policyLabel: string;
19
+ };
20
+ }
21
+ const { consent } = Astro.props as Props;
22
+ ---
23
+ <section class="wd-consent" id="wd-consent" aria-label="Cookie consent" data-pagefind-ignore hidden>
24
+ <div class="wd-consent-inner">
25
+ <p class="wd-consent-text">
26
+ {consent.message}{" "}
27
+ {consent.policyUrl && <a href={consent.policyUrl}>{consent.policyLabel}</a>}
28
+ </p>
29
+ <div class="wd-consent-actions">
30
+ <button type="button" class="wd-consent-button" data-consent="denied">{consent.declineLabel}</button>
31
+ <button type="button" class="wd-consent-button wd-consent-accept" data-consent="granted">{consent.acceptLabel}</button>
32
+ </div>
33
+ </div>
34
+ </section>
35
+
36
+ <script>
37
+ import { initConsent } from "../../scripts/consent";
38
+
39
+ initConsent(document);
40
+ document.addEventListener("astro:page-load", () => initConsent(document));
41
+ </script>
42
+
43
+ <style is:global>
44
+ .wd-consent {
45
+ position: fixed;
46
+ left: 0;
47
+ right: 0;
48
+ bottom: 0;
49
+ /* Above the topbar (10) and the page; below the search and image
50
+ overlays (100), which the reader opened on purpose. */
51
+ z-index: 50;
52
+ background: var(--wd-surface);
53
+ border-top: 1px solid var(--wd-border);
54
+ color: var(--wd-text);
55
+ box-shadow: 0 -4px 16px rgb(0 0 0 / 0.08);
56
+ }
57
+ .wd-consent[hidden] {
58
+ display: none;
59
+ }
60
+ .wd-consent-inner {
61
+ max-width: 1440px;
62
+ margin: 0 auto;
63
+ padding: 0.85rem 1.5rem;
64
+ display: flex;
65
+ align-items: center;
66
+ justify-content: space-between;
67
+ gap: 1rem 1.5rem;
68
+ }
69
+ .wd-consent-text {
70
+ margin: 0;
71
+ font-size: 0.88rem;
72
+ line-height: 1.5;
73
+ }
74
+ .wd-consent-text a {
75
+ color: var(--wd-primary);
76
+ text-decoration: underline;
77
+ }
78
+ .wd-consent-actions {
79
+ display: flex;
80
+ gap: 0.5rem;
81
+ flex-shrink: 0;
82
+ }
83
+ /* Both buttons the same size and weight but for the fill - declining is as
84
+ easy as accepting. */
85
+ .wd-consent-button {
86
+ font: inherit;
87
+ font-size: 0.85rem;
88
+ font-weight: 600;
89
+ padding: 0.45rem 1rem;
90
+ border-radius: 0.5rem;
91
+ border: 1px solid var(--wd-border);
92
+ background: var(--wd-background);
93
+ color: var(--wd-heading);
94
+ cursor: pointer;
95
+ }
96
+ .wd-consent-button:hover {
97
+ border-color: var(--wd-primary);
98
+ }
99
+ .wd-consent-accept {
100
+ background: var(--wd-primary);
101
+ border-color: var(--wd-primary);
102
+ color: var(--wd-on-primary);
103
+ }
104
+ .wd-consent-button:focus-visible {
105
+ outline: 2px solid var(--wd-primary);
106
+ outline-offset: 2px;
107
+ }
108
+ @media (max-width: 640px) {
109
+ .wd-consent-inner {
110
+ flex-direction: column;
111
+ align-items: stretch;
112
+ padding: 0.85rem 1rem;
113
+ }
114
+ .wd-consent-actions > .wd-consent-button {
115
+ flex: 1;
116
+ }
117
+ }
118
+ </style>
@@ -31,6 +31,7 @@
31
31
  // comment for the fuller rationale.
32
32
  import { isExternalHref, type DocsConfig, type Selector, type GlobalDropdownView } from '../../lib/config';
33
33
  import AppIcon from '../../components/AppIcon.astro';
34
+ import { logoWidth } from '../../lib/image-size.js';
34
35
  import { hasMobileMenu, currentOption } from '../../lib/selector-placement.js';
35
36
  import '../styles/dropdown.css';
36
37
  import '../styles/topbar.css';
@@ -82,8 +83,8 @@ const showMenu = hasMobileMenu({ sidebar: showSidebarCol, selectors, globalDropd
82
83
  </svg>
83
84
  </button>
84
85
  <a class="wd-topbar-brand" href="/">
85
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
86
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
86
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
87
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
87
88
  {brandLabel && <span>{brandLabel}</span>}
88
89
  </a>
89
90
  {/* Same class as the real topbar's own theme button -
@@ -81,8 +81,8 @@ const { navTree, hrefForSlug, currentSlug, switchers = [] } = Astro.props as Pro
81
81
  <NavTree nodes={navTree} hrefForSlug={hrefForSlug} currentSlug={currentSlug} />
82
82
  {!watermarkDisabled && (
83
83
  <div class="wd-sidebar-watermark">
84
- <img src={watermarkForLightTheme.src} alt="Powered by writedocs" class="wd-watermark-light" />
85
- <img src={watermarkForDarkTheme.src} alt="Powered by writedocs" class="wd-watermark-dark" />
84
+ <img src={watermarkForLightTheme.src} alt="Powered by writedocs" class="wd-watermark-light" width={watermarkForLightTheme.width} height={watermarkForLightTheme.height} loading="lazy" decoding="async" />
85
+ <img src={watermarkForDarkTheme.src} alt="Powered by writedocs" class="wd-watermark-dark" width={watermarkForDarkTheme.width} height={watermarkForDarkTheme.height} loading="lazy" decoding="async" />
86
86
  </div>
87
87
  )}
88
88
  </nav>
@@ -11,6 +11,7 @@
11
11
  // comment for the fuller rationale.
12
12
  import { isExternalHref, type DocsConfig } from '../../lib/config';
13
13
  import AppIcon from '../../components/AppIcon.astro';
14
+ import { logoWidth } from '../../lib/image-size.js';
14
15
  import '../styles/footer.css';
15
16
 
16
17
  interface Props {
@@ -37,8 +38,8 @@ const hasFooterContent = config.footer.columns.length > 0 || socialEntries.lengt
37
38
  <div class="wd-footer-inner">
38
39
  {hasLogoImage && (
39
40
  <a class="wd-footer-brand" href="/">
40
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
41
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
41
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
42
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
42
43
  </a>
43
44
  )}
44
45
  {config.footer.columns.length > 0 && (
@@ -13,6 +13,7 @@
13
13
  // comment for the fuller rationale.
14
14
  import { isExternalHref, type DocsConfig, type Selector, type GlobalDropdownView } from '../../lib/config';
15
15
  import AppIcon from '../../components/AppIcon.astro';
16
+ import { logoWidth } from '../../lib/image-size.js';
16
17
  import { selectorPlacements, hasMobileMenu, currentOption } from '../../lib/selector-placement.js';
17
18
  import '../styles/dropdown.css';
18
19
  import '../styles/topbar.css';
@@ -92,8 +93,8 @@ const tabRows = tabSelectors.length > 0 ? tabSelectors : globalDropdowns.length
92
93
  </button>
93
94
  )}
94
95
  <a class="wd-topbar-brand" href="/">
95
- {logoLight && <img src={logoLight} alt={config.name} height="24" class="wd-logo-light" />}
96
- {logoDark && <img src={logoDark} alt={config.name} height="24" class="wd-logo-dark" />}
96
+ {logoLight && <img src={logoLight} alt={config.name} height="24" width={logoWidth(logoLight)} class="wd-logo-light" />}
97
+ {logoDark && <img src={logoDark} alt={config.name} height="24" width={logoWidth(logoDark)} class="wd-logo-dark" />}
97
98
  {brandLabel && <span title={brandLabel}>{brandLabel}</span>}
98
99
  </a>
99
100
 
@@ -245,6 +245,36 @@ pre {
245
245
  span, so it sizes like a glyph icon would. Lives here rather than in
246
246
  AppIcon.astro so it's part of the shared stylesheet, not an inline
247
247
  <style> added to every page. */
248
+ /* An image the build gave its file's width and height
249
+ (lib/rehype-image-loading.js): those attributes reserve its place while
250
+ it loads, and this keeps its height following its width when it's shown
251
+ narrower than the file - without it, the height attribute would stretch
252
+ it. :where() adds no specificity, so any rule that sets a height wins. */
253
+ /* The note for AI agents at the top of every page (lib/agent-directive.js):
254
+ in the HTML, where an agent reads it, and out of sight. Clipped rather
255
+ than display: none, which HTML-to-text converters often drop. */
256
+ .wd-agent-note {
257
+ position: absolute;
258
+ width: 1px;
259
+ height: 1px;
260
+ margin: -1px;
261
+ padding: 0;
262
+ overflow: hidden;
263
+ clip: rect(0 0 0 0);
264
+ clip-path: inset(50%);
265
+ white-space: nowrap;
266
+ border: 0;
267
+ }
268
+ /* The logo has a width beside its height (logoWidth(), lib/image-size.js)
269
+ so its place is kept while it loads. `width: auto` lets a site's own CSS
270
+ change its height without squeezing it - the two attributes still tell
271
+ the browser its proportions. */
272
+ :where(.wd-logo-light, .wd-logo-dark) {
273
+ width: auto;
274
+ }
275
+ :where(img[data-wd-sized]) {
276
+ height: auto;
277
+ }
248
278
  img.wd-icon-img {
249
279
  display: block;
250
280
  width: 1em;
@@ -0,0 +1,47 @@
1
+ // Telling an AI agent where the documentation index is. An agent that
2
+ // lands on one page - its HTML, or its Markdown copy - has no way to know
3
+ // the site has an llms.txt listing every page, or that each page has a
4
+ // Markdown version, unless the page says so. Two short notes do:
5
+ //
6
+ // - in every HTML page, a line at the very top of <body>, hidden from
7
+ // sight and from screen readers (BaseLayout.astro, .wd-agent-note in
8
+ // base.css) - an agent reading the HTML meets it before the navigation;
9
+ // - in every page's Markdown copy, a blockquote under the title
10
+ // (src/pages/[...slug].md.ts).
11
+ //
12
+ // A third convention lives in the components, not here: an element of a
13
+ // page that isn't content but sits inside the content area - the "Copy
14
+ // page" menu, the breadcrumbs, the "#" link beside a title, previous/next -
15
+ // carries `data-markdown-ignore`. The Markdown copy has none of them, and
16
+ // the attribute tells a tool comparing the two that this is on purpose.
17
+ //
18
+ // Plain JavaScript, for scripts/agent-directive.test.js.
19
+
20
+ /** The index's address: a full URL with a `domain`, else from the site's root. */
21
+ export function llmsIndexUrl(siteUrl) {
22
+ return siteUrl ? `${siteUrl}/llms.txt` : '/llms.txt';
23
+ }
24
+
25
+ /** The note for an HTML page: `{ href, before, link, after }` - the text
26
+ * around the link to llms.txt. `markdownPages` says whether pages have a
27
+ * Markdown copy (off with `"contextMenu": false`). */
28
+ export function htmlDirective({ siteUrl = null, markdownPages = true } = {}) {
29
+ return {
30
+ href: llmsIndexUrl(siteUrl),
31
+ before: 'For AI agents: the documentation index is at ',
32
+ link: '/llms.txt',
33
+ after: markdownPages ? '. A Markdown version of every page is available by adding .md to its address.' : '.',
34
+ };
35
+ }
36
+
37
+ /** The note for a page's Markdown copy, as a blockquote. */
38
+ export function markdownDirective(siteUrl = null) {
39
+ return `> For the complete documentation index, see [llms.txt](${llmsIndexUrl(siteUrl)}).`;
40
+ }
41
+
42
+ /** A page's Markdown copy: its title, the note, its description - the line
43
+ * the page shows under its title - then its content. */
44
+ export function pageMarkdownDocument(title, body, siteUrl = null, description = undefined) {
45
+ const intro = typeof description === 'string' && description.trim() ? `${description.trim()}\n\n` : '';
46
+ return `# ${title}\n\n${markdownDirective(siteUrl)}\n\n${intro}${body}`;
47
+ }
@@ -12,6 +12,7 @@ import fs from 'node:fs';
12
12
  import path from 'node:path';
13
13
  import matter from 'gray-matter';
14
14
  import { applyVisibilityForAgents } from './visibility.js';
15
+ import { componentsToMarkdown } from './components-to-markdown.js';
15
16
 
16
17
  /** `text` with `transform` applied to everything outside fenced code blocks
17
18
  * and inline code spans; code comes back untouched. */
@@ -43,7 +44,9 @@ export function mapOutsideCode(text, transform) {
43
44
  function mapOutsideInlineCode(text, transform) {
44
45
  // Backtick runs of equal length delimit a code span (CommonMark).
45
46
  return text
46
- .split(/(`+)([\s\S]*?)(\1)(?!`)/)
47
+ // A closing run is a whole run: in "` ```bash `" the three backticks
48
+ // inside don't close the span that one backtick opened.
49
+ .split(/(?<!`)(`+)(?!`)([\s\S]*?)(?<!`)(\1)(?!`)/)
47
50
  .reduce((acc, part, i, parts) => {
48
51
  const k = i % 4;
49
52
  if (k === 0) acc.push(transform(part));
@@ -133,10 +136,27 @@ export function inlineSnippets(text, { file, contentDir, depth = 0 }) {
133
136
  return result.replace(/\n{3,}/g, '\n\n');
134
137
  }
135
138
 
139
+ /** Links and images written from the site's root (`/docs/setup/`) as full
140
+ * URLs. A page copied out of the site - pasted into a chat, fetched by an
141
+ * agent, read from llms-full.txt - has no site to resolve them against.
142
+ * Markdown links and images, and the `href`/`src`/`img` of a component;
143
+ * code is left as written, and so is everything without a `siteUrl`. */
144
+ export function absolutizeLinks(text, siteUrl) {
145
+ if (!siteUrl) return text;
146
+ return mapOutsideCode(text, (prose) =>
147
+ prose
148
+ .replace(/(\]\()\/(?!\/)/g, `$1${siteUrl}/`)
149
+ .replace(/(\b(?:href|src|img)=["'])\/(?!\/)/g, `$1${siteUrl}/`)
150
+ );
151
+ }
152
+
136
153
  /** A page's body as an agent should read it. `file` is the page's absolute
137
154
  * path (to resolve relative snippet imports). */
138
155
  export function markdownForAgents(body, { file, contentDir, variables }) {
139
156
  let text = applyVisibilityForAgents(body ?? '');
140
157
  if (file) text = inlineSnippets(text, { file, contentDir });
141
- return substituteVariables(text, variables);
158
+ text = substituteVariables(text, variables);
159
+ // Components as the Markdown that says what they show
160
+ // (lib/components-to-markdown.js) - in an .mdx page; a .md page has none.
161
+ return file && /\.md$/i.test(file) ? text : componentsToMarkdown(text);
142
162
  }