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,88 +1,152 @@
1
1
  /**
2
- * 本地 CI 预演 (闸门清单的单一事实来源): 全部步骤在此一处定义, 其余消费方——手动全链、
3
- * lefthook pre-push、CI 的两个 job、Release 的 verify job——一律经本入口调用, 不再各自枚举
4
- * (此前清单散布五处, 每加一个闸门需五处同步; 见 docs/designs/tech-debt.md 的历史登记 TD-03)。
2
+ * 本地 CI 预演 (闸门清单的单一事实来源): 全部步骤在此一处定义, 其余消费方 — 手动全链、
3
+ * lefthook pre-push、CI 三路 job (Linux / Windows / macOS) 与 Release 前置门禁 —
4
+ * 一律经本入口调用, 不再各自枚举。
5
5
  *
6
6
  * 分组:
7
- * - `--verify` 验证组 (ubuntu 可跑): build → typecheck → test → lint → format-check → 四闸门;
8
- * - `--conformance` 验收组 (语料为 macOS 口径): build → conformance (bun + node 双 target);
9
- * - (无旗标) 全链 = 验证组 + 验收组 (重复步骤去重);
10
- * - `--only <step>` 单步执行 (步骤名见 `--help`);
11
- * - `--help` 列出步骤与分组。
7
+ * - `--verify` 验证组 (ubuntu 权威全量): build → typecheck → test → 7 道只读 lint 并行;
8
+ * - `--verify-windows` Windows OS 兼容组: build → 限并发 test:windows → test:scripts;
9
+ * - `--conformance` 验收组 (语料为 macOS 口径): build → conformance (bun + node 双 target);
10
+ * - (无旗标) 全链 = 验证组 + 验收组 (重复步骤去重);
11
+ * - `--only <step>` 单步执行 (步骤名见 `--help`);
12
+ * - `--help` 列出步骤与分组。
12
13
  *
13
- * 用法: bun scripts/ci.ts [--verify | --conformance | --only <step> | --help]
14
- * 退出码: 0 全绿; 其余为首个失败步骤的退出码。
15
- *
16
- * test 步骤在隔离 HOME 下执行 (临时家目录经 makeTmpRoot 创建): 本机常备而 CI 缺失的
17
- * 环境态依赖 (如 ~/tmp 目录、家目录配置) 不再被本机状态掩盖, 此类 CI 翻车本地预演即可
18
- * 抓住 (2026-09-30 复盘: 环境态假设类失败)。
14
+ * 用法: bun scripts/ci.ts [--verify | --verify-windows | --conformance | --only <step> | --help]
15
+ * 退出码: 0 全绿; 2 参数非法; 其余为首个失败步骤的退出码。
19
16
  */
20
- import { spawnSync } from 'node:child_process';
21
- import { rmSync } from 'node:fs';
17
+ import { spawn, spawnSync } from 'node:child_process';
18
+ import * as fs from 'node:fs';
22
19
  import { join } from 'node:path';
23
20
 
24
21
  import { makeTmpRoot } from './lib/tmp-root.ts';
25
- import { resolveCliAndApi } from './lib/workspace.ts';
22
+ import { resolveProductPairs } from './lib/workspace.ts';
26
23
 
27
24
  process.chdir(join(import.meta.dir, '..'));
28
25
 
29
- /** 一个步骤: 展示名与命令参数 */
26
+ /** 一个步骤: 展示名与命令参数 (args 支持惰性生成, 避免非验收场景耦合特定产品路径) */
30
27
  interface Step {
31
28
  command: string;
32
- args: string[];
33
- /** 在隔离 HOME 下执行 (防「本地有而 CI 无」的环境态假设被本机状态掩盖) */
29
+ args: string[] | (() => string[]);
30
+ /** 在隔离 HOME / USERPROFILE 下执行 (防「本地有而 CI 无」的环境态假设被本机状态掩盖) */
34
31
  isolatedHome?: boolean;
32
+ /** 叠加给子进程的环境变量 */
33
+ env?: Readonly<Record<string, string>>;
34
+ /** 纯只读无副作用闸门: 连续出现时自动并行执行, 输出按声明序回放 */
35
+ parallel?: boolean;
35
36
  }
