specthread 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.
Files changed (77) hide show
  1. package/README.md +139 -0
  2. package/dist/bin/check.d.ts +1 -0
  3. package/dist/bin/check.js +67 -0
  4. package/dist/bin/cli.d.ts +2 -0
  5. package/dist/bin/cli.js +26 -0
  6. package/dist/bin/generate.d.ts +1 -0
  7. package/dist/bin/generate.js +55 -0
  8. package/dist/checks/changelog.d.ts +8 -0
  9. package/dist/checks/changelog.js +30 -0
  10. package/dist/checks/headings.d.ts +3 -0
  11. package/dist/checks/headings.js +54 -0
  12. package/dist/checks/links.d.ts +8 -0
  13. package/dist/checks/links.js +66 -0
  14. package/dist/checks/markers.d.ts +2 -0
  15. package/dist/checks/markers.js +60 -0
  16. package/dist/checks/pending.d.ts +2 -0
  17. package/dist/checks/pending.js +200 -0
  18. package/dist/checks/references.d.ts +2 -0
  19. package/dist/checks/references.js +41 -0
  20. package/dist/checks/sections.d.ts +3 -0
  21. package/dist/checks/sections.js +137 -0
  22. package/dist/checks/style.d.ts +10 -0
  23. package/dist/checks/style.js +61 -0
  24. package/dist/checks/timestamps.d.ts +2 -0
  25. package/dist/checks/timestamps.js +58 -0
  26. package/dist/checks/toc.d.ts +2 -0
  27. package/dist/checks/toc.js +41 -0
  28. package/dist/commands/init.d.ts +1 -0
  29. package/dist/commands/init.js +115 -0
  30. package/dist/config-loader.d.ts +2 -0
  31. package/dist/config-loader.js +106 -0
  32. package/dist/config.schema.d.ts +96 -0
  33. package/dist/config.schema.js +27 -0
  34. package/dist/constants/docs.d.ts +15 -0
  35. package/dist/constants/docs.js +16 -0
  36. package/dist/constants/patterns.d.ts +24 -0
  37. package/dist/constants/patterns.js +24 -0
  38. package/dist/constants/rules.d.ts +101 -0
  39. package/dist/constants/rules.js +97 -0
  40. package/dist/gen/pending-section.d.ts +19 -0
  41. package/dist/gen/pending-section.js +102 -0
  42. package/dist/gen/references.d.ts +13 -0
  43. package/dist/gen/references.js +144 -0
  44. package/dist/gen/summary.d.ts +27 -0
  45. package/dist/gen/summary.js +125 -0
  46. package/dist/gen/toc.d.ts +25 -0
  47. package/dist/gen/toc.js +66 -0
  48. package/dist/types.d.ts +125 -0
  49. package/dist/types.js +1 -0
  50. package/dist/utils/anchor.d.ts +20 -0
  51. package/dist/utils/anchor.js +24 -0
  52. package/dist/utils/ignore.d.ts +11 -0
  53. package/dist/utils/ignore.js +20 -0
  54. package/dist/utils/parse.d.ts +50 -0
  55. package/dist/utils/parse.js +272 -0
  56. package/dist/utils/report.d.ts +17 -0
  57. package/dist/utils/report.js +38 -0
  58. package/dist/utils/resolve.d.ts +21 -0
  59. package/dist/utils/resolve.js +157 -0
  60. package/dist/utils/scan.d.ts +11 -0
  61. package/dist/utils/scan.js +111 -0
  62. package/dist/utils/scope.d.ts +51 -0
  63. package/dist/utils/scope.js +55 -0
  64. package/package.json +29 -0
  65. package/scaffold/AGENTS.md +67 -0
  66. package/scaffold/CLAUDE.md +1 -0
  67. package/scaffold/claude/skills/check.md +43 -0
  68. package/scaffold/claude/skills/gen.md +41 -0
  69. package/scaffold/claude/skills/plan-close.md +57 -0
  70. package/scaffold/claude/skills/plan-open.md +50 -0
  71. package/scaffold/claude/skills/plan-run.md +51 -0
  72. package/scaffold/config.jsonc +71 -0
  73. package/scaffold/pending.md +34 -0
  74. package/scaffold/project.md +47 -0
  75. package/scaffold/rules.md +421 -0
  76. package/scaffold/templates/plan.md +159 -0
  77. package/scaffold/templates/spec.md +96 -0
