@sonicjs-cms/core 2.19.0 → 3.0.0-beta.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (224) hide show
  1. package/README.md +4 -3
  2. package/dist/admin-documents-form.template-KN7JF66Q.cjs +19 -0
  3. package/dist/{admin-layout-catalyst.template-UMTIN66R.js.map → admin-documents-form.template-KN7JF66Q.cjs.map} +1 -1
  4. package/dist/admin-documents-form.template-NLSI6Z42.js +6 -0
  5. package/dist/{admin-layout-catalyst.template-HFD37TY5.cjs.map → admin-documents-form.template-NLSI6Z42.js.map} +1 -1
  6. package/dist/admin-layout-catalyst.template-WHJGSWWD.js +7 -0
  7. package/dist/admin-layout-catalyst.template-WHJGSWWD.js.map +1 -0
  8. package/dist/admin-layout-catalyst.template-ZK5HD545.cjs +17 -0
  9. package/dist/admin-layout-catalyst.template-ZK5HD545.cjs.map +1 -0
  10. package/dist/app-Bo0X1OWX.d.ts +1268 -0
  11. package/dist/app-Do66yCcV.d.cts +1268 -0
  12. package/dist/cache-DDARE4QE.js +4 -0
  13. package/dist/cache-DDARE4QE.js.map +1 -0
  14. package/dist/cache-LVYS4BPL.cjs +33 -0
  15. package/dist/cache-LVYS4BPL.cjs.map +1 -0
  16. package/dist/chunk-2CB4KY7I.cjs +771 -0
  17. package/dist/chunk-2CB4KY7I.cjs.map +1 -0
  18. package/dist/chunk-2JTWQZHG.cjs +276 -0
  19. package/dist/chunk-2JTWQZHG.cjs.map +1 -0
  20. package/dist/{chunk-55RDMDOP.js → chunk-3TB6AT6X.js} +148 -55
  21. package/dist/chunk-3TB6AT6X.js.map +1 -0
  22. package/dist/{chunk-E4YFJBM2.cjs → chunk-673S7EBY.cjs} +621 -829
  23. package/dist/chunk-673S7EBY.cjs.map +1 -0
  24. package/dist/{chunk-ON5ZMSU4.js → chunk-6JQOUUOB.js} +3 -3
  25. package/dist/chunk-6JQOUUOB.js.map +1 -0
  26. package/dist/chunk-7LHUVREV.cjs +158 -0
  27. package/dist/chunk-7LHUVREV.cjs.map +1 -0
  28. package/dist/chunk-AI663NBO.js +821 -0
  29. package/dist/chunk-AI663NBO.js.map +1 -0
  30. package/dist/chunk-BDDABDAB.cjs +1149 -0
  31. package/dist/chunk-BDDABDAB.cjs.map +1 -0
  32. package/dist/chunk-BLMTL57B.js +767 -0
  33. package/dist/chunk-BLMTL57B.js.map +1 -0
  34. package/dist/{chunk-ABB34XUS.cjs → chunk-CHCBHIBM.cjs} +667 -19
  35. package/dist/chunk-CHCBHIBM.cjs.map +1 -0
  36. package/dist/chunk-DNQCEKUK.cjs +327 -0
  37. package/dist/chunk-DNQCEKUK.cjs.map +1 -0
  38. package/dist/chunk-EF2NQUIQ.js +323 -0
  39. package/dist/chunk-EF2NQUIQ.js.map +1 -0
  40. package/dist/chunk-GCDZZNIN.js +192 -0
  41. package/dist/chunk-GCDZZNIN.js.map +1 -0
  42. package/dist/{chunk-XWIA3HVX.js → chunk-HDWE5FRJ.js} +6 -1249
  43. package/dist/chunk-HDWE5FRJ.js.map +1 -0
  44. package/dist/chunk-HIKBY7MS.cjs +70 -0
  45. package/dist/chunk-HIKBY7MS.cjs.map +1 -0
  46. package/dist/chunk-IESEVHXL.js +66 -0
  47. package/dist/chunk-IESEVHXL.js.map +1 -0
  48. package/dist/chunk-IVPRUGTY.js +242 -0
  49. package/dist/chunk-IVPRUGTY.js.map +1 -0
  50. package/dist/{chunk-JZVHLLSI.cjs → chunk-IXUHXTHW.cjs} +2 -151
  51. package/dist/chunk-IXUHXTHW.cjs.map +1 -0
  52. package/dist/{chunk-7A4CB7T3.cjs → chunk-J5DCX3F6.cjs} +509 -91
  53. package/dist/chunk-J5DCX3F6.cjs.map +1 -0
  54. package/dist/chunk-J6JTWD2A.cjs +100 -0
  55. package/dist/chunk-J6JTWD2A.cjs.map +1 -0
  56. package/dist/chunk-JEQ7FLOD.cjs +199 -0
  57. package/dist/chunk-JEQ7FLOD.cjs.map +1 -0
  58. package/dist/chunk-K25XHMM3.js +566 -0
  59. package/dist/chunk-K25XHMM3.js.map +1 -0
  60. package/dist/{chunk-R4FOLLFB.cjs → chunk-LO6MEPRW.cjs} +8730 -11520
  61. package/dist/chunk-LO6MEPRW.cjs.map +1 -0
  62. package/dist/chunk-MHP7HYTT.js +273 -0
  63. package/dist/chunk-MHP7HYTT.js.map +1 -0
  64. package/dist/chunk-MP3Q2W76.js +387 -0
  65. package/dist/chunk-MP3Q2W76.js.map +1 -0
  66. package/dist/{chunk-OHYBNCVL.cjs → chunk-MVIZJOO5.cjs} +10 -1256
  67. package/dist/chunk-MVIZJOO5.cjs.map +1 -0
  68. package/dist/{chunk-UYJ6TJHX.cjs → chunk-NAVPFIG5.cjs} +148 -55
  69. package/dist/chunk-NAVPFIG5.cjs.map +1 -0
  70. package/dist/chunk-NUKJ54GA.cjs +245 -0
  71. package/dist/chunk-NUKJ54GA.cjs.map +1 -0
  72. package/dist/{chunk-BU7SFHGP.js → chunk-QZGABF2M.js} +3 -149
  73. package/dist/chunk-QZGABF2M.js.map +1 -0
  74. package/dist/{chunk-JZV22DEV.js → chunk-RJV6UXLZ.js} +611 -817
  75. package/dist/chunk-RJV6UXLZ.js.map +1 -0
  76. package/dist/chunk-RNZFGN4R.js +88 -0
  77. package/dist/chunk-RNZFGN4R.js.map +1 -0
  78. package/dist/{chunk-TFNTM3OA.js → chunk-SL6XS6YT.js} +645 -15
  79. package/dist/chunk-SL6XS6YT.js.map +1 -0
  80. package/dist/{chunk-OCL3HMEG.js → chunk-SO2T3OXR.js} +7004 -9807
  81. package/dist/chunk-SO2T3OXR.js.map +1 -0
  82. package/dist/chunk-VQHAJUZZ.cjs +408 -0
  83. package/dist/chunk-VQHAJUZZ.cjs.map +1 -0
  84. package/dist/{chunk-4NPCDK6B.js → chunk-VZ3NHR5Z.js} +505 -90
  85. package/dist/chunk-VZ3NHR5Z.js.map +1 -0
  86. package/dist/{chunk-4ZSNJDLS.cjs → chunk-WULONYGB.cjs} +9 -9
  87. package/dist/chunk-WULONYGB.cjs.map +1 -0
  88. package/dist/chunk-XFQHK64T.js +154 -0
  89. package/dist/chunk-XFQHK64T.js.map +1 -0
  90. package/dist/chunk-YA3TJ65D.cjs +575 -0
  91. package/dist/chunk-YA3TJ65D.cjs.map +1 -0
  92. package/dist/chunk-YP7GW2G5.cjs +866 -0
  93. package/dist/chunk-YP7GW2G5.cjs.map +1 -0
  94. package/dist/{chunk-QFWHAFEO.js → chunk-ZEZ245PW.js} +148 -858
  95. package/dist/chunk-ZEZ245PW.js.map +1 -0
  96. package/dist/{collection-config-B4PG-AaF.d.cts → collection-config-JgHOpFCG.d.cts} +30 -2
  97. package/dist/{collection-config-B4PG-AaF.d.ts → collection-config-JgHOpFCG.d.ts} +30 -2
  98. package/dist/config-HFXANXCC.js +6 -0
  99. package/dist/config-HFXANXCC.js.map +1 -0
  100. package/dist/config-ON6FNMYX.cjs +19 -0
  101. package/dist/config-ON6FNMYX.cjs.map +1 -0
  102. package/dist/define-plugin-BzNHc1ZI.d.ts +1321 -0
  103. package/dist/define-plugin-IWDKYaVm.d.cts +1321 -0
  104. package/dist/document-projection-TDWRJX3Z.cjs +13 -0
  105. package/dist/document-projection-TDWRJX3Z.cjs.map +1 -0
  106. package/dist/document-projection-YYMC6I4U.js +4 -0
  107. package/dist/document-projection-YYMC6I4U.js.map +1 -0
  108. package/dist/index.cjs +13734 -4328
  109. package/dist/index.cjs.map +1 -1
  110. package/dist/index.d.cts +329 -492
  111. package/dist/index.d.ts +329 -492
  112. package/dist/index.js +13385 -3998
  113. package/dist/index.js.map +1 -1
  114. package/dist/middleware.cjs +36 -32
  115. package/dist/middleware.d.cts +50 -7
  116. package/dist/middleware.d.ts +50 -7
  117. package/dist/middleware.js +7 -3
  118. package/dist/migrations-DK2YFPLR.js +4 -0
  119. package/dist/{migrations-H5IXZNCO.js.map → migrations-DK2YFPLR.js.map} +1 -1
  120. package/dist/migrations-YHNHTJOO.cjs +13 -0
  121. package/dist/{migrations-566IIPS2.cjs.map → migrations-YHNHTJOO.cjs.map} +1 -1
  122. package/dist/{plugin-bootstrap-DfVerYV4.d.cts → plugin-bootstrap-B8ThJU21.d.cts} +4315 -1661
  123. package/dist/{plugin-bootstrap-P_ciLp_C.d.ts → plugin-bootstrap-qu8hJgUt.d.ts} +4315 -1661
  124. package/dist/plugins.cjs +171 -12
  125. package/dist/plugins.d.cts +36 -2
  126. package/dist/plugins.d.ts +36 -2
  127. package/dist/plugins.js +5 -2
  128. package/dist/rbac-O73MFKDA.js +5 -0
  129. package/dist/rbac-O73MFKDA.js.map +1 -0
  130. package/dist/rbac-VONLJJKB.cjs +14 -0
  131. package/dist/rbac-VONLJJKB.cjs.map +1 -0
  132. package/dist/routes.cjs +41 -45
  133. package/dist/routes.d.cts +56 -146
  134. package/dist/routes.d.ts +56 -146
  135. package/dist/routes.js +17 -9
  136. package/dist/services.cjs +39 -72
  137. package/dist/services.d.cts +79 -54
  138. package/dist/services.d.ts +79 -54
  139. package/dist/services.js +6 -3
  140. package/dist/templates.cjs +17 -29
  141. package/dist/templates.d.cts +1 -66
  142. package/dist/templates.d.ts +1 -66
  143. package/dist/templates.js +3 -3
  144. package/dist/types-Dea1eNxU.d.cts +286 -0
  145. package/dist/types-Dea1eNxU.d.ts +286 -0
  146. package/dist/types.d.cts +1 -1
  147. package/dist/types.d.ts +1 -1
  148. package/dist/utils.cjs +18 -17
  149. package/dist/utils.d.cts +1 -1
  150. package/dist/utils.d.ts +1 -1
  151. package/dist/utils.js +2 -1
  152. package/migrations/0001_core.sql +184 -0
  153. package/migrations/0002_documents.sql +163 -0
  154. package/package.json +12 -7
  155. package/dist/admin-layout-catalyst.template-HFD37TY5.cjs +0 -17
  156. package/dist/admin-layout-catalyst.template-UMTIN66R.js +0 -7
  157. package/dist/app-C9esKLmh.d.cts +0 -112
  158. package/dist/app-C9esKLmh.d.ts +0 -112
  159. package/dist/chunk-4NPCDK6B.js.map +0 -1
  160. package/dist/chunk-4ZSNJDLS.cjs.map +0 -1
  161. package/dist/chunk-55RDMDOP.js.map +0 -1
  162. package/dist/chunk-635JAMSE.cjs +0 -653
  163. package/dist/chunk-635JAMSE.cjs.map +0 -1
  164. package/dist/chunk-7A4CB7T3.cjs.map +0 -1
  165. package/dist/chunk-ABB34XUS.cjs.map +0 -1
  166. package/dist/chunk-BU7SFHGP.js.map +0 -1
  167. package/dist/chunk-E4YFJBM2.cjs.map +0 -1
  168. package/dist/chunk-EXNEW5US.js +0 -648
  169. package/dist/chunk-EXNEW5US.js.map +0 -1
  170. package/dist/chunk-JZV22DEV.js.map +0 -1
  171. package/dist/chunk-JZVHLLSI.cjs.map +0 -1
  172. package/dist/chunk-OCL3HMEG.js.map +0 -1
  173. package/dist/chunk-OHYBNCVL.cjs.map +0 -1
  174. package/dist/chunk-ON5ZMSU4.js.map +0 -1
  175. package/dist/chunk-QFWHAFEO.js.map +0 -1
  176. package/dist/chunk-R4FOLLFB.cjs.map +0 -1
  177. package/dist/chunk-RLMUFFUD.cjs +0 -2219
  178. package/dist/chunk-RLMUFFUD.cjs.map +0 -1
  179. package/dist/chunk-TFNTM3OA.js.map +0 -1
  180. package/dist/chunk-UYJ6TJHX.cjs.map +0 -1
  181. package/dist/chunk-WAEQXGCX.cjs +0 -1898
  182. package/dist/chunk-WAEQXGCX.cjs.map +0 -1
  183. package/dist/chunk-XWIA3HVX.js.map +0 -1
  184. package/dist/chunk-ZYAYUIZE.js +0 -2217
  185. package/dist/chunk-ZYAYUIZE.js.map +0 -1
  186. package/dist/migrations-566IIPS2.cjs +0 -13
  187. package/dist/migrations-H5IXZNCO.js +0 -4
  188. package/dist/plugin-manager-BoM3Q7o7.d.cts +0 -328
  189. package/dist/plugin-manager-Efx9RyDX.d.ts +0 -328
  190. package/migrations/001_initial_schema.sql +0 -170
  191. package/migrations/002_faq_plugin.sql +0 -86
  192. package/migrations/003_stage5_enhancements.sql +0 -121
  193. package/migrations/004_stage6_user_management.sql +0 -183
  194. package/migrations/005_stage7_workflow_automation.sql +0 -294
  195. package/migrations/006_plugin_system.sql +0 -155
  196. package/migrations/007_demo_login_plugin.sql +0 -23
  197. package/migrations/008_fix_slug_validation.sql +0 -22
  198. package/migrations/009_system_logging.sql +0 -57
  199. package/migrations/011_config_managed_collections.sql +0 -15
  200. package/migrations/012_testimonials_plugin.sql +0 -80
  201. package/migrations/013_code_examples_plugin.sql +0 -177
  202. package/migrations/014_fix_plugin_registry.sql +0 -88
  203. package/migrations/015_add_remaining_plugins.sql +0 -89
  204. package/migrations/016_remove_duplicate_cache_plugin.sql +0 -17
  205. package/migrations/017_auth_configurable_fields.sql +0 -49
  206. package/migrations/018_settings_table.sql +0 -23
  207. package/migrations/019_remove_blog_posts_collection.sql +0 -15
  208. package/migrations/020_add_email_plugin.sql +0 -22
  209. package/migrations/021_add_magic_link_auth_plugin.sql +0 -42
  210. package/migrations/022_add_tinymce_plugin.sql +0 -25
  211. package/migrations/023_add_easy_mdx_plugin.sql +0 -25
  212. package/migrations/024_add_quill_editor_plugin.sql +0 -25
  213. package/migrations/025_add_easymde_plugin.sql +0 -25
  214. package/migrations/026_add_otp_login.sql +0 -42
  215. package/migrations/027_fix_slug_field_type.sql +0 -18
  216. package/migrations/028_fix_slug_field_type_in_schemas.sql +0 -30
  217. package/migrations/029_add_forms_system.sql +0 -184
  218. package/migrations/030_add_turnstile_to_forms.sql +0 -14
  219. package/migrations/031_ai_search_plugin.sql +0 -45
  220. package/migrations/032_user_profiles.sql +0 -37
  221. package/migrations/033_form_content_integration.sql +0 -19
  222. package/migrations/034_security_audit_plugin.sql +0 -27
  223. package/migrations/035_user_profiles_data_column.sql +0 -16
  224. package/migrations/036_analytics_events.sql +0 -22
