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