@open330/kiwimu 0.8.0 → 1.1.0

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/README.md CHANGED
@@ -4,19 +4,41 @@
4
4
 
5
5
  # Kiwi Mu
6
6
 
7
- **나만의 학습 위키를 만드세요**
7
+ **Turn any textbook into your personal learning wiki**
8
8
 
9
- 전공책, PDF, 웹 콘텐츠를 넣으면 — LLM이 챕터/개념별로 분석하여 상호 링크된 학습 위키를 자동 생성합니다.
9
+ 전공책, PDF, 웹 콘텐츠를 넣으면 — LLM이 자동으로 상호 링크된 학습 위키 + 퀴즈를 생성합니다.
10
10
 
11
11
  [![npm](https://img.shields.io/npm/v/@open330/kiwimu?style=flat-square&color=cb3837&logo=npm)](https://www.npmjs.com/package/@open330/kiwimu)
12
12
  [![Bun](https://img.shields.io/badge/Bun-1.0+-fbf0df?style=flat-square&logo=bun&logoColor=black)](https://bun.sh)
13
13
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.0+-3178C6?style=flat-square&logo=typescript&logoColor=white)](https://typescriptlang.org)
14
14
  [![License](https://img.shields.io/badge/License-MIT-green?style=flat-square)](LICENSE)
15
15
 
16
+ <br>
17
+
18
+ <img src="https://github.com/Open330/kiwimu/raw/main/.context/marketing/demo.gif" alt="kiwimu v1.1 데모: 본문 드래그 → 질문 → 위키 페이지로 저장" width="720">
19
+
20
+ <br>
21
+
22
+ > **v1.1 — 위키는 만드는 게 아니라 자라는 거였다.**
23
+ > 본문 드래그 → 팝오버 질문 → AI 답변 → 한 번 클릭으로 정식 위키 페이지로 승격. ([상세 글](https://jiun.dev/posts/kiwimu-v1-1))
24
+
16
25
  </div>
17
26
 
18
27
  ---
19
28
 
29
+ ## What's new in v1.1
30
+
31
+ - 🔖 **출처 추적 (Provenance Tracking)** — 모든 AI 생성 문장에 인라인 인용 자동 부착, 출처 커버리지 행렬 제공
32
+ - 🧱 **스키마 레이어** — `kiwi.toml`의 5줄로 카테고리·용어·페이지 템플릿을 정의하면 LLM이 그 안에서만 작동
33
+ - 💬 **질문 → 위키 승격** — 본문 드래그 → 질문 → "위키에 저장" 한 번이면 정식 페이지. 중복 자동 감지
34
+ - 📑 **콘텐츠 카탈로그** — 자동 카테고리 분류 + 출처 커버리지 한눈 보기
35
+ - 📈 **활동 로그** — 페이지 생성·질문·프로모트·스키마 변경이 시간선으로 누적
36
+ - 👁️ **링크 미리보기 (Peek Panel)** — `/wiki/*` 링크 클릭 시 우측 슬라이드 패널로 미리보기, 확장 버튼으로 전체 이동. 너비 드래그 조절·다이어그램·인라인 편집·드래그 Q&A까지 패널 안에서 그대로 동작
37
+ - 🗂️ **트랙 그룹핑 (Track Grouping)** — `kiwi.toml` 설정으로 사이드바·인덱스를 자동 카테고리(트랙)별로 묶어서 표시
38
+ - 🔑 **인증 토큰 영속화** — 서버 재시작해도 쿠키 기반으로 인증 유지 (관리 페이지·동적 Q&A 한 번 로그인하면 끝)
39
+
40
+ ---
41
+
20
42
  ## 30초 데모 체험
21
43
 
22
44
  API key 없이 바로 체험할 수 있습니다:
@@ -53,16 +75,37 @@ Kiwi Mu는 LLM을 활용해 이 연결을 **자동으로** 만들어, 지식을
53
75
  - **LLM 기반 문서 분석** — 챕터/섹션 구조를 보존한 원본 페이지 + 핵심 개념별 자동 생성 페이지
54
76
  - **원본/개념 분리** — 📖 원본 문서와 📝 개념 문서를 시각적으로 구분
55
77
  - **자동 상호 링크** — 원본↔개념 간 유기적 cross-link + 외부 참고 자료 (Wikipedia 등)
56
- - **학습 퀴즈**개념 페이지 기반 빈칸 채우기 / OX / 단답형 퀴즈 자동 생성
78
+ - **Dynamic Q&A**텍스트 드래그 팝오버 질문 LLM이 개념 페이지 자동 생성 + 하이라이트 링크
79
+ - **웹 페이지 편집** — serve 모드에서 ✏️ 마크다운 편집
80
+ - **SM-2 간격 반복** — Anki 스타일 SRS (퀴즈 자동 생성 포함)
81
+ - **학습 대시보드** — 숙달도, 약한 개념, 복습 일정 시각화
82
+ - **MD 파일 + 디렉토리 일괄 인제스트** — `kiwimu add <directory>`로 .md 파일 일괄 처리
83
+ - **LaTeX 수식 렌더링** — KaTeX 기반 수학 수식 지원
84
+ - **Mermaid 다이어그램 지원** — Mermaid.js 기반 다이어그램 렌더링
57
85
  - **지식 그래프** — D3.js 인터랙티브 그래프 (원본: 파란색, 개념: 초록색)
58
- - **데모 모드** — API key 없이 `--demo`로 즉시 체험
59
- - **다양한 파일 지원** — URL, PDF, DOCX, PPTX, PPT, DOC, KEY, RTF
86
+ - **데모 모드** — API key 없이 `--demo`로 즉시 체험 (양자역학 + 자료구조)
87
+ - **다양한 파일 지원** — URL, PDF, DOCX, PPTX, PPT, DOC, KEY, RTF, **MD** (디렉토리 일괄 인제스트 지원)
60
88
  - **4개 LLM 프로바이더** — Google Gemini, Azure OpenAI, OpenAI, Anthropic
61
- - **다크 모드** — 시스템 테마에 자동 대응
89
+ - **다크 모드** — 시스템 테마에 자동 대응 (100% 커버리지)
62
90
  - **모바일 지원** — 햄버거 메뉴 + 슬라이드 사이드바
91
+ - **접근성** — ARIA 속성, 검색 키보드 네비게이션
63
92
  - **웹 UI** — 브라우저에서 문서 추가, 설정 변경, 빌드 실행
64
93
  - **토큰 사용량 추적** — API 호출 수, 토큰, 예상 비용을 웹에서 확인
65
94
  - **원클릭 배포** — GitHub Pages / Vercel
95
+ - **라이브 데모** — [kiwimu.internal.jiun.dev](https://kiwimu.internal.jiun.dev)
96
+
97
+ ## vs. Alternatives
98
+
99
+ | Feature | Kiwi Mu | NotebookLM | Obsidian | Anki |
100
+ |---------|---------|------------|----------|------|
101
+ | Auto wiki from PDF | ✅ | ❌ | ❌ | ❌ |
102
+ | Knowledge graph | ✅ | ❌ | ✅ (plugin) | ❌ |
103
+ | Auto quiz generation | ✅ | ❌ | ❌ | ❌ (manual) |
104
+ | Spaced repetition | ✅ (basic) | ❌ | ❌ | ✅ |
105
+ | Self-hosted | ✅ | ❌ | ✅ | ✅ |
106
+ | One-click deploy | ✅ | ❌ | ❌ | ❌ |
107
+ | Open source | ✅ | ❌ | ❌ | ✅ |
108
+ | Free | ✅ | ✅ | Freemium | ✅ |
66
109
 
67
110
  ## Quick Start
68
111
 
@@ -112,7 +155,7 @@ Interactive 프롬프트가 실행됩니다:
112
155
  │ ○ Anthropic Claude
113
156
 
114
157
  ◆ 모델명
115
- │ gemini-2.0-flash-lite
158
+ │ gemini-3.1-flash-lite-preview
116
159
 
117
160
  ◆ API Key
118
161
  │ ••••••••••••
@@ -149,6 +192,17 @@ bunx @open330/kiwimu quiz -n 10
149
192
 
150
193
  웹에서도 `http://localhost:8000/quiz.html`에서 카드 플립 방식으로 퀴즈를 풀 수 있습니다.
151
194
 
195
+ ### Dynamic Q&A
196
+
197
+ 위키 페이지에서 이해가 안 되는 부분을 드래그하면, 팝오버가 나타나 LLM에게 질문할 수 있습니다.
198
+
199
+ 1. **텍스트 드래그** — 궁금한 구절을 선택
200
+ 2. **팝오버 질문** — "이게 뭐야?", 자유 질문, 또는 자동 생성 질문 선택
201
+ 3. **새 개념 페이지 생성** — LLM이 답변을 새로운 개념 페이지로 자동 생성
202
+ 4. **하이라이트 링크** — 드래그한 텍스트가 새 페이지로의 링크로 변환
203
+
204
+ `kiwimu serve` 모드에서 실시간으로 동작합니다. 학습 중 발생하는 궁금증을 즉시 해결하고, 위키가 유기적으로 확장됩니다.
205
+
152
206
  ### 빌드 및 서버
153
207
 
154
208
  ```bash
@@ -165,7 +219,7 @@ bunx @open330/kiwimu serve -p 3000
165
219
 
166
220
  ### 관리 페이지
167
221
 
168
- `kiwimu serve` 실행 후 콘솔에 표시되는 admin URL로 접속:
222
+ `kiwimu serve` 실행 후 콘솔에 표시되는 관리 URL (`/manage?token=...`)로 접속:
169
223
  - 위키 이름 변경
170
224
  - LLM 프로바이더/모델/API Key 설정
171
225
  - 토큰 사용량 및 예상 비용 확인
@@ -190,7 +244,8 @@ bunx @open330/kiwimu deploy --target vercel
190
244
  |------|------|
191
245
  | `kiwimu init [name]` | 새 위키 프로젝트 생성 (interactive CLI) |
192
246
  | `kiwimu init --demo` | 샘플 데이터로 즉시 체험 (API key 불필요) |
193
- | `kiwimu add <source>` | URL 또는 파일 추가 (PDF, DOCX, PPTX, DOC, PPT, KEY, RTF) |
247
+ | `kiwimu add <source>` | URL 또는 파일 추가 (PDF, DOCX, PPTX, DOC, PPT, KEY, RTF, MD) |
248
+ | `kiwimu add <directory>` | 디렉토리 내 모든 .md 파일 일괄 인제스트 |
194
249
  | `kiwimu build` | 정적 위키 사이트 빌드 |
195
250
  | `kiwimu serve [-p port]` | 웹 서버 실행 (문서 추가/관리 가능) |
196
251
  | `kiwimu quiz [-n count]` | 터미널에서 학습 퀴즈 풀기 |
@@ -208,22 +263,23 @@ bunx @open330/kiwimu deploy --target vercel
208
263
  | PPTX | ZIP/XML 파싱 |
209
264
  | DOC / PPT / RTF | macOS textutil |
210
265
  | KEY (Keynote) | 텍스트 추출 (제한적) |
266
+ | Markdown (.md) | 직접 텍스트 추출 (디렉토리 일괄 지원) |
211
267
 
212
268
  ## Supported LLM Providers
213
269
 
214
270
  | 프로바이더 | 추천 모델 | 비고 |
215
271
  |-----------|----------|------|
216
- | **Google Gemini** | `gemini-2.0-flash-lite` | [무료 API key](https://aistudio.google.com/) |
217
- | Azure OpenAI | `gpt-5-nano` | Azure 구독 필요 |
218
- | OpenAI | `gpt-4o` | API key 필요 |
219
- | Anthropic | `claude-sonnet-4-20250514` | API key 필요 |
272
+ | **Google Gemini** | `gemini-3.1-flash-lite-preview` | [무료 API key](https://aistudio.google.com/) |
273
+ | Azure OpenAI | `gpt-5.4-nano` | Azure 구독 필요 |
274
+ | OpenAI | `gpt-5.4` | API key 필요 |
275
+ | Anthropic | `claude-sonnet-4-6` | API key 필요 |
220
276
 
221
277
  ## Architecture
222
278
 
223
279
  ```
224
- 소스 (URL / PDF / DOCX / PPTX / DOC / PPT / KEY / RTF)
280
+ 소스 (URL / PDF / DOCX / PPTX / DOC / PPT / KEY / RTF / MD)
225
281
 
226
- [ Ingest ] ── Cheerio / pdf-parse / mammoth / jszip / textutil
282
+ [ Ingest ] ── Cheerio / pdf-parse / mammoth / jszip / textutil / MD 직접 추출
227
283
 
228
284
  [ Phase 1 ] ── LLM: 원본 구조 추출 (📖 원본 페이지) — 병렬 처리 (concurrency=3)
229
285
 
@@ -233,24 +289,45 @@ bunx @open330/kiwimu deploy --target vercel
233
289
 
234
290
  [ Phase 3 ] ── [[wiki link]] 해석 + 원본↔개념 cross-link
235
291
 
236
- [ Build ] ── 정적 HTML (사이드바, KaTeX, 지식 그래프, 퀴즈, 다크 모드)
292
+ [ Build ] ── 정적 HTML (사이드바, KaTeX, Mermaid, 지식 그래프, 퀴즈, 다크 모드)
237
293
 
238
294
  [ Deploy ] ── GitHub Pages / Vercel
295
+
296
+ [ Dynamic Q&A ] ── 텍스트 드래그 → 팝오버 → LLM 질문 → 새 개념 페이지 생성 + 하이라이트 링크
297
+ (serve 모드에서 실시간 동작)
239
298
  ```
240
299
 
241
300
  ```
242
301
  project-dir/
243
- ├── kiwi.toml # 프로젝트 + LLM 설정
244
- ├── kiwi.db # SQLite (문서, 링크, 퀴즈, 사용량)
245
- ├── uploads/ # 업로드된 파일
246
- └── _site/ # 빌드 결과
247
- ├── index.html # 홈 (문서 목록)
248
- ├── graph.html # 지식 그래프
249
- ├── quiz.html # 학습 퀴즈
250
- ├── wiki/ # 문서 페이지
251
- │ └── random.html # 임의 문서
252
- ├── static/ # CSS, JS, 로고
302
+ ├── kiwi.toml # 프로젝트 + LLM 설정
303
+ ├── kiwi.db # SQLite (문서, 링크, 퀴즈, 사용량)
304
+ ├── uploads/ # 업로드된 파일
305
+ └── _site/ # 빌드 결과
306
+ ├── index.html # 홈 (문서 목록)
307
+ ├── graph.html # 지식 그래프
308
+ ├── quiz.html # 학습 퀴즈
309
+ ├── dashboard.html # 학습 대시보드
310
+ ├── wiki/ # 문서 페이지
311
+ │ └── random.html # 임의 문서
312
+ ├── static/ # CSS, JS, 로고
313
+ │ ├── dynamic-qa.js # Dynamic Q&A (드래그→팝오버→질문)
314
+ │ └── edit-page.js # 웹 페이지 편집 모달
253
315
  └── search-index.json
316
+
317
+ src/
318
+ ├── services/
319
+ │ ├── dynamic-qa.ts # Dynamic Q&A 서버 로직
320
+ │ └── ingest.ts # 공유 인제스트 로직
321
+ ├── ingest/
322
+ │ ├── markdown.ts # Markdown 파일 파싱 (디렉토리 일괄 지원)
323
+ │ ├── web.ts / pdf.ts / docx.ts / pptx.ts
324
+ │ └── ...
325
+ ├── demo/
326
+ │ ├── sample-data.ts # 데모 샘플 데이터
327
+ │ └── setup.ts # 데모 초기화
328
+ └── build/static/
329
+ ├── dynamic-qa.js # Dynamic Q&A 클라이언트
330
+ └── edit-page.js # 페이지 편집 클라이언트
254
331
  ```
255
332
 
256
333
  ## Tech Stack
@@ -263,7 +340,8 @@ project-dir/
263
340
  - **JSZip** — PPTX 파싱
264
341
  - **Marked** + **sanitize-html** — Markdown → 안전한 HTML
265
342
  - **D3.js** — 지식 그래프
266
- - **KaTeX** — 수학 수식 렌더링
343
+ - **KaTeX** — LaTeX 수학 수식 렌더링
344
+ - **Mermaid.js** — 다이어그램 렌더링
267
345
  - **gh-pages** — GitHub Pages 배포
268
346
 
269
347
  ## Security
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open330/kiwimu",
3
- "version": "0.8.0",
3
+ "version": "1.1.0",
4
4
  "description": "Turn textbooks, PDFs, and web content into your own interlinked learning wiki powered by LLM",
5
5
  "type": "module",
6
6
  "bin": {
@@ -1,17 +1,44 @@
1
- import { mkdirSync, rmSync, cpSync, existsSync } from "fs";
1
+ import { mkdirSync, rmSync, cpSync, existsSync, readFileSync, writeFileSync } from "fs";
2
2
  import { join, dirname } from "path";
3
3
  import { marked } from "marked";
4
4
  import sanitizeHtml from "sanitize-html";
5
- import type { KiwiConfig } from "../config";
5
+ import { loadConfig, type KiwiConfig } from "../config";
6
6
  import type { Store } from "../store";
7
7
  import { buildGraphData } from "../pipeline/graph";
8
- import { renderPage, renderIndex, renderGraph, renderQuizPage } from "./templates";
8
+ import { renderCitationFootnotes } from "../pipeline/citations";
9
+ import { renderPage, renderIndex, renderGraph, renderQuizPage, renderDashboardPage, renderCatalogPage } from "./templates";
10
+
11
+ function escapeHtmlChars(s: string): string {
12
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
13
+ }
14
+
15
+ // Fallback: catches any ```mermaid block that slipped past the placeholder pre-pass.
16
+ // Keeps marked's existing escaping intact — the browser decodes via textContent
17
+ // when mermaid.js reads the diagram source.
18
+ function convertMermaidBlocks(html: string): string {
19
+ if (!html.includes('language-mermaid')) return html;
20
+ return html.replace(
21
+ /<pre><code class="language-mermaid">([\s\S]*?)<\/code><\/pre>/g,
22
+ (_match, code: string) => {
23
+ if (!code.trim()) return '';
24
+ return `<pre class="mermaid">${code}</pre>`;
25
+ }
26
+ );
27
+ }
9
28
 
10
29
  // Fix internal wiki links: /wiki/slug → /wiki/slug.html
11
- function fixWikiLinks(html: string): string {
30
+ // Mark non-existent pages as "red links" (wiki convention for missing pages)
31
+ function fixWikiLinks(html: string, existingSlugs?: Set<string>): string {
12
32
  return html.replace(/href="\/wiki\/([^"]+?)"/g, (match, slug) => {
13
- if (slug.endsWith(".html")) return match;
14
- return `href="/wiki/${slug}.html"`;
33
+ const cleanSlug = slug.endsWith(".html") ? slug.replace(".html", "") : slug;
34
+ const decodedSlug = decodeURIComponent(cleanSlug);
35
+ const href = slug.endsWith(".html") ? match : `href="/wiki/${slug}.html"`;
36
+
37
+ // If we have slug list and this page doesn't exist, mark as red link
38
+ if (existingSlugs && !existingSlugs.has(decodedSlug) && !existingSlugs.has(cleanSlug)) {
39
+ return `${href} class="redlink" title="문서 없음: ${decodedSlug}"`;
40
+ }
41
+ return href;
15
42
  });
16
43
  }
17
44
 
@@ -43,6 +70,79 @@ function generateToc(markdown: string): string {
43
70
  .join("")}</ul></div>`;
44
71
  }
45
72
 
73
+ // Shared markdown rendering + sanitization logic
74
+ export async function renderPageContent(page: { content: string }, existingSlugs?: Set<string>): Promise<string> {
75
+ // Convert [[wiki links]] to markdown links before rendering
76
+ // [[slug]] → [slug](/wiki/slug.html)
77
+ // [[slug|display text]] → [display text](/wiki/slug.html)
78
+ let markdown = page.content.replace(/\[\[([^\]|]+?)(?:\|([^\]]+?))?\]\]/g, (_match, slug, display) => {
79
+ const text = display || slug.replace(/-/g, ' ');
80
+ return `[${text}](/wiki/${encodeURIComponent(slug)}.html)`;
81
+ });
82
+
83
+ // Protect LaTeX math from marked() processing
84
+ // Replace $...$ and $$...$$ with placeholders to prevent _ and * from being parsed as markdown
85
+ const mathPlaceholders: string[] = [];
86
+ markdown = markdown.replace(/\$\$[\s\S]+?\$\$/g, (match) => {
87
+ mathPlaceholders.push(match);
88
+ return `%%MATH_BLOCK_${mathPlaceholders.length - 1}%%`;
89
+ });
90
+ markdown = markdown.replace(/\$(?!\$)(.+?)\$/g, (match) => {
91
+ mathPlaceholders.push(match);
92
+ return `%%MATH_INLINE_${mathPlaceholders.length - 1}%%`;
93
+ });
94
+
95
+ // Protect mermaid fenced blocks: extract verbatim before marked sees them, so
96
+ // node labels containing markdown chars (*, _, |) or HTML chars (<, >, ")
97
+ // never get mangled by marked or stripped by sanitize-html.
98
+ const mermaidBlocks: string[] = [];
99
+ markdown = markdown.replace(/```mermaid\r?\n([\s\S]*?)```/g, (_match, body: string) => {
100
+ mermaidBlocks.push(body);
101
+ return `\n\n%%MERMAID_BLOCK_${mermaidBlocks.length - 1}%%\n\n`;
102
+ });
103
+
104
+ let htmlContent = await marked(markdown);
105
+
106
+ // Restore LaTeX math from placeholders
107
+ htmlContent = htmlContent.replace(/%%MATH_(BLOCK|INLINE)_(\d+)%%/g, (_match, _type, idx) => {
108
+ return mathPlaceholders[parseInt(idx)] || '';
109
+ });
110
+ // Fallback: convert any leftover marked-emitted mermaid code blocks
111
+ htmlContent = convertMermaidBlocks(htmlContent);
112
+ htmlContent = sanitizeHtml(htmlContent, {
113
+ allowedTags: sanitizeHtml.defaults.allowedTags.concat([
114
+ 'img', 'details', 'summary', 'kbd', 'del', 's', 'sup', 'sub',
115
+ 'span', 'div', 'section', 'figure', 'figcaption', 'mark',
116
+ 'pre', 'code'
117
+ ]),
118
+ allowedAttributes: {
119
+ ...sanitizeHtml.defaults.allowedAttributes,
120
+ '*': ['id', 'class'],
121
+ 'img': ['src', 'alt', 'title', 'width', 'height'],
122
+ 'a': ['href', 'title', 'target', 'rel'],
123
+ 'span': ['class'], // For KaTeX
124
+ 'pre': ['class'], // For Mermaid
125
+ 'code': ['class'],
126
+ },
127
+ allowedSchemes: ['http', 'https', 'mailto'],
128
+ });
129
+
130
+ // Restore mermaid blocks AFTER sanitize so the diagram source is preserved
131
+ // verbatim. Escape only the HTML structural chars so the browser's textContent
132
+ // (which mermaid.js uses) yields the original characters.
133
+ htmlContent = htmlContent.replace(
134
+ /(?:<p>\s*)?%%MERMAID_BLOCK_(\d+)%%(?:\s*<\/p>)?/g,
135
+ (_match, idx) => {
136
+ const body = mermaidBlocks[parseInt(idx, 10)] || '';
137
+ if (!body.trim()) return '';
138
+ return `<pre class="mermaid">${escapeHtmlChars(body)}</pre>`;
139
+ }
140
+ );
141
+
142
+ htmlContent = fixWikiLinks(htmlContent, existingSlugs);
143
+ return htmlContent;
144
+ }
145
+
46
146
  export async function buildSite(store: Store, config: KiwiConfig, projectRoot: string): Promise<number> {
47
147
  const outputDir = join(projectRoot, config.build.output_dir);
48
148
  const wikiDir = join(outputDir, "wiki");
@@ -57,36 +157,53 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
57
157
  cpSync(assetsDir, staticDir, { recursive: true });
58
158
  }
59
159
 
60
- // Copy logo
61
- const logoSrc = join(projectRoot, "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png");
62
- const logoSrc2 = join(projectRoot, "assets", "logos", "logo_2_minimalist_icon_transparent.png");
63
- const logoFile = existsSync(logoSrc) ? logoSrc : existsSync(logoSrc2) ? logoSrc2 : null;
64
- if (logoFile) {
160
+ // Copy logo (check multiple possible locations).
161
+ // Order: shipped-with-kiwimu (works for both git clone and npm install), then
162
+ // wiki-project-local overrides, then Docker path, then the assetsDir copy
163
+ // already produced above (so Bun.file lookups stay consistent).
164
+ const kiwimuAssets = join(dirname(import.meta.path), "..", "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png");
165
+ const logoCandidates = [
166
+ kiwimuAssets,
167
+ join(projectRoot, "..", "assets", "logos", "logo_2_minimalist_icon_transparent.png"),
168
+ join(projectRoot, "assets", "logos", "logo_2_minimalist_icon_transparent.png"),
169
+ "/app/assets/logos/logo_2_minimalist_icon_transparent.png", // Docker path
170
+ join(staticDir, "logo.png"), // already copied via assetsDir → use it as the source
171
+ ];
172
+ const logoFile = logoCandidates.find(p => existsSync(p)) || null;
173
+ if (logoFile && logoFile !== join(staticDir, "logo.png")) {
65
174
  cpSync(logoFile, join(staticDir, "logo.png"));
66
175
  }
67
176
 
177
+ // Browsers fetch /favicon.ico from the site root regardless of HTML markup,
178
+ // so we mirror it from the bundled static assets if present.
179
+ const faviconSrc = join(staticDir, "favicon.ico");
180
+ if (existsSync(faviconSrc)) {
181
+ cpSync(faviconSrc, join(outputDir, "favicon.ico"));
182
+ } else if (logoFile) {
183
+ // Fall back to the logo as a favicon so /favicon.ico never 404s.
184
+ cpSync(logoFile, join(outputDir, "favicon.ico"));
185
+ }
186
+
68
187
  const pages = store.listPages();
69
188
  const sourcePages = store.listSourcePages();
70
189
  const conceptPages = store.listConceptPages();
71
190
  const wikiName = config.project.name;
72
191
  const backlinksMap = store.getAllBacklinksGrouped();
192
+ const allSlugs = new Set(pages.map(p => p.slug));
193
+ const categories = config.categories;
194
+
195
+ // Build source_id → uri map so PageLink rows can carry sourceUri (used by templates for category grouping)
196
+ const sourceUriMap = new Map<number, string>();
197
+ for (const s of store.listSources()) sourceUriMap.set(s.id, s.uri);
198
+ const sourceLink = (p: { slug: string; title: string; source_id: number; origin?: string }) => ({
199
+ slug: p.slug,
200
+ title: p.title,
201
+ sourceUri: sourceUriMap.get(p.source_id),
202
+ ...(p.origin ? { origin: p.origin } : {}),
203
+ });
73
204
 
74
205
  for (const page of pages) {
75
- let htmlContent = await marked(page.content);
76
- htmlContent = sanitizeHtml(htmlContent, {
77
- allowedTags: sanitizeHtml.defaults.allowedTags.concat([
78
- 'img', 'details', 'summary', 'kbd', 'del', 's', 'sup', 'sub',
79
- 'span', 'div', 'section', 'figure', 'figcaption', 'mark'
80
- ]),
81
- allowedAttributes: {
82
- ...sanitizeHtml.defaults.allowedAttributes,
83
- '*': ['id', 'class', 'style'],
84
- 'img': ['src', 'alt', 'title', 'width', 'height'],
85
- 'a': ['href', 'title', 'target', 'rel'],
86
- },
87
- allowedSchemes: ['http', 'https', 'mailto'],
88
- });
89
- htmlContent = fixWikiLinks(htmlContent);
206
+ const htmlContent = await renderPageContent(page, allSlugs);
90
207
 
91
208
  const { body, externalRefs } = extractExternalRefs(htmlContent);
92
209
  const toc = generateToc(page.content);
@@ -96,17 +213,25 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
96
213
  pageType: bl.page_type,
97
214
  }));
98
215
 
216
+ // Citations footer
217
+ const citations = store.getCitationsForPage(page.id);
218
+ const citationsHtml = renderCitationFootnotes(citations);
219
+
99
220
  const html = renderPage({
100
221
  wikiName,
101
222
  pageTitle: page.title,
102
223
  pageSlug: page.slug,
103
224
  pageType: page.page_type,
225
+ pageId: page.id,
226
+ origin: page.origin,
104
227
  content: body,
105
228
  externalRefs,
106
229
  toc,
107
230
  backlinks,
108
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
109
- conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
231
+ citationsHtml,
232
+ sourcePages: sourcePages.map(sourceLink),
233
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title, origin: p.origin })),
234
+ categories,
110
235
  });
111
236
 
112
237
  await Bun.write(join(wikiDir, `${page.slug}.html`), html);
@@ -114,9 +239,10 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
114
239
 
115
240
  const indexHtml = renderIndex({
116
241
  wikiName,
117
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
242
+ sourcePages: sourcePages.map(sourceLink),
118
243
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
119
- sourceCount: store.listSources().length,
244
+ sourceCount: store.countSources(),
245
+ categories,
120
246
  });
121
247
  await Bun.write(join(outputDir, "index.html"), indexHtml);
122
248
 
@@ -126,8 +252,9 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
126
252
  join(outputDir, "graph.html"),
127
253
  renderGraph({
128
254
  wikiName,
129
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
255
+ sourcePages: sourcePages.map(sourceLink),
130
256
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
257
+ categories,
131
258
  })
132
259
  );
133
260
 
@@ -146,7 +273,41 @@ export async function buildSite(store: Store, config: KiwiConfig, projectRoot: s
146
273
  page_title: q.page_title,
147
274
  page_slug: q.page_slug,
148
275
  })),
149
- sourcePages: sourcePages.map((p) => ({ slug: p.slug, title: p.title })),
276
+ sourcePages: sourcePages.map(sourceLink),
277
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
278
+ categories,
279
+ })
280
+ );
281
+
282
+ // Dashboard page
283
+ const stats = store.getLearningStats();
284
+ const weakConcepts = store.getWeakConcepts(10);
285
+ const recentAttempts = store.getQuizHistory(20);
286
+ await Bun.write(
287
+ join(outputDir, "dashboard.html"),
288
+ renderDashboardPage({
289
+ wikiName,
290
+ stats,
291
+ weakConcepts,
292
+ recentAttempts,
293
+ sourcePages: sourcePages.map(sourceLink),
294
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
295
+ categories,
296
+ })
297
+ );
298
+
299
+ // Catalog (index) page
300
+ const { generateContentIndex } = await import("../services/index-generator");
301
+ const contentIndex = await generateContentIndex(store);
302
+ await Bun.write(
303
+ join(outputDir, "catalog.html"),
304
+ renderCatalogPage({
305
+ wikiName,
306
+ categories: contentIndex.categories,
307
+ totalPages: contentIndex.totalPages,
308
+ totalLinks: contentIndex.totalLinks,
309
+ generatedAt: contentIndex.generatedAt,
310
+ sourcePages: sourcePages.map(sourceLink),
150
311
  conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title })),
151
312
  })
152
313
  );
@@ -174,3 +335,82 @@ fetch('/search-index.json').then(r=>r.json()).then(pages=>{
174
335
 
175
336
  return pages.length;
176
337
  }
338
+
339
+ export async function buildSinglePage(root: string, store: Store, slug: string): Promise<void> {
340
+ const page = store.getPage(slug);
341
+ if (!page) return;
342
+
343
+ const config = loadConfig(root);
344
+ const siteDir = join(root, config.build?.output_dir || "_site");
345
+ const wikiDir = join(siteDir, "wiki");
346
+ mkdirSync(wikiDir, { recursive: true });
347
+
348
+ const sourcePages = store.listSourcePages();
349
+ const conceptPages = store.listConceptPages();
350
+ const wikiName = config.project.name;
351
+ const backlinksMap = store.getAllBacklinksGrouped();
352
+
353
+ const sourceUriMap = new Map<number, string>();
354
+ for (const s of store.listSources()) sourceUriMap.set(s.id, s.uri);
355
+ const sourceLink = (p: { slug: string; title: string; source_id: number; origin?: string }) => ({
356
+ slug: p.slug,
357
+ title: p.title,
358
+ sourceUri: sourceUriMap.get(p.source_id),
359
+ ...(p.origin ? { origin: p.origin } : {}),
360
+ });
361
+
362
+ // Render the single page
363
+ const htmlContent = await renderPageContent(page);
364
+
365
+ const { body, externalRefs } = extractExternalRefs(htmlContent);
366
+ const toc = generateToc(page.content);
367
+ const backlinks = (backlinksMap.get(page.id) || []).map((bl) => ({
368
+ slug: bl.slug,
369
+ title: bl.title,
370
+ pageType: bl.page_type,
371
+ }));
372
+
373
+ // Citations footer
374
+ const citations = store.getCitationsForPage(page.id);
375
+ const citationsHtml = renderCitationFootnotes(citations);
376
+
377
+ const html = renderPage({
378
+ wikiName,
379
+ pageTitle: page.title,
380
+ pageSlug: page.slug,
381
+ pageType: page.page_type,
382
+ pageId: page.id,
383
+ origin: page.origin,
384
+ content: body,
385
+ externalRefs,
386
+ toc,
387
+ backlinks,
388
+ citationsHtml,
389
+ sourcePages: sourcePages.map(sourceLink),
390
+ conceptPages: conceptPages.map((p) => ({ slug: p.slug, title: p.title, origin: p.origin })),
391
+ categories: config.categories,
392
+ });
393
+
394
+ await Bun.write(join(wikiDir, `${page.slug}.html`), html);
395
+
396
+ // Update search-index.json
397
+ const searchIndexPath = join(siteDir, "search-index.json");
398
+ let searchData: Array<{ slug: string; title: string; preview: string; type: string }> = [];
399
+ if (existsSync(searchIndexPath)) {
400
+ try {
401
+ searchData = JSON.parse(readFileSync(searchIndexPath, "utf-8"));
402
+ } catch {
403
+ searchData = [];
404
+ }
405
+ }
406
+ // Remove existing entry for this slug if any
407
+ searchData = searchData.filter((p) => p.slug !== page.slug);
408
+ // Append new entry
409
+ searchData.push({
410
+ slug: page.slug,
411
+ title: page.title,
412
+ preview: page.content.slice(0, 200),
413
+ type: page.page_type,
414
+ });
415
+ await Bun.write(searchIndexPath, JSON.stringify(searchData));
416
+ }