@solidxai/core 0.1.20-beta.2 → 0.1.20-beta.3

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.
Files changed (125) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/controllers/chatter-message-archive.controller.d.ts +22 -0
  3. package/dist/controllers/chatter-message-archive.controller.d.ts.map +1 -0
  4. package/dist/controllers/chatter-message-archive.controller.js +69 -0
  5. package/dist/controllers/chatter-message-archive.controller.js.map +1 -0
  6. package/dist/controllers/module-package.controller.d.ts +493 -1
  7. package/dist/controllers/module-package.controller.d.ts.map +1 -1
  8. package/dist/controllers/module-package.controller.js +47 -3
  9. package/dist/controllers/module-package.controller.js.map +1 -1
  10. package/dist/decorators/chatter-message-archive-provider.decorator.d.ts +3 -0
  11. package/dist/decorators/chatter-message-archive-provider.decorator.d.ts.map +1 -0
  12. package/dist/decorators/chatter-message-archive-provider.decorator.js +8 -0
  13. package/dist/decorators/chatter-message-archive-provider.decorator.js.map +1 -0
  14. package/dist/dtos/confirm-module-package-import.dto.d.ts +2 -0
  15. package/dist/dtos/confirm-module-package-import.dto.d.ts.map +1 -1
  16. package/dist/dtos/confirm-module-package-import.dto.js +20 -1
  17. package/dist/dtos/confirm-module-package-import.dto.js.map +1 -1
  18. package/dist/dtos/create-module-metadata.dto.d.ts +1 -0
  19. package/dist/dtos/create-module-metadata.dto.d.ts.map +1 -1
  20. package/dist/dtos/create-module-metadata.dto.js +7 -1
  21. package/dist/dtos/create-module-metadata.dto.js.map +1 -1
  22. package/dist/dtos/export-module-package.dto.d.ts +7 -0
  23. package/dist/dtos/export-module-package.dto.d.ts.map +1 -0
  24. package/dist/dtos/export-module-package.dto.js +44 -0
  25. package/dist/dtos/export-module-package.dto.js.map +1 -0
  26. package/dist/dtos/run-module-package-seed.dto.d.ts +1 -0
  27. package/dist/dtos/run-module-package-seed.dto.d.ts.map +1 -1
  28. package/dist/dtos/run-module-package-seed.dto.js +11 -1
  29. package/dist/dtos/run-module-package-seed.dto.js.map +1 -1
  30. package/dist/dtos/validate-module-package-import.dto.d.ts +4 -0
  31. package/dist/dtos/validate-module-package-import.dto.d.ts.map +1 -0
  32. package/dist/dtos/validate-module-package-import.dto.js +30 -0
  33. package/dist/dtos/validate-module-package-import.dto.js.map +1 -0
  34. package/dist/entities/agent-registry.entity.js.map +1 -1
  35. package/dist/entities/module-metadata.entity.d.ts +1 -0
  36. package/dist/entities/module-metadata.entity.d.ts.map +1 -1
  37. package/dist/entities/module-metadata.entity.js +5 -1
  38. package/dist/entities/module-metadata.entity.js.map +1 -1
  39. package/dist/helpers/agent-required-inputs.d.ts.map +1 -1
  40. package/dist/helpers/agent-required-inputs.js +25 -1
  41. package/dist/helpers/agent-required-inputs.js.map +1 -1
  42. package/dist/helpers/bootstrap.helper.d.ts +1 -1
  43. package/dist/helpers/bootstrap.helper.d.ts.map +1 -1
  44. package/dist/helpers/bootstrap.helper.js +9 -3
  45. package/dist/helpers/bootstrap.helper.js.map +1 -1
  46. package/dist/helpers/solid-registry.d.ts +4 -0
  47. package/dist/helpers/solid-registry.d.ts.map +1 -1
  48. package/dist/helpers/solid-registry.js +11 -0
  49. package/dist/helpers/solid-registry.js.map +1 -1
  50. package/dist/index.d.ts +3 -0
  51. package/dist/index.d.ts.map +1 -1
  52. package/dist/index.js +3 -0
  53. package/dist/index.js.map +1 -1
  54. package/dist/interfaces/chatter-message-archive.interface.d.ts +22 -0
  55. package/dist/interfaces/chatter-message-archive.interface.d.ts.map +1 -0
  56. package/dist/interfaces/chatter-message-archive.interface.js +3 -0
  57. package/dist/interfaces/chatter-message-archive.interface.js.map +1 -0
  58. package/dist/seeders/module-metadata-seeder.service.js +1 -1
  59. package/dist/seeders/module-metadata-seeder.service.js.map +1 -1
  60. package/dist/seeders/seed-data/solid-core-metadata.json +102 -10
  61. package/dist/services/agent-tool-registry.service.d.ts.map +1 -1
  62. package/dist/services/agent-tool-registry.service.js +10 -6
  63. package/dist/services/agent-tool-registry.service.js.map +1 -1
  64. package/dist/services/chatter-message-archive.service.d.ts +17 -0
  65. package/dist/services/chatter-message-archive.service.d.ts.map +1 -0
  66. package/dist/services/chatter-message-archive.service.js +82 -0
  67. package/dist/services/chatter-message-archive.service.js.map +1 -0
  68. package/dist/services/model-metadata.service.js +1 -1
  69. package/dist/services/model-metadata.service.js.map +1 -1
  70. package/dist/services/module-package.service.d.ts +162 -3
  71. package/dist/services/module-package.service.d.ts.map +1 -1
  72. package/dist/services/module-package.service.js +465 -18
  73. package/dist/services/module-package.service.js.map +1 -1
  74. package/dist/services/settings/default-settings-provider.service.d.ts +20 -0
  75. package/dist/services/settings/default-settings-provider.service.d.ts.map +1 -1
  76. package/dist/services/settings/default-settings-provider.service.js +11 -0
  77. package/dist/services/settings/default-settings-provider.service.js.map +1 -1
  78. package/dist/services/solid-introspect.service.d.ts.map +1 -1
  79. package/dist/services/solid-introspect.service.js +5 -0
  80. package/dist/services/solid-introspect.service.js.map +1 -1
  81. package/dist/solid-core.module.d.ts.map +1 -1
  82. package/dist/solid-core.module.js +4 -0
  83. package/dist/solid-core.module.js.map +1 -1
  84. package/dist/testing/adapters/ui/playwright-adapter.d.ts +4 -0
  85. package/dist/testing/adapters/ui/playwright-adapter.d.ts.map +1 -1
  86. package/dist/testing/adapters/ui/playwright-adapter.js +35 -0
  87. package/dist/testing/adapters/ui/playwright-adapter.js.map +1 -1
  88. package/dist/testing/core/interpolation.d.ts.map +1 -1
  89. package/dist/testing/core/interpolation.js +38 -2
  90. package/dist/testing/core/interpolation.js.map +1 -1
  91. package/dist/testing/steps/ui/actions.step.d.ts.map +1 -1
  92. package/dist/testing/steps/ui/actions.step.js +40 -3
  93. package/dist/testing/steps/ui/actions.step.js.map +1 -1
  94. package/dist/testing/steps/ui/navigation.step.d.ts.map +1 -1
  95. package/dist/testing/steps/ui/navigation.step.js +39 -0
  96. package/dist/testing/steps/ui/navigation.step.js.map +1 -1
  97. package/package.json +4 -2
  98. package/src/controllers/chatter-message-archive.controller.ts +32 -0
  99. package/src/controllers/module-package.controller.ts +33 -1
  100. package/src/decorators/chatter-message-archive-provider.decorator.ts +4 -0
  101. package/src/dtos/confirm-module-package-import.dto.ts +17 -1
  102. package/src/dtos/create-module-metadata.dto.ts +5 -0
  103. package/src/dtos/export-module-package.dto.ts +23 -0
  104. package/src/dtos/run-module-package-seed.dto.ts +8 -0
  105. package/src/dtos/validate-module-package-import.dto.ts +11 -0
  106. package/src/entities/agent-registry.entity.ts +1 -1
  107. package/src/entities/module-metadata.entity.ts +3 -0
  108. package/src/helpers/agent-required-inputs.ts +18 -1
  109. package/src/helpers/bootstrap.helper.ts +15 -6
  110. package/src/helpers/solid-registry.ts +14 -0
  111. package/src/index.ts +3 -0
  112. package/src/interfaces/chatter-message-archive.interface.ts +22 -0
  113. package/src/seeders/module-metadata-seeder.service.ts +2 -2
  114. package/src/seeders/seed-data/solid-core-metadata.json +102 -10
  115. package/src/services/agent-tool-registry.service.ts +10 -6
  116. package/src/services/chatter-message-archive.service.ts +72 -0
  117. package/src/services/model-metadata.service.ts +1 -1
  118. package/src/services/module-package.service.ts +597 -14
  119. package/src/services/settings/default-settings-provider.service.ts +11 -0
  120. package/src/services/solid-introspect.service.ts +6 -0
  121. package/src/solid-core.module.ts +4 -0
  122. package/src/testing/adapters/ui/playwright-adapter.ts +44 -0
  123. package/src/testing/core/interpolation.ts +42 -2
  124. package/src/testing/steps/ui/actions.step.ts +52 -4
  125. package/src/testing/steps/ui/navigation.step.ts +56 -0
