@sonicjs-cms/core 2.0.10 → 2.0.12

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 (87) hide show
  1. package/README.md +75 -1
  2. package/dist/chunk-22EFGHAX.cjs +801 -0
  3. package/dist/chunk-22EFGHAX.cjs.map +1 -0
  4. package/dist/{chunk-3PHG75W4.cjs → chunk-2HRF65VF.cjs} +9 -5
  5. package/dist/chunk-2HRF65VF.cjs.map +1 -0
  6. package/dist/{chunk-DOR2IU73.cjs → chunk-3F4LF7LW.cjs} +249 -2
  7. package/dist/chunk-3F4LF7LW.cjs.map +1 -0
  8. package/dist/chunk-3OKKNBPD.cjs +70 -0
  9. package/dist/chunk-3OKKNBPD.cjs.map +1 -0
  10. package/dist/{chunk-LW33AOBF.js → chunk-5RKQB2JG.js} +6 -222
  11. package/dist/chunk-5RKQB2JG.js.map +1 -0
  12. package/dist/{chunk-Z4H6DBVF.js → chunk-6B4ENDQM.js} +12006 -10745
  13. package/dist/chunk-6B4ENDQM.js.map +1 -0
  14. package/dist/chunk-AUVW4I3D.js +1550 -0
  15. package/dist/chunk-AUVW4I3D.js.map +1 -0
  16. package/dist/{chunk-HKEK7UNV.js → chunk-CPXAVWCU.js} +3 -3
  17. package/dist/{chunk-HKEK7UNV.js.map → chunk-CPXAVWCU.js.map} +1 -1
  18. package/dist/{chunk-MXJJN4IA.js → chunk-DSDHGJ4F.js} +9 -5
  19. package/dist/chunk-DSDHGJ4F.js.map +1 -0
  20. package/dist/{chunk-F5ESJXI2.cjs → chunk-DTLB6UIH.cjs} +3 -3
  21. package/dist/{chunk-F5ESJXI2.cjs.map → chunk-DTLB6UIH.cjs.map} +1 -1
  22. package/dist/{chunk-HXA5QSI3.cjs → chunk-F4IGVB2V.cjs} +22 -6
  23. package/dist/chunk-F4IGVB2V.cjs.map +1 -0
  24. package/dist/{chunk-Q7SL7U43.cjs → chunk-K5WUGEXH.cjs} +12014 -10752
  25. package/dist/chunk-K5WUGEXH.cjs.map +1 -0
  26. package/dist/{chunk-YHG45LMU.js → chunk-LBSKQKYL.js} +20 -4
  27. package/dist/chunk-LBSKQKYL.js.map +1 -0
  28. package/dist/chunk-LWMMMW43.js +787 -0
  29. package/dist/chunk-LWMMMW43.js.map +1 -0
  30. package/dist/{chunk-6FR25MPC.js → chunk-M2YDOOBC.js} +246 -3
  31. package/dist/chunk-M2YDOOBC.js.map +1 -0
  32. package/dist/{chunk-FTMKKKNH.js → chunk-QNWYQZ55.js} +3 -3
  33. package/dist/{chunk-FTMKKKNH.js.map → chunk-QNWYQZ55.js.map} +1 -1
  34. package/dist/chunk-RDJ2QLA2.cjs +1552 -0
  35. package/dist/chunk-RDJ2QLA2.cjs.map +1 -0
  36. package/dist/chunk-RKNHW6QU.js +61 -0
  37. package/dist/chunk-RKNHW6QU.js.map +1 -0
  38. package/dist/{chunk-MU3MR2QR.cjs → chunk-YU6QFFI4.cjs} +5 -222
  39. package/dist/chunk-YU6QFFI4.cjs.map +1 -0
  40. package/dist/{chunk-CAP6QQR2.cjs → chunk-ZMSYKV62.cjs} +5 -5
  41. package/dist/{chunk-CAP6QQR2.cjs.map → chunk-ZMSYKV62.cjs.map} +1 -1
  42. package/dist/index.cjs +527 -154
  43. package/dist/index.cjs.map +1 -1
  44. package/dist/index.js +390 -13
  45. package/dist/index.js.map +1 -1
  46. package/dist/middleware.cjs +24 -23
  47. package/dist/middleware.js +3 -2
  48. package/dist/migrations-DURR3GZX.js +4 -0
  49. package/dist/migrations-DURR3GZX.js.map +1 -0
  50. package/dist/migrations-P5BD7WQK.cjs +13 -0
  51. package/dist/migrations-P5BD7WQK.cjs.map +1 -0
  52. package/dist/plugins.cjs +7 -7
  53. package/dist/plugins.js +1 -1
  54. package/dist/routes.cjs +31 -29
  55. package/dist/routes.js +8 -6
  56. package/dist/services.cjs +42 -24
  57. package/dist/services.js +4 -2
  58. package/dist/templates.cjs +17 -21
  59. package/dist/templates.js +2 -2
  60. package/dist/utils.cjs +44 -11
  61. package/dist/utils.js +2 -1
  62. package/migrations/001_initial_schema.sql +2 -2
  63. package/migrations/007_demo_login_plugin.sql +1 -1
  64. package/migrations/020_add_email_plugin.sql +22 -0
  65. package/migrations/021_add_magic_link_auth_plugin.sql +42 -0
  66. package/migrations/022_add_tinymce_plugin.sql +25 -0
  67. package/migrations/023_add_easy_mdx_plugin.sql +25 -0
  68. package/migrations/024_add_quill_editor_plugin.sql +25 -0
  69. package/migrations/025_rename_mdxeditor_to_easy_mdx.sql +22 -0
  70. package/migrations/026_add_otp_login.sql +42 -0
  71. package/package.json +7 -3
  72. package/dist/chunk-3PHG75W4.cjs.map +0 -1
  73. package/dist/chunk-6FR25MPC.js.map +0 -1
  74. package/dist/chunk-COBUPOMD.js +0 -1511
  75. package/dist/chunk-COBUPOMD.js.map +0 -1
  76. package/dist/chunk-DOR2IU73.cjs.map +0 -1
  77. package/dist/chunk-HXA5QSI3.cjs.map +0 -1
  78. package/dist/chunk-LW33AOBF.js.map +0 -1
  79. package/dist/chunk-MU3MR2QR.cjs.map +0 -1
  80. package/dist/chunk-MXJJN4IA.js.map +0 -1
  81. package/dist/chunk-NBDPIRQS.cjs +0 -1526
  82. package/dist/chunk-NBDPIRQS.cjs.map +0 -1
  83. package/dist/chunk-Q7SL7U43.cjs.map +0 -1
  84. package/dist/chunk-YHG45LMU.js.map +0 -1
  85. package/dist/chunk-Z4H6DBVF.js.map +0 -1
  86. package/migrations/002_faq_plugin.sql +0 -86
  87. package/migrations/013_code_examples_plugin.sql +0 -177
