dsh-git-push 2.16.1 → 2.18.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.
package/README.md CHANGED
@@ -17,7 +17,8 @@ DSH 的 git 提交推送与代码审计插件:提交前自动过审计门禁
17
17
  | 改名 | 给远程仓库改名(dryRun 默认开,列出旧名出现位置) | `git_remote_rename` / `rename` |
18
18
  | 凭据与账号 | 校验 GitHub token 与 SSH 公钥、生成密钥对 | `git_account_check` / `git_gen_ssh_key` |
19
19
  | 身份改写 | 把历史提交身份统一成登录账号 | `git_identity_rewrite` / `identity-rewrite` |
20
- | npm 发包 | 发布前体检,默认 dry-run,真发需二次确认 | `npm_publish` / `npm-publish` |
20
+ | 发布 | 发布 npm 包(dryRun 默认只体检;含发布前冒烟) | `npm_publish` / — |
21
+ | 撤包 | 从 registry 撤版本(默认 dryRun 预检,不可逆) | `npm_unpublish` / `unpublish` |
21
22
  | 豁免标记 | 给文件加/删豁免注释并校验是否真生效 | `exempt` |
22
23
  | I/O 风险扫描 | 扫描读写操作的风险分级 | `io_scan` / `file-io` |
23
24
  | 链接检查 | 检查文档里的 URL 是否有效 | `link_check` / `link-check` |
@@ -42,6 +42,8 @@ export const TOOL_REGISTRY = [
42
42
  { flag: 'auditExemptPaths', type: 'array', desc: '本次提交按文件临时豁免审计(数组,相对仓库根):所列文件的 finding 不参与拦截判定(含 blocker);仅本次有效,不落盘、不改 .auditignore' },
43
43
  { flag: 'auditExemptReason', type: 'string', desc: '豁免理由(可选,仅回显,不作拦截条件)' },
44
44
  { flag: 'remote', type: 'string', desc: '推送目标 remote(多 remote / fork 场景;缺省 origin)。推送与核验使用同一 remote' },
45
+ { flag: 'waitCi', type: 'boolean', desc: '推送后等 CI 结果(默认不等):按推送的 sha 查 GitHub Actions,全绿=通过、任一失败=ciFailed、超时/无 CI 如实回报' },
46
+ { flag: 'ciTimeoutSec', type: 'number', desc: '等 CI 的上限秒数(默认 900)' },
45
47
  ],
46
48
  },
47
49
  {
@@ -120,6 +122,16 @@ export const TOOL_REGISTRY = [
120
122
  { flag: 'writeOnly', type: 'boolean', desc: '只看写操作' },
121
123
  ],
122
124
  },
125
+ {
126
+ name: 'npm_unpublish', cli: 'unpublish', description: '从 npm registry 撤包(不可逆):默认 dryRun 只预检——查版本是否存在、是否被 dist-tag 指向、发布距今是否在 72h 窗口内、是否该包唯一版本,并说明撤掉的后果;真撤需同时传 dryRun:false 与 confirm:true。超出 72h 只有「无依赖者+周下载<300+单一维护者」才允许,不满足请改用 deprecate',
127
+ params: [
128
+ { flag: 'name', type: 'string', positional: 0, required: true, desc: '包名(支持 @scope/name)' },
129
+ { flag: 'version', type: 'string', positional: 1, desc: '要撤的版本(整包撤请改用 wholePackage:true)' },
130
+ { flag: 'wholePackage', type: 'boolean', desc: '撤整个包(所有版本,会给 npm unpublish 加 --force)' },
131
+ { flag: 'dryRun', type: 'boolean', desc: '只预检不真撤(默认 true)' },
132
+ { flag: 'confirm', type: 'boolean', desc: '真撤确认(dryRun:false 时必填)' },
133
+ ],
134
+ },
123
135
  {
124
136
  name: 'npm_publish', cli: 'npm-publish',
125
137
  description: 'npm 发包(后台 job + dryRun):默认 dryRun=true 只做体检与 npm publish --dry-run(不写 registry);真发必须同时 confirm=true 且 dryRun=false。dir=目标包目录(缺省工作区)、tag=发布 tag(默认 latest)、otp=2FA 一次性口令(可选)。前置体检:private:true 拦截、同名版本占用检测、npm pack 文件清单',
@@ -71,6 +71,10 @@ async function pushWithPostSteps(args, env, cfg) {
71
71
  // 推送门禁——开启时 push 需显式放行(pushConfirmed:true);未放行返回 PUSH_GATE 拦截
72
72
  pushGate: cfg.pushGate === true,
73
73
  pushConfirmed: args.pushConfirmed === true,
74
+ // 推送后等 CI 结果(默认不等):按推到远端的那个 sha 查 Actions,
75
+ // 全绿=通过、任一失败=ciFailed、超时/无 CI 如实回报(都不改变推送本身成功的事实)
76
+ waitCi: args.waitCi === true || cfg.waitCi === true,
77
+ ciTimeoutSec: Number(args.ciTimeoutSec) > 0 ? Number(args.ciTimeoutSec) : 900,
74
78
  // 精确 add 路径(逗号分隔,相对 repo);空 = git add -A 全量
75
79
  paths: String(args.paths || ''),
76
80
  });
