create-clis 1.0.0 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (87) hide show
  1. package/README.md +22 -14
  2. package/README.zh-CN.md +22 -14
  3. package/assets/manifest.json +7 -2
  4. package/assets/template/.github/ISSUE_TEMPLATE/bug_report.yml +15 -29
  5. package/assets/template/.github/ISSUE_TEMPLATE/feature_request.yml +6 -12
  6. package/assets/template/.github/PULL_REQUEST_TEMPLATE.md +3 -3
  7. package/assets/template/.github/workflows/ci.yml +69 -7
  8. package/assets/template/.github/workflows/release.yml +23 -23
  9. package/assets/template/.gitignorerc.json +1 -8
  10. package/assets/template/.oxlintrc.json +1 -6
  11. package/assets/template/.prettierignore +0 -1
  12. package/assets/template/.releaserc.json +6 -1
  13. package/assets/template/.vscode/launch.json +1 -1
  14. package/assets/template/.vscode/settings.json +1 -0
  15. package/assets/template/.vscode/tasks.json +45 -0
  16. package/assets/template/AGENTS.md +4 -4
  17. package/assets/template/CONTRIBUTING.md +6 -4
  18. package/assets/template/CONTRIBUTING.zh-CN.md +6 -4
  19. package/assets/template/_gitignore +7 -405
  20. package/assets/template/bunfig.toml +2 -11
  21. package/assets/template/docs/README.md +6 -6
  22. package/assets/template/docs/adrs/README.md +4 -2
  23. package/assets/template/docs/development.md +15 -9
  24. package/assets/template/lefthook.yml +20 -30
  25. package/assets/template/package.json +5 -6
  26. package/assets/template/packages/{{NAME}}/README.md +4 -4
  27. package/assets/template/packages/{{NAME}}/README.zh-CN.md +2 -2
  28. package/assets/template/packages/{{NAME}}/package.json +3 -1
  29. package/assets/template/packages/{{NAME}}/scripts/build.ts +50 -14
  30. package/assets/template/packages/{{NAME}}/scripts/verify-release.test.ts +140 -15
  31. package/assets/template/packages/{{NAME}}/scripts/verify-release.ts +27 -14
  32. package/assets/template/packages/{{NAME}}/tsconfig.build.json +1 -1
  33. package/assets/template/packages/{{NAME}}-cli/README.md +6 -6
  34. package/assets/template/packages/{{NAME}}-cli/README.zh-CN.md +2 -2
  35. package/assets/template/packages/{{NAME}}-cli/bin/bunfig.toml +3 -0
  36. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}} +43 -21
  37. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.cmd +8 -17
  38. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.d.mts +6 -3
  39. package/assets/template/packages/{{NAME}}-cli/bin/{{BIN_NAME}}.mjs +189 -107
  40. package/assets/template/packages/{{NAME}}-cli/package.json +3 -2
  41. package/assets/template/packages/{{NAME}}-cli/scripts/release-artifact.ts +24 -73
  42. package/assets/template/packages/{{NAME}}-cli/scripts/release.fixtures.ts +8 -3
  43. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.test.ts +16 -10
  44. package/assets/template/packages/{{NAME}}-cli/scripts/verify-release.ts +8 -52
  45. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.test.ts +3 -3
  46. package/assets/template/packages/{{NAME}}-cli/scripts/write-dist-manifest.ts +8 -68
  47. package/assets/template/scripts/ci.ts +285 -64
  48. package/assets/template/scripts/install-git-hooks.mjs +10 -0
  49. package/assets/template/scripts/install-git-hooks.test.ts +1 -1
  50. package/assets/template/scripts/lib/npm-trust-parse.ts +169 -0
  51. package/assets/template/scripts/lib/release-cli.ts +299 -0
  52. package/assets/template/scripts/lib/release-verify.ts +148 -15
  53. package/assets/template/scripts/lib/workspace.test.ts +63 -1
  54. package/assets/template/scripts/lib/workspace.ts +132 -42
  55. package/assets/template/scripts/lint-dependency-direction.test.ts +131 -0
  56. package/assets/template/scripts/lint-dependency-direction.ts +130 -0
  57. package/assets/template/scripts/lint-doc-examples.test.ts +45 -9
  58. package/assets/template/scripts/lint-doc-examples.ts +227 -50
  59. package/assets/template/scripts/lint-doc-references.test.ts +36 -0
  60. package/assets/template/scripts/lint-doc-references.ts +142 -57
  61. package/assets/template/scripts/lint-doc-shared.ts +26 -23
  62. package/assets/template/scripts/lint-stray-backups.test.ts +3 -1
  63. package/assets/template/scripts/lint-stray-backups.ts +7 -3
  64. package/assets/template/scripts/npm-trust-guard.test.ts +56 -8
  65. package/assets/template/scripts/npm-trust-guard.ts +116 -200
  66. package/assets/template/scripts/safe-install.ts +28 -23
  67. package/assets/template/scripts/transcription/api-harness.ts +28 -206
  68. package/assets/template/scripts/transcription/compare.test.ts +84 -0
  69. package/assets/template/scripts/transcription/compare.ts +4 -4
  70. package/assets/template/scripts/transcription/corpus.ts +9 -3
  71. package/assets/template/scripts/transcription/fixture.ts +2 -4
  72. package/assets/template/scripts/transcription/make-mutants.ts +116 -37
  73. package/assets/template/scripts/transcription/run-conformance.ts +57 -34
  74. package/assets/template/scripts/transcription/validate-coverage.test.ts +11 -14
  75. package/assets/template/scripts/transcription/validate-coverage.ts +8 -10
  76. package/assets/template/scripts/transcription/validate.ts +18 -3
  77. package/assets/template/tsconfig.json +2 -20
  78. package/assets/template/turbo.jsonc +7 -52
  79. package/bin/bunfig.toml +3 -0
  80. package/bin/create-clis.mjs +165 -104
  81. package/dist/create-clis.js +48 -87681
  82. package/dist/manifest.json +3 -3
  83. package/package.json +9 -5
  84. package/assets/template/packages/{{NAME}}/docs/README.md +0 -21
  85. package/assets/template/packages/{{NAME}}-cli/docs/README.md +0 -21
  86. package/bin/create-clis +0 -35
  87. package/bin/create-clis.cmd +0 -32
