dsh-plugin-packer 0.0.0-stage → 2.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/lib/assets.js ADDED
@@ -0,0 +1,556 @@
1
+ /**
2
+ * dsh-plugin-packer — runtime assets.
3
+ *
4
+ * A plain plugin pack is the plugin plus its node dependency closure. That is
5
+ * enough when everything the plugin needs lives in `node_modules`, and not
6
+ * enough when the real weight lives elsewhere on the machine: a plugin may keep
7
+ * a large tool environment, model files or a data directory under `DSH_HOME`,
8
+ * and then a plain archive reaches the next machine with none of it.
9
+ *
10
+ * A runtime asset closes that gap. It is declared per plugin in
11
+ *
12
+ * <profile>/.plugin-packer/assets/<plugin>.json
13
+ *
14
+ * staged into the archive under `assets/<id>/…`, and materialised on import by
15
+ * running a command that travels *inside* the asset — no index, no shell, no
16
+ * network. Everything here is filesystem + child-process work; the HTTP layer
17
+ * in ./index.js owns requests.
18
+ *
19
+ * The mechanism is deliberately generic: this module knows nothing about any
20
+ * particular plugin, and a plugin that needs nothing simply has no descriptor.
21
+ */
22
+ import { createHash } from 'node:crypto';
23
+ import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync } from 'node:fs';
24
+ import { cp, mkdir, readdir, stat, writeFile } from 'node:fs/promises';
25
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
26
+ import { spawn } from 'node:child_process';
27
+
28
+ /** Where a plugin declares its assets. */
29
+ export const DESCRIPTOR_DIR = '.plugin-packer/assets';
30
+ /** Archive prefix every staged asset lands under. */
31
+ export const ASSET_PREFIX = 'assets';
32
+ /** Placeholder keys a descriptor may use in paths, args and env. */
33
+ export const PLACEHOLDERS = Object.freeze(['DSH_HOME', 'PROFILE', 'ASSET', 'PLUGIN_DIR']);
34
+ /** Assets with an install recipe may not point at the network; refuse these. */
35
+ const NETWORK_FLAGS = Object.freeze(['--index-url', '--extra-index-url', '--upgrade', '--refresh']);
36
+ const ASSET_ID = /^[a-z0-9][a-z0-9._-]*$/u;
37
+ const MAX_CAPTURE = 64 * 1024;
38
+
39
+ function readJson(file) {
40
+ return JSON.parse(readFileSync(file, 'utf8'));
41
+ }
42
+
43
+ /**
44
+ * Directory that holds the asset descriptors of this profile.
45
+ * @param {string} profileDir - absolute profile directory.
46
+ * @returns {string} absolute descriptor directory.
47
+ */
48
+ export function descriptorDir(profileDir) {
49
+ return join(profileDir, '.plugin-packer', 'assets');
50
+ }
51
+
52
+ /**
53
+ * Read every descriptor in the profile, skipping (and reporting) broken ones:
54
+ * one malformed file must not hide the other plugins' assets.
55
+ * @param {string} profileDir - absolute profile directory.
56
+ * @returns {{ descriptors: any[], errors: { file: string, message: string }[] }} inventory.
57
+ */
58
+ export function readDescriptors(profileDir) {
59
+ const dir = descriptorDir(profileDir);
60
+ let names = [];
61
+ try {
62
+ names = readdirSync(dir, { withFileTypes: true })
63
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.json'))
64
+ .map((entry) => entry.name)
65
+ .sort();
66
+ } catch {
67
+ return { descriptors: [], errors: [] };
68
+ }
69
+ const descriptors = [];
70
+ const errors = [];
71
+ for (const name of names) {
72
+ try {
73
+ const raw = readJson(join(dir, name));
74
+ descriptors.push(normalizeDescriptor(raw, name));
75
+ } catch (error) {
76
+ errors.push({ file: name, message: error instanceof Error ? error.message : String(error) });
77
+ }
78
+ }
79
+ return { descriptors, errors };
80
+ }
81
+
82
+ /**
83
+ * Validate one descriptor file. Only the shape this module consumes is checked;
84
+ * the plugin name is matched against the package being exported by the caller.
85
+ * @param {any} raw - parsed JSON.
86
+ * @param {string} file - descriptor file name, for error messages.
87
+ * @returns {{ plugin: string, assets: any[], file: string }} validated descriptor.
88
+ */
89
+ export function normalizeDescriptor(raw, file) {
90
+ if (raw === null || typeof raw !== 'object') throw new Error(file + ': descriptor is not an object');
91
+ const plugin = typeof raw.plugin === 'string' ? raw.plugin.trim() : '';
92
+ if (plugin === '') throw new Error(file + ': "plugin" must name the package these assets belong to');
93
+ if (!Array.isArray(raw.assets) || raw.assets.length === 0) throw new Error(file + ': "assets" must be a non-empty array');
94
+ const assets = raw.assets.map((asset, index) => normalizeAsset(asset, file + '#' + index));
95
+ const ids = new Set();
96
+ for (const asset of assets) {
97
+ if (ids.has(asset.id)) throw new Error(file + ': duplicate asset id "' + asset.id + '"');
98
+ ids.add(asset.id);
99
+ }
100
+ return { plugin, assets, file };
101
+ }
102
+
103
+ /**
104
+ * Validate one asset entry.
105
+ * @param {any} raw - descriptor asset.
106
+ * @param {string} where - label used in error messages.
107
+ * @returns {any} normalized asset.
108
+ */
109
+ function normalizeAsset(raw, where) {
110
+ if (raw === null || typeof raw !== 'object') throw new Error(where + ': asset is not an object');
111
+ const id = typeof raw.id === 'string' ? raw.id.trim() : '';
112
+ if (!ASSET_ID.test(id)) throw new Error(where + ': "id" must match ' + String(ASSET_ID));
113
+ const kind = raw.kind === undefined ? 'offline-env' : raw.kind;
114
+ if (kind !== 'offline-env' && kind !== 'files') throw new Error(where + ': unknown kind "' + String(kind) + '" (expected offline-env or files)');
115
+ const installDir = typeof raw.installDir === 'string' ? raw.installDir.trim() : '';
116
+ if (installDir === '') throw new Error(where + ': "installDir" is required (placeholders allowed)');
117
+ const bundleDir = typeof raw.bundleDir === 'string' ? raw.bundleDir.trim() : '';
118
+ if (bundleDir === '') throw new Error(where + ': "bundleDir" is required: the local directory to stage into the archive');
119
+ const install = raw.install === undefined ? null : normalizeInstall(raw.install, where);
120
+ const postInstall = raw.postInstall === undefined ? null : normalizePostInstall(raw.postInstall, where);
121
+ return {
122
+ id,
123
+ kind,
124
+ label: typeof raw.label === 'string' && raw.label !== '' ? raw.label : id,
125
+ bundleDir,
126
+ installDir,
127
+ install,
128
+ postInstall,
129
+ keep: raw.keep === true,
130
+ excludes: Array.isArray(raw.excludes) ? raw.excludes.filter((entry) => typeof entry === 'string') : [],
131
+ };
132
+ }
133
+
134
+ function normalizeInstall(raw, where) {
135
+ if (raw === null || typeof raw !== 'object') throw new Error(where + ': "install" is not an object');
136
+ const executable = typeof raw.executable === 'string' ? raw.executable.trim() : '';
137
+ if (executable === '') throw new Error(where + ': "install.executable" must name a program inside the asset');
138
+ const args = Array.isArray(raw.args) ? raw.args : [];
139
+ for (const arg of args) if (typeof arg !== 'string') throw new Error(where + ': "install.args" must be strings');
140
+ for (const arg of args) {
141
+ for (const flag of NETWORK_FLAGS) {
142
+ if (arg === flag || arg.startsWith(flag + '=')) throw new Error(where + ': "install.args" may not use ' + flag + ' (offline assets only)');
143
+ }
144
+ }
145
+ const env = {};
146
+ if (raw.env !== undefined) {
147
+ if (raw.env === null || typeof raw.env !== 'object') throw new Error(where + ': "install.env" is not an object');
148
+ for (const [key, value] of Object.entries(raw.env)) {
149
+ if (typeof value !== 'string') throw new Error(where + ': "install.env.' + key + '" must be a string');
150
+ env[key] = value;
151
+ }
152
+ }
153
+ const expect = Array.isArray(raw.expect) ? raw.expect : [];
154
+ for (const entry of expect) if (typeof entry !== 'string') throw new Error(where + ': "install.expect" must be strings');
155
+ const timeoutMs = typeof raw.timeoutMs === 'number' && Number.isFinite(raw.timeoutMs) ? Math.max(1000, Math.min(raw.timeoutMs, 30 * 60 * 1000)) : 10 * 60 * 1000;
156
+ return { executable, args: [...args], env, cwd: typeof raw.cwd === 'string' ? raw.cwd : '<ASSET>', expect, timeoutMs };
157
+ }
158
+
159
+ function normalizePostInstall(raw, where) {
160
+ if (raw === null || typeof raw !== 'object') throw new Error(where + ': "postInstall" is not an object');
161
+ const script = typeof raw.script === 'string' ? raw.script.trim() : '';
162
+ if (script === '') throw new Error(where + ': "postInstall.script" must name a file inside the asset');
163
+ const args = Array.isArray(raw.args) ? raw.args : [];
164
+ for (const arg of args) if (typeof arg !== 'string') throw new Error(where + ': "postInstall.args" must be strings');
165
+ const env = {};
166
+ if (raw.env !== undefined) {
167
+ if (raw.env === null || typeof raw.env !== 'object') throw new Error(where + ': "postInstall.env" is not an object');
168
+ for (const [key, value] of Object.entries(raw.env)) {
169
+ if (typeof value !== 'string') throw new Error(where + ': "postInstall.env.' + key + '" must be a string');
170
+ env[key] = value;
171
+ }
172
+ }
173
+ const timeoutMs = typeof raw.timeoutMs === 'number' && Number.isFinite(raw.timeoutMs) ? Math.max(1000, Math.min(raw.timeoutMs, 10 * 60 * 1000)) : 2 * 60 * 1000;
174
+ return { script, args: [...args], env, timeoutMs };
175
+ }
176
+
177
+ /**
178
+ * List a bundle directory. Directory junctions are followed (uv links a minor
179
+ * Python version to the exact one) and symbol links are skipped, so the staged
180
+ * tree always contains real files.
181
+ * @param {string} root - absolute directory.
182
+ * @param {string[]} excludes - POSIX-relative prefixes to drop.
183
+ * @param {number} [limit] - safety valve for runaway trees.
184
+ * @returns {Promise<{ path: string, size: number, mtime: Date }[]>} relative files.
185
+ */
186
+ export async function listBundleFiles(root, excludes = [], limit = 400000) {
187
+ const files = [];
188
+ const stack = [''];
189
+ while (stack.length > 0 && files.length < limit) {
190
+ const relDir = stack.pop();
191
+ const absolute = relDir === '' ? root : join(root, relDir);
192
+ let entries;
193
+ try {
194
+ entries = await readdir(absolute, { withFileTypes: true });
195
+ } catch {
196
+ continue;
197
+ }
198
+ for (const entry of entries) {
199
+ const relPath = relDir === '' ? entry.name : relDir + '/' + entry.name;
200
+ if (excludes.some((prefix) => relPath === prefix || relPath.startsWith(prefix.replace(/\/+$/u, '') + '/'))) continue;
201
+ if (entry.isSymbolicLink()) continue;
202
+ if (entry.isDirectory()) {
203
+ stack.push(relPath);
204
+ continue;
205
+ }
206
+ if (!entry.isFile()) continue;
207
+ try {
208
+ const info = await stat(join(root, relPath));
209
+ files.push({ path: relPath, size: info.size, mtime: info.mtime });
210
+ } catch {
211
+ /* vanished mid-walk */
212
+ }
213
+ }
214
+ }
215
+ return files;
216
+ }
217
+
218
+ /**
219
+ * Stage the assets one plugin declares into archive entries.
220
+ * @param {string} profileDir - absolute profile directory.
221
+ * @param {string} pluginName - package being exported.
222
+ * @returns {Promise<{ entries: any[], sources: any[], totals: { files: number, bytes: number }, errors: string[] }>} staging.
223
+ */
224
+ export async function stageAssets(profileDir, pluginName) {
225
+ const { descriptors, errors } = readDescriptors(profileDir);
226
+ /* A descriptor that does not parse would silently export "no assets" — the
227
+ * exact failure this feature exists to prevent. Refuse instead. */
228
+ if (errors.length > 0) {
229
+ throw new Error("asset descriptor(s) unusable in " + DESCRIPTOR_DIR + ": " + errors.map((entry) => entry.file + ": " + entry.message).join("; "));
230
+ }
231
+ const mine = descriptors.filter((descriptor) => descriptor.plugin === pluginName);
232
+ const entries = [];
233
+ const sources = [];
234
+ let files = 0;
235
+ let bytes = 0;
236
+ for (const descriptor of mine) {
237
+ for (const asset of descriptor.assets) {
238
+ if (!existsSync(asset.bundleDir)) throw new Error('asset "' + asset.id + '" points at a missing bundle: ' + asset.bundleDir + ' (declare it in ' + DESCRIPTOR_DIR + '/' + descriptor.file + ')');
239
+ const listed = await listBundleFiles(asset.bundleDir, asset.excludes);
240
+ if (listed.length === 0) throw new Error('asset "' + asset.id + '" bundles no files: ' + asset.bundleDir);
241
+ let assetBytes = 0;
242
+ for (const file of listed) {
243
+ const name = ASSET_PREFIX + '/' + asset.id + '/' + file.path;
244
+ sources.push({ name, file: join(asset.bundleDir, file.path), size: file.size, mtime: file.mtime });
245
+ assetBytes += file.size;
246
+ }
247
+ entries.push({
248
+ id: asset.id,
249
+ kind: asset.kind,
250
+ label: asset.label,
251
+ installDir: asset.installDir,
252
+ keep: asset.keep,
253
+ install: asset.install === null ? null : {
254
+ executable: asset.install.executable,
255
+ args: asset.install.args,
256
+ env: asset.install.env,
257
+ cwd: asset.install.cwd,
258
+ expect: asset.install.expect,
259
+ timeoutMs: asset.install.timeoutMs,
260
+ },
261
+ postInstall: asset.postInstall,
262
+ totals: { files: listed.length, bytes: assetBytes },
263
+ });
264
+ files += listed.length;
265
+ bytes += assetBytes;
266
+ }
267
+ }
268
+ return { entries, sources, totals: { files, bytes }, errors };
269
+ }
270
+
271
+ /**
272
+ * Replace the placeholders a descriptor may use.
273
+ * @param {string} text - raw value.
274
+ * @param {{ home: string, profile: string, asset: string, plugin: string }} ctx - absolute targets.
275
+ * @returns {string} expanded value.
276
+ */
277
+ export function expand(text, ctx) {
278
+ let out = String(text);
279
+ const map = { DSH_HOME: ctx.home, PROFILE: ctx.profile, ASSET: ctx.asset, PLUGIN_DIR: ctx.plugin };
280
+ for (const [key, value] of Object.entries(map)) {
281
+ out = out.split('<' + key + '>').join(value);
282
+ }
283
+ return out;
284
+ }
285
+
286
+ /** Expand placeholders in every string of an array / object tree. */
287
+ function expandDeep(value, ctx) {
288
+ if (typeof value === 'string') return expand(value, ctx);
289
+ if (Array.isArray(value)) return value.map((entry) => expandDeep(entry, ctx));
290
+ if (value !== null && typeof value === 'object') {
291
+ const out = {};
292
+ for (const [key, entry] of Object.entries(value)) out[key] = expandDeep(entry, ctx);
293
+ return out;
294
+ }
295
+ return value;
296
+ }
297
+
298
+ /**
299
+ * Install the assets listed by an archive manifest.
300
+ *
301
+ * Order per asset: copy `assets/<id>` into its final `installDir` (the Python
302
+ * interpreter inside it is referenced by `pyvenv.cfg`, so it must live at the
303
+ * final path before the recipe runs), run the recipe, verify `expect` paths,
304
+ * then run the post-install hook.
305
+ *
306
+ * @param {{ packDir: string, profileDir: string, home: string, manifest: any, backupRoot: string, logger?: any }} options - import context.
307
+ * @returns {Promise<any[]>} one report per asset.
308
+ */
309
+ export async function installAssets(options) {
310
+ const { packDir, profileDir, home, manifest, backupRoot, logger } = options;
311
+ const listed = Array.isArray(manifest?.assets) ? manifest.assets : [];
312
+ const reports = [];
313
+ for (const entry of listed) {
314
+ const id = typeof entry?.id === 'string' ? entry.id : '';
315
+ if (!ASSET_ID.test(id)) throw new Error('archive lists an invalid asset id: ' + String(entry?.id));
316
+ const source = join(packDir, ASSET_PREFIX, id);
317
+ if (!existsSync(source)) throw new Error('archive is missing the payload of asset "' + id + '"');
318
+ const ctx = {
319
+ home,
320
+ profile: profileDir,
321
+ asset: '',
322
+ plugin: join(profileDir, 'node_modules', String(manifest?.root?.name ?? '')),
323
+ };
324
+ const declared = typeof entry.installDir === 'string' ? expand(entry.installDir, { ...ctx, asset: source }) : '';
325
+ if (declared === '' || !isAbsolute(declared)) throw new Error('asset "' + id + '" needs an absolute installDir after placeholder expansion, got: ' + declared);
326
+ const installDir = resolve(declared);
327
+ /* Plugins belong in node_modules; an asset never does. On another drive
328
+ * relative() returns an absolute path, which means "somewhere else" — fine. */
329
+ const relToModules = relative(resolve(profileDir, 'node_modules'), installDir);
330
+ const insideModules = relToModules === '' || (!relToModules.startsWith('..') && !isAbsolute(relToModules));
331
+ if (insideModules) {
332
+ throw new Error('asset "' + id + '" may not install into node_modules (' + installDir + ')');
333
+ }
334
+ ctx.asset = installDir;
335
+ /* Facts the hook cannot guess: which home, which profile, which plugin
336
+ * directory it is finishing. The descriptor may override them, but its
337
+ * defaults must already be right — the importing machine has one truth. */
338
+ const contextEnv = {
339
+ DSH_HOME: home,
340
+ DSH_PROFILE_DIR: profileDir,
341
+ DSH_PLUGIN_DIR: join(profileDir, 'node_modules', String(manifest?.root?.name ?? '')),
342
+ DSH_ASSET_DIR: installDir,
343
+ };
344
+ const stamp = new Date().toISOString().replace(/[:.]/gu, '-');
345
+ let replaced = false;
346
+ if (existsSync(installDir)) {
347
+ const backup = join(backupRoot, 'assets-' + stamp, id);
348
+ await mkdir(join(backup, '..'), { recursive: true });
349
+ try {
350
+ renameSync(installDir, backup);
351
+ replaced = true;
352
+ } catch {
353
+ rmSync(installDir, { recursive: true, force: true });
354
+ }
355
+ }
356
+ await mkdir(installDir, { recursive: true });
357
+ await cp(source, installDir, { recursive: true, dereference: true });
358
+ let install = null;
359
+ if (entry.install !== null && entry.install !== undefined) {
360
+ const executable = resolve(installDir, expand(entry.install.executable, ctx));
361
+ assertInside(installDir, executable, 'asset "' + id + '" executable');
362
+ if (!existsSync(executable)) throw new Error('asset "' + id + '" is missing its installer: ' + executable);
363
+ const cwd = resolve(expand(entry.install.cwd ?? '<ASSET>', ctx));
364
+ const env = {};
365
+ for (const [key, value] of Object.entries(entry.install.env ?? {})) env[key] = expand(value, ctx);
366
+ logger?.info?.('plugin-packer: installing asset ' + id + ' with ' + executable);
367
+ install = await runProcess({
368
+ exe: executable,
369
+ args: (entry.install.args ?? []).map((arg) => expand(arg, ctx)),
370
+ env: { ...contextEnv, ...env },
371
+ cwd,
372
+ timeoutMs: entry.install.timeoutMs ?? 10 * 60 * 1000,
373
+ });
374
+ if (install.code !== 0) {
375
+ throw new Error('asset "' + id + '" installer exited with code ' + install.code + (install.stderrTail === '' ? '' : ': ' + install.stderrTail));
376
+ }
377
+ for (const expected of entry.install.expect ?? []) {
378
+ const target = resolve(expand(expected, ctx));
379
+ if (!existsSync(target)) throw new Error('asset "' + id + '" installer finished but ' + target + ' is missing');
380
+ }
381
+ }
382
+ let postInstall = null;
383
+ if (entry.postInstall !== null && entry.postInstall !== undefined) {
384
+ const script = resolve(installDir, expand(entry.postInstall.script, ctx));
385
+ assertInside(installDir, script, 'asset "' + id + '" post-install script');
386
+ if (!existsSync(script)) throw new Error('asset "' + id + '" is missing its post-install script: ' + script);
387
+ const env = {};
388
+ for (const [key, value] of Object.entries(entry.postInstall.env ?? {})) env[key] = expand(value, ctx);
389
+ logger?.info?.('plugin-packer: activating asset ' + id + ' with ' + script);
390
+ postInstall = await runProcess({
391
+ exe: process.execPath,
392
+ args: [script, ...(entry.postInstall.args ?? []).map((arg) => expand(arg, ctx))],
393
+ env: { ...contextEnv, ...env },
394
+ cwd: installDir,
395
+ timeoutMs: entry.postInstall.timeoutMs ?? 2 * 60 * 1000,
396
+ });
397
+ if (postInstall.code !== 0) {
398
+ throw new Error('asset "' + id + '" post-install hook exited with code ' + postInstall.code + (postInstall.stderrTail === '' ? '' : ': ' + postInstall.stderrTail));
399
+ }
400
+ }
401
+ reports.push({
402
+ id,
403
+ kind: entry.kind ?? 'offline-env',
404
+ label: entry.label ?? id,
405
+ installDir,
406
+ replaced,
407
+ files: entry.totals?.files ?? null,
408
+ bytes: entry.totals?.bytes ?? null,
409
+ install,
410
+ postInstall,
411
+ });
412
+ }
413
+ return reports;
414
+ }
415
+
416
+ /** Reject a path that escapes its asset directory. */
417
+ function assertInside(root, target, what) {
418
+ const rel = relative(resolve(root), resolve(target));
419
+ if (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))) return;
420
+ throw new Error(what + ' escapes its asset directory: ' + target);
421
+ }
422
+
423
+ /**
424
+ * Run one child process without a shell and capture a bounded tail of its
425
+ * output. The asset's own executables are the only thing spawned.
426
+ * @param {{ exe: string, args: string[], env: Record<string, string>, cwd: string, timeoutMs: number }} options - process.
427
+ * @returns {Promise<{ code: number, stdoutTail: string, stderrTail: string, ms: number }>} result.
428
+ */
429
+ export function runProcess(options) {
430
+ const started = Date.now();
431
+ return new Promise((resolvePromise, rejectPromise) => {
432
+ let stdout = '';
433
+ let stderr = '';
434
+ const child = spawn(options.exe, options.args, {
435
+ cwd: existsSync(options.cwd) ? options.cwd : undefined,
436
+ env: { ...process.env, ...options.env },
437
+ windowsHide: true,
438
+ stdio: ['ignore', 'pipe', 'pipe'],
439
+ });
440
+ const keep = (current, chunk) => (current + chunk.toString('utf8')).slice(-MAX_CAPTURE);
441
+ child.stdout?.on('data', (chunk) => {
442
+ stdout = keep(stdout, chunk);
443
+ });
444
+ child.stderr?.on('data', (chunk) => {
445
+ stderr = keep(stderr, chunk);
446
+ });
447
+ const timer = setTimeout(() => {
448
+ try {
449
+ child.kill();
450
+ } catch {
451
+ /* already gone */
452
+ }
453
+ rejectPromise(new Error('timed out after ' + Math.round(options.timeoutMs / 1000) + 's: ' + options.exe));
454
+ }, options.timeoutMs);
455
+ if (typeof timer.unref === 'function') timer.unref();
456
+ child.on('error', (error) => {
457
+ clearTimeout(timer);
458
+ rejectPromise(error);
459
+ });
460
+ child.on('close', (code) => {
461
+ clearTimeout(timer);
462
+ resolvePromise({
463
+ code: typeof code === 'number' ? code : -1,
464
+ stdoutTail: stdout.trim().slice(-2000),
465
+ stderrTail: stderr.trim().slice(-2000),
466
+ ms: Date.now() - started,
467
+ });
468
+ });
469
+ });
470
+ }
471
+
472
+ /**
473
+ * Report the on-disk state of the assets declared in this profile, for the
474
+ * settings tab. Never throws: a broken descriptor is reported, not fatal.
475
+ * @param {string} profileDir - absolute profile directory.
476
+ * @param {string} home - DSH home.
477
+ * @returns {{ descriptors: any[], errors: any[] }} per-asset status.
478
+ */
479
+ export function describeAssets(profileDir, home) {
480
+ const { descriptors, errors } = readDescriptors(profileDir);
481
+ const rows = descriptors.map((descriptor) => ({
482
+ plugin: descriptor.plugin,
483
+ file: descriptor.file,
484
+ assets: descriptor.assets.map((asset) => {
485
+ const ctx = { home, profile: profileDir, asset: '', plugin: join(profileDir, 'node_modules', descriptor.plugin) };
486
+ const installDir = isAbsolute(expand(asset.installDir, { ...ctx, asset: '<asset>' })) ? expand(asset.installDir, { ...ctx, asset: join(profileDir, '.plugin-packer-placeholder') }) : '';
487
+ const present = installDir !== '' && existsSync(installDir);
488
+ const expects = (asset.install?.expect ?? []).map((expected) => {
489
+ const target = expand(expected, { ...ctx, asset: installDir });
490
+ return { path: target, ok: existsSync(target) };
491
+ });
492
+ let bytes = null;
493
+ if (existsSync(asset.bundleDir)) bytes = measureSync(asset.bundleDir);
494
+ return {
495
+ id: asset.id,
496
+ label: asset.label,
497
+ kind: asset.kind,
498
+ installDir,
499
+ installed: present,
500
+ ready: present && expects.every((entry) => entry.ok),
501
+ expect: expects,
502
+ bundleDir: asset.bundleDir,
503
+ bundle: bytes,
504
+ };
505
+ }),
506
+ }));
507
+ return { descriptors: rows, errors };
508
+ }
509
+
510
+ /** Cheap recursive byte count, tolerating unreadable entries. */
511
+ function measureSync(dir, budget = 200000) {
512
+ let files = 0;
513
+ let bytes = 0;
514
+ const stack = [dir];
515
+ while (stack.length > 0 && files < budget) {
516
+ const current = stack.pop();
517
+ let entries;
518
+ try {
519
+ entries = readdirSync(current, { withFileTypes: true });
520
+ } catch {
521
+ continue;
522
+ }
523
+ for (const entry of entries) {
524
+ const absolute = join(current, entry.name);
525
+ if (entry.isDirectory()) {
526
+ stack.push(absolute);
527
+ continue;
528
+ }
529
+ if (!entry.isFile()) continue;
530
+ try {
531
+ bytes += statSync(absolute).size;
532
+ files += 1;
533
+ } catch {
534
+ /* unreadable */
535
+ }
536
+ }
537
+ }
538
+ return { files, bytes };
539
+ }
540
+
541
+ /** Stable id for a staged bundle, used in logs. */
542
+ export function bundleDigest(dir) {
543
+ return createHash('sha256').update(String(dir)).digest('hex').slice(0, 12);
544
+ }
545
+
546
+ /** Write a file, creating its directory. Exported for the build script. */
547
+ export async function writeText(file, text) {
548
+ await mkdir(join(file, '..'), { recursive: true });
549
+ await writeFile(file, text, 'utf8');
550
+ return file;
551
+ }
552
+
553
+ /** POSIX-style separator helper for archive paths. */
554
+ export function posixify(path) {
555
+ return String(path).split(sep).join('/');
556
+ }