@nodestackapp/server 1.3.0 → 2.0.0

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 (92) hide show
  1. package/LICENSE +15 -0
  2. package/README.md +10 -10
  3. package/dist/NodeStack.d.ts +5 -0
  4. package/dist/NodeStack.d.ts.map +1 -1
  5. package/dist/NodeStack.js +19 -1
  6. package/dist/NodeStack.js.map +1 -1
  7. package/dist/admin/AdminUIBundler.d.ts.map +1 -1
  8. package/dist/admin/AdminUIBundler.js +1 -0
  9. package/dist/admin/AdminUIBundler.js.map +1 -1
  10. package/dist/admin/ui/css/analytics.css +68 -11
  11. package/dist/admin/ui/css/main.css +2189 -2015
  12. package/dist/admin/ui/css/rules.css +292 -264
  13. package/dist/admin/ui/css/webhooks.css +34 -10
  14. package/dist/admin/ui/index.html +10434 -9850
  15. package/dist/admin/ui/js/analytics.js +673 -624
  16. package/dist/admin/ui/js/api.js +16 -0
  17. package/dist/admin/ui/js/app.js +9 -18
  18. package/dist/admin/ui/js/apps.js +24 -6
  19. package/dist/admin/ui/js/collections.js +3 -4
  20. package/dist/admin/ui/js/command-palette.js +49 -18
  21. package/dist/admin/ui/js/demo.js +373 -271
  22. package/dist/admin/ui/js/modals.js +14 -14
  23. package/dist/admin/ui/js/plugin-tester.js +6 -6
  24. package/dist/admin/ui/js/plugins.js +31 -21
  25. package/dist/admin/ui/js/records.js +9 -9
  26. package/dist/admin/ui/js/rules.js +1 -1
  27. package/dist/admin/ui/js/theme.js +120 -0
  28. package/dist/admin/ui/js/views.js +632 -714
  29. package/dist/admin/ui/js/webhooks.js +27 -9
  30. package/dist/apps/AppScope.d.ts +2 -0
  31. package/dist/apps/AppScope.d.ts.map +1 -1
  32. package/dist/apps/AppScope.js +7 -3
  33. package/dist/apps/AppScope.js.map +1 -1
  34. package/dist/auth/AuthService.d.ts.map +1 -1
  35. package/dist/auth/AuthService.js +36 -9
  36. package/dist/auth/AuthService.js.map +1 -1
  37. package/dist/cli/cli.d.ts.map +1 -1
  38. package/dist/cli/cli.js +65 -1
  39. package/dist/cli/cli.js.map +1 -1
  40. package/dist/core/config/ConfigService.d.ts +1 -0
  41. package/dist/core/config/ConfigService.d.ts.map +1 -1
  42. package/dist/core/config/ConfigService.js +4 -1
  43. package/dist/core/config/ConfigService.js.map +1 -1
  44. package/dist/core/container/Tokens.d.ts +2 -0
  45. package/dist/core/container/Tokens.d.ts.map +1 -1
  46. package/dist/core/container/Tokens.js +2 -0
  47. package/dist/core/container/Tokens.js.map +1 -1
  48. package/dist/database/migrations/SystemMigrations.js +1 -1
  49. package/dist/database/migrations/SystemMigrations.js.map +1 -1
  50. package/dist/demo/DemoService.d.ts +15 -103
  51. package/dist/demo/DemoService.d.ts.map +1 -1
  52. package/dist/demo/DemoService.js +14 -419
  53. package/dist/demo/DemoService.js.map +1 -1
  54. package/dist/http/HttpServer.d.ts +3 -1
  55. package/dist/http/HttpServer.d.ts.map +1 -1
  56. package/dist/http/HttpServer.js +43 -8
  57. package/dist/http/HttpServer.js.map +1 -1
  58. package/dist/http/controllers/DemoController.d.ts.map +1 -1
  59. package/dist/http/controllers/DemoController.js +1 -0
  60. package/dist/http/controllers/DemoController.js.map +1 -1
  61. package/dist/http/controllers/HealthController.js +2 -2
  62. package/dist/http/controllers/SnapshotController.d.ts +58 -0
  63. package/dist/http/controllers/SnapshotController.d.ts.map +1 -0
  64. package/dist/http/controllers/SnapshotController.js +79 -0
  65. package/dist/http/controllers/SnapshotController.js.map +1 -0
  66. package/dist/index.d.ts +4 -1
  67. package/dist/index.d.ts.map +1 -1
  68. package/dist/index.js +7 -1
  69. package/dist/index.js.map +1 -1
  70. package/dist/records/QueryFilterParser.d.ts.map +1 -1
  71. package/dist/records/QueryFilterParser.js +2 -1
  72. package/dist/records/QueryFilterParser.js.map +1 -1
  73. package/dist/records/RecordService.d.ts.map +1 -1
  74. package/dist/records/RecordService.js +32 -14
  75. package/dist/records/RecordService.js.map +1 -1
  76. package/dist/rules/RuleEngine.d.ts +14 -0
  77. package/dist/rules/RuleEngine.d.ts.map +1 -1
  78. package/dist/rules/RuleEngine.js +144 -1
  79. package/dist/rules/RuleEngine.js.map +1 -1
  80. package/dist/schema/OpenApiGenerator.js +3 -3
  81. package/dist/snapshots/SnapshotService.d.ts +75 -0
  82. package/dist/snapshots/SnapshotService.d.ts.map +1 -0
  83. package/dist/snapshots/SnapshotService.js +775 -0
  84. package/dist/snapshots/SnapshotService.js.map +1 -0
  85. package/dist/snapshots/types.d.ts +63 -0
  86. package/dist/snapshots/types.d.ts.map +1 -0
  87. package/dist/snapshots/types.js +5 -0
  88. package/dist/snapshots/types.js.map +1 -0
  89. package/dist/templates/definitions/ecommerce.js +13 -13
  90. package/dist/templates/definitions/ecommerce.js.map +1 -1
  91. package/dist/webhooks/WebhookService.js +1 -1
  92. package/package.json +88 -88
