opacacms 0.1.0 → 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 (247) hide show
  1. package/dist/admin/index.js +49 -0
  2. package/dist/{chunk-2zm8cy1w.js → admin/webcomponent.js} +116 -168
  3. package/dist/{chunk-6dhs73zq.js → chunk-2yz1nsxs.js} +1 -1
  4. package/dist/chunk-fa5mg0hr.js +96 -0
  5. package/dist/{chunk-kwp83w8b.js → chunk-m09hahe2.js} +7 -7
  6. package/dist/{chunk-hmhcense.js → chunk-ry15hke8.js} +253 -4
  7. package/dist/chunk-vtvqfhgy.js +2442 -0
  8. package/dist/{chunk-f3nvxn63.js → chunk-y8hc6nm4.js} +1 -1
  9. package/dist/{src/cli → cli}/index.js +10 -10
  10. package/dist/{src/client.js → client.js} +2 -2
  11. package/dist/{src/db → db}/bun-sqlite.js +10 -10
  12. package/dist/{src/db → db}/d1.js +8 -8
  13. package/dist/db/index.d.ts +2 -0
  14. package/dist/db/index.js +7 -0
  15. package/dist/db/migration.d.ts +39 -0
  16. package/dist/{src/db → db}/postgres.js +10 -10
  17. package/dist/{src/db → db}/sqlite.js +8 -8
  18. package/dist/index.d.ts +0 -2
  19. package/dist/index.js +13 -0
  20. package/dist/{src/runtimes → runtimes}/bun.js +5 -6
  21. package/dist/{src/runtimes → runtimes}/cloudflare-workers.js +5 -6
  22. package/dist/{src/runtimes → runtimes}/next.js +5 -6
  23. package/dist/{src/runtimes → runtimes}/node.js +5 -6
  24. package/dist/{src/server.js → server.js} +7 -8
  25. package/dist/storage/index.d.ts +0 -3
  26. package/dist/storage/index.js +35 -0
  27. package/dist/types.d.ts +5 -2
  28. package/package.json +161 -39
  29. package/bun.lock +0 -34
  30. package/dist/api.d.ts +0 -6
  31. package/dist/chunk-8gkhn1d4.js +0 -309
  32. package/dist/chunk-dy5t83hr.js +0 -261
  33. package/dist/src/admin/index.js +0 -176
  34. package/dist/src/admin/webcomponent.js +0 -19
  35. package/dist/src/api.js +0 -27
  36. package/dist/src/index.js +0 -20
  37. package/dist/src/storage/index.js +0 -355
  38. package/global.d.ts +0 -11
  39. package/src/admin/api-client.ts +0 -63
  40. package/src/admin/auth-client.ts +0 -40
  41. package/src/admin/custom-field.ts +0 -179
  42. package/src/admin/index.ts +0 -15
  43. package/src/admin/react.tsx +0 -72
  44. package/src/admin/router.ts +0 -9
  45. package/src/admin/stores/admin-queries.ts +0 -121
  46. package/src/admin/stores/auth.ts +0 -61
  47. package/src/admin/stores/column-visibility.ts +0 -67
  48. package/src/admin/stores/config.ts +0 -15
  49. package/src/admin/stores/media.ts +0 -95
  50. package/src/admin/stores/query.ts +0 -13
  51. package/src/admin/stores/ui.ts +0 -29
  52. package/src/admin/ui/admin-client.tsx +0 -283
  53. package/src/admin/ui/admin-layout.tsx +0 -276
  54. package/src/admin/ui/components/ColumnVisibilityToggle.tsx +0 -141
  55. package/src/admin/ui/components/DataDetailSheet.tsx +0 -141
  56. package/src/admin/ui/components/DataDetailView.tsx +0 -175
  57. package/src/admin/ui/components/Table.tsx +0 -67
  58. package/src/admin/ui/components/fields/ArrayField.tsx +0 -166
  59. package/src/admin/ui/components/fields/BlocksField.tsx +0 -202
  60. package/src/admin/ui/components/fields/BooleanField.tsx +0 -50
  61. package/src/admin/ui/components/fields/CollapsibleField.tsx +0 -75
  62. package/src/admin/ui/components/fields/DateField.tsx +0 -45
  63. package/src/admin/ui/components/fields/FileField.tsx +0 -322
  64. package/src/admin/ui/components/fields/GroupField.tsx +0 -50
  65. package/src/admin/ui/components/fields/JoinField.tsx +0 -23
  66. package/src/admin/ui/components/fields/NumberField.tsx +0 -46
  67. package/src/admin/ui/components/fields/RadioField.tsx +0 -62
  68. package/src/admin/ui/components/fields/RelationshipField.tsx +0 -278
  69. package/src/admin/ui/components/fields/RowField.tsx +0 -40
  70. package/src/admin/ui/components/fields/SelectField.tsx +0 -59
  71. package/src/admin/ui/components/fields/TabsField.tsx +0 -101
  72. package/src/admin/ui/components/fields/TextAreaField.tsx +0 -54
  73. package/src/admin/ui/components/fields/TextField.tsx +0 -49
  74. package/src/admin/ui/components/fields/VirtualField.tsx +0 -53
  75. package/src/admin/ui/components/fields/index.tsx +0 -371
  76. package/src/admin/ui/components/fields/richtext-editor/index.tsx +0 -211
  77. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +0 -142
  78. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +0 -95
  79. package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +0 -226
  80. package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +0 -16
  81. package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +0 -184
  82. package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +0 -240
  83. package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +0 -40
  84. package/src/admin/ui/components/fields/utils.ts +0 -1
  85. package/src/admin/ui/components/link.tsx +0 -41
  86. package/src/admin/ui/components/media/AssetManagerModal.tsx +0 -334
  87. package/src/admin/ui/components/toast.tsx +0 -72
  88. package/src/admin/ui/components/ui/accordion.tsx +0 -51
  89. package/src/admin/ui/components/ui/alert-dialog.tsx +0 -98
  90. package/src/admin/ui/components/ui/blocks.tsx +0 -32
  91. package/src/admin/ui/components/ui/breadcrumbs.tsx +0 -59
  92. package/src/admin/ui/components/ui/button.tsx +0 -26
  93. package/src/admin/ui/components/ui/collapsible.tsx +0 -124
  94. package/src/admin/ui/components/ui/dialog.tsx +0 -79
  95. package/src/admin/ui/components/ui/group.tsx +0 -20
  96. package/src/admin/ui/components/ui/index.ts +0 -17
  97. package/src/admin/ui/components/ui/input.tsx +0 -12
  98. package/src/admin/ui/components/ui/join.tsx +0 -53
  99. package/src/admin/ui/components/ui/label.tsx +0 -11
  100. package/src/admin/ui/components/ui/radio-group.tsx +0 -75
  101. package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +0 -122
  102. package/src/admin/ui/components/ui/relationship.tsx +0 -58
  103. package/src/admin/ui/components/ui/scroll-area.tsx +0 -19
  104. package/src/admin/ui/components/ui/select.tsx +0 -187
  105. package/src/admin/ui/components/ui/separator.tsx +0 -21
  106. package/src/admin/ui/components/ui/sheet.tsx +0 -106
  107. package/src/admin/ui/components/ui/tabs.tsx +0 -116
  108. package/src/admin/ui/components/ui/utils.ts +0 -3
  109. package/src/admin/ui/hooks/use-debounce.ts +0 -15
  110. package/src/admin/ui/styles/_locale-switcher.scss +0 -33
  111. package/src/admin/ui/styles/accordion.scss +0 -60
  112. package/src/admin/ui/styles/animations.scss +0 -41
  113. package/src/admin/ui/styles/asset-manager.scss +0 -547
  114. package/src/admin/ui/styles/badge.scss +0 -13
  115. package/src/admin/ui/styles/base.scss +0 -22
  116. package/src/admin/ui/styles/button.scss +0 -161
  117. package/src/admin/ui/styles/card.scss +0 -13
  118. package/src/admin/ui/styles/collapsible.scss +0 -75
  119. package/src/admin/ui/styles/data-detail.scss +0 -92
  120. package/src/admin/ui/styles/dialog.scss +0 -102
  121. package/src/admin/ui/styles/empty-state.scss +0 -22
  122. package/src/admin/ui/styles/group.scss +0 -19
  123. package/src/admin/ui/styles/index.scss +0 -33
  124. package/src/admin/ui/styles/input.scss +0 -80
  125. package/src/admin/ui/styles/label.scss +0 -12
  126. package/src/admin/ui/styles/layout.scss +0 -56
  127. package/src/admin/ui/styles/lexical.scss +0 -469
  128. package/src/admin/ui/styles/loading.scss +0 -102
  129. package/src/admin/ui/styles/media-registry.scss +0 -597
  130. package/src/admin/ui/styles/pagination.scss +0 -20
  131. package/src/admin/ui/styles/radio-group.scss +0 -66
  132. package/src/admin/ui/styles/row.scss +0 -17
  133. package/src/admin/ui/styles/scrollbar.scss +0 -36
  134. package/src/admin/ui/styles/select.scss +0 -121
  135. package/src/admin/ui/styles/separator.scss +0 -14
  136. package/src/admin/ui/styles/sheet.scss +0 -152
  137. package/src/admin/ui/styles/sidebar.scss +0 -148
  138. package/src/admin/ui/styles/switch.scss +0 -59
  139. package/src/admin/ui/styles/table.scss +0 -207
  140. package/src/admin/ui/styles/tabs.scss +0 -62
  141. package/src/admin/ui/styles/toast.scss +0 -45
  142. package/src/admin/ui/styles/variables.scss +0 -24
  143. package/src/admin/ui/views/collection-list-view.tsx +0 -720
  144. package/src/admin/ui/views/dashboard-view.tsx +0 -263
  145. package/src/admin/ui/views/document-edit-view.tsx +0 -384
  146. package/src/admin/ui/views/global-edit-view.tsx +0 -226
  147. package/src/admin/ui/views/init-view.tsx +0 -182
  148. package/src/admin/ui/views/login-view.tsx +0 -123
  149. package/src/admin/ui/views/media-registry-view.tsx +0 -1104
  150. package/src/admin/ui/views/settings-view.tsx +0 -729
  151. package/src/admin/webcomponent.tsx +0 -15
  152. package/src/api.ts +0 -9
  153. package/src/auth/index.ts +0 -194
  154. package/src/auth/migrations.ts +0 -87
  155. package/src/auth/premissions.ts +0 -46
  156. package/src/cli/commands/generate-types.ts +0 -116
  157. package/src/cli/commands/init.ts +0 -95
  158. package/src/cli/commands/migrate-commands.ts +0 -160
  159. package/src/cli/commands/seed-command.ts +0 -11
  160. package/src/cli/d1-mock.ts +0 -101
  161. package/src/cli/index.test.ts +0 -84
  162. package/src/cli/index.ts +0 -183
  163. package/src/cli/r2-mock.ts +0 -217
  164. package/src/cli/seeding.ts +0 -405
  165. package/src/client.ts +0 -181
  166. package/src/config-utils.ts +0 -102
  167. package/src/config.ts +0 -49
  168. package/src/db/adapter.ts +0 -53
  169. package/src/db/better-sqlite.ts +0 -630
  170. package/src/db/bun-sqlite.ts +0 -646
  171. package/src/db/d1.ts +0 -711
  172. package/src/db/kysely/data-mapper.ts +0 -142
  173. package/src/db/kysely/field-mapper.ts +0 -148
  174. package/src/db/kysely/migration-generator.ts +0 -223
  175. package/src/db/kysely/query-builder.ts +0 -92
  176. package/src/db/kysely/schema-builder.ts +0 -439
  177. package/src/db/kysely/sql-utils.ts +0 -13
  178. package/src/db/postgres.ts +0 -621
  179. package/src/db/sqlite.ts +0 -658
  180. package/src/db/system-schema.ts +0 -121
  181. package/src/index.ts +0 -13
  182. package/src/runtimes/README.md +0 -59
  183. package/src/runtimes/bun.ts +0 -49
  184. package/src/runtimes/cloudflare-workers.ts +0 -38
  185. package/src/runtimes/next.ts +0 -26
  186. package/src/runtimes/node.ts +0 -52
  187. package/src/schema/collection.ts +0 -184
  188. package/src/schema/fields/base.ts +0 -164
  189. package/src/schema/fields/index.ts +0 -427
  190. package/src/schema/global.ts +0 -145
  191. package/src/schema/index.ts +0 -4
  192. package/src/schema/infer.ts +0 -72
  193. package/src/server/admin-router.ts +0 -20
  194. package/src/server/admin.ts +0 -142
  195. package/src/server/assets.ts +0 -306
  196. package/src/server/collection-router.ts +0 -55
  197. package/src/server/handlers.ts +0 -722
  198. package/src/server/middlewares/admin.ts +0 -27
  199. package/src/server/middlewares/auth.ts +0 -89
  200. package/src/server/middlewares/context.ts +0 -17
  201. package/src/server/middlewares/cors.ts +0 -24
  202. package/src/server/middlewares/database-init.ts +0 -74
  203. package/src/server/middlewares/rate-limit.ts +0 -71
  204. package/src/server/router.ts +0 -47
  205. package/src/server/setup-middlewares.ts +0 -58
  206. package/src/server/system-router.ts +0 -35
  207. package/src/server.ts +0 -9
  208. package/src/storage/adapters/cloudflare-r2.ts +0 -136
  209. package/src/storage/adapters/local.ts +0 -146
  210. package/src/storage/adapters/s3.ts +0 -186
  211. package/src/storage/errors.ts +0 -46
  212. package/src/storage/index.ts +0 -5
  213. package/src/storage/types.ts +0 -39
  214. package/src/types.ts +0 -577
  215. package/src/utils/lexical.ts +0 -37
  216. package/src/utils/logger.ts +0 -73
  217. package/src/validation.ts +0 -429
  218. package/src/validator.ts +0 -179
  219. package/test/admin-custom-field.test.ts +0 -162
  220. package/test/admin-react-field.test.tsx +0 -134
  221. package/test/api-features.test.ts +0 -78
  222. package/test/api.test.ts +0 -178
  223. package/test/auth.test.ts +0 -62
  224. package/test/cli-integration.test.ts +0 -146
  225. package/test/cli.test.ts +0 -25
  226. package/test/db/postgres.test.ts +0 -95
  227. package/test/db/sqlite-filter.test.ts +0 -53
  228. package/test/db/sqlite.test.ts +0 -82
  229. package/test/engine-features.test.ts +0 -79
  230. package/test/globals.test.ts +0 -74
  231. package/test/integration-tmp/db-app/opacacms.config.ts +0 -15
  232. package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +0 -25
  233. package/test/integration-tmp/my-test-app/index.ts +0 -8
  234. package/test/integration-tmp/my-test-app/opacacms.config.ts +0 -16
  235. package/test/integration-tmp/my-test-app/package.json +0 -12
  236. package/test/populate.test.ts +0 -79
  237. package/test/runtimes.test.ts +0 -43
  238. package/test/schema-builder.test.ts +0 -107
  239. package/test/schema-features.test.ts +0 -63
  240. package/test/seeding.test.ts +0 -68
  241. package/test/storage/local.test.ts +0 -72
  242. package/test/storage/s3.test.ts +0 -60
  243. package/test/structural-data.test.ts +0 -100
  244. package/test/test-setup.ts +0 -11
  245. package/test/validation.test.ts +0 -162
  246. package/tsconfig.json +0 -42
  247. /package/dist/{src/admin/index.css → admin/webcomponent.css} +0 -0