@@ -1,13 +1,15 @@
1
1
  /**
2
2
  * 工作区坐标派生 (单一事实来源: 根 package.json 的 workspaces)。
3
3
  *
4
- * 派生规则 (与「依赖方向纪律」同构): **CLI 包** = 带 `bin` 且其 devDependencies 引用某个无
5
- * `bin` 仓内包的包; **API 包** = 被它引用的那个无 `bin` 包 (工具 → 库 单向唯一确定)。仓内可有
6
- * 多个带 `bin` 的工具包 (如生成器包), 主产品线以依赖关系锚定; 包目录改名或包名变更时, 依赖
7
- * 本模块的脚本 (ci.ts / make-mutants.ts) 零修改。
4
+ * 派生规则 (与「依赖方向纪律」同构):
5
+ * - **双包产品对 (ProductPair)**: 带 `bin` 的 CLI 包, 其 dependencies 或 devDependencies
6
+ * 引用某个仓内无 `bin` 包 (API 包), 按依赖关系单向锚定。
7
+ * - `listWorkspacePackages` 按目录字典序稳定输出, 消除跨 OS readdir 顺序差异。
8
+ * - 当仓内同时存在多个双包产品时, 调用方应使用 `resolveProductPairs`
9
+ * 或为 `resolveCliAndApi` 传入明确的产品包名/目录提示, 不靠数组首项碰运气。
8
10
  *
9
- * 已知的单点同步 (无法运行时派生): `tsconfig.json` 的 paths 是静态配置, 改包名时需在此一处
10
- * 手动同步 (见 docs/designs/collection-relocation.md 的重建清单)。
11
+ * 已知的单点同步 (无法运行时派生): `tsconfig.json` 的 paths 是静态配置, 新增 API 包或
12
+ * 改包名时需在此一处手动同步。
11
13
  */
12
14
  import { existsSync, readFileSync, readdirSync } from 'node:fs';
13
15
  import { join } from 'node:path';
@@ -22,7 +24,35 @@ export interface WorkspacePackage {
22
24
  manifest: Record<string, unknown>;
23
25
  }
24
26
 