@@ -598,6 +602,20 @@ export async function callTool(toolName, args = {}, env = {}, cfg = defaultConfi
598
602
  }
599
603
  case 'npm_publish':
600
604
  return callNpmPublishJob(args, jobs, exec, log, env, cfg);
605
+ case 'npm_unpublish': {
606
+ // 撤包不可逆:默认 dryRun(只预检并说明后果),真撤要 dryRun:false + confirm:true
607
+ const dryRun = !(args.dryRun === false || args.dryRun === 'false' || args.noDryRun === true);
608
+ const { unpublishPackage } = await import('../npm/unpublish.js');
609
+ return unpublishPackage({
610
+ name: String(args.name || args.pkg || ''),
611
+ version: String(args.version || ''),
612
+ wholePackage: args.wholePackage === true,
613
+ registry: cfg?.npmRegistry || '',
614
+ workspaceRoot: env.workspaceRoot || '',
615
+ dryRun,
616
+ confirm: args.confirm === true,
617
+ });
618
+ }
601
619
  case 'git_remote_create': {
602
620
  if (!args.repo) return { ok: false, error: MSG_REPO_REQUIRED };
603
621
  const created = await ensureRemoteRepo({ repoPath: args.repo, visibility: args.visibility || 'private', dryRun: args.dryRun === true });
package/lib/git/ci.js ADDED
@@ -0,0 +1,135 @@
1
+ /**
2
+ * CI(GitHub Actions)结果等待 —— 推送后确认真跑绿了,而不是"推上去就算完成"。
3
+ *
4
+ * 为什么需要:推送成功只代表代码到了远端,构建/测试是否通过是另一回事。
5
+ * 实测事故:一次提交推送成功,CI 在同一 SHA 上挂了(我加的一个测试假设了 CIFS 特性,
6
+ * 在 ext4 runner 上必然失败)——只看推送结果完全发现不了。
7
+ *
8
+ * 设计取舍:
9
+ * · **只读**(GET /actions/runs),不触发、不重跑;
10
+ * · 按 **head_sha** 查,而不是查"最新一次 run"——否则并发提交会拿到别人的结果;
11
+ * · 多 workflow 同时存在时**全绿才算通过**(任一失败即 failure);
12
+ * · 刚推上去时 run 可能还没创建,给一段 grace(默认 60s)再判定「没有 CI」;
13
+ * · 超时不算失败、也不算通过,单独给 `timeout`,让调用方自己决定怎么处理。
14
+ */
15
+ import { runGit } from './exec.js';
16
+ import { githubFetch } from './api.js';
17
+ import { parseOwnerRepoFromRemote } from './remote.js';
18
+
19
+ const DEFAULT_TIMEOUT_MS = 15 * 60 * 1000;
20
+ const DEFAULT_POLL_MS = 15 * 1000;
21
+ const DEFAULT_GRACE_MS = 60 * 1000;
22
+
23
+ /** 视为「通过」的结论集合(neutral/skipped 不算红)。 */
24
+ const OK_CONCLUSIONS = new Set(['success', 'neutral', 'skipped']);
25
+
26
+ /** 从本地仓库解析 owner/repo(origin 优先,其次任意 GitHub remote)。 */
27
+ export function resolveRepoIdentity(repoPath) {
28
+ const origin = runGit(['remote', 'get-url', 'origin'], { cwd: repoPath });
29
+ const fromOrigin = parseOwnerRepoFromRemote(origin.stdout || origin.stderr || '');
30
+ if (fromOrigin.owner && fromOrigin.repo) return fromOrigin;
31
+ const all = runGit(['remote', '-v'], { cwd: repoPath });
32
+ for (const line of String(all.stdout || '').split('\n')) {
33
+ const url = line.split(/\s+/)[1] || '';
34
+ const parsed = parseOwnerRepoFromRemote(url);
35
+ if (parsed.owner && parsed.repo) return parsed;
36
+ }
37
+ return { owner: '', repo: '' };
38
+ }
39
+
40
+ /**
41
+ * 查某次提交触发的所有 workflow run。
42
+ * @returns {Promise<{ok:boolean, runs:Array<object>, error?:string}>}
43
+ */
44
+ export async function fetchRunsForSha({ owner, repo, sha, token = '', fetchImpl = githubFetch, perPage = 50 } = {}) {
45
+ if (!owner || !repo) return { ok: false, runs: [], error: '缺 owner/repo' };
46
+ if (!sha) return { ok: false, runs: [], error: '缺 sha' };
47
+ const res = await fetchImpl(`/repos/${owner}/${repo}/actions/runs?head_sha=${encodeURIComponent(sha)}&per_page=${perPage}`, { token });
48
+ if (res.status !== 200) return { ok: false, runs: [], error: res.json?.message || res.error || `HTTP ${res.status}` };
49
+ const runs = (res.json?.workflow_runs || []).map((r) => ({
50
+ id: r.id,
51
+ name: r.name || r.display_title || `run ${r.id}`,
52
+ status: r.status || '',
53
+ conclusion: r.conclusion || '',
54
+ // html_url 是 GitHub 的原字段;测试注入的桩可能直接用 url —— 两者都认,避免因字段名不同丢链接
55
+ url: r.html_url || r.url || '',
56
+ event: r.event || '',
57
+ headSha: r.head_sha || '',
58
+ }));
59
+ return { ok: true, runs };
60
+ }
61
+
62
+ /**
63
+ * 汇总一组 run 的结论(纯函数,便于单测)。
64
+ * @returns {{total:number, pending:number, failing:number, ok:number,
65
+ * conclusion:'none'|'pending'|'success'|'failure', failingRuns:Array<object>}}
66
+ */
67
+ export function summarizeRuns(runs = []) {
68
+ let pending = 0;
69
+ let failing = 0;
70
+ let ok = 0;
71
+ const failingRuns = [];
72
+ for (const r of runs) {
73
+ if (r.status && r.status !== 'completed') { pending += 1; continue; }
74
+ if (OK_CONCLUSIONS.has(String(r.conclusion || '').toLowerCase())) { ok += 1; continue; }
75
+ failing += 1;
76
+ failingRuns.push(r);
77
+ }
78
+ const conclusion = !runs.length ? 'none' : pending ? 'pending' : failing ? 'failure' : 'success';
79
+ return { total: runs.length, pending, failing, ok, conclusion, failingRuns };
80
+ }
81
+
82
+ /**
83
+ * 等某次提交的 CI 出结果。
84
+ *
85
+ * @param {{repoPath?:string, owner?:string, repo?:string, sha:string, token?:string,
86
+ * timeoutMs?:number, pollMs?:number, graceMs?:number,
87
+ * fetchImpl?:Function, sleep?:Function, now?:Function}} o
88
+ * @returns {Promise<{ok:boolean, conclusion:'success'|'failure'|'pending'|'timeout'|'none',
89
+ * runs:Array<object>, summary:object, failing?:Array<object>, url?:string,
90
+ * timedOut?:boolean, note?:string, error?:string}>}
91
+ */
92
+ export async function waitForCi({
93
+ repoPath = '', owner = '', repo = '', sha = '', token = '',
94
+ timeoutMs = DEFAULT_TIMEOUT_MS, pollMs = DEFAULT_POLL_MS, graceMs = DEFAULT_GRACE_MS,
95
+ fetchImpl = githubFetch, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), now = () => Date.now(),
96
+ } = {}) {
97
+ let own = { owner, repo };
98
+ if ((!own.owner || !own.repo) && repoPath) own = resolveRepoIdentity(repoPath);
99
+ if (!own.owner || !own.repo) return { ok: false, conclusion: 'none', runs: [], summary: summarizeRuns([]), error: '无法解析 owner/repo(origin 不是 GitHub 地址)' };
100
+ const started = now();
101
+ let lastSummary = summarizeRuns([]);
102
+ for (;;) {
103
+ const res = await fetchRunsForSha({ owner: own.owner, repo: own.repo, sha, token, fetchImpl });
104
+ if (!res.ok) return { ok: false, conclusion: 'none', runs: [], summary: lastSummary, error: res.error };
105
+ const summary = summarizeRuns(res.runs);
106
+ lastSummary = summary;
107
+ const elapsed = now() - started;
108
+ if (summary.conclusion === 'none') {
109
+ // run 还没创建:给一段 grace,超过就认为该提交没有 CI
110
+ if (elapsed >= graceMs) {
111
+ return { ok: true, conclusion: 'none', runs: res.runs, summary, note: `该提交未触发 CI(已等 ${Math.round(elapsed / 1000)}s)` };
112
+ }
113
+ await sleep(Math.min(pollMs, Math.max(0, graceMs - elapsed)));
114
+ continue;
115
+ }
116
+ if (summary.conclusion !== 'pending') {
117
+ return {
118
+ ok: summary.conclusion === 'success',
119
+ conclusion: summary.conclusion,
120
+ runs: res.runs,
121
+ summary,
122
+ ...(summary.failing ? { failing: summary.failingRuns.map((r) => ({ name: r.name, url: r.url, conclusion: r.conclusion })) } : {}),
123
+ url: summary.failingRuns[0]?.url || res.runs[0]?.url || '',
124
+ };
125
+ }
126
+ if (elapsed >= timeoutMs) {
127
+ return {
128
+ ok: false, conclusion: 'timeout', timedOut: true, runs: res.runs, summary,
129
+ note: `CI 在 ${Math.round(timeoutMs / 1000)}s 内未出结果(仍在跑)`,
130
+ url: res.runs[0]?.url || '',
131
+ };
132
+ }
133
+ await sleep(Math.min(pollMs, Math.max(0, timeoutMs - elapsed)));
134
+ }
135
+ }
package/lib/git/push.js CHANGED
@@ -7,6 +7,7 @@
7
7
  */
