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

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 (107) 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-B5YK3NZZ.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-DpAR9hiH.js +1 -0
  11. package/dist/assets/CmsHelp-DwhLI-mW.js +1 -0
  12. package/dist/assets/CmsImagePreview-cWi-cfCr.js +1 -0
  13. package/dist/assets/CmsPublisher-Dmgl7E5H.js +3 -0
  14. package/dist/assets/CmsUserCenter-D9SqVAd7.js +1 -0
  15. package/dist/assets/EditorSplitPreview-DkLHfob8.js +1 -0
  16. package/dist/assets/EditorSplitPreview-eID9z4gI.css +1 -0
  17. package/dist/assets/FormsWorkspace-DPTcxMpw.css +1 -0
  18. package/dist/assets/FormsWorkspace-Dx-yu7Rn.js +1 -0
  19. package/dist/assets/NodeContextMenu-qV4OaL33.js +1 -0
  20. package/dist/assets/NodeEditor-5Caiaqod.js +161 -0
  21. package/dist/assets/NodeEditor-rrOvlGF8.css +1 -0
  22. package/dist/assets/StatusPill-BAnTGDR_.js +1 -0
  23. package/dist/assets/TrashWorkspace-CeZzWZEm.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-CgystKmt.js +16 -0
  32. package/dist/assets/index-Cktd5m_n.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-DMowrLHc.js +1 -0
  38. package/dist/assets/preload-helper-CstCHdlQ.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-aep6ZB35.js +1 -0
  46. package/dist/assets/useNodes-DpypEHNz.js +1 -0
  47. package/dist/assets/user-C5hzf6BE.js +1 -0
  48. package/dist/assets/x-3cfZis8N.js +1 -0
  49. package/dist/{dist-3Xc2TTZw.js → dist-BP62QUQb.js} +5248 -4364
  50. package/dist/index.html +32 -30
  51. package/dist/index.js +5676 -4794
  52. package/dist/nodemailer-Ccic7tRm-Cf8qGuYa.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 +174 -0
  57. package/package.json +3 -1
  58. package/schema.sql +13 -0
  59. package/templates/astro-starter/src/components/blocks/BlockRenderer.astro +8 -0
  60. package/templates/astro-starter/src/components/blocks/Form.astro +232 -62
  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-4TsNvk2f.css +0 -1
  81. package/dist/assets/NodeEditor-DA5GRtRP.js +0 -161
  82. package/dist/assets/StatusPill-CbeW5SMT.js +0 -1
  83. package/dist/assets/TrashWorkspace-CATe46WF.js +0 -1
  84. package/dist/assets/circle-check-A-QeFqt3.js +0 -1
  85. package/dist/assets/database-hg5SqKLG.js +0 -1
  86. package/dist/assets/folder-tree-BWYot72H.js +0 -1
  87. package/dist/assets/globe-BraoljaN.js +0 -1
  88. package/dist/assets/history-pqIbKK9u.js +0 -1
  89. package/dist/assets/index-CY0VYSyt.css +0 -1
  90. package/dist/assets/index-DdG9Pozx.js +0 -14
  91. package/dist/assets/layers-B6RgfpPR.js +0 -1
  92. package/dist/assets/loader-circle-BoUkhDjq.js +0 -1
  93. package/dist/assets/monitor-CrpvInqG.js +0 -1
  94. package/dist/assets/panel-left-close-CVFakVaA.js +0 -1
  95. package/dist/assets/plus-CX_GHzXs.js +0 -1
  96. package/dist/assets/rotate-ccw-CWE4pOjs.js +0 -1
  97. package/dist/assets/save-Ctv8vW9H.js +0 -1
  98. package/dist/assets/schema-helpers-DvficKko.js +0 -1
  99. package/dist/assets/send-F-mJeL54.js +0 -1
  100. package/dist/assets/smartphone-EPce6VdP.js +0 -1
  101. package/dist/assets/trash-2-CAUF1KtI.js +0 -1
  102. package/dist/assets/useLocalStorage-C805uplI.js +0 -1
  103. package/dist/assets/useNodes-CqFlc72m.js +0 -1
  104. package/dist/assets/user-IFlT6mYq.js +0 -1
  105. package/documentation/EXTENSIONS.md +0 -204
  106. package/extension-registry.js +0 -5
  107. /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-BP62QUQb.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,174 @@
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 override the complete finisher list for that
82
+ block. This includes enabling or disabling database storage, adding/removing
83
+ email finishers, setting their recipient or recipient field, provider, subject,
84
+ sender display name, reply-to address/field, and text/HTML templates. Registered
85
+ custom finishers can be added from the registered types, enabled, removed, or
86
+ edited as JSON. With block overrides disabled, the form-level finisher list is
87
+ used unchanged.
88
+
89
+ Block overrides are saved with the page content. The public submission request
90
+ sends the page and block identifiers; KAMA reloads and validates the published
91
+ finisher configuration from the database, rather than trusting settings posted
92
+ by the visitor. Sender email addresses and transport credentials remain
93
+ deployment configuration and cannot be changed in the block sidebar. Custom
94
+ finisher JSON is validated for size and type, but each custom handler remains
95
+ responsible for validating its own settings.
96
+
97
+ KAMA registers `database` and `email` finishers by default. Add custom types by
98
+ registering a handler during server startup, before submissions are handled:
99
+
100
+ ```ts
101
+ import { registerFormFinisher } from '@brightsideoy/kama';
102
+
103
+ registerFormFinisher('webhook', async ({ finisher, payload, env }) => {
104
+ // Implement this finisher and throw if it fails.
105
+ });
106
+ ```
107
+
108
+ Then use `type: webhook` in a form's `finishers` list. Handlers run in list
109
+ order; throwing stops later finishers and returns a submission failure.
110
+
111
+ For Workers, add the Email Sending binding to your Wrangler config after
112
+ onboarding a sender domain in Cloudflare Email Service:
113
+
114
+ ```jsonc
115
+ {
116
+ "send_email": [{ "name": "FORMS_EMAIL" }]
117
+ }
118
+ ```
119
+
120
+ Set `FORMS_EMAIL_FROM` to an address at the onboarded domain. Cloudflare Email
121
+ Sending requires the appropriate Workers plan for arbitrary external
122
+ recipients. The KAMA project does not enable this binding automatically.
123
+
124
+ For Node deployments, configure:
125
+
126
+ ```sh
127
+ FORMS_SMTP_HOST=smtp.example.com
128
+ FORMS_SMTP_PORT=465
129
+ FORMS_SMTP_SECURE=true
130
+ FORMS_SMTP_USER=...
131
+ FORMS_SMTP_PASSWORD=...
132
+ FORMS_EMAIL_FROM=forms@example.com
133
+ FORMS_EMAIL_FROM_NAME=KAMA
134
+ ```
135
+
136
+ For Cloudflare authenticated SMTP, use `smtp.mx.cloudflare.net:465`, username
137
+ `api_token`, and an Email Sending: Edit API token as the password. Keep SMTP
138
+ credentials in the deployment's secret manager, never in form YAML. Use valid
139
+ sender and recipient addresses; Email Sending is intended for transactional
140
+ mail, not bulk marketing.
141
+
142
+ For forms with
143
+ `settings.requireTurnstile: true`, configure both keys:
144
+
145
+ - `PUBLIC_TURNSTILE_SITE_KEY` on the frontend site (a public Wrangler `vars`
146
+ value, or a local `.dev.vars` value). This renders the widget.
147
+ - `TURNSTILE_SECRET_KEY` on the KAMA worker (a Wrangler secret, or a local
148
+ `.dev.vars` value). The server uses it to verify each response.
149
+
150
+ Use the site key from the same Turnstile widget as the server secret. The Form
151
+ block displays a configuration warning when Turnstile is required but its site
152
+ key is missing. The block's optional **Success Message** overrides the success
153
+ message configured on the form definition.
154
+
155
+ For local Astro development only, KAMA uses Cloudflare's documented
156
+ always-pass test keys when no site key or secret is configured. These keys
157
+ cannot protect a production form; configure real keys for deployed environments.
158
+
159
+ The Astro starter's Form block loads definitions through the `CMS_WORKER`
160
+ service binding when available and sends submissions through a same-origin
161
+ `/api/forms/:formId/submissions` proxy. Outside the service binding, it uses
162
+ `PUBLIC_API_URL` server-side; local development falls back to `http://localhost:8787`.
163
+ Do not expose a server-only API secret in browser code.
164
+
165
+ For local Astro development with a configured `CMS_WORKER` binding, run the
166
+ CMS Worker locally on port `8787` as well as the Astro site. If Astro's local
167
+ service binding reports that the target Worker is not running, the page route
168
+ falls back to `127.0.0.1:8787`. Keep the site's and CMS Worker's
169
+ `FRONTEND_API_SECRET` values matched in their local secret files.
170
+
171
+ The public API serves definitions at `GET /api/v1/forms/:formId` and accepts
172
+ submissions at `POST /api/v1/forms/:formId/submissions`. The CMS uses
173
+ `GET /api/cms/forms` to populate the block selector and
174
+ `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.23",
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,10 +6,12 @@ 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 {
12
13
  instanceId: number;
14
+ contentId?: number | string;
13
15
  blockId?: string;
14
16
  componentId: string;
15
17
  data: Record<string, any>;
@@ -62,6 +64,12 @@ const visibleBlocks = safeBlocks.filter(b => {
62
64
  }
63
65
 
64
66
  switch (componentId) {
67
+ case "form":
68
+ case "form-block":
69
+ case "form_block": {
70
+ return <FormBlock data={data} blockId={block.blockId || data.blockId || ""} contentId={block.contentId || ""} />;
71
+ }
72
+
65
73
  // 🎯 ADDED NODE LIST CASES
66
74
  case "node-list":
67
75
  case "nodelist":
@@ -1,36 +1,67 @@
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
  };
10
+ blockId: number | string;
11
+ contentId: number | string;
7
12
  }
8
13
 
9
- const { data } = Astro.props;
14
+ const { data, blockId, contentId } = Astro.props;
10
15
  const formId = data?.formId;
11
16
 
12
- const kamaApiUrl = import.meta.env.KAMA_API_URL || 'http://localhost:8787';
13
- const turnstileSiteKey = import.meta.env.PUBLIC_TURNSTILE_SITE_KEY;
17
+ const safeEnv = (Astro.locals as any).safeEnv || {};
18
+ const cmsWorker = safeEnv.CMS_WORKER;
19
+ const kamaApiUrl = String(
20
+ import.meta.env.DEV && !cmsWorker
21
+ ? 'http://localhost:8787'
22
+ : import.meta.env.PUBLIC_API_URL || safeEnv.PUBLIC_API_URL || 'http://localhost:8787'
23
+ ).replace(/\/$/, '');
24
+ const configuredTurnstileSiteKey = String(
25
+ import.meta.env.PUBLIC_TURNSTILE_SITE_KEY || safeEnv.PUBLIC_TURNSTILE_SITE_KEY || ''
26
+ ).trim();
27
+ const turnstileSiteKey = configuredTurnstileSiteKey || (
28
+ import.meta.env.DEV ? '1x00000000000000000000AA' : ''
29
+ );
14
30
 
15
- // Fetch form YAML schema at render time
31
+ // Fetch the built-in form schema at render time
16
32
  let schema = null;
17
33
  if (formId) {
18
34
  try {
19
- const res = await fetch(`${kamaApiUrl}/api/ext/kama-forms/render/${formId}`);
35
+ const schemaUrl = `${kamaApiUrl}/api/v1/forms/${encodeURIComponent(formId)}`;
36
+ const schemaRequest = new Request(schemaUrl, { headers: { Accept: 'application/json' } });
37
+ const res = await fetchCmsRequest(schemaRequest, cmsWorker);
20
38
  if (res.ok) schema = await res.json();
21
- } catch (err) {
22
- console.error(`Failed to fetch schema for ${formId}`);
39
+ else console.error(`[Forms] Failed to load ${formId}: HTTP ${res.status}`);
40
+ } catch (error) {
41
+ console.error(`[Forms] Failed to load definition ${formId}:`, error);
23
42
  }
24
43
  }
25
44
 
26
45
  const requiresTurnstile = schema?.settings?.requireTurnstile === true;
46
+ const submittedFormId = Astro.url.searchParams.get('formId');
47
+ const submissionStatus = submittedFormId === formId
48
+ ? Astro.url.searchParams.get('formStatus')
49
+ : null;
50
+ const submissionMessage = Astro.url.searchParams.get('formMessage');
27
51
  ---
28
52
 
29
53
  {schema ? (
30
- <div class="kama-form-wrapper" data-form-id={formId} data-api-url={kamaApiUrl}>
54
+ <div
55
+ class="kama-form-wrapper"
56
+ data-form-id={formId}
57
+ data-form-block-id={blockId}
58
+ data-form-content-id={contentId}
59
+ data-api-url="/api/forms"
60
+ data-success-message={data?.successMessage || ''}
61
+ >
31
62
 
32
63
  <!-- 🎯 Conditionally load Cloudflare Turnstile Script -->
33
- {requiresTurnstile && (
64
+ {requiresTurnstile && turnstileSiteKey && (
34
65
  <script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
35
66
  )}
36
67
 
@@ -39,15 +70,28 @@ const requiresTurnstile = schema?.settings?.requireTurnstile === true;
39
70
  {schema.description && <p>{schema.description}</p>}
40
71
  </div>
41
72
 
42
- <div class="form-alert success" style="display: none;"></div>
43
- <div class="form-alert error" style="display: none;"></div>
73
+ <div
74
+ class="form-alert success"
75
+ role="status"
76
+ aria-live="polite"
77
+ style={submissionStatus === 'success' ? undefined : 'display: none;'}
78
+ >{submissionStatus === 'success' ? (data?.successMessage || submissionMessage || 'Form submitted successfully!') : ''}</div>
79
+ <div
80
+ class="form-alert error"
81
+ role="alert"
82
+ style={submissionStatus === 'error' ? undefined : 'display: none;'}
83
+ >{submissionStatus === 'error' ? (submissionMessage || 'Form submission failed.') : ''}</div>
44
84
 
45
- <form class="kama-public-form">
85
+ <form
86
+ class="kama-public-form"
87
+ method="post"
88
+ action={`/api/forms/${encodeURIComponent(formId)}/submissions`}
89
+ >
46
90
  {schema.fields?.map((field: any) => (
47
91
  <div class="form-group">
48
92
  <label for={`field-${field.name}`}>
49
93
  {field.label}
50
- {field.required && <span class="required">*</span>}
94
+ {field.required && <span class="required" aria-hidden="true"> *</span>}
51
95
  </label>
52
96
 
53
97
  {field.type === 'textarea' ? (
@@ -71,73 +115,199 @@ const requiresTurnstile = schema?.settings?.requireTurnstile === true;
71
115
  <div class="cf-turnstile" data-sitekey={turnstileSiteKey}></div>
72
116
  </div>
73
117
  )}
118
+ {requiresTurnstile && !turnstileSiteKey && (
119
+ <p class="form-alert error" role="alert">
120
+ This form requires Cloudflare Turnstile, but the site key is not configured.
121
+ Set PUBLIC_TURNSTILE_SITE_KEY for the site.
122
+ </p>
123
+ )}
74
124
 
75
125
  <button type="submit" class="submit-btn">Submit</button>
76
126
  </form>
77
127
  </div>
78
128
  ) : (
79
- <p class="form-error">Form definition "{formId}" could not be loaded.</p>
129
+ <p class="form-error" role="alert">Form definition "{formId}" could not be loaded.</p>
80
130
  )}
81
131
 
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');
132
+ <style>
133
+ .kama-form-wrapper {
134
+ width: 100%;
135
+ max-width: 48rem;
136
+ color: #1e293b;
137
+ }
138
+
139
+ .form-header h3 {
140
+ margin-top: 0;
141
+ }
142
+
143
+ .form-header p {
144
+ color: #334155;
145
+ }
146
+
147
+ .kama-public-form {
148
+ display: grid;
149
+ gap: 1.25rem;
150
+ }
151
+
152
+ .form-group {
153
+ display: grid;
154
+ gap: 0.4rem;
155
+ min-width: 0;
156
+ }
157
+
158
+ .form-group label {
159
+ color: #0f172a;
160
+ font-weight: 600;
161
+ }
162
+
163
+ .required {
164
+ color: #b91c1c;
165
+ }
90
166
 
91
- if (!form || !formId || !apiUrl) return;
167
+ .form-group input,
168
+ .form-group select,
169
+ .form-group textarea {
170
+ width: 100%;
171
+ min-height: 2.75rem;
172
+ padding: 0.65rem 0.75rem;
173
+ border: 1px solid #64748b;
174
+ border-radius: 0;
175
+ background: #fff;
176
+ color: #0f172a;
177
+ font: inherit;
178
+ line-height: 1.5;
179
+ }
92
180
 
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';
181
+ .form-group textarea {
182
+ min-height: 7rem;
183
+ resize: vertical;
184
+ }
98
185
 
99
- // FormData automatically picks up the hidden "cf-turnstile-response" input
100
- const formData = new FormData(form);
101
- const payload = Object.fromEntries(formData.entries());
186
+ .form-group input::placeholder,
187
+ .form-group textarea::placeholder {
188
+ color: #475569;
189
+ opacity: 1;
190
+ }
191
+
192
+ .form-group input:focus-visible,
193
+ .form-group select:focus-visible,
194
+ .form-group textarea:focus-visible,
195
+ .submit-btn:focus-visible {
196
+ outline: 3px solid #1d4ed8;
197
+ outline-offset: 2px;
198
+ }
199
+
200
+ .turnstile-container {
201
+ overflow-x: auto;
202
+ }
203
+
204
+ .submit-btn {
205
+ justify-self: start;
206
+ min-height: 2.75rem;
207
+ padding: 0.65rem 1rem;
208
+ border: 1px solid #0f172a;
209
+ border-radius: 0;
210
+ background: #0f172a;
211
+ color: #fff;
212
+ font: inherit;
213
+ font-weight: 600;
214
+ cursor: pointer;
215
+ }
216
+
217
+ .submit-btn:hover:not(:disabled) {
218
+ background: #334155;
219
+ }
220
+
221
+ .submit-btn:disabled {
222
+ cursor: wait;
223
+ opacity: 0.7;
224
+ }
225
+
226
+ .form-alert {
227
+ margin: 0 0 1rem;
228
+ padding: 0.75rem 1rem;
229
+ border: 1px solid;
230
+ border-left-width: 4px;
231
+ color: #0f172a;
232
+ }
233
+
234
+ .form-alert.success {
235
+ border-color: #166534;
236
+ background: #f0fdf4;
237
+ }
238
+
239
+ .form-alert.error,
240
+ .form-error {
241
+ margin: 0 0 1rem;
242
+ padding: 0.75rem 1rem;
243
+ border: 1px solid #b91c1c;
244
+ border-left-width: 4px;
245
+ background: #fef2f2;
246
+ color: #7f1d1d;
247
+ }
248
+
249
+ @media (max-width: 30rem) {
250
+ .submit-btn {
251
+ width: 100%;
252
+ }
253
+ }
254
+ </style>
255
+
256
+ <script is:inline>
257
+ (() => {
258
+ if (document.documentElement.dataset.kamaFormHandler) return;
259
+ document.documentElement.dataset.kamaFormHandler = 'true';
260
+
261
+ document.addEventListener('submit', async (event) => {
262
+ const form = event.target instanceof HTMLFormElement && event.target.matches('.kama-public-form')
263
+ ? event.target
264
+ : null;
265
+ if (!form) return;
266
+
267
+ event.preventDefault();
268
+ const container = form.closest('.kama-form-wrapper');
269
+ const formId = container?.getAttribute('data-form-id');
270
+ const successBox = container?.querySelector('.form-alert.success');
271
+ const errorBox = container?.querySelector('.form-alert.error');
272
+ const submitBtn = container?.querySelector('.submit-btn');
273
+ if (!container || !formId || !successBox || !errorBox || !submitBtn) return;
274
+
275
+ submitBtn.disabled = true;
276
+ successBox.style.display = 'none';
277
+ errorBox.style.display = 'none';
102
278
 
103
279
  try {
104
- const res = await fetch(`${apiUrl}/api/ext/kama-forms/submit/${formId}`, {
280
+ const payload = Object.fromEntries(new FormData(form).entries());
281
+ payload._kamaFinisherBlockId = container.getAttribute('data-form-block-id');
282
+ payload._kamaFinisherContentId = container.getAttribute('data-form-content-id');
283
+ const response = await fetch(form.action, {
105
284
  method: 'POST',
106
- headers: { 'Content-Type': 'application/json' },
285
+ headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
107
286
  body: JSON.stringify(payload)
108
287
  });
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
- }
288
+ const responseText = await response.text();
289
+ let result;
290
+ try {
291
+ result = JSON.parse(responseText);
292
+ } catch {
293
+ throw new Error(`Form API returned an invalid response (HTTP ${response.status}).`);
132
294
  }
133
- } catch (err) {
134
- if (errorBox) {
135
- errorBox.textContent = 'Server connection error.';
136
- errorBox.style.display = 'block';
295
+
296
+ if (!response.ok || !result.success) {
297
+ throw new Error(result.error || 'Form submission failed.');
137
298
  }
299
+
300
+ successBox.textContent = container.getAttribute('data-success-message') || result.message || 'Form submitted successfully!';
301
+ successBox.style.display = 'block';
302
+ form.reset();
303
+ if (window.turnstile) window.turnstile.reset();
304
+ } catch (error) {
305
+ errorBox.textContent = error instanceof Error ? error.message : 'Form submission failed.';
306
+ errorBox.style.display = 'block';
307
+ if (window.turnstile) window.turnstile.reset();
138
308
  } finally {
139
- if (submitBtn) submitBtn.disabled = false;
309
+ submitBtn.disabled = false;
140
310
  }
141
311
  });
142
- });
312
+ })();
143
313
  </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();