@@ -0,0 +1,200 @@
1
+ /**
2
+ * 관리 문서 항목 형식 (`docs/system/rules.md` §4-2).
3
+ *
4
+ * 이 검사는 관리 문서 한 파일에만 걸린다. 항목이 한곳에 모이는 것이 그 문서의 존재
5
+ * 이유라서, 다른 문서에 같은 모양이 나타나면 그건 미확정 사항 절 (생성 뷰) 이고
6
+ * 형식이 다르다 - 뷰는 `li`, 정본은 `###` 헤딩이다.
7
+ */
8
+ import { timepointGlobal } from '../constants/patterns.js';
9
+ import { RULE } from '../constants/rules.js';
10
+ import { summaryBlocks } from '../gen/summary.js';
11
+ import { invertByTarget, pendingSectionBlock } from '../gen/pending-section.js';
12
+ /** 항목 헤딩. id 뒤부터 줄 끝까지를 제목으로 본다 */
13
+ const ITEM = /^###\s+`\[[a-z]+::[a-z0-9][a-z0-9-]*\]`(.*)$/;
14
+ /** `li` 로 적힌 항목. 정본에서는 헤딩이어야 한다 */
15
+ const ITEM_AS_LI = /^\s*-\s+`\[[a-z]+::[a-z0-9][a-z0-9-]*\]`/;
16
+ /**
17
+ * 문장이 끝난 흔적.
18
+ *
19
+ * 제목은 문장으로 끝나지 않는다. 헤딩에 종결이 나타나면 본문이 이어붙은 것이다.
20
+ * 글자 수 상한을 쓰지 않는 이유는 그 숫자를 정하는 논쟁이 생기기 때문이다.
21
+ */
22
+ const SENTENCE_END = /(다|음|함|것|임)\.(\s|$)|\.\s+\S/;
23
+ /** 한 줄 안의 선택지 표기. 둘 이상이면 `li` 로 내야 한다 */
24
+ const INLINE_OPTION = /[((][a-zi0-9]{1,3}[))]/g;
25
+ /** 시점 줄. 항목 헤딩 다음 첫 내용 줄에 온다 */
26
+ const TIMEPOINT_LINE = new RegExp(`^${timepointGlobal().source}$`);
27
+ /** 헤딩 안에 남은 시점 표기. 앵커가 시점에 묶이므로 막는다 */
28
+ const TIMEPOINT_INLINE = timepointGlobal();
29
+ const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
30
+ /**
31
+ * 항목 헤딩 하나. 제목만 담고 시점·본문은 아래 줄이 갖는다.
32
+ *
33
+ * 시점을 헤딩에서 막는 이유는 앵커다. 헤딩 문자열이 앵커가 되므로 시점이 거기 있으면
34
+ * 마일스톤이 밀릴 때마다 그 항목을 가리키는 링크가 전부 깨진다. `§4-1` 이 같은 이유로
35
+ * 마커에서 시점을 뺐다.
36
+ */
37
+ const inspectHeading = (path, line, title) => {
38
+ const findings = [];
39
+ const at = (rule, message) => findings.push({ file: path, line, rule, message });
40
+ TIMEPOINT_INLINE.lastIndex = 0;
41
+ if (TIMEPOINT_INLINE.test(title)) {
42
+ at(RULE.PENDING.TIMEPOINT, '작성일과 해결 예정은 헤딩 다음 줄에 적는다 - 헤딩은 앵커가 된다');
43
+ }
44
+ if (SENTENCE_END.test(title)) {
45
+ at(RULE.PENDING.INLINE_BODY, '헤딩은 제목에서 끝난다. 본문은 아래 줄부터');
46
+ }
47
+ if ((title.match(INLINE_OPTION) ?? []).length >= 2) {
48
+ at(RULE.PENDING.INLINE_OPTIONS, '선택지는 `li` 로 낸다');
49
+ }
50
+ return findings;
51
+ };
52
+ const inspectBody = (path, line, text) => {
53
+ const findings = [];
54
+ if (ITEM_AS_LI.test(text)) {
55
+ findings.push({
56
+ file: path,
57
+ line,
58
+ rule: RULE.PENDING.ITEM_SHAPE,
59
+ message: '항목은 `###` 헤딩으로 낸다. `li` 는 앵커를 못 가져 가리킬 수 없다',
60
+ });
61
+ }
62
+ if ((text.match(INLINE_OPTION) ?? []).length >= 2) {
63
+ findings.push({
64
+ file: path,
65
+ line,
66
+ rule: RULE.PENDING.INLINE_OPTIONS,
67
+ message: '선택지는 `li` 로 낸다',
68
+ });
69
+ }
70
+ if (/\]\(\.?\.?\/?work\//.test(text) || /`work\//.test(text)) {
71
+ findings.push({
72
+ file: path,
73
+ line,
74
+ rule: RULE.PENDING.WORK_LINK,
75
+ message: '작업 문서는 흡수 후 사라진다. 근거를 항목 안으로 옮겨 적는다',
76
+ });
77
+ }
78
+ return findings;
79
+ };
80
+ /** 항목 헤딩 다음 첫 내용 줄이 시점인지 */
81
+ const inspectTimepoint = (file, at) => {
82
+ for (let i = at; i < file.lines.length; i++) {
83
+ const line = file.lines[i].trim();
84
+ if (line === '')
85
+ continue;
86
+ const stamp = TIMEPOINT_LINE.exec(line);
87
+ if (stamp === null) {
88
+ return [
89
+ {
90
+ file: file.path,
91
+ line: i + 1,
92
+ rule: RULE.PENDING.TIMEPOINT,
93
+ message: '항목 헤딩 다음 줄은 `작성일 <날짜>` 이고 `/ 해결 예정 <라벨>` 이 붙을 수 있다',
94
+ },
95
+ ];
96
+ }
97
+ if (stamp[2] !== undefined && ISO_DATE.test(stamp[2].trim())) {
98
+ return [
99
+ {
100
+ file: file.path,
101
+ line: i + 1,
102
+ rule: RULE.PENDING.TIMEPOINT,
103
+ message: `해결 예정에 달력 날짜를 쓰지 않는다 - ${stamp[2].trim()}`,
104
+ },
105
+ ];
106
+ }
107
+ return [];
108
+ }
109
+ // 헤딩 뒤에 아무 줄도 없으면 시점 줄이 빠진 것이다
110
+ return [
111
+ {
112
+ file: file.path,
113
+ line: at,
114
+ rule: RULE.PENDING.TIMEPOINT,
115
+ message: '항목 헤딩 다음 줄은 `작성일 <날짜>` 이고 `/ 해결 예정 <라벨>` 이 붙을 수 있다',
116
+ },
117
+ ];
118
+ };
119
+ /**
120
+ * 절 머리 요약 표 ↔ 항목 일치.
121
+ *
122
+ * 목차·참조 절과 같은 구조다. 생성물이라 손으로 고치면 어긋나고, 어긋남 자체가
123
+ * `docs:generate` 를 돌려야 한다는 신호다.
124
+ */
125
+ const inspectSummary = (file, index) => {
126
+ const findings = [];
127
+ for (const { blockStart, blockEnd, block } of summaryBlocks(file.lines, index)) {
128
+ const actual = file.lines.slice(blockStart - 1, blockEnd);
129
+ const rows = (lines) => lines.filter((l) => l.startsWith('| [')).length;
130
+ if (rows(actual) === 0) {
131
+ findings.push({
132
+ file: file.path,
133
+ line: blockStart,
134
+ rule: RULE.PENDING.SUMMARY_MISSING,
135
+ message: `절 머리에 요약 표가 없다 - 항목 ${rows(block)} 개`,
136
+ });
137
+ continue;
138
+ }
139
+ if (actual.join('\n') !== block.join('\n')) {
140
+ findings.push({
141
+ file: file.path,
142
+ line: blockStart,
143
+ rule: RULE.PENDING.SUMMARY_STALE,
144
+ message: `요약 표가 항목과 어긋난다 - 적힌 것 ${rows(actual)} / 항목 ${rows(block)}`,
145
+ });
146
+ }
147
+ }
148
+ return findings;
149
+ };
150
+ /**
151
+ * 문서 미확정 사항 절 ↔ 관리 문서 백링크 일치.
152
+ *
153
+ * 목차·참조 절과 같은 구조다. `docs/pending.md` 를 제외한 모든 문서가 대상이다 -
154
+ * 절 자체가 없는 문서는 `gen/pending-section.ts` 가 건드리지 않으므로 지적도 없다.
155
+ */
156
+ const inspectPendingSection = (index) => {
157
+ const pending = index.files.get(index.config.pending);
158
+ if (pending === undefined)
159
+ return [];
160
+ const byTarget = invertByTarget(pending);
161
+ const findings = [];
162
+ for (const file of index.files.values()) {
163
+ if (file.path === index.config.pending || file.pendingSection === null)
164
+ continue;
165
+ const expected = pendingSectionBlock(file, byTarget, index);
166
+ const actual = file.lines.slice(file.pendingSection.start - 1, file.pendingSection.end);
167
+ const count = (lines) => lines.filter((l) => l.startsWith('- [`')).length;
168
+ if (actual.join('\n') !== expected.join('\n')) {
169
+ findings.push({
170
+ file: file.path,
171
+ line: file.pendingSection.start,
172
+ rule: RULE.PENDING.SECTION_STALE,
173
+ message: `미확정 사항 절이 관리 문서와 어긋난다 - 적힌 것 ${count(actual)} / 관리 문서 ${count(expected)}`,
174
+ });
175
+ }
176
+ }
177
+ return findings;
178
+ };
179
+ export const checkPending = (index) => {
180
+ const file = index.files.get(index.config.pending);
181
+ if (file === undefined)
182
+ return [];
183
+ const findings = [];
184
+ let inChangeLog = false;
185
+ file.lines.forEach((raw, i) => {
186
+ const line = i + 1;
187
+ if (raw.startsWith('## 변경 이력'))
188
+ inChangeLog = true;
189
+ if (inChangeLog)
190
+ return;
191
+ const item = ITEM.exec(raw);
192
+ if (item) {
193
+ findings.push(...inspectHeading(file.path, line, item[1]));
194
+ findings.push(...inspectTimepoint(file, line));
195
+ return;
196
+ }
197
+ findings.push(...inspectBody(file.path, line, raw));
198
+ });
199
+ return [...findings, ...inspectSummary(file, index), ...inspectPendingSection(index)];
200
+ };
@@ -0,0 +1,2 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ export declare const checkReferences: (index: DocIndex) => Finding[];
@@ -0,0 +1,41 @@
1
+ import { RULE } from '../constants/rules.js';
2
+ /**
3
+ * 참조 절 ↔ 본문 링크 일치.
4
+ *
5
+ * 목차와 같은 구조다 - 본문에 이미 있는 정보를 문서 하단에 한 번 더 적는 자리라
6
+ * 손으로 관리하면 반드시 어긋난다. 생성 결과와 다르면 지적한다.
7
+ */
8
+ import { isTargetDoc } from "../utils/scope.js";
9
+ import { referenceBlock } from "../gen/references.js";
10
+ /** 블록 안 항목 줄 수. 지적 메시지에 규모를 실어준다 */
11
+ const itemCount = (lines) => lines.filter((l) => l.startsWith("- [")).length;
12
+ export const checkReferences = (index) => {
13
+ const findings = [];
14
+ for (const file of index.files.values()) {
15
+ if (!isTargetDoc(file, index.config))
16
+ continue;
17
+ // 본문 링크가 없으면 참조 절을 둘 이유가 없다
18
+ const expected = referenceBlock(file, index.config);
19
+ if (expected.length === 0)
20
+ continue;
21
+ if (file.refSection === null) {
22
+ findings.push({
23
+ file: file.path,
24
+ line: file.lines.length,
25
+ rule: RULE.REFERENCE.MISSING,
26
+ message: `참조 절이 없다 - 본문 링크 ${itemCount(expected)} 대상`,
27
+ });
28
+ continue;
29
+ }
30
+ const actual = file.lines.slice(file.refSection.start - 1, file.refSection.end);
31
+ if (actual.join("\n") !== expected.join("\n")) {
32
+ findings.push({
33
+ file: file.path,
34
+ line: file.refSection.start,
35
+ rule: RULE.REFERENCE.STALE,
36
+ message: `참조 절이 본문 링크와 어긋난다 - 적힌 것 ${itemCount(actual)} / 본문 ${itemCount(expected)}`,
37
+ });
38
+ }
39
+ }
40
+ return findings;
41
+ };
@@ -0,0 +1,3 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ /** 모든 파일의 절 참조를 훑는다 */
3
+ export declare const checkSectionRefs: (index: DocIndex) => Finding[];
@@ -0,0 +1,137 @@
1
+ import { RULE } from '../constants/rules.js';
2
+ /**
3
+ * 절 참조 유효성 - `§6-1` 이 실제로 존재하는 절을 가리키는가, 그리고
4
+ * 다른 문서의 절이면 앵커 링크로 걸려 있는가.
5
+ *
6
+ * 번호 없는 헤딩은 § 대상이 될 수 없으므로 대조 집합에 들어가지 않는다.
7
+ */
8
+ import { basename, dirname, relative } from "node:path";
9
+ import { inChangeLog, inRefSection, inToc, isCheckTarget, isHeadingLine, } from "../utils/scope.js";
10
+ /** 미해소 사유별 메시지 */
11
+ /**
12
+ * 해소 실패 사유마다 규칙 id 와 메시지.
13
+ *
14
+ * 한 map 에 둘을 함께 담는다 - 따로 두면 같은 키를 가진 map 이 둘이 되어 한쪽에만
15
+ * 사유를 더했을 때 갈라진다. id 를 `` `section-ref/${reason}` `` 처럼 조립하면
16
+ * 정의처를 벗어난 id 가 생겨 `RuleId` 로도 grep 으로도 못 찾는다.
17
+ */
18
+ const REASON = {
19
+ "no-doc-name": {
20
+ rule: RULE.SECTION_REF.NO_DOC_NAME,
21
+ message: "문서명이 없어 대상을 특정할 수 없다",
22
+ },
23
+ "unknown-doc": {
24
+ rule: RULE.SECTION_REF.UNKNOWN_DOC,
25
+ message: "없는 문서를 가리킨다",
26
+ },
27
+ "ambiguous-doc": {
28
+ rule: RULE.SECTION_REF.AMBIGUOUS_DOC,
29
+ message: "같은 이름의 문서가 여럿이다",
30
+ },
31
+ };
32
+ /**
33
+ * 문서별로 `§` 가 가리킬 수 있는 절 번호 집합을 만든다.
34
+ *
35
+ * 번호 없는 헤딩은 넣지 않는다 - 번호로 가리킬 수 없으므로 대조 대상이 아니다.
36
+ */
37
+ const sectionNumbers = (index) => {
38
+ const byFile = new Map();
39
+ for (const file of index.files.values()) {
40
+ // 절 번호는 문서만 갖는다. 코드·데이터에는 헤딩이 없다
41
+ if (file.kind !== "md")
42
+ continue;
43
+ const nums = new Set();
44
+ for (const heading of file.headings) {
45
+ if (heading.num !== null) {
46
+ nums.add(heading.num);
47
+ }
48
+ }
49
+ byFile.set(file.path, nums);
50
+ }
51
+ return byFile;
52
+ };
53
+ /**
54
+ * 고쳐 쓸 앵커 링크 자체를 만들어 지적 메시지에 실어준다.
55
+ *
56
+ * 색인이 절 번호 → 앵커 대응과 두 파일의 경로를 다 갖고 있으므로 상대 경로까지
57
+ * 계산해 완성형을 보여줄 수 있다. 사람이 대상 문서를 열어 제목을 확인하는 일이 없어진다.
58
+ * 이 계산이 그대로 자동 변환의 재료가 된다.
59
+ */
60
+ const anchorLink = (index, fromFile, targetFile, num) => {
61
+ const anchor = index.files
62
+ .get(targetFile)
63
+ ?.headings.find((h) => h.num === num)?.anchor;
64
+ const rel = relative(dirname(fromFile), targetFile);
65
+ const path = rel.startsWith(".") ? rel : `./${rel}`;
66
+ return `[\`${basename(targetFile)}\` §${num}](${path}#${anchor ?? "?"})`;
67
+ };
68
+ /** 해소되지 않은 참조. 어느 문서를 가리키는지 모르니 대조도 못 한다 */
69
+ const unresolvedFinding = (file, ref) => {
70
+ if (ref.reason === "resolved") {
71
+ throw new Error("해소된 참조에는 쓰지 않는다");
72
+ }
73
+ const detail = ref.rawTarget === null ? "" : ` - ${ref.rawTarget}`;
74
+ return {
75
+ file,
76
+ line: ref.line,
77
+ rule: REASON[ref.reason].rule,
78
+ message: `§${ref.num} ${REASON[ref.reason].message}${detail}`,
79
+ };
80
+ };
81
+ /**
82
+ * 참조 하나를 판정한다. 지적할 것이 없으면 null.
83
+ *
84
+ * 가드를 앞에 모으고 판정을 뒤에 두어 흐름이 한 방향으로 흐르게 한다.
85
+ */
86
+ const inspect = (index, numsByFile, file, ref) => {
87
+ if (ref.reason !== "resolved") {
88
+ return unresolvedFinding(file.path, ref);
89
+ }
90
+ // 해소됐다면 대상이 있다. 가드로 좁혀 두면 아래에서 단정이 필요 없다
91
+ if (ref.targetFile === null) {
92
+ return null;
93
+ }
94
+ const nums = numsByFile.get(ref.targetFile);
95
+ if (!nums?.has(ref.num)) {
96
+ const where = ref.rawTarget ?? "이 문서";
97
+ return {
98
+ file: file.path,
99
+ line: ref.line,
100
+ rule: RULE.SECTION_REF.MISSING,
101
+ message: `${where} 에 §${ref.num} 절이 없다`,
102
+ };
103
+ }
104
+ // 다른 문서의 절은 앵커 링크로 가리켜야 한다. 자기 절 참조와 코드 주석은 면제다
105
+ if (file.kind === "md" && !ref.linked && ref.targetFile !== file.path) {
106
+ return {
107
+ file: file.path,
108
+ line: ref.line,
109
+ rule: RULE.SECTION_REF.NOT_LINKED,
110
+ message: `앵커 링크로 - ${anchorLink(index, file.path, ref.targetFile, ref.num)}`,
111
+ };
112
+ }
113
+ return null;
114
+ };
115
+ /** 모든 파일의 절 참조를 훑는다 */
116
+ export const checkSectionRefs = (index) => {
117
+ const findings = [];
118
+ const numsByFile = sectionNumbers(index);
119
+ for (const file of index.files.values()) {
120
+ // 코드·데이터도 문서의 절을 가리키므로 `md` 로 좁히지 않는다
121
+ if (!isCheckTarget(file.path, index.config))
122
+ continue;
123
+ for (const ref of file.sectionRefs) {
124
+ if (file.ignored.has(ref.line) || inChangeLog(file, ref.line))
125
+ continue;
126
+ if (isHeadingLine(file, ref.line) || inToc(file, ref.line))
127
+ continue;
128
+ if (inRefSection(file, ref.line))
129
+ continue;
130
+ const finding = inspect(index, numsByFile, file, ref);
131
+ if (finding !== null) {
132
+ findings.push(finding);
133
+ }
134
+ }
135
+ }
136
+ return findings;
137
+ };
@@ -0,0 +1,10 @@
1
+ import type { DocIndex, Finding } from '../types.ts';
2
+ export declare const checkStyle: (index: DocIndex) => Finding[];
3
+ /**
4
+ * 코드에 있는 검사 id 가 규칙 문서에 선언됐는지.
5
+ *
6
+ * 선언이 없으면 문서화되지 않은 규칙을 강제하는 것이다. 역방향 (문서에만 있고 코드에
7
+ * 없는 것) 은 절 단위 판정이 애매해 검사하지 않는다 - 병기가 없는 절이 곧 사람만
8
+ * 검사하는 규칙이다.
9
+ */
10
+ export declare const checkRuleDeclared: (index: DocIndex) => Finding[];
@@ -0,0 +1,61 @@
1
+ /**
2
+ * 문체 검사 (`docs/system/rules.md` §2-6).
3
+ *
4
+ * 지금은 em dash 하나다. `Write` / `Edit` 뒤에 도는 훅이 예방하지만 스크립트나 외부
5
+ * 유입은 훅을 거치지 않으므로 상태를 보는 검사가 따로 필요하다.
6
+ */
7
+ import { EM_DASH } from '../constants/patterns.js';
8
+ import { ALL_RULE_IDS, RULE } from '../constants/rules.js';
9
+ import { codeSpanMask } from '../utils/parse.js';
10
+ import { isCheckTarget } from '../utils/scope.js';
11
+ /**
12
+ * 대상 문자를 소스에 갖는 파일. 훅과 이 검사가 서로를 망가뜨리지 않게 뺀다.
13
+ *
14
+ * 이 파일 자신은 리터럴 대신 `\u2014` 로 적어 목록에 넣지 않는다 - 훅 설정에 기대지
15
+ * 않고 손상을 막는다.
16
+ */
17
+ const SELF = ['tools/hooks/no-em-dash.mjs'];
18
+ export const checkStyle = (index) => {
19
+ const findings = [];
20
+ for (const file of index.files.values()) {
21
+ if (!isCheckTarget(file.path, index.config) || SELF.includes(file.path))
22
+ continue;
23
+ file.lines.forEach((raw, i) => {
24
+ if (!raw.includes(EM_DASH))
25
+ return;
26
+ // 백틱 안은 금지 문자를 인용한 것이다. 규칙 문서가 금지 예시를 그렇게 담는다
27
+ const mask = codeSpanMask(raw);
28
+ const at = [...raw].findIndex((c, k) => c === EM_DASH && !mask[k]);
29
+ if (at < 0)
30
+ return;
31
+ findings.push({
32
+ file: file.path,
33
+ line: i + 1,
34
+ rule: RULE.STYLE.EM_DASH,
35
+ message: "em dash 를 쓰지 않는다. 하이픈 '-' 으로",
36
+ });
37
+ });
38
+ }
39
+ return findings;
40
+ };
41
+ /**
42
+ * 코드에 있는 검사 id 가 규칙 문서에 선언됐는지.
43
+ *
44
+ * 선언이 없으면 문서화되지 않은 규칙을 강제하는 것이다. 역방향 (문서에만 있고 코드에
45
+ * 없는 것) 은 절 단위 판정이 애매해 검사하지 않는다 - 병기가 없는 절이 곧 사람만
46
+ * 검사하는 규칙이다.
47
+ */
48
+ export const checkRuleDeclared = (index) => {
49
+ const rulesPath = index.config.rules;
50
+ const doc = index.files.get(rulesPath);
51
+ if (doc === undefined)
52
+ return [];
53
+ const text = doc.lines.join('\n');
54
+ const heading = doc.headings.find((h) => h.title === '개요');
55
+ return ALL_RULE_IDS.filter((id) => !text.includes(id)).map((id) => ({
56
+ file: rulesPath,
57
+ line: heading?.line ?? 1,
58
+ rule: RULE.STYLE.RULE_UNDECLARED,
59
+ message: `검사 id 가 규칙 문서에 선언되지 않았다 - ${id}`,
60
+ }));
61
+ };
@@ -0,0 +1,2 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ export declare const checkTimestamps: (index: DocIndex) => Finding[];
@@ -0,0 +1,58 @@
1
+ import { timepointGlobal } from '../constants/patterns.js';
2
+ import { RULE } from '../constants/rules.js';
3
+ /**
4
+ * 본문 시점 표기 - 날짜를 본문에 남기지 않는가 (`docs/system/rules.md` §2-1).
5
+ *
6
+ * 문서 본문은 현재 상태와 근거만 서술하고, _누가 언제 무엇을 뒤집었는가_ 는 변경 이력이
7
+ * 갖는다. §2-1 이 금지하는 다섯 가지 중 **날짜만** 여기서 본다. 나머지 (시점을 함의하는
8
+ * 낱말·구버전 대비 서술·결정 사건 라벨) 는 낱말 매칭으로는 오탐이 커서 의미를 읽는
9
+ * 검토에 맡긴다 - `신규 5 종` 같은 콘텐츠 서술까지 걸린다.
10
+ */
11
+ import { codeSpanMask, linkTargetSpans } from "../utils/parse.js";
12
+ import { inChangeLog, inToc, isTargetDoc } from "../utils/scope.js";
13
+ const DATE = /20\d\d-\d\d-\d\d/g;
14
+ /** 시점 표기가 차지한 자리 */
15
+ const timepointSpans = (text) => [...text.matchAll(timepointGlobal())].map((m) => ({
16
+ start: m.index,
17
+ end: m.index + m[0].length,
18
+ }));
19
+ export const checkTimestamps = (index) => {
20
+ const findings = [];
21
+ for (const file of index.files.values()) {
22
+ if (!isTargetDoc(file, index.config))
23
+ continue;
24
+ let fence = false;
25
+ file.lines.forEach((text, i) => {
26
+ if (/^\s*(```|~~~)/.test(text)) {
27
+ fence = !fence;
28
+ return;
29
+ }
30
+ const line = i + 1;
31
+ // 펜스는 예시, 변경 이력은 날짜가 있어야 하는 자리, 목차는 헤딩을 복사한 생성물이다
32
+ if (fence || inChangeLog(file, line) || inToc(file, line))
33
+ return;
34
+ const mask = codeSpanMask(text);
35
+ const urls = linkTargetSpans(text);
36
+ const stamps = timepointSpans(text);
37
+ for (const m of text.matchAll(DATE)) {
38
+ // 백틱 안 날짜는 표기법 인용이다. §2-1 표가 금지 예시를 그렇게 담고 있다
39
+ if (mask[m.index])
40
+ continue;
41
+ // 링크 대상 안 날짜는 앵커 문자열의 일부다. 대상 문서 제목이 날짜를 담고 있어
42
+ // 생긴 것이므로 그 문서를 검사할 때 잡힌다
43
+ if (urls.some((u) => m.index >= u.start && m.index < u.end))
44
+ continue;
45
+ // 관리 문서 항목의 시점 표기는 항목 속성이다
46
+ if (stamps.some((s) => m.index >= s.start && m.index < s.end))
47
+ continue;
48
+ findings.push({
49
+ file: file.path,
50
+ line,
51
+ rule: RULE.TIMESTAMP.BODY_DATE,
52
+ message: `본문에 날짜 - ${m[0]}. 변경 이력으로 옮긴다`,
53
+ });
54
+ }
55
+ });
56
+ }
57
+ return findings;
58
+ };
@@ -0,0 +1,2 @@
1
+ import type { DocIndex, Finding } from "../types.ts";
2
+ export declare const checkToc: (index: DocIndex) => Finding[];
@@ -0,0 +1,41 @@
1
+ import { RULE } from '../constants/rules.js';
2
+ /**
3
+ * 목차 ↔ `##` 헤딩 일치.
4
+ *
5
+ * 목차는 생성기가 채우지만 사람이 손으로 고칠 수 있고, 절을 하나 끼워 넣으면
6
+ * 조용히 어긋난다. 생성 결과와 다르면 지적한다 - 고치는 방법은 `pnpm docs:generate --write` 다.
7
+ */
8
+ import { isTargetDoc, singleTitle } from "../utils/scope.js";
9
+ import { tocBlock } from "../gen/toc.js";
10
+ export const checkToc = (index) => {
11
+ const findings = [];
12
+ for (const file of index.files.values()) {
13
+ if (!isTargetDoc(file, index.config))
14
+ continue;
15
+ if (singleTitle(file) === null)
16
+ continue;
17
+ // `##` 절이 없으면 목차를 둘 이유가 없다
18
+ const expected = tocBlock(file.headings);
19
+ if (expected.length === 0)
20
+ continue;
21
+ if (file.tocBlock === null) {
22
+ findings.push({
23
+ file: file.path,
24
+ line: 1,
25
+ rule: RULE.TOC.MISSING,
26
+ message: "제목 아래 목차가 없다",
27
+ });
28
+ continue;
29
+ }
30
+ const actual = file.lines.slice(file.tocBlock.start - 1, file.tocBlock.end);
31
+ if (actual.join("\n") !== expected.join("\n")) {
32
+ findings.push({
33
+ file: file.path,
34
+ line: file.tocBlock.start,
35
+ rule: RULE.TOC.STALE,
36
+ message: `목차가 헤딩과 어긋난다 - 항목 ${actual.length - 2} / 헤딩 ${expected.length - 2}`,
37
+ });
38
+ }
39
+ }
40
+ return findings;
41
+ };
@@ -0,0 +1 @@
1
+ export declare const init: (args: string[]) => void;