paseo-dsh 0.2.20 → 0.2.22
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/OVERVIEW.md +4 -4
- package/OVERVIEW.zh-CN.md +15 -0
- package/README.md +6 -6
- package/client/dsh-plugins-page.tsx +960 -0
- package/client/guard.tsx +115 -0
- package/client/i18n.ts +100 -0
- package/client/labels.ts +23 -0
- package/client/locales/en.json +215 -0
- package/client/locales/zh-CN.json +213 -0
- package/client/messages.ts +85 -0
- package/client/react-native.d.ts +3 -0
- package/client/settings-screen.tsx +34 -21
- package/client/stream-stats.tsx +71 -48
- package/client/timeline.tsx +442 -123
- package/index.client.tsx +42 -4
- package/index.server.ts +30 -7
- package/package.json +8 -6
- package/paseo-plugin.json +8 -2
- package/server/bootstrap.ts +8 -2
- package/server/bridge-assets.ts +3 -2
- package/server/dsh-plugins-rpc.ts +45 -0
- package/server/dsh-plugins.ts +970 -0
- package/server/dsh-process.ts +61 -11
- package/server/provider.ts +25 -7
- package/server/session.ts +410 -48
- package/server/timeline.ts +69 -4
- package/shared/dsh-plugins-api.ts +175 -0
- package/shared/image-preview.ts +8 -1
- package/shared/settings.ts +14 -43
|
@@ -0,0 +1,970 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bundle management for the DSH profile the Paseo provider drives.
|
|
3
|
+
*
|
|
4
|
+
* The heavy lifting (compatibility preflight, pnpm, rollback, bundle
|
|
5
|
+
* activation) belongs to `dsh plugin`; this module only reads the profile,
|
|
6
|
+
* exposes the bundle inventory, and shells out to that command. The one direct
|
|
7
|
+
* write is enabling/disabling an already-installed bundle, which is a
|
|
8
|
+
* `dsh.profile.bundles` edit under the same `package.json.lock` protocol DSH
|
|
9
|
+
* uses. That keeps this page from inventing a second package manager.
|
|
10
|
+
*
|
|
11
|
+
* @module dsh-paseo/server/dsh-plugins
|
|
12
|
+
*/
|
|
13
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
14
|
+
import { randomUUID } from "node:crypto";
|
|
15
|
+
import {
|
|
16
|
+
closeSync,
|
|
17
|
+
openSync,
|
|
18
|
+
readFileSync,
|
|
19
|
+
renameSync,
|
|
20
|
+
rmSync,
|
|
21
|
+
writeFileSync,
|
|
22
|
+
} from "node:fs";
|
|
23
|
+
import { homedir } from "node:os";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import type {
|
|
26
|
+
BundleInfo,
|
|
27
|
+
BundleRow,
|
|
28
|
+
FailureCode,
|
|
29
|
+
JobKind,
|
|
30
|
+
JobState,
|
|
31
|
+
InspectSpecOutput,
|
|
32
|
+
JobStatus,
|
|
33
|
+
PluginsSnapshot,
|
|
34
|
+
SetEnabledOutput,
|
|
35
|
+
StartJobInput,
|
|
36
|
+
StartJobOutput,
|
|
37
|
+
} from "../shared/dsh-plugins-api";
|
|
38
|
+
import { dshHomeDir, profileDir, profileName } from "./bootstrap";
|
|
39
|
+
import { resolveDshCommand } from "./dsh-command.mjs";
|
|
40
|
+
import { resolveDshBinary } from "./dsh-process";
|
|
41
|
+
|
|
42
|
+
const BASE_BUNDLE = "@deepseek-ai/dsh-base";
|
|
43
|
+
const BRIDGE_BUNDLE = "dsh-paseo-bridge";
|
|
44
|
+
const PROTECTED_BUNDLES = new Set([BASE_BUNDLE, BRIDGE_BUNDLE]);
|
|
45
|
+
|
|
46
|
+
const OUTPUT_LIMIT = 16 * 1024;
|
|
47
|
+
const CAPTURE_LIMIT = 2 * 1024 * 1024;
|
|
48
|
+
const VIEW_TIMEOUT_MS = 20_000;
|
|
49
|
+
const INSTALL_TIMEOUT_MS = 15 * 60_000;
|
|
50
|
+
const LOCK_WAIT_MS = 120_000;
|
|
51
|
+
const MAX_RETAINED_JOBS = 20;
|
|
52
|
+
|
|
53
|
+
interface ProfileManifest {
|
|
54
|
+
dependencies?: Record<string, string>;
|
|
55
|
+
dsh?: {
|
|
56
|
+
profile?: { bundles?: string[] };
|
|
57
|
+
[key: string]: unknown;
|
|
58
|
+
};
|
|
59
|
+
[key: string]: unknown;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
interface RunResult {
|
|
63
|
+
code: number;
|
|
64
|
+
timedOut: boolean;
|
|
65
|
+
stdout: string;
|
|
66
|
+
stderr: string;
|
|
67
|
+
output: string;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
interface Job {
|
|
71
|
+
id: string;
|
|
72
|
+
kind: JobKind;
|
|
73
|
+
state: JobState;
|
|
74
|
+
output: string;
|
|
75
|
+
errorCode?: FailureCode;
|
|
76
|
+
errorDetail?: string;
|
|
77
|
+
updates?: Record<string, string>;
|
|
78
|
+
startedAt: number;
|
|
79
|
+
finishedAt?: number;
|
|
80
|
+
child?: ChildProcess;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export class ManagerError extends Error {
|
|
84
|
+
readonly code: FailureCode;
|
|
85
|
+
readonly detail?: string;
|
|
86
|
+
|
|
87
|
+
constructor(code: FailureCode, detail?: string) {
|
|
88
|
+
super(code);
|
|
89
|
+
this.name = "ManagerError";
|
|
90
|
+
this.code = code;
|
|
91
|
+
this.detail = detail;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function failureOf(error: unknown): { errorCode: FailureCode; errorDetail?: string } {
|
|
96
|
+
if (error instanceof ManagerError) {
|
|
97
|
+
return {
|
|
98
|
+
errorCode: error.code,
|
|
99
|
+
...(error.detail === undefined ? {} : { errorDetail: error.detail }),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
const detail = errorMessage(error);
|
|
103
|
+
return {
|
|
104
|
+
errorCode: "command-failed",
|
|
105
|
+
...(detail === "" ? {} : { errorDetail: detail }),
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export interface DshPluginsOptions {
|
|
110
|
+
profile?: string;
|
|
111
|
+
dir?: string;
|
|
112
|
+
dshHome?: string;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));
|
|
116
|
+
|
|
117
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
118
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function stringValue(value: unknown): string | undefined {
|
|
122
|
+
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function errorMessage(error: unknown): string {
|
|
126
|
+
return error instanceof Error ? error.message : String(error);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function shortDir(dir: string): string {
|
|
130
|
+
const home = homedir();
|
|
131
|
+
if (dir === home) return "~";
|
|
132
|
+
if (dir.startsWith(`${home}/`)) return `~${dir.slice(home.length)}`;
|
|
133
|
+
return dir;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
function parseProfileManifest(path: string, text: string): ProfileManifest {
|
|
137
|
+
try {
|
|
138
|
+
const parsed: unknown = JSON.parse(text);
|
|
139
|
+
if (!isRecord(parsed)) throw new Error("not an object");
|
|
140
|
+
return parsed as ProfileManifest;
|
|
141
|
+
} catch {
|
|
142
|
+
throw new ManagerError("profile-invalid", path);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function readProfileManifest(dir: string): ProfileManifest {
|
|
147
|
+
const path = join(dir, "package.json");
|
|
148
|
+
let text: string;
|
|
149
|
+
try {
|
|
150
|
+
text = readFileSync(path, "utf8");
|
|
151
|
+
} catch {
|
|
152
|
+
throw new ManagerError("profile-unreadable", path);
|
|
153
|
+
}
|
|
154
|
+
return parseProfileManifest(path, text);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* The manifest when the profile has one, `undefined` when it does not exist yet.
|
|
159
|
+
*
|
|
160
|
+
* A profile this plugin has never provisioned has no `package.json`, and
|
|
161
|
+
* `dsh plugin` initializes it on first use. Treating that state like an
|
|
162
|
+
* unreadable file made the first install fail on a profile the page could have
|
|
163
|
+
* created. A file that exists but cannot be read or parsed still fails loudly:
|
|
164
|
+
* that one hides real damage.
|
|
165
|
+
*/
|
|
166
|
+
function readProfileManifestIfPresent(dir: string): ProfileManifest | undefined {
|
|
167
|
+
const path = join(dir, "package.json");
|
|
168
|
+
let text: string;
|
|
169
|
+
try {
|
|
170
|
+
text = readFileSync(path, "utf8");
|
|
171
|
+
} catch (error) {
|
|
172
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
|
|
173
|
+
throw new ManagerError("profile-unreadable", path);
|
|
174
|
+
}
|
|
175
|
+
return parseProfileManifest(path, text);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
function writeProfileManifest(dir: string, manifest: ProfileManifest): void {
|
|
179
|
+
const path = join(dir, "package.json");
|
|
180
|
+
const temporary = join(dir, `.package.json.${process.pid}.${randomUUID()}.tmp`);
|
|
181
|
+
try {
|
|
182
|
+
writeFileSync(temporary, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 });
|
|
183
|
+
renameSync(temporary, path);
|
|
184
|
+
} finally {
|
|
185
|
+
rmSync(temporary, { force: true });
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function selectedBundles(manifest: ProfileManifest): string[] {
|
|
190
|
+
const bundles = manifest.dsh?.profile?.bundles;
|
|
191
|
+
return Array.isArray(bundles)
|
|
192
|
+
? bundles.filter((name): name is string => typeof name === "string")
|
|
193
|
+
: [];
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
function dependencies(manifest: ProfileManifest): Record<string, string> {
|
|
197
|
+
const value = manifest.dependencies;
|
|
198
|
+
if (!isRecord(value)) return {};
|
|
199
|
+
const result: Record<string, string> = {};
|
|
200
|
+
for (const [name, spec] of Object.entries(value)) {
|
|
201
|
+
if (typeof spec === "string") result[name] = spec;
|
|
202
|
+
}
|
|
203
|
+
return result;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function readInstalledPackage(dir: string, name: string): Record<string, unknown> | undefined {
|
|
207
|
+
try {
|
|
208
|
+
const parsed: unknown = JSON.parse(
|
|
209
|
+
readFileSync(join(dir, "node_modules", name, "package.json"), "utf8"),
|
|
210
|
+
);
|
|
211
|
+
return isRecord(parsed) ? parsed : undefined;
|
|
212
|
+
} catch {
|
|
213
|
+
// A broken or absent package is a normal inventory state, not a reason to
|
|
214
|
+
// fail the whole list.
|
|
215
|
+
return undefined;
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function packageDsh(pkg: Record<string, unknown>): Record<string, unknown> | undefined {
|
|
220
|
+
return isRecord(pkg.dsh) ? pkg.dsh : undefined;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function hasBundleManifest(pkg: Record<string, unknown>): boolean {
|
|
224
|
+
const dsh = packageDsh(pkg);
|
|
225
|
+
return isRecord(dsh?.bundle);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function hasClientUi(pkg: Record<string, unknown>): boolean {
|
|
229
|
+
const dsh = packageDsh(pkg);
|
|
230
|
+
return isRecord(dsh?.client);
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
const NODE_PLATFORMS = new Set([
|
|
234
|
+
"aix",
|
|
235
|
+
"android",
|
|
236
|
+
"cygwin",
|
|
237
|
+
"darwin",
|
|
238
|
+
"freebsd",
|
|
239
|
+
"haiku",
|
|
240
|
+
"linux",
|
|
241
|
+
"netbsd",
|
|
242
|
+
"openbsd",
|
|
243
|
+
"sunos",
|
|
244
|
+
"win32",
|
|
245
|
+
]);
|
|
246
|
+
|
|
247
|
+
/** Whether this host may load the bundle's optional `dsh.bundle.platforms` list. */
|
|
248
|
+
function bundlePlatformSupport(
|
|
249
|
+
pkg: Record<string, unknown>,
|
|
250
|
+
): { supported: true } | { supported: false; reason: string } {
|
|
251
|
+
const bundle = packageDsh(pkg)?.bundle;
|
|
252
|
+
if (!isRecord(bundle) || bundle.platforms === undefined) return { supported: true };
|
|
253
|
+
const platforms = bundle.platforms;
|
|
254
|
+
if (
|
|
255
|
+
!Array.isArray(platforms)
|
|
256
|
+
|| platforms.length === 0
|
|
257
|
+
|| !platforms.every((value) => typeof value === "string" && NODE_PLATFORMS.has(value))
|
|
258
|
+
) {
|
|
259
|
+
return { supported: false, reason: "" };
|
|
260
|
+
}
|
|
261
|
+
if (!platforms.includes(process.platform)) {
|
|
262
|
+
return { supported: false, reason: platforms.join(", ") };
|
|
263
|
+
}
|
|
264
|
+
return { supported: true };
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Best-effort row ids from a bundle's patch file; a parse failure yields []. */
|
|
268
|
+
function readRows(packageDir: string, pkg: Record<string, unknown>): BundleRow[] {
|
|
269
|
+
const bundle = packageDsh(pkg)?.bundle;
|
|
270
|
+
if (!isRecord(bundle)) return [];
|
|
271
|
+
const patch = bundle.patch;
|
|
272
|
+
const paths = typeof patch === "string"
|
|
273
|
+
? [patch]
|
|
274
|
+
: Array.isArray(patch)
|
|
275
|
+
? patch.filter((entry): entry is string => typeof entry === "string")
|
|
276
|
+
: [];
|
|
277
|
+
const rows: BundleRow[] = [];
|
|
278
|
+
const seen = new Set<string>();
|
|
279
|
+
for (const relativePath of paths) {
|
|
280
|
+
try {
|
|
281
|
+
const text = readFileSync(join(packageDir, relativePath), "utf8");
|
|
282
|
+
const pattern = /^\s*-\s+id:\s*["']?([A-Za-z0-9._:@/-]+)["']?\s*$/gm;
|
|
283
|
+
let match: RegExpExecArray | null;
|
|
284
|
+
while ((match = pattern.exec(text)) !== null) {
|
|
285
|
+
const id = match[1];
|
|
286
|
+
if (!seen.has(id)) {
|
|
287
|
+
seen.add(id);
|
|
288
|
+
rows.push({ id });
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
} catch {
|
|
292
|
+
// The patch may be generated or absent; rows are display-only here.
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
return rows;
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function isRegistrySpec(spec: string): boolean {
|
|
299
|
+
const value = spec.trim();
|
|
300
|
+
if (value === "" || value.length > 214) return false;
|
|
301
|
+
if (value.startsWith(".") || value.startsWith("/") || value.startsWith("~")) return false;
|
|
302
|
+
if (value.includes("\\") || value.includes(":") || value.includes("..")) return false;
|
|
303
|
+
if (/\s/.test(value)) return false;
|
|
304
|
+
return /^(@[a-z0-9._~-]+\/)?[a-z0-9._~-]+(?:@[a-z0-9^~<>=.*+|-]+)?$/i.test(value);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Dependency specs are version ranges, not package names. Keep this separate
|
|
309
|
+
* from `isRegistrySpec`, which validates the spec typed into the install box.
|
|
310
|
+
*/
|
|
311
|
+
function isRegistryDependencySpec(spec: string): boolean {
|
|
312
|
+
const value = spec.trim();
|
|
313
|
+
if (value === "" || value.length > 214) return false;
|
|
314
|
+
if (/^(?:file|link|git|github|https?|ssh|workspace|portal|npm):/i.test(value)) return false;
|
|
315
|
+
if (value.includes("\\") || value.includes("/") || value.includes("..")) return false;
|
|
316
|
+
if (/\s/.test(value)) return false;
|
|
317
|
+
if (value === "latest" || value === "next" || value === "*") return true;
|
|
318
|
+
return /^[\^~<>=v]?\d/.test(value);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
function registryName(spec: string): string {
|
|
322
|
+
const value = spec.trim();
|
|
323
|
+
const at = value.lastIndexOf("@");
|
|
324
|
+
return at > 0 ? value.slice(0, at) : value;
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
function versionParts(version: string): { numbers: number[]; prerelease?: string } | undefined {
|
|
328
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?/.exec(version.trim());
|
|
329
|
+
if (!match) return undefined;
|
|
330
|
+
return {
|
|
331
|
+
numbers: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
332
|
+
prerelease: match[4],
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function isNewer(candidate: string, current: string): boolean {
|
|
337
|
+
const next = versionParts(candidate);
|
|
338
|
+
const previous = versionParts(current);
|
|
339
|
+
if (!next || !previous) return candidate !== current;
|
|
340
|
+
for (let index = 0; index < 3; index += 1) {
|
|
341
|
+
if (next.numbers[index] !== previous.numbers[index]) {
|
|
342
|
+
return next.numbers[index] > previous.numbers[index];
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
if (next.prerelease === previous.prerelease) return false;
|
|
346
|
+
if (next.prerelease === undefined) return true;
|
|
347
|
+
if (previous.prerelease === undefined) return false;
|
|
348
|
+
return next.prerelease > previous.prerelease;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
function parseJsonLoose(text: string): unknown {
|
|
352
|
+
const trimmed = text.trim();
|
|
353
|
+
if (trimmed === "") throw new Error("empty JSON");
|
|
354
|
+
try {
|
|
355
|
+
return JSON.parse(trimmed) as unknown;
|
|
356
|
+
} catch {
|
|
357
|
+
const startObject = trimmed.indexOf("{");
|
|
358
|
+
const startArray = trimmed.indexOf("[");
|
|
359
|
+
const start = startObject < 0
|
|
360
|
+
? startArray
|
|
361
|
+
: startArray < 0
|
|
362
|
+
? startObject
|
|
363
|
+
: Math.min(startObject, startArray);
|
|
364
|
+
if (start < 0) throw new Error("no JSON value");
|
|
365
|
+
const endObject = trimmed.lastIndexOf("}");
|
|
366
|
+
const endArray = trimmed.lastIndexOf("]");
|
|
367
|
+
const end = Math.max(endObject, endArray);
|
|
368
|
+
if (end <= start) throw new Error("no complete JSON value");
|
|
369
|
+
return JSON.parse(trimmed.slice(start, end + 1)) as unknown;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function lastLines(text: string, count: number): string {
|
|
374
|
+
const lines = text.replace(/\r\n/g, "\n").split("\n");
|
|
375
|
+
while (lines.length > 0 && lines[lines.length - 1].trim() === "") lines.pop();
|
|
376
|
+
return lines.slice(-count).join("\n").trim();
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function isProcessAlive(pid: number): boolean {
|
|
380
|
+
try {
|
|
381
|
+
process.kill(pid, 0);
|
|
382
|
+
return true;
|
|
383
|
+
} catch (error) {
|
|
384
|
+
return (error as NodeJS.ErrnoException).code === "EPERM";
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function readLockPid(lockPath: string): number | undefined {
|
|
389
|
+
try {
|
|
390
|
+
const pid = Number.parseInt(readFileSync(lockPath, "utf8").trim(), 10);
|
|
391
|
+
return Number.isFinite(pid) && pid > 0 ? pid : undefined;
|
|
392
|
+
} catch {
|
|
393
|
+
return undefined;
|
|
394
|
+
}
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
async function withPackageLock<T>(dir: string, action: () => Promise<T> | T): Promise<T> {
|
|
398
|
+
const lockPath = join(dir, "package.json.lock");
|
|
399
|
+
const deadline = Date.now() + LOCK_WAIT_MS;
|
|
400
|
+
let acquired = false;
|
|
401
|
+
while (!acquired) {
|
|
402
|
+
let fd: number | undefined;
|
|
403
|
+
try {
|
|
404
|
+
fd = openSync(lockPath, "wx", 0o600);
|
|
405
|
+
writeFileSync(fd, `${process.pid}\n`);
|
|
406
|
+
acquired = true;
|
|
407
|
+
} catch (error) {
|
|
408
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
409
|
+
const holder = readLockPid(lockPath);
|
|
410
|
+
if (holder !== undefined && !isProcessAlive(holder)) {
|
|
411
|
+
rmSync(lockPath, { force: true });
|
|
412
|
+
continue;
|
|
413
|
+
}
|
|
414
|
+
if (Date.now() >= deadline) {
|
|
415
|
+
throw new ManagerError("lock-timeout", `package.json.lock (${Math.round(LOCK_WAIT_MS / 1000)}s)`);
|
|
416
|
+
}
|
|
417
|
+
await sleep(100);
|
|
418
|
+
} finally {
|
|
419
|
+
if (fd !== undefined) closeSync(fd);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
try {
|
|
424
|
+
return await action();
|
|
425
|
+
} finally {
|
|
426
|
+
// Release only a lock this process still holds. DSH takes a dead holder's
|
|
427
|
+
// lock over, so an unconditional unlink could delete the lock its new
|
|
428
|
+
// owner had just created and let two writers into the manifest.
|
|
429
|
+
const holder = readLockPid(lockPath);
|
|
430
|
+
if (holder === undefined || holder === process.pid) rmSync(lockPath, { force: true });
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
function killTree(child: ChildProcess): void {
|
|
435
|
+
if (child.pid === undefined) return;
|
|
436
|
+
const pid = child.pid;
|
|
437
|
+
const signal = (name: NodeJS.Signals) => {
|
|
438
|
+
try {
|
|
439
|
+
if (process.platform === "win32") child.kill(name);
|
|
440
|
+
else process.kill(-pid, name);
|
|
441
|
+
} catch {
|
|
442
|
+
try {
|
|
443
|
+
child.kill(name);
|
|
444
|
+
} catch {
|
|
445
|
+
// The process may already be gone.
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
};
|
|
449
|
+
signal("SIGTERM");
|
|
450
|
+
const timer = setTimeout(() => signal("SIGKILL"), 3_000);
|
|
451
|
+
timer.unref();
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export class DshPlugins {
|
|
455
|
+
readonly profile: string;
|
|
456
|
+
readonly dir: string;
|
|
457
|
+
readonly dshHome: string;
|
|
458
|
+
|
|
459
|
+
#jobs = new Map<string, Job>();
|
|
460
|
+
#activeJobId: string | undefined;
|
|
461
|
+
#updates = new Map<string, string>();
|
|
462
|
+
#dshVersionPromise: Promise<string | undefined> | undefined;
|
|
463
|
+
#children = new Set<ChildProcess>();
|
|
464
|
+
#disposed = false;
|
|
465
|
+
|
|
466
|
+
constructor(options: DshPluginsOptions = {}) {
|
|
467
|
+
this.profile = options.profile ?? profileName();
|
|
468
|
+
this.dshHome = options.dshHome ?? dshHomeDir();
|
|
469
|
+
this.dir = options.dir ?? profileDir(this.profile, this.dshHome);
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Read the profile inventory. Never starts a package operation. */
|
|
473
|
+
async list(): Promise<PluginsSnapshot> {
|
|
474
|
+
try {
|
|
475
|
+
return await this.#snapshot();
|
|
476
|
+
} catch (error) {
|
|
477
|
+
const failure = failureOf(error);
|
|
478
|
+
return {
|
|
479
|
+
profile: this.profile,
|
|
480
|
+
dir: this.dir,
|
|
481
|
+
displayDir: shortDir(this.dir),
|
|
482
|
+
bundles: [],
|
|
483
|
+
busy: false,
|
|
484
|
+
...failure,
|
|
485
|
+
};
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
async #snapshot(): Promise<PluginsSnapshot> {
|
|
490
|
+
const manifest = readProfileManifest(this.dir);
|
|
491
|
+
const deps = dependencies(manifest);
|
|
492
|
+
const selected = selectedBundles(manifest);
|
|
493
|
+
const names: string[] = [];
|
|
494
|
+
const add = (name: string) => {
|
|
495
|
+
if (!names.includes(name)) names.push(name);
|
|
496
|
+
};
|
|
497
|
+
add(BASE_BUNDLE);
|
|
498
|
+
add(BRIDGE_BUNDLE);
|
|
499
|
+
selected.forEach(add);
|
|
500
|
+
Object.keys(deps).forEach(add);
|
|
501
|
+
|
|
502
|
+
const dshVersion = await this.#getDshVersion();
|
|
503
|
+
const bundles = names.map((name) => this.#describe(name, deps[name], selected, dshVersion));
|
|
504
|
+
const activeJob = this.#activeJobId === undefined ? undefined : this.#jobs.get(this.#activeJobId);
|
|
505
|
+
return {
|
|
506
|
+
profile: this.profile,
|
|
507
|
+
dir: this.dir,
|
|
508
|
+
displayDir: shortDir(this.dir),
|
|
509
|
+
bundles,
|
|
510
|
+
busy: activeJob !== undefined,
|
|
511
|
+
...(activeJob === undefined ? {} : {
|
|
512
|
+
activeJobId: activeJob.id,
|
|
513
|
+
activeJobKind: activeJob.kind,
|
|
514
|
+
}),
|
|
515
|
+
};
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/**
|
|
519
|
+
* Enable or disable an installed bundle by editing only the ordered
|
|
520
|
+
* `dsh.profile.bundles` list. Dependencies stay installed, so disabling is
|
|
521
|
+
* reversible without a download.
|
|
522
|
+
*/
|
|
523
|
+
async setEnabled(name: string, enabled: boolean): Promise<SetEnabledOutput> {
|
|
524
|
+
const bundleName = name.trim();
|
|
525
|
+
if (bundleName === "") throw new ManagerError("invalid-name");
|
|
526
|
+
if (PROTECTED_BUNDLES.has(bundleName)) {
|
|
527
|
+
throw new ManagerError("protected", bundleName);
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
return withPackageLock(this.dir, () => {
|
|
531
|
+
const manifest = readProfileManifest(this.dir);
|
|
532
|
+
const deps = dependencies(manifest);
|
|
533
|
+
const current = selectedBundles(manifest);
|
|
534
|
+
if (enabled) {
|
|
535
|
+
if (deps[bundleName] === undefined) {
|
|
536
|
+
throw new ManagerError("not-installed", bundleName);
|
|
537
|
+
}
|
|
538
|
+
const installed = readInstalledPackage(this.dir, bundleName);
|
|
539
|
+
if (installed === undefined || !hasBundleManifest(installed)) {
|
|
540
|
+
throw new ManagerError("not-a-bundle", bundleName);
|
|
541
|
+
}
|
|
542
|
+
const platform = bundlePlatformSupport(installed);
|
|
543
|
+
if (!platform.supported) throw new ManagerError("invalid-platform", platform.reason);
|
|
544
|
+
if (current.includes(bundleName)) {
|
|
545
|
+
return { ok: true, changed: false, enabled: true };
|
|
546
|
+
}
|
|
547
|
+
current.push(bundleName);
|
|
548
|
+
} else {
|
|
549
|
+
if (!current.includes(bundleName)) {
|
|
550
|
+
return { ok: true, changed: false, enabled: false };
|
|
551
|
+
}
|
|
552
|
+
const index = current.indexOf(bundleName);
|
|
553
|
+
current.splice(index, 1);
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const dsh = isRecord(manifest.dsh) ? manifest.dsh : {};
|
|
557
|
+
const profile = isRecord(dsh.profile) ? dsh.profile : {};
|
|
558
|
+
manifest.dsh = { ...dsh, profile: { ...profile, bundles: current } };
|
|
559
|
+
writeProfileManifest(this.dir, manifest);
|
|
560
|
+
return { ok: true, changed: true, enabled };
|
|
561
|
+
});
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** Inspect an npm registry spec before the user commits to installing it. */
|
|
565
|
+
async inspectSpec(spec: string): Promise<InspectSpecOutput> {
|
|
566
|
+
const value = spec.trim();
|
|
567
|
+
if (!isRegistrySpec(value)) {
|
|
568
|
+
return { ok: false, client: false, errorCode: "invalid-spec" };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
let result: RunResult;
|
|
572
|
+
try {
|
|
573
|
+
result = await this.#runPlugin(["view", value, "--json"], VIEW_TIMEOUT_MS);
|
|
574
|
+
} catch (error) {
|
|
575
|
+
return { ok: false, client: false, ...failureOf(error) };
|
|
576
|
+
}
|
|
577
|
+
if (result.code !== 0) {
|
|
578
|
+
return { ok: false, client: false, ...this.#commandFailure(result) };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
let manifest: unknown;
|
|
582
|
+
try {
|
|
583
|
+
manifest = parseJsonLoose(result.stdout);
|
|
584
|
+
} catch {
|
|
585
|
+
return { ok: false, client: false, errorCode: "registry-unreadable" };
|
|
586
|
+
}
|
|
587
|
+
if (!isRecord(manifest)) {
|
|
588
|
+
return { ok: false, client: false, errorCode: "registry-invalid" };
|
|
589
|
+
}
|
|
590
|
+
const dsh = packageDsh(manifest);
|
|
591
|
+
if (!isRecord(dsh?.bundle)) {
|
|
592
|
+
return { ok: false, client: false, errorCode: "not-a-bundle" };
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
return {
|
|
596
|
+
ok: true,
|
|
597
|
+
name: stringValue(manifest.name) ?? registryName(value),
|
|
598
|
+
version: stringValue(manifest.version),
|
|
599
|
+
description: stringValue(manifest.description) ?? "",
|
|
600
|
+
client: hasClientUi(manifest),
|
|
601
|
+
};
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/** Start one package operation. At most one may run at a time. */
|
|
605
|
+
startJob(input: StartJobInput): StartJobOutput {
|
|
606
|
+
if (this.#disposed) throw new ManagerError("disposed");
|
|
607
|
+
if (this.#activeJobId !== undefined) {
|
|
608
|
+
throw new ManagerError("busy", this.#activeJobId);
|
|
609
|
+
}
|
|
610
|
+
const job: Job = {
|
|
611
|
+
id: randomUUID(),
|
|
612
|
+
kind: input.kind,
|
|
613
|
+
state: "running",
|
|
614
|
+
output: "",
|
|
615
|
+
startedAt: Date.now(),
|
|
616
|
+
};
|
|
617
|
+
this.#jobs.set(job.id, job);
|
|
618
|
+
this.#activeJobId = job.id;
|
|
619
|
+
|
|
620
|
+
void this.#runJob(job, input)
|
|
621
|
+
.then(() => {
|
|
622
|
+
job.state = "succeeded";
|
|
623
|
+
})
|
|
624
|
+
.catch((error) => {
|
|
625
|
+
job.state = "failed";
|
|
626
|
+
const failure = failureOf(error);
|
|
627
|
+
job.errorCode = failure.errorCode;
|
|
628
|
+
job.errorDetail = failure.errorDetail;
|
|
629
|
+
})
|
|
630
|
+
.finally(() => {
|
|
631
|
+
job.finishedAt = Date.now();
|
|
632
|
+
if (this.#activeJobId === job.id) this.#activeJobId = undefined;
|
|
633
|
+
this.#pruneJobs();
|
|
634
|
+
});
|
|
635
|
+
|
|
636
|
+
return { ok: true, id: job.id };
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
status(id: string): JobStatus {
|
|
640
|
+
const job = this.#jobs.get(id);
|
|
641
|
+
if (job === undefined) throw new ManagerError("job-missing", id);
|
|
642
|
+
return {
|
|
643
|
+
id: job.id,
|
|
644
|
+
kind: job.kind,
|
|
645
|
+
state: job.state,
|
|
646
|
+
output: job.output,
|
|
647
|
+
...(job.errorCode === undefined ? {} : { errorCode: job.errorCode }),
|
|
648
|
+
...(job.errorDetail === undefined ? {} : { errorDetail: job.errorDetail }),
|
|
649
|
+
...(job.updates === undefined ? {} : { updates: job.updates }),
|
|
650
|
+
startedAt: job.startedAt,
|
|
651
|
+
...(job.finishedAt === undefined ? {} : { finishedAt: job.finishedAt }),
|
|
652
|
+
};
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/** Kill running children when Paseo unloads the plugin. */
|
|
656
|
+
dispose(): void {
|
|
657
|
+
this.#disposed = true;
|
|
658
|
+
for (const child of this.#children) killTree(child);
|
|
659
|
+
this.#children.clear();
|
|
660
|
+
if (this.#activeJobId !== undefined) {
|
|
661
|
+
const job = this.#jobs.get(this.#activeJobId);
|
|
662
|
+
if (job !== undefined) {
|
|
663
|
+
if (job.child !== undefined) killTree(job.child);
|
|
664
|
+
job.state = "failed";
|
|
665
|
+
job.errorCode = "disposed";
|
|
666
|
+
job.finishedAt = Date.now();
|
|
667
|
+
}
|
|
668
|
+
this.#activeJobId = undefined;
|
|
669
|
+
}
|
|
670
|
+
this.#jobs.clear();
|
|
671
|
+
}
|
|
672
|
+
|
|
673
|
+
#describe(
|
|
674
|
+
name: string,
|
|
675
|
+
spec: string | undefined,
|
|
676
|
+
selected: string[],
|
|
677
|
+
dshVersion: string | undefined,
|
|
678
|
+
): BundleInfo {
|
|
679
|
+
const official = name === BASE_BUNDLE;
|
|
680
|
+
const protectedBundle = PROTECTED_BUNDLES.has(name);
|
|
681
|
+
const pkg = official ? undefined : readInstalledPackage(this.dir, name);
|
|
682
|
+
const installed = official || pkg !== undefined;
|
|
683
|
+
const bundleManifest = official || (pkg !== undefined && hasBundleManifest(pkg));
|
|
684
|
+
const enabled = selected.includes(name);
|
|
685
|
+
const version = official
|
|
686
|
+
? dshVersion
|
|
687
|
+
: pkg === undefined
|
|
688
|
+
? undefined
|
|
689
|
+
: stringValue(pkg.version);
|
|
690
|
+
const kind: BundleInfo["kind"] = !installed
|
|
691
|
+
? "missing"
|
|
692
|
+
: bundleManifest || enabled
|
|
693
|
+
? "bundle"
|
|
694
|
+
: "dependency";
|
|
695
|
+
const client = pkg !== undefined && hasClientUi(pkg);
|
|
696
|
+
const platform = pkg === undefined ? { supported: true as const } : bundlePlatformSupport(pkg);
|
|
697
|
+
const rows = pkg === undefined ? [] : readRows(join(this.dir, "node_modules", name), pkg);
|
|
698
|
+
const description = official
|
|
699
|
+
? ""
|
|
700
|
+
: pkg !== undefined
|
|
701
|
+
? stringValue(pkg.description) ?? ""
|
|
702
|
+
: "";
|
|
703
|
+
const updatable = !official
|
|
704
|
+
&& !protectedBundle
|
|
705
|
+
&& installed
|
|
706
|
+
&& bundleManifest
|
|
707
|
+
&& version !== undefined
|
|
708
|
+
&& versionParts(version) !== undefined
|
|
709
|
+
&& spec !== undefined
|
|
710
|
+
&& isRegistryDependencySpec(spec);
|
|
711
|
+
const cachedUpdate = this.#updates.get(name);
|
|
712
|
+
const update = cachedUpdate !== undefined
|
|
713
|
+
&& version !== undefined
|
|
714
|
+
&& isNewer(cachedUpdate, version)
|
|
715
|
+
? cachedUpdate
|
|
716
|
+
: undefined;
|
|
717
|
+
|
|
718
|
+
return {
|
|
719
|
+
name,
|
|
720
|
+
...(version === undefined ? {} : { version }),
|
|
721
|
+
description,
|
|
722
|
+
enabled,
|
|
723
|
+
installed,
|
|
724
|
+
kind,
|
|
725
|
+
protected: protectedBundle,
|
|
726
|
+
official,
|
|
727
|
+
client,
|
|
728
|
+
platformSupported: platform.supported,
|
|
729
|
+
...(platform.supported ? {} : { platformReason: platform.reason }),
|
|
730
|
+
removable: !protectedBundle && installed && spec !== undefined,
|
|
731
|
+
updatable,
|
|
732
|
+
...(update === undefined ? {} : { update }),
|
|
733
|
+
rows,
|
|
734
|
+
};
|
|
735
|
+
}
|
|
736
|
+
|
|
737
|
+
async #runJob(job: Job, input: StartJobInput): Promise<void> {
|
|
738
|
+
switch (input.kind) {
|
|
739
|
+
case "install": {
|
|
740
|
+
const spec = input.spec.trim();
|
|
741
|
+
const inspected = await this.inspectSpec(spec);
|
|
742
|
+
if (!inspected.ok) {
|
|
743
|
+
throw new ManagerError(inspected.errorCode ?? "command-failed", inspected.errorDetail);
|
|
744
|
+
}
|
|
745
|
+
const name = inspected.name ?? registryName(spec);
|
|
746
|
+
const manifest = readProfileManifestIfPresent(this.dir);
|
|
747
|
+
if (manifest !== undefined && dependencies(manifest)[name] !== undefined) {
|
|
748
|
+
throw new ManagerError("already-installed", name);
|
|
749
|
+
}
|
|
750
|
+
const result = await this.#runPlugin(
|
|
751
|
+
["add", "--save-exact", spec],
|
|
752
|
+
INSTALL_TIMEOUT_MS,
|
|
753
|
+
job,
|
|
754
|
+
);
|
|
755
|
+
if (result.code !== 0) throw new ManagerError("command-failed", this.#commandFailure(result).errorDetail);
|
|
756
|
+
return;
|
|
757
|
+
}
|
|
758
|
+
case "remove": {
|
|
759
|
+
const name = input.name.trim();
|
|
760
|
+
if (PROTECTED_BUNDLES.has(name)) {
|
|
761
|
+
throw new ManagerError("protected", name);
|
|
762
|
+
}
|
|
763
|
+
const manifest = readProfileManifest(this.dir);
|
|
764
|
+
if (dependencies(manifest)[name] === undefined) {
|
|
765
|
+
throw new ManagerError("not-removable", name);
|
|
766
|
+
}
|
|
767
|
+
const result = await this.#runPlugin(["remove", name], INSTALL_TIMEOUT_MS, job);
|
|
768
|
+
if (result.code !== 0) throw new ManagerError("command-failed", this.#commandFailure(result).errorDetail);
|
|
769
|
+
return;
|
|
770
|
+
}
|
|
771
|
+
case "update": {
|
|
772
|
+
const name = input.name.trim();
|
|
773
|
+
const version = input.version.trim();
|
|
774
|
+
if (PROTECTED_BUNDLES.has(name)) {
|
|
775
|
+
throw new ManagerError("protected", name);
|
|
776
|
+
}
|
|
777
|
+
if (!isRegistrySpec(`${name}@${version}`)) {
|
|
778
|
+
throw new ManagerError("invalid-version", version);
|
|
779
|
+
}
|
|
780
|
+
const manifest = readProfileManifest(this.dir);
|
|
781
|
+
if (dependencies(manifest)[name] === undefined) {
|
|
782
|
+
throw new ManagerError("not-in-dependencies", name);
|
|
783
|
+
}
|
|
784
|
+
const installed = readInstalledPackage(this.dir, name);
|
|
785
|
+
if (installed === undefined || !hasBundleManifest(installed)) {
|
|
786
|
+
throw new ManagerError("not-a-bundle", name);
|
|
787
|
+
}
|
|
788
|
+
const result = await this.#runPlugin(
|
|
789
|
+
["add", "--save-exact", `${name}@${version}`],
|
|
790
|
+
INSTALL_TIMEOUT_MS,
|
|
791
|
+
job,
|
|
792
|
+
);
|
|
793
|
+
if (result.code !== 0) throw new ManagerError("command-failed", this.#commandFailure(result).errorDetail);
|
|
794
|
+
this.#updates.delete(name);
|
|
795
|
+
return;
|
|
796
|
+
}
|
|
797
|
+
case "check":
|
|
798
|
+
await this.#checkUpdates(job);
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
async #checkUpdates(job: Job): Promise<void> {
|
|
804
|
+
const snapshot = await this.list();
|
|
805
|
+
if (snapshot.errorCode !== undefined) {
|
|
806
|
+
throw new ManagerError(snapshot.errorCode, snapshot.errorDetail);
|
|
807
|
+
}
|
|
808
|
+
const candidates = snapshot.bundles.filter((bundle) => bundle.updatable);
|
|
809
|
+
this.#updates.clear();
|
|
810
|
+
if (candidates.length === 0) {
|
|
811
|
+
job.updates = {};
|
|
812
|
+
return;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
const failures: string[] = [];
|
|
816
|
+
for (const bundle of candidates) {
|
|
817
|
+
const result = await this.#runPlugin(
|
|
818
|
+
["view", bundle.name, "version", "--json"],
|
|
819
|
+
VIEW_TIMEOUT_MS,
|
|
820
|
+
);
|
|
821
|
+
if (result.code !== 0) {
|
|
822
|
+
failures.push(`${bundle.name}: ${lastLines(result.output, 4)}`);
|
|
823
|
+
continue;
|
|
824
|
+
}
|
|
825
|
+
let latest: string | undefined;
|
|
826
|
+
try {
|
|
827
|
+
const parsed = parseJsonLoose(result.stdout);
|
|
828
|
+
latest = typeof parsed === "string"
|
|
829
|
+
? parsed
|
|
830
|
+
: isRecord(parsed)
|
|
831
|
+
? stringValue(parsed.version)
|
|
832
|
+
: undefined;
|
|
833
|
+
} catch {
|
|
834
|
+
latest = undefined;
|
|
835
|
+
}
|
|
836
|
+
if (latest === undefined) {
|
|
837
|
+
failures.push(`${bundle.name}: unreadable version`);
|
|
838
|
+
continue;
|
|
839
|
+
}
|
|
840
|
+
if (bundle.version !== undefined && isNewer(latest, bundle.version)) {
|
|
841
|
+
this.#updates.set(bundle.name, latest);
|
|
842
|
+
}
|
|
843
|
+
}
|
|
844
|
+
job.updates = Object.fromEntries(this.#updates);
|
|
845
|
+
if (failures.length > 0) {
|
|
846
|
+
throw new ManagerError("check-failed", failures.join("\n"));
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
|
|
850
|
+
#commandFailure(result: RunResult): { errorCode: "command-failed"; errorDetail: string } {
|
|
851
|
+
const reason = result.timedOut ? "timeout" : `exit ${result.code}`;
|
|
852
|
+
const tail = lastLines(result.output, 20);
|
|
853
|
+
return {
|
|
854
|
+
errorCode: "command-failed",
|
|
855
|
+
errorDetail: tail === "" ? reason : `${reason}\n${tail}`,
|
|
856
|
+
};
|
|
857
|
+
}
|
|
858
|
+
|
|
859
|
+
async #getDshVersion(): Promise<string | undefined> {
|
|
860
|
+
this.#dshVersionPromise ??= this.#readDshVersion();
|
|
861
|
+
return this.#dshVersionPromise;
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
async #readDshVersion(): Promise<string | undefined> {
|
|
865
|
+
try {
|
|
866
|
+
const result = await this.#runDsh(["--version"], 5_000);
|
|
867
|
+
const match = /(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)/.exec(`${result.stdout}\n${result.output}`);
|
|
868
|
+
return match?.[1];
|
|
869
|
+
} catch {
|
|
870
|
+
return undefined;
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
#runPlugin(args: string[], timeoutMs: number, job?: Job): Promise<RunResult> {
|
|
875
|
+
return this.#runDsh(["plugin", "--profile", this.profile, ...args], timeoutMs, job);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
#runDsh(args: string[], timeoutMs: number, job?: Job): Promise<RunResult> {
|
|
879
|
+
if (this.#disposed) {
|
|
880
|
+
return Promise.reject(new ManagerError("disposed"));
|
|
881
|
+
}
|
|
882
|
+
return new Promise((resolve, reject) => {
|
|
883
|
+
let child: ChildProcess;
|
|
884
|
+
const env = { ...process.env, DSH_HOME: this.dshHome };
|
|
885
|
+
const launch = resolveDshCommand(resolveDshBinary(env), env, this.dir);
|
|
886
|
+
try {
|
|
887
|
+
child = spawn(launch.command, [...launch.args, ...args], {
|
|
888
|
+
cwd: this.dir,
|
|
889
|
+
env,
|
|
890
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
891
|
+
detached: process.platform !== "win32",
|
|
892
|
+
});
|
|
893
|
+
} catch (error) {
|
|
894
|
+
reject(new ManagerError("spawn-failed", `${launch.command}: ${errorMessage(error)}`));
|
|
895
|
+
return;
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
this.#children.add(child);
|
|
899
|
+
if (job !== undefined) job.child = child;
|
|
900
|
+
|
|
901
|
+
let stdout = "";
|
|
902
|
+
let stderr = "";
|
|
903
|
+
let output = "";
|
|
904
|
+
let timedOut = false;
|
|
905
|
+
let settled = false;
|
|
906
|
+
const timer = setTimeout(() => {
|
|
907
|
+
timedOut = true;
|
|
908
|
+
killTree(child);
|
|
909
|
+
const fallback = setTimeout(() => {
|
|
910
|
+
finish({ code: 124, timedOut: true, stdout, stderr, output });
|
|
911
|
+
}, 5_000);
|
|
912
|
+
fallback.unref();
|
|
913
|
+
}, timeoutMs);
|
|
914
|
+
timer.unref();
|
|
915
|
+
|
|
916
|
+
const push = (chunk: string): void => {
|
|
917
|
+
output = (output + chunk).slice(-OUTPUT_LIMIT);
|
|
918
|
+
if (job !== undefined) {
|
|
919
|
+
job.output = `${job.output}${chunk}`.slice(-OUTPUT_LIMIT);
|
|
920
|
+
}
|
|
921
|
+
};
|
|
922
|
+
const finish = (result: RunResult): void => {
|
|
923
|
+
if (settled) return;
|
|
924
|
+
settled = true;
|
|
925
|
+
clearTimeout(timer);
|
|
926
|
+
if (job !== undefined && job.child === child) job.child = undefined;
|
|
927
|
+
resolve(result);
|
|
928
|
+
};
|
|
929
|
+
const fail = (error: Error): void => {
|
|
930
|
+
if (settled) return;
|
|
931
|
+
settled = true;
|
|
932
|
+
clearTimeout(timer);
|
|
933
|
+
if (job !== undefined && job.child === child) job.child = undefined;
|
|
934
|
+
reject(error);
|
|
935
|
+
};
|
|
936
|
+
|
|
937
|
+
child.stdout?.setEncoding("utf8");
|
|
938
|
+
child.stderr?.setEncoding("utf8");
|
|
939
|
+
child.stdout?.on("data", (chunk: string) => {
|
|
940
|
+
stdout = (stdout + chunk).slice(-CAPTURE_LIMIT);
|
|
941
|
+
push(chunk);
|
|
942
|
+
});
|
|
943
|
+
child.stderr?.on("data", (chunk: string) => {
|
|
944
|
+
stderr = (stderr + chunk).slice(-CAPTURE_LIMIT);
|
|
945
|
+
push(chunk);
|
|
946
|
+
});
|
|
947
|
+
child.on("error", (error) => {
|
|
948
|
+
this.#children.delete(child);
|
|
949
|
+
fail(new ManagerError("spawn-failed", `${launch.command}: ${error.message}`));
|
|
950
|
+
});
|
|
951
|
+
child.on("close", (code) => {
|
|
952
|
+
this.#children.delete(child);
|
|
953
|
+
finish({
|
|
954
|
+
code: code ?? (timedOut ? 124 : 1),
|
|
955
|
+
timedOut,
|
|
956
|
+
stdout,
|
|
957
|
+
stderr,
|
|
958
|
+
output,
|
|
959
|
+
});
|
|
960
|
+
});
|
|
961
|
+
});
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
#pruneJobs(): void {
|
|
965
|
+
for (const [id] of this.#jobs) {
|
|
966
|
+
if (this.#jobs.size <= MAX_RETAINED_JOBS) break;
|
|
967
|
+
if (id !== this.#activeJobId) this.#jobs.delete(id);
|
|
968
|
+
}
|
|
969
|
+
}
|
|
970
|
+
}
|