@@ -1,1898 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkP3XDZL6Q_cjs = require('./chunk-P3XDZL6Q.cjs');
4
- var chunkIGJUBJBW_cjs = require('./chunk-IGJUBJBW.cjs');
5
- var sqliteCore = require('drizzle-orm/sqlite-core');
6
- var v4 = require('zod/v4');
7
- var drizzleOrm = require('drizzle-orm');
8
- var d1 = require('drizzle-orm/d1');
9
- var dev = require('hono/dev');
10
-
11
- // src/db/schema.ts
12
- var schema_exports = {};
13
- chunkIGJUBJBW_cjs.__export(schema_exports, {
14
- apiTokens: () => apiTokens,
15
- collections: () => collections,
16
- content: () => content,
17
- contentVersions: () => contentVersions,
18
- formFiles: () => formFiles,
19
- formSubmissions: () => formSubmissions,
20
- forms: () => forms,
21
- insertCollectionSchema: () => insertCollectionSchema,
22
- insertContentSchema: () => insertContentSchema,
23
- insertFormFileSchema: () => insertFormFileSchema,
24
- insertFormSchema: () => insertFormSchema,
25
- insertFormSubmissionSchema: () => insertFormSubmissionSchema,
26
- insertLogConfigSchema: () => insertLogConfigSchema,
27
- insertMediaSchema: () => insertMediaSchema,
28
- insertPluginActivityLogSchema: () => insertPluginActivityLogSchema,
29
- insertPluginAssetSchema: () => insertPluginAssetSchema,
30
- insertPluginHookSchema: () => insertPluginHookSchema,
31
- insertPluginRouteSchema: () => insertPluginRouteSchema,
32
- insertPluginSchema: () => insertPluginSchema,
33
- insertSecurityEventSchema: () => insertSecurityEventSchema,
34
- insertSystemLogSchema: () => insertSystemLogSchema,
35
- insertUserSchema: () => insertUserSchema,
36
- insertWorkflowHistorySchema: () => insertWorkflowHistorySchema,
37
- logConfig: () => logConfig,
38
- media: () => media,
39
- pluginActivityLog: () => pluginActivityLog,
40
- pluginAssets: () => pluginAssets,
41
- pluginHooks: () => pluginHooks,
42
- pluginRoutes: () => pluginRoutes,
43
- plugins: () => plugins,
44
- securityEvents: () => securityEvents,
45
- selectCollectionSchema: () => selectCollectionSchema,
46
- selectContentSchema: () => selectContentSchema,
47
- selectFormFileSchema: () => selectFormFileSchema,
48
- selectFormSchema: () => selectFormSchema,
49
- selectFormSubmissionSchema: () => selectFormSubmissionSchema,
50
- selectLogConfigSchema: () => selectLogConfigSchema,
51
- selectMediaSchema: () => selectMediaSchema,
52
- selectPluginActivityLogSchema: () => selectPluginActivityLogSchema,
53
- selectPluginAssetSchema: () => selectPluginAssetSchema,
54
- selectPluginHookSchema: () => selectPluginHookSchema,
55
- selectPluginRouteSchema: () => selectPluginRouteSchema,
56
- selectPluginSchema: () => selectPluginSchema,
57
- selectSecurityEventSchema: () => selectSecurityEventSchema,
58
- selectSystemLogSchema: () => selectSystemLogSchema,
59
- selectUserSchema: () => selectUserSchema,
60
- selectWorkflowHistorySchema: () => selectWorkflowHistorySchema,
61
- systemLogs: () => systemLogs,
62
- users: () => users,
63
- workflowHistory: () => workflowHistory
64
- });
65
- var CONSTANTS = {
66
- INT8_MIN: -128,
67
- INT8_MAX: 127,
68
- INT8_UNSIGNED_MAX: 255,
69
- INT16_MIN: -32768,
70
- INT16_MAX: 32767,
71
- INT16_UNSIGNED_MAX: 65535,
72
- INT24_MIN: -8388608,
73
- INT24_MAX: 8388607,
74
- INT24_UNSIGNED_MAX: 16777215,
75
- INT32_MIN: -2147483648,
76
- INT32_MAX: 2147483647,
77
- INT32_UNSIGNED_MAX: 4294967295,
78
- INT48_MIN: -140737488355328,
79
- INT48_MAX: 140737488355327,
80
- INT48_UNSIGNED_MAX: 281474976710655,
81
- INT64_MIN: -9223372036854775808n,
82
- INT64_MAX: 9223372036854775807n,
83
- INT64_UNSIGNED_MAX: 18446744073709551615n
84
- };
85
- function isColumnType(column, columnTypes) {
86
- return columnTypes.includes(column.columnType);
87
- }
88
- function isWithEnum(column) {
89
- return "enumValues" in column && Array.isArray(column.enumValues) && column.enumValues.length > 0;
90
- }
91
- var isPgEnum = isWithEnum;
92
- var literalSchema = v4.z.union([v4.z.string(), v4.z.number(), v4.z.boolean(), v4.z.null()]);
93
- var jsonSchema = v4.z.union([
94
- literalSchema,
95
- v4.z.record(v4.z.string(), v4.z.any()),
96
- v4.z.array(v4.z.any())
97
- ]);
98
- var bufferSchema = v4.z.custom((v) => v instanceof Buffer);
99
- function columnToSchema(column, factory) {
100
- const z$1 = v4.z;
101
- const coerce = {};
102
- let schema;
103
- if (isWithEnum(column)) {
104
- schema = column.enumValues.length ? z$1.enum(column.enumValues) : z$1.string();
105
- }
106
- if (!schema) {
107
- if (isColumnType(column, ["PgGeometry", "PgPointTuple"])) {
108
- schema = z$1.tuple([z$1.number(), z$1.number()]);
109
- } else if (isColumnType(column, ["PgGeometryObject", "PgPointObject"])) {
110
- schema = z$1.object({ x: z$1.number(), y: z$1.number() });
111
- } else if (isColumnType(column, ["PgHalfVector", "PgVector"])) {
112
- schema = z$1.array(z$1.number());
113
- schema = column.dimensions ? schema.length(column.dimensions) : schema;
114
- } else if (isColumnType(column, ["PgLine"])) {
115
- schema = z$1.tuple([z$1.number(), z$1.number(), z$1.number()]);
116
- } else if (isColumnType(column, ["PgLineABC"])) {
117
- schema = z$1.object({
118
- a: z$1.number(),
119
- b: z$1.number(),
120
- c: z$1.number()
121
- });
122
- } else if (isColumnType(column, ["PgArray"])) {
123
- schema = z$1.array(columnToSchema(column.baseColumn));
124
- schema = column.size ? schema.length(column.size) : schema;
125
- } else if (column.dataType === "array") {
126
- schema = z$1.array(z$1.any());
127
- } else if (column.dataType === "number") {
128
- schema = numberColumnToSchema(column, z$1, coerce);
129
- } else if (column.dataType === "bigint") {
130
- schema = bigintColumnToSchema(column, z$1, coerce);
131
- } else if (column.dataType === "boolean") {
132
- schema = coerce === true || coerce.boolean ? z$1.coerce.boolean() : z$1.boolean();
133
- } else if (column.dataType === "date") {
134
- schema = coerce === true || coerce.date ? z$1.coerce.date() : z$1.date();
135
- } else if (column.dataType === "string") {
136
- schema = stringColumnToSchema(column, z$1, coerce);
137
- } else if (column.dataType === "json") {
138
- schema = jsonSchema;
139
- } else if (column.dataType === "custom") {
140
- schema = z$1.any();
141
- } else if (column.dataType === "buffer") {
142
- schema = bufferSchema;
143
- }
144
- }
145
- if (!schema) {
146
- schema = z$1.any();
147
- }
148
- return schema;
149
- }
150
- function numberColumnToSchema(column, z2, coerce) {
151
- let unsigned = column.getSQLType().includes("unsigned");
152
- let min;
153
- let max;
154
- let integer2 = false;
155
- if (isColumnType(column, ["MySqlTinyInt", "SingleStoreTinyInt"])) {
156
- min = unsigned ? 0 : CONSTANTS.INT8_MIN;
157
- max = unsigned ? CONSTANTS.INT8_UNSIGNED_MAX : CONSTANTS.INT8_MAX;
158
- integer2 = true;
159
- } else if (isColumnType(column, [
160
- "PgSmallInt",
161
- "PgSmallSerial",
162
- "MySqlSmallInt",
163
- "SingleStoreSmallInt"
164
- ])) {
165
- min = unsigned ? 0 : CONSTANTS.INT16_MIN;
166
- max = unsigned ? CONSTANTS.INT16_UNSIGNED_MAX : CONSTANTS.INT16_MAX;
167
- integer2 = true;
168
- } else if (isColumnType(column, [
169
- "PgReal",
170
- "MySqlFloat",
171
- "MySqlMediumInt",
172
- "SingleStoreMediumInt",
173
- "SingleStoreFloat"
174
- ])) {
175
- min = unsigned ? 0 : CONSTANTS.INT24_MIN;
176
- max = unsigned ? CONSTANTS.INT24_UNSIGNED_MAX : CONSTANTS.INT24_MAX;
177
- integer2 = isColumnType(column, ["MySqlMediumInt", "SingleStoreMediumInt"]);
178
- } else if (isColumnType(column, [
179
- "PgInteger",
180
- "PgSerial",
181
- "MySqlInt",
182
- "SingleStoreInt"
183
- ])) {
184
- min = unsigned ? 0 : CONSTANTS.INT32_MIN;
185
- max = unsigned ? CONSTANTS.INT32_UNSIGNED_MAX : CONSTANTS.INT32_MAX;
186
- integer2 = true;
187
- } else if (isColumnType(column, [
188
- "PgDoublePrecision",
189
- "MySqlReal",
190
- "MySqlDouble",
191
- "SingleStoreReal",
192
- "SingleStoreDouble",
193
- "SQLiteReal"
194
- ])) {
195
- min = unsigned ? 0 : CONSTANTS.INT48_MIN;
196
- max = unsigned ? CONSTANTS.INT48_UNSIGNED_MAX : CONSTANTS.INT48_MAX;
197
- } else if (isColumnType(column, [
198
- "PgBigInt53",
199
- "PgBigSerial53",
200
- "MySqlBigInt53",
201
- "MySqlSerial",
202
- "SingleStoreBigInt53",
203
- "SingleStoreSerial",
204
- "SQLiteInteger"
205
- ])) {
206
- unsigned = unsigned || isColumnType(column, ["MySqlSerial", "SingleStoreSerial"]);
207
- min = unsigned ? 0 : Number.MIN_SAFE_INTEGER;
208
- max = Number.MAX_SAFE_INTEGER;
209
- integer2 = true;
210
- } else if (isColumnType(column, ["MySqlYear", "SingleStoreYear"])) {
211
- min = 1901;
212
- max = 2155;
213
- integer2 = true;
214
- } else {
215
- min = Number.MIN_SAFE_INTEGER;
216
- max = Number.MAX_SAFE_INTEGER;
217
- }
218
- let schema = coerce === true || coerce?.number ? integer2 ? z2.coerce.number() : z2.coerce.number().int() : integer2 ? z2.int() : z2.number();
219
- schema = schema.gte(min).lte(max);
220
- return schema;
221
- }
222
- function bigintColumnToSchema(column, z2, coerce) {
223
- const unsigned = column.getSQLType().includes("unsigned");
224
- const min = unsigned ? 0n : CONSTANTS.INT64_MIN;
225
- const max = unsigned ? CONSTANTS.INT64_UNSIGNED_MAX : CONSTANTS.INT64_MAX;
226
- const schema = coerce === true || coerce?.bigint ? z2.coerce.bigint() : z2.bigint();
227
- return schema.gte(min).lte(max);
228
- }
229
- function stringColumnToSchema(column, z2, coerce) {
230
- if (isColumnType(column, ["PgUUID"])) {
231
- return z2.uuid();
232
- }
233
- let max;
234
- let regex;
235
- let fixed = false;
236
- if (isColumnType(column, ["PgVarchar", "SQLiteText"])) {
237
- max = column.length;
238
- } else if (isColumnType(column, ["MySqlVarChar", "SingleStoreVarChar"])) {
239
- max = column.length ?? CONSTANTS.INT16_UNSIGNED_MAX;
240
- } else if (isColumnType(column, ["MySqlText", "SingleStoreText"])) {
241
- if (column.textType === "longtext") {
242
- max = CONSTANTS.INT32_UNSIGNED_MAX;
243
- } else if (column.textType === "mediumtext") {
244
- max = CONSTANTS.INT24_UNSIGNED_MAX;
245
- } else if (column.textType === "text") {
246
- max = CONSTANTS.INT16_UNSIGNED_MAX;
247
- } else {
248
- max = CONSTANTS.INT8_UNSIGNED_MAX;
249
- }
250
- }
251
- if (isColumnType(column, [
252
- "PgChar",
253
- "MySqlChar",
254
- "SingleStoreChar"
255
- ])) {
256
- max = column.length;
257
- fixed = true;
258
- }
259
- if (isColumnType(column, ["PgBinaryVector"])) {
260
- regex = /^[01]+$/;
261
- max = column.dimensions;
262
- }
263
- let schema = coerce === true || coerce?.string ? z2.coerce.string() : z2.string();
264
- schema = regex ? schema.regex(regex) : schema;
265
- return max && fixed ? schema.length(max) : max ? schema.max(max) : schema;
266
- }
267
- function getColumns(tableLike) {
268
- return drizzleOrm.isTable(tableLike) ? drizzleOrm.getTableColumns(tableLike) : drizzleOrm.getViewSelectedFields(tableLike);
269
- }
270
- function handleColumns(columns, refinements, conditions, factory) {
271
- const columnSchemas = {};
272
- for (const [key, selected] of Object.entries(columns)) {
273
- if (!drizzleOrm.is(selected, drizzleOrm.Column) && !drizzleOrm.is(selected, drizzleOrm.SQL) && !drizzleOrm.is(selected, drizzleOrm.SQL.Aliased) && typeof selected === "object") {
274
- const columns2 = drizzleOrm.isTable(selected) || drizzleOrm.isView(selected) ? getColumns(selected) : selected;
275
- columnSchemas[key] = handleColumns(columns2, refinements[key] ?? {}, conditions);
276
- continue;
277
- }
278
- const refinement = refinements[key];
279
- if (refinement !== void 0 && typeof refinement !== "function") {
280
- columnSchemas[key] = refinement;
281
- continue;
282
- }
283
- const column = drizzleOrm.is(selected, drizzleOrm.Column) ? selected : void 0;
284
- const schema = column ? columnToSchema(column) : v4.z.any();
285
- const refined = typeof refinement === "function" ? refinement(schema) : schema;
286
- if (conditions.never(column)) {
287
- continue;
288
- } else {
289
- columnSchemas[key] = refined;
290
- }
291
- if (column) {
292
- if (conditions.nullable(column)) {
293
- columnSchemas[key] = columnSchemas[key].nullable();
294
- }
295
- if (conditions.optional(column)) {
296
- columnSchemas[key] = columnSchemas[key].optional();
297
- }
298
- }
299
- }
300
- return v4.z.object(columnSchemas);
301
- }
302
- function handleEnum(enum_, factory) {
303
- const zod = v4.z;
304
- return zod.enum(enum_.enumValues);
305
- }
306
- var selectConditions = {
307
- never: () => false,
308
- optional: () => false,
309
- nullable: (column) => !column.notNull
310
- };
311
- var insertConditions = {
312
- never: (column) => column?.generated?.type === "always" || column?.generatedIdentity?.type === "always",
313
- optional: (column) => !column.notNull || column.notNull && column.hasDefault,
314
- nullable: (column) => !column.notNull
315
- };
316
- var createSelectSchema = (entity, refine) => {
317
- if (isPgEnum(entity)) {
318
- return handleEnum(entity);
319
- }
320
- const columns = getColumns(entity);
321
- return handleColumns(columns, {}, selectConditions);
322
- };
323
- var createInsertSchema = (entity, refine) => {
324
- const columns = getColumns(entity);
325
- return handleColumns(columns, refine ?? {}, insertConditions);
326
- };
327
-
328
- // src/db/schema.ts
329
- var users = sqliteCore.sqliteTable("users", {
330
- id: sqliteCore.text("id").primaryKey(),
331
- email: sqliteCore.text("email").notNull().unique(),
332
- username: sqliteCore.text("username").notNull().unique(),
333
- firstName: sqliteCore.text("first_name").notNull(),
334
- lastName: sqliteCore.text("last_name").notNull(),
335
- passwordHash: sqliteCore.text("password_hash"),
336
- // Hashed password, nullable for OAuth users
337
- role: sqliteCore.text("role").notNull().default("viewer"),
338
- // 'admin', 'editor', 'author', 'viewer'
339
- avatar: sqliteCore.text("avatar"),
340
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
341
- lastLoginAt: sqliteCore.integer("last_login_at"),
342
- createdAt: sqliteCore.integer("created_at").notNull(),
343
- updatedAt: sqliteCore.integer("updated_at").notNull()
344
- });
345
- var collections = sqliteCore.sqliteTable("collections", {
346
- id: sqliteCore.text("id").primaryKey(),
347
- name: sqliteCore.text("name").notNull().unique(),
348
- displayName: sqliteCore.text("display_name").notNull(),
349
- description: sqliteCore.text("description"),
350
- schema: sqliteCore.text("schema", { mode: "json" }).notNull(),
351
- // JSON schema definition
352
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
353
- managed: sqliteCore.integer("managed", { mode: "boolean" }).notNull().default(false),
354
- // Config-managed collections cannot be edited in UI
355
- sourceType: sqliteCore.text("source_type").default("user"),
356
- // 'user' (normal), 'form' (form-derived)
357
- sourceId: sqliteCore.text("source_id"),
358
- // stores the form ID for form-derived collections
359
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
360
- updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
361
- });
362
- var content = sqliteCore.sqliteTable("content", {
363
- id: sqliteCore.text("id").primaryKey(),
364
- collectionId: sqliteCore.text("collection_id").notNull().references(() => collections.id),
365
- slug: sqliteCore.text("slug").notNull(),
366
- title: sqliteCore.text("title").notNull(),
367
- data: sqliteCore.text("data", { mode: "json" }).notNull(),
368
- // JSON content data
369
- status: sqliteCore.text("status").notNull().default("draft"),
370
- // 'draft', 'published', 'archived'
371
- publishedAt: sqliteCore.integer("published_at", { mode: "timestamp" }),
372
- authorId: sqliteCore.text("author_id").notNull().references(() => users.id),
373
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
374
- updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
375
- });
376
- var contentVersions = sqliteCore.sqliteTable("content_versions", {
377
- id: sqliteCore.text("id").primaryKey(),
378
- contentId: sqliteCore.text("content_id").notNull().references(() => content.id),
379
- version: sqliteCore.integer("version").notNull(),
380
- data: sqliteCore.text("data", { mode: "json" }).notNull(),
381
- authorId: sqliteCore.text("author_id").notNull().references(() => users.id),
382
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
383
- });
384
- var media = sqliteCore.sqliteTable("media", {
385
- id: sqliteCore.text("id").primaryKey(),
386
- filename: sqliteCore.text("filename").notNull(),
387
- originalName: sqliteCore.text("original_name").notNull(),
388
- mimeType: sqliteCore.text("mime_type").notNull(),
389
- size: sqliteCore.integer("size").notNull(),
390
- width: sqliteCore.integer("width"),
391
- height: sqliteCore.integer("height"),
392
- folder: sqliteCore.text("folder").notNull().default("uploads"),
393
- r2Key: sqliteCore.text("r2_key").notNull(),
394
- // R2 storage key
395
- publicUrl: sqliteCore.text("public_url").notNull(),
396
- // CDN URL
397
- thumbnailUrl: sqliteCore.text("thumbnail_url"),
398
- alt: sqliteCore.text("alt"),
399
- caption: sqliteCore.text("caption"),
400
- tags: sqliteCore.text("tags", { mode: "json" }),
401
- // JSON array of tags
402
- uploadedBy: sqliteCore.text("uploaded_by").notNull().references(() => users.id),
403
- uploadedAt: sqliteCore.integer("uploaded_at").notNull(),
404
- updatedAt: sqliteCore.integer("updated_at"),
405
- publishedAt: sqliteCore.integer("published_at"),
406
- scheduledAt: sqliteCore.integer("scheduled_at"),
407
- archivedAt: sqliteCore.integer("archived_at"),
408
- deletedAt: sqliteCore.integer("deleted_at")
409
- });
410
- var apiTokens = sqliteCore.sqliteTable("api_tokens", {
411
- id: sqliteCore.text("id").primaryKey(),
412
- name: sqliteCore.text("name").notNull(),
413
- token: sqliteCore.text("token").notNull().unique(),
414
- userId: sqliteCore.text("user_id").notNull().references(() => users.id),
415
- permissions: sqliteCore.text("permissions", { mode: "json" }).notNull(),
416
- // Array of permissions
417
- expiresAt: sqliteCore.integer("expires_at", { mode: "timestamp" }),
418
- lastUsedAt: sqliteCore.integer("last_used_at", { mode: "timestamp" }),
419
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
420
- });
421
- var workflowHistory = sqliteCore.sqliteTable("workflow_history", {
422
- id: sqliteCore.text("id").primaryKey(),
423
- contentId: sqliteCore.text("content_id").notNull().references(() => content.id),
424
- action: sqliteCore.text("action").notNull(),
425
- fromStatus: sqliteCore.text("from_status").notNull(),
426
- toStatus: sqliteCore.text("to_status").notNull(),
427
- userId: sqliteCore.text("user_id").notNull().references(() => users.id),
428
- comment: sqliteCore.text("comment"),
429
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
430
- });
431
- var plugins = sqliteCore.sqliteTable("plugins", {
432
- id: sqliteCore.text("id").primaryKey(),
433
- name: sqliteCore.text("name").notNull().unique(),
434
- displayName: sqliteCore.text("display_name").notNull(),
435
- description: sqliteCore.text("description"),
436
- version: sqliteCore.text("version").notNull(),
437
- author: sqliteCore.text("author").notNull(),
438
- category: sqliteCore.text("category").notNull(),
439
- icon: sqliteCore.text("icon"),
440
- status: sqliteCore.text("status").notNull().default("inactive"),
441
- // 'active', 'inactive', 'error'
442
- isCore: sqliteCore.integer("is_core", { mode: "boolean" }).notNull().default(false),
443
- settings: sqliteCore.text("settings", { mode: "json" }),
444
- permissions: sqliteCore.text("permissions", { mode: "json" }),
445
- dependencies: sqliteCore.text("dependencies", { mode: "json" }),
446
- downloadCount: sqliteCore.integer("download_count").notNull().default(0),
447
- rating: sqliteCore.integer("rating").notNull().default(0),
448
- installedAt: sqliteCore.integer("installed_at").notNull(),
449
- activatedAt: sqliteCore.integer("activated_at"),
450
- lastUpdated: sqliteCore.integer("last_updated").notNull(),
451
- errorMessage: sqliteCore.text("error_message"),
452
- createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3)),
453
- updatedAt: sqliteCore.integer("updated_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
454
- });
455
- var pluginHooks = sqliteCore.sqliteTable("plugin_hooks", {
456
- id: sqliteCore.text("id").primaryKey(),
457
- pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id),
458
- hookName: sqliteCore.text("hook_name").notNull(),
459
- handlerName: sqliteCore.text("handler_name").notNull(),
460
- priority: sqliteCore.integer("priority").notNull().default(10),
461
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
462
- createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
463
- });
464
- var pluginRoutes = sqliteCore.sqliteTable("plugin_routes", {
465
- id: sqliteCore.text("id").primaryKey(),
466
- pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id),
467
- path: sqliteCore.text("path").notNull(),
468
- method: sqliteCore.text("method").notNull(),
469
- handlerName: sqliteCore.text("handler_name").notNull(),
470
- middleware: sqliteCore.text("middleware", { mode: "json" }),
471
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
472
- createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
473
- });
474
- var pluginAssets = sqliteCore.sqliteTable("plugin_assets", {
475
- id: sqliteCore.text("id").primaryKey(),
476
- pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id),
477
- assetType: sqliteCore.text("asset_type").notNull(),
478
- // 'css', 'js', 'image', 'font'
479
- assetPath: sqliteCore.text("asset_path").notNull(),
480
- loadOrder: sqliteCore.integer("load_order").notNull().default(100),
481
- loadLocation: sqliteCore.text("load_location").notNull().default("footer"),
482
- // 'header', 'footer'
483
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
484
- createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
485
- });
486
- var pluginActivityLog = sqliteCore.sqliteTable("plugin_activity_log", {
487
- id: sqliteCore.text("id").primaryKey(),
488
- pluginId: sqliteCore.text("plugin_id").notNull().references(() => plugins.id),
489
- action: sqliteCore.text("action").notNull(),
490
- userId: sqliteCore.text("user_id"),
491
- details: sqliteCore.text("details", { mode: "json" }),
492
- timestamp: sqliteCore.integer("timestamp").notNull().$defaultFn(() => Math.floor(Date.now() / 1e3))
493
- });
494
- var insertUserSchema = createInsertSchema(users, {
495
- email: (schema) => schema.email(),
496
- firstName: (schema) => schema.min(1),
497
- lastName: (schema) => schema.min(1),
498
- username: (schema) => schema.min(3)
499
- });
500
- var selectUserSchema = createSelectSchema(users);
501
- var insertCollectionSchema = createInsertSchema(collections, {
502
- name: (schema) => schema.min(1).regex(/^[a-z0-9_]+$/, "Collection name must be lowercase with underscores"),
503
- displayName: (schema) => schema.min(1)
504
- });
505
- var selectCollectionSchema = createSelectSchema(collections);
506
- var insertContentSchema = createInsertSchema(content, {
507
- slug: (schema) => schema.min(1).regex(/^[a-zA-Z0-9_-]+$/, "Slug must contain only letters, numbers, underscores, and hyphens"),
508
- title: (schema) => schema.min(1),
509
- status: (schema) => schema
510
- });
511
- var selectContentSchema = createSelectSchema(content);
512
- var insertMediaSchema = createInsertSchema(media, {
513
- filename: (schema) => schema.min(1),
514
- originalName: (schema) => schema.min(1),
515
- mimeType: (schema) => schema.min(1),
516
- size: (schema) => schema.positive(),
517
- r2Key: (schema) => schema.min(1),
518
- publicUrl: (schema) => schema.url(),
519
- folder: (schema) => schema.min(1)
520
- });
521
- var selectMediaSchema = createSelectSchema(media);
522
- var insertWorkflowHistorySchema = createInsertSchema(workflowHistory, {
523
- action: (schema) => schema.min(1),
524
- fromStatus: (schema) => schema.min(1),
525
- toStatus: (schema) => schema.min(1)
526
- });
527
- var selectWorkflowHistorySchema = createSelectSchema(workflowHistory);
528
- var insertPluginSchema = createInsertSchema(plugins, {
529
- name: (schema) => schema.min(1),
530
- displayName: (schema) => schema.min(1),
531
- version: (schema) => schema.min(1),
532
- author: (schema) => schema.min(1),
533
- category: (schema) => schema.min(1)
534
- });
535
- var selectPluginSchema = createSelectSchema(plugins);
536
- var insertPluginHookSchema = createInsertSchema(pluginHooks, {
537
- hookName: (schema) => schema.min(1),
538
- handlerName: (schema) => schema.min(1)
539
- });
540
- var selectPluginHookSchema = createSelectSchema(pluginHooks);
541
- var insertPluginRouteSchema = createInsertSchema(pluginRoutes, {
542
- path: (schema) => schema.min(1),
543
- method: (schema) => schema.min(1),
544
- handlerName: (schema) => schema.min(1)
545
- });
546
- var selectPluginRouteSchema = createSelectSchema(pluginRoutes);
547
- var insertPluginAssetSchema = createInsertSchema(pluginAssets, {
548
- assetType: (schema) => schema.min(1),
549
- assetPath: (schema) => schema.min(1)
550
- });
551
- var selectPluginAssetSchema = createSelectSchema(pluginAssets);
552
- var insertPluginActivityLogSchema = createInsertSchema(pluginActivityLog, {
553
- action: (schema) => schema.min(1)
554
- });
555
- var selectPluginActivityLogSchema = createSelectSchema(pluginActivityLog);
556
- var systemLogs = sqliteCore.sqliteTable("system_logs", {
557
- id: sqliteCore.text("id").primaryKey(),
558
- level: sqliteCore.text("level").notNull(),
559
- // 'debug', 'info', 'warn', 'error', 'fatal'
560
- category: sqliteCore.text("category").notNull(),
561
- // 'auth', 'api', 'workflow', 'plugin', 'media', 'system', etc.
562
- message: sqliteCore.text("message").notNull(),
563
- data: sqliteCore.text("data", { mode: "json" }),
564
- // Additional structured data
565
- userId: sqliteCore.text("user_id").references(() => users.id),
566
- sessionId: sqliteCore.text("session_id"),
567
- requestId: sqliteCore.text("request_id"),
568
- ipAddress: sqliteCore.text("ip_address"),
569
- userAgent: sqliteCore.text("user_agent"),
570
- method: sqliteCore.text("method"),
571
- // HTTP method for API logs
572
- url: sqliteCore.text("url"),
573
- // Request URL for API logs
574
- statusCode: sqliteCore.integer("status_code"),
575
- // HTTP status code for API logs
576
- duration: sqliteCore.integer("duration"),
577
- // Request duration in milliseconds
578
- stackTrace: sqliteCore.text("stack_trace"),
579
- // Error stack trace for error logs
580
- tags: sqliteCore.text("tags", { mode: "json" }),
581
- // Array of tags for categorization
582
- source: sqliteCore.text("source"),
583
- // Source component/module that generated the log
584
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
585
- });
586
- var logConfig = sqliteCore.sqliteTable("log_config", {
587
- id: sqliteCore.text("id").primaryKey(),
588
- category: sqliteCore.text("category").notNull().unique(),
589
- enabled: sqliteCore.integer("enabled", { mode: "boolean" }).notNull().default(true),
590
- level: sqliteCore.text("level").notNull().default("info"),
591
- // minimum log level to store
592
- retention: sqliteCore.integer("retention").notNull().default(30),
593
- // days to keep logs
594
- maxSize: sqliteCore.integer("max_size").default(1e4),
595
- // max number of logs per category
596
- createdAt: sqliteCore.integer("created_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date()),
597
- updatedAt: sqliteCore.integer("updated_at", { mode: "timestamp" }).notNull().$defaultFn(() => /* @__PURE__ */ new Date())
598
- });
599
- var insertSystemLogSchema = createInsertSchema(systemLogs, {
600
- level: (schema) => schema.min(1),
601
- category: (schema) => schema.min(1),
602
- message: (schema) => schema.min(1)
603
- });
604
- var selectSystemLogSchema = createSelectSchema(systemLogs);
605
- var insertLogConfigSchema = createInsertSchema(logConfig, {
606
- category: (schema) => schema.min(1),
607
- level: (schema) => schema.min(1)
608
- });
609
- var selectLogConfigSchema = createSelectSchema(logConfig);
610
- var securityEvents = sqliteCore.sqliteTable("security_events", {
611
- id: sqliteCore.text("id").primaryKey(),
612
- eventType: sqliteCore.text("event_type").notNull(),
613
- severity: sqliteCore.text("severity").notNull().default("info"),
614
- userId: sqliteCore.text("user_id"),
615
- email: sqliteCore.text("email"),
616
- ipAddress: sqliteCore.text("ip_address"),
617
- userAgent: sqliteCore.text("user_agent"),
618
- countryCode: sqliteCore.text("country_code"),
619
- requestPath: sqliteCore.text("request_path"),
620
- requestMethod: sqliteCore.text("request_method"),
621
- details: sqliteCore.text("details", { mode: "json" }),
622
- fingerprint: sqliteCore.text("fingerprint"),
623
- blocked: sqliteCore.integer("blocked").notNull().default(0),
624
- createdAt: sqliteCore.integer("created_at").notNull().$defaultFn(() => Date.now())
625
- });
626
- var insertSecurityEventSchema = createInsertSchema(securityEvents, {
627
- eventType: (schema) => schema.min(1),
628
- severity: (schema) => schema.min(1)
629
- });
630
- var selectSecurityEventSchema = createSelectSchema(securityEvents);
631
- var forms = sqliteCore.sqliteTable("forms", {
632
- id: sqliteCore.text("id").primaryKey(),
633
- name: sqliteCore.text("name").notNull().unique(),
634
- // Machine name (e.g., "contact-form")
635
- displayName: sqliteCore.text("display_name").notNull(),
636
- // Human name (e.g., "Contact Form")
637
- description: sqliteCore.text("description"),
638
- category: sqliteCore.text("category").notNull().default("general"),
639
- // contact, survey, registration, etc.
640
- // Form.io schema (JSON)
641
- formioSchema: sqliteCore.text("formio_schema", { mode: "json" }).notNull(),
642
- // Complete Form.io JSON schema
643
- // Settings (JSON)
644
- settings: sqliteCore.text("settings", { mode: "json" }),
645
- // emailNotifications, successMessage, etc.
646
- // Status & Management
647
- isActive: sqliteCore.integer("is_active", { mode: "boolean" }).notNull().default(true),
648
- isPublic: sqliteCore.integer("is_public", { mode: "boolean" }).notNull().default(true),
649
- managed: sqliteCore.integer("managed", { mode: "boolean" }).notNull().default(false),
650
- // Metadata
651
- icon: sqliteCore.text("icon"),
652
- color: sqliteCore.text("color"),
653
- tags: sqliteCore.text("tags", { mode: "json" }),
654
- // JSON array
655
- // Stats
656
- submissionCount: sqliteCore.integer("submission_count").notNull().default(0),
657
- viewCount: sqliteCore.integer("view_count").notNull().default(0),
658
- // Ownership
659
- createdBy: sqliteCore.text("created_by").references(() => users.id),
660
- updatedBy: sqliteCore.text("updated_by").references(() => users.id),
661
- // Timestamps
662
- createdAt: sqliteCore.integer("created_at").notNull(),
663
- updatedAt: sqliteCore.integer("updated_at").notNull()
664
- });
665
- var formSubmissions = sqliteCore.sqliteTable("form_submissions", {
666
- id: sqliteCore.text("id").primaryKey(),
667
- formId: sqliteCore.text("form_id").notNull().references(() => forms.id, { onDelete: "cascade" }),
668
- // Submission data
669
- submissionData: sqliteCore.text("submission_data", { mode: "json" }).notNull(),
670
- // The actual form data
671
- // Submission metadata
672
- status: sqliteCore.text("status").notNull().default("pending"),
673
- // pending, reviewed, approved, rejected, spam
674
- submissionNumber: sqliteCore.integer("submission_number"),
675
- // User information
676
- userId: sqliteCore.text("user_id").references(() => users.id),
677
- userEmail: sqliteCore.text("user_email"),
678
- // Tracking
679
- ipAddress: sqliteCore.text("ip_address"),
680
- userAgent: sqliteCore.text("user_agent"),
681
- referrer: sqliteCore.text("referrer"),
682
- utmSource: sqliteCore.text("utm_source"),
683
- utmMedium: sqliteCore.text("utm_medium"),
684
- utmCampaign: sqliteCore.text("utm_campaign"),
685
- // Review/Processing
686
- reviewedBy: sqliteCore.text("reviewed_by").references(() => users.id),
687
- reviewedAt: sqliteCore.integer("reviewed_at"),
688
- reviewNotes: sqliteCore.text("review_notes"),
689
- // Flags
690
- isSpam: sqliteCore.integer("is_spam", { mode: "boolean" }).notNull().default(false),
691
- isArchived: sqliteCore.integer("is_archived", { mode: "boolean" }).notNull().default(false),
692
- // Content integration
693
- contentId: sqliteCore.text("content_id").references(() => content.id),
694
- // Links submission to its content item
695
- // Timestamps
696
- submittedAt: sqliteCore.integer("submitted_at").notNull(),
697
- updatedAt: sqliteCore.integer("updated_at").notNull()
698
- });
699
- var formFiles = sqliteCore.sqliteTable("form_files", {
700
- id: sqliteCore.text("id").primaryKey(),
701
- submissionId: sqliteCore.text("submission_id").notNull().references(() => formSubmissions.id, { onDelete: "cascade" }),
702
- mediaId: sqliteCore.text("media_id").notNull().references(() => media.id, { onDelete: "cascade" }),
703
- fieldName: sqliteCore.text("field_name").notNull(),
704
- // Form field that uploaded this file
705
- uploadedAt: sqliteCore.integer("uploaded_at").notNull()
706
- });
707
- var insertFormSchema = createInsertSchema(forms);
708
- var selectFormSchema = createSelectSchema(forms);
709
- var insertFormSubmissionSchema = createInsertSchema(formSubmissions);
710
- var selectFormSubmissionSchema = createSelectSchema(formSubmissions);
711
- var insertFormFileSchema = createInsertSchema(formFiles);
712
- var selectFormFileSchema = createSelectSchema(formFiles);
713
- var Logger = class {
714
- db;
715
- enabled = true;
716
- configCache = /* @__PURE__ */ new Map();
717
- lastConfigRefresh = 0;
718
- configRefreshInterval = 6e4;
719
- // 1 minute
720
- constructor(database) {
721
- this.db = d1.drizzle(database);
722
- }
723
- /**
724
- * Log a debug message
725
- */
726
- async debug(category, message, data, context) {
727
- return this.log("debug", category, message, data, context);
728
- }
729
- /**
730
- * Log an info message
731
- */
732
- async info(category, message, data, context) {
733
- return this.log("info", category, message, data, context);
734
- }
735
- /**
736
- * Log a warning message
737
- */
738
- async warn(category, message, data, context) {
739
- return this.log("warn", category, message, data, context);
740
- }
741
- /**
742
- * Log an error message
743
- */
744
- async error(category, message, error, context) {
745
- const errorData = error instanceof Error ? {
746
- name: error.name,
747
- message: error.message,
748
- stack: error.stack
749
- } : error;
750
- return this.log("error", category, message, errorData, {
751
- ...context,
752
- stackTrace: error instanceof Error ? error.stack : void 0
753
- });
754
- }
755
- /**
756
- * Log a fatal message
757
- */
758
- async fatal(category, message, error, context) {
759
- const errorData = error instanceof Error ? {
760
- name: error.name,
761
- message: error.message,
762
- stack: error.stack
763
- } : error;
764
- return this.log("fatal", category, message, errorData, {
765
- ...context,
766
- stackTrace: error instanceof Error ? error.stack : void 0
767
- });
768
- }
769
- /**
770
- * Log an API request
771
- */
772
- async logRequest(method, url, statusCode, duration, context) {
773
- const level = statusCode >= 500 ? "error" : statusCode >= 400 ? "warn" : "info";
774
- return this.log(level, "api", `${method} ${url} - ${statusCode}`, {
775
- method,
776
- url,
777
- statusCode,
778
- duration
779
- }, {
780
- ...context,
781
- method,
782
- url,
783
- statusCode,
784
- duration
785
- });
786
- }
787
- /**
788
- * Log an authentication event
789
- */
790
- async logAuth(action, userId, success = true, context) {
791
- const level = success ? "info" : "warn";
792
- return this.log(level, "auth", `Authentication ${action}: ${success ? "success" : "failed"}`, {
793
- action,
794
- success,
795
- userId
796
- }, {
797
- ...context,
798
- userId,
799
- tags: ["authentication", action]
800
- });
801
- }
802
- /**
803
- * Log a security event
804
- */
805
- async logSecurity(event, severity, context) {
806
- const level = severity === "critical" ? "fatal" : severity === "high" ? "error" : "warn";
807
- return this.log(level, "security", `Security event: ${event}`, {
808
- event,
809
- severity
810
- }, {
811
- ...context,
812
- tags: ["security", severity]
813
- });
814
- }
815
- /**
816
- * Core logging method
817
- */
818
- async log(level, category, message, data, context) {
819
- if (!this.enabled) return;
820
- try {
821
- const config = await this.getConfig(category);
822
- if (!config || !config.enabled || !this.shouldLog(level, config.level)) {
823
- return;
824
- }
825
- const logEntry = {
826
- id: crypto.randomUUID(),
827
- level,
828
- category,
829
- message,
830
- data: data ? JSON.stringify(data) : null,
831
- userId: context?.userId || null,
832
- sessionId: context?.sessionId || null,
833
- requestId: context?.requestId || null,
834
- ipAddress: context?.ipAddress || null,
835
- userAgent: context?.userAgent || null,
836
- method: context?.method || null,
837
- url: context?.url || null,
838
- statusCode: context?.statusCode || null,
839
- duration: context?.duration || null,
840
- stackTrace: context?.stackTrace || null,
841
- tags: context?.tags ? JSON.stringify(context.tags) : null,
842
- source: context?.source || null,
843
- createdAt: /* @__PURE__ */ new Date()
844
- };
845
- await this.db.insert(systemLogs).values(logEntry);
846
- if (config.maxSize) {
847
- await this.cleanupCategory(category, config.maxSize);
848
- }
849
- } catch (error) {
850
- console.error("Logger error:", error);
851
- }
852
- }
853
- /**
854
- * Get logs with filtering and pagination
855
- */
856
- async getLogs(filter = {}) {
857
- try {
858
- const conditions = [];
859
- if (filter.level && filter.level.length > 0) {
860
- conditions.push(drizzleOrm.inArray(systemLogs.level, filter.level));
861
- }
862
- if (filter.category && filter.category.length > 0) {
863
- conditions.push(drizzleOrm.inArray(systemLogs.category, filter.category));
864
- }
865
- if (filter.userId) {
866
- conditions.push(drizzleOrm.eq(systemLogs.userId, filter.userId));
867
- }
868
- if (filter.source) {
869
- conditions.push(drizzleOrm.eq(systemLogs.source, filter.source));
870
- }
871
- if (filter.search) {
872
- conditions.push(
873
- drizzleOrm.like(systemLogs.message, `%${filter.search}%`)
874
- );
875
- }
876
- if (filter.startDate) {
877
- conditions.push(drizzleOrm.gte(systemLogs.createdAt, filter.startDate));
878
- }
879
- if (filter.endDate) {
880
- conditions.push(drizzleOrm.lte(systemLogs.createdAt, filter.endDate));
881
- }
882
- const whereClause = conditions.length > 0 ? drizzleOrm.and(...conditions) : void 0;
883
- const totalResult = await this.db.select({ count: drizzleOrm.count() }).from(systemLogs).where(whereClause);
884
- const total = totalResult[0]?.count || 0;
885
- const sortColumn = filter.sortBy === "level" ? systemLogs.level : filter.sortBy === "category" ? systemLogs.category : systemLogs.createdAt;
886
- const sortFn = filter.sortOrder === "asc" ? drizzleOrm.asc : drizzleOrm.desc;
887
- const logs = await this.db.select().from(systemLogs).where(whereClause).orderBy(sortFn(sortColumn)).limit(filter.limit || 50).offset(filter.offset || 0);
888
- return { logs, total };
889
- } catch (error) {
890
- console.error("Error getting logs:", error);
891
- return { logs: [], total: 0 };
892
- }
893
- }
894
- /**
895
- * Get log configuration for a category
896
- */
897
- async getConfig(category) {
898
- try {
899
- const now = Date.now();
900
- if (this.configCache.has(category) && now - this.lastConfigRefresh < this.configRefreshInterval) {
901
- return this.configCache.get(category) || null;
902
- }
903
- const configs = await this.db.select().from(logConfig).where(drizzleOrm.eq(logConfig.category, category));
904
- const config = configs[0] || null;
905
- if (config) {
906
- this.configCache.set(category, config);
907
- this.lastConfigRefresh = now;
908
- }
909
- return config;
910
- } catch (error) {
911
- console.error("Error getting log config:", error);
912
- return null;
913
- }
914
- }
915
- /**
916
- * Update log configuration
917
- */
918
- async updateConfig(category, updates) {
919
- try {
920
- await this.db.update(logConfig).set({
921
- ...updates,
922
- updatedAt: /* @__PURE__ */ new Date()
923
- }).where(drizzleOrm.eq(logConfig.category, category));
924
- this.configCache.delete(category);
925
- } catch (error) {
926
- console.error("Error updating log config:", error);
927
- }
928
- }
929
- /**
930
- * Get all log configurations
931
- */
932
- async getAllConfigs() {
933
- try {
934
- return await this.db.select().from(logConfig);
935
- } catch (error) {
936
- console.error("Error getting log configs:", error);
937
- return [];
938
- }
939
- }
940
- /**
941
- * Clean up old logs for a category
942
- */
943
- async cleanupCategory(category, maxSize) {
944
- try {
945
- const countResult = await this.db.select({ count: drizzleOrm.count() }).from(systemLogs).where(drizzleOrm.eq(systemLogs.category, category));
946
- const currentCount = countResult[0]?.count || 0;
947
- if (currentCount > maxSize) {
948
- const cutoffLogs = await this.db.select({ createdAt: systemLogs.createdAt }).from(systemLogs).where(drizzleOrm.eq(systemLogs.category, category)).orderBy(drizzleOrm.desc(systemLogs.createdAt)).limit(1).offset(maxSize - 1);
949
- if (cutoffLogs[0]) {
950
- await this.db.delete(systemLogs).where(
951
- drizzleOrm.and(
952
- drizzleOrm.eq(systemLogs.category, category),
953
- drizzleOrm.lte(systemLogs.createdAt, cutoffLogs[0].createdAt)
954
- )
955
- );
956
- }
957
- }
958
- } catch (error) {
959
- console.error("Error cleaning up logs:", error);
960
- }
961
- }
962
- /**
963
- * Clean up logs based on retention policy
964
- */
965
- async cleanupByRetention() {
966
- try {
967
- const configs = await this.getAllConfigs();
968
- for (const config of configs) {
969
- if (config.retention > 0) {
970
- const cutoffDate = /* @__PURE__ */ new Date();
971
- cutoffDate.setDate(cutoffDate.getDate() - config.retention);
972
- await this.db.delete(systemLogs).where(
973
- drizzleOrm.and(
974
- drizzleOrm.eq(systemLogs.category, config.category),
975
- drizzleOrm.lte(systemLogs.createdAt, cutoffDate)
976
- )
977
- );
978
- }
979
- }
980
- } catch (error) {
981
- console.error("Error cleaning up logs by retention:", error);
982
- }
983
- }
984
- /**
985
- * Check if a log level should be recorded based on configuration
986
- */
987
- shouldLog(level, configLevel) {
988
- const levels = ["debug", "info", "warn", "error", "fatal"];
989
- const levelIndex = levels.indexOf(level);
990
- const configLevelIndex = levels.indexOf(configLevel);
991
- return levelIndex >= configLevelIndex;
992
- }
993
- /**
994
- * Enable or disable logging
995
- */
996
- setEnabled(enabled) {
997
- this.enabled = enabled;
998
- }
999
- /**
1000
- * Check if logging is enabled
1001
- */
1002
- isEnabled() {
1003
- return this.enabled;
1004
- }
1005
- };
1006
- var loggerInstance = null;
1007
- function getLogger(database) {
1008
- if (!loggerInstance && database) {
1009
- loggerInstance = new Logger(database);
1010
- }
1011
- if (!loggerInstance) {
1012
- throw new Error("Logger not initialized. Call getLogger with a database instance first.");
1013
- }
1014
- return loggerInstance;
1015
- }
1016
- function initLogger(database) {
1017
- loggerInstance = new Logger(database);
1018
- return loggerInstance;
1019
- }
1020
-
1021
- // src/services/cache.ts
1022
- var CacheService = class {
1023
- config;
1024
- memoryCache = /* @__PURE__ */ new Map();
1025
- constructor(config) {
1026
- this.config = config;
1027
- }
1028
- /**
1029
- * Generate cache key with prefix
1030
- */
1031
- generateKey(type, identifier) {
1032
- const parts = [this.config.keyPrefix, type];
1033
- if (identifier) {
1034
- parts.push(identifier);
1035
- }
1036
- return parts.join(":");
1037
- }
1038
- /**
1039
- * Get value from cache
1040
- */
1041
- async get(key) {
1042
- const cached = this.memoryCache.get(key);
1043
- if (!cached) {
1044
- return null;
1045
- }
1046
- if (Date.now() > cached.expires) {
1047
- this.memoryCache.delete(key);
1048
- return null;
1049
- }
1050
- return cached.value;
1051
- }
1052
- /**
1053
- * Get value from cache with source information
1054
- */
1055
- async getWithSource(key) {
1056
- const cached = this.memoryCache.get(key);
1057
- if (!cached) {
1058
- return {
1059
- hit: false,
1060
- data: null,
1061
- source: "none"
1062
- };
1063
- }
1064
- if (Date.now() > cached.expires) {
1065
- this.memoryCache.delete(key);
1066
- return {
1067
- hit: false,
1068
- data: null,
1069
- source: "expired"
1070
- };
1071
- }
1072
- return {
1073
- hit: true,
1074
- data: cached.value,
1075
- source: "memory",
1076
- ttl: (cached.expires - Date.now()) / 1e3
1077
- // TTL in seconds
1078
- };
1079
- }
1080
- /**
1081
- * Set value in cache
1082
- */
1083
- async set(key, value, ttl) {
1084
- const expires = Date.now() + (ttl || this.config.ttl) * 1e3;
1085
- this.memoryCache.set(key, { value, expires });
1086
- }
1087
- /**
1088
- * Delete specific key from cache
1089
- */
1090
- async delete(key) {
1091
- this.memoryCache.delete(key);
1092
- }
1093
- /**
1094
- * Invalidate cache keys matching a pattern
1095
- * For memory cache, we do simple string matching
1096
- */
1097
- async invalidate(pattern) {
1098
- const regexPattern = pattern.replace(/\*/g, ".*").replace(/\?/g, ".");
1099
- const regex = new RegExp(`^${regexPattern}$`);
1100
- for (const key of this.memoryCache.keys()) {
1101
- if (regex.test(key)) {
1102
- this.memoryCache.delete(key);
1103
- }
1104
- }
1105
- }
1106
- /**
1107
- * Clear all cache
1108
- */
1109
- async clear() {
1110
- this.memoryCache.clear();
1111
- }
1112
- /**
1113
- * Get value from cache or set it using a callback
1114
- */
1115
- async getOrSet(key, callback, ttl) {
1116
- const cached = await this.get(key);
1117
- if (cached !== null) {
1118
- return cached;
1119
- }
1120
- const value = await callback();
1121
- await this.set(key, value, ttl);
1122
- return value;
1123
- }
1124
- };
1125
- var CACHE_CONFIGS = {
1126
- api: {
1127
- ttl: 300,
1128
- // 5 minutes
1129
- keyPrefix: "api"
1130
- },
1131
- user: {
1132
- ttl: 600,
1133
- // 10 minutes
1134
- keyPrefix: "user"
1135
- },
1136
- content: {
1137
- ttl: 300,
1138
- // 5 minutes
1139
- keyPrefix: "content"
1140
- },
1141
- collection: {
1142
- ttl: 600,
1143
- // 10 minutes
1144
- keyPrefix: "collection"
1145
- }
1146
- };
1147
- function getCacheService(config) {
1148
- return new CacheService(config);
1149
- }
1150
-
1151
- // src/services/settings.ts
1152
- var SettingsService = class {
1153
- constructor(db) {
1154
- this.db = db;
1155
- }
1156
- /**
1157
- * Get a setting value by category and key
1158
- */
1159
- async getSetting(category, key) {
1160
- try {
1161
- const result = await this.db.prepare("SELECT value FROM settings WHERE category = ? AND key = ?").bind(category, key).first();
1162
- if (!result) {
1163
- return null;
1164
- }
1165
- return JSON.parse(result.value);
1166
- } catch (error) {
1167
- console.error(`Error getting setting ${category}.${key}:`, error);
1168
- return null;
1169
- }
1170
- }
1171
- /**
1172
- * Get all settings for a category
1173
- */
1174
- async getCategorySettings(category) {
1175
- try {
1176
- const { results } = await this.db.prepare("SELECT key, value FROM settings WHERE category = ?").bind(category).all();
1177
- const settings = {};
1178
- for (const row of results || []) {
1179
- const r = row;
1180
- settings[r.key] = JSON.parse(r.value);
1181
- }
1182
- return settings;
1183
- } catch (error) {
1184
- console.error(`Error getting category settings for ${category}:`, error);
1185
- return {};
1186
- }
1187
- }
1188
- /**
1189
- * Set a setting value
1190
- */
1191
- async setSetting(category, key, value) {
1192
- try {
1193
- const now = Date.now();
1194
- const jsonValue = JSON.stringify(value);
1195
- await this.db.prepare(`
1196
- INSERT INTO settings (id, category, key, value, created_at, updated_at)
1197
- VALUES (?, ?, ?, ?, ?, ?)
1198
- ON CONFLICT(category, key) DO UPDATE SET
1199
- value = excluded.value,
1200
- updated_at = excluded.updated_at
1201
- `).bind(crypto.randomUUID(), category, key, jsonValue, now, now).run();
1202
- return true;
1203
- } catch (error) {
1204
- console.error(`Error setting ${category}.${key}:`, error);
1205
- return false;
1206
- }
1207
- }
1208
- /**
1209
- * Set multiple settings at once
1210
- */
1211
- async setMultipleSettings(category, settings) {
1212
- try {
1213
- const now = Date.now();
1214
- for (const [key, value] of Object.entries(settings)) {
1215
- const jsonValue = JSON.stringify(value);
1216
- await this.db.prepare(`
1217
- INSERT INTO settings (id, category, key, value, created_at, updated_at)
1218
- VALUES (?, ?, ?, ?, ?, ?)
1219
- ON CONFLICT(category, key) DO UPDATE SET
1220
- value = excluded.value,
1221
- updated_at = excluded.updated_at
1222
- `).bind(crypto.randomUUID(), category, key, jsonValue, now, now).run();
1223
- }
1224
- return true;
1225
- } catch (error) {
1226
- console.error(`Error setting multiple settings for ${category}:`, error);
1227
- return false;
1228
- }
1229
- }
1230
- /**
1231
- * Get general settings with defaults
1232
- */
1233
- async getGeneralSettings(userEmail) {
1234
- const settings = await this.getCategorySettings("general");
1235
- return {
1236
- siteName: settings.siteName || "SonicJS AI",
1237
- siteDescription: settings.siteDescription || "A modern headless CMS powered by AI",
1238
- adminEmail: settings.adminEmail || userEmail || "admin@example.com",
1239
- timezone: settings.timezone || "UTC",
1240
- language: settings.language || "en",
1241
- maintenanceMode: settings.maintenanceMode || false
1242
- };
1243
- }
1244
- /**
1245
- * Save general settings
1246
- */
1247
- async saveGeneralSettings(settings) {
1248
- const settingsToSave = {};
1249
- if (settings.siteName !== void 0) settingsToSave.siteName = settings.siteName;
1250
- if (settings.siteDescription !== void 0) settingsToSave.siteDescription = settings.siteDescription;
1251
- if (settings.adminEmail !== void 0) settingsToSave.adminEmail = settings.adminEmail;
1252
- if (settings.timezone !== void 0) settingsToSave.timezone = settings.timezone;
1253
- if (settings.language !== void 0) settingsToSave.language = settings.language;
1254
- if (settings.maintenanceMode !== void 0) settingsToSave.maintenanceMode = settings.maintenanceMode;
1255
- return await this.setMultipleSettings("general", settingsToSave);
1256
- }
1257
- /**
1258
- * Get security settings with defaults
1259
- */
1260
- async getSecuritySettings() {
1261
- const settings = await this.getCategorySettings("security");
1262
- return {
1263
- jwtExpiresIn: settings.jwtExpiresIn || "30d",
1264
- jwtRefreshGraceSeconds: typeof settings.jwtRefreshGraceSeconds === "number" ? settings.jwtRefreshGraceSeconds : 60 * 60 * 24 * 7
1265
- };
1266
- }
1267
- /**
1268
- * Save security settings
1269
- */
1270
- async saveSecuritySettings(settings) {
1271
- const settingsToSave = {};
1272
- if (settings.jwtExpiresIn !== void 0) settingsToSave.jwtExpiresIn = settings.jwtExpiresIn;
1273
- if (settings.jwtRefreshGraceSeconds !== void 0)
1274
- settingsToSave.jwtRefreshGraceSeconds = settings.jwtRefreshGraceSeconds;
1275
- return await this.setMultipleSettings("security", settingsToSave);
1276
- }
1277
- };
1278
-
1279
- // src/services/telemetry-service.ts
1280
- var TelemetryService = class {
1281
- config;
1282
- identity = null;
1283
- enabled = true;
1284
- eventQueue = [];
1285
- isInitialized = false;
1286
- constructor(config) {
1287
- this.config = {
1288
- ...chunkP3XDZL6Q_cjs.getTelemetryConfig(),
1289
- ...config
1290
- };
1291
- this.enabled = this.config.enabled;
1292
- }
1293
- /**
1294
- * Initialize the telemetry service
1295
- */
1296
- async initialize(identity) {
1297
- if (!this.enabled) {
1298
- if (this.config.debug) {
1299
- console.log("[Telemetry] Disabled via configuration");
1300
- }
1301
- return;
1302
- }
1303
- try {
1304
- this.identity = identity;
1305
- if (this.config.debug) {
1306
- console.log("[Telemetry] Initialized with installation ID:", identity.installationId);
1307
- }
1308
- this.isInitialized = true;
1309
- await this.flushQueue();
1310
- } catch (error) {
1311
- if (this.config.debug) {
1312
- console.error("[Telemetry] Initialization failed:", error);
1313
- }
1314
- this.enabled = false;
1315
- }
1316
- }
1317
- /**
1318
- * Track a telemetry event
1319
- */
1320
- async track(event, properties) {
1321
- if (!this.enabled) return;
1322
- try {
1323
- const sanitizedProps = this.sanitizeProperties(properties);
1324
- const enrichedProps = {
1325
- ...sanitizedProps,
1326
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
1327
- version: this.getVersion()
1328
- };
1329
- if (!this.isInitialized) {
1330
- this.eventQueue.push({ event, properties: enrichedProps });
1331
- if (this.config.debug) {
1332
- console.log("[Telemetry] Queued event:", event, enrichedProps);
1333
- }
1334
- return;
1335
- }
1336
- if (this.identity && this.config.host) {
1337
- const payload = {
1338
- data: {
1339
- installation_id: this.identity.installationId,
1340
- event_type: event,
1341
- properties: enrichedProps,
1342
- timestamp: enrichedProps.timestamp
1343
- }
1344
- };
1345
- fetch(`${this.config.host}/v1/events`, {
1346
- method: "POST",
1347
- headers: { "Content-Type": "application/json" },
1348
- body: JSON.stringify(payload)
1349
- }).catch(() => {
1350
- });
1351
- if (this.config.debug) {
1352
- console.log("[Telemetry] Tracked event:", event, enrichedProps);
1353
- }
1354
- } else if (this.config.debug) {
1355
- console.log("[Telemetry] Event (no endpoint):", event, enrichedProps);
1356
- }
1357
- } catch (error) {
1358
- if (this.config.debug) {
1359
- console.error("[Telemetry] Failed to track event:", error);
1360
- }
1361
- }
1362
- }
1363
- /**
1364
- * Track installation started
1365
- */
1366
- async trackInstallationStarted(properties) {
1367
- await this.track("installation_started", properties);
1368
- }
1369
- /**
1370
- * Track installation completed
1371
- */
1372
- async trackInstallationCompleted(properties) {
1373
- await this.track("installation_completed", properties);
1374
- }
1375
- /**
1376
- * Track installation failed
1377
- */
1378
- async trackInstallationFailed(error, properties) {
1379
- await this.track("installation_failed", {
1380
- ...properties,
1381
- errorType: chunkP3XDZL6Q_cjs.sanitizeErrorMessage(error)
1382
- });
1383
- }
1384
- /**
1385
- * Track dev server started
1386
- */
1387
- async trackDevServerStarted(properties) {
1388
- await this.track("dev_server_started", properties);
1389
- }
1390
- /**
1391
- * Track page view in admin UI
1392
- */
1393
- async trackPageView(route, properties) {
1394
- await this.track("page_viewed", {
1395
- ...properties,
1396
- route: chunkP3XDZL6Q_cjs.sanitizeRoute(route)
1397
- });
1398
- }
1399
- /**
1400
- * Track error (sanitized)
1401
- */
1402
- async trackError(error, properties) {
1403
- await this.track("error_occurred", {
1404
- ...properties,
1405
- errorType: chunkP3XDZL6Q_cjs.sanitizeErrorMessage(error)
1406
- });
1407
- }
1408
- /**
1409
- * Track plugin activation
1410
- */
1411
- async trackPluginActivated(properties) {
1412
- await this.track("plugin_activated", properties);
1413
- }
1414
- /**
1415
- * Track migration run
1416
- */
1417
- async trackMigrationRun(properties) {
1418
- await this.track("migration_run", properties);
1419
- }
1420
- /**
1421
- * Flush queued events
1422
- */
1423
- async flushQueue() {
1424
- if (this.eventQueue.length === 0) return;
1425
- const queue = [...this.eventQueue];
1426
- this.eventQueue = [];
1427
- for (const { event, properties } of queue) {
1428
- await this.track(event, properties);
1429
- }
1430
- }
1431
- /**
1432
- * Sanitize properties to ensure no PII
1433
- */
1434
- sanitizeProperties(properties) {
1435
- if (!properties) return {};
1436
- const sanitized = {};
1437
- for (const [key, value] of Object.entries(properties)) {
1438
- if (value === void 0) continue;
1439
- if (key === "route" && typeof value === "string") {
1440
- sanitized[key] = chunkP3XDZL6Q_cjs.sanitizeRoute(value);
1441
- continue;
1442
- }
1443
- if (key.toLowerCase().includes("error") && typeof value === "string") {
1444
- sanitized[key] = chunkP3XDZL6Q_cjs.sanitizeErrorMessage(value);
1445
- continue;
1446
- }
1447
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1448
- sanitized[key] = value;
1449
- }
1450
- }
1451
- return sanitized;
1452
- }
1453
- /**
1454
- * Get SonicJS version
1455
- */
1456
- getVersion() {
1457
- try {
1458
- if (typeof process !== "undefined" && process.env) {
1459
- return process.env.SONICJS_VERSION || "2.0.0";
1460
- }
1461
- return "2.0.0";
1462
- } catch {
1463
- return "unknown";
1464
- }
1465
- }
1466
- /**
1467
- * Shutdown the telemetry service (no-op for fetch-based telemetry)
1468
- */
1469
- async shutdown() {
1470
- }
1471
- /**
1472
- * Enable telemetry
1473
- */
1474
- enable() {
1475
- this.enabled = true;
1476
- }
1477
- /**
1478
- * Disable telemetry
1479
- */
1480
- disable() {
1481
- this.enabled = false;
1482
- }
1483
- /**
1484
- * Check if telemetry is enabled
1485
- */
1486
- isEnabled() {
1487
- return this.enabled;
1488
- }
1489
- };
1490
- var telemetryInstance = null;
1491
- function getTelemetryService(config) {
1492
- if (!telemetryInstance) {
1493
- telemetryInstance = new TelemetryService(config);
1494
- }
1495
- return telemetryInstance;
1496
- }
1497
- async function initTelemetry(identity, config) {
1498
- const service = getTelemetryService(config);
1499
- await service.initialize(identity);
1500
- return service;
1501
- }
1502
- function createInstallationIdentity(projectName) {
1503
- const installationId = chunkP3XDZL6Q_cjs.generateInstallationId();
1504
- const identity = { installationId };
1505
- if (projectName) {
1506
- identity.projectId = chunkP3XDZL6Q_cjs.generateProjectId(projectName);
1507
- }
1508
- return identity;
1509
- }
1510
- var appInstance = null;
1511
- function setAppInstance(app) {
1512
- appInstance = app;
1513
- }
1514
- function getAppInstance() {
1515
- return appInstance;
1516
- }
1517
- var CATEGORY_INFO = {
1518
- "Auth": {
1519
- title: "Authentication",
1520
- description: "User authentication and authorization endpoints",
1521
- icon: "&#x1f510;"
1522
- },
1523
- "Content": {
1524
- title: "Content Management",
1525
- description: "Content creation, retrieval, and management",
1526
- icon: "&#x1f4dd;"
1527
- },
1528
- "Media": {
1529
- title: "Media Management",
1530
- description: "File upload, storage, and media operations",
1531
- icon: "&#x1f5bc;&#xfe0f;"
1532
- },
1533
- "Admin": {
1534
- title: "Admin Interface",
1535
- description: "Administrative panel and management features",
1536
- icon: "&#x2699;&#xfe0f;"
1537
- },
1538
- "System": {
1539
- title: "System",
1540
- description: "Health checks and system information",
1541
- icon: "&#x1f527;"
1542
- },
1543
- "Search": {
1544
- title: "Search",
1545
- description: "AI-powered search, full-text search, and analytics",
1546
- icon: "&#x1f50d;"
1547
- },
1548
- "API Keys": {
1549
- title: "API Keys",
1550
- description: "API key management and authentication",
1551
- icon: "&#x1f511;"
1552
- },
1553
- "Workflow": {
1554
- title: "Workflow",
1555
- description: "Content workflow and approval processes",
1556
- icon: "&#x1f504;"
1557
- },
1558
- "Cache": {
1559
- title: "Cache",
1560
- description: "Cache management and invalidation",
1561
- icon: "&#x26a1;"
1562
- },
1563
- "Forms": {
1564
- title: "Forms",
1565
- description: "Form submissions and management",
1566
- icon: "&#x1f4cb;"
1567
- },
1568
- "Files": {
1569
- title: "Files",
1570
- description: "File serving from R2 storage",
1571
- icon: "&#x1f4c1;"
1572
- }
1573
- };
1574
- var ROUTE_METADATA = {
1575
- // Auth endpoints
1576
- "POST /auth/login": { description: "Authenticate user with email and password (returns JWT)", category: "Auth", authentication: false },
1577
- "POST /auth/login/form": { description: "Form-based login (sets session cookie)", category: "Auth", authentication: false },
1578
- "POST /auth/register": { description: "Register a new user account", category: "Auth", authentication: false },
1579
- "POST /auth/logout": { description: "Log out the current user and invalidate session", category: "Auth", authentication: true },
1580
- "GET /auth/me": { description: "Get current authenticated user information", category: "Auth", authentication: true },
1581
- "POST /auth/refresh": { description: "Refresh authentication token", category: "Auth", authentication: true },
1582
- "POST /auth/seed-admin": { description: "Create or reset the admin user account", category: "Auth", authentication: false },
1583
- "POST /auth/magic-link/request": { description: "Request a magic link login email", category: "Auth", authentication: false },
1584
- "GET /auth/magic-link/verify": { description: "Verify magic link token and authenticate", category: "Auth", authentication: false },
1585
- "POST /auth/otp/request": { description: "Request a one-time password via email", category: "Auth", authentication: false },
1586
- "POST /auth/otp/verify": { description: "Verify OTP code and authenticate", category: "Auth", authentication: false },
1587
- // Content endpoints
1588
- "GET /api/collections": { description: "List all available collections", category: "Content", authentication: false },
1589
- "GET /api/collections/:collection/content": { description: "Get all content items from a specific collection", category: "Content", authentication: false },
1590
- "GET /api/content/:id": { description: "Get a specific content item by ID", category: "Content", authentication: false },
1591
- "POST /api/content": { description: "Create a new content item", category: "Content", authentication: true },
1592
- "PUT /api/content/:id": { description: "Update an existing content item", category: "Content", authentication: true },
1593
- "DELETE /api/content/:id": { description: "Delete a content item", category: "Content", authentication: true },
1594
- "GET /api/content/:id/versions": { description: "Get version history for a content item", category: "Content", authentication: true },
1595
- "POST /api/content/:id/restore/:versionId": { description: "Restore a content item to a previous version", category: "Content", authentication: true },
1596
- // Media endpoints
1597
- "GET /api/media": { description: "List all media files with pagination", category: "Media", authentication: false },
1598
- "GET /api/media/:id": { description: "Get a specific media file by ID", category: "Media", authentication: false },
1599
- "POST /api/media/upload": { description: "Upload a new media file to R2 storage", category: "Media", authentication: true },
1600
- "DELETE /api/media/:id": { description: "Delete a media file from storage", category: "Media", authentication: true },
1601
- // Admin API endpoints
1602
- "GET /admin/api/stats": { description: "Get dashboard statistics (collections, content, media, users)", category: "Admin", authentication: true },
1603
- "GET /admin/api/storage": { description: "Get storage usage information", category: "Admin", authentication: true },
1604
- "GET /admin/api/activity": { description: "Get recent activity logs", category: "Admin", authentication: true },
1605
- "GET /admin/api/collections": { description: "List all collections with field counts", category: "Admin", authentication: true },
1606
- "POST /admin/api/collections": { description: "Create a new collection", category: "Admin", authentication: true },
1607
- "GET /admin/api/collections/:id": { description: "Get a specific collection with its fields", category: "Admin", authentication: true },
1608
- "PATCH /admin/api/collections/:id": { description: "Update an existing collection", category: "Admin", authentication: true },
1609
- "DELETE /admin/api/collections/:id": { description: "Delete a collection (must be empty)", category: "Admin", authentication: true },
1610
- "GET /admin/api/collections/:id/fields": { description: "Get fields for a specific collection", category: "Admin", authentication: true },
1611
- "POST /admin/api/collections/:id/fields": { description: "Add a field to a collection", category: "Admin", authentication: true },
1612
- "PATCH /admin/api/collections/:id/fields/:fieldId": { description: "Update a collection field", category: "Admin", authentication: true },
1613
- "DELETE /admin/api/collections/:id/fields/:fieldId": { description: "Remove a field from a collection", category: "Admin", authentication: true },
1614
- "POST /admin/api/collections/:id/fields/reorder": { description: "Reorder fields in a collection", category: "Admin", authentication: true },
1615
- "GET /admin/api/migrations/status": { description: "Get database migration status", category: "Admin", authentication: true },
1616
- "POST /admin/api/migrations/run": { description: "Run pending database migrations", category: "Admin", authentication: true },
1617
- "GET /admin/api/content": { description: "List content items with filtering and pagination", category: "Admin", authentication: true },
1618
- "GET /admin/api/content/:id": { description: "Get a content item for admin editing", category: "Admin", authentication: true },
1619
- "POST /admin/api/content": { description: "Create content via admin API", category: "Admin", authentication: true },
1620
- "PUT /admin/api/content/:id": { description: "Update content via admin API", category: "Admin", authentication: true },
1621
- "DELETE /admin/api/content/:id": { description: "Delete content via admin API", category: "Admin", authentication: true },
1622
- "GET /admin/api/media": { description: "List media files for admin management", category: "Admin", authentication: true },
1623
- "POST /admin/api/media/upload": { description: "Upload media via admin interface", category: "Admin", authentication: true },
1624
- "DELETE /admin/api/media/:id": { description: "Delete media via admin interface", category: "Admin", authentication: true },
1625
- "GET /admin/api/users": { description: "List all users", category: "Admin", authentication: true },
1626
- "POST /admin/api/users": { description: "Create a new user", category: "Admin", authentication: true },
1627
- "PUT /admin/api/users/:id": { description: "Update a user", category: "Admin", authentication: true },
1628
- "DELETE /admin/api/users/:id": { description: "Delete a user", category: "Admin", authentication: true },
1629
- "GET /admin/api/logs": { description: "Get application logs with filtering", category: "Admin", authentication: true },
1630
- "GET /admin/api/plugins": { description: "List all registered plugins", category: "Admin", authentication: true },
1631
- "POST /admin/api/plugins/:id/toggle": { description: "Enable or disable a plugin", category: "Admin", authentication: true },
1632
- "GET /admin/api/settings": { description: "Get application settings", category: "Admin", authentication: true },
1633
- "PUT /admin/api/settings": { description: "Update application settings", category: "Admin", authentication: true },
1634
- "GET /admin/api/forms": { description: "List all forms", category: "Admin", authentication: true },
1635
- "GET /admin/api/forms/:id": { description: "Get form details and submissions", category: "Admin", authentication: true },
1636
- "POST /admin/api/forms": { description: "Create a new form", category: "Admin", authentication: true },
1637
- "PUT /admin/api/forms/:id": { description: "Update a form", category: "Admin", authentication: true },
1638
- "DELETE /admin/api/forms/:id": { description: "Delete a form", category: "Admin", authentication: true },
1639
- "GET /admin/api/forms/:id/submissions": { description: "Get form submissions", category: "Admin", authentication: true },
1640
- "DELETE /admin/api/forms/:id/submissions/:submissionId": { description: "Delete a form submission", category: "Admin", authentication: true },
1641
- // Search endpoints
1642
- "GET /api/search": { description: "Search content using AI, FTS5, keyword, or hybrid mode", category: "Search", authentication: false },
1643
- "POST /api/search/click": { description: "Track a search result click for analytics", category: "Search", authentication: false },
1644
- "GET /admin/plugins/ai-search/api/status": { description: "Get search plugin status and configuration", category: "Search", authentication: true },
1645
- "POST /admin/plugins/ai-search/api/index": { description: "Trigger content indexing for search", category: "Search", authentication: true },
1646
- "POST /admin/plugins/ai-search/api/index/reset": { description: "Reset the search index", category: "Search", authentication: true },
1647
- "GET /admin/plugins/ai-search/api/analytics": { description: "Get search analytics and metrics", category: "Search", authentication: true },
1648
- "GET /admin/plugins/ai-search/api/analytics/queries": { description: "Get top search queries", category: "Search", authentication: true },
1649
- "GET /admin/plugins/ai-search/api/analytics/clicks": { description: "Get click-through analytics", category: "Search", authentication: true },
1650
- "GET /admin/plugins/ai-search/api/fts5/status": { description: "Get FTS5 full-text search status", category: "Search", authentication: true },
1651
- "POST /admin/plugins/ai-search/api/fts5/rebuild": { description: "Rebuild the FTS5 search index", category: "Search", authentication: true },
1652
- "GET /admin/plugins/ai-search/api/facets": { description: "Get available search facets", category: "Search", authentication: true },
1653
- "GET /admin/plugins/ai-search/api/experiments": { description: "List search A/B test experiments", category: "Search", authentication: true },
1654
- "POST /admin/plugins/ai-search/api/experiments": { description: "Create a search A/B test experiment", category: "Search", authentication: true },
1655
- "GET /admin/plugins/ai-search/api/experiments/:id": { description: "Get experiment details", category: "Search", authentication: true },
1656
- "PUT /admin/plugins/ai-search/api/experiments/:id": { description: "Update an experiment", category: "Search", authentication: true },
1657
- "DELETE /admin/plugins/ai-search/api/experiments/:id": { description: "Delete an experiment", category: "Search", authentication: true },
1658
- "POST /admin/plugins/ai-search/api/experiments/:id/start": { description: "Start an experiment", category: "Search", authentication: true },
1659
- "POST /admin/plugins/ai-search/api/experiments/:id/stop": { description: "Stop a running experiment", category: "Search", authentication: true },
1660
- "GET /admin/plugins/ai-search/api/experiments/:id/results": { description: "Get experiment results and statistics", category: "Search", authentication: true },
1661
- "GET /admin/plugins/ai-search/api/quality": { description: "Get search quality agent analysis", category: "Search", authentication: true },
1662
- "POST /admin/plugins/ai-search/api/quality/run": { description: "Run search quality analysis", category: "Search", authentication: true },
1663
- "GET /admin/plugins/ai-search/api/quality/recommendations": { description: "Get quality improvement recommendations", category: "Search", authentication: true },
1664
- "POST /admin/plugins/ai-search/api/quality/recommendations/:id/apply": { description: "Apply a quality recommendation", category: "Search", authentication: true },
1665
- "POST /admin/plugins/ai-search/api/quality/recommendations/:id/dismiss": { description: "Dismiss a quality recommendation", category: "Search", authentication: true },
1666
- "GET /admin/plugins/ai-search/api/synonyms": { description: "List search synonyms", category: "Search", authentication: true },
1667
- "POST /admin/plugins/ai-search/api/synonyms": { description: "Add a search synonym", category: "Search", authentication: true },
1668
- "DELETE /admin/plugins/ai-search/api/synonyms/:id": { description: "Delete a search synonym", category: "Search", authentication: true },
1669
- "GET /admin/plugins/ai-search/api/query-rules": { description: "List search query rules", category: "Search", authentication: true },
1670
- "POST /admin/plugins/ai-search/api/query-rules": { description: "Create a query rule", category: "Search", authentication: true },
1671
- "PUT /admin/plugins/ai-search/api/query-rules/:id": { description: "Update a query rule", category: "Search", authentication: true },
1672
- "DELETE /admin/plugins/ai-search/api/query-rules/:id": { description: "Delete a query rule", category: "Search", authentication: true },
1673
- "GET /admin/plugins/ai-search/api/settings": { description: "Get search plugin settings", category: "Search", authentication: true },
1674
- "PUT /admin/plugins/ai-search/api/settings": { description: "Update search plugin settings", category: "Search", authentication: true },
1675
- // API Key endpoints
1676
- "GET /admin/api-keys/api/keys": { description: "List all API keys", category: "API Keys", authentication: true },
1677
- "POST /admin/api-keys/api/keys": { description: "Create a new API key", category: "API Keys", authentication: true },
1678
- "DELETE /admin/api-keys/api/keys/:id": { description: "Revoke an API key", category: "API Keys", authentication: true },
1679
- "PUT /admin/api-keys/api/keys/:id": { description: "Update an API key", category: "API Keys", authentication: true },
1680
- // Cache endpoints
1681
- "GET /admin/cache/api/stats": { description: "Get cache statistics", category: "Cache", authentication: true },
1682
- "POST /admin/cache/api/purge": { description: "Purge cache entries", category: "Cache", authentication: true },
1683
- "GET /admin/cache/api/entries": { description: "List cache entries", category: "Cache", authentication: true },
1684
- "DELETE /admin/cache/api/entries/:key": { description: "Delete a specific cache entry", category: "Cache", authentication: true },
1685
- // Workflow endpoints
1686
- "GET /workflow/status/:id": { description: "Get workflow status for a content item", category: "Workflow", authentication: true },
1687
- "POST /workflow/submit/:id": { description: "Submit content for review", category: "Workflow", authentication: true },
1688
- "POST /workflow/approve/:id": { description: "Approve content in review", category: "Workflow", authentication: true },
1689
- "POST /workflow/reject/:id": { description: "Reject content in review", category: "Workflow", authentication: true },
1690
- "POST /workflow/publish/:id": { description: "Publish approved content", category: "Workflow", authentication: true },
1691
- "POST /workflow/unpublish/:id": { description: "Unpublish content", category: "Workflow", authentication: true },
1692
- "GET /workflow/history/:id": { description: "Get workflow history for a content item", category: "Workflow", authentication: true },
1693
- // Form endpoints (public)
1694
- "POST /forms/:formId/submit": { description: "Submit a form (public endpoint)", category: "Forms", authentication: false },
1695
- "GET /forms/:formId": { description: "Get form definition for rendering", category: "Forms", authentication: false },
1696
- "POST /api/forms/:formId/submit": { description: "Submit a form via API", category: "Forms", authentication: false },
1697
- "GET /api/forms/:formId": { description: "Get form definition via API", category: "Forms", authentication: false },
1698
- // System endpoints
1699
- "GET /health": { description: "Health check endpoint for monitoring", category: "System", authentication: false },
1700
- "GET /api/health": { description: "API health check with schema information", category: "System", authentication: false },
1701
- "GET /api": { description: "API root - returns API information and available endpoints", category: "System", authentication: false },
1702
- "GET /api/system/info": { description: "Get system information and version", category: "System", authentication: false },
1703
- "GET /api/system/schema": { description: "Get database schema information", category: "System", authentication: false },
1704
- // File serving
1705
- "GET /files/*": { description: "Serve files from R2 storage (public access)", category: "Files", authentication: false },
1706
- // Database tools
1707
- "POST /admin/database-tools/api/query": { description: "Execute a database query", category: "Admin", authentication: true },
1708
- "GET /admin/database-tools/api/tables": { description: "List database tables", category: "Admin", authentication: true },
1709
- "GET /admin/database-tools/api/tables/:name": { description: "Get table schema and sample data", category: "Admin", authentication: true },
1710
- // Seed data
1711
- "POST /admin/seed-data/api/generate": { description: "Generate seed data for development", category: "Admin", authentication: true },
1712
- "GET /admin/seed-data/api/status": { description: "Get seed data generation status", category: "Admin", authentication: true },
1713
- // Email plugin
1714
- "POST /admin/plugins/email/api/send": { description: "Send an email", category: "Admin", authentication: true },
1715
- "GET /admin/plugins/email/api/templates": { description: "List email templates", category: "Admin", authentication: true },
1716
- "POST /admin/plugins/email/api/test": { description: "Send a test email", category: "Admin", authentication: true }
1717
- };
1718
- var INCLUDED_ROUTE_PATTERNS = [
1719
- /^\/api\//,
1720
- // All /api/* routes
1721
- /^\/api$/,
1722
- // API root
1723
- /^\/auth\/(?!login$|register$)/,
1724
- // Auth routes except GET login/register HTML pages
1725
- /^\/auth\/login$/,
1726
- // POST /auth/login (method filtered later)
1727
- /^\/auth\/register$/,
1728
- // POST /auth/register (method filtered later)
1729
- /^\/admin\/api\//,
1730
- // Admin API endpoints
1731
- /^\/admin\/api-keys\/api\//,
1732
- // API key management
1733
- /^\/admin\/cache\/api\//,
1734
- // Cache management API
1735
- /^\/admin\/plugins\/.*\/api\//,
1736
- // Plugin API endpoints
1737
- /^\/admin\/database-tools\/api\//,
1738
- // Database tools API
1739
- /^\/admin\/seed-data\/api\//,
1740
- // Seed data API
1741
- /^\/workflow\//,
1742
- // Workflow endpoints
1743
- /^\/health$/,
1744
- // Health check
1745
- /^\/files\//,
1746
- // File serving
1747
- /^\/forms\//
1748
- // Public form endpoints
1749
- ];
1750
- var EXCLUDED_ROUTES = /* @__PURE__ */ new Set([
1751
- "GET /auth/login",
1752
- "GET /auth/register",
1753
- "GET /auth/login/form"
1754
- ]);
1755
- var cachedRouteList = null;
1756
- function isIncludedRoute(method, path) {
1757
- const key = `${method} ${path}`;
1758
- if (EXCLUDED_ROUTES.has(key)) {
1759
- return false;
1760
- }
1761
- return INCLUDED_ROUTE_PATTERNS.some((pattern) => pattern.test(path));
1762
- }
1763
- function inferCategory(path) {
1764
- if (path.startsWith("/auth/")) return "Auth";
1765
- if (path.startsWith("/api/search")) return "Search";
1766
- if (path.startsWith("/api/media")) return "Media";
1767
- if (path.startsWith("/api/system")) return "System";
1768
- if (path.startsWith("/api/content") || path.startsWith("/api/collections")) return "Content";
1769
- if (path.startsWith("/api/forms")) return "Forms";
1770
- if (path.startsWith("/admin/api-keys")) return "API Keys";
1771
- if (path.startsWith("/admin/cache")) return "Cache";
1772
- if (path.startsWith("/admin/plugins/ai-search")) return "Search";
1773
- if (path.startsWith("/admin/api")) return "Admin";
1774
- if (path.startsWith("/admin/database-tools")) return "Admin";
1775
- if (path.startsWith("/admin/seed-data")) return "Admin";
1776
- if (path.startsWith("/admin/plugins/email")) return "Admin";
1777
- if (path.startsWith("/workflow/")) return "Workflow";
1778
- if (path.startsWith("/forms/")) return "Forms";
1779
- if (path.startsWith("/files/")) return "Files";
1780
- if (path === "/health" || path.startsWith("/api")) return "System";
1781
- return "Other";
1782
- }
1783
- function inferAuth(path) {
1784
- if (path === "/health" || path === "/api" || path === "/api/health") return false;
1785
- if (path === "/api/system/info" || path === "/api/system/schema") return false;
1786
- if (path.startsWith("/files/")) return false;
1787
- if (path.startsWith("/forms/") || path.startsWith("/api/forms/")) return false;
1788
- if (path.startsWith("/admin/")) return true;
1789
- if (path.startsWith("/workflow/")) return true;
1790
- return "unknown";
1791
- }
1792
- function buildRouteList(app) {
1793
- if (cachedRouteList) return cachedRouteList;
1794
- if (!app) return [];
1795
- try {
1796
- const routes = dev.inspectRoutes(app);
1797
- const seen = /* @__PURE__ */ new Set();
1798
- const result = [];
1799
- for (const route of routes) {
1800
- if (route.isMiddleware) continue;
1801
- if (route.method === "ALL") continue;
1802
- const key = `${route.method} ${route.path}`;
1803
- if (seen.has(key)) continue;
1804
- seen.add(key);
1805
- if (!isIncludedRoute(route.method, route.path)) continue;
1806
- const meta = ROUTE_METADATA[key];
1807
- if (meta) {
1808
- result.push({
1809
- method: route.method,
1810
- path: route.path,
1811
- description: meta.description,
1812
- authentication: meta.authentication,
1813
- category: meta.category,
1814
- documented: true
1815
- });
1816
- } else {
1817
- result.push({
1818
- method: route.method,
1819
- path: route.path,
1820
- description: "",
1821
- authentication: inferAuth(route.path),
1822
- category: inferCategory(route.path),
1823
- documented: false
1824
- });
1825
- }
1826
- }
1827
- const methodOrder = { GET: 0, POST: 1, PUT: 2, PATCH: 3, DELETE: 4 };
1828
- result.sort((a, b) => {
1829
- const catCmp = a.category.localeCompare(b.category);
1830
- if (catCmp !== 0) return catCmp;
1831
- const methCmp = (methodOrder[a.method] ?? 5) - (methodOrder[b.method] ?? 5);
1832
- if (methCmp !== 0) return methCmp;
1833
- return a.path.localeCompare(b.path);
1834
- });
1835
- cachedRouteList = result;
1836
- return result;
1837
- } catch (error) {
1838
- console.error("Failed to inspect routes:", error);
1839
- return [];
1840
- }
1841
- }
1842
-
1843
- exports.CACHE_CONFIGS = CACHE_CONFIGS;
1844
- exports.CATEGORY_INFO = CATEGORY_INFO;
1845
- exports.CacheService = CacheService;
1846
- exports.Logger = Logger;
1847
- exports.SettingsService = SettingsService;
1848
- exports.TelemetryService = TelemetryService;
1849
- exports.apiTokens = apiTokens;
1850
- exports.buildRouteList = buildRouteList;
1851
- exports.collections = collections;
1852
- exports.content = content;
1853
- exports.contentVersions = contentVersions;
1854
- exports.createInstallationIdentity = createInstallationIdentity;
1855
- exports.getAppInstance = getAppInstance;
1856
- exports.getCacheService = getCacheService;
1857
- exports.getLogger = getLogger;
1858
- exports.getTelemetryService = getTelemetryService;
1859
- exports.initLogger = initLogger;
1860
- exports.initTelemetry = initTelemetry;
1861
- exports.insertCollectionSchema = insertCollectionSchema;
1862
- exports.insertContentSchema = insertContentSchema;
1863
- exports.insertLogConfigSchema = insertLogConfigSchema;
1864
- exports.insertMediaSchema = insertMediaSchema;
1865
- exports.insertPluginActivityLogSchema = insertPluginActivityLogSchema;
1866
- exports.insertPluginAssetSchema = insertPluginAssetSchema;
1867
- exports.insertPluginHookSchema = insertPluginHookSchema;
1868
- exports.insertPluginRouteSchema = insertPluginRouteSchema;
1869
- exports.insertPluginSchema = insertPluginSchema;
1870
- exports.insertSystemLogSchema = insertSystemLogSchema;
1871
- exports.insertUserSchema = insertUserSchema;
1872
- exports.insertWorkflowHistorySchema = insertWorkflowHistorySchema;
1873
- exports.logConfig = logConfig;
1874
- exports.media = media;
1875
- exports.pluginActivityLog = pluginActivityLog;
1876
- exports.pluginAssets = pluginAssets;
1877
- exports.pluginHooks = pluginHooks;
1878
- exports.pluginRoutes = pluginRoutes;
1879
- exports.plugins = plugins;
1880
- exports.schema_exports = schema_exports;
1881
- exports.selectCollectionSchema = selectCollectionSchema;
1882
- exports.selectContentSchema = selectContentSchema;
1883
- exports.selectLogConfigSchema = selectLogConfigSchema;
1884
- exports.selectMediaSchema = selectMediaSchema;
1885
- exports.selectPluginActivityLogSchema = selectPluginActivityLogSchema;
1886
- exports.selectPluginAssetSchema = selectPluginAssetSchema;
1887
- exports.selectPluginHookSchema = selectPluginHookSchema;
1888
- exports.selectPluginRouteSchema = selectPluginRouteSchema;
1889
- exports.selectPluginSchema = selectPluginSchema;
1890
- exports.selectSystemLogSchema = selectSystemLogSchema;
1891
- exports.selectUserSchema = selectUserSchema;
1892
- exports.selectWorkflowHistorySchema = selectWorkflowHistorySchema;
1893
- exports.setAppInstance = setAppInstance;
1894
- exports.systemLogs = systemLogs;
1895
- exports.users = users;
1896
- exports.workflowHistory = workflowHistory;
1897
- //# sourceMappingURL=chunk-WAEQXGCX.cjs.map
1898
- //# sourceMappingURL=chunk-WAEQXGCX.cjs.map