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
@@ -0,0 +1,299 @@
1
+ /**
2
+ * CLI 包发布自证脚本的共享收口层 (供工作区内全部 CLI 包共用)。
3
+ *
4
+ * 动机: 三个 CLI 包此前各自复制了 write-dist-manifest.ts / verify-release.ts /
5
+ * release-artifact.ts 的绝大多数逻辑 (~500 行), 已衍生出文案漂移、资产校验分叉与
6
+ * `import.meta.dir` vs `fileURLToPath` 不一致。本模块将共享的 git 采集、清单构建、
7
+ * 写盘、资产白名单展开与 CLI 入口收口在一处, 各包只保留纯声明配置。
8
+ */
9
+ import { existsSync, readFileSync, statSync, writeFileSync } from 'node:fs';
10
+ import { basename, join } from 'node:path';
11
+
12
+ import {
13
+ type DistState,
14
+ type PackFacts,
15
+ type ReleaseFacts,
16
+ type ReleaseVerdict,
17
+ type VerifyProfile,
18
+ judgeRelease,
19
+ normalizeCommit,
20
+ readDistState,
21
+ readGitText,
22
+ readPackFiles,
23
+ sha256File,
24
+ shortHash,
25
+ } from './release-verify.ts';
26
+
27
+ /** 产物身份清单的通用形状 */
28
+ export interface CliDistManifest {
29
+ schemaVersion: number;
30
+ commit: string | null;
31
+ dirty: boolean | null;
32
+ cliSha256: string;
33
+ builtAt: string;
34
+ }
35
+
36
+ /** 从 git 采集到的事实 (非 git 检出或 git 不可用时为 null) */
37
+ export interface GitFacts {
38
+ commit: string | null;
39
+ dirty: boolean | null;
40
+ }
41
+
42
+ /** 动态资产白名单的解析结果 */
43
+ export interface PackExpectation {
44
+ files: readonly string[] | null;
45
+ issue: string | null;
46
+ }
47
+
48
+ /** 资产清单白名单配置 (面向带 assets/template + assets/manifest.json 的包) */
49
+ export interface AssetPackConfig {
50
+ /** 不含动态模板的固定白名单项 (结果数组将保持此前缀顺序) */
51
+ baseFiles: readonly string[];
52
+ /** assets 目录名 (默认 assets) */
53
+ assetDir?: string;
54
+ /** 模板目录名 (默认 template) */
55
+ templateDir?: string;
56
+ /** 清单文件名 (默认 manifest.json) */
57
+ manifestFile?: string;
58
+ /** 期望 schemaVersion (默认 1) */
59
+ schemaVersion?: number;
60
+ /** npm 会静默过滤、严禁以原名落入模板资产的文件名黑名单 */
61
+ unshippableBasenames: readonly string[];
62
+ /** 是否一并拒绝任何以 `.` 开头的隐藏文件名 (供严禁隐藏点文件随包的场景) */
63
+ rejectDotfiles?: boolean;
64
+ }
65
+
66
+ /** 输出通道抽象 (与既有包内 ReleaseIo 接口兼容, 测试可注入内存缓冲) */
67
+ export interface ReleaseIo {
68
+ out: (line: string) => void;
69
+ err: (line: string) => void;
70
+ }
71
+
72
+ const DEFAULT_IO: ReleaseIo = {
73
+ out: (line) => process.stdout.write(`${line}\n`),
74
+ err: (line) => process.stderr.write(`${line}\n`),
75
+ };
76
+
77
+ /** 采集 git 事实: HEAD 提交哈希与工作树干净态 */
78
+ export function collectGitFacts(root: string): GitFacts {
79
+ const status = readGitText(root, ['status', '--porcelain']);
80
+ return {
81
+ commit: normalizeCommit(readGitText(root, ['rev-parse', 'HEAD'])),
82
+ dirty: status === null ? null : status.trim() !== '',
83
+ };
84
+ }
85
+
86
+ /** 构造产物身份清单 (纯函数) */
87
+ export function buildCliManifest(fields: {
88
+ cliSha256: string;
89
+ git: GitFacts;
90
+ builtAt: string;
91
+ schemaVersion?: number;
92
+ }): CliDistManifest {
93
+ return {
94
+ schemaVersion: fields.schemaVersion ?? 1,
95
+ commit: fields.git.commit,
96
+ dirty: fields.git.dirty,
97
+ cliSha256: fields.cliSha256,
98
+ builtAt: fields.builtAt,
99
+ };
100
+ }
101
+
102
+ /** 采集产物摘要并写出 dist/manifest.json; 产物缺失或零字节时返回 null 且不写盘 */
103
+ export function writeCliDistManifest(
104
+ distDir: string,
105
+ profile: Pick<VerifyProfile, 'entryFile' | 'manifestFile' | 'schemaVersion'>,
106
+ git: GitFacts,
107
+ builtAt: string,
108
+ ): CliDistManifest | null {
109
+ const entryPath = join(distDir, profile.entryFile);
110
+ if (!existsSync(entryPath)) return null;
111
+ const info = statSync(entryPath);
112
+ if (!info.isFile() || info.size === 0) return null;
113
+ const manifest = buildCliManifest({
114
+ cliSha256: sha256File(entryPath),
115
+ git,
116
+ builtAt,
117
+ schemaVersion: profile.schemaVersion,
118
+ });
119
+ writeFileSync(
120
+ join(distDir, profile.manifestFile),
121
+ `${JSON.stringify(manifest, null, 2)}\n`,
122
+ );
123
+ return manifest;
124
+ }
125
+
126
+ /** 把 git 事实翻译成简短人读标签 */
127
+ export function formatGitSourceLabel(manifest: CliDistManifest): string {
128
+ if (manifest.commit === null) return '非 git 检出 (未记录提交)';
129
+ const dirty = manifest.dirty === true ? ' (脏工作树)' : '';
130
+ return `提交 ${shortHash(manifest.commit)}${dirty}`;
131
+ }
132
+
133
+ /** 运行写清单 CLI 主流程 (返回退出码 0 / 1) */
134
+ export function runWriteDistManifestCli(
135
+ packageRoot: string,
136
+ profile: Pick<VerifyProfile, 'entryFile' | 'manifestFile' | 'schemaVersion'>,
137
+ io: ReleaseIo = DEFAULT_IO,
138
+ ): number {
139
+ const manifest = writeCliDistManifest(
140
+ join(packageRoot, 'dist'),
141
+ profile,
142
+ collectGitFacts(packageRoot),
143
+ new Date().toISOString(),
144
+ );
145
+ if (manifest === null) {
146
+ io.err(
147
+ `产物清单未写入: dist/${profile.entryFile} 缺失或为空, 先跑 bun build 产出产物`,
148
+ );
149
+ return 1;
150
+ }
151
+ io.out(
152
+ `产物清单已写入 dist/${profile.manifestFile}: ${formatGitSourceLabel(manifest)} · 摘要 ${shortHash(manifest.cliSha256)}`,
153
+ );
154
+ return 0;
155
+ }
156
+
157
+ /**
158
+ * 读取带动态模板资产包的期望发行白名单: 固定基座 + assets/manifest.json + 展开的模板资产路径。
159
+ * 任一校验不过 (缺失 / 非 JSON / schemaVersion 不符 / files 形状不符 / 含 npm 不可发名) 一律落 issue 不抛。
160
+ */
161
+ export function readAssetPackExpectation(
162
+ packageRoot: string,
163
+ config: AssetPackConfig,
164
+ ): PackExpectation {
165
+ const assetDir = config.assetDir ?? 'assets';
166
+ const templateDir = config.templateDir ?? 'template';
167
+ const manifestFile = config.manifestFile ?? 'manifest.json';
168
+ const expectedSchema = config.schemaVersion ?? 1;
169
+ const label = `${assetDir}/${manifestFile}`;
170
+ const manifestPath = join(packageRoot, assetDir, manifestFile);
171
+
172
+ if (!existsSync(manifestPath)) {
173
+ return {
174
+ files: null,
175
+ issue: `模板资产清单缺失 (${label} 不存在), 发行包白名单无从建立; 先跑构建 (bun run build)`,
176
+ };
177
+ }
178
+ let raw: string;
179
+ try {
180
+ raw = readFileSync(manifestPath, 'utf8');
181
+ } catch {
182
+ return { files: null, issue: `模板资产清单 (${label}) 读取失败` };
183
+ }
184
+ let parsed: unknown;
185
+ try {
186
+ parsed = JSON.parse(raw);
187
+ } catch {
188
+ return { files: null, issue: `模板资产清单 (${label}) 不是合法 JSON` };
189
+ }
190
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
191
+ return { files: null, issue: '模板资产清单应为 JSON 对象' };
192
+ }
193
+ const fields = parsed as Record<string, unknown>;
194
+ if (fields.schemaVersion !== expectedSchema) {
195
+ return {
196
+ files: null,
197
+ issue: `模板资产清单 schemaVersion 不受支持 (期望 ${expectedSchema})`,
198
+ };
199
+ }
200
+ if (
201
+ !Array.isArray(fields.files) ||
202
+ fields.files.length === 0 ||
203
+ fields.files.some(
204
+ (file) =>
205
+ typeof file !== 'string' ||
206
+ file === '' ||
207
+ file.includes('\\') ||
208
+ file.startsWith('/') ||
209
+ file.split('/').includes('..'),
210
+ )
211
+ ) {
212
+ return {
213
+ files: null,
214
+ issue: '模板资产清单 files 字段形状不符 (应为非空 POSIX 相对路径数组)',
215
+ };
216
+ }
217
+ const assets = fields.files as string[];
218
+ const blocked = new Set(config.unshippableBasenames);
219
+ const rejectDotfiles = config.rejectDotfiles === true;
220
+ const unshippable = assets.filter((file) => {
221
+ const base = basename(file);
222
+ return blocked.has(base) || (rejectDotfiles && base.startsWith('.'));
223
+ });
224
+ if (unshippable.length > 0) {
225
+ return {
226
+ files: null,
227
+ issue:
228
+ `模板资产含 npm 打包机制硬性剔除或易忽略的隐藏文件名 (发不到包里): ${unshippable.join(', ')}; ` +
229
+ '资产须以载体名随包并在生成期还原',
230
+ };
231
+ }
232
+ return {
233
+ files: [
234
+ ...config.baseFiles,
235
+ label,
236
+ ...assets.map((file) => `${assetDir}/${templateDir}/${file}`),
237
+ ],
238
+ issue: null,
239
+ };
240
+ }
241
+
242
+ /** 带可选动态资产白名单的 CLI 发布闸门判定 (纯函数) */
243
+ export function judgeCliRelease(
244
+ facts: ReleaseFacts,
245
+ profile: VerifyProfile,
246
+ expectation?: PackExpectation,
247
+ extraJudge?: () => string | null,
248
+ ): ReleaseVerdict {
249
+ if (expectation === undefined) {
250
+ return judgeRelease(facts, profile, extraJudge);
251
+ }
252
+ const combinedExtra = (): string | null => {
253
+ if (expectation.issue !== null) return expectation.issue;
254
+ return extraJudge === undefined ? null : extraJudge();
255
+ };
256
+ return judgeRelease(
257
+ facts,
258
+ { ...profile, packExpected: expectation.files ?? [] },
259
+ combinedExtra,
260
+ );
261
+ }
262
+
263
+ /** 运行 CLI 发布自证闸门 (返回退出码 0 / 1) */
264
+ export function runVerifyReleaseCli(
265
+ root: string,
266
+ profile: VerifyProfile,
267
+ io: ReleaseIo = DEFAULT_IO,
268
+ packFacts: PackFacts = readPackFiles(root),
269
+ expectation?: PackExpectation,
270
+ extraJudge?: () => string | null,
271
+ ): number {
272
+ const facts: ReleaseFacts = {
273
+ gitStatus: readGitText(root, ['status', '--porcelain']),
274
+ gitHead: normalizeCommit(readGitText(root, ['rev-parse', 'HEAD'])),
275
+ dist: readDistState(join(root, 'dist'), profile),
276
+ pack: packFacts,
277
+ };
278
+ const verdict = judgeCliRelease(facts, profile, expectation, extraJudge);
279
+ if (verdict.ok) {
280
+ io.out(
281
+ `发布前置校验通过: 提交 ${shortHash(verdict.commit)} · 产物摘要 ${shortHash(verdict.sha256)}`,
282
+ );
283
+ return 0;
284
+ }
285
+ io.err(`发布前置校验未通过: ${verdict.reason}`);
286
+ io.err(
287
+ ' 处置: 工作树不干净就提交或 stash 后重新构建再发 (bun run build 会同时写产物与清单);' +
288
+ ' 发行面包内文件与白名单不符就清掉包根的多余文件 (如备份移出仓库), 或同步白名单常量。',
289
+ );
290
+ return 1;
291
+ }
292
+
293
+ export type {
294
+ DistState,
295
+ PackFacts,
296
+ ReleaseFacts,
297
+ ReleaseVerdict,
298
+ VerifyProfile,
299
+ };
@@ -7,10 +7,17 @@
7
7
  * 再证产物就位 (存在 / 非空 / 可读), 然后让清单与提交、产物三者逐项对上, 专属判定,