8
8
 
9
9
  import { describeHooks, probeHooks } from './hooks.js';
10
+ import { waitForCi } from './ci.js';
10
11
  import { existsSync } from 'node:fs';
11
12
  import { join } from 'node:path';
12
13
  import { autoTagDSHProject, ensureAuxSshRemote, readPkgVersion, updateRemoteTrackingRef } from './post-push.js';
@@ -55,7 +56,13 @@ import { resolveRepoVisibility, cachedVisibility } from './visibility.js';
55
56
  * customIgnorePatterns:逗号/换行分隔的 gitignore pattern,追加进 .gitignore(幂等)
56
57
  * @returns {{ok, steps: string[], commitSha?, pushed?, push?, remoteHeads?, error?}}
57
58
  */
58
- export async function commitAndPush({ repoPath = '', message = '', messageItems = null, push = true, dryRun = false, token = '', customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh', pushGate = false, pushConfirmed = false, paths = '', remote = '' } = {}) {
59
+ export async function commitAndPush({
60
+ repoPath = '', message = '', messageItems = null, push = true, dryRun = false, token = '',
61
+ customIgnorePatterns = '', requirementsConfirmed = false, force = false, pushMethod = 'ssh',
62
+ pushGate = false, pushConfirmed = false, paths = '', remote = '',
63
+ // 推送后是否等 CI 结果(默认不等:多数推送不需要阻塞);ciTimeoutSec 为等待上限
64
+ waitCi = false, ciTimeoutSec = 900,
65
+ } = {}) {
59
66
  const steps = [];
60
67
  if (!repoPath || !existsSync(join(repoPath, '.git'))) return { ok: false, steps: ['预检'], error: `非 git 仓库: ${repoPath || '(空)'}` };
61
68
  // message 支持三种形态(字符串 / 数组 / {subject,items}):在预检处**单点**组装成规范提交信息,
@@ -211,6 +218,18 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
211
218
  legacyIdentity,
212
219
  };
213
220
  }
221
+ /**
222
+ * 推送后按需等待 CI。用 commitSha(推到远端的那个提交)而不是"最新 run",
223
+ * 否则并发提交时会把别人的结果当自己的。超时/无 CI 都不算失败,只如实回报。
224
+ */
225
+ const collectCi = async () => {
226
+ if (!waitCi) return null;
227
+ try {
228
+ return await waitForCi({ repoPath, sha: commitSha, token, timeoutMs: Math.max(30, Number(ciTimeoutSec) || 900) * 1000 });
229
+ } catch (e) {
230
+ return { ok: false, conclusion: 'none', error: `等待 CI 出错:${String(e?.message || e).slice(0, 200)}`, runs: [], summary: { total: 0 } };
231
+ }
232
+ };
214
233
  steps.push('push');
215
234
  // 通道由 dispatchPush 单点决策(默认 SSH:推本地 HEAD、远端 sha 与本地一致;无密钥才回落 API)。
216
235
  // ⚠️ dispatchPush 是 async:必须 await(旧 bug:同步调用导致 pr.ok 恒 undefined,推送从未成功)
@@ -219,7 +238,10 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
219
238
  // D24:pr.pushed=false(内容级短路「远端已是最新」)→ 如实 pushed:false(commitPushDoPush 语义)
220
239
  // committed 必须如实带上:cleanSkipCommit 时本次**没有产生新提交**。
221
240
  // 此前这条路径缺 committed 字段,job 输出就兜底成「已提交,未推送」——与实际相反 ✗(实测复现)
222
- if (!pr.pushed) return { ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: false, push: pr, identity, legacyIdentity };
241
+ if (!pr.pushed) {
242
+ const ci = await collectCi();
243
+ return { ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: false, push: pr, identity, legacyIdentity, ...(ci ? { ci } : {}) };
244
+ }
223
245
  // 推送后增强对两条通道一视同仁:remote-tracking ref + aux remote + autoTag + remote heads。
224
246
  // 原先只有 API 分支做这些,SSH 分支只拉 heads → 走 SSH 时本地 origin/<branch> 引用不更新,
225
247
  // 下次 ahead/behind 判断就会错位。
@@ -238,7 +260,13 @@ export async function commitAndPush({ repoPath = '', message = '', messageItems
238
260
  };
239
261
  }
240
262
  // committed 如实带上:cleanSkipCommit 时推的是**此前已提交的领先内容**,本次没有新提交
241
- return { ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: true, push: enhanced.push, autoTag: enhanced.autoTag, ...(enhanced.heads ? { remoteHeads: enhanced.heads } : {}), identity, legacyIdentity };
263
+ const ci = await collectCi();
264
+ if (ci) steps.push(`ci-${ci.conclusion}`);
265
+ return {
266
+ ok: true, steps, commitSha, committed: !cleanSkipCommit, pushed: true, push: enhanced.push,
267
+ autoTag: enhanced.autoTag, ...(enhanced.heads ? { remoteHeads: enhanced.heads } : {}), identity, legacyIdentity,
268
+ ...(ci ? { ci, ...(ci.conclusion === 'failure' ? { ciFailed: true } : {}) } : {}),
269
+ };
242
270
  }
