opacacms 0.1.1 → 0.1.2

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 (212) hide show
  1. package/package.json +36 -1
  2. package/bun.lock +0 -34
  3. package/global.d.ts +0 -11
  4. package/src/admin/api-client.ts +0 -63
  5. package/src/admin/auth-client.ts +0 -40
  6. package/src/admin/custom-field.ts +0 -179
  7. package/src/admin/index.ts +0 -15
  8. package/src/admin/react.tsx +0 -72
  9. package/src/admin/router.ts +0 -9
  10. package/src/admin/stores/admin-queries.ts +0 -121
  11. package/src/admin/stores/auth.ts +0 -61
  12. package/src/admin/stores/column-visibility.ts +0 -67
  13. package/src/admin/stores/config.ts +0 -15
  14. package/src/admin/stores/media.ts +0 -95
  15. package/src/admin/stores/query.ts +0 -13
  16. package/src/admin/stores/ui.ts +0 -29
  17. package/src/admin/ui/admin-client.tsx +0 -283
  18. package/src/admin/ui/admin-layout.tsx +0 -276
  19. package/src/admin/ui/components/ColumnVisibilityToggle.tsx +0 -141
  20. package/src/admin/ui/components/DataDetailSheet.tsx +0 -141
  21. package/src/admin/ui/components/DataDetailView.tsx +0 -175
  22. package/src/admin/ui/components/Table.tsx +0 -67
  23. package/src/admin/ui/components/fields/ArrayField.tsx +0 -166
  24. package/src/admin/ui/components/fields/BlocksField.tsx +0 -202
  25. package/src/admin/ui/components/fields/BooleanField.tsx +0 -50
  26. package/src/admin/ui/components/fields/CollapsibleField.tsx +0 -75
  27. package/src/admin/ui/components/fields/DateField.tsx +0 -45
  28. package/src/admin/ui/components/fields/FileField.tsx +0 -322
  29. package/src/admin/ui/components/fields/GroupField.tsx +0 -50
  30. package/src/admin/ui/components/fields/JoinField.tsx +0 -23
  31. package/src/admin/ui/components/fields/NumberField.tsx +0 -46
  32. package/src/admin/ui/components/fields/RadioField.tsx +0 -62
  33. package/src/admin/ui/components/fields/RelationshipField.tsx +0 -278
  34. package/src/admin/ui/components/fields/RowField.tsx +0 -40
  35. package/src/admin/ui/components/fields/SelectField.tsx +0 -59
  36. package/src/admin/ui/components/fields/TabsField.tsx +0 -101
  37. package/src/admin/ui/components/fields/TextAreaField.tsx +0 -54
  38. package/src/admin/ui/components/fields/TextField.tsx +0 -49
  39. package/src/admin/ui/components/fields/VirtualField.tsx +0 -53
  40. package/src/admin/ui/components/fields/index.tsx +0 -371
  41. package/src/admin/ui/components/fields/richtext-editor/index.tsx +0 -211
  42. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +0 -142
  43. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +0 -95
  44. package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +0 -226
  45. package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +0 -16
  46. package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +0 -184
  47. package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +0 -240
  48. package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +0 -40
  49. package/src/admin/ui/components/fields/utils.ts +0 -1
  50. package/src/admin/ui/components/link.tsx +0 -41
  51. package/src/admin/ui/components/media/AssetManagerModal.tsx +0 -334
  52. package/src/admin/ui/components/toast.tsx +0 -72
  53. package/src/admin/ui/components/ui/accordion.tsx +0 -51
  54. package/src/admin/ui/components/ui/alert-dialog.tsx +0 -98
  55. package/src/admin/ui/components/ui/blocks.tsx +0 -32
  56. package/src/admin/ui/components/ui/breadcrumbs.tsx +0 -59
  57. package/src/admin/ui/components/ui/button.tsx +0 -26
  58. package/src/admin/ui/components/ui/collapsible.tsx +0 -124
  59. package/src/admin/ui/components/ui/dialog.tsx +0 -79
  60. package/src/admin/ui/components/ui/group.tsx +0 -20
  61. package/src/admin/ui/components/ui/index.ts +0 -17
  62. package/src/admin/ui/components/ui/input.tsx +0 -12
  63. package/src/admin/ui/components/ui/join.tsx +0 -53
  64. package/src/admin/ui/components/ui/label.tsx +0 -11
  65. package/src/admin/ui/components/ui/radio-group.tsx +0 -75
  66. package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +0 -122
  67. package/src/admin/ui/components/ui/relationship.tsx +0 -58
  68. package/src/admin/ui/components/ui/scroll-area.tsx +0 -19
  69. package/src/admin/ui/components/ui/select.tsx +0 -187
  70. package/src/admin/ui/components/ui/separator.tsx +0 -21
  71. package/src/admin/ui/components/ui/sheet.tsx +0 -106
  72. package/src/admin/ui/components/ui/tabs.tsx +0 -116
  73. package/src/admin/ui/components/ui/utils.ts +0 -3
  74. package/src/admin/ui/hooks/use-debounce.ts +0 -15
  75. package/src/admin/ui/styles/_locale-switcher.scss +0 -33
  76. package/src/admin/ui/styles/accordion.scss +0 -60
  77. package/src/admin/ui/styles/animations.scss +0 -41
  78. package/src/admin/ui/styles/asset-manager.scss +0 -547
  79. package/src/admin/ui/styles/badge.scss +0 -13
  80. package/src/admin/ui/styles/base.scss +0 -22
  81. package/src/admin/ui/styles/button.scss +0 -161
  82. package/src/admin/ui/styles/card.scss +0 -13
  83. package/src/admin/ui/styles/collapsible.scss +0 -75
  84. package/src/admin/ui/styles/data-detail.scss +0 -92
  85. package/src/admin/ui/styles/dialog.scss +0 -102
  86. package/src/admin/ui/styles/empty-state.scss +0 -22
  87. package/src/admin/ui/styles/group.scss +0 -19
  88. package/src/admin/ui/styles/index.scss +0 -33
  89. package/src/admin/ui/styles/input.scss +0 -80
  90. package/src/admin/ui/styles/label.scss +0 -12
  91. package/src/admin/ui/styles/layout.scss +0 -56
  92. package/src/admin/ui/styles/lexical.scss +0 -469
  93. package/src/admin/ui/styles/loading.scss +0 -102
  94. package/src/admin/ui/styles/media-registry.scss +0 -597
  95. package/src/admin/ui/styles/pagination.scss +0 -20
  96. package/src/admin/ui/styles/radio-group.scss +0 -66
  97. package/src/admin/ui/styles/row.scss +0 -17
  98. package/src/admin/ui/styles/scrollbar.scss +0 -36
  99. package/src/admin/ui/styles/select.scss +0 -121
  100. package/src/admin/ui/styles/separator.scss +0 -14
  101. package/src/admin/ui/styles/sheet.scss +0 -152
  102. package/src/admin/ui/styles/sidebar.scss +0 -148
  103. package/src/admin/ui/styles/switch.scss +0 -59
  104. package/src/admin/ui/styles/table.scss +0 -207
  105. package/src/admin/ui/styles/tabs.scss +0 -62
  106. package/src/admin/ui/styles/toast.scss +0 -45
  107. package/src/admin/ui/styles/variables.scss +0 -24
  108. package/src/admin/ui/views/collection-list-view.tsx +0 -720
  109. package/src/admin/ui/views/dashboard-view.tsx +0 -263
  110. package/src/admin/ui/views/document-edit-view.tsx +0 -384
  111. package/src/admin/ui/views/global-edit-view.tsx +0 -226
  112. package/src/admin/ui/views/init-view.tsx +0 -182
  113. package/src/admin/ui/views/login-view.tsx +0 -123
  114. package/src/admin/ui/views/media-registry-view.tsx +0 -1104
  115. package/src/admin/ui/views/settings-view.tsx +0 -729
  116. package/src/admin/webcomponent.tsx +0 -15
  117. package/src/auth/index.ts +0 -194
  118. package/src/auth/migrations.ts +0 -87
  119. package/src/auth/premissions.ts +0 -46
  120. package/src/cli/commands/generate-types.ts +0 -116
  121. package/src/cli/commands/init.ts +0 -95
  122. package/src/cli/commands/migrate-commands.ts +0 -160
  123. package/src/cli/commands/seed-command.ts +0 -11
  124. package/src/cli/d1-mock.ts +0 -101
  125. package/src/cli/index.test.ts +0 -84
  126. package/src/cli/index.ts +0 -183
  127. package/src/cli/r2-mock.ts +0 -217
  128. package/src/cli/seeding.ts +0 -409
  129. package/src/client.ts +0 -181
  130. package/src/config-utils.ts +0 -102
  131. package/src/config.ts +0 -49
  132. package/src/db/adapter.ts +0 -53
  133. package/src/db/better-sqlite.ts +0 -630
  134. package/src/db/bun-sqlite.ts +0 -646
  135. package/src/db/d1.ts +0 -711
  136. package/src/db/index.ts +0 -2
  137. package/src/db/kysely/data-mapper.ts +0 -142
  138. package/src/db/kysely/field-mapper.ts +0 -148
  139. package/src/db/kysely/migration-generator.ts +0 -223
  140. package/src/db/kysely/query-builder.ts +0 -92
  141. package/src/db/kysely/schema-builder.ts +0 -439
  142. package/src/db/kysely/sql-utils.ts +0 -13
  143. package/src/db/migration.ts +0 -40
  144. package/src/db/postgres.ts +0 -621
  145. package/src/db/sqlite.ts +0 -658
  146. package/src/db/system-schema.ts +0 -121
  147. package/src/index.ts +0 -11
  148. package/src/runtimes/README.md +0 -59
  149. package/src/runtimes/bun.ts +0 -49
  150. package/src/runtimes/cloudflare-workers.ts +0 -38
  151. package/src/runtimes/next.ts +0 -26
  152. package/src/runtimes/node.ts +0 -52
  153. package/src/schema/collection.ts +0 -184
  154. package/src/schema/fields/base.ts +0 -164
  155. package/src/schema/fields/index.ts +0 -427
  156. package/src/schema/global.ts +0 -145
  157. package/src/schema/index.ts +0 -4
  158. package/src/schema/infer.ts +0 -72
  159. package/src/server/admin-router.ts +0 -20
  160. package/src/server/admin.ts +0 -142
  161. package/src/server/assets.ts +0 -306
  162. package/src/server/collection-router.ts +0 -55
  163. package/src/server/handlers.ts +0 -722
  164. package/src/server/middlewares/admin.ts +0 -27
  165. package/src/server/middlewares/auth.ts +0 -89
  166. package/src/server/middlewares/context.ts +0 -17
  167. package/src/server/middlewares/cors.ts +0 -24
  168. package/src/server/middlewares/database-init.ts +0 -74
  169. package/src/server/middlewares/rate-limit.ts +0 -71
  170. package/src/server/router.ts +0 -47
  171. package/src/server/setup-middlewares.ts +0 -58
  172. package/src/server/system-router.ts +0 -35
  173. package/src/server.ts +0 -9
  174. package/src/storage/adapters/cloudflare-r2.ts +0 -136
  175. package/src/storage/adapters/local.ts +0 -146
  176. package/src/storage/adapters/s3.ts +0 -186
  177. package/src/storage/errors.ts +0 -46
  178. package/src/storage/index.ts +0 -6
  179. package/src/storage/types.ts +0 -39
  180. package/src/types.ts +0 -605
  181. package/src/utils/lexical.ts +0 -37
  182. package/src/utils/logger.ts +0 -73
  183. package/src/validation.ts +0 -429
  184. package/src/validator.ts +0 -179
  185. package/test/admin-custom-field.test.ts +0 -162
  186. package/test/admin-react-field.test.tsx +0 -134
  187. package/test/api-features.test.ts +0 -78
  188. package/test/api.test.ts +0 -178
  189. package/test/auth.test.ts +0 -62
  190. package/test/cli-integration.test.ts +0 -148
  191. package/test/cli.test.ts +0 -25
  192. package/test/db/postgres.test.ts +0 -95
  193. package/test/db/sqlite-filter.test.ts +0 -53
  194. package/test/db/sqlite.test.ts +0 -82
  195. package/test/engine-features.test.ts +0 -79
  196. package/test/globals.test.ts +0 -74
  197. package/test/integration-tmp/db-app/opacacms.config.ts +0 -15
  198. package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +0 -25
  199. package/test/integration-tmp/my-test-app/index.ts +0 -8
  200. package/test/integration-tmp/my-test-app/opacacms.config.ts +0 -16
  201. package/test/integration-tmp/my-test-app/package.json +0 -12
  202. package/test/populate.test.ts +0 -79
  203. package/test/runtimes.test.ts +0 -43
  204. package/test/schema-builder.test.ts +0 -107
  205. package/test/schema-features.test.ts +0 -63
  206. package/test/seeding.test.ts +0 -68
  207. package/test/storage/local.test.ts +0 -72
  208. package/test/storage/s3.test.ts +0 -60
  209. package/test/structural-data.test.ts +0 -100
  210. package/test/test-setup.ts +0 -11
  211. package/test/validation.test.ts +0 -162
  212. package/tsconfig.json +0 -42
