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