dsh-devdock 2.5.0 → 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.
@@ -1,288 +0,0 @@
1
- /**
2
- * npm CLI 执行器(DevDock 的 npm 模块 · 打包/发布)。
3
- *
4
- * 这里只做一件 registry API 做不到的事:真正运行 npm 自己的命令。
5
- * `npm pack` 的文件筛选规则(files 字段、.npmignore、默认忽略项)复杂到
6
- * 不值得重写一遍——由 npm 自己算,结果才和用户之后手动执行一致。
7
- *
8
- * 令牌只通过**环境变量**传入(`npm_config_//registry.npmjs.org/:_authToken`),
9
- * 不出现在 argv 里:argv 在进程列表、错误日志、崩溃转储里都可能被看到。
10
- *
11
- * 与 GitRunner 相同的两段式捕获:正常走管道;受限宿主上管道会 EPERM,
12
- * 那时改用临时文件重定向——否则打包/发布在这个宿主上根本用不了。
13
- */
14
- import { spawn } from 'node:child_process';
15
- import { closeSync, openSync, readFileSync, unlinkSync } from 'node:fs';
16
- import { randomBytes } from 'node:crypto';
17
- import { tmpdir } from 'node:os';
18
- import path from 'node:path';
19
-
20
- /** npm 可执行文件。Windows 上是 npm.cmd,否则 spawn 找不到。 */
21
- export function resolveNpmBinary() {
22
- return process.platform === 'win32' ? 'npm.cmd' : 'npm';
23
- }
24
-
25
- /**
26
- * 把令牌折成 npm 能读的环境变量。
27
- *
28
- * npm 的配置项都可以用 `npm_config_<key>` 覆盖,带斜杠的嵌套键同样成立。
29
- *
30
- * @param {string} token
31
- * @param {string} [registry]
32
- * @returns {Record<string, string>}
33
- */
34
- export function npmAuthEnv(token, registry = 'https://registry.npmjs.org') {
35
- const env = {};
36
- if (typeof token === 'string' && token !== '') {
37
- const host = registry.replace(/^https?:/, '').replace(/\/+$/, '');
38
- env[`npm_config_${host}/:_authToken`] = token;
39
- }
40
- env.npm_config_registry = registry;
41
- // 没有终端:任何交互式提示都必须立刻失败而不是挂住。
42
- env.npm_config_yes = 'true';
43
- env.npm_config_progress = 'false';
44
- env.npm_config_update_notifier = 'false';
45
- env.npm_config_fund = 'false';
46
- env.npm_config_audit = 'false';
47
- env.npm_config_color = 'false';
48
- return env;
49
- }
50
-
51
- /** 一次 npm 调用的错误。 */
52
- export class NpmError extends Error {
53
- /**
54
- * @param {string} code TIMEOUT|EPERM|FAILED
55
- * @param {string} message 中文可读信息
56
- * @param {{stdout?: string, stderr?: string, exitCode?: number}} [details]
57
- */
58
- constructor(code, message, details = {}) {
59
- super(message);
60
- this.name = 'NpmError';
61
- this.code = code;
62
- this.stdout = details.stdout ?? '';
63
- this.stderr = details.stderr ?? '';
64
- this.exitCode = details.exitCode ?? null;
65
- }
66
- }
67
-
68
- export class NpmRunner {
69
- /** @param {{binary?: string, timeoutMs?: number}} [options] */
70
- constructor(options = {}) {
71
- this.#binary = options.binary || resolveNpmBinary();
72
- this.#timeoutMs = Number.isFinite(options.timeoutMs) ? options.timeoutMs : 180_000;
73
- }
74
-
75
- #binary;
76
- #timeoutMs;
77
-
78
- /**
79
- * 运行一条 npm 子命令。
80
- *
81
- * @param {string[]} args
82
- * @param {object} [options]
83
- * @param {string} [options.cwd]
84
- * @param {Record<string,string>} [options.env]
85
- * @param {number} [options.timeoutMs]
86
- * @param {boolean} [options.allowFailure] 非零退出也 resolve,由调用方看 code
87
- * @returns {Promise<{stdout: string, stderr: string, code: number}>}
88
- */
89
- async run(args, options = {}) {
90
- let result;
91
- try {
92
- result = await this.#runPiped(args, options);
93
- } catch (error) {
94
- const denied = error?.code === 'EPERM'
95
- || error?.cause?.code === 'EPERM'
96
- || /EPERM/.test(String(error?.message ?? ''));
97
- if (!denied) throw error;
98
- result = await this.#runToFiles(args, options);
99
- }
100
-
101
- if (result.code !== 0 && !options.allowFailure) {
102
- // npm 把 warning 打在 stderr 前几行,真正的 error(如 403 的 body)
103
- // 在更后面。这里取「首个 error 行 + 末尾若干行」,而不是机械地取
104
- // 前 3 行——那样只能看到 repository.url 规范化之类的 warning,把
105
- // 真正的 403 / EOTP 原因漏掉。
106
- const lines = (result.stderr || result.stdout || '')
107
- .split('\n')
108
- .map((line) => line.trim())
109
- .filter(Boolean);
110
- const firstError = lines.find((line) => /npm error|error code|EOTP|E403|E401|E402|E404/i.test(line));
111
- const tail = lines.slice(-6).join(' / ');
112
- const message = [firstError, tail].filter(Boolean).join(' | ');
113
- throw new NpmError('FAILED', `npm 执行失败(退出码 ${result.code}):${message}`, result);
114
- }
115
- return result;
116
- }
117
-
118
- /** spawn 时共用的选项。 */
119
- #spawnOptions(options, stdio) {
120
- return {
121
- cwd: options.cwd ?? process.cwd(),
122
- env: { ...process.env, ...(options.env ?? {}) },
123
- windowsHide: true,
124
- // 不用 shell: true —— 那会让参数(如 --otp、--tag)经过 cmd 的
125
- // 元字符解析,请求体里的值就可能注入命令。改用显式 cmd.exe,参数
126
- // 作为 argv 单独传入,由 spawn 逐项转义,不经过 shell 解析。
127
- stdio,
128
- };
129
- }
130
-
131
- /** 把「npm 可执行文件 + 参数」折成 spawn 的 command + args。
132
- * Windows 上 npm 是 .cmd,必须经 cmd.exe 执行;这里用 /d /s /c 显式
133
- * 包装,参数仍是独立 argv 项,避免 shell 元字符注入。 */
134
- #commandAndArgs(args) {
135
- if (process.platform === 'win32') {
136
- return { command: 'cmd.exe', args: ['/d', '/s', '/c', this.#binary, ...args] };
137
- }
138
- return { command: this.#binary, args };
139
- }
140
-
141
- /** 正常路径:管道捕获。 */
142
- #runPiped(args, options) {
143
- const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
144
- const { command, args: argv } = this.#commandAndArgs(args);
145
- return new Promise((resolve, reject) => {
146
- let child;
147
- try {
148
- child = spawn(command, argv, this.#spawnOptions(options, ['ignore', 'pipe', 'pipe']));
149
- } catch (error) {
150
- reject(new NpmError('FAILED', `无法启动 npm:${error.message}`));
151
- return;
152
- }
153
- let stdout = '';
154
- let stderr = '';
155
- let settled = false;
156
- let timer = null;
157
- const finish = (fn, value) => {
158
- if (settled) return;
159
- settled = true;
160
- if (timer) clearTimeout(timer);
161
- fn(value);
162
- };
163
- timer = setTimeout(() => {
164
- try { child.kill('SIGKILL'); } catch { /* 已退出 */ }
165
- finish(reject, new NpmError('TIMEOUT', `npm 执行超时(${Math.round(timeoutMs / 1000)} 秒)`, { stdout, stderr }));
166
- }, timeoutMs);
167
- child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8'); });
168
- child.stderr?.on('data', (chunk) => { stderr += chunk.toString('utf8'); });
169
- child.on('error', (error) => {
170
- finish(reject, new NpmError('EPERM', `npm 启动失败:${error.message}`, { stdout, stderr }));
171
- });
172
- child.on('close', (code) => finish(resolve, { stdout, stderr, code: code ?? 0 }));
173
- });
174
- }
175
-
176
- /**
177
- * 受限宿主路径:两个流都重定向到临时文件。
178
- *
179
- * 文件用 0o600 创建并在 finally 里删除——npm 的输出可能包含包内路径,
180
- * 不该留在临时目录里。
181
- */
182
- async #runToFiles(args, options) {
183
- const timeoutMs = options.timeoutMs ?? this.#timeoutMs;
184
- const token = randomBytes(8).toString('hex');
185
- const outPath = path.join(tmpdir(), `dsh-npm-${token}.out`);
186
- const errPath = path.join(tmpdir(), `dsh-npm-${token}.err`);
187
- let outFd;
188
- let errFd;
189
- try {
190
- outFd = openSync(outPath, 'w', 0o600);
191
- errFd = openSync(errPath, 'w', 0o600);
192
- } catch (error) {
193
- if (outFd !== undefined) closeSync(outFd);
194
- throw new NpmError('FAILED', `无法创建 npm 输出临时文件:${error.message}`);
195
- }
196
-
197
- try {
198
- const { command, args: argv } = this.#commandAndArgs(args);
199
- const code = await new Promise((resolvePromise, reject) => {
200
- let child;
201
- try {
202
- child = spawn(command, argv, this.#spawnOptions(options, ['ignore', outFd, errFd]));
203
- } catch (error) {
204
- reject(new NpmError('FAILED', `无法启动 npm:${error.message}`));
205
- return;
206
- }
207
- let settled = false;
208
- let timer = null;
209
- const finish = (fn, value) => {
210
- if (settled) return;
211
- settled = true;
212
- if (timer) clearTimeout(timer);
213
- fn(value);
214
- };
215
- timer = setTimeout(() => {
216
- try { child.kill('SIGKILL'); } catch { /* 已退出 */ }
217
- finish(reject, new NpmError('TIMEOUT', `npm 执行超时(${Math.round(timeoutMs / 1000)} 秒)`));
218
- }, timeoutMs);
219
- child.on('error', (error) => {
220
- finish(reject, new NpmError('FAILED', `npm 启动失败:${error.message}`));
221
- });
222
- child.on('close', (exitCode) => {
223
- finish(resolvePromise, typeof exitCode === 'number' ? exitCode : 1);
224
- });
225
- });
226
-
227
- const stdout = readFileSync(outPath, 'utf8');
228
- const stderr = readFileSync(errPath, 'utf8');
229
- return { stdout, stderr, code };
230
- } finally {
231
- try { closeSync(outFd); } catch { /* 已关闭 */ }
232
- try { closeSync(errFd); } catch { /* 已关闭 */ }
233
- try { unlinkSync(outPath); } catch { /* 已删除 */ }
234
- try { unlinkSync(errPath); } catch { /* 已删除 */ }
235
- }
236
- }
237
- }
238
-
239
- /**
240
- * 解析 `npm pack --json` 的输出。
241
- *
242
- * 有些版本的 npm 会在 JSON 之前混入 prepare 脚本的日志,所以从第一个 `[`
243
- * 或 `{` 开始截取。
244
- *
245
- * @param {string} stdout
246
- * @returns {object|null}
247
- */
248
- export function parsePackJson(stdout) {
249
- const text = String(stdout ?? '');
250
- const bracket = text.indexOf('[');
251
- const brace = text.indexOf('{');
252
- let start;
253
- if (bracket >= 0 && (brace < 0 || bracket < brace)) start = bracket;
254
- else if (brace >= 0) start = brace;
255
- else return null;
256
- try {
257
- const parsed = JSON.parse(text.slice(start));
258
- return Array.isArray(parsed) ? (parsed[0] ?? null) : parsed;
259
- } catch {
260
- return null;
261
- }
262
- }
263
-
264
- /**
265
- * 把 npm pack 的 JSON 投影成界面要的形状,文件按体积倒序。
266
- *
267
- * @param {object|null} raw
268
- * @returns {object}
269
- */
270
- export function mapPackResult(raw) {
271
- const entry = raw && typeof raw === 'object' ? raw : {};
272
- const files = Array.isArray(entry.files) ? entry.files : [];
273
- return {
274
- filename: typeof entry.filename === 'string' ? entry.filename : '',
275
- name: typeof entry.name === 'string' ? entry.name : '',
276
- version: typeof entry.version === 'string' ? entry.version : '',
277
- size: Number.isFinite(entry.size) ? entry.size : null,
278
- unpackedSize: Number.isFinite(entry.unpackedSize) ? entry.unpackedSize : null,
279
- totalFiles: Number.isFinite(entry.totalFiles) ? entry.totalFiles : files.length,
280
- files: files
281
- .map((row) => ({
282
- path: typeof row.path === 'string' ? row.path : '',
283
- size: Number.isFinite(row.size) ? row.size : 0,
284
- }))
285
- .filter((row) => row.path !== '')
286
- .sort((a, b) => b.size - a.size),
287
- };
288
- }