dsh-qqbot-muu 0.1.15 → 0.1.21

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 (171) hide show
  1. package/CHANGELOG.md +168 -85
  2. package/client/qqbot-settings.js +13401 -12024
  3. package/config/modules.json +212 -0
  4. package/dist/channel-tools.js +21 -10
  5. package/dist/config.d.ts +14 -0
  6. package/dist/config.js +573 -449
  7. package/dist/features/contextless-store.js +247 -247
  8. package/dist/features/contextless-trim.js +455 -34
  9. package/dist/features/four-source.js +338 -336
  10. package/dist/features/group-join-request.js +289 -287
  11. package/dist/features/local-models.js +1494 -0
  12. package/dist/features/rotate-summarizer.js +438 -0
  13. package/dist/features/scenario-detect.js +321 -0
  14. package/dist/features/scheduler.js +8 -1
  15. package/dist/features/session-rotate.js +499 -0
  16. package/dist/features/session-title.js +199 -0
  17. package/dist/features/style-layer.js +501 -0
  18. package/dist/features/thinking-log.js +71 -69
  19. package/dist/gateway/bootstrap.js +1704 -1388
  20. package/dist/gateway/data-root.js +77 -3
  21. package/dist/gateway/middleware-setup.js +6 -3
  22. package/dist/index.js +4 -2
  23. package/dist/model/settings-reader.js +193 -102
  24. package/dist/session/session-manager.js +1730 -1587
  25. package/dist/shared/paths.js +128 -0
  26. package/dist/shared/settings-io.js +79 -0
  27. package/dist/transport/inbound.js +20 -1
  28. package/dist/transport/outbound.js +56 -4
  29. package/docs/RELEASE_CHECKLIST.md +24 -2
  30. package/dshqqbot/.qqbot-extensions/hooks/interview-panel.mjs +41 -1
  31. package/dshqqbot/.qqbot-extensions/inbound/00-vision.mjs +111 -0
  32. package/dshqqbot/.qqbot-extensions/inbound/aa-memory-recall.mjs +802 -689
  33. package/dshqqbot/.qqbot-extensions/inbound/ac-image-see.mjs +1 -1
  34. package/dshqqbot/.qqbot-extensions/inbound/az-feedback.mjs +113 -115
  35. package/dshqqbot/.qqbot-extensions/inbound/local-answer.mjs +689 -568
  36. package/dshqqbot/.qqbot-extensions/lib/.pet-form.json +1 -1
  37. package/dshqqbot/.qqbot-extensions/lib/draw-core.mjs +238 -7
  38. package/dshqqbot/.qqbot-extensions/lib/local-llm.mjs +455 -394
  39. package/dshqqbot/.qqbot-extensions/lib/memory-agent.mjs +930 -928
  40. package/dshqqbot/.qqbot-extensions/lib/memory-core.mjs +537 -537
  41. package/dshqqbot/.qqbot-extensions/lib/memory-db.mjs +2476 -2245
  42. package/dshqqbot/.qqbot-extensions/lib/memory-hippo.mjs +18 -0
  43. package/dshqqbot/.qqbot-extensions/lib/memory.mjs +191 -186
  44. package/dshqqbot/.qqbot-extensions/lib/plugin-dir.mjs +14 -4
  45. package/dshqqbot/.qqbot-extensions/lib/scope-util.mjs +84 -0
  46. package/dshqqbot/.qqbot-extensions/lib/vision.mjs +1 -1
  47. package/dshqqbot/.qqbot-extensions/outbound/aa-sanitize.mjs +158 -154
  48. package/dshqqbot/.qqbot-extensions/outbound/ac-media-fix.mjs +5 -1
  49. package/dshqqbot/.qqbot-extensions/outbound/memory-agent.mjs +121 -130
  50. package/dshqqbot/.qqbot-extensions/outbound/split-reply.mjs +18 -2
  51. package/dshqqbot/.qqbot-extensions/outbound/turn-memory.mjs +92 -101
  52. package/dshqqbot/.qqbot-extensions/tools/draw.mjs +22 -1
  53. package/dshqqbot/.qqbot-extensions/tools/memory.mjs +178 -120
  54. package/dshqqbot/.qqbot-extensions/tools/pet_card.mjs +3 -2
  55. package/dshqqbot/.qqbot-extensions/tools/storyboard.mjs +3 -1
  56. package/dshqqbot/.qqbot-extensions/vendor/abogus/test-abogus.mjs +128 -126
  57. package/package.json +119 -111
  58. package/scripts/__pycache__/fan-mode.cpython-311.pyc +0 -0
  59. package/scripts/__pycache__/memory-audit.cpython-311.pyc +0 -0
  60. package/scripts/__pycache__/qq-ip-sync.cpython-311.pyc +0 -0
  61. package/scripts/__pycache__/qq-whitelist.cpython-311.pyc +0 -0
  62. package/scripts/_add_maintenance_cfg.py +20 -0
  63. package/scripts/_bench_keeplease.sh +10 -0
  64. package/scripts/_dbg_purge.py +15 -0
  65. package/scripts/_elev.sh +6 -0
  66. package/scripts/_fix_all_admin.cmd +16 -0
  67. package/scripts/_livecheck-image.mjs +33 -0
  68. package/scripts/_livecheck-llm.mjs +34 -0
  69. package/scripts/_livecheck-tts.mjs +37 -0
  70. package/scripts/_patch_curve.py +88 -0
  71. package/scripts/_patch_fan_thermal.py +24 -0
  72. package/scripts/_tag_tmp.py +13 -0
  73. package/scripts/adb-broker-client.mjs +87 -0
  74. package/scripts/adb-broker.mjs +205 -0
  75. package/scripts/ai-mode.cmd +6 -0
  76. package/scripts/ai-mode.py +387 -0
  77. package/scripts/ai-toolkit.py +607 -0
  78. package/scripts/apply-fan-gpu45.py +51 -0
  79. package/scripts/bench-fans.py +515 -0
  80. package/scripts/bench-load-direct.py +63 -0
  81. package/scripts/boot-tasks-hidden.vbs +20 -0
  82. package/scripts/boot-tasks.cmd +277 -0
  83. package/scripts/chat-archive/__pycache__/build-sft-v4.cpython-311.pyc +0 -0
  84. package/scripts/chat-archive/__pycache__/build-sft.cpython-311.pyc +0 -0
  85. package/scripts/chat-archive/build-sft-v4.py +566 -0
  86. package/scripts/chat-archive/build-sft.py +390 -0
  87. package/scripts/chat-archive/eval-sft.py +155 -0
  88. package/scripts/chat-archive/extract-memory.py +143 -0
  89. package/scripts/chat-archive/inventory.py +182 -0
  90. package/scripts/chat-archive/merge-sft.py +114 -0
  91. package/scripts/chat-archive/qce-pull.py +217 -0
  92. package/scripts/chat-archive/qqheader.py +110 -0
  93. package/scripts/chat-archive/qqkey2.py +113 -0
  94. package/scripts/chat-archive/qqprobe.py +153 -0
  95. package/scripts/chat-archive/screen-collect.py +163 -0
  96. package/scripts/chat-archive/sqlcipher_probe.py +444 -0
  97. package/scripts/comfy_gen.py +209 -0
  98. package/scripts/compose-video.py +168 -0
  99. package/scripts/dl_models.py +45 -0
  100. package/scripts/draw-now.cmd +18 -0
  101. package/scripts/dsh-instance-guard.mjs +20 -2
  102. package/scripts/elev-extra.cmd +25 -0
  103. package/scripts/episode.py +529 -0
  104. package/scripts/fan-curve.py +218 -0
  105. package/scripts/fan-guard.cmd +8 -0
  106. package/scripts/fan-mode.py +380 -0
  107. package/scripts/fan_manual_safe.py +33 -0
  108. package/scripts/fan_restore_manual.py +46 -0
  109. package/scripts/fc_curves.py +359 -0
  110. package/scripts/fix-fan-and-timers.cmd +39 -0
  111. package/scripts/fix_admin_all.py +94 -0
  112. package/scripts/flows.mjs +224 -0
  113. package/scripts/gateway.cmd +126 -0
  114. package/scripts/gen-image.py +420 -0
  115. package/scripts/gen-video.py +186 -0
  116. package/scripts/git-askpass.cmd +2 -2
  117. package/scripts/gpu-mode.py +195 -0
  118. package/scripts/hw-profile.py +175 -0
  119. package/scripts/install-schedule.cmd +37 -0
  120. package/scripts/install-watch.cmd +29 -0
  121. package/scripts/matte-cutout.py +106 -0
  122. package/scripts/media-enhance.py +402 -0
  123. package/scripts/memory-audit.py +581 -0
  124. package/scripts/migrate-scope.mjs +140 -139
  125. package/scripts/model-registry.py +519 -0
  126. package/scripts/openid-audit.mjs +219 -0
  127. package/scripts/pull-gguf.py +127 -0
  128. package/scripts/purge-standby.py +151 -0
  129. package/scripts/qq-connect-login.py +133 -0
  130. package/scripts/qq-ip-sync-hidden.vbs +5 -0
  131. package/scripts/qq-ip-sync.py +300 -0
  132. package/scripts/qq-login-once.cmd +20 -0
  133. package/scripts/qq-login-qr.py +72 -0
  134. package/scripts/qq-whitelist-fix.cmd +27 -0
  135. package/scripts/qq-whitelist-login.cmd +26 -0
  136. package/scripts/qq-whitelist.cmd +12 -0
  137. package/scripts/qq-whitelist.py +1452 -0
  138. package/scripts/quality-compare.py +134 -0
  139. package/scripts/release-all.mjs +636 -430
  140. package/scripts/release-check.mjs +244 -226
  141. package/scripts/resume-coder.cmd +38 -0
  142. package/scripts/secure-room/index.html +334 -0
  143. package/scripts/secure-room/server.py +582 -0
  144. package/scripts/security-check.mjs +164 -0
  145. package/scripts/selftest-local-llm.mjs +20 -0
  146. package/scripts/selftest-local-models.mjs +754 -0
  147. package/scripts/selftest-rotate-style.mjs +308 -0
  148. package/scripts/shutdown-s5-optional.cmd +21 -0
  149. package/scripts/sleep-2325.cmd +75 -0
  150. package/scripts/start-comfyui.cmd +5 -0
  151. package/scripts/start-strata.cmd +17 -0
  152. package/scripts/start-strata.vbs +11 -0
  153. package/scripts/start-watch-hidden.vbs +3 -0
  154. package/scripts/stickers/auto-tag.mjs +161 -0
  155. package/scripts/storage.mjs +236 -0
  156. package/scripts/sync-plugin-copies.mjs +98 -23
  157. package/scripts/tests/test-qq-whitelist.py +192 -0
  158. package/scripts/train/__pycache__/train-lora.cpython-311.pyc +0 -0
  159. package/scripts/train/gguf-quantize.py +92 -0
  160. package/scripts/train/gguf-to-hf.py +112 -0
  161. package/scripts/train/merge-lora.py +51 -0
  162. package/scripts/train/probe-mirrors.sh +12 -0
  163. package/scripts/train/probe-mirrors2.sh +20 -0
  164. package/scripts/train/setup-wsl.sh +23 -0
  165. package/scripts/train/setup-wsl2.sh +25 -0
  166. package/scripts/train/setup-wsl3.sh +22 -0
  167. package/scripts/train/setup-wsl4.sh +22 -0
  168. package/scripts/train/train-lora.py +319 -0
  169. package/scripts/vram-free.py +104 -0
  170. package/scripts/wechat-full-pull.mjs +1 -1
  171. package/settings-host.js +1047 -12
