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,27 +0,0 @@
1
- import type { Context, Next } from "hono";
2
-
3
- export const adminMiddleware = async (c: Context, next: Next) => {
4
- const user = c.get("user");
5
-
6
- // Check if it's one of the few allowed "public" admin endpoints
7
- const isPublicAdmin =
8
- c.req.path.endsWith("/__admin/metadata") || c.req.path.endsWith("/__admin/setup");
9
-
10
- if (!user && !isPublicAdmin) {
11
- return c.json({ message: "Unauthorized" }, 401);
12
- }
13
-
14
- // Public admin endpoints are allowed anonymously (they return sanitized safe data)
15
- if (isPublicAdmin) {
16
- await next();
17
- return;
18
- }
19
-
20
- // For everything else, require authenticated user with admin role
21
- if (user.role === "admin" || user.role?.includes("admin")) {
22
- await next();
23
- return;
24
- }
25
-
26
- return c.json({ message: "Forbidden" }, 403);
27
- };
@@ -1,89 +0,0 @@
1
- import type { Session, User } from "better-auth";
2
- import type { Context, MiddlewareHandler, Next } from "hono";
3
- import type { Auth } from "../../auth";
4
- import { logger } from "../../utils/logger";
5
-
6
- export type AuthContextVariables = {
7
- user: User | null;
8
- session: Session | null;
9
- apiKey?: {
10
- id: string;
11
- name: string | null;
12
- permissions?: Record<string, string[]> | null;
13
- referenceId: string;
14
- } | null;
15
- };
16
-
17
- export function createAuthMiddleware(
18
- getAuth: () => Auth | undefined,
19
- ): MiddlewareHandler<{ Variables: AuthContextVariables }> {
20
- return async (c: Context, next: Next) => {
21
- const auth = getAuth();
22
-
23
- if (!auth) {
24
- c.set("user", null);
25
- c.set("session", null);
26
- c.set("apiKey", null);
27
- await next();
28
- return;
29
- }
30
-
31
- // 1. Try Session Auth
32
- const session = await auth.api.getSession({ headers: c.req.raw.headers });
33
- if (session) {
34
- c.set("user", session.user);
35
- c.set("session", session.session);
36
- c.set("apiKey", null);
37
- await next();
38
- return;
39
- }
40
-
41
- // 2. Try API Key Auth
42
- const authHeader = c.req.header("Authorization");
43
- if (authHeader && authHeader.startsWith("Bearer ")) {
44
- const token = authHeader.split(" ")[1];
45
- if (token) {
46
- try {
47
- // verifyApiKey expects { headers, body: { key: string } }
48
- const result = await (auth.api as any).verifyApiKey({
49
- headers: c.req.raw.headers,
50
- body: { key: token },
51
- });
52
-
53
- if (result && result.valid && result.key) {
54
- c.set("apiKey", {
55
- id: result.key.id,
56
- name: result.key.name,
57
- permissions: result.key.permissions,
58
- referenceId: result.key.referenceId,
59
- });
60
-
61
- // Optimize fetching User for API Keys by reading directly from local context or optimized DB query
62
- // Instead of fully simulating `auth.api.getUser`, we can extract the user info directly
63
- // from the adapter.
64
- try {
65
- const ownerResult = await auth.options.database?.findOne?.("_users", {
66
- id: result.key.referenceId,
67
- });
68
- c.set("user", ownerResult || null);
69
- } catch (e) {
70
- logger.warn("Failed to fetch API key owner from database:", e);
71
- c.set("user", null);
72
- }
73
-
74
- c.set("session", null);
75
- await next();
76
- return;
77
- }
78
- } catch (err) {
79
- logger.warn("API Key verification failed:", err);
80
- }
81
- }
82
- }
83
-
84
- c.set("user", null);
85
- c.set("session", null);
86
- c.set("apiKey", null);
87
- await next();
88
- };
89
- }
@@ -1,17 +0,0 @@
1
- import type { Context, MiddlewareHandler, Next } from "hono";
2
- import type { OpacaConfig } from "../../types";
3
-
4
- export type OpacaContextVariables = {
5
- config: OpacaConfig;
6
- db: OpacaConfig["db"];
7
- };
8
-
9
- export function createContextMiddleware(
10
- config: OpacaConfig,
11
- ): MiddlewareHandler<{ Variables: OpacaContextVariables }> {
12
- return async (c: Context, next: Next) => {
13
- c.set("config", config);
14
- c.set("db", config.db);
15
- await next();
16
- };
17
- }
@@ -1,24 +0,0 @@
1
- import type { MiddlewareHandler } from "hono";
2
- import { cors } from "hono/cors";
3
- import type { OpacaConfig } from "../../types";
4
-
5
- export function createCorsMiddleware(config: OpacaConfig): MiddlewareHandler {
6
- const trustedOrigins = config.trustedOrigins || [];
7
-
8
- return cors({
9
- origin: async (origin, _c) => {
10
- // If trustedOrigins is a function, evaluate it
11
- const allowed =
12
- typeof trustedOrigins === "function" ? await trustedOrigins(_c.req.raw) : trustedOrigins;
13
-
14
- // If origin is in the list, allow it. If the list is empty, allow none (safe default)
15
- if (Array.isArray(allowed) && allowed.includes(origin)) {
16
- return origin;
17
- }
18
- return undefined;
19
- },
20
- allowMethods: ["POST", "GET", "PUT", "PATCH", "DELETE", "OPTIONS"],
21
- exposeHeaders: ["Content-Length"],
22
- credentials: true,
23
- });
24
- }
@@ -1,74 +0,0 @@
1
- import type { MiddlewareHandler } from "hono";
2
- import { type Auth, createAuth } from "../../auth";
3
- import { runAuthMigrations } from "../../auth/migrations";
4
- import { getSystemCollections } from "../../db/system-schema";
5
- import type { OpacaConfig } from "../../types";
6
- import { logger } from "../../utils/logger";
7
-
8
- /**
9
- * Middleware for database connection and schema synchronization.
10
- * This runs once per server startup via a 'migrated' flag in the shared state.
11
- */
12
- export function createDatabaseInitMiddleware(
13
- config: OpacaConfig,
14
- state: { auth: Auth | undefined; migrated: boolean },
15
- ): MiddlewareHandler {
16
- const supportsAuth =
17
- config.db.name === "sqlite" || config.db.name === "postgres" || config.db.name === "d1";
18
-
19
- return async (_c, next) => {
20
- if (!state.migrated) {
21
- const isDev = typeof process !== "undefined" && process.env.NODE_ENV !== "production";
22
-
23
- if (isDev) {
24
- logger.info(`Connecting to database: ${logger.format("yellow", config.db.name)}...`);
25
- } else {
26
- logger.debug(`Connecting to database: ${config.db.name}...`);
27
- }
28
-
29
- await config.db.connect();
30
-
31
- // 1. Load internal schema mapping (Always required for adapter to function)
32
- // This doesn't modify the DB unless push: true
33
- if (isDev) {
34
- logger.debug("Synchronizing database schema...");
35
- }
36
-
37
- const allCollections = [...config.collections];
38
- // Inject system collections (auth + assets) for migration
39
- for (const systemCol of getSystemCollections()) {
40
- if (!allCollections.find((c) => c.slug === systemCol.slug)) {
41
- allCollections.push(systemCol);
42
- }
43
- }
44
-
45
- await config.db.migrate(allCollections, config.globals);
46
-
47
- if (isDev) {
48
- logger.success("Database schema synchronized.");
49
- }
50
-
51
- // 2. Control whether migrations/schema pushing happens automatically
52
- const shouldMigrate = config.runMigrationsOnStartup || isDev;
53
-
54
- if (shouldMigrate) {
55
- if (config.runMigrationsOnStartup && config.db.runMigrations) {
56
- logger.info("Running file-based migrations on startup...");
57
- await config.db.runMigrations();
58
- }
59
-
60
- // Run auth table migrations
61
- await runAuthMigrations(config.db);
62
- } else {
63
- logger.debug("Automatic schema migrations skipped (Production).");
64
- }
65
-
66
- // Create auth instance AFTER database is connected and tables exist
67
- if (supportsAuth && !state.auth) {
68
- state.auth = await createAuth(config);
69
- }
70
- state.migrated = true;
71
- }
72
- await next();
73
- };
74
- }
@@ -1,71 +0,0 @@
1
- import { WorkersKVStore } from "@hono-rate-limiter/cloudflare";
2
- import type { Context, MiddlewareHandler } from "hono";
3
- import { rateLimiter } from "hono-rate-limiter";
4
- import type { OpacaConfig } from "../../types";
5
-
6
- export function createRateLimitMiddleware(config: OpacaConfig): MiddlewareHandler {
7
- const rateLimitConfig = config.api?.rateLimit;
8
-
9
- if (rateLimitConfig?.enabled === false) {
10
- return async (_c, next) => await next();
11
- }
12
-
13
- const windowMs = rateLimitConfig?.windowMs || 60000;
14
- const limit = rateLimitConfig?.limit || 100;
15
-
16
- return async (c, next) => {
17
- // 1. Check for manual provider in config (e.g. Cloudflare ratelimit binding)
18
- let provider = rateLimitConfig?.provider?.(c as any);
19
-
20
- // 2. Auto-detect Cloudflare RateLimit binding if no manual provider/store is provided
21
- if (!provider && !rateLimitConfig?.store && c.env) {
22
- // Look for a binding that looks like a RateLimit binding (has 'limit' method)
23
- const rateLimitKey = Object.keys(c.env).find(
24
- (key) => (c.env as any)[key]?.limit && typeof (c.env as any)[key].limit === "function",
25
- );
26
- if (rateLimitKey) {
27
- provider = (c.env as any)[rateLimitKey];
28
- }
29
- }
30
-
31
- // 3. If a provider (like native Cloudflare binding) is found, use it
32
- if (provider) {
33
- const limiter = rateLimiter({
34
- binding: () => provider,
35
- keyGenerator:
36
- (rateLimitConfig?.keyGenerator as any) ||
37
- ((c: Context) =>
38
- c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "anonymous"),
39
- });
40
- return limiter(c, next);
41
- }
42
-
43
- // 4. Fallback to Store-based or Memory-based rate limiting
44
- let resolvedStore = rateLimitConfig?.store;
45
-
46
- // Auto-detect KV store if on Cloudflare and no store/provider is found
47
- if (!resolvedStore && c.env) {
48
- const kvBindingKey = Object.keys(c.env).find(
49
- (key) => key.startsWith("OPACA_") && (c.env as any)[key]?.put && (c.env as any)[key]?.get,
50
- );
51
-
52
- if (kvBindingKey) {
53
- resolvedStore = new WorkersKVStore({ namespace: (c.env as any)[kvBindingKey] });
54
- }
55
- }
56
-
57
- const limiter = rateLimiter({
58
- windowMs,
59
- limit,
60
- standardHeaders: "draft-6",
61
- store: resolvedStore,
62
- keyGenerator:
63
- (rateLimitConfig?.keyGenerator as any) ||
64
- ((c: Context) =>
65
- c.req.header("cf-connecting-ip") || c.req.header("x-forwarded-for") || "anonymous"),
66
- message: "Too many requests from this IP, please try again after a minute.",
67
- });
68
-
69
- return limiter(c, next);
70
- };
71
- }
@@ -1,47 +0,0 @@
1
- import { Hono } from "hono";
2
-
3
- import type { Auth } from "../auth";
4
- import type { OpacaConfig } from "../types";
5
-
6
- import { createAdminRouter } from "./admin-router";
7
- import { mountCollectionRoutes, mountGlobalRoutes } from "./collection-router";
8
- import {
9
- type ApiContextVariables,
10
- setupAuthMiddlewares,
11
- setupMiddlewares,
12
- } from "./setup-middlewares";
13
- import { createAssetsServingRouter, createSystemRouter } from "./system-router";
14
-
15
- export type { ApiContextVariables } from "./setup-middlewares";
16
-
17
- export function createAPIRouter(config: OpacaConfig): Hono<{ Variables: ApiContextVariables }> {
18
- // Auth and migration state
19
- const state = { auth: undefined as Auth | undefined, migrated: false };
20
-
21
- // Create Router
22
- const router = new Hono<{ Variables: ApiContextVariables }>().basePath("/api");
23
-
24
- // Apply Middlewares
25
- setupMiddlewares(router, config, state);
26
- setupAuthMiddlewares(router, config, state);
27
-
28
- // Health Check
29
- router.get("/", (c) => {
30
- return c.json({ status: "ok", version: "1.0.0", appName: config.appName });
31
- });
32
-
33
- // Mount Admin API routes
34
- router.route("/__admin", createAdminRouter(config, state));
35
-
36
- // Mount System API routes (Assets management)
37
- router.route("/__system", createSystemRouter(config));
38
-
39
- // Serve Assets
40
- router.route("/", createAssetsServingRouter(config));
41
-
42
- // Mount Collections & Globals dynamic routes
43
- mountCollectionRoutes(router, config, state);
44
- mountGlobalRoutes(router, config, state);
45
-
46
- return router;
47
- }
@@ -1,58 +0,0 @@
1
- import type { Hono } from "hono";
2
- import type { Auth } from "../auth";
3
- import type { OpacaConfig } from "../types";
4
- import { logger } from "../utils/logger";
5
- import { type AuthContextVariables, createAuthMiddleware } from "./middlewares/auth";
6
- import { createContextMiddleware, type OpacaContextVariables } from "./middlewares/context";
7
- import { createCorsMiddleware } from "./middlewares/cors";
8
- import { createDatabaseInitMiddleware } from "./middlewares/database-init";
9
- import { createRateLimitMiddleware } from "./middlewares/rate-limit";
10
-
11
- export type ApiContextVariables = OpacaContextVariables & AuthContextVariables;
12
-
13
- export function setupMiddlewares(
14
- router: Hono<{ Variables: ApiContextVariables }>,
15
- config: OpacaConfig,
16
- state: { auth: Auth | undefined; migrated: boolean },
17
- ) {
18
- // Add X-Powered-By header
19
- router.use("*", async (c, next) => {
20
- await next();
21
- c.res.headers.set("X-Powered-By", "OpacaCMS");
22
- });
23
-
24
- // Core Middlewares
25
- router.use("*", createContextMiddleware(config));
26
- router.use("*", createRateLimitMiddleware(config));
27
- router.use("*", createCorsMiddleware(config));
28
- router.use("*", createDatabaseInitMiddleware(config, state));
29
-
30
- // Global Error Handler
31
- router.onError((err, c) => {
32
- logger.error(`API Error: ${err.message}`, err);
33
- return c.json({ message: "Internal Server Error", error: err.message }, 500);
34
- });
35
- }
36
-
37
- export function setupAuthMiddlewares(
38
- router: Hono<{ Variables: ApiContextVariables }>,
39
- config: OpacaConfig,
40
- state: { auth: Auth | undefined },
41
- ) {
42
- const supportsAuth =
43
- config.db.name === "sqlite" || config.db.name === "postgres" || config.db.name === "d1";
44
-
45
- if (supportsAuth) {
46
- router.use(
47
- "*",
48
- createAuthMiddleware(() => state.auth),
49
- );
50
-
51
- router.on(["POST", "GET"], ["/auth/*"], async (c) => {
52
- if (!state.auth) {
53
- return c.json({ message: "Auth not initialized" }, 503);
54
- }
55
- return await state.auth.handler(c.req.raw);
56
- });
57
- }
58
- }
@@ -1,35 +0,0 @@
1
- import { Hono } from "hono";
2
- import { getSystemCollections } from "../db/system-schema";
3
- import type { OpacaConfig } from "../types";
4
- import { createAssetsHandlers } from "./assets";
5
- import { adminMiddleware } from "./middlewares/admin";
6
- import type { ApiContextVariables } from "./router";
7
-
8
- export function createSystemRouter(config: OpacaConfig) {
9
- const systemRouter = new Hono<{ Variables: ApiContextVariables }>();
10
-
11
- if (config.storages) {
12
- const assetsHandlers = createAssetsHandlers(config);
13
-
14
- systemRouter.post("/assets/upload", adminMiddleware, assetsHandlers.upload);
15
- systemRouter.get("/assets", adminMiddleware, assetsHandlers.list);
16
- systemRouter.post("/assets/presign-upload", adminMiddleware, assetsHandlers.presign);
17
- }
18
-
19
- return systemRouter;
20
- }
21
-
22
- export function createAssetsServingRouter(config: OpacaConfig) {
23
- const assetsServingRouter = new Hono<{ Variables: ApiContextVariables }>();
24
-
25
- if (config.storages) {
26
- const assetsHandlers = createAssetsHandlers(config);
27
- const assetCol = getSystemCollections().find((c) => c.slug === "_opaca_assets");
28
- const assetPath = `/${assetCol?.apiPath || assetCol?.slug || "_opaca_assets"}`;
29
-
30
- // Serve Assets (Public/Admin depending on access, but for now allow public if URL is known)
31
- assetsServingRouter.get(`${assetPath}/:id/view`, assetsHandlers.serve);
32
- }
33
-
34
- return assetsServingRouter;
35
- }
package/src/server.ts DELETED
@@ -1,9 +0,0 @@
1
- // Server-only entry point (runtime-agnostic core)
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";
@@ -1,136 +0,0 @@
1
- import type { R2Bucket } from "@cloudflare/workers-types";
2
- import { FileTooLargeError, Invalidmime_typeError, StorageError } from "../errors";
3
- import type {
4
- FileData,
5
- FileRecord,
6
- StorageAdapter,
7
- StorageAdapterConfig,
8
- UploadOptions,
9
- } from "../types";
10
-
11
- export interface R2AdapterConfig extends StorageAdapterConfig {
12
- bucketBinding: R2Bucket; // e.g., env.MY_ASSETS_BUCKET
13
- }
14
-
15
- export function createR2Storage(config: R2AdapterConfig): StorageAdapter {
16
- const getFullKey = (filename: string) => {
17
- return config.prefix ? `${config.prefix.replace(/\/$/, "")}/${filename}` : filename;
18
- };
19
-
20
- const getPublicUrl = (filename: string) => {
21
- if (!config.publicUrl) {
22
- throw new Error(
23
- "Cloudflare R2 requires a 'publicUrl' (custom domain) configured in the adapter to return accessible URLs.",
24
- );
25
- }
26
- return `${config.publicUrl.replace(/\/$/, "")}/${getFullKey(filename)}`;
27
- };
28
-
29
- return {
30
- name: "cloudflare-r2",
31
-
32
- async upload(file: FileRecord, options?: UploadOptions): Promise<FileData> {
33
- try {
34
- if (options?.allowedmime_types && !options.allowedmime_types.includes(file.mime_type)) {
35
- throw new Invalidmime_typeError(
36
- "cloudflare-r2",
37
- options.allowedmime_types,
38
- file.mime_type,
39
- );
40
- }
41
-
42
- if (options?.maxFileSize && file.filesize > options.maxFileSize) {
43
- throw new FileTooLargeError("cloudflare-r2", options.maxFileSize, file.filesize);
44
- }
45
-
46
- let finalFilename = file.filename;
47
- if (options?.generateUniqueName) {
48
- const ext = file.original_filename.split(".").pop() || "";
49
- const hash = crypto.randomUUID().split("-")[0];
50
- finalFilename = `${finalFilename.replace(`.${ext}`, "")}-${hash}.${ext}`;
51
- }
52
-
53
- const key = getFullKey(finalFilename);
54
-
55
- const body = file.buffer || file.stream;
56
- if (!body) {
57
- throw new StorageError(
58
- "cloudflare-r2",
59
- "upload",
60
- `No content provided for file ${file.filename}`,
61
- );
62
- }
63
-
64
- await config.bucketBinding.put(key, body as any, {
65
- httpMetadata: {
66
- contentType: file.mime_type,
67
- },
68
- });
69
-
70
- return {
71
- filename: finalFilename,
72
- mime_type: file.mime_type,
73
- filesize: file.filesize,
74
- url: getPublicUrl(finalFilename),
75
- };
76
- } catch (error) {
77
- if (error instanceof StorageError) throw error;
78
- throw new StorageError(
79
- "cloudflare-r2",
80
- "upload",
81
- `Failed to upload ${file.filename} to R2 bucket`,
82
- error,
83
- );
84
- }
85
- },
86
-
87
- async delete(filename: string): Promise<void> {
88
- try {
89
- await config.bucketBinding.delete(getFullKey(filename));
90
- } catch (error) {
91
- throw new StorageError(
92
- "cloudflare-r2",
93
- "delete",
94
- `Failed to delete ${filename} from R2 bucket`,
95
- error,
96
- );
97
- }
98
- },
99
-
100
- async exists(filename: string): Promise<boolean> {
101
- try {
102
- const head = await config.bucketBinding.head(getFullKey(filename));
103
- return head !== null;
104
- } catch (error) {
105
- throw new StorageError(
106
- "cloudflare-r2",
107
- "exists",
108
- `Failed to check existence of ${filename} in R2 bucket`,
109
- error,
110
- );
111
- }
112
- },
113
-
114
- async download(filename: string): Promise<ReadableStream<Uint8Array>> {
115
- try {
116
- const object = await config.bucketBinding.get(getFullKey(filename));
117
- if (!object) {
118
- throw new StorageError("cloudflare-r2", "download", `File not found: ${filename}`);
119
- }
120
- return object.body as unknown as ReadableStream<Uint8Array>;
121
- } catch (error) {
122
- if (error instanceof StorageError) throw error;
123
- throw new StorageError(
124
- "cloudflare-r2",
125
- "download",
126
- `Failed to download ${filename} from R2 bucket`,
127
- error,
128
- );
129
- }
130
- },
131
-
132
- // Note: Cloudflare R2 does not natively support presigned URLs for client-side uploads
133
- // via the internal binding API. To support Direct-to-Cloud uploads on Cloudflare,
134
- // developers should use the `createS3Adapter` pointing to their R2 S3-compatible endpoint.
135
- };
136
- }