package/src/db/index.ts DELETED
@@ -1,2 +0,0 @@
1
- export * from "./adapter";
2
- export * from "./migration";
@@ -1,142 +0,0 @@
1
- import { toSnakeCase } from "./field-mapper";
2
-
3
- /**
4
- * Converts a snake_case string to camelCase.
5
- */
6
- export function toCamelCase(str: string): string {
7
- if (str.startsWith("_")) return str; // Keep system prefixes
8
- return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
9
- }
10
-
11
- export function flattenPayload(payload: any, prefix = "", excludeKeys: string[] = []): any {
12
- if (typeof payload !== "object" || payload === null || Array.isArray(payload)) return payload;
13
- const result: any = {};
14
-
15
- for (const key in payload) {
16
- if (Object.hasOwn(payload, key)) {
17
- const value = payload[key];
18
- if (value === undefined) continue;
19
-
20
- // Do not flatten Date objects or arrays
21
- if (
22
- typeof value === "object" &&
23
- value !== null &&
24
- !Array.isArray(value) &&
25
- !(value instanceof Date) &&
26
- !excludeKeys.includes(key)
27
- ) {
28
- // Only flatten objects that aren't system keys (like _access)
29
- if (key.startsWith("_") && prefix === "") {
30
- result[key] = value;
31
- } else {
32
- // It's a group, flatten it
33
- const flatNested = flattenPayload(value, `${prefix}${key}__`);
34
- Object.assign(result, flatNested);
35
- }
36
- } else {
37
- if (value === undefined) continue;
38
- // IMPORTANT: Convert column name to snake_case when saving
39
- const colName = `${prefix}${toSnakeCase(key)}`;
40
-
41
- // Serialize arrays and objects to JSON strings for SQLite/D1
42
- if (typeof value === "object" && value !== null) {
43
- result[colName] = JSON.stringify(value);
44
- } else {
45
- result[colName] = value;
46
- }
47
- }
48
- }
49
- }
50
- return result;
51
- }
52
-
53
- export function unflattenRow(row: any): any {
54
- if (typeof row !== "object" || row === null || Array.isArray(row)) return row;
55
- const result: any = {};
56
-
57
- for (const key in row) {
58
- if (Object.hasOwn(row, key)) {
59
- let value = row[key];
60
-
61
- // Try to parse JSON strings back to objects/arrays
62
- if (typeof value === "string") {
63
- const trimmed = value.trim();
64
- if (
65
- (trimmed.startsWith("[") && trimmed.endsWith("]")) ||
66
- (trimmed.startsWith("{") && trimmed.endsWith("}"))
67
- ) {
68
- try {
69
- value = JSON.parse(value);
70
- } catch (e) {
71
- // Not valid JSON, keep as string
72
- }
73
- }
74
- }
75
-
76
- // If it's a direct match for timestamps or system fields, keep as is
77
- if (
78
- key === "created_at" ||
79
- key === "updated_at" ||
80
- key === "createdAt" ||
81
- key === "updatedAt"
82
- ) {
83
- if (typeof value === "string" && !value.includes("T") && value.includes(" ")) {
84
- // Normalize SQLite/D1 "YYYY-MM-DD HH:MM:SS" to ISO "YYYY-MM-DDTHH:MM:SSZ"
85
- value = `${value.replace(" ", "T")}Z`;
86
- }
87
- result[toCamelCase(key)] = value;
88
- continue;
89
- }
90
-
91
- if (key.startsWith("_")) {
92
- result[key] = value;
93
- continue;
94
- }
95
-
96
- const parts = key.split("__");
97
- if (parts.length === 1) {
98
- result[toCamelCase(key)] = value;
99
- continue;
100
- }
101
-
102
- // Try to unflatten, but detect collisions (e.g., "email" vs "email_verified")
103
- let current = result;
104
- let collision = false;
105
- const path: any[] = [];
106
-
107
- for (let i = 0; i < parts.length - 1; i++) {
108
- const part = toCamelCase(parts[i]!);
109
- if (
110
- current[part] !== undefined &&
111
- (typeof current[part] !== "object" || current[part] === null)
112
- ) {
113
- collision = true;
114
- break;
115
- }
116
- path.push({ obj: current, key: part });
117
- if (!current[part]) {
118
- current[part] = {};
119
- }
120
- current = current[part];
121
- }
122
-
123
- if (!collision) {
124
- const lastPart = toCamelCase(parts[parts.length - 1]!);
125
- if (current[lastPart] !== undefined && typeof current[lastPart] === "object") {
126
- collision = true;
127
- } else {
128
- current[lastPart] = value;
129
- }
130
- }
131
-
132
- if (collision) {
133
- // If we hit a collision, we must undo any structural changes made for this key
134
- // and just use the full camelCase key at the root.
135
- // Actually, just setting it at the root is mostly safe as long as we don't leave
136
- // empty objects that shouldn't be there. But for simplicity and robustness:
137
- result[toCamelCase(key)] = value;
138
- }
139
- }
140
- }
141
- return result;
142
- }
@@ -1,148 +0,0 @@
1
- import type { Field } from "../../types";
2
-
3
- export function toSnakeCase(str: string): string {
4
- return str
5
- .replace(/([A-Z])/g, "_$1")
6
- .toLowerCase()
7
- .replace(/^_/, "");
8
- }
9
-
10
- /**
11
- * Maps an OpacaCMS FieldType to a Kysely column data type for PostgreSQL.
12
- */
13
- export function mapFieldToPostgresType(field: Field): string {
14
- switch (field.type) {
15
- case "text":
16
- case "richtext":
17
- case "select":
18
- case "radio":
19
- case "relationship":
20
- return "text";
21
- case "number":
22
- return "double precision";
23
- case "boolean":
24
- return "boolean";
25
- case "date":
26
- return "timestamp with time zone";
27
- case "json":
28
- case "file":
29
- return "jsonb";
30
- default:
31
- return "text";
32
- }
33
- }
34
-
35
- /**
36
- * Maps an OpacaCMS FieldType to a Kysely column data type for SQLite/D1.
37
- */
38
- export function mapFieldToSQLiteType(field: Field): string {
39
- switch (field.type) {
40
- case "text":
41
- case "richtext":
42
- case "select":
43
- case "radio":
44
- case "relationship":
45
- case "date": // SQLite stores dates as text
46
- case "json":
47
- case "file":
48
- return "text";
49
- case "number":
50
- return "numeric";
51
- case "boolean":
52
- return "integer"; // 0 or 1
53
- default:
54
- return "text";
55
- }
56
- }
57
-
58
- /**
59
- * Recursively flattens a field list, collecting only fields with a 'name'.
60
- * This skips layout fields like 'row', 'collapsible', 'tabs' while preserving their nested named fields.
61
- * Group and Blocks fields are also flattened, prefixing their children's names to avoid collisions.
62
- * It explicitly excludes virtual fields like 'join' since they are resolved at runtime.
63
- */
64
- export function flattenFields(fields: Field[], prefix = ""): Field[] {
65
- const result: Field[] = [];
66
-
67
- for (const field of fields) {
68
- if (field.type === "join" || field.type === "virtual") continue;
69
-
70
- const currentName = field.name ? `${prefix}${field.name}` : undefined;
71
-
72
- if (field.type === "group") {
73
- if (field.fields && Array.isArray(field.fields)) {
74
- const nextPrefix = currentName ? `${currentName}__` : "";
75
- result.push(...flattenFields(field.fields, nextPrefix));
76
- }
77
- continue;
78
- }
79
-
80
- if (field.type === "blocks") {
81
- continue;
82
- }
83
-
84
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
85
- continue;
86
- }
87
-
88
- if (currentName) {
89
- result.push({ ...field, name: currentName });
90
- }
91
-
92
- if (field.type === "row" || field.type === "collapsible") {
93
- if (field.fields && Array.isArray(field.fields)) {
94
- result.push(...flattenFields(field.fields, prefix));
95
- }
96
- }
97
-
98
- if (field.type === "tabs" && field.tabs && Array.isArray(field.tabs)) {
99
- for (const tab of field.tabs) {
100
- if (tab.fields && Array.isArray(tab.fields)) {
101
- result.push(...flattenFields(tab.fields, prefix));
102
- }
103
- }
104
- }
105
- }
106
-
107
- return result;
108
- }
109
-
110
- /**
111
- * Recursively find all relational fields (relationship with hasMany or blocks).
112
- * This is used by adapters to fetch related data during findOne/find.
113
- */
114
- export function getRelationalFields(fields: Field[], prefix = ""): Field[] {
115
- const result: Field[] = [];
116
-
117
- for (const field of fields) {
118
- const currentName = field.name ? `${prefix}${field.name}` : undefined;
119
-
120
- if (
121
- (field.type === "relationship" && "hasMany" in field && field.hasMany) ||
122
- field.type === "blocks"
123
- ) {
124
- if (currentName) {
125
- result.push({ ...field, name: currentName });
126
- }
127
- continue;
128
- }
129
-
130
- if (field.type === "group" || field.type === "row" || field.type === "collapsible") {
131
- if (field.fields && Array.isArray(field.fields)) {
132
- const nextPrefix = field.type === "group" && field.name ? `${currentName}__` : prefix;
133
- result.push(...getRelationalFields(field.fields, nextPrefix));
134
- }
135
- continue;
136
- }
137
-
138
- if (field.type === "tabs" && field.tabs && Array.isArray(field.tabs)) {
139
- for (const tab of field.tabs) {
140
- if (tab.fields && Array.isArray(tab.fields)) {
141
- result.push(...getRelationalFields(tab.fields, prefix));
142
- }
143
- }
144
- }
145
- }
146
-
147
- return result;
148
- }
@@ -1,223 +0,0 @@
1
- import type { Collection, Global } from "../../types";
2
- import {
3
- flattenFields,
4
- mapFieldToPostgresType,
5
- mapFieldToSQLiteType,
6
- toSnakeCase,
7
- } from "./field-mapper";
8
-
9
- /**
10
- * Generates Kysely migration code for 'up' and 'down' functions based on schema definitions.
11
- */
12
- export function generateMigrationCode(
13
- collections: Collection[],
14
- globals: Global[] = [],
15
- dialect: "postgres" | "sqlite" | "d1",
16
- ): string {
17
- const allSchemas = [...collections, ...globals];
18
- const mapType = dialect === "postgres" ? mapFieldToPostgresType : mapFieldToSQLiteType;
19
- const tsType = dialect === "postgres" ? "timestamp with time zone" : "text";
20
-
21
- let upCode = "";
22
- let downCode = "";
23
-
24
- for (const collection of allSchemas) {
25
- const slug = collection.slug;
26
- const flattenedFields = flattenFields(collection.fields);
27
-
28
- // Main Table
29
- upCode += ` await db.schema.createTable('${slug}')\n`;
30
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
31
-
32
- for (const field of flattenedFields) {
33
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
34
- const colName = toSnakeCase(field.name!);
35
- if (colName === "id") continue;
36
-
37
- const colType = mapType(field);
38
- const constraints: string[] = [];
39
- if (field.required) constraints.push("notNull()");
40
- if (field.unique) constraints.push("unique()");
41
-
42
- if (field.defaultValue !== undefined) {
43
- let val = field.defaultValue;
44
- if (typeof val === "string") {
45
- val = `'${val}'`;
46
- } else if (typeof val === "boolean") {
47
- val = dialect === "sqlite" || dialect === "d1" ? (val ? 1 : 0) : val;
48
- }
49
- constraints.push(`defaultTo(${val})`);
50
- }
51
-
52
- const constraintChain = constraints.length > 0 ? `.${constraints.join(".")}` : "";
53
- upCode += ` .addColumn('${colName}', '${colType}', (col) => col${constraintChain})\n`;
54
- }
55
-
56
- // Timestamps
57
- const ts = (collection as any).timestamps !== false;
58
- if (ts) {
59
- const config =
60
- typeof (collection as any).timestamps === "object" ? (collection as any).timestamps : {};
61
- const createdField = toSnakeCase(config.createdAt || "createdAt");
62
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
63
- upCode += ` .addColumn('${createdField}', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))\n`;
64
- upCode += ` .addColumn('${updatedField}', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))\n`;
65
- }
66
- upCode += ` .execute();\n\n`;
67
-
68
- downCode = ` await db.schema.dropTable('${slug}').execute();\n` + downCode;
69
-
70
- // Join Tables
71
- for (const field of flattenedFields) {
72
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
73
- const colName = toSnakeCase(field.name!);
74
- const joinTableName = `${slug}_${colName}_relations`.toLowerCase();
75
- upCode += ` await db.schema.createTable('${joinTableName}')\n`;
76
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
77
- upCode += ` .addColumn('source_id', 'text', (col) => col.notNull())\n`;
78
- upCode += ` .addColumn('target_id', 'text', (col) => col.notNull())\n`;
79
- upCode += ` .addColumn('order', 'integer', (col) => col.defaultTo(0))\n`;
80
- upCode += ` .execute();\n\n`;
81
-
82
- downCode = ` await db.schema.dropTable('${joinTableName}').execute();\n` + downCode;
83
- }
84
- }
85
-
86
- // Block Tables
87
- for (const field of collection.fields) {
88
- if (field.type === "blocks" && field.blocks && Array.isArray(field.blocks)) {
89
- for (const block of field.blocks) {
90
- const blockName = toSnakeCase(field.name!);
91
- const blockTableName = `${slug}_${blockName}_${block.slug}`.toLowerCase();
92
-
93
- upCode += ` await db.schema.createTable('${blockTableName}')\n`;
94
- upCode += ` .addColumn('id', 'text', (col) => col.primaryKey())\n`;
95
- upCode += ` .addColumn('_parent_id', 'text', (col) => col.notNull())\n`;
96
- upCode += ` .addColumn('_order', 'integer', (col) => col.defaultTo(0))\n`;
97
- upCode += ` .addColumn('block_type', 'text', (col) => col.notNull())\n`;
98
-
99
- const blockFlattened = flattenFields(block.fields);
100
- for (const bField of blockFlattened) {
101
- const bColName = toSnakeCase(bField.name!);
102
- if (bColName === "id") continue;
103
- const bColType = mapType(bField);
104
-
105
- const bConstraints: string[] = [];
106
- if (bField.required) bConstraints.push("notNull()");
107
- if (bField.unique) bConstraints.push("unique()");
108
- if (bField.defaultValue !== undefined) {
109
- let bVal = bField.defaultValue;
110
- if (typeof bVal === "string") bVal = `'${bVal}'`;
111
- else if (typeof bVal === "boolean")
112
- bVal = dialect === "sqlite" || dialect === "d1" ? (bVal ? 1 : 0) : bVal;
113
- bConstraints.push(`defaultTo(${bVal})`);
114
- }
115
-
116
- const bConstraintChain = bConstraints.length > 0 ? `.${bConstraints.join(".")}` : "";
117
- upCode += ` .addColumn('${bColName}', '${bColType}', (col) => col${bConstraintChain})\n`;
118
- }
119
- upCode += ` .addColumn('created_at', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))\n`;
120
- upCode += ` .addColumn('updated_at', '${tsType}', (col) => col.defaultTo('CURRENT_TIMESTAMP'))\n`;
121
- upCode += ` .execute();\n\n`;
122
-
123
- downCode = ` await db.schema.dropTable('${blockTableName}').execute();\n` + downCode;
124
- }
125
- }
126
- }
127
- }
128
-
129
- return `import type { OpacaMigrationDb } from 'opacacms/db';
130
-
131
- export async function up(db: OpacaMigrationDb): Promise<void> {
132
- ${upCode}}
133
-
134
- export async function down(db: OpacaMigrationDb): Promise<void> {
135
- ${downCode}}
136
- `;
137
- }
138
-
139
- /**
140
- * Generates raw SQL migration code for Cloudflare D1.
141
- */
142
- export function generateSQLCode(collections: Collection[], globals: Global[] = []): string {
143
- const allSchemas = [...collections, ...globals];
144
- let sql = "-- OpacaCMS Auto-generated SQL Migration\n\n";
145
-
146
- for (const collection of allSchemas) {
147
- const slug = collection.slug;
148
- const flattenedFields = flattenFields(collection.fields);
149
-
150
- sql += `CREATE TABLE IF NOT EXISTS "${slug}" (\n`;
151
- sql += ` "id" TEXT PRIMARY KEY`;
152
-
153
- for (const field of flattenedFields) {
154
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
155
- const colName = toSnakeCase(field.name!);
156
- if (colName === "id") continue;
157
-
158
- const colType = mapFieldToSQLiteType(field);
159
- sql += `,\n "${colName}" ${colType.toUpperCase()}`;
160
- if (field.required) sql += " NOT NULL";
161
- if (field.unique) sql += " UNIQUE";
162
- if (field.defaultValue !== undefined) {
163
- let val = field.defaultValue;
164
- if (typeof val === "string") val = `'${val}'`;
165
- else if (typeof val === "boolean") val = val ? 1 : 0;
166
- sql += ` DEFAULT ${val}`;
167
- }
168
- }
169
-
170
- const ts = (collection as any).timestamps !== false;
171
- if (ts) {
172
- const config =
173
- typeof (collection as any).timestamps === "object" ? (collection as any).timestamps : {};
174
- const createdField = toSnakeCase(config.createdAt || "createdAt");
175
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
176
- sql += `,\n "${createdField}" TEXT DEFAULT CURRENT_TIMESTAMP`;
177
- sql += `,\n "${updatedField}" TEXT DEFAULT CURRENT_TIMESTAMP`;
178
- }
179
- sql += "\n);\n\n";
180
-
181
- // Join Tables
182
- for (const field of flattenedFields) {
183
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
184
- const colName = toSnakeCase(field.name!);
185
- const joinTableName = `${slug}_${colName}_relations`.toLowerCase();
186
- sql += `CREATE TABLE IF NOT EXISTS "${joinTableName}" (\n`;
187
- sql += ` "id" TEXT PRIMARY KEY,\n`;
188
- sql += ` "source_id" TEXT NOT NULL,\n`;
189
- sql += ` "target_id" TEXT NOT NULL,\n`;
190
- sql += ` "order" INTEGER DEFAULT 0\n`;
191
- sql += `);\n\n`;
192
- }
193
- }
194
-
195
- // Block Tables
196
- for (const field of collection.fields) {
197
- if (field.type === "blocks" && field.blocks && Array.isArray(field.blocks)) {
198
- for (const block of field.blocks) {
199
- const blockName = toSnakeCase(field.name!);
200
- const blockTableName = `${slug}_${blockName}_${block.slug}`.toLowerCase();
201
- sql += `CREATE TABLE IF NOT EXISTS "${blockTableName}" (\n`;
202
- sql += ` "id" TEXT PRIMARY KEY,\n`;
203
- sql += ` "_parent_id" TEXT NOT NULL,\n`;
204
- sql += ` "_order" INTEGER DEFAULT 0,\n`;
205
- sql += ` "block_type" TEXT NOT NULL`;
206
-
207
- const blockFlattened = flattenFields(block.fields);
208
- for (const bField of blockFlattened) {
209
- const bColName = toSnakeCase(bField.name!);
210
- if (bColName === "id") continue;
211
- const bColType = mapFieldToSQLiteType(bField);
212
- sql += `,\n "${bColName}" ${bColType.toUpperCase()}`;
213
- }
214
- sql += `,\n "created_at" TEXT DEFAULT CURRENT_TIMESTAMP,\n`;
215
- sql += ` "updated_at" TEXT DEFAULT CURRENT_TIMESTAMP\n`;
216
- sql += `);\n\n`;
217
- }
218
- }
219
- }
220
- }
221
-
222
- return sql;
223
- }
@@ -1,92 +0,0 @@
1
- import type { ExpressionBuilder } from "kysely";
2
-
3
- /**
4
- * Builds a Kysely expression from a generic query object.
5
- *
6
- * @param eb The Kysely ExpressionBuilder (e.g., from .where((eb) => buildKyselyWhere(eb, query)))
7
- * @param query The query object (e.g., { age: { gt: 18 }, name: 'John' })
8
- * @returns A single Expression combining all conditions with AND, or undefined.
9
- */
10
- export function buildKyselyWhere(
11
- eb: ExpressionBuilder<any, any>,
12
- query: Record<string, any> | undefined,
13
- ): any {
14
- if (!query || Object.keys(query).length === 0) return undefined;
15
-
16
- const conditions: any[] = [];
17
-
18
- for (const [key, value] of Object.entries(query)) {
19
- if (value === undefined) continue;
20
-
21
- if (key === "or" && Array.isArray(value)) {
22
- const orConditions = value.map((v) => buildKyselyWhere(eb, v)).filter((c) => c !== undefined);
23
- if (orConditions.length > 0) {
24
- conditions.push(eb.or(orConditions));
25
- }
26
- continue;
27
- }
28
-
29
- if (key === "and" && Array.isArray(value)) {
30
- const andConditions = value
31
- .map((v) => buildKyselyWhere(eb, v))
32
- .filter((c) => c !== undefined);
33
- if (andConditions.length > 0) {
34
- conditions.push(eb.and(andConditions));
35
- }
36
- continue;
37
- }
38
-
39
- if (
40
- typeof value === "object" &&
41
- value !== null &&
42
- !Array.isArray(value) &&
43
- !(value instanceof Date)
44
- ) {
45
- for (const [op, val] of Object.entries(value)) {
46
- if (val === undefined) continue;
47
- switch (op) {
48
- case "gt":
49
- conditions.push(eb(key, ">", val));
50
- break;
51
- case "gte":
52
- conditions.push(eb(key, ">=", val));
53
- break;
54
- case "lt":
55
- conditions.push(eb(key, "<", val));
56
- break;
57
- case "lte":
58
- conditions.push(eb(key, "<=", val));
59
- break;
60
- case "like":
61
- conditions.push(eb(key, "like", String(val)));
62
- break;
63
- case "ne":
64
- if (val === null) conditions.push(eb(key, "is not", null));
65
- else conditions.push(eb(key, "!=", val));
66
- break;
67
- case "in":
68
- if (Array.isArray(val)) conditions.push(eb(key, "in", val));
69
- break;
70
- case "is":
71
- if (val === null) conditions.push(eb(key, "is", null));
72
- break;
73
- default:
74
- if (val === null) conditions.push(eb(key, "is", null));
75
- else conditions.push(eb(key, "=", val));
76
- break;
77
- }
78
- }
79
- } else {
80
- if (value === null) {
81
- conditions.push(eb(key, "is", null));
82
- } else {
83
- conditions.push(eb(key, "=", value));
84
- }
85
- }
86
- }
87
-
88
- if (conditions.length === 0) return undefined;
89
- if (conditions.length === 1) return conditions[0];
90
-
91
- return eb.and(conditions);
92
- }