36
37
 
37
- /** CLI 入口坐标: 由 workspaces 派生 (chdir 之后相对仓库根) */
38
- const { cli } = resolveCliAndApi(process.cwd());
39
- const CLI_SRC = `${cli.dir}/src/cli.ts`;
38
+ /** 惰性派生转写验收 CLI 入口坐标 (单产品仓取唯一对; 多产品仓按 docs/protocol 锚点唯一定位) */
39
+ function resolveConformanceCliSrc(): string {
40
+ const root = process.cwd();
41
+ const pairs = resolveProductPairs(root);
42
+ const matched =
43
+ pairs.length === 1
44
+ ? pairs[0]
45
+ : pairs.find(({ api }) =>
46
+ fs.existsSync(join(root, api.dir, 'docs', 'protocol')),
47
+ );
48
+ if (matched === undefined) {
49
+ throw new Error('未找到承接转写验收的 CLI + API 双包产品');
50
+ }
51
+ return `${matched.cli.dir}/src/cli.ts`;
52
+ }
53
+
54
+ /** Windows 兼容专项测试环境: 跳过已在 Linux 全量校验过的重复真机 npm pack, 禁用 npm 更新检查 */
55
+ const WINDOWS_TEST_ENV: Readonly<Record<string, string>> = {
56
+ CI_SKIP_PACK_TEST: '1',
57
+ NO_UPDATE_NOTIFIER: '1',
58
+ npm_config_update_notifier: 'false',
59
+ };
40
60
 
41
61
  /** 步骤表 (清单唯一来源): 键即 `--only` 接受的步骤名 */