@@ -1,439 +0,0 @@
1
- import type { Kysely } from "kysely";
2
- import { sql } from "kysely";
3
- import type { Collection, Global } from "../../types";
4
- import { logger } from "../../utils/logger";
5
- import { getSystemCollections } from "../system-schema";
6
- import {
7
- flattenFields,
8
- getRelationalFields,
9
- mapFieldToPostgresType,
10
- mapFieldToSQLiteType,
11
- toSnakeCase,
12
- } from "./field-mapper";
13
- import { assertSafeIdentifier } from "./sql-utils";
14
-
15
- export type DialectType = "postgres" | "sqlite" | "d1";
16
-
17
- /**
18
- * Dynamically pushes schemas to the database using Kysely's safe Schema Builder API.
19
- *
20
- * @param db The Kysely database instance
21
- * @param dialect "postgres", "sqlite", or "d1"
22
- * @param collections The user collections
23
- * @param globals The user globals
24
- * @param options Push options
25
- */
26
- export async function pushSchema(
27
- db: Kysely<any>,
28
- dialect: DialectType,
29
- collections: Collection[],
30
- globals: Global[] = [],
31
- options: { pushDestructive?: boolean } = {},
32
- ): Promise<void> {
33
- const rawSchemas = [...getSystemCollections(), ...collections, ...globals];
34
- const allSchemas: (Collection | Global)[] = [];
35
- const seenSlugs = new Set<string>();
36
-
37
- for (const schema of rawSchemas) {
38
- if (!seenSlugs.has(schema.slug)) {
39
- seenSlugs.add(schema.slug);
40
- allSchemas.push(schema);
41
- }
42
- }
43
- const { pushDestructive } = options;
44
-
45
- logger.debug(`Starting schema push via Kysely (${dialect})...`);
46
-
47
- const mapType = dialect === "postgres" ? mapFieldToPostgresType : mapFieldToSQLiteType;
48
-
49
- // 1. Fetch existing tables based on dialect
50
- let existingTables: string[] = [];
51
- try {
52
- if (dialect === "postgres") {
53
- const res =
54
- await sql`SELECT table_name FROM information_schema.tables WHERE table_schema = 'public'`.execute(
55
- db,
56
- );
57
- existingTables = (res.rows as any[]).map((r) => r.table_name);
58
- } else {
59
- // SQLite/D1
60
- const res = await sql`SELECT name FROM sqlite_master WHERE type='table'`.execute(db);
61
- existingTables = (res.rows as any[]).map((r) => r.name);
62
- }
63
- } catch (_) {
64
- logger.warn("Failed to fetch existing tables:");
65
- }
66
-
67
- logger.info(`Existing tables: ${existingTables.join(", ")}`);
68
- const existingTableSet = new Set(existingTables);
69
- const expectedTableNames = new Set<string>();
70
-
71
- for (const collection of allSchemas) {
72
- const slug = collection.slug;
73
- const tableName = toSnakeCase(slug);
74
- assertSafeIdentifier(tableName);
75
- expectedTableNames.add(tableName);
76
-
77
- const flattenedFields = flattenFields(collection.fields);
78
- const hasTimestamps = collection.timestamps !== false;
79
- const versions = (collection as any).versions;
80
-
81
- // Check if table exists
82
- if (!existingTableSet.has(tableName)) {
83
- logger.info(` -> Creating table: ${logger.format("green", `"${tableName}"`)}`);
84
- let builder = db.schema.createTable(tableName).ifNotExists();
85
-
86
- // OpacaCMS uses string IDs for everything
87
- builder = builder.addColumn("id", "text", (col) => col.primaryKey());
88
-
89
- for (const field of flattenedFields) {
90
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
91
- const colName = toSnakeCase(field.name!);
92
- if (colName === "id") continue;
93
-
94
- assertSafeIdentifier(colName);
95
- const colType = mapType(field);
96
-
97
- builder = builder.addColumn(colName, colType as any, (col) => {
98
- let c = col;
99
- if (field.unique) c = c.unique();
100
- if (field.required) c = c.notNull();
101
- if (field.defaultValue !== undefined) c = c.defaultTo(field.defaultValue);
102
- return c;
103
- });
104
- }
105
-
106
- // Versions & Drafts column
107
- if (versions?.drafts) {
108
- builder = builder.addColumn("_status", "text", (col) => col.defaultTo("draft"));
109
- }
110
-
111
- // Timestamps columns
112
- if (hasTimestamps) {
113
- const ts = (collection as any).timestamps ?? {};
114
- const config = typeof ts === "object" ? ts : {};
115
- const createdField = toSnakeCase(config.createdAt ?? "createdAt");
116
- const updatedField = toSnakeCase(config.updatedAt ?? "updatedAt");
117
- const tsType = (dialect === "postgres" ? "timestamp with time zone" : "text") as any;
118
- builder = builder.addColumn(createdField, tsType, (col) =>
119
- col.defaultTo(sql`CURRENT_TIMESTAMP`),
120
- );
121
- builder = builder.addColumn(updatedField, tsType, (col) =>
122
- col.defaultTo(sql`CURRENT_TIMESTAMP`),
123
- );
124
- }
125
-
126
- await builder.execute();
127
-
128
- // Create Versions Table if needed
129
- if (versions) {
130
- const versionsTable = `${slug}_versions`.toLowerCase();
131
- assertSafeIdentifier(versionsTable);
132
- expectedTableNames.add(versionsTable);
133
-
134
- if (!existingTableSet.has(versionsTable)) {
135
- logger.info(
136
- ` -> Creating versions table: ${logger.format("green", `"${versionsTable}"`)}`,
137
- );
138
- await db.schema
139
- .createTable(versionsTable)
140
- .addColumn("id", "text", (col) => col.primaryKey())
141
- .addColumn("_parent_id", "text", (col) => col.notNull())
142
- .addColumn("_version_data", (dialect === "postgres" ? "jsonb" : "text") as any, (col) =>
143
- col.notNull(),
144
- )
145
- .addColumn("_status", "text")
146
- .addColumn(
147
- "created_at",
148
- (dialect === "postgres" ? "timestamp with time zone" : "text") as any,
149
- (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`),
150
- )
151
- .execute();
152
- }
153
- }
154
- } else {
155
- // Alter table logic
156
- let existingColumns: string[] = [];
157
- try {
158
- if (dialect === "postgres") {
159
- const res =
160
- await sql`SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ${slug}`.execute(
161
- db,
162
- );
163
- existingColumns = (res.rows as any[]).map((r) => r.column_name);
164
- } else {
165
- const res = await sql`PRAGMA table_info(${sql.id(slug)})`.execute(db);
166
- existingColumns = (res.rows as any[]).map((r) => r.name);
167
- }
168
- } catch (e) {
169
- logger.warn(`Failed to fetch columns for ${slug}:`, e);
170
- }
171
- const existingColSet = new Set(existingColumns);
172
-
173
- for (const field of flattenedFields) {
174
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) continue;
175
- const colName = toSnakeCase(field.name!);
176
- if (colName === "id") continue;
177
-
178
- assertSafeIdentifier(colName);
179
- if (!existingColSet.has(colName)) {
180
- logger.info(
181
- ` -> Adding missing column: ${logger.format("green", `${slug}.${colName}`)}`,
182
- );
183
- const colType = mapType(field);
184
- await db.schema
185
- .alterTable(slug)
186
- .addColumn(colName, colType as any)
187
- .execute();
188
- }
189
- }
190
-
191
- // Versions & Drafts column (Alter)
192
- if (versions?.drafts && !existingColSet.has("_status")) {
193
- logger.info(` -> Adding missing status column to: ${slug}`);
194
- await db.schema
195
- .alterTable(slug)
196
- .addColumn("_status", "text", (col) => col.defaultTo("draft"))
197
- .execute();
198
- }
199
-
200
- // Timestamps columns (Alter)
201
- if (hasTimestamps) {
202
- const ts = (collection as any).timestamps ?? {};
203
- const config = typeof ts === "object" ? ts : {};
204
- const createdField = toSnakeCase(config.createdAt ?? "createdAt");
205
- const updatedField = toSnakeCase(config.updatedAt ?? "updatedAt");
206
- const tsType = (dialect === "postgres" ? "timestamp with time zone" : "text") as any;
207
-
208
- if (!existingColSet.has(createdField)) {
209
- logger.info(` -> Adding missing timestamp column: ${slug}.${createdField}`);
210
- await db.schema
211
- .alterTable(slug)
212
- .addColumn(createdField, tsType, (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))
213
- .execute();
214
- }
215
- if (!existingColSet.has(updatedField)) {
216
- logger.info(` -> Adding missing timestamp column: ${slug}.${updatedField}`);
217
- await db.schema
218
- .alterTable(slug)
219
- .addColumn(updatedField, tsType, (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`))
220
- .execute();
221
- }
222
- }
223
-
224
- // Versions table (Alter phase)
225
- if (versions) {
226
- const versionsTable = `${slug}_versions`.toLowerCase();
227
- expectedTableNames.add(versionsTable);
228
- if (!existingTableSet.has(versionsTable)) {
229
- logger.info(` -> Creating missing versions table for: ${slug}`);
230
- await db.schema
231
- .createTable(versionsTable)
232
- .addColumn("id", "text", (col) => col.primaryKey())
233
- .addColumn("_parent_id", "text", (col) => col.notNull())
234
- .addColumn("_version_data", (dialect === "postgres" ? "jsonb" : "text") as any, (col) =>
235
- col.notNull(),
236
- )
237
- .addColumn("_status", "text")
238
- .addColumn(
239
- "created_at",
240
- (dialect === "postgres" ? "timestamp with time zone" : "text") as any,
241
- (col) => col.defaultTo(sql`CURRENT_TIMESTAMP`),
242
- )
243
- .execute();
244
- }
245
- }
246
-
247
- // Column Pruning
248
- if (pushDestructive) {
249
- const expectedCols = new Set(
250
- flattenedFields
251
- .filter((f) => !(f.type === "relationship" && f.hasMany))
252
- .map((f) => toSnakeCase(f.name!)),
253
- );
254
- if (hasTimestamps) {
255
- const ts = (collection as any).timestamps ?? {};
256
- const config = typeof ts === "object" ? ts : {};
257
- expectedCols.add(toSnakeCase(config.createdAt ?? "createdAt"));
258
- expectedCols.add(toSnakeCase(config.updatedAt ?? "updatedAt"));
259
- }
260
- if (versions?.drafts) expectedCols.add("_status");
261
- expectedCols.add("id");
262
-
263
- for (const existingCol of existingColumns) {
264
- if (!expectedCols.has(existingCol)) {
265
- logger.info(
266
- ` -> Dropping stale column: ${logger.format("red", `${slug}.${existingCol}`)}`,
267
- );
268
- try {
269
- await db.schema.alterTable(slug).dropColumn(existingCol).execute();
270
- } catch (_) {
271
- logger.warn(`Failed to drop column ${existingCol}.`);
272
- }
273
- }
274
- }
275
- }
276
- }
277
-
278
- const relationalFields = getRelationalFields(collection.fields);
279
-
280
- // Join tables (hasMany)
281
- for (const field of relationalFields) {
282
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
283
- const sourceIdType = "text";
284
- const colName = toSnakeCase(field.name!);
285
- const joinTableName = `${slug}_${colName}_relations`.toLowerCase();
286
- assertSafeIdentifier(joinTableName);
287
- expectedTableNames.add(joinTableName);
288
-
289
- if (!existingTableSet.has(joinTableName)) {
290
- logger.info(
291
- ` -> Creating relation table: ${logger.format("green", `"${joinTableName}"`)}`,
292
- );
293
- await db.schema
294
- .createTable(joinTableName)
295
- .ifNotExists()
296
- .addColumn("id", "text", (col) => col.primaryKey())
297
- .addColumn("source_id", sourceIdType, (col) => col.notNull())
298
- .addColumn("target_id", "text", (col) => col.notNull())
299
- .addColumn("order", "integer", (col) => col.defaultTo(0))
300
- .execute();
301
- }
302
- }
303
- }
304
-
305
- // Block tables
306
- for (const field of relationalFields) {
307
- if (field.type === "blocks" && field.blocks && Array.isArray(field.blocks)) {
308
- const parentIdType = "text";
309
-
310
- for (const block of field.blocks) {
311
- const blockName = toSnakeCase(field.name!);
312
- const blockSlug = toSnakeCase(block.slug);
313
- assertSafeIdentifier(blockName);
314
- assertSafeIdentifier(blockSlug);
315
-
316
- const blockTableName = `${slug}_${blockName}_${blockSlug}`.toLowerCase();
317
- assertSafeIdentifier(blockTableName);
318
- expectedTableNames.add(blockTableName);
319
-
320
- if (!existingTableSet.has(blockTableName)) {
321
- logger.info(
322
- ` -> Creating block table: ${logger.format("green", `"${blockTableName}"`)}`,
323
- );
324
- let bBuilder = db.schema
325
- .createTable(blockTableName)
326
- .ifNotExists()
327
- .addColumn("id", "text", (col) => col.primaryKey())
328
- .addColumn("_parent_id", parentIdType, (col) => col.notNull())
329
- .addColumn("_order", "integer", (col) => col.defaultTo(0))
330
- .addColumn("block_type", "text", (col) => col.notNull().defaultTo(block.slug));
331
-
332
- const blockFlattened = flattenFields(block.fields);
333
- for (const bField of blockFlattened) {
334
- const bColName = toSnakeCase(bField.name!);
335
- if (bColName === "id") continue;
336
-
337
- assertSafeIdentifier(bColName);
338
- const bColType = mapType(bField);
339
- bBuilder = bBuilder.addColumn(bColName, bColType as any, (col) => {
340
- let c = col;
341
- if (bField.unique) c = c.unique();
342
- if (bField.required) c = c.notNull();
343
- if (bField.defaultValue !== undefined) c = c.defaultTo(bField.defaultValue);
344
- return c;
345
- });
346
- }
347
-
348
- const tsType = (dialect === "postgres" ? "timestamp with time zone" : "text") as any;
349
- bBuilder = bBuilder.addColumn("created_at", tsType, (col) =>
350
- col.defaultTo(sql`CURRENT_TIMESTAMP`),
351
- );
352
- bBuilder = bBuilder.addColumn("updated_at", tsType, (col) =>
353
- col.defaultTo(sql`CURRENT_TIMESTAMP`),
354
- );
355
-
356
- await bBuilder.execute();
357
- } else {
358
- // Alter block table
359
- let existingBCols: string[] = [];
360
- try {
361
- if (dialect === "postgres") {
362
- const res =
363
- await sql`SELECT column_name FROM information_schema.columns WHERE table_schema = 'public' AND table_name = ${blockTableName}`.execute(
364
- db,
365
- );
366
- existingBCols = (res.rows as any[]).map((r) => r.column_name);
367
- } else {
368
- const res = await sql`PRAGMA table_info(${sql.id(blockTableName)})`.execute(db);
369
- existingBCols = (res.rows as any[]).map((r) => r.name);
370
- }
371
- } catch (_) {
372
- // Ignore
373
- }
374
- const existingBColSet = new Set(existingBCols);
375
- const blockFlattened = flattenFields(block.fields);
376
-
377
- for (const bField of blockFlattened) {
378
- const bColName = toSnakeCase(bField.name!);
379
- if (bColName === "id") continue;
380
-
381
- if (!existingBColSet.has(bColName)) {
382
- const bColType = mapType(bField);
383
- await db.schema
384
- .alterTable(blockTableName)
385
- .addColumn(bColName, bColType as any)
386
- .execute();
387
- }
388
- }
389
-
390
- // Ensure internal block columns exist
391
- if (!existingBColSet.has("_parent_id")) {
392
- await db.schema
393
- .alterTable(blockTableName)
394
- .addColumn("_parent_id", "text", (col) => col.notNull().defaultTo(""))
395
- .execute();
396
- }
397
- if (!existingBColSet.has("_order")) {
398
- await db.schema
399
- .alterTable(blockTableName)
400
- .addColumn("_order", "integer", (col) => col.defaultTo(0))
401
- .execute();
402
- }
403
- if (!existingBColSet.has("block_type")) {
404
- await db.schema
405
- .alterTable(blockTableName)
406
- .addColumn("block_type", "text", (col) => col.notNull().defaultTo(block.slug))
407
- .execute();
408
- }
409
- }
410
- }
411
- }
412
- }
413
- }
414
-
415
- // Table Pruning
416
- if (pushDestructive) {
417
- for (const tableName of existingTables) {
418
- if (
419
- !expectedTableNames.has(tableName) &&
420
- !tableName.startsWith("better_auth") &&
421
- !tableName.startsWith("__kysely")
422
- ) {
423
- logger.info(` -> Dropping stale table: ${logger.format("red", `"${tableName}"`)}`);
424
- try {
425
- await db.schema.dropTable(tableName).ifExists().cascade().execute();
426
- } catch (_) {
427
- // sqlite might not support cascade, try without
428
- try {
429
- await db.schema.dropTable(tableName).ifExists().execute();
430
- } catch (_) {
431
- logger.warn(`Failed to drop table ${tableName}`);
432
- }
433
- }
434
- }
435
- }
436
- }
437
-
438
- logger.success(`Schema push to Kysely (${dialect}) completed.`);
439
- }
@@ -1,13 +0,0 @@
1
- export function assertSafeIdentifier(identifier: string): void {
2
- if (typeof identifier !== "string" || !identifier) {
3
- throw new Error(`Invalid identifier: must be a non-empty string. Got: ${identifier}`);
4
- }
5
-
6
- const isValid = /^[a-zA-Z0-9_-]+$/.test(identifier);
7
-
8
- if (!isValid) {
9
- throw new Error(
10
- `API Error: Unsafe SQL identifier detected: "${identifier}". Identifiers can only contain alphanumeric characters, underscores, and hyphens.`,
11
- );
12
- }
13
- }