@twinsearth/timemachine-dsh-plugin 0.0.0-stage → 0.1.1

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/src/plugin.mjs ADDED
@@ -0,0 +1,213 @@
1
+ /**
2
+ * Server half of @twinsearth/timemachine-dsh-plugin.
3
+ *
4
+ * The plugin needs no Cordis service to mount. When the host exposes a
5
+ * Connection service the panel routes are registered; otherwise it still loads
6
+ * and reports why the routes are absent.
7
+ *
8
+ * GET /api/twinsearth/timemachine/health
9
+ * GET /api/twinsearth/timemachine/status
10
+ * GET /api/twinsearth/timemachine/estimate
11
+ * POST /api/twinsearth/timemachine/create
12
+ * POST /api/twinsearth/timemachine/plan
13
+ * POST /api/twinsearth/timemachine/restore
14
+ * POST /api/twinsearth/timemachine/import
15
+ * POST /api/twinsearth/timemachine/inspect
16
+ * POST /api/twinsearth/timemachine/settings
17
+ * POST /api/twinsearth/timemachine/auto/run
18
+ */
19
+
20
+ import {
21
+ createAuto,
22
+ createManual,
23
+ getEstimate,
24
+ getStatus,
25
+ importPoint,
26
+ inspectPoint,
27
+ pickerUnavailable,
28
+ plan,
29
+ restore,
30
+ saveSettings,
31
+ startAutoScheduler,
32
+ } from './service.mjs';
33
+
34
+ export const name = 'timemachine';
35
+ export const inject = [];
36
+
37
+ export const ROUTE_PREFIX = '/api/twinsearth/timemachine';
38
+ export const ROUTE_PATHS = Object.freeze({
39
+ health: `${ROUTE_PREFIX}/health`,
40
+ status: `${ROUTE_PREFIX}/status`,
41
+ estimate: `${ROUTE_PREFIX}/estimate`,
42
+ create: `${ROUTE_PREFIX}/create`,
43
+ plan: `${ROUTE_PREFIX}/plan`,
44
+ restore: `${ROUTE_PREFIX}/restore`,
45
+ import: `${ROUTE_PREFIX}/import`,
46
+ inspect: `${ROUTE_PREFIX}/inspect`,
47
+ settings: `${ROUTE_PREFIX}/settings`,
48
+ autoRun: `${ROUTE_PREFIX}/auto/run`,
49
+ });
50
+
51
+ export const RESTORE_CONFIRM = 'restore';
52
+ const NO_STORE = Object.freeze({ 'cache-control': 'no-store' });
53
+
54
+ function json(payload, init = {}) {
55
+ return Response.json(payload, { headers: NO_STORE, ...init });
56
+ }
57
+
58
+ function fail(reason_code, detail, status = 400) {
59
+ return json({ ok: false, reason_code, detail }, { status });
60
+ }
61
+
62
+ async function readBody(request) {
63
+ try {
64
+ const body = await request.json();
65
+ return body !== null && typeof body === 'object' && !Array.isArray(body) ? body : {};
66
+ } catch {
67
+ return {};
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Mount the routes. Exported so tests can drive it with a fake registry.
73
+ * @param {object} ctx
74
+ * @param {object} rawConfig
75
+ * @param {{dshHome?: string, runner?: Function, pnpmFile?: string|null}} [deps]
76
+ */
77
+ export function registerRoutes(ctx, rawConfig, deps = {}) {
78
+ const report = { mounted: false, reason: 'the host has no Connection service', paths: Object.values(ROUTE_PATHS) };
79
+ if (typeof ctx?.inject !== 'function') return report;
80
+ ctx.inject(['connection'], (webCtx) => {
81
+ const registry = webCtx?.connection?.fetch;
82
+ if (registry === undefined || typeof registry.register !== 'function') {
83
+ report.reason = 'the connection service carries no fetch registry';
84
+ return;
85
+ }
86
+ let busy = false;
87
+ const guarded = async (label, work) => {
88
+ if (busy) return fail('TIMEMACHINE_BUSY', '另一个备份/还原操作正在运行,请稍后再试', 409);
89
+ busy = true;
90
+ try {
91
+ return await work();
92
+ } catch (error) {
93
+ ctx.logger?.warn?.(`${name}: ${label} failed: ${error instanceof Error ? error.message : String(error)}`);
94
+ return fail('TIMEMACHINE_INTERNAL', error instanceof Error ? error.message : String(error), 500);
95
+ } finally {
96
+ busy = false;
97
+ }
98
+ };
99
+ const register = (method, url, handler) => {
100
+ registry.register({
101
+ path: url,
102
+ methods: [method],
103
+ requestBody: 'buffered',
104
+ fetch: async (request) => {
105
+ if (request.method !== method) return fail('METHOD_NOT_ALLOWED', `${request.method} is not allowed`, 405);
106
+ return handler(request);
107
+ },
108
+ });
109
+ };
110
+
111
+ register('GET', ROUTE_PATHS.health, async () => json({ ok: true, plugin: name, mounted: true }));
112
+ register('GET', ROUTE_PATHS.status, async () => json(getStatus(rawConfig, deps)));
113
+ register('GET', ROUTE_PATHS.estimate, async () => json({ ok: true, ...getEstimate(rawConfig, deps) }));
114
+ register('POST', ROUTE_PATHS.create, async (request) => guarded('create', async () => {
115
+ const body = await readBody(request);
116
+ const result = body.kind === 'auto'
117
+ ? await createAuto(rawConfig, deps)
118
+ : await createManual(rawConfig, deps);
119
+ return json(result, { status: result.ok ? 200 : 400 });
120
+ }));
121
+ register('POST', ROUTE_PATHS.autoRun, async () => guarded('auto', async () => json(await createAuto(rawConfig, deps))));
122
+ register('POST', ROUTE_PATHS.plan, async (request) => {
123
+ const body = await readBody(request);
124
+ const result = plan(rawConfig, body, deps);
125
+ return json(result, { status: result.ok ? 200 : 400 });
126
+ });
127
+ register('POST', ROUTE_PATHS.restore, async (request) => {
128
+ const body = await readBody(request);
129
+ if (body.confirm !== RESTORE_CONFIRM) {
130
+ return fail('TIMEMACHINE_CONFIRM_REQUIRED', `pass confirm:"${RESTORE_CONFIRM}" to apply a restore`);
131
+ }
132
+ return guarded('restore', async () => {
133
+ const result = await restore(rawConfig, body, deps);
134
+ return json(result, { status: result.ok ? 200 : 400 });
135
+ });
136
+ });
137
+ register('POST', ROUTE_PATHS.import, async (request) => {
138
+ const body = await readBody(request);
139
+ return guarded('import', async () => {
140
+ const result = importPoint(rawConfig, body, deps);
141
+ return json(result, { status: result.ok ? 200 : 400 });
142
+ });
143
+ });
144
+ register('POST', ROUTE_PATHS.inspect, async (request) => {
145
+ const body = await readBody(request);
146
+ const result = inspectPoint(rawConfig, body, deps);
147
+ return json(result, { status: result.ok ? 200 : 400 });
148
+ });
149
+ register('POST', ROUTE_PATHS.settings, async (request) => {
150
+ const body = await readBody(request);
151
+ const result = saveSettings(rawConfig, body, deps);
152
+ return json(result);
153
+ });
154
+ register('POST', `${ROUTE_PREFIX}/pick-root`, async () => json(pickerUnavailable('文件夹')));
155
+ register('POST', `${ROUTE_PREFIX}/pick-file`, async () => json(pickerUnavailable('还原点文件')));
156
+ report.mounted = true;
157
+ report.reason = null;
158
+ });
159
+ return report;
160
+ }
161
+
162
+ /**
163
+ * Cordis entry point. The returned disposer also carries the mount report.
164
+ * @param {object} ctx
165
+ * @param {object} [config]
166
+ * @param {{dshHome?: string, runner?: Function, pnpmFile?: string|null}} [deps]
167
+ */
168
+ export function apply(ctx, config = {}, deps = {}) {
169
+ const runtimeDeps = {
170
+ ...deps,
171
+ getWorkspaceRegistry: () => {
172
+ try {
173
+ return ctx?.get?.('workspaceRegistry');
174
+ } catch {
175
+ return undefined;
176
+ }
177
+ },
178
+ };
179
+ const routes = registerRoutes(ctx, config, runtimeDeps);
180
+ ctx.logger?.info?.(`${name}: routes ${routes.mounted ? 'mounted' : `not mounted (${routes.reason})`}`);
181
+ const stopScheduler = startAutoScheduler({
182
+ dshHome: deps.dshHome,
183
+ getConfig: () => config,
184
+ onRun: async () => { await createAuto(config, runtimeDeps); },
185
+ onError: (error) => {
186
+ ctx.logger?.warn?.(`${name}: automatic restore point failed: ${error instanceof Error ? error.message : String(error)}`);
187
+ },
188
+ });
189
+ let disposed = false;
190
+ ctx.effect?.(() => () => {
191
+ disposed = true;
192
+ stopScheduler();
193
+ });
194
+ const dispose = () => {
195
+ disposed = true;
196
+ stopScheduler();
197
+ };
198
+ for (const [key, value] of Object.entries({
199
+ ok: true,
200
+ mounted: true,
201
+ plugin: name,
202
+ routes: Object.values(ROUTE_PATHS),
203
+ routes_mounted: routes.mounted,
204
+ routes_reason: routes.reason,
205
+ disposed: () => disposed,
206
+ })) {
207
+ dispose[key] = value;
208
+ }
209
+ dispose.displayName = name;
210
+ return dispose;
211
+ }
212
+
213
+ export default apply;
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Plugin inventory, third-party reinstall and optional package capture.
3
+ *
4
+ * A restore point records `dsh.profile.bundles` and `dependencies`, then
5
+ * rebuilds code by installing `<name>@latest` (or a saved tarball). It never
6
+ * copies `node_modules`.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { spawn } from 'node:child_process';
12
+
13
+ /** The package doing the restore must never reinstall itself while running. */
14
+ export const SELF_PLUGIN = '@twinsearth/timemachine-dsh-plugin';
15
+
16
+ const OFFICIAL_SCOPE = '@deepseek-ai/';
17
+
18
+ /** A package name safe to pass as one argv element. */
19
+ export function isSafePackageName(name) {
20
+ return typeof name === 'string'
21
+ && name.length > 0
22
+ && name.length <= 214
23
+ && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/iu.test(name);
24
+ }
25
+
26
+ export function isThirdParty(name) {
27
+ return isSafePackageName(name) && !name.startsWith(OFFICIAL_SCOPE) && name !== SELF_PLUGIN;
28
+ }
29
+
30
+ const KNOWN_EXPERIMENTAL = new Set([
31
+ '@deepseek-ai/dsh-experimental-plugin-market-bundle',
32
+ '@deepseek-ai/dsh-experimental-auto-review',
33
+ '@deepseek-ai/dsh-experimental-forge-bundle',
34
+ '@deepseek-ai/dsh-experimental-inspector-profile',
35
+ '@deepseek-ai/dsh-experimental-cot-translation-bundle',
36
+ '@deepseek-ai/dsh-personalized-recommendations',
37
+ ]);
38
+
39
+ export function pluginKind(name, row = null) {
40
+ if (name === SELF_PLUGIN) return 'self';
41
+ if (name.startsWith(OFFICIAL_SCOPE)) {
42
+ return name.includes('experimental') || KNOWN_EXPERIMENTAL.has(name) || row?.experimental === true ? 'experimental' : 'official';
43
+ }
44
+ return 'third_party';
45
+ }
46
+
47
+ /** Parse the row headers of `cordis.patch.yml` without a YAML dependency. */
48
+ export function parsePluginRows(text) {
49
+ const rows = [];
50
+ let current = null;
51
+ for (const raw of String(text ?? '').split(/\r?\n/u)) {
52
+ const line = raw.trim();
53
+ const id = /^-\s+id:\s*['"]?([^'"\s]+)['"]?\s*$/u.exec(line);
54
+ if (id !== null) {
55
+ if (current !== null) rows.push(current);
56
+ current = { id: id[1], name: null, disabled: null };
57
+ continue;
58
+ }
59
+ if (current === null) continue;
60
+ const name = /^name:\s*['"]?([^'"\s]+)['"]?\s*$/u.exec(line);
61
+ if (name !== null) {
62
+ current.name = name[1];
63
+ continue;
64
+ }
65
+ const disabled = /^disabled:\s*(true|false)\s*$/iu.exec(line);
66
+ if (disabled !== null) current.disabled = disabled[1].toLowerCase() === 'true';
67
+ }
68
+ if (current !== null) rows.push(current);
69
+ return rows;
70
+ }
71
+
72
+ /**
73
+ * Read a profile's bundle list, dependency pins and patch rows.
74
+ * @param {{dshHome: string, profile?: string}} input
75
+ */
76
+ export function readProfilePlugins(input) {
77
+ const dshHome = path.resolve(input.dshHome);
78
+ const profile = typeof input.profile === 'string' && input.profile !== '' ? input.profile : 'desktop';
79
+ const dir = path.join(dshHome, 'profiles', profile);
80
+ const packageFile = path.join(dir, 'package.json');
81
+ const pkg = (() => {
82
+ try { return JSON.parse(fs.readFileSync(packageFile, 'utf8')); } catch { return null; }
83
+ })();
84
+ if (pkg === null) {
85
+ return {
86
+ ok: false,
87
+ reason_code: 'RESTORE_PROFILE_NOT_FOUND',
88
+ detail: `${packageFile} does not exist or is not valid JSON`,
89
+ profile_dir: dir,
90
+ bundles: [],
91
+ dependencies: {},
92
+ plugins: [],
93
+ all_plugins: [],
94
+ rows: [],
95
+ };
96
+ }
97
+ const bundles = Array.isArray(pkg?.dsh?.profile?.bundles)
98
+ ? pkg.dsh.profile.bundles.filter((value) => typeof value === 'string' && value !== '')
99
+ : [];
100
+ const dependencies = {};
101
+ for (const [name, version] of Object.entries(pkg?.dependencies ?? {})) {
102
+ if (typeof version === 'string') dependencies[name] = version;
103
+ }
104
+ let patchText = '';
105
+ try { patchText = fs.readFileSync(path.join(dir, 'cordis.patch.yml'), 'utf8'); } catch { patchText = ''; }
106
+ const rows = parsePluginRows(patchText);
107
+ const byName = new Map();
108
+ for (const row of rows) {
109
+ if (typeof row.name === 'string' && isSafePackageName(row.name) && !byName.has(row.name)) byName.set(row.name, row);
110
+ }
111
+ const names = new Set(bundles);
112
+ for (const row of rows) {
113
+ if (typeof row.name === 'string' && isSafePackageName(row.name)) names.add(row.name);
114
+ }
115
+ const allPlugins = [];
116
+ for (const name of names) {
117
+ if (!isSafePackageName(name)) continue;
118
+ const row = byName.get(name) ?? null;
119
+ const inBundles = bundles.includes(name);
120
+ const enabled = row?.disabled === null || row?.disabled === undefined
121
+ ? (inBundles ? true : null)
122
+ : row.disabled !== true;
123
+ allPlugins.push({
124
+ name,
125
+ version: dependencies[name] ?? null,
126
+ enabled,
127
+ row_id: row?.id ?? null,
128
+ source: inBundles ? 'bundle' : 'row',
129
+ kind: pluginKind(name, row),
130
+ });
131
+ }
132
+ allPlugins.sort((a, b) => a.name.localeCompare(b.name));
133
+ const plugins = allPlugins.filter((row) => row.kind === 'third_party');
134
+ return {
135
+ ok: true,
136
+ profile_dir: dir,
137
+ bundles,
138
+ dependencies,
139
+ plugins,
140
+ all_plugins: allPlugins,
141
+ rows,
142
+ };
143
+ }
144
+
145
+ /** A filesystem-safe stem for a plugin tarball name. */
146
+ export function packageFileStem(name) {
147
+ return String(name).replace(/^@/u, '').replace(/[\\/]/gu, '-').replace(/[^a-z0-9._-]/giu, '_');
148
+ }
149
+
150
+ /**
151
+ * Run a child process with bounded output.
152
+ * @param {string} command
153
+ * @param {string[]} args
154
+ * @param {{cwd: string, env?: Record<string,string>, timeout_ms?: number}} options
155
+ */
156
+ export function runProcess(command, args, options) {
157
+ return new Promise((resolve) => {
158
+ let child;
159
+ try {
160
+ child = spawn(command, args, {
161
+ cwd: options.cwd,
162
+ env: { ...process.env, CI: 'true', npm_config_yes: 'true', npm_config_fund: 'false', npm_config_audit: 'false', ...options.env },
163
+ shell: process.platform === 'win32' && /\.(cmd|bat)$/i.test(command),
164
+ windowsHide: true,
165
+ stdio: ['ignore', 'pipe', 'pipe'],
166
+ });
167
+ } catch (error) {
168
+ resolve({ code: null, stdout: '', stderr: '', timed_out: false, error: error instanceof Error ? error.message : String(error) });
169
+ return;
170
+ }
171
+ let stdout = '';
172
+ let stderr = '';
173
+ let timedOut = false;
174
+ const cap = 256 * 1024;
175
+ child.stdout?.setEncoding('utf8');
176
+ child.stderr?.setEncoding('utf8');
177
+ child.stdout?.on('data', (chunk) => { if (stdout.length < cap) stdout += String(chunk); });
178
+ child.stderr?.on('data', (chunk) => { if (stderr.length < cap) stderr += String(chunk); });
179
+ const timer = setTimeout(() => {
180
+ timedOut = true;
181
+ try { child.kill('SIGKILL'); } catch { /* already gone */ }
182
+ }, options.timeout_ms ?? 240_000);
183
+ timer.unref?.();
184
+ child.on('error', (error) => {
185
+ clearTimeout(timer);
186
+ resolve({ code: null, stdout, stderr, timed_out: timedOut, error: error.message });
187
+ });
188
+ child.on('close', (code) => {
189
+ clearTimeout(timer);
190
+ resolve({ code, stdout, stderr, timed_out: timedOut });
191
+ });
192
+ });
193
+ }
194
+
195
+ function npmCommand() {
196
+ return process.platform === 'win32' ? 'npm.cmd' : 'npm';
197
+ }
198
+
199
+ /**
200
+ * Find the pnpm that ships with DSH, so a pnpm-managed profile is not rewritten
201
+ * by npm. Returns `null` when this host does not expose one.
202
+ */
203
+ export function resolvePnpm(execPath = process.execPath) {
204
+ const candidates = [];
205
+ const dir = path.dirname(execPath);
206
+ candidates.push(path.resolve(dir, '..', '..', 'pnpm', 'dist', 'pnpm.mjs'));
207
+ candidates.push(path.resolve(dir, '..', 'pnpm', 'dist', 'pnpm.mjs'));
208
+ for (let up = dir, index = 0; index < 5; index += 1) {
209
+ candidates.push(path.join(up, 'resources', 'runtime', 'primary-runtime', 'dependencies', 'pnpm', 'dist', 'pnpm.mjs'));
210
+ candidates.push(path.join(up, 'runtime', 'primary-runtime', 'dependencies', 'pnpm', 'dist', 'pnpm.mjs'));
211
+ up = path.dirname(up);
212
+ }
213
+ for (const file of candidates) {
214
+ try {
215
+ if (fs.statSync(file).isFile()) return file;
216
+ } catch { /* next */ }
217
+ }
218
+ return null;
219
+ }
220
+
221
+ /**
222
+ * Install third-party plugins. pnpm is preferred; npm is a fallback that uses
223
+ * `--no-save` so the archived package.json is not rewritten by an installer.
224
+ * @param {{
225
+ * profileDir: string, plugins: Array<{name: string, version?: string|null}>,
226
+ * packages?: Record<string,string>, runner?: typeof runProcess,
227
+ * timeout_ms?: number, pnpmFile?: string|null, onProgress?: (event: object) => void,
228
+ * }} input
229
+ */
230
+ export async function reinstallPlugins(input) {
231
+ const runner = input.runner ?? runProcess;
232
+ const packages = input.packages ?? {};
233
+ const installed = [];
234
+ const failed = [];
235
+ const skipped = [];
236
+ const plugins = Array.isArray(input.plugins) ? input.plugins : [];
237
+ if (plugins.length === 0) return { ok: true, manager: 'none', installed, failed, skipped };
238
+ if (!fs.existsSync(input.profileDir)) {
239
+ return { ok: false, reason_code: 'RESTORE_PROFILE_NOT_FOUND', detail: input.profileDir, manager: 'none', installed, failed, skipped };
240
+ }
241
+ const pnpmFile = input.pnpmFile === undefined ? resolvePnpm() : input.pnpmFile;
242
+ const manager = pnpmFile !== null && pnpmFile !== undefined ? 'pnpm' : 'npm';
243
+ for (const plugin of plugins) {
244
+ const name = plugin?.name;
245
+ if (!isSafePackageName(name)) {
246
+ skipped.push({ name: String(name), reason: 'unsafe package name' });
247
+ continue;
248
+ }
249
+ if (name === SELF_PLUGIN) {
250
+ skipped.push({ name, reason: 'the running plugin is not reinstalled' });
251
+ continue;
252
+ }
253
+ const tarball = packages[name];
254
+ const spec = typeof tarball === 'string' && tarball !== '' ? `file:${tarball}` : `${name}@latest`;
255
+ const args = manager === 'pnpm'
256
+ ? ['--dir', input.profileDir, 'add', spec, '--reporter=append-only', '--prefer-online']
257
+ : ['install', '--no-save', '--package-lock=false', '--omit=dev', '--prefer-online', spec];
258
+ const command = manager === 'pnpm' ? process.execPath : npmCommand();
259
+ const argv = manager === 'pnpm' ? [pnpmFile, ...args] : args;
260
+ input.onProgress?.({ phase: 'install', name, spec, manager });
261
+ const result = await runner(command, argv, {
262
+ cwd: input.profileDir,
263
+ timeout_ms: input.timeout_ms ?? 240_000,
264
+ });
265
+ const row = {
266
+ name,
267
+ spec,
268
+ manager,
269
+ code: result.code,
270
+ timed_out: result.timed_out === true,
271
+ stdout_tail: String(result.stdout ?? '').slice(-2000),
272
+ stderr_tail: String(result.stderr ?? '').slice(-2000),
273
+ };
274
+ if (result.code === 0) {
275
+ installed.push(row);
276
+ } else {
277
+ failed.push({ ...row, error: result.error ?? null });
278
+ return {
279
+ ok: false,
280
+ reason_code: 'RESTORE_PLUGIN_INSTALL_FAILED',
281
+ detail: `${name}: ${manager} exited ${String(result.code)}${result.timed_out === true ? ' (timeout)' : ''}`,
282
+ manager,
283
+ installed,
284
+ failed,
285
+ skipped,
286
+ };
287
+ }
288
+ }
289
+ if (manager === 'npm') {
290
+ // npm --no-save leaves package.json at the archived pins. Record what was
291
+ // actually installed so the next DSH boot and a later restore agree.
292
+ try {
293
+ const pkgFile = path.join(input.profileDir, 'package.json');
294
+ const pkg = JSON.parse(fs.readFileSync(pkgFile, 'utf8'));
295
+ pkg.dependencies = pkg.dependencies !== null && typeof pkg.dependencies === 'object' ? pkg.dependencies : {};
296
+ for (const row of installed) {
297
+ const installedPkg = path.join(input.profileDir, 'node_modules', ...row.name.split('/'), 'package.json');
298
+ try {
299
+ const meta = JSON.parse(fs.readFileSync(installedPkg, 'utf8'));
300
+ if (typeof meta.version === 'string') pkg.dependencies[row.name] = meta.version;
301
+ } catch { /* keep the archived pin */ }
302
+ }
303
+ fs.writeFileSync(pkgFile, `${JSON.stringify(pkg, null, 2)}\n`, 'utf8');
304
+ } catch { /* a package.json write failure is reported by the next status, not here */ }
305
+ }
306
+ return { ok: true, manager, installed, failed, skipped };
307
+ }
308
+
309
+ /**
310
+ * Save plugin tarballs only when the user ticks "also save install packages".
311
+ * @param {{profileDir: string, plugins: Array<{name: string, version?: string|null}>, destination: string, runner?: typeof runProcess, timeout_ms?: number}} input
312
+ */
313
+ export async function packPluginTarballs(input) {
314
+ const runner = input.runner ?? runProcess;
315
+ const packages = {};
316
+ const files = [];
317
+ const failed = [];
318
+ fs.mkdirSync(input.destination, { recursive: true });
319
+ for (const plugin of input.plugins ?? []) {
320
+ if (!isSafePackageName(plugin.name) || plugin.name === SELF_PLUGIN) continue;
321
+ const spec = `${plugin.name}@${typeof plugin.version === 'string' && plugin.version !== '' ? plugin.version : 'latest'}`;
322
+ const result = await runner(npmCommand(), ['pack', spec, '--pack-destination', input.destination, '--json'], {
323
+ cwd: input.profileDir,
324
+ timeout_ms: input.timeout_ms ?? 240_000,
325
+ });
326
+ if (result.code !== 0) {
327
+ failed.push({ name: plugin.name, spec, stderr_tail: String(result.stderr ?? '').slice(-2000) });
328
+ continue;
329
+ }
330
+ const found = findPackedFile(result.stdout, input.destination, plugin.name);
331
+ if (found === null) {
332
+ failed.push({ name: plugin.name, spec, detail: 'npm pack produced no tarball' });
333
+ continue;
334
+ }
335
+ const bytes = fs.statSync(found).size;
336
+ packages[plugin.name] = found;
337
+ files.push({ name: plugin.name, file: found, bytes });
338
+ }
339
+ return { ok: failed.length === 0, packages, files, failed };
340
+ }
341
+
342
+ function findPackedFile(stdout, destination, name) {
343
+ let parsed = null;
344
+ try { parsed = JSON.parse(String(stdout)); } catch { parsed = null; }
345
+ if (Array.isArray(parsed) && typeof parsed[0]?.filename === 'string') {
346
+ const candidate = path.join(destination, parsed[0].filename);
347
+ if (fs.existsSync(candidate)) return candidate;
348
+ }
349
+ const stem = packageFileStem(name).toLowerCase();
350
+ for (const entry of fs.existsSync(destination) ? fs.readdirSync(destination) : []) {
351
+ const lower = entry.toLowerCase();
352
+ if (lower.startsWith(`${stem}-`) && lower.endsWith('.tgz')) return path.join(destination, entry);
353
+ }
354
+ return null;
355
+ }