@@ -1,1511 +0,0 @@
1
- // src/services/collection-loader.ts
2
- var registeredCollections = [];
3
- function registerCollections(collections) {
4
- for (const config of collections) {
5
- if (!config.name || !config.displayName || !config.schema) {
6
- console.error(`Invalid collection config: missing required fields`, config);
7
- continue;
8
- }
9
- const normalizedConfig = {
10
- ...config,
11
- managed: config.managed !== void 0 ? config.managed : true,
12
- isActive: config.isActive !== void 0 ? config.isActive : true
13
- };
14
- registeredCollections.push(normalizedConfig);
15
- console.log(`\u2713 Registered collection: ${config.name}`);
16
- }
17
- }
18
- async function loadCollectionConfigs() {
19
- const collections = [...registeredCollections];
20
- try {
21
- const modules = import.meta.glob?.("../collections/*.collection.ts", { eager: true }) || {};
22
- for (const [path, module] of Object.entries(modules)) {
23
- try {
24
- const configModule = module;
25
- if (!configModule.default) {
26
- console.warn(`Collection file ${path} does not export a default config`);
27
- continue;
28
- }
29
- const config = configModule.default;
30
- if (!config.name || !config.displayName || !config.schema) {
31
- console.error(`Invalid collection config in ${path}: missing required fields`);
32
- continue;
33
- }
34
- const normalizedConfig = {
35
- ...config,
36
- managed: config.managed !== void 0 ? config.managed : true,
37
- isActive: config.isActive !== void 0 ? config.isActive : true
38
- };
39
- collections.push(normalizedConfig);
40
- console.log(`\u2713 Loaded collection config: ${config.name}`);
41
- } catch (error) {
42
- console.error(`Error loading collection from ${path}:`, error);
43
- }
44
- }
45
- console.log(`Loaded ${collections.length} total collection configuration(s) (${registeredCollections.length} registered, ${collections.length - registeredCollections.length} from core)`);
46
- return collections;
47
- } catch (error) {
48
- console.error("Error loading collection configurations:", error);
49
- return collections;
50
- }
51
- }
52
- async function loadCollectionConfig(name) {
53
- try {
54
- console.warn("loadCollectionConfig requires implementation in consuming application");
55
- return null;
56
- } catch (error) {
57
- console.error(`Error loading collection ${name}:`, error);
58
- return null;
59
- }
60
- }
61
- async function getAvailableCollectionNames() {
62
- try {
63
- const modules = import.meta.glob?.("../collections/*.collection.ts") || {};
64
- const names = [];
65
- for (const path of Object.keys(modules)) {
66
- const match = path.match(/\/([^/]+)\.collection\.ts$/);
67
- if (match && match[1]) {
68
- names.push(match[1]);
69
- }
70
- }
71
- return names;
72
- } catch (error) {
73
- console.error("Error getting collection names:", error);
74
- return [];
75
- }
76
- }
77
- function validateCollectionConfig(config) {
78
- const errors = [];
79
- if (!config.name) {
80
- errors.push("Collection name is required");
81
- } else if (!/^[a-z0-9_]+$/.test(config.name)) {
82
- errors.push("Collection name must contain only lowercase letters, numbers, and underscores");
83
- }
84
- if (!config.displayName) {
85
- errors.push("Display name is required");
86
- }
87
- if (!config.schema) {
88
- errors.push("Schema is required");
89
- } else {
90
- if (config.schema.type !== "object") {
91
- errors.push('Schema type must be "object"');
92
- }
93
- if (!config.schema.properties || typeof config.schema.properties !== "object") {
94
- errors.push("Schema must have properties");
95
- }
96
- for (const [fieldName, fieldConfig] of Object.entries(config.schema.properties || {})) {
97
- if (!fieldConfig.type) {
98
- errors.push(`Field "${fieldName}" is missing type`);
99
- }
100
- if (fieldConfig.type === "reference" && !fieldConfig.collection) {
101
- errors.push(`Reference field "${fieldName}" is missing collection property`);
102
- }
103
- if (["select", "multiselect", "radio"].includes(fieldConfig.type) && !fieldConfig.enum) {
104
- errors.push(`Select field "${fieldName}" is missing enum options`);
105
- }
106
- }
107
- }
108
- return {
109
- valid: errors.length === 0,
110
- errors
111
- };
112
- }
113
-
114
- // src/services/collection-sync.ts
115
- async function syncCollections(db) {
116
- console.log("\u{1F504} Starting collection sync...");
117
- const results = [];
118
- const configs = await loadCollectionConfigs();
119
- if (configs.length === 0) {
120
- console.log("\u26A0\uFE0F No collection configurations found");
121
- return results;
122
- }
123
- for (const config of configs) {
124
- const result = await syncCollection(db, config);
125
- results.push(result);
126
- }
127
- const created = results.filter((r) => r.status === "created").length;
128
- const updated = results.filter((r) => r.status === "updated").length;
129
- const unchanged = results.filter((r) => r.status === "unchanged").length;
130
- const errors = results.filter((r) => r.status === "error").length;
131
- console.log(`\u2705 Collection sync complete: ${created} created, ${updated} updated, ${unchanged} unchanged, ${errors} errors`);
132
- return results;
133
- }
134
- async function syncCollection(db, config) {
135
- try {
136
- const validation = validateCollectionConfig(config);
137
- if (!validation.valid) {
138
- return {
139
- name: config.name,
140
- status: "error",
141
- error: `Validation failed: ${validation.errors.join(", ")}`
142
- };
143
- }
144
- const existingStmt = db.prepare("SELECT * FROM collections WHERE name = ?");
145
- const existing = await existingStmt.bind(config.name).first();
146
- const now = Date.now();
147
- const collectionId = existing?.id || `col-${config.name}-${crypto.randomUUID().slice(0, 8)}`;
148
- const schemaJson = JSON.stringify(config.schema);
149
- const isActive = config.isActive !== false ? 1 : 0;
150
- const managed = config.managed !== false ? 1 : 0;
151
- if (!existing) {
152
- const insertStmt = db.prepare(`
153
- INSERT INTO collections (id, name, display_name, description, schema, is_active, managed, created_at, updated_at)
154
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
155
- `);
156
- await insertStmt.bind(
157
- collectionId,
158
- config.name,
159
- config.displayName,
160
- config.description || null,
161
- schemaJson,
162
- isActive,
163
- managed,
164
- now,
165
- now
166
- ).run();
167
- console.log(` \u2713 Created collection: ${config.name}`);
168
- return {
169
- name: config.name,
170
- status: "created",
171
- message: `Created collection "${config.displayName}"`
172
- };
173
- } else {
174
- const existingSchema = existing.schema ? JSON.stringify(existing.schema) : "{}";
175
- const existingDisplayName = existing.display_name;
176
- const existingDescription = existing.description;
177
- const existingIsActive = existing.is_active;
178
- const existingManaged = existing.managed;
179
- const needsUpdate = schemaJson !== existingSchema || config.displayName !== existingDisplayName || (config.description || null) !== existingDescription || isActive !== existingIsActive || managed !== existingManaged;
180
- if (!needsUpdate) {
181
- return {
182
- name: config.name,
183
- status: "unchanged",
184
- message: `Collection "${config.displayName}" is up to date`
185
- };
186
- }
187
- const updateStmt = db.prepare(`
188
- UPDATE collections
189
- SET display_name = ?, description = ?, schema = ?, is_active = ?, managed = ?, updated_at = ?
190
- WHERE name = ?
191
- `);
192
- await updateStmt.bind(
193
- config.displayName,
194
- config.description || null,
195
- schemaJson,
196
- isActive,
197
- managed,
198
- now,
199
- config.name
200
- ).run();
201
- console.log(` \u2713 Updated collection: ${config.name}`);
202
- return {
203
- name: config.name,
204
- status: "updated",
205
- message: `Updated collection "${config.displayName}"`
206
- };
207
- }
208
- } catch (error) {
209
- console.error(` \u2717 Error syncing collection ${config.name}:`, error);
210
- return {
211
- name: config.name,
212
- status: "error",
213
- error: error instanceof Error ? error.message : "Unknown error"
214
- };
215
- }
216
- }
217
- async function isCollectionManaged(db, collectionName) {
218
- try {
219
- const stmt = db.prepare("SELECT managed FROM collections WHERE name = ?");
220
- const result = await stmt.bind(collectionName).first();
221
- return result?.managed === 1;
222
- } catch (error) {
223
- console.error(`Error checking if collection is managed:`, error);
224
- return false;
225
- }
226
- }
227
- async function getManagedCollections(db) {
228
- try {
229
- const stmt = db.prepare("SELECT name FROM collections WHERE managed = 1");
230
- const { results } = await stmt.all();
231
- return (results || []).map((row) => row.name);
232
- } catch (error) {
233
- console.error("Error getting managed collections:", error);
234
- return [];
235
- }
236
- }
237
- async function cleanupRemovedCollections(db) {
238
- try {
239
- const configs = await loadCollectionConfigs();
240
- const configNames = new Set(configs.map((c) => c.name));
241
- const managedCollections = await getManagedCollections(db);
242
- const removed = [];
243
- for (const managedName of managedCollections) {
244
- if (!configNames.has(managedName)) {
245
- const updateStmt = db.prepare(`
246
- UPDATE collections
247
- SET is_active = 0, updated_at = ?
248
- WHERE name = ? AND managed = 1
249
- `);
250
- await updateStmt.bind(Date.now(), managedName).run();
251
- removed.push(managedName);
252
- console.log(` \u26A0\uFE0F Deactivated removed collection: ${managedName}`);
253
- }
254
- }
255
- return removed;
256
- } catch (error) {
257
- console.error("Error cleaning up removed collections:", error);
258
- return [];
259
- }
260
- }
261
- async function fullCollectionSync(db) {
262
- const results = await syncCollections(db);
263
- const removed = await cleanupRemovedCollections(db);
264
- return { results, removed };
265
- }
266
-
267
- // src/services/migrations.ts
268
- var MigrationService = class {
269
- constructor(db) {
270
- this.db = db;
271
- }
272
- /**
273
- * Initialize the migrations tracking table
274
- */
275
- async initializeMigrationsTable() {
276
- const createTableQuery = `
277
- CREATE TABLE IF NOT EXISTS migrations (
278
- id TEXT PRIMARY KEY,
279
- name TEXT NOT NULL,
280
- filename TEXT NOT NULL,
281
- applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
282
- checksum TEXT
283
- )
284
- `;
285
- await this.db.prepare(createTableQuery).run();
286
- }
287
- /**
288
- * Get all available migrations from the migrations directory
289
- */
290
- async getAvailableMigrations() {
291
- const migrations = [];
292
- const migrationFiles = [
293
- { id: "001", name: "Initial Schema", filename: "001_initial_schema.sql", description: "Initial database schema with users, content, collections, and media tables" },
294
- { id: "002", name: "FAQ Plugin", filename: "002_faq_plugin.sql", description: "FAQ plugin tables and initial data" },
295
- { id: "003", name: "Stage 5 Enhancements", filename: "003_stage5_enhancements.sql", description: "Enhanced content management and media handling" },
296
- { id: "004", name: "User Management", filename: "004_stage6_user_management.sql", description: "Advanced user management with roles and permissions" },
297
- { id: "005", name: "Workflow & Automation", filename: "005_stage7_workflow_automation.sql", description: "Workflow states, automation rules, and scheduled content" },
298
- { id: "006", name: "Plugin System", filename: "006_plugin_system.sql", description: "Plugin registration and configuration system" },
299
- { id: "007", name: "Demo Login Plugin", filename: "007_demo_login_plugin.sql", description: "Demo login functionality" },
300
- { id: "008", name: "Fix Slug Validation", filename: "008_fix_slug_validation.sql", description: "Fix slug validation in content" },
301
- { id: "009", name: "System Logging", filename: "009_system_logging.sql", description: "System logging and audit trails" },
302
- { id: "011", name: "Config Managed Collections", filename: "011_config_managed_collections.sql", description: "Configuration for managed collections" },
303
- { id: "012", name: "Testimonials Plugin", filename: "012_testimonials_plugin.sql", description: "Testimonials plugin and collection" },
304
- { id: "013", name: "Code Examples Plugin", filename: "013_code_examples_plugin.sql", description: "Code examples plugin and collection" },
305
- { id: "014", name: "Fix Plugin Registry", filename: "014_fix_plugin_registry.sql", description: "Fix plugin registry issues" },
306
- { id: "015", name: "Add Remaining Plugins", filename: "015_add_remaining_plugins.sql", description: "Add remaining core plugins" },
307
- { id: "016", name: "Remove Duplicate Cache Plugin", filename: "016_remove_duplicate_cache_plugin.sql", description: "Remove duplicate cache plugin entries" },
308
- { id: "017", name: "Auth Configurable Fields", filename: "017_auth_configurable_fields.sql", description: "Configurable authentication fields" }
309
- ];
310
- const appliedResult = await this.db.prepare(
311
- "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at ASC"
312
- ).all();
313
- const appliedMigrations = new Map(
314
- appliedResult.results?.map((row) => [row.id, row]) || []
315
- );
316
- await this.autoDetectAppliedMigrations(appliedMigrations);
317
- for (const file of migrationFiles) {
318
- const applied = appliedMigrations.has(file.id);
319
- const appliedData = appliedMigrations.get(file.id);
320
- migrations.push({
321
- id: file.id,
322
- name: file.name,
323
- filename: file.filename,
324
- description: file.description,
325
- applied,
326
- appliedAt: applied ? appliedData?.applied_at : void 0,
327
- size: await this.getMigrationFileSize(file.filename)
328
- });
329
- }
330
- return migrations;
331
- }
332
- /**
333
- * Auto-detect applied migrations by checking if their tables exist
334
- */
335
- async autoDetectAppliedMigrations(appliedMigrations) {
336
- if (!appliedMigrations.has("001")) {
337
- const hasBasicTables = await this.checkTablesExist(["users", "content", "collections", "media"]);
338
- if (hasBasicTables) {
339
- appliedMigrations.set("001", {
340
- id: "001",
341
- applied_at: (/* @__PURE__ */ new Date()).toISOString(),
342
- name: "Initial Schema",
343
- filename: "001_initial_schema.sql"
344
- });
345
- await this.markMigrationApplied("001", "Initial Schema", "001_initial_schema.sql");
346
- }
347
- }
348
- if (!appliedMigrations.has("002")) {
349
- const hasFaqTables = await this.checkTablesExist(["faqs", "faq_categories"]);
350
- if (hasFaqTables) {
351
- appliedMigrations.set("002", {
352
- id: "002",
353
- applied_at: (/* @__PURE__ */ new Date()).toISOString(),
354
- name: "FAQ Plugin",
355
- filename: "002_faq_plugin.sql"
356
- });
357
- await this.markMigrationApplied("002", "FAQ Plugin", "002_faq_plugin.sql");
358
- }
359
- }
360
- if (!appliedMigrations.has("003")) {
361
- const hasEnhancedTables = await this.checkTablesExist(["content_versions", "email_themes", "email_templates"]);
362
- if (hasEnhancedTables) {
363
- appliedMigrations.set("003", {
364
- id: "003",
365
- applied_at: (/* @__PURE__ */ new Date()).toISOString(),
366
- name: "Stage 5 Enhancements",
367
- filename: "003_stage5_enhancements.sql"
368
- });
369
- await this.markMigrationApplied("003", "Stage 5 Enhancements", "003_stage5_enhancements.sql");
370
- }
371
- }
372
- if (!appliedMigrations.has("004")) {
373
- const hasUserTables = await this.checkTablesExist(["api_tokens", "workflow_history"]);
374
- if (hasUserTables) {
375
- appliedMigrations.set("004", {
376
- id: "004",
377
- applied_at: (/* @__PURE__ */ new Date()).toISOString(),
378
- name: "User Management",
379
- filename: "004_stage6_user_management.sql"
380
- });
381
- await this.markMigrationApplied("004", "User Management", "004_stage6_user_management.sql");
382
- }
383
- }
384
- if (!appliedMigrations.has("006")) {
385
- const hasPluginTables = await this.checkTablesExist(["plugins", "plugin_hooks"]);
386
- if (hasPluginTables) {
387
- appliedMigrations.set("006", {
388
- id: "006",
389
- applied_at: (/* @__PURE__ */ new Date()).toISOString(),
390
- name: "Plugin System",
391
- filename: "006_plugin_system.sql"
392
- });
393
- await this.markMigrationApplied("006", "Plugin System", "006_plugin_system.sql");
394
- }
395
- }
396
- }
397
- /**
398
- * Check if specific tables exist in the database
399
- */
400
- async checkTablesExist(tableNames) {
401
- try {
402
- for (const tableName of tableNames) {
403
- const result = await this.db.prepare(
404
- `SELECT name FROM sqlite_master WHERE type='table' AND name=?`
405
- ).bind(tableName).first();
406
- if (!result) {
407
- return false;
408
- }
409
- }
410
- return true;
411
- } catch (error) {
412
- return false;
413
- }
414
- }
415
- /**
416
- * Get migration status summary
417
- */
418
- async getMigrationStatus() {
419
- await this.initializeMigrationsTable();
420
- const migrations = await this.getAvailableMigrations();
421
- const appliedMigrations = migrations.filter((m) => m.applied);
422
- const pendingMigrations = migrations.filter((m) => !m.applied);
423
- const lastApplied = appliedMigrations.length > 0 ? appliedMigrations[appliedMigrations.length - 1]?.appliedAt : void 0;
424
- return {
425
- totalMigrations: migrations.length,
426
- appliedMigrations: appliedMigrations.length,
427
- pendingMigrations: pendingMigrations.length,
428
- lastApplied,
429
- migrations
430
- };
431
- }
432
- /**
433
- * Mark a migration as applied
434
- */
435
- async markMigrationApplied(migrationId, name, filename) {
436
- await this.initializeMigrationsTable();
437
- await this.db.prepare(
438
- "INSERT OR REPLACE INTO migrations (id, name, filename, applied_at) VALUES (?, ?, ?, CURRENT_TIMESTAMP)"
439
- ).bind(migrationId, name, filename).run();
440
- }
441
- /**
442
- * Check if a specific migration has been applied
443
- */
444
- async isMigrationApplied(migrationId) {
445
- await this.initializeMigrationsTable();
446
- const result = await this.db.prepare(
447
- "SELECT COUNT(*) as count FROM migrations WHERE id = ?"
448
- ).bind(migrationId).first();
449
- return result?.count > 0;
450
- }
451
- /**
452
- * Get the last applied migration
453
- */
454
- async getLastAppliedMigration() {
455
- await this.initializeMigrationsTable();
456
- const result = await this.db.prepare(
457
- "SELECT id, name, filename, applied_at FROM migrations ORDER BY applied_at DESC LIMIT 1"
458
- ).first();
459
- if (!result) return null;
460
- return {
461
- id: result.id,
462
- name: result.name,
463
- filename: result.filename,
464
- applied: true,
465
- appliedAt: result.applied_at
466
- };
467
- }
468
- /**
469
- * Get migration file size (simulated)
470
- */
471
- async getMigrationFileSize(filename) {
472
- const sizesMap = {
473
- "001_initial_schema.sql": 15420,
474
- "002_faq_plugin.sql": 2340,
475
- "003_stage5_enhancements.sql": 8920,
476
- "004_stage6_user_management.sql": 12680,
477
- "005_stage7_workflow_automation.sql": 18750,
478
- "006_plugin_system.sql": 5430
479
- };
480
- return sizesMap[filename] || 1e3;
481
- }
482
- /**
483
- * Run pending migrations
484
- */
485
- async runPendingMigrations() {
486
- const status = await this.getMigrationStatus();
487
- const pendingMigrations = status.migrations.filter((m) => !m.applied);
488
- if (pendingMigrations.length === 0) {
489
- return {
490
- success: true,
491
- message: "All migrations are up to date",
492
- applied: []
493
- };
494
- }
495
- const applied = [];
496
- for (const migration of pendingMigrations) {
497
- try {
498
- await this.applyMigration(migration);
499
- await this.markMigrationApplied(migration.id, migration.name, migration.filename);
500
- applied.push(migration.id);
501
- } catch (error) {
502
- console.error(`Failed to apply migration ${migration.id}:`, error);
503
- break;
504
- }
505
- }
506
- return {
507
- success: true,
508
- message: `Applied ${applied.length} migration(s)`,
509
- applied
510
- };
511
- }
512
- /**
513
- * Apply a specific migration
514
- */
515
- async applyMigration(migration) {
516
- console.log(`Applying migration ${migration.id}: ${migration.name}`);
517
- const migrationSQL = await this.getMigrationSQL(migration.id);
518
- if (migrationSQL === null) {
519
- throw new Error(`Migration SQL not found for ${migration.id}`);
520
- }
521
- if (migrationSQL === "") {
522
- console.log(`Skipping migration ${migration.id} (empty/obsolete)`);
523
- return;
524
- }
525
- const statements = this.splitSQLStatements(migrationSQL);
526
- for (const statement of statements) {
527
- if (statement.trim()) {
528
- try {
529
- await this.db.prepare(statement).run();
530
- } catch (error) {
531
- console.error(`Error executing statement: ${statement}`, error);
532
- throw error;
533
- }
534
- }
535
- }
536
- }
537
- /**
538
- * Split SQL into statements, handling CREATE TRIGGER properly
539
- */
540
- splitSQLStatements(sql) {
541
- const statements = [];
542
- let current = "";
543
- let inTrigger = false;
544
- const lines = sql.split("\n");
545
- for (const line of lines) {
546
- const trimmed = line.trim();
547
- if (trimmed.startsWith("--") || trimmed.length === 0) {
548
- continue;
549
- }
550
- if (trimmed.toUpperCase().includes("CREATE TRIGGER")) {
551
- inTrigger = true;
552
- }
553
- current += line + "\n";
554
- if (inTrigger && trimmed.toUpperCase() === "END;") {
555
- statements.push(current.trim());
556
- current = "";
557
- inTrigger = false;
558
- } else if (!inTrigger && trimmed.endsWith(";")) {
559
- statements.push(current.trim());
560
- current = "";
561
- }
562
- }
563
- if (current.trim()) {
564
- statements.push(current.trim());
565
- }
566
- return statements.filter((s) => s.length > 0);
567
- }
568
- /**
569
- * Get migration SQL by ID
570
- */
571
- async getMigrationSQL(migrationId) {
572
- switch (migrationId) {
573
- case "001":
574
- return `
575
- -- Initial schema for SonicJS AI
576
- -- Create users table for authentication
577
- CREATE TABLE IF NOT EXISTS users (
578
- id TEXT PRIMARY KEY,
579
- email TEXT NOT NULL UNIQUE,
580
- username TEXT NOT NULL UNIQUE,
581
- first_name TEXT NOT NULL,
582
- last_name TEXT NOT NULL,
583
- password_hash TEXT,
584
- role TEXT NOT NULL DEFAULT 'viewer',
585
- avatar TEXT,
586
- is_active INTEGER NOT NULL DEFAULT 1,
587
- last_login_at INTEGER,
588
- created_at INTEGER NOT NULL,
589
- updated_at INTEGER NOT NULL
590
- );
591
-
592
- -- Create collections table for content schema definitions
593
- CREATE TABLE IF NOT EXISTS collections (
594
- id TEXT PRIMARY KEY,
595
- name TEXT NOT NULL UNIQUE,
596
- display_name TEXT NOT NULL,
597
- description TEXT,
598
- schema TEXT NOT NULL,
599
- is_active INTEGER NOT NULL DEFAULT 1,
600
- created_at INTEGER NOT NULL,
601
- updated_at INTEGER NOT NULL
602
- );
603
-
604
- -- Create content table for actual content data
605
- CREATE TABLE IF NOT EXISTS content (
606
- id TEXT PRIMARY KEY,
607
- collection_id TEXT NOT NULL REFERENCES collections(id),
608
- slug TEXT NOT NULL,
609
- title TEXT NOT NULL,
610
- data TEXT NOT NULL,
611
- status TEXT NOT NULL DEFAULT 'draft',
612
- published_at INTEGER,
613
- author_id TEXT NOT NULL REFERENCES users(id),
614
- created_by TEXT NOT NULL REFERENCES users(id),
615
- created_at INTEGER NOT NULL,
616
- updated_at INTEGER NOT NULL
617
- );
618
-
619
- -- Create content_versions table for versioning
620
- CREATE TABLE IF NOT EXISTS content_versions (
621
- id TEXT PRIMARY KEY,
622
- content_id TEXT NOT NULL REFERENCES content(id),
623
- version INTEGER NOT NULL,
624
- data TEXT NOT NULL,
625
- author_id TEXT NOT NULL REFERENCES users(id),
626
- created_at INTEGER NOT NULL
627
- );
628
-
629
- -- Create media/files table with comprehensive R2 integration
630
- CREATE TABLE IF NOT EXISTS media (
631
- id TEXT PRIMARY KEY,
632
- filename TEXT NOT NULL,
633
- original_name TEXT NOT NULL,
634
- mime_type TEXT NOT NULL,
635
- size INTEGER NOT NULL,
636
- width INTEGER,
637
- height INTEGER,
638
- folder TEXT NOT NULL DEFAULT 'uploads',
639
- r2_key TEXT NOT NULL,
640
- public_url TEXT NOT NULL,
641
- thumbnail_url TEXT,
642
- alt TEXT,
643
- caption TEXT,
644
- tags TEXT,
645
- uploaded_by TEXT NOT NULL REFERENCES users(id),
646
- uploaded_at INTEGER NOT NULL,
647
- updated_at INTEGER,
648
- published_at INTEGER,
649
- scheduled_at INTEGER,
650
- archived_at INTEGER,
651
- deleted_at INTEGER
652
- );
653
-
654
- -- Create API tokens table for programmatic access
655
- CREATE TABLE IF NOT EXISTS api_tokens (
656
- id TEXT PRIMARY KEY,
657
- name TEXT NOT NULL,
658
- token TEXT NOT NULL UNIQUE,
659
- user_id TEXT NOT NULL REFERENCES users(id),
660
- permissions TEXT NOT NULL,
661
- expires_at INTEGER,
662
- last_used_at INTEGER,
663
- created_at INTEGER NOT NULL
664
- );
665
-
666
- -- Create workflow history table for content workflow tracking
667
- CREATE TABLE IF NOT EXISTS workflow_history (
668
- id TEXT PRIMARY KEY,
669
- content_id TEXT NOT NULL REFERENCES content(id),
670
- action TEXT NOT NULL,
671
- from_status TEXT NOT NULL,
672
- to_status TEXT NOT NULL,
673
- user_id TEXT NOT NULL REFERENCES users(id),
674
- comment TEXT,
675
- created_at INTEGER NOT NULL
676
- );
677
-
678
- -- Create indexes for better performance
679
- CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
680
- CREATE INDEX IF NOT EXISTS idx_users_username ON users(username);
681
- CREATE INDEX IF NOT EXISTS idx_users_role ON users(role);
682
-
683
- CREATE INDEX IF NOT EXISTS idx_collections_name ON collections(name);
684
- CREATE INDEX IF NOT EXISTS idx_collections_active ON collections(is_active);
685
-
686
- CREATE INDEX IF NOT EXISTS idx_content_collection ON content(collection_id);
687
- CREATE INDEX IF NOT EXISTS idx_content_author ON content(author_id);
688
- CREATE INDEX IF NOT EXISTS idx_content_status ON content(status);
689
- CREATE INDEX IF NOT EXISTS idx_content_published ON content(published_at);
690
- CREATE INDEX IF NOT EXISTS idx_content_slug ON content(slug);
691
-
692
- CREATE INDEX IF NOT EXISTS idx_content_versions_content ON content_versions(content_id);
693
- CREATE INDEX IF NOT EXISTS idx_content_versions_version ON content_versions(version);
694
-
695
- CREATE INDEX IF NOT EXISTS idx_media_folder ON media(folder);
696
- CREATE INDEX IF NOT EXISTS idx_media_type ON media(mime_type);
697
- CREATE INDEX IF NOT EXISTS idx_media_uploaded_by ON media(uploaded_by);
698
- CREATE INDEX IF NOT EXISTS idx_media_uploaded_at ON media(uploaded_at);
699
- CREATE INDEX IF NOT EXISTS idx_media_deleted ON media(deleted_at);
700
-
701
- CREATE INDEX IF NOT EXISTS idx_api_tokens_user ON api_tokens(user_id);
702
- CREATE INDEX IF NOT EXISTS idx_api_tokens_token ON api_tokens(token);
703
-
704
- CREATE INDEX IF NOT EXISTS idx_workflow_history_content ON workflow_history(content_id);
705
- CREATE INDEX IF NOT EXISTS idx_workflow_history_user ON workflow_history(user_id);
706
-
707
- -- Insert default admin user (password: admin123)
708
- INSERT OR IGNORE INTO users (
709
- id, email, username, first_name, last_name, password_hash,
710
- role, is_active, created_at, updated_at
711
- ) VALUES (
712
- 'admin-user-id',
713
- 'admin@sonicjs.com',
714
- 'admin',
715
- 'Admin',
716
- 'User',
717
- 'd1c379e871838f44e21d5a55841349e50636f06df139bfef11870eec74c381db',
718
- 'admin',
719
- 1,
720
- strftime('%s', 'now') * 1000,
721
- strftime('%s', 'now') * 1000
722
- );
723
-
724
- -- Insert sample collections
725
- INSERT OR IGNORE INTO collections (
726
- id, name, display_name, description, schema,
727
- is_active, created_at, updated_at
728
- ) VALUES (
729
- 'blog-posts-collection',
730
- 'blog_posts',
731
- 'Blog Posts',
732
- 'Blog post content collection',
733
- '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"excerpt":{"type":"string","title":"Excerpt"},"featured_image":{"type":"string","title":"Featured Image","format":"media"},"tags":{"type":"array","title":"Tags","items":{"type":"string"}},"status":{"type":"string","title":"Status","enum":["draft","published","archived"],"default":"draft"}},"required":["title"]}',
734
- 1,
735
- strftime('%s', 'now') * 1000,
736
- strftime('%s', 'now') * 1000
737
- ),
738
- (
739
- 'pages-collection',
740
- 'pages',
741
- 'Pages',
742
- 'Static page content collection',
743
- '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"slug":{"type":"string","title":"Slug"},"meta_description":{"type":"string","title":"Meta Description"},"featured_image":{"type":"string","title":"Featured Image","format":"media"}},"required":["title"]}',
744
- 1,
745
- strftime('%s', 'now') * 1000,
746
- strftime('%s', 'now') * 1000
747
- ),
748
- (
749
- 'news-collection',
750
- 'news',
751
- 'News',
752
- 'News article content collection',
753
- '{"type":"object","properties":{"title":{"type":"string","title":"Title","required":true},"content":{"type":"string","title":"Content","format":"richtext"},"publish_date":{"type":"string","title":"Publish Date","format":"date"},"author":{"type":"string","title":"Author"},"category":{"type":"string","title":"Category","enum":["technology","business","general"]}},"required":["title"]}',
754
- 1,
755
- strftime('%s', 'now') * 1000,
756
- strftime('%s', 'now') * 1000
757
- );
758
-
759
- -- Insert sample content
760
- INSERT OR IGNORE INTO content (
761
- id, collection_id, slug, title, data, status,
762
- author_id, created_by, created_at, updated_at
763
- ) VALUES (
764
- 'welcome-blog-post',
765
- 'blog-posts-collection',
766
- 'welcome-to-sonicjs-ai',
767
- 'Welcome to SonicJS AI',
768
- '{"title":"Welcome to SonicJS AI","content":"<h1>Welcome to SonicJS AI</h1><p>This is your first blog post created with SonicJS AI, a modern headless CMS built on Cloudflare Workers.</p><h2>Features</h2><ul><li>Cloudflare-native architecture</li><li>TypeScript-first development</li><li>Hono.js framework</li><li>D1 database</li><li>R2 media storage</li><li>Edge computing</li></ul><p>Get started by exploring the admin interface and creating your own content!</p>","excerpt":"Welcome to SonicJS AI, a modern headless CMS built on Cloudflare Workers with TypeScript and Hono.js.","status":"published","tags":["welcome","cms","cloudflare"]}',
769
- 'published',
770
- 'admin-user-id',
771
- 'admin-user-id',
772
- strftime('%s', 'now') * 1000,
773
- strftime('%s', 'now') * 1000
774
- );
775
- `;
776
- case "002":
777
- return `
778
- CREATE TABLE IF NOT EXISTS faqs (
779
- id INTEGER PRIMARY KEY AUTOINCREMENT,
780
- question TEXT NOT NULL,
781
- answer TEXT NOT NULL,
782
- category TEXT,
783
- tags TEXT,
784
- isPublished INTEGER NOT NULL DEFAULT 1,
785
- sortOrder INTEGER NOT NULL DEFAULT 0,
786
- created_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now')),
787
- updated_at INTEGER NOT NULL DEFAULT (strftime('%s', 'now'))
788
- );
789
-
790
- CREATE INDEX IF NOT EXISTS idx_faqs_category ON faqs(category);
791
- CREATE INDEX IF NOT EXISTS idx_faqs_published ON faqs(isPublished);
792
- CREATE INDEX IF NOT EXISTS idx_faqs_sort_order ON faqs(sortOrder);
793
-
794
- CREATE TRIGGER IF NOT EXISTS faqs_updated_at
795
- AFTER UPDATE ON faqs
796
- BEGIN
797
- UPDATE faqs SET updated_at = strftime('%s', 'now') WHERE id = NEW.id;
798
- END;
799
- `;
800
- case "006":
801
- return `
802
- -- Plugin System Tables
803
- CREATE TABLE IF NOT EXISTS plugins (
804
- id TEXT PRIMARY KEY,
805
- name TEXT NOT NULL UNIQUE,
806
- display_name TEXT NOT NULL,
807
- description TEXT,
808
- version TEXT NOT NULL,
809
- author TEXT NOT NULL,
810
- category TEXT NOT NULL,
811
- icon TEXT,
812
- status TEXT DEFAULT 'inactive' CHECK (status IN ('active', 'inactive', 'error')),
813
- is_core BOOLEAN DEFAULT FALSE,
814
- settings JSON,
815
- permissions JSON,
816
- dependencies JSON,
817
- download_count INTEGER DEFAULT 0,
818
- rating REAL DEFAULT 0,
819
- installed_at INTEGER NOT NULL,
820
- activated_at INTEGER,
821
- last_updated INTEGER NOT NULL,
822
- error_message TEXT,
823
- created_at INTEGER DEFAULT (unixepoch()),
824
- updated_at INTEGER DEFAULT (unixepoch())
825
- );
826
-
827
- CREATE TABLE IF NOT EXISTS plugin_hooks (
828
- id TEXT PRIMARY KEY,
829
- plugin_id TEXT NOT NULL,
830
- hook_name TEXT NOT NULL,
831
- handler_name TEXT NOT NULL,
832
- priority INTEGER DEFAULT 10,
833
- is_active BOOLEAN DEFAULT TRUE,
834
- created_at INTEGER DEFAULT (unixepoch()),
835
- FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE,
836
- UNIQUE(plugin_id, hook_name, handler_name)
837
- );
838
-
839
- CREATE TABLE IF NOT EXISTS plugin_routes (
840
- id TEXT PRIMARY KEY,
841
- plugin_id TEXT NOT NULL,
842
- path TEXT NOT NULL,
843
- method TEXT NOT NULL,
844
- handler_name TEXT NOT NULL,
845
- middleware JSON,
846
- is_active BOOLEAN DEFAULT TRUE,
847
- created_at INTEGER DEFAULT (unixepoch()),
848
- FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE,
849
- UNIQUE(plugin_id, path, method)
850
- );
851
-
852
- CREATE TABLE IF NOT EXISTS plugin_assets (
853
- id TEXT PRIMARY KEY,
854
- plugin_id TEXT NOT NULL,
855
- asset_type TEXT NOT NULL CHECK (asset_type IN ('css', 'js', 'image', 'font')),
856
- asset_path TEXT NOT NULL,
857
- load_order INTEGER DEFAULT 100,
858
- load_location TEXT DEFAULT 'footer' CHECK (load_location IN ('header', 'footer')),
859
- is_active BOOLEAN DEFAULT TRUE,
860
- created_at INTEGER DEFAULT (unixepoch()),
861
- FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE
862
- );
863
-
864
- CREATE TABLE IF NOT EXISTS plugin_activity_log (
865
- id TEXT PRIMARY KEY,
866
- plugin_id TEXT NOT NULL,
867
- action TEXT NOT NULL,
868
- user_id TEXT,
869
- details JSON,
870
- timestamp INTEGER DEFAULT (unixepoch()),
871
- FOREIGN KEY (plugin_id) REFERENCES plugins(id) ON DELETE CASCADE
872
- );
873
-
874
- -- Create indexes
875
- CREATE INDEX IF NOT EXISTS idx_plugins_status ON plugins(status);
876
- CREATE INDEX IF NOT EXISTS idx_plugins_category ON plugins(category);
877
- CREATE INDEX IF NOT EXISTS idx_plugin_hooks_plugin ON plugin_hooks(plugin_id);
878
- CREATE INDEX IF NOT EXISTS idx_plugin_routes_plugin ON plugin_routes(plugin_id);
879
- CREATE INDEX IF NOT EXISTS idx_plugin_assets_plugin ON plugin_assets(plugin_id);
880
- CREATE INDEX IF NOT EXISTS idx_plugin_activity_plugin ON plugin_activity_log(plugin_id);
881
- CREATE INDEX IF NOT EXISTS idx_plugin_activity_timestamp ON plugin_activity_log(timestamp);
882
-
883
- -- Insert core plugins
884
- INSERT OR IGNORE INTO plugins (
885
- id, name, display_name, description, version, author, category, icon,
886
- status, is_core, permissions, installed_at, last_updated
887
- ) VALUES
888
- (
889
- 'core-auth',
890
- 'core-auth',
891
- 'Authentication System',
892
- 'Core authentication and user management system',
893
- '1.0.0',
894
- 'SonicJS Team',
895
- 'security',
896
- '\u{1F510}',
897
- 'active',
898
- TRUE,
899
- '["manage:users", "manage:roles", "manage:permissions"]',
900
- unixepoch(),
901
- unixepoch()
902
- ),
903
- (
904
- 'core-media',
905
- 'core-media',
906
- 'Media Manager',
907
- 'Core media upload and management system',
908
- '1.0.0',
909
- 'SonicJS Team',
910
- 'media',
911
- '\u{1F4F8}',
912
- 'active',
913
- TRUE,
914
- '["manage:media", "upload:files"]',
915
- unixepoch(),
916
- unixepoch()
917
- ),
918
- (
919
- 'core-workflow',
920
- 'core-workflow',
921
- 'Workflow Engine',
922
- 'Content workflow and approval system',
923
- '1.0.0',
924
- 'SonicJS Team',
925
- 'content',
926
- '\u{1F504}',
927
- 'active',
928
- TRUE,
929
- '["manage:workflows", "approve:content"]',
930
- unixepoch(),
931
- unixepoch()
932
- ),
933
- (
934
- 'cache',
935
- 'cache',
936
- 'Cache System',
937
- 'Three-tiered caching system with memory, KV, and database layers',
938
- '1.0.0',
939
- 'SonicJS Team',
940
- 'performance',
941
- '\u26A1',
942
- 'active',
943
- TRUE,
944
- '["manage:cache","view:stats"]',
945
- unixepoch(),
946
- unixepoch()
947
- ),
948
- (
949
- 'design',
950
- 'design-plugin',
951
- 'Design System',
952
- 'Design system management including themes, components, and UI customization. Provides a visual interface for managing design tokens, typography, colors, and component library.',
953
- '1.0.0',
954
- 'SonicJS',
955
- 'ui',
956
- '\u{1F3A8}',
957
- 'active',
958
- TRUE,
959
- '["design.view", "design.edit"]',
960
- unixepoch(),
961
- unixepoch()
962
- );
963
- `;
964
- case "003":
965
- case "004":
966
- case "005":
967
- case "007":
968
- case "008":
969
- case "009":
970
- case "011":
971
- case "012":
972
- case "013":
973
- case "014":
974
- case "015":
975
- case "016":
976
- case "017":
977
- return "";
978
- default:
979
- return null;
980
- }
981
- }
982
- /**
983
- * Validate database schema (placeholder)
984
- */
985
- async validateSchema() {
986
- const issues = [];
987
- const requiredTables = [
988
- "users",
989
- "content",
990
- "collections",
991
- "media",
992
- "sessions"
993
- ];
994
- for (const table of requiredTables) {
995
- try {
996
- await this.db.prepare(`SELECT COUNT(*) FROM ${table} LIMIT 1`).first();
997
- } catch (error) {
998
- issues.push(`Missing table: ${table}`);
999
- }
1000
- }
1001
- return {
1002
- valid: issues.length === 0,
1003
- issues
1004
- };
1005
- }
1006
- };
1007
-
1008
- // src/services/plugin-service.ts
1009
- var PluginService = class {
1010
- constructor(db) {
1011
- this.db = db;
1012
- }
1013
- async getAllPlugins() {
1014
- await this.ensureAllPluginsExist();
1015
- const stmt = this.db.prepare(`
1016
- SELECT * FROM plugins
1017
- ORDER BY is_core DESC, display_name ASC
1018
- `);
1019
- const { results } = await stmt.all();
1020
- return (results || []).map(this.mapPluginFromDb);
1021
- }
1022
- /**
1023
- * Ensure all plugins from the registry exist in the database
1024
- * Auto-installs any newly detected plugins with inactive status
1025
- *
1026
- * Note: This method should be overridden or configured with a plugin registry
1027
- * in the consuming application
1028
- */
1029
- async ensureAllPluginsExist() {
1030
- console.log("[PluginService] ensureAllPluginsExist - requires PLUGIN_REGISTRY configuration");
1031
- }
1032
- async getPlugin(pluginId) {
1033
- const stmt = this.db.prepare("SELECT * FROM plugins WHERE id = ?");
1034
- const plugin = await stmt.bind(pluginId).first();
1035
- if (!plugin) return null;
1036
- return this.mapPluginFromDb(plugin);
1037
- }
1038
- async getPluginByName(name) {
1039
- const stmt = this.db.prepare("SELECT * FROM plugins WHERE name = ?");
1040
- const plugin = await stmt.bind(name).first();
1041
- if (!plugin) return null;
1042
- return this.mapPluginFromDb(plugin);
1043
- }
1044
- async getPluginStats() {
1045
- const stmt = this.db.prepare(`
1046
- SELECT
1047
- COUNT(*) as total,
1048
- COUNT(CASE WHEN status = 'active' THEN 1 END) as active,
1049
- COUNT(CASE WHEN status = 'inactive' THEN 1 END) as inactive,
1050
- COUNT(CASE WHEN status = 'error' THEN 1 END) as errors
1051
- FROM plugins
1052
- `);
1053
- const stats = await stmt.first();
1054
- return {
1055
- total: stats.total || 0,
1056
- active: stats.active || 0,
1057
- inactive: stats.inactive || 0,
1058
- errors: stats.errors || 0
1059
- };
1060
- }
1061
- async installPlugin(pluginData) {
1062
- const id = pluginData.id || `plugin-${Date.now()}`;
1063
- const now = Math.floor(Date.now() / 1e3);
1064
- const stmt = this.db.prepare(`
1065
- INSERT INTO plugins (
1066
- id, name, display_name, description, version, author, category, icon,
1067
- status, is_core, settings, permissions, dependencies, download_count,
1068
- rating, installed_at, last_updated
1069
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1070
- `);
1071
- await stmt.bind(
1072
- id,
1073
- pluginData.name || id,
1074
- pluginData.display_name || "Unnamed Plugin",
1075
- pluginData.description || "",
1076
- pluginData.version || "1.0.0",
1077
- pluginData.author || "Unknown",
1078
- pluginData.category || "utilities",
1079
- pluginData.icon || "\u{1F50C}",
1080
- "inactive",
1081
- pluginData.is_core || false,
1082
- JSON.stringify(pluginData.settings || {}),
1083
- JSON.stringify(pluginData.permissions || []),
1084
- JSON.stringify(pluginData.dependencies || []),
1085
- pluginData.download_count || 0,
1086
- pluginData.rating || 0,
1087
- now,
1088
- now
1089
- ).run();
1090
- await this.logActivity(id, "installed", null, { version: pluginData.version });
1091
- const installed = await this.getPlugin(id);
1092
- if (!installed) throw new Error("Failed to install plugin");
1093
- return installed;
1094
- }
1095
- async uninstallPlugin(pluginId) {
1096
- const plugin = await this.getPlugin(pluginId);
1097
- if (!plugin) throw new Error("Plugin not found");
1098
- if (plugin.is_core) throw new Error("Cannot uninstall core plugins");
1099
- if (plugin.status === "active") {
1100
- await this.deactivatePlugin(pluginId);
1101
- }
1102
- const stmt = this.db.prepare("DELETE FROM plugins WHERE id = ?");
1103
- await stmt.bind(pluginId).run();
1104
- await this.logActivity(pluginId, "uninstalled", null, { name: plugin.name });
1105
- }
1106
- async activatePlugin(pluginId) {
1107
- const plugin = await this.getPlugin(pluginId);
1108
- if (!plugin) throw new Error("Plugin not found");
1109
- if (plugin.dependencies && plugin.dependencies.length > 0) {
1110
- await this.checkDependencies(plugin.dependencies);
1111
- }
1112
- const now = Math.floor(Date.now() / 1e3);
1113
- const stmt = this.db.prepare(`
1114
- UPDATE plugins
1115
- SET status = 'active', activated_at = ?, error_message = NULL
1116
- WHERE id = ?
1117
- `);
1118
- await stmt.bind(now, pluginId).run();
1119
- await this.logActivity(pluginId, "activated", null);
1120
- }
1121
- async deactivatePlugin(pluginId) {
1122
- const plugin = await this.getPlugin(pluginId);
1123
- if (!plugin) throw new Error("Plugin not found");
1124
- await this.checkDependents(plugin.name);
1125
- const stmt = this.db.prepare(`
1126
- UPDATE plugins
1127
- SET status = 'inactive', activated_at = NULL
1128
- WHERE id = ?
1129
- `);
1130
- await stmt.bind(pluginId).run();
1131
- await this.logActivity(pluginId, "deactivated", null);
1132
- }
1133
- async updatePluginSettings(pluginId, settings) {
1134
- const plugin = await this.getPlugin(pluginId);
1135
- if (!plugin) throw new Error("Plugin not found");
1136
- const stmt = this.db.prepare(`
1137
- UPDATE plugins
1138
- SET settings = ?, updated_at = unixepoch()
1139
- WHERE id = ?
1140
- `);
1141
- await stmt.bind(JSON.stringify(settings), pluginId).run();
1142
- await this.logActivity(pluginId, "settings_updated", null);
1143
- }
1144
- async setPluginError(pluginId, error) {
1145
- const stmt = this.db.prepare(`
1146
- UPDATE plugins
1147
- SET status = 'error', error_message = ?
1148
- WHERE id = ?
1149
- `);
1150
- await stmt.bind(error, pluginId).run();
1151
- await this.logActivity(pluginId, "error", null, { error });
1152
- }
1153
- async getPluginActivity(pluginId, limit = 10) {
1154
- const stmt = this.db.prepare(`
1155
- SELECT * FROM plugin_activity_log
1156
- WHERE plugin_id = ?
1157
- ORDER BY timestamp DESC
1158
- LIMIT ?
1159
- `);
1160
- const { results } = await stmt.bind(pluginId, limit).all();
1161
- return (results || []).map((row) => ({
1162
- id: row.id,
1163
- action: row.action,
1164
- userId: row.user_id,
1165
- details: row.details ? JSON.parse(row.details) : null,
1166
- timestamp: row.timestamp
1167
- }));
1168
- }
1169
- async registerHook(pluginId, hookName, handlerName, priority = 10) {
1170
- const id = `hook-${Date.now()}`;
1171
- const stmt = this.db.prepare(`
1172
- INSERT INTO plugin_hooks (id, plugin_id, hook_name, handler_name, priority)
1173
- VALUES (?, ?, ?, ?, ?)
1174
- `);
1175
- await stmt.bind(id, pluginId, hookName, handlerName, priority).run();
1176
- }
1177
- async registerRoute(pluginId, path, method, handlerName, middleware) {
1178
- const id = `route-${Date.now()}`;
1179
- const stmt = this.db.prepare(`
1180
- INSERT INTO plugin_routes (id, plugin_id, path, method, handler_name, middleware)
1181
- VALUES (?, ?, ?, ?, ?, ?)
1182
- `);
1183
- await stmt.bind(
1184
- id,
1185
- pluginId,
1186
- path,
1187
- method,
1188
- handlerName,
1189
- JSON.stringify(middleware || [])
1190
- ).run();
1191
- }
1192
- async getPluginHooks(pluginId) {
1193
- const stmt = this.db.prepare(`
1194
- SELECT * FROM plugin_hooks
1195
- WHERE plugin_id = ? AND is_active = TRUE
1196
- ORDER BY priority ASC
1197
- `);
1198
- const { results } = await stmt.bind(pluginId).all();
1199
- return results || [];
1200
- }
1201
- async getPluginRoutes(pluginId) {
1202
- const stmt = this.db.prepare(`
1203
- SELECT * FROM plugin_routes
1204
- WHERE plugin_id = ? AND is_active = TRUE
1205
- `);
1206
- const { results } = await stmt.bind(pluginId).all();
1207
- return results || [];
1208
- }
1209
- async checkDependencies(dependencies) {
1210
- for (const dep of dependencies) {
1211
- const plugin = await this.getPluginByName(dep);
1212
- if (!plugin || plugin.status !== "active") {
1213
- throw new Error(`Required dependency '${dep}' is not active`);
1214
- }
1215
- }
1216
- }
1217
- async checkDependents(pluginName) {
1218
- const stmt = this.db.prepare(`
1219
- SELECT id, display_name FROM plugins
1220
- WHERE status = 'active'
1221
- AND dependencies LIKE ?
1222
- `);
1223
- const { results } = await stmt.bind(`%"${pluginName}"%`).all();
1224
- if (results && results.length > 0) {
1225
- const names = results.map((p) => p.display_name).join(", ");
1226
- throw new Error(`Cannot deactivate. The following plugins depend on this one: ${names}`);
1227
- }
1228
- }
1229
- async logActivity(pluginId, action, userId, details) {
1230
- const id = `activity-${Date.now()}`;
1231
- const stmt = this.db.prepare(`
1232
- INSERT INTO plugin_activity_log (id, plugin_id, action, user_id, details)
1233
- VALUES (?, ?, ?, ?, ?)
1234
- `);
1235
- await stmt.bind(
1236
- id,
1237
- pluginId,
1238
- action,
1239
- userId,
1240
- details ? JSON.stringify(details) : null
1241
- ).run();
1242
- }
1243
- mapPluginFromDb(row) {
1244
- return {
1245
- id: row.id,
1246
- name: row.name,
1247
- display_name: row.display_name,
1248
- description: row.description,
1249
- version: row.version,
1250
- author: row.author,
1251
- category: row.category,
1252
- icon: row.icon,
1253
- status: row.status,
1254
- is_core: row.is_core === 1,
1255
- settings: row.settings ? JSON.parse(row.settings) : void 0,
1256
- permissions: row.permissions ? JSON.parse(row.permissions) : void 0,
1257
- dependencies: row.dependencies ? JSON.parse(row.dependencies) : void 0,
1258
- download_count: row.download_count || 0,
1259
- rating: row.rating || 0,
1260
- installed_at: row.installed_at,
1261
- activated_at: row.activated_at,
1262
- last_updated: row.last_updated,
1263
- error_message: row.error_message
1264
- };
1265
- }
1266
- };
1267
-
1268
- // src/services/plugin-bootstrap.ts
1269
- var PluginBootstrapService = class {
1270
- constructor(db) {
1271
- this.db = db;
1272
- this.pluginService = new PluginService(db);
1273
- }
1274
- pluginService;
1275
- /**
1276
- * Core plugins that should always be available in the system
1277
- */
1278
- CORE_PLUGINS = [
1279
- {
1280
- id: "core-auth",
1281
- name: "core-auth",
1282
- display_name: "Authentication System",
1283
- description: "Core authentication and user management system",
1284
- version: "1.0.0",
1285
- author: "SonicJS Team",
1286
- category: "security",
1287
- icon: "\u{1F510}",
1288
- permissions: ["manage:users", "manage:roles", "manage:permissions"],
1289
- dependencies: [],
1290
- settings: {
1291
- requiredFields: {
1292
- email: { required: true, minLength: 5, label: "Email", type: "email" },
1293
- password: { required: true, minLength: 8, label: "Password", type: "password" },
1294
- username: { required: true, minLength: 3, label: "Username", type: "text" },
1295
- firstName: { required: true, minLength: 1, label: "First Name", type: "text" },
1296
- lastName: { required: true, minLength: 1, label: "Last Name", type: "text" }
1297
- },
1298
- validation: {
1299
- emailFormat: true,
1300
- allowDuplicateUsernames: false,
1301
- passwordRequirements: {
1302
- requireUppercase: false,
1303
- requireLowercase: false,
1304
- requireNumbers: false,
1305
- requireSpecialChars: false
1306
- }
1307
- },
1308
- registration: {
1309
- enabled: true,
1310
- requireEmailVerification: false,
1311
- defaultRole: "viewer"
1312
- }
1313
- }
1314
- },
1315
- {
1316
- id: "core-media",
1317
- name: "core-media",
1318
- display_name: "Media Manager",
1319
- description: "Core media upload and management system",
1320
- version: "1.0.0",
1321
- author: "SonicJS Team",
1322
- category: "media",
1323
- icon: "\u{1F4F8}",
1324
- permissions: ["manage:media", "upload:files"],
1325
- dependencies: [],
1326
- settings: {}
1327
- },
1328
- {
1329
- id: "database-tools",
1330
- name: "database-tools",
1331
- display_name: "Database Tools",
1332
- description: "Database management tools including truncate, backup, and validation",
1333
- version: "1.0.0",
1334
- author: "SonicJS Team",
1335
- category: "system",
1336
- icon: "\u{1F5C4}\uFE0F",
1337
- permissions: ["manage:database", "admin"],
1338
- dependencies: [],
1339
- settings: {
1340
- enableTruncate: true,
1341
- enableBackup: true,
1342
- enableValidation: true,
1343
- requireConfirmation: true
1344
- }
1345
- },
1346
- {
1347
- id: "seed-data",
1348
- name: "seed-data",
1349
- display_name: "Seed Data",
1350
- description: "Generate realistic example users and content for testing and development",
1351
- version: "1.0.0",
1352
- author: "SonicJS Team",
1353
- category: "development",
1354
- icon: "\u{1F331}",
1355
- permissions: ["admin"],
1356
- dependencies: [],
1357
- settings: {
1358
- userCount: 20,
1359
- contentCount: 200,
1360
- defaultPassword: "password123"
1361
- }
1362
- },
1363
- {
1364
- id: "core-cache",
1365
- name: "core-cache",
1366
- display_name: "Cache System",
1367
- description: "Three-tiered caching system with memory, KV, and database layers",
1368
- version: "1.0.0",
1369
- author: "SonicJS Team",
1370
- category: "performance",
1371
- icon: "\u26A1",
1372
- permissions: ["manage:cache", "view:stats"],
1373
- dependencies: [],
1374
- settings: {
1375
- enableMemoryCache: true,
1376
- enableKVCache: true,
1377
- enableDatabaseCache: true,
1378
- defaultTTL: 3600
1379
- }
1380
- },
1381
- {
1382
- id: "workflow-plugin",
1383
- name: "workflow-plugin",
1384
- display_name: "Workflow Management",
1385
- description: "Content workflow management with approval chains, scheduling, and automation",
1386
- version: "1.0.0-beta.1",
1387
- author: "SonicJS Team",
1388
- category: "content",
1389
- icon: "\u{1F504}",
1390
- permissions: ["manage:workflows", "view:workflows", "transition:content"],
1391
- dependencies: ["content-plugin"],
1392
- settings: {
1393
- enableApprovalChains: true,
1394
- enableScheduling: true,
1395
- enableAutomation: true,
1396
- enableNotifications: true
1397
- }
1398
- }
1399
- ];
1400
- /**
1401
- * Bootstrap all core plugins - install them if they don't exist
1402
- */
1403
- async bootstrapCorePlugins() {
1404
- console.log("[PluginBootstrap] Starting core plugin bootstrap process...");
1405
- try {
1406
- for (const corePlugin of this.CORE_PLUGINS) {
1407
- await this.ensurePluginInstalled(corePlugin);
1408
- }
1409
- console.log(
1410
- "[PluginBootstrap] Core plugin bootstrap completed successfully"
1411
- );
1412
- } catch (error) {
1413
- console.error("[PluginBootstrap] Error during plugin bootstrap:", error);
1414
- throw error;
1415
- }
1416
- }
1417
- /**
1418
- * Ensure a specific plugin is installed
1419
- */
1420
- async ensurePluginInstalled(plugin) {
1421
- try {
1422
- const existingPlugin = await this.pluginService.getPlugin(plugin.id);
1423
- if (existingPlugin) {
1424
- console.log(
1425
- `[PluginBootstrap] Plugin already installed: ${plugin.display_name} (status: ${existingPlugin.status})`
1426
- );
1427
- if (existingPlugin.version !== plugin.version) {
1428
- console.log(
1429
- `[PluginBootstrap] Updating plugin version: ${plugin.display_name} from ${existingPlugin.version} to ${plugin.version}`
1430
- );
1431
- await this.updatePlugin(plugin);
1432
- }
1433
- if (plugin.id === "core-auth" && existingPlugin.status !== "active") {
1434
- console.log(
1435
- `[PluginBootstrap] Core-auth plugin is inactive, activating it now...`
1436
- );
1437
- await this.pluginService.activatePlugin(plugin.id);
1438
- }
1439
- } else {
1440
- console.log(
1441
- `[PluginBootstrap] Installing plugin: ${plugin.display_name}`
1442
- );
1443
- await this.pluginService.installPlugin({
1444
- ...plugin,
1445
- is_core: plugin.name.startsWith("core-")
1446
- });
1447
- if (plugin.name.startsWith("core-")) {
1448
- console.log(
1449
- `[PluginBootstrap] Activating newly installed core plugin: ${plugin.display_name}`
1450
- );
1451
- await this.pluginService.activatePlugin(plugin.id);
1452
- }
1453
- }
1454
- } catch (error) {
1455
- console.error(
1456
- `[PluginBootstrap] Error ensuring plugin ${plugin.display_name}:`,
1457
- error
1458
- );
1459
- }
1460
- }
1461
- /**
1462
- * Update an existing plugin
1463
- */
1464
- async updatePlugin(plugin) {
1465
- const now = Math.floor(Date.now() / 1e3);
1466
- const stmt = this.db.prepare(`
1467
- UPDATE plugins
1468
- SET
1469
- version = ?,
1470
- description = ?,
1471
- permissions = ?,
1472
- settings = ?,
1473
- last_updated = ?
1474
- WHERE id = ?
1475
- `);
1476
- await stmt.bind(
1477
- plugin.version,
1478
- plugin.description,
1479
- JSON.stringify(plugin.permissions),
1480
- JSON.stringify(plugin.settings || {}),
1481
- now,
1482
- plugin.id
1483
- ).run();
1484
- }
1485
- /**
1486
- * Check if bootstrap is needed (first run detection)
1487
- */
1488
- async isBootstrapNeeded() {
1489
- try {
1490
- for (const corePlugin of this.CORE_PLUGINS.filter(
1491
- (p) => p.name.startsWith("core-")
1492
- )) {
1493
- const exists = await this.pluginService.getPlugin(corePlugin.id);
1494
- if (!exists) {
1495
- return true;
1496
- }
1497
- }
1498
- return false;
1499
- } catch (error) {
1500
- console.error(
1501
- "[PluginBootstrap] Error checking bootstrap status:",
1502
- error
1503
- );
1504
- return true;
1505
- }
1506
- }
1507
- };
1508
-
1509
- export { MigrationService, PluginBootstrapService, PluginService, cleanupRemovedCollections, fullCollectionSync, getAvailableCollectionNames, getManagedCollections, isCollectionManaged, loadCollectionConfig, loadCollectionConfigs, registerCollections, syncCollection, syncCollections, validateCollectionConfig };
1510
- //# sourceMappingURL=chunk-COBUPOMD.js.map
1511
- //# sourceMappingURL=chunk-COBUPOMD.js.map