@capyclaw/publisher 0.1.0 → 0.1.4

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/server/impl.mjs CHANGED
@@ -9,24 +9,30 @@
9
9
  * - root(要发布的仓库 checkout)是调用参数,不再是模块常量;
10
10
  * - npm view / npm pack 的缓存挂在每次调用的 context 上(服务进程长驻,避免跨调用串味);
11
11
  * - 新增轻量 pack 闸(npm pack --dry-run 断言 package.json/main/patch 必在包内),
12
- * 顶替原 scripts/verify-publishable.mjs 的核心保护。
12
+ * 顶替原 scripts/verify-publishable.mjs 的核心保护;
13
+ * - npm/tar 子进程全部异步 spawn(spawnSync 会把宿主事件循环钉死,
14
+ * 与 README「npm 调用全部异步」的承诺矛盾),结果结构与 spawnSync 同形。
13
15
  */
14
16
 
15
- import { spawnSync } from 'node:child_process'
17
+ import { spawn } from 'node:child_process'
16
18
  import crypto from 'node:crypto'
17
19
  import fs from 'node:fs'
18
20
  import os from 'node:os'
19
21
  import path from 'node:path'
20
22
 
21
23
  import { validatePlugin } from '@capyclaw/plugin-validator'
24
+ import { stagePlugin } from '@capyclaw/plugin-kit/packaging/pack'
25
+ import { makeSelfContained } from '@capyclaw/plugin-kit/packaging/self-contained'
22
26
 
23
27
  /** 支撑库目录(相对仓库根):纯库/独立服务,无 dsh.bundle,插件发现集不收,显式清单维护。
24
28
  * 可用 DSH_PUBLISHER_LIBS(JSON 数组,相对 root 的路径)覆盖。 */
25
29
  export const DEFAULT_SUPPORT_LIBS = [
26
- 'packages/capyclaw-plugin-kit',
27
- 'packages/capyclaw-document-workbench',
28
- 'packages/capyclaw-host-shell',
29
- 'extensions/bridges/ppt-bridge/capyclaw-skills-service',
30
+ 'C/packages/capyclaw-plugin-kit',
31
+ 'C/packages/capyclaw-document-workbench',
32
+ 'C/packages/capyclaw-host-shell',
33
+ 'C/packages/capyclaw-skills-service',
34
+ 'C/packages/capyclaw-portal',
35
+ 'C/packages/capyclaw-suite-kit',
30
36
  ]
31
37
 
32
38
  /** 与原脚本一致的失败状态集(其余视为通过或跳过)。 */
@@ -53,7 +59,17 @@ export function publishGateErrors(pkg, srcDir) {
53
59
  }
54
60
  const patch = pkg.dsh?.bundle?.patch
55
61
  const patches = Array.isArray(patch) ? patch : patch ? [patch] : []
56
- if (!patches.length) errors.push('缺少 dsh.bundle.patch(dsh 不会把这个包当作 profile 层加载)')
62
+ /* dsh.member: true —— 只随套件分发的成员包(如各 workbench)。
63
+ * 它们不向 profile 插入任何行,所以没有 bundle.patch 是**正确状态**;反过来,
64
+ * 成员包若声明了补丁就会和套件重复声明同一行,把卸载守卫焊死。
65
+ * 与 C/tools/capyclaw-plugin-release 的判定必须逐字一致(parity 闸会比对)。 */
66
+ if (pkg.dsh?.member === true) {
67
+ if (patches.length) {
68
+ errors.push('dsh.member: true 的成员包不应声明 dsh.bundle.patch(会与套件重复声明同一行)')
69
+ }
70
+ } else if (!patches.length) {
71
+ errors.push('缺少 dsh.bundle.patch(dsh 不会把这个包当作 profile 层加载)')
72
+ }
57
73
  for (const rel of patches) {
58
74
  if (!fs.existsSync(path.join(srcDir, rel))) errors.push(`dsh.bundle.patch 指向的文件不存在: ${rel}`)
59
75
  }
@@ -91,7 +107,7 @@ export function libraryGateErrors(pkg) {
91
107
  }
92
108
 
