igniteui-astro-components 0.0.27 → 0.0.29

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 (96) hide show
  1. package/README.md +82 -74
  2. package/package.json +16 -2
  3. package/src/assets/images/anatomy-test.png +0 -0
  4. package/src/components/CopyCode/CopyCode.astro +21 -7
  5. package/src/components/DocsBreadcrumb/DocsBreadcrumb.astro +33 -21
  6. package/src/components/DocsBreadcrumb/DocsBreadcrumb.scss +44 -43
  7. package/src/components/DocsBreadcrumb/README.md +10 -14
  8. package/src/components/DocsSidebar/DocsSidebar.astro +47 -45
  9. package/src/components/DocsSidebar/DocsSidebar.scss +120 -122
  10. package/src/components/DocsSidebar/README.md +25 -21
  11. package/src/components/DocsSidebar/SidebarFilterInput.astro +24 -29
  12. package/src/components/DocsSidebar/SidebarFilterInput.scss +90 -89
  13. package/src/components/DocsSidebar/SidebarLabel.astro +35 -26
  14. package/src/components/DocsSidebar/sidebar-filter.ts +93 -56
  15. package/src/components/DocsSubHeader/DocsSubHeader.astro +256 -195
  16. package/src/components/DocsSubHeader/DocsSubHeader.scss +181 -178
  17. package/src/components/DocsSubHeader/README.md +18 -16
  18. package/src/components/DocsToc/DocsToc.astro +301 -280
  19. package/src/components/DocsToc/DocsToc.scss +20 -21
  20. package/src/components/DocsToc/README.md +11 -9
  21. package/src/components/DocsToc/toTreeNodes.ts +3 -8
  22. package/src/components/DocsTree/DocsTree.astro +32 -20
  23. package/src/components/DocsTree/DocsTreeItem.astro +35 -30
  24. package/src/components/DocsTree/README.md +16 -15
  25. package/src/components/DocsTree/docs-tree.scss +267 -268
  26. package/src/components/GlobalFooter/GlobalFooter.astro +10 -10
  27. package/src/components/GlobalFooter/README.md +3 -2
  28. package/src/components/GlobalNavBar/GlobalNavBar.astro +4 -2
  29. package/src/components/GlobalNavBar/GlobalNavBar.module.scss +222 -222
  30. package/src/components/GlobalNavBar/README.md +3 -2
  31. package/src/components/LicenseIndicator/LicenseIndicator.astro +7 -5
  32. package/src/components/LicenseIndicator/LicenseIndicator.scss +3 -3
  33. package/src/components/MobileSidebarToggle/MobileSidebarToggle.astro +16 -17
  34. package/src/components/MobileSidebarToggle/README.md +3 -2
  35. package/src/components/MobileTocToggle/MobileTocToggle.astro +75 -61
  36. package/src/components/MobileTocToggle/MobileTocToggle.scss +65 -59
  37. package/src/components/Search/README.md +1 -0
  38. package/src/components/Search/Search.astro +137 -109
  39. package/src/components/Search/Search.scss +20 -20
  40. package/src/components/SearchAdvanced/README.md +21 -15
  41. package/src/components/SearchAdvanced/SearchAdvanced.astro +205 -133
  42. package/src/components/SearchAdvanced/SearchAdvanced.scss +152 -153
  43. package/src/components/mdx/Anatomy/Anatomy.astro +51 -0
  44. package/src/components/mdx/Anatomy/Anatomy.scss +40 -0
  45. package/src/components/mdx/ApiLink/ApiLink.astro +133 -113
  46. package/src/components/mdx/ApiLink/ApiLink.scss +9 -9
  47. package/src/components/mdx/ApiLink/README.md +26 -22
  48. package/src/components/mdx/ApiLink/api-link-index.ts +196 -173
  49. package/src/components/mdx/ApiRef/ApiRef.astro +54 -51
  50. package/src/components/mdx/ApiRef/README.md +20 -15
  51. package/src/components/mdx/Badge/Badge.astro +14 -14
  52. package/src/components/mdx/Badge/Badge.scss +61 -56
  53. package/src/components/mdx/Badge/README.md +24 -19
  54. package/src/components/mdx/DocsAside/DocsAside.astro +30 -37
  55. package/src/components/mdx/DocsAside/DocsAside.scss +82 -82
  56. package/src/components/mdx/DocsAside/README.md +22 -22
  57. package/src/components/mdx/Faq/Faq.astro +86 -0
  58. package/src/components/mdx/Faq/Faq.scss +105 -0
  59. package/src/components/mdx/Faq/FaqItem.astro +117 -0
  60. package/src/components/mdx/Faq/README.md +223 -0
  61. package/src/components/mdx/Faq/types.ts +34 -0
  62. package/src/components/mdx/PlatformBlock/PlatformBlock.astro +3 -2
  63. package/src/components/mdx/PlatformBlock/README.md +6 -8
  64. package/src/components/mdx/Sample/README.md +21 -16
  65. package/src/components/mdx/Sample/Sample.astro +97 -74
  66. package/src/components/mdx/Sample/Sample.scss +132 -132
  67. package/src/content-helper.ts +71 -72
  68. package/src/content.config.ts +1 -6
  69. package/src/integration.ts +566 -512
  70. package/src/layouts/DocsLayout/DocsLayout.astro +228 -182
  71. package/src/layouts/DocsLayout/DocsLayout.scss +261 -261
  72. package/src/layouts/DocsLayout/README.md +24 -35
  73. package/src/lib/nav-helpers.ts +88 -82
  74. package/src/lib/types.ts +76 -76
  75. package/src/llms.ts +205 -166
  76. package/src/platform.ts +312 -162
  77. package/src/plugins/rehype-heading-anchors.ts +45 -45
  78. package/src/plugins/rehype-pagefind-ignore.ts +19 -19
  79. package/src/plugins/rehype-table-wrapper.ts +30 -30
  80. package/src/plugins/remark-docfx.ts +12 -0
  81. package/src/plugins/remark-env-vars.ts +12 -4
  82. package/src/plugins/remark-md-links.ts +10 -4
  83. package/src/scripts/icon-manifest.ts +13 -5
  84. package/src/scripts/sample-widget.ts +557 -501
  85. package/src/sidebar.ts +103 -97
  86. package/src/styles/global/_code-blocks.scss +43 -44
  87. package/src/styles/global/_component-themes.scss +151 -153
  88. package/src/styles/global/_icon-gallery.scss +81 -81
  89. package/src/styles/global/_index.scss +0 -1
  90. package/src/styles/global/_markdown.scss +816 -787
  91. package/src/styles/global/_palette.scss +456 -110
  92. package/src/styles/global/_search-shared.scss +402 -398
  93. package/src/styles/global/_type-scale.scss +127 -127
  94. package/src/styles/global/_variables.scss +138 -111
  95. package/src/styles/theme.scss +41 -41
  96. package/src/virtual-modules.d.ts +11 -2
