@brightsideoy/kama 1.0.0-alpha.25 → 1.0.0-alpha.26

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 (83) hide show
  1. package/bin/cli.js +8 -2
  2. package/dist/assets/AssetEditor-BQp8ufSp.js +1 -0
  3. package/dist/assets/CmsAccordion-91I5Rx5D.css +1 -0
  4. package/dist/assets/CmsAccordion-BgdaB8QZ.js +1 -0
  5. package/dist/assets/CmsBadge-BT2jTJUu.js +1 -0
  6. package/dist/assets/CmsButton-DnhPsHXA.js +1 -0
  7. package/dist/assets/CmsFieldTaxonomy-DkAT1fuc.js +1 -0
  8. package/dist/assets/CmsHelp-BIbzY-Mi.js +1 -0
  9. package/dist/assets/CmsImagePreview-BhM7S_v8.js +1 -0
  10. package/dist/assets/CmsPublisher-Dc38zXt9.js +3 -0
  11. package/dist/assets/CmsUserCenter-CAaiCweN.js +1 -0
  12. package/dist/assets/EditorSplitPreview-fCwIcjhd.js +1 -0
  13. package/dist/assets/FormsWorkspace-Bb6wv80Y.js +2 -0
  14. package/dist/assets/FormsWorkspace-CGs6eUjz.css +1 -0
  15. package/dist/assets/NodeContextMenu-Bt_TK17e.js +1 -0
  16. package/dist/assets/{NodeEditor-rrOvlGF8.css → NodeEditor-C82xLR0T.css} +1 -1
  17. package/dist/assets/NodeEditor-Cv8XIMCm.js +161 -0
  18. package/dist/assets/StatusPill-HY1gCP9c.js +1 -0
  19. package/dist/assets/TrashWorkspace-C-PKJBRC.js +1 -0
  20. package/dist/assets/{_plugin-vue_export-helper-BdT0OEbg.js → _plugin-vue_export-helper-BK_c4R_m.js} +1 -1
  21. package/dist/assets/circle-check-CksZGUB7.js +1 -0
  22. package/dist/assets/database--QlkzG9u.js +1 -0
  23. package/dist/assets/globe-TuZP0v6A.js +1 -0
  24. package/dist/assets/history-CIbqkRx3.js +1 -0
  25. package/dist/assets/{index-DaXMl545.css → index-BYlliwPU.css} +1 -1
  26. package/dist/assets/index-C2AF4yr_.js +16 -0
  27. package/dist/assets/layers-BwACvD_U.js +1 -0
  28. package/dist/assets/loader-circle-DYEFqbD4.js +1 -0
  29. package/dist/assets/panel-left-close-Cpq52HZy.js +1 -0
  30. package/dist/assets/plus-BA5G4zTK.js +1 -0
  31. package/dist/assets/preload-helper-Bjoj7SyZ.js +1 -0
  32. package/dist/assets/rotate-ccw-DvjWccJd.js +1 -0
  33. package/dist/assets/save-Dwhm8QNL.js +1 -0
  34. package/dist/assets/send-Bs4eROle.js +1 -0
  35. package/dist/assets/smartphone-i429gh5p.js +1 -0
  36. package/dist/assets/trash-2-CrOsVo1D.js +1 -0
  37. package/dist/assets/{useCmsState-BblziYb-.js → useCmsState-rZqeAwK1.js} +1 -1
  38. package/dist/assets/{useNodes-GLoFdA2T.js → useNodes-B-Q6yDsj.js} +1 -1
  39. package/dist/assets/user-DKryA1QU.js +1 -0
  40. package/dist/assets/x-DOWbsdzd.js +1 -0
  41. package/dist/{dist-ZQFhgFUY.js → dist-BAUJQ0-e.js} +95 -38
  42. package/dist/index.html +25 -26
  43. package/dist/index.js +94 -37
  44. package/dist/{nodemailer-Ccic7tRm-Chwouykd.js → nodemailer-Ccic7tRm-Dl2YIOIv.js} +1 -1
  45. package/dist/schema-compiler.js +1 -1
  46. package/documentation/FORMS.md +181 -99
  47. package/package.json +1 -1
  48. package/templates/astro-starter/astro-preview-dev-integration.mjs +83 -0
  49. package/templates/astro-starter/astro.config.mjs +11 -0
  50. package/templates/astro-starter/src/middleware.ts +11 -9
  51. package/dist/assets/AssetEditor-CVfLHR57.js +0 -1
  52. package/dist/assets/CmsBadge-DB0WNyWx.js +0 -1
  53. package/dist/assets/CmsButton-BbvewMhp.js +0 -1
  54. package/dist/assets/CmsFieldTaxonomy-DWlLLL92.js +0 -1
  55. package/dist/assets/CmsHelp-D4z0YSWX.js +0 -1
  56. package/dist/assets/CmsImagePreview-cWi-cfCr.js +0 -1
  57. package/dist/assets/CmsPublisher-Dz_XTFmW.js +0 -3
  58. package/dist/assets/CmsUserCenter-DE_op9OZ.js +0 -1
  59. package/dist/assets/EditorSplitPreview-C9Gb4usO.js +0 -1
  60. package/dist/assets/FormsWorkspace-DPTcxMpw.css +0 -1
  61. package/dist/assets/FormsWorkspace-DdYcrdg3.js +0 -1
  62. package/dist/assets/NodeContextMenu-qV4OaL33.js +0 -1
  63. package/dist/assets/NodeEditor-BNKrtv8t.js +0 -161
  64. package/dist/assets/StatusPill-BAnTGDR_.js +0 -1
  65. package/dist/assets/TrashWorkspace-DtbKBkM2.js +0 -1
  66. package/dist/assets/circle-check-CB39w7cZ.js +0 -1
  67. package/dist/assets/createLucideIcon-BIiMnJpN.js +0 -1
  68. package/dist/assets/database-mgNVRFlp.js +0 -1
  69. package/dist/assets/globe-Clq_OlnU.js +0 -1
  70. package/dist/assets/history-ZSqpsbjQ.js +0 -1
  71. package/dist/assets/index-N7ViZ7U5.js +0 -16
  72. package/dist/assets/layers-CH2VvrZT.js +0 -1
  73. package/dist/assets/loader-circle-CwP4GuFX.js +0 -1
  74. package/dist/assets/panel-left-close-g4nIMIjy.js +0 -1
  75. package/dist/assets/plus-DCPXsir3.js +0 -1
  76. package/dist/assets/preload-helper-CstCHdlQ.js +0 -1
  77. package/dist/assets/rotate-ccw-tUaGL4DO.js +0 -1
  78. package/dist/assets/save-BUYaWIjt.js +0 -1
  79. package/dist/assets/send-UE48lWD8.js +0 -1
  80. package/dist/assets/smartphone-B7c4WqQk.js +0 -1
  81. package/dist/assets/trash-2-D8h6WxFK.js +0 -1
  82. package/dist/assets/user-Bo_HcyTz.js +0 -1
  83. package/dist/assets/x-3cfZis8N.js +0 -1
@@ -1,9 +1,25 @@
1
1
  # Forms