243
271
  // 失败回执附结构化诊断(分类 + 置信度 + 下一步)
244
272
  const dg = pr.diagnosis || classifyPushFailure(String(pr.reason || ''), { method: pr.method });
@@ -0,0 +1,131 @@
1
+ /**
2
+ * npm 撤包(`npm unpublish`)。
3
+ *
4
+ * 为什么单独做、且**默认 dryRun**:撤包不可逆——
5
+ * · 一个 `包@版本` 一旦用过,即使撤掉也**永久不能再发**同一个号;
6
+ * · 官方只承诺 registry 不再提供,不承诺清 CDN/第三方镜像/已下载副本;
7
+ * · 撤掉 `latest` 会让 dist-tags 悬空,影响所有 `npm i <包>` 的人。
8
+ * 所以调用方必须先看清「要撤什么、撤完会怎样」,再显式 `confirm` 才真撤。
9
+ *
10
+ * 预检能回答什么(都不联网到第三方,只查 registry 元数据):
11
+ * · 版本是否存在;dist-tags 是否指向它(撤 latest 有额外影响);
12
+ * · 发布距今是否在 72 小时窗口内(窗口内且无依赖者才符合官方条件);
13
+ * · 是否该包唯一版本(撤光会让包名冷却 24h)。
14
+ * 预检**不能**回答:是否有其它包依赖它(公共 registry 没有 reverse-deps 接口),
15
+ * 这一条只能由 npm 服务端判定,失败时如实把 npm 的报错回传。
16
+ */
17
+ import { DEFAULT_REGISTRY, NPM_TIMEOUT_MS, normalizeRegistry, runNpm } from './registry.js';
18
+ import { npmArgs, writeNpmrc } from './npmrc.js';
19
+ import { readNpmToken } from '../core/credentials.js';
20
+
21
+ /** 官方 unpublish 政策里的时间窗:发布 72h 内(且无依赖者)可自由撤。 */
22
+ const UNPUBLISH_WINDOW_MS = 72 * 60 * 60 * 1000;
23
+ /** 整包撤光后,同名包 24h 内不能发布。 */
24
+ const WHOLE_PACKAGE_COOLDOWN_MS = 24 * 60 * 60 * 1000;
25
+
26
+ /** 归一化包名/版本入参,做前置校验(不联网)。 */
27
+ export function parseTarget({ name = '', version = '', wholePackage = false } = {}) {
28
+ const pkg = String(name || '').trim();
29
+ const ver = String(version || '').trim();
30
+ if (!pkg) return { ok: false, error: '缺 name(要撤的包名)' };
31
+ if (!/^(@[a-z0-9][\w.-]*\/)?[a-z0-9][\w.-]*$/i.test(pkg)) return { ok: false, error: `包名不合法:${pkg}` };
32
+ if (!wholePackage && !ver) return { ok: false, error: '缺 version;若确实要撤整个包,请显式传 wholePackage:true(会连带撤所有版本)' };
33
+ if (!wholePackage && !/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(ver)) return { ok: false, error: `版本号不合法:${ver}` };
34
+ return { ok: true, name: pkg, version: ver, wholePackage: wholePackage === true };
35
+ }
36
+
37
+ /**
38
+ * 预检:查 registry 元数据,给出「撤这个版本会发生什么」。
39
+ * @param {{name:string, version:string, wholePackage?:boolean,
40
+ * registry?:string, timeoutMs?:number, fetchImpl?:Function}} o
41
+ */
42
+ export async function preflightUnpublish({ name = '', version = '', wholePackage = false, registry = DEFAULT_REGISTRY, timeoutMs = NPM_TIMEOUT_MS, fetchImpl = globalThis.fetch } = {}) {
43
+ const target = parseTarget({ name, version, wholePackage });
44
+ if (!target.ok) return { ok: false, error: target.error };
45
+ const reg = normalizeRegistry(registry);
46
+ const url = `${reg.replace(/\/$/, '')}/${name.replace('/', '%2f')}`;
47
+ const ctrl = new AbortController();
48
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
49
+ try {
50
+ const res = await fetchImpl(url, { signal: ctrl.signal, headers: { accept: 'application/json' } });
51
+ if (res.status === 404) return { ok: false, error: `registry 上不存在该包:${name}` };
52
+ if (res.status !== 200) return { ok: false, error: `查询失败:HTTP ${res.status}` };
53
+ const doc = await res.json();
54
+ const versions = Object.keys(doc.versions || {});
55
+ const publishedAt = (doc.time || {})[target.version] || '';
56
+ const ageMs = publishedAt ? Date.now() - Date.parse(publishedAt) : null;
57
+ const tagsPointingHere = Object.entries(doc['dist-tags'] || {}).filter(([, v]) => v === target.version).map(([t]) => t);
58
+ if (!wholePackage && !versions.includes(target.version)) {
59
+ return { ok: false, error: `版本不存在:${name}@${target.version}(现有版本:${versions.join(', ')})` };
60
+ }
61
+ const warnings = [];
62
+ if (tagsPointingHere.length) {
63
+ warnings.push(`dist-tag ${tagsPointingHere.join('/')} 指向该版本:撤掉后这些 tag 会失效/悬空(建议先把 tag 移到其它版本)`);
64
+ }
65
+ if (versions.length <= 1) {
66
+ warnings.push(`该包只有 1 个版本:撤光后同名包名将冷却 ${WHOLE_PACKAGE_COOLDOWN_MS / 3600000} 小时`);
67
+ }
68
+ return {
69
+ ok: true,
70
+ name, version: target.version, wholePackage: target.wholePackage,
71
+ exists: true,
72
+ versions,
73
+ publishedAt,
74
+ ageHours: ageMs === null ? null : Math.round(ageMs / 3600000),
75
+ withinWindow: ageMs === null ? null : ageMs <= UNPUBLISH_WINDOW_MS,
76
+ tagsPointingHere,
77
+ warnings,
78
+ // 72h 内只是「可以申请撤」的必要条件之一;依赖者一条只有服务端能判
79
+ policyHint: ageMs !== null && ageMs > UNPUBLISH_WINDOW_MS
80
+ ? '已超出 72h 窗口:只有「无依赖者 + 近一周下载<300 + 单一维护者」三者同时满足才允许撤,否则只能 npm deprecate'
81
+ : '在 72h 窗口内:无其它包依赖它时可直接撤',
82
+ // 撤包不可逆的提醒:即使成功,该版本号也永久作废
83
+ irreversible: `撤掉后 ${name}@${target.version} 永久不能再发布(只能发新版本号)`,
84
+ };
85
+ } catch (e) {
86
+ return { ok: false, error: `查询失败:${String(e?.message || e).slice(0, 200)}` };
87
+ } finally { clearTimeout(timer); }
88
+ }
89
+
90
+ /**
91
+ * 执行撤包。
92
+ * @param {{name:string, version?:string, wholePackage?:boolean, registry?:string,
93
+ * workspaceRoot?:string, dryRun?:boolean, confirm?:boolean, timeoutMs?:number}} o
94
+ */
95
+ export async function unpublishPackage({
96
+ name = '', version = '', wholePackage = false,
97
+ registry = DEFAULT_REGISTRY, workspaceRoot = '',
98
+ dryRun = true, confirm = false, timeoutMs = 120000,
99
+ } = {}) {
100
+ const pre = await preflightUnpublish({ name, version, wholePackage, registry });
101
+ if (!pre.ok) return { ok: false, blocked: 'preflight-failed', error: pre.error };
102
+ if (dryRun) {
103
+ return {
104
+ ok: true, dryRun: true, ...pre,
105
+ wouldRun: `npm unpublish ${name}${wholePackage ? '' : `@${pre.version}`}${wholePackage ? ' --force' : ''}`,
106
+ hint: '确认无误后传 dryRun:false + confirm:true 才真正撤包(不可逆)',
107
+ };
108
+ }
109
+ if (confirm !== true) {
110
+ return { ok: false, blocked: 'need-confirm', ...pre, error: '真实撤包不可逆:需同时传 dryRun:false 与 confirm:true' };
111
+ }
112
+ const token = (() => { try { return readNpmToken({ workspaceRoot }); } catch { return ''; } })();
113
+ const rc = writeNpmrc({ workspaceRoot, registry, token });
114
+ if (!rc.ok) return { ok: false, error: rc.error || 'npmrc 写入失败' };
115
+ const args = ['unpublish', wholePackage ? name : `${name}@${pre.version}`, ...npmArgs({ npmrcFile: rc.file, registry })];
116
+ if (wholePackage) args.push('--force');
117
+ const r = runNpm(args, { timeoutMs, env: { NO_UPDATE_NOTIFIER: '1' } });
118
+ if (!r.ok) {
119
+ return {
120
+ ok: false, ...pre,
121
+ error: `npm unpublish 失败:${String(r.error || r.stderr || r.stdout || '').slice(0, 400)}`,
122
+ hint: '若提示 72h/依赖者/下载量限制,说明不满足官方撤包条件——改用 npm deprecate 让使用者看到警告而不破坏构建',
123
+ };
124
+ }
125
+ return {
126
+ ok: true, dryRun: false, ...pre,
127
+ unpublishd: wholePackage ? `${name}(全部版本)` : `${name}@${pre.version}`,
128
+ stdout: String(r.stdout || '').slice(-2000),
129
+ note: '撤包不可逆:该版本号永久作废;对外索引(第三方镜像/文档)不会自动清理',
130
+ };
131
+ }
package/lib/self/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  */
10
10
 