25
- /** 读根 package.json 的 workspaces 并展开为包清单 (支持 'dir/*' 形态; 其它形态显式报错) */
27
+ /** 一组双包产品: CLI 薄壳包 + 所依赖的仓内 API 包 */
28
+ export interface ProductPair {
29
+ cli: WorkspacePackage;
30
+ api: WorkspacePackage;
31
+ }
32
+
33
+ /** 提取包清单里的全部依赖名 (dependencies + devDependencies) */
34
+ export function listDeclaredDeps(pkg: WorkspacePackage): string[] {
35
+ const deps = pkg.manifest.dependencies;
36
+ const devDeps = pkg.manifest.devDependencies;
37
+ const names = new Set<string>();
38
+ if (deps !== null && typeof deps === 'object' && !Array.isArray(deps)) {
39
+ for (const key of Object.keys(deps as Record<string, unknown>)) {
40
+ names.add(key);
41
+ }
42
+ }
43
+ if (
44
+ devDeps !== null &&
45
+ typeof devDeps === 'object' &&
46
+ !Array.isArray(devDeps)
47
+ ) {
48
+ for (const key of Object.keys(devDeps as Record<string, unknown>)) {
49
+ names.add(key);
50
+ }
51
+ }
52
+ return [...names].sort();
53
+ }
54
+
55
+ /** 读根 package.json 的 workspaces 并展开为包清单 (按目录字典序稳定输出) */
26
56
  export function listWorkspacePackages(root: string): WorkspacePackage[] {
27
57
  const rootManifest = JSON.parse(
28
58
  readFileSync(join(root, 'package.json'), 'utf8'),
@@ -40,9 +70,10 @@ export function listWorkspacePackages(root: string): WorkspacePackage[] {
40
70
  );
41
71
  }
42
72
  const parent = match[1]!;
43
- for (const entry of readdirSync(join(root, parent), {
73
+ const entries = readdirSync(join(root, parent), {
44
74
  withFileTypes: true,
45
- })) {
75
+ }).sort((a, b) => a.name.localeCompare(b.name));
76
+ for (const entry of entries) {
46
77
  if (!entry.isDirectory()) continue;
47
78
  const dir = `${parent}/${entry.name}`;
48
79
  const manifestPath = join(root, dir, 'package.json');
@@ -55,46 +86,105 @@ export function listWorkspacePackages(root: string): WorkspacePackage[] {
55
86
  packages.push({ name: manifest.name, dir, manifest });
56
87
  }
57
88
  }
58
- return packages;
89
+ return packages.sort((a, b) => a.dir.localeCompare(b.dir));
59
90
  }
60
91
 
61
92
  /**
62
- * 派生主产品两包: 带 bin 且依赖某个无 bin 仓内包的, 是主 CLI 包; 被它引用的无 bin 包是 API 包。
63
- * (判据依据: 「依赖方向纪律」工具 → 库单向; 仓内可有多个带 bin 的工具包, 主产品线以依赖关系锚定。)
93
+ * 派生仓内全部「CLI → API」双包产品对 (稳定排序)。
94
+ * 判据: CLI 包带 `bin`, 且在 dependencies 或 devDependencies 中引用某个专属产品 API 包 (无 `bin`)。
95
+ * 跨 CLI 共享私有库 (`clisRole: 'shared-lib'` 或被多个 CLI 共同依赖的 `private: true` 无 bin 库)
96
+ * 不视为单一产品的 API 主包; 存在多候选时优先匹配对称命名 (`<api>-cli`)。
64
97
  */
65
- export function resolveCliAndApi(root: string): {
66
- cli: WorkspacePackage;
67
- api: WorkspacePackage;
68
- } {
98
+ export function resolveProductPairs(root: string): ProductPair[] {
69
99
  const packages = listWorkspacePackages(root);
70
- const cli = packages.find((pkg) => {
71
- if (pkg.manifest.bin === undefined) return false;
72
- const devDeps = (pkg.manifest.devDependencies ?? {}) as Record<
73
- string,
74
- unknown
75
- >;
76
- return packages.some(
77
- (other) =>
78
- other !== pkg &&
79
- other.manifest.bin === undefined &&
80
- other.name in devDeps,
100
+ const byName = new Map(packages.map((pkg) => [pkg.name, pkg]));
101
+ const cliInDegree = new Map<string, number>();
102
+
103
+ for (const pkg of packages) {
104
+ if (pkg.manifest.bin === undefined) continue;
105
+ for (const depName of listDeclaredDeps(pkg)) {
106
+ const target = byName.get(depName);
107
+ if (
108
+ target !== undefined &&
109
+ target !== pkg &&
110
+ target.manifest.bin === undefined
111
+ ) {
112
+ cliInDegree.set(target.name, (cliInDegree.get(target.name) ?? 0) + 1);
113
+ }
114
+ }
115
+ }
116
+
117
+ const isSharedLib = (pkg: WorkspacePackage): boolean => {
118
+ if (pkg.manifest.clisRole === 'shared-lib') return true;
119
+ return (
120
+ pkg.manifest.private === true && (cliInDegree.get(pkg.name) ?? 0) > 1
121
+ );
122
+ };
123
+
124
+ const pairs: ProductPair[] = [];
125
+ for (const pkg of packages) {
126
+ if (pkg.manifest.bin === undefined) continue;
127
+ const candidates: WorkspacePackage[] = [];
128
+ for (const depName of listDeclaredDeps(pkg)) {
129
+ const target = byName.get(depName);
130
+ if (
131
+ target !== undefined &&
132
+ target !== pkg &&
133
+ target.manifest.bin === undefined &&
134
+ !isSharedLib(target)
135
+ ) {
136
+ candidates.push(target);
137
+ }
138
+ }
139
+ if (candidates.length === 0) continue;
140
+ const symmetric = candidates.find(
141
+ (target) =>
142
+ pkg.name === `${target.name}-cli` || pkg.dir === `${target.dir}-cli`,
81
143
  );
82
- });
83
- if (cli === undefined) {
144
+ pairs.push({ cli: pkg, api: symmetric ?? candidates[0]! });
145
+ }
146
+ return pairs;
147
+ }
148
+
149
+ /**
150
+ * 派生指定 (或唯一) 产品的 CLI + API 两包。
151
+ * - 未传 productHint 且仓内仅有一对时, 直接返回该唯一对 (兼容单产品模板仓);
152
+ * - 仓内存在多对双包产品时, 必须通过 productHint (CLI 或 API 的包名或相对目录) 显式指定,
153
+ * 防跨 OS 目录序或静默命中错误产品。
154
+ */
155
+ export function resolveCliAndApi(
156
+ root: string,
157
+ productHint?: string,
158
+ ): ProductPair {
159
+ const pairs = resolveProductPairs(root);
160
+ if (pairs.length === 0) {
84
161
  throw new Error('未找到主 CLI 包 (带 bin 且依赖仓内无 bin 包)');
85
162
  }
86
- const devDeps = (cli.manifest.devDependencies ?? {}) as Record<
87
- string,
88
- unknown
89
- >;
90
- const api = packages.find(
91
- (pkg) =>
92
- pkg.name !== cli.name &&
93
- pkg.manifest.bin === undefined &&
94
- pkg.name in devDeps,
95
- );
96
- if (api === undefined) {
97
- throw new Error(`未找到 CLI 包 (${cli.name}) 所依赖的仓内 API 包`);
163
+ if (productHint !== undefined) {
164
+ const matched = pairs.find(
165
+ ({ cli, api }) =>
166
+ cli.name === productHint ||
167
+ api.name === productHint ||
168
+ cli.dir === productHint ||
169
+ api.dir === productHint,
170
+ );
171
+ if (matched === undefined) {
172
+ const available = pairs
173
+ .map(({ cli, api }) => `${cli.name} → ${api.name}`)
174
+ .join(', ');
175
+ throw new Error(
176
+ `未找到匹配 ${productHint} 的双包产品 (现有: ${available})`,
177
+ );
178
+ }
179
+ return matched;
180
+ }
181
+ if (pairs.length > 1) {
182
+ const available = pairs
183
+ .map(({ cli, api }) => `${cli.name} → ${api.name}`)
184
+ .join(', ');
185
+ throw new Error(
186
+ `仓内存在 ${pairs.length} 组双包产品 (${available}), 请传入 productHint 显式指定`,
187
+ );
98
188
  }
99
- return { cli, api };
189
+ return pairs[0]!;
100
190
  }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * 依赖方向闸门单测: 覆盖合法分层、CLI↔CLI 禁令、库→CLI 禁令、环依赖与公开库深度限制。
3
+ */
4
+ import { afterAll, describe, expect, test } from 'bun:test';
5
+
6
+ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
7
+ import { dirname, join } from 'node:path';
8
+
9
+ import { makeTmpRoot } from './lib/tmp-root.ts';
10
+ import { checkDependencyDirection } from './lint-dependency-direction.ts';
11
+
12
+ const roots: string[] = [];
13
+ function makeRoot(files: Record<string, unknown>): string {
14
+ const root = makeTmpRoot('dep-dir-');
15
+ roots.push(root);
16
+ for (const [rel, content] of Object.entries(files)) {
17
+ const abs = join(root, rel);
18
+ mkdirSync(dirname(abs), { recursive: true });
19
+ writeFileSync(abs, JSON.stringify(content, null, 2));
20
+ }
21
+ return root;
22
+ }
23
+ afterAll(() => {
24
+ for (const root of roots) rmSync(root, { recursive: true, force: true });
25
+ });
26
+
27
+ describe('checkDependencyDirection', () => {
28
+ test('合法单向分层 (CLI → 公开库 / 私有库, 公开库深度 ≤ 2) 全绿', () => {
29
+ const root = makeRoot({
30
+ 'package.json': { workspaces: ['packages/*'] },
31
+ 'packages/core/package.json': { name: '@x/core' },
32
+ 'packages/mid/package.json': {
33
+ name: '@x/mid',
34
+ dependencies: { '@x/core': '1.0.0' },
35
+ },
36
+ 'packages/top/package.json': {
37
+ name: '@x/top',
38
+ dependencies: { '@x/mid': '1.0.0' },
39
+ },
40
+ 'packages/internal/package.json': {
41
+ name: '@x/internal',
42
+ private: true,
43
+ dependencies: { '@x/core': '1.0.0' },
44
+ },
45
+ 'packages/tool-cli/package.json': {
46
+ name: '@x/tool-cli',
47
+ bin: { tool: 'bin/tool.mjs' },
48
+ devDependencies: { '@x/top': '1.0.0', '@x/internal': '1.0.0' },
49
+ },
50
+ });
51
+ expect(checkDependencyDirection(root)).toEqual([]);
52
+ });
53
+
54
+ test('CLI 依赖另一个 CLI (含 devDependencies) 亮红灯', () => {
55
+ const root = makeRoot({
56
+ 'package.json': { workspaces: ['packages/*'] },
57
+ 'packages/a-cli/package.json': {
58
+ name: '@x/a-cli',
59
+ bin: { a: 'bin/a.mjs' },
60
+ devDependencies: { '@x/b-cli': '1.0.0' },
61
+ },
62
+ 'packages/b-cli/package.json': {
63
+ name: '@x/b-cli',
64
+ bin: { b: 'bin/b.mjs' },
65
+ },
66
+ });
67
+ const violations = checkDependencyDirection(root);
68
+ expect(violations).toHaveLength(1);
69
+ expect(violations[0]).toContain('CLI ↔ CLI');
70
+ });
71
+
72
+ test('公开库或私有库反向依赖 CLI 亮红灯', () => {
73
+ const root = makeRoot({
74
+ 'package.json': { workspaces: ['packages/*'] },
75
+ 'packages/lib/package.json': {
76
+ name: '@x/lib',
77
+ dependencies: { '@x/app-cli': '1.0.0' },
78
+ },
79
+ 'packages/priv/package.json': {
80
+ name: '@x/priv',
81
+ private: true,
82
+ devDependencies: { '@x/app-cli': '1.0.0' },
83
+ },
84
+ 'packages/app-cli/package.json': {
85
+ name: '@x/app-cli',
86
+ bin: { app: 'bin/app.mjs' },
87
+ },
88
+ });
89
+ const violations = checkDependencyDirection(root);
90
+ expect(violations).toHaveLength(2);
91
+ expect(violations.every((v) => v.includes('反向依赖 CLI'))).toBe(true);
92
+ });
93
+
94
+ test('循环依赖亮红灯', () => {
95
+ const root = makeRoot({
96
+ 'package.json': { workspaces: ['packages/*'] },
97
+ 'packages/a/package.json': {
98
+ name: '@x/a',
99
+ dependencies: { '@x/b': '1.0.0' },
100
+ },
101
+ 'packages/b/package.json': {
102
+ name: '@x/b',
103
+ dependencies: { '@x/a': '1.0.0' },
104
+ },
105
+ });
106
+ const violations = checkDependencyDirection(root);
107
+ expect(violations.some((v) => v.includes('循环依赖'))).toBe(true);
108
+ });
109
+
110
+ test('公开库链深度超过 2 亮红灯', () => {
111
+ const root = makeRoot({
112
+ 'package.json': { workspaces: ['packages/*'] },
113
+ 'packages/l0/package.json': { name: '@x/l0' },
114
+ 'packages/l1/package.json': {
115
+ name: '@x/l1',
116
+ dependencies: { '@x/l0': '1.0.0' },
117
+ },
118
+ 'packages/l2/package.json': {
119
+ name: '@x/l2',
120
+ dependencies: { '@x/l1': '1.0.0' },
121
+ },
122
+ 'packages/l3/package.json': {
123
+ name: '@x/l3',
124
+ dependencies: { '@x/l2': '1.0.0' },
125
+ },
126
+ });
127
+ const violations = checkDependencyDirection(root);
128
+ expect(violations).toHaveLength(1);
129
+ expect(violations[0]).toContain('超过最大深度 2');
130
+ });
131
+ });
@@ -0,0 +1,130 @@
1
+ /**
2
+ * 依赖方向闸门: 强制执行 docs/designs/dependency-direction.md 约定的包间依赖有向无环图。
3
+ *
4
+ * 包分类 (确定性字段, 与 docs/designs/package-classification.md 同源):
5
+ * - cli: package.json 有 `bin` 字段
6
+ * - public-lib: 无 `bin`, 且 `private !== true`
7
+ * - private-lib: 无 `bin`, 且 `private === true`
8
+ *
9
+ * 规则 (dependencies 与 devDependencies 一视同仁):
10
+ * 1. 禁止 public-lib → cli 与 private-lib → cli (库不得反向依赖工具)
11
+ * 2. 禁止 cli → cli (工具之间不得互相依赖; 共享需求抽库)
12
+ * 3. 禁止任何环依赖 (有向无环图)
13
+ * 4. 禁止 public-lib → public-lib 链条深度 > 2 (即边数 > 2, 超过 3 个公开库串联)
14
+ *
15
+ * 用法: bun scripts/lint-dependency-direction.ts
16
+ * 退出码: 0 全绿; 1 存在违规。
17
+ */
18
+ import {
19
+ type WorkspacePackage,
20
+ listDeclaredDeps,
21
+ listWorkspacePackages,
22
+ } from './lib/workspace.ts';
23
+ import { REPO_ROOT } from './lint-doc-shared.ts';
24
+
25
+ export type PackageKind = 'cli' | 'public-lib' | 'private-lib';
26
+
27
+ /** 确定性推导包分类 */
28
+ export function classifyPackage(pkg: WorkspacePackage): PackageKind {
29
+ if (pkg.manifest.bin !== undefined) return 'cli';
30
+ return pkg.manifest.private === true ? 'private-lib' : 'public-lib';
31
+ }
32
+
33
+ /** 校验工作区所有包的内部依赖方向与无环约束, 返回违规人话列表 */
34
+ export function checkDependencyDirection(root: string = REPO_ROOT): string[] {
35
+ const packages = listWorkspacePackages(root);
36
+ const byName = new Map(packages.map((pkg) => [pkg.name, pkg]));
37
+ const kinds = new Map(
38
+ packages.map((pkg) => [pkg.name, classifyPackage(pkg)]),
39
+ );
40
+ const graph = new Map<string, string[]>();
41
+ const violations: string[] = [];
42
+
43
+ for (const pkg of packages) {
44
+ const fromKind = kinds.get(pkg.name)!;
45
+ const internalDeps = listDeclaredDeps(pkg).filter((dep) => byName.has(dep));
46
+ graph.set(pkg.name, internalDeps);
47
+
48
+ for (const dep of internalDeps) {
49
+ if (dep === pkg.name) {
50
+ violations.push(`${pkg.name} 存在自依赖`);
51
+ continue;
52
+ }
53
+ const toKind = kinds.get(dep)!;
54
+ if (fromKind === 'cli' && toKind === 'cli') {
55
+ violations.push(
56
+ `禁止 CLI ↔ CLI 依赖: ${pkg.name} (${pkg.dir}) → ${dep} (共享能力请抽为库包)`,
57
+ );
58
+ } else if (fromKind !== 'cli' && toKind === 'cli') {
59
+ violations.push(
60
+ `禁止库反向依赖 CLI: ${pkg.name} [${fromKind}] → ${dep} [cli]`,
61
+ );
62
+ }
63
+ }
64
+ }
65
+
66
+ // 有向环检测 (三色 DFS: 0 未访问 / 1 栈中 / 2 已完成)
67
+ const color = new Map<string, number>();
68
+ const stack: string[] = [];
69
+ const reportedCycles = new Set<string>();
70
+
71
+ const dfs = (node: string): void => {
72
+ color.set(node, 1);
73
+ stack.push(node);
74
+ for (const next of graph.get(node) ?? []) {
75
+ const state = color.get(next) ?? 0;
76
+ if (state === 1) {
77
+ const idx = stack.indexOf(next);
78
+ const cycle = [...stack.slice(idx), next].join(' → ');
79
+ if (!reportedCycles.has(cycle)) {
80
+ reportedCycles.add(cycle);
81
+ violations.push(`禁止循环依赖: ${cycle}`);
82
+ }
83
+ } else if (state === 0) {
84
+ dfs(next);
85
+ }
86
+ }
87
+ stack.pop();
88
+ color.set(node, 2);
89
+ };
90
+
91
+ for (const pkg of packages) {
92
+ if ((color.get(pkg.name) ?? 0) === 0) dfs(pkg.name);
93
+ }
94
+
95
+ // public-lib → public-lib 深度检测 (最大允许深度 2, 即至多 2 条边)
96
+ const checkPublicDepth = (node: string, chain: string[]): void => {
97
+ if (chain.length - 1 > 2) {
98
+ violations.push(
99
+ `公开库依赖链超过最大深度 2: ${chain.join(' → ')} (请先提炼中间层)`,
100
+ );
101
+ return;
102
+ }
103
+ for (const next of graph.get(node) ?? []) {
104
+ if (kinds.get(next) !== 'public-lib') continue;
105
+ if (chain.includes(next)) continue;
106
+ checkPublicDepth(next, [...chain, next]);
107
+ }
108
+ };
109
+
110
+ for (const pkg of packages) {
111
+ if (kinds.get(pkg.name) === 'public-lib') {
112
+ checkPublicDepth(pkg.name, [pkg.name]);
113
+ }
114
+ }
115
+
116
+ return violations;
117
+ }
118
+
119
+ function main(): void {
120
+ const violations = checkDependencyDirection();
121
+ if (violations.length === 0) {
122
+ process.stdout.write('依赖方向闸门全绿 ✓\n');
123
+ return;
124
+ }
125
+ process.stderr.write(`依赖方向闸门检出 ${violations.length} 项违规:\n`);
126
+ for (const item of violations) process.stderr.write(` ✗ ${item}\n`);
127
+ process.exitCode = 1;
128
+ }
129
+
130
+ if (import.meta.main) main();
@@ -1,6 +1,6 @@
1
1
  /**
2
- * 文档示例闸门单测: 采集 / 判据 / 分类各纯函数逐一断言; 集成面用临时 mini 根验证
3
- * 「片段块判跳过」与「CLI 档旗标缺失抓得住」。
2
+ * 文档示例闸门单测: 采集 / 判据 / 分类各纯函数逐一断言; 集成面覆盖片段跳过、
3
+ * 本仓包名 TS2307 拦截与多 CLI 旗标核对。
4
4
  */
5
5
  import { afterAll, describe, expect, test } from 'bun:test';
6
6
 
@@ -13,6 +13,7 @@ import {
13
13
  checkTsExamples,
14
14
  classifyBlock,
15
15
  extractCommandTokens,
16
+ extractNamedShellCommands,
16
17
  extractShellCommands,
17
18
  extractTsBlocks,
18
19
  isSelfContained,
@@ -54,7 +55,7 @@ describe('isSelfContained', () => {
54
55
  });
55
56
 
56
57
  describe('extractShellCommands', () => {
57
- test('只收 shell 块内以 {{BIN_NAME}} 起首的非注释行, 前缀精确', () => {
58
+ test('只收 shell 块内以指定命令起首的非注释行, 前缀精确', () => {
58
59
  const text = [
59
60
  '```shell',
60
61
  '# 注释跳过',
@@ -66,10 +67,23 @@ describe('extractShellCommands', () => {
66
67
  ].join('\n');
67
68
  expect(extractShellCommands(text)).toEqual(['{{BIN_NAME}} --yes']);
68
69
  });
70
+
71
+ test('多命令采集支持 shell / bash 块并精准归属 binName', () => {
72
+ const text = [
73
+ '```bash',
74
+ 'extra --dry-run config.json',
75
+ 'create-app my-app --tier standard',
76
+ '```',
77
+ ].join('\n');
78
+ expect(extractNamedShellCommands(text, ['extra', 'create-app'])).toEqual([
79
+ { binName: 'extra', command: 'extra --dry-run config.json' },
80
+ { binName: 'create-app', command: 'create-app my-app --tier standard' },
81
+ ]);
82
+ });
69
83
  });
70
84
 
71
85
  describe('extractCommandTokens', () => {
72
- test('旗标去 = 值; 第一个位置参数当子命令; 旗标的值不采集', () => {
86
+ test('旗标去 = 值; 仅首个纯标识符位置参数当子命令; 路径/文件不误判为子命令', () => {
73
87
  expect(extractCommandTokens('{{BIN_NAME}} --yes --force')).toEqual([
74
88
  '--yes',
75
89
  '--force',
@@ -78,6 +92,9 @@ describe('extractCommandTokens', () => {
78
92
  extractCommandTokens('{{BIN_NAME}} --exclude my-kits --exclude url'),
79
93
  ).toEqual(['--exclude']);
80
94
  expect(extractCommandTokens('{{BIN_NAME}} config')).toEqual(['config']);
95
+ expect(extractCommandTokens('extra ./deploy.json --dry-run')).toEqual([
96
+ '--dry-run',
97
+ ]);
81
98
  expect(extractCommandTokens('{{BIN_NAME}}')).toEqual([]);
82
99
  });
83
100
  });
@@ -98,32 +115,51 @@ describe('parseTscErrors + classifyBlock', () => {
98
115
  });
99
116
 
100
117
  describe('checkTsExamples 集成', () => {
101
- test('片段块 (引用块外上下文) 判跳过而非断裂', () => {
118
+ test('非本仓虚构模块判跳过, 本仓 scope 模块找不到直接判真断裂', () => {
102
119
  const root = makeRoot({
120
+ 'package.json': JSON.stringify({ workspaces: ['packages/*'] }),
121
+ 'packages/demo/package.json': JSON.stringify({ name: '@acme/demo' }),
103
122
  'tsconfig.json': '{"compilerOptions":{"noEmit":true}}',
104
123
  'docs/a.md': "```ts\nimport { nope } from 'nowhere-pkg';\nnope();\n```\n",
124
+ 'docs/b.md':
125
+ "```ts\nimport { gone } from '@acme/renamed-pkg';\ngone();\n```\n",
105
126
  });
106
127
  const { real, fragments } = checkTsExamples(root);
107
- expect(real).toEqual([]);
108
128
  expect(fragments).toHaveLength(1);
129
+ expect(real).toHaveLength(1);
130
+ expect(real[0]).toContain('docs/b.md');
109
131
  }, 120000);
110
132
  });
111
133
 
112
134
  describe('checkCliExamples 集成', () => {
113
- test('文档写了 --help 里没有的旗标即抓出; 文档漏登记不误报', () => {
135
+ test('多 CLI 并存时各自按 --help 核对旗标, 缺旗标精准报出', () => {
114
136
  const root = makeRoot({
137
+ 'package.json': JSON.stringify({ workspaces: ['packages/*'] }),
138
+ 'packages/{{NAME}}-cli/package.json': JSON.stringify({
139
+ name: '{{SCOPE}}/{{NAME}}-cli',
140
+ bin: { '{{BIN_NAME}}': 'bin/{{BIN_NAME}}.mjs' },
141
+ }),
115
142
  'packages/{{NAME}}-cli/src/cli.ts':
116
143
  "console.log(['{{BIN_NAME}} --yes 执行删除', '{{BIN_NAME}} config 查看配置'].join('\\n'));\n",
144
+ 'packages/extra-cli/package.json': JSON.stringify({
145
+ name: '@acme/extra-cli',
146
+ bin: { extra: 'bin/extra.mjs' },
147
+ }),
148
+ 'packages/extra-cli/src/cli.ts':
149
+ "console.log(['extra --dry-run 干跑', 'extra init 初始化'].join('\\n'));\n",
117
150
  'README.md': [
118
151
  '```shell',
119
152
  '{{BIN_NAME}} --yes',
120
153
  '{{BIN_NAME}} --nope',
121
154
  '{{BIN_NAME}} config',
155
+ 'extra init',
156
+ 'extra --bogus',
122
157
  '```',
123
158
  ].join('\n'),
124
159
  });
125
160
  const missing = checkCliExamples(root);
126
- expect(missing).toHaveLength(1);
127
- expect(missing[0]).toContain('--nope');
161
+ expect(missing).toHaveLength(2);
162
+ expect(missing.some((line) => line.includes('--nope'))).toBe(true);
163
+ expect(missing.some((line) => line.includes('--bogus'))).toBe(true);
128
164
  }, 60000);
129
165
  });