create-clis 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 (104) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +113 -0
  3. package/README.zh-CN.md +113 -0
  4. package/assets/manifest.json +99 -0
  5. package/assets/template/.editorconfig +12 -0
  6. package/assets/template/.gitattributes +18 -0
  7. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +86 -0
  8. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +45 -0
  9. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +26 -0
  10. package/assets/template/.github/workflows/ci.yml +42 -0
  11. package/assets/template/.github/workflows/release.yml +65 -0
  12. package/assets/template/.gitignorerc.json +21 -0
  13. package/assets/template/.nvmrc +1 -0
  14. package/assets/template/.oxlintrc.json +52 -0
  15. package/assets/template/.prettierignore +11 -0
  16. package/assets/template/.prettierrc +11 -0
  17. package/assets/template/.releaserc.json +17 -0
  18. package/assets/template/.vscode/extensions.json +8 -0
  19. package/assets/template/.vscode/launch.json +13 -0
  20. package/assets/template/.vscode/settings.json +14 -0
  21. package/assets/template/AGENTS.md +25 -0
  22. package/assets/template/CODE_OF_CONDUCT.md +91 -0
  23. package/assets/template/CONTRIBUTING.md +85 -0
  24. package/assets/template/CONTRIBUTING.zh-CN.md +85 -0
  25. package/assets/template/LICENSE +21 -0
  26. package/assets/template/README.md +22 -0
  27. package/assets/template/README.zh-CN.md +22 -0
  28. package/assets/template/SECURITY.md +21 -0
  29. package/assets/template/_gitignore +409 -0
  30. package/assets/template/_npmrc +6 -0
  31. package/assets/template/bunfig.toml +16 -0
  32. package/assets/template/docs/README.md +30 -0
  33. package/assets/template/docs/adrs/README.md +7 -0
  34. package/assets/template/docs/designs/README.md +11 -0
  35. package/assets/template/docs/designs/tech-debt.md +22 -0
  36. package/assets/template/docs/development.md +59 -0
  37. package/assets/template/lefthook.yml +55 -0
  38. package/assets/template/package.json +38 -0
  39. package/assets/template/packages/{{NAME}}/CHANGELOG.md +3 -0
  40. package/assets/template/packages/{{NAME}}/LICENSE +21 -0
  41. package/assets/template/packages/{{NAME}}/README.md +33 -0
  42. package/assets/template/packages/{{NAME}}/README.zh-CN.md +33 -0
  43. package/assets/template/packages/{{NAME}}/docs/README.md +21 -0
  44. package/assets/template/packages/{{NAME}}/package.json +40 -0
  45. package/assets/template/packages/{{NAME}}/scripts/build.ts +82 -0
  46. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +214 -0
  47. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +152 -0
  48. package/assets/template/packages/{{NAME}}/src/index.ts +15 -0
  49. package/assets/template/packages/{{NAME}}/tsconfig.build.json +12 -0
  50. package/assets/template/packages/{{NAME}}/tsconfig.json +5 -0
  51. package/assets/template/packages/{{NAME}}-cli/CHANGELOG.md +3 -0
  52. package/assets/template/packages/{{NAME}}-cli/LICENSE +21 -0
  53. package/assets/template/packages/{{NAME}}-cli/README.md +35 -0
  54. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +35 -0
  55. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +30 -0
  56. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +30 -0
  57. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +23 -0
  58. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +212 -0
  59. package/assets/template/packages/{{NAME}}-cli/docs/README.md +21 -0
  60. package/assets/template/packages/{{NAME}}-cli/package.json +48 -0
  61. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +141 -0
  62. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +70 -0
  63. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +444 -0
  64. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +72 -0
  65. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +126 -0
  66. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +81 -0
  67. package/assets/template/packages/{{NAME}}-cli/src/cli.ts +36 -0
  68. package/assets/template/packages/{{NAME}}-cli/tsconfig.json +4 -0
  69. package/assets/template/scripts/ci.ts +163 -0
  70. package/assets/template/scripts/install-git-hooks.mjs +122 -0
  71. package/assets/template/scripts/install-git-hooks.test.ts +418 -0
  72. package/assets/template/scripts/lib/git-env.ts +21 -0
  73. package/assets/template/scripts/lib/release-verify.ts +431 -0
  74. package/assets/template/scripts/lib/tmp-root.ts +17 -0
  75. package/assets/template/scripts/lib/workspace.test.ts +92 -0
  76. package/assets/template/scripts/lib/workspace.ts +100 -0
  77. package/assets/template/scripts/lint-doc-examples.test.ts +129 -0
  78. package/assets/template/scripts/lint-doc-examples.ts +249 -0
  79. package/assets/template/scripts/lint-doc-references.test.ts +158 -0
  80. package/assets/template/scripts/lint-doc-references.ts +308 -0
  81. package/assets/template/scripts/lint-doc-shared.ts +59 -0
  82. package/assets/template/scripts/lint-stray-backups.test.ts +53 -0
  83. package/assets/template/scripts/lint-stray-backups.ts +39 -0
  84. package/assets/template/scripts/npm-trust-guard.test.ts +253 -0
  85. package/assets/template/scripts/npm-trust-guard.ts +533 -0
  86. package/assets/template/scripts/safe-install.ts +39 -0
  87. package/assets/template/scripts/transcription/api-harness.ts +219 -0
  88. package/assets/template/scripts/transcription/compare.ts +421 -0
  89. package/assets/template/scripts/transcription/corpus.ts +208 -0
  90. package/assets/template/scripts/transcription/fixture.ts +290 -0
  91. package/assets/template/scripts/transcription/make-mutants.ts +425 -0
  92. package/assets/template/scripts/transcription/report.ts +86 -0
  93. package/assets/template/scripts/transcription/run-conformance.ts +344 -0
  94. package/assets/template/scripts/transcription/validate-coverage.test.ts +119 -0
  95. package/assets/template/scripts/transcription/validate-coverage.ts +144 -0
  96. package/assets/template/scripts/transcription/validate.ts +366 -0
  97. package/assets/template/tsconfig.json +46 -0
  98. package/assets/template/turbo.jsonc +60 -0
  99. package/bin/create-clis +35 -0
  100. package/bin/create-clis.cmd +32 -0
  101. package/bin/create-clis.mjs +219 -0
  102. package/dist/create-clis.js +87682 -0
  103. package/dist/manifest.json +7 -0
  104. package/package.json +57 -0