8
8
  * 最后对发行面包内文件与白名单。
9
9
  */
10
- import { execFileSync } from 'node:child_process';
10
+ import { execFileSync, spawnSync } from 'node:child_process';
11
11
  import { createHash } from 'node:crypto';
12
- import { existsSync, readFileSync, statSync } from 'node:fs';
13
- import { join } from 'node:path';
12
+ import {
13
+ existsSync,
14
+ mkdtempSync,
15
+ readFileSync,
16
+ rmSync,
17
+ statSync,
18
+ } from 'node:fs';
19
+ import { tmpdir } from 'node:os';
20
+ import { join, win32 } from 'node:path';
14
21
 
15
22
  import { cleanGitEnv } from './git-env.ts';
16
23
 
@@ -251,6 +258,104 @@ export const parsePackFiles = (raw: string): string[] | null => {
251
258
  return paths;
252
259
  };
253
260
 
261
+ /** npm 子进程调用描述 */
262
+ export interface NpmCommandInvocation {
263
+ command: string;
264
+ args: string[];
265
+ /** Windows 回退 ComSpec /d /s /c 调 npm.cmd 时为 true */
266
+ windowsVerbatimArguments?: boolean;
267
+ }
268
+
269
+ /** 校验 Windows 绝对路径 (仅允许盘符绝对路径或 UNC 路径, 拒绝相对路径与 /usr/bin) */
270
+ const isWin32AbsolutePath = (dir: string): boolean =>
271
+ /^(?:[A-Za-z]:[/\\]|\\\\[^\\]+\\[^\\]+)/.test(dir);
272
+
273
+ const CMD_META_OR_SPACE_RE = /[\s&|<>^()%!]/;
274
+ const CMD_FORBIDDEN_RE = /[\r\n\0"]/;
275
+
276
+ const wrapCmdDoubleQuotes = (segment: string): string =>
277
+ `"${segment.replace(/(\\+)$/, '$1$1')}"`;
278
+
279
+ /** 转义传入 Windows .cmd 批处理的单个参数 (防御外层 cmd 与内部 %* 双层展开) */
280
+ const escapeWin32BatchArg = (arg: string): string => {
281
+ if (CMD_FORBIDDEN_RE.test(arg)) {
282
+ throw new Error('Windows 批处理调用参数包含不可安全转义的字符');
283
+ }
284
+ if (arg === '') return '""';
285
+ if (!CMD_META_OR_SPACE_RE.test(arg)) return arg;
286
+ if (!/[%!]/.test(arg)) return wrapCmdDoubleQuotes(arg);
287
+
288
+ let out = '';
289
+ let buf = '';
290
+ for (const ch of arg) {
291
+ if (ch === '%' || ch === '!') {
292
+ if (buf !== '') {
293
+ out += wrapCmdDoubleQuotes(buf);
294
+ buf = '';
295
+ }
296
+ out += `^^^${ch}`;
297
+ } else {
298
+ buf += ch;
299
+ }
300
+ }
301
+ if (buf !== '') out += wrapCmdDoubleQuotes(buf);
302
+ return out;
303
+ };
304
+
305
+ /** 构造搭配 cmd.exe /d /s /c + windowsVerbatimArguments: true 的单串命令 */
306
+ const buildNpmBatchCommandLine = (args: readonly string[]): string => {
307
+ const escapedArgs = args.map(escapeWin32BatchArg);
308
+ const inner =
309
+ escapedArgs.length === 0
310
+ ? '"npm.cmd"'
311
+ : `"npm.cmd" ${escapedArgs.join(' ')}`;
312
+ return `"${inner}"`;
313
+ };
314
+
315
+ /**
316
+ * 推导 npm 子进程调用方式 (跨平台零 shell):
317
+ * - POSIX 直接调 `npm`;
318
+ * - Windows 优先绕开 `npm.cmd` 批处理壳层 (Bun 在 Windows 下经 `shell: true` 调 `.cmd`
319
+ * 存在挂起与句柄占用风险, 亦规避 CVE-2024-27980 壳层转义问题), 定位 PATH 内的
320
+ * `node_modules/npm/bin/npm-cli.js` 并以原生 `node.exe` 直调; 极端定制环境再回退
321
+ * `cmd.exe /d /s /c` 单串命令并启用 `windowsVerbatimArguments: true`。
322
+ */
323
+ export const resolveNpmCommand = (
324
+ args: readonly string[],
325
+ platform: NodeJS.Platform = process.platform,
326
+ env: NodeJS.ProcessEnv = process.env,
327
+ pathExists: (path: string) => boolean = existsSync,
328
+ ): NpmCommandInvocation => {
329
+ if (platform !== 'win32') return { command: 'npm', args: [...args] };
330
+ const execPath = env.npm_execpath;
331
+ if (
332
+ typeof execPath === 'string' &&
333
+ /npm-cli\.js$/i.test(execPath) &&
334
+ pathExists(execPath)
335
+ ) {
336
+ return { command: 'node', args: [execPath, ...args] };
337
+ }
338
+ const pathList = (env.PATH ?? env.Path ?? '')
339
+ .split(';')
340
+ .map((item) => item.trim().replace(/^"|"$/g, ''))
341
+ .filter((item) => item !== '' && isWin32AbsolutePath(item));
342
+ for (const dir of pathList) {
343
+ const npmCli = win32.join(dir, 'node_modules', 'npm', 'bin', 'npm-cli.js');
344
+ if (!pathExists(npmCli)) continue;
345
+ const nodeExe = win32.join(dir, 'node.exe');
346
+ return {
347
+ command: pathExists(nodeExe) ? nodeExe : 'node',
348
+ args: [npmCli, ...args],
349
+ };
350
+ }
351
+ const comspec = env.ComSpec ?? env.COMSPEC ?? 'cmd.exe';
352
+ return {
353
+ command: comspec,
354
+ args: ['/d', '/s', '/c', buildNpmBatchCommandLine(args)],
355
+ windowsVerbatimArguments: true,
356
+ };
357
+ };
358
+
254
359
  /**
255
360
  * 跑 `npm pack --dry-run --json --ignore-scripts` 收发行面包内文件清单 (只读, 不落 tarball)。
256
361
  *
@@ -260,25 +365,51 @@ export const parsePackFiles = (raw: string): string[] | null => {
260
365
  * 采集失败 (npm 不在 PATH / 非零退出 / 输出非 JSON) 一律落 issue, 不抛: 判定层按「采不到就拒」处理。
261
366
  */
262
367
  export const readPackFiles = (root: string): PackFacts => {
263
- // Windows 的 npm 是 npm.cmd, execFile 不走 shell 时不会自动补扩展名
264
- const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
368
+ const cacheDir = mkdtempSync(join(tmpdir(), 'npm-pack-cache-'));
265
369
  let raw: string;
266
370
  try {
267
- raw = execFileSync(
268
- npm,
269
- ['pack', '--dry-run', '--json', '--ignore-scripts'],
270
- {
271
- cwd: root,
272
- encoding: 'utf8',
273
- stdio: ['ignore', 'pipe', 'ignore'],
274
- maxBuffer: 32 * 1024 * 1024,
371
+ const invocation = resolveNpmCommand([
372
+ 'pack',
373
+ '--dry-run',
374
+ '--json',
375
+ '--ignore-scripts',
376
+ '--no-update-notifier',
377
+ '--cache',
378
+ cacheDir,
379
+ ]);
380
+ const result = spawnSync(invocation.command, invocation.args, {
381
+ cwd: root,
382
+ encoding: 'utf8',
383
+ stdio: ['ignore', 'pipe', 'ignore'],
384
+ maxBuffer: 32 * 1024 * 1024,
385
+ windowsVerbatimArguments: invocation.windowsVerbatimArguments,
386
+ env: {
387
+ ...process.env,
388
+ NO_UPDATE_NOTIFIER: '1',
389
+ npm_config_update_notifier: 'false',
390
+ npm_config_fund: 'false',
391
+ npm_config_audit: 'false',
275
392
  },
276
- );
393
+ });
394
+ if (result.error !== undefined || result.status !== 0) {
395
+ return {
396
+ files: null,
397
+ issue: 'npm pack 跑不起来 (需要 npm: 不在 PATH 或非零退出)',
398
+ };
399
+ }
400
+ raw = result.stdout ?? '';
277
401
  } catch {
278
402
  return {
279
403
  files: null,
280
404
  issue: 'npm pack 跑不起来 (需要 npm: 不在 PATH 或非零退出)',
281
405
  };
406
+ } finally {
407
+ rmSync(cacheDir, {
408
+ recursive: true,
409
+ force: true,
410
+ maxRetries: 5,
411
+ retryDelay: 100,
412
+ });
282
413
  }
283
414
  const files = parsePackFiles(raw);
284
415
  if (files === null) {
@@ -404,9 +535,11 @@ export const judgeRelease = (
404
535
  };
405
536
  }
406
537
  if (dist.manifest.commit !== gitHead) {
538
+ const manifestCommit =
539
+ typeof dist.manifest.commit === 'string' ? dist.manifest.commit : null;
407
540
  return {
408
541
  ok: false,
409
- reason: `产物清单记录的提交 ${shortHash(String(dist.manifest.commit))} 与 HEAD ${shortHash(gitHead)} 不一致, 产物不是本次提交构建的`,
542
+ reason: `产物清单记录的提交 ${shortHash(manifestCommit)} 与 HEAD ${shortHash(gitHead)} 不一致, 产物不是本次提交构建的`,
410
543
  };
411
544
  }
412
545
  if (dist.manifest[profile.shaField] !== dist.entrySha256) {
@@ -8,7 +8,11 @@ import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
8
8
  import { dirname, join } from 'node:path';
9
9
 
10
10
  import { makeTmpRoot } from './tmp-root.ts';
11
- import { listWorkspacePackages, resolveCliAndApi } from './workspace.ts';
11
+ import {
12
+ listWorkspacePackages,
13
+ resolveCliAndApi,
14
+ resolveProductPairs,
15
+ } from './workspace.ts';
12
16
 
13
17
  const roots: string[] = [];
14
18
  function makeRoot(files: Record<string, unknown>): string {
@@ -89,4 +93,62 @@ describe('resolveCliAndApi', () => {
89
93
  });
90
94
  expect(() => listWorkspacePackages(root)).toThrow(/暂不支持派生/);
91
95
  });
96
+
97
+ test('多组双包产品并存时: resolveProductPairs 全量返回, resolveCliAndApi 须显式指定', () => {
98
+ const root = makeRoot({
99
+ 'package.json': { workspaces: ['packages/*'] },
100
+ 'packages/alpha/package.json': { name: '@x/alpha' },
101
+ 'packages/alpha-cli/package.json': {
102
+ name: '@x/alpha-cli',
103
+ bin: { alpha: 'bin/alpha.mjs' },
104
+ devDependencies: { '@x/alpha': '1.0.0' },
105
+ },
106
+ 'packages/beta/package.json': { name: '@x/beta' },
107
+ 'packages/beta-cli/package.json': {
108
+ name: '@x/beta-cli',
109
+ bin: { beta: 'bin/beta.mjs' },
110
+ dependencies: { '@x/beta': '1.0.0' },
111
+ },
112
+ });
113
+ const pairs = resolveProductPairs(root);
114
+ expect(pairs.map((p) => `${p.cli.name}->${p.api.name}`)).toEqual([
115
+ '@x/alpha-cli->@x/alpha',
116
+ '@x/beta-cli->@x/beta',
117
+ ]);
118
+ expect(() => resolveCliAndApi(root)).toThrow(/请传入 productHint/);
119
+ expect(resolveCliAndApi(root, '@x/beta').cli.name).toBe('@x/beta-cli');
120
+ expect(resolveCliAndApi(root, 'packages/alpha-cli').api.name).toBe(
121
+ '@x/alpha',
122
+ );
123
+ expect(() => resolveCliAndApi(root, '@x/missing')).toThrow(
124
+ /未找到匹配 @x\/missing/,
125
+ );
126
+ });
127
+
128
+ test('仓内存在多 CLI 共享私有库时, 双包配对精准锚定专属 API 包且单包 CLI 不误配', () => {
129
+ const root = makeRoot({
130
+ 'package.json': { workspaces: ['packages/*'] },
131
+ 'packages/shared-utils/package.json': {
132
+ name: '@x/shared-utils',
133
+ private: true,
134
+ clisRole: 'shared-lib',
135
+ },
136
+ 'packages/create-x/package.json': {
137
+ name: 'create-x',
138
+ bin: { 'create-x': 'bin/create-x.mjs' },
139
+ devDependencies: { '@x/shared-utils': '1.0.0' },
140
+ },
141
+ 'packages/tool/package.json': { name: '@x/tool' },
142
+ 'packages/tool-cli/package.json': {
143
+ name: '@x/tool-cli',
144
+ bin: { tool: 'bin/tool.mjs' },
145
+ devDependencies: { '@x/shared-utils': '1.0.0', '@x/tool': '1.0.0' },
146
+ },
147
+ });
148
+ const pairs = resolveProductPairs(root);
149
+ expect(pairs.map((p) => `${p.cli.name}->${p.api.name}`)).toEqual([
150
+ '@x/tool-cli->@x/tool',
151
+ ]);
152
+ expect(resolveCliAndApi(root).api.name).toBe('@x/tool');
153
+ });
92
154
  });