@@ -55,8 +55,13 @@ import { defineConfig } from 'astro/config';
55
55
  import type { AstroIntegration } from 'astro';
56
56
  import mdx from '@astrojs/mdx';
57
57
  import {
58
- buildLlmsTxt, buildLlmsMetaMap, getBroadSectionsForPlatform, toUrlSlug,
59
- type LlmsMeta, type LlmsSet, type SidebarItem,
58
+ buildLlmsTxt,
59
+ buildLlmsMetaMap,
60
+ getBroadSectionsForPlatform,
61
+ toUrlSlug,
62
+ type LlmsMeta,
63
+ type LlmsSet,
64
+ type SidebarItem,
60
65
  } from './llms.ts';
61
66
  import { buildSidebarFromToc } from './sidebar';
62
67
  import { getPlatformHead } from './platform';
@@ -79,36 +84,36 @@ export type DocsMode = 'development' | 'staging' | 'production';
79
84
  // ---------------------------------------------------------------------------
80
85
 
81
86
  export interface ProductLink {
82
- /** Display label shown in the DocsSubHeader, e.g. `"Angular"`. */
83
- label: string;
84
- /** Absolute or root-relative href to the sibling docs site. */
85
- href: string;
86
- /**
87
- * Optional platform key (matches `PlatformKey`).
88
- * When it equals the current build's platform the link is omitted from the DocsSubHeader.
89
- */
90
- platform?: PlatformKey;
87
+ /** Display label shown in the DocsSubHeader, e.g. `"Angular"`. */
88
+ label: string;
89
+ /** Absolute or root-relative href to the sibling docs site. */
90
+ href: string;
91
+ /**
92
+ * Optional platform key (matches `PlatformKey`).
93
+ * When it equals the current build's platform the link is omitted from the DocsSubHeader.
94
+ */
95
+ platform?: PlatformKey;
91
96
  }
92
97
 
93
98
  export interface SiteMetaOptions {
94
- title: string;
95
- description?: string;
96
- /** Path to the source markdown files. */
97
- docsDir?: string;
98
- sidebar?: SidebarItem[];
99
- platform?: PlatformKey | null;
100
- navLang?: NavLang;
101
- /** Build / deployment mode. Exposed via `process.env.DOCS_BUILD_MODE`. */
102
- mode?: DocsMode;
103
- /** Named documentation subsets linked from llms.txt. */
104
- llmsSets?: LlmsSet[];
105
- /** Cross-product navigation links rendered in the DocsSubHeader. */
106
- productLinks?: ProductLink[];
107
- /**
108
- * Extra `<head>` entries injected via the `virtual:docs-template/site-meta`
109
- * module and rendered by `DocsLayout.astro`.
110
- */
111
- head?: HeadEntry[];
99
+ title: string;
100
+ description?: string;
101
+ /** Path to the source markdown files. */
102
+ docsDir?: string;
103
+ sidebar?: SidebarItem[];
104
+ platform?: PlatformKey | null;
105
+ navLang?: NavLang;
106
+ /** Build / deployment mode. Exposed via `process.env.DOCS_BUILD_MODE`. */
107
+ mode?: DocsMode;
108
+ /** Named documentation subsets linked from llms.txt. */
109
+ llmsSets?: LlmsSet[];
110
+ /** Cross-product navigation links rendered in the DocsSubHeader. */
111
+ productLinks?: ProductLink[];
112
+ /**
113
+ * Extra `<head>` entries injected via the `virtual:docs-template/site-meta`
114
+ * module and rendered by `DocsLayout.astro`.
115
+ */
116
+ head?: HeadEntry[];
112
117
  }
113
118
 
114
119
  /**
@@ -122,250 +127,278 @@ export interface SiteMetaOptions {
122
127
  * - Inline <style>{`…`}</style> blocks
123
128
  */