@@ -0,0 +1,129 @@
1
+ /**
2
+ * 文档示例闸门单测: 采集 / 判据 / 分类各纯函数逐一断言; 集成面用临时 mini 根验证
3
+ * 「片段块判跳过」与「CLI 档旗标缺失抓得住」。
4
+ */
5
+ import { afterAll, describe, expect, test } from 'bun:test';
6
+
7
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+
10
+ import { makeTmpRoot } from './lib/tmp-root.ts';
11
+ import {
12
+ checkCliExamples,
13
+ checkTsExamples,
14
+ classifyBlock,
15
+ extractCommandTokens,
16
+ extractShellCommands,
17
+ extractTsBlocks,
18
+ isSelfContained,
19
+ parseTscErrors,
20
+ } from './lint-doc-examples.ts';
21
+
22
+ const roots: string[] = [];
23
+ function makeRoot(files: Record<string, string>): string {
24
+ const root = makeTmpRoot('doc-examples-');
25
+ roots.push(root);
26
+ for (const [rel, content] of Object.entries(files)) {
27
+ const abs = join(root, rel);
28
+ mkdirSync(dirname(abs), { recursive: true });
29
+ writeFileSync(abs, content);
30
+ }
31
+ return root;
32
+ }
33
+ afterAll(() => {
34
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
35
+ });
36
+
37
+ describe('extractTsBlocks', () => {
38
+ test('取出 ```ts 块并给出内容首行行号 (1 起)', () => {
39
+ const text = ['# 标题', '', '```ts', 'const a = 1;', '```', '尾'].join(
40
+ '\n',
41
+ );
42
+ const blocks = extractTsBlocks(text, 'x.md');
43
+ expect(blocks).toHaveLength(1);
44
+ expect(blocks[0]!.startLine).toBe(4);
45
+ expect(blocks[0]!.content).toBe('const a = 1;');
46
+ });
47
+ });
48
+
49
+ describe('isSelfContained', () => {
50
+ test('行首 import 视为自足; 片段块不算', () => {
51
+ expect(isSelfContained("import { a } from 'x';")).toBe(true);
52
+ expect(isSelfContained('// import 在注释里\nconst a = b;')).toBe(false);
53
+ });
54
+ });
55
+
56
+ describe('extractShellCommands', () => {
57
+ test('只收 shell 块内以 {{BIN_NAME}} 起首的非注释行, 前缀精确', () => {
58
+ const text = [
59
+ '```shell',
60
+ '# 注释跳过',
61
+ '{{BIN_NAME}} --yes',
62
+ '{{BIN_NAME}}-rs --target x',
63
+ 'bunx {{BIN_NAME}}',
64
+ '```',
65
+ '{{BIN_NAME}} 块外不算',
66
+ ].join('\n');
67
+ expect(extractShellCommands(text)).toEqual(['{{BIN_NAME}} --yes']);
68
+ });
69
+ });
70
+
71
+ describe('extractCommandTokens', () => {
72
+ test('旗标去 = 值; 第一个位置参数当子命令; 旗标的值不采集', () => {
73
+ expect(extractCommandTokens('{{BIN_NAME}} --yes --force')).toEqual([
74
+ '--yes',
75
+ '--force',
76
+ ]);
77
+ expect(
78
+ extractCommandTokens('{{BIN_NAME}} --exclude my-kits --exclude url'),
79
+ ).toEqual(['--exclude']);
80
+ expect(extractCommandTokens('{{BIN_NAME}} config')).toEqual(['config']);
81
+ expect(extractCommandTokens('{{BIN_NAME}}')).toEqual([]);
82
+ });
83
+ });
84
+
85
+ describe('parseTscErrors + classifyBlock', () => {
86
+ test('解析 block 序号与错误码, 分类干净 / 片段 / 真错', () => {
87
+ const output = [
88
+ "block-0.ts(3,5): error TS2304: Cannot find name 'panel'.",
89
+ "block-1.ts(3,5): error TS2345: Argument of type 'string' is not assignable.",
90
+ "block-1.ts(9,1): error TS2304: Cannot find name 'x'.",
91
+ ].join('\n');
92
+ const perBlock = parseTscErrors(output);
93
+ expect(classifyBlock(perBlock.get(0))).toBe('fragment');
94
+ expect(classifyBlock(perBlock.get(1))).toBe('real');
95
+ expect(classifyBlock(perBlock.get(2))).toBe('clean');
96
+ expect(classifyBlock(undefined)).toBe('clean');
97
+ });
98
+ });
99
+
100
+ describe('checkTsExamples 集成', () => {
101
+ test('片段块 (引用块外上下文) 判跳过而非断裂', () => {
102
+ const root = makeRoot({
103
+ 'tsconfig.json': '{"compilerOptions":{"noEmit":true}}',
104
+ 'docs/a.md': "```ts\nimport { nope } from 'nowhere-pkg';\nnope();\n```\n",
105
+ });
106
+ const { real, fragments } = checkTsExamples(root);
107
+ expect(real).toEqual([]);
108
+ expect(fragments).toHaveLength(1);
109
+ }, 120000);
110
+ });
111
+
112
+ describe('checkCliExamples 集成', () => {
113
+ test('文档写了 --help 里没有的旗标即抓出; 文档漏登记不误报', () => {
114
+ const root = makeRoot({
115
+ 'packages/{{NAME}}-cli/src/cli.ts':
116
+ "console.log(['{{BIN_NAME}} --yes 执行删除', '{{BIN_NAME}} config 查看配置'].join('\\n'));\n",
117
+ 'README.md': [
118
+ '```shell',
119
+ '{{BIN_NAME}} --yes',
120
+ '{{BIN_NAME}} --nope',
121
+ '{{BIN_NAME}} config',
122
+ '```',
123
+ ].join('\n'),
124
+ });
125
+ const missing = checkCliExamples(root);
126
+ expect(missing).toHaveLength(1);
127
+ expect(missing[0]).toContain('--nope');
128
+ }, 60000);
129
+ });
@@ -0,0 +1,249 @@
1
+ /**
2
+ * 文档示例闸门: ts 代码块的真实类型校验 + shell 块的 CLI 面核对。
3
+ *
4
+ * 动机: 2026-09-30 漂移复审实测抓到文档示例与真实签名不符 (api-surface 的
5
+ * `isSuccessOutcome` 片段入参类型错误, 照抄编译报 TS2345), 属「只有人工审计才能发现」
6
+ * 的类别; 示例可编译性是确定性事实, 故落为闸门 (镜像实现对: fiu-kits 的 lint-doc-examples)。
7
+ *
8
+ * 两档:
9
+ * - 类型档: 采集「自足」ts 块 (判据: 块内出现行首 import 语句), 拼成临时 tsc 工程对 API 包
10
+ * 真实类型校验 (临时工程 extends 仓库根 tsconfig, paths 直连源码单源; typeRoots 指回仓
11
+ * 内 @types, 临时目录解析不到 bun 类型实测 TS2688)。报错分类: 全为「名字未找到」类
12
+ * (TS2304 等) 的块判为片段 (依赖上文块, 不做跨块拼接), 打印 INFO 跳过; 含其他错误
13
+ * (TS2345 签名不符 / TS2339 成员不存在等) 的块判为真断裂, 红灯。
14
+ * - CLI 档: 采集 shell 块内以 `{{BIN_NAME}}` 开头的命令, 提取旗标与子命令, 对照 `--help`
15
+ * 输出逐一核对存在性 (抓「新增旗标漏登记进文档 / 文档写了不存在的旗标」)。
16
+ *
17
+ * 用法: bun scripts/lint-doc-examples.ts
18
+ * 退出码: 0 全绿; 1 存在断裂。
19
+ */
20
+ import { spawnSync } from 'node:child_process';
21
+ import { readFileSync, rmSync, writeFileSync } from 'node:fs';
22
+ import { join } from 'node:path';
23
+
24
+ import { makeTmpRoot } from './lib/tmp-root.ts';
25
+ import { REPO_ROOT, walkFiles } from './lint-doc-shared.ts';
26
+
27
+ const CLI_ENTRY = 'packages/{{NAME}}-cli/src/cli.ts';
28
+
29
+ /** 一个被采集到的 ts 代码块 */
30
+ export interface TsBlock {
31
+ file: string;
32
+ /** 块内容首行的行号 (1 起) */
33
+ startLine: number;
34
+ content: string;
35
+ }
36
+
37
+ /** 提取全文的 ```ts 块 (闭合围栏以 ``` 收尾; startLine 指向内容首行) */
38
+ export function extractTsBlocks(content: string, file = '<inline>'): TsBlock[] {
39
+ const blocks: TsBlock[] = [];
40
+ const lines = content.split('\n');
41
+ let start: number | null = null;
42
+ for (let i = 0; i < lines.length; i += 1) {
43
+ if (start === null && /^```ts\s*$/.test(lines[i]!)) {
44
+ start = i + 1;
45
+ continue;
46
+ }
47
+ if (start !== null && /^```\s*$/.test(lines[i]!)) {
48
+ blocks.push({
49
+ file,
50
+ startLine: start + 1,
51
+ content: lines.slice(start, i).join('\n'),
52
+ });
53
+ start = null;
54
+ }
55
+ }
56
+ return blocks;
57
+ }
58
+
59
+ /** 自足判据: 块内出现行首 import 语句 (片段块依赖上文变量, 不参与编译) */
60
+ export function isSelfContained(block: string): boolean {
61
+ return /^import\b/m.test(block);
62
+ }
63
+
64
+ /** 提取 shell 块中以 {{BIN_NAME}} 开头的命令行 (跳过注释行) */
65
+ export function extractShellCommands(content: string): string[] {
66
+ const commands: string[] = [];
67
+ const lines = content.split('\n');
68
+ let inShell = false;
69
+ for (const line of lines) {
70
+ if (/^```shell\s*$/.test(line)) {
71
+ inShell = true;
72
+ continue;
73
+ }
74
+ if (inShell && /^```\s*$/.test(line)) {
75
+ inShell = false;
76
+ continue;
77
+ }
78
+ if (!inShell) continue;
79
+ const trimmed = line.trim();
80
+ if (trimmed.startsWith('#') || !/^{{BIN_NAME}}(\s|$)/.test(trimmed)) continue;
81
+ commands.push(trimmed);
82
+ }
83
+ return commands;
84
+ }
85
+
86
+ /** 从一条命令提取待核对 token: --旗标 (去掉 =值, 去重) 与首个位置参数 (子命令) */
87
+ export function extractCommandTokens(command: string): string[] {
88
+ const tokens: string[] = [];
89
+ const parts = command.split(/\s+/).slice(1);
90
+ for (const part of parts) {
91
+ if (part.startsWith('-')) {
92
+ tokens.push(part.split('=')[0]!);
93
+ continue;
94
+ }
95
+ // 位置参数: 只认第一个 (子命令); 其余是旗标的值 (如 --exclude my-kits 的 my-kits)
96
+ if (tokens.length === 0) tokens.push(part);
97
+ }
98
+ return [...new Set(tokens)];
99
+ }
100
+
101
+ /** 解析 tsc 输出为「块序号 -> 错误码集合」 */
102
+ export function parseTscErrors(output: string): Map<number, Set<string>> {
103
+ const perBlock = new Map<number, Set<string>>();
104
+ for (const line of output.split('\n')) {
105
+ const m = line.match(/block-(\d+)\.ts\(\d+,\d+\): error (TS\d+)/);
106
+ if (!m) continue;
107
+ const idx = Number(m[1]);
108
+ const set = perBlock.get(idx) ?? new Set<string>();
109
+ set.add(m[2]!);
110
+ perBlock.set(idx, set);
111
+ }
112
+ return perBlock;
113
+ }
114
+
115
+ /** 「名字 / 上下文未找到」类错误码: 全由此类构成的块判为片段 (依赖上文块) */
116
+ const FRAGMENT_ERROR_CODES: ReadonlySet<string> = new Set([
117
+ 'TS2304', // Cannot find name
118
+ 'TS2552', // Cannot find name (did you mean ...)
119
+ 'TS18046', // 'x' is of type 'unknown' (收窄所需的守卫未定义时连带)
120
+ 'TS2580', // Cannot find name 'require'
121
+ 'TS2503', // Cannot find namespace
122
+ 'TS2307', // Cannot find module (片段引用未随块给出的模块)
123
+ ]);
124
+
125
+ /** 分类一个块的错误集合: 'clean' | 'fragment' | 'real' */
126
+ export function classifyBlock(
127
+ codes: Set<string> | undefined,
128
+ ): 'clean' | 'fragment' | 'real' {
129
+ if (codes === undefined || codes.size === 0) return 'clean';
130
+ return [...codes].every((code) => FRAGMENT_ERROR_CODES.has(code))
131
+ ? 'fragment'
132
+ : 'real';
133
+ }
134
+
135
+ /** 类型档: 采集自足块 → 临时工程编译 → 返回 (真断裂条目, 片段 INFO 列表) */
136
+ export function checkTsExamples(root: string = REPO_ROOT): {
137
+ real: string[];
138
+ fragments: string[];
139
+ } {
140
+ const blocks: TsBlock[] = [];
141
+ for (const file of walkFiles(root, ['.md'])) {
142
+ for (const block of extractTsBlocks(
143
+ readFileSync(join(root, file), 'utf8'),
144
+ file,
145
+ )) {
146
+ if (isSelfContained(block.content)) blocks.push(block);
147
+ }
148
+ }
149
+ if (blocks.length === 0) return { real: [], fragments: [] };
150
+
151
+ // 临时工程: extends 仓库根 tsconfig (paths 直连单源), typeRoots 指回仓内 @types
152
+ const tmp = makeTmpRoot('doc-examples-');
153
+ try {
154
+ for (const [index, block] of blocks.entries()) {
155
+ writeFileSync(join(tmp, `block-${index}.ts`), `${block.content}\n`);
156
+ }
157
+ writeFileSync(
158
+ join(tmp, 'tsconfig.json'),
159
+ `${JSON.stringify(
160
+ {
161
+ extends: join(root, 'tsconfig.json'),
162
+ compilerOptions: {
163
+ noEmit: true,
164
+ typeRoots: [join(root, 'node_modules', '@types')],
165
+ },
166
+ include: ['./*.ts'],
167
+ },
168
+ null,
169
+ 2,
170
+ )}\n`,
171
+ );
172
+ const result = spawnSync(
173
+ 'bunx',
174
+ ['tsc', '-p', join(tmp, 'tsconfig.json')],
175
+ { cwd: root, encoding: 'utf8' },
176
+ );
177
+ const perBlock = parseTscErrors(`${result.stdout ?? ''}`);
178
+ const real: string[] = [];
179
+ const fragments: string[] = [];
180
+ for (const [index, block] of blocks.entries()) {
181
+ const kind = classifyBlock(perBlock.get(index));
182
+ const at = `${block.file}:${block.startLine}`;
183
+ if (kind === 'fragment') {
184
+ fragments.push(
185
+ `${at} (引用块外上下文, ${[...(perBlock.get(index) ?? [])].join('/')})`,
186
+ );
187
+ } else if (kind === 'real') {
188
+ const detail = `${result.stdout ?? ''}`
189
+ .split('\n')
190
+ .filter((line) => line.includes(`block-${index}.ts(`))
191
+ .map((line) => line.replace(/^.*block-\d+\.ts/, '行内'))
192
+ .join('; ');
193
+ real.push(`${at} :: ${detail}`);
194
+ }
195
+ }
196
+ return { real, fragments };
197
+ } finally {
198
+ rmSync(tmp, { recursive: true, force: true });
199
+ }
200
+ }
201
+
202
+ /** CLI 档: 采集 README 类 shell 块的 {{BIN_NAME}} 命令, 对照 --help 核对旗标与子命令 */
203
+ export function checkCliExamples(root: string = REPO_ROOT): string[] {
204
+ const missing: string[] = [];
205
+ const help = spawnSync('bun', [join(root, CLI_ENTRY), '--help'], {
206
+ cwd: root,
207
+ encoding: 'utf8',
208
+ });
209
+ if (help.status !== 0) {
210
+ return [`CLI --help 执行失败 (exit ${String(help.status)}), 无法核对示例`];
211
+ }
212
+ const helpText = help.stdout ?? '';
213
+ for (const file of walkFiles(root, ['.md'])) {
214
+ const content = readFileSync(join(root, file), 'utf8');
215
+ for (const command of extractShellCommands(content)) {
216
+ for (const token of extractCommandTokens(command)) {
217
+ if (!helpText.includes(token)) {
218
+ missing.push(
219
+ `${file} :: 命令 "${command}" 的 ${token} 在 --help 输出中不存在`,
220
+ );
221
+ }
222
+ }
223
+ }
224
+ }
225
+ return missing;
226
+ }
227
+
228
+ /** 主流程: 两档都跑, 断裂即红灯 */
229
+ function main(): void {
230
+ const { real, fragments } = checkTsExamples();
231
+ const missingCli = checkCliExamples();
232
+ if (fragments.length > 0) {
233
+ process.stdout.write(
234
+ `类型档片段跳过 (依赖块外上下文, 非断裂): ${fragments.length} 块\n`,
235
+ );
236
+ for (const fragment of fragments) process.stdout.write(` ${fragment}\n`);
237
+ }
238
+ if (real.length === 0 && missingCli.length === 0) {
239
+ process.stdout.write('文档示例闸门全绿 ✓ (类型档 / CLI 档)\n');
240
+ return;
241
+ }
242
+ process.stderr.write('文档示例闸门检出断裂:\n');
243
+ for (const item of real) process.stderr.write(` [类型档] ${item}\n`);
244
+ for (const item of missingCli) process.stderr.write(` [CLI 档] ${item}\n`);
245
+ process.exitCode = 1;
246
+ }
247
+
248
+ // 仅作为入口执行时跑主流程 (被 import 时不执行, 供测试)
249
+ if (import.meta.main) main();
@@ -0,0 +1,158 @@
1
+ /**
2
+ * 文档引用闸门单测: 在临时根上建 mini 文档树, 对三类断裂逐一验证「抓得住」,
3
+ * 对保守口径 (裸 § 跳过 / 代码块内跳过 / ADR 豁免词) 逐一验证「不误报」。
4
+ */
5
+ import { afterAll, describe, expect, test } from 'bun:test';
6
+
7
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
+ import { dirname, join } from 'node:path';
9
+
10
+ import { makeTmpRoot } from './lib/tmp-root.ts';
11
+ import {
12
+ collectAdrNumbers,
13
+ collectSectionNumbers,
14
+ findAllIssues,
15
+ resolveSectionTarget,
16
+ stripFencedCode,
17
+ } from './lint-doc-references.ts';
18
+
19
+ /** 临时根 (跟随套件惯例落 ~/tmp; 一测一根, 结束后整体清理) */
20
+ const roots: string[] = [];
21
+ function makeRoot(files: Record<string, string>): string {
22
+ const root = makeTmpRoot('doc-refs-');
23
+ roots.push(root);
24
+ for (const [rel, content] of Object.entries(files)) {
25
+ const abs = join(root, rel);
26
+ mkdirSync(dirname(abs), { recursive: true });
27
+ writeFileSync(abs, content);
28
+ }
29
+ mkdirSync(join(root, 'docs', 'adrs'), { recursive: true });
30
+ writeFileSync(
31
+ join(root, 'docs', 'adrs', '0001-first.md'),
32
+ '# ADR 0001: 首篇\n',
33
+ );
34
+ return root;
35
+ }
36
+ afterAll(() => {
37
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
38
+ });
39
+
40
+ describe('stripFencedCode', () => {
41
+ test('围栏内行置空, 围栏外与行数原样保留', () => {
42
+ const input = ['外一', '```ts', '](不存在.md)', '```', '外二'].join('\n');
43
+ const out = stripFencedCode(input).split('\n');
44
+ expect(out).toHaveLength(5);
45
+ expect(out[0]).toBe('外一');
46
+ expect(out[2]).toBe('');
47
+ expect(out[4]).toBe('外二');
48
+ });
49
+ });
50
+
51
+ describe('collectSectionNumbers', () => {
52
+ test('收集 ## N. / ### N.M / #### N.M.K 编号', () => {
53
+ const numbers = collectSectionNumbers(
54
+ ['## 3. 契约', '### 3.4 平移表', '#### 3.4.1 细则', '### 无编号'].join(
55
+ '\n',
56
+ ),
57
+ );
58
+ expect([...numbers].sort()).toEqual(['3', '3.4', '3.4.1']);
59
+ });
60
+ });
61
+
62
+ describe('相对链接', () => {
63
+ test('存在即过, 不存在抓出 (file:line 定位)', () => {
64
+ const root = makeRoot({
65
+ 'docs/a.md': '见 [乙](b.md) 与 [缺](missing.md)。\n',
66
+ 'docs/b.md': '# 乙\n',
67
+ });
68
+ const issues = findAllIssues(root).filter((f) => f.kind === 'link');
69
+ expect(issues).toHaveLength(1);
70
+ expect(issues[0]!.file).toBe('docs/a.md');
71
+ expect(issues[0]!.line).toBe(1);
72
+ expect(issues[0]!.reference).toBe('missing.md');
73
+ });
74
+
75
+ test('根相对 (/x.md) 按仓库根解析; 外链与纯锚点跳过', () => {
76
+ const root = makeRoot({
77
+ 'docs/a.md':
78
+ '[根](../root-ok.md) [外](https://example.com/x.md) [锚](#局部) [也外](mailto:x@y.z)\n',
79
+ 'root-ok.md': '# 根\n',
80
+ });
81
+ expect(findAllIssues(root).filter((f) => f.kind === 'link')).toHaveLength(
82
+ 0,
83
+ );
84
+ });
85
+
86
+ test('围栏代码块内的链接不参与判定', () => {
87
+ const root = makeRoot({
88
+ 'docs/a.md': '```md\n[缺](missing.md)\n```\n',
89
+ });
90
+ expect(findAllIssues(root).filter((f) => f.kind === 'link')).toHaveLength(
91
+ 0,
92
+ );
93
+ });
94
+ });
95
+
96
+ describe('§章节引用', () => {
97
+ test('目标文档存在节号即过; 无该节号抓出', () => {
98
+ const root = makeRoot({
99
+ 'docs/a.md': '见 api-surface.md §3.4 与 api-surface.md §9.9。\n',
100
+ 'docs/api-surface.md': '## 3. 契约\n### 3.4 平移表\n',
101
+ });
102
+ const issues = findAllIssues(root).filter((f) => f.kind === 'section');
103
+ expect(issues).toHaveLength(1);
104
+ expect(issues[0]!.reference).toBe('§9.9');
105
+ });
106
+
107
+ test('子节存在视为命中 (§3 指向的节内有 3.4)', () => {
108
+ const root = makeRoot({
109
+ 'docs/a.md': '见 api-surface.md §3。\n',
110
+ 'docs/api-surface.md': '## 3. 契约\n### 3.4 平移表\n',
111
+ });
112
+ expect(
113
+ findAllIssues(root).filter((f) => f.kind === 'section'),
114
+ ).toHaveLength(0);
115
+ });
116
+
117
+ test('裸 § 无目标线索时跳过 (保守口径, 不误报)', () => {
118
+ const root = makeRoot({
119
+ 'docs/a.md': '见 §9 「取舍」 与 设计文档 §7。\n',
120
+ });
121
+ expect(
122
+ findAllIssues(root).filter((f) => f.kind === 'section'),
123
+ ).toHaveLength(0);
124
+ });
125
+
126
+ test('别名解析: 窗口内出现已知别名即锁定目标文档', () => {
127
+ const line = '见「可编程 API 面」§3.4 的';
128
+ expect(
129
+ resolveSectionTarget(line, line.indexOf('§'), 'docs', new Map()),
130
+ ).toBe('packages/{{NAME}}/docs/designs/api-surface.md');
131
+ });
132
+ });
133
+
134
+ describe('ADR 编号', () => {
135
+ test('存在的编号过, 幽灵编号抓出; 豁免词行跳过', () => {
136
+ const root = makeRoot({
137
+ 'docs/a.md': '见 ADR 0001 与 ADR 0099。\n',
138
+ 'docs/b.md': 'ADR 0088 尚未创建, 按历史约定处理。\n',
139
+ });
140
+ expect([...collectAdrNumbers(root)]).toEqual(['0001']);
141
+ const issues = findAllIssues(root).filter((f) => f.kind === 'adr');
142
+ expect(issues).toHaveLength(1);
143
+ expect(issues[0]!.file).toBe('docs/a.md');
144
+ expect(issues[0]!.reference).toBe('ADR 0099');
145
+ });
146
+
147
+ test('两级查找面: 包级 ADR (packages/*/docs/adrs) 同样被收集与校验', () => {
148
+ const root = makeRoot({
149
+ 'docs/a.md': '见 ADR 0021 与 ADR 0022。\n',
150
+ 'packages/x/docs/adrs/0021-in-package.md': '# ADR 0021: 包级\n',
151
+ });
152
+ // 夹具自带 docs/adrs/0001-first.md, 与包级 0021 一并被收集
153
+ expect([...collectAdrNumbers(root)]).toEqual(['0001', '0021']);
154
+ const issues = findAllIssues(root).filter((f) => f.kind === 'adr');
155
+ expect(issues).toHaveLength(1);
156
+ expect(issues[0]!.reference).toBe('ADR 0022');
157
+ });
158
+ });