forked from TanStack/ai
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-docs-config.ts
More file actions
278 lines (228 loc) · 7.15 KB
/
Copy pathsync-docs-config.ts
File metadata and controls
278 lines (228 loc) · 7.15 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import { readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'
import { basename, extname, join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
const __dirname = fileURLToPath(new URL('.', import.meta.url))
const docsRoot = resolve(__dirname, '../docs')
const configPath = resolve(docsRoot, 'config.json')
// Folders to ignore when crawling
const IGNORED_FOLDERS = ['framework', 'protocol', 'reference']
// Define the preferred order of sections (folders not listed here will be appended at the end)
const SECTION_ORDER = ['getting-started', 'guides', 'api', 'adapters']
// Special label overrides for specific folder names
const LABEL_OVERRIDES: Record<string, string> = {
api: 'API',
}
interface DocChild {
label: string
to: string
order?: number
}
interface DocSection {
label: string
children: Array<DocChild>
collapsible?: boolean
defaultCollapsed?: boolean
}
interface DocConfig {
$schema?: string
docSearch?: {
appId: string
apiKey: string
indexName: string
}
sections: Array<DocSection>
}
interface FrontmatterData {
title: string | null
order: number | null
}
/**
* Converts a folder name to a label (e.g., "getting-started" -> "Getting Started")
*/
function folderNameToLabel(folderName: string): string {
// Check for override first
if (LABEL_OVERRIDES[folderName]) {
return LABEL_OVERRIDES[folderName]
}
return folderName
.split('-')
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ')
}
/**
* Extracts the title and order from frontmatter in a markdown file
*/
function extractFrontmatterData(filePath: string): FrontmatterData {
try {
const content = readFileSync(filePath, 'utf-8')
const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---/)
if (!frontmatterMatch) {
return { title: null, order: null }
}
const frontmatter = frontmatterMatch[1]
const titleMatch = frontmatter?.match(/^title:\s*(.+)$/m)
const orderMatch = frontmatter?.match(/^order:\s*(\d+)$/m)
let title: string | null = null
if (titleMatch && titleMatch[1]) {
// Remove quotes if present
title = titleMatch[1].replace(/^["']|["']$/g, '').trim()
}
let order: number | null = null
if (orderMatch && orderMatch[1]) {
order = parseInt(orderMatch[1], 10)
}
return { title, order }
} catch {
return { title: null, order: null }
}
}
/**
* Gets all markdown files in a directory and generates children entries
*/
function getChildrenFromFolder(
folderPath: string,
folderName: string,
): Array<DocChild> {
const children: Array<DocChild> = []
try {
const files = readdirSync(folderPath)
for (const file of files) {
const filePath = join(folderPath, file)
const stat = statSync(filePath)
if (stat.isFile() && extname(file) === '.md') {
const fileNameWithoutExt = basename(file, '.md')
const { title, order } = extractFrontmatterData(filePath)
const child: DocChild = {
label: title || folderNameToLabel(fileNameWithoutExt),
to: `${folderName}/${fileNameWithoutExt}`,
}
if (order !== null) {
child.order = order
}
children.push(child)
}
}
// Sort children by order (items with order come first, sorted by order value)
// Items without order go at the end in arbitrary order
children.sort((a, b) => {
if (a.order !== undefined && b.order !== undefined) {
return a.order - b.order
}
if (a.order !== undefined) {
return -1
}
if (b.order !== undefined) {
return 1
}
return 0
})
// Remove order property from children before returning (it's only used for sorting)
return children.map(({ label, to }) => ({ label, to }))
} catch (error) {
console.error(`Error reading folder ${folderPath}:`, error)
}
return children
}
/**
* Crawls the docs folder and generates sections
*/
function generateSections(): Array<DocSection> {
const sectionsMap = new Map<string, DocSection>()
try {
const entries = readdirSync(docsRoot)
for (const entry of entries) {
const entryPath = join(docsRoot, entry)
const stat = statSync(entryPath)
// Skip if not a directory, is ignored, or is a special file
if (
!stat.isDirectory() ||
IGNORED_FOLDERS.includes(entry) ||
entry.startsWith('.')
) {
continue
}
const children = getChildrenFromFolder(entryPath, entry)
if (children.length > 0) {
sectionsMap.set(entry, {
label: folderNameToLabel(entry),
children,
})
}
}
} catch (error) {
console.error('Error crawling docs folder:', error)
}
// Sort sections based on SECTION_ORDER
const sortedSections: Array<DocSection> = []
// First, add sections in the preferred order
for (const folderName of SECTION_ORDER) {
const section = sectionsMap.get(folderName)
if (section) {
sortedSections.push(section)
sectionsMap.delete(folderName)
}
}
// Then, add any remaining sections not in the preferred order
for (const section of sectionsMap.values()) {
sortedSections.push(section)
}
return sortedSections
}
/**
* Reads the config.json and updates sections while preserving other fields
*/
function updateConfig(newSections: Array<DocSection>): void {
let config: DocConfig
try {
const configContent = readFileSync(configPath, 'utf-8')
config = JSON.parse(configContent)
} catch (error) {
console.error('Error reading config.json:', error)
return
}
// Get labels of newly generated sections
const newSectionLabels = new Set(newSections.map((s) => s.label))
// Filter out old sections that will be replaced by new ones
const preservedSections = config.sections.filter(
(section) => !newSectionLabels.has(section.label),
)
// Find the insertion point - we want to insert new sections before the reference sections
// Reference sections typically have "collapsible" property
const firstCollapsibleIndex = preservedSections.findIndex(
(s) => s.collapsible,
)
let updatedSections: Array<DocSection>
if (firstCollapsibleIndex === -1) {
// No collapsible sections, just append new sections
updatedSections = [...newSections, ...preservedSections]
} else {
// Insert new sections before collapsible sections
updatedSections = [
...newSections,
...preservedSections.slice(firstCollapsibleIndex),
]
}
// Update config with new sections
config.sections = updatedSections
// Write back to config.json with proper formatting
try {
writeFileSync(configPath, JSON.stringify(config, null, 2) + '\n', 'utf-8')
console.log('✅ config.json has been updated successfully!')
} catch (error) {
console.error('Error writing config.json:', error)
}
}
/**
* Main function
*/
function main(): void {
console.log('🔍 Scanning docs folder...\n')
const newSections = generateSections()
console.log('📝 Generated sections:')
for (const section of newSections) {
console.log(` - ${section.label} (${section.children.length} items)`)
}
console.log('')
updateConfig(newSections)
}
main()