124
129
  function stripMdxForLlms(raw: string): string {
125
- return raw
126
- // Remove all import lines
127
- .replace(/^import\s+.+from\s+['"][^'"]+['"];?\r?\n/gm, '')
128
- // Remove <style>{`...`}</style> blocks (multiline)
129
- .replace(/<style>\{`[\s\S]*?`\}<\/style>\s*/g, '')
130
- // Remove self-closing components: <Sample … />, <ApiRef … />, <ApiLink … />
131
- .replace(/<(Sample|ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*\/>\s*/g, '')
132
- // Remove paired components: <ApiRef …>…</ApiRef>
133
- .replace(/<(ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*>[\s\S]*?<\/\1>\s*/g, '')
134
- // Collapse 3+ blank lines left behind into 2
135
- .replace(/\n{3,}/g, '\n\n')
136
- .trim() + '\n';
130
+ return (
131
+ raw
132
+ // Remove all import lines
133
+ .replace(/^import\s+.+from\s+['"][^'"]+['"];?\r?\n/gm, '')
134
+ // Remove <style>{`...`}</style> blocks (multiline)
135
+ .replace(/<style>\{`[\s\S]*?`\}<\/style>\s*/g, '')
136
+ // Remove self-closing components: <Sample … />, <ApiRef … />, <ApiLink … />
137
+ .replace(/<(Sample|ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*\/>\s*/g, '')
138
+ // Remove paired components: <ApiRef …>…</ApiRef>
139
+ .replace(/<(ApiRef|ApiLink|ComponentBlock|PlatformBlock)\b[^>]*>[\s\S]*?<\/\1>\s*/g, '')
140
+ // Collapse 3+ blank lines left behind into 2
141
+ .replace(/\n{3,}/g, '\n\n')
142
+ .trim() + '\n'
143
+ );
137
144
  }
138
145
 
139
146
  /**
140
147
  * Astro integration that exposes site metadata as the virtual module
141
148
  * `virtual:docs-template/site-meta` and generates /llms.txt at build time.
142
149
  */
143
- export function siteMetaIntegration({
150
+ export function siteMetaIntegration(
151
+ {
144
152
  title,
145
153
  description = '',
146
154
  docsDir,
147
155
  sidebar,
148
156
  platform = null,
149
157
  navLang = 'en',
150
- mode = 'development',
158
+ mode: _mode = 'development',
151
159
  llmsSets = [],
152
160
  productLinks = [],
153
161
  head = [],
154
- }: SiteMetaOptions = {} as SiteMetaOptions): AstroIntegration {
155
- const llmsMetaMap = docsDir
156
- ? buildLlmsMetaMap(docsDir, sidebar ?? [])
157
- : new Map<string, LlmsMeta>();
158
-
159
- const virtualId = 'virtual:docs-template/site-meta';
160
- const resolvedId = '\0' + virtualId;
161
-
162
- const navVirtualId = 'virtual:docs-template/nav-html';
163
- const navResolvedId = '\0' + navVirtualId;
164
-
165
- // Navigation buckets for this platform.
166
- const broadSections = getBroadSectionsForPlatform(platform ?? null);
167
- // Captured from astro:config:done; used to generate llms.txt content and virtual module.
168
- let configuredSite = '';
169
- // Cached virtual module source — built once in astro:config:done after
170
- // trailingSlash is known and reused on every subsequent Vite load() call.
171
- let siteMetaCode = '';
172
-
173
- return {
174
- name: 'docs-template:site-meta',
175
- hooks: {
176
- 'astro:config:done'({ config }) {
177
- configuredSite = (config.site?.toString() ?? '').replace(/\/$/, '');
178
- siteMetaCode = `export const title = ${JSON.stringify(title)};
162
+ }: SiteMetaOptions = {} as SiteMetaOptions,
163
+ ): AstroIntegration {
164
+ const llmsMetaMap = docsDir
165
+ ? buildLlmsMetaMap(docsDir, sidebar ?? [])
166
+ : new Map<string, LlmsMeta>();
167
+
168
+ const virtualId = 'virtual:docs-template/site-meta';
169
+ const resolvedId = '\0' + virtualId;
170
+
171
+ const navVirtualId = 'virtual:docs-template/nav-html';
172
+ const navResolvedId = '\0' + navVirtualId;
173
+
174
+ // Navigation buckets for this platform.
175
+ const broadSections = getBroadSectionsForPlatform(platform ?? null);
176
+ // Captured from astro:config:done; used to generate llms.txt content and virtual module.
177
+ let configuredSite = '';
178
+ // Cached virtual module source — built once in astro:config:done after
179
+ // trailingSlash is known and reused on every subsequent Vite load() call.
180
+ let siteMetaCode = '';
181
+
182
+ return {
183
+ name: 'docs-template:site-meta',
184
+ hooks: {
185
+ 'astro:config:done'({ config }) {
186
+ configuredSite = (config.site?.toString() ?? '').replace(/\/$/, '');
187
+ siteMetaCode = `export const title = ${JSON.stringify(title)};
179
188
  export const sidebar = ${JSON.stringify(sidebar ?? [])};
180
189
  export const productLinks = ${JSON.stringify(productLinks)};
181
190
  export const headEntries = ${JSON.stringify(head ?? [])};
182
191
  export const trailingSlash = ${JSON.stringify(config.trailingSlash)};
183
192
  export const navLang = ${JSON.stringify(navLang)};
184
193
  `;
194
+ },
195
+ 'astro:config:setup'({ updateConfig, injectRoute }) {
196
+ injectRoute({
197
+ pattern: '/sitemap.xml',
198
+ entrypoint: fileURLToPath(new URL('./routes/sitemap.xml.ts', import.meta.url)),
199
+ prerender: true,
200
+ });
201
+
202
+ // Inject the dynamic doc-page route so consuming projects don't
203
+ // need their own [...slug].astro. Project pages take priority over
204
+ // injected routes, so the template's own src/pages/[...slug].astro
205
+ // still wins when the template is used standalone.
206
+ injectRoute({
207
+ pattern: '/[...slug]',
208
+ entrypoint: fileURLToPath(new URL('./routes/[...slug].astro', import.meta.url)),
209
+ prerender: true,
210
+ });
211
+
212
+ // Configure Sass loadPaths so bare `highlight.js/scss/vs2015`
213
+ // imports in the platform theme files resolve from node_modules.
214
+ updateConfig({
215
+ vite: {
216
+ css: {
217
+ preprocessorOptions: {
218
+ scss: {
219
+ loadPaths: [path.join(process.cwd(), 'node_modules')],
220
+ // The if-function deprecation originates inside
221
+ // igniteui-theming (vendor code we cannot modify).
222
+ silenceDeprecations: ['if-function'],
223
+ },
224
+ },
185
225
  },
186
- 'astro:config:setup'({ updateConfig, injectRoute }) {
187
- injectRoute({
188
- pattern: '/sitemap.xml',
189
- entrypoint: fileURLToPath(new URL('./routes/sitemap.xml.ts', import.meta.url)),
190
- prerender: true,
191
- });
192
-
193
- // Inject the dynamic doc-page route so consuming projects don't
194
- // need their own [...slug].astro. Project pages take priority over
195
- // injected routes, so the template's own src/pages/[...slug].astro
196
- // still wins when the template is used standalone.
197
- injectRoute({
198
- pattern: '/[...slug]',
199
- entrypoint: fileURLToPath(new URL('./routes/[...slug].astro', import.meta.url)),
200
- prerender: true,
201
- });
202
-
203
-
204
- // Configure Sass loadPaths so bare `highlight.js/scss/vs2015`
205
- // imports in the platform theme files resolve from node_modules.
206
- updateConfig({
207
- vite: {
208
- css: {
209
- preprocessorOptions: {
210
- scss: {
211
- loadPaths: [path.join(process.cwd(), 'node_modules')],
212
- // The if-function deprecation originates inside
213
- // igniteui-theming (vendor code we cannot modify).
214
- silenceDeprecations: ['if-function'],
215
- },
216
- },
217
- },
218
- },
219
- });
220
- updateConfig({
221
- vite: {
222
- plugins: [{
223
- name: 'vite-plugin-docs-template-site-meta',
224
- resolveId(id: string) {
225
- if (id === virtualId) return resolvedId;
226
- if (id === navVirtualId) return navResolvedId;
227
- },
228
- load(id: string) {
229
- if (id === resolvedId) return siteMetaCode;
230
- if (id !== navResolvedId) return;
231
-
232
- return `export const platform = ${JSON.stringify(platform ?? null)};`;
233
- },
234
- }],
235
- },
236
- });
237
- },
226
+ },
227
+ });
228
+ updateConfig({
229
+ vite: {
230
+ plugins: [
231
+ {
232
+ name: 'vite-plugin-docs-template-site-meta',
233
+ resolveId(id: string) {
234
+ if (id === virtualId) return resolvedId;
235
+ if (id === navVirtualId) return navResolvedId;
236
+ },
237
+ load(id: string) {
238
+ if (id === resolvedId) return siteMetaCode;
239
+ if (id !== navResolvedId) return;
238
240
 
239
- 'astro:server:setup'({ server }) {
240
- if (!docsDir) return;
241
- server.middlewares.use(async (req, res, next) => {
242
- // Only handle requests ending in .md
243
- if (!req.url?.endsWith('.md')) return next();
244
- // Strip leading slash and .md suffix to get the slug
245
- const slug = req.url.slice(1, -3);
246
- for (const ext of ['.md', '.mdx']) {
247
- const src = path.join(docsDir, slug + ext);
248
- try {
249
- const raw = await fsp.readFile(src, 'utf-8');
250
- res.setHeader('Content-Type', 'text/plain; charset=utf-8');
251
- res.end(raw);
252
- return;
253
- } catch { /* try next extension */ }
241
+ return `export const platform = ${JSON.stringify(platform ?? null)};`;
242
+ },
243
+ },
244
+ ],
245
+ },
246
+ });
247
+ },
248
+
249
+ 'astro:server:setup'({ server }) {
250
+ if (!docsDir) return;
251
+ server.middlewares.use(async (req, res, next) => {
252
+ // Only handle requests ending in .md
253
+ if (!req.url?.endsWith('.md')) return next();
254
+ // Strip leading slash and .md suffix to get the slug
255
+ const slug = req.url.slice(1, -3);
256
+ for (const ext of ['.md', '.mdx']) {
257
+ const src = path.join(docsDir, slug + ext);
258
+ try {
259
+ const raw = await fsp.readFile(src, 'utf-8');
260
+ res.setHeader('Content-Type', 'text/plain; charset=utf-8');
261
+ res.end(raw);
262
+ return;
263
+ } catch {
264
+ /* try next extension */
265
+ }
266
+ }
267
+ next();
268
+ });
269
+ },
270
+
271
+ async 'astro:build:done'({ dir, pages }) {
272
+ const outDir = fileURLToPath(dir);
273
+
274
+ // Copy package scripts to the build output /scripts/ directory.
275
+ const pkgScripts = fileURLToPath(new URL('../public/scripts', import.meta.url));
276
+ if (fs.existsSync(pkgScripts)) copyDirSync(pkgScripts, path.join(outDir, 'scripts'));
277
+
278
+ // Write our custom llms.txt after all rendering — always wins over plugin output.
279
+ const llmsContent = buildLlmsTxt(
280
+ configuredSite,
281
+ title,
282
+ description,
283
+ sidebar ?? [],
284
+ llmsMetaMap,
285
+ llmsSets,
286
+ broadSections,
287
+ );
288
+ await fsp.writeFile(path.join(outDir, 'llms.txt'), llmsContent, 'utf-8');
289
+
290
+ if (!docsDir) return;
291
+
292
+ // pages[].pathname is like "accordion/" or "charts/chart-api/" — strip trailing slash.
293
+ const slugs = pages
294
+ .map((p) => p.pathname.replace(/\/$/, ''))
295
+ .filter((s) => s && s !== '404' && s !== 'index');
296
+
297
+ await Promise.all(
298
+ slugs.map(async (slug) => {
299
+ for (const ext of ['.md', '.mdx']) {
300
+ const src = path.join(docsDir, slug + ext);
301
+ try {
302
+ const raw = await fsp.readFile(src, 'utf-8');
303
+ const dest = path.join(outDir, slug + '.md');
304
+ await fsp.mkdir(path.dirname(dest), { recursive: true });
305
+ await fsp.writeFile(dest, stripMdxForLlms(raw), 'utf-8');
306
+ break;
307
+ } catch {
308
+ /* try next extension */
309
+ }
310
+ }
311
+ }),
312
+ );
313
+
314
+ // ── llms-full.txt / llms-small.txt ──────────────────────────────────
315
+ // Read back the already-written per-page .md files and combine them.
316
+ const pageTexts = (
317
+ await Promise.all(
318
+ slugs.map(async (slug) => {
319
+ try {
320
+ return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
321
+ } catch {
322
+ return '';
323
+ }
324
+ }),
325
+ )
326
+ ).filter(Boolean);
327
+
328
+ const fullContent = pageTexts.join('\n\n---\n\n');
329
+ await fsp.writeFile(path.join(outDir, 'llms-full.txt'), fullContent, 'utf-8');
330
+
331
+ // Small variant: strip fenced code blocks and inline code.
332
+ const smallContent = fullContent
333
+ .replace(/^```[\s\S]*?^```/gm, '')
334
+ .replace(/`[^`\n]+`/g, '')
335
+ .replace(/\n{3,}/g, '\n\n')
336
+ .trim();
337
+ await fsp.writeFile(path.join(outDir, 'llms-small.txt'), smallContent, 'utf-8');
338
+
339
+ // ── /_llms-txt/{set-slug}.txt ────────────────────────────────────────
340
+ if (llmsSets.length > 0) {
341
+ const llmsTxtDir = path.join(outDir, '_llms-txt');
342
+ await fsp.mkdir(llmsTxtDir, { recursive: true });
343
+
344
+ await Promise.all(
345
+ llmsSets.map(async (set) => {
346
+ const matchingSlugs = slugs.filter((slug) =>
347
+ set.paths.some((pattern) => {
348
+ if (pattern.endsWith('*')) {
349
+ return slug.startsWith(pattern.slice(0, -1));
350
+ }
351
+ return slug === pattern || slug.startsWith(pattern + '/');
352
+ }),
353
+ );
354
+
355
+ const setText = (
356
+ await Promise.all(
357
+ matchingSlugs.map(async (slug) => {
358
+ try {
359
+ return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
360
+ } catch {
361
+ return '';
254
362
  }
255
- next();
256
- });
257
- },
258
-
259
- async 'astro:build:done'({ dir, pages }) {
260
- const outDir = fileURLToPath(dir);
261
-
262
- // Copy package scripts to the build output /scripts/ directory.
263
- const pkgScripts = fileURLToPath(new URL('../public/scripts', import.meta.url));
264
- if (fs.existsSync(pkgScripts)) copyDirSync(pkgScripts, path.join(outDir, 'scripts'));
265
-
266
- // Write our custom llms.txt after all rendering — always wins over plugin output.
267
- const llmsContent = buildLlmsTxt(configuredSite, title, description, sidebar ?? [], llmsMetaMap, llmsSets, broadSections);
268
- await fsp.writeFile(path.join(outDir, 'llms.txt'), llmsContent, 'utf-8');
269
-
270
- if (!docsDir) return;
271
-
272
- // pages[].pathname is like "accordion/" or "charts/chart-api/" — strip trailing slash.
273
- const slugs = pages
274
- .map(p => p.pathname.replace(/\/$/, ''))
275
- .filter(s => s && s !== '404' && s !== 'index');
363
+ }),
364
+ )
365
+ )
366
+ .filter(Boolean)
367
+ .join('\n\n---\n\n');
368
+
369
+ await fsp.writeFile(
370
+ path.join(llmsTxtDir, toUrlSlug(set.label) + '.txt'),
371
+ setText,
372
+ 'utf-8',
373
+ );
374
+ }),
375
+ );
376
+ }
276
377
 
277
- await Promise.all(
278
- slugs.map(async (slug) => {
279
- for (const ext of ['.md', '.mdx']) {
280
- const src = path.join(docsDir, slug + ext);
281
- try {
282
- const raw = await fsp.readFile(src, 'utf-8');
283
- const dest = path.join(outDir, slug + '.md');
284
- await fsp.mkdir(path.dirname(dest), { recursive: true });
285
- await fsp.writeFile(dest, stripMdxForLlms(raw), 'utf-8');
286
- break;
287
- } catch { /* try next extension */ }
288
- }
289
- })
290
- );
291
-
292
- // ── llms-full.txt / llms-small.txt ──────────────────────────────────
293
- // Read back the already-written per-page .md files and combine them.
294
- const pageTexts = (
295
- await Promise.all(
296
- slugs.map(async (slug) => {
297
- try {
298
- return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
299
- } catch { return ''; }
300
- })
301
- )
302
- ).filter(Boolean);
303
-
304
- const fullContent = pageTexts.join('\n\n---\n\n');
305
- await fsp.writeFile(path.join(outDir, 'llms-full.txt'), fullContent, 'utf-8');
306
-
307
- // Small variant: strip fenced code blocks and inline code.
308
- const smallContent = fullContent
309
- .replace(/^```[\s\S]*?^```/gm, '')
310
- .replace(/`[^`\n]+`/g, '')
311
- .replace(/\n{3,}/g, '\n\n')
312
- .trim();
313
- await fsp.writeFile(path.join(outDir, 'llms-small.txt'), smallContent, 'utf-8');
314
-
315
- // ── /_llms-txt/{set-slug}.txt ────────────────────────────────────────
316
- if (llmsSets.length > 0) {
317
- const llmsTxtDir = path.join(outDir, '_llms-txt');
318
- await fsp.mkdir(llmsTxtDir, { recursive: true });
319
-
320
- await Promise.all(
321
- llmsSets.map(async (set) => {
322
- const matchingSlugs = slugs.filter((slug) =>
323
- set.paths.some((pattern) => {
324
- if (pattern.endsWith('*')) {
325
- return slug.startsWith(pattern.slice(0, -1));
326
- }
327
- return slug === pattern || slug.startsWith(pattern + '/');
328
- })
329
- );
330
-
331
- const setText = (
332
- await Promise.all(
333
- matchingSlugs.map(async (slug) => {
334
- try {
335
- return await fsp.readFile(path.join(outDir, slug + '.md'), 'utf-8');
336
- } catch { return ''; }
337
- })
338
- )
339
- ).filter(Boolean).join('\n\n---\n\n');
340
-
341
- await fsp.writeFile(
342
- path.join(llmsTxtDir, toUrlSlug(set.label) + '.txt'),
343
- setText,
344
- 'utf-8',
345
- );
346
- })
347
- );
348
- }
349
-
350
- // Run pagefind to generate the search index from the built HTML.
351
- // The index is written to <outDir>/pagefind/ and served statically.
352
- console.log('[docs-template] Running pagefind…');
353
- try {
354
- const { index, errors: initErrors } = await pagefindCreateIndex({});
355
- if (initErrors?.length) throw new Error(initErrors.join(', '));
356
- const { errors: addErrors } = await index!.addDirectory({ path: outDir, rootSelector: 'main' });
357
- if (addErrors?.length) console.warn('[docs-template] pagefind addDirectory warnings:', addErrors);
358
- const { errors: writeErrors } = await index!.writeFiles({
359
- outputPath: path.join(outDir, 'pagefind'),
360
- });
361
- if (writeErrors?.length) console.warn('[docs-template] pagefind writeFiles warnings:', writeErrors);
362
- console.log('[docs-template] pagefind index written.');
363
- } catch (err) {
364
- console.warn('[docs-template] pagefind failed — search index will be unavailable.', err);
365
- }
366
- },
367
- },
368
- };
378
+ // Run pagefind to generate the search index from the built HTML.
379
+ // The index is written to <outDir>/pagefind/ and served statically.
380
+ console.log('[docs-template] Running pagefind…');
381
+ try {
382
+ const { index, errors: initErrors } = await pagefindCreateIndex({});
383
+ if (initErrors?.length) throw new Error(initErrors.join(', '));
384
+ const { errors: addErrors } = await index!.addDirectory({
385
+ path: outDir,
386
+ rootSelector: 'main',
387
+ });
388
+ if (addErrors?.length)
389
+ console.warn('[docs-template] pagefind addDirectory warnings:', addErrors);
390
+ const { errors: writeErrors } = await index!.writeFiles({
391
+ outputPath: path.join(outDir, 'pagefind'),
392
+ });
393
+ if (writeErrors?.length)
394
+ console.warn('[docs-template] pagefind writeFiles warnings:', writeErrors);
395
+ console.log('[docs-template] pagefind index written.');
396
+ } catch (err) {
397
+ console.warn('[docs-template] pagefind failed — search index will be unavailable.', err);
398
+ }
399
+ },
400
+ },
401
+ };
369
402
  }
370
403
 
371
404
  export { buildSidebarFromToc };
@@ -376,19 +409,24 @@ export type { LlmsMeta, LlmsSet } from './llms.ts';
376
409
  // ---------------------------------------------------------------------------
377
410
 
378
411
  const MIME: Record<string, string> = {
379
- png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg',
380
- gif: 'image/gif', svg: 'image/svg+xml', webp: 'image/webp',
381
- avif: 'image/avif', ico: 'image/x-icon',
412
+ png: 'image/png',
413
+ jpg: 'image/jpeg',
414
+ jpeg: 'image/jpeg',
415
+ gif: 'image/gif',
416
+ svg: 'image/svg+xml',
417
+ webp: 'image/webp',
418
+ avif: 'image/avif',
419
+ ico: 'image/x-icon',
382
420
  };
383
421
 
384
422
  function copyDirSync(src: string, dest: string): void {
385
- fs.mkdirSync(dest, { recursive: true });
386
- for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
387
- const s = path.join(src, entry.name);
388
- const d = path.join(dest, entry.name);
389
- if (entry.isDirectory()) copyDirSync(s, d);
390
- else fs.copyFileSync(s, d);
391
- }
423
+ fs.mkdirSync(dest, { recursive: true });
424
+ for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
425
+ const s = path.join(src, entry.name);
426
+ const d = path.join(dest, entry.name);
427
+ if (entry.isDirectory()) copyDirSync(s, d);
428
+ else fs.copyFileSync(s, d);
429
+ }
392
430
  }
393
431
 
394
432
  /**
@@ -399,51 +437,51 @@ function copyDirSync(src: string, dest: string): void {
399
437
  * @param options.urlPath - URL prefix under which images are served (default `'/images'`).
400
438
  */
401
439
  export function staticImagesIntegration(
402
- imagesDir: string,
403
- { urlPath = '/images' }: { urlPath?: string } = {},
440
+ imagesDir: string,
441
+ { urlPath = '/images' }: { urlPath?: string } = {},
404
442
  ): AstroIntegration {
405
- return {
406
- name: 'static-images',
407
- hooks: {
408
- 'astro:server:setup'({ server }) {
409
- server.middlewares.use(urlPath, (req, res, next) => {
410
- // Extract path (no query string)
411
- const rawUrl = req.url || '/';
412
- const requestPath = rawUrl.split('?', 1)[0] || '/';
413
- // Decode URL component; reject malformed encodings
414
- let decodedPath: string;
415
- try {
416
- decodedPath = decodeURIComponent(requestPath);
417
- } catch {
418
- return next();
419
- }
420
- // Build absolute file path and ensure it stays within imagesDir
421
- const basePath = path.resolve(imagesDir);
422
- const relativePath = decodedPath.replace(/^\/+/, '');
423
- const filePath = path.resolve(path.join(basePath, relativePath));
424
- // Prevent path traversal outside of imagesDir
425
- if (filePath !== basePath && !filePath.startsWith(basePath + path.sep)) {
426
- return next();
427
- }
428
- try {
429
- if (fs.statSync(filePath).isFile()) {
430
- const ext = path.extname(filePath).slice(1).toLowerCase();
431
- res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
432
- fs.createReadStream(filePath).pipe(res);
433
- return;
434
- }
435
- } catch {
436
- /* file not found — fall through */
437
- }
438
- next();
439
- });
440
- },
441
- async 'astro:build:done'({ dir }) {
442
- const destImages = path.join(fileURLToPath(dir), urlPath.replace(/^\//, ''));
443
- copyDirSync(imagesDir, destImages);
444
- },
445
- },
446
- };
443
+ return {
444
+ name: 'static-images',
445
+ hooks: {
446
+ 'astro:server:setup'({ server }) {
447
+ server.middlewares.use(urlPath, (req, res, next) => {
448
+ // Extract path (no query string)
449
+ const rawUrl = req.url || '/';
450
+ const requestPath = rawUrl.split('?', 1)[0] || '/';
451
+ // Decode URL component; reject malformed encodings
452
+ let decodedPath: string;
453
+ try {
454
+ decodedPath = decodeURIComponent(requestPath);
455
+ } catch {
456
+ return next();
457
+ }
458
+ // Build absolute file path and ensure it stays within imagesDir
459
+ const basePath = path.resolve(imagesDir);
460
+ const relativePath = decodedPath.replace(/^\/+/, '');
461
+ const filePath = path.resolve(path.join(basePath, relativePath));
462
+ // Prevent path traversal outside of imagesDir
463
+ if (filePath !== basePath && !filePath.startsWith(basePath + path.sep)) {
464
+ return next();
465
+ }
466
+ try {
467
+ if (fs.statSync(filePath).isFile()) {
468
+ const ext = path.extname(filePath).slice(1).toLowerCase();
469
+ res.setHeader('Content-Type', MIME[ext] || 'application/octet-stream');
470
+ fs.createReadStream(filePath).pipe(res);
471
+ return;
472
+ }
473
+ } catch {
474
+ /* file not found — fall through */
475
+ }
476
+ next();
477
+ });
478
+ },
479
+ async 'astro:build:done'({ dir }) {
480
+ const destImages = path.join(fileURLToPath(dir), urlPath.replace(/^\//, ''));
481
+ copyDirSync(imagesDir, destImages);
482
+ },
483
+ },
484
+ };
447
485
  }
448
486
 
449
487
  /**
@@ -452,34 +490,34 @@ export function staticImagesIntegration(
452
490
  * (e.g. raw `<img>` tags in markdown/MDX content).
453
491
  */
454
492
  function createBasePrependIntegration(base: string): AstroIntegration {
455
- const normalizedBase = base.replace(/\/$/, '');
456
-
457
- function rewriteDir(dir: string): void {
458
- for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
459
- const full = path.join(dir, entry.name);
460
- if (entry.isDirectory()) { rewriteDir(full); continue; }
461
- if (!entry.name.endsWith('.html')) continue;
462
-
463
- const original = fs.readFileSync(full, 'utf-8');
464
- const rewritten = original.replace(
465
- /\bsrc="(\/[^"]*)"/g,
466
- (_: string, url: string) => {
467
- if (url.startsWith(normalizedBase + '/')) return `src="${url}"`;
468
- return `src="${normalizedBase}${url}"`;
469
- },
470
- );
471
- if (rewritten !== original) fs.writeFileSync(full, rewritten, 'utf-8');
472
- }
493
+ const normalizedBase = base.replace(/\/$/, '');
494
+
495
+ function rewriteDir(dir: string): void {
496
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
497
+ const full = path.join(dir, entry.name);
498
+ if (entry.isDirectory()) {
499
+ rewriteDir(full);
500
+ continue;
501
+ }
502
+ if (!entry.name.endsWith('.html')) continue;
503
+
504
+ const original = fs.readFileSync(full, 'utf-8');
505
+ const rewritten = original.replace(/\bsrc="(\/[^"]*)"/g, (_: string, url: string) => {
506
+ if (url.startsWith(normalizedBase + '/')) return `src="${url}"`;
507
+ return `src="${normalizedBase}${url}"`;
508
+ });
509
+ if (rewritten !== original) fs.writeFileSync(full, rewritten, 'utf-8');
473
510
  }
474
-
475
- return {
476
- name: 'docs-template:base-prepend',
477
- hooks: {
478
- 'astro:build:done'({ dir }) {
479
- rewriteDir(fileURLToPath(dir));
480
- },
481
- },
482
- };
511
+ }
512
+
513
+ return {
514
+ name: 'docs-template:base-prepend',
515
+ hooks: {
516
+ 'astro:build:done'({ dir }) {
517
+ rewriteDir(fileURLToPath(dir));
518
+ },
519
+ },
520
+ };
483
521
  }
484
522
 
485
523
  // ---------------------------------------------------------------------------
@@ -487,65 +525,65 @@ function createBasePrependIntegration(base: string): AstroIntegration {
487
525
  // ---------------------------------------------------------------------------
488
526
 
489
527
  export interface DocsSiteSource {
490
- /** Absolute path to the TOC file. */
491
- tocPath: string;
492
- /** Absolute path to the Markdown docs directory. */
493
- docsDir: string;
494
- /**
495
- * Absolute path to images directory.
496
- * Omit to skip the images integration.
497
- */
498
- imagesDir?: string;
528
+ /** Absolute path to the TOC file. */
529
+ tocPath: string;
530
+ /** Absolute path to the Markdown docs directory. */
531
+ docsDir: string;
532
+ /**
533
+ * Absolute path to images directory.
534
+ * Omit to skip the images integration.
535
+ */
536
+ imagesDir?: string;
499
537
  }
500
538
 
501
539
  export interface CreateDocsSiteOptions {
502
- /** Deployed site URL. */
503
- site: string;
504
- /** Base path, e.g. `'/docs'`. */
505
- base?: string;
506
- /** Site title shown in the browser tab and DocsSubHeader. */
507
- title: string;
508
- /** Short description for the llms.txt header. */
509
- description?: string;
510
- /** Content source paths. */
511
- source: Partial<DocsSiteSource>;
512
- /** Sidebar builder options. */
513
- sidebar?: {
514
- /** Patterns to exclude from the TOC. */
515
- exclude?: RegExp[];
516
- };
517
- /**
518
- * Platform identifier. Drives CDN styles/scripts injected into `<head>`
519
- * and the build-time nav prefetch endpoint.
520
- */
521
- platform?: PlatformKey | null;
522
- /** Locale for the nav prefetch URL. */
523
- navLang?: NavLang;
524
- /**
525
- * Extra `<head>` entries appended after the platform entries.
526
- */
527
- head?: HeadEntry[];
528
- /**
529
- * Build / deployment mode.
530
- * - `'development'` — local development (default)
531
- * - `'staging'` — pre-production environment
532
- * - `'production'` — production deployment
533
- *
534
- * Exposed as `process.env.DOCS_BUILD_MODE`.
535
- */
536
- mode?: DocsMode;
537
- /**
538
- * Named documentation subsets. Each entry generates a dedicated
539
- * `/_llms-txt/{slug}.txt` and adds a link under
540
- * `## Documentation sets` in `llms.txt`.
541
- */
542
- llmsSets?: LlmsSet[];
543
- /** Cross-product navigation links rendered in the DocsSubHeader. */
544
- productLinks?: ProductLink[];
545
- /** Extra Astro integrations appended after the built-in ones. */
546
- integrations?: AstroIntegration[];
547
- /** Any remaining keys are spread into `defineConfig` (markdown, image, build, …). */
548
- [key: string]: unknown;
540
+ /** Deployed site URL. */
541
+ site: string;
542
+ /** Base path, e.g. `'/docs'`. */
543
+ base?: string;
544
+ /** Site title shown in the browser tab and DocsSubHeader. */
545
+ title: string;
546
+ /** Short description for the llms.txt header. */
547
+ description?: string;
548
+ /** Content source paths. */
549
+ source: Partial<DocsSiteSource>;
550
+ /** Sidebar builder options. */
551
+ sidebar?: {
552
+ /** Patterns to exclude from the TOC. */
553
+ exclude?: RegExp[];
554
+ };
555
+ /**
556
+ * Platform identifier. Drives CDN styles/scripts injected into `<head>`
557
+ * and the build-time nav prefetch endpoint.
558
+ */
559
+ platform?: PlatformKey | null;
560
+ /** Locale for the nav prefetch URL. */
561
+ navLang?: NavLang;
562
+ /**
563
+ * Extra `<head>` entries appended after the platform entries.
564
+ */
565
+ head?: HeadEntry[];
566
+ /**
567
+ * Build / deployment mode.
568
+ * - `'development'` — local development (default)
569
+ * - `'staging'` — pre-production environment
570
+ * - `'production'` — production deployment
571
+ *
572
+ * Exposed as `process.env.DOCS_BUILD_MODE`.
573
+ */
574
+ mode?: DocsMode;
575
+ /**
576
+ * Named documentation subsets. Each entry generates a dedicated
577
+ * `/_llms-txt/{slug}.txt` and adds a link under
578
+ * `## Documentation sets` in `llms.txt`.
579
+ */
580
+ llmsSets?: LlmsSet[];
581
+ /** Cross-product navigation links rendered in the DocsSubHeader. */
582
+ productLinks?: ProductLink[];
583
+ /** Extra Astro integrations appended after the built-in ones. */
584
+ integrations?: AstroIntegration[];
585
+ /** Any remaining keys are spread into `defineConfig` (markdown, image, build, …). */
586
+ [key: string]: unknown;
549
587
  }
550
588
 
551
589
  /**
@@ -565,133 +603,149 @@ export interface CreateDocsSiteOptions {
565
603
  *
566
604
  * @param options - Configuration options.
567
605
  */
568
- export function createDocsSite(options: CreateDocsSiteOptions = {} as CreateDocsSiteOptions): ReturnType<typeof defineConfig> {
569
- const {
570
- site,
571
- base,
572
- title,
573
- description = '',
574
- source = {},
575
- sidebar: sidebarOptions = {},
576
- platform = null,
577
- navLang = 'en',
578
- mode = 'development',
579
- productLinks = [],
580
- head = [],
581
- llmsSets = [] as LlmsSet[],
582
- integrations: extraIntegrations = [],
583
- ...astroExtra
584
- } = options;
585
-
586
- const sidebar = buildSidebarFromToc({
587
- tocPath: source.tocPath!,
588
- docsDir: source.docsDir!,
589
- exclude: sidebarOptions.exclude ?? [],
590
- });
591
-
592
- // Expose env vars so consuming content.config.ts and components can read them.
593
- if (source.docsDir) {
594
- process.env.DOCS_SOURCE_PATH = source.docsDir;
595
- }
596
- process.env.DOCS_BUILD_MODE = mode;
597
- process.env.DOCS_BASE = base ? base.replace(/\/$/, '') : '';
598
- if (!process.env.DOCS_ENV) {
599
- process.env.DOCS_ENV = mode;
600
- }
601
- // Expose the platform so plugins can set data-platform on widgets they generate.
602
- if (platform) {
603
- process.env.DOCS_PLATFORM = platform;
604
- }
605
-
606
- // Platform CDN entries come first so site-specific `head` entries can override.
607
- const platformHead = platform ? getPlatformHead(platform, navLang) : [];
608
-
609
- // highlight.js for code-tab syntax highlighting inside code-view widgets.
610
- const codeViewHead: HeadEntry[] = [
611
- { tag: 'link', attrs: { rel: 'stylesheet', href: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.min.css' } },
612
- { tag: 'script', attrs: { src: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js', defer: true } },
613
- ];
614
-
615
- // Auto-configure a Vite dev-server proxy so sample-widget.ts can fetch
616
- // /code-viewer/*.json from the local demos server without CORS issues.
617
- const devProxy: Record<string, object> = {};
618
- if (source.docsDir) {
619
- try {
620
- const docsRoot = path.resolve(source.docsDir);
621
- const envCandidates = [
622
- path.join(docsRoot, 'en', 'environment.json'),
623
- path.join(docsRoot, 'environment.json'),
624
- path.join(path.dirname(docsRoot), 'environment.json'),
625
- path.join(path.dirname(docsRoot), 'en', 'environment.json'),
626
- ];
627
- const envFile = envCandidates.find(c => fs.existsSync(c));
628
- if (envFile) {
629
- const envData = JSON.parse(fs.readFileSync(envFile, 'utf-8'));
630
- const envKey = process.env.DOCS_ENV ?? process.env.NODE_ENV ?? 'production';
631
- const env: Record<string, string> = envData[envKey] ?? envData.production ?? {};
632
- const demosUrl = env.dvDemosBaseUrl || env.demosBaseUrl;
633
- if (demosUrl) {
634
- const u = new URL(demosUrl);
635
- if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
636
- const cfg = { target: demosUrl, changeOrigin: true, secure: false };
637
- devProxy['/code-viewer'] = cfg;
638
- devProxy['/assets/code-viewer'] = cfg;
639
- }
640
- }
641
- }
642
- } catch { /* non-fatal — proxy just won't be configured */ }
606
+ export function createDocsSite(
607
+ options: CreateDocsSiteOptions = {} as CreateDocsSiteOptions,
608
+ ): ReturnType<typeof defineConfig> {
609
+ const {
610
+ site,
611
+ base,
612
+ title,
613
+ description = '',
614
+ source = {},
615
+ sidebar: sidebarOptions = {},
616
+ platform = null,
617
+ navLang = 'en',
618
+ mode = 'development',
619
+ productLinks = [],
620
+ head = [],
621
+ llmsSets = [] as LlmsSet[],
622
+ integrations: extraIntegrations = [],
623
+ ...astroExtra
624
+ } = options;
625
+
626
+ const sidebar = buildSidebarFromToc({
627
+ tocPath: source.tocPath!,
628
+ docsDir: source.docsDir!,
629
+ exclude: sidebarOptions.exclude ?? [],
630
+ });
631
+
632
+ // Expose env vars so consuming content.config.ts and components can read them.
633
+ if (source.docsDir) {
634
+ process.env.DOCS_SOURCE_PATH = source.docsDir;
635
+ }
636
+ process.env.DOCS_BUILD_MODE = mode;
637
+ process.env.DOCS_BASE = base ? base.replace(/\/$/, '') : '';
638
+ if (!process.env.DOCS_ENV) {
639
+ process.env.DOCS_ENV = mode;
640
+ }
641
+ // Expose the platform so plugins can set data-platform on widgets they generate.
642
+ if (platform) {
643
+ process.env.DOCS_PLATFORM = platform;
644
+ }
645
+
646
+ // Platform CDN entries come first so site-specific `head` entries can override.
647
+ const platformHead = platform ? getPlatformHead(platform, navLang) : [];
648
+
649
+ // highlight.js for code-tab syntax highlighting inside code-view widgets.
650
+ const codeViewHead: HeadEntry[] = [
651
+ {
652
+ tag: 'link',
653
+ attrs: {
654
+ rel: 'stylesheet',
655
+ href: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/vs2015.min.css',
656
+ },
657
+ },
658
+ {
659
+ tag: 'script',
660
+ attrs: {
661
+ src: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js',
662
+ defer: true,
663
+ },
664
+ },
665
+ ];
666
+
667
+ // Auto-configure a Vite dev-server proxy so sample-widget.ts can fetch
668
+ // /code-viewer/*.json from the local demos server without CORS issues.
669
+ const devProxy: Record<string, object> = {};
670
+ if (source.docsDir) {
671
+ try {
672
+ const docsRoot = path.resolve(source.docsDir);
673
+ const envCandidates = [
674
+ path.join(docsRoot, 'en', 'environment.json'),
675
+ path.join(docsRoot, 'environment.json'),
676
+ path.join(path.dirname(docsRoot), 'environment.json'),
677
+ path.join(path.dirname(docsRoot), 'en', 'environment.json'),
678
+ ];
679
+ const envFile = envCandidates.find((c) => fs.existsSync(c));
680
+ if (envFile) {
681
+ const envData = JSON.parse(fs.readFileSync(envFile, 'utf-8'));
682
+ const envKey = process.env.DOCS_ENV ?? process.env.NODE_ENV ?? 'production';
683
+ const env: Record<string, string> = envData[envKey] ?? envData.production ?? {};
684
+ const demosUrl = env.dvDemosBaseUrl || env.demosBaseUrl;
685
+ if (demosUrl) {
686
+ const u = new URL(demosUrl);
687
+ if (u.hostname === 'localhost' || u.hostname === '127.0.0.1') {
688
+ const cfg = { target: demosUrl, changeOrigin: true, secure: false };
689
+ devProxy['/code-viewer'] = cfg;
690
+ devProxy['/assets/code-viewer'] = cfg;
691
+ }
692
+ }
693
+ }
694
+ } catch {
695
+ /* non-fatal — proxy just won't be configured */
643
696
  }
644
-
645
- return defineConfig({
646
- site,
647
- ...(base !== undefined ? { base } : {}),
648
- // Docs sites serve images statically — disable Astro's image optimization
649
- // so relative image paths in markdown don't cause build errors.
650
- image: { service: { entrypoint: 'astro/assets/services/noop' }, ...(astroExtra as any).image },
651
- ...astroExtra,
652
- vite: {
653
- ...(astroExtra as any).vite,
654
- server: {
655
- ...(astroExtra as any).vite?.server,
656
- proxy: {
657
- ...devProxy,
658
- ...(astroExtra as any).vite?.server?.proxy,
659
- },
660
- },
661
- },
662
- markdown: {
663
- ...(astroExtra as any).markdown,
664
- remarkPlugins: [
665
- remarkEnvVars,
666
- remarkMdLinks,
667
- remarkHtmlTransforms,
668
- ...((astroExtra as any).markdown?.remarkPlugins ?? []),
669
- ],
670
- rehypePlugins: [
671
- rehypeCodeView,
672
- rehypeTableWrapper,
673
- rehypeHeadingAnchors,
674
- rehypePagefindIgnore,
675
- ...((astroExtra as any).markdown?.rehypePlugins ?? []),
676
- ],
697
+ }
698
+
699
+ return defineConfig({
700
+ site,
701
+ ...(base !== undefined ? { base } : {}),
702
+ // Docs sites serve images statically — disable Astro's image optimization
703
+ // so relative image paths in markdown don't cause build errors.
704
+ image: { service: { entrypoint: 'astro/assets/services/noop' }, ...(astroExtra as any).image },
705
+ ...astroExtra,
706
+ vite: {
707
+ ...(astroExtra as any).vite,
708
+ server: {
709
+ ...(astroExtra as any).vite?.server,
710
+ proxy: {
711
+ ...devProxy,
712
+ ...(astroExtra as any).vite?.server?.proxy,
677
713
  },
678
- integrations: [
679
- siteMetaIntegration({
680
- title,
681
- description,
682
- docsDir: source.docsDir,
683
- sidebar,
684
- platform,
685
- navLang,
686
- mode,
687
- llmsSets,
688
- productLinks,
689
- head: [...platformHead, ...codeViewHead, ...head],
690
- }),
691
- mdx(),
692
- ...(source.imagesDir ? [staticImagesIntegration(source.imagesDir)] : []),
693
- ...(base ? [createBasePrependIntegration(base)] : []),
694
- ...extraIntegrations,
695
- ],
696
- });
714
+ },
715
+ },
716
+ markdown: {
717
+ ...(astroExtra as any).markdown,
718
+ remarkPlugins: [
719
+ remarkEnvVars,
720
+ remarkMdLinks,
721
+ remarkHtmlTransforms,
722
+ ...((astroExtra as any).markdown?.remarkPlugins ?? []),
723
+ ],
724
+ rehypePlugins: [
725
+ rehypeCodeView,
726
+ rehypeTableWrapper,
727
+ rehypeHeadingAnchors,
728
+ rehypePagefindIgnore,
729
+ ...((astroExtra as any).markdown?.rehypePlugins ?? []),
730
+ ],
731
+ },
732
+ integrations: [
733
+ siteMetaIntegration({
734
+ title,
735
+ description,
736
+ docsDir: source.docsDir,
737
+ sidebar,
738
+ platform,
739
+ navLang,
740
+ mode,
741
+ llmsSets,
742
+ productLinks,
743
+ head: [...platformHead, ...codeViewHead, ...head],
744
+ }),
745
+ mdx(),
746
+ ...(source.imagesDir ? [staticImagesIntegration(source.imagesDir)] : []),
747
+ ...(base ? [createBasePrependIntegration(base)] : []),
748
+ ...extraIntegrations,
749
+ ],
750
+ });
697
751
  }