@jungtz/wiki-router 1.0.1

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.
package/dist/index.mjs ADDED
@@ -0,0 +1,449 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ /**
5
+ * 內嵌 LLM Wiki 提示詞模板
6
+ * 與原始 server/prompts/ 目錄中的檔案保持同步
7
+ */
8
+
9
+ const SPLIT_PROMPT = `# 角色:專業文件架構師 (Documentation Architect)
10
+
11
+ ## 任務目標
12
+ 將提供的 JSON 資料完整解析並轉換為多個獨立的 Markdown \`.md\` 檔案。
13
+ JSON 可能來自 CMS、API 回應、設定檔或任何結構化資料來源。
14
+
15
+ ## 原始 JSON 資料
16
+ \`\`\`json
17
+ {{context}}
18
+ \`\`\`
19
+
20
+ ## 處理規則:
21
+
22
+ ### 1. 結構識別(自動語義分析)
23
+ - 分析 JSON 的頂層結構(object / array / 巢狀)
24
+ - 若為巢狀物件,以**第一層 key** 作為主題分群依據(如 \`data.rooms\` → 房間主題、\`data.location\` → 地點主題)
25
+ - 若為頂層陣列,每個元素視為獨立條目,依內容主題分組
26
+
27
+ ### 2. 完整性強制規則(最高優先)
28
+ - **逐項清點**:陣列型資料必須逐一列出所有項目,先數原始 JSON 中有幾筆,輸出後再數確認數量一致
29
+ - **巢狀陣列全收**:若某欄位本身是陣列(如設施清單、標籤列表),必須列出該陣列中的**每一項**
30
+ - **不因長度省略**:資料再多也不能用「等」、「...」、「其他」概括
31
+
32
+ ### 3. 資訊提取(語義識別)
33
+ - **標題欄位**:自動識別代表名稱/標題的欄位(\`title\`、\`name\`、\`label\`、\`subject\`)
34
+ - **內文欄位**:自動識別長文字欄位(\`content\`、\`description\`、\`body\`、\`intro\`、\`text\`)
35
+ - **時間欄位**:自動識別時間相關欄位(\`time\`、\`date\`、\`checkin\`、\`checkout\`、\`created_at\`、\`published_at\`)
36
+ - **數值欄位**:自動識別價格/數量欄位(\`price\`、\`qty\`、\`user\`、\`capacity\`、\`size\`)
37
+ - **布林欄位**:自動識別開關欄位(\`enable\`、\`display\`、\`is_*\`),轉為「啟用/停用」
38
+ - **巢狀物件**:遞迴展開,保留層級結構(如 \`social.{instagram_url, instagram_display}\`)
39
+ - **多語言欄位**:若欄位為 \`{zh_tw, en, ja, ...}\` 結構,以 \`zh_tw\` 為主要輸出語言,不存在時依序 fallback
40
+
41
+ ### 4. 格式還原
42
+ - 若內容為 JSON 字串(Quill Delta 等 RTF 格式),解析後還原為純文字
43
+ - 轉義換行 \`\\n\` → 真實換行、\`\\t\` → 縮排
44
+ - 內嵌 HTML(\`<a href>\`, \`<img>\`, \`<br>\`)還原為對應 Markdown 語法
45
+ - 內嵌 URL 保留為可點擊連結
46
+
47
+ ### 5. 檔案拆分原則
48
+ - 依照 JSON 的**第一層 key** 或**語義主題**拆分成獨立 \`.md\` 檔案
49
+ - 每個檔案涵蓋一個獨立主題區塊
50
+ - 檔名使用英文,反映主題(如 \`Rooms.md\`、\`Policies.md\`、\`Facilities.md\`)
51
+
52
+ ### 6. 索引生成 (Index.md)
53
+ - 彙整所有產出的檔案,生成 \`Index.md\`
54
+ - 格式:\`- [顯示名稱](檔名.md):一句話摘要涵蓋的關鍵主題與具體資訊\`
55
+ - 摘要必須具體,禁止只重複檔名
56
+
57
+ ### 7. 輸出約束
58
+ - **輸出順序**:先 \`Index.md\`,再依序輸出其他檔案
59
+ - **必須標示檔名**:每個程式碼區塊正上方必須有 \`### 檔名.md\` 標題,不可省略
60
+ - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
61
+ - 所有 JSON 內容一律轉為人類可讀的 Markdown,不可保留原始 JSON 字串
62
+
63
+ ## 輸出格式規範:
64
+
65
+ ### Index.md
66
+ \`\`\`markdown
67
+ # 知識庫目錄
68
+ - [顯示名稱 A](A.md):涵蓋的關鍵主題與具體資訊摘要
69
+ - [顯示名稱 B](B.md):涵蓋的關鍵主題與具體資訊摘要
70
+ \`\`\`
71
+
72
+ ---
73
+
74
+ ### 檔名.md
75
+ \`\`\`markdown
76
+ [還原後的 Markdown 內容]
77
+ \`\`\`
78
+
79
+ ---
80
+
81
+ (重複上述格式直到所有檔案輸出完畢)`;
82
+
83
+ const MERGE_PROMPT = `# 角色:知識庫合併架構師 (Knowledge Merge Architect)
84
+
85
+ ## 任務目標
86
+ 將新的內容合併到既有的知識庫檔案結構中,根據內容類型與主題智能決定「新增頁面」、「合併到既有頁面」或「更新既有頁面」。
87
+
88
+ ## 既有知識庫目錄 (Index.md)
89
+ \`\`\`markdown
90
+ {{indexContent}}
91
+ \`\`\`
92
+
93
+ ## 新內容類型:{{fileType}}
94
+ ## 新內容
95
+ \`\`\`{{contentBlock}}
96
+ {{newContent}}
97
+ \`\`\`
98
+
99
+ ## 處理規則:
100
+
101
+ ### 1. 結構識別(依 fileType)
102
+
103
+ **json**:
104
+ - 分析 JSON 頂層結構,以第一層 key 或語義主題分群
105
+ - 若為巢狀物件,每個第一層 key 視為一個主題區塊
106
+ - 若為頂層陣列,每個元素視為獨立條目
107
+
108
+ **markdown**:
109
+ - 依照 \`##\` 或 \`###\` 標題拆分成獨立區塊
110
+ - 每個區塊視為一個新知識條目
111
+
112
+ ### 2. 合併策略判斷
113
+
114
+ 對每個條目,檢查是否與既有 Index.md 中的頁面相關:
115
+
116
+ - **主題全新**(目錄中無相關頁面)→ 建立**新檔案**,Index.md 追加新條目
117
+ - **主題已存在**(標題或關鍵詞與既有頁面重疊)→ 將新內容**合併**到既有檔案,保留既有結構,新增內容作為補充。合併後輸出該檔案的**完整內容**
118
+ - **既有檔案缺少條目**(例如列表型資料漏了某筆)→ 必須**補齊**,將缺漏條目加入對應區塊
119
+ - **內容衝突**(同一主題但資訊不一致,如價格變動、規則修改)→ 以**新內容為準**更新,標記 \`> 更新於 YYYY-MM-DD\`
120
+ - **內容重複**(完全相同)→ 跳過,不輸出
121
+
122
+ ### 3. 完整性驗證
123
+ - 陣列型資料:比對新內容的項目數與既有檔案收錄數,缺漏必須補齊
124
+ - 巢狀陣列(如設施清單、標籤列表):逐一檢查是否全數收錄
125
+ - 多語言欄位:以 \`zh_tw\` 為主要輸出語言,不存在時 fallback 到 \`en\`
126
+ - JSON 字串內容(Quill Delta 等):\`\\n\` → 換行、\`\\t\` → 縮排、HTML → Markdown
127
+
128
+ ### 4. 輸出約束
129
+ - **輸出順序**:先輸出更新後的 \`Index.md\`,再依序輸出所有新增或更新過的檔案
130
+ - 每個檔案前必須有 \`### 檔名.md\` 作為標題,絕對不可省略
131
+ - 每個檔案以獨立 \` \`\`\`markdown \` 程式碼區塊呈現
132
+ - **只輸出有變動的檔案**,未修改的既有檔案不需重複輸出
133
+ - 合併的檔案必須包含**完整內容**(既有 + 新增),不可只輸出差異
134
+
135
+ ## 輸出格式規範:
136
+
137
+ ### Index.md
138
+ \`\`\`markdown
139
+ # 知識庫目錄
140
+ - [顯示名稱 A](A.md):一句話摘要涵蓋的關鍵主題
141
+ - [顯示名稱 B](B.md):一句話摘要涵蓋的關鍵主題
142
+ \`\`\`
143
+
144
+ ---
145
+
146
+ ### 檔名.md
147
+ \`\`\`markdown
148
+ [完整內容]
149
+ \`\`\`
150
+
151
+ ---
152
+
153
+ (重複上述格式直到所有變動檔案輸出完畢)`;
154
+
155
+ const ROUTER_PROMPT = `# 角色設定
156
+ 你是一個精準的「知識庫路由助手 (Router)」。
157
+ 你的唯一任務是分析使用者的問題,並從提供的目錄清單中,挑選出最可能包含解答的檔案名稱。
158
+
159
+ # 使用者問題
160
+ {{prompt}}
161
+
162
+ # 知識庫目錄
163
+ {{indexContent}}
164
+
165
+ # 挑選原則
166
+ - 從目錄中每個檔案的**摘要**判斷相關性,不只比對檔名
167
+ - 考慮同義詞與相關概念(例如:「運動」「健身」→ Facilities.md;「怎麼去」「交通」→ Location_and_Transport.md)
168
+ - 若問題涉及多個主題(如「房價和退房時間」),選取所有相關檔案
169
+
170
+ # 輸出嚴格規範
171
+ 1. **僅輸出檔名**:從「知識庫目錄」中挑選最相關的完整檔案名稱(必須包含 \`.md\` 後綴)。
172
+ 2. **多檔處理**:若有多個檔案相關,請以半形逗號 \`,\` 分隔。
173
+ 3. **無相關時**:若判斷目錄中的檔案皆不相關,請直接回覆 \`NONE\`。
174
+ 4. **禁止任何廢話**:**絕對禁止**輸出任何解釋文字、問候語、符號,也**禁止**使用 Markdown 標記(如代碼塊 \` \`\`\` \` \`\`\` 或清單 \`-\`)。
175
+
176
+ **正確輸出範例:**
177
+ Introduction.md,Policy_Info.md`;
178
+
179
+ /**
180
+ * LLM 輸出解析器
181
+ * 將 LLM 回應中的 Markdown 程式碼區塊解析為獨立檔案
182
+ */
183
+
184
+ /**
185
+ * @typedef {{ filename: string, content: string }} WikiFile
186
+ */
187
+
188
+ /**
189
+ * 解析 LLM 回應,提取程式碼區塊作為獨立檔案
190
+ * @param {string} output - LLM 原始回應文字
191
+ * @returns {WikiFile[]}
192
+ */
193
+ function parseWikiOutput(output) {
194
+ const lines = output.split(/\r?\n/);
195
+ let currentFilename = null;
196
+ let insideCodeBlock = false;
197
+ let currentContent = [];
198
+ const results = [];
199
+
200
+ for (const line of lines) {
201
+ if (line.trim().startsWith('```')) {
202
+ if (!insideCodeBlock) {
203
+ insideCodeBlock = true;
204
+ currentContent = [];
205
+ } else {
206
+ insideCodeBlock = false;
207
+ if (!currentFilename) {
208
+ currentFilename = results.length === 0 ? 'Index.md' : `Unknown_File_${results.length}.md`;
209
+ }
210
+ if (currentFilename) {
211
+ const content = currentContent.join('\n');
212
+ results.push({ filename: currentFilename, content });
213
+ currentFilename = null;
214
+ }
215
+ }
216
+ continue
217
+ }
218
+
219
+ if (insideCodeBlock) {
220
+ currentContent.push(line);
221
+ } else {
222
+ let name = null;
223
+ const titleMatch = line.match(/^#{1,4}\s+([^#]+)/);
224
+ if (titleMatch) {
225
+ name = titleMatch[1].replace(/[<>:"/\\|?*\[\]]/g, '').trim();
226
+ } else {
227
+ const mdMatch = line.match(/([a-zA-Z0-9_.-]+\.md)/i);
228
+ if (mdMatch) name = mdMatch[1].trim();
229
+ }
230
+
231
+ if (name && name.length < 50) {
232
+ if (!name.toLowerCase().endsWith('.md')) name += '.md';
233
+ currentFilename = name;
234
+ }
235
+ }
236
+ }
237
+
238
+ return results
239
+ }
240
+
241
+ /**
242
+ * wiki-router - LLM Wiki 知識庫路由引擎
243
+ *
244
+ * 使用方式:
245
+ * const { createWikiRouter } = require('@jungtz/wiki-router')
246
+ * const wiki = createWikiRouter({ router, knowledgeDir, outputDir })
247
+ * await wiki.build()
248
+ * const ctx = await wiki.getContext('user question')
249
+ */
250
+
251
+
252
+ /** @typedef {import('./types').WikiRouterConfig} WikiRouterConfig */
253
+ /** @typedef {import('./types').WikiRouterInstance} WikiRouterInstance */
254
+
255
+ /**
256
+ * 建立 WikiRouter 實例
257
+ * @param {WikiRouterConfig} config
258
+ * @returns {WikiRouterInstance}
259
+ */
260
+ function createWikiRouter(config) {
261
+ const {
262
+ router,
263
+ knowledgeDir,
264
+ outputDir,
265
+ modelId,
266
+ routerModelId,
267
+ } = config;
268
+
269
+ if (!router) throw new Error('[wiki-router] router is required')
270
+ if (!knowledgeDir) throw new Error('[wiki-router] knowledgeDir is required')
271
+ if (!outputDir) throw new Error('[wiki-router] outputDir is required')
272
+
273
+ const resolvedKnowledgeDir = path.resolve(knowledgeDir);
274
+ const resolvedOutputDir = path.resolve(outputDir);
275
+
276
+ /**
277
+ * 向 LLM 發送對話並取得完整回應
278
+ * @param {{ role: string, content: string }[]} messages
279
+ * @param {string} [overrideModelId]
280
+ * @returns {Promise<string|null>}
281
+ */
282
+ async function chat(messages, overrideModelId) {
283
+ const wikiModelId = overrideModelId || modelId || process.env.WIKI_MODEL || 'ollama-local/gemma4:31b';
284
+
285
+ try {
286
+ let provider;
287
+ let modelName = wikiModelId;
288
+
289
+ if (wikiModelId.includes('/')) {
290
+ const parts = wikiModelId.split('/');
291
+ provider = parts[0];
292
+ modelName = parts.slice(1).join('/');
293
+ }
294
+
295
+ // 使用 AI Router 進行對話
296
+ if (router && provider) {
297
+ await router.switchModel(provider, modelName);
298
+ let content = '';
299
+ const stream = router.chat(messages);
300
+ for await (const chunk of stream) {
301
+ if (chunk.type === 'content') content += chunk.content;
302
+ }
303
+ return content
304
+ }
305
+
306
+ return null
307
+ } catch (err) {
308
+ console.error(`[Wiki Chat Error] Model: ${wikiModelId}, Error:`, err.message);
309
+ return null
310
+ }
311
+ }
312
+
313
+ /**
314
+ * 建構或更新 LLM Wiki 知識庫
315
+ * @returns {Promise<boolean>}
316
+ */
317
+ async function build() {
318
+ try {
319
+ if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
320
+
321
+ const knowledgeFiles = fs.readdirSync(resolvedKnowledgeDir)
322
+ .filter(f => f.endsWith('.json') || f.endsWith('.md'))
323
+ .sort();
324
+
325
+ if (knowledgeFiles.length === 0) {
326
+ console.warn(`[Wiki] No .json or .md files found in: ${resolvedKnowledgeDir}`);
327
+ return false
328
+ }
329
+
330
+ let totalFiles = 0;
331
+
332
+ for (const knowledgeFile of knowledgeFiles) {
333
+ const existingFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
334
+ const isFirstTime = existingFiles.length === 0;
335
+ const filePath = path.join(resolvedKnowledgeDir, knowledgeFile);
336
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
337
+ const fileType = knowledgeFile.endsWith('.json') ? 'json' : 'markdown';
338
+
339
+ console.log(`[Wiki] Processing: ${knowledgeFile} (type: ${fileType}, mode: ${isFirstTime ? 'first' : 'merge'})`);
340
+
341
+ let finalPrompt;
342
+ if (isFirstTime && fileType === 'json') {
343
+ finalPrompt = SPLIT_PROMPT.replace('{{context}}', fileContent);
344
+ } else {
345
+ const indexPath = path.join(resolvedOutputDir, 'Index.md');
346
+ const indexContent = fs.existsSync(indexPath)
347
+ ? fs.readFileSync(indexPath, 'utf-8')
348
+ : '';
349
+ finalPrompt = MERGE_PROMPT
350
+ .replace('{{indexContent}}', indexContent)
351
+ .replace('{{fileType}}', fileType)
352
+ .replace('{{contentBlock}}', fileType === 'json' ? 'json' : 'markdown')
353
+ .replace('{{newContent}}', fileContent);
354
+ }
355
+
356
+ const output = await chat([{ role: 'user', content: finalPrompt }]);
357
+ if (!output) {
358
+ console.warn(`[Wiki] No output for: ${knowledgeFile}`);
359
+ continue
360
+ }
361
+
362
+ const parsed = parseWikiOutput(output);
363
+ if (parsed.length === 0) {
364
+ console.error(`[Wiki] Failed to parse output for: ${knowledgeFile}. Raw:`, output);
365
+ continue
366
+ }
367
+
368
+ for (const { filename, content } of parsed) {
369
+ fs.writeFileSync(path.join(resolvedOutputDir, filename), content);
370
+ console.log(`[Wiki] ${isFirstTime ? 'Generated' : 'Updated'}: ${filename}`);
371
+ }
372
+ totalFiles += parsed.length;
373
+ }
374
+
375
+ if (totalFiles === 0) return false
376
+ return true
377
+ } catch (err) {
378
+ console.error('[Wiki Generation Error]', err);
379
+ return false
380
+ }
381
+ }
382
+
383
+ /**
384
+ * 根據使用者問題取得相關的 Wiki 上下文
385
+ * @param {string} prompt - 使用者問題
386
+ * @returns {Promise<string>}
387
+ */
388
+ async function getContext(prompt) {
389
+ try {
390
+ if (!fs.existsSync(resolvedOutputDir)) fs.mkdirSync(resolvedOutputDir, { recursive: true });
391
+
392
+ let wikiFiles = fs.readdirSync(resolvedOutputDir).filter(f => f.endsWith('.md'));
393
+
394
+ if (wikiFiles.length === 0) {
395
+ const success = await build();
396
+ if (!success) return ''
397
+ }
398
+
399
+ const indexPath = path.join(resolvedOutputDir, 'Index.md');
400
+ if (!fs.existsSync(indexPath)) {
401
+ console.warn('[Wiki] Index.md not found.');
402
+ return ''
403
+ }
404
+
405
+ const indexContent = fs.readFileSync(indexPath, 'utf-8');
406
+ const selectionPrompt = ROUTER_PROMPT
407
+ .replace('{{prompt}}', prompt)
408
+ .replace('{{indexContent}}', indexContent);
409
+
410
+ const routeModel = routerModelId || process.env.WIKI_ROUTER_MODEL || modelId || process.env.WIKI_MODEL;
411
+ const output = await chat(
412
+ [{ role: 'user', content: selectionPrompt }],
413
+ routeModel
414
+ );
415
+ if (!output) return ''
416
+
417
+ const selectedFilesStr = output.trim();
418
+ if (selectedFilesStr === 'NONE' || !selectedFilesStr) {
419
+ console.log('[Wiki] No relevant files selected by LLM.');
420
+ return ''
421
+ }
422
+
423
+ const selectedFiles = selectedFilesStr.split(',').map(s => s.trim());
424
+ let relevantContext = '\n[Wiki 相關參考資料]:\n';
425
+ let loadedCount = 0;
426
+
427
+ for (const file of selectedFiles) {
428
+ const filePath = path.join(resolvedOutputDir, file);
429
+ if (fs.existsSync(filePath)) {
430
+ relevantContext += `\n--- 檔案: ${file} ---\n${fs.readFileSync(filePath, 'utf-8')}\n`;
431
+ loadedCount++;
432
+ }
433
+ }
434
+
435
+ if (loadedCount > 0) {
436
+ console.log(`[Wiki] LLM correctly routed to ${loadedCount} file(s): ${selectedFiles.join(', ')}`);
437
+ return relevantContext
438
+ }
439
+
440
+ } catch (err) {
441
+ console.error('[Wiki Context Error]', err);
442
+ }
443
+ return ''
444
+ }
445
+
446
+ return { build, getContext }
447
+ }
448
+
449
+ export { MERGE_PROMPT, ROUTER_PROMPT, SPLIT_PROMPT, createWikiRouter, parseWikiOutput };
@@ -0,0 +1,65 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * LLM 輸出解析器
5
+ * 將 LLM 回應中的 Markdown 程式碼區塊解析為獨立檔案
6
+ */
7
+
8
+ /**
9
+ * @typedef {{ filename: string, content: string }} WikiFile
10
+ */
11
+
12
+ /**
13
+ * 解析 LLM 回應,提取程式碼區塊作為獨立檔案
14
+ * @param {string} output - LLM 原始回應文字
15
+ * @returns {WikiFile[]}
16
+ */
17
+ function parseWikiOutput(output) {
18
+ const lines = output.split(/\r?\n/);
19
+ let currentFilename = null;
20
+ let insideCodeBlock = false;
21
+ let currentContent = [];
22
+ const results = [];
23
+
24
+ for (const line of lines) {
25
+ if (line.trim().startsWith('```')) {
26
+ if (!insideCodeBlock) {
27
+ insideCodeBlock = true;
28
+ currentContent = [];
29
+ } else {
30
+ insideCodeBlock = false;
31
+ if (!currentFilename) {
32
+ currentFilename = results.length === 0 ? 'Index.md' : `Unknown_File_${results.length}.md`;
33
+ }
34
+ if (currentFilename) {
35
+ const content = currentContent.join('\n');
36
+ results.push({ filename: currentFilename, content });
37
+ currentFilename = null;
38
+ }
39
+ }
40
+ continue
41
+ }
42
+
43
+ if (insideCodeBlock) {
44
+ currentContent.push(line);
45
+ } else {
46
+ let name = null;
47
+ const titleMatch = line.match(/^#{1,4}\s+([^#]+)/);
48
+ if (titleMatch) {
49
+ name = titleMatch[1].replace(/[<>:"/\\|?*\[\]]/g, '').trim();
50
+ } else {
51
+ const mdMatch = line.match(/([a-zA-Z0-9_.-]+\.md)/i);
52
+ if (mdMatch) name = mdMatch[1].trim();
53
+ }
54
+
55
+ if (name && name.length < 50) {
56
+ if (!name.toLowerCase().endsWith('.md')) name += '.md';
57
+ currentFilename = name;
58
+ }
59
+ }
60
+ }
61
+
62
+ return results
63
+ }
64
+
65
+ exports.parseWikiOutput = parseWikiOutput;
@@ -0,0 +1 @@
1
+ export { parseWikiOutput, WikiFile } from './index.js';
@@ -0,0 +1,63 @@
1
+ /**
2
+ * LLM 輸出解析器
3
+ * 將 LLM 回應中的 Markdown 程式碼區塊解析為獨立檔案
4
+ */
5
+
6
+ /**
7
+ * @typedef {{ filename: string, content: string }} WikiFile
8
+ */
9
+
10
+ /**
11
+ * 解析 LLM 回應,提取程式碼區塊作為獨立檔案
12
+ * @param {string} output - LLM 原始回應文字
13
+ * @returns {WikiFile[]}
14
+ */
15
+ function parseWikiOutput(output) {
16
+ const lines = output.split(/\r?\n/);
17
+ let currentFilename = null;
18
+ let insideCodeBlock = false;
19
+ let currentContent = [];
20
+ const results = [];
21
+
22
+ for (const line of lines) {
23
+ if (line.trim().startsWith('```')) {
24
+ if (!insideCodeBlock) {
25
+ insideCodeBlock = true;
26
+ currentContent = [];
27
+ } else {
28
+ insideCodeBlock = false;
29
+ if (!currentFilename) {
30
+ currentFilename = results.length === 0 ? 'Index.md' : `Unknown_File_${results.length}.md`;
31
+ }
32
+ if (currentFilename) {
33
+ const content = currentContent.join('\n');
34
+ results.push({ filename: currentFilename, content });
35
+ currentFilename = null;
36
+ }
37
+ }
38
+ continue
39
+ }
40
+
41
+ if (insideCodeBlock) {
42
+ currentContent.push(line);
43
+ } else {
44
+ let name = null;
45
+ const titleMatch = line.match(/^#{1,4}\s+([^#]+)/);
46
+ if (titleMatch) {
47
+ name = titleMatch[1].replace(/[<>:"/\\|?*\[\]]/g, '').trim();
48
+ } else {
49
+ const mdMatch = line.match(/([a-zA-Z0-9_.-]+\.md)/i);
50
+ if (mdMatch) name = mdMatch[1].trim();
51
+ }
52
+
53
+ if (name && name.length < 50) {
54
+ if (!name.toLowerCase().endsWith('.md')) name += '.md';
55
+ currentFilename = name;
56
+ }
57
+ }
58
+ }
59
+
60
+ return results
61
+ }
62
+
63
+ export { parseWikiOutput };