magic-editor-x 1.5.1 → 2.0.0

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 (97) hide show
  1. package/CHANGELOG.md +268 -0
  2. package/LICENSE +1 -7
  3. package/README.md +317 -1078
  4. package/dist/admin/ConfigurationPage-B1uCIE3J.js +767 -0
  5. package/dist/admin/ConfigurationPage-DvAifELO.mjs +767 -0
  6. package/dist/admin/CustomBlocksPage-6-OQwpXQ.mjs +1741 -0
  7. package/dist/admin/CustomBlocksPage-6eWCOreU.js +1743 -0
  8. package/dist/admin/EditorField-DocyD2Q3.js +5506 -0
  9. package/dist/admin/EditorField-ThSoOCPm.mjs +5471 -0
  10. package/dist/admin/api-B-RsxJCs.js +34 -0
  11. package/dist/admin/api-C4XsDZxd.mjs +35 -0
  12. package/dist/admin/de-B8XFFhHh.js +95 -0
  13. package/dist/admin/de-BMxADn2Z.mjs +231 -0
  14. package/dist/admin/de-DBR893G4.js +13 -0
  15. package/dist/admin/de-DcDPRzV4.js +155 -0
  16. package/dist/admin/de-Dx7vUW0Z.js +231 -0
  17. package/dist/admin/de-RAxzvrwm.mjs +95 -0
  18. package/dist/admin/de-fBFh09Wl.mjs +13 -0
  19. package/dist/admin/de-n5V6c5RT.mjs +155 -0
  20. package/dist/admin/en-BQ5Pxe2o.mjs +231 -0
  21. package/dist/admin/en-BqNm3nMQ.mjs +155 -0
  22. package/dist/admin/en-BzfyifEU.mjs +95 -0
  23. package/dist/admin/en-D-DGftl0.js +155 -0
  24. package/dist/admin/en-D9Nfccux.mjs +13 -0
  25. package/dist/admin/en-DcWUTE2J.js +95 -0
  26. package/dist/admin/en-gueRT44P.js +13 -0
  27. package/dist/admin/en-sNn4z9lA.js +231 -0
  28. package/dist/admin/es-B0Zy8DVg.mjs +13 -0
  29. package/dist/admin/es-B6NYq0VH.mjs +231 -0
  30. package/dist/admin/es-BOtVc9qv.js +95 -0
  31. package/dist/admin/es-C2OJVYkV.mjs +95 -0
  32. package/dist/admin/es-DRGs7meF.js +13 -0
  33. package/dist/admin/es-DVsXnS0N.js +231 -0
  34. package/dist/admin/es-Di0pyQCh.js +155 -0
  35. package/dist/admin/es-SzeTV4q8.mjs +155 -0
  36. package/dist/admin/fr-B8rdLAIL.js +13 -0
  37. package/dist/admin/fr-Bpo5Uq1f.mjs +95 -0
  38. package/dist/admin/fr-D6F--jIB.js +155 -0
  39. package/dist/admin/fr-DfxKaOc_.js +95 -0
  40. package/dist/admin/fr-DhgPYHIH.mjs +155 -0
  41. package/dist/admin/fr-DmG3_Cn-.mjs +231 -0
  42. package/dist/admin/fr-Fwxcj4SM.js +231 -0
  43. package/dist/admin/fr-oiUb2bb_.mjs +13 -0
  44. package/dist/admin/index-CwfaB5-e.js +155 -0
  45. package/dist/admin/index-D1Q5Rlt6.mjs +156 -0
  46. package/dist/admin/index.js +3 -2
  47. package/dist/admin/index.mjs +1 -1
  48. package/dist/admin/pt-B3Jce6uT.mjs +13 -0
  49. package/dist/admin/pt-BPo0ex21.js +155 -0
  50. package/dist/admin/pt-BbdwHlWF.mjs +231 -0
  51. package/dist/admin/pt-BiWuSBcH.js +13 -0
  52. package/dist/admin/pt-BvSl1btT.mjs +155 -0
  53. package/dist/admin/pt-C6nr71Yw.js +231 -0
  54. package/dist/admin/pt-DqCXuI4S.mjs +95 -0
  55. package/dist/admin/pt-LCvjwk0y.js +95 -0
  56. package/dist/admin/sanitize-9UVcXFfc.js +552 -0
  57. package/dist/admin/sanitize-D4kfZ_ly.mjs +551 -0
  58. package/dist/admin/useT-B5M49wGH.js +130 -0
  59. package/dist/admin/useT-CjX6fL2m.mjs +131 -0
  60. package/dist/server/index.js +4531 -39542
  61. package/dist/server/index.mjs +4534 -39527
  62. package/package.json +111 -74
  63. package/strapi-admin.js +3 -0
  64. package/strapi-server.js +3 -0
  65. package/COPYRIGHT_NOTICE.txt +0 -20
  66. package/dist/_chunks/App-DImBvISP.js +0 -2146
  67. package/dist/_chunks/App-iNfbV7cz.mjs +0 -2143
  68. package/dist/_chunks/CustomBlocksPage-COPOZ2-_.mjs +0 -1517
  69. package/dist/_chunks/CustomBlocksPage-Cj-0TTUs.js +0 -1519
  70. package/dist/_chunks/LicensePage-CmvILX9m.js +0 -393
  71. package/dist/_chunks/LicensePage-gLRoo8WJ.mjs +0 -391
  72. package/dist/_chunks/LiveCollaborationPanel-BFybu8h0.js +0 -222
  73. package/dist/_chunks/LiveCollaborationPanel-CVgl4IyR.mjs +0 -220
  74. package/dist/_chunks/Settings-ButYcfrm.mjs +0 -438
  75. package/dist/_chunks/Settings-BzGqgrxD.js +0 -440
  76. package/dist/_chunks/de-C_0Mj-Zo.mjs +0 -296
  77. package/dist/_chunks/de-DVNVpAt9.js +0 -296
  78. package/dist/_chunks/en-B7AAf1ie.mjs +0 -296
  79. package/dist/_chunks/en-C2hv5GsA.js +0 -296
  80. package/dist/_chunks/es-BzJqcIST.js +0 -274
  81. package/dist/_chunks/es-zdP8sd-f.mjs +0 -274
  82. package/dist/_chunks/fr-CtAgOgH1.mjs +0 -274
  83. package/dist/_chunks/fr-D3GwqAAJ.js +0 -274
  84. package/dist/_chunks/getTranslation-BADoesEn.js +0 -57807
  85. package/dist/_chunks/getTranslation-D3h3Z3gU.mjs +0 -57791
  86. package/dist/_chunks/index-BXBnwuRw.js +0 -2158
  87. package/dist/_chunks/index-BvEdg518.mjs +0 -2159
  88. package/dist/_chunks/index-DDFAuQNT.js +0 -6955
  89. package/dist/_chunks/index-DEi6nwfM.mjs +0 -6933
  90. package/dist/_chunks/pt-BmUw6YMP.mjs +0 -274
  91. package/dist/_chunks/pt-CFo0nTbj.js +0 -274
  92. package/dist/_chunks/tools-BXzd0lx5.mjs +0 -2265
  93. package/dist/_chunks/tools-Q0uwDS9E.js +0 -2296
  94. package/dist/style.css +0 -1103
  95. package/pics/collab-magiceditorX.png +0 -0
  96. package/pics/editorX.png +0 -0
  97. package/pics/liveCollabwidget1.png +0 -0
