opacacms 0.1.12 → 0.1.13

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 (217) hide show
  1. package/dist/admin/index.js +0 -4
  2. package/dist/admin/webcomponent.d.ts +0 -1
  3. package/dist/admin/webcomponent.js +0 -4
  4. package/dist/admin.css +1 -0
  5. package/package.json +8 -2
  6. package/bun.lock +0 -34
  7. package/dist/admin/index.css +0 -47
  8. package/dist/admin/webcomponent.css +0 -47
  9. package/global.d.ts +0 -11
  10. package/src/admin/api-client.ts +0 -63
  11. package/src/admin/auth-client.ts +0 -40
  12. package/src/admin/custom-field.ts +0 -179
  13. package/src/admin/index.ts +0 -15
  14. package/src/admin/react.tsx +0 -72
  15. package/src/admin/router.ts +0 -9
  16. package/src/admin/stores/admin-queries.ts +0 -121
  17. package/src/admin/stores/auth.ts +0 -61
  18. package/src/admin/stores/column-visibility.ts +0 -67
  19. package/src/admin/stores/config.ts +0 -15
  20. package/src/admin/stores/media.ts +0 -95
  21. package/src/admin/stores/query.ts +0 -13
  22. package/src/admin/stores/ui.ts +0 -29
  23. package/src/admin/ui/admin-client.tsx +0 -283
  24. package/src/admin/ui/admin-layout.tsx +0 -276
  25. package/src/admin/ui/components/ColumnVisibilityToggle.tsx +0 -141
  26. package/src/admin/ui/components/DataDetailSheet.tsx +0 -141
  27. package/src/admin/ui/components/DataDetailView.tsx +0 -175
  28. package/src/admin/ui/components/Table.tsx +0 -67
  29. package/src/admin/ui/components/fields/ArrayField.tsx +0 -166
  30. package/src/admin/ui/components/fields/BlocksField.tsx +0 -202
  31. package/src/admin/ui/components/fields/BooleanField.tsx +0 -50
  32. package/src/admin/ui/components/fields/CollapsibleField.tsx +0 -75
  33. package/src/admin/ui/components/fields/DateField.tsx +0 -45
  34. package/src/admin/ui/components/fields/FileField.tsx +0 -322
  35. package/src/admin/ui/components/fields/GroupField.tsx +0 -50
  36. package/src/admin/ui/components/fields/JoinField.tsx +0 -23
  37. package/src/admin/ui/components/fields/NumberField.tsx +0 -46
  38. package/src/admin/ui/components/fields/RadioField.tsx +0 -62
  39. package/src/admin/ui/components/fields/RelationshipField.tsx +0 -278
  40. package/src/admin/ui/components/fields/RowField.tsx +0 -40
  41. package/src/admin/ui/components/fields/SelectField.tsx +0 -59
  42. package/src/admin/ui/components/fields/TabsField.tsx +0 -101
  43. package/src/admin/ui/components/fields/TextAreaField.tsx +0 -54
  44. package/src/admin/ui/components/fields/TextField.tsx +0 -49
  45. package/src/admin/ui/components/fields/VirtualField.tsx +0 -53
  46. package/src/admin/ui/components/fields/index.tsx +0 -371
  47. package/src/admin/ui/components/fields/richtext-editor/index.tsx +0 -211
  48. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageComponent.tsx +0 -142
  49. package/src/admin/ui/components/fields/richtext-editor/nodes/ImageNode.tsx +0 -95
  50. package/src/admin/ui/components/fields/richtext-editor/plugins/ComponentPickerPlugin.tsx +0 -226
  51. package/src/admin/ui/components/fields/richtext-editor/plugins/EditableSyncPlugin.tsx +0 -16
  52. package/src/admin/ui/components/fields/richtext-editor/plugins/NotionToolbarPlugin.tsx +0 -184
  53. package/src/admin/ui/components/fields/richtext-editor/plugins/SimpleToolbarPlugin.tsx +0 -240
  54. package/src/admin/ui/components/fields/richtext-editor/plugins/ValueSyncPlugin.tsx +0 -40
  55. package/src/admin/ui/components/fields/utils.ts +0 -1
  56. package/src/admin/ui/components/link.tsx +0 -41
  57. package/src/admin/ui/components/media/AssetManagerModal.tsx +0 -334
  58. package/src/admin/ui/components/toast.tsx +0 -72
  59. package/src/admin/ui/components/ui/accordion.tsx +0 -51
  60. package/src/admin/ui/components/ui/alert-dialog.tsx +0 -98
  61. package/src/admin/ui/components/ui/blocks.tsx +0 -32
  62. package/src/admin/ui/components/ui/breadcrumbs.tsx +0 -59
  63. package/src/admin/ui/components/ui/button.tsx +0 -26
  64. package/src/admin/ui/components/ui/collapsible.tsx +0 -124
  65. package/src/admin/ui/components/ui/dialog.tsx +0 -79
  66. package/src/admin/ui/components/ui/group.tsx +0 -20
  67. package/src/admin/ui/components/ui/index.ts +0 -17
  68. package/src/admin/ui/components/ui/input.tsx +0 -12
  69. package/src/admin/ui/components/ui/join.tsx +0 -53
  70. package/src/admin/ui/components/ui/label.tsx +0 -11
  71. package/src/admin/ui/components/ui/radio-group.tsx +0 -75
  72. package/src/admin/ui/components/ui/relationship-detail-sheet.tsx +0 -122
  73. package/src/admin/ui/components/ui/relationship.tsx +0 -58
  74. package/src/admin/ui/components/ui/scroll-area.tsx +0 -19
  75. package/src/admin/ui/components/ui/select.tsx +0 -187
  76. package/src/admin/ui/components/ui/separator.tsx +0 -21
  77. package/src/admin/ui/components/ui/sheet.tsx +0 -106
  78. package/src/admin/ui/components/ui/tabs.tsx +0 -116
  79. package/src/admin/ui/components/ui/utils.ts +0 -3
  80. package/src/admin/ui/hooks/use-debounce.ts +0 -15
  81. package/src/admin/ui/styles/_locale-switcher.scss +0 -33
  82. package/src/admin/ui/styles/accordion.scss +0 -60
  83. package/src/admin/ui/styles/animations.scss +0 -41
  84. package/src/admin/ui/styles/asset-manager.scss +0 -547
  85. package/src/admin/ui/styles/badge.scss +0 -13
  86. package/src/admin/ui/styles/base.scss +0 -22
  87. package/src/admin/ui/styles/button.scss +0 -161
  88. package/src/admin/ui/styles/card.scss +0 -13
  89. package/src/admin/ui/styles/collapsible.scss +0 -75
  90. package/src/admin/ui/styles/data-detail.scss +0 -92
  91. package/src/admin/ui/styles/dialog.scss +0 -102
  92. package/src/admin/ui/styles/empty-state.scss +0 -22
  93. package/src/admin/ui/styles/group.scss +0 -19
  94. package/src/admin/ui/styles/index.scss +0 -33
  95. package/src/admin/ui/styles/input.scss +0 -80
  96. package/src/admin/ui/styles/label.scss +0 -12
  97. package/src/admin/ui/styles/layout.scss +0 -56
  98. package/src/admin/ui/styles/lexical.scss +0 -469
  99. package/src/admin/ui/styles/loading.scss +0 -102
  100. package/src/admin/ui/styles/media-registry.scss +0 -597
  101. package/src/admin/ui/styles/pagination.scss +0 -20
  102. package/src/admin/ui/styles/radio-group.scss +0 -66
  103. package/src/admin/ui/styles/row.scss +0 -17
  104. package/src/admin/ui/styles/scrollbar.scss +0 -36
  105. package/src/admin/ui/styles/select.scss +0 -121
  106. package/src/admin/ui/styles/separator.scss +0 -14
  107. package/src/admin/ui/styles/sheet.scss +0 -152
  108. package/src/admin/ui/styles/sidebar.scss +0 -148
  109. package/src/admin/ui/styles/switch.scss +0 -59
  110. package/src/admin/ui/styles/table.scss +0 -207
  111. package/src/admin/ui/styles/tabs.scss +0 -62
  112. package/src/admin/ui/styles/toast.scss +0 -45
  113. package/src/admin/ui/styles/variables.scss +0 -24
  114. package/src/admin/ui/views/collection-list-view.tsx +0 -720
  115. package/src/admin/ui/views/dashboard-view.tsx +0 -263
  116. package/src/admin/ui/views/document-edit-view.tsx +0 -384
  117. package/src/admin/ui/views/global-edit-view.tsx +0 -226
  118. package/src/admin/ui/views/init-view.tsx +0 -182
  119. package/src/admin/ui/views/login-view.tsx +0 -123
  120. package/src/admin/ui/views/media-registry-view.tsx +0 -1104
  121. package/src/admin/ui/views/settings-view.tsx +0 -729
  122. package/src/admin/webcomponent.tsx +0 -15
  123. package/src/auth/index.ts +0 -194
  124. package/src/auth/migrations.ts +0 -87
  125. package/src/auth/premissions.ts +0 -46
  126. package/src/cli/commands/generate-types.ts +0 -116
  127. package/src/cli/commands/init.ts +0 -95
  128. package/src/cli/commands/migrate-commands.ts +0 -160
  129. package/src/cli/commands/seed-command.ts +0 -11
  130. package/src/cli/d1-mock.ts +0 -101
  131. package/src/cli/index.test.ts +0 -84
  132. package/src/cli/index.ts +0 -183
  133. package/src/cli/r2-mock.ts +0 -217
  134. package/src/cli/seeding.ts +0 -409
  135. package/src/client.ts +0 -181
  136. package/src/config-utils.ts +0 -102
  137. package/src/config.ts +0 -49
  138. package/src/db/adapter.ts +0 -53
  139. package/src/db/better-sqlite.ts +0 -657
  140. package/src/db/bun-sqlite.ts +0 -666
  141. package/src/db/d1.ts +0 -721
  142. package/src/db/index.ts +0 -10
  143. package/src/db/kysely/data-mapper.ts +0 -142
  144. package/src/db/kysely/field-mapper.ts +0 -149
  145. package/src/db/kysely/migration-generator.ts +0 -223
  146. package/src/db/kysely/query-builder.ts +0 -92
  147. package/src/db/kysely/schema-builder.ts +0 -439
  148. package/src/db/kysely/sql-utils.ts +0 -13
  149. package/src/db/postgres.ts +0 -631
  150. package/src/db/sqlite.ts +0 -670
  151. package/src/db/system-schema.ts +0 -121
  152. package/src/index.ts +0 -13
  153. package/src/runtimes/README.md +0 -59
  154. package/src/runtimes/bun.ts +0 -49
  155. package/src/runtimes/cloudflare-workers.ts +0 -38
  156. package/src/runtimes/next.ts +0 -26
  157. package/src/runtimes/node.ts +0 -52
  158. package/src/schema/collection.ts +0 -184
  159. package/src/schema/fields/base.ts +0 -164
  160. package/src/schema/fields/index.ts +0 -427
  161. package/src/schema/global.ts +0 -145
  162. package/src/schema/index.ts +0 -4
  163. package/src/schema/infer.ts +0 -72
  164. package/src/server/admin-router.ts +0 -20
  165. package/src/server/admin.ts +0 -142
  166. package/src/server/assets.ts +0 -306
  167. package/src/server/collection-router.ts +0 -55
  168. package/src/server/handlers.ts +0 -722
  169. package/src/server/middlewares/admin.ts +0 -27
  170. package/src/server/middlewares/auth.ts +0 -89
  171. package/src/server/middlewares/context.ts +0 -17
  172. package/src/server/middlewares/cors.ts +0 -24
  173. package/src/server/middlewares/database-init.ts +0 -74
  174. package/src/server/middlewares/rate-limit.ts +0 -77
  175. package/src/server/router.ts +0 -47
  176. package/src/server/setup-middlewares.ts +0 -58
  177. package/src/server/system-router.ts +0 -35
  178. package/src/server.ts +0 -9
  179. package/src/storage/adapters/cloudflare-r2.ts +0 -136
  180. package/src/storage/adapters/local.ts +0 -146
  181. package/src/storage/adapters/s3.ts +0 -186
  182. package/src/storage/errors.ts +0 -46
  183. package/src/storage/index.ts +0 -5
  184. package/src/storage/types.ts +0 -39
  185. package/src/types.ts +0 -577
  186. package/src/utils/lexical.ts +0 -37
  187. package/src/utils/logger.ts +0 -73
  188. package/src/validation.ts +0 -429
  189. package/src/validator.ts +0 -179
  190. package/test/admin-custom-field.test.ts +0 -162
  191. package/test/admin-react-field.test.tsx +0 -134
  192. package/test/api-features.test.ts +0 -78
  193. package/test/api.test.ts +0 -178
  194. package/test/auth.test.ts +0 -62
  195. package/test/cli-integration.test.ts +0 -148
  196. package/test/cli.test.ts +0 -25
  197. package/test/db/postgres.test.ts +0 -95
  198. package/test/db/sqlite-filter.test.ts +0 -53
  199. package/test/db/sqlite.test.ts +0 -82
  200. package/test/engine-features.test.ts +0 -79
  201. package/test/globals.test.ts +0 -74
  202. package/test/integration-tmp/db-app/opacacms.config.ts +0 -15
  203. package/test/integration-tmp/my-sqlite-app/opacacms.config.ts +0 -25
  204. package/test/integration-tmp/my-test-app/index.ts +0 -8
  205. package/test/integration-tmp/my-test-app/opacacms.config.ts +0 -16
  206. package/test/integration-tmp/my-test-app/package.json +0 -12
  207. package/test/populate.test.ts +0 -79
  208. package/test/runtimes.test.ts +0 -43
  209. package/test/schema-builder.test.ts +0 -107
  210. package/test/schema-features.test.ts +0 -63
  211. package/test/seeding.test.ts +0 -68
  212. package/test/storage/local.test.ts +0 -72
  213. package/test/storage/s3.test.ts +0 -60
  214. package/test/structural-data.test.ts +0 -100
  215. package/test/test-setup.ts +0 -11
  216. package/test/validation.test.ts +0 -162
  217. package/tsconfig.json +0 -42