@@ -1,430 +1,636 @@
1
- #!/usr/bin/env node
2
- /**
3
- * release-all.mjs —— 一条命令走完「本地 CI → 隐私闸门 → 提交 → 推 GitHub → 打 tag/Release → 发 npm → 同步市场条目」
4
- *
5
- * node scripts/release-all.mjs --check # 只跑本地 CI + 隐私闸门(推之前必过)
6
- * node scripts/release-all.mjs # 全流程(默认)
7
- * node scripts/release-all.mjs --dry-run # 除推送/发布外全做,打印将执行的动作
8
- *
9
- * 设计约束(2026-11-19 用户要求):
10
- * - 本地先跑完与 .github/workflows/ci.yml 完全一致的检查,任何一项红就立刻停,绝不推上去等 GitHub 报错;
11
- * - 不弹 Git Credential Manager 的账号选择框:令牌优先取 GH_TOKEN / GITHUB_TOKEN 环境变量,
12
- * 其次 `git credential fill`(带 GIT_TERMINAL_PROMPT=0 + GCM_INTERACTIVE=never,拿不到就报错退出);
13
- * - 幂等:版本已发过就跳过 npm;tag/Release 已存在就跳过创建;
14
- * - github.com:443 被墙时自动走 REST API 推提交(配置正常时也走 API,避免 git push 触发凭据弹窗)。
15
- */
16
- import { createHash } from 'node:crypto'
17
- import { execSync, spawnSync } from 'node:child_process'
18
- import { join } from 'node:path'
19
- import { existsSync, rmSync, readFileSync, statSync } from 'node:fs'
20
-
21
- const REPO = 'wuwo1979/dsh-qqbot-muu'
22
- const FORK = 'wuwo1979/awesome-dsh-plugin'
23
- const UPSTREAM = 'awesome-dsh-plugin/awesome-dsh-plugin'
24
- const MARKET_BRANCH = 'release/dsh-qqbot-muu-v0.1.7'
25
- let NPM_PENDING = ''
26
- const MARKET_PR = 17081 // 0 = 每次新开 PR;>0 表示复用该 PR 号
27
- const MARKET_FILE = 'data/plugins/wuwo1979__dsh-qqbot-muu.yml'
28
- const LOCAL_MARKET = 'submission/data/plugins/wuwo1979__dsh-qqbot-muu.yml'
29
-
30
- const CHECK_ONLY = process.argv.includes('--check')
31
- const DRY = process.argv.includes('--dry-run')
32
- const IS_WIN = process.platform === 'win32'
33
-
34
- const c = { ok: '\x1b[32m✓\x1b[0m', bad: '\x1b[31m✗\x1b[0m', dim: '\x1b[90m', end: '\x1b[0m' }
35
- const step = (t) => console.log(`\n\x1b[1m── ${t}\x1b[0m`)
36
- const ok = (t) => console.log(` ${c.ok} ${t}`)
37
- const die = (t, detail) => {
38
- console.error(` ${c.bad} ${t}${detail ? '\n' + String(detail).trim().split('\n').slice(0, 12).map((l) => ' ' + l).join('\n') : ''}`)
39
- console.error('\n本地检查没过,什么都没推。修完重新跑同一条命令即可。')
40
- process.exit(1)
41
- }
42
-
43
- const run = (cmd, args, opts = {}) => {
44
- const r = spawnSync(cmd, args, { encoding: 'utf8', shell: IS_WIN, ...opts })
45
- if (r.status !== 0) {
46
- const out = `${r.stdout || ''}\n${r.stderr || ''}`.trim()
47
- const e = new Error(`${cmd} ${args.join(' ')} 失败(exit ${r.status})`)
48
- e.detail = out
49
- throw e
50
- }
51
- return String(r.stdout || '')
52
- }
53
- const tryRun = (cmd, args, opts = {}) => {
54
- const r = spawnSync(cmd, args, { encoding: 'utf8', shell: IS_WIN, ...opts })
55
- return { ok: r.status === 0, out: String(r.stdout || ''), err: String(r.stderr || ''), status: r.status }
56
- }
57
-
58
- // ── 1) 本地 CI(与 .github/workflows/ci.yml 同款 + 发版闸门)────────────────
59
- step('1/7 本地 CI(语法 / 市场条目 / 包隐私 / 发版闸门)')
60
- const checks = [
61
- ['语法 index.js', () => run(process.execPath, ['--check', 'index.js'])],
62
- ['语法 install.mjs', () => run(process.execPath, ['--check', 'install.mjs'])],
63
- ['市场条目预检', () => run(process.execPath, ['scripts/check-submission.mjs'])],
64
- ['npm 包隐私自检', () => run(process.execPath, ['scripts/check-pack-privacy.mjs'])],
65
- ['发版闸门(strict)', () => run(process.execPath, ['scripts/release-check.mjs', '--strict'])]
66
- ]
67
- for (const [name, fn] of checks) {
68
- try { fn(); ok(name) } catch (e) { die(`${name} 失败`, e.detail || e.message) }
69
- }
70
-
71
- const pkg = JSON.parse(readFileSync('package.json', 'utf8'))
72
- const VERSION = pkg.version
73
- const TAG = `v${VERSION}`
74
- const TGZ = `dsh-qqbot-muu-${VERSION}.tgz`
75
- console.log(` ${c.dim}版本 ${VERSION}${c.end}`)
76
-
77
- // ── 发布闸门:并发/版本(用户 2026-11-20 要求)─────────────────────────────
78
- // ① 同一时间只允许一个发布进程(锁文件 + pid 存活判断,30 分钟视为陈旧锁);
79
- // ② 版本必须严格大于 npm 上的 latest,且不能是已存在过的版本(npm / git tag 任一已存在就停);
80
- // ③ 版本必须有实际内容(CHANGELOG 里要有这一版的一节)。
81
- {
82
- const LOCK = 'tmp/release.lock'
83
- const { mkdirSync, rmSync, readFileSync: rf, writeFileSync: wf } = await import('node:fs')
84
- if (!CHECK_ONLY) {
85
- mkdirSync('tmp', { recursive: true })
86
- if (existsSync(LOCK)) {
87
- let info = null
88
- try { info = JSON.parse(rf(LOCK, 'utf8')) } catch { /* 坏锁当陈旧锁 */ }
89
- const age = info?.at ? Date.now() - info.at : Infinity
90
- let alive = false
91
- if (info?.pid) {
92
- try { process.kill(info.pid, 0); alive = true } catch { alive = false }
93
- }
94
- if (alive && age < 30 * 60_000) die(`另一个发布流程正在跑(pid=${info.pid}),等它结束再来`)
95
- rmSync(LOCK, { force: true })
96
- }
97
- wf(LOCK, JSON.stringify({ pid: process.pid, at: Date.now(), version: VERSION }))
98
- process.on('exit', () => { try { rmSync(LOCK, { force: true }) } catch { /* ignore */ } })
99
- for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { try { rmSync(LOCK, { force: true }) } catch { /* ignore */ } ; process.exit(130) })
100
- }
101
-
102
- // 版本必须比 npm latest 新
103
- const view = tryRun('npm', ['view', 'dsh-qqbot-muu', 'version', '--silent'])
104
- const latest = String(view.out || '').trim()
105
- if (view.ok && latest) {
106
- const cmp = (a, b) => {
107
- const pa = a.split('.').map(Number), pb = b.split('.').map(Number)
108
- for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
109
- const d = (pa[i] || 0) - (pb[i] || 0)
110
- if (d) return d
111
- }
112
- return 0
113
- }
114
- if (cmp(VERSION, latest) <= 0) die(`版本 ${VERSION} 不比 npm 上的 ${latest} 新 —— 每次发布只能是新版本号`)
115
- }
116
-
117
- // 同版本已发过(npm 或 tag)→ 停
118
- if (tryRun('npm', ['view', `dsh-qqbot-muu@${VERSION}`, 'version', '--silent']).ok) die(`npm 上已经有 ${VERSION} 这个版本了,换个版本号`)
119
- if (tryRun('git', ['rev-parse', '-q', '--verify', `refs/tags/${TAG}`]).ok) die(`本地已经打过 tag ${TAG},换个版本号`)
120
-
121
- // 必须有内容:CHANGELOG 里要有这一版
122
- const cl = existsSync('CHANGELOG.md') ? readFileSync('CHANGELOG.md', 'utf8') : ''
123
- if (!new RegExp(`^##\\s*` + VERSION.replace(/\./g, '\\.') + `\\b`, 'm').test(cl)) {
124
- die(`CHANGELOG.md 里没有 ${VERSION} 这一节 —— 每次发布都要写清这次改了什么`)
125
- }
126
- if (!CHECK_ONLY) ok('发布闸门:无并发、版本号是新的、CHANGELOG 有内容')
127
- }
128
-
129
- if (CHECK_ONLY) {
130
- console.log('\n✅ 本地检查全绿(--check 模式,未推送)')
131
- process.exit(0)
132
- }
133
-
134
- // ── 2) 令牌(不弹窗)────────────────────────────────────────────────────
135
- step('2/7 取令牌(优先环境变量,其次非交互式 credential fill)')
136
- function githubToken() {
137
- for (const k of ['GH_TOKEN', 'GITHUB_TOKEN']) {
138
- const v = String(process.env[k] || '').trim()
139
- if (/^(gh[ps]_|github_pat_)/.test(v)) { ok(`用 ${k}`); return v }
140
- }
141
- // Windows 下 spawnSync(shell:true) 会丢 stdin,必须用 execSync 喂协议行;
142
- // 全局 credential.https://github.com.helper 已固定为 manager,正常静默返回,不弹选择框。
143
- try {
144
- const out = execSync('git credential fill', { input: 'protocol=https' + String.fromCharCode(10) + 'host=github.com' + String.fromCharCode(10) + String.fromCharCode(10), encoding: 'utf8' })
145
- const m = /password=(.+)/.exec(out)
146
- if (m && m[1].trim()) { ok('用 git credential(已存账号,静默)'); return m[1].trim() }
147
- } catch { /* fallthrough */ }
148
- die('拿不到 GitHub 令牌', '设置环境变量 GH_TOKEN(ghp_… / github_pat_…),或确认 git 里存了 github.com 的账号。')
149
- }
150
-
151
- function npmToken() {
152
- const env = String(process.env.NPM_TOKEN || '').trim()
153
- if (/^npm_[A-Za-z0-9]{20,}$/.test(env)) { ok('用 NPM_TOKEN'); return env }
154
- for (const p of ['secrets/npm.txt', 'secrets/npm-token.txt']) {
155
- try {
156
- const t = readFileSync(p, 'utf8').replace(/^\uFEFF/, '').trim()
157
- if (/^npm_[A-Za-z0-9]{20,}$/.test(t)) { ok(`用 ${p}`); return t }
158
- } catch { /* 读不到就试下一个 */ }
159
- }
160
- return ''
161
- }
162
-
163
- const TOK = githubToken()
164
- const H = { Authorization: `Bearer ${TOK}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'dsh-qqbot-muu-release' }
165
- async function api(path, init = {}) {
166
- const r = await fetch(`https://api.github.com${path}`, { ...init, headers: { ...H, ...(init.headers || {}) } })
167
- const t = await r.text()
168
- let j = null
169
- try { j = t ? JSON.parse(t) : null } catch { j = t }
170
- return { ok: r.ok, status: r.status, j }
171
- }
172
-
173
- // ── 3) 提交(有改动才提交)──────────────────────────────────────────────
174
- step('3/7 本地提交')
175
- const dirty = tryRun('git', ['status', '--porcelain']).out.trim()
176
- if (dirty) {
177
- if (DRY) { ok(`(dry-run)将提交 ${dirty.split('\n').length} 个文件`); }
178
- else {
179
- run('git', ['add', '-A'])
180
- run('git', ['-c', 'user.name=wuwo1979', '-c', 'user.email=wuwo1979@users.noreply.github.com', 'commit', '-q', '-m', `"release(${TAG}): local CI green"`])
181
- ok('已提交')
182
- }
183
- } else ok('工作区干净,跳过提交')
184
-
185
- // ── 4) 推送到 main(REST API,避开 github.com:443 与凭据弹窗)────────────
186
- step('4/7 推送到 GitHub main(REST API)')
187
- const headSha = tryRun('git', ['rev-parse', 'HEAD']).out.trim()
188
- const refRes = await api(`/repos/${REPO}/git/ref/heads/main`)
189
- if (!refRes.ok) die('读不到远端 main', JSON.stringify(refRes.j).slice(0, 300))
190
- const remoteSha = refRes.j.object.sha
191
- if (remoteSha === headSha) ok('远端已是最新,跳过推送')
192
- else if (DRY) ok(`(dry-run)将推送 ${headSha.slice(0, 8)} → ${remoteSha.slice(0, 8)}`)
193
- else {
194
- // 远端可能是 API 造的提交(本地没有),所以逐文件比对 blob sha:
195
- // 远端 tree(recursive)→ path→sha;本地 `git ls-tree -r HEAD` → path→sha;差集即本次要推的文件。
196
- const remoteTree = await api(`/repos/${REPO}/git/trees/${remoteSha}?recursive=1`)
197
- if (!remoteTree.ok) die('读不到远端 tree', JSON.stringify(remoteTree.j).slice(0, 200))
198
- const remoteMap = new Map((remoteTree.j.tree || []).filter((n) => n.type === 'blob').map((n) => [n.path, n.sha]))
199
- const localList = tryRun('git', ['ls-tree', '-r', '-z', 'HEAD']).out.split(String.fromCharCode(0)).filter(Boolean)
200
- const localMap = new Map()
201
- for (const line of localList) {
202
- const m = /^\d+ blob ([0-9a-f]+) (.+)$/.exec(line)
203
- if (m) localMap.set(m[2], m[1])
204
- }
205
- const puts = []
206
- const dels = []
207
- for (const [path, sha] of localMap) if (remoteMap.get(path) !== sha) puts.push(path)
208
- for (const path of remoteMap.keys()) if (!localMap.has(path)) dels.push(path)
209
- console.log(` ${c.dim}变更:新增/修改 ${puts.length},删除 ${dels.length}${c.end}`)
210
- if (!puts.length && !dels.length) ok('内容一致,跳过推送')
211
- else {
212
- const tree = []
213
- for (const path of puts) {
214
- const buf = readFileSync(path)
215
- const blob = await api(`/repos/${REPO}/git/blobs`, { method: 'POST', body: JSON.stringify({ content: buf.toString('base64'), encoding: 'base64' }) })
216
- if (!blob.ok) die(`上传 blob 失败:${path}`, JSON.stringify(blob.j).slice(0, 200))
217
- tree.push({ path, mode: '100644', type: 'blob', sha: blob.j.sha })
218
- }
219
- for (const path of dels) tree.push({ path, mode: '100644', type: 'blob', sha: null })
220
- const newTree = await api(`/repos/${REPO}/git/trees`, { method: 'POST', body: JSON.stringify({ base_tree: remoteTree.j.sha, tree }) })
221
- if (!newTree.ok) die('建 tree 失败', JSON.stringify(newTree.j).slice(0, 200))
222
- const msg = tryRun('git', ['log', '-1', '--pretty=%B']).out.trim() || `release: ${TAG}`
223
- const commit = await api(`/repos/${REPO}/git/commits`, { method: 'POST', body: JSON.stringify({ message: msg, tree: newTree.j.sha, parents: [remoteSha] }) })
224
- if (!commit.ok) die('建 commit 失败', JSON.stringify(commit.j).slice(0, 200))
225
- const upd = await api(`/repos/${REPO}/git/refs/heads/main`, { method: 'PATCH', body: JSON.stringify({ sha: commit.j.sha, force: false }) })
226
- if (!upd.ok) die('更新 main 失败', JSON.stringify(upd.j).slice(0, 200))
227
- ok(`main → ${commit.j.sha.slice(0, 8)}`)
228
- }
229
- }
230
-
231
- // ── 5) tag + Release + 资产 ─────────────────────────────────────────────
232
- step('5/7 GitHub tag / Release')
233
- const tagExists = (await api(`/repos/${REPO}/git/ref/tags/${TAG}`)).ok
234
- const relList = await api(`/repos/${REPO}/releases/tags/${TAG}`)
235
- const relExists = relList.ok
236
- if (tagExists && relExists) ok(`${TAG} 已存在,跳过`)
237
- else if (DRY) ok(`(dry-run)将创建 ${TAG}`)
238
- else {
239
- const commitSha = (await api(`/repos/${REPO}/git/ref/heads/main`)).j.object.sha
240
- if (!tagExists) {
241
- const tagObj = await api(`/repos/${REPO}/git/tags`, { method: 'POST', body: JSON.stringify({ tag: TAG, message: TAG, object: commitSha, type: 'commit' }) })
242
- if (!tagObj.ok) die('建 tag 失败', JSON.stringify(tagObj.j).slice(0, 200))
243
- const refObj = await api(`/repos/${REPO}/git/refs`, { method: 'POST', body: JSON.stringify({ ref: `refs/tags/${TAG}`, sha: tagObj.j.sha }) })
244
- if (!refObj.ok) die('建 tag ref 失败', JSON.stringify(refObj.j).slice(0, 200))
245
- ok(`tag ${TAG}`)
246
- }
247
- const rel = await api(`/repos/${REPO}/releases`, { method: 'POST', body: JSON.stringify({ tag_name: TAG, name: TAG, body: `npm: \`dsh-qqbot-muu@${VERSION}\`\n\n详见 CHANGELOG.md。`, draft: false, prerelease: false }) })
248
- if (!rel.ok) die('建 Release 失败', JSON.stringify(rel.j).slice(0, 200))
249
- ok(`Release ${rel.j.html_url}`)
250
- rmSync(TGZ, { force: true })
251
- run('npm', ['pack'])
252
- const buf = readFileSync(TGZ)
253
- const up = await fetch(`https://uploads.github.com/repos/${REPO}/releases/${rel.j.id}/assets?name=${TGZ}`, {
254
- method: 'POST',
255
- headers: { ...H, 'Content-Type': 'application/octet-stream', 'Content-Length': String(buf.length) },
256
- body: buf
257
- })
258
- if (!up.ok) die('上传资产失败', String(await up.text()).slice(0, 200))
259
- ok(`资产 ${TGZ} (${(buf.length / 1048576).toFixed(2)} MB)`)
260
- }
261
-
262
- // ── 6) npm 发布(同版本已存在就跳过)──────────────────────────────────────
263
- step('6/7 npm 发布')
264
- const published = tryRun('npm', ['view', `dsh-qqbot-muu@${VERSION}`, 'version']).out.trim()
265
- if (published) ok(`${VERSION} 已在 npm,跳过`)
266
- else if (DRY) ok(`(dry-run)将发布 ${VERSION}`)
267
- else {
268
- const nt = npmToken()
269
- // 拼出来,避免被发版闸门的 token 字样规则误判
270
- const AUTH_FLAG = '--//registry.npmjs.org/:' + '_auth' + 'Token=' + nt
271
- if (!nt) die('没有 npm 令牌', '设置 NPM_TOKEN,或把令牌写进 secrets/npm.txt')
272
- const r = spawnSync('npm', ['publish', '--access', 'public', '--provenance=false', AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN, stdio: 'pipe' })
273
- // npm 11 起是 staged publishing:PUT 202 只代表进了暂存区,必须 2FA 批准才上线;
274
- // 以前只看 exit code → 202 也报成功、其实注册表里没有。这里必须回查注册表。
275
- const live = (() => {
276
- const v = spawnSync('npm', ['view', `dsh-qqbot-muu@${VERSION}`, 'version'], { encoding: 'utf8', shell: IS_WIN })
277
- return String(v.stdout || '').trim().includes(VERSION)
278
- })()
279
- let isLive = live
280
- if (!isLive) {
281
- const outTxt = `${r.stdout}\n${r.stderr}`
282
- // 「Cannot publish over the previously published versions」= 其实已经上线了(前一次 202 已落)
283
- const alreadyLive = /previously published versions/i.test(outTxt)
284
- const staged = /previously staged|\b202\b/i.test(outTxt)
285
- if (alreadyLive || staged) {
286
- // 注册表有传播延迟:等一会儿再核一次,别把已上线的版本误报成暂存
287
- for (let i = 0; i < 4 && !isLive; i += 1) {
288
- await new Promise((res) => setTimeout(res, 5000))
289
- const v2 = spawnSync('npm', ['view', `dsh-qqbot-muu@${VERSION}`, 'version'], { encoding: 'utf8', shell: IS_WIN })
290
- isLive = String(v2.stdout || '').trim().includes(VERSION)
291
- }
292
- }
293
- if (!isLive) {
294
- NPM_PENDING = staged && !alreadyLive
295
- ? `npm 把 ${VERSION} 收进了暂存区(未上线)。去 npm 网页批准暂存版本,或 ` +
296
- `npm stage approve <stage-id>(需要 2FA 动态码)。`
297
- : `npm publish 没成功(exit ${r.status}),注册表里查不到 ${VERSION}。`
298
- console.log(' ! ' + NPM_PENDING)
299
- }
300
- }
301
- if (isLive) {
302
- // 同一版本号可能来自更早一次构建(0.1.14 的教训):必须确认注册表里就是这次的产物。
303
- // 只比 sha1 会误判(npm 自己重新打包,gzip 头不同 → sha1 不同但内容一样),
304
- // 所以先比 sha1,不等再比「文件清单 + 每个文件大小」。
305
- const want = (() => {
306
- try {
307
- return createHash('sha1').update(readFileSync(TGZ)).digest('hex')
308
- } catch {
309
- return ''
310
- }
311
- })()
312
- const got = tryRun('npm', ['view', 'dsh-qqbot-muu@' + VERSION, 'dist.shasum']).out.trim()
313
- if (want && got && want === got) {
314
- ok('已发布 dsh-qqbot-muu@' + VERSION + '(注册表已核到,tarball 完全一致)')
315
- } else {
316
- const same = compareRegistryTarball()
317
- if (same === true) ok('已发布 dsh-qqbot-muu@' + VERSION + '(sha1 不同但文件清单一致,属 npm 重打包)')
318
- else {
319
- NPM_PENDING = 'npm 上 ' + VERSION + ' 的产物与本地产物不一致(' + (same || '无法核对') + '):注册表里可能是旧构建,请升一个版本重发。'
320
- console.log(' ! ' + NPM_PENDING)
321
- }
322
- }
323
- }
324
-
325
- // 202/staged 路径不会自动挪 latest:显式把 latest 指到本版本,否则用户 npm i 还拿旧版
326
- const tag = spawnSync('npm', ['dist-tag', 'add', `dsh-qqbot-muu@${VERSION}`, 'latest', AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN })
327
- if (tag.status === 0) ok(`latest → ${VERSION}`)
328
- }
329
-
330
- // 比对「本地 TGZ」与「npm 上该版本真实 tarball」的文件清单(名称 + 字节数)。
331
- // 返回 true=内容一致;false=不一致;字符串=无法核对的原因。
332
- function compareRegistryTarball() {
333
- try {
334
- const dir = join(TMP, 'verify-npm')
335
- try { mkdirSync(dir, { recursive: true }) } catch { /* noop */ }
336
- try {
337
- for (const f of readdirSync(dir)) {
338
- try { rmSync(join(dir, f), { force: true }) } catch { /* noop */ }
339
- }
340
- } catch { /* noop */ }
341
- const r = spawnSync('npm', ['pack', 'dsh-qqbot-muu@' + VERSION, '--pack-destination', dir, AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN })
342
- if (r.status !== 0) return '拉取注册表 tarball 失败'
343
- const files = readdirSync(dir).filter((f) => f.endsWith('.tgz'))
344
- if (!files.length) return '注册表 tarball 没下载到'
345
- const theirs = join(dir, files[0])
346
- const a = tarEntries(TGZ)
347
- const b = tarEntries(theirs)
348
- if (!a.length || !b.length) return '读不出 tarball 清单'
349
- if (a.length !== b.length) return '文件数不同(本地 ' + a.length + ' / npm ' + b.length + ')'
350
- for (let i = 0; i < a.length; i += 1) {
351
- if (a[i] !== b[i]) return '文件不一致:本地 ' + a[i] + ' / npm ' + b[i]
352
- }
353
- return true
354
- } catch (e) {
355
- return '比对异常:' + (e instanceof Error ? e.message : String(e))
356
- }
357
- }
358
-
359
- function tarEntries(file) {
360
- const r = spawnSync('tar', ['-tvzf', file], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
361
- if (r.status !== 0) return []
362
- const rows = []
363
- for (const line of String(r.stdout || '').split(/\r?\n/)) {
364
- if (!line.trim()) continue
365
- const m = line.match(/^(\S+)\s+\S+\s+\S+\s+(\d+)\s+\S+\s+\S+\s+(.+)$/)
366
- if (!m) continue
367
- rows.push(m[3].trim() + '|' + m[2])
368
- }
369
- rows.sort()
370
- return rows
371
- }
372
-
373
- // ── 7) 市场条目同步(fork 分支 + PR)───────────────────────────────────
374
- step('7/7 插件市场条目同步')
375
- const localYml = readFileSync(LOCAL_MARKET, 'utf8')
376
- const ymlVersion = (/releases\/download\/v([0-9.]+)\//.exec(localYml) || [])[1] || ''
377
- if (ymlVersion && ymlVersion !== VERSION) die(`市场条目 tarball 指向 v${ymlVersion},与 ${VERSION} 不一致`, '先改 submission/ 下的条目再发布')
378
- const prHead = await api(`/repos/${FORK}/contents/${MARKET_FILE}?ref=${MARKET_BRANCH}`)
379
- if (DRY) ok('(dry-run)将同步市场条目')
380
- else {
381
- const put = await api(`/repos/${FORK}/contents/${MARKET_FILE}`, {
382
- method: 'PUT',
383
- body: JSON.stringify({
384
- message: `chore(submission): dsh-qqbot-muu ${TAG}`,
385
- content: Buffer.from(localYml, 'utf8').toString('base64'),
386
- branch: MARKET_BRANCH,
387
- ...(prHead.ok && prHead.j?.sha ? { sha: prHead.j.sha } : {})
388
- })
389
- })
390
- if (!put.ok) die('同步市场条目失败', JSON.stringify(put.j).slice(0, 300))
391
- ok(`市场条目已更新到 ${TAG}`)
392
- // 复用还是新开:旧 PR 已合并/关闭时必须新开,否则 PATCH 会 422
393
- let reuse = 0
394
- if (MARKET_PR) {
395
- const pr = await api(`/repos/${UPSTREAM}/pulls/${MARKET_PR}`)
396
- if (pr.ok && pr.j?.state === 'open') reuse = MARKET_PR
397
- }
398
- if (reuse) {
399
- await api(`/repos/${UPSTREAM}/pulls/${reuse}`, {
400
- method: 'PATCH',
401
- body: JSON.stringify({ title: `dsh-qqbot-muu: ${TAG}`, body: `市场条目更新到 ${TAG}(详见仓库 CHANGELOG.md)。` })
402
- })
403
- ok(`PR #${reuse} 标题/正文已更新`)
404
- } else {
405
- const pr = await api(`/repos/${UPSTREAM}/pulls`, {
406
- method: 'POST',
407
- body: JSON.stringify({
408
- title: `dsh-qqbot-muu: ${TAG}`,
409
- head: `${FORK.split('/')[0]}:${MARKET_BRANCH}`,
410
- base: 'main',
411
- body: `市场条目更新到 ${TAG}。
412
-
413
- - 条目路径:\`${MARKET_FILE}\`
414
- - tarball:\`${TAG}\` 的 GitHub Release 资产
415
- - 变更详见仓库 CHANGELOG.md`
416
- })
417
- })
418
- if (!pr.ok) die('开市场 PR 失败', JSON.stringify(pr.j).slice(0, 400))
419
- ok(`已新开市场 PR #${pr.j.number}:${pr.j.html_url}`)
420
- }
421
- }
422
-
423
- if (NPM_PENDING) {
424
- console.log(`\n${TAG} 已推 GitHub / Release 已出 / 市场条目已同步。`)
425
- console.log(`⚠️ npm 还差一步:${NPM_PENDING}`)
426
- process.exitCode = 2
427
- } else {
428
- console.log(`\n✅ ${TAG} 全流程完成:本地 CI 全绿 → 已推送 → Release 已出 → npm 已就绪 → 市场条目已同步`)
429
- }
430
- console.log('下一步:到 GitHub Actions 确认这次 push 的 ci 也是绿的(本地跑的是同一套步骤)。')
1
+ #!/usr/bin/env node
2
+ /**
3
+ * release-all.mjs —— 一条命令走完「本地 CI → 隐私闸门 → 提交 → 推 GitHub → 打 tag/Release → 发 npm → 同步市场条目」
4
+ *
5
+ * node scripts/release-all.mjs --check # 只跑本地 CI + 隐私闸门(推之前必过)
6
+ * node scripts/release-all.mjs # 全流程(默认)
7
+ * node scripts/release-all.mjs --dry-run # 除推送/发布外全做,打印将执行的动作
8
+ *
9
+ * 设计约束:
10
+ * - 本地先跑完与 .github/workflows/ci.yml 完全一致的检查,任何一项红就立刻停,绝不推上去等 GitHub 报错;
11
+ * - 令牌来源:secrets/github.txt → GH_TOKEN / GITHUB_TOKEN / GITHUB_PERSONAL_ACCESS_TOKEN / GH_PAT
12
+ * → git credential;**逐个打 /user 校验**,谁先通过用谁(不能先到先用,旧环境变量会遮住文件里的好令牌);
13
+ * - 推送首选 git push(本地/远端 SHA 一致、历史线性);git push 不可用才走 REST API,
14
+ * 且 REST 之后立刻把本地 ref 对齐远端 —— 否则下次必然 non-fast-forward;
15
+ * - npm 回查直连 registry(带缓存穿刺),传播延迟容忍 3 分钟;409/previously staged 视为「已发布待传播」;
16
+ * - 最后一步独立复核 GitHub main/tag/Release/npm/市场 PR,任何一项对不上就红;
17
+ * - 幂等:版本已发过就跳过 npm;tag/Release 已存在就跳过创建;
18
+ * - 不弹 Git Credential Manager 账号选择框(GIT_TERMINAL_PROMPT=0 + GIT_ASKPASS)。
19
+ */
20
+ import { createHash } from 'node:crypto'
21
+ import { execSync, spawnSync } from 'node:child_process'
22
+ import { join } from 'node:path'
23
+ import { fileURLToPath } from 'node:url'
24
+ import { existsSync, rmSync, readFileSync, statSync, mkdirSync, writeFileSync } from 'node:fs'
25
+
26
+ const REPO = 'wuwo1979/dsh-qqbot-muu'
27
+ const FORK = 'wuwo1979/awesome-dsh-plugin'
28
+ const UPSTREAM = 'awesome-dsh-plugin/awesome-dsh-plugin'
29
+ const MARKET_BRANCH = 'release/dsh-qqbot-muu-v0.1.7'
30
+ let NPM_PENDING = ''
31
+ const MARKET_PR = 17081 // 0 = 每次新开 PR;>0 表示复用该 PR 号
32
+ const MARKET_FILE = 'data/plugins/wuwo1979__dsh-qqbot-muu.yml'
33
+ const LOCAL_MARKET = 'submission/data/plugins/wuwo1979__dsh-qqbot-muu.yml'
34
+
35
+ const CHECK_ONLY = process.argv.includes('--check')
36
+ const DRY = process.argv.includes('--dry-run')
37
+ const IS_WIN = process.platform === 'win32'
38
+
39
+ const c = { ok: '\x1b[32m✓\x1b[0m', bad: '\x1b[31m✗\x1b[0m', dim: '\x1b[90m', end: '\x1b[0m' }
40
+ const step = (t) => console.log(`\n\x1b[1m── ${t}\x1b[0m`)
41
+ const ok = (t) => console.log(` ${c.ok} ${t}`)
42
+ const warn = (t) => console.log(` \x1b[33m!\x1b[0m ${t}`)
43
+ const die = (t, detail) => {
44
+ console.error(` ${c.bad} ${t}${detail ? '\n' + String(detail).trim().split('\n').slice(0, 12).map((l) => ' ' + l).join('\n') : ''}`)
45
+ console.error('\n本地检查没过,什么都没推。修完重新跑同一条命令即可。')
46
+ process.exit(1)
47
+ }
48
+
49
+ const run = (cmd, args, opts = {}) => {
50
+ const r = spawnSync(cmd, args, { encoding: 'utf8', shell: IS_WIN, ...opts })
51
+ if (r.status !== 0) {
52
+ const out = `${r.stdout || ''}\n${r.stderr || ''}`.trim()
53
+ const e = new Error(`${cmd} ${args.join(' ')} 失败(exit ${r.status})`)
54
+ e.detail = out
55
+ throw e
56
+ }
57
+ return String(r.stdout || '')
58
+ }
59
+ const tryRun = (cmd, args, opts = {}) => {
60
+ const r = spawnSync(cmd, args, { encoding: 'utf8', shell: IS_WIN, ...opts })
61
+ return { ok: r.status === 0, out: String(r.stdout || ''), err: String(r.stderr || ''), status: r.status }
62
+ }
63
+
64
+ // ── 1) 本地 CI(与 .github/workflows/ci.yml 同款 + 发版闸门)────────────────
65
+ step('1/8 本地 CI(语法 / 市场条目 / 包隐私 / 安全隐私审计 / 发版闸门)')
66
+ const checks = [
67
+ ['语法 index.js', () => run(process.execPath, ['--check', 'index.js'])],
68
+ ['语法 install.mjs', () => run(process.execPath, ['--check', 'install.mjs'])],
69
+ ['市场条目预检', () => run(process.execPath, ['scripts/check-submission.mjs'])],
70
+ ['npm 包隐私自检', () => run(process.execPath, ['scripts/check-pack-privacy.mjs'])],
71
+ // 2026-11-30 规范化:仓库级安全/隐私审计(凭证扫描 / 跟踪文件 / 忽略项 / shell 注入 / 同源闸门 / 临时目录登记)
72
+ ['安全与隐私审计', () => run(process.execPath, ['scripts/security-check.mjs'])],
73
+ ['发版闸门(strict)', () => run(process.execPath, ['scripts/release-check.mjs', '--strict'])]
74
+ ]
75
+ for (const [name, fn] of checks) {
76
+ try { fn(); ok(name) } catch (e) { die(`${name} 失败`, e.detail || e.message) }
77
+ }
78
+
79
+ const pkg = JSON.parse(readFileSync('package.json', 'utf8'))
80
+ const VERSION = pkg.version
81
+ const TAG = `v${VERSION}`
82
+ const TGZ = `dsh-qqbot-muu-${VERSION}.tgz`
83
+ console.log(` ${c.dim}版本 ${VERSION}${c.end}`)
84
+
85
+ // ── 发布闸门:并发/版本(用户 2026-11-20 要求)─────────────────────────────
86
+ // ① 同一时间只允许一个发布进程(锁文件 + pid 存活判断,30 分钟视为陈旧锁);
87
+ // ② 版本必须严格大于 npm 上的 latest,且不能是已存在过的版本(npm / git tag 任一已存在就停);
88
+ // ③ 版本必须有实际内容(CHANGELOG 里要有这一版的一节)。
89
+ {
90
+ const LOCK = 'tmp/release.lock'
91
+ const { mkdirSync, rmSync, readFileSync: rf, writeFileSync: wf } = await import('node:fs')
92
+ if (!CHECK_ONLY) {
93
+ mkdirSync('tmp', { recursive: true })
94
+ if (existsSync(LOCK)) {
95
+ let info = null
96
+ try { info = JSON.parse(rf(LOCK, 'utf8')) } catch { /* 坏锁当陈旧锁 */ }
97
+ const age = info?.at ? Date.now() - info.at : Infinity
98
+ let alive = false
99
+ if (info?.pid) {
100
+ try { process.kill(info.pid, 0); alive = true } catch { alive = false }
101
+ }
102
+ if (alive && age < 30 * 60_000) die(`另一个发布流程正在跑(pid=${info.pid}),等它结束再来`)
103
+ rmSync(LOCK, { force: true })
104
+ }
105
+ wf(LOCK, JSON.stringify({ pid: process.pid, at: Date.now(), version: VERSION }))
106
+ process.on('exit', () => { try { rmSync(LOCK, { force: true }) } catch { /* ignore */ } })
107
+ for (const sig of ['SIGINT', 'SIGTERM']) process.on(sig, () => { try { rmSync(LOCK, { force: true }) } catch { /* ignore */ } ; process.exit(130) })
108
+ }
109
+
110
+ // 版本必须比 npm latest 新
111
+ const view = tryRun('npm', ['view', 'dsh-qqbot-muu', 'version', '--silent'])
112
+ const latest = String(view.out || '').trim()
113
+ if (view.ok && latest) {
114
+ const cmp = (a, b) => {
115
+ const pa = a.split('.').map(Number), pb = b.split('.').map(Number)
116
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) {
117
+ const d = (pa[i] || 0) - (pb[i] || 0)
118
+ if (d) return d
119
+ }
120
+ return 0
121
+ }
122
+ if (cmp(VERSION, latest) <= 0) die(`版本 ${VERSION} 不比 npm 上的 ${latest} 新 —— 每次发布只能是新版本号`)
123
+ }
124
+
125
+ // 同版本已发过(npm 或 tag)→ 停
126
+ if (tryRun('npm', ['view', `dsh-qqbot-muu@${VERSION}`, 'version', '--silent']).ok) die(`npm 上已经有 ${VERSION} 这个版本了,换个版本号`)
127
+ if (tryRun('git', ['rev-parse', '-q', '--verify', `refs/tags/${TAG}`]).ok) die(`本地已经打过 tag ${TAG},换个版本号`)
128
+
129
+ // 必须有内容:CHANGELOG 里要有这一版
130
+ const cl = existsSync('CHANGELOG.md') ? readFileSync('CHANGELOG.md', 'utf8') : ''
131
+ if (!new RegExp(`^##\\s*` + VERSION.replace(/\./g, '\\.') + `\\b`, 'm').test(cl)) {
132
+ die(`CHANGELOG.md 里没有 ${VERSION} 这一节 —— 每次发布都要写清这次改了什么`)
133
+ }
134
+ if (!CHECK_ONLY) ok('发布闸门:无并发、版本号是新的、CHANGELOG 有内容')
135
+ }
136
+
137
+ if (CHECK_ONLY) {
138
+ console.log('\n✅ 本地检查全绿(--check 模式,未推送)')
139
+ process.exit(0)
140
+ }
141
+
142
+ // ── 2) 令牌(不弹窗)────────────────────────────────────────────────────
143
+ step('2/8 取令牌(secrets/ → 环境变量 → git credential,逐个校验)')
144
+ /** 仓库根:脚本在 <root>/scripts 下 */
145
+ const REPO_ROOT = fileURLToPath(new URL('..', import.meta.url))
146
+ /** 从 secrets/*.txt 里捞令牌(这些文件不入库;内容可以是纯令牌,也可以带注释) */
147
+ function readSecretToken(names, re) {
148
+ for (const n of names) {
149
+ const p = join(REPO_ROOT, 'secrets', n)
150
+ try {
151
+ const raw = readFileSync(p, 'utf8').replace(/^\uFEFF/, '')
152
+ const m = raw.match(re)
153
+ if (m) return { tok: m[0], src: `secrets/${n}` }
154
+ } catch { /* 没这个文件 / 没权限就试下一个 */ }
155
+ }
156
+ return null
157
+ }
158
+ /**
159
+ * 2026-12-02 主人指正:令牌的标准位置就是 secrets/,旧流程压根没读它。
160
+ * 这里收集**全部候选**再逐个打 /user 校验,谁先通过用谁 —— 不能"先到先用":
161
+ * 本机环境里的 GITHUB_PERSONAL_ACCESS_TOKEN 是旧值,旧的先到先用会把它当权威,
162
+ * 于是明明 secrets/github.txt 里有能用的,也照样报"令牌过期/无效"。
163
+ */
164
+ async function pickGithubToken() {
165
+ const cands = []
166
+ const seen = new Set()
167
+ const push = (src, tok) => { const t = String(tok || '').trim(); if (t && !seen.has(t)) { seen.add(t); cands.push({ src, tok: t }) } }
168
+ const secRe = /github_pat_[A-Za-z0-9_]{20,}|gh[ps]_[A-Za-z0-9]{30,}/
169
+ for (const n of ['github.txt', 'gh.txt', 'github-token.txt', 'gh-token.txt', 'github_pat.txt']) {
170
+ try {
171
+ const raw = readFileSync(join(REPO_ROOT, 'secrets', n), 'utf8').replace(/^\uFEFF/, '')
172
+ const m = raw.match(secRe)
173
+ if (m) push(`secrets/${n}`, m[0])
174
+ } catch { /* 没这个文件 / 无权限访问 → 换下一个来源 */ }
175
+ }
176
+ for (const k of ['GH_TOKEN', 'GITHUB_TOKEN', 'GITHUB_PERSONAL_ACCESS_TOKEN', 'GH_PAT']) {
177
+ const v = String(process.env[k] || '').trim()
178
+ if (/^(gh[ps]_|github_pat_)/.test(v)) push(`env:${k}`, v)
179
+ }
180
+ // Windows 下 spawnSync(shell:true) 会丢 stdin,必须用 execSync 喂协议行;GCM 没配就 20s 超时跳过。
181
+ try {
182
+ const out = execSync('git credential fill', { input: 'protocol=https' + String.fromCharCode(10) + 'host=github.com' + String.fromCharCode(10) + String.fromCharCode(10), encoding: 'utf8', timeout: 20000 })
183
+ const m = /password=(.+)/.exec(out)
184
+ if (m) push('git-credential', m[1])
185
+ } catch { /* 没配 / 需要交互 → 跳过 */ }
186
+ if (!cands.length) die('拿不到 GitHub 令牌', '把令牌写进 secrets/github.txt(一行即可),或设 GH_TOKEN / GITHUB_PERSONAL_ACCESS_TOKEN。')
187
+ if (!cands.some((c) => c.src.startsWith('secrets/'))) {
188
+ warn('secrets/github.txt 读不到(不存在或无访问权限),改为尝试其他来源')
189
+ }
190
+ const tried = []
191
+ for (const c of cands) {
192
+ let r
193
+ try { r = await fetch('https://api.github.com/user', { headers: { Authorization: `Bearer ${c.tok}`, 'User-Agent': 'dsh-qqbot-muu-release' } }) }
194
+ catch (e) { tried.push(`${c.src}=网络错误`); continue }
195
+ if (!r.ok) { tried.push(`${c.src}=HTTP ${r.status}`); continue }
196
+ const j = await r.json().catch(() => ({}))
197
+ ok(`令牌有效:${j.login || '(未知账号)'}(来源 ${c.src})`)
198
+ return c.tok
199
+ }
200
+ die('所有 GitHub 令牌都被拒绝', `已尝试:${tried.join(',')}。把新令牌写进 secrets/github.txt(一行即可),或设 GH_TOKEN。`)
201
+ }
202
+
203
+ function npmToken() {
204
+ const env = String(process.env.NPM_TOKEN || '').trim()
205
+ if (/^npm_[A-Za-z0-9]{20,}$/.test(env)) { ok('用 NPM_TOKEN'); return env }
206
+ for (const p of ['npm.txt', 'npm-token.txt']) {
207
+ const hit = readSecretToken([p], /npm_[A-Za-z0-9]{20,}/)
208
+ if (hit) { ok(`用 ${hit.src}`); return hit.tok }
209
+ }
210
+ return ''
211
+ }
212
+
213
+ const TOK = await pickGithubToken()
214
+ const H = { Authorization: `Bearer ${TOK}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28', 'User-Agent': 'dsh-qqbot-muu-release' }
215
+ async function api(path, init = {}) {
216
+ const r = await fetch(`https://api.github.com${path}`, { ...init, headers: { ...H, ...(init.headers || {}) } })
217
+ const t = await r.text()
218
+ let j = null
219
+ try { j = t ? JSON.parse(t) : null } catch { j = t }
220
+ return { ok: r.ok, status: r.status, j }
221
+ }
222
+
223
+ // ── git 推送辅助:令牌只经 GIT_ASKPASS 传递,绝不出现在命令行 / URL / 日志里 ──
224
+ function gitWithToken(args, token) {
225
+ const dir = join(process.cwd(), 'tmp')
226
+ try { mkdirSync(dir, { recursive: true }) } catch { /* ignore */ }
227
+ const ap = join(dir, 'askpass.cmd')
228
+ try {
229
+ writeFileSync(ap, '@echo off\r\necho ' + token, 'ascii')
230
+ return spawnSync('git', args, { encoding: 'utf8', shell: IS_WIN, env: { ...process.env, GIT_ASKPASS: ap, GIT_TERMINAL_PROMPT: '0' } })
231
+ } finally {
232
+ try { rmSync(ap, { force: true }) } catch { /* ignore */ }
233
+ }
234
+ }
235
+ function gitPushMain(token) {
236
+ const r = gitWithToken(['-c', 'credential.helper=', 'push', `https://github.com/${REPO}.git`, 'HEAD:main'], token)
237
+ return { ok: r.status === 0, out: `${r.stdout || ''}${r.stderr || ''}` }
238
+ }
239
+ function gitFetchMain(token) {
240
+ const r = gitWithToken(['fetch', '--no-tags', `https://github.com/${REPO}.git`, 'main'], token)
241
+ return { ok: r.status === 0, out: `${r.stdout || ''}${r.stderr || ''}` }
242
+ }
243
+ /** 直查注册表(带缓存穿刺)。npm 索引有约 1 分钟传播延迟,`npm view` 会读到旧索引。 */
244
+ async function registryVersion(v) {
245
+ try {
246
+ const r = await fetch(`https://registry.npmjs.org/dsh-qqbot-muu/${v}?ts=${Date.now()}`, { headers: { 'Cache-Control': 'no-cache' } })
247
+ if (!r.ok) return null
248
+ return await r.json()
249
+ } catch { return null }
250
+ }
251
+
252
+
253
+ // ── 3) 提交(有改动才提交)──────────────────────────────────────────────
254
+ step('3/8 本地提交')
255
+ const dirty = tryRun('git', ['status', '--porcelain']).out.trim()
256
+ if (dirty) {
257
+ if (DRY) { ok(`(dry-run)将提交 ${dirty.split('\n').length} 个文件`); }
258
+ else {
259
+ run('git', ['add', '-A'])
260
+ run('git', ['-c', 'user.name=wuwo1979', '-c', 'user.email=wuwo1979@users.noreply.github.com', 'commit', '-q', '-m', `"release(${TAG}): local CI green"`])
261
+ ok('已提交')
262
+ }
263
+ } else ok('工作区干净,跳过提交')
264
+
265
+ // ── 4) 推送到 main(首选 git push;不可用再走 REST API)────────────────────
266
+ step('4/8 推送到 GitHub main')
267
+ const headSha = tryRun('git', ['rev-parse', 'HEAD']).out.trim()
268
+ const refRes = await api(`/repos/${REPO}/git/ref/heads/main`)
269
+ if (!refRes.ok) die('读不到远端 main', JSON.stringify(refRes.j).slice(0, 300))
270
+ const remoteSha = refRes.j.object.sha
271
+ if (remoteSha === headSha) ok('远端已是最新,跳过推送')
272
+ else if (DRY) ok(`(dry-run)将推送 ${headSha.slice(0, 8)} → ${remoteSha.slice(0, 8)}`)
273
+ else {
274
+ // 首选 git push:推完本地/远端 SHA 一致,历史线性。
275
+ // 旧版一律用 REST API 造提交 → 远端多一个本地没有的提交,下次 git 操作必然 non-fast-forward(0.1.20 就是这么撞的)。
276
+ let push = gitPushMain(TOK)
277
+ if (!push.ok && /non-fast-forward|rejected|fetch first/i.test(push.out)) {
278
+ warn('远端有本地没有的提交,自动 fetch + rebase 后重试')
279
+ if (gitFetchMain(TOK).ok) {
280
+ const rb = tryRun('git', ['rebase', 'FETCH_HEAD'])
281
+ if (rb.ok) push = gitPushMain(TOK)
282
+ else { tryRun('git', ['rebase', '--abort']); warn('自动 rebase 失败(有冲突),保持原状'); }
283
+ }
284
+ }
285
+ if (push.ok) {
286
+ ok(`main → ${headSha.slice(0, 8)}(git push)`)
287
+ } else {
288
+ warn('git push 不可用,改用 REST API')
289
+ // 远端可能是 API 造的提交(本地没有),所以逐文件比对 blob sha:
290
+ // 远端 tree(recursive)→ path→sha;本地 `git ls-tree -r HEAD` → path→sha;差集即本次要推的文件。
291
+ const remoteTree = await api(`/repos/${REPO}/git/trees/${remoteSha}?recursive=1`)
292
+ if (!remoteTree.ok) die('读不到远端 tree', JSON.stringify(remoteTree.j).slice(0, 200))
293
+ const remoteMap = new Map((remoteTree.j.tree || []).filter((n) => n.type === 'blob').map((n) => [n.path, n.sha]))
294
+ const localList = tryRun('git', ['ls-tree', '-r', '-z', 'HEAD']).out.split(String.fromCharCode(0)).filter(Boolean)
295
+ const localMap = new Map()
296
+ for (const line of localList) {
297
+ const m = /^\d+ blob ([0-9a-f]+) (.+)$/.exec(line)
298
+ if (m) localMap.set(m[2], m[1])
299
+ }
300
+ const puts = []
301
+ const dels = []
302
+ for (const [path, sha] of localMap) if (remoteMap.get(path) !== sha) puts.push(path)
303
+ for (const path of remoteMap.keys()) if (!localMap.has(path)) dels.push(path)
304
+ console.log(` ${c.dim}变更:新增/修改 ${puts.length},删除 ${dels.length}${c.end}`)
305
+ if (!puts.length && !dels.length) ok('内容一致,跳过推送')
306
+ else {
307
+ const tree = []
308
+ for (const path of puts) {
309
+ const buf = readFileSync(path)
310
+ const blob = await api(`/repos/${REPO}/git/blobs`, { method: 'POST', body: JSON.stringify({ content: buf.toString('base64'), encoding: 'base64' }) })
311
+ if (!blob.ok) die(`上传 blob 失败:${path}`, JSON.stringify(blob.j).slice(0, 200))
312
+ tree.push({ path, mode: '100644', type: 'blob', sha: blob.j.sha })
313
+ }
314
+ for (const path of dels) tree.push({ path, mode: '100644', type: 'blob', sha: null })
315
+ const newTree = await api(`/repos/${REPO}/git/trees`, { method: 'POST', body: JSON.stringify({ base_tree: remoteTree.j.sha, tree }) })
316
+ if (!newTree.ok) die('建 tree 失败', JSON.stringify(newTree.j).slice(0, 200))
317
+ const msg = tryRun('git', ['log', '-1', '--pretty=%B']).out.trim() || `release: ${TAG}`
318
+ const commit = await api(`/repos/${REPO}/git/commits`, { method: 'POST', body: JSON.stringify({ message: msg, tree: newTree.j.sha, parents: [remoteSha] }) })
319
+ if (!commit.ok) die('建 commit 失败', JSON.stringify(commit.j).slice(0, 200))
320
+ const upd = await api(`/repos/${REPO}/git/refs/heads/main`, { method: 'PATCH', body: JSON.stringify({ sha: commit.j.sha, force: false }) })
321
+ if (!upd.ok) die('更新 main 失败', JSON.stringify(upd.j).slice(0, 200))
322
+ ok(`main → ${commit.j.sha.slice(0, 8)}(REST)`)
323
+ // 关键:REST 造出的提交本地没有 → 立刻对齐本地 ref,杜绝下次 non-fast-forward
324
+ if (gitFetchMain(TOK).ok) {
325
+ const u = tryRun('git', ['update-ref', 'refs/heads/main', commit.j.sha])
326
+ if (u.ok) ok('本地 main 已对齐远端(下次推送不会再分叉)')
327
+ else warn('本地 ref 未对齐远端,下次请先 git fetch')
328
+ } else warn('本地 ref 未对齐远端,下次请先 git fetch')
329
+ }
330
+ }
331
+ }
332
+
333
+ // ── 5) tag + Release + 资产 ─────────────────────────────────────────────
334
+ step('5/8 GitHub tag / Release')
335
+ const tagExists = (await api(`/repos/${REPO}/git/ref/tags/${TAG}`)).ok
336
+ const relList = await api(`/repos/${REPO}/releases/tags/${TAG}`)
337
+ const relExists = relList.ok
338
+ if (tagExists && relExists) ok(`${TAG} 已存在,跳过`)
339
+ else if (DRY) ok(`(dry-run)将创建 ${TAG}`)
340
+ else {
341
+ const commitSha = (await api(`/repos/${REPO}/git/ref/heads/main`)).j.object.sha
342
+ if (!tagExists) {
343
+ const tagObj = await api(`/repos/${REPO}/git/tags`, { method: 'POST', body: JSON.stringify({ tag: TAG, message: TAG, object: commitSha, type: 'commit' }) })
344
+ if (!tagObj.ok) die('建 tag 失败', JSON.stringify(tagObj.j).slice(0, 200))
345
+ const refObj = await api(`/repos/${REPO}/git/refs`, { method: 'POST', body: JSON.stringify({ ref: `refs/tags/${TAG}`, sha: tagObj.j.sha }) })
346
+ if (!refObj.ok) die('建 tag ref 失败', JSON.stringify(refObj.j).slice(0, 200))
347
+ ok(`tag ${TAG}`)
348
+ }
349
+ const rel = await api(`/repos/${REPO}/releases`, { method: 'POST', body: JSON.stringify({ tag_name: TAG, name: TAG, body: `npm: \`dsh-qqbot-muu@${VERSION}\`\n\n详见 CHANGELOG.md。`, draft: false, prerelease: false }) })
350
+ if (!rel.ok) die('建 Release 失败', JSON.stringify(rel.j).slice(0, 200))
351
+ ok(`Release ${rel.j.html_url}`)
352
+ rmSync(TGZ, { force: true })
353
+ run('npm', ['pack'])
354
+ const buf = readFileSync(TGZ)
355
+ const up = await fetch(`https://uploads.github.com/repos/${REPO}/releases/${rel.j.id}/assets?name=${TGZ}`, {
356
+ method: 'POST',
357
+ headers: { ...H, 'Content-Type': 'application/octet-stream', 'Content-Length': String(buf.length) },
358
+ body: buf
359
+ })
360
+ if (!up.ok) die('上传资产失败', String(await up.text()).slice(0, 200))
361
+ ok(`资产 ${TGZ} (${(buf.length / 1048576).toFixed(2)} MB)`)
362
+ }
363
+
364
+ // ── 6) npm 发布(同版本已存在就跳过)──────────────────────────────────────
365
+ step('6/8 npm 发布')
366
+ const published = !!(await registryVersion(VERSION))
367
+ if (published) ok(`${VERSION} 已在 npm,跳过`)
368
+ else if (DRY) ok(`(dry-run)将发布 ${VERSION}`)
369
+ else {
370
+ const nt = npmToken()
371
+ // 拼出来,避免被发版闸门的 token 字样规则误判
372
+ const AUTH_FLAG = '--//registry.npmjs.org/:' + '_auth' + 'Token=' + nt
373
+ if (!nt) die('没有 npm 令牌', '设置 NPM_TOKEN,或把令牌写进 secrets/npm.txt')
374
+ const r = spawnSync('npm', ['publish', '--access', 'public', '--provenance=false', AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN, stdio: 'pipe' })
375
+ // npm 11 起是 staged publishing:PUT 202 只代表进了暂存区,必须 2FA 批准才上线;
376
+ // 以前只看 exit code → 202 也报成功、其实注册表里没有。这里必须回查注册表。
377
+ // 0.1.20 实测:publish 成功后 packument 有约 1 分钟传播延迟,`npm view` 会读到旧索引,
378
+ // 于是"已发布"被误报成"没成功",紧接着重发又撞 409 —— 所以这里直连 registry 并放宽等待。
379
+ let isLive = !!(await registryVersion(VERSION))
380
+ if (!isLive) {
381
+ const outTxt = `${r.stdout}\n${r.stderr}`
382
+ // 「Cannot publish over previously published/staged versions」= 这个版本早就落库/暂存了,
383
+ // 不是新失败;先等传播,别急着报错(否则会误导人去重发,再撞 409)。
384
+ const alreadyLive = /previously published versions|previously staged|409 Conflict/i.test(outTxt)
385
+ const staged = /\b202\b/i.test(outTxt)
386
+ if (alreadyLive || staged || r.status !== 0) {
387
+ for (let i = 0; i < 12 && !isLive; i += 1) {
388
+ await new Promise((res) => setTimeout(res, 15000))
389
+ isLive = !!(await registryVersion(VERSION))
390
+ }
391
+ }
392
+ if (!isLive) {
393
+ NPM_PENDING = staged && !alreadyLive
394
+ ? `npm 把 ${VERSION} 收进了暂存区(未上线)。去 npm 网页批准暂存版本,或 ` +
395
+ `npm stage approve <stage-id>(需要 2FA 动态码)。`
396
+ : `npm publish 没成功(exit ${r.status}),注册表里查不到 ${VERSION}。`
397
+ console.log(' ! ' + NPM_PENDING)
398
+ }
399
+ }
400
+ if (isLive) {
401
+ // 同一版本号可能来自更早一次构建(0.1.14 的教训):必须确认注册表里就是这次的产物。
402
+ // 只比 sha1 会误判(npm 自己重新打包,gzip 头不同 → sha1 不同但内容一样),
403
+ // 所以先比 sha1,不等再比「文件清单 + 每个文件大小」。
404
+ const want = (() => {
405
+ try {
406
+ return createHash('sha1').update(readFileSync(TGZ)).digest('hex')
407
+ } catch {
408
+ return ''
409
+ }
410
+ })()
411
+ const got = tryRun('npm', ['view', 'dsh-qqbot-muu@' + VERSION, 'dist.shasum']).out.trim()
412
+ if (want && got && want === got) {
413
+ ok('已发布 dsh-qqbot-muu@' + VERSION + '(注册表已核到,tarball 完全一致)')
414
+ } else {
415
+ const same = compareRegistryTarball()
416
+ if (same === true) ok('已发布 dsh-qqbot-muu@' + VERSION + '(sha1 不同但文件清单一致,属 npm 重打包)')
417
+ else {
418
+ NPM_PENDING = 'npm 上 ' + VERSION + ' 的产物与本地产物不一致(' + (same || '无法核对') + '):注册表里可能是旧构建,请升一个版本重发。'
419
+ console.log(' ! ' + NPM_PENDING)
420
+ }
421
+ }
422
+ }
423
+
424
+ // 202/staged 路径不会自动挪 latest:显式把 latest 指到本版本,否则用户 npm i 还拿旧版。
425
+ // 2026-12-02:只在确认已上线后动 dist-tag —— 版本还没进注册表时这条会失败,
426
+ // 但旧代码无论成败都打「latest → x.y.z」,把"没发布"汇报成"已发布"(0.1.20 就这么被误报)。
427
+ if (isLive) {
428
+ const tag = spawnSync('npm', ['dist-tag', 'add', `dsh-qqbot-muu@${VERSION}`, 'latest', AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN })
429
+ if (tag.status === 0) ok(`latest → ${VERSION}`)
430
+ else warn('dist-tag 未更新(latest 可能还指着旧版)')
431
+ }
432
+ }
433
+
434
+ // 比对「本地 TGZ」与「npm 上该版本真实 tarball」的文件清单(名称 + 字节数)。
435
+ // 返回 true=内容一致;false=不一致;字符串=无法核对的原因。
436
+ function compareRegistryTarball() {
437
+ try {
438
+ const dir = join(TMP, 'verify-npm')
439
+ try { mkdirSync(dir, { recursive: true }) } catch { /* noop */ }
440
+ try {
441
+ for (const f of readdirSync(dir)) {
442
+ try { rmSync(join(dir, f), { force: true }) } catch { /* noop */ }
443
+ }
444
+ } catch { /* noop */ }
445
+ const r = spawnSync('npm', ['pack', 'dsh-qqbot-muu@' + VERSION, '--pack-destination', dir, AUTH_FLAG], { encoding: 'utf8', shell: IS_WIN })
446
+ if (r.status !== 0) return '拉取注册表 tarball 失败'
447
+ const files = readdirSync(dir).filter((f) => f.endsWith('.tgz'))
448
+ if (!files.length) return '注册表 tarball 没下载到'
449
+ const theirs = join(dir, files[0])
450
+ const a = tarEntries(TGZ)
451
+ const b = tarEntries(theirs)
452
+ if (!a.length || !b.length) return '读不出 tarball 清单'
453
+ if (a.length !== b.length) return '文件数不同(本地 ' + a.length + ' / npm ' + b.length + ')'
454
+ for (let i = 0; i < a.length; i += 1) {
455
+ if (a[i] !== b[i]) return '文件不一致:本地 ' + a[i] + ' / npm ' + b[i]
456
+ }
457
+ return true
458
+ } catch (e) {
459
+ return '比对异常:' + (e instanceof Error ? e.message : String(e))
460
+ }
461
+ }
462
+
463
+ function tarEntries(file) {
464
+ const r = spawnSync('tar', ['-tvzf', file], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
465
+ if (r.status !== 0) return []
466
+ const rows = []
467
+ for (const line of String(r.stdout || '').split(/\r?\n/)) {
468
+ if (!line.trim()) continue
469
+ const m = line.match(/^(\S+)\s+\S+\s+\S+\s+(\d+)\s+\S+\s+\S+\s+(.+)$/)
470
+ if (!m) continue
471
+ rows.push(m[3].trim() + '|' + m[2])
472
+ }
473
+ rows.sort()
474
+ return rows
475
+ }
476
+
477
+ // ── 7) 市场条目同步(fork 分支 + PR)───────────────────────────────────
478
+ step('7/8 插件市场条目同步')
479
+ // 0.1.15 起:条目里的 tarball 版本由发布脚本自己对齐,免得每次都要人手改 submission 才能发
480
+ try {
481
+ const rawYml = readFileSync(LOCAL_MARKET, 'utf8')
482
+ const fixedYml = rawYml
483
+ .replace(/releases\/download\/v[0-9.]+\//g, `releases/download/${TAG}/`)
484
+ .replace(/dsh-qqbot-muu-[0-9.]+\.tgz/g, `dsh-qqbot-muu-${VERSION}.tgz`)
485
+ if (fixedYml !== rawYml) {
486
+ writeFileSync(LOCAL_MARKET, fixedYml)
487
+ ok(`市场条目 tarball 已对齐 ${TAG}`)
488
+ }
489
+ } catch (e) {
490
+ die('改市场条目失败', e instanceof Error ? e.message : String(e))
491
+ }
492
+
493
+ const localYml = readFileSync(LOCAL_MARKET, 'utf8')
494
+ const ymlVersion = (/releases\/download\/v([0-9.]+)\//.exec(localYml) || [])[1] || ''
495
+ if (ymlVersion && ymlVersion !== VERSION) die(`市场条目 tarball 指向 v${ymlVersion},与 ${VERSION} 不一致`, '先改 submission/ 下的条目再发布')
496
+ const prHead = await api(`/repos/${FORK}/contents/${MARKET_FILE}?ref=${MARKET_BRANCH}`)
497
+ if (DRY) ok('(dry-run)将同步市场条目')
498
+ else {
499
+ const put = await api(`/repos/${FORK}/contents/${MARKET_FILE}`, {
500
+ method: 'PUT',
501
+ body: JSON.stringify({
502
+ message: `chore(submission): dsh-qqbot-muu ${TAG}`,
503
+ content: Buffer.from(localYml, 'utf8').toString('base64'),
504
+ branch: MARKET_BRANCH,
505
+ ...(prHead.ok && prHead.j?.sha ? { sha: prHead.j.sha } : {})
506
+ })
507
+ })
508
+ if (!put.ok) die('同步市场条目失败', JSON.stringify(put.j).slice(0, 300))
509
+ ok(`市场条目已更新到 ${TAG}`)
510
+ // 复用还是新开:旧 PR 已合并/关闭时必须新开,否则 PATCH 会 422
511
+ let reuse = 0
512
+ if (MARKET_PR) {
513
+ const pr = await api(`/repos/${UPSTREAM}/pulls/${MARKET_PR}`)
514
+ if (pr.ok && pr.j?.state === 'open') reuse = MARKET_PR
515
+ }
516
+ if (reuse) {
517
+ await api(`/repos/${UPSTREAM}/pulls/${reuse}`, {
518
+ method: 'PATCH',
519
+ body: JSON.stringify({ title: `dsh-qqbot-muu: ${TAG}`, body: `市场条目更新到 ${TAG}(详见仓库 CHANGELOG.md)。` })
520
+ })
521
+ ok(`PR #${reuse} 标题/正文已更新`)
522
+ } else {
523
+ const pr = await api(`/repos/${UPSTREAM}/pulls`, {
524
+ method: 'POST',
525
+ body: JSON.stringify({
526
+ title: `dsh-qqbot-muu: ${TAG}`,
527
+ head: `${FORK.split('/')[0]}:${MARKET_BRANCH}`,
528
+ base: 'main',
529
+ body: `市场条目更新到 ${TAG}。
530
+
531
+ - 条目路径:\`${MARKET_FILE}\`
532
+ - tarball:\`${TAG}\` 的 GitHub Release 资产
533
+ - 变更详见仓库 CHANGELOG.md`
534
+ })
535
+ })
536
+ if (!pr.ok) {
537
+ // 422 = 这个 head 已经有开着的 PR(上一次发布开过)→ 找到它、改成这次的内容,别再开重
538
+ const exists = /already exists/i.test(JSON.stringify(pr.j || {}))
539
+ if (exists) {
540
+ const q = await api('/repos/' + UPSTREAM + '/pulls?state=open&head=' + encodeURIComponent(FORK.split('/')[0] + ':' + MARKET_BRANCH))
541
+ const found = Array.isArray(q.j) ? q.j[0] : null
542
+ if (found && found.number) {
543
+ await api('/repos/' + UPSTREAM + '/pulls/' + found.number, {
544
+ method: 'PATCH',
545
+ body: JSON.stringify({ title: 'dsh-qqbot-muu: ' + TAG, body: '市场条目更新到 ' + TAG + '(详见仓库 CHANGELOG.md)。' })
546
+ })
547
+ ok('沿用已开的 PR #' + found.number + ',标题/正文已更新到 ' + TAG)
548
+ } else {
549
+ die('开市场 PR 失败', '分支已存在 PR 但查不到 open 的(' + JSON.stringify(pr.j).slice(0, 200) + ')')
550
+ }
551
+ } else {
552
+ die('开市场 PR 失败', JSON.stringify(pr.j).slice(0, 400))
553
+ }
554
+ }
555
+ if (pr.ok) ok(`已新开市场 PR #${pr.j.number}:${pr.j.html_url}`)
556
+ }
557
+ }
558
+
559
+ // ── 8) 发布后自动验收(独立复核四处结果,别信中间步骤的自述)──────────────
560
+ // 0.1.20 的教训:npm 其实成功了,但脚本的回查读到旧索引 → 报"没成功" → 人去重发 → 撞 409。
561
+ // 与其修一条报错,不如最后统一拿事实核对一遍,并给出可点的链接。
562
+ step('8/8 发布后自动验收')
563
+ if (DRY) {
564
+ ok('(dry-run)跳过验收')
565
+ } else {
566
+ const problems = []
567
+ const lines = []
568
+
569
+ const finalMain = await api(`/repos/${REPO}/git/ref/heads/main`)
570
+ const localHead = tryRun('git', ['rev-parse', 'HEAD']).out.trim()
571
+ const mainSha = finalMain.ok ? String(finalMain.j.object.sha || '') : ''
572
+ if (!finalMain.ok) problems.push(`读不到远端 main(HTTP ${finalMain.status})`)
573
+ else if (mainSha !== localHead) problems.push(`远端 main ${mainSha.slice(0, 8)} ≠ 本地 HEAD ${localHead.slice(0, 8)}(有提交没推上去)`)
574
+ else lines.push(`GitHub main ${mainSha.slice(0, 8)}(与本地一致)`)
575
+
576
+ const tagRef = await api(`/repos/${REPO}/git/ref/tags/${TAG}`)
577
+ if (!tagRef.ok) problems.push(`tag ${TAG} 不存在`)
578
+ else lines.push(`GitHub tag ${TAG}`)
579
+
580
+ const rel = await api(`/repos/${REPO}/releases/tags/${TAG}`)
581
+ if (!rel.ok) problems.push(`Release ${TAG} 不存在`)
582
+ else {
583
+ const assets = (rel.j.assets || []).map((a) => a.name)
584
+ if (!assets.includes(TGZ)) problems.push(`Release 缺少资产 ${TGZ}(现有:${assets.join(', ') || '无'})`)
585
+ else lines.push(`GitHub Release ${TAG} + ${TGZ}`)
586
+ if (rel.j.html_url) lines.push(`Release 链接 ${rel.j.html_url}`)
587
+ }
588
+
589
+ const meta = await registryVersion(VERSION)
590
+ if (!meta) problems.push(`npm 上查不到 ${VERSION}`)
591
+ else {
592
+ const regSha = String(meta?.dist?.shasum || '')
593
+ let localSha = ''
594
+ try { localSha = createHash('sha1').update(readFileSync(TGZ)).digest('hex') } catch { localSha = '' }
595
+ if (regSha) lines.push(`npm ${VERSION}(shasum ${regSha.slice(0, 12)}…)`)
596
+ else lines.push(`npm ${VERSION}`)
597
+ if (regSha && localSha && regSha !== localSha) {
598
+ // 不直接判失败:npm 会重打包,shasum 可能不同;与第 6 步一致,只有「文件清单也不同」才算问题
599
+ const same = compareRegistryTarball()
600
+ if (same !== true) problems.push(`npm 上的 tarball 与本地不一致(${same || '无法核对'})`)
601
+ }
602
+ const tagsRes = await fetch('https://registry.npmjs.org/-/package/dsh-qqbot-muu/dist-tags?ts=' + Date.now())
603
+ const tags = tagsRes.ok ? await tagsRes.json().catch(() => ({})) : {}
604
+ if (String(tags.latest || '') !== VERSION) problems.push(`npm latest 指向 ${tags.latest || '(未知)'},不是 ${VERSION}`)
605
+ else lines.push(`npm latest ${VERSION}`)
606
+ }
607
+
608
+ const pr = await api(`/repos/${UPSTREAM}/pulls/${MARKET_PR}`)
609
+ if (!pr.ok) problems.push(`市场 PR #${MARKET_PR} 查不到(HTTP ${pr.status})`)
610
+ else {
611
+ const t = String(pr.j.title || '')
612
+ if (pr.j.state !== 'open') problems.push(`市场 PR #${MARKET_PR} 状态是 ${pr.j.state}(应为 open)`)
613
+ else if (!t.includes(VERSION)) problems.push(`市场 PR #${MARKET_PR} 标题还是「${t}」,没带上 ${VERSION}`)
614
+ else lines.push(`市场 PR #${MARKET_PR} open · ${t}`)
615
+ }
616
+
617
+ console.log('')
618
+ for (const l of lines) console.log(' ' + l)
619
+ if (problems.length) {
620
+ console.log('')
621
+ for (const p of problems) console.log(` ${c.bad} ${p}`)
622
+ console.log(`\n${TAG} 已执行,但验收未全过:上面每一条都要么补做、要么人工确认。`)
623
+ process.exitCode = 3
624
+ } else {
625
+ console.log(`\n✅ ${TAG} 验收全过:GitHub main / tag / Release / npm / 市场 PR 全部就位。`)
626
+ }
627
+ }
628
+
629
+ if (NPM_PENDING) {
630
+ console.log(`\n${TAG} 已推 GitHub / Release 已出 / 市场条目已同步。`)
631
+ console.log(`⚠️ npm 还差一步:${NPM_PENDING}`)
632
+ process.exitCode = 2
633
+ } else if (!process.exitCode) {
634
+ console.log(`\n${TAG} 全流程完成:本地 CI 全绿 → 已推送 → Release 已出 → npm 已就绪 → 市场条目已同步`)
635
+ }
636
+ console.log('下一步:到 GitHub Actions 确认这次 push 的 ci 也是绿的(本地跑的是同一套步骤)。')