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,15 +0,0 @@
1
- import r2wc from "@r2wc/react-to-web-component";
2
- import { AdminClient } from "./ui/admin-client";
3
- import "./ui/styles/index.scss";
4
-
5
- const OpacaAdminWebComponent = r2wc(AdminClient, {
6
- props: {
7
- serverUrl: "string",
8
- config: "json",
9
- initialNeedsInit: "boolean",
10
- },
11
- });
12
-
13
- if (typeof window !== "undefined" && !customElements.get("opaca-admin")) {
14
- customElements.define("opaca-admin", OpacaAdminWebComponent);
15
- }
package/src/api.ts DELETED
@@ -1,9 +0,0 @@
1
- // API-only entry point (runtime agnostic - works in Next.js, Bun, Node, Edge)
2
- // DB adapters are imported separately via opacacms/db/postgres, opacacms/db/sqlite, etc.
3
-
4
- export * from "./config";
5
- export * from "./db/adapter";
6
- export * from "./server/admin";
7
- export * from "./server/handlers";
8
- export * from "./server/router";
9
- export * from "./types";
package/src/auth/index.ts DELETED
@@ -1,194 +0,0 @@
1
- import { apiKey } from "@better-auth/api-key";
2
- import { betterAuth } from "better-auth";
3
- import { admin } from "better-auth/plugins";
4
- import { CamelCasePlugin } from "kysely";
5
-
6
- import type { OpacaConfig } from "../types";
7
- import { createPermissions } from "./premissions";
8
-
9
- export async function createAuth(config: OpacaConfig) {
10
- const userAuth = config.auth || {};
11
- const trustedOrigins = config.trustedOrigins;
12
-
13
- const { ac, roles } = createPermissions(config);
14
-
15
- const rawDb = config.db.raw;
16
-
17
- const env = (typeof process !== "undefined" ? process.env : {}) as any;
18
-
19
- const baseURL = String(config.serverURL || env.BETTER_AUTH_URL || "").replace(/\/$/, "");
20
-
21
- if (!baseURL) {
22
- throw new Error(
23
- "[OpacaAuth] baseURL could not be determined. Please provide 'serverURL' in your config or 'BETTER_AUTH_URL' in your environment.",
24
- );
25
- }
26
-
27
- const authURL = `${baseURL}/api/auth`;
28
-
29
- const secret = env.OPACA_SECRET || env.BETTER_AUTH_SECRET || config.secret;
30
-
31
- if (!secret) {
32
- throw new Error(
33
- "[OpacaAuth] No secret found for authentication. Please provide 'OPACA_SECRET' or 'BETTER_AUTH_SECRET'.",
34
- );
35
- }
36
-
37
- if (typeof process !== "undefined" && !env.BETTER_AUTH_URL) {
38
- process.env.BETTER_AUTH_URL = authURL;
39
- }
40
-
41
- let databaseConfig: any;
42
-
43
- if (config.db.name === "postgres" && rawDb) {
44
- const { PostgresJSDialect } = await import("kysely-postgres-js");
45
- const { Kysely } = await import("kysely");
46
-
47
- const kysely = new Kysely({
48
- dialect: new PostgresJSDialect({ postgres: rawDb as any }),
49
- plugins: [new CamelCasePlugin()],
50
- });
51
-
52
- databaseConfig = {
53
- db: kysely,
54
- type: "pg",
55
- };
56
- } else if (config.db.name === "d1" && rawDb) {
57
- const { D1Dialect } = await import("kysely-d1");
58
- const { Kysely } = await import("kysely");
59
-
60
- const kysely = new Kysely({
61
- dialect: new D1Dialect({ database: rawDb as any }),
62
- plugins: [new CamelCasePlugin()],
63
- });
64
-
65
- databaseConfig = {
66
- db: kysely,
67
- type: "sqlite",
68
- };
69
- } else {
70
- // Fallback for Bun SQLite or other SQLite variants compatible with direct binding
71
- databaseConfig = {
72
- db: rawDb,
73
- type: "sqlite",
74
- };
75
- }
76
-
77
- const isSecure = baseURL.startsWith("https");
78
-
79
- const plugins = [
80
- admin({
81
- ac,
82
- roles,
83
- }),
84
- ...(userAuth.features?.apiKeys?.enabled
85
- ? [
86
- apiKey({
87
- defaultPrefix: "opaca_",
88
- schema: {
89
- apikey: {
90
- modelName: "_api_keys",
91
- },
92
- },
93
- }),
94
- ]
95
- : []),
96
- ];
97
-
98
- // Not dynamically importing two-factor as it's not present,
99
- // but if we were to support it without installing:
100
- // if (userAuth.features?.mfa?.enabled) {
101
- // const { twoFactor } = require('@better-auth/two-factor');
102
- // plugins.push(twoFactor({ issuer: userAuth.features.mfa.issuer }));
103
- // }
104
-
105
- const socialProviders: Record<string, any> = {};
106
- if (userAuth.socialProviders?.github) {
107
- socialProviders.github = userAuth.socialProviders.github;
108
- }
109
- if (userAuth.socialProviders?.google) {
110
- socialProviders.google = userAuth.socialProviders.google;
111
- }
112
-
113
- return betterAuth({
114
- // FORCE OpacaCMS global database connection
115
- database: databaseConfig,
116
-
117
- // FORCE predictable API routing
118
- baseURL: baseURL,
119
- basePath: "/api/auth",
120
- secret: secret,
121
- trustedOrigins,
122
-
123
- // Map strictly constrained user strategies
124
- emailAndPassword: {
125
- enabled: userAuth.strategies?.emailPassword !== false,
126
- },
127
-
128
- socialProviders,
129
-
130
- // Forced model names for system integrity
131
- user: {
132
- modelName: "_users",
133
- },
134
-
135
- session: {
136
- modelName: "_sessions",
137
- expiresIn: (userAuth.session?.expiresInDays || 30) * 86400,
138
- updateAge: userAuth.session?.updateAgeSeconds || 86400,
139
- },
140
-
141
- account: {
142
- modelName: "_accounts",
143
- },
144
-
145
- verification: {
146
- modelName: "_verifications",
147
- },
148
-
149
- advanced: {
150
- useSecureCookies: isSecure,
151
- defaultCookieAttributes: {
152
- sameSite: (isSecure ? "none" : "lax") as any,
153
- secure: isSecure,
154
- },
155
- },
156
-
157
- databaseHooks: {
158
- user: {
159
- create: {
160
- before: async (user) => {
161
- try {
162
- let userCount = 0;
163
- try {
164
- userCount = await config.db.count("_users");
165
- } catch (e) {
166
- // Fallback: the "_users" collection might not be in the OpacaCMS schema
167
- // but the table exists in the DB (managed by better-auth).
168
- const result = await config.db.unsafe("SELECT COUNT(*) as count FROM _users");
169
- // Handle different response formats (D1 vs Others)
170
- const rows = (result as any)?.results || result || [];
171
- userCount = Number(rows[0]?.count || rows[0]?.["count(*)"] || 0);
172
- }
173
-
174
- if (userCount === 0) {
175
- return {
176
- data: {
177
- ...user,
178
- role: "admin",
179
- },
180
- };
181
- }
182
- } catch (e) {
183
- console.error("[OpacaAuth] Failed to check user count in hook:", e);
184
- }
185
- },
186
- },
187
- },
188
- },
189
-
190
- plugins,
191
- });
192
- }
193
-
194
- export type Auth = Awaited<ReturnType<typeof createAuth>>;
@@ -1,87 +0,0 @@
1
- import { toSnakeCase } from "../db/kysely/field-mapper";
2
- import { getSystemCollections } from "../db/system-schema";
3
- import type { DatabaseAdapter, Field } from "../types";
4
- import { logger } from "../utils/logger";
5
-
6
- /**
7
- * Creates the Better Auth core tables using raw SQL if they don't exist.
8
- */
9
- export async function runAuthMigrations(db: DatabaseAdapter) {
10
- const rawDb = db.raw;
11
-
12
- if (!rawDb) {
13
- logger.error("Database not connected yet. Skipping auth migrations.");
14
- return;
15
- }
16
-
17
- const isPostgres = db.name === "postgres";
18
- const authCollections = getSystemCollections().filter((c) =>
19
- ["_users", "_sessions", "_accounts", "_verifications", "_api_keys"].includes(c.slug),
20
- );
21
-
22
- try {
23
- for (const collection of authCollections) {
24
- const columnDefs: string[] = [];
25
-
26
- // Primary Key
27
- columnDefs.push(`"id" TEXT PRIMARY KEY`);
28
-
29
- for (const field of collection.fields) {
30
- if (field.name === "id") continue;
31
-
32
- let type = "TEXT";
33
- if (field.type === "number") type = "INTEGER";
34
- if (field.type === "boolean") type = isPostgres ? "BOOLEAN" : "INTEGER";
35
- if (field.type === "date") type = isPostgres ? "TIMESTAMPTZ" : "TEXT";
36
-
37
- let definition = `"${toSnakeCase(field.name!)}" ${type}`;
38
-
39
- if (field.required) definition += " NOT NULL";
40
- if (field.unique) definition += " UNIQUE";
41
-
42
- if (field.defaultValue !== undefined) {
43
- const val =
44
- typeof field.defaultValue === "string" ? `'${field.defaultValue}'` : field.defaultValue;
45
- definition += ` DEFAULT ${val}`;
46
- }
47
-
48
- if (field.references) {
49
- definition += ` REFERENCES "${field.references.table}"("${toSnakeCase(field.references.column)}")`;
50
- if (field.references.onDelete) {
51
- definition += ` ON DELETE ${field.references.onDelete.toUpperCase()}`;
52
- }
53
- }
54
-
55
- columnDefs.push(definition);
56
- }
57
-
58
- const ts = (collection as any).timestamps;
59
- if (ts !== false && ts !== undefined) {
60
- const config = typeof ts === "object" ? ts : {};
61
- const createdField = toSnakeCase(config.createdAt || "createdAt");
62
- const updatedField = toSnakeCase(config.updatedAt || "updatedAt");
63
-
64
- // Check if they are already in fields (to avoid duplicates)
65
- const fieldNames = new Set(collection.fields.map((f) => toSnakeCase(f.name!)));
66
-
67
- if (!fieldNames.has(createdField)) {
68
- columnDefs.push(
69
- `"${createdField}" ${isPostgres ? "TIMESTAMPTZ" : "TEXT"} DEFAULT CURRENT_TIMESTAMP`,
70
- );
71
- }
72
- if (!fieldNames.has(updatedField)) {
73
- columnDefs.push(
74
- `"${updatedField}" ${isPostgres ? "TIMESTAMPTZ" : "TEXT"} DEFAULT CURRENT_TIMESTAMP`,
75
- );
76
- }
77
- }
78
-
79
- logger.info(` -> Verifying table: ${logger.format("green", `"${collection.slug}"`)}`);
80
- await db.unsafe(`CREATE TABLE IF NOT EXISTS "${collection.slug}" (${columnDefs.join(", ")})`);
81
- }
82
-
83
- logger.success("Auth tables verified/created successfully.");
84
- } catch (error) {
85
- logger.error("Failed to create auth tables:", error);
86
- }
87
- }
@@ -1,46 +0,0 @@
1
- import { createAccessControl } from "better-auth/plugins/access";
2
- import type { OpacaConfig } from "../types";
3
-
4
- export function createPermissions(config: OpacaConfig): {
5
- ac: ReturnType<typeof createAccessControl>;
6
- roles: Record<string, any>;
7
- } {
8
- const resources: Record<string, string[]> = {
9
- user: ["create", "read", "update", "delete", "ban", "impersonate"],
10
- session: ["read", "revoke", "delete"],
11
- };
12
-
13
- for (const collection of config.collections) {
14
- resources[collection.slug] = ["create", "read", "update", "delete"];
15
- }
16
-
17
- const ac = createAccessControl(resources);
18
-
19
- const adminRole = ac.newRole({
20
- user: ["create", "read", "update", "delete", "ban", "impersonate"],
21
- session: ["read", "revoke", "delete"],
22
- });
23
-
24
- for (const collection of config.collections) {
25
- // @ts-expect-error dynamic role extension
26
- adminRole[collection.slug] = ["create", "read", "update", "delete"];
27
- }
28
-
29
- const userRole = ac.newRole({});
30
-
31
- const roles: Record<string, any> = {
32
- admin: adminRole,
33
- user: userRole,
34
- };
35
-
36
- if (config.access?.roles) {
37
- for (const [roleName, permissions] of Object.entries(config.access.roles)) {
38
- roles[roleName] = ac.newRole(permissions as Record<string, string[]>);
39
- }
40
- }
41
-
42
- return {
43
- ac,
44
- roles,
45
- };
46
- }
@@ -1,116 +0,0 @@
1
- import fs from "node:fs";
2
- import { resolve } from "node:path";
3
- import type { SerializableConfig } from "../../types";
4
-
5
- export async function generateTypesCommand(url: string, token: string, out: string) {
6
- console.log(`[OpacaCMS] Fetching metadata from ${url}/api/__admin/metadata...`);
7
-
8
- let data: SerializableConfig;
9
- try {
10
- const res = await fetch(`${url.replace(/\/$/, "")}/api/__admin/metadata`, {
11
- headers: {
12
- Authorization: `Bearer ${token}`,
13
- },
14
- });
15
-
16
- if (!res.ok) {
17
- if (res.status === 401 || res.status === 403) {
18
- throw new Error(
19
- "Authentication failed. Ensure your API Key is correct and has the necessary permissions.",
20
- );
21
- }
22
- const errorText = await res.text().catch(() => "Unknown error");
23
- throw new Error(`Server responded with ${res.status}: ${errorText}`);
24
- }
25
-
26
- data = await res.json();
27
- } catch (err: any) {
28
- console.error(`[OpacaCMS] Failed to fetch metadata: ${err.message}`);
29
- process.exit(1);
30
- }
31
-
32
- console.log(
33
- `[OpacaCMS] Successfully fetched metadata for ${data.collections.length} collections and ${data.globals?.length || 0} globals.`,
34
- );
35
-
36
- let dtsContent = `// Automatically generated by OpacaCMS CLI
37
- // Do not edit this file manually
38
-
39
- export interface OpacaAsset {
40
- assetId: string;
41
- url: string;
42
- filename: string;
43
- mime_type: string;
44
- filesize: number;
45
- meta?: Record<string, any>;
46
- }
47
-
48
- export interface OpacaCollections {
49
- collections: {
50
- `;
51
-
52
- // Process Collections
53
- for (const collection of data.collections) {
54
- dtsContent += ` "${collection.slug}": {\n`;
55
- dtsContent += ` id: string | number;\n`;
56
- for (const field of collection.fields) {
57
- const typeStr = mapFieldToTsType(field.type);
58
- const isOptional = field.required ? "" : "?";
59
- dtsContent += ` ${field.name}${isOptional}: ${typeStr};\n`;
60
- }
61
- if (collection.timestamps) {
62
- dtsContent += ` createdAt: string;\n`;
63
- dtsContent += ` updatedAt: string;\n`;
64
- }
65
- dtsContent += ` };\n`;
66
- }
67
-
68
- dtsContent += ` };\n`;
69
-
70
- // Process Globals
71
- if (data.globals && data.globals.length > 0) {
72
- dtsContent += ` globals: {\n`;
73
- for (const globalConf of data.globals) {
74
- dtsContent += ` "${globalConf.slug}": {\n`;
75
- for (const field of globalConf.fields) {
76
- const typeStr = mapFieldToTsType(field.type);
77
- const isOptional = field.required ? "" : "?";
78
- dtsContent += ` ${field.name}${isOptional}: ${typeStr};\n`;
79
- }
80
- dtsContent += ` };\n`;
81
- }
82
- dtsContent += ` };\n`;
83
- } else {
84
- dtsContent += ` globals: Record<string, any>;\n`;
85
- }
86
-
87
- dtsContent += `}\n`;
88
-
89
- const outputPath = resolve(process.cwd(), out || "opaca-types.d.ts");
90
- fs.writeFileSync(outputPath, dtsContent);
91
-
92
- console.log(`[OpacaCMS] Types successfully generated at ${outputPath}`);
93
- }
94
-
95
- function mapFieldToTsType(type: string): string {
96
- switch (type) {
97
- case "text":
98
- case "textarea":
99
- case "richtext":
100
- case "select":
101
- case "date":
102
- return "string";
103
- case "number":
104
- return "number";
105
- case "boolean":
106
- return "boolean";
107
- case "json":
108
- return "any | any[]";
109
- case "file":
110
- return "OpacaAsset";
111
- case "relationship":
112
- return "string | number | any"; // Can be ID or populated object
113
- default:
114
- return "any";
115
- }
116
- }
@@ -1,95 +0,0 @@
1
- import fs from "node:fs";
2
- import { resolve } from "node:path";
3
-
4
- export async function initCommand(target: string, example?: string) {
5
- console.log(`[OpacaCMS] Initializing new project in ./${target}...`);
6
-
7
- if (example) {
8
- console.log(`[OpacaCMS] Using example template: ${example}`);
9
-
10
- // Breadth-first or climbing up search for examples
11
- let currentDir = resolve(import.meta.dirname);
12
- let exampleDir = "";
13
-
14
- // Try process.cwd() first
15
- const localExample = resolve(process.cwd(), "examples", example);
16
- if (fs.existsSync(localExample)) {
17
- exampleDir = localExample;
18
- } else {
19
- // Climb up from source
20
- while (currentDir !== resolve(currentDir, "..")) {
21
- const potential = resolve(currentDir, "examples", example);
22
- if (fs.existsSync(potential)) {
23
- exampleDir = potential;
24
- break;
25
- }
26
- currentDir = resolve(currentDir, "..");
27
- }
28
- }
29
-
30
- if (!exampleDir) {
31
- console.error(
32
- `[OpacaCMS] Example ${example} not found.`,
33
- );
34
- process.exit(1);
35
- }
36
- fs.cpSync(exampleDir, resolve(process.cwd(), target), { recursive: true });
37
- console.log(`[OpacaCMS] Copied example ${example} to ${target}!`);
38
- return;
39
- }
40
-
41
- console.log(`[OpacaCMS] Generating default boilerplate...`);
42
- fs.mkdirSync(resolve(process.cwd(), target), { recursive: true });
43
-
44
- const configCode = `import { defineConfig } from 'opacacms';
45
- import { createSQLiteAdapter } from 'opacacms/db/sqlite';
46
-
47
- export default defineConfig({
48
- appName: "My OpacaCMS App",
49
- db: createSQLiteAdapter('local.db'),
50
- collections: [
51
- {
52
- slug: 'posts',
53
- fields: [
54
- { name: 'title', type: 'text', required: true },
55
- { name: 'content', type: 'text' }
56
- ]
57
- }
58
- ]
59
- });
60
- `;
61
- fs.writeFileSync(resolve(process.cwd(), target, "opacacms.config.ts"), configCode);
62
-
63
- const serverCode = `import { Hono } from 'hono';
64
- import { createAPIRouter } from 'opacacms/server';
65
- import config from './opacacms.config';
66
-
67
- const app = new Hono();
68
- app.route('/api', createAPIRouter(config));
69
-
70
- export default app;
71
- `;
72
- fs.writeFileSync(resolve(process.cwd(), target, "index.ts"), serverCode);
73
-
74
- const pkgJson = {
75
- name: target,
76
- type: "module",
77
- scripts: {
78
- start: "bun run index.ts",
79
- dev: "bun run --watch index.ts",
80
- },
81
- dependencies: {
82
- opacacms: "latest",
83
- hono: "^4.0.0",
84
- },
85
- };
86
- fs.writeFileSync(
87
- resolve(process.cwd(), target, "package.json"),
88
- JSON.stringify(pkgJson, null, 2),
89
- );
90
-
91
- console.log(`[OpacaCMS] Project created successfully!`);
92
- console.log(`\ncd ${target}`);
93
- console.log(`bun install`);
94
- console.log(`bun run dev\n`);
95
- }