@@ -0,0 +1,775 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.SnapshotService = void 0;
37
+ const fs = __importStar(require("fs"));
38
+ const path = __importStar(require("path"));
39
+ const crypto = __importStar(require("crypto"));
40
+ const AppError_1 = require("../core/errors/AppError");
41
+ const MaintenanceGate_1 = require("../core/maintenance/MaintenanceGate");
42
+ const types_1 = require("./types");
43
+ class SnapshotService {
44
+ config;
45
+ db;
46
+ schemaService;
47
+ fileStorageService;
48
+ eventBus;
49
+ realtimeService;
50
+ customPaths;
51
+ maintenanceGate;
52
+ maxSnapshots = types_1.MAX_SNAPSHOTS;
53
+ constructor(config, db, schemaService, fileStorageService, eventBus, realtimeService, maintenanceGate, customPaths) {
54
+ this.config = config;
55
+ this.db = db;
56
+ this.schemaService = schemaService;
57
+ this.fileStorageService = fileStorageService;
58
+ this.eventBus = eventBus;
59
+ this.realtimeService = realtimeService;
60
+ this.customPaths = customPaths;
61
+ this.maintenanceGate = maintenanceGate || new MaintenanceGate_1.MaintenanceGate();
62
+ this.ensureMigratedLegacySnapshot();
63
+ }
64
+ getGate() {
65
+ return this.maintenanceGate;
66
+ }
67
+ get dbPath() {
68
+ return this.customPaths?.dbPath || this.config.dbPath;
69
+ }
70
+ get storageDir() {
71
+ return this.customPaths?.storageDir || this.fileStorageService.storageDir || this.config.storageDir;
72
+ }
73
+ get snapshotsDir() {
74
+ return this.customPaths?.snapshotsDir || this.customPaths?.snapshotDir || path.join(this.config.dataDir, '.snapshots');
75
+ }
76
+ get manifestPath() {
77
+ return path.join(this.snapshotsDir, 'manifest.json');
78
+ }
79
+ get legacySnapshotDir() {
80
+ if (this.customPaths && 'legacySnapshotDir' in this.customPaths) {
81
+ return this.customPaths.legacySnapshotDir;
82
+ }
83
+ if (this.customPaths && this.customPaths.snapshotDir) {
84
+ return this.customPaths.snapshotDir;
85
+ }
86
+ // Only default to global .demo_snapshot if this is the standalone/root service (not scoped with custom paths)
87
+ if (!this.customPaths || (!this.customPaths.snapshotsDir && !this.customPaths.snapshotDir)) {
88
+ return path.join(this.config.dataDir, '.demo_snapshot');
89
+ }
90
+ return undefined;
91
+ }
92
+ // ==========================================
93
+ // Backward compatibility getters for DemoService
94
+ // ==========================================
95
+ get snapshotDir() {
96
+ const active = this.getActiveOrLatestSnapshot();
97
+ if (active) {
98
+ return path.join(this.snapshotsDir, active.id);
99
+ }
100
+ return this.snapshotsDir;
101
+ }
102
+ get snapshotDbPath() {
103
+ const active = this.getActiveOrLatestSnapshot();
104
+ if (active) {
105
+ return path.join(this.snapshotsDir, active.id, 'data.db');
106
+ }
107
+ return path.join(this.snapshotsDir, 'latest_fallback_data.db');
108
+ }
109
+ get snapshotMetadataPath() {
110
+ const active = this.getActiveOrLatestSnapshot();
111
+ if (active) {
112
+ return path.join(this.snapshotsDir, active.id, 'metadata.json');
113
+ }
114
+ return path.join(this.snapshotsDir, 'latest_fallback_metadata.json');
115
+ }
116
+ get snapshotStorageDir() {
117
+ const active = this.getActiveOrLatestSnapshot();
118
+ if (active) {
119
+ return path.join(this.snapshotsDir, active.id, 'storage');
120
+ }
121
+ return path.join(this.snapshotsDir, 'latest_fallback_storage');
122
+ }
123
+ /**
124
+ * Automatically migrates legacy .demo_snapshot if it exists and no generic snapshots exist yet.
125
+ */
126
+ ensureMigratedLegacySnapshot() {
127
+ try {
128
+ if (!this.legacySnapshotDir || !fs.existsSync(this.legacySnapshotDir))
129
+ return;
130
+ const legacyDb = path.join(this.legacySnapshotDir, 'data.db');
131
+ const legacyMeta = path.join(this.legacySnapshotDir, 'metadata.json');
132
+ if (!fs.existsSync(legacyDb) || !fs.existsSync(legacyMeta))
133
+ return;
134
+ if (!fs.existsSync(this.snapshotsDir)) {
135
+ fs.mkdirSync(this.snapshotsDir, { recursive: true });
136
+ }
137
+ const existing = this.listSnapshots();
138
+ if (existing.length > 0)
139
+ return;
140
+ let meta = {};
141
+ try {
142
+ meta = JSON.parse(fs.readFileSync(legacyMeta, 'utf-8'));
143
+ }
144
+ catch {
145
+ meta = {};
146
+ }
147
+ const id = meta.id || `snap_${Date.now()}_legacy`;
148
+ const targetDir = path.join(this.snapshotsDir, id);
149
+ fs.mkdirSync(targetDir, { recursive: true });
150
+ fs.copyFileSync(legacyDb, path.join(targetDir, 'data.db'));
151
+ const legacyStorage = path.join(this.legacySnapshotDir, 'storage');
152
+ const targetStorage = path.join(targetDir, 'storage');
153
+ fs.mkdirSync(targetStorage, { recursive: true });
154
+ if (fs.existsSync(legacyStorage)) {
155
+ fs.cpSync(legacyStorage, targetStorage, { recursive: true });
156
+ }
157
+ const migratedMetadata = {
158
+ id,
159
+ name: meta.name || 'Initial Clean State',
160
+ description: meta.description || 'Pristine demo baseline state',
161
+ createdAt: meta.createdAt || new Date().toISOString(),
162
+ collections: meta.collections || [],
163
+ totalCollections: meta.totalCollections || 0,
164
+ totalRecords: meta.totalRecords || 0,
165
+ totalFiles: meta.totalFiles || 0,
166
+ storageSizeBytes: meta.storageSizeBytes || 0,
167
+ dbSizeBytes: meta.dbSizeBytes || 0,
168
+ contentHash: meta.contentHash,
169
+ isActive: true,
170
+ };
171
+ fs.writeFileSync(path.join(targetDir, 'metadata.json'), JSON.stringify(migratedMetadata, null, 2), 'utf-8');
172
+ this.saveManifest({
173
+ activeSnapshotId: id,
174
+ snapshots: [migratedMetadata],
175
+ });
176
+ }
177
+ catch {
178
+ // ignore migration failures gracefully
179
+ }
180
+ }
181
+ readManifest() {
182
+ if (!fs.existsSync(this.manifestPath)) {
183
+ return { activeSnapshotId: null, snapshots: [] };
184
+ }
185
+ try {
186
+ const parsed = JSON.parse(fs.readFileSync(this.manifestPath, 'utf-8'));
187
+ return {
188
+ activeSnapshotId: parsed.activeSnapshotId || null,
189
+ snapshots: Array.isArray(parsed.snapshots) ? parsed.snapshots : [],
190
+ };
191
+ }
192
+ catch {
193
+ return { activeSnapshotId: null, snapshots: [] };
194
+ }
195
+ }
196
+ saveManifest(manifest) {
197
+ if (!fs.existsSync(this.snapshotsDir)) {
198
+ fs.mkdirSync(this.snapshotsDir, { recursive: true });
199
+ }
200
+ fs.writeFileSync(this.manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
201
+ }
202
+ /**
203
+ * Returns all snapshots sorted chronologically by createdAt (oldest first).
204
+ */
205
+ listSnapshots() {
206
+ if (!fs.existsSync(this.snapshotsDir)) {
207
+ return [];
208
+ }
209
+ const manifest = this.readManifest();
210
+ const diskSnapshots = [];
211
+ const validIds = new Set();
212
+ try {
213
+ const entries = fs.readdirSync(this.snapshotsDir, { withFileTypes: true });
214
+ for (const entry of entries) {
215
+ if (!entry.isDirectory())
216
+ continue;
217
+ const snapDir = path.join(this.snapshotsDir, entry.name);
218
+ const metaPath = path.join(snapDir, 'metadata.json');
219
+ const dbPath = path.join(snapDir, 'data.db');
220
+ if (fs.existsSync(metaPath) && fs.existsSync(dbPath)) {
221
+ try {
222
+ const meta = JSON.parse(fs.readFileSync(metaPath, 'utf-8'));
223
+ if (meta.id) {
224
+ diskSnapshots.push({
225
+ ...meta,
226
+ isActive: meta.id === manifest.activeSnapshotId,
227
+ });
228
+ validIds.add(meta.id);
229
+ }
230
+ }
231
+ catch {
232
+ // ignore corrupt metadata
233
+ }
234
+ }
235
+ }
236
+ }
237
+ catch {
238
+ return [];
239
+ }
240
+ // Sort chronologically (oldest first)
241
+ diskSnapshots.sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
242
+ // Update manifest if count or active id differs
243
+ if (manifest.snapshots.length !== diskSnapshots.length ||
244
+ (manifest.activeSnapshotId && !validIds.has(manifest.activeSnapshotId))) {
245
+ const newActiveId = validIds.has(manifest.activeSnapshotId || '')
246
+ ? manifest.activeSnapshotId
247
+ : diskSnapshots[diskSnapshots.length - 1]?.id || null;
248
+ this.saveManifest({
249
+ activeSnapshotId: newActiveId,
250
+ snapshots: diskSnapshots,
251
+ });
252
+ }
253
+ return diskSnapshots;
254
+ }
255
+ getSnapshot(id) {
256
+ const snapshots = this.listSnapshots();
257
+ return snapshots.find((s) => s.id === id) || null;
258
+ }
259
+ getLatestSnapshot() {
260
+ const snapshots = this.listSnapshots();
261
+ return snapshots.length > 0 ? snapshots[snapshots.length - 1] : null;
262
+ }
263
+ getActiveOrLatestSnapshot() {
264
+ const snapshots = this.listSnapshots();
265
+ if (snapshots.length === 0)
266
+ return null;
267
+ const manifest = this.readManifest();
268
+ if (manifest.activeSnapshotId) {
269
+ const active = snapshots.find((s) => s.id === manifest.activeSnapshotId);
270
+ if (active)
271
+ return active;
272
+ }
273
+ return snapshots[snapshots.length - 1];
274
+ }
275
+ hasSnapshot() {
276
+ return this.listSnapshots().length > 0;
277
+ }
278
+ /**
279
+ * Creates a new snapshot.
280
+ * If snapshot count >= maxSnapshots (10), requires evictOldest: true to remove the oldest.
281
+ */
282
+ async createSnapshot(options = {}) {
283
+ if (!fs.existsSync(this.snapshotsDir)) {
284
+ fs.mkdirSync(this.snapshotsDir, { recursive: true });
285
+ }
286
+ return await this.maintenanceGate.executeExclusive(async () => {
287
+ const currentSnapshots = this.listSnapshots();
288
+ let toEvict = [];
289
+ if (currentSnapshots.length >= this.maxSnapshots) {
290
+ if (!options.evictOldest) {
291
+ const oldest = currentSnapshots[0];
292
+ const error = new AppError_1.ConflictError(`Snapshot limit of ${this.maxSnapshots} reached. Creating a new snapshot will delete the oldest snapshot '${oldest.name}'. Please confirm eviction to proceed.`, {
293
+ code: 'SNAPSHOT_LIMIT_REACHED',
294
+ limit: this.maxSnapshots,
295
+ oldestSnapshot: oldest,
296
+ });
297
+ throw error;
298
+ }
299
+ // Calculate snapshot(s) to evict once new snapshot succeeds
300
+ const evictCount = currentSnapshots.length - this.maxSnapshots + 1;
301
+ toEvict = currentSnapshots.slice(0, evictCount);
302
+ }
303
+ // 1. Flush SQLite WAL to disk
304
+ this.db.checkpoint();
305
+ // 2. Prepare new snapshot directory
306
+ const id = `snap_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
307
+ const snapDir = path.join(this.snapshotsDir, id);
308
+ fs.mkdirSync(snapDir, { recursive: true });
309
+ try {
310
+ // 3. Compact & snapshot SQLite database transactional state
311
+ const snapDbPath = path.join(snapDir, 'data.db');
312
+ const normalizedDbPath = snapDbPath.replace(/\\/g, '/');
313
+ this.db.exec(`VACUUM INTO '${normalizedDbPath}';`);
314
+ if (!fs.existsSync(snapDbPath) || fs.statSync(snapDbPath).size === 0) {
315
+ throw new Error('VACUUM INTO failed to generate a valid snapshot database file.');
316
+ }
317
+ // 4. Snapshot uploaded files storage
318
+ const snapStorageDir = path.join(snapDir, 'storage');
319
+ fs.mkdirSync(snapStorageDir, { recursive: true });
320
+ if (fs.existsSync(this.storageDir)) {
321
+ fs.cpSync(this.storageDir, snapStorageDir, { recursive: true });
322
+ }
323
+ // 5. Compute metadata & statistics
324
+ const live = this.calculateLiveStats();
325
+ const storageStats = this.getDirectoryStats(snapStorageDir);
326
+ const dbSizeBytes = fs.statSync(snapDbPath).size;
327
+ const contentHash = this.computeStateHash();
328
+ const metadata = {
329
+ id,
330
+ name: options.name?.trim() || `Snapshot #${currentSnapshots.length + 1}`,
331
+ description: options.description?.trim() || 'Application state snapshot',
332
+ createdAt: new Date().toISOString(),
333
+ collections: live.collections,
334
+ totalCollections: live.totalCollections,
335
+ totalRecords: live.totalRecords,
336
+ totalFiles: storageStats.count,
337
+ storageSizeBytes: storageStats.sizeBytes,
338
+ dbSizeBytes,
339
+ contentHash,
340
+ isActive: true,
341
+ };
342
+ fs.writeFileSync(path.join(snapDir, 'metadata.json'), JSON.stringify(metadata, null, 2), 'utf-8');
343
+ // 6. Only now evict oldest snapshot(s) after new snapshot is captured & validated
344
+ if (toEvict.length > 0) {
345
+ for (const snap of toEvict) {
346
+ this.removeSnapshotFiles(snap.id);
347
+ }
348
+ }
349
+ const evictedIds = new Set(toEvict.map((s) => s.id));
350
+ const updatedSnapshots = [
351
+ ...this.listSnapshots().filter((s) => !evictedIds.has(s.id) && s.id !== id),
352
+ metadata,
353
+ ].sort((a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime());
354
+ this.saveManifest({
355
+ activeSnapshotId: id,
356
+ snapshots: updatedSnapshots,
357
+ });
358
+ // 7. Emit events
359
+ this.eventBus.emit('snapshot:create', metadata);
360
+ this.eventBus.emit('demo:snapshot', metadata);
361
+ this.realtimeService.broadcastSystemEvent('SNAPSHOT_CREATE', { metadata });
362
+ return metadata;
363
+ }
364
+ catch (err) {
365
+ // Rollback new snapshot files on failure so oldest snapshots remain safe
366
+ if (fs.existsSync(snapDir)) {
367
+ try {
368
+ fs.rmSync(snapDir, { recursive: true, force: true });
369
+ }
370
+ catch { }
371
+ }
372
+ throw err;
373
+ }
374
+ });
375
+ }
376
+ /**
377
+ * Restores application state from a specific snapshot (or active/latest snapshot).
378
+ * Note: Future snapshots are NOT deleted; all snapshots remain intact.
379
+ */
380
+ async restoreSnapshot(id) {
381
+ const snapshots = this.listSnapshots();
382
+ if (snapshots.length === 0) {
383
+ throw new AppError_1.NotFoundError('No demo snapshot found. Please create a snapshot first before attempting to restore.');
384
+ }
385
+ let target;
386
+ if (id) {
387
+ target = snapshots.find((s) => s.id === id);
388
+ if (!target) {
389
+ throw new AppError_1.NotFoundError(`Snapshot with ID '${id}' was not found.`);
390
+ }
391
+ }
392
+ else {
393
+ target = this.getActiveOrLatestSnapshot() || snapshots[snapshots.length - 1];
394
+ }
395
+ const snapDir = path.join(this.snapshotsDir, target.id);
396
+ const snapDbPath = path.join(snapDir, 'data.db');
397
+ const snapStorageDir = path.join(snapDir, 'storage');
398
+ if (!fs.existsSync(snapDbPath)) {
399
+ throw new AppError_1.NotFoundError(`Snapshot database file not found for '${target.name}' (${target.id}).`);
400
+ }
401
+ return await this.maintenanceGate.executeExclusive(async () => {
402
+ const startTime = Date.now();
403
+ // 1. Lock database and checkpoint WAL journal
404
+ this.db.lock();
405
+ this.db.checkpoint();
406
+ // 2. Safely close database connection
407
+ this.db.close();
408
+ try {
409
+ // 3. Overwrite live data.db with snapshot
410
+ fs.copyFileSync(snapDbPath, this.dbPath);
411
+ // 4. Remove existing WAL and SHM journal files
412
+ const walPath = `${this.dbPath}-wal`;
413
+ if (fs.existsSync(walPath)) {
414
+ try {
415
+ fs.unlinkSync(walPath);
416
+ }
417
+ catch {
418
+ // ignore
419
+ }
420
+ }
421
+ const shmPath = `${this.dbPath}-shm`;
422
+ if (fs.existsSync(shmPath)) {
423
+ try {
424
+ fs.unlinkSync(shmPath);
425
+ }
426
+ catch {
427
+ // ignore
428
+ }
429
+ }
430
+ // 5. Restore file storage
431
+ if (fs.existsSync(this.storageDir)) {
432
+ fs.rmSync(this.storageDir, { recursive: true, force: true });
433
+ }
434
+ fs.mkdirSync(this.storageDir, { recursive: true });
435
+ if (fs.existsSync(snapStorageDir)) {
436
+ fs.cpSync(snapStorageDir, this.storageDir, { recursive: true });
437
+ }
438
+ }
439
+ finally {
440
+ // 6. Guaranteed database driver reconnection and unlock
441
+ try {
442
+ this.db.reconnect();
443
+ }
444
+ finally {
445
+ this.db.unlock();
446
+ }
447
+ }
448
+ const durationMs = Date.now() - startTime;
449
+ // Update active snapshot ID in manifest without deleting any snapshots!
450
+ this.saveManifest({
451
+ activeSnapshotId: target.id,
452
+ snapshots: this.listSnapshots(),
453
+ });
454
+ // 7. Broadcast SSE realtime events
455
+ this.realtimeService.broadcastSystemEvent('SNAPSHOT_RESTORE', {
456
+ timestamp: new Date().toISOString(),
457
+ snapshot: target,
458
+ durationMs,
459
+ });
460
+ this.realtimeService.broadcastSystemEvent('DEMO_RESET', {
461
+ timestamp: new Date().toISOString(),
462
+ snapshot: target,
463
+ durationMs,
464
+ });
465
+ this.eventBus.emit('snapshot:restore', { metadata: target, durationMs });
466
+ this.eventBus.emit('demo:reset', { metadata: target, durationMs });
467
+ return {
468
+ success: true,
469
+ message: `Successfully restored state '${target.name}' in ${durationMs}ms.`,
470
+ durationMs,
471
+ snapshot: target,
472
+ restoredAt: new Date().toISOString(),
473
+ };
474
+ });
475
+ }
476
+ /**
477
+ * Deletes a specific snapshot by ID.
478
+ */
479
+ async deleteSnapshot(id) {
480
+ return await this.maintenanceGate.executeExclusive(async () => {
481
+ const target = this.getSnapshot(id);
482
+ if (!target) {
483
+ throw new AppError_1.NotFoundError(`Snapshot with ID '${id}' was not found.`);
484
+ }
485
+ this.removeSnapshotFiles(id);
486
+ const remaining = this.listSnapshots();
487
+ const manifest = this.readManifest();
488
+ let newActiveId = manifest.activeSnapshotId;
489
+ if (newActiveId === id) {
490
+ newActiveId = remaining[remaining.length - 1]?.id || null;
491
+ }
492
+ this.saveManifest({
493
+ activeSnapshotId: newActiveId,
494
+ snapshots: remaining,
495
+ });
496
+ this.eventBus.emit('snapshot:delete', { id, timestamp: new Date().toISOString() });
497
+ this.realtimeService.broadcastSystemEvent('SNAPSHOT_DELETE', { id });
498
+ });
499
+ }
500
+ /**
501
+ * Deletes all snapshots.
502
+ */
503
+ async clearAllSnapshots() {
504
+ return await this.maintenanceGate.executeExclusive(async () => {
505
+ if (fs.existsSync(this.snapshotsDir)) {
506
+ try {
507
+ const entries = fs.readdirSync(this.snapshotsDir, { withFileTypes: true });
508
+ for (const entry of entries) {
509
+ if (entry.isDirectory()) {
510
+ fs.rmSync(path.join(this.snapshotsDir, entry.name), { recursive: true, force: true });
511
+ }
512
+ }
513
+ }
514
+ catch {
515
+ // ignore
516
+ }
517
+ this.saveManifest({ activeSnapshotId: null, snapshots: [] });
518
+ }
519
+ // Also clear legacy .demo_snapshot if it exists and is scoped for this service
520
+ if (this.legacySnapshotDir && fs.existsSync(this.legacySnapshotDir)) {
521
+ try {
522
+ fs.rmSync(this.legacySnapshotDir, { recursive: true, force: true });
523
+ }
524
+ catch {
525
+ // ignore
526
+ }
527
+ }
528
+ this.eventBus.emit('snapshot:clear', { timestamp: new Date().toISOString() });
529
+ this.eventBus.emit('demo:clear', { timestamp: new Date().toISOString() });
530
+ this.realtimeService.broadcastSystemEvent('SNAPSHOT_CLEAR', {});
531
+ });
532
+ }
533
+ removeSnapshotFiles(id) {
534
+ const snapDir = path.join(this.snapshotsDir, id);
535
+ if (fs.existsSync(snapDir)) {
536
+ try {
537
+ fs.rmSync(snapDir, { recursive: true, force: true });
538
+ }
539
+ catch {
540
+ // ignore
541
+ }
542
+ }
543
+ }
544
+ /**
545
+ * Retrieves status and live drift against a specific snapshot or the active/latest baseline.
546
+ */
547
+ getStatus(targetSnapshotId) {
548
+ const snapshots = this.listSnapshots();
549
+ if (snapshots.length === 0) {
550
+ return {
551
+ hasSnapshot: false,
552
+ total: 0,
553
+ maxLimit: this.maxSnapshots,
554
+ snapshots: [],
555
+ activeSnapshot: null,
556
+ snapshot: null,
557
+ };
558
+ }
559
+ let target;
560
+ if (targetSnapshotId) {
561
+ target = snapshots.find((s) => s.id === targetSnapshotId);
562
+ }
563
+ if (!target) {
564
+ target = this.getActiveOrLatestSnapshot() || snapshots[snapshots.length - 1];
565
+ }
566
+ try {
567
+ const live = this.calculateLiveStats();
568
+ const liveContentHash = this.computeStateHash();
569
+ const collectionsDelta = live.totalCollections - target.totalCollections;
570
+ const recordsDelta = live.totalRecords - target.totalRecords;
571
+ const filesDelta = live.totalFiles - target.totalFiles;
572
+ const contentChanged = Boolean(target.contentHash && liveContentHash !== target.contentHash);
573
+ const isModified = collectionsDelta !== 0 || recordsDelta !== 0 || filesDelta !== 0 || contentChanged;
574
+ return {
575
+ hasSnapshot: true,
576
+ total: snapshots.length,
577
+ maxLimit: this.maxSnapshots,
578
+ snapshots,
579
+ activeSnapshot: target,
580
+ snapshot: target,
581
+ liveStats: {
582
+ totalCollections: live.totalCollections,
583
+ totalRecords: live.totalRecords,
584
+ totalFiles: live.totalFiles,
585
+ contentHash: liveContentHash,
586
+ drift: {
587
+ collectionsDelta,
588
+ recordsDelta,
589
+ filesDelta,
590
+ contentChanged,
591
+ isModified,
592
+ },
593
+ },
594
+ };
595
+ }
596
+ catch {
597
+ return {
598
+ hasSnapshot: true,
599
+ total: snapshots.length,
600
+ maxLimit: this.maxSnapshots,
601
+ snapshots,
602
+ activeSnapshot: target,
603
+ snapshot: target,
604
+ };
605
+ }
606
+ }
607
+ // ==========================================
608
+ // DemoService Backwards Compatibility Aliases
609
+ // ==========================================
610
+ async snapshot(options = {}) {
611
+ return this.createSnapshot({ ...options, evictOldest: true });
612
+ }
613
+ async reset() {
614
+ return this.restoreSnapshot();
615
+ }
616
+ async clearSnapshot() {
617
+ return this.clearAllSnapshots();
618
+ }
619
+ // ==========================================
620
+ // Statistics & Content Hash Calculation
621
+ // ==========================================
622
+ calculateLiveStats() {
623
+ const collections = this.schemaService.getAllCollections();
624
+ let totalRecords = 0;
625
+ const colDetails = [];
626
+ for (const c of collections) {
627
+ let count = 0;
628
+ try {
629
+ const row = this.db.get(`SELECT COUNT(*) as count FROM "${c.name}"`);
630
+ count = row ? row.count : 0;
631
+ }
632
+ catch {
633
+ // table might not exist
634
+ }
635
+ totalRecords += count;
636
+ colDetails.push({
637
+ name: c.name,
638
+ type: c.type,
639
+ recordsCount: count,
640
+ schemaFieldsCount: c.schema ? c.schema.length : 0,
641
+ });
642
+ }
643
+ // Count super admins
644
+ try {
645
+ const adminRow = this.db.get('SELECT COUNT(*) as count FROM _admins');
646
+ if (adminRow?.count) {
647
+ totalRecords += adminRow.count;
648
+ }
649
+ }
650
+ catch {
651
+ // ignore
652
+ }
653
+ const filesStat = this.getDirectoryStats(this.storageDir);
654
+ return {
655
+ totalCollections: collections.length,
656
+ totalRecords,
657
+ totalFiles: filesStat.count,
658
+ collections: colDetails,
659
+ };
660
+ }
661
+ getDirectoryStats(dirPath) {
662
+ let count = 0;
663
+ let sizeBytes = 0;
664
+ if (!fs.existsSync(dirPath))
665
+ return { count, sizeBytes };
666
+ const walk = (current) => {
667
+ try {
668
+ const entries = fs.readdirSync(current, { withFileTypes: true });
669
+ for (const entry of entries) {
670
+ const full = path.join(current, entry.name);
671
+ if (entry.isDirectory()) {
672
+ walk(full);
673
+ }
674
+ else if (entry.isFile()) {
675
+ count++;
676
+ try {
677
+ sizeBytes += fs.statSync(full).size;
678
+ }
679
+ catch {
680
+ // ignore
681
+ }
682
+ }
683
+ }
684
+ }
685
+ catch {
686
+ // ignore
687
+ }
688
+ };
689
+ walk(dirPath);
690
+ return { count, sizeBytes };
691
+ }
692
+ computeStateHash() {
693
+ const hash = crypto.createHash('sha256');
694
+ // 1. Schema & Collections definition (sorted by collection name)
695
+ const collections = this.schemaService.getAllCollections().sort((a, b) => a.name.localeCompare(b.name));
696
+ for (const c of collections) {
697
+ hash.update(`col:${c.id}:${c.name}:${c.type}:${c.system ? 1 : 0}`);
698
+ hash.update(`schema:${JSON.stringify(c.schema || [])}`);
699
+ hash.update(`indexes:${JSON.stringify(c.indexes || [])}`);
700
+ hash.update(`rules:${c.listRule}:${c.viewRule}:${c.createRule}:${c.updateRule}:${c.deleteRule}`);
701
+ hash.update(`options:${JSON.stringify(c.options || {})}`);
702
+ }
703
+ // 2. Collection records content (sorted by id within each table)
704
+ for (const c of collections) {
705
+ try {
706
+ const rows = this.db.all(`SELECT * FROM "${c.name}" ORDER BY "id" ASC`);
707
+ hash.update(`table:${c.name}:count:${rows.length}`);
708
+ for (const row of rows) {
709
+ const sortedKeys = Object.keys(row).sort();
710
+ const canonicalRow = {};
711
+ for (const k of sortedKeys) {
712
+ canonicalRow[k] = row[k];
713
+ }
714
+ hash.update(JSON.stringify(canonicalRow));
715
+ }
716
+ }
717
+ catch {
718
+ // Table might not exist or query failed
719
+ }
720
+ }
721
+ // 3. Super Admin records
722
+ try {
723
+ const adminRows = this.db.all('SELECT id, email, created, updated FROM _admins ORDER BY "id" ASC');
724
+ hash.update(`admins:count:${adminRows.length}`);
725
+ for (const row of adminRows) {
726
+ hash.update(JSON.stringify(row));
727
+ }
728
+ }
729
+ catch {
730
+ // ignore
731
+ }
732
+ // 4. File storage manifest
733
+ const files = this.getFileManifest(this.storageDir);
734
+ hash.update(`files:count:${files.length}`);
735
+ for (const f of files) {
736
+ hash.update(`${f.relPath}:${f.sizeBytes}:${f.md5}`);
737
+ }
738
+ return hash.digest('hex');
739
+ }
740
+ getFileManifest(dirPath) {
741
+ const list = [];
742
+ if (!fs.existsSync(dirPath))
743
+ return list;
744
+ const walk = (current) => {
745
+ try {
746
+ const entries = fs.readdirSync(current, { withFileTypes: true });
747
+ for (const entry of entries) {
748
+ const full = path.join(current, entry.name);
749
+ if (entry.isDirectory()) {
750
+ walk(full);
751
+ }
752
+ else if (entry.isFile()) {
753
+ try {
754
+ const stat = fs.statSync(full);
755
+ const relPath = path.relative(dirPath, full).replace(/\\/g, '/');
756
+ const buf = fs.readFileSync(full);
757
+ const md5 = crypto.createHash('md5').update(buf).digest('hex');
758
+ list.push({ relPath, sizeBytes: stat.size, md5 });
759
+ }
760
+ catch {
761
+ // ignore
762
+ }
763
+ }
764
+ }
765
+ }
766
+ catch {
767
+ // ignore
768
+ }
769
+ };
770
+ walk(dirPath);
771
+ return list.sort((a, b) => a.relPath.localeCompare(b.relPath));
772
+ }
773
+ }
774
+ exports.SnapshotService = SnapshotService;
775
+ //# sourceMappingURL=SnapshotService.js.map