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/packer.js ADDED
@@ -0,0 +1,694 @@
1
+ /**
2
+ * Profile inventory plus export/import for DSH plugin packages.
3
+ *
4
+ * A DSH plugin is a package the profile depends on that declares dsh.bundle
5
+ * (a Cordis patch layer) or dsh.client (a browser half). Such a package is
6
+ * only self-contained when its dependency closure travels with it: the
7
+ * profile uses a hoisted node_modules, so a plugin's runtime dependencies are
8
+ * siblings in that same tree, and a portable archive has to carry them.
9
+ *
10
+ * Everything here is pure filesystem work on the profile directory; the HTTP
11
+ * layer in ./index.js owns requests and the plugin-manager service.
12
+ */
13
+ import { existsSync, readdirSync, readFileSync, realpathSync, statSync } from 'node:fs';
14
+ import { cp, mkdir, rename, rm, writeFile } from 'node:fs/promises';
15
+ import { dirname, isAbsolute, join, posix, relative, sep } from 'node:path';
16
+
17
+ /** Archive format marker; import refuses anything else. */
18
+ export const PACK_FORMAT = 'dsh-plugin-pack';
19
+ /** Format this packer emits. 2 adds the optional runtime-asset block; a pack
20
+ * without assets is still written as format 1, so an archive stays readable by
21
+ * tooling that predates the asset block. */
22
+ export const PACK_FORMAT_VERSION = 2;
23
+ /** Formats this packer accepts on import. */
24
+ export const ACCEPTED_FORMAT_VERSIONS = Object.freeze([1, 2]);
25
+ /** Package names npm accepts; also the path-traversal guard for imports. */
26
+ const PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*$/i;
27
+
28
+ function readJson(file) {
29
+ return JSON.parse(readFileSync(file, 'utf8'));
30
+ }
31
+
32
+ function tryReadJson(file) {
33
+ try {
34
+ return readJson(file);
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Resolve a package directory the way Node resolves a specifier from fromDir.
42
+ * @param {string} fromDir - directory the resolution starts at.
43
+ * @param {string} name - package name.
44
+ * @returns {string | null} canonical package directory, or null when absent.
45
+ */
46
+ export function resolvePackageDir(fromDir, name) {
47
+ let current = fromDir;
48
+ for (;;) {
49
+ const candidate = join(current, 'node_modules', name);
50
+ if (existsSync(join(candidate, 'package.json'))) {
51
+ try {
52
+ return realpathSync(candidate);
53
+ } catch {
54
+ return candidate;
55
+ }
56
+ }
57
+ const parent = dirname(current);
58
+ if (parent === current) return null;
59
+ current = parent;
60
+ }
61
+ }
62
+
63
+ /**
64
+ * Recursively list regular files below a directory. Symbolic links are
65
+ * skipped: a link either points inside the same package (already listed) or
66
+ * outside the archive boundary, and following it would make the export
67
+ * non-portable.
68
+ * @param {string} dir - absolute directory.
69
+ * @param {number} [limit] - maximum files to collect.
70
+ * @param {{ includeFile: (relPath: string) => boolean, includeDir: (relDir: string) => boolean } | null} [filter] - optional
71
+ * allow-list applied while walking; a rejected directory is never entered.
72
+ * @returns {{ path: string, size: number, mtime: Date }[]} relative files.
73
+ */
74
+ export function listFiles(dir, limit = 200000, filter = null) {
75
+ const files = [];
76
+ const stack = [''];
77
+ while (stack.length > 0) {
78
+ const relDir = stack.pop();
79
+ if (relDir === undefined) break;
80
+ const absolute = relDir === '' ? dir : join(dir, relDir);
81
+ let entries;
82
+ try {
83
+ entries = readdirSync(absolute, { withFileTypes: true });
84
+ } catch {
85
+ continue;
86
+ }
87
+ for (const entry of entries) {
88
+ const relPath = relDir === '' ? entry.name : relDir + '/' + entry.name;
89
+ if (entry.isSymbolicLink()) continue;
90
+ if (entry.isDirectory()) {
91
+ if (filter !== null && !filter.includeDir(relPath)) continue;
92
+ stack.push(relPath);
93
+ continue;
94
+ }
95
+ if (!entry.isFile()) continue;
96
+ if (filter !== null && !filter.includeFile(relPath)) continue;
97
+ let stat;
98
+ try {
99
+ stat = statSync(join(dir, relPath));
100
+ } catch {
101
+ continue;
102
+ }
103
+ files.push({ path: relPath, size: stat.size, mtime: stat.mtime });
104
+ if (files.length >= limit) return files;
105
+ }
106
+ }
107
+ return files;
108
+ }
109
+
110
+ /**
111
+ * Translate one npm-style glob into a regular expression.
112
+ * Only `*` (within a path segment), `**` (across segments) and `?` are
113
+ * supported, which is the whole syntax plugin `files` lists actually use.
114
+ * @param {string} pattern - glob such as `lib/types/**\/*.d.ts`.
115
+ * @returns {RegExp} anchored expression.
116
+ */
117
+ function globToRegExp(pattern) {
118
+ let out = '^';
119
+ for (let index = 0; index < pattern.length; index += 1) {
120
+ const char = pattern[index];
121
+ if (char === '*') {
122
+ if (pattern[index + 1] === '*') {
123
+ index += 1;
124
+ if (pattern[index + 1] === '/') {
125
+ index += 1;
126
+ out += '(?:.*/)?';
127
+ } else {
128
+ out += '.*';
129
+ }
130
+ } else {
131
+ out += '[^/]*';
132
+ }
133
+ } else if (char === '?') {
134
+ out += '[^/]';
135
+ } else if ('\\^$.|+()[]{}'.includes(char)) {
136
+ out += '\\' + char;
137
+ } else {
138
+ out += char;
139
+ }
140
+ }
141
+ return new RegExp(out + '$');
142
+ }
143
+
144
+ /**
145
+ * Build the walk filter for one package's `files` allow-list.
146
+ *
147
+ * Export used to archive the whole installed directory, which is wrong for a
148
+ * package installed as a `link:` to a working tree: this very plugin measures
149
+ * 240 MB on disk because of its build caches, and every export dragged all of
150
+ * it into the zip. npm itself only installs `files`, so honouring it is both
151
+ * correct and much smaller. A package without `files` keeps the old
152
+ * everything-but-symlinks behaviour.
153
+ * @param {any} manifest - the package manifest (only `files` is read).
154
+ * @returns {{ includeFile: (relPath: string) => boolean, includeDir: (relDir: string) => boolean } | null} filter.
155
+ */
156
+ export function filesFilter(manifest) {
157
+ const declared = Array.isArray(manifest?.files)
158
+ ? manifest.files.filter((entry) => typeof entry === 'string' && entry.trim() !== '')
159
+ : [];
160
+ if (declared.length === 0) return null;
161
+ const patterns = declared.map((entry) => {
162
+ const normalized = entry.replace(/\\/g, '/').replace(/^\.?\//, '').replace(/\/+$/, '');
163
+ return { entry: normalized, regex: /[*?]/.test(normalized) ? globToRegExp(normalized) : null };
164
+ });
165
+ /* npm always ships these regardless of `files`. */
166
+ const alwaysFile = /^(?:readme|license|licence|changelog|history|notice)(?:\.[A-Za-z0-9]+)?$/;
167
+ const includeFile = (relPath) => {
168
+ if (relPath === 'package.json') return true;
169
+ if (!relPath.includes('/') && alwaysFile.test(relPath)) return true;
170
+ for (const pattern of patterns) {
171
+ if (pattern.regex !== null) {
172
+ if (pattern.regex.test(relPath)) return true;
173
+ } else if (relPath === pattern.entry || relPath.startsWith(pattern.entry + '/')) {
174
+ return true;
175
+ }
176
+ }
177
+ return false;
178
+ };
179
+ const includeDir = (relDir) => {
180
+ if (relDir === '') return true;
181
+ for (const pattern of patterns) {
182
+ if (pattern.regex !== null) {
183
+ /* A glob reaches anything below its literal prefix, so only a
184
+ * directory disjoint from that prefix can be pruned. */
185
+ const literal = pattern.entry.split(/[*?]/)[0];
186
+ const prefix = literal.includes('/') ? literal.slice(0, literal.lastIndexOf('/')) : '';
187
+ if (prefix === '' || prefix === relDir || prefix.startsWith(relDir + '/') || relDir.startsWith(prefix + '/')) return true;
188
+ continue;
189
+ }
190
+ if (pattern.entry === relDir || pattern.entry.startsWith(relDir + '/') || relDir.startsWith(pattern.entry + '/')) return true;
191
+ }
192
+ return false;
193
+ };
194
+ return { includeFile, includeDir };
195
+ }
196
+
197
+ /** Directory-size cache keyed by absolute path and mtime. */
198
+ const sizeCache = new Map();
199
+
200
+ /**
201
+ * Measure a package directory, reusing a cached result while its mtime holds.
202
+ * @param {string} dir - absolute package directory.
203
+ * @returns {{ bytes: number, files: number, newest: number }} aggregate size,
204
+ * file count, and the newest file mtime (epoch ms) seen while walking.
205
+ */
206
+ export function measureDir(dir) {
207
+ let stamp = 0;
208
+ try {
209
+ stamp = statSync(dir).mtimeMs;
210
+ } catch {
211
+ return { bytes: 0, files: 0, newest: 0 };
212
+ }
213
+ const cached = sizeCache.get(dir);
214
+ if (cached !== undefined && cached.stamp === stamp) return cached.value;
215
+ const files = listFiles(dir);
216
+ let bytes = 0;
217
+ let newest = 0;
218
+ for (const file of files) {
219
+ bytes += file.size;
220
+ const stampOfFile = file.mtime instanceof Date ? file.mtime.getTime() : 0;
221
+ if (stampOfFile > newest) newest = stampOfFile;
222
+ }
223
+ const value = { bytes, files: files.length, newest };
224
+ sizeCache.set(dir, { stamp, value });
225
+ return value;
226
+ }
227
+
228
+ /**
229
+ * Read the two dates a catalogue row shows: when this package directory
230
+ * appeared in the profile, and when its manifest last changed.
231
+ *
232
+ * Birth time is the honest "installed at" on a copy/import (Windows and
233
+ * macOS keep it, Linux reports 0), so it is preferred and mtime is the
234
+ * fallback for filesystems that cannot say.
235
+ * @param {string} dir - absolute package directory.
236
+ * @returns {{ installedAt: string | null, manifestAt: string | null }} ISO dates.
237
+ */
238
+ export function readPackageDates(dir) {
239
+ const stamps = (file) => {
240
+ try {
241
+ const info = statSync(file);
242
+ return {
243
+ born: Number.isFinite(info.birthtimeMs) && info.birthtimeMs > 0 ? info.birthtimeMs : info.mtimeMs,
244
+ modified: info.mtimeMs,
245
+ };
246
+ } catch {
247
+ return { born: 0, modified: 0 };
248
+ }
249
+ };
250
+ const manifest = stamps(join(dir, 'package.json'));
251
+ const root = stamps(dir);
252
+ const born = manifest.born > 0 ? manifest.born : root.born;
253
+ return {
254
+ installedAt: born > 0 ? new Date(born).toISOString() : null,
255
+ manifestAt: manifest.modified > 0 ? new Date(manifest.modified).toISOString() : null,
256
+ };
257
+ }
258
+
259
+ /**
260
+ * Read the profile manifest and the bundle roster it declares.
261
+ * @param {string} profileDir - absolute profile directory.
262
+ * @returns {{ manifest: any, dependencies: Record<string, string>, bundles: Set<string> }} profile facts.
263
+ */
264
+ export function readProfileFacts(profileDir) {
265
+ const manifest = readJson(join(profileDir, 'package.json'));
266
+ const dependencies = { ...(manifest.dependencies ?? {}) };
267
+ const bundles = new Set(Array.isArray(manifest.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : []);
268
+ return { manifest, dependencies, bundles };
269
+ }
270
+
271
+ /**
272
+ * Whether a package manifest describes an installable DSH plugin.
273
+ * @param {any} manifest - package.json contents.
274
+ * @returns {boolean} true when the package declares a bundle patch or a client half.
275
+ */
276
+ export function isPluginManifest(manifest) {
277
+ return manifest?.dsh?.bundle !== undefined || manifest?.dsh?.client !== undefined;
278
+ }
279
+
280
+ /** Sort keys the catalogue understands. */
281
+ export const SORT_KEYS = Object.freeze(['name', 'installed', 'updated', 'size', 'status', 'version']);
282
+
283
+ /**
284
+ * Build the catalogue the settings tab renders. Rows split three ways: plugin
285
+ * packages present in the profile (exportable), plugin dependencies that ship
286
+ * inside the application bundle (visible but not exportable, because their
287
+ * bytes are not on the profile filesystem), and ordinary dependencies, which
288
+ * are omitted because they are not plugins.
289
+ *
290
+ * Every row carries the two dates the tab shows (`installedAt` = when the
291
+ * directory appeared, `updatedAt` = newest file mtime) so the caller can sort
292
+ * and label without a second pass over the disk.
293
+ * @param {string} profileDir - absolute profile directory.
294
+ * @param {{ sort?: string, order?: 'asc' | 'desc' }} [options] - ordering.
295
+ * @returns {{ profile: string, sort: string, order: 'asc' | 'desc', rows: any[] }} catalogue.
296
+ */
297
+ export function listPlugins(profileDir, options = {}) {
298
+ const { dependencies, bundles } = readProfileFacts(profileDir);
299
+ const rows = [];
300
+ const seen = new Set();
301
+ const modulesRoot = join(profileDir, 'node_modules');
302
+ /**
303
+ * A package whose real path sits outside `node_modules` was installed as a
304
+ * link (`link:` dependency, junction or symlink) and points at a working
305
+ * tree. Its directory size then includes build caches, asset sources and
306
+ * deliverables that never ship, so the tab labels it instead of implying the
307
+ * plugin itself is that large.
308
+ */
309
+ const isLinked = (dir) => {
310
+ const rel = relative(modulesRoot, dir);
311
+ return rel === '' || rel.startsWith('..') || isAbsolute(rel);
312
+ };
313
+ const pushMeasured = (dir, row) => {
314
+ if (dir === null) {
315
+ rows.push(row);
316
+ return;
317
+ }
318
+ const measured = measureDir(dir);
319
+ const dates = readPackageDates(dir);
320
+ const newest = Math.max(measured.newest, dates.manifestAt === null ? 0 : Date.parse(dates.manifestAt));
321
+ rows.push({
322
+ ...row,
323
+ bytes: measured.bytes,
324
+ files: measured.files,
325
+ linked: isLinked(dir),
326
+ installedAt: dates.installedAt,
327
+ updatedAt: newest > 0 ? new Date(newest).toISOString() : null,
328
+ });
329
+ };
330
+ for (const [name, range] of Object.entries(dependencies)) {
331
+ seen.add(name);
332
+ const dir = resolvePackageDir(profileDir, name);
333
+ if (dir === null) {
334
+ pushMeasured(null, {
335
+ name,
336
+ range,
337
+ version: null,
338
+ installed: false,
339
+ exportable: false,
340
+ reason: 'bundled-in-app',
341
+ bundle: null,
342
+ client: null,
343
+ enabled: false,
344
+ description: null,
345
+ bytes: null,
346
+ files: null,
347
+ installedAt: null,
348
+ updatedAt: null,
349
+ });
350
+ continue;
351
+ }
352
+ const manifest = tryReadJson(join(dir, 'package.json'));
353
+ if (!isPluginManifest(manifest)) continue;
354
+ pushMeasured(dir, {
355
+ name,
356
+ range,
357
+ version: manifest.version ?? null,
358
+ installed: true,
359
+ exportable: true,
360
+ reason: null,
361
+ bundle: manifest.dsh?.bundle !== undefined,
362
+ client: manifest.dsh?.client !== undefined,
363
+ enabled: bundles.has(name),
364
+ description: typeof manifest.description === 'string' ? manifest.description : null,
365
+ });
366
+ }
367
+ /* Bundles the profile enables but does not depend on come from the
368
+ * application itself (the shipped @deepseek-ai layers). They are listed so
369
+ * the catalogue is complete; their bytes are not on the profile disk. */
370
+ for (const name of bundles) {
371
+ if (seen.has(name)) continue;
372
+ const dir = resolvePackageDir(profileDir, name);
373
+ if (dir === null) {
374
+ pushMeasured(null, {
375
+ name,
376
+ range: null,
377
+ version: null,
378
+ installed: false,
379
+ exportable: false,
380
+ reason: 'bundled-in-app',
381
+ bundle: true,
382
+ client: null,
383
+ enabled: true,
384
+ description: null,
385
+ bytes: null,
386
+ files: null,
387
+ installedAt: null,
388
+ updatedAt: null,
389
+ });
390
+ continue;
391
+ }
392
+ const manifest = tryReadJson(join(dir, 'package.json'));
393
+ pushMeasured(dir, {
394
+ name,
395
+ range: null,
396
+ version: manifest?.version ?? null,
397
+ installed: true,
398
+ exportable: isPluginManifest(manifest),
399
+ reason: isPluginManifest(manifest) ? null : 'not-a-plugin',
400
+ bundle: manifest?.dsh?.bundle !== undefined,
401
+ client: manifest?.dsh?.client !== undefined,
402
+ enabled: true,
403
+ description: typeof manifest?.description === 'string' ? manifest.description : null,
404
+ });
405
+ }
406
+ const sort = SORT_KEYS.includes(options.sort) ? options.sort : 'updated';
407
+ const order = options.order === 'asc' || options.order === 'desc'
408
+ ? options.order
409
+ : sort === 'name' || sort === 'status' || sort === 'version' ? 'asc' : 'desc';
410
+ const sortValue = (row) => {
411
+ switch (sort) {
412
+ case 'name': return row.name.toLowerCase();
413
+ case 'installed': return row.installedAt === null ? -1 : Date.parse(row.installedAt);
414
+ case 'updated': return row.updatedAt === null ? -1 : Date.parse(row.updatedAt);
415
+ case 'size': return row.bytes ?? -1;
416
+ case 'status': return row.exportable ? (row.enabled ? 0 : 1) : 2;
417
+ case 'version': return row.version ?? '';
418
+ default: return 0;
419
+ }
420
+ };
421
+ rows.sort((left, right) => {
422
+ const a = sortValue(left);
423
+ const b = sortValue(right);
424
+ const primary = typeof a === 'string' ? a.localeCompare(b) : a - b;
425
+ if (primary !== 0) return order === 'desc' ? -primary : primary;
426
+ /* A tie keeps exportable rows above application-bundled ones, then falls
427
+ * back to the name so the list never reshuffles between refreshes. */
428
+ const rank = (row) => (row.exportable ? (row.enabled ? 0 : 1) : 2);
429
+ return rank(left) - rank(right) || left.name.localeCompare(right.name);
430
+ });
431
+ return { profile: profileDir, sort, order, rows };
432
+ }
433
+
434
+ /**
435
+ * Expand one plugin into its dependency closure. Dependencies are followed
436
+ * through dependencies and through resolvable optionalDependencies /
437
+ * peerDependencies. Anything that does not resolve inside the profile ships
438
+ * with the application itself and is recorded as host-provided, not copied.
439
+ * @param {string} profileDir - absolute profile directory.
440
+ * @param {string} rootName - package name of the plugin to expand.
441
+ * @param {string | null} [knownDir] - directory of the root package when it is
442
+ * not installed in the profile (packing a plugin source tree).
443
+ * @returns {{ root: any, packages: any[], hostProvided: any[] }} closure.
444
+ */
445
+ export function expandClosure(profileDir, rootName, knownDir = null) {
446
+ const rootDir = knownDir ?? resolvePackageDir(profileDir, rootName);
447
+ if (rootDir === null) throw new Error('plugin "' + rootName + '" is not installed in this profile');
448
+ const rootManifest = tryReadJson(join(rootDir, 'package.json'));
449
+ if (!isPluginManifest(rootManifest)) throw new Error('package "' + rootName + '" is not a DSH plugin');
450
+ const packages = new Map();
451
+ const hostProvided = new Map();
452
+ const pending = [{ name: rootName, from: profileDir, requiredBy: null, dir: rootDir }];
453
+ while (pending.length > 0) {
454
+ const item = pending.shift();
455
+ if (item === undefined) break;
456
+ const dir = item.dir ?? resolvePackageDir(item.from, item.name);
457
+ const manifest = dir === null ? undefined : tryReadJson(join(dir, 'package.json'));
458
+ if (dir === null || manifest === undefined) {
459
+ const known = hostProvided.get(item.name);
460
+ if (known === undefined) hostProvided.set(item.name, { name: item.name, requiredBy: [item.requiredBy] });
461
+ else if (item.requiredBy !== null && !known.requiredBy.includes(item.requiredBy)) known.requiredBy.push(item.requiredBy);
462
+ continue;
463
+ }
464
+ if (packages.has(dir)) continue;
465
+ const dependencies = manifest.dependencies ?? {};
466
+ const optional = manifest.optionalDependencies ?? {};
467
+ const peers = manifest.peerDependencies ?? {};
468
+ const peerMeta = manifest.peerDependenciesMeta ?? {};
469
+ const owner = manifest.name ?? item.name;
470
+ packages.set(dir, {
471
+ name: owner,
472
+ version: typeof manifest.version === 'string' ? manifest.version : null,
473
+ dir,
474
+ dependencies,
475
+ /* Kept so planArchive can honour the package's own `files` allow-list. */
476
+ files: Array.isArray(manifest.files) ? manifest.files : null,
477
+ });
478
+ for (const depName of Object.keys(dependencies)) pending.push({ name: depName, from: dir, requiredBy: owner });
479
+ for (const depName of Object.keys(optional)) pending.push({ name: depName, from: dir, requiredBy: owner });
480
+ for (const depName of Object.keys(peers)) {
481
+ if (peerMeta[depName]?.optional === true && resolvePackageDir(dir, depName) === null) continue;
482
+ pending.push({ name: depName, from: dir, requiredBy: owner });
483
+ }
484
+ }
485
+ const list = [...packages.values()];
486
+ list.sort((left, right) => (left.name === rootName ? -1 : right.name === rootName ? 1 : left.name.localeCompare(right.name)));
487
+ return {
488
+ root: {
489
+ name: rootName,
490
+ version: rootManifest.version ?? null,
491
+ bundle: rootManifest.dsh?.bundle !== undefined,
492
+ client: rootManifest.dsh?.client !== undefined,
493
+ },
494
+ packages: list,
495
+ hostProvided: [...hostProvided.values()].sort((left, right) => left.name.localeCompare(right.name)),
496
+ };
497
+ }
498
+
499
+ /**
500
+ * Compute the archive layout for a closure.
501
+ * @param {string} profileDir - absolute profile directory.
502
+ * @param {{ packages: any[] }} closure - expanded closure.
503
+ * @returns {{ relative: (dir: string) => string, sources: any[], total: number, files: number }} archive plan.
504
+ */
505
+ export function planArchive(profileDir, closure) {
506
+ const modulesRoot = join(profileDir, 'node_modules');
507
+ const relativeByDir = new Map();
508
+ for (const entry of closure.packages) {
509
+ const relInside = relative(modulesRoot, entry.dir);
510
+ /* A package linked from another drive makes relative() return an absolute
511
+ * path; that is not portable, so the archive keeps the package name. */
512
+ const portable = relInside !== '' && !isAbsolute(relInside) && !relInside.startsWith('..') && !relInside.includes(sep + '.pnpm');
513
+ relativeByDir.set(entry.dir, posix.join('packages', (portable ? relInside : entry.name).split(sep).join('/')));
514
+ }
515
+ const sources = [];
516
+ let total = 0;
517
+ for (const entry of closure.packages) {
518
+ const prefix = relativeByDir.get(entry.dir);
519
+ const filter = filesFilter({ files: entry.files });
520
+ for (const file of listFiles(entry.dir, 200000, filter)) {
521
+ sources.push({ name: prefix + '/' + file.path, file: join(entry.dir, file.path), size: file.size, mtime: file.mtime });
522
+ total += file.size;
523
+ }
524
+ }
525
+ return { relative: (dir) => relativeByDir.get(dir) ?? posix.join('packages', dir), sources, total, files: sources.length };
526
+ }
527
+
528
+ /**
529
+ * Build the manifest stored at the archive root.
530
+ * @param {any} closure - expanded closure.
531
+ * @param {any} plan - archive plan.
532
+ * @param {{ profileName: string, enabled: boolean, generatorVersion: string }} info - profile facts.
533
+ * @returns {any} manifest object.
534
+ */
535
+ export function buildManifest(closure, plan, info) {
536
+ const assets = Array.isArray(info.assets) ? info.assets : [];
537
+ return {
538
+ format: PACK_FORMAT,
539
+ // Additive: only a pack that carries runtime assets needs format 2.
540
+ formatVersion: assets.length === 0 ? 1 : PACK_FORMAT_VERSION,
541
+ createdAt: new Date().toISOString(),
542
+ generator: { name: 'dsh-plugin-packer', version: info.generatorVersion },
543
+ profile: { name: info.profileName },
544
+ root: { ...closure.root, enabled: info.enabled },
545
+ packages: closure.packages.map((entry) => ({
546
+ name: entry.name,
547
+ version: entry.version,
548
+ path: plan.relative(entry.dir),
549
+ dependencies: entry.dependencies,
550
+ })),
551
+ hostProvided: closure.hostProvided,
552
+ assets,
553
+ totals: {
554
+ packages: closure.packages.length,
555
+ files: plan.files,
556
+ bytes: plan.total,
557
+ assets: assets.length,
558
+ assetBytes: assets.reduce((sum, asset) => sum + (asset?.totals?.bytes ?? 0), 0),
559
+ assetFiles: assets.reduce((sum, asset) => sum + (asset?.totals?.files ?? 0), 0),
560
+ },
561
+ };
562
+ }
563
+
564
+ /**
565
+ * Sanitize an archive entry name into a path below the extraction root.
566
+ * @param {string} name - entry name from the archive.
567
+ * @returns {string | null} safe POSIX-relative path, or null when unacceptable.
568
+ */
569
+ export function safeEntryPath(name) {
570
+ if (name.includes('\\')) return null;
571
+ if (name.startsWith('/') || /^[a-zA-Z]:/.test(name)) return null;
572
+ const normalized = posix.normalize(name);
573
+ if (normalized === '.' || normalized === '..') return null;
574
+ if (normalized.startsWith('../')) return null;
575
+ if (normalized.split('/').includes('..')) return null;
576
+ return normalized;
577
+ }
578
+
579
+ /**
580
+ * Extract an archive into a fresh directory.
581
+ * @param {string} targetDir - directory to extract into (created).
582
+ * @param {{ name: string, directory: boolean, data: Buffer }[]} members - archive members.
583
+ * @returns {Promise<number>} number of files written.
584
+ */
585
+ export async function extractArchive(targetDir, members) {
586
+ await mkdir(targetDir, { recursive: true });
587
+ let written = 0;
588
+ for (const member of members) {
589
+ const safe = safeEntryPath(member.name);
590
+ if (safe === null) throw new Error('archive contains an unsafe path: ' + member.name);
591
+ const destination = join(targetDir, safe.split('/').join(sep));
592
+ if (member.directory) {
593
+ await mkdir(destination, { recursive: true });
594
+ continue;
595
+ }
596
+ await mkdir(dirname(destination), { recursive: true });
597
+ await writeFile(destination, member.data);
598
+ written += 1;
599
+ }
600
+ return written;
601
+ }
602
+
603
+ /**
604
+ * Keep only the newest `keep` backup batches under a backup root.
605
+ *
606
+ * Every import moves the displaced package directories aside, and every asset
607
+ * import moves the displaced environment aside too. On a machine that swaps
608
+ * plugin versions a few times those piles add up to gigabytes, so pruning is
609
+ * part of installing rather than an afterthought. Directories that do not look
610
+ * like our own batches are left alone.
611
+ * @param {string} backupRoot - `<profile>/.plugin-packer/backups`.
612
+ * @param {number} [keep] - batches to retain.
613
+ * @returns {Promise<{ removed: string[], kept: string[] }>} what changed.
614
+ */
615
+ export async function pruneBackups(backupRoot, keep = 5) {
616
+ let entries;
617
+ try {
618
+ entries = readdirSync(backupRoot, { withFileTypes: true });
619
+ } catch {
620
+ return { removed: [], kept: [] };
621
+ }
622
+ const batches = entries
623
+ .filter((entry) => entry.isDirectory())
624
+ .map((entry) => {
625
+ let stamp = 0;
626
+ try {
627
+ stamp = statSync(join(backupRoot, entry.name)).mtimeMs;
628
+ } catch {
629
+ stamp = 0;
630
+ }
631
+ return { name: entry.name, stamp };
632
+ })
633
+ .sort((left, right) => right.stamp - left.stamp);
634
+ const kept = batches.slice(0, Math.max(0, keep)).map((entry) => entry.name);
635
+ const removed = [];
636
+ for (const batch of batches.slice(Math.max(0, keep))) {
637
+ try {
638
+ await rm(join(backupRoot, batch.name), { recursive: true, force: true });
639
+ removed.push(batch.name);
640
+ } catch {
641
+ /* a locked file keeps its batch; it is retried on the next import */
642
+ }
643
+ }
644
+ return { removed, kept };
645
+ }
646
+
647
+ /**
648
+ * Install an extracted pack into the profile. Existing package directories
649
+ * are moved aside first, so a failed import never destroys the working
650
+ * installation. The profile manifest records the root plugin as a dependency;
651
+ * the caller decides whether the bundle is enabled.
652
+ * @param {string} profileDir - absolute profile directory.
653
+ * @param {string} packDir - directory the archive was extracted into.
654
+ * @param {string} backupRoot - directory that receives displaced packages.
655
+ * @returns {Promise<{ root: any, replaced: string[], installed: string[], manifest: any }>} install report.
656
+ */
657
+ export async function installPack(profileDir, packDir, backupRoot) {
658
+ const manifest = tryReadJson(join(packDir, 'manifest.json'));
659
+ if (manifest === undefined) throw new Error('archive has no manifest.json');
660
+ if (manifest.format !== PACK_FORMAT) throw new Error('archive is not a DSH plugin pack (format: ' + String(manifest.format) + ')');
661
+ if (!ACCEPTED_FORMAT_VERSIONS.includes(manifest.formatVersion)) throw new Error('unsupported pack format version ' + String(manifest.formatVersion) + ' (expected one of ' + ACCEPTED_FORMAT_VERSIONS.join(', ') + ')');
662
+ if (!Array.isArray(manifest.packages) || manifest.packages.length === 0) throw new Error('archive lists no packages');
663
+ const modulesRoot = join(profileDir, 'node_modules');
664
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
665
+ const replaced = [];
666
+ const installed = [];
667
+ for (const entry of manifest.packages) {
668
+ if (typeof entry?.name !== 'string' || !PACKAGE_NAME.test(entry.name)) throw new Error('archive lists an invalid package name: ' + String(entry?.name));
669
+ if (typeof entry?.path !== 'string') throw new Error('archive entry for ' + entry.name + ' has no path');
670
+ const safe = safeEntryPath(entry.path);
671
+ if (safe === null) throw new Error('archive lists an unsafe package path: ' + entry.path);
672
+ const source = join(packDir, safe.split('/').join(sep));
673
+ if (!existsSync(join(source, 'package.json'))) throw new Error('archive is missing package contents for ' + entry.name);
674
+ const destination = join(modulesRoot, entry.name.split('/').join(sep));
675
+ if (existsSync(destination)) {
676
+ const backup = join(backupRoot, stamp, entry.name.split('/').join(sep));
677
+ await mkdir(dirname(backup), { recursive: true });
678
+ await rename(destination, backup);
679
+ replaced.push(entry.name);
680
+ }
681
+ await mkdir(dirname(destination), { recursive: true });
682
+ await cp(source, destination, { recursive: true, dereference: true });
683
+ installed.push(entry.name);
684
+ }
685
+ const profileManifest = readJson(join(profileDir, 'package.json'));
686
+ const dependencies = { ...(profileManifest.dependencies ?? {}) };
687
+ if (typeof manifest.root?.name === 'string') {
688
+ const version = manifest.root.version;
689
+ dependencies[manifest.root.name] = typeof version === 'string' ? '^' + version : '*';
690
+ }
691
+ profileManifest.dependencies = dependencies;
692
+ await writeFile(join(profileDir, 'package.json'), JSON.stringify(profileManifest, null, 2) + '\n');
693
+ return { root: manifest.root, replaced, installed, manifest, packDir, formatVersion: manifest.formatVersion };
694
+ }