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,137 @@
1
+ // 授權類規則:README、LICENSE 檔、package.json 三處的授權是否一致。
2
+ import { findSection, sectionText } from '../sections.js';
3
+
4
+ const PROPRIETARY = 'PROPRIETARY';
5
+
6
+ // README 文字裡的授權名稱(順序重要:先比對較長、較特定的名稱)
7
+ const README_PATTERNS = [
8
+ ['AGPL-3.0', /\bAGPL(?:[- ]?v?3(?:\.0)?)?\b|GNU Affero/i],
9
+ ['LGPL-3.0', /\bLGPL[- ]?v?3(?:\.0)?\b/i],
10
+ ['LGPL-2.1', /\bLGPL[- ]?v?2\.1\b/i],
11
+ ['GPL-3.0', /(?<![AL])\bGPL[- ]?v?3(?:\.0)?\b|GNU General Public License v(?:ersion )?3/i],
12
+ ['GPL-2.0', /(?<![AL])\bGPL[- ]?v?2(?:\.0)?\b|GNU General Public License v(?:ersion )?2/i],
13
+ ['Apache-2.0', /\bApache(?:[- ]License)?[- ,]*(?:v(?:ersion)?\s*)?2(?:\.0)?\b/i],
14
+ ['MPL-2.0', /\bMPL[- ]?2(?:\.0)?\b|Mozilla Public License/i],
15
+ ['BSD-3-Clause', /\bBSD[- ]3(?:[- ]Clause)?\b/i],
16
+ ['BSD-2-Clause', /\bBSD[- ]2(?:[- ]Clause)?\b/i],
17
+ ['CC-BY-NC-SA-4.0', /\bCC[- ]BY[- ]NC[- ]SA(?:[- ]4\.0)?\b/i],
18
+ ['CC-BY-NC-4.0', /\bCC[- ]BY[- ]NC(?![- ]SA)(?:[- ]4\.0)?\b/i],
19
+ ['CC-BY-SA-4.0', /\bCC[- ]BY[- ]SA(?:[- ]4\.0)?\b/i],
20
+ ['CC-BY-4.0', /\bCC[- ]BY(?![- ](?:NC|SA))(?:[- ]4\.0)?\b/i],
21
+ ['CC0-1.0', /\bCC0\b/i],
22
+ ['Unlicense', /\bUnlicense\b/],
23
+ ['ISC', /\bISC\b/],
24
+ ['MIT', /\bMIT\b/],
25
+ ];
26
+ const PROPRIETARY_PATTERN = /保留所有權利|版權所有|不開放|未授權|all rights reserved|proprietary|\bUNLICENSED\b/i;
27
+
28
+ /** 從 README 的授權章節找出授權名稱 */
29
+ export function licensesInText(text) {
30
+ const found = new Set();
31
+ let rest = text;
32
+ for (const [id, pattern] of README_PATTERNS) {
33
+ if (pattern.test(rest)) {
34
+ found.add(id);
35
+ rest = rest.replace(new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : `${pattern.flags}g`), ' ');
36
+ }
37
+ }
38
+ if (!found.size && PROPRIETARY_PATTERN.test(text)) found.add(PROPRIETARY);
39
+ return found;
40
+ }
41
+
42
+ /** 從 LICENSE 檔的全文判斷授權 */
43
+ export function licenseOfFile(text) {
44
+ const head = text.slice(0, 3000);
45
+ if (/GNU AFFERO GENERAL PUBLIC LICENSE/i.test(head)) return 'AGPL-3.0';
46
+ if (/GNU LESSER GENERAL PUBLIC LICENSE[\s\S]{0,60}Version 2\.1/i.test(head)) return 'LGPL-2.1';
47
+ if (/GNU LESSER GENERAL PUBLIC LICENSE/i.test(head)) return 'LGPL-3.0';
48
+ if (/GNU GENERAL PUBLIC LICENSE[\s\S]{0,60}Version 2/i.test(head)) return 'GPL-2.0';
49
+ if (/GNU GENERAL PUBLIC LICENSE/i.test(head)) return 'GPL-3.0';
50
+ if (/Apache License[\s\S]{0,60}Version 2\.0/i.test(head)) return 'Apache-2.0';
51
+ if (/Mozilla Public License,?\s*(?:Version|v\.?)\s*2\.0/i.test(head)) return 'MPL-2.0';
52
+ if (/MIT License|Permission is hereby granted, free of charge/i.test(head)) return 'MIT';
53
+ if (/ISC License|Permission to use, copy, modify, and\/or distribute this software for any purpose/i.test(head)) return 'ISC';
54
+ if (/This is free and unencumbered software released into the public domain/i.test(head)) return 'Unlicense';
55
+ if (/CC0 1\.0|Creative Commons Zero/i.test(head)) return 'CC0-1.0';
56
+ if (/Redistribution and use in source and binary forms/i.test(head)) return /Neither the name/i.test(text) ? 'BSD-3-Clause' : 'BSD-2-Clause';
57
+ if (/Attribution-NonCommercial-ShareAlike 4\.0/i.test(head)) return 'CC-BY-NC-SA-4.0';
58
+ if (/Attribution-NonCommercial 4\.0/i.test(head)) return 'CC-BY-NC-4.0';
59
+ if (/Attribution-ShareAlike 4\.0/i.test(head)) return 'CC-BY-SA-4.0';
60
+ if (/Attribution 4\.0 International/i.test(head)) return 'CC-BY-4.0';
61
+ if (PROPRIETARY_PATTERN.test(head) && !/permission is hereby granted/i.test(head)) return PROPRIETARY;
62
+ return null;
63
+ }
64
+
65
+ /** package.json 的 license 欄位 */
66
+ export function licensesOfPackage(pkg) {
67
+ const value = typeof pkg?.license === 'string' ? pkg.license : pkg?.license?.type;
68
+ if (typeof value !== 'string' || /^SEE LICEN[CS]E IN/i.test(value)) return new Set();
69
+ if (/^UNLICENSED$/i.test(value)) return new Set([PROPRIETARY]);
70
+ return new Set(
71
+ value
72
+ .replace(/[()]/g, ' ')
73
+ .split(/\s+(?:OR|AND|WITH)\s+/i)
74
+ .map((s) => s.trim().replace(/-only$|-or-later$|\+$/i, ''))
75
+ .filter(Boolean),
76
+ );
77
+ }
78
+
79
+ /** 專案根目錄的授權檔 */
80
+ export function licenseFiles(project) {
81
+ return project.list('.').filter((name) => /^(?:LICEN[CS]E|COPYING)(?:[-.][\w.-]+)?$/i.test(name) && !project.isDir(name));
82
+ }
83
+
84
+ const same = (a, b) => a.toLowerCase() === b.toLowerCase();
85
+ const overlaps = (a, b) => [...a].some((x) => [...b].some((y) => same(x, y)));
86
+ const show = (set) => (set.size ? [...set].map((x) => (x === PROPRIETARY ? '保留所有權利' : x)).join(' / ') : '—');
87
+ const showEn = (set) => (set.size ? [...set].map((x) => (x === PROPRIETARY ? 'all rights reserved' : x)).join(' / ') : '—');
88
+
89
+ export const checks = {
90
+ LIC001(ctx) {
91
+ if (findSection(ctx.sections, 'license')) return [];
92
+ const files = licenseFiles(ctx.project);
93
+ if (files.length) {
94
+ const id = licenseOfFile(ctx.project.readText(files[0]) ?? '');
95
+ // 授權檔寫的是「保留所有權利」,視為不公開的專案
96
+ if (id === PROPRIETARY) return [];
97
+ const license = id ?? { 'zh-TW': '看不出是哪一種授權', en: 'license not recognized' };
98
+ return [{ messageKey: 'file', params: { file: files[0], license }, line: null, column: null }];
99
+ }
100
+ const fromPkg = [...licensesOfPackage(ctx.pkg)].filter((x) => x !== PROPRIETARY);
101
+ // npm init 預設會填 ISC,只有這個值又沒有授權檔時,不當成刻意選的授權
102
+ if (!fromPkg.length || (fromPkg.length === 1 && same(fromPkg[0], 'ISC'))) return [];
103
+ return [{ messageKey: 'package', params: { license: fromPkg.join(' / ') }, line: null, column: null }];
104
+ },
105
+
106
+ LIC002(ctx) {
107
+ const section = findSection(ctx.sections, 'license');
108
+ if (!section) return [];
109
+ const readme = licensesInText(sectionText(ctx.md, section));
110
+ const files = licenseFiles(ctx.project);
111
+ const fromFile = new Set(files.map((f) => licenseOfFile(ctx.project.readText(f) ?? '')).filter(Boolean));
112
+ const fromPkg = licensesOfPackage(ctx.pkg);
113
+ const sources = [
114
+ ['README', readme],
115
+ [files[0] ?? 'LICENSE', fromFile],
116
+ ['package.json', fromPkg],
117
+ ].filter(([, set]) => set.size > 0);
118
+ let conflict = false;
119
+ for (let i = 0; i < sources.length; i++) {
120
+ for (let k = i + 1; k < sources.length; k++) if (!overlaps(sources[i][1], sources[k][1])) conflict = true;
121
+ }
122
+ if (!conflict) return [];
123
+ const details = {
124
+ 'zh-TW': `README 寫 ${show(readme)},${files[0] ?? 'LICENSE'} 檔是 ${show(fromFile)},package.json 是 ${show(fromPkg)}`,
125
+ en: `README says ${showEn(readme)}, ${files[0] ?? 'LICENSE'} is ${showEn(fromFile)}, package.json is ${showEn(fromPkg)}`,
126
+ };
127
+ return [{ messageKey: 'mismatch', params: { details }, line: section.line, column: 1 }];
128
+ },
129
+
130
+ LIC003(ctx) {
131
+ const section = findSection(ctx.sections, 'license');
132
+ if (!section) return [];
133
+ const readme = licensesInText(sectionText(ctx.md, section));
134
+ if (!readme.size || readme.has(PROPRIETARY) || licenseFiles(ctx.project).length) return [];
135
+ return [{ messageKey: 'missing', params: { license: [...readme].join(' / ') }, line: section.line, column: 1 }];
136
+ },
137
+ };
@@ -0,0 +1,110 @@
1
+ // 圖片與連結類規則。
2
+ import path from 'node:path';
3
+ import { hasPlaceholder } from '../data.js';
4
+ import { introRange, hostOf, isBadge, isExternal } from './util.js';
5
+
6
+ const PLACEHOLDER_HOSTS = ['fakeimg.pl', 'placehold.co', 'placehold.it', 'via.placeholder.com', 'placeholder.com', 'dummyimage.com', 'picsum.photos', 'placekitten.com', 'loremflickr.com', 'placeimg.com'];
7
+ const GENERIC_ALT = /^(?:圖片?|截圖|畫面|照片|示意圖|範例圖片?|image|img|picture|pic|photo|screenshot|screen ?shot|preview|預覽)\s*\d*$/i;
8
+ const ALT_BAD_START = /^(?:圖片|截圖|image|picture|photo)\s*[::]|^(?:an? )?(?:image|picture|photo|screenshot) of\b/i;
9
+ const FILE_NAME = /\.(?:png|jpe?g|gif|webp|svg|avif|bmp)$/i;
10
+ const VAGUE_LINK_TEXT = new Set(['這裡', '點這裡', '點此', '點我', '按這裡', '按此', '請點我', '請點這裡', '連結', '網址', '線上觀看連結', '觀看連結', '傳送門', 'here', 'click here', 'click', 'link', 'this link', 'this', 'read more', 'more', 'details']);
11
+ const POPULARITY = /(?:img\.shields\.io|badgen\.net)\/github\/(stars|forks|watchers|followers|issues-pr(?:-raw|-closed)?|issues(?:-raw|-closed)?|downloads|contributors)/i;
12
+
13
+ /** 把 README 裡的相對路徑換成專案根目錄底下的路徑 */
14
+ function resolveInProject(ctx, href) {
15
+ let target = href.split('#')[0].split('?')[0];
16
+ if (!target) return null;
17
+ try {
18
+ target = decodeURIComponent(target);
19
+ } catch {
20
+ // 保留原字串
21
+ }
22
+ const resolved = target.startsWith('/') ? target.slice(1) : path.posix.join(ctx.readmeDir, target);
23
+ return path.posix.normalize(resolved);
24
+ }
25
+
26
+ export const checks = {
27
+ IMG001(ctx) {
28
+ return ctx.md.images.filter((img) => img.altMissing).map((img) => ({ messageKey: 'missing', line: img.line, column: img.column }));
29
+ },
30
+
31
+ IMG002(ctx) {
32
+ const out = [];
33
+ for (const img of ctx.md.images) {
34
+ if (img.altMissing || !img.alt || isBadge(img.src) || hasPlaceholder(img.alt)) continue;
35
+ const alt = img.alt.trim();
36
+ if (GENERIC_ALT.test(alt) || ALT_BAD_START.test(alt) || FILE_NAME.test(alt)) {
37
+ out.push({ messageKey: 'generic', params: { alt }, line: img.line, column: img.column });
38
+ }
39
+ }
40
+ return out;
41
+ },
42
+
43
+ IMG003(ctx) {
44
+ const out = [];
45
+ for (const img of ctx.md.images) {
46
+ if (!img.src || isExternal(img.src) || img.src.startsWith('#') || hasPlaceholder(img.src)) continue;
47
+ const target = resolveInProject(ctx, img.src);
48
+ if (target && !ctx.project.exists(target)) out.push({ messageKey: 'missing', params: { path: img.src }, line: img.line, column: img.column });
49
+ }
50
+ return out;
51
+ },
52
+
53
+ IMG004(ctx) {
54
+ const out = [];
55
+ for (const img of ctx.md.images) {
56
+ const host = hostOf(img.src);
57
+ if (host && PLACEHOLDER_HOSTS.some((h) => host === h || host.endsWith(`.${h}`))) {
58
+ out.push({ messageKey: 'found', params: { host }, line: img.line, column: img.column });
59
+ }
60
+ }
61
+ return out;
62
+ },
63
+
64
+ IMG005(ctx) {
65
+ if (ctx.md.images.some((img) => !isBadge(img.src))) return [];
66
+ const demoSections = ctx.sections.filter((s) => s.level === 2 && s.block === 'demo');
67
+ const { start, end } = introRange(ctx.md);
68
+ const inDemo = (line) => (line > start && line < end) || demoSections.some((s) => line > s.line && line < s.endLine);
69
+ const hasLiveLink = ctx.md.links.some((l) => /^https?:\/\//i.test(l.href) && inDemo(l.line) && !isBadge(l.href));
70
+ if (hasLiveLink) return [];
71
+ return [{ messageKey: 'missing', line: null, column: null }];
72
+ },
73
+
74
+ IMG007(ctx) {
75
+ const byLine = new Map();
76
+ for (const img of ctx.md.images) {
77
+ const m = img.src.match(POPULARITY);
78
+ if (!m) continue;
79
+ if (!byLine.has(img.line)) byLine.set(img.line, { column: img.column, kinds: [] });
80
+ const kind = m[1].replace(/-(raw|closed)$/, '');
81
+ if (!byLine.get(img.line).kinds.includes(kind)) byLine.get(img.line).kinds.push(kind);
82
+ }
83
+ return [...byLine.entries()].map(([line, info]) => ({
84
+ messageKey: 'found',
85
+ params: { kinds: { 'zh-TW': info.kinds.join('、'), en: info.kinds.join(', ') } },
86
+ line,
87
+ column: info.column,
88
+ }));
89
+ },
90
+
91
+ LNK001(ctx) {
92
+ const out = [];
93
+ for (const link of ctx.md.links) {
94
+ const href = link.href.trim();
95
+ if (!href || href.startsWith('#') || isExternal(href) || hasPlaceholder(href)) continue;
96
+ const target = resolveInProject(ctx, href);
97
+ if (target && !ctx.project.exists(target)) out.push({ messageKey: 'missing', params: { path: href }, line: link.line, column: link.column });
98
+ }
99
+ return out;
100
+ },
101
+
102
+ LNK004(ctx) {
103
+ const out = [];
104
+ for (const link of ctx.md.links) {
105
+ const text = link.text.trim().replace(/[。.!!::]+$/, '').toLowerCase();
106
+ if (text && VAGUE_LINK_TEXT.has(text)) out.push({ messageKey: 'vague', params: { text: link.text.trim() }, line: link.line, column: link.column });
107
+ }
108
+ return out;
109
+ },
110
+ };
@@ -0,0 +1,248 @@
1
+ // 結構與「還沒填完」類的規則。
2
+ import { data, hasPlaceholder, isSyntaxMention, placeholderPattern } from '../data.js';
3
+ import { plainText } from '../markdown.js';
4
+ import { blockInfo, findSection, sectionDef } from '../sections.js';
5
+ import { introRange, proseLines } from './util.js';
6
+
7
+ const WRAPPER_TAG_ONLY = /^\s*(?:<\/?(?:div|p|center|section|span|br|picture)\b[^>]*>\s*)+$/i;
8
+
9
+ /** 狀態行:「狀態:」「Status:」開頭(可以是清單項目或粗體) */
10
+ function statusLinePattern() {
11
+ const prefixes = [...data.conventions.status.prefixes['zh-TW'], ...data.conventions.status.prefixes.en];
12
+ return new RegExp(`^\\s*(?:[-*+]\\s+)?(?:\\*\\*|__)?(?:${prefixes.join('|')})(?:\\*\\*|__)?\\s*[::]`, 'i');
13
+ }
14
+
15
+ /** 一個區塊拿掉圖片、包圖片的連結、HTML 標籤與分隔符號後,還有沒有文字 */
16
+ function blockHasText(md, block) {
17
+ const text = md.lines
18
+ .filter((l) => l.line >= block.startLine && l.line <= block.endLine)
19
+ .map((l) => l.prose)
20
+ .join(' ')
21
+ .replace(/!\[[^\]]*\]\([^)]*\)/g, '')
22
+ .replace(/!\[[^\]]*\]\[[^\]]*\]/g, '')
23
+ .replace(/<img\b[^>]*>/gi, '')
24
+ .replace(/\[\s*\]\([^)]*\)/g, '')
25
+ .replace(/\[\s*\]\[[^\]]*\]/g, '')
26
+ .replace(/<[^>]+>/g, '')
27
+ .replace(/[||·•\s]/g, '');
28
+ return text.length > 0;
29
+ }
30
+
31
+ /** 計算一句話說明的長度:中文以字計(英文單字算一個),英文以字元計 */
32
+ function descriptionLength(text, lang) {
33
+ if (lang === 'en') return text.length;
34
+ const han = (text.match(/\p{Script=Han}/gu) ?? []).length;
35
+ const words = (text.match(/[A-Za-z0-9]+/g) ?? []).length;
36
+ const punct = (text.match(/[^\p{Script=Han}A-Za-z0-9\s]/gu) ?? []).length;
37
+ return han + words + punct;
38
+ }
39
+
40
+ /** 第 1 塊:一級標題之後、下一個標題之前的第一個有文字的區塊 */
41
+ function findDescription(md) {
42
+ const { h1, end } = introRange(md);
43
+ if (!h1) return { h1: null, block: null };
44
+ const nextHeading = md.headings.find((h) => h.line > h1.line);
45
+ const limit = nextHeading ? Math.min(nextHeading.line, end) : end;
46
+ const firstLine = h1.style === 'setext' ? h1.line + 1 : h1.line;
47
+ for (const block of md.blocks) {
48
+ if (block.startLine <= firstLine || block.startLine >= limit) continue;
49
+ if (block.type === 'wrapper' || block.type === 'heading') continue;
50
+ if ((block.type === 'paragraph' || block.type === 'html') && !blockHasText(md, block)) continue;
51
+ // 狀態行寫在說明前面時,跳過它繼續找
52
+ if (block.type === 'paragraph' && block.startLine === block.endLine && statusLinePattern().test(md.lines[block.startLine - 1].raw)) continue;
53
+ return { h1, block };
54
+ }
55
+ return { h1, block: null };
56
+ }
57
+
58
+ // 必填章節裡,另外有專門規則負責的(章節 → 規則代號)
59
+ const HANDLED_ELSEWHERE = { 'api-docs': 'TYPE-API001' };
60
+ // 「安裝與執行」底下的小節
61
+ const INSTALL_CHILDREN = new Set(['requirements', 'install-steps']);
62
+
63
+ function ruleApplies(id, type) {
64
+ const rule = data.rules.rules.find((r) => r.id === id);
65
+ return Boolean(rule && rule.status === 'implemented' && rule.types.includes(type));
66
+ }
67
+
68
+ /**
69
+ * 「安裝與執行」裡,「環境需求」「執行測試」以外的地方有沒有寫指令或步驟。
70
+ * 只有一個「安裝」標題直接寫步驟、把步驟拆成好幾個自訂小節(「取得專案」「安裝套件」)、或用表格連到各平台的安裝說明,都算有寫安裝步驟。
71
+ */
72
+ function installWrittenDirectly(ctx) {
73
+ const section = findSection(ctx.sections, 'getting-started');
74
+ if (!section) return false;
75
+ const excluded = ctx.sections.filter(
76
+ (s) => s.line > section.line && s.line < section.endLine && (s.ids.includes('requirements') || s.ids.includes('testing')),
77
+ );
78
+ const inRange = (n) => n > section.line && n < section.endLine && !excluded.some((s) => n > s.line && n < s.endLine);
79
+ // 指令區塊、清單步驟、表格、連到其他安裝說明的連結,都算有寫
80
+ return ctx.md.codeBlocks.some((b) => inRange(b.startLine))
81
+ || ctx.md.links.some((l) => inRange(l.line))
82
+ || ctx.md.lines.some((l) => inRange(l.line) && l.kind === 'text' && /^\s*(?:\d+[.)]|[-*+])\s+\S|^\s*\|/.test(l.raw));
83
+ }
84
+
85
+ export const checks = {
86
+ STR002(ctx) {
87
+ const { md } = ctx;
88
+ const out = [];
89
+ const first = md.lines.find((l) => l.kind === 'text' && !l.definition && !WRAPPER_TAG_ONLY.test(l.raw));
90
+ const h1s = md.headings.filter((h) => h.level === 1);
91
+ if (h1s.length === 0) {
92
+ out.push({ messageKey: 'missing', line: first?.line ?? 1, column: 1 });
93
+ } else if (!first || first.line !== h1s[0].line) {
94
+ out.push({ messageKey: 'notFirst', line: first?.line ?? 1, column: 1 });
95
+ }
96
+ h1s.slice(1).forEach((h, i) => out.push({ messageKey: 'extra', params: { count: i + 2 }, line: h.line, column: 1 }));
97
+ return out;
98
+ },
99
+
100
+ STR003(ctx) {
101
+ const { h1, block } = findDescription(ctx.md);
102
+ if (!h1) return [];
103
+ const missing = () => [{ messageKey: 'missing', line: h1.line, column: 1 }];
104
+ if (!block) return missing();
105
+ if (block.type === 'blockquote') return [];
106
+ if (block.type !== 'paragraph' && block.type !== 'html') return missing();
107
+ return [];
108
+ },
109
+
110
+ STR014(ctx) {
111
+ const { md } = ctx;
112
+ const { block } = findDescription(md);
113
+ if (!block) return [];
114
+ const raw = md.lines.filter((l) => l.line >= block.startLine && l.line <= block.endLine).map((l) => l.raw);
115
+ if (block.type === 'blockquote') return [{ messageKey: 'quote', line: block.startLine, column: 1 }];
116
+ if (block.type !== 'paragraph' && block.type !== 'html') return [];
117
+ if (statusLinePattern().test(raw[0])) return [];
118
+ // 一句話說明只看第一行(下一行可能就是狀態)
119
+ const text = plainText(raw[0]);
120
+ if (hasPlaceholder(text)) return [];
121
+ const max = data.conventions.oneLiner.maxLength[ctx.docLang];
122
+ const length = descriptionLength(text, ctx.docLang);
123
+ if (length > max) return [{ messageKey: 'tooLong', params: { length, max }, line: block.startLine, column: 1 }];
124
+ return [];
125
+ },
126
+
127
+ STR004(ctx) {
128
+ const { md } = ctx;
129
+ const { h1, start, end } = introRange(md);
130
+ const lines = md.lines.filter((l) => l.line > start && l.line < end && l.kind === 'text');
131
+ const pattern = statusLinePattern();
132
+ if (lines.some((l) => pattern.test(l.raw))) return [];
133
+ const values = [...data.conventions.status.values['zh-TW'], ...data.conventions.status.values.en];
134
+ const text = lines.map((l) => plainText(l.raw)).join(' ');
135
+ if (values.some((v) => (/[A-Za-z]/.test(v) ? new RegExp(`\\b${v}\\b`, 'i').test(text) : text.includes(v)))) return [];
136
+ const badges = md.images.filter((img) => img.line > start && img.line < end);
137
+ if (badges.some((img) => /status|maintained|maintenance|archived|deprecated/i.test(`${img.src} ${img.alt ?? ''}`))) return [];
138
+ return [{ messageKey: 'missing', line: h1 ? h1.line : null, column: h1 ? 1 : null }];
139
+ },
140
+
141
+ STR005(ctx) {
142
+ const out = [];
143
+ let prev = null;
144
+ for (const h of ctx.md.headings) {
145
+ if (prev !== null && h.level > prev + 1) {
146
+ out.push({ messageKey: 'skip', params: { from: prev, to: h.level }, line: h.line, column: 1 });
147
+ }
148
+ prev = h.level;
149
+ }
150
+ return out;
151
+ },
152
+
153
+ STR006(ctx) {
154
+ const out = [];
155
+ const has = (id) => ctx.sections.some((s) => s.ids.includes(id));
156
+ for (const id of ctx.typeDef.required) {
157
+ // 這幾個章節有專門的規則檢查(判斷得比較寬鬆),不在這裡重複報
158
+ if (HANDLED_ELSEWHERE[id] && ruleApplies(HANDLED_ELSEWHERE[id], ctx.type)) continue;
159
+ // 整個「安裝與執行」都沒有時,只報缺少「安裝與執行」,不再逐一報底下的小節
160
+ if (INSTALL_CHILDREN.has(id) && !has('getting-started')) continue;
161
+ if (has(id)) continue;
162
+ // 只有一個「安裝」二級標題、底下直接寫步驟(沒有分小節),也算有寫安裝步驟
163
+ if (id === 'install-steps' && installWrittenDirectly(ctx)) continue;
164
+ const def = sectionDef(id);
165
+ out.push({ messageKey: 'missing', params: { section: def.title, type: ctx.typeDef.name }, line: null, column: null, block: def.block });
166
+ }
167
+ return out;
168
+ },
169
+
170
+ STR007(ctx) {
171
+ const out = [];
172
+ let max = null;
173
+ for (const section of ctx.sections) {
174
+ if (section.level !== 2 || !section.block) continue;
175
+ const info = blockInfo(section.block);
176
+ if (max && info.index < max.info.index) {
177
+ out.push({
178
+ messageKey: 'order',
179
+ params: { heading: section.text, number: info.number, before: max.section.text, beforeNumber: max.info.number },
180
+ line: section.line,
181
+ column: 1,
182
+ block: section.block,
183
+ });
184
+ continue;
185
+ }
186
+ if (!max || info.index > max.info.index) max = { section, info };
187
+ }
188
+ return out;
189
+ },
190
+
191
+ STR008(ctx) {
192
+ const h2 = ctx.sections.filter((s) => s.level === 2);
193
+ const index = h2.findIndex((s) => s.ids.includes('license'));
194
+ if (index === -1 || index === h2.length - 1) return [];
195
+ const after = h2[index + 1];
196
+ return [{ messageKey: 'notLast', params: { heading: after.text }, line: after.line, column: 1 }];
197
+ },
198
+
199
+ STR009(ctx) {
200
+ const { md } = ctx;
201
+ const out = [];
202
+ for (const section of ctx.sections) {
203
+ if (section.level < 2) continue;
204
+ const hasContent = md.lines.some(
205
+ (l) =>
206
+ l.line > section.line &&
207
+ l.line < section.endLine &&
208
+ ((l.kind === 'text' && !l.heading) || l.kind === 'fence' || l.kind === 'code'),
209
+ );
210
+ if (!hasContent) out.push({ messageKey: 'empty', params: { heading: section.text }, line: section.line, column: 1 });
211
+ }
212
+ return out;
213
+ },
214
+
215
+ STR010(ctx) {
216
+ const { md } = ctx;
217
+ const out = [];
218
+ const phrases = ['請務必依據你的專案', '請斟酌', '範本不是絕對', 'Lorem ipsum'];
219
+ for (const line of proseLines(md)) {
220
+ for (const phrase of phrases) {
221
+ const index = line.prose.toLowerCase().indexOf(phrase.toLowerCase());
222
+ if (index !== -1) out.push({ messageKey: 'phrase', params: { text: line.raw.slice(index, index + phrase.length) }, line: line.line, column: index + 1 });
223
+ }
224
+ const bare = line.prose.trim().replace(/^(?:[-*+]|\d+[.)])\s+/, '');
225
+ if (/^(?:\.{3,}|…+)$/.test(bare)) out.push({ messageKey: 'ellipsis', line: line.line, column: line.raw.indexOf(bare[0]) + 1 });
226
+ }
227
+ for (const line of md.lines) {
228
+ if (line.kind !== 'text' && line.kind !== 'code') continue;
229
+ const index = line.raw.toLowerCase().indexOf('example@example.com');
230
+ if (index !== -1) out.push({ messageKey: 'phrase', params: { text: 'example@example.com' }, line: line.line, column: index + 1 });
231
+ }
232
+ return out;
233
+ },
234
+
235
+ STR015(ctx) {
236
+ const out = [];
237
+ for (const line of ctx.md.lines) {
238
+ if (line.kind !== 'text' && line.kind !== 'code') continue;
239
+ for (const m of line.raw.matchAll(placeholderPattern())) {
240
+ if (isSyntaxMention(m[0])) continue;
241
+ out.push({ messageKey: 'placeholder', params: { text: m[0] }, line: line.line, column: m.index + 1 });
242
+ }
243
+ }
244
+ return out;
245
+ },
246
+ };
247
+
248
+ export { findDescription, findSection };
@@ -0,0 +1,55 @@
1
+ // 類型專屬規則:後端 API、作品集、課程範例各自多出來的要求。
2
+ import { readPackageJson } from '../project.js';
3
+ import { findSection } from '../sections.js';
4
+ import { proseLines, readableText } from './util.js';
5
+
6
+ const API_DOC_HINT = /swagger|api-docs|openapi|redoc|scalar|postman|\/docs\b|\/api\/docs/i;
7
+ const DB_DEPS = ['prisma', '@prisma/client', 'knex', 'sequelize', 'typeorm', 'drizzle-orm', '@mikro-orm/core'];
8
+ const DB_FILES = ['prisma', 'migrations', 'db/migrations', 'database/migrations', 'knexfile.js', 'knexfile.ts', 'knexfile.cjs', 'knexfile.mjs', '.sequelizerc', 'drizzle.config.ts', 'drizzle.config.js', 'ormconfig.json', 'ormconfig.js', 'ormconfig.ts'];
9
+
10
+ function hasSection(ctx, id) {
11
+ return Boolean(findSection(ctx.sections, id));
12
+ }
13
+
14
+ export const checks = {
15
+ 'TYPE-API001'(ctx) {
16
+ if (hasSection(ctx, 'api-docs')) return [];
17
+ if (ctx.md.links.some((l) => API_DOC_HINT.test(l.href) || /API\s*(?:文件|docs?|documentation|reference)/i.test(l.text))) return [];
18
+ if (ctx.md.lines.some((l) => l.kind === 'text' && /https?:\/\/\S*(?:swagger|api-docs|openapi|redoc|\/docs\b)/i.test(l.raw))) return [];
19
+ return [{ messageKey: 'missing', line: null, column: null }];
20
+ },
21
+
22
+ 'TYPE-API002'(ctx) {
23
+ const evidence = DB_FILES.filter((f) => ctx.project.exists(f));
24
+ const pkg = readPackageJson(ctx.project);
25
+ const deps = { ...pkg?.dependencies, ...pkg?.devDependencies };
26
+ evidence.push(...DB_DEPS.filter((d) => d in deps));
27
+ if (!evidence.length) return [];
28
+ if (/migrat|seed|db push|db:push|db:migrate|db:setup|db:init|schema:sync|createdb|CREATE DATABASE/i.test(ctx.md.source)) return [];
29
+ const anchor = findSection(ctx.sections, 'getting-started');
30
+ return [{ messageKey: 'missing', params: { evidence: evidence.slice(0, 3).join(', ') }, line: anchor?.line ?? null, column: anchor ? 1 : null }];
31
+ },
32
+
33
+ 'TYPE-API003'(ctx) {
34
+ for (const block of ctx.md.codeBlocks) {
35
+ if (['http', 'rest', 'httpie'].includes(block.lang)) return [];
36
+ if (block.lines.some(({ text }) => /\b(?:curl|wget|httpie|xh)\b|^\s*(?:\$\s+)?http\s+(?:GET|POST|PUT|PATCH|DELETE)\b|fetch\(/i.test(text))) return [];
37
+ }
38
+ return [{ messageKey: 'missing', line: null, column: null }];
39
+ },
40
+
41
+ 'TYPE-PF001'(ctx) {
42
+ return hasSection(ctx, 'my-role') ? [] : [{ messageKey: 'missing', line: null, column: null }];
43
+ },
44
+
45
+ 'TYPE-PF002'(ctx) {
46
+ return hasSection(ctx, 'design-decisions') ? [] : [{ messageKey: 'missing', line: null, column: null }];
47
+ },
48
+
49
+ 'TYPE-CS002'(ctx) {
50
+ if (hasSection(ctx, 'course-unit')) return [];
51
+ const UNIT = /第\s*[0-9一二三四五六七八九十]+\s*(?:週|周|堂|章|單元|課|講)|\b(?:Lesson|Week|Chapter|Unit|Module|Session)\s*\d+/i;
52
+ if (proseLines(ctx.md).some((l) => UNIT.test(readableText(l)))) return [];
53
+ return [{ messageKey: 'missing', line: null, column: null }];
54
+ },
55
+ };