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/CHANGELOG.md +48 -0
- package/LICENSE +21 -0
- package/README.md +180 -2
- package/client.js +1848 -0
- package/cordis.patch.yml +11 -0
- package/icon.svg +6 -0
- package/index.js +108 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +124 -4
- package/src/host/npm.js +424 -0
- package/src/host/platform.js +771 -0
|
@@ -0,0 +1,771 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* DevDock · npm 平台插件 · Host 实现。
|
|
3
|
+
*
|
|
4
|
+
* 这个模块不认识内核:它拿到一个经过内核裁剪的 `context`(存储、错误构造、
|
|
5
|
+
* 校验函数、llm 探测),返回一份标准平台定义。内核负责把 routes 挂到
|
|
6
|
+
* webServer、把 actions 聚合进 `devdock` 工具。
|
|
7
|
+
*
|
|
8
|
+
* ## 路由前缀(拆包时最容易踩的坑)
|
|
9
|
+
*
|
|
10
|
+
* 内核把平台路由挂在 `/api/push/<平台 id>` 之下。旧元包里的路径写成
|
|
11
|
+
* `/npm/packages`,注册时会被拼成 `/api/push/npm/npm/packages` —— 多了一
|
|
12
|
+
* 段 `npm`,请求全部 404,而且看起来像是「后端没实现」。
|
|
13
|
+
*
|
|
14
|
+
* 所以这里的 `path` 一律是**平台内相对路径**:`/packages`(最终
|
|
15
|
+
* `/api/push/npm/packages`)。客户端侧对应 `const API = core.API + '/npm'`
|
|
16
|
+
* 再拼 `/packages`,两边各写一次平台 id,绝不重复写第二遍。
|
|
17
|
+
*
|
|
18
|
+
* ## 审查不在这里
|
|
19
|
+
*
|
|
20
|
+
* 发布前审查已经独立成 `dsh-devdock-review`。本包**不提供** npmPublishReview
|
|
21
|
+
* 方法,也没有 `/review/run` 路由:审查是一件独立产品,两个平台各存一份
|
|
22
|
+
* 必然分叉。客户端用 `core.useCapability('review')` 探测它在不在。
|
|
23
|
+
*
|
|
24
|
+
* ## 与内核的分工
|
|
25
|
+
*
|
|
26
|
+
* 只用 registry 只读 API 的事(认令牌、列包、看版本、查依赖)在本包的
|
|
27
|
+
* `./npm.js` 里;真正要跑 npm 的事(pack / publish)用内核的
|
|
28
|
+
* `dsh-devdock-core/src/host/npmcli.js` —— 那是共享执行器,不复制一份。
|
|
29
|
+
*
|
|
30
|
+
* @module src/host/platform.js
|
|
31
|
+
*/
|
|
32
|
+
|
|
33
|
+
import { readFile, writeFile } from 'node:fs/promises';
|
|
34
|
+
import path from 'node:path';
|
|
35
|
+
|
|
36
|
+
import { NpmRunner, mapPackResult, npmAuthEnv, parsePackJson } from 'dsh-devdock-core/src/host/npmcli.js';
|
|
37
|
+
import {
|
|
38
|
+
npmLatestVersion,
|
|
39
|
+
npmPackageStatus,
|
|
40
|
+
npmPackument,
|
|
41
|
+
npmSearchByMaintainer,
|
|
42
|
+
npmSearchText,
|
|
43
|
+
npmWhoami,
|
|
44
|
+
} from './npm.js';
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* 判断一个 semver range 是否已经覆盖 latest。
|
|
48
|
+
*
|
|
49
|
+
* 故意只做保守判断:能明确判定「已满足」时才返回 true,其余一律当作可能
|
|
50
|
+
* 过时。这个值只用于提示「要不要去看看」,误报一次比漏报一次更容易接受
|
|
51
|
+
* ——漏报会让用户以为自己是最新的。
|
|
52
|
+
*
|
|
53
|
+
* @param {string} range package.json 里写的版本范围
|
|
54
|
+
* @param {string} latest 注册表上的最新版本
|
|
55
|
+
* @returns {boolean}
|
|
56
|
+
*/
|
|
57
|
+
function rangeSatisfied(range, latest) {
|
|
58
|
+
const clean = String(range || '').trim();
|
|
59
|
+
if (clean === '' || clean === '*' || clean === 'latest') return true;
|
|
60
|
+
// 精确版本:直接比字符串。
|
|
61
|
+
if (/^v?=\d/.test(clean) || /^\d+\.\d+\.\d+$/.test(clean)) {
|
|
62
|
+
return clean.replace(/^v?=?/, '') === latest;
|
|
63
|
+
}
|
|
64
|
+
// caret / tilde:比较主版本(tilde 再要求次版本相同)。
|
|
65
|
+
const match = clean.match(/^[~^](\d+)(?:\.(\d+))?/);
|
|
66
|
+
if (match) {
|
|
67
|
+
const parts = String(latest ?? '').split('.');
|
|
68
|
+
const major = Number(parts[0]);
|
|
69
|
+
const minor = Number(parts[1]);
|
|
70
|
+
if (!Number.isFinite(major)) return false;
|
|
71
|
+
if (clean.startsWith('^')) return major === Number(match[1]);
|
|
72
|
+
return major === Number(match[1]) && minor === Number(match[2]);
|
|
73
|
+
}
|
|
74
|
+
// 其余写法(>= 、|| 、tag 名等)交给保守分支。
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** 依赖检查的并发上限:太小会慢到没人等,太大会被 registry 限流。 */
|
|
79
|
+
const DEP_CONCURRENCY = 6;
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* 平台定义工厂。
|
|
83
|
+
*
|
|
84
|
+
* @param {object} context 内核注入的平台上下文
|
|
85
|
+
* @returns {object} PlatformDefinition
|
|
86
|
+
*/
|
|
87
|
+
export function npmPlatform(context) {
|
|
88
|
+
const {
|
|
89
|
+
store,
|
|
90
|
+
httpError,
|
|
91
|
+
requireString,
|
|
92
|
+
optionalString,
|
|
93
|
+
clampInt,
|
|
94
|
+
} = context;
|
|
95
|
+
|
|
96
|
+
/* ---------------- 共用小工具 ---------------- */
|
|
97
|
+
|
|
98
|
+
/** 复用同一个 npm 执行器:二进制与超时只解析一次。 */
|
|
99
|
+
let npmRunnerCache = null;
|
|
100
|
+
const runner = () => {
|
|
101
|
+
if (!npmRunnerCache) npmRunnerCache = new NpmRunner();
|
|
102
|
+
return npmRunnerCache;
|
|
103
|
+
};
|
|
104
|
+
|
|
105
|
+
/** 目录参数:省略时用进程工作目录。 */
|
|
106
|
+
const dirOf = (input) => {
|
|
107
|
+
const value = typeof input?.path === 'string' && input.path.trim() !== ''
|
|
108
|
+
? input.path.trim()
|
|
109
|
+
: '';
|
|
110
|
+
return value === '' ? process.cwd() : value;
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** 当前 npm 账号(带令牌),没有则 undefined。 */
|
|
114
|
+
const currentAccount = () => store.activeNpmAccount();
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* 当前 npm 账号(带令牌),缺失时给出可执行的提示而不是空结果。
|
|
118
|
+
* @returns {Promise<object>}
|
|
119
|
+
*/
|
|
120
|
+
async function requireAccount() {
|
|
121
|
+
const account = await store.activeNpmAccount();
|
|
122
|
+
if (!account) {
|
|
123
|
+
throw httpError(401, 'NO_ACCOUNT', '还没有登录 npm。请在 设置 › DevDock › npm 中添加一个 Granular Access Token。');
|
|
124
|
+
}
|
|
125
|
+
return account;
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* 读取并解析一个目录下的 package.json。
|
|
130
|
+
* @param {string} dir
|
|
131
|
+
* @returns {Promise<{file: string, doc: object}>}
|
|
132
|
+
*/
|
|
133
|
+
async function readManifest(dir) {
|
|
134
|
+
const file = path.join(dir, 'package.json');
|
|
135
|
+
let raw;
|
|
136
|
+
try {
|
|
137
|
+
raw = await readFile(file, 'utf8');
|
|
138
|
+
} catch {
|
|
139
|
+
throw httpError(404, 'NOT_FOUND', `这个目录下没有 package.json:${dir}`);
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
return { file, doc: JSON.parse(raw) };
|
|
143
|
+
} catch {
|
|
144
|
+
throw httpError(400, 'BAD_REQUEST', 'package.json 不是合法 JSON,无法解析。');
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/* ---------------- npm registry:账号与包(只读) ---------------- */
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* `GET /accounts` — npm 账号列表(不带令牌)。
|
|
152
|
+
* @returns {Promise<object>}
|
|
153
|
+
*/
|
|
154
|
+
async function npmAccounts() {
|
|
155
|
+
return store.npmAccounts();
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* `POST /account` — 校验令牌后存储。
|
|
160
|
+
*
|
|
161
|
+
* 令牌先验证再保存:存一个没验证过的令牌,结果就是设置页里挂着一个
|
|
162
|
+
* 什么都做不了的账号。
|
|
163
|
+
*
|
|
164
|
+
* @param {object} body `{ token }`
|
|
165
|
+
* @returns {Promise<object>}
|
|
166
|
+
*/
|
|
167
|
+
async function npmAccountAdd(body) {
|
|
168
|
+
const token = requireString(body, 'token', 'npm 令牌').trim();
|
|
169
|
+
const who = await npmWhoami({ token });
|
|
170
|
+
return store.saveNpmAccount({ login: who.login, token });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* `POST /account/remove` — 忘掉一个账号。
|
|
175
|
+
* @param {object} body `{ id }`
|
|
176
|
+
* @returns {Promise<{removed: boolean}>}
|
|
177
|
+
*/
|
|
178
|
+
async function npmAccountRemove(body) {
|
|
179
|
+
const id = requireString(body, 'id', '账号 id');
|
|
180
|
+
const removed = await store.deleteNpmAccount(id);
|
|
181
|
+
if (!removed) throw httpError(404, 'NOT_FOUND', '找不到这个 npm 账号,可能已被移除。');
|
|
182
|
+
return { removed: true };
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* `POST /account/active` — 切换当前账号。
|
|
187
|
+
* @param {object} body `{ id }`
|
|
188
|
+
* @returns {Promise<{activeId: string}>}
|
|
189
|
+
*/
|
|
190
|
+
async function npmAccountActive(body) {
|
|
191
|
+
const id = requireString(body, 'id', '账号 id');
|
|
192
|
+
const ok = await store.setActiveNpmAccount(id);
|
|
193
|
+
if (!ok) throw httpError(404, 'NOT_FOUND', '找不到这个 npm 账号。');
|
|
194
|
+
return { activeId: id };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* `GET /packages` — 当前账号维护的包。
|
|
199
|
+
* @param {object} query `{ size, from }`
|
|
200
|
+
* @returns {Promise<object>}
|
|
201
|
+
*/
|
|
202
|
+
async function npmPackages(query) {
|
|
203
|
+
const account = await requireAccount();
|
|
204
|
+
const result = await npmSearchByMaintainer({
|
|
205
|
+
token: account.token,
|
|
206
|
+
login: account.login,
|
|
207
|
+
size: clampInt(query?.size, 1, 250, 20),
|
|
208
|
+
from: clampInt(query?.from, 0, 100_000, 0),
|
|
209
|
+
});
|
|
210
|
+
await store.touchNpmAccount(account.id);
|
|
211
|
+
return { login: account.login, items: result.items, total: result.total };
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* `GET /package` — 一个包的版本与 dist-tags。
|
|
216
|
+
*
|
|
217
|
+
* 公开数据,令牌不是必需的;有令牌时带上,私有包/组织包才解析得到。
|
|
218
|
+
*
|
|
219
|
+
* @param {object} query `{ name }`
|
|
220
|
+
* @returns {Promise<object>}
|
|
221
|
+
*/
|
|
222
|
+
async function npmPackage(query) {
|
|
223
|
+
const name = requireString(query, 'name', '包名').trim();
|
|
224
|
+
const account = await currentAccount();
|
|
225
|
+
return npmPackument({ name, token: account ? account.token : undefined });
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/**
|
|
229
|
+
* `GET /search` — 按关键词搜索包。
|
|
230
|
+
*
|
|
231
|
+
* 公开数据,不要求登录;有账号时带上令牌,私有包才搜得到。
|
|
232
|
+
*
|
|
233
|
+
* @param {object} query `{ q, size }`
|
|
234
|
+
* @returns {Promise<object>}
|
|
235
|
+
*/
|
|
236
|
+
async function npmSearch(query) {
|
|
237
|
+
const text = typeof query?.q === 'string' ? query.q.trim() : '';
|
|
238
|
+
if (text === '') throw httpError(400, 'BAD_REQUEST', '请输入要搜索的包名或关键词。');
|
|
239
|
+
const account = await currentAccount();
|
|
240
|
+
const result = await npmSearchText({
|
|
241
|
+
text,
|
|
242
|
+
size: clampInt(query?.size, 1, 100, 20),
|
|
243
|
+
token: account ? account.token : undefined,
|
|
244
|
+
});
|
|
245
|
+
return { query: text, items: result.items, total: result.total };
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/* ---------------- npm CLI:初始化 / 打包 / 发布 ---------------- */
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* `POST /init` — 给一个还没有 package.json 的目录生成一份。
|
|
252
|
+
*
|
|
253
|
+
* 只在文件不存在时写,绝不覆盖:一个已有 package.json 的目录被意外重置,
|
|
254
|
+
* 代价远大于省掉一次手动创建。
|
|
255
|
+
*
|
|
256
|
+
* @param {{path?: string, name?: string, version?: string}} body
|
|
257
|
+
* @returns {Promise<object>}
|
|
258
|
+
*/
|
|
259
|
+
async function npmInit(body) {
|
|
260
|
+
const dir = dirOf(body);
|
|
261
|
+
const file = path.join(dir, 'package.json');
|
|
262
|
+
|
|
263
|
+
try {
|
|
264
|
+
await readFile(file, 'utf8');
|
|
265
|
+
throw httpError(409, 'CONFLICT', '这个目录已经有 package.json 了,不会覆盖它。');
|
|
266
|
+
} catch (error) {
|
|
267
|
+
if (error && error.code !== 'ENOENT') throw error;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// 默认包名取目录名:npm 只接受小写与有限字符,先规范化再判断。
|
|
271
|
+
const fallback = path.basename(dir).toLowerCase().replace(/[^a-z0-9._~-]+/g, '-').replace(/^-+|-+$/g, '');
|
|
272
|
+
const name = typeof body?.name === 'string' && body.name.trim() !== ''
|
|
273
|
+
? body.name.trim()
|
|
274
|
+
: (fallback === '' ? 'my-package' : fallback);
|
|
275
|
+
const version = typeof body?.version === 'string' && body.version.trim() !== ''
|
|
276
|
+
? body.version.trim()
|
|
277
|
+
: '0.1.0';
|
|
278
|
+
|
|
279
|
+
const doc = {
|
|
280
|
+
name,
|
|
281
|
+
version,
|
|
282
|
+
description: '',
|
|
283
|
+
main: 'index.js',
|
|
284
|
+
scripts: { test: 'echo "no test specified" && exit 1' },
|
|
285
|
+
keywords: [],
|
|
286
|
+
license: 'MIT',
|
|
287
|
+
files: ['index.js'],
|
|
288
|
+
};
|
|
289
|
+
|
|
290
|
+
try {
|
|
291
|
+
await writeFile(file, JSON.stringify(doc, null, 2) + '\n', 'utf8');
|
|
292
|
+
} catch (error) {
|
|
293
|
+
throw httpError(500, 'INTERNAL', `无法写入 package.json:${error.message}`);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
return { path: file, created: true, name, version };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* `GET /pack` — 打包预演:npm 会收进哪些文件、多大。
|
|
301
|
+
*
|
|
302
|
+
* 只跑 `--dry-run`,不落任何文件。这是「打包审查」的数据来源。
|
|
303
|
+
*
|
|
304
|
+
* @param {{path?: string}} query
|
|
305
|
+
* @returns {Promise<object>}
|
|
306
|
+
*/
|
|
307
|
+
async function npmPackInspect(query) {
|
|
308
|
+
const dir = dirOf(query);
|
|
309
|
+
const result = await runner().run(['pack', '--dry-run', '--json'], { cwd: dir });
|
|
310
|
+
const packed = mapPackResult(parsePackJson(result.stdout));
|
|
311
|
+
return { ...packed, dryRun: true };
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* `POST /pack` — 真正生成 .tgz。
|
|
316
|
+
* @param {{path?: string}} body
|
|
317
|
+
* @returns {Promise<object>}
|
|
318
|
+
*/
|
|
319
|
+
async function npmPack(body) {
|
|
320
|
+
const dir = dirOf(body);
|
|
321
|
+
const result = await runner().run(['pack', '--json'], { cwd: dir });
|
|
322
|
+
const packed = mapPackResult(parsePackJson(result.stdout));
|
|
323
|
+
return { ...packed, dryRun: false, path: path.join(dir, packed.filename) };
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* `POST /publish` — 发布到 npm。
|
|
328
|
+
*
|
|
329
|
+
* 需要 2FA 的账号必须带 otp;没有 otp 时 npm 的报错会被翻译成一句可执行
|
|
330
|
+
* 的提示,而不是让用户对着 EOTP 发呆。
|
|
331
|
+
*
|
|
332
|
+
* @param {{path?: string, otp?: string, tag?: string}} body
|
|
333
|
+
* @returns {Promise<object>}
|
|
334
|
+
*/
|
|
335
|
+
async function npmPublish(body) {
|
|
336
|
+
const account = await store.activeNpmAccount();
|
|
337
|
+
if (!account) {
|
|
338
|
+
throw httpError(401, 'NO_ACCOUNT', '还没有登录 npm,请先在 设置 › DevDock › npm 添加令牌。');
|
|
339
|
+
}
|
|
340
|
+
const dir = dirOf(body);
|
|
341
|
+
|
|
342
|
+
const args = ['publish', '--json'];
|
|
343
|
+
// prepublishOnly 里的 `npm test` 在 monorepo workspace 环境下会与工作区
|
|
344
|
+
// 根的 test 脚本互相缠绕(根目录 test = npm --workspace <pkg> test,而
|
|
345
|
+
// 那个包的 prepublishOnly 又是 npm test),导致发布前钩子递归失败。
|
|
346
|
+
// 发布前的测试由审查插件(dsh-devdock-review)承担,这里跳过脚本。
|
|
347
|
+
args.push('--ignore-scripts');
|
|
348
|
+
|
|
349
|
+
// 防御性校验:--tag 是 dist-tag 名,只允许 npm 认可的字符;
|
|
350
|
+
// --otp 是 6-8 位数字。任何越界字符直接拒绝,不进入子进程 argv。
|
|
351
|
+
const tag = typeof body?.tag === 'string' ? body.tag.trim() : '';
|
|
352
|
+
if (tag !== '') {
|
|
353
|
+
if (!/^[a-zA-Z0-9._@-]+$/.test(tag) || tag.length > 64) {
|
|
354
|
+
throw httpError(400, 'BAD_REQUEST', '发布标签(tag)含非法字符,只能是字母、数字、点、下划线、连字符。');
|
|
355
|
+
}
|
|
356
|
+
args.push('--tag', tag);
|
|
357
|
+
}
|
|
358
|
+
const otp = typeof body?.otp === 'string' ? body.otp.trim() : '';
|
|
359
|
+
if (otp !== '') {
|
|
360
|
+
if (!/^\d{6,8}$/.test(otp)) {
|
|
361
|
+
throw httpError(400, 'BAD_REQUEST', '验证码(otp)必须是 6 到 8 位数字。');
|
|
362
|
+
}
|
|
363
|
+
args.push('--otp', otp);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
try {
|
|
367
|
+
await runner().run(args, { cwd: dir, env: npmAuthEnv(account.token) });
|
|
368
|
+
// npm publish 的输出不是 pack 的 JSON 结构,别用 parsePackJson 解析。
|
|
369
|
+
// 从 package.json 读回真实的 name/version,这是发布出去的确切值。
|
|
370
|
+
let name = '';
|
|
371
|
+
let version = '';
|
|
372
|
+
try {
|
|
373
|
+
const doc = JSON.parse(await readFile(path.join(dir, 'package.json'), 'utf8'));
|
|
374
|
+
name = doc.name ?? '';
|
|
375
|
+
version = doc.version ?? '';
|
|
376
|
+
} catch { /* 读不到就用空值 */ }
|
|
377
|
+
await store.touchNpmAccount(account.id);
|
|
378
|
+
return { published: true, name, version };
|
|
379
|
+
} catch (error) {
|
|
380
|
+
const text = `${error.stderr || ''} ${error.message || ''}`;
|
|
381
|
+
if (/EOTP|one-time password|two-factor/i.test(text)) {
|
|
382
|
+
throw httpError(401, 'UNAUTHORIZED', '这次发布需要一次性验证码(2FA):请在发布对话框里填入 6 位验证码后重试。');
|
|
383
|
+
}
|
|
384
|
+
if (/E403|403 Forbidden|cannot publish over/i.test(text)) {
|
|
385
|
+
throw httpError(403, 'FORBIDDEN', error.message);
|
|
386
|
+
}
|
|
387
|
+
// 带上完整 stderr 尾部,否则 prepublishOnly 里的测试失败原因被截断,
|
|
388
|
+
// 只能看到「npm test」三个字,无从定位。
|
|
389
|
+
const tail = String(error.stderr || error.stdout || '')
|
|
390
|
+
.split('\n').filter((line) => line.trim() !== '').slice(-12).join('\n');
|
|
391
|
+
throw httpError(500, 'INTERNAL', error.message + (tail ? '\n---\n' + tail : ''));
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/* ---------------- 发布前自检与依赖 ---------------- */
|
|
396
|
+
|
|
397
|
+
/**
|
|
398
|
+
* `GET /preflight` — 发布前自检。
|
|
399
|
+
*
|
|
400
|
+
* 把「发了才发现包名被占 / 版本重复 / 忘了 README」这几类错误提前到本地
|
|
401
|
+
* 就能发现。检查分三级:fail 会直接导致发布失败,warn 多半是遗漏,
|
|
402
|
+
* info 只是提示。只读本地 package.json 与 registry,不写任何东西。
|
|
403
|
+
*
|
|
404
|
+
* @param {{path?: string}} options
|
|
405
|
+
* @returns {Promise<object>}
|
|
406
|
+
*/
|
|
407
|
+
async function npmPreflight(options) {
|
|
408
|
+
const dir = dirOf(options);
|
|
409
|
+
const { file, doc } = await readManifest(dir);
|
|
410
|
+
|
|
411
|
+
const checks = [];
|
|
412
|
+
const add = (id, level, message, hint) => checks.push({ id, level, message, hint: hint || '' });
|
|
413
|
+
const exists = async (rel) => {
|
|
414
|
+
try { await readFile(path.join(dir, rel)); return true; } catch { return false; }
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
const name = typeof doc.name === 'string' ? doc.name.trim() : '';
|
|
418
|
+
const version = typeof doc.version === 'string' ? doc.version.trim() : '';
|
|
419
|
+
|
|
420
|
+
if (name === '') add('name', 'fail', '缺少 name 字段', 'npm 用 name 作为包的唯一标识');
|
|
421
|
+
else if (!/^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(name)) {
|
|
422
|
+
add('name', 'fail', 'name 不是合法的 npm 包名', '只能是小写字母、数字、- . _ ~;scope 用 @scope/name');
|
|
423
|
+
} else {
|
|
424
|
+
add('name', 'pass', 'name 格式合法', name);
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
if (version === '') add('version', 'fail', '缺少 version 字段', '发布必须带版本号');
|
|
428
|
+
else if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) {
|
|
429
|
+
add('version', 'fail', 'version 不是合法 semver', version);
|
|
430
|
+
} else {
|
|
431
|
+
add('version', 'pass', 'version 格式合法', version);
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// registry 占用:名字被占用不一定是问题,版本重复一定是。
|
|
435
|
+
if (name !== '') {
|
|
436
|
+
const account = await currentAccount();
|
|
437
|
+
const status = await npmPackageStatus({ name, token: account ? account.token : undefined });
|
|
438
|
+
if (status.error) {
|
|
439
|
+
add('registry', 'warn', '无法查询 registry', status.error);
|
|
440
|
+
} else if (!status.exists) {
|
|
441
|
+
add('registry', 'pass', '包名未被占用', name);
|
|
442
|
+
} else {
|
|
443
|
+
add('registry', 'info', 'npm 上已存在同名包',
|
|
444
|
+
'如果这是你自己的包就正常;否则发布会被拒绝。latest 为 ' + (status.latest || '—'));
|
|
445
|
+
if (version !== '' && status.versions.includes(version)) {
|
|
446
|
+
add('version-taken', 'fail', '这个版本已经发布过',
|
|
447
|
+
version + ' 已存在,请提升版本号后再发布');
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
// 常见遗漏:README / LICENSE / files。
|
|
453
|
+
if (await exists('README.md')) add('readme', 'pass', 'README.md 存在', '');
|
|
454
|
+
else add('readme', 'warn', '缺少 README.md', 'npm 页面会没有说明');
|
|
455
|
+
|
|
456
|
+
const licenseFile = (await exists('LICENSE')) || (await exists('LICENSE.md'));
|
|
457
|
+
if (licenseFile) add('license', 'pass', '许可证文件存在', '');
|
|
458
|
+
else if (typeof doc.license === 'string' && doc.license !== '') {
|
|
459
|
+
add('license', 'pass', 'package.json 声明了 license', doc.license);
|
|
460
|
+
} else {
|
|
461
|
+
add('license', 'warn', '没有许可证文件,也没声明 license', '默认发布出去的包是不可自由使用的');
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
const files = Array.isArray(doc.files) ? doc.files : null;
|
|
465
|
+
if (files) {
|
|
466
|
+
add('files', 'pass', 'package.json 声明了 files', files.length + ' 项');
|
|
467
|
+
} else {
|
|
468
|
+
add('files', 'warn', '没有声明 files 字段', '默认会把目录下几乎所有文件都发布出去');
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// 入口文件必须真实存在,否则装了也 require 不到。
|
|
472
|
+
if (typeof doc.main === 'string' && doc.main !== '') {
|
|
473
|
+
if (await exists(doc.main)) add('main', 'pass', 'main 指向的文件存在', doc.main);
|
|
474
|
+
else add('main', 'fail', 'main 指向的文件不存在', doc.main);
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
if (doc.private === true) {
|
|
478
|
+
add('private', 'fail', 'package.json 标了 private: true', 'private 的包无法发布,先去掉这个字段');
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
const counts = {
|
|
482
|
+
fail: checks.filter((row) => row.level === 'fail').length,
|
|
483
|
+
warn: checks.filter((row) => row.level === 'warn').length,
|
|
484
|
+
pass: checks.filter((row) => row.level === 'pass').length,
|
|
485
|
+
info: checks.filter((row) => row.level === 'info').length,
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
return {
|
|
489
|
+
path: file,
|
|
490
|
+
name,
|
|
491
|
+
version,
|
|
492
|
+
checks,
|
|
493
|
+
counts,
|
|
494
|
+
// 只有 fail 会阻止发布;warn 值得看一眼但不必拦。
|
|
495
|
+
publishable: counts.fail === 0,
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
/**
|
|
500
|
+
* `GET /deps` — 工作区 package.json 里的依赖,逐个比对 npm 上的最新版。
|
|
501
|
+
*
|
|
502
|
+
* 这是本插件少有的「不需要跳去别处」的 npm 能力:读本地文件,只把版本号
|
|
503
|
+
* 拿去问 registry,最后在面板里直接给出「有没有更新」。
|
|
504
|
+
*
|
|
505
|
+
* @param {{path?: string}} options
|
|
506
|
+
* @returns {Promise<object>}
|
|
507
|
+
*/
|
|
508
|
+
async function npmDeps(options) {
|
|
509
|
+
const dir = dirOf(options);
|
|
510
|
+
const { file, doc } = await readManifest(dir);
|
|
511
|
+
|
|
512
|
+
const groups = [
|
|
513
|
+
['dependencies', doc.dependencies],
|
|
514
|
+
['devDependencies', doc.devDependencies],
|
|
515
|
+
];
|
|
516
|
+
const rows = [];
|
|
517
|
+
for (const [group, table] of groups) {
|
|
518
|
+
if (!table || typeof table !== 'object') continue;
|
|
519
|
+
for (const [name, range] of Object.entries(table)) {
|
|
520
|
+
if (typeof range !== 'string') continue;
|
|
521
|
+
rows.push({ name, range, group });
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
const account = await currentAccount();
|
|
526
|
+
const token = account ? account.token : undefined;
|
|
527
|
+
|
|
528
|
+
const results = [];
|
|
529
|
+
for (let index = 0; index < rows.length; index += DEP_CONCURRENCY) {
|
|
530
|
+
const slice = rows.slice(index, index + DEP_CONCURRENCY);
|
|
531
|
+
const settled = await Promise.all(slice.map(async (row) => {
|
|
532
|
+
const info = await npmLatestVersion({ name: row.name, token });
|
|
533
|
+
return {
|
|
534
|
+
...row,
|
|
535
|
+
latest: info.latest,
|
|
536
|
+
error: info.error ?? null,
|
|
537
|
+
outdated: info.latest !== null && !rangeSatisfied(row.range, info.latest),
|
|
538
|
+
};
|
|
539
|
+
}));
|
|
540
|
+
results.push(...settled);
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
return {
|
|
544
|
+
path: file,
|
|
545
|
+
name: typeof doc.name === 'string' ? doc.name : '',
|
|
546
|
+
version: typeof doc.version === 'string' ? doc.version : '',
|
|
547
|
+
items: results,
|
|
548
|
+
total: results.length,
|
|
549
|
+
outdated: results.filter((row) => row.outdated).length,
|
|
550
|
+
failed: results.filter((row) => row.error !== null).length,
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/* ---------------- 平台定义 ---------------- */
|
|
555
|
+
|
|
556
|
+
return {
|
|
557
|
+
id: 'npm',
|
|
558
|
+
label: 'npm',
|
|
559
|
+
// 与元包里的顺序一致:GitHub(10) → npm(20) → Cloudflare(30) → 审查(40)。
|
|
560
|
+
order: 20,
|
|
561
|
+
icon: 'NpmMark',
|
|
562
|
+
|
|
563
|
+
start() {
|
|
564
|
+
/* 没有需要在挂载时注册的副作用;账号与包都是按需读取。 */
|
|
565
|
+
},
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 业务方法集合。
|
|
569
|
+
*
|
|
570
|
+
* 路由与工具动作都调用这里,所以界面点「发布」和模型请求发布走的是
|
|
571
|
+
* 同一条代码路径(one operation, two callers)。
|
|
572
|
+
*/
|
|
573
|
+
host: {
|
|
574
|
+
accounts: npmAccounts,
|
|
575
|
+
accountAdd: npmAccountAdd,
|
|
576
|
+
accountRemove: npmAccountRemove,
|
|
577
|
+
accountActive: npmAccountActive,
|
|
578
|
+
packages: npmPackages,
|
|
579
|
+
package: npmPackage,
|
|
580
|
+
search: npmSearch,
|
|
581
|
+
init: npmInit,
|
|
582
|
+
packInspect: npmPackInspect,
|
|
583
|
+
pack: npmPack,
|
|
584
|
+
publish: npmPublish,
|
|
585
|
+
preflight: npmPreflight,
|
|
586
|
+
deps: npmDeps,
|
|
587
|
+
},
|
|
588
|
+
|
|
589
|
+
/**
|
|
590
|
+
* 路由表。**路径是平台内相对路径**:内核会加 `/api/push/npm` 前缀。
|
|
591
|
+
* 写成 `/npm/packages` 会变成 `/api/push/npm/npm/packages`。
|
|
592
|
+
*/
|
|
593
|
+
routes: [
|
|
594
|
+
{ path: '/accounts', method: 'GET', run: async () => npmAccounts() },
|
|
595
|
+
{ path: '/account', method: 'POST', run: async ({ body }) => npmAccountAdd(body) },
|
|
596
|
+
{ path: '/account/remove', method: 'POST', run: async ({ body }) => npmAccountRemove(body) },
|
|
597
|
+
{ path: '/account/active', method: 'POST', run: async ({ body }) => npmAccountActive(body) },
|
|
598
|
+
{
|
|
599
|
+
path: '/packages',
|
|
600
|
+
method: 'GET',
|
|
601
|
+
run: async ({ query }) => npmPackages({
|
|
602
|
+
size: Number(query('size')) || undefined,
|
|
603
|
+
from: Number(query('from')) || 0,
|
|
604
|
+
}),
|
|
605
|
+
},
|
|
606
|
+
{
|
|
607
|
+
path: '/package',
|
|
608
|
+
method: 'GET',
|
|
609
|
+
run: async ({ query }) => npmPackage({ name: query('name') }),
|
|
610
|
+
},
|
|
611
|
+
{
|
|
612
|
+
path: '/search',
|
|
613
|
+
method: 'GET',
|
|
614
|
+
run: async ({ query }) => npmSearch({
|
|
615
|
+
q: query('q'),
|
|
616
|
+
size: Number(query('size')) || undefined,
|
|
617
|
+
}),
|
|
618
|
+
},
|
|
619
|
+
{ path: '/init', method: 'POST', run: async ({ body }) => npmInit(body) },
|
|
620
|
+
{
|
|
621
|
+
path: '/pack',
|
|
622
|
+
method: 'GET',
|
|
623
|
+
run: async ({ query }) => npmPackInspect({ path: query('path') }),
|
|
624
|
+
},
|
|
625
|
+
{ path: '/pack', method: 'POST', run: async ({ body }) => npmPack(body) },
|
|
626
|
+
{ path: '/publish', method: 'POST', run: async ({ body }) => npmPublish(body) },
|
|
627
|
+
{
|
|
628
|
+
path: '/preflight',
|
|
629
|
+
method: 'GET',
|
|
630
|
+
run: async ({ query }) => npmPreflight({ path: query('path') }),
|
|
631
|
+
},
|
|
632
|
+
{
|
|
633
|
+
path: '/deps',
|
|
634
|
+
method: 'GET',
|
|
635
|
+
run: async ({ query }) => npmDeps({ path: query('path') }),
|
|
636
|
+
},
|
|
637
|
+
],
|
|
638
|
+
|
|
639
|
+
actions: [
|
|
640
|
+
{
|
|
641
|
+
id: 'accounts',
|
|
642
|
+
description: '列出已登录的 npm 账号(不含令牌)与当前账号',
|
|
643
|
+
run: async () => npmAccounts(),
|
|
644
|
+
render: (value) => {
|
|
645
|
+
const rows = value.accounts || [];
|
|
646
|
+
if (rows.length === 0) return '【npm】还没有登录任何账号,请在 设置 › DevDock › npm 中添加令牌。';
|
|
647
|
+
return ['【npm】账号:', ...rows.map((row) =>
|
|
648
|
+
` ${row.login}${row.id === value.activeId ? '(当前)' : ''}`)].join('\n');
|
|
649
|
+
},
|
|
650
|
+
},
|
|
651
|
+
{
|
|
652
|
+
id: 'packages',
|
|
653
|
+
description: '列出当前 npm 账号维护的包',
|
|
654
|
+
parameters: {
|
|
655
|
+
size: { type: 'number', description: '返回条数,默认 20' },
|
|
656
|
+
from: { type: 'number', description: '起始偏移,默认 0' },
|
|
657
|
+
},
|
|
658
|
+
run: async (args) => npmPackages({
|
|
659
|
+
size: Number(args?.size) || undefined,
|
|
660
|
+
from: Number(args?.from) || 0,
|
|
661
|
+
}),
|
|
662
|
+
render: (value) => (value.items.length === 0
|
|
663
|
+
? `【npm】${value.login} 名下没有查到包。`
|
|
664
|
+
: [`【npm】${value.login} 维护的包(${value.total} 个):`,
|
|
665
|
+
...value.items.map((row) => ` ${row.name}${row.version ? ' v' + row.version : ''}`)].join('\n')),
|
|
666
|
+
},
|
|
667
|
+
{
|
|
668
|
+
id: 'package',
|
|
669
|
+
description: '查看一个包的版本、dist-tags、体积与依赖',
|
|
670
|
+
parameters: { name: { type: 'string', description: '包名,支持 @scope/name' } },
|
|
671
|
+
run: async (args) => {
|
|
672
|
+
const name = optionalString(args?.name);
|
|
673
|
+
if (!name) throw httpError(400, 'BAD_REQUEST', 'package 需要 name,例如 react。');
|
|
674
|
+
return npmPackage({ name });
|
|
675
|
+
},
|
|
676
|
+
render: (value) => {
|
|
677
|
+
const pkg = value.pkg || {};
|
|
678
|
+
return [`【npm】${pkg.name} v${pkg.latestVersion || '—'}(共 ${pkg.versionCount || 0} 个版本)`,
|
|
679
|
+
` 许可证 ${pkg.license || '—'} · 体积 ${pkg.unpackedSize === null ? '—' : pkg.unpackedSize + ' B'}`,
|
|
680
|
+
` ${pkg.description || ''}`].join('\n');
|
|
681
|
+
},
|
|
682
|
+
},
|
|
683
|
+
{
|
|
684
|
+
id: 'search',
|
|
685
|
+
description: '按关键词搜索 npm 上的包',
|
|
686
|
+
parameters: {
|
|
687
|
+
q: { type: 'string', description: '搜索关键词' },
|
|
688
|
+
size: { type: 'number', description: '返回条数,默认 20' },
|
|
689
|
+
},
|
|
690
|
+
run: async (args) => {
|
|
691
|
+
const q = optionalString(args?.q);
|
|
692
|
+
if (!q) throw httpError(400, 'BAD_REQUEST', 'search 需要 q,例如 electron。');
|
|
693
|
+
return npmSearch({ q, size: Number(args?.size) || undefined });
|
|
694
|
+
},
|
|
695
|
+
render: (value) => (value.items.length === 0
|
|
696
|
+
? `【npm】没有搜到「${value.query}」。`
|
|
697
|
+
: [`【npm】搜索「${value.query}」(${value.total} 个结果):`,
|
|
698
|
+
...value.items.map((row) => ` ${row.name}${row.version ? ' v' + row.version : ''}`)].join('\n')),
|
|
699
|
+
},
|
|
700
|
+
{
|
|
701
|
+
id: 'preflight',
|
|
702
|
+
description: '发布前自检:包名、版本、registry 占用、README、许可证、入口文件',
|
|
703
|
+
parameters: { path: { type: 'string', description: '项目目录,省略时用当前工作目录' } },
|
|
704
|
+
run: async (args, toolContext) => {
|
|
705
|
+
const dir = optionalString(args?.path)
|
|
706
|
+
?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
|
|
707
|
+
return npmPreflight({ path: dir });
|
|
708
|
+
},
|
|
709
|
+
render: (value) => {
|
|
710
|
+
const bad = value.checks.filter((row) => row.level === 'fail');
|
|
711
|
+
const warn = value.checks.filter((row) => row.level === 'warn');
|
|
712
|
+
return [`【npm】${value.name || '(无 name)'} v${value.version || '(无 version)'}`
|
|
713
|
+
+ ` · ${value.publishable ? '可以发布' : '不能发布'}`,
|
|
714
|
+
...bad.map((row) => ` 阻断:${row.message}`),
|
|
715
|
+
...warn.map((row) => ` 提醒:${row.message}`)].join('\n');
|
|
716
|
+
},
|
|
717
|
+
},
|
|
718
|
+
{
|
|
719
|
+
id: 'deps',
|
|
720
|
+
description: '检查当前项目依赖是否有更新(逐个比对 npm 上的最新版)',
|
|
721
|
+
parameters: { path: { type: 'string', description: '项目目录,省略时用当前工作目录' } },
|
|
722
|
+
run: async (args, toolContext) => {
|
|
723
|
+
const dir = optionalString(args?.path)
|
|
724
|
+
?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
|
|
725
|
+
return npmDeps({ path: dir });
|
|
726
|
+
},
|
|
727
|
+
render: (value) => {
|
|
728
|
+
const outdated = value.items.filter((row) => row.outdated);
|
|
729
|
+
if (value.total === 0) return '【npm】这个项目没有声明依赖。';
|
|
730
|
+
return [`【npm】${value.name || '项目'} v${value.version || '—'}:`
|
|
731
|
+
+ `${value.total} 个依赖,${value.outdated} 个有更新`,
|
|
732
|
+
...outdated.slice(0, 20).map((row) =>
|
|
733
|
+
` ${row.name} ${row.range} → ${row.latest}`)].join('\n');
|
|
734
|
+
},
|
|
735
|
+
},
|
|
736
|
+
{
|
|
737
|
+
id: 'pack',
|
|
738
|
+
description: '打包预演:列出 npm pack 会收进包里的文件与体积(不落文件)',
|
|
739
|
+
parameters: { path: { type: 'string', description: '项目目录,省略时用当前工作目录' } },
|
|
740
|
+
run: async (args, toolContext) => {
|
|
741
|
+
const dir = optionalString(args?.path)
|
|
742
|
+
?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
|
|
743
|
+
return npmPackInspect({ path: dir });
|
|
744
|
+
},
|
|
745
|
+
render: (value) => (value.totalFiles === 0
|
|
746
|
+
? '【npm】npm pack 没有收集到任何文件,发布出去会是一个空包。'
|
|
747
|
+
: [`【npm】将打包 ${value.totalFiles} 个文件,压缩后 ${value.size ?? 0} 字节:`,
|
|
748
|
+
...value.files.slice(0, 20).map((row) => ` ${row.path}(${row.size} B)`)].join('\n')),
|
|
749
|
+
},
|
|
750
|
+
{
|
|
751
|
+
id: 'publish',
|
|
752
|
+
description: '发布到 npm(需要 path;账号启用 2FA 时还需要 otp)',
|
|
753
|
+
parameters: {
|
|
754
|
+
path: { type: 'string', description: '项目目录,省略时用当前工作目录' },
|
|
755
|
+
otp: { type: 'string', description: '6-8 位一次性验证码,仅 2FA 账号需要' },
|
|
756
|
+
tag: { type: 'string', description: 'dist-tag,默认 latest' },
|
|
757
|
+
},
|
|
758
|
+
run: async (args, toolContext) => {
|
|
759
|
+
const dir = optionalString(args?.path)
|
|
760
|
+
?? (typeof toolContext?.resolvePath === 'function' ? await toolContext.resolvePath() : process.cwd());
|
|
761
|
+
return npmPublish({
|
|
762
|
+
path: dir,
|
|
763
|
+
otp: optionalString(args?.otp),
|
|
764
|
+
tag: optionalString(args?.tag),
|
|
765
|
+
});
|
|
766
|
+
},
|
|
767
|
+
render: (value) => `【npm】已发布 ${value.name || '(未知包名)'} ${value.version || ''}`.trim(),
|
|
768
|
+
},
|
|
769
|
+
],
|
|
770
|
+
};
|
|
771
|
+
}
|