@@ -4,15 +4,20 @@ import {
4
4
  Logger,
5
5
  NotFoundException,
6
6
  } from '@nestjs/common';
7
+ import { InjectDataSource } from '@nestjs/typeorm';
7
8
  import { createHash } from 'crypto';
8
9
  import archiver from 'archiver';
9
10
  import { createWriteStream } from 'fs';
11
+ import * as semver from 'semver';
10
12
  import { DisallowInProduction } from 'src/decorators/disallow-in-production.decorator';
11
13
  import { ConfirmModulePackageImportDto } from 'src/dtos/confirm-module-package-import.dto';
14
+ import { ExportModulePackageDto } from 'src/dtos/export-module-package.dto';
12
15
  import { RunModulePackageBuildDto } from 'src/dtos/run-module-package-build.dto';
13
16
  import { RunModulePackageSeedDto } from 'src/dtos/run-module-package-seed.dto';
17
+ import { ModuleMetadata } from 'src/entities/module-metadata.entity';
14
18
  import { CommandService } from 'src/helpers/command.service';
15
19
  import { ModuleMetadataHelperService } from 'src/helpers/module-metadata-helper.service';
20
+ import { DataSource } from 'typeorm';
16
21
  import * as fs from 'fs/promises';
17
22
  import * as path from 'path';
18
23
  import { v4 as uuidv4 } from 'uuid';
@@ -27,6 +32,7 @@ type ModulePackageManifest = {
27
32
  };
28
33
  module: {
29
34
  name: string;
35
+ version?: string;
30
36
  displayName?: string;
31
37
  description?: string;
32
38
  };
@@ -46,12 +52,45 @@ type ValidationPayload = {
46
52
  warnings: string[];
47
53
  };
48
54
 