11
11
 
12
- export const VERSION = '2.16.1'; // 2.16.1:发布前彩排/冒烟按**包形态**验证(纯 CLI 包不再被判死)。历史实现一律 import('<包名>') 探测公开面:只有 bin、没有 main/exports 的纯 CLI 包必然报「Cannot find package .../index.js」,把好包误判成坏包、报错还写「加载失败」。现改为 classifyPackageForm 判形态:有库入口→import;只有 bin→**真跑** bin --version(断言输出含版本)与 --help(断言退出码 0);两者皆无→明确报「没有任何可验证入口」。真跑 bin 还能抓到 import 测不到的故障(bin 判据用字面路径、npm 装的是符号链接 → 执行静默 exit 0 零输出)。历史:2.16.0 建仓 CIFS 安全初始化。
12
+ export const VERSION = '2.18.0'; // 2.18.0:新增 npm_unpublish(撤包)。撤包不可逆——同一 `包@版本` 撤掉后永久不能再发,撤掉 latest 会让 `npm i <包>` 悬空——所以默认 dryRun:预检版本是否存在、是否被 dist-tag 指向、发布距今是否在官方 72h 窗口内、是否该包唯一版本(撤光会冷却 24h),并说明撤掉后的后果;真撤必须 dryRun:false + confirm:true 双确认。超出 72h 只有「无依赖者 + 周下载<300 + 单一维护者」三条件同时满足才允许,否则只能 deprecate——预检会把这条政策原文写进 policyHint。历史:2.17.0 推送后等 CI。
13
13
  // 实测后果:该目录有 package.json ⇒ npm 去打包整棵 DSH 树、输出 2.1MB > spawnSync 默认 maxBuffer 1MB ⇒ ENOBUFS(npm_publish 的体检与真发全部失败);
14
14
  // 该目录没有 package.json 时报 ENOENT。现 publish 的两个调用点显式传 cwd=目标包目录,并给 runNpm 加 16MB maxBuffer。
15
15
  // 2.8.3:文案修正——「零改动 / 无新提交」明确为**正常成功路径**(注入用法、工具描述、README、skill 同批改),并修 job 输出自相矛盾(cleanSkipCommit 路径补 committed:false,不再显示「已提交,未推送」)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-git-push",
3
- "version": "2.16.1",
3
+ "version": "2.18.0",
4
4
  "description": "DSH git 自动提交推送插件——统一函数入口架构(规则/审计/git/自身/侧边栏/评分/豁免/上下文/HTTP/测试十大总入口)",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",