Debian Codegraph @

www/src/pages/search-index.json.js

raw symbols SCIP
1 import { readFile } from 'node:fs/promises';
2 import { join } from 'node:path';
3 import GithubSlugger from 'github-slugger';
4
5 import { getFolder, COLLECTIONS } from '../lib/content';
6
7 /**
8 * Strip markdown/HTML to plain text for search indexing
9 * @param {string} markdown
10 * @returns {string}
11 */
12 function toPlainText(markdown) {
13 return markdown
14 .replace(/```[\s\S]*?```/g, '') // Remove code blocks
15 .replace(/`([^`]+)`/g, '$1') // Keep inline code content
16 .replace(/<[^>]+>/g, '') // Remove HTML tags
17 .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // Keep link text
18 .replace(/[*_~#]/g, '') // Remove markdown formatting
19 .replace(/\s+/g, ' ') // Normalize whitespace
20 .trim();
21 }
22
23 /**
24 * Extract H2/H3 sections from markdown for deep linking.
25 * @param {string} markdown
26 * @returns {Array<{title: string, anchor: string, content: string}>}
27 */
28 function extractSections(markdown) {
29 const withoutFrontmatter = markdown.replace(/^---\n[\s\S]*?\n---\n/, '');
30 const headingRegex = /^(#{2,3})\s+(.+)$/gm;
31 const matches = [...withoutFrontmatter.matchAll(headingRegex)];
32 /** @type {Array<{title: string, anchor: string, content: string}>} */
33 const sections = [];
34
35 for (let i = 0; i < matches.length; i++) {
36 const match = matches[i];
37 const title = match[2].trim();
38 const level = match[1].length;
39 const anchor = title.toLowerCase().replace(/[^\w\s-]/g, '').replace(/\s+/g, '-');
40
41 // Get content until next heading of same or higher level
42 const startPos = (match.index ?? 0) + match[0].length;
43 let endPos = withoutFrontmatter.length;
44 for (let j = i + 1; j < matches.length; j++) {
45 if (matches[j][1].length <= level) {
46 endPos = matches[j].index ?? withoutFrontmatter.length;
47 break;
48 }
49 }
50
51 const content = toPlainText(withoutFrontmatter.slice(startPos, endPos));
52 if (content.length > 20) {
53 sections.push({title, anchor, content: content.slice(0, 200)});
54 }
55 }
56
57 return sections;
58 }
59
60
61 /** @type {import('astro').APIRoute} */
62 export const GET = async () => {
63 /** @type {any[]} */
64 const results = [];
65
66 await Promise.all(
67 COLLECTIONS.map(async (collectionId) => {
68 try {
69 const folder = await getFolder(collectionId);
70 const files = folder.allFiles;
71 const collection = folder.frontmatter.title;
72
73 // Slug as a keyword so "docs" -> "Documentation" etc.
74 results.push({
75 id: folder.url,
76 url: folder.url,
77 title: folder.frontmatter.title,
78 description: folder.frontmatter.description || '',
79 keywords: [collectionId, ...(folder.frontmatter.keywords || [])].join(', '),
80 parent: null,
81 collection,
82 breadcrumb: []
83 });
84
85 // Explicit aliases for /docs H2 anchors. Covers user phrasings that
86 // don't appear in headings or body text (e.g. "back button" -> History).
87 const DOCS_ALIASES = {
88 installation: ['install', 'getting started', 'quick start'],
89 boosting: ['boost', 'progressive enhancement'],
90 history: ['back button', 'pushState'],
91 synchronization: ['sync', 'debounce', 'throttle', 'race condition'],
92 'css-transitions': ['fade'],
93 'multi-target-updates': ['oob', 'out of band'],
94 'client-side-scripting': ['javascript', 'hyperscript'],
95 configuration: ['settings', 'meta tag'],
96 debugging: ['debug', 'devtools', 'logAll'],
97 'requests--responses': ['XHR', 'fetch', 'ajax'],
98 };
99
100 // Index each H2 in docs.mdx as a search hit; H3s become child hits with the H2 as breadcrumb.
101 if (collectionId === 'docs' && folder.path) {
102 const raw = await readFile(join(process.cwd(), 'src', 'content', folder.path), 'utf-8');
103 const body = raw.replace(/^---\n[\s\S]*?\n---\n/, '').replace(/```[\s\S]*?```/g, '');
104 const slugger = new GithubSlugger();
105 const headingRe = /^(#{1,6})[ \t]+(.+?)[ \t]*$/gm;
106 const headings = [...body.matchAll(headingRe)].map(m => ({
107 depth: m[1].length,
108 text: m[2].trim(),
109 lineEnd: (m.index ?? 0) + m[0].length,
110 index: m.index ?? 0,
111 anchor: slugger.slug(m[2].trim().replace(/`/g, '')),
112 }));
113 // children of `h` with depth in (h.depth, maxDepth], stopping
114 // at the next heading of equal-or-shallower depth.
115 const subHeadings = (h, maxDepth) => {
116 const start = headings.indexOf(h) + 1;
117 const out = [];
118 for (let j = start; j < headings.length; j++) {
119 const c = headings[j];
120 if (c.depth <= h.depth) break;
121 if (c.depth <= maxDepth) out.push(c);
122 }
123 return out;
124 };
125 let currentH1 = null, currentH2 = null;
126 for (let i = 0; i < headings.length; i++) {
127 const h = headings[i];
128 if (h.depth > 3) continue;
129 if (h.depth === 1) currentH1 = h.text;
130 if (h.depth === 2) currentH2 = h.text;
131 const next = headings.slice(i + 1).find(n => n.depth <= h.depth);
132 const content = toPlainText(body.slice(h.lineEnd, next?.index ?? body.length)).slice(0, 200);
133 const keywords = h.depth === 1
134 ? subHeadings(h, 2).map(c => c.text).join(', ')
135 : h.depth === 2
136 ? [currentH1, ...(DOCS_ALIASES[h.anchor] || []), ...subHeadings(h, 4).map(c => c.text)].filter(Boolean).join(', ')
137 : '';
138 results.push({
139 id: `/docs#${h.anchor}`,
140 url: `/docs#${h.anchor}`,
141 title: h.text,
142 description: content,
143 keywords,
144 parent: h.depth >= 3 ? currentH2 : null,
145 collection,
146 breadcrumb: h.depth >= 3 ? [currentH2].filter(Boolean) : [],
147 });
148 }
149 return;
150 }
151
152 // Add subfolder entries (e.g., Reference > Headers, Docs > Getting Started)
153 /** @param {typeof folder} parentFolder */
154 const addSubfolders = (parentFolder) => {
155 for (const subfolder of parentFolder.folders) {
156 const breadcrumb = subfolder.breadcrumbs
157 .slice(1, -1)
158 .map(b => b.label);
159
160 results.push({
161 id: subfolder.url,
162 url: subfolder.url,
163 title: subfolder.frontmatter.title,
164 description: subfolder.frontmatter.description || '',
165 keywords: subfolder.frontmatter.keywords?.join(', ') || '',
166 parent: null,
167 collection,
168 breadcrumb
169 });
170
171 addSubfolders(subfolder);
172 }
173 };
174 addSubfolders(folder);
175
176 for (const file of files) {
177 /** @type {Array<{title: string, anchor: string, content: string}>} */
178 let sections = [];
179 const fileId = file.path.startsWith(`${collectionId}/`)
180 ? file.path.replace(`${collectionId}/`, '')
181 : file.path;
182
183 for (const ext of ['.md', '.mdx']) {
184 try {
185 const path = join(process.cwd(), 'src', 'content', collectionId, fileId + ext);
186 sections = extractSections(await readFile(path, 'utf-8'));
187 break;
188 } catch {}
189 }
190
191 // Use breadcrumbs from content system (skip first=collection, last=current page)
192 const breadcrumb = file.breadcrumbs
193 .slice(1, -1)
194 .map(b => b.label);
195
196 const keywords = file.frontmatter.keywords?.join(', ') || '';
197
198 results.push({
199 id: file.url,
200 url: file.url,
201 title: file.frontmatter.title,
202 description: file.frontmatter.description || '',
203 keywords,
204 parent: null,
205 collection,
206 breadcrumb
207 });
208
209 for (const section of sections) {
210 results.push({
211 id: `${file.url}#${section.anchor}`,
212 url: `${file.url}#${section.anchor}`,
213 title: section.title,
214 description: section.content,
215 parent: file.frontmatter.title,
216 collection,
217 breadcrumb
218 });
219 }
220 }
221 } catch (error) {
222 console.warn(`Skipping ${collectionId}:`, error);
223 }
224 })
225 );
226
227 return new Response(
228 JSON.stringify({results}),
229 {status: 200, headers: {'Content-Type': 'application/json'}}
230 );
231 };