@@ -0,0 +1,767 @@
1
+ import { jsx, jsxs } from "react/jsx-runtime";
2
+ import { Box, Flex, Typography, Switch, Grid, Field, SingleSelect, SingleSelectOption, TextInput, TextButton, NumberInput, Button, Badge, Alert } from "@strapi/design-system";
3
+ import { useForm, useFetchClient, useNotification, useRBAC, Page, Form, Blocker } from "@strapi/strapi/admin";
4
+ import { Check } from "@strapi/icons";
5
+ import { P as PERMISSIONS } from "./index-D1Q5Rlt6.mjs";
6
+ import { u as useT, S as SectionCard, P as PageShell, C as ConfirmAction } from "./useT-CjX6fL2m.mjs";
7
+ import { useEffect, useState, useRef, useCallback, useMemo } from "react";
8
+ import "styled-components";
9
+ import { A as API, r as readApiError } from "./api-C4XsDZxd.mjs";
10
+ import { useIntl } from "react-intl";
11
+ const DraftSync = ({ values }) => {
12
+ const setValues = useForm("MagicEditorXDraftSync", (state) => state.setValues);
13
+ useEffect(() => {
14
+ setValues(values);
15
+ }, [values, setValues]);
16
+ return null;
17
+ };
18
+ const PropertyList = ({ items }) => /* @__PURE__ */ jsx(Box, { tag: "dl", margin: 0, children: /* @__PURE__ */ jsx(Flex, { direction: "column", alignItems: "stretch", gap: 3, children: items.map((item) => /* @__PURE__ */ jsxs(
19
+ Flex,
20
+ {
21
+ gap: { initial: 1, medium: 4 },
22
+ direction: { initial: "column", medium: "row" },
23
+ alignItems: { initial: "flex-start", medium: "baseline" },
24
+ minWidth: 0,
25
+ children: [
26
+ /* @__PURE__ */ jsx(Box, { tag: "dt", minWidth: 0, flex: { initial: "0 0 auto", medium: "0 0 26rem" }, children: /* @__PURE__ */ jsx(Typography, { variant: "sigma", textColor: "neutral600", children: item.label }) }),
27
+ /* @__PURE__ */ jsxs(Box, { tag: "dd", margin: 0, minWidth: 0, flex: "1 1 auto", children: [
28
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", textColor: "neutral800", children: item.value }),
29
+ item.hint ? /* @__PURE__ */ jsx(Box, { paddingTop: 1, children: /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: item.hint }) }) : null
30
+ ] })
31
+ ]
32
+ },
33
+ item.key
34
+ )) }) });
35
+ const PROVIDERS = Object.freeze(["anthropic", "openai", "openai-compatible"]);
36
+ const MODEL_PATTERN = /^[A-Za-z0-9._:/@-]+$/;
37
+ const LIMITS = Object.freeze({
38
+ maxInputChars: Object.freeze({ min: 200, max: 5e4 }),
39
+ maxOutputTokens: Object.freeze({ min: 64, max: 16e3 })
40
+ });
41
+ const EDITABLE = ["enabled", "provider", "baseUrl", "model", "maxInputChars", "maxOutputTokens"];
42
+ const toDraft = (ai) => ({
43
+ enabled: Boolean(ai.enabled),
44
+ provider: PROVIDERS.includes(ai.provider) ? ai.provider : "anthropic",
45
+ baseUrl: ai.baseUrl || "",
46
+ model: ai.model || "",
47
+ maxInputChars: ai.maxInputChars ?? 8e3,
48
+ maxOutputTokens: ai.maxOutputTokens ?? 4096,
49
+ apiKeyMode: "keep",
50
+ apiKey: ""
51
+ });
52
+ const applyProvider = (draft, provider, defaultModels = {}) => {
53
+ const previousDefault = defaultModels[draft.provider] || "";
54
+ const model = !draft.model || draft.model === previousDefault ? defaultModels[provider] || "" : draft.model;
55
+ return { ...draft, provider, model };
56
+ };
57
+ const endpointChanged = (draft, saved) => draft.provider !== saved.provider || draft.baseUrl !== saved.baseUrl;
58
+ const validateDraft = (draft, { saved, ai, environment }) => {
59
+ const errors = {};
60
+ if (!PROVIDERS.includes(draft.provider)) errors.provider = "required";
61
+ const model = String(draft.model || "").trim();
62
+ if (!model) errors.model = "required";
63
+ else if (model.length > 120 || !MODEL_PATTERN.test(model)) errors.model = "modelPattern";
64
+ const baseUrl = String(draft.baseUrl || "").trim();
65
+ if (!baseUrl && draft.provider === "openai-compatible") errors.baseUrl = "required";
66
+ if (baseUrl) {
67
+ const url = (() => {
68
+ try {
69
+ return new URL(baseUrl);
70
+ } catch {
71
+ return null;
72
+ }
73
+ })();
74
+ if (!url || !["http:", "https:"].includes(url.protocol) || url.username || url.password || baseUrl.length > 500) {
75
+ errors.baseUrl = "url";
76
+ } else if (url.protocol !== "https:" && !(environment && environment.allowPrivateBaseUrl)) {
77
+ errors.baseUrl = "https";
78
+ }
79
+ }
80
+ for (const key of ["maxInputChars", "maxOutputTokens"]) {
81
+ const value = draft[key];
82
+ const { min, max } = LIMITS[key];
83
+ if (value === void 0 || value === null || value === "") errors[key] = "required";
84
+ else if (!Number.isInteger(value) || value < min || value > max) errors[key] = "range";
85
+ }
86
+ if (draft.apiKeyMode === "replace") {
87
+ const key = String(draft.apiKey || "").trim();
88
+ if (!key) errors.apiKey = "required";
89
+ else if (key.length > 500) errors.apiKey = "tooLong";
90
+ else if (ai && !ai.canStoreApiKey) errors.apiKey = "cannotStore";
91
+ } else if (draft.apiKeyMode === "keep" && saved && endpointChanged(draft, saved) && ai && ai.hasApiKey && !ai.apiKeyFromEnvironment) {
92
+ errors.apiKey = "reenter";
93
+ }
94
+ return errors;
95
+ };
96
+ const toPayload = (draft) => {
97
+ const ai = {
98
+ enabled: Boolean(draft.enabled),
99
+ provider: draft.provider,
100
+ baseUrl: String(draft.baseUrl || "").trim(),
101
+ model: String(draft.model || "").trim(),
102
+ maxInputChars: draft.maxInputChars,
103
+ maxOutputTokens: draft.maxOutputTokens
104
+ };
105
+ if (draft.apiKeyMode === "remove") ai.apiKey = "";
106
+ if (draft.apiKeyMode === "replace") ai.apiKey = String(draft.apiKey || "").trim();
107
+ return { ai };
108
+ };
109
+ const adjustedFields = (draft, stored) => EDITABLE.filter((key) => {
110
+ const sent = key === "baseUrl" || key === "model" ? String(draft[key] || "").trim() : draft[key];
111
+ return sent !== stored[key];
112
+ });
113
+ const mapServerErrors = (details) => {
114
+ const out = {};
115
+ const fieldErrors = details && typeof details === "object" ? details.fieldErrors || {} : {};
116
+ for (const [key, messages] of Object.entries(fieldErrors)) {
117
+ const message = Array.isArray(messages) ? messages[0] : String(messages || "");
118
+ const field = key.startsWith("ai.") ? key.slice(3) : null;
119
+ if (field && EDITABLE.concat(["apiKey"]).includes(field)) out[field] = message;
120
+ else out._form = message;
121
+ }
122
+ if (!Object.keys(out).length && details && Array.isArray(details.formErrors) && details.formErrors[0]) {
123
+ out._form = details.formErrors[0];
124
+ }
125
+ return out;
126
+ };
127
+ const sameDraft = (a, b) => EDITABLE.every((key) => a[key] === b[key]) && a.apiKeyMode === b.apiKeyMode && (a.apiKeyMode !== "replace" || a.apiKey === b.apiKey);
128
+ const useConfigurationForm = () => {
129
+ const { get, put, post } = useFetchClient();
130
+ const [status, setStatus] = useState("loading");
131
+ const [dto, setDto] = useState(null);
132
+ const [saved, setSaved] = useState(null);
133
+ const [draft, setDraft] = useState(null);
134
+ const [serverErrors, setServerErrors] = useState({});
135
+ const [showErrors, setShowErrors] = useState(false);
136
+ const [saving, setSaving] = useState(false);
137
+ const [testing, setTesting] = useState(false);
138
+ const mounted = useRef(true);
139
+ useEffect(() => {
140
+ mounted.current = true;
141
+ return () => {
142
+ mounted.current = false;
143
+ };
144
+ }, []);
145
+ const fetchSettings = useCallback(
146
+ () => get(API.settings).then(
147
+ ({ data }) => {
148
+ if (!mounted.current) return;
149
+ const next = toDraft(data.data.ai);
150
+ setDto(data.data);
151
+ setSaved(next);
152
+ setDraft(next);
153
+ setServerErrors({});
154
+ setShowErrors(false);
155
+ setStatus("ready");
156
+ },
157
+ () => {
158
+ if (mounted.current) setStatus("error");
159
+ }
160
+ ),
161
+ [get]
162
+ );
163
+ useEffect(() => {
164
+ fetchSettings();
165
+ }, [fetchSettings]);
166
+ const load = useCallback(() => {
167
+ setStatus("loading");
168
+ fetchSettings();
169
+ }, [fetchSettings]);
170
+ const errors = useMemo(() => {
171
+ if (!draft || !dto) return {};
172
+ return validateDraft(draft, { saved, ai: dto.ai, environment: dto.environment });
173
+ }, [draft, dto, saved]);
174
+ const setField = useCallback((key, value) => {
175
+ setDraft((current) => ({ ...current, [key]: value }));
176
+ setServerErrors((current) => {
177
+ if (!current[key] && !current._form) return current;
178
+ const next = { ...current };
179
+ delete next[key];
180
+ delete next._form;
181
+ return next;
182
+ });
183
+ }, []);
184
+ const replaceDraft = useCallback((next) => setDraft(next), []);
185
+ const dirty = Boolean(draft && saved && !sameDraft(draft, saved));
186
+ const hasErrors = Object.keys(errors).length > 0;
187
+ const save = useCallback(async () => {
188
+ setShowErrors(true);
189
+ if (hasErrors) return { ok: false, invalid: true };
190
+ setSaving(true);
191
+ try {
192
+ const { data } = await put(API.settings, toPayload(draft));
193
+ const stored = toDraft(data.data.ai);
194
+ const adjusted = adjustedFields(draft, stored);
195
+ setDto(data.data);
196
+ setSaved(stored);
197
+ setDraft(stored);
198
+ setServerErrors({});
199
+ setShowErrors(false);
200
+ return { ok: true, adjusted };
201
+ } catch (error) {
202
+ const info = readApiError(error);
203
+ setServerErrors(mapServerErrors(info.details));
204
+ return { ok: false, message: info.status === 400 ? null : info.message };
205
+ } finally {
206
+ if (mounted.current) setSaving(false);
207
+ }
208
+ }, [draft, hasErrors, put]);
209
+ const clearServerErrors = useCallback(() => setServerErrors({}), []);
210
+ const discard = useCallback(() => {
211
+ setDraft(saved);
212
+ setServerErrors({});
213
+ setShowErrors(false);
214
+ }, [saved]);
215
+ const test = useCallback(async () => {
216
+ setShowErrors(true);
217
+ const blocking = Object.keys(errors).filter((key) => key !== "apiKey" || draft.apiKeyMode === "replace");
218
+ if (blocking.length) return { ok: false, invalid: true };
219
+ setTesting(true);
220
+ try {
221
+ const payload = toPayload(draft);
222
+ if (draft.apiKeyMode === "remove") delete payload.ai.apiKey;
223
+ await post(API.settingsAiTest, payload);
224
+ return { ok: true };
225
+ } catch (error) {
226
+ const info = readApiError(error);
227
+ return { ok: false, code: info.code, status: info.status };
228
+ } finally {
229
+ if (mounted.current) setTesting(false);
230
+ }
231
+ }, [draft, errors, post]);
232
+ const visibleErrors = useMemo(() => {
233
+ const merged = showErrors ? { ...errors } : {};
234
+ for (const [key, value] of Object.entries(serverErrors)) merged[key] = { server: value };
235
+ return merged;
236
+ }, [errors, serverErrors, showErrors]);
237
+ return {
238
+ status,
239
+ dto,
240
+ saved,
241
+ draft,
242
+ errors: visibleErrors,
243
+ dirty,
244
+ hasErrors,
245
+ saving,
246
+ testing,
247
+ reload: load,
248
+ setField,
249
+ replaceDraft,
250
+ save,
251
+ discard,
252
+ test,
253
+ clearServerErrors
254
+ };
255
+ };
256
+ const errorText = (t, error, field) => {
257
+ if (!error) return void 0;
258
+ if (typeof error === "object") return error.server;
259
+ switch (error) {
260
+ case "required":
261
+ return t("settings.validation.required", "This field is required.");
262
+ case "modelPattern":
263
+ return t(
264
+ "settings.validation.model",
265
+ "Use letters, digits and the characters . _ : / @ - (up to 120 characters)."
266
+ );
267
+ case "url":
268
+ return t("settings.validation.url", "Enter a valid http or https URL without user name or password.");
269
+ case "https":
270
+ return t(
271
+ "settings.validation.https",
272
+ "Use an https URL. Private or http hosts need ai.allowPrivateBaseUrl in config/plugins.js."
273
+ );
274
+ case "range":
275
+ return t("settings.validation.range", "Enter a whole number from {min} to {max}.", LIMITS[field] || {});
276
+ case "reenter":
277
+ return t(
278
+ "settings.validation.reenterKey",
279
+ "Enter the API key again when you change the provider or base URL."
280
+ );
281
+ case "cannotStore":
282
+ return t("settings.validation.cannotStore", "Set MAGIC_EDITOR_X_ENCRYPTION_KEY to store an API key.");
283
+ case "tooLong":
284
+ return t("settings.validation.keyTooLong", "The API key is too long.");
285
+ default:
286
+ return t("settings.validation.invalid", "Check this value.");
287
+ }
288
+ };
289
+ const providerName = (t, draft) => {
290
+ if (draft.provider === "anthropic") return t("settings.ai.provider.anthropic.name", "Anthropic");
291
+ if (draft.provider === "openai") return t("settings.ai.provider.openai.name", "OpenAI");
292
+ const host = (() => {
293
+ try {
294
+ return draft.baseUrl ? new URL(draft.baseUrl).host : "";
295
+ } catch {
296
+ return "";
297
+ }
298
+ })();
299
+ return host || t("settings.ai.provider.compatible.name", "the server at the base URL");
300
+ };
301
+ const KeyStatus = ({ ai, draft, t }) => {
302
+ let tone = { backgroundColor: "neutral150", textColor: "neutral700" };
303
+ let label = t("settings.ai.key.status.none", "No key stored");
304
+ let text = "";
305
+ if (ai.apiKeyFromEnvironment) {
306
+ tone = { backgroundColor: "success100", textColor: "success700" };
307
+ label = t("settings.ai.key.status.environment", "From the environment");
308
+ text = t(
309
+ "settings.ai.key.environmentHint",
310
+ "The ai.apiKey setting in config/plugins.js is used and overrides a stored key."
311
+ );
312
+ } else if (draft.apiKeyMode === "remove") {
313
+ tone = { backgroundColor: "warning200", textColor: "neutral800" };
314
+ label = t("settings.ai.key.status.removing", "Removed when you save");
315
+ } else if (ai.apiKeyUnreadable) {
316
+ tone = { backgroundColor: "warning200", textColor: "neutral800" };
317
+ label = t("settings.ai.key.status.unreadable", "Stored key unreadable");
318
+ text = t(
319
+ "settings.ai.key.unreadableHint",
320
+ "A key is stored but cannot be decrypted, usually because MAGIC_EDITOR_X_ENCRYPTION_KEY changed. Enter the key again."
321
+ );
322
+ } else if (ai.hasApiKey) {
323
+ tone = { backgroundColor: "success100", textColor: "success700" };
324
+ label = t("settings.ai.key.status.stored", "Stored, encrypted");
325
+ }
326
+ return /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, children: [
327
+ /* @__PURE__ */ jsx(Badge, { ...tone, children: label }),
328
+ text ? /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: text }) : null
329
+ ] });
330
+ };
331
+ const AiSection = ({ form, readOnly, onTest }) => {
332
+ const t = useT();
333
+ const { draft, dto, errors, setField, replaceDraft, testing } = form;
334
+ const ai = dto.ai;
335
+ const defaults = dto.environment.defaults || { models: {}, baseUrls: {} };
336
+ const keyDisabled = readOnly || ai.apiKeyFromEnvironment || !ai.canStoreApiKey;
337
+ return /* @__PURE__ */ jsxs(
338
+ SectionCard,
339
+ {
340
+ title: t("settings.ai.title", "AI assistant"),
341
+ subtitle: t(
342
+ "settings.ai.subtitle",
343
+ "Editors can improve, shorten, translate or continue selected text with your own AI provider. It is off until you turn it on."
344
+ ),
345
+ action: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: onTest, loading: testing, disabled: testing, children: t("settings.ai.test", "Test connection") }),
346
+ children: [
347
+ /* @__PURE__ */ jsxs(Flex, { gap: 4, alignItems: "flex-start", justifyContent: "space-between", minWidth: 0, children: [
348
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "flex-start", gap: 1, minWidth: 0, flex: "1 1 auto", children: [
349
+ /* @__PURE__ */ jsx(Typography, { variant: "omega", fontWeight: "bold", textColor: "neutral800", id: "mex-ai-enabled-label", children: t("settings.ai.enabled.label", "Turn on the AI assistant") }),
350
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", id: "mex-ai-enabled-hint", children: t(
351
+ "settings.ai.enabled.privacy",
352
+ "When an editor runs an AI action, the selected text is sent to {provider}. Nothing is sent while the assistant is off.",
353
+ { provider: providerName(t, draft) }
354
+ ) })
355
+ ] }),
356
+ /* @__PURE__ */ jsx(
357
+ Switch,
358
+ {
359
+ checked: draft.enabled,
360
+ onCheckedChange: (checked) => setField("enabled", checked === true),
361
+ disabled: readOnly,
362
+ "aria-labelledby": "mex-ai-enabled-label",
363
+ "aria-describedby": "mex-ai-enabled-hint",
364
+ onLabel: t("settings.switch.on", "On"),
365
+ offLabel: t("settings.switch.off", "Off"),
366
+ visibleLabels: true
367
+ }
368
+ )
369
+ ] }),
370
+ /* @__PURE__ */ jsxs(Grid.Root, { gap: { initial: 4, medium: 5 }, children: [
371
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(Field.Root, { name: "provider", error: errorText(t, errors.provider, "provider"), required: true, children: [
372
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.provider.label", "Provider") }),
373
+ /* @__PURE__ */ jsxs(
374
+ SingleSelect,
375
+ {
376
+ value: draft.provider,
377
+ disabled: readOnly,
378
+ onChange: (value) => replaceDraft(applyProvider(draft, String(value), defaults.models)),
379
+ children: [
380
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "anthropic", children: t("settings.ai.provider.anthropic", "Anthropic (Messages API)") }),
381
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "openai", children: t("settings.ai.provider.openai", "OpenAI (Chat Completions)") }),
382
+ /* @__PURE__ */ jsx(SingleSelectOption, { value: "openai-compatible", children: t("settings.ai.provider.compatible", "OpenAI-compatible server") })
383
+ ]
384
+ }
385
+ ),
386
+ /* @__PURE__ */ jsx(Field.Error, {})
387
+ ] }) }),
388
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
389
+ Field.Root,
390
+ {
391
+ name: "model",
392
+ error: errorText(t, errors.model, "model"),
393
+ hint: defaults.models[draft.provider] ? t("settings.ai.model.hint", "Default: {model}", { model: defaults.models[draft.provider] }) : t("settings.ai.model.hintCompatible", "Use the model name your server expects."),
394
+ required: true,
395
+ children: [
396
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.model.label", "Model") }),
397
+ /* @__PURE__ */ jsx(
398
+ TextInput,
399
+ {
400
+ value: draft.model,
401
+ disabled: readOnly,
402
+ onChange: (event) => setField("model", event.target.value)
403
+ }
404
+ ),
405
+ /* @__PURE__ */ jsx(Field.Hint, {}),
406
+ /* @__PURE__ */ jsx(Field.Error, {})
407
+ ]
408
+ }
409
+ ) }),
410
+ /* @__PURE__ */ jsx(Grid.Item, { col: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
411
+ Field.Root,
412
+ {
413
+ name: "baseUrl",
414
+ error: errorText(t, errors.baseUrl, "baseUrl"),
415
+ hint: defaults.baseUrls[draft.provider] ? t("settings.ai.baseUrl.hint", "Leave empty to use {url}.", {
416
+ url: defaults.baseUrls[draft.provider]
417
+ }) : t(
418
+ "settings.ai.baseUrl.hintCompatible",
419
+ "Required. Requests go to the base URL followed by /v1/chat/completions."
420
+ ),
421
+ required: draft.provider === "openai-compatible",
422
+ children: [
423
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.baseUrl.label", "Base URL") }),
424
+ /* @__PURE__ */ jsx(
425
+ TextInput,
426
+ {
427
+ type: "url",
428
+ value: draft.baseUrl,
429
+ disabled: readOnly,
430
+ placeholder: defaults.baseUrls[draft.provider] || "https://",
431
+ onChange: (event) => setField("baseUrl", event.target.value)
432
+ }
433
+ ),
434
+ /* @__PURE__ */ jsx(Field.Hint, {}),
435
+ /* @__PURE__ */ jsx(Field.Error, {})
436
+ ]
437
+ }
438
+ ) }),
439
+ /* @__PURE__ */ jsxs(Grid.Item, { col: 12, direction: "column", alignItems: "stretch", minWidth: 0, children: [
440
+ /* @__PURE__ */ jsxs(
441
+ Field.Root,
442
+ {
443
+ name: "apiKey",
444
+ error: errorText(t, errors.apiKey, "apiKey"),
445
+ hint: !ai.canStoreApiKey && !ai.apiKeyFromEnvironment ? t(
446
+ "settings.ai.key.cannotStoreHint",
447
+ "Set MAGIC_EDITOR_X_ENCRYPTION_KEY (at least 32 characters) on the server to store a key here, or pass ai.apiKey in config/plugins.js."
448
+ ) : t(
449
+ "settings.ai.key.hint",
450
+ "Leave empty to keep the stored key. The key is never shown again after saving."
451
+ ),
452
+ children: [
453
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.key.label", "API key") }),
454
+ /* @__PURE__ */ jsxs(Flex, { direction: "column", alignItems: "stretch", gap: 2, children: [
455
+ /* @__PURE__ */ jsx(KeyStatus, { ai, draft, t }),
456
+ /* @__PURE__ */ jsx(
457
+ TextInput,
458
+ {
459
+ type: "password",
460
+ autoComplete: "new-password",
461
+ value: draft.apiKeyMode === "replace" ? draft.apiKey : "",
462
+ disabled: keyDisabled || draft.apiKeyMode === "remove",
463
+ placeholder: t("settings.ai.key.placeholder", "Enter a new key"),
464
+ onChange: (event) => {
465
+ const value = event.target.value;
466
+ replaceDraft({ ...draft, apiKey: value, apiKeyMode: value ? "replace" : "keep" });
467
+ }
468
+ }
469
+ )
470
+ ] }),
471
+ /* @__PURE__ */ jsx(Field.Hint, {}),
472
+ /* @__PURE__ */ jsx(Field.Error, {})
473
+ ]
474
+ }
475
+ ),
476
+ !readOnly && ai.hasApiKey && !ai.apiKeyFromEnvironment ? /* @__PURE__ */ jsx(Box, { paddingTop: 2, children: draft.apiKeyMode === "remove" ? /* @__PURE__ */ jsx(TextButton, { onClick: () => replaceDraft({ ...draft, apiKeyMode: "keep", apiKey: "" }), children: t("settings.ai.key.keep", "Keep the stored key") }) : /* @__PURE__ */ jsx(TextButton, { onClick: () => replaceDraft({ ...draft, apiKeyMode: "remove", apiKey: "" }), children: t("settings.ai.key.remove", "Remove the stored key") }) }) : null
477
+ ] }),
478
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
479
+ Field.Root,
480
+ {
481
+ name: "maxInputChars",
482
+ error: errorText(t, errors.maxInputChars, "maxInputChars"),
483
+ hint: t(
484
+ "settings.ai.maxInput.hint",
485
+ "Longer selections are refused. Allowed: {min} to {max} characters.",
486
+ LIMITS.maxInputChars
487
+ ),
488
+ required: true,
489
+ children: [
490
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.maxInput.label", "Maximum text length") }),
491
+ /* @__PURE__ */ jsx(
492
+ NumberInput,
493
+ {
494
+ value: draft.maxInputChars ?? null,
495
+ disabled: readOnly,
496
+ onValueChange: (value) => setField("maxInputChars", value ?? null)
497
+ }
498
+ ),
499
+ /* @__PURE__ */ jsx(Field.Hint, {}),
500
+ /* @__PURE__ */ jsx(Field.Error, {})
501
+ ]
502
+ }
503
+ ) }),
504
+ /* @__PURE__ */ jsx(Grid.Item, { col: 6, xs: 12, s: 12, m: 6, direction: "column", alignItems: "stretch", minWidth: 0, children: /* @__PURE__ */ jsxs(
505
+ Field.Root,
506
+ {
507
+ name: "maxOutputTokens",
508
+ error: errorText(t, errors.maxOutputTokens, "maxOutputTokens"),
509
+ hint: t(
510
+ "settings.ai.maxOutput.hint",
511
+ "Upper limit for one answer. Allowed: {min} to {max} tokens.",
512
+ LIMITS.maxOutputTokens
513
+ ),
514
+ required: true,
515
+ children: [
516
+ /* @__PURE__ */ jsx(Field.Label, { children: t("settings.ai.maxOutput.label", "Maximum answer length (tokens)") }),
517
+ /* @__PURE__ */ jsx(
518
+ NumberInput,
519
+ {
520
+ value: draft.maxOutputTokens ?? null,
521
+ disabled: readOnly,
522
+ onValueChange: (value) => setField("maxOutputTokens", value ?? null)
523
+ }
524
+ ),
525
+ /* @__PURE__ */ jsx(Field.Hint, {}),
526
+ /* @__PURE__ */ jsx(Field.Error, {})
527
+ ]
528
+ }
529
+ ) })
530
+ ] }),
531
+ /* @__PURE__ */ jsx(Typography, { variant: "pi", textColor: "neutral600", children: t(
532
+ "settings.ai.rbacHint",
533
+ 'Only roles with the "Use the AI assistant" permission see the assistant. Requests per editor are limited to {count} per minute.',
534
+ { count: dto.environment.requestsPerMinute }
535
+ ) })
536
+ ]
537
+ }
538
+ );
539
+ };
540
+ const megabytes = (t, formatNumber, bytes) => t("settings.environment.megabytes", "{size} MB", {
541
+ size: formatNumber(Number(bytes || 0) / (1024 * 1024), { maximumFractionDigits: 1 })
542
+ });
543
+ const EnvironmentSection = ({ environment }) => {
544
+ const t = useT();
545
+ const { formatNumber } = useIntl();
546
+ const on = (value) => value ? /* @__PURE__ */ jsx(Badge, { backgroundColor: "success100", textColor: "success700", children: t("settings.environment.on", "On") }) : /* @__PURE__ */ jsx(Badge, { backgroundColor: "neutral150", textColor: "neutral700", children: t("settings.environment.off", "Off") });
547
+ const rawHtml = {
548
+ sanitize: t(
549
+ "settings.environment.rawHtml.sanitize",
550
+ "Cleaned on save (scripts and event handlers removed)"
551
+ ),
552
+ allow: t("settings.environment.rawHtml.allow", "Stored as typed (the frontend must sanitise it)"),
553
+ disable: t("settings.environment.rawHtml.disable", "Emptied on save")
554
+ }[environment.rawHtml] || environment.rawHtml;
555
+ const collaboration = environment.collaboration || {};
556
+ return /* @__PURE__ */ jsx(
557
+ SectionCard,
558
+ {
559
+ title: t("settings.environment.title", "Server configuration"),
560
+ subtitle: t(
561
+ "settings.environment.subtitle",
562
+ "These options are set in config/plugins.js and apply after a restart. They cannot be changed here."
563
+ ),
564
+ children: /* @__PURE__ */ jsx(
565
+ PropertyList,
566
+ {
567
+ items: [
568
+ {
569
+ key: "collaboration",
570
+ label: t("settings.environment.collaboration", "Live collaboration"),
571
+ value: on(collaboration.enabled),
572
+ hint: collaboration.enabled ? t(
573
+ "settings.environment.collaborationHint",
574
+ "Socket path {path}. Other servers are checked every {interval} ms.",
575
+ {
576
+ path: collaboration.path || "",
577
+ interval: collaboration.pollIntervalMs ?? 0
578
+ }
579
+ ) : void 0
580
+ },
581
+ {
582
+ key: "snapshots",
583
+ label: t("settings.environment.snapshots", "Automatic snapshots"),
584
+ value: collaboration.snapshotIntervalMinutes ? t("settings.environment.snapshotsEvery", "Every {minutes} minutes during live editing", {
585
+ minutes: collaboration.snapshotIntervalMinutes
586
+ }) : t("settings.environment.snapshotsOff", "Off")
587
+ },
588
+ { key: "rawHtml", label: t("settings.environment.rawHtml", "Raw HTML block"), value: rawHtml },
589
+ {
590
+ key: "images",
591
+ label: t("settings.environment.maxImage", "Largest image upload"),
592
+ value: megabytes(t, formatNumber, environment.uploads && environment.uploads.maxImageBytes)
593
+ },
594
+ {
595
+ key: "files",
596
+ label: t("settings.environment.maxFile", "Largest file upload"),
597
+ value: megabytes(t, formatNumber, environment.uploads && environment.uploads.maxFileBytes)
598
+ },
599
+ {
600
+ key: "privateAi",
601
+ label: t("settings.environment.privateAi", "Private AI hosts allowed"),
602
+ value: on(environment.allowPrivateBaseUrl),
603
+ hint: t(
604
+ "settings.environment.privateAiHint",
605
+ "Needed for local models on localhost or a private network (ai.allowPrivateBaseUrl)."
606
+ )
607
+ }
608
+ ]
609
+ }
610
+ )
611
+ }
612
+ );
613
+ };
614
+ const RBAC = [...PERMISSIONS.settingsRead, ...PERMISSIONS.settingsUpdate];
615
+ const testErrorText = (t, code) => {
616
+ switch (code) {
617
+ case "NOT_CONFIGURED":
618
+ return t("settings.test.notConfigured", "Connection failed: the provider is not configured.");
619
+ case "NO_API_KEY":
620
+ return t("settings.test.noKey", "Connection failed: no API key is available.");
621
+ case "AUTH_FAILED":
622
+ return t("settings.test.auth", "Connection failed: the provider rejected the API key.");
623
+ case "PROVIDER_RATE_LIMIT":
624
+ return t("settings.test.rateLimit", "Connection failed: the provider is busy or rate limited.");
625
+ case "TIMEOUT":
626
+ return t("settings.test.timeout", "Connection failed: the provider did not answer in time.");
627
+ case "REFUSED":
628
+ return t("settings.test.refused", "The provider answered but declined the test request.");
629
+ default:
630
+ return t("settings.test.failed", "Connection failed. Check the provider, base URL, model and key.");
631
+ }
632
+ };
633
+ const ConfigurationPage = () => {
634
+ const t = useT();
635
+ const { toggleNotification } = useNotification();
636
+ const { allowedActions, isLoading: rbacLoading } = useRBAC(RBAC);
637
+ const form = useConfigurationForm();
638
+ const title = t("settings.configuration.title", "Configuration");
639
+ if (rbacLoading || form.status === "loading") {
640
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
641
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
642
+ /* @__PURE__ */ jsx(Page.Loading, {})
643
+ ] });
644
+ }
645
+ if (!allowedActions.canRead) {
646
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
647
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
648
+ /* @__PURE__ */ jsx(Page.NoPermissions, {})
649
+ ] });
650
+ }
651
+ if (form.status === "error") {
652
+ return /* @__PURE__ */ jsxs(Page.Main, { children: [
653
+ /* @__PURE__ */ jsx(Page.Title, { children: title }),
654
+ /* @__PURE__ */ jsx(
655
+ Page.Error,
656
+ {
657
+ content: t(
658
+ "settings.configuration.loadError",
659
+ "The settings could not be loaded. Nothing can be saved until they load."
660
+ ),
661
+ action: /* @__PURE__ */ jsx(Button, { variant: "secondary", onClick: form.reload, children: t("settings.retry", "Try again") })
662
+ }
663
+ )
664
+ ] });
665
+ }
666
+ const readOnly = !allowedActions.canUpdate;
667
+ const onSave = async () => {
668
+ const result = await form.save();
669
+ if (result.ok) {
670
+ toggleNotification({
671
+ type: "success",
672
+ message: result.adjusted.length ? t("settings.save.adjusted", "Settings saved. The server adjusted: {fields}.", {
673
+ fields: result.adjusted.join(", ")
674
+ }) : t("settings.save.success", "Settings saved.")
675
+ });
676
+ } else if (result.invalid) {
677
+ toggleNotification({
678
+ type: "warning",
679
+ message: t("settings.save.invalid", "Some values need attention before saving.")
680
+ });
681
+ } else {
682
+ toggleNotification({
683
+ type: "danger",
684
+ message: t(
685
+ "settings.save.error",
686
+ "The settings could not be saved. Your changes are still in the form."
687
+ )
688
+ });
689
+ }
690
+ };
691
+ const onTest = async () => {
692
+ const result = await form.test();
693
+ if (result.ok) {
694
+ toggleNotification({
695
+ type: "success",
696
+ message: t("settings.test.success", "Connection works. The provider answered.")
697
+ });
698
+ } else if (result.invalid) {
699
+ toggleNotification({
700
+ type: "warning",
701
+ message: t("settings.test.invalid", "Fix the highlighted fields before testing.")
702
+ });
703
+ } else {
704
+ toggleNotification({ type: "danger", message: testErrorText(t, result.code) });
705
+ }
706
+ };
707
+ return /* @__PURE__ */ jsxs(
708
+ PageShell,
709
+ {
710
+ title,
711
+ subtitle: readOnly ? t(
712
+ "settings.configuration.readOnly",
713
+ 'You can view these settings. Changing them needs the "Update settings" permission.'
714
+ ) : t(
715
+ "settings.configuration.subtitle",
716
+ "Choose an AI provider for the editor assistant and review the server options."
717
+ ),
718
+ primaryAction: readOnly ? null : /* @__PURE__ */ jsx(
719
+ Button,
720
+ {
721
+ startIcon: /* @__PURE__ */ jsx(Check, {}),
722
+ onClick: onSave,
723
+ loading: form.saving,
724
+ disabled: form.saving || !form.dirty,
725
+ children: t("settings.save", "Save")
726
+ }
727
+ ),
728
+ secondaryAction: readOnly ? null : /* @__PURE__ */ jsx(
729
+ ConfirmAction,
730
+ {
731
+ disabled: !form.dirty || form.saving,
732
+ trigger: /* @__PURE__ */ jsx(Button, { variant: "tertiary", disabled: !form.dirty || form.saving, children: t("settings.discard", "Discard changes") }),
733
+ title: t("settings.discard.title", "Discard your changes?"),
734
+ body: t(
735
+ "settings.discard.body",
736
+ "The form goes back to the stored settings. Your unsaved changes are lost."
737
+ ),
738
+ confirmLabel: t("settings.discard.confirm", "Discard changes"),
739
+ variant: "danger-light",
740
+ onConfirm: () => form.discard()
741
+ }
742
+ ),
743
+ children: [
744
+ form.errors._form ? /* @__PURE__ */ jsx(
745
+ Alert,
746
+ {
747
+ variant: "danger",
748
+ closeLabel: t("settings.close", "Close"),
749
+ onClose: form.clearServerErrors,
750
+ title: t("settings.save.rejected", "The server rejected the settings"),
751
+ children: typeof form.errors._form === "object" ? form.errors._form.server : form.errors._form
752
+ }
753
+ ) : null,
754
+ /* @__PURE__ */ jsx(AiSection, { form, readOnly, onTest }),
755
+ /* @__PURE__ */ jsx(EnvironmentSection, { environment: form.dto.environment }),
756
+ /* @__PURE__ */ jsxs(Form, { method: "PUT", initialValues: form.saved, children: [
757
+ /* @__PURE__ */ jsx(DraftSync, { values: form.draft }),
758
+ /* @__PURE__ */ jsx(Blocker, {})
759
+ ] })
760
+ ]
761
+ }
762
+ );
763
+ };
764
+ export {
765
+ ConfigurationPage,
766
+ ConfigurationPage as default
767
+ };