@brightsideoy/kama 1.0.0-alpha.21 → 1.0.0-alpha.22

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 (106) hide show
  1. package/bin/cli.js +3 -62
  2. package/content/definitions/blocks/form.yaml +20 -0
  3. package/content/definitions/forms/.gitkeep +0 -0
  4. package/content/{forms → definitions/forms}/contact.yaml +0 -6
  5. package/content/{forms → definitions/forms}/subscription.yaml +0 -6
  6. package/dist/assets/AssetEditor-DW0KuNhg.js +1 -0
  7. package/dist/assets/CmsBadge-DnHEoBs-.js +1 -0
  8. package/dist/assets/CmsButton-DjIeMqGt.js +1 -0
  9. package/dist/assets/CmsDataRow-BKQ3_7BX.js +1 -0
  10. package/dist/assets/CmsFieldTaxonomy-ZB3iCGJl.js +1 -0
  11. package/dist/assets/CmsHelp-y1my4i_c.js +1 -0
  12. package/dist/assets/CmsImagePreview-cWi-cfCr.js +1 -0
  13. package/dist/assets/CmsPublisher-BOylClC7.js +3 -0
  14. package/dist/assets/CmsUserCenter-D9SqVAd7.js +1 -0
  15. package/dist/assets/EditorSplitPreview-c4y6AaHo.js +1 -0
  16. package/dist/assets/EditorSplitPreview-eID9z4gI.css +1 -0
  17. package/dist/assets/FormsWorkspace-5Mk4ulr5.js +1 -0
  18. package/dist/assets/FormsWorkspace-DPTcxMpw.css +1 -0
  19. package/dist/assets/NodeContextMenu-qV4OaL33.js +1 -0
  20. package/dist/assets/{NodeEditor-4TsNvk2f.css → NodeEditor-CMVD5LSR.css} +1 -1
  21. package/dist/assets/NodeEditor-DLhgHaBi.js +161 -0
  22. package/dist/assets/StatusPill-BAnTGDR_.js +1 -0
  23. package/dist/assets/TrashWorkspace-Cot9mtw0.js +1 -0
  24. package/dist/assets/{_plugin-vue_export-helper-CQxWhVtr.js → _plugin-vue_export-helper-BdT0OEbg.js} +1 -1
  25. package/dist/assets/circle-check-CB39w7cZ.js +1 -0
  26. package/dist/assets/createLucideIcon-BIiMnJpN.js +1 -0
  27. package/dist/assets/database-mgNVRFlp.js +1 -0
  28. package/dist/assets/folder-tree-BsiMujM5.js +1 -0
  29. package/dist/assets/globe-5RHPG-2-.js +1 -0
  30. package/dist/assets/history-ZSqpsbjQ.js +1 -0
  31. package/dist/assets/index-CXtujYMT.js +16 -0
  32. package/dist/assets/index-M4hAA5qU.css +1 -0
  33. package/dist/assets/layers-CH2VvrZT.js +1 -0
  34. package/dist/assets/loader-circle-CwP4GuFX.js +1 -0
  35. package/dist/assets/monitor-o1JOGzBn.js +1 -0
  36. package/dist/assets/panel-left-close-g4nIMIjy.js +1 -0
  37. package/dist/assets/plus-DwPH9Xh7.js +1 -0
  38. package/dist/assets/preload-helper-oCQc7Owg.js +1 -0
  39. package/dist/assets/rotate-ccw-tUaGL4DO.js +1 -0
  40. package/dist/assets/save-BUYaWIjt.js +1 -0
  41. package/dist/assets/schema-helpers-uuDCw8Rb.js +1 -0
  42. package/dist/assets/send-UE48lWD8.js +1 -0
  43. package/dist/assets/smartphone-CUB4k13p.js +1 -0
  44. package/dist/assets/trash-2-D8h6WxFK.js +1 -0
  45. package/dist/assets/useCmsState-Bc7cgBp5.js +1 -0
  46. package/dist/assets/useLocalStorage-DO_mDpwe.js +1 -0
  47. package/dist/assets/useNodes-DlRMd4Br.js +1 -0
  48. package/dist/assets/user-C5hzf6BE.js +1 -0
  49. package/dist/{dist-3Xc2TTZw.js → dist-CVtRUnHl.js} +4731 -4251
  50. package/dist/index.html +32 -30
  51. package/dist/index.js +4643 -4173
  52. package/dist/nodemailer-Ccic7tRm-KQqZAWb5.js +7877 -0
  53. package/dist/nodemailer-Ccic7tRm.js +7908 -0
  54. package/dist/rolldown-runtime-B0aSnxlc.js +20 -0
  55. package/dist/schema-compiler.js +1 -1
  56. package/documentation/FORMS.md +165 -0
  57. package/package.json +3 -1
  58. package/schema.sql +13 -0
  59. package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +7 -0
  60. package/templates/astro-starter/src/components/blocks/Form.astro +117 -65
  61. package/templates/astro-starter/src/lib/cms-fetch.ts +19 -0
  62. package/templates/astro-starter/src/pages/[...slug].astro +2 -4
  63. package/templates/astro-starter/src/pages/api/forms/[...path].ts +57 -0
  64. package/templates/kama-worker/index.js +1 -14
  65. package/templates/kama-worker/server.js +0 -2
  66. package/content/definitions/block-kama-forms.yaml +0 -5
  67. package/dist/assets/AssetEditor-B4W7tV1a.js +0 -1
  68. package/dist/assets/CmsBadge-D0Ob9qPU.js +0 -1
  69. package/dist/assets/CmsButton-CbOfxvjr.js +0 -1
  70. package/dist/assets/CmsDataRow--H4iI_u_.js +0 -1
  71. package/dist/assets/CmsFieldTaxonomy-C_AwHDwY.js +0 -1
  72. package/dist/assets/CmsHelp-BQkr9KyU.js +0 -1
  73. package/dist/assets/CmsImagePreview-DuHPBzml.js +0 -1
  74. package/dist/assets/CmsPaneResizer-B62ZqsnE.js +0 -1
  75. package/dist/assets/CmsPublisher-XSCPrp5L.js +0 -3
  76. package/dist/assets/CmsUserCenter-D3XDzKDC.js +0 -1
  77. package/dist/assets/EditorSplitPreview-BzKh4wFB.css +0 -1
  78. package/dist/assets/EditorSplitPreview-Cp2x0O_P.js +0 -1
  79. package/dist/assets/NodeContextMenu-C_HWBGeb.js +0 -1
  80. package/dist/assets/NodeEditor-DA5GRtRP.js +0 -161
  81. package/dist/assets/StatusPill-CbeW5SMT.js +0 -1
  82. package/dist/assets/TrashWorkspace-CATe46WF.js +0 -1
  83. package/dist/assets/circle-check-A-QeFqt3.js +0 -1
  84. package/dist/assets/database-hg5SqKLG.js +0 -1
  85. package/dist/assets/folder-tree-BWYot72H.js +0 -1
  86. package/dist/assets/globe-BraoljaN.js +0 -1
  87. package/dist/assets/history-pqIbKK9u.js +0 -1
  88. package/dist/assets/index-CY0VYSyt.css +0 -1
  89. package/dist/assets/index-DdG9Pozx.js +0 -14
  90. package/dist/assets/layers-B6RgfpPR.js +0 -1
  91. package/dist/assets/loader-circle-BoUkhDjq.js +0 -1
  92. package/dist/assets/monitor-CrpvInqG.js +0 -1
  93. package/dist/assets/panel-left-close-CVFakVaA.js +0 -1
  94. package/dist/assets/plus-CX_GHzXs.js +0 -1
  95. package/dist/assets/rotate-ccw-CWE4pOjs.js +0 -1
  96. package/dist/assets/save-Ctv8vW9H.js +0 -1
  97. package/dist/assets/schema-helpers-DvficKko.js +0 -1
  98. package/dist/assets/send-F-mJeL54.js +0 -1
  99. package/dist/assets/smartphone-EPce6VdP.js +0 -1
  100. package/dist/assets/trash-2-CAUF1KtI.js +0 -1
  101. package/dist/assets/useLocalStorage-C805uplI.js +0 -1
  102. package/dist/assets/useNodes-CqFlc72m.js +0 -1
  103. package/dist/assets/user-IFlT6mYq.js +0 -1
  104. package/documentation/EXTENSIONS.md +0 -204
  105. package/extension-registry.js +0 -5
  106. /package/dist/assets/{CmsPaneResizer-Dkidd4pI.css → preload-helper-Dkidd4pI.css} +0 -0