55
+ type ModulePackageMode = 'install' | 'update';
56
+
57
+ // new: module not installed. first_version: installed module is unversioned, package is versioned.
58
+ // legacy_package: package is unversioned while the module is installed.
59
+ type ModulePackageVersionComparison = 'new' | 'upgrade' | 'same' | 'downgrade' | 'first_version' | 'legacy_package';
60
+
61
+ type ModulePackageFileDiff = {
62
+ added: string[];
63
+ modified: string[];
64
+ removed: string[];
65
+ unchangedCount: number;
66
+ };
67
+
68
+ type ModulePackageChangeSet = {
69
+ solidApi: ModulePackageFileDiff;
70
+ solidUi: ModulePackageFileDiff;
71
+ };
72
+
73
+ type ModulePackageBackup = {
74
+ path: string;
75
+ version: string | null;
76
+ createdAt: string;
77
+ };
78
+
49
79
  type PreviewPayload = {
50
80
  module: {
51
81
  name: string;
82
+ version?: string;
52
83
  displayName?: string;
53
84
  description?: string;
54
85
  };
86
+ mode: ModulePackageMode;
87
+ installedVersion: string | null;
88
+ incomingVersion: string | null;
89
+ versionComparison: ModulePackageVersionComparison | null;
90
+ requiresVersionAcknowledgement: boolean;
91
+ identicalContent: boolean;
92
+ contentFingerprint: string | null;
93
+ changeSet: ModulePackageChangeSet | null;
55
94
  manifest: ModulePackageManifest;
56
95
  contentsSummary: {
57
96
  totalEntries: number;
@@ -92,10 +131,17 @@ type ModulePackageStatusFile = {
92
131
  preview: PreviewPayload | null;
93
132
  validation: ValidationPayload | null;
94
133
  conflicts: string[];
134
+ mode: ModulePackageMode;
135
+ installedVersion: string | null;
136
+ incomingVersion: string | null;
137
+ versionComparison: ModulePackageVersionComparison | null;
138
+ backup: ModulePackageBackup | null;
139
+ restoredFromBackup: boolean;
95
140
  outputs: {
96
141
  import: string | null;
97
142
  build: string | null;
98
143
  seed: string | null;
144
+ restore: string | null;
99
145
  };
100
146
  errorMessage: string | null;
101
147
  createdAt: string;
@@ -114,10 +160,16 @@ type ModulePackageRuntimeCleanupResult = {
114
160
  removedExportTransactions: number;
115
161
  removedImportLooseEntries: number;
116
162
  removedExportLooseEntries: number;
163
+ removedBackups: number;
117
164
  clearedActiveTransactionPointer: boolean;
118
165
  clearedAt: string;
119
166
  };
120
167
 
168
+ type InstalledModuleState = {
169
+ installed: boolean;
170
+ version: string | null;
171
+ };
172
+
121
173
  type ModulePackageActiveTransactionFile = {
122
174
  transactionKey: string;
123
175
  updatedAt: string;
@@ -134,6 +186,7 @@ enum ModulePackageStatus {
134
186
  build_succeeded = 'build_succeeded',
135
187
  seed_running = 'seed_running',
136
188
  seed_failed = 'seed_failed',
189
+ restore_running = 'restore_running',
137
190
  completed = 'completed',
138
191
  failed = 'failed',
139
192
  }
@@ -143,14 +196,18 @@ export class ModulePackageService {
143
196
  private readonly logger = new Logger(ModulePackageService.name);
144
197
  private static readonly SUPPORTED_SCHEMA_VERSION = '1.0';
145
198
  private static readonly SUPPORTED_PACKAGE_TYPE = 'solidx-module';
199
+ private static readonly OVERWRITE_CONFIRMATION_WARNING = 'The target module already exists locally and will require overwrite confirmation.';
200
+ private static readonly VERSION_ACKNOWLEDGEMENT_COMPARISONS: ModulePackageVersionComparison[] = ['same', 'downgrade', 'legacy_package'];
146
201
 
147
202
  constructor(
148
203
  private readonly commandService: CommandService,
149
204
  private readonly moduleMetadataHelperService: ModuleMetadataHelperService,
205
+ @InjectDataSource()
206
+ private readonly dataSource: DataSource,
150
207
  ) { }
151
208
 
152
209
  @DisallowInProduction()
153
- async validateUpload(file: Express.Multer.File) {
210
+ async validateUpload(file: Express.Multer.File, expectedModuleNameInput?: string) {
154
211
  if (!file) {
155
212
  throw new BadRequestException('A .sldx archive file is required.');
156
213
  }
@@ -168,6 +225,11 @@ export class ModulePackageService {
168
225
 
169
226
  const parsed = await this.parseArchive(archiveFilePath);
170
227
  await this.extractArchive(archiveFilePath, extractDirPath);
228
+ await this.applyInstallStateToPreview(
229
+ parsed,
230
+ this.resolveExtractRoot(extractDirPath, parsed.archiveRootPrefix),
231
+ (expectedModuleNameInput ?? '').trim() || null,
232
+ );
171
233
 
172
234
  const transaction: ModulePackageStatusFile = {
173
235
  transactionKey,
@@ -184,10 +246,17 @@ export class ModulePackageService {
184
246
  preview: parsed.preview,
185
247
  validation: parsed.validation,
186
248
  conflicts: parsed.preview.conflicts,
249
+ mode: parsed.preview.mode,
250
+ installedVersion: parsed.preview.installedVersion,
251
+ incomingVersion: parsed.preview.incomingVersion,
252
+ versionComparison: parsed.preview.versionComparison,
253
+ backup: null,
254
+ restoredFromBackup: false,
187
255
  outputs: {
188
256
  import: null,
189
257
  build: null,
190
258
  seed: null,
259
+ restore: null,
191
260
  },
192
261
  errorMessage: parsed.validation.valid ? null : parsed.validation.errors.join('\n'),
193
262
  createdAt: new Date().toISOString(),
@@ -236,7 +305,7 @@ export class ModulePackageService {
236
305
  }
237
306
 
238
307
  @DisallowInProduction()
239
- async exportModulePackage(moduleNameInput: string): Promise<ModulePackageExportFile> {
308
+ async exportModulePackage(moduleNameInput: string, dto: ExportModulePackageDto = {}): Promise<ModulePackageExportFile> {
240
309
  const moduleName = (moduleNameInput ?? '').trim();
241
310
  if (!moduleName) {
242
311
  throw new BadRequestException('A module name is required to export a module package.');
@@ -250,15 +319,23 @@ export class ModulePackageService {
250
319
  await this.assertPathExists(solidUiModulePath, 'solid-ui module path');
251
320
  await this.assertPathExists(metadataFilePath, 'module metadata file');
252
321
 
253
- const metadataDocument = this.parseMetadataDocument(
322
+ let metadataDocument = this.parseMetadataDocument(
254
323
  await fs.readFile(metadataFilePath, 'utf-8'),
255
324
  [],
256
325
  );
257
326
 
327
+ const currentVersion = this.toValidVersion(metadataDocument?.moduleMetadata?.version);
328
+ const exportVersion = this.resolveExportVersion(currentVersion, dto);
329
+ if (exportVersion !== currentVersion) {
330
+ // The version is owned by the metadata file, so write it back before staging the package.
331
+ metadataDocument = await this.writeModuleVersion(metadataFilePath, exportVersion);
332
+ await this.syncModuleVersionInDb(moduleName, exportVersion);
333
+ }
334
+
258
335
  const transactionKey = uuidv4();
259
336
  const exportRoot = path.join(this.getModulePackageExportsRoot(), transactionKey);
260
337
  const stagingDir = path.join(exportRoot, 'staging');
261
- const archiveFileName = `${moduleName}.sldx`;
338
+ const archiveFileName = exportVersion ? `${moduleName}-v${exportVersion}.sldx` : `${moduleName}.sldx`;
262
339
  const archiveFilePath = path.join(exportRoot, archiveFileName);
263
340
 
264
341
  await fs.mkdir(path.join(stagingDir, 'solid-api', 'src'), { recursive: true });
@@ -300,8 +377,13 @@ export class ModulePackageService {
300
377
  });
301
378
  }
302
379
 
303
- const overwriteExisting = dto.overwriteExisting ?? false;
304
- if (preview.conflicts.length > 0 && !overwriteExisting) {
380
+ const isUpdate = transaction.mode === 'update';
381
+ if (isUpdate) {
382
+ await this.assertUpdateApproved(transaction, dto);
383
+ }
384
+
385
+ const overwriteExisting = isUpdate || (dto.overwriteExisting ?? false);
386
+ if (!isUpdate && preview.conflicts.length > 0 && !overwriteExisting) {
305
387
  throw new BadRequestException({
306
388
  message: 'Conflicts were detected. Re-submit with overwriteExisting=true to continue.',
307
389
  conflicts: preview.conflicts,
@@ -317,15 +399,18 @@ export class ModulePackageService {
317
399
  const moduleName = preview.module.name;
318
400
  const solidApiTarget = this.getSolidApiModuleTargetPath(moduleName);
319
401
  const solidUiTarget = this.getSolidUiModuleTargetPath(moduleName);
320
- const extractRoot = transaction.archiveRootPrefix
321
- ? path.join(transaction.extractDirPath as string, transaction.archiveRootPrefix.replace(/\/$/, ''))
322
- : transaction.extractDirPath as string;
402
+ const extractRoot = this.resolveExtractRoot(transaction.extractDirPath as string, transaction.archiveRootPrefix);
323
403
  const solidApiSource = path.join(extractRoot, 'solid-api', 'src', moduleName);
324
404
  const solidUiSource = path.join(extractRoot, 'solid-ui', 'src', moduleName);
325
405
 
326
406
  await this.assertPathExists(solidApiSource, 'solid-api module source');
327
407
  await this.assertPathExists(solidUiSource, 'solid-ui module source');
328
408
 
409
+ if (isUpdate) {
410
+ transaction.backup = await this.backupModuleFolders(transactionKey, moduleName, transaction.installedVersion);
411
+ await this.writeStatusFile(transactionKey, transaction);
412
+ }
413
+
329
414
  if (overwriteExisting) {
330
415
  await fs.rm(solidApiTarget, { recursive: true, force: true });
331
416
  await fs.rm(solidUiTarget, { recursive: true, force: true });
@@ -337,6 +422,12 @@ export class ModulePackageService {
337
422
  await fs.cp(solidApiSource, solidApiTarget, { recursive: true, force: overwriteExisting });
338
423
  await fs.cp(solidUiSource, solidUiTarget, { recursive: true, force: overwriteExisting });
339
424
 
425
+ // The installed metadata file records the installed version, whichever tool produced the package.
426
+ await this.writeModuleVersion(
427
+ await this.moduleMetadataHelperService.getModuleMetadataFilePath(moduleName),
428
+ transaction.incomingVersion,
429
+ );
430
+
340
431
  if (transaction.extractDirPath) {
341
432
  await fs.rm(transaction.extractDirPath, { recursive: true, force: true });
342
433
  transaction.extractDirPath = null;
@@ -345,10 +436,14 @@ export class ModulePackageService {
345
436
  transaction.status = ModulePackageStatus.awaiting_restart;
346
437
  transaction.currentStep = 'restart';
347
438
  transaction.outputs.import = [
439
+ isUpdate
440
+ ? `Updated ${moduleName} from ${this.formatVersion(transaction.installedVersion)} to ${this.formatVersion(transaction.incomingVersion)}`
441
+ : null,
348
442
  `Placed solid-api module at ${solidApiTarget}`,
349
443
  `Placed solid-ui module at ${solidUiTarget}`,
350
444
  `Metadata file placed at ${preview.requiredPaths.metadataPath}`,
351
- ].join('\n');
445
+ transaction.backup ? `Backed up the previous module folders to ${transaction.backup.path}` : null,
446
+ ].filter(Boolean).join('\n');
352
447
  await this.writeStatusFile(transactionKey, transaction);
353
448
  await this.syncActiveTransactionPointer(transaction);
354
449
 
@@ -444,15 +539,16 @@ export class ModulePackageService {
444
539
  await this.writeStatusFile(transactionKey, transaction);
445
540
 
446
541
  try {
542
+ const seedArgs = ['seed', '--modules-to-seed', moduleName, ...(dto.prune ? ['--prune'] : [])];
447
543
  const output = await this.commandService.executeCommandWithArgs({
448
544
  command: 'npx',
449
- args: ['-y', '@solidxai/solidctl@latest', 'seed', '--modules-to-seed', moduleName],
545
+ args: ['-y', '@solidxai/solidctl@latest', ...seedArgs],
450
546
  cwd: this.getProjectRoot(),
451
547
  });
452
548
  transaction.status = ModulePackageStatus.completed;
453
549
  transaction.currentStep = 'done';
454
550
  transaction.outputs.seed = [
455
- `solidctl seed --modules-to-seed ${moduleName} [success]`,
551
+ `solidctl ${seedArgs.join(' ')} [success]`,
456
552
  output,
457
553
  ].filter(Boolean).join('\n');
458
554
  await this.writeStatusFile(transactionKey, transaction);
@@ -470,6 +566,110 @@ export class ModulePackageService {
470
566
  }
471
567
  }
472
568
 
569
+ // The most recent update backup of a module that has not been restored yet, so a finished update can still be rolled back.
570
+ @DisallowInProduction()
571
+ async getLatestBackup(moduleNameInput: string) {
572
+ const moduleName = (moduleNameInput ?? '').trim();
573
+ if (!moduleName) {
574
+ throw new BadRequestException('A module name is required to look up its backup.');
575
+ }
576
+
577
+ await this.cleanupModulePackageTransactions();
578
+
579
+ const candidates: ModulePackageStatusFile[] = [];
580
+ for (const entry of await this.readDirSafe(this.getModulePackageImportsRoot())) {
581
+ if (!entry.isDirectory() || !/^[a-zA-Z0-9-]+$/.test(entry.name)) {
582
+ continue;
583
+ }
584
+
585
+ try {
586
+ const transaction = await this.loadTransaction(entry.name);
587
+ if (
588
+ transaction.moduleName === moduleName
589
+ && transaction.backup
590
+ && !transaction.restoredFromBackup
591
+ && this.isRestorableStatus(transaction.status)
592
+ && await this.pathExists(transaction.backup.path)
593
+ ) {
594
+ candidates.push(transaction);
595
+ }
596
+ } catch (error) {
597
+ continue;
598
+ }
599
+ }
600
+
601
+ candidates.sort((left, right) => new Date(right.backup!.createdAt).getTime() - new Date(left.backup!.createdAt).getTime());
602
+ const latest = candidates[0];
603
+ if (!latest) {
604
+ return null;
605
+ }
606
+
607
+ const installedState = await this.resolveInstalledState(moduleName);
608
+ return {
609
+ ...this.toStatusResponse(latest),
610
+ currentVersion: installedState.version,
611
+ };
612
+ }
613
+
614
+ @DisallowInProduction()
615
+ async restoreBackup(transactionKey: string) {
616
+ const transaction = await this.loadTransaction(transactionKey);
617
+ const moduleName = transaction.moduleName;
618
+ const backup = transaction.backup;
619
+
620
+ if (!moduleName || !backup) {
621
+ throw new BadRequestException('This module package transaction has no backup to restore.');
622
+ }
623
+
624
+ if (!this.isRestorableStatus(transaction.status)) {
625
+ throw new BadRequestException(`A backup cannot be restored while the transaction is ${transaction.status}.`);
626
+ }
627
+
628
+ await this.assertPathExists(backup.path, 'module backup');
629
+
630
+ transaction.status = ModulePackageStatus.restore_running;
631
+ transaction.currentStep = 'restore';
632
+ transaction.errorMessage = null;
633
+ await this.writeStatusFile(transactionKey, transaction);
634
+
635
+ try {
636
+ const targets = [
637
+ { label: 'solid-api', source: path.join(backup.path, 'solid-api'), target: this.getSolidApiModuleTargetPath(moduleName) },
638
+ { label: 'solid-ui', source: path.join(backup.path, 'solid-ui'), target: this.getSolidUiModuleTargetPath(moduleName) },
639
+ ];
640
+ const outputs: string[] = [`Restored ${moduleName} ${this.formatVersion(backup.version)} from ${backup.path}`];
641
+
642
+ for (const { label, source, target } of targets) {
643
+ await fs.rm(target, { recursive: true, force: true });
644
+ if (await this.pathExists(source)) {
645
+ await fs.mkdir(path.dirname(target), { recursive: true });
646
+ await fs.cp(source, target, { recursive: true });
647
+ outputs.push(`Restored ${label} module at ${target}`);
648
+ } else {
649
+ outputs.push(`Removed ${label} module at ${target} (it did not exist before the update)`);
650
+ }
651
+ }
652
+
653
+ transaction.status = ModulePackageStatus.awaiting_restart;
654
+ transaction.currentStep = 'restart';
655
+ transaction.restoredFromBackup = true;
656
+ transaction.outputs.restore = outputs.join('\n');
657
+ transaction.outputs.build = null;
658
+ transaction.outputs.seed = null;
659
+ await this.writeStatusFile(transactionKey, transaction);
660
+ await this.syncActiveTransactionPointer(transaction);
661
+
662
+ return this.toStatusResponse(transaction);
663
+ } catch (error: any) {
664
+ transaction.status = ModulePackageStatus.failed;
665
+ transaction.currentStep = 'restore';
666
+ transaction.errorMessage = error.message ?? 'Failed to restore the module backup.';
667
+ await this.writeStatusFile(transactionKey, transaction);
668
+ await this.syncActiveTransactionPointer(transaction);
669
+ throw error;
670
+ }
671
+ }
672
+
473
673
  private async parseArchive(archiveFilePath: string): Promise<ParsedArchive> {
474
674
  const entries = await this.listArchiveEntries(archiveFilePath);
475
675
  const archiveRootPrefix = this.detectArchiveRootPrefix(entries);
@@ -509,6 +709,7 @@ export class ModulePackageService {
509
709
  },
510
710
  preview: {
511
711
  module: { name: '', displayName: '' },
712
+ ...this.getEmptyInstallState(),
512
713
  manifest: this.getFallbackManifest(),
513
714
  contentsSummary: {
514
715
  totalEntries: normalizedEntries.length,
@@ -536,6 +737,12 @@ export class ModulePackageService {
536
737
  if (!manifest.module?.name) {
537
738
  validationErrors.push('manifest.json module.name is required.');
538
739
  }
740
+ if (manifest.module?.version !== undefined && manifest.module?.version !== null && !this.toValidVersion(manifest.module.version)) {
741
+ validationErrors.push(`manifest.json module.version "${manifest.module.version}" is not a valid semver version.`);
742
+ }
743
+ if (!this.toValidVersion(manifest.module?.version)) {
744
+ validationWarnings.push('This package is unversioned.');
745
+ }
539
746
 
540
747
  const moduleName = manifest.module?.name ?? '';
541
748
  const expectedPaths = this.buildExpectedPaths(moduleName);
@@ -578,7 +785,7 @@ export class ModulePackageService {
578
785
 
579
786
  const conflicts = await this.detectConflicts(moduleName);
580
787
  if (conflicts.length > 0) {
581
- validationWarnings.push('The target module already exists locally and will require overwrite confirmation.');
788
+ validationWarnings.push(ModulePackageService.OVERWRITE_CONFIRMATION_WARNING);
582
789
  }
583
790
 
584
791
  const validation: ValidationPayload = {
@@ -589,6 +796,8 @@ export class ModulePackageService {
589
796
 
590
797
  const preview: PreviewPayload = {
591
798
  module: manifest.module,
799
+ ...this.getEmptyInstallState(),
800
+ incomingVersion: this.toValidVersion(manifest.module?.version),
592
801
  manifest,
593
802
  contentsSummary: {
594
803
  totalEntries: normalizedEntries.length,
@@ -615,6 +824,336 @@ export class ModulePackageService {
615
824
  };
616
825
  }
617
826
 
827
+ private getEmptyInstallState() {
828
+ return {
829
+ mode: 'install' as ModulePackageMode,
830
+ installedVersion: null,
831
+ incomingVersion: null,
832
+ versionComparison: null,
833
+ requiresVersionAcknowledgement: false,
834
+ identicalContent: false,
835
+ contentFingerprint: null,
836
+ changeSet: null,
837
+ };
838
+ }
839
+
840
+ // Works out whether this is an install or an update of an existing module and fills the
841
+ // version / change-set parts of the preview. Runs after extraction because it needs file contents.
842
+ private async applyInstallStateToPreview(parsed: ParsedArchive, extractRoot: string, expectedModuleName: string | null) {
843
+ const { preview, validation } = parsed;
844
+ const moduleName = parsed.manifest.module?.name ?? '';
845
+
846
+ if (expectedModuleName && moduleName !== expectedModuleName) {
847
+ validation.errors.push(`This package is for module "${moduleName || 'unknown'}", but you are updating "${expectedModuleName}".`);
848
+ }
849
+
850
+ if (moduleName) {
851
+ validation.errors.push(...await this.verifyArchiveChecksums(parsed.manifest, extractRoot));
852
+
853
+ const incomingChecksums = await this.computeModuleContentChecksums(
854
+ path.join(extractRoot, 'solid-api', 'src', moduleName),
855
+ path.join(extractRoot, 'solid-ui', 'src', moduleName),
856
+ moduleName,
857
+ );
858
+ preview.contentFingerprint = this.computeContentFingerprint(incomingChecksums);
859
+
860
+ const installedState = await this.resolveInstalledState(moduleName);
861
+ preview.versionComparison = this.compareModuleVersions(installedState, preview.incomingVersion);
862
+
863
+ if (installedState.installed) {
864
+ const installedChecksums = await this.computeModuleContentChecksums(
865
+ this.getSolidApiModuleTargetPath(moduleName),
866
+ this.getSolidUiModuleTargetPath(moduleName),
867
+ moduleName,
868
+ );
869
+
870
+ preview.mode = 'update';
871
+ preview.installedVersion = installedState.version;
872
+ preview.identicalContent = this.computeContentFingerprint(installedChecksums) === preview.contentFingerprint;
873
+ preview.changeSet = {
874
+ solidApi: this.diffChecksums(installedChecksums, incomingChecksums, `solid-api/src/${moduleName}/`),
875
+ solidUi: this.diffChecksums(installedChecksums, incomingChecksums, `solid-ui/src/${moduleName}/`),
876
+ };
877
+ preview.requiresVersionAcknowledgement = preview.identicalContent
878
+ || ModulePackageService.VERSION_ACKNOWLEDGEMENT_COMPARISONS.includes(preview.versionComparison);
879
+ preview.nextActions = [
880
+ 'Review the version change and the files that will change.',
881
+ 'Approve the update to replace the module folders. The current folders are backed up first.',
882
+ 'Wait for service restart, then run build and seed.',
883
+ ];
884
+
885
+ validation.warnings = validation.warnings.filter((warning) => warning !== ModulePackageService.OVERWRITE_CONFIRMATION_WARNING);
886
+ validation.warnings.push(...this.buildUpdateWarnings(preview));
887
+ }
888
+ }
889
+
890
+ validation.valid = validation.errors.length === 0;
891
+ }
892
+
893
+ private buildUpdateWarnings(preview: PreviewPayload): string[] {
894
+ const installed = this.formatVersion(preview.installedVersion);
895
+ const incoming = this.formatVersion(preview.incomingVersion);
896
+ const warnings: string[] = [];
897
+
898
+ if (preview.versionComparison === 'downgrade') {
899
+ warnings.push(`This package (${incoming}) is older than the installed version (${installed}).`);
900
+ } else if (preview.versionComparison === 'same') {
901
+ warnings.push(preview.identicalContent
902
+ ? `${installed} is already installed with identical content.`
903
+ : `${installed} is already installed, but this package's content is different.`);
904
+ } else if (preview.versionComparison === 'legacy_package' && preview.installedVersion) {
905
+ warnings.push(`The installed module is ${installed}, but this package is unversioned. After the update the module will be unversioned.`);
906
+ }
907
+
908
+ if (preview.identicalContent && preview.versionComparison !== 'same') {
909
+ warnings.push('The package content is identical to the installed module.');
910
+ }
911
+
912
+ warnings.push('Updating replaces the solid-api and solid-ui module folders. Local changes inside them are kept only in the backup.');
913
+ return warnings;
914
+ }
915
+
916
+ private compareModuleVersions(installedState: InstalledModuleState, incomingVersion: string | null): ModulePackageVersionComparison {
917
+ if (!installedState.installed) {
918
+ return 'new';
919
+ }
920
+ if (!incomingVersion) {
921
+ return 'legacy_package';
922
+ }
923
+ if (!installedState.version) {
924
+ return 'first_version';
925
+ }
926
+
927
+ const comparison = semver.compare(incomingVersion, installedState.version);
928
+ return comparison > 0 ? 'upgrade' : comparison === 0 ? 'same' : 'downgrade';
929
+ }
930
+
931
+ private async assertUpdateApproved(transaction: ModulePackageStatusFile, dto: ConfirmModulePackageImportDto) {
932
+ const moduleName = transaction.moduleName as string;
933
+ const incomingVersion = transaction.incomingVersion ?? null;
934
+
935
+ if ((dto.confirmedVersion ?? null) !== incomingVersion) {
936
+ throw new BadRequestException({
937
+ message: `Approve the update to ${this.formatVersion(incomingVersion)} to continue.`,
938
+ incomingVersion,
939
+ });
940
+ }
941
+
942
+ if (transaction.preview?.requiresVersionAcknowledgement && !dto.acknowledgeVersionChange) {
943
+ throw new BadRequestException(
944
+ 'This update is a reinstall, a downgrade, identical content or an unversioned package. Acknowledge the version change to continue.',
945
+ );
946
+ }
947
+
948
+ const currentState = await this.resolveInstalledState(moduleName);
949
+ if (!currentState.installed || currentState.version !== transaction.installedVersion) {
950
+ throw new BadRequestException(
951
+ `The installed module changed since this package was previewed (now ${this.formatVersion(currentState.version)}). Upload the package again to refresh the preview.`,
952
+ );
953
+ }
954
+ }
955
+
956
+ private async resolveInstalledState(moduleName: string): Promise<InstalledModuleState> {
957
+ const metadataFilePath = await this.moduleMetadataHelperService.getModuleMetadataFilePath(moduleName);
958
+ const installed = (await this.pathExists(this.getSolidApiModuleTargetPath(moduleName)))
959
+ || (await this.pathExists(this.getSolidUiModuleTargetPath(moduleName)))
960
+ || (await this.pathExists(metadataFilePath));
961
+
962
+ let version: string | null = null;
963
+ if (await this.pathExists(metadataFilePath)) {
964
+ try {
965
+ const metadataDocument = JSON.parse(await fs.readFile(metadataFilePath, 'utf-8'));
966
+ version = this.toValidVersion(metadataDocument?.moduleMetadata?.version);
967
+ } catch (error) {
968
+ version = null;
969
+ }
970
+ }
971
+
972
+ return { installed, version };
973
+ }
974
+
975
+ private async verifyArchiveChecksums(manifest: ModulePackageManifest, extractRoot: string): Promise<string[]> {
976
+ const expected = manifest.checksums;
977
+ if (!expected || Object.keys(expected).length === 0) {
978
+ return [];
979
+ }
980
+
981
+ const actual = await this.computeDirectoryChecksums(extractRoot, ['manifest.json']);
982
+ const actualPaths = Object.keys(actual).filter((entry) => !this.isMacOsMetadataEntry(entry));
983
+ const missing = Object.keys(expected).filter((entry) => !(entry in actual));
984
+ const unexpected = actualPaths.filter((entry) => !(entry in expected));
985
+ const mismatched = Object.keys(expected).filter((entry) => entry in actual && actual[entry] !== expected[entry]);
986
+ const errors: string[] = [];
987
+
988
+ if (mismatched.length > 0) {
989
+ errors.push(`Checksum mismatch for ${this.summarizePaths(mismatched)}. The package may be corrupted or was modified after export.`);
990
+ }
991
+ if (missing.length > 0) {
992
+ errors.push(`Archive is missing files listed in manifest.json checksums: ${this.summarizePaths(missing)}.`);
993
+ }
994
+ if (unexpected.length > 0) {
995
+ errors.push(`Archive contains files not listed in manifest.json checksums: ${this.summarizePaths(unexpected)}.`);
996
+ }
997
+
998
+ return errors;
999
+ }
1000
+
1001
+ // Checksums keyed by package path (solid-api/src/<m>/..., solid-ui/src/<m>/...). The metadata file is
1002
+ // hashed without its version so a version bump alone does not count as a content change.
1003
+ private async computeModuleContentChecksums(solidApiDir: string, solidUiDir: string, moduleName: string): Promise<Record<string, string>> {
1004
+ const checksums: Record<string, string> = {};
1005
+ const roots: Array<[string, string]> = [
1006
+ [`solid-api/src/${moduleName}`, solidApiDir],
1007
+ [`solid-ui/src/${moduleName}`, solidUiDir],
1008
+ ];
1009
+
1010
+ for (const [prefix, rootDir] of roots) {
1011
+ if (!(await this.pathExists(rootDir))) {
1012
+ continue;
1013
+ }
1014
+
1015
+ const rootChecksums = await this.computeDirectoryChecksums(rootDir);
1016
+ for (const [relativePath, checksum] of Object.entries(rootChecksums)) {
1017
+ if (this.isMacOsMetadataEntry(relativePath) || path.posix.basename(relativePath) === '.DS_Store') {
1018
+ continue;
1019
+ }
1020
+ checksums[`${prefix}/${relativePath}`] = checksum;
1021
+ }
1022
+ }
1023
+
1024
+ const metadataKey = `solid-api/src/${moduleName}/metadata/${moduleName}-metadata.json`;
1025
+ if (checksums[metadataKey]) {
1026
+ const metadataText = await fs.readFile(path.join(solidApiDir, 'metadata', `${moduleName}-metadata.json`), 'utf-8');
1027
+ try {
1028
+ const versionless = this.withModuleVersion(JSON.parse(metadataText), null);
1029
+ checksums[metadataKey] = createHash('sha256').update(JSON.stringify(versionless)).digest('hex');
1030
+ } catch (error) {
1031
+ // Unparseable metadata keeps its raw checksum.
1032
+ }
1033
+ }
1034
+
1035
+ return checksums;
1036
+ }
1037
+
1038
+ private computeContentFingerprint(checksums: Record<string, string>): string {
1039
+ const lines = Object.keys(checksums).sort().map((entry) => `${entry}:${checksums[entry]}`);
1040
+ return createHash('sha256').update(lines.join('\n')).digest('hex');
1041
+ }
1042
+
1043
+ private diffChecksums(installed: Record<string, string>, incoming: Record<string, string>, prefix: string): ModulePackageFileDiff {
1044
+ const strip = (entries: string[]) => entries.filter((entry) => entry.startsWith(prefix)).map((entry) => entry.slice(prefix.length)).sort();
1045
+ const installedPaths = Object.keys(installed);
1046
+ const incomingPaths = Object.keys(incoming);
1047
+
1048
+ const added = strip(incomingPaths.filter((entry) => !(entry in installed)));
1049
+ const removed = strip(installedPaths.filter((entry) => !(entry in incoming)));
1050
+ const shared = incomingPaths.filter((entry) => entry in installed);
1051
+ const modified = strip(shared.filter((entry) => installed[entry] !== incoming[entry]));
1052
+ const unchangedCount = strip(shared.filter((entry) => installed[entry] === incoming[entry])).length;
1053
+
1054
+ return { added, modified, removed, unchangedCount };
1055
+ }
1056
+
1057
+ private async backupModuleFolders(transactionKey: string, moduleName: string, version: string | null): Promise<ModulePackageBackup> {
1058
+ const backupPath = path.join(this.getModulePackageBackupsRoot(), transactionKey);
1059
+ await fs.rm(backupPath, { recursive: true, force: true });
1060
+ await fs.mkdir(backupPath, { recursive: true });
1061
+
1062
+ const sources: Array<[string, string]> = [
1063
+ ['solid-api', this.getSolidApiModuleTargetPath(moduleName)],
1064
+ ['solid-ui', this.getSolidUiModuleTargetPath(moduleName)],
1065
+ ];
1066
+ for (const [label, sourcePath] of sources) {
1067
+ if (await this.pathExists(sourcePath)) {
1068
+ await fs.cp(sourcePath, path.join(backupPath, label), { recursive: true });
1069
+ }
1070
+ }
1071
+
1072
+ const backup: ModulePackageBackup = { path: backupPath, version, createdAt: new Date().toISOString() };
1073
+ await fs.writeFile(path.join(backupPath, 'backup.json'), JSON.stringify({ moduleName, ...backup }, null, 2));
1074
+ return backup;
1075
+ }
1076
+
1077
+ private resolveExportVersion(currentVersion: string | null, dto: ExportModulePackageDto): string | null {
1078
+ const explicitVersion = (dto.version ?? '').trim();
1079
+ if (explicitVersion) {
1080
+ const version = this.toValidVersion(explicitVersion);
1081
+ if (!version) {
1082
+ throw new BadRequestException(`"${explicitVersion}" is not a valid semver version.`);
1083
+ }
1084
+ // An explicit version only sets the initial version; versioned modules move forward with a bump.
1085
+ if (currentVersion && version !== currentVersion) {
1086
+ throw new BadRequestException(`This module is already at v${currentVersion}. Choose a patch, minor or major bump instead.`);
1087
+ }
1088
+ return version;
1089
+ }
1090
+
1091
+ const bump = dto.bump ?? 'none';
1092
+ if (bump === 'none') {
1093
+ return currentVersion;
1094
+ }
1095
+
1096
+ const nextVersion = semver.inc(currentVersion ?? '0.0.0', bump);
1097
+ if (!nextVersion) {
1098
+ throw new BadRequestException(`Unable to bump version ${currentVersion ?? '0.0.0'} by ${bump}.`);
1099
+ }
1100
+ return nextVersion;
1101
+ }
1102
+
1103
+ // Writes the version into the metadata file, leaving the file untouched when it already matches.
1104
+ private async writeModuleVersion(metadataFilePath: string, version: string | null) {
1105
+ const currentDocument = JSON.parse(await fs.readFile(metadataFilePath, 'utf-8'));
1106
+ if ((currentDocument?.moduleMetadata?.version ?? null) === version) {
1107
+ return currentDocument;
1108
+ }
1109
+
1110
+ const metadataDocument = this.withModuleVersion(currentDocument, version);
1111
+ await fs.writeFile(metadataFilePath, JSON.stringify(metadataDocument, null, 2));
1112
+ return metadataDocument;
1113
+ }
1114
+
1115
+ // Returns a copy of the metadata document with moduleMetadata.version set right after name, or removed when null.
1116
+ private withModuleVersion(metadataDocument: any, version: string | null) {
1117
+ if (!metadataDocument?.moduleMetadata) {
1118
+ return metadataDocument;
1119
+ }
1120
+
1121
+ const { version: _previousVersion, ...moduleMetadata } = metadataDocument.moduleMetadata;
1122
+ const entries = Object.entries(moduleMetadata);
1123
+ if (version) {
1124
+ entries.splice(entries.findIndex(([key]) => key === 'name') + 1, 0, ['version', version]);
1125
+ }
1126
+
1127
+ return { ...metadataDocument, moduleMetadata: Object.fromEntries(entries) };
1128
+ }
1129
+
1130
+ private async syncModuleVersionInDb(moduleName: string, version: string | null) {
1131
+ try {
1132
+ await this.dataSource.getRepository(ModuleMetadata).update({ name: moduleName }, { version });
1133
+ } catch (error) {
1134
+ this.logger.warn(`Failed to update the version of module ${moduleName} in the database: ${String(error)}`);
1135
+ }
1136
+ }
1137
+
1138
+ private toValidVersion(value: unknown): string | null {
1139
+ return typeof value === 'string' ? semver.valid(value.trim()) : null;
1140
+ }
1141
+
1142
+ private formatVersion(version: string | null | undefined) {
1143
+ return version ? `v${version}` : 'unversioned';
1144
+ }
1145
+
1146
+ private summarizePaths(paths: string[], limit = 5) {
1147
+ const shown = paths.slice(0, limit).join(', ');
1148
+ return paths.length > limit ? `${shown} and ${paths.length - limit} more` : shown;
1149
+ }
1150
+
1151
+ private resolveExtractRoot(extractDirPath: string, archiveRootPrefix: string | null) {
1152
+ return archiveRootPrefix
1153
+ ? path.join(extractDirPath, archiveRootPrefix.replace(/\/$/, ''))
1154
+ : extractDirPath;
1155
+ }
1156
+
618
1157
  private parseManifest(manifestText: string, validationErrors: string[]): ModulePackageManifest | null {
619
1158
  if (!manifestText) {
620
1159
  return null;
@@ -765,7 +1304,27 @@ export class ModulePackageService {
765
1304
  throw new NotFoundException(`Module package transaction ${transactionKey} was not found.`);
766
1305
  }
767
1306
 
768
- return JSON.parse(await fs.readFile(statusFilePath, 'utf-8')) as ModulePackageStatusFile;
1307
+ return this.normalizeTransaction(JSON.parse(await fs.readFile(statusFilePath, 'utf-8')));
1308
+ }
1309
+
1310
+ // Status files written before module versioning existed lack the update fields; default them so those imports still resume.
1311
+ private normalizeTransaction(transaction: any): ModulePackageStatusFile {
1312
+ return {
1313
+ ...transaction,
1314
+ mode: transaction.mode ?? 'install',
1315
+ installedVersion: transaction.installedVersion ?? null,
1316
+ incomingVersion: transaction.incomingVersion ?? this.toValidVersion(transaction.manifest?.module?.version),
1317
+ versionComparison: transaction.versionComparison ?? null,
1318
+ backup: transaction.backup ?? null,
1319
+ restoredFromBackup: transaction.restoredFromBackup ?? false,
1320
+ outputs: {
1321
+ import: null,
1322
+ build: null,
1323
+ seed: null,
1324
+ restore: null,
1325
+ ...(transaction.outputs ?? {}),
1326
+ },
1327
+ };
769
1328
  }
770
1329
 
771
1330
  private isResumableStatus(status: string | null | undefined) {
@@ -777,9 +1336,15 @@ export class ModulePackageService {
777
1336
  ModulePackageStatus.build_succeeded,
778
1337
  ModulePackageStatus.seed_running,
779
1338
  ModulePackageStatus.seed_failed,
1339
+ ModulePackageStatus.restore_running,
780
1340
  ].includes(status as ModulePackageStatus);
781
1341
  }
782
1342
 
1343
+ private isRestorableStatus(status: string | null | undefined) {
1344
+ return this.isResumableStatus(status)
1345
+ || [ModulePackageStatus.failed, ModulePackageStatus.completed].includes(status as ModulePackageStatus);
1346
+ }
1347
+
783
1348
  private async createWorkingDir(transactionKey: string) {
784
1349
  const baseDir = path.join(
785
1350
  this.getModulePackageImportsRoot(),
@@ -816,6 +1381,13 @@ export class ModulePackageService {
816
1381
  );
817
1382
  }
818
1383
 
1384
+ private getModulePackageBackupsRoot() {
1385
+ return path.join(
1386
+ this.getModulePackageRuntimeRoot(),
1387
+ 'module-package-backups',
1388
+ );
1389
+ }
1390
+
819
1391
  private getModulePackageRuntimeRoot() {
820
1392
  const configuredRuntimeRoot = process.env.SOLIDX_MODULE_PACKAGE_RUNTIME_DIR?.trim();
821
1393
 
@@ -921,6 +1493,7 @@ export class ModulePackageService {
921
1493
  private async collectRuntimeCleanupSnapshot() {
922
1494
  const importEntries = await this.readDirSafe(this.getModulePackageImportsRoot());
923
1495
  const exportEntries = await this.readDirSafe(this.getModulePackageExportsRoot());
1496
+ const backupEntries = await this.readDirSafe(this.getModulePackageBackupsRoot());
924
1497
 
925
1498
  const importTransactionEntries = importEntries.filter(
926
1499
  (entry) => entry.isDirectory() && /^[a-zA-Z0-9-]+$/.test(entry.name),
@@ -941,6 +1514,7 @@ export class ModulePackageService {
941
1514
  removedExportTransactions: exportTransactionEntries.length,
942
1515
  removedImportLooseEntries: importLooseEntries.length,
943
1516
  removedExportLooseEntries: exportLooseEntries.length,
1517
+ removedBackups: backupEntries.filter((entry) => entry.isDirectory()).length,
944
1518
  clearedActiveTransactionPointer: importEntries.some((entry) => entry.name === 'active-transaction.json'),
945
1519
  };
946
1520
  }
@@ -998,6 +1572,8 @@ export class ModulePackageService {
998
1572
  }
999
1573
 
1000
1574
  await fs.rm(path.join(importsRoot, transactionKey), { recursive: true, force: true });
1575
+ // A backup never outlives its transaction.
1576
+ await fs.rm(path.join(this.getModulePackageBackupsRoot(), transactionKey), { recursive: true, force: true });
1001
1577
 
1002
1578
  if (activePointer?.transactionKey === transactionKey) {
1003
1579
  await fs.rm(this.getActiveTransactionFilePath(), { force: true });
@@ -1072,6 +1648,12 @@ export class ModulePackageService {
1072
1648
  currentStep: transaction.currentStep,
1073
1649
  moduleName: transaction.moduleName,
1074
1650
  moduleDisplayName: transaction.moduleDisplayName,
1651
+ mode: transaction.mode,
1652
+ installedVersion: transaction.installedVersion,
1653
+ incomingVersion: transaction.incomingVersion,
1654
+ versionComparison: transaction.versionComparison,
1655
+ backup: transaction.backup,
1656
+ restoredFromBackup: transaction.restoredFromBackup,
1075
1657
  archiveFileName: transaction.archiveFileName,
1076
1658
  manifest: transaction.manifest,
1077
1659
  preview: transaction.preview,
@@ -1097,6 +1679,7 @@ export class ModulePackageService {
1097
1679
  },
1098
1680
  module: {
1099
1681
  name: moduleName,
1682
+ version: this.toValidVersion(metadataDocument?.moduleMetadata?.version) ?? undefined,
1100
1683
  displayName: metadataDocument?.moduleMetadata?.displayName,
1101
1684
  description: metadataDocument?.moduleMetadata?.description,
1102
1685
  },