readme-guide 0.0.0-stage → 0.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.
@@ -0,0 +1,424 @@
1
+ // 輕量的 Markdown 解析:只做到規則用得到的程度。
2
+ // 處理:程式碼區塊(``` 與 ~~~)、HTML 註解、標題(# 與底線式、單行 <h1>)、
3
+ // 行內程式碼、圖片與連結(含參照式、徽章外面包連結)、HTML 的 <img> 與 <a>、表格。
4
+ // 不處理:縮排四格的程式碼區塊、跨行的 HTML 標籤、跨行的行內程式碼。
5
+
6
+ const FENCE_OPEN = /^(\s*)(`{3,}|~{3,})(.*)$/;
7
+ const ATX_HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
8
+ const SETEXT_H1 = /^ {0,3}=+[ \t]*$/;
9
+ const SETEXT_H2 = /^ {0,3}-+[ \t]*$/;
10
+ const HTML_HEADING = /^\s*<h([1-6])\b[^>]*>(.*?)<\/h\1>\s*$/i;
11
+ const REF_DEFINITION = /^ {0,3}\[([^\]]+)\]:\s*<?([^\s>]+)>?(?:\s+(?:"[^"]*"|'[^']*'|\([^)]*\)))?\s*$/;
12
+ const LIST_ITEM = /^\s{0,3}(?:[-*+]|\d+[.)])(?:\s|$)/;
13
+ const BLOCKQUOTE = /^\s{0,3}>/;
14
+ const THEMATIC_BREAK = /^\s{0,3}([-*_])(?:\s*\1){2,}\s*$/;
15
+ const TABLE_SEPARATOR = /^\s*\|?\s*:?-+:?\s*(?:\|\s*:?-+:?\s*)*\|?\s*$/;
16
+ const HTML_LINE = /^\s{0,3}<\/?[a-zA-Z][^>]*>?/;
17
+ // 只有開關標籤、沒有文字的一行(例如 <div align="center">)
18
+ const WRAPPER_TAG_ONLY = /^\s*(?:<\/?(?:div|p|center|section|span|br|picture)\b[^>]*>\s*)+$/i;
19
+
20
+ /**
21
+ * 解析 Markdown 文字。
22
+ * @param {string} source 原始文字
23
+ */
24
+ export function parseMarkdown(source) {
25
+ const text = source.replace(/^\uFEFF/, '').replace(/\r\n?/g, '\n');
26
+ const raw = text.split('\n');
27
+ /** 每一行的種類:blank、text、fence、code、comment、frontmatter */
28
+ const kinds = new Array(raw.length).fill('text');
29
+ const codeBlocks = [];
30
+
31
+ // 第一輪:前置資料、程式碼區塊、HTML 註解
32
+ let i = 0;
33
+ if (raw[0] === '---') {
34
+ const end = raw.findIndex((line, idx) => idx > 0 && idx < 60 && (line === '---' || line === '...'));
35
+ const body = end > 0 ? raw.slice(1, end) : [];
36
+ if (end > 0 && body.length > 0 && body.every((line) => line.trim() === '' || /^[\w-]+\s*:/.test(line) || /^\s/.test(line))) {
37
+ for (let k = 0; k <= end; k++) kinds[k] = 'frontmatter';
38
+ i = end + 1;
39
+ }
40
+ }
41
+ let fence = null;
42
+ let inComment = false;
43
+ for (; i < raw.length; i++) {
44
+ const line = raw[i];
45
+ if (fence) {
46
+ const close = line.match(/^\s*(`{3,}|~{3,})\s*$/);
47
+ if (close && close[1][0] === fence.char && close[1].length >= fence.length) {
48
+ kinds[i] = 'fence';
49
+ fence.block.endLine = i + 1;
50
+ fence = null;
51
+ } else {
52
+ kinds[i] = 'code';
53
+ fence.block.lines.push({ line: i + 1, text: line });
54
+ }
55
+ continue;
56
+ }
57
+ if (inComment) {
58
+ kinds[i] = 'comment';
59
+ if (line.includes('-->')) inComment = false;
60
+ continue;
61
+ }
62
+ const open = line.match(FENCE_OPEN);
63
+ if (open && !(open[2][0] === '`' && open[3].includes('`'))) {
64
+ const info = open[3].trim();
65
+ const lang = (info.match(/^\{?\.?([^\s{}]+)/)?.[1] ?? '').toLowerCase();
66
+ const block = { startLine: i + 1, endLine: raw.length, info, lang, fence: open[2], lines: [] };
67
+ codeBlocks.push(block);
68
+ fence = { char: open[2][0], length: open[2].length, block };
69
+ kinds[i] = 'fence';
70
+ continue;
71
+ }
72
+ if (/^\s*<!--/.test(line)) {
73
+ kinds[i] = 'comment';
74
+ const rest = line.slice(line.indexOf('<!--') + 4);
75
+ if (!rest.includes('-->')) inComment = true;
76
+ continue;
77
+ }
78
+ kinds[i] = line.trim() === '' ? 'blank' : 'text';
79
+ }
80
+
81
+ // 參照式連結的定義
82
+ const definitions = new Map();
83
+ const isDefinition = new Array(raw.length).fill(false);
84
+ raw.forEach((line, idx) => {
85
+ if (kinds[idx] !== 'text') return;
86
+ const m = line.match(REF_DEFINITION);
87
+ if (m && !/^\^/.test(m[1])) {
88
+ definitions.set(normalizeLabel(m[1]), m[2]);
89
+ isDefinition[idx] = true;
90
+ }
91
+ });
92
+
93
+ // 第二輪:標題
94
+ const headings = [];
95
+ const headingAt = new Map();
96
+ for (let idx = 0; idx < raw.length; idx++) {
97
+ if (kinds[idx] !== 'text' || isDefinition[idx]) continue;
98
+ const line = raw[idx];
99
+ const atx = line.match(ATX_HEADING);
100
+ if (atx) {
101
+ addHeading(idx, atx[1].length, atx[2] ?? '', 'atx');
102
+ continue;
103
+ }
104
+ const html = line.match(HTML_HEADING);
105
+ if (html) {
106
+ addHeading(idx, Number(html[1]), html[2], 'html');
107
+ continue;
108
+ }
109
+ const next = raw[idx + 1];
110
+ if (next !== undefined && kinds[idx + 1] === 'text' && isParagraphLine(line)) {
111
+ const prevIsText = idx > 0 && kinds[idx - 1] === 'text' && !headingAt.has(idx - 1) && isParagraphLine(raw[idx - 1]);
112
+ if (SETEXT_H1.test(next)) {
113
+ addHeading(idx, 1, line.trim(), 'setext', idx + 1);
114
+ idx++;
115
+ } else if (SETEXT_H2.test(next) && !prevIsText) {
116
+ addHeading(idx, 2, line.trim(), 'setext', idx + 1);
117
+ idx++;
118
+ }
119
+ }
120
+ }
121
+
122
+ function addHeading(idx, level, rawText, style, underlineIdx) {
123
+ const heading = { line: idx + 1, level, raw: rawText, text: plainText(rawText), style };
124
+ headings.push(heading);
125
+ headingAt.set(idx, heading);
126
+ if (underlineIdx !== undefined) headingAt.set(underlineIdx, heading);
127
+ }
128
+
129
+ // 行內內容:遮掉行內程式碼與註解後的文字、圖片、連結
130
+ const lines = [];
131
+ const images = [];
132
+ const links = [];
133
+ const inlineCode = [];
134
+ for (let idx = 0; idx < raw.length; idx++) {
135
+ const kind = kinds[idx];
136
+ const entry = { line: idx + 1, raw: raw[idx], kind, prose: '', heading: headingAt.get(idx) ?? null, definition: isDefinition[idx] };
137
+ lines.push(entry);
138
+ if (kind !== 'text') continue;
139
+ if (headingAt.has(idx) && headingAt.get(idx).line !== idx + 1) {
140
+ // 底線式標題的底線本身沒有內容
141
+ continue;
142
+ }
143
+ const { masked, spans } = maskInline(raw[idx]);
144
+ entry.prose = masked;
145
+ for (const span of spans) inlineCode.push({ line: idx + 1, column: span.start + 1, text: span.text });
146
+ if (isDefinition[idx]) continue;
147
+ extractInline(masked, raw[idx], idx + 1, definitions, images, links);
148
+ }
149
+
150
+ // 區塊:連續的非空行合成一塊
151
+ const blocks = [];
152
+ let current = null;
153
+ for (let idx = 0; idx < raw.length; idx++) {
154
+ const kind = kinds[idx];
155
+ if (kind === 'fence' || kind === 'code') {
156
+ const block = codeBlocks.find((b) => b.startLine === idx + 1);
157
+ if (block) {
158
+ current = null;
159
+ blocks.push({ type: 'code', startLine: block.startLine, endLine: block.endLine, code: block });
160
+ }
161
+ continue;
162
+ }
163
+ if (kind !== 'text' || isDefinition[idx]) {
164
+ current = null;
165
+ continue;
166
+ }
167
+ if (headingAt.has(idx)) {
168
+ current = null;
169
+ const heading = headingAt.get(idx);
170
+ if (heading.line === idx + 1) blocks.push({ type: 'heading', startLine: idx + 1, endLine: heading.style === 'setext' ? idx + 2 : idx + 1, heading });
171
+ continue;
172
+ }
173
+ if (!current) {
174
+ current = { type: blockType(raw, idx), startLine: idx + 1, endLine: idx + 1 };
175
+ blocks.push(current);
176
+ } else {
177
+ current.endLine = idx + 1;
178
+ }
179
+ }
180
+
181
+ return { source: text, lines, kinds, headings, codeBlocks, blocks, images, links, inlineCode, definitions };
182
+ }
183
+
184
+ function isParagraphLine(line) {
185
+ return !LIST_ITEM.test(line) && !BLOCKQUOTE.test(line) && !HTML_LINE.test(line) && !line.includes('|') && !THEMATIC_BREAK.test(line) && !ATX_HEADING.test(line);
186
+ }
187
+
188
+ function blockType(raw, idx) {
189
+ const line = raw[idx];
190
+ if (BLOCKQUOTE.test(line)) return 'blockquote';
191
+ if (THEMATIC_BREAK.test(line)) return 'thematic';
192
+ if (LIST_ITEM.test(line)) return 'list';
193
+ if (line.includes('|') && raw[idx + 1] !== undefined && TABLE_SEPARATOR.test(raw[idx + 1]) && raw[idx + 1].includes('-')) return 'table';
194
+ if (WRAPPER_TAG_ONLY.test(line)) return 'wrapper';
195
+ if (HTML_LINE.test(line)) return 'html';
196
+ return 'paragraph';
197
+ }
198
+
199
+ /**
200
+ * 把行內程式碼與行內 HTML 註解換成等長的空白,位置不變。
201
+ * @param {string} line
202
+ */
203
+ export function maskInline(line) {
204
+ const chars = line.split('');
205
+ const spans = [];
206
+ let pos = 0;
207
+ while (pos < line.length) {
208
+ if (line[pos] === '\\' && line[pos + 1] === '`') {
209
+ pos += 2;
210
+ continue;
211
+ }
212
+ if (line[pos] !== '`') {
213
+ pos++;
214
+ continue;
215
+ }
216
+ let runEnd = pos;
217
+ while (line[runEnd] === '`') runEnd++;
218
+ const run = line.slice(pos, runEnd);
219
+ let search = runEnd;
220
+ let close = -1;
221
+ while (search < line.length) {
222
+ const found = line.indexOf(run, search);
223
+ if (found === -1) break;
224
+ let after = found + run.length;
225
+ if (line[found - 1] !== '`' && line[after] !== '`') {
226
+ close = found;
227
+ break;
228
+ }
229
+ while (line[after] === '`') after++;
230
+ search = after;
231
+ }
232
+ if (close === -1) {
233
+ pos = runEnd;
234
+ continue;
235
+ }
236
+ spans.push({ start: pos, end: close + run.length, text: line.slice(runEnd, close).trim() });
237
+ for (let k = pos; k < close + run.length; k++) chars[k] = ' ';
238
+ pos = close + run.length;
239
+ }
240
+ let masked = chars.join('');
241
+ masked = masked.replace(/<!--.*?-->/g, (m) => ' '.repeat(m.length));
242
+ return { masked, spans };
243
+ }
244
+
245
+ /**
246
+ * 從遮好的文字找出圖片與連結。位置以原始行為準(遮罩不改變長度)。
247
+ */
248
+ function extractInline(masked, original, lineNo, definitions, images, links) {
249
+ // HTML 的 <img>
250
+ for (const m of masked.matchAll(/<img\b([^>]*)>/gi)) {
251
+ const attrs = parseAttributes(m[1]);
252
+ images.push({
253
+ kind: 'html',
254
+ alt: attrs.alt ?? null,
255
+ altMissing: attrs.alt === undefined,
256
+ src: attrs.src ?? '',
257
+ line: lineNo,
258
+ column: m.index + 1,
259
+ });
260
+ }
261
+ // HTML 的 <a href>
262
+ for (const m of masked.matchAll(/<a\b([^>]*)>(.*?)<\/a>/gi)) {
263
+ const attrs = parseAttributes(m[1]);
264
+ if (attrs.href !== undefined) {
265
+ links.push({ kind: 'html', text: plainText(m[2]), href: attrs.href, line: lineNo, column: m.index + 1 });
266
+ }
267
+ }
268
+ // 自動連結 <https://...>
269
+ for (const m of masked.matchAll(/<((?:https?|mailto):[^>\s]+)>/gi)) {
270
+ links.push({ kind: 'autolink', text: m[1], href: m[1], line: lineNo, column: m.index + 1 });
271
+ }
272
+ // Markdown 的圖片與連結(可能巢狀:[![徽章](圖)](連結))
273
+ scanBrackets(masked, 0, masked.length, lineNo, definitions, images, links);
274
+ }
275
+
276
+ function scanBrackets(text, from, to, lineNo, definitions, images, links) {
277
+ let pos = from;
278
+ while (pos < to) {
279
+ const ch = text[pos];
280
+ if (ch === '\\') {
281
+ pos += 2;
282
+ continue;
283
+ }
284
+ const isImage = ch === '!' && text[pos + 1] === '[';
285
+ if (ch !== '[' && !isImage) {
286
+ pos++;
287
+ continue;
288
+ }
289
+ const open = isImage ? pos + 1 : pos;
290
+ const close = findClosingBracket(text, open, to);
291
+ if (close === -1) {
292
+ pos = open + 1;
293
+ continue;
294
+ }
295
+ const label = text.slice(open + 1, close);
296
+ let target = null;
297
+ let end = close + 1;
298
+ if (text[close + 1] === '(') {
299
+ const parsed = parseDestination(text, close + 1, to);
300
+ if (parsed) {
301
+ target = parsed.href;
302
+ end = parsed.end;
303
+ }
304
+ } else if (text[close + 1] === '[') {
305
+ const refClose = text.indexOf(']', close + 2);
306
+ if (refClose !== -1) {
307
+ const ref = text.slice(close + 2, refClose) || label;
308
+ const href = definitions.get(normalizeLabel(ref));
309
+ if (href !== undefined) {
310
+ target = href;
311
+ end = refClose + 1;
312
+ }
313
+ }
314
+ } else {
315
+ const href = definitions.get(normalizeLabel(label));
316
+ if (href !== undefined) target = href;
317
+ }
318
+ if (target === null) {
319
+ pos = open + 1;
320
+ continue;
321
+ }
322
+ if (isImage) {
323
+ images.push({ kind: 'markdown', alt: label.trim(), altMissing: label.trim() === '', src: target, line: lineNo, column: pos + 1 });
324
+ } else {
325
+ links.push({ kind: 'markdown', text: plainText(label), rawText: label, href: target, line: lineNo, column: pos + 1 });
326
+ // 連結文字裡面可能還有圖片(徽章)
327
+ scanBrackets(text, open + 1, close, lineNo, definitions, images, links);
328
+ }
329
+ pos = end;
330
+ }
331
+ }
332
+
333
+ function findClosingBracket(text, open, to) {
334
+ let depth = 0;
335
+ for (let k = open; k < to; k++) {
336
+ if (text[k] === '\\') {
337
+ k++;
338
+ continue;
339
+ }
340
+ if (text[k] === '[') depth++;
341
+ else if (text[k] === ']') {
342
+ depth--;
343
+ if (depth === 0) return k;
344
+ }
345
+ }
346
+ return -1;
347
+ }
348
+
349
+ function parseDestination(text, parenPos, to) {
350
+ let k = parenPos + 1;
351
+ while (text[k] === ' ') k++;
352
+ let href = '';
353
+ if (text[k] === '<') {
354
+ const close = text.indexOf('>', k);
355
+ if (close === -1) return null;
356
+ href = text.slice(k + 1, close);
357
+ k = close + 1;
358
+ } else {
359
+ let depth = 0;
360
+ const start = k;
361
+ while (k < to) {
362
+ const c = text[k];
363
+ if (c === '\\') {
364
+ k += 2;
365
+ continue;
366
+ }
367
+ if (c === '(') depth++;
368
+ else if (c === ')') {
369
+ if (depth === 0) break;
370
+ depth--;
371
+ } else if (c === ' ') break;
372
+ k++;
373
+ }
374
+ href = text.slice(start, k);
375
+ }
376
+ // 選填的標題 "..."
377
+ while (text[k] === ' ') k++;
378
+ if (text[k] === '"' || text[k] === "'") {
379
+ const quote = text[k];
380
+ const close = text.indexOf(quote, k + 1);
381
+ if (close === -1) return null;
382
+ k = close + 1;
383
+ while (text[k] === ' ') k++;
384
+ }
385
+ if (text[k] !== ')') return null;
386
+ return { href, end: k + 1 };
387
+ }
388
+
389
+ function parseAttributes(source) {
390
+ const attrs = {};
391
+ for (const m of source.matchAll(/([a-zA-Z-:]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'>]+)))?/g)) {
392
+ attrs[m[1].toLowerCase()] = m[2] ?? m[3] ?? m[4] ?? '';
393
+ }
394
+ return attrs;
395
+ }
396
+
397
+ function normalizeLabel(label) {
398
+ return label.trim().replace(/\s+/g, ' ').toLowerCase();
399
+ }
400
+
401
+ /**
402
+ * 去掉 Markdown 與 HTML 標記,只留下看得到的文字。
403
+ * @param {string} source
404
+ */
405
+ export function plainText(source) {
406
+ return source
407
+ .replace(/<!--.*?-->/g, '')
408
+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '')
409
+ .replace(/<img\b[^>]*>/gi, '')
410
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
411
+ .replace(/\[([^\]]*)\]\[[^\]]*\]/g, '$1')
412
+ .replace(/<[^>]+>/g, '')
413
+ .replace(/`+([^`]*)`+/g, '$1')
414
+ .replace(/(\*\*|__)(.*?)\1/g, '$2')
415
+ .replace(/(^|[^\w*])[*_]([^*_]+)[*_](?=[^\w*]|$)/g, '$1$2')
416
+ .replace(/\\([\\`*_{}[\]()#+\-.!|>])/g, '$1')
417
+ .replace(/\s+/g, ' ')
418
+ .trim();
419
+ }
420
+
421
+ /** 是否是會被貼到終端機執行的程式碼區塊 */
422
+ export function isShellLanguage(lang) {
423
+ return ['bash', 'sh', 'shell', 'zsh', 'console', 'shellsession', 'fish', 'powershell', 'ps1', 'pwsh', 'cmd', 'bat', 'batch', 'terminal'].includes(lang);
424
+ }
package/src/project.js ADDED
@@ -0,0 +1,86 @@
1
+ // 專案資料夾的存取。檢查工具只透過這裡讀專案檔案,測試時可以換成記憶體裡的假專案。
2
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
3
+ import path from 'node:path';
4
+
5
+ /**
6
+ * 真實的專案資料夾。
7
+ * @param {string} dir 專案資料夾的絕對路徑
8
+ */
9
+ export function fsProject(dir) {
10
+ const abs = (rel) => path.resolve(dir, rel);
11
+ return {
12
+ dir,
13
+ name: path.basename(dir),
14
+ exists: (rel) => existsSync(abs(rel)),
15
+ isDir: (rel) => existsSync(abs(rel)) && statSync(abs(rel)).isDirectory(),
16
+ readText: (rel) => {
17
+ try {
18
+ return readFileSync(abs(rel), 'utf8');
19
+ } catch {
20
+ return null;
21
+ }
22
+ },
23
+ list: (rel = '.') => {
24
+ try {
25
+ return readdirSync(abs(rel));
26
+ } catch {
27
+ return [];
28
+ }
29
+ },
30
+ };
31
+ }
32
+
33
+ /**
34
+ * 記憶體裡的假專案(測試用)。
35
+ * @param {Record<string,string>} files 路徑對內容,路徑用 / 分隔
36
+ * @param {string} [name] 專案資料夾名稱
37
+ */
38
+ export function memoryProject(files, name = 'demo-project') {
39
+ const norm = (rel) => path.posix.normalize(rel.replace(/\\/g, '/')).replace(/^\.\//, '').replace(/\/$/, '');
40
+ const fileMap = new Map(Object.entries(files).map(([k, v]) => [norm(k), v]));
41
+ const dirs = new Set(['.']);
42
+ for (const key of fileMap.keys()) {
43
+ const parts = key.split('/');
44
+ for (let i = 1; i < parts.length; i++) dirs.add(parts.slice(0, i).join('/'));
45
+ }
46
+ return {
47
+ dir: `/memory/${name}`,
48
+ name,
49
+ exists: (rel) => fileMap.has(norm(rel)) || dirs.has(norm(rel)),
50
+ isDir: (rel) => dirs.has(norm(rel)),
51
+ readText: (rel) => fileMap.get(norm(rel)) ?? null,
52
+ list: (rel = '.') => {
53
+ const base = norm(rel);
54
+ const prefix = base === '.' ? '' : `${base}/`;
55
+ const names = new Set();
56
+ for (const key of [...fileMap.keys(), ...dirs]) {
57
+ if (key === '.' || !key.startsWith(prefix)) continue;
58
+ const rest = key.slice(prefix.length);
59
+ if (rest) names.add(rest.split('/')[0]);
60
+ }
61
+ return [...names];
62
+ },
63
+ };
64
+ }
65
+
66
+ const IGNORED_ENTRIES = new Set(['.DS_Store', 'Thumbs.db', '.git']);
67
+
68
+ /**
69
+ * 專案資料夾裡除了 README(與其他 .md 文件)之外,還有沒有別的檔案。
70
+ * 只有 README 時,要對照專案檔案的規則會被跳過。
71
+ * @param {ReturnType<typeof fsProject>} project
72
+ */
73
+ export function hasProjectFiles(project) {
74
+ return project.list('.').some((entry) => !IGNORED_ENTRIES.has(entry) && !/\.md$/i.test(entry));
75
+ }
76
+
77
+ /** 讀 package.json,讀不到或格式錯誤時回傳 null */
78
+ export function readPackageJson(project, dir = '.') {
79
+ const text = project.readText(dir === '.' ? 'package.json' : `${dir}/package.json`);
80
+ if (text === null) return null;
81
+ try {
82
+ return JSON.parse(text);
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
@@ -0,0 +1,167 @@
1
+ // 把 README 的標題對到 rules/headings.json 定義的章節,再對到八塊。
2
+ import { data } from './data.js';
3
+
4
+ const EMOJI = /[\p{Extended_Pictographic}\u{FE0F}\u{200D}\u{20E3}]/gu;
5
+
6
+ /**
7
+ * 標題文字正規化:小寫、去掉表情符號、編號、結尾冒號與括號補充。
8
+ * @param {string} text
9
+ */
10
+ export function normalizeHeading(text) {
11
+ return text
12
+ .replace(EMOJI, '')
13
+ .replace(/\u3000/g, ' ')
14
+ .trim()
15
+ .replace(/^(?:\d+(?:\.\d+)*[.)、]?|[一二三四五六七八九十]+、)\s*/, '')
16
+ .replace(/\s*[((][^))]*[))]\s*$/, '')
17
+ .replace(/\s*[::]\s*$/, '')
18
+ .replace(/\s+/g, ' ')
19
+ .trim()
20
+ .toLowerCase();
21
+ }
22
+
23
+ /** 每個正規化後的別名對到哪些章節 */
24
+ function buildAliasIndex() {
25
+ const index = new Map();
26
+ const add = (alias, ids) => {
27
+ const key = normalizeHeading(alias);
28
+ if (!index.has(key)) index.set(key, new Set());
29
+ for (const id of ids) index.get(key).add(id);
30
+ };
31
+ for (const section of data.headings.sections) {
32
+ for (const lang of Object.keys(section.title)) add(section.title[lang], [section.id]);
33
+ for (const lang of Object.keys(section.aliases)) for (const alias of section.aliases[lang]) add(alias, [section.id]);
34
+ }
35
+ for (const combo of data.headings.combined) {
36
+ for (const lang of Object.keys(combo.aliases)) for (const alias of combo.aliases[lang]) add(alias, combo.sections);
37
+ }
38
+ return index;
39
+ }
40
+
41
+ let aliasIndex = null;
42
+
43
+ /**
44
+ * 找出一個標題對到哪些章節。
45
+ * @param {string} text 標題的純文字
46
+ * @param {number} level 標題層級
47
+ * @returns {string[]} 章節代號
48
+ */
49
+ export function matchHeading(text, level) {
50
+ aliasIndex ??= buildAliasIndex();
51
+ const whole = normalizeHeading(text);
52
+ const candidates = [whole];
53
+ // 雙語標題:「功能 / Features」「安裝與執行|Getting Started」
54
+ const parts = text.split(/\s*[//||]\s*|\s+[-–—]\s+/).map(normalizeHeading).filter(Boolean);
55
+ if (parts.length > 1) candidates.push(...parts);
56
+ let found = null;
57
+ for (const candidate of candidates) {
58
+ const hit = aliasIndex.get(candidate);
59
+ if (hit) {
60
+ found = [...hit];
61
+ break;
62
+ }
63
+ }
64
+ if (!found) return [];
65
+ if (found.length > 1) {
66
+ // 同一個名稱對到不同層級的章節時(例如 Installation),以層級相同的優先
67
+ const sameLevel = found.filter((id) => sectionDef(id).level === level);
68
+ const isCombined = data.headings.combined.some((c) => c.sections.length === found.length && c.sections.every((s) => found.includes(s)));
69
+ if (!isCombined && sameLevel.length > 0) return sameLevel.slice(0, 1);
70
+ if (!isCombined) return found.slice(0, 1);
71
+ }
72
+ return found;
73
+ }
74
+
75
+ /** 依代號取得章節定義 */
76
+ export function sectionDef(id) {
77
+ return data.headings.sections.find((s) => s.id === id);
78
+ }
79
+
80
+ /**
81
+ * 依代號取得塊的資訊(含編號)。編號由 rules/blocks.json 的排列順序決定。
82
+ * @param {string} slug
83
+ */
84
+ export function blockInfo(slug) {
85
+ const index = data.blocks.blocks.findIndex((b) => b.slug === slug);
86
+ if (index === -1) return null;
87
+ const block = data.blocks.blocks[index];
88
+ return { slug, index, number: String(index + 1).padStart(2, '0'), name: block.name };
89
+ }
90
+
91
+ /**
92
+ * 依標題切出章節,並對到八塊。
93
+ * @param {ReturnType<import('./markdown.js').parseMarkdown>} md
94
+ */
95
+ export function buildSections(md) {
96
+ const total = md.lines.length;
97
+ return md.headings.map((heading, i) => {
98
+ let endLine = total + 1;
99
+ for (let k = i + 1; k < md.headings.length; k++) {
100
+ if (md.headings[k].level <= heading.level) {
101
+ endLine = md.headings[k].line;
102
+ break;
103
+ }
104
+ }
105
+ const ids = heading.level >= 2 ? matchHeading(heading.text, heading.level) : [];
106
+ const block = ids.length ? sectionDef(ids[0]).block : null;
107
+ return { ...heading, endLine, ids, block };
108
+ });
109
+ }
110
+
111
+ /**
112
+ * 找某個章節(第一個符合的標題,層級 2 的優先)。
113
+ * @param {ReturnType<typeof buildSections>} sections
114
+ * @param {string} id
115
+ */
116
+ export function findSection(sections, id) {
117
+ const all = sections.filter((s) => s.ids.includes(id));
118
+ return all.find((s) => s.level === 2) ?? all[0] ?? null;
119
+ }
120
+
121
+ /**
122
+ * 某一行屬於哪一塊:往上找最近一個對得到章節的二級標題;在第一個二級標題之前算第 1 塊。
123
+ * @param {ReturnType<typeof buildSections>} sections
124
+ * @param {number} line
125
+ */
126
+ export function blockOfLine(sections, line) {
127
+ let result = null;
128
+ let sawH2 = false;
129
+ for (const section of sections) {
130
+ if (section.line > line) break;
131
+ if (section.level === 2) {
132
+ sawH2 = true;
133
+ result = section.block;
134
+ } else if (section.level > 2 && sawH2 && result === null && section.block) {
135
+ // 二級標題對不到章節,但底下的三級標題對得到
136
+ result = section.block;
137
+ }
138
+ }
139
+ if (!sawH2) return data.blocks.blocks[0].slug;
140
+ return result;
141
+ }
142
+
143
+ /**
144
+ * 章節範圍內的行(不含標題本身)。
145
+ * @param {ReturnType<import('./markdown.js').parseMarkdown>} md
146
+ * @param {{line:number,endLine:number}} section
147
+ */
148
+ export function sectionLines(md, section) {
149
+ return md.lines.filter((l) => l.line > section.line && l.line < section.endLine);
150
+ }
151
+
152
+ /**
153
+ * 章節範圍內的程式碼區塊。
154
+ */
155
+ export function sectionCodeBlocks(md, section) {
156
+ return md.codeBlocks.filter((b) => b.startLine > section.line && b.startLine < section.endLine);
157
+ }
158
+
159
+ /**
160
+ * 章節範圍內所有文字(含程式碼),用來找關鍵字。
161
+ */
162
+ export function sectionText(md, section) {
163
+ return sectionLines(md, section)
164
+ .filter((l) => l.kind !== 'comment' && l.kind !== 'frontmatter')
165
+ .map((l) => l.raw)
166
+ .join('\n');
167
+ }