dsh-devdock-npm 0.0.0-stage → 3.0.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/client.js ADDED
@@ -0,0 +1,1848 @@
1
+ /**
2
+ * DevDock · npm · 浏览器半边。
3
+ *
4
+ * 三段界面(设置页那一块、左栏包浏览、工作区项目标签页)都在这里,共用
5
+ * 组件与样式来自内核:`require('dsh-devdock-core/client')`。
6
+ *
7
+ * ## 路由前缀
8
+ *
9
+ * 内核把平台路由挂在 `/api/push/<平台 id>` 之下,所以本包声明的
10
+ * `route.path = '/packages'` 实际是 `/api/push/npm/packages`。
11
+ * 客户端因此用 `core.API + '/npm'` 作为 API 前缀,再拼自己的 `/packages`
12
+ * 之类**子路径**——子路径里绝不能再写一次 `/npm`,否则会得到
13
+ * `/api/push/npm/npm/packages`。
14
+ *
15
+ * ## 审查是可选能力,不是依赖
16
+ *
17
+ * 发布前审查已经独立成 `dsh-devdock-review`。本包**不 require 它**:直接
18
+ * require 会让「只装 npm」直接报错,而不是「少一个功能」。改为用内核的
19
+ * 能力表 `core.useCapability('review')` 探测——查到就渲染可用的入口(打开
20
+ * `review.NpmDialog`),查不到就渲染 `core.FeatureMissing` 灰色入口并
21
+ * 提示去装 `dsh-devdock-review`。
22
+ */
23
+ window.__ModuleLoader__.load({
24
+ // Must equal package.json `name`: the loader keys client modules by package
25
+ // name, so a mismatch registers the module under an id nobody resolves and
26
+ // every surface vanishes while the Host half still reports active.
27
+ id: 'dsh-devdock-npm',
28
+ factory: (require) => {
29
+ 'use strict';
30
+ const module = { exports: {} };
31
+ const exports = module.exports;
32
+
33
+ const core = require('dsh-devdock-core/client');
34
+ const { h, React, Icon, Btn, Modal, Segmented, t, api, copyText, relativeTime } = core;
35
+ const { useState, useEffect, useRef, useCallback } = React;
36
+
37
+ /** 本平台的路由前缀:内核前缀 + 平台 id。子路径不再重复 `/npm`。 */
38
+ const API = core.API + '/npm';
39
+ /** 内联提示的存活时间(内核统一)。 */
40
+ const TOAST_MS = core.TOAST_MS;
41
+ const NpmMark = core.NpmMark;
42
+ const readViewPref = core.readViewPref;
43
+ const writeViewPref = core.writeViewPref;
44
+
45
+ /* ────────────────────────────── 文案 ────────────────────────────────── */
46
+
47
+ /**
48
+ * npm 的全部措辞(92 条)。由 scripts 从元包抽取后固化在这里——逐条
49
+ * 重写是纯粹的浪费,而键名与措辞都已被元包的测试覆盖。
50
+ *
51
+ * 注意:这里只登记自己的键,通用键(取消/确认/加载中…)仍由内核提供;
52
+ * 列表/卡片、目录条这类三处界面共用的措辞也放在这里,因为内核不认识
53
+ * npm 的界面。
54
+ */
55
+ const ZH = {
56
+ npmReadOnly: '账号与包',
57
+ npmTokenPlaceholder: '粘贴 npm Granular Access Token',
58
+ npmAdd: '添加账号',
59
+ npmCurrent: '当前',
60
+ npmSwitch: '切换',
61
+ npmRemove: '移除',
62
+ npmNoPackages: '还没有读取到包(令牌需要是 read-only 或 read-write)',
63
+ npmVersionCount: '共 {n} 个版本',
64
+ npmLatest: 'latest',
65
+ npmDeprecated: '已废弃',
66
+ npmDepsTitle: '工作区依赖',
67
+ npmDepsSummary: '共 {total} 个 · {outdated} 个有更新',
68
+ npmDepsNoCwd: '当前没有工作区目录。',
69
+ npmDepsReading: '正在读取 package.json 并比对线上版本…',
70
+ npmDepsEmpty: '这个 package.json 里没有依赖。',
71
+ npmDepOutdated: '有更新',
72
+ npmDepCurrent: '已最新',
73
+ npmDepUnknown: '读取失败',
74
+ npmDepGroupOutdated: '可更新',
75
+ npmDepGroupCurrent: '已是最新',
76
+ npmDepGroupFailed: '读取失败',
77
+ npmFactVersions: '版本',
78
+ npmFactSize: '体积',
79
+ npmFactFiles: '文件',
80
+ npmFactLicense: '许可',
81
+ npmFactDeps: '依赖',
82
+ npmCopyInstall: '复制安装命令',
83
+ npmDepsOfLatest: '最新版依赖',
84
+ npmAccountSection: 'npm 账号',
85
+ npmNoAccountHint: '在设置里添加一个 Granular Access Token',
86
+ npmAddSave: '保存',
87
+ npmAddAccount: '添加 npm 账号',
88
+ npmTokenClassic: 'Classic 令牌',
89
+ npmTokenGranular: 'Granular 令牌',
90
+ npmSearchPlaceholder: '搜索 npm 包,回车确认',
91
+ npmSearchAction: '搜索',
92
+ npmSearchResult: '搜索「{q}」· {n} 个结果',
93
+ npmSearchEmpty: '没有找到匹配的包',
94
+ npmMineTitle: '我维护的包',
95
+ npmNeedLogin: '还没有登录 npm,可在 设置 › DevDock › npm 里添加令牌。',
96
+ npmPackagesSection: '我的包',
97
+ npmProjectTitle: '这个项目',
98
+ npmPkgName: '包名',
99
+ npmPkgVersion: '版本',
100
+ npmPreflightTitle: '发布前自检',
101
+ npmPreflightOk: '可以发布',
102
+ npmPreflightBlocked: '有阻断项',
103
+ npmInitTitle: '创建 package.json',
104
+ npmInitHint: '这个目录还没有 package.json。填个包名就能开始,之后可以继续改。',
105
+ npmInitNamePlaceholder: '包名(小写,可留空用目录名)',
106
+ npmInitAction: '创建',
107
+ npmPackTitle: '打包',
108
+ npmPackSummary: '共 {n} 个文件 · {size}',
109
+ npmPackFiles: '文件',
110
+ npmPackSize: '压缩后',
111
+ npmPackUnpacked: '解压后',
112
+ npmPackMore: '还有 {n} 个较小的文件未显示',
113
+ npmPackAction: '生成压缩包',
114
+ npmPacked: '已生成 {file}',
115
+ npmPublishHint: '发布会读取这个目录的 package.json,版本号取自其中的 version。',
116
+ npmOtpPlaceholder: '6 位验证码',
117
+ npmPublishAction: '发布到 npm',
118
+ npmPublished: '已发布 {name}@{version}',
119
+ npmAccountSwitch: 'npm 账号',
120
+ npmTabOverview: '概览',
121
+ npmTabVersions: '版本',
122
+ npmTabPublish: '发布',
123
+ npmUpdated: '更新于',
124
+ npmNoDate: '无日期',
125
+ npmNoDescription: '暂无简介',
126
+ npmNotMine: '他人包',
127
+ npmDistTags: 'dist-tags',
128
+ npmPublishTag: '发布标签',
129
+ npmPublishVersionNote: '将发布的版本:{version}(取自 package.json)',
130
+ npmPublishConfirm: '确认发布',
131
+ npmReviewTitle: '发布前审查',
132
+ npmReviewHint: '先检查即将发布的包内容,再决定是否发布。规则扫描(敏感信息)始终执行,模型审查可选。',
133
+ npmReviewOpen: '发布前审查',
134
+ npmReviewFindings: '问题',
135
+ npmReviewBlockerCount: '阻断项',
136
+ npmReviewHintShort: '发布前先检查包内容',
137
+ npmReviewSummary: '{n} 个问题({b} 个阻断)',
138
+ /* 审查插件不在场时灰色入口的说明(拆包后新增的措辞)。 */
139
+ npmReviewMissingHint: '需要安装审查插件才能做发布前审查。',
140
+ npmNoDirYet: '还没有选择目录',
141
+ npmChangeDir: '换目录',
142
+ headerPickDirBig: '选择目录',
143
+ headerClearDir: '清除',
144
+ manageOpen: '管理仓库',
145
+ repoOpen: '在浏览器打开',
146
+ viewList: '列表',
147
+ viewCard: '卡片',
148
+ viewSizeSmall: '小',
149
+ viewSizeLarge: '大',
150
+ pjViewResult: '查看结果',
151
+ };
152
+
153
+ const EN = {
154
+ npmReadOnly: 'Accounts and packages',
155
+ npmTokenPlaceholder: 'Paste an npm Granular Access Token',
156
+ npmAdd: 'Add account',
157
+ npmCurrent: 'Current',
158
+ npmSwitch: 'Switch',
159
+ npmRemove: 'Remove',
160
+ npmNoPackages: 'No packages read yet (the token needs read access)',
161
+ npmVersionCount: '{n} versions',
162
+ npmLatest: 'latest',
163
+ npmDeprecated: 'deprecated',
164
+ npmDepsTitle: 'Workspace dependencies',
165
+ npmDepsSummary: '{total} total · {outdated} with updates',
166
+ npmDepsNoCwd: 'No workspace directory.',
167
+ npmDepsReading: 'Reading package.json and checking the registry…',
168
+ npmDepsEmpty: 'This package.json declares no dependencies.',
169
+ npmDepOutdated: 'Update',
170
+ npmDepCurrent: 'Current',
171
+ npmDepUnknown: 'Failed',
172
+ npmDepGroupOutdated: 'Can update',
173
+ npmDepGroupCurrent: 'Up to date',
174
+ npmDepGroupFailed: 'Failed',
175
+ npmFactVersions: 'Versions',
176
+ npmFactSize: 'Size',
177
+ npmFactFiles: 'Files',
178
+ npmFactLicense: 'License',
179
+ npmFactDeps: 'Deps',
180
+ npmCopyInstall: 'Copy install',
181
+ npmDepsOfLatest: 'Latest dependencies',
182
+ npmAccountSection: 'npm accounts',
183
+ npmNoAccountHint: 'Add a Granular Access Token in Settings',
184
+ npmAddSave: 'Save',
185
+ npmAddAccount: 'Add npm account',
186
+ npmTokenClassic: 'Classic token',
187
+ npmTokenGranular: 'Granular token',
188
+ npmSearchPlaceholder: 'Search npm packages, Enter to run',
189
+ npmSearchAction: 'Search',
190
+ npmSearchResult: '“{q}” · {n} results',
191
+ npmSearchEmpty: 'No matching packages',
192
+ npmMineTitle: 'Packages I maintain',
193
+ npmNeedLogin: 'Not signed in to npm. Add a token in Settings › DevDock › npm.',
194
+ npmPackagesSection: 'My packages',
195
+ npmProjectTitle: 'This project',
196
+ npmPkgName: 'Name',
197
+ npmPkgVersion: 'Version',
198
+ npmPreflightTitle: 'Publish preflight',
199
+ npmPreflightOk: 'Ready to publish',
200
+ npmPreflightBlocked: 'Blocked',
201
+ npmInitTitle: 'Create package.json',
202
+ npmInitHint: 'This directory has no package.json yet. Enter a name to start.',
203
+ npmInitNamePlaceholder: 'Package name (lowercase, blank = folder name)',
204
+ npmInitAction: 'Create',
205
+ npmPackTitle: 'Pack',
206
+ npmPackSummary: '{n} files · {size}',
207
+ npmPackFiles: 'Files',
208
+ npmPackSize: 'Tarball',
209
+ npmPackUnpacked: 'Unpacked',
210
+ npmPackMore: '{n} smaller files not shown',
211
+ npmPackAction: 'Build tarball',
212
+ npmPacked: 'Created {file}',
213
+ npmPublishHint: "Publishing reads this directory's package.json; the version comes from its version field.",
214
+ npmOtpPlaceholder: '6-digit code',
215
+ npmPublishAction: 'Publish to npm',
216
+ npmPublished: 'Published {name}@{version}',
217
+ npmAccountSwitch: 'npm account',
218
+ npmTabOverview: 'Overview',
219
+ npmTabVersions: 'Versions',
220
+ npmTabPublish: 'Publish',
221
+ npmUpdated: 'Updated',
222
+ npmNoDate: 'No date',
223
+ npmNoDescription: 'No description',
224
+ npmNotMine: 'Not mine',
225
+ npmDistTags: 'dist-tags',
226
+ npmPublishTag: 'Publish tag',
227
+ npmPublishVersionNote: 'Version to publish: {version} (from package.json)',
228
+ npmPublishConfirm: 'Confirm publish',
229
+ npmReviewTitle: 'Pre-publish review',
230
+ npmReviewHint: 'Review what will be published before it goes out. Secret scanning always runs; model review is optional.',
231
+ npmReviewOpen: 'Pre-publish review',
232
+ npmReviewFindings: 'Findings',
233
+ npmReviewBlockerCount: 'Blockers',
234
+ npmReviewHintShort: 'Check the package before publishing',
235
+ npmReviewSummary: '{n} findings ({b} blockers)',
236
+ /* 审查插件不在场时灰色入口的说明(拆包后新增的措辞)。 */
237
+ npmReviewMissingHint: 'Install the review plugin to run a pre-publish review.',
238
+ npmNoDirYet: 'No folder selected',
239
+ npmChangeDir: 'Change',
240
+ headerPickDirBig: 'Choose folder',
241
+ headerClearDir: 'Clear',
242
+ manageOpen: 'Manage repository',
243
+ repoOpen: 'Open in browser',
244
+ viewList: 'List',
245
+ viewCard: 'Cards',
246
+ viewSizeSmall: 'Small',
247
+ viewSizeLarge: 'Large',
248
+ pjViewResult: 'View results',
249
+ };
250
+
251
+ /* ───────────────────────── 小工具(本平台内) ───────────────────────── */
252
+
253
+ /**
254
+ * 一条「标签 : 值」的事实,用于包详情顶部。
255
+ * @param {string} label
256
+ * @param {string} value
257
+ */
258
+ function packageFact(label, value) {
259
+ return h('span', { className: 'dsh-push-npm-fact', key: label },
260
+ h('span', { className: 'dsh-push-npm-fact-label' }, label),
261
+ h('span', { className: 'dsh-push-npm-fact-value' }, value));
262
+ }
263
+
264
+ /** 字节数 → 人类可读;未知时给破折号而不是 0B。 */
265
+ function formatBytes(bytes) {
266
+ if (typeof bytes !== 'number' || !Number.isFinite(bytes) || bytes <= 0) return '—';
267
+ if (bytes < 1024) return bytes + ' B';
268
+ if (bytes < 1024 * 1024) return Math.round(bytes / 1024) + ' KB';
269
+ return (bytes / (1024 * 1024)).toFixed(1) + ' MB';
270
+ }
271
+
272
+ /** 版本行:包详情里共用。 */
273
+ function renderVersionRow(row) {
274
+ return h('div', { key: row.version, className: 'dsh-push-npm-version' },
275
+ h('span', { className: 'dsh-push-mono' }, row.version),
276
+ row.isLatest ? h('span', { className: 'dsh-push-pill' }, t('npmLatest')) : null,
277
+ row.deprecated ? h('span', { className: 'dsh-push-pill dsh-push-pill--warn' }, t('npmDeprecated')) : null,
278
+ h('span', { className: 'dsh-push-hint' }, relativeTime(row.publishedAt)));
279
+ }
280
+
281
+ /**
282
+ * 列表 / 卡片切换 + 卡片尺寸。
283
+ *
284
+ * 内核不提供这个控件(它不认识「仓库卡片」这种概念),所以平台自己做;
285
+ * 但它只组合内核的 Segmented,没有自己的样式表。
286
+ */
287
+ function ViewSwitch(props) {
288
+ return h('div', { className: 'dsh-push-viewswitch' },
289
+ h(Segmented, {
290
+ value: props.mode,
291
+ onChange: props.onMode,
292
+ options: [
293
+ { value: 'list', label: t('viewList') },
294
+ { value: 'card', label: t('viewCard') },
295
+ ],
296
+ }),
297
+ props.mode === 'card'
298
+ ? h(Segmented, {
299
+ value: props.size,
300
+ onChange: props.onSize,
301
+ options: [
302
+ { value: 'small', label: t('viewSizeSmall') },
303
+ { value: 'large', label: t('viewSizeLarge') },
304
+ ],
305
+ })
306
+ : null);
307
+ }
308
+
309
+ /* ───────────────────────── 目录条(三处共用) ───────────────────────── */
310
+
311
+ /**
312
+ * 目录条:显示当前目录,或提示选一个。
313
+ *
314
+ * 发布与打包都依赖一个真实目录,但三处 npm 面板拿不到它的方式不同
315
+ * (侧栏没有 scope、设置页没有 scope、工作区标签页有 scope)。
316
+ * 这里统一成一个控件:有 dir 时显示路径,没有时给「选择目录」。
317
+ *
318
+ * @param {{ctx: object, dir: string, onPick: () => void, onClear?: () => void,
319
+ * compact?: boolean}} props
320
+ */
321
+ function NpmDirBar(props) {
322
+ const dir = props.dir || '';
323
+ return h('div', { className: 'dsh-push-npm-dirbar' + (props.compact ? ' dsh-push-npm-dirbar--compact' : '') },
324
+ h(Icon, { name: 'branch', size: 12 }),
325
+ dir === ''
326
+ ? h('span', { className: 'dsh-push-npm-dirbar-empty' }, t('npmNoDirYet'))
327
+ : h('span', { className: 'dsh-push-npm-dirbar-path', title: dir }, dir),
328
+ h('span', { className: 'dsh-push-page-spacer' }),
329
+ h(Btn, { mini: true, onClick: props.onPick },
330
+ dir === '' ? t('headerPickDirBig') : t('npmChangeDir')),
331
+ dir !== '' && typeof props.onClear === 'function'
332
+ ? h(Btn, { mini: true, onClick: props.onClear }, t('headerClearDir'))
333
+ : null);
334
+ }
335
+
336
+ /**
337
+ * 读取并持久化 npm 面板使用的目录。
338
+ *
339
+ * 工作区标签页有 scope 时以 scope 为准(它跟随当前会话),否则用用户
340
+ * 在本面板里选过的值。这样三处行为一致,又不会互相打架。
341
+ *
342
+ * @param {object} ctx
343
+ * @param {string} scopeDir 来自 props.scope 的目录,可能为空
344
+ * @returns {{dir: string, pick: () => Promise<void>, clear: () => void}}
345
+ */
346
+ function useNpmDir(ctx, scopeDir) {
347
+ const [own, setOwn] = useState(() => readViewPref('npmDir', ''));
348
+ const dir = scopeDir && scopeDir !== '' ? scopeDir : own;
349
+
350
+ const pick = async () => {
351
+ let chosen = null;
352
+ try {
353
+ const workspace = typeof ctx.get === 'function' ? ctx.get('uiWorkspace') : null;
354
+ if (workspace && typeof workspace.pickDirectory === 'function') {
355
+ chosen = await workspace.pickDirectory();
356
+ }
357
+ } catch { /* 用户取消或服务不可用 */ }
358
+ if (typeof chosen === 'string' && chosen !== '') {
359
+ setOwn(chosen);
360
+ writeViewPref('npmDir', chosen);
361
+ }
362
+ };
363
+
364
+ const clear = () => {
365
+ setOwn('');
366
+ writeViewPref('npmDir', '');
367
+ };
368
+
369
+ return { dir, pick, clear };
370
+ }
371
+
372
+ /* ───────────────────────── 审查入口(能力探测) ───────────────────────── */
373
+
374
+ /**
375
+ * 发布前审查入口。
376
+ *
377
+ * **这是本包与审查插件之间唯一的耦合点,而且是单向探测**:审查插件在
378
+ * apply 时用 `core.registerCapability('review', { NpmDialog, ... })` 登记,
379
+ * 这里用 `useCapability` 查。查到就渲染真正的按钮(点开 NpmDialog),
380
+ * 查不到就渲染内核提供的灰色入口并提示去装。
381
+ *
382
+ * 为什么不直接 require:那会让「只装 npm」在 require 处直接报错,
383
+ * 也就是把可选功能变成硬依赖。
384
+ *
385
+ * @param {{ctx: object, cwd: string, onReviewed?: (data: object) => void,
386
+ * label?: string, disabled?: boolean}} props
387
+ */
388
+ function NpmReviewEntry(props) {
389
+ const review = core.useCapability('review');
390
+ const [open, setOpen] = useState(false);
391
+ const Dialog = review && typeof review.NpmDialog === 'function' ? review.NpmDialog : null;
392
+
393
+ if (!Dialog) {
394
+ return h(core.FeatureMissing, {
395
+ label: t('npmReviewTitle'),
396
+ hint: t('npmReviewMissingHint'),
397
+ packageName: 'dsh-devdock-review',
398
+ });
399
+ }
400
+
401
+ return h('span', { className: 'dsh-push-inline' },
402
+ h(Btn, {
403
+ mini: true,
404
+ disabled: Boolean(props.disabled),
405
+ onClick: () => setOpen(true),
406
+ }, props.label || t('npmReviewOpen')),
407
+ open
408
+ ? h(Dialog, {
409
+ open: true,
410
+ ctx: props.ctx,
411
+ cwd: props.cwd,
412
+ onClose: () => setOpen(false),
413
+ onReviewed: (data) => {
414
+ setOpen(false);
415
+ if (typeof props.onReviewed === 'function') props.onReviewed(data);
416
+ },
417
+ })
418
+ : null);
419
+ }
420
+
421
+ /* ────────────────────── 包卡片 + 管理弹窗(列表/卡片) ────────────────── */
422
+
423
+ /**
424
+ * 一张包卡片。
425
+ *
426
+ * npm 没有 star/fork,对应的位置放版本数、体积和最近发布时间——同样
427
+ * 是「一眼能比的三个数字」。固定最小高度、描述两行截断、指标固定底部,
428
+ * 这样一排卡片永远对齐。
429
+ *
430
+ * @param {{pkg: object, size: string, onOpen: () => void, onManage: () => void}} props
431
+ */
432
+ function NpmPackageCard(props) {
433
+ const pkg = props.pkg || {};
434
+ const large = props.size === 'large';
435
+ const canInstall = typeof pkg.name === 'string' && pkg.name !== '';
436
+
437
+ return h('div', {
438
+ className: 'dsh-push-pkgcard' + (large ? ' dsh-push-pkgcard--large' : ''),
439
+ },
440
+ h('div', { className: 'dsh-push-pkgcard-head' },
441
+ h('span', { className: 'dsh-push-pkgcard-name', title: pkg.name }, pkg.name),
442
+ pkg.version
443
+ ? h('span', { className: 'dsh-push-pill dsh-push-pill--idle' }, 'v' + pkg.version)
444
+ : null),
445
+
446
+ h('div', { className: 'dsh-push-pkgcard-meta' },
447
+ h(Icon, { name: 'branch', size: 11 }),
448
+ h('span', null, pkg.date ? t('npmUpdated') + ' ' + relativeTime(pkg.date) : t('npmNoDate'))),
449
+
450
+ h('div', { className: 'dsh-push-pkgcard-desc' },
451
+ pkg.description || h('span', { className: 'dsh-push-rv-muted' }, t('npmNoDescription'))),
452
+
453
+ h('div', { className: 'dsh-push-pkgcard-metrics' },
454
+ h('span', { className: 'dsh-push-pkgcard-metric' },
455
+ h(Icon, { name: 'branch', size: 11 }),
456
+ h('span', null, pkg.versions || '—')),
457
+ pkg.license
458
+ ? h('span', { className: 'dsh-push-pkgcard-metric' }, pkg.license)
459
+ : null,
460
+ pkg.owned === false
461
+ ? h('span', { className: 'dsh-push-pkgcard-metric dsh-push-rv-muted' }, t('npmNotMine'))
462
+ : null),
463
+
464
+ h('div', { className: 'dsh-push-pkgcard-actions' },
465
+ h(Btn, { mini: true, onClick: props.onManage }, t('manageOpen')),
466
+ canInstall
467
+ ? h(Btn, {
468
+ mini: true,
469
+ onClick: () => copyText('npm i ' + pkg.name),
470
+ }, t('npmCopyInstall'))
471
+ : null));
472
+ }
473
+
474
+ /** npm 包的列表行:名字点开管理弹窗,其余部分展开详情。 */
475
+ function NpmPackageRow(props) {
476
+ const pkg = props.pkg || {};
477
+ const open = Boolean(props.expanded);
478
+ return h('div', { className: 'dsh-push-repo' },
479
+ h('div', { className: 'dsh-push-repo-head', onClick: props.onToggle },
480
+ h(Icon, { name: 'chevron', size: 12 }),
481
+ h('button', {
482
+ type: 'button',
483
+ className: 'dsh-push-repo-name dsh-push-repo-name--link',
484
+ title: pkg.name + ' — ' + t('manageOpen'),
485
+ onClick: (event) => {
486
+ if (event && typeof event.stopPropagation === 'function') event.stopPropagation();
487
+ props.onManage();
488
+ },
489
+ }, pkg.name),
490
+ pkg.version ? h('span', { className: 'dsh-push-pill' }, 'v' + pkg.version) : null,
491
+ h('span', { className: 'dsh-push-repo-meta' },
492
+ pkg.date ? relativeTime(pkg.date) : '—')),
493
+
494
+ pkg.description
495
+ ? h('div', { className: 'dsh-push-repo-desc', title: pkg.description }, pkg.description)
496
+ : null,
497
+
498
+ open
499
+ ? h('div', { className: 'dsh-push-repo-detail' },
500
+ h('div', { className: 'dsh-push-row-hint' },
501
+ t('npmFactVersions') + ': ' + (pkg.versions || '—')
502
+ + (pkg.license ? ' · ' + pkg.license : '')),
503
+
504
+ h('div', { className: 'dsh-push-npm-install' },
505
+ h('code', { className: 'dsh-push-mono' }, 'npm i ' + pkg.name),
506
+ h(Btn, { mini: true, onClick: () => copyText('npm i ' + pkg.name) },
507
+ t('npmCopyInstall'))),
508
+
509
+ h('div', { className: 'dsh-push-actions' },
510
+ h(Btn, { onClick: props.onManage }, t('manageOpen')),
511
+ pkg.links && pkg.links.npm
512
+ ? h('a', {
513
+ className: 'dsh-push-btn',
514
+ href: pkg.links.npm,
515
+ target: '_blank',
516
+ rel: 'noreferrer',
517
+ }, h(Icon, { name: 'external', size: 12 }), t('repoOpen'))
518
+ : null))
519
+ : null);
520
+ }
521
+
522
+ /**
523
+ * npm 包管理弹窗。
524
+ *
525
+ * 一个居中弹窗,顶部是包名与状态,下面分「概览 / 版本 / 发布」三页。
526
+ * 发布新版本也在这里,因为「发布」本就是「这个包」的一个动作。
527
+ *
528
+ * @param {{open: boolean, ctx: object, pkg: object, cwd?: string,
529
+ * onClose: () => void, onChanged?: () => void}} props
530
+ */
531
+ function NpmPackageModal(props) {
532
+ const ctx = props.ctx;
533
+ const pkg = props.pkg || {};
534
+ const name = typeof pkg.name === 'string' ? pkg.name : '';
535
+ // 从包列表打开时没有目录,所以这个弹窗自己解析一个:
536
+ // 有 props.cwd 用它,否则用用户在目录条里选的。
537
+ const dirState = useNpmDir(ctx, props.cwd || '');
538
+ const cwd = dirState.dir;
539
+ const open = Boolean(props.open && name !== '');
540
+
541
+ const [tab, setTab] = useState('overview');
542
+ const [detail, setDetail] = useState(null);
543
+ const [loading, setLoading] = useState(false);
544
+ const [error, setError] = useState('');
545
+ const [busy, setBusy] = useState(false);
546
+ const [notice, setNotice] = useState('');
547
+
548
+ /* 发布表单 */
549
+ const [publishTag, setPublishTag] = useState('latest');
550
+ const [publishVersion, setPublishVersion] = useState('');
551
+ const [otp, setOtp] = useState('');
552
+ const [needOtp, setNeedOtp] = useState(false);
553
+ const [publishArm, setPublishArm] = useState(false);
554
+ /* 发布前审查的结果摘要(审查本身在 dsh-devdock-review 里跑)。 */
555
+ const [reviewDone, setReviewDone] = useState(null);
556
+
557
+ const aliveRef = useRef(true);
558
+ useEffect(() => {
559
+ aliveRef.current = true;
560
+ return () => { aliveRef.current = false; };
561
+ }, []);
562
+
563
+ useEffect(() => {
564
+ if (!notice) return undefined;
565
+ const id = setTimeout(() => { if (aliveRef.current) setNotice(''); }, TOAST_MS);
566
+ return () => clearTimeout(id);
567
+ }, [notice]);
568
+
569
+ const load = useCallback(async () => {
570
+ if (name === '') return;
571
+ setLoading(true);
572
+ setError('');
573
+ try {
574
+ const data = await api(ctx, API + '/package?name=' + encodeURIComponent(name));
575
+ if (!aliveRef.current) return;
576
+ const info = data && data.pkg ? data.pkg : null;
577
+ setDetail(info);
578
+ // 发布版本默认填「下一个补丁版」,省掉一次手算。
579
+ if (info && info.latestVersion) {
580
+ const parts = String(info.latestVersion).split('.');
581
+ const patch = Number(parts[2] || 0);
582
+ if (Number.isFinite(patch)) {
583
+ setPublishVersion(parts[0] + '.' + parts[1] + '.' + (patch + 1));
584
+ }
585
+ }
586
+ } catch (err) {
587
+ if (aliveRef.current) setError(err.message);
588
+ } finally {
589
+ if (aliveRef.current) setLoading(false);
590
+ }
591
+ }, [ctx, name]);
592
+
593
+ useEffect(() => {
594
+ if (!open) return;
595
+ setTab('overview');
596
+ setDetail(null);
597
+ setError('');
598
+ setNotice('');
599
+ setPublishArm(false);
600
+ setNeedOtp(false);
601
+ setOtp('');
602
+ load();
603
+ }, [open, load]);
604
+
605
+ const publish = async () => {
606
+ setBusy(true);
607
+ setError('');
608
+ setNotice('');
609
+ try {
610
+ const data = await api(ctx, API + '/publish', {
611
+ method: 'POST',
612
+ body: { path: cwd, otp: otp.trim(), tag: publishTag.trim() },
613
+ });
614
+ if (aliveRef.current) {
615
+ setNotice(t('npmPublished', { name: data.name, version: data.version }));
616
+ setPublishArm(false);
617
+ setNeedOtp(false);
618
+ setOtp('');
619
+ }
620
+ await load();
621
+ if (typeof props.onChanged === 'function') props.onChanged();
622
+ } catch (err) {
623
+ if (err.code === 'UNAUTHORIZED') setNeedOtp(true);
624
+ if (aliveRef.current) setError(err.message);
625
+ } finally {
626
+ if (aliveRef.current) setBusy(false);
627
+ }
628
+ };
629
+
630
+ if (!open) return null;
631
+
632
+ const facts = detail
633
+ ? h('div', { className: 'dsh-push-npm-facts' },
634
+ packageFact(t('npmFactVersions'), String(detail.versionCount)),
635
+ packageFact(t('npmFactSize'), formatBytes(detail.unpackedSize)),
636
+ packageFact(t('npmFactFiles'), detail.fileCount === null ? '—' : String(detail.fileCount)),
637
+ packageFact(t('npmFactLicense'), detail.license || '—'),
638
+ packageFact(t('npmFactDeps'), String(Object.keys(detail.dependencies || {}).length)))
639
+ : null;
640
+
641
+ const overview = h('div', { className: 'dsh-push-modal-page' },
642
+ facts,
643
+ detail
644
+ ? h('div', { className: 'dsh-push-npm-install' },
645
+ h('code', { className: 'dsh-push-mono' }, 'npm i ' + detail.name + '@' + detail.latestVersion),
646
+ h(Btn, {
647
+ mini: true,
648
+ onClick: () => copyText('npm i ' + detail.name + '@' + detail.latestVersion),
649
+ }, t('npmCopyInstall')))
650
+ : null,
651
+ detail && Object.keys(detail.distTags || {}).length > 0
652
+ ? h('div', { className: 'dsh-push-field' },
653
+ h('span', { className: 'dsh-push-field-label' }, t('npmDistTags')),
654
+ h('div', { className: 'dsh-push-chips' },
655
+ Object.entries(detail.distTags).map(([tag, version]) =>
656
+ h('span', { key: tag, className: 'dsh-push-pill' }, tag + ' → ' + version))))
657
+ : null,
658
+ detail && Object.keys(detail.dependencies || {}).length > 0
659
+ ? h('div', { className: 'dsh-push-field' },
660
+ h('span', { className: 'dsh-push-field-label' }, t('npmDepsOfLatest')),
661
+ h('div', { className: 'dsh-push-npm-depnames' },
662
+ Object.entries(detail.dependencies).slice(0, 30).map(([dep, range]) =>
663
+ h('span', { key: dep, className: 'dsh-push-pill dsh-push-pill--idle' },
664
+ dep + ' ' + range))))
665
+ : null,
666
+ detail && detail.repository
667
+ ? h('div', { className: 'dsh-push-row-hint' }, detail.repository)
668
+ : null);
669
+
670
+ const versions = h('div', { className: 'dsh-push-modal-page' },
671
+ detail
672
+ ? h('div', null,
673
+ h('div', { className: 'dsh-push-row-hint' },
674
+ t('npmVersionCount', { n: detail.versionCount })),
675
+ h('div', { className: 'dsh-push-npm-versions' },
676
+ detail.versions.map(renderVersionRow)))
677
+ : h('div', { className: 'dsh-push-hint' }, loading ? t('loading') : '—'));
678
+
679
+ /* 发布页:这是「发布版本」的入口,也是这个弹窗存在的主要理由之一。 */
680
+ const publishPage = h('div', { className: 'dsh-push-modal-page' },
681
+ /* 目录条放在最上面:没有目录时它就是「选择目录」的入口,
682
+ * 而不是让用户对着一句错误提示束手无策。 */
683
+ h(NpmDirBar, { ctx, dir: cwd, onPick: dirState.pick, onClear: dirState.clear }),
684
+ h('div', { className: 'dsh-push-hint' }, t('npmPublishHint')),
685
+
686
+ h('div', { className: 'dsh-push-field' },
687
+ h('span', { className: 'dsh-push-field-label' }, t('npmPublishTag')),
688
+ h('input', {
689
+ className: 'dsh-push-input',
690
+ type: 'text',
691
+ value: publishTag,
692
+ spellCheck: false,
693
+ style: { width: '160px' },
694
+ onChange: (e) => setPublishTag(e.target.value),
695
+ })),
696
+
697
+ needOtp
698
+ ? h('div', { className: 'dsh-push-field' },
699
+ h('span', { className: 'dsh-push-field-label' }, t('npmOtpPlaceholder')),
700
+ h('input', {
701
+ className: 'dsh-push-input',
702
+ type: 'text',
703
+ value: otp,
704
+ inputMode: 'numeric',
705
+ maxLength: 8,
706
+ style: { width: '120px' },
707
+ onChange: (e) => setOtp(e.target.value),
708
+ }))
709
+ : null,
710
+
711
+ h('div', { className: 'dsh-push-row-hint' },
712
+ t('npmPublishVersionNote', { version: publishVersion || '—' })),
713
+ /* 审查入口:能力探测版——审查插件不在场时是灰色提示,不是报错。 */
714
+ h('div', { className: 'dsh-push-inline' },
715
+ h(NpmReviewEntry, {
716
+ ctx,
717
+ cwd,
718
+ disabled: busy || !cwd,
719
+ onReviewed: (data) => setReviewDone(data),
720
+ })),
721
+
722
+ /* 摘要可点击:直接看结果,不必重新跑一次审查。 */
723
+ reviewDone
724
+ ? h('button', {
725
+ type: 'button',
726
+ className: 'dsh-push-npm-reviewsummary',
727
+ onClick: () => setTab('publish'),
728
+ },
729
+ h('div', { className: 'dsh-push-npm-facts' },
730
+ packageFact(t('npmReviewFindings'), String((reviewDone.findings || []).length)),
731
+ packageFact(t('npmReviewBlockerCount'), String((reviewDone.findings || [])
732
+ .filter((row) => row.severity === 'blocker').length))),
733
+ h('span', { className: 'dsh-push-row-hint' }, t('pjViewResult')))
734
+ : null,
735
+
736
+ /* 发布是不可逆写操作:走两步确认,和删除仓库那个模式一致。 */
737
+ publishArm
738
+ ? h('div', { className: 'dsh-push-actions' },
739
+ h(Btn, {
740
+ kind: 'danger',
741
+ disabled: busy,
742
+ onClick: publish,
743
+ }, busy ? t('loading') : t('npmPublishConfirm')),
744
+ h(Btn, { disabled: busy, onClick: () => setPublishArm(false) }, t('cancel')))
745
+ : h('div', { className: 'dsh-push-actions' },
746
+ h(Btn, {
747
+ kind: 'primary',
748
+ disabled: busy || !cwd,
749
+ onClick: () => setPublishArm(true),
750
+ }, t('npmPublishAction'))),
751
+
752
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
753
+ notice ? h('div', { className: 'dsh-push-ok' }, notice) : null);
754
+
755
+ const page = tab === 'overview' ? overview : (tab === 'versions' ? versions : publishPage);
756
+
757
+ return h(Modal, {
758
+ open,
759
+ onClose: props.onClose,
760
+ title: name,
761
+ wide: true,
762
+ footer: [
763
+ h('div', { className: 'dsh-push-modal-status', key: 'status' },
764
+ loading ? h('span', { className: 'dsh-push-row-hint' }, t('loading')) : null,
765
+ notice ? h('div', { className: 'dsh-push-ok' }, notice) : null),
766
+ h(Btn, { key: 'refresh', mini: true, onClick: load }, t('refresh')),
767
+ h(Btn, { key: 'close', onClick: props.onClose }, t('close')),
768
+ ],
769
+ },
770
+ h('div', { className: 'dsh-push-modal-tabs' },
771
+ h(Segmented, {
772
+ value: tab,
773
+ onChange: setTab,
774
+ options: [
775
+ { value: 'overview', label: t('npmTabOverview') },
776
+ { value: 'versions', label: t('npmTabVersions') },
777
+ { value: 'publish', label: t('npmTabPublish') },
778
+ ],
779
+ })),
780
+ h('div', { className: 'dsh-push-modal-body' },
781
+ error && tab !== 'publish' ? h('div', { className: 'dsh-push-error' }, error) : null,
782
+ page));
783
+ }
784
+
785
+ /* ───────────────────────── 账号卡片(仅设置页) ───────────────────────── */
786
+
787
+ /**
788
+ * npm 账号管理。
789
+ *
790
+ * 只出现在设置页:账号是「一处管理、处处使用」的东西,在侧栏和标签页
791
+ * 里再放一份同样的增删界面既重复,也容易让人误以为它们各自独立。
792
+ *
793
+ * @param {{ctx: object, onChanged?: () => void}} props
794
+ */
795
+ function NpmAccountCards(props) {
796
+ const ctx = props.ctx;
797
+ const [data, setData] = useState(null);
798
+ const [adding, setAdding] = useState(false);
799
+ const [token, setToken] = useState('');
800
+ const [busy, setBusy] = useState('');
801
+ const [error, setError] = useState('');
802
+ const aliveRef = useRef(true);
803
+
804
+ useEffect(() => {
805
+ aliveRef.current = true;
806
+ return () => { aliveRef.current = false; };
807
+ }, []);
808
+
809
+ const load = useCallback(async () => {
810
+ try {
811
+ const next = await api(ctx, API + '/accounts');
812
+ // 同一份数据也写进同步缓存,侧栏用它决定是否提示「去设置里添加」。
813
+ npmAccountCache.length = 0;
814
+ if (next && Array.isArray(next.accounts)) npmAccountCache.push(...next.accounts);
815
+ if (aliveRef.current) setData(next || { accounts: [], activeId: null });
816
+ } catch (err) {
817
+ if (aliveRef.current) setError(err.message);
818
+ }
819
+ }, [ctx]);
820
+
821
+ useEffect(() => { load(); }, [load]);
822
+
823
+ const run = async (label, action) => {
824
+ setBusy(label);
825
+ setError('');
826
+ try {
827
+ await action();
828
+ await load();
829
+ if (typeof props.onChanged === 'function') props.onChanged();
830
+ } catch (err) {
831
+ if (aliveRef.current) setError(err.message);
832
+ } finally {
833
+ if (aliveRef.current) setBusy('');
834
+ }
835
+ };
836
+
837
+ const add = () => run('add', async () => {
838
+ const value = String(token || '').trim();
839
+ if (value === '') return;
840
+ await api(ctx, API + '/account', { method: 'POST', body: { token: value } });
841
+ if (aliveRef.current) { setToken(''); setAdding(false); }
842
+ });
843
+
844
+ const list = (data && data.accounts) || [];
845
+ const activeId = data ? data.activeId : null;
846
+
847
+ const tokenField = h('input', {
848
+ className: 'dsh-push-input dsh-push-acc-token',
849
+ type: 'password',
850
+ value: token,
851
+ placeholder: t('npmTokenPlaceholder'),
852
+ spellCheck: false,
853
+ onChange: (e) => setToken(e.target.value),
854
+ });
855
+
856
+ const addPanel = h('div', { className: 'dsh-push-acc-panel' },
857
+ tokenField,
858
+ h('div', { className: 'dsh-push-inline' },
859
+ h(Btn, { kind: 'primary', disabled: busy === 'add' || token.trim() === '', onClick: add },
860
+ t('npmAddSave')),
861
+ h(Btn, { disabled: Boolean(busy), onClick: () => { setAdding(false); setToken(''); } },
862
+ t('cancel'))));
863
+
864
+ const addRow = h('button', {
865
+ type: 'button',
866
+ className: 'dsh-push-acc-addrow',
867
+ onClick: () => setAdding(true),
868
+ }, h(Icon, { name: 'plus', size: 12 }), t('npmAddAccount'));
869
+
870
+ const emptyCard = h('button', {
871
+ type: 'button',
872
+ className: 'dsh-push-acc-card dsh-push-acc-card--empty',
873
+ onClick: () => setAdding(true),
874
+ },
875
+ h(NpmMark, { size: 20 }),
876
+ h('span', { className: 'dsh-push-acc-card-empty' }, t('npmAdd')),
877
+ h('span', { className: 'dsh-push-acc-card-hint' }, t('npmNoAccountHint')));
878
+
879
+ const accountCard = (account) => h('div', {
880
+ key: account.id,
881
+ className: 'dsh-push-acc-card',
882
+ },
883
+ h(NpmMark, { size: 22 }),
884
+ h('div', { className: 'dsh-push-acc-card-main' },
885
+ h('div', { className: 'dsh-push-acc-card-name' }, account.login),
886
+ h('div', { className: 'dsh-push-acc-card-sub' },
887
+ h('span', { className: 'dsh-push-acc-card-login' },
888
+ account.tokenKind === 'classic' ? t('npmTokenClassic') : t('npmTokenGranular')),
889
+ account.id === activeId
890
+ ? h('span', { className: 'dsh-push-pill' }, t('npmCurrent'))
891
+ : null)),
892
+ h('div', { className: 'dsh-push-inline' },
893
+ account.id === activeId
894
+ ? null
895
+ : h(Btn, {
896
+ mini: true,
897
+ disabled: Boolean(busy),
898
+ onClick: () => run('switch', () => api(ctx, API + '/account/active', {
899
+ method: 'POST',
900
+ body: { id: account.id },
901
+ })),
902
+ }, t('npmSwitch')),
903
+ h('button', {
904
+ type: 'button',
905
+ className: 'dsh-push-iconbtn',
906
+ title: t('npmRemove'),
907
+ 'aria-label': t('npmRemove'),
908
+ disabled: Boolean(busy),
909
+ onClick: () => run('remove', () => api(ctx, API + '/account/remove', {
910
+ method: 'POST',
911
+ body: { id: account.id },
912
+ })),
913
+ }, h(Icon, { name: 'close', size: 12 }))));
914
+
915
+ /* 渲染顺序:账号卡片 → 添加表单(adding 时)。
916
+ * 关键点:adding 一旦为 true 就必须出现输入框,与「当前有几个账号」
917
+ * 无关。之前把空卡片和添加表单绑在互斥分支里,导致点了空卡片没反应。 */
918
+ const stackChildren = list.map(accountCard);
919
+ if (adding) {
920
+ stackChildren.push(addPanel);
921
+ } else if (list.length === 0) {
922
+ stackChildren.push(emptyCard);
923
+ } else {
924
+ stackChildren.push(addRow);
925
+ }
926
+
927
+ return h('div', { className: 'dsh-push-group' },
928
+ h('div', { className: 'dsh-push-group-head' },
929
+ h('span', null, t('npmAccountSection')),
930
+ h('span', { className: 'dsh-push-row-hint' }, t('npmReadOnly'))),
931
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
932
+ h('div', { className: 'dsh-push-acc-stack' }, stackChildren));
933
+ }
934
+
935
+ /**
936
+ * npm 账号选择器(面板头部用)。
937
+ *
938
+ * 显示当前账号、可以就地切换、切换后通知父级重新读取数据。没有账号时
939
+ * 不渲染空下拉,而是给一条去设置添加的提示(由调用方决定怎么显示)。
940
+ *
941
+ * @param {{ctx: object, onChange?: () => void, onError?: (m: string) => void}} props
942
+ */
943
+ function NpmAccountPicker(props) {
944
+ const ctx = props.ctx;
945
+ const [data, setData] = useState(null);
946
+ const [busy, setBusy] = useState(false);
947
+
948
+ const load = useCallback(async () => {
949
+ try {
950
+ const next = await api(ctx, API + '/accounts');
951
+ setData(next || { accounts: [], activeId: null });
952
+ npmAccountCache.length = 0;
953
+ if (next && Array.isArray(next.accounts)) npmAccountCache.push(...next.accounts);
954
+ } catch {
955
+ setData({ accounts: [], activeId: null });
956
+ }
957
+ }, [ctx]);
958
+
959
+ useEffect(() => { load(); }, [load]);
960
+
961
+ const switchTo = async (id) => {
962
+ if (!id) return;
963
+ setBusy(true);
964
+ try {
965
+ await api(ctx, API + '/account/active', { method: 'POST', body: { id } });
966
+ await load();
967
+ if (typeof props.onChange === 'function') props.onChange();
968
+ } catch (err) {
969
+ // 失败时不做乐观更新:界面停在旧账号,错误交给上层提示。
970
+ if (typeof props.onError === 'function') props.onError(err.message);
971
+ } finally {
972
+ setBusy(false);
973
+ }
974
+ };
975
+
976
+ const list = (data && data.accounts) || [];
977
+ if (list.length === 0) return null;
978
+ const activeId = data ? data.activeId : null;
979
+
980
+ return h('div', { className: 'dsh-push-npm-picker' },
981
+ h(NpmMark, { size: 14 }),
982
+ h('select', {
983
+ className: 'dsh-push-select dsh-push-npm-picker-select',
984
+ value: activeId || '',
985
+ 'aria-label': t('npmAccountSwitch'),
986
+ disabled: busy,
987
+ onChange: (e) => switchTo(e.target.value),
988
+ }, list.map((account) => h('option', {
989
+ key: account.id,
990
+ value: account.id,
991
+ }, account.login))));
992
+ }
993
+
994
+ /** 由 NpmAccountCards / NpmSearchPanel 刷新,供同步判断是否已登录。 */
995
+ const npmAccountCache = [];
996
+
997
+ /**
998
+ * npm 是否已登录(同步判断,仅用于渲染一个提示条)。
999
+ *
1000
+ * 这里的同步缓存是刻意的:侧栏在渲染时需要立刻知道「该不该提示去设置
1001
+ * 里添加账号」,而那次请求不是渲染的关键路径。真的操作仍由各面板自己
1002
+ * 发起请求。
1003
+ *
1004
+ * @returns {boolean}
1005
+ */
1006
+ function npmLoggedIn() {
1007
+ return npmAccountCache.length > 0;
1008
+ }
1009
+
1010
+ /* ───────────────────────── 设置页:账号 + 我的包 ───────────────────────── */
1011
+
1012
+ /**
1013
+ * 设置页的 npm 一页。
1014
+ *
1015
+ * 这里是唯一能增删账号的地方;包列表是这个账号名下的包。侧栏负责找包,
1016
+ * 工作区标签页负责当前项目,三者内容不重复。
1017
+ *
1018
+ * @param {{ctx: object, reloadKey?: number}} props
1019
+ */
1020
+ function NpmSection(props) {
1021
+ const ctx = props.ctx;
1022
+ const [packages, setPackages] = useState(null);
1023
+ // 与左侧栏各自记住视图偏好:设置页更宽,默认用卡片。
1024
+ const [viewMode, setViewMode] = useState(() => readViewPref('npm.section', 'card'));
1025
+ const [cardSize, setCardSize] = useState(() => readViewPref('npm.section.size', 'small'));
1026
+ const [managePkg, setManagePkg] = useState(null);
1027
+ // 设置页同样自己记一个目录;三处共用同一个偏好键。
1028
+ const dirState = useNpmDir(ctx, '');
1029
+ const [reviewDone, setReviewDone] = useState(null);
1030
+ const [busy, setBusy] = useState(false);
1031
+ const [error, setError] = useState('');
1032
+ const aliveRef = useRef(true);
1033
+
1034
+ useEffect(() => {
1035
+ aliveRef.current = true;
1036
+ return () => { aliveRef.current = false; };
1037
+ }, []);
1038
+
1039
+ const loadPackages = useCallback(async () => {
1040
+ try {
1041
+ const data = await api(ctx, API + '/packages?size=30');
1042
+ if (aliveRef.current) setPackages(data ? data.items : []);
1043
+ } catch (err) {
1044
+ if (aliveRef.current && err.code !== 'NO_ACCOUNT') setError(err.message);
1045
+ if (aliveRef.current) setPackages(null);
1046
+ }
1047
+ }, [ctx]);
1048
+
1049
+ useEffect(() => { loadPackages(); }, [loadPackages, props.reloadKey]);
1050
+
1051
+ const refresh = async () => {
1052
+ setBusy(true);
1053
+ await loadPackages();
1054
+ if (aliveRef.current) setBusy(false);
1055
+ };
1056
+
1057
+ const pkgRow = (pkg) => h('div', { key: pkg.name, className: 'dsh-push-row dsh-push-npm-pkgrow' },
1058
+ h('div', { className: 'dsh-push-row-main' },
1059
+ h('span', { className: 'dsh-push-mono' }, pkg.name),
1060
+ h('span', { className: 'dsh-push-hint' }, pkg.version ? 'v' + pkg.version : ''),
1061
+ h('span', { className: 'dsh-push-hint' }, relativeTime(pkg.date))),
1062
+ h('div', { className: 'dsh-push-inline' },
1063
+ h(Btn, { mini: true, onClick: () => copyText('npm i ' + pkg.name) },
1064
+ t('npmCopyInstall'))));
1065
+
1066
+ const rows = packages || [];
1067
+ const list = rows.length === 0
1068
+ ? h('div', { className: 'dsh-push-hint' }, t('npmNoPackages'))
1069
+ : (viewMode === 'card'
1070
+ ? h('div', {
1071
+ key: 'npm-section-cards',
1072
+ className: 'dsh-push-repocards'
1073
+ + (cardSize === 'large' ? ' dsh-push-repocards--large' : ''),
1074
+ }, rows.map((pkg) => h(NpmPackageCard, {
1075
+ key: pkg.name,
1076
+ pkg,
1077
+ size: cardSize,
1078
+ onOpen: () => setManagePkg(pkg),
1079
+ onManage: () => setManagePkg(pkg),
1080
+ })))
1081
+ : h('div', { className: 'dsh-push-rows' }, rows.map((pkg) => h(NpmPackageRow, {
1082
+ key: pkg.name,
1083
+ pkg,
1084
+ expanded: false,
1085
+ onToggle: () => setManagePkg(pkg),
1086
+ onManage: () => setManagePkg(pkg),
1087
+ }))));
1088
+
1089
+ const viewSwitch = h(ViewSwitch, {
1090
+ mode: viewMode,
1091
+ size: cardSize,
1092
+ onMode: (next) => { setViewMode(next); writeViewPref('npm.section', next); },
1093
+ onSize: (next) => { setCardSize(next); writeViewPref('npm.section.size', next); },
1094
+ });
1095
+
1096
+ return h('div', { className: 'dsh-push-npm-settings' },
1097
+ h(NpmAccountCards, { ctx, onChanged: loadPackages }),
1098
+ h('div', { className: 'dsh-push-group' },
1099
+ h('div', { className: 'dsh-push-group-head' },
1100
+ h('span', null, t('npmPackagesSection')),
1101
+ h(Btn, { mini: true, disabled: busy, onClick: refresh },
1102
+ busy ? t('loading') : t('refresh')),
1103
+ h(NpmReviewEntry, {
1104
+ ctx,
1105
+ cwd: dirState.dir,
1106
+ label: t('npmReviewOpen'),
1107
+ onReviewed: (data) => setReviewDone(data),
1108
+ })),
1109
+ viewSwitch,
1110
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1111
+ list),
1112
+ reviewDone
1113
+ ? h('div', { className: 'dsh-push-npm-facts' },
1114
+ packageFact(t('npmReviewFindings'), String((reviewDone.findings || []).length)),
1115
+ packageFact(t('npmReviewBlockerCount'), String((reviewDone.findings || [])
1116
+ .filter((row) => row.severity === 'blocker').length)))
1117
+ : null,
1118
+ h(NpmDirBar, { ctx, dir: dirState.dir, onPick: dirState.pick, onClear: dirState.clear }),
1119
+ h(NpmPackageModal, {
1120
+ open: Boolean(managePkg),
1121
+ ctx,
1122
+ pkg: managePkg,
1123
+ cwd: '',
1124
+ onClose: () => setManagePkg(null),
1125
+ onChanged: loadPackages,
1126
+ }));
1127
+ }
1128
+
1129
+ /* ───────────────────────── 左栏:找包 / 看包 ───────────────────────── */
1130
+
1131
+ /**
1132
+ * 包搜索与详情。
1133
+ *
1134
+ * 左侧栏的职责是「看和找」,不是「管」:没有账号增删,只有一个搜索框和
1135
+ * 自己的包。没登录时给一句去设置里添加的提示,而不是再复制一份登录表单。
1136
+ *
1137
+ * @param {{ctx: object, available: boolean, reloadKey?: number}} props
1138
+ */
1139
+ function NpmSearchPanel(props) {
1140
+ const ctx = props.ctx;
1141
+ const [query, setQuery] = useState('');
1142
+ const [term, setTerm] = useState('');
1143
+ const [items, setItems] = useState(null);
1144
+ const [busy, setBusy] = useState(false);
1145
+ const [error, setError] = useState('');
1146
+ const [openName, setOpenName] = useState('');
1147
+ const [detail, setDetail] = useState(null);
1148
+ // 列表 / 卡片,与设置页同样的两种密度;偏好各自独立保存。
1149
+ const [viewMode, setViewMode] = useState(() => readViewPref('npm.panel', 'list'));
1150
+ const [cardSize, setCardSize] = useState(() => readViewPref('npm.panel.size', 'small'));
1151
+ const [managePkg, setManagePkg] = useState(null);
1152
+ // 目录 + 发布前审查:侧栏没有 scope,自己记一个目录。
1153
+ const dirState = useNpmDir(ctx, '');
1154
+ const [reviewDone, setReviewDone] = useState(null);
1155
+ const aliveRef = useRef(true);
1156
+
1157
+ useEffect(() => {
1158
+ aliveRef.current = true;
1159
+ return () => { aliveRef.current = false; };
1160
+ }, []);
1161
+
1162
+ const search = useCallback(async (text) => {
1163
+ const value = String(text || '').trim();
1164
+ if (value === '') return;
1165
+ setBusy(true);
1166
+ setError('');
1167
+ setOpenName('');
1168
+ setDetail(null);
1169
+ try {
1170
+ const params = new URLSearchParams({ q: value, size: '30' });
1171
+ const data = await api(ctx, API + '/search?' + params.toString());
1172
+ if (aliveRef.current) setItems((data && data.items) || []);
1173
+ } catch (err) {
1174
+ if (aliveRef.current) { setError(err.message); setItems(null); }
1175
+ } finally {
1176
+ if (aliveRef.current) setBusy(false);
1177
+ }
1178
+ }, [ctx]);
1179
+
1180
+ /* 没输关键词时先显示「自己的包」,那是最可能的默认意图。 */
1181
+ const loadMine = useCallback(async () => {
1182
+ if (!props.available) { setItems(null); return; }
1183
+ setBusy(true);
1184
+ setError('');
1185
+ try {
1186
+ const data = await api(ctx, API + '/packages?size=30');
1187
+ if (aliveRef.current) setItems((data && data.items) || []);
1188
+ } catch (err) {
1189
+ if (aliveRef.current && err.code !== 'NO_ACCOUNT') setError(err.message);
1190
+ if (aliveRef.current) setItems(null);
1191
+ } finally {
1192
+ if (aliveRef.current) setBusy(false);
1193
+ }
1194
+ }, [ctx, props.available]);
1195
+
1196
+ useEffect(() => { loadMine(); }, [loadMine, props.reloadKey]);
1197
+
1198
+ const open = async (name) => {
1199
+ if (openName === name) { setOpenName(''); setDetail(null); return; }
1200
+ setOpenName(name);
1201
+ setDetail(null);
1202
+ try {
1203
+ const data = await api(ctx, API + '/package?name=' + encodeURIComponent(name));
1204
+ if (aliveRef.current) setDetail(data && data.pkg ? data.pkg : null);
1205
+ } catch (err) {
1206
+ if (aliveRef.current) setError(err.message);
1207
+ }
1208
+ };
1209
+
1210
+ const detailBlock = () => h('div', { className: 'dsh-push-npm-detail' },
1211
+ h('div', { className: 'dsh-push-npm-facts' },
1212
+ packageFact(t('npmFactVersions'), String(detail.versionCount)),
1213
+ packageFact(t('npmFactSize'), formatBytes(detail.unpackedSize)),
1214
+ packageFact(t('npmFactLicense'), detail.license || '—'),
1215
+ packageFact(t('npmFactDeps'), String(Object.keys(detail.dependencies || {}).length))),
1216
+ h('div', { className: 'dsh-push-npm-install' },
1217
+ h('code', { className: 'dsh-push-mono' }, 'npm i ' + detail.name + '@' + detail.latestVersion),
1218
+ h(Btn, {
1219
+ mini: true,
1220
+ onClick: () => copyText('npm i ' + detail.name + '@' + detail.latestVersion),
1221
+ }, t('npmCopyInstall'))),
1222
+ detail.versions.slice(0, 8).map(renderVersionRow));
1223
+
1224
+ const row = (pkg) => h('div', { key: pkg.name, className: 'dsh-push-row' },
1225
+ h('div', {
1226
+ className: 'dsh-push-row-main dsh-push-npm-browse-main',
1227
+ onClick: () => open(pkg.name),
1228
+ },
1229
+ h('span', { className: 'dsh-push-mono' }, pkg.name),
1230
+ h('span', { className: 'dsh-push-hint' }, pkg.version ? 'v' + pkg.version : ''),
1231
+ pkg.date ? h('span', { className: 'dsh-push-hint' }, relativeTime(pkg.date)) : null),
1232
+ pkg.description
1233
+ ? h('div', { className: 'dsh-push-row-hint dsh-push-npm-browse-desc' }, pkg.description)
1234
+ : null,
1235
+ openName === pkg.name && detail ? detailBlock() : null);
1236
+
1237
+ const searchRow = h('div', { className: 'dsh-push-search dsh-push-search--compact dsh-push-npm-searchrow' },
1238
+ h(Icon, { name: 'search', size: 13 }),
1239
+ h('input', {
1240
+ type: 'text',
1241
+ value: query,
1242
+ placeholder: t('npmSearchPlaceholder'),
1243
+ onChange: (e) => setQuery(e.target.value),
1244
+ onKeyDown: (e) => {
1245
+ if (e.key !== 'Enter') return;
1246
+ setTerm(query.trim());
1247
+ search(query);
1248
+ },
1249
+ }),
1250
+ query.trim() === ''
1251
+ ? null
1252
+ : h('button', {
1253
+ type: 'button',
1254
+ className: 'dsh-push-iconbtn',
1255
+ title: t('npmSearchAction'),
1256
+ onClick: () => { setTerm(query.trim()); search(query); },
1257
+ }, h(Icon, { name: 'search', size: 12 })));
1258
+
1259
+ const viewSwitch = h(ViewSwitch, {
1260
+ mode: viewMode,
1261
+ size: cardSize,
1262
+ onMode: (next) => { setViewMode(next); writeViewPref('npm.panel', next); },
1263
+ onSize: (next) => { setCardSize(next); writeViewPref('npm.panel.size', next); },
1264
+ });
1265
+
1266
+ const meta = h('div', { className: 'dsh-push-row-hint dsh-push-npm-searchmeta' },
1267
+ busy
1268
+ ? t('loading')
1269
+ : (term === ''
1270
+ ? t('npmMineTitle')
1271
+ : t('npmSearchResult', { q: term, n: (items || []).length })));
1272
+
1273
+ const rows = items || [];
1274
+ const emptyHint = term === '' ? t('npmNoPackages') : t('npmSearchEmpty');
1275
+ const body = rows.length === 0
1276
+ ? (busy ? null : h('div', { className: 'dsh-push-empty' }, emptyHint))
1277
+ : (viewMode === 'card'
1278
+ ? h('div', {
1279
+ key: 'npm-cards',
1280
+ className: 'dsh-push-repocards'
1281
+ + (cardSize === 'large' ? ' dsh-push-repocards--large' : ''),
1282
+ }, rows.map((pkg) => h(NpmPackageCard, {
1283
+ key: pkg.name,
1284
+ pkg,
1285
+ size: cardSize,
1286
+ onOpen: () => setManagePkg(pkg),
1287
+ onManage: () => setManagePkg(pkg),
1288
+ })))
1289
+ : h('div', { className: 'dsh-push-rows' }, rows.map((pkg) => h(NpmPackageRow, {
1290
+ key: pkg.name,
1291
+ pkg,
1292
+ expanded: openName === pkg.name,
1293
+ onToggle: () => open(pkg.name),
1294
+ onManage: () => setManagePkg(pkg),
1295
+ }))));
1296
+
1297
+ /* 审查条:能力探测版入口 + 上一次的摘要。 */
1298
+ const reviewBar = h('div', { className: 'dsh-push-inline dsh-push-npm-reviewbar' },
1299
+ h('span', { className: 'dsh-push-row-hint' },
1300
+ reviewDone
1301
+ ? t('npmReviewSummary', {
1302
+ n: (reviewDone.findings || []).length,
1303
+ b: (reviewDone.findings || []).filter((row) => row.severity === 'blocker').length,
1304
+ })
1305
+ : t('npmReviewHintShort')),
1306
+ h('span', { className: 'dsh-push-page-spacer' }),
1307
+ h(NpmReviewEntry, {
1308
+ ctx,
1309
+ cwd: dirState.dir,
1310
+ onReviewed: (data) => setReviewDone(data),
1311
+ }));
1312
+
1313
+ return h('div', { className: 'dsh-push-npm-browse' },
1314
+ searchRow,
1315
+ // 目录条始终显示:没有目录时它是「选择目录」的入口,
1316
+ // 而不是让用户面对一个没有出口的提示。
1317
+ h(NpmDirBar, {
1318
+ ctx,
1319
+ dir: dirState.dir,
1320
+ onPick: dirState.pick,
1321
+ onClear: dirState.clear,
1322
+ compact: true,
1323
+ }),
1324
+ reviewBar,
1325
+ viewSwitch,
1326
+ props.available ? null : h('div', { className: 'dsh-push-hint' }, t('npmNeedLogin')),
1327
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1328
+ meta,
1329
+ body,
1330
+ h(NpmPackageModal, {
1331
+ open: Boolean(managePkg),
1332
+ ctx,
1333
+ pkg: managePkg,
1334
+ cwd: '',
1335
+ onClose: () => setManagePkg(null),
1336
+ onChanged: () => { if (term === '') loadMine(); else search(term); },
1337
+ }));
1338
+ }
1339
+
1340
+ /**
1341
+ * 目录里还没有 package.json 时显示的一张卡片。
1342
+ *
1343
+ * 之前这里只写「没有 package.json」,然后就没有下一步——一个空目录等于
1344
+ * 走到死路。现在直接给出创建入口:填个名字就能开始。
1345
+ *
1346
+ * @param {{ctx: object, cwd: string, onCreated: () => void}} props
1347
+ */
1348
+ function NpmInitCard(props) {
1349
+ const ctx = props.ctx;
1350
+ const [name, setName] = useState('');
1351
+ const [busy, setBusy] = useState(false);
1352
+ const [error, setError] = useState('');
1353
+
1354
+ const create = async () => {
1355
+ setBusy(true);
1356
+ setError('');
1357
+ try {
1358
+ await api(ctx, API + '/init', {
1359
+ method: 'POST',
1360
+ body: { path: props.cwd, name: name.trim() },
1361
+ });
1362
+ if (typeof props.onCreated === 'function') props.onCreated();
1363
+ } catch (err) {
1364
+ setError(err.message);
1365
+ } finally {
1366
+ setBusy(false);
1367
+ }
1368
+ };
1369
+
1370
+ return h('div', { className: 'dsh-push-group' },
1371
+ h('div', { className: 'dsh-push-group-head' },
1372
+ h('span', null, t('npmInitTitle'))),
1373
+ h('div', { className: 'dsh-push-npm-init' },
1374
+ h('div', { className: 'dsh-push-hint' }, t('npmInitHint')),
1375
+ h('div', { className: 'dsh-push-inline' },
1376
+ h('input', {
1377
+ className: 'dsh-push-input',
1378
+ type: 'text',
1379
+ value: name,
1380
+ placeholder: t('npmInitNamePlaceholder'),
1381
+ spellCheck: false,
1382
+ style: { width: '220px' },
1383
+ onChange: (e) => setName(e.target.value),
1384
+ }),
1385
+ h(Btn, { kind: 'primary', disabled: busy, onClick: create },
1386
+ busy ? t('loading') : t('npmInitAction'))),
1387
+ error ? h('div', { className: 'dsh-push-error' }, error) : null));
1388
+ }
1389
+
1390
+ /**
1391
+ * 发布到 npm。
1392
+ *
1393
+ * 需要 2FA 的账号在第一次发布时会拿到 EOTP;那时把验证码输入框摆出来,
1394
+ * 而不是让用户对着一个红字错误自己猜。
1395
+ *
1396
+ * @param {{ctx: object, cwd: string}} props
1397
+ */
1398
+ function NpmPublishRow(props) {
1399
+ const ctx = props.ctx;
1400
+ // 发布必须有真实目录。没有时这个组件自己负责让用户选一个,
1401
+ // 而不是只显示一句「需要选择工作区」。
1402
+ const dirState = useNpmDir(ctx, props.cwd || '');
1403
+ const cwd = dirState.dir;
1404
+ const [otp, setOtp] = useState('');
1405
+ const [busy, setBusy] = useState(false);
1406
+ const [error, setError] = useState('');
1407
+ const [notice, setNotice] = useState('');
1408
+ const [needOtp, setNeedOtp] = useState(false);
1409
+
1410
+ const publish = async () => {
1411
+ if (cwd === '') return;
1412
+ setBusy(true);
1413
+ setError('');
1414
+ setNotice('');
1415
+ try {
1416
+ const data = await api(ctx, API + '/publish', {
1417
+ method: 'POST',
1418
+ body: { path: cwd, otp: otp.trim() },
1419
+ });
1420
+ setNotice(t('npmPublished', { name: data.name, version: data.version }));
1421
+ setNeedOtp(false);
1422
+ setOtp('');
1423
+ } catch (err) {
1424
+ // 需要验证码时把输入框露出来,其余错误原样显示。
1425
+ if (err.code === 'UNAUTHORIZED') setNeedOtp(true);
1426
+ setError(err.message);
1427
+ } finally {
1428
+ setBusy(false);
1429
+ }
1430
+ };
1431
+
1432
+ return h('div', { className: 'dsh-push-npm-publish' },
1433
+ h(NpmDirBar, { ctx, dir: cwd, onPick: dirState.pick, onClear: dirState.clear }),
1434
+ h('div', { className: 'dsh-push-row-hint' }, t('npmPublishHint')),
1435
+ needOtp
1436
+ ? h('div', { className: 'dsh-push-inline' },
1437
+ h('input', {
1438
+ className: 'dsh-push-input',
1439
+ type: 'text',
1440
+ value: otp,
1441
+ placeholder: t('npmOtpPlaceholder'),
1442
+ inputMode: 'numeric',
1443
+ maxLength: 8,
1444
+ style: { width: '110px' },
1445
+ onChange: (e) => setOtp(e.target.value),
1446
+ }))
1447
+ : null,
1448
+ h('div', { className: 'dsh-push-inline' },
1449
+ h(Btn, {
1450
+ kind: 'primary',
1451
+ disabled: busy || (needOtp && otp.trim() === ''),
1452
+ onClick: publish,
1453
+ }, busy ? t('loading') : t('npmPublishAction'))),
1454
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1455
+ notice ? h('div', { className: 'dsh-push-ok' }, notice) : null);
1456
+ }
1457
+
1458
+ /**
1459
+ * 打包:把 npm 会收进包里的文件列出来,按体积倒序。
1460
+ *
1461
+ * 打包前能看见「哪些文件进去了」是本插件相对命令行的主要价值——
1462
+ * `npm pack --dry-run` 的输出是给人扫一眼的,不是给界面用的。
1463
+ *
1464
+ * @param {{ctx: object, cwd: string}} props
1465
+ */
1466
+ function NpmPackPanel(props) {
1467
+ const ctx = props.ctx;
1468
+ const cwd = props.cwd || '';
1469
+ const [report, setReport] = useState(null);
1470
+ const [busy, setBusy] = useState(false);
1471
+ const [error, setError] = useState('');
1472
+ const [notice, setNotice] = useState('');
1473
+
1474
+ const inspect = useCallback(async () => {
1475
+ if (cwd === '') return;
1476
+ setBusy(true);
1477
+ setError('');
1478
+ try {
1479
+ const data = await api(ctx, API + '/pack?path=' + encodeURIComponent(cwd));
1480
+ setReport(data);
1481
+ } catch (err) {
1482
+ setError(err.message);
1483
+ setReport(null);
1484
+ } finally {
1485
+ setBusy(false);
1486
+ }
1487
+ }, [ctx, cwd]);
1488
+
1489
+ useEffect(() => { inspect(); }, [inspect]);
1490
+
1491
+ const build = async () => {
1492
+ setBusy(true);
1493
+ setError('');
1494
+ setNotice('');
1495
+ try {
1496
+ const data = await api(ctx, API + '/pack', {
1497
+ method: 'POST',
1498
+ body: { path: cwd },
1499
+ });
1500
+ setNotice(t('npmPacked', { file: data.filename }));
1501
+ } catch (err) {
1502
+ setError(err.message);
1503
+ } finally {
1504
+ setBusy(false);
1505
+ }
1506
+ };
1507
+
1508
+ const files = (report && report.files) || [];
1509
+ const top = files.slice(0, 12);
1510
+
1511
+ const row = (entry) => h('div', { key: entry.path, className: 'dsh-push-npm-packfile' },
1512
+ h('span', { className: 'dsh-push-mono' }, entry.path),
1513
+ h('span', { className: 'dsh-push-hint' }, formatBytes(entry.size)));
1514
+
1515
+ return h('div', { className: 'dsh-push-group' },
1516
+ h('div', { className: 'dsh-push-group-head' },
1517
+ h('span', null, t('npmPackTitle')),
1518
+ h('div', { className: 'dsh-push-inline' },
1519
+ report
1520
+ ? h('span', { className: 'dsh-push-row-hint' },
1521
+ t('npmPackSummary', { n: report.totalFiles, size: formatBytes(report.size) }))
1522
+ : null,
1523
+ h(Btn, { mini: true, disabled: busy, onClick: inspect }, t('refresh')))),
1524
+
1525
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1526
+ notice ? h('div', { className: 'dsh-push-ok' }, notice) : null,
1527
+
1528
+ report
1529
+ ? h('div', { className: 'dsh-push-npm-pack' },
1530
+ h('div', { className: 'dsh-push-npm-facts' },
1531
+ packageFact(t('npmPackFiles'), String(report.totalFiles)),
1532
+ packageFact(t('npmPackSize'), formatBytes(report.size)),
1533
+ packageFact(t('npmPackUnpacked'), formatBytes(report.unpackedSize))),
1534
+ h('div', { className: 'dsh-push-npm-packfiles' }, top.map(row)),
1535
+ files.length > top.length
1536
+ ? h('div', { className: 'dsh-push-row-hint' },
1537
+ t('npmPackMore', { n: files.length - top.length }))
1538
+ : null,
1539
+ h('div', { className: 'dsh-push-inline' },
1540
+ h(Btn, { kind: 'primary', disabled: busy, onClick: build },
1541
+ busy ? t('loading') : t('npmPackAction'))))
1542
+ : (busy ? h('div', { className: 'dsh-push-hint' }, t('loading')) : null),
1543
+ h(NpmPublishRow, { ctx, cwd }));
1544
+ }
1545
+
1546
+ /* ───────────────────────── 工作区依赖检查 ───────────────────────── */
1547
+
1548
+ /**
1549
+ * 工作区依赖检查。
1550
+ *
1551
+ * 这是 npm 模块里唯一「不需要跳去别处」的重头功能:读本目录的
1552
+ * package.json,把每个依赖的版本号拿去问 registry,然后按「已最新 /
1553
+ * 有更新 / 读取失败」分组显示。
1554
+ *
1555
+ * @param {{ctx: object, cwd: string}} props
1556
+ */
1557
+ function NpmDepsSection(props) {
1558
+ const ctx = props.ctx;
1559
+ const cwd = props.cwd || '';
1560
+ const [result, setResult] = useState(null);
1561
+ const [busy, setBusy] = useState(false);
1562
+ const [error, setError] = useState('');
1563
+ const aliveRef = useRef(true);
1564
+
1565
+ useEffect(() => {
1566
+ aliveRef.current = true;
1567
+ return () => { aliveRef.current = false; };
1568
+ }, []);
1569
+
1570
+ const load = useCallback(async () => {
1571
+ if (cwd === '') return;
1572
+ setBusy(true);
1573
+ setError('');
1574
+ try {
1575
+ const data = await api(ctx, API + '/deps?path=' + encodeURIComponent(cwd));
1576
+ if (aliveRef.current) setResult(data);
1577
+ } catch (err) {
1578
+ if (aliveRef.current) { setError(err.message); setResult(null); }
1579
+ } finally {
1580
+ if (aliveRef.current) setBusy(false);
1581
+ }
1582
+ }, [ctx, cwd]);
1583
+
1584
+ useEffect(() => { load(); }, [load]);
1585
+
1586
+ const items = (result && result.items) || [];
1587
+ const outdated = items.filter((row) => row.outdated);
1588
+ const current = items.filter((row) => !row.outdated && row.latest);
1589
+ const failed = items.filter((row) => row.error);
1590
+
1591
+ const renderRow = (row) => h('div', { key: row.group + ':' + row.name, className: 'dsh-push-npm-dep' },
1592
+ h('span', { className: 'dsh-push-npm-dep-name' }, row.name),
1593
+ h('span', { className: 'dsh-push-npm-dep-range' }, row.range),
1594
+ h('span', { className: 'dsh-push-npm-dep-latest' },
1595
+ row.error ? '—' : 'v' + row.latest),
1596
+ row.outdated
1597
+ ? h('span', { className: 'dsh-push-pill dsh-push-pill--warn' }, t('npmDepOutdated'))
1598
+ : (row.error
1599
+ ? h('span', { className: 'dsh-push-pill' }, t('npmDepUnknown'))
1600
+ : h('span', { className: 'dsh-push-pill' }, t('npmDepCurrent'))));
1601
+
1602
+ return h('div', { className: 'dsh-push-group' },
1603
+ h('div', { className: 'dsh-push-group-head' },
1604
+ h('span', null, t('npmDepsTitle')),
1605
+ h('div', { className: 'dsh-push-inline' },
1606
+ result
1607
+ ? h('span', { className: 'dsh-push-row-hint' },
1608
+ t('npmDepsSummary', { total: result.total, outdated: result.outdated }))
1609
+ : null,
1610
+ h(Btn, { mini: true, disabled: busy, onClick: load },
1611
+ busy ? t('loading') : t('refresh')))),
1612
+
1613
+ cwd === ''
1614
+ ? h('div', { className: 'dsh-push-hint' }, t('npmDepsNoCwd'))
1615
+ : (error
1616
+ ? h('div', { className: 'dsh-push-error' }, error)
1617
+ : (busy && result === null
1618
+ ? h('div', { className: 'dsh-push-hint' }, t('npmDepsReading'))
1619
+ : (result === null
1620
+ ? null
1621
+ : (result.total === 0
1622
+ ? h('div', { className: 'dsh-push-hint' }, t('npmDepsEmpty'))
1623
+ : h('div', { className: 'dsh-push-npm-deps' },
1624
+ outdated.length > 0
1625
+ ? h('div', { className: 'dsh-push-npm-depgroup' },
1626
+ h('div', { className: 'dsh-push-npm-depgroup-head' },
1627
+ t('npmDepGroupOutdated') + ' · ' + outdated.length),
1628
+ outdated.map(renderRow))
1629
+ : null,
1630
+ current.length > 0
1631
+ ? h('div', { className: 'dsh-push-npm-depgroup' },
1632
+ h('div', { className: 'dsh-push-npm-depgroup-head' },
1633
+ t('npmDepGroupCurrent') + ' · ' + current.length),
1634
+ current.map(renderRow))
1635
+ : null,
1636
+ failed.length > 0
1637
+ ? h('div', { className: 'dsh-push-npm-depgroup' },
1638
+ h('div', { className: 'dsh-push-npm-depgroup-head' },
1639
+ t('npmDepGroupFailed') + ' · ' + failed.length),
1640
+ failed.map(renderRow))
1641
+ : null))))));
1642
+ }
1643
+
1644
+ /* ───────────────────────── 工作区项目标签页 ───────────────────────── */
1645
+
1646
+ /**
1647
+ * 项目视角的 npm 面板。
1648
+ *
1649
+ * 标签页绑定的是一个目录,所以这里只讲「这个项目」:它是谁、能不能
1650
+ * 发布、依赖新不新、包打出来多大。换一个目录就是另一套信息——这才是
1651
+ * 这个入口存在的理由。
1652
+ *
1653
+ * @param {{ctx: object, scope?: object}} props
1654
+ */
1655
+ function NpmProjectPanel(props) {
1656
+ const ctx = props.ctx;
1657
+ // scope 里优先用 repoRoot:仓库根才是 package.json 通常所在的位置。
1658
+ const scopeDir = (props.scope && (props.scope.repoRoot || props.scope.cwd)) || '';
1659
+ const [manifest, setManifest] = useState(null);
1660
+ const [preflight, setPreflight] = useState(null);
1661
+ const [busy, setBusy] = useState(false);
1662
+ const [error, setError] = useState('');
1663
+ // 目录:工作区标签页有 scope 时以它为准,否则用面板里选的。
1664
+ const dirState = useNpmDir(ctx, scopeDir);
1665
+ const cwd = dirState.dir;
1666
+ const [reviewDone, setReviewDone] = useState(null);
1667
+ const aliveRef = useRef(true);
1668
+
1669
+ useEffect(() => {
1670
+ aliveRef.current = true;
1671
+ return () => { aliveRef.current = false; };
1672
+ }, []);
1673
+
1674
+ const load = useCallback(async () => {
1675
+ if (cwd === '') return;
1676
+ setBusy(true);
1677
+ setError('');
1678
+ const params = '?path=' + encodeURIComponent(cwd);
1679
+ const [deps, checks] = await Promise.all([
1680
+ api(ctx, API + '/deps' + params).catch((err) => ({ __error: err.message })),
1681
+ api(ctx, API + '/preflight' + params).catch((err) => ({ __error: err.message })),
1682
+ ]);
1683
+ if (!aliveRef.current) return;
1684
+ setManifest(deps && !deps.__error ? deps : null);
1685
+ setPreflight(checks && !checks.__error ? checks : null);
1686
+ if ((deps && deps.__error) || (checks && checks.__error)) {
1687
+ setError((deps && deps.__error) || (checks && checks.__error));
1688
+ }
1689
+ if (aliveRef.current) setBusy(false);
1690
+ }, [ctx, cwd]);
1691
+
1692
+ useEffect(() => { load(); }, [load]);
1693
+
1694
+ /* 没有目录时也要给出完整控件:目录条用来选,审查入口保留
1695
+ * (审查会提示先选目录),只有依赖目录的数据分组隐藏。
1696
+ * 之前这里直接 return,导致整个面板只剩一句提示。 */
1697
+ if (cwd === '') {
1698
+ return h('div', { className: 'dsh-push-npm-project' },
1699
+ h(NpmDirBar, { ctx, dir: cwd, onPick: dirState.pick }),
1700
+ h('div', { className: 'dsh-push-hint' }, t('npmDepsNoCwd')),
1701
+ h('div', { className: 'dsh-push-group' },
1702
+ h('div', { className: 'dsh-push-group-head' },
1703
+ h('span', null, t('npmReviewTitle')),
1704
+ h(NpmReviewEntry, {
1705
+ ctx,
1706
+ cwd,
1707
+ onReviewed: (data) => setReviewDone(data),
1708
+ })),
1709
+ h('div', { className: 'dsh-push-row-hint' }, t('npmReviewHint'))));
1710
+ }
1711
+
1712
+ /* 没有 package.json:给出创建入口,而不是一句死路提示。 */
1713
+ if (!busy && !manifest && !preflight && error) {
1714
+ return h('div', { className: 'dsh-push-npm-project' },
1715
+ h(NpmDirBar, { ctx, dir: cwd, onPick: dirState.pick, onClear: dirState.clear }),
1716
+ h(NpmInitCard, { ctx, cwd, onCreated: load }),
1717
+ h('div', { className: 'dsh-push-hint' }, error));
1718
+ }
1719
+
1720
+ const TONE = {
1721
+ fail: 'dsh-push-sev--blocker',
1722
+ warn: 'dsh-push-sev--medium',
1723
+ info: 'dsh-push-sev--info',
1724
+ pass: 'dsh-push-sev--low',
1725
+ };
1726
+
1727
+ const checks = (preflight && preflight.checks) || [];
1728
+ const checkRow = (rowItem) => h('div', { key: rowItem.id, className: 'dsh-push-npm-check' },
1729
+ h('span', { className: 'dsh-push-sev ' + (TONE[rowItem.level] || '') },
1730
+ h('span', { className: 'dsh-push-rv-dot' })),
1731
+ h('span', { className: 'dsh-push-npm-check-msg' }, rowItem.message),
1732
+ rowItem.hint ? h('span', { className: 'dsh-push-row-hint' }, rowItem.hint) : null);
1733
+
1734
+ const facts = manifest
1735
+ ? h('div', { className: 'dsh-push-npm-facts' },
1736
+ packageFact(t('npmPkgName'), manifest.name || '—'),
1737
+ packageFact(t('npmPkgVersion'), manifest.version || '—'),
1738
+ packageFact(t('npmFactDeps'), String(manifest.total || 0)))
1739
+ : null;
1740
+
1741
+ const verdict = preflight
1742
+ ? h('div', { className: 'dsh-push-npm-checkhead' },
1743
+ h('span', { className: 'dsh-push-row-hint' }, t('npmPreflightTitle')),
1744
+ h('span', {
1745
+ className: 'dsh-push-pill' + (preflight.publishable ? '' : ' dsh-push-pill--warn'),
1746
+ }, preflight.publishable ? t('npmPreflightOk') : t('npmPreflightBlocked')))
1747
+ : null;
1748
+
1749
+ const checkList = checks.length > 0
1750
+ ? h('div', { className: 'dsh-push-npm-checks' }, checks.map(checkRow))
1751
+ : null;
1752
+
1753
+ const group = h('div', { className: 'dsh-push-group' },
1754
+ h('div', { className: 'dsh-push-group-head' },
1755
+ h('span', null, t('npmProjectTitle')),
1756
+ h(Btn, { mini: true, disabled: busy, onClick: load },
1757
+ busy ? t('loading') : t('refresh'))),
1758
+ error ? h('div', { className: 'dsh-push-error' }, error) : null,
1759
+ facts,
1760
+ verdict,
1761
+ checkList);
1762
+
1763
+ return h('div', { className: 'dsh-push-npm-project' },
1764
+ h(NpmDirBar, { ctx, dir: cwd, onPick: dirState.pick, onClear: dirState.clear }),
1765
+ group,
1766
+
1767
+ /* 发布前审查:三处 npm 面板都有这个入口,行为一致。 */
1768
+ h('div', { className: 'dsh-push-group' },
1769
+ h('div', { className: 'dsh-push-group-head' },
1770
+ h('span', null, t('npmReviewTitle')),
1771
+ h(NpmReviewEntry, {
1772
+ ctx,
1773
+ cwd,
1774
+ onReviewed: (data) => setReviewDone(data),
1775
+ })),
1776
+ reviewDone
1777
+ ? h('div', { className: 'dsh-push-npm-facts' },
1778
+ packageFact(t('npmReviewFindings'), String((reviewDone.findings || []).length)),
1779
+ packageFact(t('npmReviewBlockerCount'), String((reviewDone.findings || [])
1780
+ .filter((row) => row.severity === 'blocker').length)))
1781
+ : h('div', { className: 'dsh-push-row-hint' }, t('npmReviewHint'))),
1782
+
1783
+ h(NpmPackPanel, { ctx, cwd }),
1784
+ h(NpmDepsSection, { ctx, cwd }));
1785
+ }
1786
+
1787
+ /* ────────────────────────── 面板注册 ───────────────────────────────── */
1788
+
1789
+ /** 设置页那一块:账号卡片 + 我的包。 */
1790
+ function settingsPanel(props) {
1791
+ return h(NpmSection, { ctx: props.ctx, reloadKey: props.reloadKey });
1792
+ }
1793
+
1794
+ /** 左侧栏:找包、看包、看详情。 */
1795
+ function sidebarPanel(props) {
1796
+ return h('div', null,
1797
+ h('div', { className: 'dsh-push-page-head' },
1798
+ h('span', { className: 'dsh-push-page-spacer' }),
1799
+ // 头部显示并能切换当前账号——侧栏的搜索与列表都用这个账号的令牌。
1800
+ h(NpmAccountPicker, { ctx: props.ctx })),
1801
+ h(NpmSearchPanel, {
1802
+ ctx: props.ctx,
1803
+ available: Boolean(npmLoggedIn()),
1804
+ reloadKey: props.reloadKey,
1805
+ }));
1806
+ }
1807
+
1808
+ /** 工作区标签页:这个项目自己的事(自检、打包、依赖、发布)。 */
1809
+ function workspacePanel(props) {
1810
+ return h('div', null,
1811
+ h('div', { className: 'dsh-push-page-head' },
1812
+ h('span', { className: 'dsh-push-page-spacer' }),
1813
+ // 发布用的令牌来自当前账号,所以这里必须能看见并切换它。
1814
+ h(NpmAccountPicker, { ctx: props.ctx })),
1815
+ h('div', { className: 'dsh-push-scroll' },
1816
+ h(NpmProjectPanel, { ctx: props.ctx, scope: props.scope })));
1817
+ }
1818
+
1819
+ /**
1820
+ * 挂载。
1821
+ *
1822
+ * 只注册面板,不注册能力:本包**不提供**审查能力,它是审查的**调用方**。
1823
+ * 能力表由 dsh-devdock-review 登记,这里只探测。
1824
+ */
1825
+ function apply(ctx) {
1826
+ core.attachHostLocale(ctx);
1827
+ core.registerMessages('zh', ZH);
1828
+ core.registerMessages('en', EN);
1829
+
1830
+ // 面板属于这个 fiber:宿主卸载插件时随之消失,不会留一个点不开的入口。
1831
+ ctx.effect(() => core.registerPanel({
1832
+ id: 'npm',
1833
+ label: 'npm',
1834
+ order: 20,
1835
+ mark: NpmMark,
1836
+ settings: settingsPanel,
1837
+ sidebar: sidebarPanel,
1838
+ workspace: workspacePanel,
1839
+ }), 'npm: panel');
1840
+ }
1841
+
1842
+ exports.apply = apply;
1843
+ // 只有 slots 是必需的;locale 由内核用 ctx.get 探测。
1844
+ exports.inject = ['slots'];
1845
+
1846
+ return module.exports;
1847
+ },
1848
+ });