-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.astro
More file actions
75 lines (66 loc) · 2.65 KB
/
Copy pathindex.astro
File metadata and controls
75 lines (66 loc) · 2.65 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
---
import { sidebar } from 'virtual:docs-template/site-meta';
import { readFileSync, existsSync } from 'node:fs';
import path from 'node:path';
type SidebarEntry = { label: string; slug: string } | { label: string; items: SidebarEntry[] };
type TocItem = { name?: string; href?: string; default?: boolean; header?: boolean; items?: TocItem[] };
// DOCS_SOURCE_PATH is set by createDocsSite() to the absolute components docsDir.
// This is the same path used by the sidebar and content collection — single source of truth.
const docsDir = process.env.DOCS_SOURCE_PATH ?? path.join(process.cwd(), 'src', 'content', (process.env.DOCS_LANG ?? 'en'), 'components');
const tocPath = path.join(docsDir, 'toc.json');
const toc: TocItem[] = existsSync(tocPath)
? (JSON.parse(readFileSync(tocPath, 'utf8')) as TocItem[])
: [];
function hrefToSlug(href: string): string {
if (!href) return '';
let slug = href
.replace(/\\/g, '/')
.replace(/\.(md|mdx)$/i, '')
.toLowerCase();
slug = slug.replace(/\/index$/, '');
return slug === 'index' ? '' : slug;
}
function joinSlugPrefix(slugPrefix: string, slug: string): string {
if (!slugPrefix) return slug;
return slug ? `${slugPrefix}/${slug}` : slugPrefix;
}
function findDefaultSlug(items: TocItem[]): string | null {
for (const item of items) {
if (item.default && item.href) {
return hrefToSlug(item.href);
}
if (item.items) {
const found = findDefaultSlug(item.items);
if (found) return found;
}
}
return null;
}
function firstSlug(items: SidebarEntry[]): string | null {
for (const item of items) {
if ('slug' in item) return item.slug;
if ('items' in item) {
const found = firstSlug(item.items);
if (found) return found;
}
}
return null;
}
function slugExistsInSidebar(items: SidebarEntry[], target: string): boolean {
for (const item of items) {
if ('slug' in item && item.slug === target) return true;
if ('items' in item && slugExistsInSidebar(item.items, target)) return true;
}
return false;
}
const typedSidebar = sidebar as SidebarEntry[];
const defaultSlug = findDefaultSlug(toc);
const slugPrefix = process.env.DOCS_SLUG_PREFIX ?? '';
const prefixedDefault = defaultSlug !== null ? joinSlugPrefix(slugPrefix, defaultSlug) : null;
const slug = (prefixedDefault && slugExistsInSidebar(typedSidebar, prefixedDefault))
? prefixedDefault
: firstSlug(typedSidebar);
const base = import.meta.env.BASE_URL.replace(/\/$/, '');
const redirectTo = slug ? `${base}/${slug}` : `${base}/404`;
return Astro.redirect(redirectTo, 301);
---