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