42
62
  const STEPS: Readonly<Record<string, Step>> = {
43
63
  build: { command: 'bun', args: ['run', 'build'] },
44
64
  typecheck: { command: 'bun', args: ['run', 'typecheck'] },
45
65
  test: { command: 'bun', args: ['run', 'test'], isolatedHome: true },
46
- lint: { command: 'bunx', args: ['oxlint'] },
47
- 'format-check': { command: 'bunx', args: ['prettier', '--check', '.'] },
48
- 'lint:refs': { command: 'bun', args: ['scripts/lint-doc-references.ts'] },
49
- 'lint:examples': { command: 'bun', args: ['scripts/lint-doc-examples.ts'] },
66
+ 'test:windows': {
67
+ command: 'bun',
68
+ args: [
69
+ 'x',
70
+ '--no-install',
71
+ 'turbo',
72
+ 'run',
73
+ 'test',
74
+ '--concurrency=2',
75
+ '--continue=dependencies-successful',
76
+ ],
77
+ isolatedHome: true,
78
+ env: WINDOWS_TEST_ENV,
79
+ },
80
+ 'test:scripts': {
81
+ command: 'bun',
82
+ args: ['test', 'scripts/'],
83
+ isolatedHome: true,
84
+ env: WINDOWS_TEST_ENV,
85
+ },
86
+ lint: {
87
+ command: 'bun',
88
+ args: ['x', '--no-install', 'oxlint'],
89
+ parallel: true,
90
+ },
91
+ 'format-check': {
92
+ command: 'bun',
93
+ args: ['fmt', '--check'],
94
+ parallel: true,
95
+ },
96
+ 'lint:refs': {
97
+ command: 'bun',
98
+ args: ['scripts/lint-doc-references.ts'],
99
+ parallel: true,
100
+ },
101
+ 'lint:examples': {
102
+ command: 'bun',
103
+ args: ['scripts/lint-doc-examples.ts'],
104
+ parallel: true,
105
+ },
106
+ 'lint:deps': {
107
+ command: 'bun',
108
+ args: ['scripts/lint-dependency-direction.ts'],
109
+ parallel: true,
110
+ },
50
111
  'lint:coverage': {
51
112
  command: 'bun',
52
113
  args: ['scripts/transcription/validate-coverage.ts'],
114
+ parallel: true,
53
115
  },
54
- 'lint:backups': { command: 'bun', args: ['scripts/lint-stray-backups.ts'] },
55
- // 发布凭据预检 (OIDC 换证): 发布特有, 不进任何组——普通 CI job 与本机全链跑不到它,
56
- // 仅 Release 的 release job (获批后) 经 `--only npm-trust` 调用; 非 OIDC 环境下手动跑时
57
- // 脚本自行跳过。注意: 换证与登记逐字段核对 (含 environment 声明), 调用点必须在带
58
- // environment 的 job 里, 否则会被 npm 以误导性的 404 (package not found) 拒绝
116
+ 'lint:backups': {
117
+ command: 'bun',
118
+ args: ['scripts/lint-stray-backups.ts'],
119
+ parallel: true,
120
+ },
121
+ // 发布凭据预检 (OIDC 换证): 发布特有, 不进任何组 — 仅 Release 的 release job (获批后)
122
+ // 经 `--only npm-trust` 调用; 非 OIDC 环境下手动跑时脚本自行跳过。
59
123
  'npm-trust': {
60
124
  command: 'bun',
61
125
  args: ['scripts/npm-trust-guard.ts', 'verify-oidc'],
62
126
  },
63
127
  'conformance:bun': {
64
128
  command: 'bun',
65
- args: [
129
+ args: () => [
66
130
  'scripts/transcription/run-conformance.ts',
67
131
  '--target',
68
- `bun ${CLI_SRC}`,
132
+ `bun ${resolveConformanceCliSrc()}`,
69
133
  '--api-target',
70
134
  'bun scripts/transcription/api-harness.ts',
71
135
  ],
72
136
  },
73
137
  'conformance:node': {
74
138
  command: 'bun',
75
- args: [
139
+ args: () => [
76
140
  'scripts/transcription/run-conformance.ts',
77
141
  '--target',
78
- `node ${CLI_SRC}`,
142
+ `node ${resolveConformanceCliSrc()}`,
79
143
  '--api-target',
80
144
  'node scripts/transcription/api-harness.ts',
81
145
  ],
82
146
  },
83
147
  };
84
148
 
85
- /** 验证组 (ubuntu 可跑; CI 与 Release 的 verify job 即此组) */
149
+ /** 验证组 (ubuntu 权威全量; CI 的 verify job 即此组) */
86
150
  const VERIFY_GROUP: readonly string[] = [
87
151
  'build',
88
152
  'typecheck',
@@ -91,14 +155,22 @@ const VERIFY_GROUP: readonly string[] = [
91
155
  'format-check',
92
156
  'lint:refs',
93
157
  'lint:examples',
158
+ 'lint:deps',
94
159
  'lint:coverage',
95
160
  'lint:backups',
96
161
  ];
97
162
 
163
+ /** Windows OS 兼容组 (跳过 OS 无关静态检查与已在 Linux 全量校验的重复 npm pack) */
164
+ const VERIFY_WINDOWS_GROUP: readonly string[] = [
165
+ 'build',
166
+ 'test:windows',
167
+ 'test:scripts',
168
+ ];
169
+
98
170
  /**
99
171
  * 验收组 (转写验收需 macOS 口径: 语料的 du 磁盘占用按 APFS 块分配录制)。
100
172
  * 组内含 build: node target 直跑 CLI 源码时按 exports 解析到 API 包 dist,
101
- * 而 node 不读 tsconfig paths (bun 独有), 无产物即全数 ERR_MODULE_NOT_FOUND (2026-09-29 CI 实翻)。
173
+ * 而 node 不读 tsconfig paths (bun 独有), 无产物即全数 ERR_MODULE_NOT_FOUND。
102
174
  */
103
175
  const CONFORMANCE_GROUP: readonly string[] = [
104
176
  'build',
@@ -106,16 +178,137 @@ const CONFORMANCE_GROUP: readonly string[] = [
106
178
  'conformance:node',
107
179
  ];
108
180
 
109
- /** 跑一步 (stdio 透传), 失败即携其退出码终止 */
181
+ /** 预建隔离家目录内的标准配置子目录 (Windows 上 SHGetKnownFolderPath 校验 AppData\Roaming 存在) */
182
+ function prepareIsolatedHome(home: string): void {
183
+ for (const parts of [
184
+ ['.config', 'turborepo'],
185
+ ['.config', 'vercel'],
186
+ ['AppData', 'Roaming'],
187
+ ['AppData', 'Local'],
188
+ ]) {
189
+ fs.mkdirSync(join(home, ...parts), { recursive: true });
190
+ }
191
+ }
192
+
193
+ /** 组装单步环境变量 (可选叠加隔离 HOME / XDG / AppData / Turbo 配置路径与步骤专有 env) */
194
+ function buildStepEnv(step: Step, home: string | undefined): NodeJS.ProcessEnv {
195
+ const env: NodeJS.ProcessEnv = { ...process.env, ...step.env };
196
+ if (home !== undefined) {
197
+ const configDir = join(home, '.config');
198
+ env.HOME = home;
199
+ env.USERPROFILE = home;
200
+ env.XDG_CONFIG_HOME = configDir;
201
+ env.APPDATA = join(home, 'AppData', 'Roaming');
202
+ env.LOCALAPPDATA = join(home, 'AppData', 'Local');
203
+ env.TURBO_CONFIG_DIR_PATH = join(configDir, 'turborepo');
204
+ env.VERCEL_CONFIG_DIR_PATH = join(configDir, 'vercel');
205
+ }
206
+ return env;
207
+ }
208
+
209
+ /** 跑一步串行步骤 (stdio 透传), 失败即携其退出码终止 */
110
210
  function runStep(name: string): void {
111
211
  const step = STEPS[name]!;
112
212
  process.stdout.write(`\n=== ${name} ===\n`);
213
+ const args = typeof step.args === 'function' ? step.args() : step.args;
113
214
  const home = step.isolatedHome === true ? makeTmpRoot('ci-home-') : undefined;
114
- if (home !== undefined) process.stdout.write(`隔离 HOME: ${home}\n`);
115
- const env = home === undefined ? process.env : { ...process.env, HOME: home };
116
- const result = spawnSync(step.command, step.args, { stdio: 'inherit', env });
117
- if (home !== undefined) rmSync(home, { recursive: true, force: true });
118
- if (result.status !== 0) process.exit(result.status ?? 1);
215
+ try {
216
+ if (home !== undefined) {
217
+ prepareIsolatedHome(home);
218
+ process.stdout.write(`隔离 HOME: ${home}\n`);
219
+ }
220
+ const result = spawnSync(step.command, args, {
221
+ stdio: 'inherit',
222
+ env: buildStepEnv(step, home),
223
+ });
224
+ if (result.error !== undefined) {
225
+ process.stderr.write(`步骤 ${name} 启动失败: ${result.error.message}\n`);
226
+ process.exit(1);
227
+ }
228
+ if (result.status !== 0) process.exit(result.status ?? 1);
229
+ } finally {
230
+ if (home !== undefined) {
231
+ fs.rmSync(home, {
232
+ recursive: true,
233
+ force: true,
234
+ maxRetries: 5,
235
+ retryDelay: 100,
236
+ });
237
+ }
238
+ }
239
+ }
240
+
241
+ interface ParallelResult {
242
+ name: string;
243
+ status: number;
244
+ stdout: string;
245
+ stderr: string;
246
+ }
247
+
248
+ /** 异步执行单条只读并行步骤并收集输出 */
249
+ function spawnParallelStep(name: string): Promise<ParallelResult> {
250
+ const step = STEPS[name]!;
251
+ const args = typeof step.args === 'function' ? step.args() : step.args;
252
+ return new Promise((resolve) => {
253
+ const child = spawn(step.command, args, {
254
+ stdio: ['ignore', 'pipe', 'pipe'],
255
+ env: buildStepEnv(step, undefined),
256
+ });
257
+ let stdout = '';
258
+ let stderr = '';
259
+ child.stdout.setEncoding('utf8');
260
+ child.stderr.setEncoding('utf8');
261
+ child.stdout.on('data', (chunk: string) => {
262
+ stdout += chunk;
263
+ });
264
+ child.stderr.on('data', (chunk: string) => {
265
+ stderr += chunk;
266
+ });
267
+ child.on('error', (error) => {
268
+ resolve({
269
+ name,
270
+ status: 1,
271
+ stdout,
272
+ stderr: `${stderr}步骤 ${name} 启动失败: ${error.message}\n`,
273
+ });
274
+ });
275
+ child.on('close', (code) => {
276
+ resolve({ name, status: code ?? 1, stdout, stderr });
277
+ });
278
+ });
279
+ }
280
+
281
+ /** 并行执行连续的只读检查步骤, 按原声明顺序整块回放输出并在首个失败处退出 */
282
+ async function runParallelBatch(names: readonly string[]): Promise<void> {
283
+ const results = await Promise.all(names.map(spawnParallelStep));
284
+ let firstFailure = 0;
285
+ for (const res of results) {
286
+ process.stdout.write(`\n=== ${res.name} ===\n`);
287
+ if (res.stdout.length > 0) process.stdout.write(res.stdout);
288
+ if (res.stderr.length > 0) process.stderr.write(res.stderr);
289
+ if (res.status !== 0 && firstFailure === 0) firstFailure = res.status;
290
+ }
291
+ if (firstFailure !== 0) process.exit(firstFailure);
292
+ }
293
+
294
+ /** 按步骤序列编排执行: 连续的 parallel 步骤自动成批并发, 其余严格串行 */
295
+ async function runSteps(names: readonly string[]): Promise<void> {
296
+ let index = 0;
297
+ while (index < names.length) {
298
+ const name = names[index]!;
299
+ if (STEPS[name]?.parallel === true) {
300
+ const batch: string[] = [];
301
+ while (index < names.length && STEPS[names[index]!]?.parallel === true) {
302
+ batch.push(names[index]!);
303
+ index += 1;
304
+ }
305
+ if (batch.length === 1) runStep(batch[0]!);
306
+ else await runParallelBatch(batch);
307
+ continue;
308
+ }
309
+ runStep(name);
310
+ index += 1;
311
+ }
119
312
  }
120
313
 
121
314
  /** 帮助文本 */
@@ -123,30 +316,58 @@ const HELP_TEXT = [
123
316
  '本地 CI 预演 (闸门清单单一事实来源)',
124
317
  '',
125
318
  '用法: bun scripts/ci.ts [选项]',
126
- ' --verify 验证组: ' + VERIFY_GROUP.join(' → '),
127
- ' --conformance 验收组: ' + CONFORMANCE_GROUP.join(' → '),
128
- ' (无旗标) 全链 = 验证组 + 验收组 (去重)',
129
- ' --only <step> 单步执行',
130
- ' --help 本帮助',
319
+ ' --verify 验证组 (Linux 全量): ' + VERIFY_GROUP.join(' → '),
320
+ ' --verify-windows Windows 兼容组: ' + VERIFY_WINDOWS_GROUP.join(' → '),
321
+ ' --conformance 验收组 (macOS 口径): ' + CONFORMANCE_GROUP.join(' → '),
322
+ ' (无旗标) 全链 = 验证组 + 验收组 (去重)',
323
+ ' --only <step> 单步执行',
324
+ ' --help 本帮助',
131
325
  '',
132
326
  '步骤名: ' + Object.keys(STEPS).join(' / '),
133
327
  ].join('\n');
134
328
 
135
- /** 解析入口旗标为待跑步骤序列 */
136
- function resolveSteps(argv: string[]): string[] | null {
137
- const onlyIndex = argv.indexOf('--only');
138
- if (onlyIndex >= 0) {
139
- const name = argv[onlyIndex + 1];
140
- if (name === undefined || STEPS[name] === undefined) {
141
- process.stderr.write(
142
- `--only 缺步骤名或步骤不存在: ${String(name)}\n\n${HELP_TEXT}\n`,
143
- );
144
- process.exit(2);
329
+ /** 解析入口旗标为待跑步骤序列 (显式拒绝未知旗标与互斥组合) */
330
+ function resolveSteps(argv: string[]): string[] {
331
+ const modes: string[] = [];
332
+ let onlyStep: string | undefined;
333
+
334
+ for (let i = 0; i < argv.length; i += 1) {
335
+ const arg = argv[i]!;
336
+ if (
337
+ arg === '--verify' ||
338
+ arg === '--verify-windows' ||
339
+ arg === '--conformance'
340
+ ) {
341
+ modes.push(arg);
342
+ continue;
145
343
  }
146
- return [name];
344
+ if (arg === '--only') {
345
+ const name = argv[i + 1];
346
+ if (name === undefined || STEPS[name] === undefined) {
347
+ process.stderr.write(
348
+ `--only 缺步骤名或步骤不存在: ${String(name)}\n\n${HELP_TEXT}\n`,
349
+ );
350
+ process.exit(2);
351
+ }
352
+ onlyStep = name;
353
+ modes.push('--only');
354
+ i += 1;
355
+ continue;
356
+ }
357
+ process.stderr.write(`未知参数: ${arg}\n\n${HELP_TEXT}\n`);
358
+ process.exit(2);
359
+ }
360
+
361
+ if (modes.length > 1) {
362
+ process.stderr.write(
363
+ `旗标互斥, 一次只能指定一种模式: ${modes.join(', ')}\n\n${HELP_TEXT}\n`,
364
+ );
365
+ process.exit(2);
147
366
  }
148
- if (argv.includes('--verify')) return [...VERIFY_GROUP];
149
- if (argv.includes('--conformance')) return [...CONFORMANCE_GROUP];
367
+ if (onlyStep !== undefined) return [onlyStep];
368
+ if (modes[0] === '--verify') return [...VERIFY_GROUP];
369
+ if (modes[0] === '--verify-windows') return [...VERIFY_WINDOWS_GROUP];
370
+ if (modes[0] === '--conformance') return [...CONFORMANCE_GROUP];
150
371
  // 全链: 验证组 + 验收组中未出现过的步骤 (build 去重)
151
372
  return [
152
373
  ...VERIFY_GROUP,
@@ -157,7 +378,7 @@ function resolveSteps(argv: string[]): string[] | null {
157
378
  if (process.argv.includes('--help')) {
158
379
  process.stdout.write(`${HELP_TEXT}\n`);
159
380
  } else {
160
- const steps = resolveSteps(process.argv.slice(2))!;
161
- for (const name of steps) runStep(name);
381
+ const steps = resolveSteps(process.argv.slice(2));
382
+ await runSteps(steps);
162
383
  process.stdout.write('\nCI 预演全绿 ✓\n');
163
384
  }
@@ -52,11 +52,21 @@ const realpathOr = (value) => {
52
52
  }
53
53
  };
54
54
 
55
+ /** 清洗宿主 GIT_* 环境变量: 防止外层 git 钩子或子模块环境把 rev-parse 改道到别的仓库 */
56
+ const cleanGitEnv = () => {
57
+ const env = {};
58
+ for (const [key, value] of Object.entries(process.env)) {
59
+ if (!key.startsWith('GIT_') && value !== undefined) env[key] = value;
60
+ }
61
+ return env;
62
+ };
63
+
55
64
  /** 包根所在 git 仓库的根 (不在仓库内或 git 不可用时为 null) */
56
65
  const gitToplevel = () => {
57
66
  const out = run('git', ['rev-parse', '--show-toplevel'], {
58
67
  cwd: PKG_ROOT,
59
68
  encoding: 'utf8',
69
+ env: cleanGitEnv(),
60
70
  });
61
71
  return out.status === 0 ? out.stdout.trim() : null;
62
72
  };
@@ -92,7 +92,7 @@ const sandboxes: string[] = [];
92
92
 
93
93
  /** 建一个用例沙箱根 (mkdtemp 保证互不干扰) */
94
94
  const makeSandbox = (): string => {
95
- const root = mkdtempSync(join(tmpdir(), 'sweep-hooks-'));
95
+ const root = mkdtempSync(join(tmpdir(), 'hooks-'));
96
96
  sandboxes.push(root);
97
97
  return root;
98
98
  };
@@ -0,0 +1,169 @@
1
+ /**
2
+ * npm Trusted Publisher 登记解析、差异比对与运行环境判定纯函数库 (零副作用、零 I/O)。
3
+ */
4
+ import type { WorkspacePackage } from './workspace.ts';
5
+
6
+ /** npm trust list 解析出的登记条目 (缺行字段落成 null) */
7
+ export interface TrustEntry {
8
+ type: string | null;
9
+ id: string | null;
10
+ file: string | null;
11
+ environment: string | null;
12
+ repository: string;
13
+ }
14
+
15
+ /** 期望的登记形态 (owner/repo 从 git origin 派生, 其余为常量) */
16
+ export interface TrustExpectation {
17
+ repository: string;
18
+ file: string;
19
+ environment: string;
20
+ }
21
+
22
+ /** OIDC 运行环境判定: ready = 可预检; missing-permission = Actions 里漏配 id-token; not-ci = 本地 */
23
+ export type OidcEnvVerdict = 'ready' | 'missing-permission' | 'not-ci';
24
+
25
+ /** 剥终端 CSI 序列 (颜色着色与 spinner 的光标控制; 参数段 [0-9;?]*, 末字符为任意字母) */
26
+ export const stripCsi = (text: string): string =>
27
+ text.replace(
28
+ new RegExp(String.fromCharCode(27) + '\\[[0-9;?]*[A-Za-z]', 'g'),
29
+ '',
30
+ );
31
+
32
+ /** 剥控制字符并收拢空白 (npm 输出属低信任输入, 落进人读文案前先降噪) */
33
+ export const cleanText = (text: string): string =>
34
+ text.replace(/[\p{Cc}]+/gu, ' ').trim();
35
+
36
+ /**
37
+ * 剥 pty 伪影: `script` 开场的 ^D + 退格序列、CRLF 行尾与孤立终端控制符。
38
+ * 须在 stripCsi 之后调用: 本函数的控制符剥离面覆盖 ESC 本身, 先把完整 CSI 序列剥掉再除残留。
39
+ */
40
+ export const stripPtyNoise = (text: string): string =>
41
+ text
42
+ .replace(/\r/g, '')
43
+ // eslint-disable-next-line no-control-regex -- 此处刻意匹配 pty 残留控制符 (script 开场的 ^D 与退格), 属预期匹配
44
+ .replace(/[\x00-\x08\x0b\x0c\x0e-\x1f]/g, '');
45
+
46
+ /** 从 git remote 原文派生 owner/repo; 非 GitHub 远端或形状不符返回 null */
47
+ export function deriveRepoFromRemoteUrl(raw: string): string | null {
48
+ const cleaned = raw.trim().replace(/\.git$/, '');
49
+ const match = cleaned.match(/github\.com[:/]([^/\s]+)\/([^/\s]+)$/);
50
+ if (match === null || match[1] === undefined || match[2] === undefined) {
51
+ return null;
52
+ }
53
+ return `${match[1]}/${match[2]}`;
54
+ }
55
+
56
+ /** Trusted Publisher ID 合法字符白名单 (UUID / 字母数字连字符下划线点) */
57
+ export const isValidTrustId = (id: string): boolean =>
58
+ /^[A-Za-z0-9._-]+$/.test(id);
59
+
60
+ /** POSIX 单引号安全转义 (安全字符集保持裸写便于日志阅读, 含元字符或空白则严格单引号包裹) */
61
+ export const shellQuote = (arg: string): string =>
62
+ /^[A-Za-z0-9_@%+=:,./-]+$/.test(arg)
63
+ ? arg
64
+ : `'${arg.replace(/'/g, "'\\''")}'`;
65
+
66
+ /**
67
+ * 解析 `npm trust list` 的人读输出为多条记录 (防止多条登记时跨条串味)。
68
+ * 遇到重复键名或空行分段时自动切分新条目; 仅保留含非空 repository 字段的可信条目。
69
+ */
70
+ export function parseTrustListEntries(raw: string): TrustEntry[] {
71
+ const text = stripPtyNoise(stripCsi(raw));
72
+ const keys = new Set(['type', 'id', 'file', 'environment', 'repository']);
73
+ const entries: TrustEntry[] = [];
74
+ let current: Partial<Record<keyof TrustEntry, string>> = {};
75
+
76
+ const flush = (): void => {
77
+ if (current.repository !== undefined && current.repository !== '') {
78
+ entries.push({
79
+ type: current.type ?? null,
80
+ id: current.id ?? null,
81
+ file: current.file ?? null,
82
+ environment: current.environment ?? null,
83
+ repository: current.repository,
84
+ });
85
+ }
86
+ current = {};
87
+ };
88
+
89
+ for (const line of text.split('\n')) {
90
+ const match = /^([a-z]+):[ \t]*(.+)$/.exec(line.trim());
91
+ if (match === null) {
92
+ if (line.trim() === '' && Object.keys(current).length > 0) flush();
93
+ continue;
94
+ }
95
+ const key = match[1] as keyof TrustEntry;
96
+ if (!keys.has(key)) continue;
97
+ if (current[key] !== undefined) flush();
98
+ const cleaned = cleanText(match[2]!);
99
+ if (cleaned !== '') current[key] = cleaned;
100
+ }
101
+ flush();
102
+ return entries;
103
+ }
104
+
105
+ /** 解析 `npm trust list` 的首条记录 (兼容单登记调用方; 未见 repository 行时返回 null) */
106
+ export function parseTrustListOutput(raw: string): TrustEntry | null {
107
+ return parseTrustListEntries(raw)[0] ?? null;
108
+ }
109
+
110
+ /** 登记比对 (纯函数): 逐字段列出与期望值的差异, 全一致返回空列表 */
111
+ export function diffTrust(
112
+ actual: TrustEntry,
113
+ expected: TrustExpectation,
114
+ ): string[] {
115
+ const problems: string[] = [];
116
+ if (actual.repository !== expected.repository) {
117
+ problems.push(
118
+ `repository: ${actual.repository} → 期望 ${expected.repository}`,
119
+ );
120
+ }
121
+ if (actual.file !== expected.file) {
122
+ problems.push(
123
+ `workflow 文件: ${actual.file ?? '(未设置)'} → 期望 ${expected.file}`,
124
+ );
125
+ }
126
+ if (actual.environment !== expected.environment) {
127
+ problems.push(
128
+ `environment: ${actual.environment ?? '(未设置)'} → 期望 ${expected.environment}`,
129
+ );
130
+ }
131
+ return problems;
132
+ }
133
+
134
+ /** OIDC 环境判定 (纯函数): 三分支各自对应不同出口, 防「权限漏配」被静默放过 */
135
+ export function classifyOidcEnv(
136
+ env: Record<string, string | undefined>,
137
+ ): OidcEnvVerdict {
138
+ if (env.GITHUB_ACTIONS !== 'true') return 'not-ci';
139
+ return env.ACTIONS_ID_TOKEN_REQUEST_URL !== undefined &&
140
+ env.ACTIONS_ID_TOKEN_REQUEST_TOKEN !== undefined
141
+ ? 'ready'
142
+ : 'missing-permission';
143
+ }
144
+
145
+ /** 生成经 pty 包装的 npm 调用坐标 (保证 npm web 认证交互的 TTY 要求) */
146
+ export function ptyWrapArgs(
147
+ platform: NodeJS.Platform,
148
+ npm: string,
149
+ args: string[],
150
+ ): { command: string; args: string[] } {
151
+ if (platform === 'darwin') {
152
+ return { command: 'script', args: ['-q', '/dev/null', npm, ...args] };
153
+ }
154
+ if (platform === 'linux') {
155
+ const quoted = [npm, ...args].map(shellQuote).join(' ');
156
+ return {
157
+ command: 'script',
158
+ args: ['-qec', quoted, '/dev/null'],
159
+ };
160
+ }
161
+ return { command: npm, args };
162
+ }
163
+
164
+ /** 预检核对面 (纯函数): 可发布 (非 private) 的包, 与发布链单源一致 */
165
+ export function filterPublishable(
166
+ packages: readonly WorkspacePackage[],
167
+ ): WorkspacePackage[] {
168
+ return packages.filter((pkg) => pkg.manifest.private !== true);
169
+ }