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
package/src/db/sqlite.ts DELETED
@@ -1,660 +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, getRelationalFields, toSnakeCase } from "./kysely/field-mapper";
12
- import { buildKyselyWhere } from "./kysely/query-builder";
13
- import { pushSchema } from "./kysely/schema-builder";
14
-
15
- export class SQLiteAdapter extends BaseDatabaseAdapter {
16
- override name = "sqlite";
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 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) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
119
- .map((f) => f.name!) || [];
120
-
121
- const flatData = flattenPayload(data, "", jsonFields);
122
-
123
- const relationalFields = getRelationalFields(colDef?.fields || []);
124
- const hasManyData: Record<string, unknown[]> = {};
125
- const blocksData: Record<string, unknown[]> = {};
126
-
127
- for (const field of relationalFields) {
128
- const key = field.name!;
129
- if (Array.isArray(flatData[key])) {
130
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
131
- hasManyData[key] = flatData[key];
132
- } else if (field.type === "blocks") {
133
- blocksData[key] = flatData[key];
134
- }
135
- delete flatData[key];
136
- }
137
- }
138
-
139
- if (!flatData.id) flatData.id = crypto.randomUUID();
140
-
141
- // Whitelist only fields that exist in the database
142
- const dbFields = flattenFields(colDef?.fields || []);
143
- const validCols = new Set(dbFields.map((f: any) => toSnakeCase(f.name!)));
144
- validCols.add("id");
145
-
146
- const ts = colDef?.timestamps !== false;
147
- if (ts) {
148
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
149
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
150
- const createdField = toSnakeCase(config.createdAt || "createdAt");
151
-
152
- validCols.add(createdField);
153
- validCols.add(updatedField);
154
-
155
- if (!flatData[createdField]) flatData[createdField] = new Date().toISOString();
156
- if (!flatData[updatedField]) flatData[updatedField] = new Date().toISOString();
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)}_${toSnakeCase(block.blockType)}`.toLowerCase();
186
- const bId = block.id || crypto.randomUUID();
187
-
188
- const blockDef = relationalFields.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 relationalFields = getRelationalFields(colDef.fields);
239
- for (const field of relationalFields) {
240
- if (!field.name) continue;
241
- const snakeName = toSnakeCase(field.name);
242
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
243
- const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
244
- try {
245
- const relations = await executor
246
- .selectFrom(joinTableName)
247
- .selectAll()
248
- .where("source_id", "=", row.id)
249
- .orderBy("order", "asc")
250
- .execute();
251
- const parts = field.name.split("__");
252
- let current = unflattened;
253
- for (let i = 0; i < parts.length - 1; i++) {
254
- if (!current[parts[i]!]) current[parts[i]!] = {};
255
- current = current[parts[i]!];
256
- }
257
- current[parts[parts.length - 1]!] = relations.map((r: any) => r.target_id);
258
- } catch (e) { }
259
- } else if (field.type === "blocks" && field.blocks) {
260
- const blockData: any[] = [];
261
- for (const b of field.blocks) {
262
- const blockTableName =
263
- `${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
264
- try {
265
- const blocks = await executor
266
- .selectFrom(blockTableName)
267
- .selectAll()
268
- .where("_parent_id", "=", row.id)
269
- .execute();
270
-
271
- for (const blk of blocks) {
272
- const uf = unflattenRow(blk);
273
- uf.blockType = blk.block_type;
274
- blockData.push(uf);
275
- }
276
- } catch (e) { }
277
- }
278
- blockData.sort((a: any, b: any) => a._order - b._order);
279
- blockData.forEach((b: any) => {
280
- delete b._order;
281
- delete b._parent_id;
282
- });
283
- const parts = field.name.split("__");
284
- let current = unflattened;
285
- for (let i = 0; i < parts.length - 1; i++) {
286
- if (!current[parts[i]!]) current[parts[i]!] = {};
287
- current = current[parts[i]!];
288
- }
289
- current[parts[parts.length - 1]!] = blockData;
290
- }
291
- }
292
- }
293
-
294
- return unflattened as T;
295
- }
296
-
297
- override async find<T extends object>(
298
- collection: string,
299
- query?: Record<string, unknown>,
300
- options?: FindOptions,
301
- ): Promise<PaginatedResult<T>> {
302
- const page = options?.page || 1;
303
- const limit = options?.limit || 10;
304
- const offset = (page - 1) * limit;
305
-
306
- const total = await this.count(collection, query);
307
-
308
- let qb = this._db.selectFrom(collection).selectAll().limit(limit).offset(offset);
309
- if (query && Object.keys(query).length > 0) {
310
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
311
- }
312
- if (options?.sort) {
313
- const [col, dir] = (options.sort ?? "").split(":");
314
- if (col) {
315
- qb = qb.orderBy(col as any, dir === "desc" ? "desc" : "asc");
316
- }
317
- } else {
318
- qb = qb.orderBy("created_at" as any, "desc");
319
- }
320
-
321
- const rows = await qb.execute();
322
- const docs = await Promise.all(rows.map((row) => this.findOne<T>(collection, { id: row.id })));
323
-
324
- const totalPages = Math.ceil(total / limit);
325
- return {
326
- docs: docs.filter(Boolean) as T[],
327
- totalDocs: total,
328
- limit,
329
- totalPages,
330
- page,
331
- pagingCounter: offset + 1,
332
- hasNextPage: page * limit < total,
333
- hasPrevPage: page > 1,
334
- prevPage: page > 1 ? page - 1 : null,
335
- nextPage: page < totalPages ? page + 1 : null,
336
- };
337
- }
338
-
339
- override async update<T extends object>(
340
- collection: string,
341
- query: Record<string, unknown> | string | number,
342
- data: Partial<T>,
343
- ): Promise<T> {
344
- return this._db.transaction().execute(async (tx) => {
345
- let normalizedQuery = query;
346
- if (typeof query !== "object" || query === null) {
347
- normalizedQuery = { id: query };
348
- }
349
-
350
- const current = await this.findOne<any>(
351
- collection,
352
- normalizedQuery as Record<string, unknown>,
353
- tx,
354
- );
355
- if (!current) throw new Error("Document not found");
356
-
357
- const colDef = this._collections.find((c) => c.slug === collection);
358
- const jsonFields =
359
- colDef?.fields
360
- .filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
361
- .map((f) => f.name!) || [];
362
-
363
- const flatData = flattenPayload(data, "", jsonFields);
364
-
365
- const relationalFields = getRelationalFields(colDef?.fields || []);
366
- const hasManyData: Record<string, unknown[]> = {};
367
- const blocksData: Record<string, unknown[]> = {};
368
-
369
- for (const field of relationalFields) {
370
- const key = field.name!;
371
- if (Array.isArray(flatData[key])) {
372
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
373
- hasManyData[key] = flatData[key];
374
- } else if (field.type === "blocks") {
375
- blocksData[key] = flatData[key];
376
- }
377
- delete flatData[key];
378
- }
379
- }
380
-
381
- const ts = colDef?.timestamps !== false;
382
- if (ts) {
383
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
384
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
385
- flatData[updatedField] = new Date().toISOString();
386
- }
387
-
388
- if (Object.keys(flatData).length > 0) {
389
- const coercedData = await this.coerceData(collection, flatData);
390
- await tx.updateTable(collection).set(coercedData).where("id", "=", current.id).execute();
391
- }
392
-
393
- for (const [key, values] of Object.entries(hasManyData)) {
394
- const joinTableName = `${collection}_${toSnakeCase(key)}_relations`.toLowerCase();
395
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
396
- if (values.length > 0) {
397
- const joinData = values.map((val: any, idx: number) => {
398
- const tId = typeof val === "object" ? val.id : val;
399
- return { id: crypto.randomUUID(), source_id: current.id, target_id: tId, order: idx };
400
- });
401
- await tx.insertInto(joinTableName).values(joinData).execute();
402
- }
403
- }
404
-
405
- for (const [key, blocks] of Object.entries(blocksData)) {
406
- const fieldDef = relationalFields.find((f) => f.name === key && f.type === "blocks");
407
- if (fieldDef?.type === "blocks" && fieldDef.blocks) {
408
- for (const b of fieldDef.blocks) {
409
- const blockTableName =
410
- `${collection}_${toSnakeCase(key)}_${toSnakeCase(b.slug)}`.toLowerCase();
411
- try {
412
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
413
- } catch (e) { }
414
- }
415
- }
416
-
417
- for (let i = 0; i < (blocks as any[]).length; i++) {
418
- const block = blocks[i] as any;
419
- if (!block.blockType) continue;
420
- const blockTableName =
421
- `${collection}_${toSnakeCase(key)}_${toSnakeCase(block.blockType)}`.toLowerCase();
422
- const bId = block.id || crypto.randomUUID();
423
-
424
- const blockConfig = (fieldDef as any)?.blocks?.find(
425
- (b: any) => b.slug === block.blockType,
426
- );
427
- const blockJsonFields =
428
- blockConfig?.fields
429
- .filter((f: any) => ["richtext", "json", "file"].includes(f.type))
430
- .map((f: any) => f.name!) || [];
431
-
432
- const blockFlatData = flattenPayload({ ...block, id: bId }, "", blockJsonFields);
433
-
434
- for (const f of blockJsonFields) {
435
- if (blockFlatData[f] && typeof blockFlatData[f] === "object") {
436
- blockFlatData[f] = JSON.stringify(blockFlatData[f]);
437
- }
438
- }
439
-
440
- delete blockFlatData.blockType;
441
- const coercedBlockData = await this.coerceData(blockTableName, {
442
- ...blockFlatData,
443
- _parent_id: current.id,
444
- _order: i,
445
- block_type: block.blockType,
446
- });
447
- await tx.insertInto(blockTableName).values(coercedBlockData).execute();
448
- }
449
- }
450
-
451
- return this.findOne<T>(collection, { id: current.id }, tx) as Promise<T>;
452
- });
453
- }
454
-
455
- override async delete(
456
- collection: string,
457
- query: Record<string, unknown> | string | number,
458
- ): Promise<boolean> {
459
- let normalizedQuery = query;
460
- if (typeof query !== "object" || query === null) {
461
- normalizedQuery = { id: query };
462
- }
463
-
464
- const current = await this.findOne<any>(collection, normalizedQuery as Record<string, unknown>);
465
- if (!current) return false;
466
-
467
- await this._db.transaction().execute(async (tx) => {
468
- const colDef = this._collections.find((c) => c.slug === collection);
469
- if (colDef) {
470
- const relationalFields = getRelationalFields(colDef.fields);
471
- for (const field of relationalFields) {
472
- if (!field.name) continue;
473
- const snakeName = toSnakeCase(field.name);
474
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
475
- const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
476
- try {
477
- await tx.deleteFrom(joinTableName).where("source_id", "=", current.id).execute();
478
- } catch (e) { }
479
- } else if (field.type === "blocks" && field.blocks) {
480
- for (const b of field.blocks) {
481
- const blockTableName =
482
- `${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
483
- try {
484
- await tx.deleteFrom(blockTableName).where("_parent_id", "=", current.id).execute();
485
- } catch (e) { }
486
- }
487
- }
488
- }
489
- }
490
- await tx.deleteFrom(collection).where("id", "=", current.id).execute();
491
- });
492
-
493
- return true;
494
- }
495
-
496
- override async updateMany<T extends object>(
497
- collection: string,
498
- query: Record<string, unknown>,
499
- data: Partial<T>,
500
- ): Promise<number> {
501
- return this._db.transaction().execute(async (tx) => {
502
- let qb = tx.updateTable(collection);
503
- if (query && Object.keys(query).length > 0) {
504
- qb = qb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
505
- }
506
-
507
- const colDef = this._collections.find((c) => c.slug === collection);
508
- const jsonFields =
509
- colDef?.fields
510
- .filter((f) => f.name && (["richtext", "json", "file"].includes(f.type) || f.localized))
511
- .map((f) => f.name!) || [];
512
-
513
- const flatData = flattenPayload(data, "", jsonFields);
514
-
515
- for (const key in flatData) {
516
- if (Array.isArray(flatData[key])) {
517
- delete flatData[key];
518
- }
519
- }
520
-
521
- const ts = colDef?.timestamps !== false;
522
- if (ts) {
523
- const config = typeof colDef?.timestamps === "object" ? colDef.timestamps : {};
524
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
525
- flatData[updatedField] = new Date().toISOString();
526
- }
527
-
528
- if (Object.keys(flatData).length > 0) {
529
- const coercedData = await this.coerceData(collection, flatData);
530
- const result = await qb.set(coercedData).executeTakeFirst();
531
- return Number(result.numUpdatedRows || 0);
532
- }
533
- return 0;
534
- });
535
- }
536
-
537
- override async deleteMany(collection: string, query: Record<string, unknown>): Promise<number> {
538
- return this._db.transaction().execute(async (tx) => {
539
- let selectQb = tx.selectFrom(collection).select("id");
540
- if (query && Object.keys(query).length > 0) {
541
- selectQb = selectQb.where((eb) => buildKyselyWhere(eb, query) || eb.val(true));
542
- }
543
- const docs = await selectQb.execute();
544
- if (docs.length === 0) return 0;
545
-
546
- const ids = docs.map((d) => d.id as string);
547
- const colDef = this._collections.find((c) => c.slug === collection);
548
-
549
- if (colDef) {
550
- const relationalFields = getRelationalFields(colDef.fields);
551
- for (const field of relationalFields) {
552
- if (!field.name) continue;
553
- const snakeName = toSnakeCase(field.name);
554
- if (field.type === "relationship" && "hasMany" in field && field.hasMany) {
555
- const joinTableName = `${collection}_${snakeName}_relations`.toLowerCase();
556
- try {
557
- await tx.deleteFrom(joinTableName).where("source_id", "in", ids).execute();
558
- } catch (e) { }
559
- } else if (field.type === "blocks" && field.blocks) {
560
- for (const b of field.blocks) {
561
- const blockTableName =
562
- `${collection}_${snakeName}_${toSnakeCase(b.slug)}`.toLowerCase();
563
- try {
564
- await tx.deleteFrom(blockTableName).where("_parent_id", "in", ids).execute();
565
- } catch (e) { }
566
- }
567
- }
568
- }
569
- }
570
-
571
- const result = await tx.deleteFrom(collection).where("id", "in", ids).executeTakeFirst();
572
- return Number(result.numDeletedRows || 0);
573
- });
574
- }
575
-
576
- override async findGlobal<T extends object>(slug: string): Promise<T | null> {
577
- const row = await this._db
578
- .selectFrom(slug as any)
579
- .selectAll()
580
- .limit(1)
581
- .executeTakeFirst();
582
- return row ? (unflattenRow(row) as T) : null;
583
- }
584
-
585
- override async updateGlobal<T extends object>(slug: string, data: Partial<T>): Promise<T> {
586
- const existing = await this.findGlobal<any>(slug);
587
- const flatData = flattenPayload(data);
588
-
589
- const globalDef = this._globals.find((g) => g.slug === slug);
590
- const ts = globalDef?.timestamps !== false;
591
- if (ts) {
592
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
593
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
594
- flatData[updatedField] = new Date().toISOString();
595
- }
596
-
597
- if (!existing) {
598
- if (!flatData.id) flatData.id = "global";
599
- if (ts) {
600
- const config = typeof globalDef?.timestamps === "object" ? globalDef.timestamps : {};
601
- const createdField = toSnakeCase(config.createdAt || "createdAt");
602
- if (!flatData[createdField])
603
- flatData[createdField] = flatData[toSnakeCase(config.updatedAt || "updatedAt")];
604
- }
605
- await this._db
606
- .insertInto(slug as any)
607
- .values(flatData)
608
- .execute();
609
- } else {
610
- await this._db
611
- .updateTable(slug as any)
612
- .set(flatData)
613
- .where("id", "=", (existing as any).id)
614
- .execute();
615
- }
616
- return this.findGlobal<T>(slug) as Promise<T>;
617
- }
618
-
619
- override async runMigrations(): Promise<void> {
620
- const migrator = new Migrator({
621
- db: this._db,
622
- provider: new FileMigrationProvider({
623
- fs,
624
- path,
625
- migrationFolder: path.resolve(process.cwd(), this.migrationDir),
626
- }),
627
- });
628
-
629
- const { error, results } = await migrator.migrateToLatest();
630
-
631
- results?.forEach((it) => {
632
- if (it.status === "Success") {
633
- logger.success(`🚀 Migration "${it.migrationName}" was executed successfully`);
634
- } else if (it.status === "Error") {
635
- logger.error(`❌ Migration "${it.migrationName}" failed`);
636
- }
637
- });
638
-
639
- if (error) {
640
- throw error;
641
- }
642
- }
643
-
644
- override async migrate(collections: Collection[], globals: Global[] = []): Promise<void> {
645
- this._collections = collections;
646
- this._globals = globals;
647
- if (this.push) {
648
- await pushSchema(this._db, "sqlite", collections, globals, {
649
- pushDestructive: this.pushDestructive,
650
- });
651
- }
652
- }
653
- }
654
-
655
- export function createSQLiteAdapter(
656
- path: string,
657
- options?: { push?: boolean; pushDestructive?: boolean; migrationDir?: string },
658
- ): SQLiteAdapter {
659
- return new SQLiteAdapter(path, options);
660
- }