@@ -1,657 +0,0 @@
1
- import fs from "node:fs/promises";
2
- import path from "node:path";
3
- import { createRequire } from "node:module";
4
- const require = createRequire(import.meta.url);
5
- const Database = require("better-sqlite3");
6
- import { CompiledQuery, FileMigrationProvider, Kysely, Migrator, SqliteDialect, sql } from "kysely";
7
- import type { Collection, FindOptions, Global, PaginatedResult } from "../types";
8
- import { logger } from "../utils/logger";
9
- import { BaseDatabaseAdapter } from "./adapter";
10
- import { flattenPayload, unflattenRow } from "./kysely/data-mapper";
11
- import { flattenFields, toSnakeCase } from "./kysely/field-mapper";
12
- import { buildKyselyWhere } from "./kysely/query-builder";
13
- import { pushSchema } from "./kysely/schema-builder";
14
-
15
- export class BetterSQLiteAdapter extends BaseDatabaseAdapter {
16
- override name = "better-sqlite3";
17
- private _rawDb: any;
18
- private _db: Kysely<any>;
19
- private _collections: Collection[] = [];
20
- private _globals: Global[] = [];
21
- override push: boolean;
22
- override migrationDir: string;
23
- override pushDestructive: boolean;
24
-
25
- override get raw() {
26
- return this._rawDb;
27
- }
28
-
29
- override get db() {
30
- return this._db;
31
- }
32
-
33
- constructor(
34
- path: string,
35
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
36
- ) {
37
- super();
38
- this._rawDb = new Database(path);
39
- this._db = new Kysely<any>({
40
- dialect: new SqliteDialect({
41
- database: this._rawDb,
42
- }),
43
- });
44
- this.push = options?.push ?? process.env.NODE_ENV !== "production";
45
- this.pushDestructive = options?.pushDestructive ?? false;
46
- this.migrationDir = options?.migrationDir ?? "./migrations";
47
- }
48
-
49
- override async connect() {
50
- // Synchronous internally
51
- }
52
-
53
- override async disconnect() {
54
- await this._db.destroy();
55
- }
56
-
57
- override async unsafe(query: string, params?: any[]): Promise<unknown> {
58
- const compiled = CompiledQuery.raw(query, (params || []) as any);
59
- const result = await this._db.executeQuery(compiled);
60
- return result.rows;
61
- }
62
-
63
- private async coerceData(collection: string, data: any): Promise<any> {
64
- const colDef = this._collections.find((c) => c.slug === collection);
65
- if (!colDef) return data;
66
-
67
- const result = { ...data };
68
- const { flattenFields } = await import("./kysely/field-mapper.js");
69
- const allFields = flattenFields(colDef.fields);
70
-
71
- for (const field of allFields) {
72
- const colName = toSnakeCase(field.name!);
73
- if (!(colName in result)) continue;
74
-
75
- const value = result[colName];
76
- if (value === undefined || value === null) continue;
77
-
78
- switch (field.type) {
79
- case "boolean":
80
- result[colName] = value ? 1 : 0;
81
- break;
82
- case "number":
83
- result[colName] = Number(value);
84
- break;
85
- case "date":
86
- if (value instanceof Date) {
87
- result[colName] = value.toISOString();
88
- } else if (typeof value === "string") {
89
- result[colName] = new Date(value).toISOString();
90
- }
91
- break;
92
- case "richtext":
93
- case "json":
94
- case "file":
95
- if (typeof value === "object") {
96
- result[colName] = JSON.stringify(value);
97
- }
98
- break;
99
- }
100
- }
101
-
102
- return result;
103
- }
104
-
105
- override async count(collection: string, query?: Record<string, unknown>): Promise<number> {
106
- const tableName = toSnakeCase(collection);
107
- let qb = this._db.selectFrom(tableName).select((eb) => eb.fn.count("id").as("count"));
108
- if (query && Object.keys(query).length > 0) {
109
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
110
- }
111
- const result = await qb.executeTakeFirst();
112
- return Number(result?.count || 0);
113
- }
114
-
115
- override async create<T extends object>(collection: string, data: Partial<T>): Promise<T> {
116
- const tableName = toSnakeCase(collection);
117
- return this._db.transaction().execute(async (tx) => {
118
- const colDef = this._collections.find((c) => c.slug === collection);
119
- const jsonFields =
120
- colDef?.fields
121
- .filter((f) => ["richtext", "json", "file"].includes(f.type))
122
- .map((f) => f.name!) || [];
123
-
124
- const flatData = flattenPayload(data, "", jsonFields);
125
-
126
- for (const field of jsonFields) {
127
- if (flatData[field] && typeof flatData[field] === "object") {
128
- flatData[field] = JSON.stringify(flatData[field]);
129
- }
130
- }
131
-
132
- const hasManyData: Record<string, unknown[]> = {};
133
- const blocksData: Record<string, unknown[]> = {};
134
-
135
- for (const key in flatData) {
136
- if (Array.isArray(flatData[key])) {
137
- const isHasMany = colDef?.fields.some(
138
- (f) => f.type === "relationship" && "hasMany" in f && f.hasMany && f.name === key,
139
- );
140
-
141
- if (isHasMany) {
142
- hasManyData[key] = flatData[key];
143
- } else {
144
- blocksData[key] = flatData[key];
145
- }
146
- delete flatData[key];
147
- }
148
- }
149
-
150
- if (!flatData.id) flatData.id = crypto.randomUUID();
151
-
152
- // Whitelist only fields that exist in the database
153
- const dbFields = flattenFields(colDef?.fields || []);
154
- const validCols = new Set(dbFields.map((f: any) => toSnakeCase(f.name!)));
155
- validCols.add("id");
156
-
157
- const ts = colDef?.timestamps !== false;
158
- if (ts) {
159
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
160
- validCols.add(toSnakeCase(config.createdAt || "createdAt"));
161
- validCols.add(toSnakeCase(config.updatedAt || "updatedAt"));
162
- }
163
-
164
- const filteredData: Record<string, any> = {};
165
- for (const col of Object.keys(flatData)) {
166
- if (validCols.has(col)) {
167
- filteredData[col] = flatData[col];
168
- }
169
- }
170
-
171
- const coercedData = await this.coerceData(collection, filteredData);
172
- await tx.insertInto(tableName).values(coercedData).execute();
173
-
174
- for (const [key, values] of Object.entries(hasManyData)) {
175
- const joinTableName = `${tableName}_${toSnakeCase(key)}_relations`.toLowerCase();
176
- if (values.length > 0) {
177
- const joinData = values.map((val: any, idx: number) => {
178
- const tId = typeof val === "object" ? val.id : val;
179
- return { id: crypto.randomUUID(), source_id: flatData.id, target_id: tId, order: idx };
180
- });
181
- await tx.insertInto(joinTableName).values(joinData).execute();
182
- }
183
- }
184
-
185
- for (const [key, blocks] of Object.entries(blocksData)) {
186
- for (let i = 0; i < (blocks as any[]).length; i++) {
187
- const block = blocks[i] as any;
188
- if (!block.blockType) continue;
189
- const blockTableName =
190
- `${tableName}_${toSnakeCase(key)}_${block.blockType}`.toLowerCase();
191
- const bId = block.id || crypto.randomUUID();
192
-
193
- const blockDef = colDef?.fields.find((f) => f.name === key && f.type === "blocks");
194
- const blockConfig = (blockDef as any)?.blocks?.find(
195
- (b: any) => b.slug === block.blockType,
196
- );
197
- const blockJsonFields =
198
- blockConfig?.fields
199
- .filter((f: any) => ["richtext", "json", "file"].includes(f.type))
200
- .map((f: any) => f.name!) || [];
201
-
202
- const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
203
-
204
- for (const f of blockJsonFields) {
205
- if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
206
- blockFlatData[f] = JSON.stringify(blockFlatData[f]);
207
- }
208
- }
209
-
210
- delete blockFlatData.blockType;
211
- const coercedBlockData = await this.coerceData(blockTableName, {
212
- ...blockFlatData,
213
- _parent_id: flatData.id,
214
- _order: i,
215
- block_type: block.blockType,
216
- });
217
- await tx.insertInto(blockTableName).values(coercedBlockData).execute();
218
- }
219
- }
220
-
221
- return this.findOne<T>(collection, { id: flatData.id }, tx) as Promise<T>;
222
- });
223
- }
224
-
225
- override async findOne<T extends object>(
226
- collection: string,
227
- query: Record<string, unknown>,
228
- tx?: any,
229
- ): Promise<T | null> {
230
- const tableName = toSnakeCase(collection);
231
- const executor = tx || this._db;
232
- let qb = executor.selectFrom(tableName).selectAll();
233
- if (query && Object.keys(query).length > 0) {
234
- qb = qb.where((eb: any) => buildKyselyWhere(eb, query) || eb.val(true));
235
- }
236
-
237
- const row = await qb.executeTakeFirst();
238
- if (!row) return null;
239
-
240
- const unflattened = unflattenRow(row);
241
- const colDef = this._collections.find((c) => c.slug === collection);
242
-
243
- if (colDef) {
244
- const { getRelationalFields, toSnakeCase } = await import("./kysely/field-mapper.js");
245
- const relationalFields = getRelationalFields(colDef.fields);
246
-
247
- for (const field of relationalFields) {
248
- if (!field.name) continue;
249
- const snakeName = toSnakeCase(field.name);
250
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
251
- const joinTableName = `${tableName}_${snakeName}_relations`.toLowerCase();
252
- try {
253
- const relations = await executor
254
- .selectFrom(joinTableName)
255
- .selectAll()
256
- .where("source_id", "=", row.id)
257
- .orderBy("order", "asc")
258
- .execute();
259
- unflattened[field.name!] = relations.map((r: any) => r.target_id);
260
- } catch (e) { }
261
- } else if (field.type === "blocks" && field.blocks) {
262
- const blockData: any[] = [];
263
- for (const b of field.blocks) {
264
- const blockTableName = `${tableName}_${snakeName}_${b.slug}`.toLowerCase();
265
- try {
266
- const blocks = await executor
267
- .selectFrom(blockTableName)
268
- .selectAll()
269
- .where("_parent_id", "=", row.id)
270
- .execute();
271
-
272
- for (const blk of blocks) {
273
- const uf = unflattenRow(blk);
274
- uf.blockType = blk.block_type;
275
- blockData.push(uf);
276
- }
277
- } catch (e) { }
278
- }
279
- blockData.sort((a: any, b: any) => a._order - b._order);
280
- blockData.forEach((b: any) => {
281
- delete b._order;
282
- delete b._parent_id;
283
- });
284
- unflattened[field.name!] = blockData;
285
- }
286
- }
287
- }
288
-
289
- return unflattened as T;
290
- }
291
-
292
- override async find<T extends object>(
293
- collection: string,
294
- query?: Record<string, unknown>,
295
- options?: FindOptions,
296
- ): Promise<PaginatedResult<T>> {
297
- const page = options?.page || 1;
298
- const limit = options?.limit || 10;
299
- const offset = (page - 1) * limit;
300
-
301
- const total = await this.count(collection, query);
302
-
303
- const tableName = toSnakeCase(collection);
304
- let qb = this._db.selectFrom(tableName).selectAll().limit(limit).offset(offset);
305
- if (query && Object.keys(query).length > 0) {
306
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
307
- }
308
- if (options?.sort) {
309
- const isDesc = options.sort.startsWith("-");
310
- const col = isDesc ? options.sort.substring(1) : options.sort;
311
- qb = qb.orderBy(col as any, isDesc ? "desc" : "asc");
312
- } else {
313
- qb = qb.orderBy("created_at" as any, "desc");
314
- }
315
-
316
- const rows = await qb.execute();
317
- const docs = await Promise.all(rows.map((row) => this.findOne<T>(collection, { id: row.id })));
318
-
319
- const totalPages = Math.ceil(total / limit);
320
- return {
321
- docs: docs.filter(Boolean) as T[],
322
- totalDocs: total,
323
- limit,
324
- totalPages,
325
- page,
326
- pagingCounter: offset + 1,
327
- hasNextPage: page * limit < total,
328
- hasPrevPage: page > 1,
329
- prevPage: page > 1 ? page - 1 : null,
330
- nextPage: page < totalPages ? page + 1 : null,
331
- };
332
- }
333
-
334
- override async update<T extends object>(
335
- collection: string,
336
- query: Record<string, unknown> | string | number,
337
- data: Partial<T>,
338
- ): Promise<T> {
339
- const tableName = toSnakeCase(collection);
340
- return this._db.transaction().execute(async (tx) => {
341
- let normalizedQuery = query;
342
- if (typeof query !== "object" || query === null) {
343
- normalizedQuery = { id: query };
344
- }
345
-
346
- const current = await this.findOne<any>(
347
- collection,
348
- normalizedQuery as Record<string, unknown>,
349
- tx,
350
- );
351
- if (!current) throw new Error("Document not found");
352
-
353
- const colDef = this._collections.find((c) => c.slug === collection);
354
- const jsonFields =
355
- colDef?.fields
356
- .filter((f) => ["richtext", "json", "file"].includes(f.type))
357
- .map((f) => f.name!) || [];
358
-
359
- const flatData = flattenPayload(data, "", jsonFields);
360
-
361
- for (const field of jsonFields) {
362
- if (flatData[field] && typeof flatData[field] === "object") {
363
- flatData[field] = JSON.stringify(flatData[field]);
364
- }
365
- }
366
-
367
- const hasManyData: Record<string, unknown[]> = {};
368
- const blocksData: Record<string, unknown[]> = {};
369
-
370
- for (const key in flatData) {
371
- if (Array.isArray(flatData[key])) {
372
- const isHasMany = colDef?.fields.some(
373
- (f) => f.type === "relationship" && "hasMany" in f && f.hasMany && f.name === key,
374
- );
375
- if (isHasMany) {
376
- hasManyData[key] = flatData[key];
377
- } else {
378
- blocksData[key] = flatData[key];
379
- }
380
- delete flatData[key];
381
- }
382
- }
383
-
384
- flatData.updated_at = new Date().toISOString();
385
-
386
- if (Object.keys(flatData).length > 0) {
387
- const coercedData = await this.coerceData(collection, flatData);
388
- await tx.updateTable(tableName).set(coercedData).where("id", "=", current.id).execute();
389
- }
390
-
391
- for (const [key, values] of Object.entries(hasManyData)) {
392
- const joinTableName = `${tableName}_${toSnakeCase(key)}_relations`.toLowerCase();
393
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
394
- if (values.length > 0) {
395
- const joinData = values.map((val: any, idx: number) => {
396
- const tId = typeof val === "object" ? val.id : val;
397
- return { id: crypto.randomUUID(), source_id: current.id, target_id: tId, order: idx };
398
- });
399
- await tx.insertInto(joinTableName).values(joinData).execute();
400
- }
401
- }
402
-
403
- for (const [key, blocks] of Object.entries(blocksData)) {
404
- const fieldDef = colDef?.fields.find((f) => f.name === key);
405
- if (fieldDef?.type === "blocks" && fieldDef.blocks) {
406
- for (const b of fieldDef.blocks) {
407
- const blockTableName = `${tableName}_${toSnakeCase(key)}_${b.slug}`.toLowerCase();
408
- try {
409
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
410
- } catch (e) { }
411
- }
412
- }
413
-
414
- for (let i = 0; i < (blocks as any[]).length; i++) {
415
- const block = blocks[i] as any;
416
- if (!block.blockType) continue;
417
- const blockTableName =
418
- `${tableName}_${toSnakeCase(key)}_${block.blockType}`.toLowerCase();
419
- const bId = block.id || crypto.randomUUID();
420
-
421
- const blockConfig = (fieldDef as any)?.blocks?.find(
422
- (b: any) => b.slug === block.blockType,
423
- );
424
- const blockJsonFields =
425
- blockConfig?.fields
426
- .filter((f: any) => ["richtext", "json", "file"].includes(f.type))
427
- .map((f: any) => f.name!) || [];
428
-
429
- const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
430
-
431
- for (const f of blockJsonFields) {
432
- if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
433
- blockFlatData[f] = JSON.stringify(blockFlatData[f]);
434
- }
435
- }
436
-
437
- delete blockFlatData.blockType;
438
- const coercedBlockData = await this.coerceData(blockTableName, {
439
- ...blockFlatData,
440
- _parent_id: current.id,
441
- _order: i,
442
- block_type: block.blockType,
443
- });
444
- await tx.insertInto(blockTableName).values(coercedBlockData).execute();
445
- }
446
- }
447
-
448
- return this.findOne<T>(collection, { id: current.id }, tx) as Promise<T>;
449
- });
450
- }
451
-
452
- override async delete(
453
- collection: string,
454
- query: Record<string, unknown> | string | number,
455
- ): Promise<boolean> {
456
- const tableName = toSnakeCase(collection);
457
- let normalizedQuery = query;
458
- if (typeof query !== "object" || query === null) {
459
- normalizedQuery = { id: query };
460
- }
461
-
462
- const current = await this.findOne<any>(collection, normalizedQuery as Record<string, unknown>);
463
- if (!current) return false;
464
-
465
- await this._db.transaction().execute(async (tx) => {
466
- const colDef = this._collections.find((c) => c.slug === collection);
467
- if (colDef) {
468
- for (const field of colDef.fields) {
469
- const snakeName = toSnakeCase(field.name!);
470
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
471
- const joinTableName = `${tableName}_${snakeName}_relations`.toLowerCase();
472
- try {
473
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
474
- } catch (e) { }
475
- } else if (field.type === "blocks" && field.blocks) {
476
- for (const b of field.blocks) {
477
- const blockTableName = `${tableName}_${snakeName}_${b.slug}`.toLowerCase();
478
- try {
479
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
480
- } catch (e) { }
481
- }
482
- }
483
- }
484
- }
485
- await tx.deleteFrom(tableName).where("id", "=", current.id).execute();
486
- });
487
-
488
- return true;
489
- }
490
-
491
- override async updateMany<T extends object>(
492
- collection: string,
493
- query: Record<string, unknown>,
494
- data: Partial<T>,
495
- ): Promise<number> {
496
- const tableName = toSnakeCase(collection);
497
- return this._db.transaction().execute(async (tx) => {
498
- let qb = tx.updateTable(tableName);
499
- if (query && Object.keys(query).length > 0) {
500
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
501
- }
502
-
503
- const colDef = this._collections.find((c) => c.slug === collection);
504
- const jsonFields =
505
- colDef?.fields
506
- .filter((f) => ["richtext", "json", "file"].includes(f.type))
507
- .map((f) => f.name!) || [];
508
-
509
- const flatData = flattenPayload(data, "", jsonFields);
510
-
511
- for (const field of jsonFields) {
512
- if (flatData[field] && typeof flatData[field] === "object") {
513
- flatData[field] = JSON.stringify(flatData[field]);
514
- }
515
- }
516
-
517
- for (const key in flatData) {
518
- if (Array.isArray(flatData[key])) {
519
- delete flatData[key];
520
- }
521
- }
522
-
523
- flatData.updated_at = new Date().toISOString();
524
-
525
- if (Object.keys(flatData).length > 0) {
526
- const coercedData = await this.coerceData(collection, flatData);
527
- const result = await qb.set(coercedData).executeTakeFirst();
528
- return Number(result.numUpdatedRows || 0);
529
- }
530
- return 0;
531
- });
532
- }
533
-
534
- override async deleteMany(collection: string, query: Record<string, unknown>): Promise<number> {
535
- const tableName = toSnakeCase(collection);
536
- return this._db.transaction().execute(async (tx) => {
537
- let selectQb = tx.selectFrom(tableName).select("id");
538
- if (query && Object.keys(query).length > 0) {
539
- selectQb = selectQb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
540
- }
541
- const docs = await selectQb.execute();
542
- if (docs.length === 0) return 0;
543
-
544
- const ids = docs.map((d) => d.id as string);
545
- const colDef = this._collections.find((c) => c.slug === collection);
546
-
547
- if (colDef) {
548
- for (const field of colDef.fields) {
549
- const snakeName = toSnakeCase(field.name!);
550
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
551
- const joinTableName = `${tableName}_${snakeName}_relations`.toLowerCase();
552
- try {
553
- await tx.deleteFrom(joinTableName).where("source_id", "in", ids).execute();
554
- } catch (e) { }
555
- } else if (field.type === "blocks" && field.blocks) {
556
- for (const b of field.blocks) {
557
- const blockTableName = `${tableName}_${snakeName}_${b.slug}`.toLowerCase();
558
- try {
559
- await tx.deleteFrom(blockTableName).where("_parent_id", "in", ids).execute();
560
- } catch (e) { }
561
- }
562
- }
563
- }
564
- }
565
-
566
- const result = await tx.deleteFrom(tableName).where("id", "in", ids).executeTakeFirst();
567
- return Number(result.numDeletedRows || 0);
568
- });
569
- }
570
-
571
- override async findGlobal<T extends object>(slug: string): Promise<T | null> {
572
- const tableName = toSnakeCase(slug);
573
- const row = await this._db
574
- .selectFrom(tableName as any)
575
- .selectAll()
576
- .limit(1)
577
- .executeTakeFirst();
578
- return row ? (unflattenRow(row) as T) : null;
579
- }
580
-
581
- override async updateGlobal<T extends object>(slug: string, data: Partial<T>): Promise<T> {
582
- const tableName = toSnakeCase(slug);
583
- const existing = await this.findGlobal<any>(slug);
584
- const flatData = flattenPayload(data);
585
-
586
- const globalDef = this._globals.find((g) => g.slug === slug);
587
- const ts = globalDef?.timestamps !== false;
588
- if (ts) {
589
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
590
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
591
- flatData[updatedField] = new Date().toISOString();
592
- }
593
-
594
- if (!existing) {
595
- if (!flatData.id) flatData.id = "global";
596
- if (ts) {
597
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
598
- const createdField = toSnakeCase(config.createdAt || "createdAt");
599
- if (!flatData[createdField])
600
- flatData[createdField] = flatData[toSnakeCase(config.updatedAt || "updatedAt")];
601
- }
602
- await this._db
603
- .insertInto(tableName as any)
604
- .values(flatData)
605
- .execute();
606
- } else {
607
- await this._db
608
- .updateTable(tableName as any)
609
- .set(flatData)
610
- .where("id", "=", (existing as any).id)
611
- .execute();
612
- }
613
- return this.findGlobal<T>(slug) as Promise<T>;
614
- }
615
-
616
- override async runMigrations(): Promise<void> {
617
- const migrator = new Migrator({
618
- db: this._db,
619
- provider: new FileMigrationProvider({
620
- fs,
621
- path,
622
- migrationFolder: path.resolve(process.cwd(), this.migrationDir),
623
- }),
624
- });
625
-
626
- const { error, results } = await migrator.migrateToLatest();
627
-
628
- results?.forEach((it) => {
629
- if (it.status === "Success") {
630
- logger.success(`🚀 Migration "${it.migrationName}" was executed successfully`);
631
- } else if (it.status === "Error") {
632
- logger.error(`❌ Migration "${it.migrationName}" failed`);
633
- }
634
- });
635
-
636
- if (error) {
637
- throw error;
638
- }
639
- }
640
-
641
- override async migrate(collections: Collection[], globals: Global[] = []): Promise<void> {
642
- this._collections = collections;
643
- this._globals = globals;
644
- if (this.push) {
645
- await pushSchema(this._db, "sqlite", collections, globals, {
646
- pushDestructive: this.pushDestructive,
647
- });
648
- }
649
- }
650
- }
651
-
652
- export function createBetterSQLiteAdapter(
653
- path: string,
654
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
655
- ): BetterSQLiteAdapter {
656
- return new BetterSQLiteAdapter(path, options);
657
- }