93
109
  /** 插件扫码根目录 + 包名形态。(移植自 plugin-release;发布闸用不到 suite 校验器注入) */
94
- const PLUGIN_BASES = ['packages', 'extensions/official', 'extensions/bridges', 'extensions/bridges/*/plugin']
110
+ const PLUGIN_BASES = ['C/packages', 'B/official', 'A/projects']
95
111
  const PUBLISHABLE_NAME = /^((@[\w.-]+\/)?dsh-[\w.-]+|@capyclaw\/[\w.-]+)$/
96
112
 
97
113
  /** 找出 root 下所有**可发布**的插件目录(过得了发布闸的才算)。未就绪的落 lastSkipped。 */
@@ -105,7 +121,7 @@ export function discoverPlugins({ root, includeNotReady = false } = {}) {
105
121
  try {
106
122
  const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'))
107
123
  const publishable = PUBLISHABLE_NAME.test(pkg.name || '')
108
- && (pkg.dsh?.bundle || pkg.dsh?.client || pkg.dsh?.suite)
124
+ && (pkg.dsh?.bundle || pkg.dsh?.client || pkg.dsh?.suite || pkg.dsh?.member)
109
125
  if (publishable && !seen.has(pkg.name)) {
110
126
  seen.add(pkg.name)
111
127
  const reasons = publishGateErrors(pkg, dir)
@@ -139,39 +155,96 @@ export function pkgOf(dir) {
139
155
 
140
156
  /** npm 直调(node npm-cli.js,不走 shell):含空格的临时/用户目录不会被拆词。 */
141
157
  const NPM_CLI = path.join(path.dirname(process.execPath), 'node_modules', 'npm', 'bin', 'npm-cli.js')
142
- function rawNpmRun(args, options = {}) {
158
+
159
+ /** 异步 spawn + 收集 stdout/stderr,resolve 与 spawnSync 同形的结果
160
+ * ({ status, signal, stdout, stderr, error? },stdout/stderr 恒为 utf8 字符串)。
161
+ * 子进程运行期间事件循环不被阻塞——健康探活/聊天流/插件页照常响应。
162
+ * spawn 同步抛错或 child 'error' 事件都不 reject:与 spawnSync 一样返回
163
+ * status: null + error,调用方统一按 status !== 0 判失败,错误文案不变。
164
+ * options.timeout(若传入)与 spawnSync 等价:到点 kill 子进程,返回 ETIMEDOUT;
165
+ * 现有调用点都不传 timeout,不引入新行为。 */
166
+ function spawnCapture(command, args, options = {}) {
167
+ const { timeout, killSignal = 'SIGTERM', encoding, ...spawnOptions } = options
168
+ return new Promise((resolve) => {
169
+ let stdout = ''
170
+ let stderr = ''
171
+ let settled = false
172
+ let timedOut = false
173
+ let timer = null
174
+ let child = null
175
+ const finish = (result) => {
176
+ if (settled) return
177
+ settled = true
178
+ if (timer) clearTimeout(timer)
179
+ resolve(result)
180
+ }
181
+ try {
182
+ child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'], windowsHide: true, ...spawnOptions })
183
+ } catch (error) {
184
+ /* 先构造结果再 finish:finish 会立刻 resolve Promise,后赋值就丢了。 */
185
+ finish({ status: null, signal: null, stdout, stderr, error })
186
+ return
187
+ }
188
+ child.stdout?.setEncoding('utf8')
189
+ child.stderr?.setEncoding('utf8')
190
+ child.stdout?.on('data', (chunk) => { stdout += chunk })
191
+ child.stderr?.on('data', (chunk) => { stderr += chunk })
192
+ child.on('error', (error) => {
193
+ finish({ status: null, signal: null, stdout, stderr, error })
194
+ })
195
+ /* 'close' 在 stdio 流结束后才触发,此时 stdout/stderr 已收集完整。 */
196
+ child.on('close', (code, signal) => {
197
+ if (timedOut) {
198
+ const error = Object.assign(new Error(`spawn ${command} ETIMEDOUT`), { code: 'ETIMEDOUT' })
199
+ finish({ status: null, signal: signal || killSignal, stdout, stderr, error })
200
+ return
201
+ }
202
+ finish({ status: code, signal, stdout, stderr })
203
+ })
204
+ if (typeof timeout === 'number' && timeout > 0) {
205
+ timer = setTimeout(() => {
206
+ timedOut = true
207
+ try { child.kill(killSignal) } catch { /* 已经退出 */ }
208
+ }, timeout)
209
+ }
210
+ })
211
+ }
212
+
213
+ /** 异步 npm 直调:返回 Promise,结果与 spawnSync 同形(status/stdout/stderr/error)。 */
214
+ export async function rawNpmRun(args, options = {}) {
143
215
  if (fs.existsSync(NPM_CLI)) {
144
- return spawnSync(process.execPath, [NPM_CLI, ...args], { encoding: 'utf8', stdio: 'pipe', ...options })
216
+ return spawnCapture(process.execPath, [NPM_CLI, ...args], options)
145
217
  }
146
- return spawnSync('npm', args, { encoding: 'utf8', stdio: 'pipe', shell: process.platform === 'win32', ...options })
218
+ return spawnCapture('npm', args, { shell: process.platform === 'win32', ...options })
147
219
  }
148
220
 
149
221
  function createNpmContext() {
150
- /** npm view 结果缓存:同一次运行里同一 specifier 只查一次。 */
222
+ /** npm view 结果缓存:同一次运行里同一 specifier 只查一次。
223
+ * 缓存的是 Promise:并发调用共享同一次查询,语义与同步版一致。 */
151
224
  const viewCache = new Map()
152
225
  const npmView = (spec, field) => {
153
226
  const key = `${spec}|${field}`
154
227
  if (!viewCache.has(key)) viewCache.set(key, rawNpmRun(['view', spec, field]))
155
228
  return viewCache.get(key)
156
229
  }
157
- const alreadyPublished = (name, version) => {
158
- const r = npmView(`${name}@${version}`, 'version')
230
+ const alreadyPublished = async (name, version) => {
231
+ const r = await npmView(`${name}@${version}`, 'version')
159
232
  if (r.status !== 0) return false
160
233
  return String(r.stdout).trim() === version
161
234
  }
162
235
  /** registry 上已发布 tarball 的 sha1(拿不到返回 null,网络闪断降级为警告)。 */
163
- const npmShasumOf = (name, version) => {
164
- const r = npmView(`${name}@${version}`, 'dist.shasum')
236
+ const npmShasumOf = async (name, version) => {
237
+ const r = await npmView(`${name}@${version}`, 'dist.shasum')
165
238
  if (r.status !== 0) return null
166
239
  return String(r.stdout).trim() || null
167
240
  }
168
241
  /** 本地 npm pack 产物的 sha1(npm pack 确定性:同内容同哈希)。结果按目录缓存。 */
169
242
  const localShasumCache = new Map()
170
- const localShasumOf = (dir) => {
243
+ const localShasumOf = async (dir) => {
171
244
  if (localShasumCache.has(dir)) return localShasumCache.get(dir)
172
245
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-sha-'))
173
246
  try {
174
- const pack = rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
247
+ const pack = await rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
175
248
  if (pack.status !== 0) return null
176
249
  const tgz = path.join(tmp, String(pack.stdout).trim().split(/\r?\n/).pop())
177
250
  const sha = crypto.createHash('sha1').update(fs.readFileSync(tgz)).digest('hex')
@@ -185,10 +258,18 @@ function createNpmContext() {
185
258
  }
186
259
 
187
260
  /** 发布顺序闸:待发包的 @capyclaw 依赖闭包,每一项必须 registry 可解析或在同批发布。
188
- * 拦截「只发 suite 不发依赖」这类顺序手滑(发布成功 ≠ 用户能装上)。 */
189
- export function orderGate(pkg, localMap, batch, npm) {
261
+ * 拦截「只发 suite 不发依赖」这类顺序手滑(发布成功 ≠ 用户能装上)。
262
+ *
263
+ * 自包含例外:列在 bundledDependencies 里的依赖**已经实体在 tarball 内**,
264
+ * 安装时 npm/pnpm 用包内副本、根本不会去 registry 解析。这类依赖不该被本闸拦下
265
+ * ——否则「全自包含」的包反而会因为成员尚未上架而发不出去。 */
266
+ export async function orderGate(pkg, localMap, batch, npm) {
190
267
  const errors = []
191
268
  const warnings = []
269
+ const bundled = new Set([
270
+ ...(Array.isArray(pkg.bundledDependencies) ? pkg.bundledDependencies : []),
271
+ ...(Array.isArray(pkg.bundleDependencies) ? pkg.bundleDependencies : []),
272
+ ])
192
273
  const seen = new Set([pkg.name])
193
274
  const queue = [pkg]
194
275
  while (queue.length) {
@@ -199,7 +280,9 @@ export function orderGate(pkg, localMap, batch, npm) {
199
280
  seen.add(name)
200
281
  const local = localMap.get(name)
201
282
  if (local) queue.push(local.pkg) /* 闭包继续沿本仓包展开 */
202
- const resolvable = npm.npmView(`${name}@${range}`, 'version')
283
+ /* 已随包携带:安装侧不查 registry,无需顺序约束。 */
284
+ if (bundled.has(name)) continue
285
+ const resolvable = await npm.npmView(`${name}@${range}`, 'version')
203
286
  if (resolvable.status === 0) continue /* ① registry 已可解析 */
204
287
  if (batch.has(name)) {
205
288
  warnings.push(`${name}@${range} registry 暂不可解析,依赖同批发布(确认批次包含它)`)
@@ -247,7 +330,7 @@ export function scanDirForSecrets(root) {
247
330
  /** 轻量 pack 闸:① npm pack --dry-run 断言分发必需文件真的会进包;
248
331
  * ② 真实 pack + 解包 + 逐文件扫密钥/本机信息(凭据绝不上 npm)。
249
332
  * (顶替原 verify-publishable 的核心断言;干净目录安装级检查不在这里重复。) */
250
- export function packGateErrors(pkg, dir, npm) {
333
+ export async function packGateErrors(pkg, dir, npm) {
251
334
  const mustHave = ['package.json']
252
335
  if (pkg.main) mustHave.push(String(pkg.main).replace(/^\.\//, ''))
253
336
  const patch = pkg.dsh?.bundle?.patch
@@ -256,7 +339,7 @@ export function packGateErrors(pkg, dir, npm) {
256
339
  }
257
340
  if (pkg.dsh?.client) mustHave.push('client/client.js')
258
341
  if (pkg.dsh?.suite) mustHave.push(String(pkg.dsh.suite).replace(/^\.\//, ''))
259
- const r = npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
342
+ const r = await npm.rawNpmRun(['pack', '--dry-run', '--json'], { cwd: dir })
260
343
  if (r.status !== 0) return [`npm pack --dry-run 失败: ${String(r.stderr || r.stdout || '').trim().slice(0, 200)}`]
261
344
  let packed = []
262
345
  try {
@@ -270,10 +353,10 @@ export function packGateErrors(pkg, dir, npm) {
270
353
  /* 真实 pack + 解包 + 密钥扫描:发布产物里不该有任何凭据/本机信息。 */
271
354
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-scan-'))
272
355
  try {
273
- const pack = npm.rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
356
+ const pack = await npm.rawNpmRun(['pack', '--pack-destination', tmp], { cwd: dir })
274
357
  if (pack.status !== 0) return [...errors, 'npm pack 失败(无法做密钥扫描)']
275
358
  const tgz = String(pack.stdout).trim().split(/\r?\n/).pop()
276
- const extract = spawnSync('tar', ['-xzf', tgz, '-C', tmp], { cwd: tmp, encoding: 'utf8' })
359
+ const extract = await spawnCapture('tar', ['-xzf', tgz, '-C', tmp], { cwd: tmp })
277
360
  if (extract.status !== 0) return [...errors, 'tarball 解包失败(无法做密钥扫描)']
278
361
  const extracted = path.join(tmp, 'package')
279
362
  if (fs.existsSync(extracted)) {
@@ -286,18 +369,97 @@ export function packGateErrors(pkg, dir, npm) {
286
369
  }
287
370
 
288
371
  /** 发布预检:npm 凭据状态(ambient:宿主已登录或 NODE_AUTH_TOKEN)。 */
289
- export function npmWhoami() {
290
- const r = rawNpmRun(['whoami'])
372
+ export async function npmWhoami() {
373
+ const r = await rawNpmRun(['whoami'])
291
374
  if (r.status !== 0) {
292
375
  return { ok: false, hint: 'npm whoami 失败——在宿主机 npm login,或设置 NODE_AUTH_TOKEN' }
293
376
  }
294
377
  return { ok: true, user: String(r.stdout).trim() }
295
378
  }
296
379
 
380
+ /* ────────────────────────── 自包含发布目录 ────────────────────────── */
381
+
382
+ /** 真 suite = dsh.suite 清单里有「成员」(path 不是 '.' 的自条目)。
383
+ * 公共插件也带 dsh-suite.json,但只有自己的自条目,不属于这种情况。 */
384
+ function isRealSuite(dir, pkg) {
385
+ const rel = pkg.dsh?.suite
386
+ if (!rel) return false
387
+ const file = path.join(dir, String(rel))
388
+ if (!fs.existsSync(file)) return false
389
+ try {
390
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'))
391
+ return Object.values(manifest.packages || {}).some((entry) => entry?.path && entry.path !== '.' && entry.path !== './')
392
+ } catch {
393
+ return false
394
+ }
395
+ }
396
+
397
+ /** 在 dist/suites/<bridge>/package 里找同名同版本的自包含拼装产物。 */
398
+ function findAssembledSuite(root, name, version) {
399
+ const suitesDir = path.join(root, 'dist', 'suites')
400
+ if (!fs.existsSync(suitesDir)) return null
401
+ let entries = []
402
+ try { entries = fs.readdirSync(suitesDir, { withFileTypes: true }) } catch { return null }
403
+ for (const entry of entries) {
404
+ if (!entry.isDirectory()) continue
405
+ const candidate = path.join(suitesDir, entry.name, 'package')
406
+ const pkgFile = path.join(candidate, 'package.json')
407
+ if (!fs.existsSync(pkgFile)) continue
408
+ try {
409
+ const p = JSON.parse(fs.readFileSync(pkgFile, 'utf8'))
410
+ if (p.name === name && p.version === version) return candidate
411
+ } catch { /* 坏包跳过 */ }
412
+ }
413
+ return null
414
+ }
415
+
416
+ /**
417
+ * 解析「真正要发布的那份内容」。
418
+ *
419
+ * 为什么不能直接发源码树:`npm publish` 会剥离 node_modules,只有
420
+ * package.json 的 bundledDependencies 列出的依赖才进 tarball。源码树里既没有
421
+ * node_modules,也没有 bundledDependencies,发出去的必然是瘦包——用户安装时
422
+ * 还得回 registry 逐个解析依赖(2.4.x 时代的实际行为)。
423
+ *
424
+ * 两类包分别处理:
425
+ * - 真 suite:改用 C 段拼装产物(dsh-suite.json 已改写成 ./node_modules/…,
426
+ * 成员与闭包都在包内,bundledDependencies 已写好)。找不到就报错,不静默降级。
427
+ * - 其它包:临时 staging(按 files 白名单)+ 实体化依赖闭包 + 写 bundledDependencies。
428
+ *
429
+ * @returns {{publishDir:string, cleanup:()=>void, mode:string, bundled?:string[]}|{error:string}}
430
+ */
431
+ export function preparePublishDir(dir, root, pkg) {
432
+ if (isRealSuite(dir, pkg)) {
433
+ const assembled = findAssembledSuite(root, pkg.name, pkg.version)
434
+ if (!assembled) {
435
+ return {
436
+ error: `找不到自包含拼装产物:${pkg.name}@${pkg.version} 不在 dist/suites/*/package 里。`
437
+ + '先跑 npm run assemble,否则发出去的 suite 里没有成员,安装后要回 registry 拉取。',
438
+ }
439
+ }
440
+ return { publishDir: assembled, cleanup: () => {}, mode: 'assembled-suite' }
441
+ }
442
+
443
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), 'pub-selfcontained-'))
444
+ try {
445
+ stagePlugin({ srcDir: dir, destDir: staging, keepNodeModules: false })
446
+ const result = makeSelfContained({ stagingDir: staging, root })
447
+ return {
448
+ publishDir: staging,
449
+ cleanup: () => fs.rmSync(staging, { recursive: true, force: true }),
450
+ mode: 'staged-self-contained',
451
+ bundled: result.bundled,
452
+ }
453
+ } catch (error) {
454
+ fs.rmSync(staging, { recursive: true, force: true })
455
+ return { error: `自包含 staging 失败: ${error.message}` }
456
+ }
457
+ }
458
+
297
459
  /* ────────────────────────── 主流程(移植) ────────────────────────── */
298
460
 
299
461
  /** 单包发布流程(插件与库共用)。返回结果记录。 */
300
- async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dryRun, npm, log }) {
462
+ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dryRun, npm, log, root }) {
301
463
  const pkg = pkgOf(dir)
302
464
  const label = `${pkg.name}@${pkg.version}`
303
465
  if (only && pkg.name !== only) return null
@@ -318,10 +480,12 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
318
480
  }
319
481
  }
320
482
 
321
- if (npm.alreadyPublished(pkg.name, pkg.version)) {
322
- /* 同版本漂移闸:npm pack 确定性 ⇒ 本地 sha1 == registry dist.shasum 当且仅当内容一致。 */
323
- const remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
324
- const localSha = remoteSha ? npm.localShasumOf(dir) : null
483
+ if (await npm.alreadyPublished(pkg.name, pkg.version)) {
484
+ /* 同版本漂移闸:npm pack 确定性 ⇒ 本地 sha1 == registry dist.shasum 当且仅当内容一致。
485
+ * 注意这里比的是**源码树**,语义是「源码有没有偷偷改过而没 bump 版本」,
486
+ * 与下面发布时使用的自包含产物无关。 */
487
+ const remoteSha = await npm.npmShasumOf(pkg.name, pkg.version)
488
+ const localSha = remoteSha ? await npm.localShasumOf(dir) : null
325
489
  if (remoteSha && localSha && remoteSha !== localSha) {
326
490
  log(`✗ ${label} — 同版本内容漂移:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${localSha.slice(0, 8)}`)
327
491
  log(' npm 不允许同版本重发,请 bump 版本后再发布')
@@ -332,59 +496,76 @@ async function publishOne(dir, { kind, localMap, batch, only, tag, skipTests, dr
332
496
  return { label, status: 'skipped-exists' }
333
497
  }
334
498
 
335
- /* pack 闸只对「真要发布」的包跑(真实 pack + 解包扫描很重,已发布的包由漂移闸把关)。 */
336
- if (kind === 'plugin') {
337
- const packErrors = packGateErrors(pkg, dir, npm)
338
- if (packErrors.length) {
339
- log(`✗ ${label} — pack 闸未过`)
340
- for (const item of packErrors) log(` - ${item}`)
341
- return { label, status: 'pack-incomplete', detail: packErrors }
342
- }
499
+ /* 自包含产物:npm/pnpm 会剥离 node_modules,必须发布「依赖已实体化且写进
500
+ * bundledDependencies」的那一份,否则装出来是瘦包、要回 registry 拉依赖。 */
501
+ const prepared = preparePublishDir(dir, root, pkg)
502
+ if (prepared.error) {
503
+ log(`✗ ${label} — 无法准备自包含产物`)
504
+ log(` - ${prepared.error}`)
505
+ return { label, status: 'pack-incomplete', detail: [prepared.error] }
343
506
  }
344
507
 
345
- /* 发布顺序闸(发布成功 ≠ 用户能装上):依赖闭包须 registry 可解析或同批发布。 */
346
- const order = orderGate(pkg, localMap, batch, npm)
347
- if (order.errors.length) {
348
- log(`✗ ${label} — 发布顺序闸未过(发布后用户 npm install 会失败)`)
349
- for (const item of order.errors) log(` - ${item}`)
350
- return { label, status: 'order-blocked', detail: order.errors }
351
- }
352
- for (const w of order.warnings) log(`! ${label} — ${w}`)
508
+ try {
509
+ /* pack 闸只对「真要发布」的包跑(真实 pack + 解包扫描很重,已发布的包由漂移闸把关)。
510
+ * 校验对象是自包含产物——那才是真正上 registry 的内容。 */
511
+ if (kind === 'plugin') {
512
+ const packErrors = await packGateErrors(pkg, prepared.publishDir, npm)
513
+ if (packErrors.length) {
514
+ log(`✗ ${label} — pack 闸未过`)
515
+ for (const item of packErrors) log(` - ${item}`)
516
+ return { label, status: 'pack-incomplete', detail: packErrors }
517
+ }
518
+ }
353
519
 
354
- if (!skipTests && pkg.scripts?.test) {
355
- const t = npm.rawNpmRun(['test'], { cwd: dir })
356
- if (t.status !== 0) {
357
- log(`✗ ${label} — npm test 失败,跳过发布`)
358
- return { label, status: 'test-failed', detail: (t.stdout || '') + (t.stderr || '') }
520
+ /* 发布顺序闸(发布成功 ≠ 用户能装上):依赖闭包须 registry 可解析或同批发布。
521
+ * 用**自包含产物**的清单判定:bundledDependencies 在源码树里没有,
522
+ * 只有 staging/拼装产物里才有,拿错清单会把已随包携带的依赖误判成必须上架。 */
523
+ const order = await orderGate(pkgOf(prepared.publishDir), localMap, batch, npm)
524
+ if (order.errors.length) {
525
+ log(`✗ ${label} — 发布顺序闸未过(发布后用户 npm install 会失败)`)
526
+ for (const item of order.errors) log(` - ${item}`)
527
+ return { label, status: 'order-blocked', detail: order.errors }
359
528
  }
360
- }
529
+ for (const w of order.warnings) log(`! ${label} — ${w}`)
361
530
 
362
- if (dryRun) {
363
- log(`→ ${label} — 待发布(dry run${tag !== 'latest' ? `,dist-tag=${tag}` : ''})`)
364
- return { label, status: 'would-publish' }
365
- }
531
+ if (!skipTests && pkg.scripts?.test) {
532
+ const t = await npm.rawNpmRun(['test'], { cwd: dir })
533
+ if (t.status !== 0) {
534
+ log(`✗ ${label} — npm test 失败,跳过发布`)
535
+ return { label, status: 'test-failed', detail: (t.stdout || '') + (t.stderr || '') }
536
+ }
537
+ }
366
538
 
367
- const access = pkg.publishConfig?.access || 'public'
368
- const expectedSha = npm.localShasumOf(dir)
369
- const pub = npm.rawNpmRun(['publish', '--access', access, '--tag', tag], { cwd: dir })
370
- if (pub.status !== 0) {
371
- log(`✗ ${label} — npm publish 失败`)
372
- log(String(pub.stderr || pub.stdout || '').trim().slice(0, 500))
373
- return { label, status: 'publish-failed', detail: (pub.stdout || '') + (pub.stderr || '') }
374
- }
375
- /* 发布后复核:registry 收到的 tarball 必须与本地 pack 逐字节一致(shasum)。 */
376
- let remoteSha = null
377
- for (let i = 0; i < 5 && !remoteSha; i++) {
378
- if (i) Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 3000)
379
- remoteSha = npm.npmShasumOf(pkg.name, pkg.version)
380
- }
381
- if (remoteSha && expectedSha && remoteSha !== expectedSha) {
382
- log(`✗ ${label} — 发布后复核失败:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${expectedSha.slice(0, 8)}(registry 可能收到脏产物,bump 后重发)`)
383
- return { label, status: 'publish-corrupted', detail: `shasum ${remoteSha} != ${expectedSha}` }
539
+ if (dryRun) {
540
+ log(`→ ${label} — 待发布(dry run,自包含产物=${prepared.mode}${prepared.bundled ? `,内置 ${prepared.bundled.length} 个依赖` : ''}${tag !== 'latest' ? `,dist-tag=${tag}` : ''})`)
541
+ return { label, status: 'would-publish' }
542
+ }
543
+
544
+ const access = pkg.publishConfig?.access || 'public'
545
+ const expectedSha = await npm.localShasumOf(prepared.publishDir)
546
+ const pub = await npm.rawNpmRun(['publish', '--access', access, '--tag', tag], { cwd: prepared.publishDir })
547
+ if (pub.status !== 0) {
548
+ log(`✗ ${label} — npm publish 失败`)
549
+ log(String(pub.stderr || pub.stdout || '').trim().slice(0, 500))
550
+ return { label, status: 'publish-failed', detail: (pub.stdout || '') + (pub.stderr || '') }
551
+ }
552
+ /* 发布后复核:registry 收到的 tarball 必须与本地 pack 逐字节一致(shasum)。 */
553
+ let remoteSha = null
554
+ for (let i = 0; i < 5 && !remoteSha; i++) {
555
+ /* publishOne 是 async:用 await 睡,别用 Atomics.wait 同步钉住宿主事件循环。 */
556
+ if (i) await new Promise((resolve) => { setTimeout(resolve, 3000) })
557
+ remoteSha = await npm.npmShasumOf(pkg.name, pkg.version)
558
+ }
559
+ if (remoteSha && expectedSha && remoteSha !== expectedSha) {
560
+ log(`✗ ${label} — 发布后复核失败:registry ${remoteSha.slice(0, 8)} ≠ 本地 ${expectedSha.slice(0, 8)}(registry 可能收到脏产物,bump 后重发)`)
561
+ return { label, status: 'publish-corrupted', detail: `shasum ${remoteSha} != ${expectedSha}` }
562
+ }
563
+ if (!remoteSha) log(`! ${label} — 发布后复核降级:registry shasum 暂不可见(副本延迟),请稍后人工核对`)
564
+ log(`✓ ${label} — 已发布(自包含产物=${prepared.mode}${tag !== 'latest' ? `,dist-tag=${tag}` : ''})`)
565
+ return { label, status: 'published' }
566
+ } finally {
567
+ prepared.cleanup()
384
568
  }
385
- if (!remoteSha) log(`! ${label} — 发布后复核降级:registry shasum 暂不可见(副本延迟),请稍后人工核对`)
386
- log(`✓ ${label} — 已发布${tag !== 'latest' ? `(dist-tag=${tag})` : ''}`)
387
- return { label, status: 'published' }
388
569
  }
389
570
 
390
571
  /** 解析工作区 root:参数 → DSH_PUBLISHER_ROOT。 */
@@ -430,15 +611,16 @@ export async function runPublish(options = {}) {
430
611
  const pkg = pkgOf(dir)
431
612
  localMap.set(pkg.name, { pkg, dir })
432
613
  }
433
- const batch = new Set(
434
- [...usableLibDirs, ...pluginDirs]
435
- .map((dir) => pkgOf(dir))
436
- .filter((pkg) => !only || pkg.name === only)
437
- .filter((pkg) => !npm.alreadyPublished(pkg.name, pkg.version))
438
- .map((pkg) => pkg.name),
439
- )
614
+ /* alreadyPublished 是异步的:filter 回调里不能 await,改逐包顺序判定
615
+ * (npm view 缓存保证同一 specifier 只查一次,语义与原 filter 链一致)。 */
616
+ const batch = new Set()
617
+ for (const dir of [...usableLibDirs, ...pluginDirs]) {
618
+ const pkg = pkgOf(dir)
619
+ if (only && pkg.name !== only) continue
620
+ if (!(await npm.alreadyPublished(pkg.name, pkg.version))) batch.add(pkg.name)
621
+ }
440
622
 
441
- const shared = { localMap, batch, only, tag, skipTests, dryRun, npm, log }
623
+ const shared = { localMap, batch, only, tag, skipTests, dryRun, npm, log, root }
442
624
  // 先库后插件:plugin-kit 等支撑库必须先上 registry,插件发布时依赖才可解析
443
625
  for (const dir of usableLibDirs) results.push(await publishOne(dir, { kind: 'lib', ...shared }))
444
626
  for (const dir of pluginDirs) results.push(await publishOne(dir, { kind: 'plugin', ...shared }))