@sonicjs-cms/core 2.0.10 → 2.1.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 (77) hide show
  1. package/dist/chunk-22EFGHAX.cjs +801 -0
  2. package/dist/chunk-22EFGHAX.cjs.map +1 -0
  3. package/dist/{chunk-3PHG75W4.cjs → chunk-2MBNRFS5.cjs} +7 -5
  4. package/dist/chunk-2MBNRFS5.cjs.map +1 -0
  5. package/dist/{chunk-LW33AOBF.js → chunk-5RKQB2JG.js} +6 -222
  6. package/dist/chunk-5RKQB2JG.js.map +1 -0
  7. package/dist/{chunk-HXA5QSI3.cjs → chunk-7EGKU7OO.cjs} +22 -6
  8. package/dist/chunk-7EGKU7OO.cjs.map +1 -0
  9. package/dist/{chunk-6FR25MPC.js → chunk-F4K5QAN6.js} +246 -3
  10. package/dist/chunk-F4K5QAN6.js.map +1 -0
  11. package/dist/{chunk-MXJJN4IA.js → chunk-K5JZ4JI3.js} +7 -5
  12. package/dist/chunk-K5JZ4JI3.js.map +1 -0
  13. package/dist/{chunk-Z4H6DBVF.js → chunk-KZ5XDGE6.js} +11991 -10731
  14. package/dist/chunk-KZ5XDGE6.js.map +1 -0
  15. package/dist/{chunk-Q7SL7U43.cjs → chunk-LPM3NPAX.cjs} +12001 -10740
  16. package/dist/chunk-LPM3NPAX.cjs.map +1 -0
  17. package/dist/chunk-LWMMMW43.js +787 -0
  18. package/dist/chunk-LWMMMW43.js.map +1 -0
  19. package/dist/chunk-NMVOTNSL.js +61 -0
  20. package/dist/chunk-NMVOTNSL.js.map +1 -0
  21. package/dist/{chunk-FTMKKKNH.js → chunk-QNWYQZ55.js} +3 -3
  22. package/dist/{chunk-FTMKKKNH.js.map → chunk-QNWYQZ55.js.map} +1 -1
  23. package/dist/{chunk-COBUPOMD.js → chunk-T7IYBGGO.cjs} +5 -770
  24. package/dist/chunk-T7IYBGGO.cjs.map +1 -0
  25. package/dist/{chunk-YHG45LMU.js → chunk-UJ4K4B23.js} +20 -4
  26. package/dist/chunk-UJ4K4B23.js.map +1 -0
  27. package/dist/chunk-WBX5YMTB.cjs +70 -0
  28. package/dist/chunk-WBX5YMTB.cjs.map +1 -0
  29. package/dist/{chunk-DOR2IU73.cjs → chunk-YP52USGX.cjs} +249 -2
  30. package/dist/chunk-YP52USGX.cjs.map +1 -0
  31. package/dist/{chunk-MU3MR2QR.cjs → chunk-YU6QFFI4.cjs} +5 -222
  32. package/dist/chunk-YU6QFFI4.cjs.map +1 -0
  33. package/dist/{chunk-CAP6QQR2.cjs → chunk-ZMSYKV62.cjs} +5 -5
  34. package/dist/{chunk-CAP6QQR2.cjs.map → chunk-ZMSYKV62.cjs.map} +1 -1
  35. package/dist/{chunk-NBDPIRQS.cjs → chunk-ZPMFT2JW.js} +4 -786
  36. package/dist/chunk-ZPMFT2JW.js.map +1 -0
  37. package/dist/index.cjs +520 -147
  38. package/dist/index.cjs.map +1 -1
  39. package/dist/index.js +389 -12
  40. package/dist/index.js.map +1 -1
  41. package/dist/middleware.cjs +24 -23
  42. package/dist/middleware.js +3 -2
  43. package/dist/migrations-IHERIQVD.js +4 -0
  44. package/dist/migrations-IHERIQVD.js.map +1 -0
  45. package/dist/migrations-POFD5KNG.cjs +13 -0
  46. package/dist/migrations-POFD5KNG.cjs.map +1 -0
  47. package/dist/routes.cjs +31 -29
  48. package/dist/routes.js +8 -6
  49. package/dist/services.cjs +42 -24
  50. package/dist/services.js +4 -2
  51. package/dist/templates.cjs +17 -21
  52. package/dist/templates.js +2 -2
  53. package/dist/utils.cjs +44 -11
  54. package/dist/utils.js +2 -1
  55. package/migrations/001_initial_schema.sql +2 -2
  56. package/migrations/007_demo_login_plugin.sql +1 -1
  57. package/migrations/020_add_email_plugin.sql +22 -0
  58. package/migrations/021_add_magic_link_auth_plugin.sql +42 -0
  59. package/migrations/021_add_otp_login.sql +42 -0
  60. package/migrations/022_add_tinymce_plugin.sql +25 -0
  61. package/migrations/023_add_easy_mdx_plugin.sql +25 -0
  62. package/migrations/024_add_quill_editor_plugin.sql +25 -0
  63. package/migrations/025_rename_mdxeditor_to_easy_mdx.sql +22 -0
  64. package/package.json +5 -3
  65. package/dist/chunk-3PHG75W4.cjs.map +0 -1
  66. package/dist/chunk-6FR25MPC.js.map +0 -1
  67. package/dist/chunk-COBUPOMD.js.map +0 -1
  68. package/dist/chunk-DOR2IU73.cjs.map +0 -1
  69. package/dist/chunk-HXA5QSI3.cjs.map +0 -1
  70. package/dist/chunk-LW33AOBF.js.map +0 -1
  71. package/dist/chunk-MU3MR2QR.cjs.map +0 -1
  72. package/dist/chunk-MXJJN4IA.js.map +0 -1
  73. package/dist/chunk-NBDPIRQS.cjs.map +0 -1
  74. package/dist/chunk-Q7SL7U43.cjs.map +0 -1
  75. package/dist/chunk-YHG45LMU.js.map +0 -1
  76. package/dist/chunk-Z4H6DBVF.js.map +0 -1
  77. package/migrations/002_faq_plugin.sql +0 -86
