@stainless-api/docs 0.1.0-beta.4 → 0.1.0-beta.41

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 (108) hide show
  1. package/CHANGELOG.md +297 -0
  2. package/components/variables.css +2 -32
  3. package/eslint-suppressions.json +47 -0
  4. package/locals.d.ts +14 -0
  5. package/package.json +35 -31
  6. package/plugin/buildAlgoliaIndex.ts +31 -6
  7. package/plugin/cms/server.ts +98 -55
  8. package/plugin/cms/sidebar-builder.ts +7 -26
  9. package/plugin/cms/worker.ts +3 -3
  10. package/plugin/components/SDKSelect.astro +7 -5
  11. package/plugin/components/SnippetCode.tsx +11 -7
  12. package/plugin/components/search/SearchAlgolia.astro +5 -20
  13. package/plugin/components/search/SearchIsland.tsx +33 -22
  14. package/plugin/generateAPIReferenceLink.ts +2 -2
  15. package/plugin/globalJs/ai-dropdown-options.ts +235 -0
  16. package/plugin/globalJs/navigation.ts +7 -27
  17. package/plugin/helpers/getPageLoadEvent.ts +1 -1
  18. package/plugin/index.ts +52 -25
  19. package/plugin/languages.ts +2 -2
  20. package/plugin/loadPluginConfig.ts +103 -32
  21. package/plugin/middlewareBuilder/stainlessMiddleware.d.ts +1 -1
  22. package/plugin/react/Routing.tsx +60 -57
  23. package/plugin/referencePlaceholderUtils.ts +1 -1
  24. package/plugin/replaceSidebarPlaceholderMiddleware.ts +5 -1
  25. package/plugin/routes/Docs.astro +59 -85
  26. package/plugin/routes/Overview.astro +10 -16
  27. package/plugin/routes/markdown.ts +7 -7
  28. package/plugin/vendor/preview.worker.docs.js +7566 -6784
  29. package/resolveSrcFile.ts +10 -0
  30. package/scripts/vendor_deps.ts +1 -1
  31. package/shared/getSharedLogger.ts +15 -0
  32. package/shared/terminalUtils.ts +3 -0
  33. package/src/content.config.ts +9 -0
  34. package/stl-docs/components/AIDropdown.tsx +63 -0
  35. package/stl-docs/components/{content-panel/ContentBreadcrumbs.tsx → ContentBreadcrumbs.tsx} +2 -2
  36. package/stl-docs/components/Head.astro +16 -0
  37. package/stl-docs/components/Header.astro +3 -2
  38. package/stl-docs/components/PageTitle.astro +82 -0
  39. package/stl-docs/components/TableOfContents.astro +34 -0
  40. package/stl-docs/components/ThemeSelect.astro +80 -112
  41. package/stl-docs/components/content-panel/ContentPanel.astro +9 -39
  42. package/stl-docs/components/headers/DefaultHeader.astro +1 -1
  43. package/stl-docs/components/headers/HeaderLinks.astro +1 -1
  44. package/stl-docs/components/headers/SplashMobileMenuToggle.astro +19 -0
  45. package/stl-docs/components/headers/StackedHeader.astro +29 -24
  46. package/stl-docs/components/icons/chat-gpt.tsx +17 -0
  47. package/stl-docs/components/icons/claude.tsx +10 -0
  48. package/stl-docs/components/icons/cursor.tsx +10 -0
  49. package/stl-docs/components/icons/gemini.tsx +19 -0
  50. package/stl-docs/components/icons/markdown.tsx +10 -0
  51. package/stl-docs/components/index.ts +1 -0
  52. package/stl-docs/components/mintlify-compat/Accordion.astro +7 -38
  53. package/stl-docs/components/mintlify-compat/AccordionGroup.astro +9 -23
  54. package/stl-docs/components/mintlify-compat/Columns.astro +40 -42
  55. package/stl-docs/components/mintlify-compat/Frame.astro +16 -18
  56. package/stl-docs/components/mintlify-compat/Step.astro +30 -32
  57. package/stl-docs/components/mintlify-compat/Steps.astro +8 -10
  58. package/stl-docs/components/mintlify-compat/callouts/Callout.astro +10 -3
  59. package/stl-docs/components/mintlify-compat/callouts/Check.astro +7 -3
  60. package/stl-docs/components/mintlify-compat/callouts/Danger.astro +7 -3
  61. package/stl-docs/components/mintlify-compat/callouts/Info.astro +7 -3
  62. package/stl-docs/components/mintlify-compat/callouts/Note.astro +7 -3
  63. package/stl-docs/components/mintlify-compat/callouts/Tip.astro +7 -3
  64. package/stl-docs/components/mintlify-compat/callouts/Warning.astro +7 -3
  65. package/stl-docs/components/mintlify-compat/card.css +33 -35
  66. package/stl-docs/components/nav-tabs/NavDropdown.astro +29 -63
  67. package/stl-docs/components/nav-tabs/NavTabs.astro +79 -65
  68. package/stl-docs/components/nav-tabs/SecondaryNavTabs.astro +15 -7
  69. package/stl-docs/components/nav-tabs/buildNavLinks.ts +4 -3
  70. package/stl-docs/components/pagination/HomeLink.astro +10 -0
  71. package/stl-docs/components/pagination/Pagination.astro +173 -0
  72. package/stl-docs/components/pagination/PaginationLinkEmphasized.astro +22 -0
  73. package/stl-docs/components/pagination/PaginationLinkQuiet.astro +13 -0
  74. package/stl-docs/components/pagination/util.ts +71 -0
  75. package/stl-docs/components/scripts.ts +1 -0
  76. package/stl-docs/components/{Sidebar.astro → sidebars/BaseSidebar.astro} +2 -3
  77. package/stl-docs/components/sidebars/SDKSelectSidebar.astro +8 -0
  78. package/stl-docs/disableCalloutSyntax.ts +36 -0
  79. package/stl-docs/index.ts +76 -27
  80. package/stl-docs/loadStlDocsConfig.ts +35 -5
  81. package/stl-docs/proseMarkdown/proseMarkdownIntegration.ts +64 -0
  82. package/stl-docs/proseMarkdown/proseMarkdownMiddleware.ts +34 -0
  83. package/stl-docs/proseMarkdown/toMarkdown.ts +158 -0
  84. package/stl-docs/tabsMiddleware.ts +12 -4
  85. package/styles/code.css +115 -127
  86. package/styles/fonts.css +32 -17
  87. package/styles/links.css +10 -49
  88. package/styles/overrides.css +53 -57
  89. package/styles/page.css +90 -59
  90. package/styles/sdk_select.css +9 -7
  91. package/styles/search.css +59 -69
  92. package/styles/sidebar.css +190 -127
  93. package/styles/toc.css +37 -33
  94. package/theme.css +9 -1
  95. package/tsconfig.json +2 -5
  96. package/virtual-module.d.ts +7 -4
  97. package/plugin/globalJs/ai-dropdown.ts +0 -57
  98. package/stl-docs/components/APIReferenceAIDropdown.tsx +0 -86
  99. package/stl-docs/components/content-panel/ProseAIDropdown.tsx +0 -64
  100. /package/{plugin/assets → assets}/fonts/geist/OFL.txt +0 -0
  101. /package/{plugin/assets → assets}/fonts/geist/geist-italic-latin-ext.woff2 +0 -0
  102. /package/{plugin/assets → assets}/fonts/geist/geist-italic-latin.woff2 +0 -0
  103. /package/{plugin/assets → assets}/fonts/geist/geist-latin-ext.woff2 +0 -0
  104. /package/{plugin/assets → assets}/fonts/geist/geist-latin.woff2 +0 -0
  105. /package/{plugin/assets → assets}/fonts/geist/geist-mono-italic-latin-ext.woff2 +0 -0
  106. /package/{plugin/assets → assets}/fonts/geist/geist-mono-italic-latin.woff2 +0 -0
  107. /package/{plugin/assets → assets}/fonts/geist/geist-mono-latin-ext.woff2 +0 -0
  108. /package/{plugin/assets → assets}/fonts/geist/geist-mono-latin.woff2 +0 -0