@@ -0,0 +1,20 @@
1
+ //#region \0rolldown/runtime.js
2
+ var e = Object.create, t = Object.defineProperty, n = Object.getOwnPropertyDescriptor, r = Object.getOwnPropertyNames, i = Object.getPrototypeOf, a = Object.prototype.hasOwnProperty, o = (e, t) => () => (t || (e((t = { exports: {} }).exports, t), e = null), t.exports), s = (e, n) => {
3
+ let r = {};
4
+ for (var i in e) t(r, i, {
5
+ get: e[i],
6
+ enumerable: !0
7
+ });
8
+ return n || t(r, Symbol.toStringTag, { value: "Module" }), r;
9
+ }, c = (e, i, o, s) => {
10
+ if (i && typeof i == "object" || typeof i == "function") for (var c = r(i), l = 0, u = c.length, d; l < u; l++) d = c[l], !a.call(e, d) && d !== o && t(e, d, {
11
+ get: ((e) => i[e]).bind(null, d),
12
+ enumerable: !(s = n(i, d)) || s.enumerable
13
+ });
14
+ return e;
15
+ }, l = (n, r, o) => (o = n == null ? {} : e(i(n)), c(r || !n || !n.__esModule || !a.call(n, "default") ? t(o, "default", {
16
+ value: n,
17
+ enumerable: !0
18
+ }) : o, n));
19
+ //#endregion
20
+ export { s as n, l as r, o as t };
@@ -30,7 +30,7 @@ async function f() {
30
30
  if (n(f)) l = (await import(t(f).href)).compileDefinitions;
31
31
  else if (n(p)) l = (await import(t(p).href)).compileDefinitions;
32
32
  else try {
33
- l = (await import("./dist-3Xc2TTZw.js")).compileDefinitions;
33
+ l = (await import("./dist-CVtRUnHl.js")).compileDefinitions;
34
34
  } catch (e) {
35
35
  console.error("\x1B[31m ✖\x1B[0m \x1B[31mCould not resolve Kama Schema Engine:\x1B[0m", e), process.exit(1);
36
36
  }
@@ -0,0 +1,165 @@
1
+ # Forms
2
+
3
+ KAMA forms are built-in. Store each form definition as a YAML file in
4
+ `content/definitions/forms/`; its filename is the fallback form ID. Run
5
+ `npm run bundle:definitions` after adding or changing definitions before
6
+ deploying.
7
+
8
+ ```yaml
9
+ id: contact
10
+ title: Contact us
11
+ description: Send our team a message.
12
+ fields:
13
+ - name: email
14
+ label: Email
15
+ type: email
16
+ required: true
17
+ - name: message
18
+ label: Message
19
+ type: textarea
20
+ required: true
21
+ settings:
22
+ successMessage: Thanks for getting in touch.
23
+ requireTurnstile: false
24
+ ```
25
+
26
+ The built-in **Form** block provides a form selector for pages. Finishers run
27
+ after field validation and Turnstile verification. All finishers are off by
28
+ default. Select a form in the CMS Forms sidebar to configure **Save submissions
29
+ to database**, **Email the team**, and **Send confirmation to submitter**.
30
+ Once saved, settings are stored in the CMS database and override YAML finisher
31
+ settings.
32
+ With no finisher enabled, valid submissions receive the configured success
33
+ response but are not stored or emailed. The Forms panel makes that state clear.
34
+ Saved submissions are available from the Forms panel and stored in
35
+ `kama_forms_table`. If an existing table has the old schema, KAMA recreates it
36
+ at startup.
37
+
38
+ The Forms sidebar's email settings use a fixed team address or the form's email
39
+ field for a submitter confirmation. Provider credentials and sender addresses
40
+ are deployment configuration, never stored in the CMS database or form YAML.
41
+ For code-defined forms, email finishers can also be configured in YAML. Custom
42
+ finisher types remain available through YAML or registered server handlers and
43
+ are preserved when the built-in settings are edited:
44
+
45
+ ```yaml
46
+ finishers:
47
+ - id: notify-team
48
+ type: email
49
+ provider: auto
50
+ to: team@example.com
51
+ subject: "New message from {{fullName}}"
52
+ replyToField: email
53
+ - id: confirmation
54
+ type: email
55
+ provider: auto
56
+ toField: email
57
+ subject: "We received your message"
58
+ text: "Thanks {{fullName}}, we received your message."
59
+ ```
60
+
61
+ `toField` must name a form field with `type: email`. Email bodies default to
62
+ all submitted fields; optional `text` and `html` templates support `{{field}}`
63
+ placeholders. Values inserted into HTML templates are escaped. Every email
64
+ finisher uses `FORMS_EMAIL_FROM` as its sender. With `provider: auto`, KAMA uses
65
+ the Cloudflare binding when present, otherwise SMTP in Node. Set
66
+ `provider: cloudflare` or `provider: smtp` to require one transport. An email
67
+ finisher failure fails the submission and suppresses the success response.
68
+ Email delivery and database writes cannot be rolled back atomically, so a
69
+ failed submission may have already run earlier finishers; retries can repeat
70
+ those side effects.
71
+
72
+ Email finishers can set a subject, sender display name, and reply-to address.
73
+ Use `subjectField`, `fromNameField`, or `replyToField` to select submission
74
+ values; `replyToField` must be an email field. Subject text also supports
75
+ `{{field}}` interpolation. The actual sender email remains
76
+ `FORMS_EMAIL_FROM`, while optional `FORMS_EMAIL_FROM_NAME` supplies a
77
+ deployment-wide sender-name fallback. Plain-text and HTML body templates are
78
+ optional; otherwise the message includes all submitted fields. Values
79
+ interpolated into HTML templates are escaped.
80
+
81
+ The Form block's editor sidebar can opt into per-block overrides for subject,
82
+ sender display name, reply-to address/field, and message bodies. This lets pages
83
+ reuse a form with different email presentation while preserving the form's
84
+ configured recipients, sender address, and enabled finishers. Overrides are
85
+ validated against the selected form schema and cannot change recipients or mail
86
+ transport.
87
+
88
+ KAMA registers `database` and `email` finishers by default. Add custom types by
89
+ registering a handler during server startup, before submissions are handled:
90
+
91
+ ```ts
92
+ import { registerFormFinisher } from '@brightsideoy/kama';
93
+
94
+ registerFormFinisher('webhook', async ({ finisher, payload, env }) => {
95
+ // Implement this finisher and throw if it fails.
96
+ });
97
+ ```
98
+
99
+ Then use `type: webhook` in a form's `finishers` list. Handlers run in list
100
+ order; throwing stops later finishers and returns a submission failure.
101
+
102
+ For Workers, add the Email Sending binding to your Wrangler config after
103
+ onboarding a sender domain in Cloudflare Email Service:
104
+
105
+ ```jsonc
106
+ {
107
+ "send_email": [{ "name": "FORMS_EMAIL" }]
108
+ }
109
+ ```
110
+
111
+ Set `FORMS_EMAIL_FROM` to an address at the onboarded domain. Cloudflare Email
112
+ Sending requires the appropriate Workers plan for arbitrary external
113
+ recipients. The KAMA project does not enable this binding automatically.
114
+
115
+ For Node deployments, configure:
116
+
117
+ ```sh
118
+ FORMS_SMTP_HOST=smtp.example.com
119
+ FORMS_SMTP_PORT=465
120
+ FORMS_SMTP_SECURE=true
121
+ FORMS_SMTP_USER=...
122
+ FORMS_SMTP_PASSWORD=...
123
+ FORMS_EMAIL_FROM=forms@example.com
124
+ FORMS_EMAIL_FROM_NAME=KAMA
125
+ ```
126
+
127
+ For Cloudflare authenticated SMTP, use `smtp.mx.cloudflare.net:465`, username
128
+ `api_token`, and an Email Sending: Edit API token as the password. Keep SMTP
129
+ credentials in the deployment's secret manager, never in form YAML. Use valid
130
+ sender and recipient addresses; Email Sending is intended for transactional
131
+ mail, not bulk marketing.
132
+
133
+ For forms with
134
+ `settings.requireTurnstile: true`, configure both keys:
135
+
136
+ - `PUBLIC_TURNSTILE_SITE_KEY` on the frontend site (a public Wrangler `vars`
137
+ value, or a local `.dev.vars` value). This renders the widget.
138
+ - `TURNSTILE_SECRET_KEY` on the KAMA worker (a Wrangler secret, or a local
139
+ `.dev.vars` value). The server uses it to verify each response.
140
+
141
+ Use the site key from the same Turnstile widget as the server secret. The Form
142
+ block displays a configuration warning when Turnstile is required but its site
143
+ key is missing. The block's optional **Success Message** overrides the success
144
+ message configured on the form definition.
145
+
146
+ For local Astro development only, KAMA uses Cloudflare's documented
147
+ always-pass test keys when no site key or secret is configured. These keys
148
+ cannot protect a production form; configure real keys for deployed environments.
149
+
150
+ The Astro starter's Form block loads definitions through the `CMS_WORKER`
151
+ service binding when available and sends submissions through a same-origin
152
+ `/api/forms/:formId/submissions` proxy. Outside the service binding, it uses
153
+ `PUBLIC_API_URL` server-side; local development falls back to `http://localhost:8787`.
154
+ Do not expose a server-only API secret in browser code.
155
+
156
+ For local Astro development with a configured `CMS_WORKER` binding, run the
157
+ CMS Worker locally on port `8787` as well as the Astro site. If Astro's local
158
+ service binding reports that the target Worker is not running, the page route
159
+ falls back to `127.0.0.1:8787`. Keep the site's and CMS Worker's
160
+ `FRONTEND_API_SECRET` values matched in their local secret files.
161
+
162
+ The public API serves definitions at `GET /api/v1/forms/:formId` and accepts
163
+ submissions at `POST /api/v1/forms/:formId/submissions`. The CMS uses
164
+ `GET /api/cms/forms` to populate the block selector and
165
+ `GET /api/cms/forms/:formId/submissions` to display saved entries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brightsideoy/kama",
3
- "version": "1.0.0-alpha.21",
3
+ "version": "1.0.0-alpha.22",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -58,6 +58,7 @@
58
58
  "locale-codes": "^1.3.1",
59
59
  "lru-cache": "^11.5.2",
60
60
  "lucide-vue-next": "^1.0.0",
61
+ "nodemailer": "^10.5.0",
61
62
  "sharp": "^0.35.3",
62
63
  "vue": "^3.5.41",
63
64
  "vue-advanced-cropper": "^2.8.9",
@@ -71,6 +72,7 @@
71
72
  "@libsql/client": "^0.14.0",
72
73
  "@types/js-yaml": "^4.0.9",
73
74
  "@types/node": "^26.2.0",
75
+ "@types/nodemailer": "^8.0.2",
74
76
  "@types/sharp": "^0.31.1",
75
77
  "@types/yaml": "^1.9.6",
76
78
  "@vitejs/plugin-vue": "^6.0.8",
package/schema.sql CHANGED
@@ -39,6 +39,19 @@ CREATE TABLE IF NOT EXISTS "sessions" (
39
39
  FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
40
40
  );
41
41
 
42
+ CREATE TABLE IF NOT EXISTS "kama_forms_table" (
43
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
44
+ form_id TEXT NOT NULL,
45
+ payload_json TEXT NOT NULL,
46
+ createdAt TEXT DEFAULT CURRENT_TIMESTAMP
47
+ );
48
+
49
+ CREATE TABLE IF NOT EXISTS "kama_form_settings" (
50
+ form_id TEXT PRIMARY KEY,
51
+ finishers_json TEXT NOT NULL DEFAULT '[]',
52
+ updatedAt TEXT DEFAULT CURRENT_TIMESTAMP
53
+ );
54
+
42
55
  CREATE TABLE IF NOT EXISTS "channels" (
43
56
  id INTEGER PRIMARY KEY AUTOINCREMENT,
44
57
  key TEXT UNIQUE NOT NULL,
@@ -6,6 +6,7 @@ import HeaderImage from "@/components/blocks/HeaderImage.astro";
6
6
  import ColumnLayout from "@/components/blocks/ColumnLayout.astro";
7
7
  import HtmlBlock from "@/components/blocks/HtmlBlock.astro";
8
8
  import NodeList from "@/components/blocks/NodeList.astro"; // 🎯 NEW IMPORT
9
+ import FormBlock from "@/components/blocks/Form.astro";
9
10
  import { extractHtml } from "@/utils/tiptap";
10
11
 
11
12
  interface Block {
@@ -62,6 +63,12 @@ const visibleBlocks = safeBlocks.filter(b => {
62
63
  }
63
64
 
64
65
  switch (componentId) {
66
+ case "form":
67
+ case "form-block":
68
+ case "form_block": {
69
+ return <FormBlock data={data} />;
70
+ }
71
+
65
72
  // 🎯 ADDED NODE LIST CASES
66
73
  case "node-list":
67
74
  case "nodelist":
@@ -1,36 +1,74 @@
1
1
  ---
2
2
  // src/components/blocks/Form.astro
3
+ import { fetchCmsRequest } from '../../lib/cms-fetch';
4
+
3
5
  interface Props {
4
6
  data: {
5
7
  formId: string;
8
+ successMessage?: string;
6
9
  };
7
10
  }
8
11
 
9
12
  const { data } = Astro.props;
10
13
  const formId = data?.formId;
11
-
12
- const kamaApiUrl = import.meta.env.KAMA_API_URL || 'http://localhost:8787';
13
- const turnstileSiteKey = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY;
14
-
15
- // Fetch form YAML schema at render time
14
+ const finisherOverrides = data?.emailOverridesEnabled === true ? {
15
+ subject: data.emailSubject || undefined,
16
+ subjectField: data.emailSubjectField || undefined,
17
+ fromName: data.emailFromName || undefined,
18
+ fromNameField: data.emailFromNameField || undefined,
19
+ replyTo: data.emailReplyTo || undefined,
20
+ replyToField: data.emailReplyToField || undefined,
21
+ text: data.emailText || undefined,
22
+ html: data.emailHtml || undefined,
23
+ } : {};
24
+
25
+ const safeEnv = (Astro.locals as any).safeEnv || {};
26
+ const cmsWorker = safeEnv.CMS_WORKER;
27
+ const kamaApiUrl = String(
28
+ import.meta.env.DEV && !cmsWorker
29
+ ? 'http://localhost:8787'
30
+ : import.meta.env.PUBLIC_API_URL || safeEnv.PUBLIC_API_URL || 'http://localhost:8787'
31
+ ).replace(/\/$/, '');
32
+ const configuredTurnstileSiteKey = String(
33
+ import.meta.env.PUBLIC_TURNSTILE_SITE_KEY || safeEnv.PUBLIC_TURNSTILE_SITE_KEY || ''
34
+ ).trim();
35
+ const turnstileSiteKey = configuredTurnstileSiteKey || (
36
+ import.meta.env.DEV ? '1x00000000000000000000AA' : ''
37
+ );
38
+
39
+ // Fetch the built-in form schema at render time
16
40
  let schema = null;
17
41
  if (formId) {
18
42
  try {
19
- const res = await fetch(`${kamaApiUrl}/api/ext/kama-forms/render/${formId}`);
43
+ const schemaUrl = `${kamaApiUrl}/api/v1/forms/${encodeURIComponent(formId)}`;
44
+ const schemaRequest = new Request(schemaUrl, { headers: { Accept: 'application/json' } });
45
+ const res = await fetchCmsRequest(schemaRequest, cmsWorker);
20
46
  if (res.ok) schema = await res.json();
21
- } catch (err) {
22
- console.error(`Failed to fetch schema for ${formId}`);
47
+ else console.error(`[Forms] Failed to load ${formId}: HTTP ${res.status}`);
48
+ } catch (error) {
49
+ console.error(`[Forms] Failed to load definition ${formId}:`, error);
23
50
  }
24
51
  }
25
52
 
26
53
  const requiresTurnstile = schema?.settings?.requireTurnstile === true;
54
+ const submittedFormId = Astro.url.searchParams.get('formId');
55
+ const submissionStatus = submittedFormId === formId
56
+ ? Astro.url.searchParams.get('formStatus')
57
+ : null;
58
+ const submissionMessage = Astro.url.searchParams.get('formMessage');
27
59
  ---
28
60
 
29
61
  {schema ? (
30
- <div class="kama-form-wrapper" data-form-id={formId} data-api-url={kamaApiUrl}>
62
+ <div
63
+ class="kama-form-wrapper"
64
+ data-form-id={formId}
65
+ data-api-url="/api/forms"
66
+ data-success-message={data?.successMessage || ''}
67
+ data-finisher-overrides={JSON.stringify(finisherOverrides)}
68
+ >
31
69
 
32
70
  <!-- 🎯 Conditionally load Cloudflare Turnstile Script -->
33
- {requiresTurnstile && (
71
+ {requiresTurnstile && turnstileSiteKey && (
34
72
  <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
35
73
  )}
36
74
 
@@ -39,10 +77,23 @@ const requiresTurnstile = schema?.settings?.requireTurnstile === true;
39
77
  {schema.description && <p>{schema.description}</p>}
40
78
  </div>
41
79
 
42
- <div class="form-alert success" style="display: none;"></div>
43
- <div class="form-alert error" style="display: none;"></div>
44
-
45
- <form class="kama-public-form">
80
+ <div
81
+ class="form-alert success"
82
+ role="status"
83
+ aria-live="polite"
84
+ style={submissionStatus === 'success' ? undefined : 'display: none;'}
85
+ >{submissionStatus === 'success' ? (data?.successMessage || submissionMessage || 'Form submitted successfully!') : ''}</div>
86
+ <div
87
+ class="form-alert error"
88
+ role="alert"
89
+ style={submissionStatus === 'error' ? undefined : 'display: none;'}
90
+ >{submissionStatus === 'error' ? (submissionMessage || 'Form submission failed.') : ''}</div>
91
+
92
+ <form
93
+ class="kama-public-form"
94
+ method="post"
95
+ action={`/api/forms/${encodeURIComponent(formId)}/submissions`}
96
+ >
46
97
  {schema.fields?.map((field: any) => (
47
98
  <div class="form-group">
48
99
  <label for={`field-${field.name}`}>
@@ -71,6 +122,12 @@ const requiresTurnstile = schema?.settings?.requireTurnstile === true;
71
122
  <div class="cf-turnstile" data-sitekey={turnstileSiteKey}></div>
72
123
  </div>
73
124
  )}
125
+ {requiresTurnstile && !turnstileSiteKey && (
126
+ <p class="form-alert error" role="alert">
127
+ This form requires Cloudflare Turnstile, but the site key is not configured.
128
+ Set PUBLIC_TURNSTILE_SITE_KEY for the site.
129
+ </p>
130
+ )}
74
131
 
75
132
  <button type="submit" class="submit-btn">Submit</button>
76
133
  </form>
@@ -79,65 +136,60 @@ const requiresTurnstile = schema?.settings?.requireTurnstile === true;
79
136
  <p class="form-error">Form definition "{formId}" could not be loaded.</p>
80
137
  )}
81
138
 
82
- <script>
83
- document.querySelectorAll('.kama-form-wrapper').forEach((container) => {
84
- const form = container.querySelector<HTMLFormElement>('.kama-public-form');
85
- const formId = container.getAttribute('data-form-id');
86
- const apiUrl = container.getAttribute('data-api-url');
87
- const successBox = container.querySelector<HTMLDivElement>('.form-alert.success');
88
- const errorBox = container.querySelector<HTMLDivElement>('.form-alert.error');
89
- const submitBtn = container.querySelector<HTMLButtonElement>('.submit-btn');
90
-
91
- if (!form || !formId || !apiUrl) return;
92
-
93
- form.addEventListener('submit', async (e) => {
94
- e.preventDefault();
95
- if (submitBtn) submitBtn.disabled = true;
96
- if (successBox) successBox.style.display = 'none';
97
- if (errorBox) errorBox.style.display = 'none';
98
-
99
- // FormData automatically picks up the hidden "cf-turnstile-response" input
100
- const formData = new FormData(form);
101
- const payload = Object.fromEntries(formData.entries());
139
+ <script is:inline>
140
+ (() => {
141
+ if (document.documentElement.dataset.kamaFormHandler) return;
142
+ document.documentElement.dataset.kamaFormHandler = 'true';
143
+
144
+ document.addEventListener('submit', async (event) => {
145
+ const form = event.target instanceof HTMLFormElement && event.target.matches('.kama-public-form')
146
+ ? event.target
147
+ : null;
148
+ if (!form) return;
149
+
150
+ event.preventDefault();
151
+ const container = form.closest('.kama-form-wrapper');
152
+ const formId = container?.getAttribute('data-form-id');
153
+ const successBox = container?.querySelector('.form-alert.success');
154
+ const errorBox = container?.querySelector('.form-alert.error');
155
+ const submitBtn = container?.querySelector('.submit-btn');
156
+ if (!container || !formId || !successBox || !errorBox || !submitBtn) return;
157
+
158
+ submitBtn.disabled = true;
159
+ successBox.style.display = 'none';
160
+ errorBox.style.display = 'none';
102
161
 
103
162
  try {
104
- const res = await fetch(`${apiUrl}/api/ext/kama-forms/submit/${formId}`, {
163
+ const payload = Object.fromEntries(new FormData(form).entries());
164
+ payload._kamaFinisherOverrides = JSON.parse(container.getAttribute('data-finisher-overrides') || '{}');
165
+ const response = await fetch(form.action, {
105
166
  method: 'POST',
106
- headers: { 'Content-Type': 'application/json' },
167
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
107
168
  body: JSON.stringify(payload)
108
169
  });
109
-
110
- const result = await res.json();
111
-
112
- if (res.ok && result.success) {
113
- if (successBox) {
114
- successBox.textContent = result.message || 'Form submitted successfully!';
115
- successBox.style.display = 'block';
116
- }
117
- form.reset();
118
-
119
- // 🎯 Reset Turnstile after successful submission if the user wants to submit again
120
- if (window.turnstile) {
121
- window.turnstile.reset();
122
- }
123
- } else {
124
- if (errorBox) {
125
- errorBox.textContent = result.error || 'Form submission failed.';
126
- errorBox.style.display = 'block';
127
- }
128
- // 🎯 Reset Turnstile on failure so they get a fresh token
129
- if (window.turnstile) {
130
- window.turnstile.reset();
131
- }
170
+ const responseText = await response.text();
171
+ let result;
172
+ try {
173
+ result = JSON.parse(responseText);
174
+ } catch {
175
+ throw new Error(`Form API returned an invalid response (HTTP ${response.status}).`);
132
176
  }
133
- } catch (err) {
134
- if (errorBox) {
135
- errorBox.textContent = 'Server connection error.';
136
- errorBox.style.display = 'block';
177
+
178
+ if (!response.ok || !result.success) {
179
+ throw new Error(result.error || 'Form submission failed.');
137
180
  }
181
+
182
+ successBox.textContent = container.getAttribute('data-success-message') || result.message || 'Form submitted successfully!';
183
+ successBox.style.display = 'block';
184
+ form.reset();
185
+ if (window.turnstile) window.turnstile.reset();
186
+ } catch (error) {
187
+ errorBox.textContent = error instanceof Error ? error.message : 'Form submission failed.';
188
+ errorBox.style.display = 'block';
189
+ if (window.turnstile) window.turnstile.reset();
138
190
  } finally {
139
- if (submitBtn) submitBtn.disabled = false;
191
+ submitBtn.disabled = false;
140
192
  }
141
193
  });
142
- });
194
+ })();
143
195
  </script>
@@ -0,0 +1,19 @@
1
+ export async function fetchCmsRequest(
2
+ request: Request,
3
+ cmsWorker: { fetch: (request: Request) => Promise<Response> } | undefined,
4
+ ): Promise<Response> {
5
+ if (!cmsWorker) return fetch(request);
6
+
7
+ const fallbackRequest = request.clone();
8
+ const response = await cmsWorker.fetch(request);
9
+ if (!import.meta.env.DEV || response.status !== 503) return response;
10
+
11
+ const errorText = await response.clone().text();
12
+ if (!/^Worker ".+" not found\. Make sure it is running locally\.$/.test(errorText.trim())) {
13
+ return response;
14
+ }
15
+
16
+ const requestUrl = new URL(request.url);
17
+ const localUrl = new URL(`${requestUrl.pathname}${requestUrl.search}`, "http://127.0.0.1:8787");
18
+ return fetch(new Request(localUrl, fallbackRequest));
19
+ }
@@ -6,6 +6,7 @@ import SkeletonLayout from "../layouts/SkeletonLayout.astro";
6
6
  import BlockRenderer from "../components/blocks/BlockRenderer.astro";
7
7
  import Breadcrumb from "../components/global/Breadcrumb.astro";
8
8
  import { getNodeByPath, getChannelId, getTree, getTreeId } from "../lib/cms";
9
+ import { fetchCmsRequest } from "../lib/cms-fetch";
9
10
  import type { NodeResponse, TreeNode } from "../lib/cms";
10
11
 
11
12
  export const prerender = false;
@@ -101,10 +102,7 @@ const customFetch = async (input: RequestInfo | URL, init?: RequestInit) => {
101
102
 
102
103
  const req = new Request(urlStr, fetchOpts);
103
104
 
104
- if (cmsWorker && typeof cmsWorker.fetch === "function") {
105
- return cmsWorker.fetch(req);
106
- }
107
- return fetch(req);
105
+ return fetchCmsRequest(req, cmsWorker);
108
106
  };
109
107
 
110
108
  const channelId = getChannelId();
@@ -0,0 +1,57 @@
1
+ import type { APIRoute } from "astro";
2
+ import { fetchCmsRequest } from "../../../lib/cms-fetch";
3
+
4
+ export const prerender = false;
5
+
6
+ export const POST: APIRoute = async ({ params, request, locals }) => {
7
+ const path = params.path?.split("/").filter(Boolean) || [];
8
+ if (path.length !== 2 || path[1] !== "submissions") {
9
+ return new Response("Not Found", { status: 404 });
10
+ }
11
+
12
+ const safeEnv = (locals as any).safeEnv || {};
13
+ const cmsWorker = safeEnv.CMS_WORKER;
14
+ const apiUrl = String(
15
+ import.meta.env.DEV && !cmsWorker
16
+ ? "http://localhost:8787"
17
+ : import.meta.env.PUBLIC_API_URL || safeEnv.PUBLIC_API_URL || "http://localhost:8787"
18
+ ).replace(/\/$/, "");
19
+ const formId = encodeURIComponent(path[0]);
20
+
21
+ try {
22
+ const contentType = request.headers.get("content-type") || "";
23
+ const payload = contentType.includes("application/json")
24
+ ? await request.text()
25
+ : JSON.stringify(Object.fromEntries(new URLSearchParams(await request.text()).entries()));
26
+ const backendRequest = new Request(
27
+ `${apiUrl}/api/v1/forms/${formId}/submissions`,
28
+ {
29
+ method: "POST",
30
+ headers: {
31
+ Accept: "application/json",
32
+ "Content-Type": "application/json",
33
+ },
34
+ body: payload,
35
+ }
36
+ );
37
+ const response = await fetchCmsRequest(backendRequest, cmsWorker);
38
+ if (request.headers.get("accept")?.includes("text/html")) {
39
+ const result = await response.clone().json().catch(() => ({}));
40
+ const redirectUrl = new URL(request.headers.get("referer") || "/", request.url);
41
+ if (redirectUrl.origin !== new URL(request.url).origin) {
42
+ redirectUrl.pathname = "/";
43
+ redirectUrl.search = "";
44
+ }
45
+ redirectUrl.searchParams.set("formId", path[0]);
46
+ redirectUrl.searchParams.set("formStatus", response.ok && result.success ? "success" : "error");
47
+ if (!(response.ok && result.success)) {
48
+ redirectUrl.searchParams.set("formMessage", result.error || "Form submission failed.");
49
+ }
50
+ return Response.redirect(redirectUrl, 303);
51
+ }
52
+ return response;
53
+ } catch (error) {
54
+ console.error("[Forms Proxy] Failed to forward form submission:", error);
55
+ return Response.json({ error: "Could not reach the form submission service." }, { status: 502 });
56
+ }
57
+ };
@@ -2,29 +2,16 @@
2
2
  import { Hono } from 'hono';
3
3
  import kamaWorker from '@brightsideoy/kama';
4
4
  import * as localBundle from './bundled-definitions.js';
5
- import { activeExtensions } from './extension-registry.js';
6
5
 
7
6
  const app = new Hono();
8
7
 
9
- // 1. 🎯 Mount Extension Routes Natively
10
- for (const ext of activeExtensions) {
11
- if (ext.routes?.public) {
12
- app.route(`/api/v1/ext/${ext.id}`, ext.routes.public);
13
- }
14
- if (ext.routes?.admin) {
15
- app.route(`/api/admin/ext/${ext.id}`, ext.routes.admin);
16
- }
17
- }
18
-
19
- // 2. 🎯 Mount Precompiled Core CMS (Fallback catch-all)
8
+ // Mount the precompiled core CMS.
20
9
  app.all('*', async (c) => {
21
10
  const schemas = localBundle.BUNDLED_DEFINITIONS || localBundle.default || localBundle;
22
11
 
23
- // Inject the extensions array so the UI and core can read it (e.g. for dynamic menus)
24
12
  const customEnv = {
25
13
  ...c.env,
26
14
  BUNDLED_DEFINITIONS: schemas,
27
- KAMA_EXTENSIONS: activeExtensions,
28
15
  KAMA_RUNTIME: 'cloudflare'
29
16
  };
30
17
 
@@ -3,7 +3,6 @@ import { serveStatic } from '@hono/node-server/serve-static';
3
3
  import { Hono } from 'hono';
4
4
  import kamaApp from '@brightsideoy/kama';
5
5
  import * as localBundle from './bundled-definitions.js';
6
- import { activeExtensions } from './extension-registry.js'; // 🎯 1. Import the auto-generated registry
7
6
  import dotenv from 'dotenv';
8
7
  import { readFileSync, existsSync, statSync } from 'node:fs';
9
8
  import { join } from 'node:path';
@@ -47,7 +46,6 @@ async function getCustomEnv(c) {
47
46
  ...process.env,
48
47
  ...(c.env || {}),
49
48
  BUNDLED_DEFINITIONS: cachedSchemas,
50
- KAMA_EXTENSIONS: activeExtensions, // 🎯 2. Pass extensions dynamically into the Core
51
49
  KAMA_RUNTIME: (c.env && c.env.DB) ? 'cloudflare' : 'node'
52
50
  };
53
51
  }
@@ -1,5 +0,0 @@
1
- id: kama-forms-block
2
- label: Kama Forms Block
3
- category: Extensions
4
- fields:
5
- - title