@@ -0,0 +1,801 @@
1
+ 'use strict';
2
+
3
+ // src/services/collection-loader.ts
4
+ var registeredCollections = [];
5
+ function registerCollections(collections) {
6
+ for (const config of collections) {
7
+ if (!config.name || !config.displayName || !config.schema) {
8
+ console.error(`Invalid collection config: missing required fields`, config);
9
+ continue;
10
+ }
11
+ const normalizedConfig = {
12
+ ...config,
13
+ managed: config.managed !== void 0 ? config.managed : true,
14
+ isActive: config.isActive !== void 0 ? config.isActive : true
15
+ };
16
+ registeredCollections.push(normalizedConfig);
17
+ console.log(`\u2713 Registered collection: ${config.name}`);
18
+ }
19
+ }
20
+ async function loadCollectionConfigs() {
21
+ const collections = [...registeredCollections];
22
+ try {
23
+ const modules = undefined?.("../collections/*.collection.ts", { eager: true }) || {};
24
+ for (const [path, module] of Object.entries(modules)) {
25
+ try {
26
+ const configModule = module;
27
+ if (!configModule.default) {
28
+ console.warn(`Collection file ${path} does not export a default config`);
29
+ continue;
30
+ }
31
+ const config = configModule.default;
32
+ if (!config.name || !config.displayName || !config.schema) {
33
+ console.error(`Invalid collection config in ${path}: missing required fields`);
34
+ continue;
35
+ }
36
+ const normalizedConfig = {
37
+ ...config,
38
+ managed: config.managed !== void 0 ? config.managed : true,
39
+ isActive: config.isActive !== void 0 ? config.isActive : true
40
+ };
41
+ collections.push(normalizedConfig);
42
+ console.log(`\u2713 Loaded collection config: ${config.name}`);
43
+ } catch (error) {
44
+ console.error(`Error loading collection from ${path}:`, error);
45
+ }
46
+ }
47
+ console.log(`Loaded ${collections.length} total collection configuration(s) (${registeredCollections.length} registered, ${collections.length - registeredCollections.length} from core)`);
48
+ return collections;
49
+ } catch (error) {
50
+ console.error("Error loading collection configurations:", error);
51
+ return collections;
52
+ }
53
+ }
54
+ async function loadCollectionConfig(name) {
55
+ try {
56
+ console.warn("loadCollectionConfig requires implementation in consuming application");
57
+ return null;
58
+ } catch (error) {
59
+ console.error(`Error loading collection ${name}:`, error);
60
+ return null;
61
+ }
62
+ }
63
+ async function getAvailableCollectionNames() {
64
+ try {
65
+ const modules = undefined?.("../collections/*.collection.ts") || {};
66
+ const names = [];
67
+ for (const path of Object.keys(modules)) {
68
+ const match = path.match(/\/([^/]+)\.collection\.ts$/);
69
+ if (match && match[1]) {
70
+ names.push(match[1]);
71
+ }
72
+ }
73
+ return names;
74
+ } catch (error) {
75
+ console.error("Error getting collection names:", error);
76
+ return [];
77
+ }
78
+ }
79
+ function validateCollectionConfig(config) {
80
+ const errors = [];
81
+ if (!config.name) {
82
+ errors.push("Collection name is required");
83
+ } else if (!/^[a-z0-9_]+$/.test(config.name)) {
84
+ errors.push("Collection name must contain only lowercase letters, numbers, and underscores");
85
+ }
86
+ if (!config.displayName) {
87
+ errors.push("Display name is required");
88
+ }
89
+ if (!config.schema) {
90
+ errors.push("Schema is required");
91
+ } else {
92
+ if (config.schema.type !== "object") {
93
+ errors.push('Schema type must be "object"');
94
+ }
95
+ if (!config.schema.properties || typeof config.schema.properties !== "object") {
96
+ errors.push("Schema must have properties");
97
+ }
98
+ for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) {
99
+ if (!fieldConfig.type) {
100
+ errors.push(`Field "${fieldName}" is missing type`);
101
+ }
102
+ if (fieldConfig.type === "reference" && !fieldConfig.collection) {
103
+ errors.push(`Reference field "${fieldName}" is missing collection property`);
104
+ }
105
+ if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) {
106
+ errors.push(`Select field "${fieldName}" is missing enum options`);
107
+ }
108
+ }
109
+ }
110
+ return {
111
+ valid: errors.length === 0,
112
+ errors
113
+ };
114
+ }
115
+
116
+ // src/services/collection-sync.ts
117
+ async function syncCollections(db) {
118
+ console.log("\u{1F504} Starting collection sync...");
119
+ const results = [];
120
+ const configs = await loadCollectionConfigs();
121
+ if (configs.length === 0) {
122
+ console.log("\u26A0\uFE0F No collection configurations found");
123
+ return results;
124
+ }
125
+ for (const config of configs) {
126
+ const result = await syncCollection(db, config);
127
+ results.push(result);
128
+ }
129
+ const created = results.filter((r) => r.status === "created").length;
130
+ const updated = results.filter((r) => r.status === "updated").length;
131
+ const unchanged = results.filter((r) => r.status === "unchanged").length;
132
+ const errors = results.filter((r) => r.status === "error").length;
133
+ console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`);
134
+ return results;
135
+ }
136
+ async function syncCollection(db, config) {
137
+ try {
138
+ const validation = validateCollectionConfig(config);
139
+ if (!validation.valid) {
140
+ return {
141
+ name: config.name,
142
+ status: "error",
143
+ error: `Validation failed: ${validation.errors.join(", ")}`
144
+ };
145
+ }
146
+ const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?");
147
+ const existing = await existingStmt.bind(config.name).first();
148
+ const now = Date.now();
149
+ const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`;
150
+ const schemaJson = JSON.stringify(config.schema);
151
+ const isActive = config.isActive !== false ? 1 : 0;
152
+ const managed = config.managed !== false ? 1 : 0;
153
+ if (!existing) {
154
+ const insertStmt = db.prepare(`
155
+ INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at)
156
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
157
+ `);
158
+ await insertStmt.bind(
159
+ collectionId,
160
+ config.name,
161
+ config.displayName,
162
+ config.description || null,
163
+ schemaJson,
164
+ isActive,
165
+ managed,
166
+ now,
167
+ now
168
+ ).run();
169
+ console.log(` \u2713 Created collection: ${config.name}`);
170
+ return {
171
+ name: config.name,
172
+ status: "created",
173
+ message: `Created collection "${config.displayName}"`
174
+ };
175
+ } else {
176
+ const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}";
177
+ const existingDisplayName = existing.display_name;
178
+ const existingDescription = existing.description;
179
+ const existingIsActive = existing.is_active;
180
+ const existingManaged = existing.managed;
181
+ const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged;
182
+ if (!needsUpdate) {
183
+ return {
184
+ name: config.name,
185
+ status: "unchanged",
186
+ message: `Collection "${config.displayName}" is up to date`
187
+ };
188
+ }
189
+ const updateStmt = db.prepare(`
190
+ UPDATE collections
191
+ SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ?
192
+ WHERE name = ?
193
+ `);
194
+ await updateStmt.bind(
195
+ config.displayName,
196
+ config.description || null,
197
+ schemaJson,
198
+ isActive,
199
+ managed,
200
+ now,
201
+ config.name
202
+ ).run();
203
+ console.log(` \u2713 Updated collection: ${config.name}`);
204
+ return {
205
+ name: config.name,
206
+ status: "updated",
207
+ message: `Updated collection "${config.displayName}"`
208
+ };
209
+ }
210
+ } catch (error) {
211
+ console.error(` \u2717 Error syncing collection ${config.name}:`, error);
212
+ return {
213
+ name: config.name,
214
+ status: "error",
215
+ error: error instanceof Error ? error.message : "Unknown error"
216
+ };
217
+ }
218
+ }
219
+ async function isCollectionManaged(db, collectionName) {
220
+ try {
221
+ const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?");
222
+ const result = await stmt.bind(collectionName).first();
223
+ return result?.managed === 1;
224
+ } catch (error) {
225
+ console.error(`Error checking if collection is managed:`, error);
226
+ return false;
227
+ }
228
+ }
229
+ async function getManagedCollections(db) {
230
+ try {
231
+ const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1");
232
+ const { results } = await stmt.all();
233
+ return (results || []).map((row) => row.name);
234
+ } catch (error) {
235
+ console.error("Error getting managed collections:", error);
236
+ return [];
237
+ }
238
+ }
239
+ async function cleanupRemovedCollections(db) {
240
+ try {
241
+ const configs = await loadCollectionConfigs();
242
+ const configNames = new Set(configs.map((c) => c.name));
243
+ const managedCollections = await getManagedCollections(db);
244
+ const removed = [];
245
+ for (const managedName of managedCollections) {
246
+ if (!configNames.has(managedName)) {
247
+ const updateStmt = db.prepare(`
248
+ UPDATE collections
249
+ SET is_active = 0, updated_at = ?
250
+ WHERE name = ? AND managed = 1
251
+ `);
252
+ await updateStmt.bind(Date.now(), managedName).run();
253
+ removed.push(managedName);
254
+ console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`);
255
+ }
256
+ }
257
+ return removed;
258
+ } catch (error) {
259
+ console.error("Error cleaning up removed collections:", error);
260
+ return [];
261
+ }
262
+ }
263
+ async function fullCollectionSync(db) {
264
+ const results = await syncCollections(db);
265
+ const removed = await cleanupRemovedCollections(db);
266
+ return { results, removed };
267
+ }
268
+
269
+ // src/services/plugin-service.ts
270
+ var PluginService = class {
271
+ constructor(db) {
272
+ this.db = db;
273
+ }
274
+ async getAllPlugins() {
275
+ await this.ensureAllPluginsExist();
276
+ const stmt = this.db.prepare(`
277
+ SELECT * FROM plugins
278
+ ORDER BY is_core DESC, display_name ASC
279
+ `);
280
+ const { results } = await stmt.all();
281
+ return (results || []).map(this.mapPluginFromDb);
282
+ }
283
+ /**
284
+ * Ensure all plugins from the registry exist in the database
285
+ * Auto-installs any newly detected plugins with inactive status
286
+ *
287
+ * Note: This method should be overridden or configured with a plugin registry
288
+ * in the consuming application
289
+ */
290
+ async ensureAllPluginsExist() {
291
+ console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration");
292
+ }
293
+ async getPlugin(pluginId) {
294
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?");
295
+ const plugin = await stmt.bind(pluginId).first();
296
+ if (!plugin) return null;
297
+ return this.mapPluginFromDb(plugin);
298
+ }
299
+ async getPluginByName(name) {
300
+ const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?");
301
+ const plugin = await stmt.bind(name).first();
302
+ if (!plugin) return null;
303
+ return this.mapPluginFromDb(plugin);
304
+ }
305
+ async getPluginStats() {
306
+ const stmt = this.db.prepare(`
307
+ SELECT
308
+ COUNT(*) as total,
309
+ COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
310
+ COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive,
311
+ COUNT(CASE WHEN status = 'error' THEN 1 END) as errors
312
+ FROM plugins
313
+ `);
314
+ const stats = await stmt.first();
315
+ return {
316
+ total: stats.total || 0,
317
+ active: stats.active || 0,
318
+ inactive: stats.inactive || 0,
319
+ errors: stats.errors || 0
320
+ };
321
+ }
322
+ async installPlugin(pluginData) {
323
+ const id = pluginData.id || `plugin-${Date.now()}`;
324
+ const now = Math.floor(Date.now() / 1e3);
325
+ const stmt = this.db.prepare(`
326
+ INSERT INTO plugins (
327
+ id, name, display_name, description, version, author, category, icon,
328
+ status, is_core, settings, permissions, dependencies, download_count,
329
+ rating, installed_at, last_updated
330
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
331
+ `);
332
+ await stmt.bind(
333
+ id,
334
+ pluginData.name || id,
335
+ pluginData.display_name || "Unnamed Plugin",
336
+ pluginData.description || "",
337
+ pluginData.version || "1.0.0",
338
+ pluginData.author || "Unknown",
339
+ pluginData.category || "utilities",
340
+ pluginData.icon || "\u{1F50C}",
341
+ "inactive",
342
+ pluginData.is_core || false,
343
+ JSON.stringify(pluginData.settings || {}),
344
+ JSON.stringify(pluginData.permissions || []),
345
+ JSON.stringify(pluginData.dependencies || []),
346
+ pluginData.download_count || 0,
347
+ pluginData.rating || 0,
348
+ now,
349
+ now
350
+ ).run();
351
+ await this.logActivity(id, "installed", null, { version: pluginData.version });
352
+ const installed = await this.getPlugin(id);
353
+ if (!installed) throw new Error("Failed to install plugin");
354
+ return installed;
355
+ }
356
+ async uninstallPlugin(pluginId) {
357
+ const plugin = await this.getPlugin(pluginId);
358
+ if (!plugin) throw new Error("Plugin not found");
359
+ if (plugin.is_core) throw new Error("Cannot uninstall core plugins");
360
+ if (plugin.status === "active") {
361
+ await this.deactivatePlugin(pluginId);
362
+ }
363
+ const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?");
364
+ await stmt.bind(pluginId).run();
365
+ await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name });
366
+ }
367
+ async activatePlugin(pluginId) {
368
+ const plugin = await this.getPlugin(pluginId);
369
+ if (!plugin) throw new Error("Plugin not found");
370
+ if (plugin.dependencies && plugin.dependencies.length > 0) {
371
+ await this.checkDependencies(plugin.dependencies);
372
+ }
373
+ const now = Math.floor(Date.now() / 1e3);
374
+ const stmt = this.db.prepare(`
375
+ UPDATE plugins
376
+ SET status = 'active', activated_at = ?, error_message = NULL
377
+ WHERE id = ?
378
+ `);
379
+ await stmt.bind(now, pluginId).run();
380
+ await this.logActivity(pluginId, "activated", null);
381
+ }
382
+ async deactivatePlugin(pluginId) {
383
+ const plugin = await this.getPlugin(pluginId);
384
+ if (!plugin) throw new Error("Plugin not found");
385
+ await this.checkDependents(plugin.name);
386
+ const stmt = this.db.prepare(`
387
+ UPDATE plugins
388
+ SET status = 'inactive', activated_at = NULL
389
+ WHERE id = ?
390
+ `);
391
+ await stmt.bind(pluginId).run();
392
+ await this.logActivity(pluginId, "deactivated", null);
393
+ }
394
+ async updatePluginSettings(pluginId, settings) {
395
+ const plugin = await this.getPlugin(pluginId);
396
+ if (!plugin) throw new Error("Plugin not found");
397
+ const stmt = this.db.prepare(`
398
+ UPDATE plugins
399
+ SET settings = ?, updated_at = unixepoch()
400
+ WHERE id = ?
401
+ `);
402
+ await stmt.bind(JSON.stringify(settings), pluginId).run();
403
+ await this.logActivity(pluginId, "settings_updated", null);
404
+ }
405
+ async setPluginError(pluginId, error) {
406
+ const stmt = this.db.prepare(`
407
+ UPDATE plugins
408
+ SET status = 'error', error_message = ?
409
+ WHERE id = ?
410
+ `);
411
+ await stmt.bind(error, pluginId).run();
412
+ await this.logActivity(pluginId, "error", null, { error });
413
+ }
414
+ async getPluginActivity(pluginId, limit = 10) {
415
+ const stmt = this.db.prepare(`
416
+ SELECT * FROM plugin_activity_log
417
+ WHERE plugin_id = ?
418
+ ORDER BY timestamp DESC
419
+ LIMIT ?
420
+ `);
421
+ const { results } = await stmt.bind(pluginId, limit).all();
422
+ return (results || []).map((row) => ({
423
+ id: row.id,
424
+ action: row.action,
425
+ userId: row.user_id,
426
+ details: row.details ? JSON.parse(row.details) : null,
427
+ timestamp: row.timestamp
428
+ }));
429
+ }
430
+ async registerHook(pluginId, hookName, handlerName, priority = 10) {
431
+ const id = `hook-${Date.now()}`;
432
+ const stmt = this.db.prepare(`
433
+ INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority)
434
+ VALUES (?, ?, ?, ?, ?)
435
+ `);
436
+ await stmt.bind(id, pluginId, hookName, handlerName, priority).run();
437
+ }
438
+ async registerRoute(pluginId, path, method, handlerName, middleware) {
439
+ const id = `route-${Date.now()}`;
440
+ const stmt = this.db.prepare(`
441
+ INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware)
442
+ VALUES (?, ?, ?, ?, ?, ?)
443
+ `);
444
+ await stmt.bind(
445
+ id,
446
+ pluginId,
447
+ path,
448
+ method,
449
+ handlerName,
450
+ JSON.stringify(middleware || [])
451
+ ).run();
452
+ }
453
+ async getPluginHooks(pluginId) {
454
+ const stmt = this.db.prepare(`
455
+ SELECT * FROM plugin_hooks
456
+ WHERE plugin_id = ? AND is_active = TRUE
457
+ ORDER BY priority ASC
458
+ `);
459
+ const { results } = await stmt.bind(pluginId).all();
460
+ return results || [];
461
+ }
462
+ async getPluginRoutes(pluginId) {
463
+ const stmt = this.db.prepare(`
464
+ SELECT * FROM plugin_routes
465
+ WHERE plugin_id = ? AND is_active = TRUE
466
+ `);
467
+ const { results } = await stmt.bind(pluginId).all();
468
+ return results || [];
469
+ }
470
+ async checkDependencies(dependencies) {
471
+ for (const dep of dependencies) {
472
+ const plugin = await this.getPluginByName(dep);
473
+ if (!plugin || plugin.status !== "active") {
474
+ throw new Error(`Required dependency '${dep}' is not active`);
475
+ }
476
+ }
477
+ }
478
+ async checkDependents(pluginName) {
479
+ const stmt = this.db.prepare(`
480
+ SELECT id, display_name FROM plugins
481
+ WHERE status = 'active'
482
+ AND dependencies LIKE ?
483
+ `);
484
+ const { results } = await stmt.bind(`%"${pluginName}"%`).all();
485
+ if (results && results.length > 0) {
486
+ const names = results.map((p) => p.display_name).join(", ");
487
+ throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`);
488
+ }
489
+ }
490
+ async logActivity(pluginId, action, userId, details) {
491
+ const id = `activity-${Date.now()}`;
492
+ const stmt = this.db.prepare(`
493
+ INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details)
494
+ VALUES (?, ?, ?, ?, ?)
495
+ `);
496
+ await stmt.bind(
497
+ id,
498
+ pluginId,
499
+ action,
500
+ userId,
501
+ details ? JSON.stringify(details) : null
502
+ ).run();
503
+ }
504
+ mapPluginFromDb(row) {
505
+ return {
506
+ id: row.id,
507
+ name: row.name,
508
+ display_name: row.display_name,
509
+ description: row.description,
510
+ version: row.version,
511
+ author: row.author,
512
+ category: row.category,
513
+ icon: row.icon,
514
+ status: row.status,
515
+ is_core: row.is_core === 1,
516
+ settings: row.settings ? JSON.parse(row.settings) : void 0,
517
+ permissions: row.permissions ? JSON.parse(row.permissions) : void 0,
518
+ dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0,
519
+ download_count: row.download_count || 0,
520
+ rating: row.rating || 0,
521
+ installed_at: row.installed_at,
522
+ activated_at: row.activated_at,
523
+ last_updated: row.last_updated,
524
+ error_message: row.error_message
525
+ };
526
+ }
527
+ };
528
+
529
+ // src/services/plugin-bootstrap.ts
530
+ var PluginBootstrapService = class {
531
+ constructor(db) {
532
+ this.db = db;
533
+ this.pluginService = new PluginService(db);
534
+ }
535
+ pluginService;
536
+ /**
537
+ * Core plugins that should always be available in the system
538
+ */
539
+ CORE_PLUGINS = [
540
+ {
541
+ id: "core-auth",
542
+ name: "core-auth",
543
+ display_name: "Authentication System",
544
+ description: "Core authentication and user management system",
545
+ version: "1.0.0",
546
+ author: "SonicJS Team",
547
+ category: "security",
548
+ icon: "\u{1F510}",
549
+ permissions: ["manage:users", "manage:roles", "manage:permissions"],
550
+ dependencies: [],
551
+ settings: {
552
+ requiredFields: {
553
+ email: { required: true, minLength: 5, label: "Email", type: "email" },
554
+ password: { required: true, minLength: 8, label: "Password", type: "password" },
555
+ username: { required: true, minLength: 3, label: "Username", type: "text" },
556
+ firstName: { required: true, minLength: 1, label: "First Name", type: "text" },
557
+ lastName: { required: true, minLength: 1, label: "Last Name", type: "text" }
558
+ },
559
+ validation: {
560
+ emailFormat: true,
561
+ allowDuplicateUsernames: false,
562
+ passwordRequirements: {
563
+ requireUppercase: false,
564
+ requireLowercase: false,
565
+ requireNumbers: false,
566
+ requireSpecialChars: false
567
+ }
568
+ },
569
+ registration: {
570
+ enabled: true,
571
+ requireEmailVerification: false,
572
+ defaultRole: "viewer"
573
+ }
574
+ }
575
+ },
576
+ {
577
+ id: "core-media",
578
+ name: "core-media",
579
+ display_name: "Media Manager",
580
+ description: "Core media upload and management system",
581
+ version: "1.0.0",
582
+ author: "SonicJS Team",
583
+ category: "media",
584
+ icon: "\u{1F4F8}",
585
+ permissions: ["manage:media", "upload:files"],
586
+ dependencies: [],
587
+ settings: {}
588
+ },
589
+ {
590
+ id: "database-tools",
591
+ name: "database-tools",
592
+ display_name: "Database Tools",
593
+ description: "Database management tools including truncate, backup, and validation",
594
+ version: "1.0.0",
595
+ author: "SonicJS Team",
596
+ category: "system",
597
+ icon: "\u{1F5C4}\uFE0F",
598
+ permissions: ["manage:database", "admin"],
599
+ dependencies: [],
600
+ settings: {
601
+ enableTruncate: true,
602
+ enableBackup: true,
603
+ enableValidation: true,
604
+ requireConfirmation: true
605
+ }
606
+ },
607
+ {
608
+ id: "seed-data",
609
+ name: "seed-data",
610
+ display_name: "Seed Data",
611
+ description: "Generate realistic example users and content for testing and development",
612
+ version: "1.0.0",
613
+ author: "SonicJS Team",
614
+ category: "development",
615
+ icon: "\u{1F331}",
616
+ permissions: ["admin"],
617
+ dependencies: [],
618
+ settings: {
619
+ userCount: 20,
620
+ contentCount: 200,
621
+ defaultPassword: "password123"
622
+ }
623
+ },
624
+ {
625
+ id: "core-cache",
626
+ name: "core-cache",
627
+ display_name: "Cache System",
628
+ description: "Three-tiered caching system with memory, KV, and database layers",
629
+ version: "1.0.0",
630
+ author: "SonicJS Team",
631
+ category: "performance",
632
+ icon: "\u26A1",
633
+ permissions: ["manage:cache", "view:stats"],
634
+ dependencies: [],
635
+ settings: {
636
+ enableMemoryCache: true,
637
+ enableKVCache: true,
638
+ enableDatabaseCache: true,
639
+ defaultTTL: 3600
640
+ }
641
+ },
642
+ {
643
+ id: "workflow-plugin",
644
+ name: "workflow-plugin",
645
+ display_name: "Workflow Management",
646
+ description: "Content workflow management with approval chains, scheduling, and automation",
647
+ version: "1.0.0-beta.1",
648
+ author: "SonicJS Team",
649
+ category: "content",
650
+ icon: "\u{1F504}",
651
+ permissions: ["manage:workflows", "view:workflows", "transition:content"],
652
+ dependencies: ["content-plugin"],
653
+ settings: {
654
+ enableApprovalChains: true,
655
+ enableScheduling: true,
656
+ enableAutomation: true,
657
+ enableNotifications: true
658
+ }
659
+ },
660
+ {
661
+ id: "easy-mdx",
662
+ name: "easy-mdx",
663
+ display_name: "EasyMDE Editor",
664
+ description: "Lightweight markdown editor with live preview for richtext fields",
665
+ version: "1.0.0",
666
+ author: "SonicJS Team",
667
+ category: "editor",
668
+ icon: "\u270D\uFE0F",
669
+ permissions: [],
670
+ dependencies: [],
671
+ settings: {
672
+ defaultHeight: 400,
673
+ toolbar: "full",
674
+ placeholder: "Start writing your content..."
675
+ }
676
+ }
677
+ ];
678
+ /**
679
+ * Bootstrap all core plugins - install them if they don't exist
680
+ */
681
+ async bootstrapCorePlugins() {
682
+ console.log("[PluginBootstrap] Starting core plugin bootstrap process...");
683
+ try {
684
+ for (const corePlugin of this.CORE_PLUGINS) {
685
+ await this.ensurePluginInstalled(corePlugin);
686
+ }
687
+ console.log(
688
+ "[PluginBootstrap] Core plugin bootstrap completed successfully"
689
+ );
690
+ } catch (error) {
691
+ console.error("[PluginBootstrap] Error during plugin bootstrap:", error);
692
+ throw error;
693
+ }
694
+ }
695
+ /**
696
+ * Ensure a specific plugin is installed
697
+ */
698
+ async ensurePluginInstalled(plugin) {
699
+ try {
700
+ const existingPlugin = await this.pluginService.getPlugin(plugin.id);
701
+ if (existingPlugin) {
702
+ console.log(
703
+ `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})`
704
+ );
705
+ if (existingPlugin.version !== plugin.version) {
706
+ console.log(
707
+ `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}`
708
+ );
709
+ await this.updatePlugin(plugin);
710
+ }
711
+ if (plugin.id === "core-auth" && existingPlugin.status !== "active") {
712
+ console.log(
713
+ `[PluginBootstrap] Core-auth plugin is inactive, activating it now...`
714
+ );
715
+ await this.pluginService.activatePlugin(plugin.id);
716
+ }
717
+ } else {
718
+ console.log(
719
+ `[PluginBootstrap] Installing plugin: ${plugin.display_name}`
720
+ );
721
+ await this.pluginService.installPlugin({
722
+ ...plugin,
723
+ is_core: plugin.name.startsWith("core-")
724
+ });
725
+ if (plugin.name.startsWith("core-")) {
726
+ console.log(
727
+ `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}`
728
+ );
729
+ await this.pluginService.activatePlugin(plugin.id);
730
+ }
731
+ }
732
+ } catch (error) {
733
+ console.error(
734
+ `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`,
735
+ error
736
+ );
737
+ }
738
+ }
739
+ /**
740
+ * Update an existing plugin
741
+ */
742
+ async updatePlugin(plugin) {
743
+ const now = Math.floor(Date.now() / 1e3);
744
+ const stmt = this.db.prepare(`
745
+ UPDATE plugins
746
+ SET
747
+ version = ?,
748
+ description = ?,
749
+ permissions = ?,
750
+ settings = ?,
751
+ last_updated = ?
752
+ WHERE id = ?
753
+ `);
754
+ await stmt.bind(
755
+ plugin.version,
756
+ plugin.description,
757
+ JSON.stringify(plugin.permissions),
758
+ JSON.stringify(plugin.settings || {}),
759
+ now,
760
+ plugin.id
761
+ ).run();
762
+ }
763
+ /**
764
+ * Check if bootstrap is needed (first run detection)
765
+ */
766
+ async isBootstrapNeeded() {
767
+ try {
768
+ for (const corePlugin of this.CORE_PLUGINS.filter(
769
+ (p) => p.name.startsWith("core-")
770
+ )) {
771
+ const exists = await this.pluginService.getPlugin(corePlugin.id);
772
+ if (!exists) {
773
+ return true;
774
+ }
775
+ }
776
+ return false;
777
+ } catch (error) {
778
+ console.error(
779
+ "[PluginBootstrap] Error checking bootstrap status:",
780
+ error
781
+ );
782
+ return true;
783
+ }
784
+ }
785
+ };
786
+
787
+ exports.PluginBootstrapService = PluginBootstrapService;
788
+ exports.PluginService = PluginService;
789
+ exports.cleanupRemovedCollections = cleanupRemovedCollections;
790
+ exports.fullCollectionSync = fullCollectionSync;
791
+ exports.getAvailableCollectionNames = getAvailableCollectionNames;
792
+ exports.getManagedCollections = getManagedCollections;
793
+ exports.isCollectionManaged = isCollectionManaged;
794
+ exports.loadCollectionConfig = loadCollectionConfig;
795
+ exports.loadCollectionConfigs = loadCollectionConfigs;
796
+ exports.registerCollections = registerCollections;
797
+ exports.syncCollection = syncCollection;
798
+ exports.syncCollections = syncCollections;
799
+ exports.validateCollectionConfig = validateCollectionConfig;
800
+ //# sourceMappingURL=chunk-22EFGHAX.cjs.map
801
+ //# sourceMappingURL=chunk-22EFGHAX.cjs.map