@@ -0,0 +1,71 @@
1
+ import type { StarlightRouteData } from '@astrojs/starlight/route-data';
2
+ import { getCollection } from 'astro:content';
3
+
4
+ export type SidebarEntry = StarlightRouteData['sidebar'][number];
5
+ export type SidebarLink = Extract<SidebarEntry, { type: 'link' }>;
6
+ export type SidebarGroup = Extract<SidebarEntry, { type: 'group' }>;
7
+
8
+ export const flattenSidebar = (sidebar: SidebarEntry[]): SidebarLink[] =>
9
+ sidebar.flatMap((e) => (e.type === 'group' ? flattenSidebar(e.entries) : e));
10
+
11
+ function findParentOfSidebarEntry(sidebar: SidebarEntry[], targetEntry: SidebarEntry): SidebarGroup | null {
12
+ for (const entry of sidebar) {
13
+ if (entry.type === 'group') {
14
+ if (entry.entries.includes(targetEntry)) {
15
+ return entry;
16
+ }
17
+ const foundInChild = findParentOfSidebarEntry(entry.entries, targetEntry);
18
+ if (foundInChild) {
19
+ return foundInChild;
20
+ }
21
+ }
22
+ }
23
+ return null;
24
+ }
25
+
26
+ export async function getPrevNextPage(page: StarlightRouteData, paginationEnabled: boolean) {
27
+ // TODO: respect user `next` / `prev` config from frontmatter the way starlight does
28
+
29
+ if (!paginationEnabled) return null;
30
+
31
+ const docsContent = await getCollection('docs');
32
+ const findSidebarLinkInContent = (link: SidebarLink) =>
33
+ docsContent.find((doc) => {
34
+ if (doc.id === 'index' && link.href === '/') return true;
35
+ return doc.id === link.href.replace(/^\//, '').replace(/\/$/, '');
36
+ });
37
+
38
+ const currentSidebar = page.sidebar;
39
+
40
+ const paginationSequence: (SidebarLink & { description?: string })[] = flattenSidebar(currentSidebar)
41
+ // Remove injected stl-mobile-only-sidebar-item links - TODO: better solution for this
42
+ .filter((link) => !(link.attrs.class ?? '').trim().split(/\s+/).includes('stl-mobile-only-sidebar-item'))
43
+ // Remove data-stldocs-method links from pagination sequence
44
+ .filter((link) => !link.attrs['data-stldocs-method'])
45
+ // Map data-stldocs-overview=readme links so that their name is not just “Overview”
46
+ .map((link) => {
47
+ if (link.attrs['data-stldocs-overview'] && link.label === 'Overview') {
48
+ const parent = findParentOfSidebarEntry(currentSidebar, link);
49
+ if (parent) return { ...link, label: parent.label };
50
+ }
51
+ return link;
52
+ })
53
+ .map((link) => {
54
+ const contentEntry = findSidebarLinkInContent(link);
55
+ if (contentEntry) return { ...link, description: contentEntry.data.description };
56
+ return link;
57
+ });
58
+
59
+ const currentIndex = paginationSequence.findIndex((e) => e.isCurrent);
60
+ if (currentIndex === -1) return null;
61
+
62
+ const prevIndex = currentIndex > 0 ? currentIndex - 1 : null;
63
+ const nextIndex = currentIndex < paginationSequence.length - 1 ? currentIndex + 1 : null;
64
+ const prevSidebarEntry = prevIndex !== null ? (paginationSequence[prevIndex] ?? null) : null;
65
+ const nextSidebarEntry = nextIndex !== null ? (paginationSequence[nextIndex] ?? null) : null;
66
+
67
+ return {
68
+ prev: prevSidebarEntry,
69
+ next: nextSidebarEntry,
70
+ };
71
+ }
@@ -0,0 +1 @@
1
+ export * from '@stainless-api/ui-primitives/scripts';
@@ -1,11 +1,10 @@
1
1
  ---
2
2
  import Default from '@astrojs/starlight/components/Sidebar.astro';
3
- import SDKSelect from '../../plugin/components/SDKSelect.astro';
4
- import HeaderLinks from './headers/HeaderLinks.astro';
3
+ import HeaderLinks from '../headers/HeaderLinks.astro';
5
4
  ---
6
5
 
7
6
  <div class="stl-sidebar-header-links">
8
7
  <HeaderLinks />
9
8
  </div>
10
- <SDKSelect />
9
+ <slot name="sdk-select" />
11
10
  <Default><slot /></Default>
@@ -0,0 +1,8 @@
1
+ ---
2
+ import BaseSidebar from './BaseSidebar.astro';
3
+ import SDKSelect from '../../../plugin/components/SDKSelect.astro';
4
+ ---
5
+
6
+ <BaseSidebar>
7
+ <SDKSelect slot="sdk-select" />
8
+ </BaseSidebar>
@@ -0,0 +1,36 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import type { StarlightPlugin } from '@astrojs/starlight/types';
3
+
4
+ export const disableCalloutSyntaxAstroIntegration = {
5
+ name: 'stl-starlight-remove-callout-syntax',
6
+ hooks: {
7
+ 'astro:config:setup': ({ config: astroConfig }) => {
8
+ // Remove starlight callout syntax in favor of our own callout component
9
+ // updateConfig always deeply merges arrays so we need to mutate remarkPlugins directly
10
+ // in order to remove plugins that starlight added
11
+ astroConfig.markdown.remarkPlugins = astroConfig.markdown.remarkPlugins.filter((plugin, i, arr) => {
12
+ if (typeof plugin !== 'function') return true;
13
+ // remove:
14
+ // 1. remarkDirective plugin
15
+ if (plugin.name === 'remarkDirective') return false;
16
+ // 2. directly followed by remarkAsides plugin (inner function named 'attacher')
17
+ if (plugin.name === 'attacher') {
18
+ const prev = arr[i - 1];
19
+ if (typeof prev === 'function' && prev.name === 'remarkDirective') return false;
20
+ }
21
+ // 3. remarkDirectivesRestoration plugin
22
+ if (plugin.name === 'remarkDirectivesRestoration') return false;
23
+ return true;
24
+ });
25
+ },
26
+ },
27
+ } satisfies AstroIntegration;
28
+
29
+ export const disableCalloutSyntaxStarlightPlugin = {
30
+ name: 'stl-starlight-remove-callout-syntax',
31
+ hooks: {
32
+ 'config:setup': ({ addIntegration }) => {
33
+ addIntegration(disableCalloutSyntaxAstroIntegration);
34
+ },
35
+ },
36
+ } satisfies StarlightPlugin;
package/stl-docs/index.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import starlight from '@astrojs/starlight';
2
2
  import react from '@astrojs/react';
3
+ import type { StarlightPlugin } from '@astrojs/starlight/types';
3
4
  import { stainlessStarlight } from '../plugin';
5
+ import { disableCalloutSyntaxStarlightPlugin } from './disableCalloutSyntax';
4
6
 
5
7
  import type { AstroIntegration } from 'astro';
6
8
 
@@ -16,11 +18,15 @@ import {
16
18
  type StarlightSidebarConfig,
17
19
  } from './loadStlDocsConfig';
18
20
  import { buildVirtualModuleString } from '../shared/virtualModule';
19
-
20
- import geistPath from '../plugin/assets/fonts/geist/geist-latin.woff2?url';
21
+ import type * as StlDocsVirtualModule from 'virtual:stl-docs-virtual-module';
22
+ import { resolveSrcFile } from '../resolveSrcFile';
23
+ import { stainlessDocsMarkdownRenderer } from './proseMarkdown/proseMarkdownIntegration';
24
+ import { setSharedLogger } from '../shared/getSharedLogger';
21
25
 
22
26
  export * from '../plugin';
23
27
 
28
+ const COMPONENTS_FOLDER = '/stl-docs/components';
29
+
24
30
  function stainlessDocsStarlightIntegration(config: NormalizedStainlessDocsConfig) {
25
31
  // We transform our tabs into a Starlight sidebar
26
32
  // This gives them all the built-in features of Starlight (eg. auto-generated entries by directory)
@@ -41,13 +47,34 @@ function stainlessDocsStarlightIntegration(config: NormalizedStainlessDocsConfig
41
47
 
42
48
  type ComponentOverrides = StarlightConfigDefined['components'];
43
49
  const componentOverrides: ComponentOverrides = {
44
- Search: '@stainless-api/docs/Search',
45
- Sidebar: '@stainless-api/docs/Sidebar',
46
- Header: '@stainless-api/docs/Header',
47
- ThemeSelect: '@stainless-api/docs/ThemeSelect',
48
- ContentPanel: '@stainless-api/docs/ContentPanel',
50
+ Sidebar: resolveSrcFile(COMPONENTS_FOLDER, './sidebars/BaseSidebar.astro'),
51
+ Header: resolveSrcFile(COMPONENTS_FOLDER, './Header.astro'),
52
+ Head: resolveSrcFile(COMPONENTS_FOLDER, './Head.astro'),
53
+ ThemeSelect: resolveSrcFile(COMPONENTS_FOLDER, './ThemeSelect.astro'),
54
+ ContentPanel: resolveSrcFile(COMPONENTS_FOLDER, './content-panel/ContentPanel.astro'),
55
+ TableOfContents: resolveSrcFile(COMPONENTS_FOLDER, './TableOfContents.astro'),
56
+ PageTitle: resolveSrcFile(COMPONENTS_FOLDER, './PageTitle.astro'),
57
+ Pagination: resolveSrcFile(COMPONENTS_FOLDER, './pagination/Pagination.astro'),
49
58
  };
50
59
 
60
+ const plugins: StarlightPlugin[] = [
61
+ // Disable starlight callout syntax in favor of our own component
62
+ disableCalloutSyntaxStarlightPlugin,
63
+ ];
64
+
65
+ if (config.apiReference !== null) {
66
+ plugins.push(
67
+ stainlessStarlight({
68
+ ...config.apiReference,
69
+ contextMenu: config.contextMenu,
70
+ }),
71
+ );
72
+ componentOverrides.Sidebar = resolveSrcFile(COMPONENTS_FOLDER, './sidebars/SDKSelectSidebar.astro');
73
+ componentOverrides.Search = resolveSrcFile('/plugin/components/search/Search.astro');
74
+ }
75
+
76
+ plugins.push(...config.starlightCompat.plugins);
77
+
51
78
  // TODO: re-add once we figure out what to do with the client router
52
79
  // if (config.enableClientRouter) {
53
80
  // // logger.info(`Client router is enabled`);
@@ -79,33 +106,27 @@ function stainlessDocsStarlightIntegration(config: NormalizedStainlessDocsConfig
79
106
  setupNavLinksInitial();
80
107
  `,
81
108
  },
82
- // TODO: for users who are overriding the font stack in their own styles, how can we know that
83
- // and preload their font instead of ours?
84
- {
85
- tag: 'link',
86
- attrs: {
87
- rel: 'preload',
88
- as: 'font',
89
- type: 'font/woff2',
90
- crossorigin: 'anonymous',
91
- href: geistPath,
92
- },
93
- },
94
109
  ],
95
- routeMiddleware: [...config.starlightCompat.routeMiddleware, '@stainless-api/docs/tabsMiddleware'],
96
- customCss: ['@stainless-api/docs/theme', ...config.customCss],
97
- plugins: [stainlessStarlight(config.apiReference), ...config.starlightCompat.plugins],
110
+ routeMiddleware: [
111
+ ...config.starlightCompat.routeMiddleware,
112
+ resolveSrcFile('/stl-docs/tabsMiddleware.ts'),
113
+ ],
114
+ customCss: [resolveSrcFile('/theme.css'), ...config.customCss],
115
+ plugins,
98
116
  });
99
117
  }
100
118
 
101
- function stainlessDocsIntegration(config: NormalizedStainlessDocsConfig): AstroIntegration {
102
- const virtualId = `virtual:stl-stl-starlight-virtual-module`;
119
+ function stainlessDocsIntegration(
120
+ config: NormalizedStainlessDocsConfig,
121
+ apiReferenceBasePath: string | null,
122
+ ): AstroIntegration {
123
+ const virtualId = `virtual:stl-docs-virtual-module`;
103
124
  // The '\0' prefix tells Vite “this is a virtual module” and prevents it from being resolved again.
104
125
  const resolvedId = `\0${virtualId}`;
105
126
  let redirects: NormalizedRedirectConfig | null = null;
106
127
 
107
128
  return {
108
- name: 'stl-docs-integration',
129
+ name: 'stl-docs-astro',
109
130
  hooks: {
110
131
  'astro:config:setup': ({ updateConfig, command, config: astroConfig }) => {
111
132
  // // we only handle redirects for builds
@@ -132,7 +153,12 @@ function stainlessDocsIntegration(config: NormalizedStainlessDocsConfig): AstroI
132
153
  HEADER_LINKS: config.header.links,
133
154
  HEADER_LAYOUT: config.header.layout,
134
155
  ENABLE_CLIENT_ROUTER: config.enableClientRouter,
135
- });
156
+ API_REFERENCE_BASE_PATH: apiReferenceBasePath,
157
+ ENABLE_PROSE_MARKDOWN_RENDERING: config.enableProseMarkdownRendering,
158
+ // TODO: do not duplicate this between both virtual modules
159
+ ENABLE_CONTEXT_MENU: config.contextMenu,
160
+ RENDER_PAGE_DESCRIPTIONS: config.renderPageDescriptions,
161
+ } satisfies typeof StlDocsVirtualModule);
136
162
  }
137
163
  },
138
164
  },
@@ -158,6 +184,17 @@ function stainlessDocsIntegration(config: NormalizedStainlessDocsConfig): AstroI
158
184
  };
159
185
  }
160
186
 
187
+ function sharedLoggerIntegration(): AstroIntegration {
188
+ return {
189
+ name: 'stainless',
190
+ hooks: {
191
+ 'astro:config:setup': ({ logger }) => {
192
+ setSharedLogger(logger);
193
+ },
194
+ },
195
+ };
196
+ }
197
+
161
198
  export function stainlessDocs(config: StainlessDocsUserConfig) {
162
199
  const normalizedConfigResult = parseStlDocsConfig(config);
163
200
  if (normalizedConfigResult.result === 'error') {
@@ -166,9 +203,21 @@ export function stainlessDocs(config: StainlessDocsUserConfig) {
166
203
  process.exit(1);
167
204
  }
168
205
  const normalizedConfig = normalizedConfigResult.config;
206
+
207
+ // TODO: need to refactor this, but this allows us to get the base path for the API reference _if_ it exists
208
+ // if it doesn't exist, the value of basePath is null.
209
+ // the stl-starlight virtual module has base path, but it's not available when there's no API reference
210
+ const hasApiReference = normalizedConfig.apiReference !== null;
211
+ let apiReferenceBasePath: string | null = null;
212
+ if (hasApiReference) {
213
+ apiReferenceBasePath = normalizedConfig.apiReference?.basePath ?? '/api';
214
+ }
215
+
169
216
  return [
217
+ sharedLoggerIntegration(), // this **must** be first so it can set the shared logger used by our other integrations
170
218
  react(),
171
219
  stainlessDocsStarlightIntegration(normalizedConfig),
172
- stainlessDocsIntegration(normalizedConfig),
220
+ stainlessDocsIntegration(normalizedConfig, apiReferenceBasePath),
221
+ stainlessDocsMarkdownRenderer({ enabled: normalizedConfig.enableProseMarkdownRendering }),
173
222
  ];
174
223
  }
@@ -45,7 +45,8 @@ type Tabs = {
45
45
  sidebar?: SidebarEntry[];
46
46
  /**
47
47
  * Whether to hide the tab in the tab bar.
48
- * Defaults to `false`.
48
+ *
49
+ * @default false
49
50
  */
50
51
  hidden?: boolean;
51
52
  }[];
@@ -58,7 +59,7 @@ export type HeaderLink = {
58
59
  };
59
60
 
60
61
  export type StainlessDocsUserConfig = {
61
- apiReference: StainlessStarlightUserConfig;
62
+ apiReference?: StainlessStarlightUserConfig;
62
63
  tabs?: Tabs;
63
64
  header?: {
64
65
  layout?: HeaderLayout;
@@ -67,7 +68,26 @@ export type StainlessDocsUserConfig = {
67
68
  experimental?: {
68
69
  starlightCompat?: ExperimentalStarlightCompatibilityConfig;
69
70
  enableClientRouter?: boolean;
71
+ /**
72
+ * Disable markdown rendering for prose content. Only disable this if it is causing issues.
73
+ *
74
+ * @default false
75
+ */
76
+ disableProseMarkdownRendering?: boolean;
70
77
  };
78
+ /**
79
+ * Whether to show the context menu with options like "Copy as Markdown" and "Open in ChatGPT".
80
+ *
81
+ * @default true
82
+ */
83
+ contextMenu?: boolean;
84
+
85
+ /**
86
+ * Whether to render page descriptions in prose page headers
87
+ *
88
+ * @default true
89
+ */
90
+ renderPageDescriptions?: boolean;
71
91
  } & PassThroughStarlightConfigOptions;
72
92
 
73
93
  type HeaderLayout = 'default' | 'stacked';
@@ -119,6 +139,12 @@ function normalizeConfig(userConfig: StainlessDocsUserConfig) {
119
139
  description: userConfig.description,
120
140
  tagline: userConfig.tagline,
121
141
  logo: userConfig.logo,
142
+ favicon: userConfig.favicon,
143
+ disable404Route: userConfig.disable404Route,
144
+ editLink: userConfig.editLink,
145
+ locales: userConfig.locales,
146
+ lastUpdated: userConfig.lastUpdated,
147
+ pagination: userConfig.pagination,
122
148
  },
123
149
  starlightCompat: {
124
150
  components: userConfig.experimental?.starlightCompat?.components ?? {},
@@ -126,8 +152,12 @@ function normalizeConfig(userConfig: StainlessDocsUserConfig) {
126
152
  routeMiddleware: normalizeRouteMiddleware(userConfig),
127
153
  },
128
154
  enableClientRouter: userConfig.experimental?.enableClientRouter ?? false,
129
- apiReference: userConfig.apiReference,
155
+ apiReference: userConfig.apiReference ?? null,
130
156
  sidebar: userConfig.sidebar,
157
+ enableProseMarkdownRendering:
158
+ userConfig.experimental?.disableProseMarkdownRendering === true ? false : true,
159
+ contextMenu: userConfig.contextMenu ?? true,
160
+ renderPageDescriptions: userConfig.renderPageDescriptions ?? true,
131
161
  };
132
162
 
133
163
  return configWithDefaults;
@@ -136,11 +166,11 @@ function normalizeConfig(userConfig: StainlessDocsUserConfig) {
136
166
  export type NormalizedStainlessDocsConfig = ReturnType<typeof normalizeConfig>;
137
167
 
138
168
  /*
139
- The goal of the code in this file is to take a user's config and normalize it.
169
+ The goal of the code in this file is to take a user's config and normalize it.
140
170
  Specifically: we want a single complete config format used throughout the internals of the plugin.
141
171
 
142
172
  We've tried to avoid any config values being optional/undefined. To accomplish this:
143
- - Any optional config values should have their defaults set here: eg. basePath defaults to /api
173
+ - Any optional config values should have their defaults set here: eg. basePath defaults to /api
144
174
  - If a field is only used in certain contexts, we make each context a discriminated union (see SpecRetrieverConfig)
145
175
  - We prefer empty arrays over undefined/null
146
176
  */
@@ -0,0 +1,64 @@
1
+ import type { AstroIntegration } from 'astro';
2
+ import { readFile, writeFile } from 'fs/promises';
3
+ import { toMarkdown } from './toMarkdown';
4
+ import { resolveSrcFile } from '../../resolveSrcFile';
5
+ import { getSharedLogger } from '../../shared/getSharedLogger';
6
+ import { bold } from '../../shared/terminalUtils';
7
+
8
+ export function stainlessDocsMarkdownRenderer({ enabled }: { enabled: boolean }): AstroIntegration {
9
+ return {
10
+ name: 'stl-docs-md',
11
+ hooks: {
12
+ 'astro:config:setup': ({ addMiddleware }) => {
13
+ if (enabled) {
14
+ addMiddleware({
15
+ entrypoint: resolveSrcFile('/stl-docs/proseMarkdown/proseMarkdownMiddleware.ts'),
16
+ order: 'post',
17
+ });
18
+ }
19
+ },
20
+ 'astro:build:done': async ({ assets, logger: localLogger, dir }) => {
21
+ const logger = getSharedLogger({ fallback: localLogger });
22
+ if (!enabled) {
23
+ logger.info('Stainless Docs prose Markdown rendering is disabled, skipping...');
24
+ return;
25
+ }
26
+ const starlightPagePatterns = ['/[...slug]'];
27
+ const pagesToRender = Array.from(assets.entries())
28
+ .filter(([k]) => {
29
+ if (starlightPagePatterns.includes(k)) {
30
+ return true;
31
+ }
32
+ return false;
33
+ })
34
+ .map(([, v]) => v)
35
+ .flat()
36
+ .map((v) => v.pathname);
37
+
38
+ logger.info(bold(`Building ${pagesToRender.length} Markdown pages for prose content`));
39
+
40
+ const outputBasePath = dir.pathname;
41
+
42
+ let completedCount = 0;
43
+ for (const absHtmlPath of pagesToRender) {
44
+ const txt = await readFile(absHtmlPath, 'utf-8');
45
+ const md = await toMarkdown(txt);
46
+ if (md) {
47
+ const absMdPath = absHtmlPath.replace('.html', '.md');
48
+ await writeFile(absMdPath, md, 'utf-8');
49
+
50
+ completedCount++;
51
+
52
+ const relHtmlPath = absHtmlPath.replace(outputBasePath, '');
53
+ const relMdPath = absMdPath.replace(outputBasePath, '');
54
+
55
+ logger.info(`(${completedCount}/${pagesToRender.length}) ${relHtmlPath} -> ${relMdPath}`);
56
+ } else {
57
+ logger.error(`Failed to render ${absHtmlPath} as Markdown`);
58
+ process.exit(1);
59
+ }
60
+ }
61
+ },
62
+ },
63
+ };
64
+ }
@@ -0,0 +1,34 @@
1
+ import { defineMiddleware } from 'astro:middleware';
2
+ import { toMarkdown } from './toMarkdown';
3
+ import { API_REFERENCE_BASE_PATH } from 'virtual:stl-docs-virtual-module';
4
+
5
+ // this is only run in `astro dev` for rendering prose content as Markdown on the fly.
6
+ export const onRequest = defineMiddleware(async (context, next) => {
7
+ // eslint-disable-next-line turbo/no-undeclared-env-vars
8
+ if (!import.meta.env.DEV) {
9
+ return next();
10
+ }
11
+
12
+ if (API_REFERENCE_BASE_PATH && context.url.pathname.startsWith(API_REFERENCE_BASE_PATH)) {
13
+ // handled by the API reference API route in stl-starlight plugin
14
+ return next();
15
+ }
16
+
17
+ if (!context.url.pathname.endsWith('/index.md')) {
18
+ return next();
19
+ }
20
+
21
+ const htmlUrl = new URL(context.url.pathname.replace('index.md', ''), context.url);
22
+ const resp = await fetch(htmlUrl);
23
+ if (!resp.ok) {
24
+ return new Response('Failed to fetch HTML', { status: 400 });
25
+ }
26
+ const html = await resp.text();
27
+ const md = await toMarkdown(html);
28
+
29
+ if (!md) {
30
+ return new Response('Failed to render Markdown', { status: 400 });
31
+ }
32
+
33
+ return new Response(md, { status: 200 });
34
+ });
@@ -0,0 +1,158 @@
1
+ import { unified } from 'unified';
2
+ import rehypeParse from 'rehype-parse';
3
+ import rehypeRemark from 'rehype-remark';
4
+ import remarkGfm from 'remark-gfm';
5
+ import remarkStringify from 'remark-stringify';
6
+ import { HTMLElement, parse } from 'node-html-parser';
7
+
8
+ type PaginationLink = {
9
+ href: string;
10
+ label: string;
11
+ };
12
+
13
+ type PaginationItems = {
14
+ prev: PaginationLink | null;
15
+ next: PaginationLink | null;
16
+ };
17
+
18
+ function parsePaginationLink(footer: HTMLElement, rel: 'next' | 'prev'): PaginationLink | null {
19
+ const link = footer.querySelector(`.pagination-links a[rel="${rel}"]`);
20
+ if (!link) {
21
+ return null;
22
+ }
23
+
24
+ const title = link.querySelector('.link-title');
25
+ if (!title) {
26
+ return null;
27
+ }
28
+
29
+ const href = link.getAttribute('href');
30
+ if (!href) {
31
+ return null;
32
+ }
33
+
34
+ return {
35
+ href,
36
+ label: title.text,
37
+ };
38
+ }
39
+
40
+ function isRelativeLink(href: string) {
41
+ return href.startsWith('/');
42
+ }
43
+
44
+ function hasExtension(href: string) {
45
+ return href.includes('.');
46
+ }
47
+
48
+ function removeTrailingSlash(href: string) {
49
+ return href.replace(/\/$/, '');
50
+ }
51
+
52
+ function makeMarkdownLinks(el: HTMLElement) {
53
+ el.querySelectorAll('a').forEach((a) => {
54
+ const href = a.getAttribute('href');
55
+ if (!href) {
56
+ return a;
57
+ }
58
+
59
+ if (isRelativeLink(href) && !hasExtension(href)) {
60
+ if (href === '/') {
61
+ a.setAttribute('href', '/index.md');
62
+ } else {
63
+ a.setAttribute('href', `${removeTrailingSlash(href)}/index.md`);
64
+ }
65
+ }
66
+ return a;
67
+ });
68
+ }
69
+
70
+ function removeHiddenElements(el: HTMLElement) {
71
+ const hiddenSelectors = ['.sl-anchor-link'];
72
+ for (const selector of hiddenSelectors) {
73
+ const hiddenElements = el.querySelectorAll(selector);
74
+ for (const hiddenElement of hiddenElements) {
75
+ hiddenElement.remove();
76
+ }
77
+ }
78
+ }
79
+
80
+ export async function toMarkdown(html: string) {
81
+ const root = parse(html);
82
+
83
+ const mainEl = root.querySelector('main');
84
+
85
+ if (!mainEl) {
86
+ return null;
87
+ }
88
+
89
+ makeMarkdownLinks(mainEl);
90
+
91
+ const footer = mainEl.querySelector('footer');
92
+
93
+ const markdownContentEl = mainEl.querySelector('.sl-markdown-content');
94
+ if (!markdownContentEl) {
95
+ return null;
96
+ }
97
+
98
+ removeHiddenElements(markdownContentEl);
99
+
100
+ const articleContent = markdownContentEl.innerHTML;
101
+
102
+ const paginationLinks: PaginationItems = {
103
+ prev: null,
104
+ next: null,
105
+ };
106
+
107
+ if (footer) {
108
+ paginationLinks.prev = parsePaginationLink(footer, 'prev');
109
+ paginationLinks.next = parsePaginationLink(footer, 'next');
110
+ }
111
+
112
+ let md = (
113
+ await unified()
114
+ .use(rehypeParse, { fragment: true }) // parse HTML
115
+ .use(rehypeRemark) // rehype (HTML) -> remark (MD AST)
116
+ .use(remarkGfm) // tables, strikethrough, autolinks, etc.
117
+ .use(remarkStringify, {
118
+ fences: true,
119
+ bullet: '-',
120
+ listItemIndent: 'one',
121
+ rule: '-',
122
+ })
123
+ .process(articleContent)
124
+ ).toString();
125
+
126
+ const title = root.querySelector('title')?.textContent;
127
+ const description = root.querySelector('meta[name="description"]')?.attributes.content;
128
+ const lastUpdated = root.querySelector('.meta time')?.attributes.datetime;
129
+
130
+ // let htmlUrl = url.toString().replace('.md', '');
131
+ // if (htmlUrl.endsWith('/index')) {
132
+ // htmlUrl = htmlUrl.replace('/index', '');
133
+ // }
134
+
135
+ md = [
136
+ '---',
137
+ `title: ${title}`,
138
+ description ? `description: ${description}` : [],
139
+ lastUpdated ? `lastUpdated: ${lastUpdated}` : [],
140
+ // `source_url:`,
141
+ // ` html: ${htmlUrl}`,
142
+ // ` md: ${url.toString()}`,
143
+ '---\n',
144
+ md,
145
+ ]
146
+ .flat()
147
+ .join('\n');
148
+
149
+ if (paginationLinks.prev) {
150
+ md += `\n\n[Previous](${paginationLinks.prev.href})`;
151
+ }
152
+
153
+ if (paginationLinks.next) {
154
+ md += `\n\n[Next](${paginationLinks.next.href})`;
155
+ }
156
+
157
+ return md;
158
+ }