2
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.
3
+ KAMA forms are defined in YAML and can be added to pages with the built-in
4
+ **Form** block. The CMS lets you configure submission storage and email
5
+ finishers, and view saved submissions.
6
+
7
+ ## Contents
8
+
9
+ - [Form definitions](#form-definitions)
10
+ - [Add a form to a page](#add-a-form-to-a-page)
11
+ - [Submissions](#submissions)
12
+ - [Finishers](#finishers)
13
+ - [Email delivery](#email-delivery)
14
+ - [Turnstile verification](#turnstile-verification)
15
+ - [Local development](#local-development)
16
+ - [API reference](#api-reference)
17
+
18
+ ## Form definitions
19
+
20
+ Create a YAML file in `content/definitions/forms/`. Its filename is used as the
21
+ form ID if you do not set `id` in the file. After adding or changing definitions,
22
+ run `npm run bundle:definitions` before deploying.
7
23
 
8
24
  ```yaml
9
25
  id: contact
@@ -23,79 +39,83 @@ settings:
23
39
  requireTurnstile: false
24
40
  ```
25
41
 
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
42
+ ## Add a form to a page
43
+
44
+ Add the **Form** block to a page and select the form. The block's optional
45
+ **Success Message** overrides the message in the form definition.
46
+
47
+ ## Submissions
48
+
49
+ All finishers are disabled by default. A valid submission with no finisher
50
+ enabled receives the configured success response, but is not saved or emailed.
51
+
52
+ Select a form in the Forms sidebar, then use the **Finishers** tab in the main
53
+ workspace to enable **Save submissions to database**. Saved entries are
54
+ available in the **Submissions** tab. That tab is shown only when database
55
+ storage is enabled. If an existing table has the old schema, KAMA recreates it
36
56
  at startup.
37
57
 
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:
58
+ Expand a submission to view its values in a field/value table using the form's
59
+ field labels. Use **Download CSV** to export submissions, or select individual
60
+ submissions and delete them together; each submission can also be deleted on
61
+ its own.
62
+
63
+ The **Finishers** tab also lets you configure email notifications, including a
64
+ fixed team recipient or the form's email field for a submitter confirmation.
65
+ Provider credentials remain deployment configuration. Set a package-wide
66
+ default sender with `FORMS_EMAIL_FROM`, or set a sender address on an individual
67
+ email finisher. Finisher settings are grouped into collapsible sections to make
68
+ the configuration easier to scan. Team notifications and submitter confirmations
69
+ have separate sections and can be enabled and configured independently. Each
70
+ section shows its enabled state while collapsed.
71
+
72
+ ## Finishers
73
+
74
+ Finishers run after field validation and Turnstile verification, in the order
75
+ listed. KAMA registers the `database` and `email` finishers by default. You can
76
+ configure finishers on the form or override them on an individual Form block.
77
+
78
+ ### Configure finishers on a form
79
+
80
+ For code-defined forms, configure email finishers in the form's YAML:
44
81
 
45
82
  ```yaml
46
83
  finishers:
47
84
  - id: notify-team
48
85
  type: email
49
- provider: auto
86
+ from: notifications@example.com
50
87
  to: team@example.com
51
88
  subject: "New message from {{fullName}}"
52
89
  replyToField: email
53
90
  - id: confirmation
54
91
  type: email
55
- provider: auto
56
92
  toField: email
57
93
  subject: "We received your message"
58
94
  text: "Thanks {{fullName}}, we received your message."
59
95
  ```
60
96
 
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.
97
+ When finisher settings are saved in the CMS, they override the YAML settings.
98
+ Registered custom finishers are preserved when built-in settings are edited.
99
+
100
+ ### Override finishers on a Form block
101
+
102
+ The block editor can replace the form's complete finisher list. It supports
103
+ enabling or disabling database storage, adding or removing email finishers, and
104
+ setting their recipient, sender email, subject, sender name, reply-to, and
105
+ message templates. Registered custom finishers can also be added, enabled,
106
+ removed, or edited as JSON. Email transport is configured once for the KAMA
107
+ package environment, not per form or block.
108
+
109
+ Block overrides are saved with the page. On submission, KAMA reloads and
110
+ validates the published finisher configuration from the database instead of
111
+ trusting settings sent by the visitor. Transport credentials cannot be changed
112
+ in the block editor. Sender addresses must be authorized by the configured
113
+ email provider. Custom finisher JSON is validated for size and type; each
114
+ custom handler must validate its own settings.
71
115
 
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:
116
+ ### Add a custom finisher
117
+
118
+ Register a handler during server startup, before submissions are handled:
99
119
 
100
120
  ```ts
101
121
  import { registerFormFinisher } from '@brightsideoy/kama';
@@ -105,25 +125,48 @@ registerFormFinisher('webhook', async ({ finisher, payload, env }) => {
105
125
  });
106
126
  ```
107
127
 
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.
128
+ Then add `type: webhook` to a form's `finishers` list. Handlers run in list
129
+ order. If one throws, later finishers do not run and the submission fails.
130
+
131
+ ## Email delivery
132
+
133
+ ### Configure the transport
110
134
 
111
- For Workers, add the Email Sending binding to your Wrangler config after
112
- onboarding a sender domain in Cloudflare Email Service:
135
+ Set `FORMS_EMAIL_PROVIDER` once in the KAMA package's runtime environment. For
136
+ local Cloudflare development, put it in `.dev.vars`; for deployed Workers, put
137
+ it in Wrangler `vars`:
138
+
139
+ ```sh
140
+ # .dev.vars
141
+ FORMS_EMAIL_PROVIDER=cloudflare
142
+ ```
143
+
144
+ - `cloudflare` requires the Cloudflare Email Sending binding.
145
+ - `smtp` requires SMTP configuration and is available in the Node runtime.
146
+ - `auto` (the default) uses the Cloudflare binding when available; otherwise
147
+ it uses SMTP in Node.
148
+
149
+ For Workers, set the provider as a Wrangler variable and add the Email Sending
150
+ binding after onboarding a sender domain in Cloudflare Email Service:
113
151
 
114
152
  ```jsonc
115
153
  {
154
+ "vars": {
155
+ "FORMS_EMAIL_PROVIDER": "cloudflare"
156
+ },
116
157
  "send_email": [{ "name": "FORMS_EMAIL" }]
117
158
  }
118
159
  ```
119
160
 
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.
161
+ Set `FORMS_EMAIL_FROM` to the package-wide default sender address at the
162
+ onboarded domain. An individual email finisher can override it with `from`.
163
+ Cloudflare Email Sending requires the appropriate Workers plan for arbitrary
164
+ external recipients. KAMA does not enable the binding automatically.
123
165
 
124
166
  For Node deployments, configure:
125
167
 
126
168
  ```sh
169
+ FORMS_EMAIL_PROVIDER=smtp
127
170
  FORMS_SMTP_HOST=smtp.example.com
128
171
  FORMS_SMTP_PORT=465
129
172
  FORMS_SMTP_SECURE=true
@@ -139,36 +182,75 @@ credentials in the deployment's secret manager, never in form YAML. Use valid
139
182
  sender and recipient addresses; Email Sending is intended for transactional
140
183
  mail, not bulk marketing.
141
184
 
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.
185
+ ### Customize email content
186
+
187
+ Use `from` to override the package-wide `FORMS_EMAIL_FROM` sender for this
188
+ finisher. The address must be authorized by the selected email provider. If
189
+ omitted, the package-wide sender is used.
190
+
191
+ Use `toField` to select a recipient from the submission; it must name a form
192
+ field with `type: email`. Use `subjectField`, `fromNameField`, or
193
+ `replyToField` to select submission values. `replyToField` must also name an
194
+ email field. Keep the sender address fixed; use `replyToField` when replies
195
+ should go to the submitter. Subject text and optional `text` or `html` bodies
196
+ support `{{field}}` placeholders. Interpolated HTML values are escaped.
197
+
198
+ If no body template is set, the message includes all submitted fields.
199
+ `FORMS_EMAIL_FROM` is the sender fallback, and `FORMS_EMAIL_FROM_NAME` provides
200
+ an optional deployment-wide sender-name fallback.
201
+
202
+ If an email finisher fails, the submission fails and KAMA does not return a
203
+ success response. Email delivery and database writes cannot be rolled back
204
+ atomically, so earlier finishers may already have run. Retrying can repeat
205
+ those side effects.
206
+
207
+ ## Turnstile verification
208
+
209
+ For forms with `settings.requireTurnstile: true`, configure both keys:
210
+
211
+ - `PUBLIC_TURNSTILE_SITE_KEY` on the frontend site, as a public Wrangler `vars`
212
+ value or local `.dev.vars` value. This renders the widget.
213
+ - `TURNSTILE_SECRET_KEY` on the KAMA Worker, as a Wrangler secret or local
214
+ `.dev.vars` value. The server uses it to verify each response.
215
+
216
+ Use keys from the same Turnstile widget. The Form block warns when Turnstile is
217
+ required but the site key is missing.
218
+
219
+ For local Astro development only, KAMA uses Cloudflare's documented always-pass
220
+ test keys when no site key or secret is configured. These keys do not protect a
221
+ production form; configure real keys for deployed environments.
222
+
223
+ ## Local development
224
+
225
+ ### Connect the Astro site to KAMA
226
+
227
+ When available, the Astro starter uses the `CMS_WORKER` service binding for CMS
228
+ API and `/media/*` requests. Form submissions go through the same-origin
229
+ `/api/forms/:formId/submissions` proxy. Without the binding, it uses
230
+ `PUBLIC_API_URL` server-side; local development defaults to the CMS Worker at
231
+ `http://127.0.0.1:8787`.
232
+
233
+ For local Astro development, run the CMS Worker on port `8787` as well as the
234
+ Astro site. If the local service binding reports that its target Worker is not
235
+ running, page and media proxies fall back to `127.0.0.1:8787`. Keep the site's
236
+ and CMS Worker's `FRONTEND_API_SECRET` values matched in their local secret
237
+ files. Never expose a server-only API secret in browser code.
238
+
239
+ ### Draft preview iframe
240
+
241
+ The starter serves Vite modules requested by KAMA's sandboxed Draft iframe from
242
+ the local dev server. The exception is limited to opaque-origin `GET` and `HEAD`
243
+ requests for Vite/source assets and media; API and page requests remain
244
+ protected by Astro's cross-origin dev guard. Keep the dev server bound to
245
+ loopback.
246
+
247
+ ## API reference
248
+
249
+ | Method | Endpoint | Purpose |
250
+ | --- | --- | --- |
251
+ | `GET` | `/api/v1/forms/:formId` | Fetch a form definition. |
252
+ | `POST` | `/api/v1/forms/:formId/submissions` | Submit a form. |
253
+ | `GET` | `/api/cms/forms` | Populate the Form block selector. |
254
+ | `GET` | `/api/cms/forms/:formId/submissions` | Fetch saved submissions and field labels. |
255
+ | `DELETE` | `/api/cms/forms/:formId/submissions/:submissionId` | Delete one saved submission. |
256
+ | `DELETE` | `/api/cms/forms/:formId/submissions` | Delete selected submissions; send `{ "ids": [1, 2] }` as JSON. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@brightsideoy/kama",
3
- "version": "1.0.0-alpha.25",
3
+ "version": "1.0.0-alpha.26",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -0,0 +1,83 @@
1
+ import path from 'node:path';
2
+
3
+ export function localPreviewDevIntegration(projectRoot) {
4
+ const sourceFilePrefix = `/@fs${path.resolve(projectRoot, 'src').replace(/\\/g, '/')}/`;
5
+
6
+ return {
7
+ name: 'kama-local-preview-dev-security',
8
+ hooks: {
9
+ 'astro:config:setup': ({ command, updateConfig }) => {
10
+ if (command !== 'dev') return;
11
+
12
+ updateConfig({
13
+ vite: {
14
+ plugins: [{
15
+ name: 'kama:allow-sandboxed-preview-assets',
16
+ enforce: 'post',
17
+ configureServer(server) {
18
+ return () => {
19
+ server.middlewares.stack.unshift({
20
+ route: '',
21
+ handle: async (request, response, next) => {
22
+ if (
23
+ request.headers.origin !== 'null' ||
24
+ request.headers['sec-fetch-site'] !== 'cross-site' ||
25
+ !['GET', 'HEAD'].includes(request.method || '')
26
+ ) {
27
+ return next();
28
+ }
29
+
30
+ let pathname;
31
+ try {
32
+ pathname = new URL(request.url || '/', 'http://localhost').pathname;
33
+ } catch {
34
+ return next();
35
+ }
36
+
37
+ const isViteAsset =
38
+ pathname === '/@vite/client' ||
39
+ pathname === '/@vite/env' ||
40
+ pathname.startsWith('/@id/') ||
41
+ pathname.startsWith('/node_modules/.vite/') ||
42
+ pathname.startsWith('/src/') ||
43
+ (pathname.startsWith('/@fs/') && pathname.includes('/node_modules/vite/dist/client/')) ||
44
+ pathname.startsWith(sourceFilePrefix);
45
+
46
+ if (isViteAsset) {
47
+ const isStylesheet = request.headers.accept?.includes('text/css') || false;
48
+ let transformUrl = request.url || '/';
49
+ if (isStylesheet && !/[?&]direct(?:&|$)/.test(transformUrl)) {
50
+ transformUrl += transformUrl.includes('?') ? '&direct' : '?direct';
51
+ }
52
+
53
+ try {
54
+ const result = await server.environments.client.transformRequest(transformUrl);
55
+ if (!result) return next();
56
+
57
+ response.statusCode = 200;
58
+ response.setHeader('Access-Control-Allow-Origin', 'null');
59
+ response.setHeader('Vary', 'Origin');
60
+ response.setHeader('Cache-Control', 'no-cache');
61
+ response.setHeader(
62
+ 'Content-Type',
63
+ isStylesheet ? 'text/css; charset=utf-8' : 'text/javascript; charset=utf-8',
64
+ );
65
+ return response.end(request.method === 'HEAD' ? undefined : result.code);
66
+ } catch (error) {
67
+ return next(error);
68
+ }
69
+ }
70
+
71
+ if (pathname.startsWith('/media/')) request.headers['sec-fetch-site'] = 'same-site';
72
+ next();
73
+ },
74
+ });
75
+ };
76
+ },
77
+ }],
78
+ },
79
+ });
80
+ },
81
+ },
82
+ };
83
+ }
@@ -2,6 +2,7 @@ import { defineConfig } from 'astro/config';
2
2
  import node from '@astrojs/node';
3
3
  import path from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
+ import { localPreviewDevIntegration } from './astro-preview-dev-integration.mjs';
5
6
 
6
7
  const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
8
 
@@ -13,7 +14,17 @@ export default defineConfig({
13
14
  trailingSlash: 'ignore',
14
15
  image: { service: { entrypoint: './src/lib/media/kama-image-service.ts' } },
15
16
  adapter: node({ mode: "standalone" }),
17
+ integrations: [localPreviewDevIntegration(__dirname)],
16
18
  vite: {
19
+ server: {
20
+ cors: {
21
+ origin: [
22
+ "null",
23
+ /^https?:\/\/localhost(?::\d+)?$/,
24
+ /^https?:\/\/127\.0\.0\.1(?::\d+)?$/,
25
+ ],
26
+ },
27
+ },
17
28
  resolve: { alias: { '@': path.resolve(__dirname, './src') } },
18
29
  ssr: {
19
30
  external: ['cloudflare:workers', 'tinyexec', 'node:child_process', 'node:fs', 'node:url', 'node:path', 'node:stream', 'node:readline', 'node:stream/promises']
@@ -1,6 +1,7 @@
1
1
  // src/middleware.ts
2
2
 
3
3
  import { defineMiddleware } from "astro:middleware";
4
+ import { fetchCmsRequest } from "./lib/cms-fetch";
4
5
 
5
6
  /**
6
7
  * Safely extracts environment variables across Astro 7, Node.js, and Cloudflare Workers
@@ -104,20 +105,21 @@ export const onRequest = defineMiddleware(async (context, next) => {
104
105
 
105
106
  // 2. Cold Fetch: Pass to CMS worker for AVIF transformation
106
107
  const cmsWorker = workerEnv?.CMS_WORKER;
107
- const envApiUrl = import.meta.env?.PUBLIC_API_URL;
108
- const workerApiUrl = workerEnv?.PUBLIC_API_URL;
109
- const baseApiUrl = String(envApiUrl || workerApiUrl || "https://kama.kamaengine.com");
108
+ const envApiUrl = import.meta.env?.PUBLIC_API_URL || import.meta.env?.PUBLIC_CMS_URL;
109
+ const workerApiUrl = workerEnv?.PUBLIC_API_URL || workerEnv?.PUBLIC_CMS_URL;
110
+ const localDevApiUrl = "http://127.0.0.1:8787";
111
+ const fallbackApiUrl = isDev ? localDevApiUrl : "https://kama.kamaengine.com";
112
+ const baseApiUrl = String(
113
+ isDev && !cmsWorker
114
+ ? localDevApiUrl
115
+ : workerApiUrl || envApiUrl || fallbackApiUrl
116
+ );
110
117
  const cleanApiUrl = baseApiUrl.endsWith("/") ? baseApiUrl.slice(0, -1) : baseApiUrl;
111
118
 
112
119
  const mediaUrl = `${cleanApiUrl}${pathname}${context.url.search}`;
113
120
  const mediaReq = new Request(mediaUrl, { headers: context.request.headers });
114
121
 
115
- let mediaResponse: Response;
116
- if (cmsWorker && typeof cmsWorker.fetch === "function") {
117
- mediaResponse = await cmsWorker.fetch(mediaReq);
118
- } else {
119
- mediaResponse = await fetch(mediaReq);
120
- }
122
+ const mediaResponse = await fetchCmsRequest(mediaReq, cmsWorker);
121
123
 
122
124
  const newHeaders = new Headers(mediaResponse.headers);
123
125
 
@@ -1 +0,0 @@
1
- import{C as e,Ct as t,E as n,G as r,I as i,P as a,Q as o,R as s,W as c,X as l,_ as u,b as d,g as f,i as p,k as m,m as h,ot as g,q as _,t as v,u as y,v as b,w as x,y as S,yt as ee}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{i as te}from"./useNodes-GLoFdA2T.js";import{a as ne,n as re}from"./useCmsState-BblziYb-.js";import{n as C,r as ie,t as ae}from"./NodeContextMenu-qV4OaL33.js";import{a as oe,i as se,n as ce,r as le,t as w}from"./CmsImagePreview-cWi-cfCr.js";import{n as ue,t as T}from"./trash-2-D8h6WxFK.js";import{t as de}from"./layers-CH2VvrZT.js";import{t as fe}from"./panel-left-close-g4nIMIjy.js";import{t as pe}from"./save-BUYaWIjt.js";import{t as E}from"./CmsButton-BbvewMhp.js";import{n as D,t as O}from"./CmsBadge-DB0WNyWx.js";import{t as me}from"./CmsFieldTaxonomy-DWlLLL92.js";m(),g(),_(),p();var he={class:`asset-editor-wrapper canvas`},k={class:`entity-header`},A={class:`top-row`},j={class:`node-info`},M={class:`dynamic-title-group`},N={class:`inline-title-input`},P={key:0},F={key:1},I={class:`meta-row`},L={key:0,class:`slug-badge`},R={class:`actions-group`},ge={class:`btn-text`},_e={class:`editor-body`},ve={key:0,class:`loading-state`},ye={key:1,class:`asset-content-scroll`},be={class:`main-preview-section`},xe={key:1,class:`doc-preview`},Se={class:`preview-footer`},Ce=[`href`],we={class:`data-column`},Te={class:`data-header`},Ee={class:`data-content`},De={class:`form-group`},Oe={class:`form-group`},ke={class:`form-group`},Ae={class:`form-group`},je={class:`usage-and-crops-section`},Me={class:`usage-section-container`},Ne={class:`gallery-header-row`},Pe={key:0,class:`usage-empty standalone-empty`},Fe={key:1,class:`list-container`},Ie={class:`node-title`},Le={class:`meta-stack`},Re={class:`node-field`},ze={key:0,class:`crop-showcase`},Be={class:`crop-name`},Ve={key:0,class:`usage-section-container`,style:{"margin-top":`40px`}},He={class:`gallery-header-row`},Ue={class:`list-container`},We={class:`meta-stack`},Ge={class:`node-field`},Ke={key:0,class:`crop-showcase`},qe={class:`crop-item`},Je={class:`crop-name`},Ye=[`onClick`],z=v(n({__name:`AssetEditor`,props:{assetId:{}},setup(n){let p=n,{activeView:m,nodeSchemas:g}=re(),{confirmDiscard:_}=ne(),{navigateToNodeById:v}=te(),z=l(null),B=l(!0),V=l(!1),H=l({filename:``,title:``,alt:``,tags:[]}),U=l({filename:``,title:``,alt:``,tags:[]}),W=l(!1),G=l(null),K=l(null),Xe=()=>{if(W.value){W.value=!1;return}G.value&&(K.value=G.value.getBoundingClientRect()),W.value=!0},Ze=f(()=>{let e=[{key:`copy-url`,label:`Copy Public URL`,icon:ie},{key:`open-tab`,label:`Open in New Tab`,icon:C}];return z.value&&z.value.connectedNodes?.length>0&&(e.push({key:`div-nodes`,label:``,divider:!0}),e.push({key:`show-nodes`,label:`Connected Nodes (${z.value.connectedNodes.length})`,icon:ce})),e.push({key:`div-1`,label:``,divider:!0},{key:`delete`,label:`Delete Asset`,icon:T}),e}),Qe=async e=>{W.value=!1,z.value&&(e===`copy-url`&&z.value.url?await navigator.clipboard.writeText(z.value.url):e===`open-tab`&&z.value.url?window.open(z.value.url,`_blank`):e===`delete`?await _(`Are you sure you want to delete "${z.value.filename||`this asset`}"?`,`Delete Asset?`,`Delete`,`Cancel`)&&await $e():e===`show-nodes`&&Y())},$e=async()=>{try{(await fetch(`/api/admin/assets/${p.assetId}`,{method:`DELETE`})).ok&&(window.dispatchEvent(new CustomEvent(`cms-assets-updated`)),m.value={type:`dashboard`})}catch{}},et=f(()=>H.value.filename!==U.value.filename||H.value.title!==U.value.title||H.value.alt!==U.value.alt||JSON.stringify(H.value.tags)!==JSON.stringify(U.value.tags)),q=async()=>{B.value=!0;try{let e=await fetch(`/api/admin/assets/${p.assetId}/details`);if(e.ok){let t=await e.json();z.value=t;let n={filename:t.filename||``,title:t.title||``,alt:t.alt||``,tags:t.tags||[]};H.value={...n},U.value={...n}}}catch{}finally{B.value=!1}},tt=async()=>{V.value=!0;try{(await fetch(`/api/admin/assets/${p.assetId}`,{method:`PUT`,headers:{"Content-Type":`application/json`},body:JSON.stringify(H.value)})).ok&&(U.value=JSON.parse(JSON.stringify(H.value)),window.dispatchEvent(new CustomEvent(`cms-assets-updated`)))}catch{}finally{V.value=!1}},nt=async e=>{let t=`Permanently delete orphaned crop "${z.value?.variants?.find(t=>String(t.id)===String(e))?.filename||`variant`}"?`;if(await _(t,`Delete Crop`,`Delete`,`Cancel`))try{(await fetch(`/api/admin/assets/purge/${e}`,{method:`DELETE`})).ok&&(z.value?.variants&&(z.value.variants=z.value.variants.filter(t=>String(t.id)!==String(e))),window.dispatchEvent(new CustomEvent(`cms-assets-updated`)),await q())}catch{}},J=async()=>{let e=$.value;if(e.length===0)return;let t=`Are you sure you want to permanently delete all ${e.length} orphaned crops?`;if(await _(t,`Purge All Orphaned Crops`,`Purge All`,`Cancel`))try{for(let t of e)await fetch(`/api/admin/assets/purge/${t.id}`,{method:`DELETE`});window.dispatchEvent(new CustomEvent(`cms-assets-updated`)),await q()}catch(e){console.error(`Failed to purge crops`,e)}},rt=e=>{m.value={type:`node`},v(String(e)),window.dispatchEvent(new CustomEvent(`cms-switch-sidebar-tab`,{detail:`vault`}))},Y=()=>{sessionStorage.setItem(`cms-vault-asset-filter`,p.assetId),window.dispatchEvent(new CustomEvent(`cms-filter-vault-by-asset`,{detail:p.assetId})),window.dispatchEvent(new CustomEvent(`cms-switch-sidebar-tab`,{detail:`vault`}))},X=f(()=>z.value&&(z.value.mimeType?.startsWith(`image/`)||/\.(jpg|jpeg|png|webp|gif|svg)$/i.test(z.value.filename))),Z=e=>{if(!e)return`0 B`;let t=1024,n=[`B`,`KB`,`MB`,`GB`],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/t**r).toFixed(1))+` `+n[r]},it=(e,t)=>{if(!t||t===`Original`||t===`Unknown Crop`)return t||`Original Image`;try{let n=g.value[e];if(!n)return t;let r=null,i=e=>{if(!(!e||r))for(let n of Object.values(e))n.crop&&t===`standard`&&n.crop.label&&(r=n.crop.label),n.crops&&n.crops[t]&&n.crops[t].label&&(r=n.crops[t].label)};return i(n.fields),n.tabs&&Object.values(n.tabs).forEach(e=>i(e.fields)),r||t}catch{return t}},Q=f(()=>{if(!z.value||!z.value.connectedNodes)return[];let e=new Map;for(let t of z.value.connectedNodes){let n=String(t.id),r=t.contentType||t.nodeType,i=t.fieldKey?.split(`.`)[0]||`Content Area`,a=t.fieldKey?.match(/^blocks\[(\d+)\]/);a&&(i=`Block ${parseInt(a[1],10)+1}`);let o=String(t.assetId)!==String(z.value.id),s=null;if(o){let e=z.value.variants?.find(e=>String(e.id)===String(t.assetId));if(e){let n=`Unknown Crop`,i=t.fieldKey?.match(/\.variants\.([^.]+)/);if(i)n=i[1];else{let t=e.filename?.match(/^(.+?)_ast_/);t&&(n=t[1])}s={id:e.id,url:e.url,label:it(r,n)}}}else s={id:z.value.id,url:z.value.url,label:`Original Image`};if(!e.has(n))e.set(n,{id:t.id,title:t.title,nodeType:r,fieldKeys:new Set([i]),usedAssets:s?[s]:[]});else{let t=e.get(n);t.fieldKeys.add(i),s&&!t.usedAssets.some(e=>e.id===s.id)&&t.usedAssets.push(s)}}return Array.from(e.values()).map(e=>({...e,fieldKey:Array.from(e.fieldKeys).join(`, `)}))}),$=f(()=>{if(!z.value||!z.value.variants)return[];let e=new Set(z.value.connectedNodes?.map(e=>String(e.assetId))||[]);return z.value.variants.filter(t=>!e.has(String(t.id)))}),at=e=>{let t=e?.match(/^(.+?)_ast_/);return t?t[1]:`Unknown Crop`};return a(()=>q()),(n,a)=>(i(),d(`div`,he,[u(`header`,k,[u(`div`,A,[u(`div`,j,[u(`div`,M,[u(`span`,N,[z.value?(i(),d(`span`,P,t(z.value.filename),1)):(i(),d(`span`,F,`Loading Asset...`))])]),u(`div`,I,[z.value?(i(),d(`span`,L,t(Z(z.value.sizeBytes))+` • `+t(z.value.mimeType),1)):S(``,!0)])]),u(`div`,R,[z.value?(i(),d(`div`,{key:0,class:`context-wrapper`,ref_key:`contextTriggerRef`,ref:G},[x(E,{variant:`secondary`,title:`More Options`,onClick:Xe,disabled:V.value,class:`transparent-btn icon-only-btn`},{default:c(()=>[x(o(se),{size:16})]),_:1},8,[`disabled`]),x(ae,{show:W.value,items:Ze.value,"anchor-rect":K.value,onSelect:Qe,onClose:a[0]||=e=>W.value=!1},null,8,[`show`,`items`,`anchor-rect`])],512)):S(``,!0),x(E,{variant:`primary`,class:`save-btn`,disabled:V.value||!et.value,onClick:tt},{default:c(()=>[x(o(pe),{size:14,class:`save-icon`}),u(`span`,ge,t(V.value?`Saving...`:`Save Metadata`),1)]),_:1},8,[`disabled`])])])]),u(`div`,_e,[B.value?(i(),d(`div`,ve,`Loading asset details...`)):z.value?(i(),d(`div`,ye,[u(`div`,be,[u(`div`,{class:ee([`preview-container`,{"is-doc":!X.value}])},[X.value?(i(),b(w,{key:0,url:z.value.url,alt:z.value.alt||z.value.filename,width:1200,quality:85,class:`main-preview-wrapper`},null,8,[`url`,`alt`])):(i(),d(`div`,xe,[x(o(ue),{size:64}),a[5]||=u(`span`,null,`Preview not available for this file type`,-1)]))],2),u(`div`,Se,[u(`span`,null,`Original Upload: `+t(new Date(z.value.createdAt).toLocaleString()),1),u(`a`,{href:z.value.url,target:`_blank`,class:`ext-link`},[a[6]||=e(`Open original file `,-1),x(o(C),{size:12})],8,Ce)])]),u(`div`,we,[u(`div`,Te,[u(`h3`,null,[x(o(le),{size:14,class:`inline-icon`}),a[7]||=e(` Metadata `,-1)])]),u(`div`,Ee,[u(`div`,De,[a[8]||=u(`label`,null,`Filename`,-1),r(u(`input`,{"onUpdate:modelValue":a[1]||=e=>H.value.filename=e,type:`text`,class:`cms-input`},null,512),[[y,H.value.filename]]),a[9]||=u(`span`,{class:`help-text`},`Changing this does not break the permanent CDN link.`,-1)]),u(`div`,Oe,[a[10]||=u(`label`,null,`Media Tags`,-1),x(me,{modelValue:H.value.tags,"onUpdate:modelValue":a[2]||=e=>H.value.tags=e,fieldKey:`media-tag`,config:{taxonomy:`media-tag`,multiple:!0}},null,8,[`modelValue`]),a[11]||=u(`span`,{class:`help-text`},`Used to organize and filter assets in the media library.`,-1)]),u(`div`,ke,[a[12]||=u(`label`,null,`Title (Internal/SEO)`,-1),r(u(`input`,{"onUpdate:modelValue":a[3]||=e=>H.value.title=e,type:`text`,class:`cms-input`},null,512),[[y,H.value.title]])]),u(`div`,Ae,[a[13]||=u(`label`,null,`Alt Text (Accessibility)`,-1),r(u(`textarea`,{"onUpdate:modelValue":a[4]||=e=>H.value.alt=e,class:`cms-input cms-textarea`},null,512),[[y,H.value.alt]])])])]),u(`div`,je,[u(`div`,Me,[u(`div`,Ne,[u(`h3`,null,[x(o(de),{size:16,class:`inline-icon`}),a[14]||=e(` Node Usage `,-1)]),Q.value.length>0?(i(),d(`button`,{key:0,class:`action-btn outline`,onClick:Y,title:`Show these nodes in the left Vault pane`},[x(o(fe),{size:13}),a[15]||=e(` Vault Filter `,-1)])):S(``,!0)]),Q.value.length===0?(i(),d(`div`,Pe,[...a[16]||=[u(`span`,{class:`status-dot warning`},null,-1),u(`span`,null,`Asset is not currently used on any nodes.`,-1)]])):(i(),d(`div`,Fe,[(i(!0),d(h,null,s(Q.value,n=>(i(),b(D,{key:n.id,clickable:``,onClick:e=>rt(n.id)},{title:c(()=>[a[17]||=u(`span`,{class:`status-dot success`},null,-1),u(`span`,Ie,t(n.title||`Untitled`),1),x(O,{variant:`type`},{default:c(()=>[e(t(n.nodeType||`page`),1)]),_:2},1024)]),meta:c(()=>[u(`div`,Le,[u(`span`,Re,`Used in field: `+t(n.fieldKey),1),X.value?(i(),d(`div`,ze,[(i(!0),d(h,null,s(n.usedAssets,e=>(i(),d(`div`,{key:e.id,class:`crop-item`},[x(w,{url:e.url,alt:e.label,width:200,quality:75,class:`crop-img-fixed-height`},null,8,[`url`,`alt`]),u(`span`,Be,t(e.label),1)]))),128))])):S(``,!0)])]),_:2},1032,[`onClick`]))),128))]))]),$.value.length>0?(i(),d(`div`,Ve,[u(`div`,He,[u(`h3`,null,[x(o(oe),{size:16,class:`inline-icon`}),e(` Orphaned Crops (`+t($.value.length)+`) `,1)]),u(`button`,{class:`action-btn outline text-danger`,onClick:J},[x(o(T),{size:13}),a[18]||=e(` Purge All `,-1)])]),a[21]||=u(`p`,{class:`gallery-desc`},`These crops were generated previously but are no longer attached to any nodes. You can safely delete them to save storage space.`,-1),u(`div`,Ue,[(i(!0),d(h,null,s($.value,n=>(i(),b(D,{key:n.id},{title:c(()=>[a[19]||=u(`span`,{class:`node-title`},`Orphaned Crop`,-1),x(O,{variant:`type`},{default:c(()=>[e(t(Z(n.sizeBytes)),1)]),_:2},1024)]),meta:c(()=>[u(`div`,We,[u(`span`,Ge,`Generated: `+t(new Date(n.createdAt).toLocaleDateString()),1),X.value?(i(),d(`div`,Ke,[u(`div`,qe,[x(w,{url:n.url,alt:n.filename,width:200,quality:75,class:`crop-img-fixed-height`},null,8,[`url`,`alt`]),u(`span`,Je,t(at(n.filename)),1)])])):S(``,!0)])]),actions:c(()=>[u(`button`,{class:`action-btn outline text-danger`,style:{border:`none`},onClick:e=>nt(n.id)},[x(o(T),{size:13}),a[20]||=e(` Purge `,-1)],8,Ye)]),_:2},1024))),128))])])):S(``,!0)])])):S(``,!0)])]))}}),[[`__scopeId`,`data-v-ee6004e3`]]);export{z as default};
@@ -1 +0,0 @@
1
- import{E as e,I as t,_ as n,b as r,i,k as a,ot as o,p as s,t as c,y as l,yt as u,z as d}from"./_plugin-vue_export-helper-BdT0OEbg.js";a(),i(),o();var f={class:`row-main`},p={key:0,class:`row-title-group`},m={key:1,class:`row-meta-group`},h=c(e({__name:`CmsDataRow`,props:{isSelected:{type:Boolean},clickable:{type:Boolean}},setup(e){return(i,a)=>(t(),r(`div`,{class:u([`cms-data-row`,{"is-selected":e.isSelected,"is-clickable":e.clickable}]),onClick:a[2]||=e=>i.$emit(`click`)},[i.$slots.prefix?(t(),r(`div`,{key:0,class:`row-prefix`,onClick:a[0]||=s(()=>{},[`stop`])},[d(i.$slots,`prefix`,{},void 0,!0)])):l(``,!0),n(`div`,f,[i.$slots.title?(t(),r(`div`,p,[d(i.$slots,`title`,{},void 0,!0)])):l(``,!0),i.$slots.meta?(t(),r(`div`,m,[d(i.$slots,`meta`,{},void 0,!0)])):l(``,!0)]),i.$slots.actions?(t(),r(`div`,{key:1,class:`row-actions`,onClick:a[1]||=s(()=>{},[`stop`])},[d(i.$slots,`actions`,{},void 0,!0)])):l(``,!0)],2))}}),[[`__scopeId`,`data-v-dba1b464`]]);a(),o();var g=c(e({__name:`CmsBadge`,props:{variant:{}},setup(e){return(n,i)=>(t(),r(`span`,{class:u([`cms-badge`,[`variant-${e.variant||`default`}`]])},[d(n.$slots,`default`,{},void 0,!0)],2))}}),[[`__scopeId`,`data-v-a1e8e7f0`]]);export{h as n,g as t};
@@ -1 +0,0 @@
1
- import{E as e,I as t,b as n,k as r,ot as i,t as a,yt as o,z as s}from"./_plugin-vue_export-helper-BdT0OEbg.js";r(),i();var c=[`disabled`,`type`],l=a(e({__name:`CmsButton`,props:{variant:{},size:{},disabled:{type:Boolean},type:{}},setup(e){return(r,i)=>(t(),n(`button`,{class:o([`cms-btn`,`btn-${e.variant||`primary`}`,e.size===`sm`?`btn-sm`:`btn-md`]),disabled:e.disabled,type:e.type||`button`},[s(r.$slots,`default`,{},void 0,!0)],10,c))}}),[[`__scopeId`,`data-v-071f7ec6`]]);export{l as t};
@@ -1 +0,0 @@
1
- import{C as e,Ct as t,E as n,I as r,P as i,Q as a,R as o,_ as s,b as c,g as l,i as u,k as d,m as f,ot as p,p as m,q as h,t as g,w as _,yt as v}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{s as y}from"./useNodes-GLoFdA2T.js";import{t as b}from"./loader-circle-CwP4GuFX.js";d(),h(),p(),u();var x={key:0,class:`loading-state`},S={key:1,class:`empty-state`},C={key:2,class:`taxonomy-pills`},w=[`disabled`,`onClick`],T=[`disabled`,`value`],E={value:``,disabled:``},D=[`value`],O=g(n({__name:`CmsFieldTaxonomy`,props:{modelValue:{},fieldKey:{},config:{},disabled:{type:Boolean},invalid:{type:Boolean}},emits:[`update:modelValue`],setup(n,{emit:u}){let d=n,p=u,{termsMap:h,fetchTerms:g,isLoading:O}=y(),k=l(()=>d.config.taxonomy||d.config.taxonomyKey||d.fieldKey),A=l(()=>{let e=k.value;return!e||!h.value||!h.value[e]?[]:h.value[e]}),j=l(()=>d.modelValue?(Array.isArray(d.modelValue)?d.modelValue:[d.modelValue]).map(e=>{let t=``;return t=typeof e==`string`?e:typeof e==`object`&&e&&e.id?String(e.id):String(e),t.startsWith(`trm_`)&&(t=t.replace(`trm_`,``)),parseInt(t,10)}).filter(e=>!isNaN(e)):[]),M=l(()=>d.config.multiple===!0);i(async()=>{let e=k.value;e&&(!h.value||!h.value[e])&&await g(e)});let N=e=>{if(!d.disabled){if(M.value){let t=[...j.value],n=t.indexOf(e);n>=0?t.splice(n,1):t.push(e),p(`update:modelValue`,t.map(e=>`trm_${e}`))}else p(`update:modelValue`,`trm_${e}`)}},P=e=>e.label||e.title||e.name||`Term #${e.id}`;return(i,l)=>(r(),c(`div`,{class:v([`cms-field-taxonomy`,{"is-invalid":n.invalid,"is-disabled":n.disabled}])},[a(O)&&A.value.length===0?(r(),c(`div`,x,[_(a(b),{size:14,class:`spinner`}),e(` Loading `+t(n.config.taxonomy||n.fieldKey)+`... `,1)])):A.value.length===0?(r(),c(`div`,S,` No terms found for `+t(n.config.taxonomy||n.fieldKey)+`. `,1)):M.value?(r(),c(`div`,C,[(r(!0),c(f,null,o(A.value,e=>(r(),c(`button`,{key:e.id,type:`button`,class:v([`tax-pill`,{"is-active":j.value.includes(e.id)}]),disabled:n.disabled,onClick:m(t=>N(e.id),[`prevent`])},t(P(e)),11,w))),128))])):(r(),c(`select`,{key:3,class:`taxonomy-select`,disabled:n.disabled,value:j.value.length>0?j.value[0]:``,onChange:l[0]||=e=>N(parseInt(e.target.value,10))},[s(`option`,E,`Select `+t(n.config.label||n.config.taxonomy||n.fieldKey)+`...`,1),(r(!0),c(f,null,o(A.value,e=>(r(),c(`option`,{key:e.id,value:e.id},t(P(e)),9,D))),128))],40,T))],2))}}),[[`__scopeId`,`data-v-1a55cb97`]]);export{O as t};
@@ -1 +0,0 @@
1
- import{C as e,E as t,I as n,Q as r,_ as i,b as a,k as o,q as s,t as c,w as l}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{a as u,i as d}from"./useNodes-GLoFdA2T.js";import{n as f,r as p,t as m}from"./plus-DCPXsir3.js";import{t as h}from"./database-mgNVRFlp.js";import{n as g,t as _}from"./globe-Clq_OlnU.js";import{t as v}from"./layers-CH2VvrZT.js";o(),s();var y={class:`help-canvas`},b={class:`help-container`},x={class:`steps-grid`},S={class:`step-card`},C={class:`card-header`},w={class:`card-icon channel-icon`},T={class:`step-card`},E={class:`card-header`},D={class:`card-icon tree-icon`},O={class:`step-card`},k={class:`card-header`},A={class:`card-icon vault-icon`},j={class:`architecture-guide`},M={class:`guide-header`},N={class:`guide-columns`},P={class:`guide-col-arrow`},F={class:`guide-col-arrow`},I={class:`guide-col-arrow`},L=c(t({__name:`CmsHelp`,setup(t){let{handleAddNewChannel:o}=p(),{handleAddNewTree:s}=u(),{handleAddNewNode:c}=d();return(t,u)=>(n(),a(`main`,y,[i(`div`,b,[u[17]||=i(`header`,{class:`help-header`},[i(`h1`,null,`KAMA`),i(`p`,null,`Build modular content in the Vault, organize it into Navigation Trees, and expose it to your channels via API.`)],-1),i(`div`,x,[i(`div`,S,[i(`div`,C,[i(`div`,w,[l(r(_),{size:20})]),u[3]||=i(`div`,{class:`step-badge`},`Step 1`,-1)]),u[5]||=i(`div`,{class:`card-content`},[i(`h3`,null,`Channels`),i(`p`,null,`Delivery targets that consume your headless API.`)],-1),i(`button`,{class:`card-action-btn`,onClick:u[0]||=(...e)=>r(o)&&r(o)(...e)},[l(r(m),{size:16}),u[4]||=e(` Create Channel `,-1)])]),i(`div`,T,[i(`div`,E,[i(`div`,D,[l(r(g),{size:20})]),u[6]||=i(`div`,{class:`step-badge`},`Step 2`,-1)]),u[8]||=i(`div`,{class:`card-content`},[i(`h3`,null,`Trees`),i(`p`,null,`Decoupled structural hierarchies and navigation menus.`)],-1),i(`button`,{class:`card-action-btn`,onClick:u[1]||=(...e)=>r(s)&&r(s)(...e)},[l(r(m),{size:16}),u[7]||=e(` Create Tree `,-1)])]),i(`div`,O,[i(`div`,k,[i(`div`,A,[l(r(h),{size:20})]),u[9]||=i(`div`,{class:`step-badge`},`Step 3`,-1)]),u[11]||=i(`div`,{class:`card-content`},[i(`h3`,null,`Vault`),i(`p`,null,`Flat, headless content store for reusable content items.`)],-1),i(`button`,{class:`card-action-btn`,onClick:u[2]||=e=>r(c)()},[l(r(m),{size:16}),u[10]||=e(` Create Content `,-1)])])]),i(`section`,j,[i(`div`,M,[l(r(v),{size:18,class:`guide-icon`}),u[12]||=i(`h4`,null,`Architecture Flow`,-1)]),i(`div`,N,[u[13]||=i(`div`,{class:`guide-col`},[i(`strong`,null,`1. Content Vault`),i(`p`,null,`Raw content entities existing independently of routing.`)],-1),i(`div`,P,[l(r(f),{size:16})]),u[14]||=i(`div`,{class:`guide-col`},[i(`strong`,null,`2. Navigation Trees`),i(`p`,null,`Decoupled structures mapping content items to URL hierarchies.`)],-1),i(`div`,F,[l(r(f),{size:16})]),u[15]||=i(`div`,{class:`guide-col`},[i(`strong`,null,`3. Channels`),i(`p`,null,`Delivery targets binding trees and languages to specific contexts.`)],-1),i(`div`,I,[l(r(f),{size:16})]),u[16]||=i(`div`,{class:`guide-col`},[i(`strong`,null,`4. Headless API`),i(`p`,null,`Endpoints serving structured JSON to your frontends.`)],-1)])])])]))}}),[[`__scopeId`,`data-v-c739c397`]]);export{L as default};
@@ -1 +0,0 @@
1
- import{E as e,H as t,I as n,Q as r,X as i,b as a,g as o,k as s,ot as c,q as l,t as u,w as d,y as f,yt as p}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{t as m}from"./createLucideIcon-BIiMnJpN.js";import{t as h}from"./loader-circle-CwP4GuFX.js";var g=m(`crop`,[[`path`,{d:`M6 2v14a2 2 0 0 0 2 2h14`,key:`ron5a4`}],[`path`,{d:`M18 22V8a2 2 0 0 0-2-2H2`,key:`7s9ehn`}]]),_=m(`ellipsis-vertical`,[[`circle`,{cx:`12`,cy:`12`,r:`1`,key:`41hilf`}],[`circle`,{cx:`12`,cy:`5`,r:`1`,key:`gxeob9`}],[`circle`,{cx:`12`,cy:`19`,r:`1`,key:`lyex9k`}]]),v=m(`info`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`M12 16v-4`,key:`1dtifu`}],[`path`,{d:`M12 8h.01`,key:`e9boi3`}]]),y=m(`link`,[[`path`,{d:`M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71`,key:`1cjeqo`}],[`path`,{d:`M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71`,key:`19qd67`}]]);function b(e,t){if(!e)return``;if(!e.includes(`/media/`))return e;try{let n=new URL(e,window.location.origin);return n.pathname.toLowerCase().endsWith(`.svg`)?n.pathname+n.search:(t.w&&n.searchParams.set(`w`,String(t.w)),t.h&&n.searchParams.set(`h`,String(t.h)),n.searchParams.set(`q`,String(t.q||75)),n.searchParams.set(`f`,String(t.f||`auto`)),n.pathname+n.search)}catch{return e}}s(),c(),l();var x={class:`cms-image-preview`},S=[`src`,`alt`],C={key:1,class:`loading-overlay`},w=u(e({__name:`CmsImagePreview`,props:{url:{},alt:{default:`Image preview`},width:{default:800},quality:{default:85},isProcessing:{type:Boolean,default:!1}},setup(e){let s=e,c=i(!1),l=i(null),u=o(()=>{if(!s.url)return!1;let e=s.url.toLowerCase();return e.endsWith(`.svg`)||e.includes(`image/svg+xml`)||e.includes(`.svg?`)});t(()=>s.url,(e,t)=>{e&&e!==t&&(c.value=!0,l.value=null)});let m=()=>{c.value=!1},g=()=>{if(l.value!==s.url&&_.value!==s.url){l.value=s.url,c.value=!0;return}c.value=!1},_=o(()=>s.url?u.value||l.value===s.url?s.url:b(s.url,{w:s.width,q:s.quality}):``);return(t,i)=>(n(),a(`div`,x,[_.value?(n(),a(`img`,{key:0,src:_.value,alt:e.alt,class:p([`preview-img`,{"is-blurring":e.isProcessing||c.value,"is-svg":u.value}]),onLoad:m,onError:g},null,42,S)):f(``,!0),e.isProcessing||c.value?(n(),a(`div`,C,[d(r(h),{size:16,class:`spinner`})])):f(``,!0)]))}}),[[`__scopeId`,`data-v-2d18a75f`]]);export{g as a,_ as i,y as n,v as r,w as t};
@@ -1,3 +0,0 @@
1
- import{C as e,Ct as t,E as n,I as r,P as i,Q as a,R as o,W as s,X as c,_ as l,b as u,g as d,i as f,k as p,m,ot as h,p as g,q as _,t as v,v as y,w as b,y as x}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{c as S,i as ee}from"./useNodes-GLoFdA2T.js";import{n as te,r as C}from"./useCmsState-BblziYb-.js";import{t as w}from"./circle-check-CB39w7cZ.js";import{n as ne,t as T}from"./send-UE48lWD8.js";import{n as re,t as ie}from"./globe-Clq_OlnU.js";import{t as ae}from"./history-ZSqpsbjQ.js";import{t as E}from"./loader-circle-CwP4GuFX.js";import{t as D}from"./CmsButton-BbvewMhp.js";import{n as O,t as k}from"./CmsBadge-DB0WNyWx.js";p(),_(),h(),f();var oe={class:`publisher-canvas full-width`},se={class:`publisher-container full-width`},ce={class:`publisher-header`},le={class:`header-actions`},ue={key:0,class:`empty-publisher-state`},de={key:1,class:`empty-publisher-state`},fe={key:2,class:`channel-groups-list`},pe={class:`group-header`},A={class:`group-title`},j=[`checked`,`indeterminate`,`onChange`],M={class:`count-badge`},N={class:`nodes-table`},P=[`checked`,`onChange`],F={class:`node-title`},I={key:3,class:`history-section`},L={class:`history-header`},R={class:`history-card`},z={class:`node-title`},B={class:`history-time`},V=v(n({__name:`CmsPublisher`,setup(n){let f=te(),{loadNodeContent:p}=ee(),h=c(!1),_=c(new Set),v=c(null),V=c(!1),H=c([]),U=c([]),W=c(new Set),me=async()=>{if(f.hasLoadedStats.value){H.value=f.vaultStats.value?.pendingNodes||[],U.value=f.vaultStats.value?.recentActivity||[];return}h.value=!0;try{let e=await fetch(`/api/cms/stats`);if(e.ok){let t=await e.json();f.vaultStats.value=t,f.hasLoadedStats.value=!0,H.value=t.pendingNodes||[],U.value=t.recentActivity||[]}}catch{}finally{h.value=!1}},G=d(()=>{let e=new Map;if(H.value.forEach(t=>{let n=String(f.activeNode.value?.id)===String(t.id),r=S(t),i=n&&f.hasUnpublishedChanges.value||r.hasUnpublishedChanges;e.set(String(t.id),{...t,evalState:{...r,hasUnpublishedChanges:i}})}),f.activeNode.value?.id){let t=String(f.activeNode.value.id),n=S(f.activeNode.value),r=f.hasUnpublishedChanges.value||n.hasUnpublishedChanges;(n.isDraft||n.isUnpublishedDraft||r)&&(e.has(t)||e.set(t,{...f.activeNode.value,evalState:{...n,hasUnpublishedChanges:r}}))}return Array.from(e.values())}),he=d(()=>{let e=new Map,t=`Unassigned / Vault Only`;return e.set(t,{channelName:t,nodes:[]}),G.value.forEach(n=>{let r=n.channelNames||[];r.length===0?e.get(t).nodes.push(n):r.forEach(t=>{e.has(t)||e.set(t,{channelName:t,nodes:[]}),e.get(t).nodes.push(n)})}),Array.from(e.values()).filter(e=>e.nodes.length>0)}),K=e=>W.value.has(e),ge=e=>{let t=new Set(W.value);t.has(e)?t.delete(e):t.add(e),W.value=t},q=e=>e.filter(e=>W.value.has(e.id)).length,J=e=>e.length>0&&e.every(e=>W.value.has(e.id)),_e=e=>q(e)>0&&q(e)<e.length,Y=e=>{let t=new Set(W.value),n=J(e);e.forEach(e=>{n?t.delete(e.id):t.add(e.id)}),W.value=t},X=d(()=>W.value.size),Z=e=>{p({id:e.id,title:e.title,slug:e.slug,nodeType:e.contentType||e.nodeType,channelId:e.channelId||``,language:e.language||`en`,children:[]})},Q=e=>{U.value=[{id:e.id,title:e.title||`Untitled Document`,slug:e.slug,contentType:e.contentType||e.nodeType||`page`,updatedAt:new Date().toISOString()},...U.value.filter(t=>String(t.id)!==String(e.id))].slice(0,10)},ve=async e=>{_.value.add(e);try{let t=G.value.find(t=>String(t.id)===String(e));if((await C.publishNode(e)).ok){f.updateNodeInState(e,{status:`published`,hasUnpublishedChanges:!1}),H.value=H.value.filter(t=>String(t.id)!==String(e)),String(f.activeNode.value?.id)===String(e)&&(f.activeNode.value.status=`published`,f.activeNode.value.hasUnpublishedChanges=!1);let n=new Set(W.value);n.delete(e),W.value=n,t&&Q(t),f.invalidateStats(),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`cms-node-updated`))}}finally{_.value.delete(e)}},$=async e=>{if(e.length===0)return;let t=e.map(e=>e.id);t.forEach(e=>_.value.add(e));try{let e=await C.publishNodesBatch(t);if(e.ok){let t=(await e.json()).publishedIds||[];for(let e of t)f.updateNodeInState(e,{status:`published`,hasUnpublishedChanges:!1}),String(f.activeNode.value?.id)===String(e)&&(f.activeNode.value.status=`published`,f.activeNode.value.hasUnpublishedChanges=!1);G.value.filter(e=>t.includes(e.id)).forEach(e=>Q(e)),H.value=H.value.filter(e=>!t.includes(e.id));let n=new Set(W.value);t.forEach(e=>n.delete(e)),W.value=n,f.invalidateStats(),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`cms-node-updated`))}}finally{t.forEach(e=>_.value.delete(e))}},ye=async(e,t)=>{v.value=e;let n=q(t)>0?t.filter(e=>W.value.has(e.id)):t;await $(n),v.value=null},be=async()=>{V.value=!0;let e=X.value>0?G.value.filter(e=>W.value.has(e.id)):G.value;await $(e),V.value=!1},xe=e=>{if(!e)return``;try{return new Date(e).toLocaleString([],{dateStyle:`medium`,timeStyle:`short`})}catch{return e}};return i(()=>me()),(n,i)=>(r(),u(`main`,oe,[l(`div`,se,[l(`header`,ce,[i[2]||=l(`div`,{class:`header-title-group`},[l(`h1`,null,`Publishing Center`),l(`p`,null,`Review and release pending drafts or bulk-publish updates across your distribution channels.`)],-1),l(`div`,le,[G.value.length>0?(r(),y(D,{key:0,variant:`primary`,class:`publish-all-btn`,disabled:V.value||_.value.size>0,onClick:be},{default:s(()=>[V.value?(r(),y(a(E),{key:0,size:16,class:`spin`})):(r(),y(a(T),{key:1,size:16})),l(`span`,null,t(X.value>0?`Publish Selected (${X.value})`:`Publish All
2
- (${G.value.length})`),1)]),_:1},8,[`disabled`])):x(``,!0)])]),h.value&&G.value.length===0?(r(),u(`div`,ue,[b(a(E),{size:28,class:`spin empty-icon`}),i[3]||=l(`p`,null,`Gathering pending content updates...`,-1)])):G.value.length===0?(r(),u(`div`,de,[b(a(w),{size:36,class:`success-icon`}),i[4]||=l(`h3`,null,`All Content Published!`,-1),i[5]||=l(`p`,null,`No draft changes or pending revisions found. Your delivery channels are fully up to date.`,-1)])):(r(),u(`div`,fe,[(r(!0),u(m,null,o(he.value,n=>(r(),u(`section`,{key:n.channelName,class:`channel-group-card`},[l(`div`,pe,[l(`div`,A,[l(`label`,{class:`checkbox-container`,onClick:i[0]||=g(()=>{},[`stop`])},[l(`input`,{type:`checkbox`,checked:J(n.nodes),indeterminate:_e(n.nodes),onChange:e=>Y(n.nodes)},null,40,j),i[6]||=l(`span`,{class:`checkmark`},null,-1)]),b(a(ie),{size:18,class:`channel-icon`}),l(`h2`,null,t(n.channelName),1),l(`span`,M,t(n.nodes.length)+` Pending`,1)]),b(D,{variant:`secondary`,size:`sm`,disabled:v.value===n.channelName||V.value,onClick:e=>ye(n.channelName,n.nodes)},{default:s(()=>[v.value===n.channelName?(r(),y(a(E),{key:0,size:14,class:`spin`})):(r(),y(a(T),{key:1,size:14})),l(`span`,null,t(q(n.nodes)>0?`Publish Selected
3
- (${q(n.nodes)})`:`Publish Channel Items`),1)]),_:2},1032,[`disabled`,`onClick`])]),l(`div`,N,[(r(!0),u(m,null,o(n.nodes,n=>(r(),y(O,{key:n.id,"is-selected":K(n.id),clickable:``,onClick:e=>Z(n)},{prefix:s(()=>[l(`label`,{class:`checkbox-container`,onClick:i[1]||=g(()=>{},[`stop`])},[l(`input`,{type:`checkbox`,checked:K(n.id),onChange:e=>ge(n.id)},null,40,P),i[7]||=l(`span`,{class:`checkmark`},null,-1)])]),title:s(()=>[l(`span`,F,t(n.title||`Untitled Draft`),1),b(k,{variant:`type`},{default:s(()=>[e(t(n.contentType||n.nodeType||`page`),1)]),_:2},1024)]),meta:s(()=>[b(k,{variant:`slug`},{default:s(()=>[e(`/`+t(n.slug),1)]),_:2},1024),(r(!0),u(m,null,o(n.treeNames,n=>(r(),y(k,{variant:`tree`,key:n},{default:s(()=>[b(a(re),{size:11}),e(` `+t(n),1)]),_:2},1024))),128))]),actions:s(()=>[b(D,{variant:`secondary`,size:`sm`,class:`icon-only-btn`,title:`Publish Item`,disabled:_.value.has(n.id)||V.value,onClick:g(e=>ve(n.id),[`stop`])},{default:s(()=>[_.value.has(n.id)?(r(),y(a(E),{key:0,size:14,class:`spin`})):(r(),y(a(T),{key:1,size:14}))]),_:2},1032,[`disabled`,`onClick`])]),_:2},1032,[`is-selected`,`onClick`]))),128))])]))),128))])),U.value.length>0?(r(),u(`section`,I,[l(`div`,L,[b(a(ae),{size:18,class:`history-icon`}),i[8]||=l(`h2`,null,`Recently Published`,-1)]),l(`div`,R,[(r(!0),u(m,null,o(U.value,n=>(r(),y(O,{key:n.id,clickable:``,onClick:e=>Z(n)},{prefix:s(()=>[b(a(w),{size:16,class:`published-check`})]),title:s(()=>[l(`span`,z,t(n.title||`Untitled Document`),1),b(k,{variant:`type`},{default:s(()=>[e(t(n.contentType||n.nodeType||`page`),1)]),_:2},1024)]),meta:s(()=>[b(k,{variant:`slug`},{default:s(()=>[e(`/`+t(n.slug),1)]),_:2},1024)]),actions:s(()=>[l(`div`,B,[b(a(ne),{size:12}),l(`span`,null,t(xe(n.updatedAt)),1)])]),_:2},1032,[`onClick`]))),128))])])):x(``,!0)])]))}}),[[`__scopeId`,`data-v-e0e64ba6`]]);export{V as default};
@@ -1 +0,0 @@
1
- import{C as e,Ct as t,E as ee,G as n,I as r,P as i,Q as a,W as o,X as s,_ as c,b as l,i as u,k as d,ot as f,p,q as m,t as h,u as g,w as _,y as te}from"./_plugin-vue_export-helper-BdT0OEbg.js";import{i as v,n as y,r as ne,t as b}from"./user-Bo_HcyTz.js";import{t as re}from"./save-BUYaWIjt.js";import{t as x}from"./CmsButton-BbvewMhp.js";d(),f(),m(),u();var ie={class:`user-center-canvas`},S={class:`user-center-container`},ae={key:0,class:`account-message error-message`,role:`alert`},C={key:1,class:`account-message success-message`,role:`status`},w={key:2,class:`account-message`},T={key:3,class:`settings-grid`},E={class:`settings-column`},D={class:`settings-card`},O={class:`card-header`},k={class:`header-title`},A={class:`form-group`},j={class:`form-group`},M=[`value`],N={class:`form-group`},P=[`value`],F={class:`form-actions`},I={class:`settings-card`},L={class:`card-header`},oe={class:`header-title`},R={class:`card-body`},z={class:`settings-column`},B={class:`settings-card`},V={class:`card-header`},H={class:`header-title`},U={class:`form-group`},W={class:`form-group`},G={class:`form-group`},K={class:`form-actions`},q=h(ee({__name:`CmsUserCenter`,setup(ee){let u=s(null),d=s(``),f=s(``),m=s(``),h=s(``),q=s(!0),J=s(!1),Y=s(!1),X=s(!1),Z=s(``),Q=s(``),$=async e=>{let t=await e.json().catch(()=>({}));if(!e.ok)throw Error(t.error||`Request failed (${e.status}).`);return t},se=async()=>{q.value=!0,Z.value=``;try{let e=await $(await fetch(`/api/auth/me`,{cache:`no-store`}));u.value=e.user,d.value=e.user.name}catch(e){Z.value=e instanceof Error?e.message:`Could not load your account.`}finally{q.value=!1}},ce=async()=>{if(!J.value){J.value=!0,Z.value=``,Q.value=``;try{let e=await $(await fetch(`/api/auth/profile`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({name:d.value})}));u.value=e.user,Q.value=`Profile updated.`,window.dispatchEvent(new CustomEvent(`cms-user-updated`,{detail:e.user}))}catch(e){Z.value=e instanceof Error?e.message:`Could not update your profile.`}finally{J.value=!1}}},le=async()=>{if(!Y.value){if(Z.value=``,Q.value=``,m.value!==h.value){Z.value=`The new passwords do not match.`;return}Y.value=!0;try{await $(await fetch(`/api/auth/password`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({currentPassword:f.value,newPassword:m.value})})),f.value=``,m.value=``,h.value=``,Q.value=`Password changed. Other active sessions have been signed out.`}catch(e){Z.value=e instanceof Error?e.message:`Could not change your password.`}finally{Y.value=!1}}},ue=async()=>{if(!X.value){X.value=!0,Z.value=``;try{await $(await fetch(`/api/auth/logout-all`,{method:`POST`})),window.dispatchEvent(new Event(`cms-auth-logout`))}catch(e){Z.value=e instanceof Error?e.message:`Could not sign out.`}finally{X.value=!1}}};return i(se),(ee,i)=>(r(),l(`main`,ie,[c(`div`,S,[i[15]||=c(`header`,{class:`view-header`},[c(`h1`,null,`Account`),c(`p`,null,`Manage your CMS profile and sign-in security.`)],-1),Z.value?(r(),l(`p`,ae,t(Z.value),1)):Q.value?(r(),l(`p`,C,t(Q.value),1)):te(``,!0),q.value?(r(),l(`p`,w,`Loading account...`)):(r(),l(`div`,T,[c(`div`,E,[c(`section`,D,[c(`header`,O,[c(`div`,k,[_(a(b),{size:18,class:`section-icon`}),i[4]||=c(`h2`,null,`Profile`,-1)])]),c(`form`,{class:`card-body`,onSubmit:p(ce,[`prevent`])},[c(`div`,A,[i[5]||=c(`label`,{for:`account-name`},`Display name`,-1),n(c(`input`,{id:`account-name`,"onUpdate:modelValue":i[0]||=e=>d.value=e,maxlength:`100`,required:``},null,512),[[g,d.value,void 0,{trim:!0}]])]),c(`div`,j,[i[6]||=c(`label`,{for:`account-email`},`Sign-in email`,-1),c(`input`,{id:`account-email`,value:u.value?.email,disabled:``},null,8,M)]),c(`div`,N,[i[7]||=c(`label`,{for:`account-role`},`Role`,-1),c(`input`,{id:`account-role`,value:u.value?.role,disabled:``},null,8,P)]),c(`div`,F,[_(x,{type:`submit`,variant:`primary`,disabled:J.value||!d.value},{default:o(()=>[_(a(re),{size:14}),c(`span`,null,t(J.value?`Saving...`:`Save profile`),1)]),_:1},8,[`disabled`])])],32)]),c(`section`,I,[c(`header`,L,[c(`div`,oe,[_(a(y),{size:18,class:`section-icon`}),i[8]||=c(`h2`,null,`Sessions`,-1)])]),c(`div`,R,[i[9]||=c(`p`,{class:`card-description`},`Signing out will revoke this session and all other active sessions.`,-1),_(x,{variant:`secondary`,disabled:X.value,onClick:ue},{default:o(()=>[_(a(ne),{size:14}),e(t(X.value?`Signing out...`:`Sign out everywhere`),1)]),_:1},8,[`disabled`])])])]),c(`div`,z,[c(`section`,B,[c(`header`,V,[c(`div`,H,[_(a(v),{size:18,class:`section-icon`}),i[10]||=c(`h2`,null,`Change password`,-1)])]),c(`form`,{class:`card-body`,onSubmit:p(le,[`prevent`])},[c(`div`,U,[i[11]||=c(`label`,{for:`current-password`},`Current password`,-1),n(c(`input`,{id:`current-password`,"onUpdate:modelValue":i[1]||=e=>f.value=e,type:`password`,autocomplete:`current-password`,required:``},null,512),[[g,f.value]])]),c(`div`,W,[i[12]||=c(`label`,{for:`new-password`},`New password`,-1),n(c(`input`,{id:`new-password`,"onUpdate:modelValue":i[2]||=e=>m.value=e,type:`password`,autocomplete:`new-password`,minlength:`12`,required:``},null,512),[[g,m.value]]),i[13]||=c(`small`,null,`Use at least 12 characters.`,-1)]),c(`div`,G,[i[14]||=c(`label`,{for:`confirm-password`},`Confirm new password`,-1),n(c(`input`,{id:`confirm-password`,"onUpdate:modelValue":i[3]||=e=>h.value=e,type:`password`,autocomplete:`new-password`,minlength:`12`,required:``},null,512),[[g,h.value]])]),c(`div`,K,[_(x,{type:`submit`,variant:`primary`,disabled:Y.value},{default:o(()=>[_(a(v),{size:14}),c(`span`,null,t(Y.value?`Changing...`:`Change password`),1)]),_:1},8,[`disabled`])])],32)])])]))])]))}}),[[`__scopeId`,`data-v-ff082993`]]);export{q as default};