@perkyzz/emvb 0.3.0 → 0.5.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 (163) hide show
  1. package/README.md +22 -4
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +5 -2
  4. package/src/admin/access/role.ts +9 -3
  5. package/src/admin/agents-api.ts +39 -0
  6. package/src/admin/api.ts +17 -7
  7. package/src/admin/content-api.ts +7 -51
  8. package/src/admin/content-item.ts +22 -0
  9. package/src/admin/design-api.ts +30 -0
  10. package/src/admin/editor/A11yCopilot.tsx +1 -1
  11. package/src/admin/editor/CommandPalette.tsx +43 -2
  12. package/src/admin/editor/Editor.tsx +133 -332
  13. package/src/admin/editor/EditorOverlay.tsx +3 -1
  14. package/src/admin/editor/PerfMeter.tsx +1 -1
  15. package/src/admin/editor/ShortcutsDialog.tsx +4 -1
  16. package/src/admin/editor/Timeline.tsx +124 -9
  17. package/src/admin/editor/canvas/CanvasFrame.tsx +51 -368
  18. package/src/admin/editor/canvas/DeviceBar.tsx +4 -1
  19. package/src/admin/editor/canvas/SelectionOverlay.tsx +86 -46
  20. package/src/admin/editor/canvas/canvas-scale.ts +20 -0
  21. package/src/admin/editor/canvas/drop-line.ts +24 -0
  22. package/src/admin/editor/canvas/use-canvas-dnd.ts +207 -0
  23. package/src/admin/editor/canvas/use-canvas-session.ts +216 -0
  24. package/src/admin/editor/collection-previews.ts +28 -5
  25. package/src/admin/editor/editor-chrome.tsx +346 -0
  26. package/src/admin/editor/editor-commands.ts +360 -0
  27. package/src/admin/editor/editor-css.ts +4 -0
  28. package/src/admin/editor/element-chrome.ts +89 -0
  29. package/src/admin/editor/feature-css.ts +37 -18
  30. package/src/admin/editor/host.ts +33 -0
  31. package/src/admin/editor/icons/IconLibraryDialog.tsx +64 -218
  32. package/src/admin/editor/icons/library.ts +29 -19
  33. package/src/admin/editor/icons/use-icon-library.ts +315 -0
  34. package/src/admin/editor/palette-items.ts +36 -5
  35. package/src/admin/editor/palette.ts +9 -4
  36. package/src/admin/editor/panels/AddPanel.tsx +2 -67
  37. package/src/admin/editor/panels/ColorControl.tsx +21 -18
  38. package/src/admin/editor/panels/ElementPanel.tsx +40 -99
  39. package/src/admin/editor/panels/LayersPanel.tsx +34 -62
  40. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  41. package/src/admin/editor/panels/SiteStylesDrawer.tsx +16 -10
  42. package/src/admin/editor/panels/TokenScales.tsx +4 -2
  43. package/src/admin/editor/panels/VariableSection.tsx +1 -10
  44. package/src/admin/editor/panels/color-space.ts +12 -1
  45. package/src/admin/editor/panels/inline-error.tsx +11 -0
  46. package/src/admin/editor/panels/settings/AdvancedFields.tsx +143 -1
  47. package/src/admin/editor/panels/settings/AudienceEditor.tsx +115 -7
  48. package/src/admin/editor/panels/settings/DraftTextField.tsx +42 -9
  49. package/src/admin/editor/panels/settings/FieldControl.tsx +6 -0
  50. package/src/admin/editor/panels/settings/FormBindControl.tsx +8 -4
  51. package/src/admin/editor/panels/settings/IconPicker.tsx +21 -1
  52. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +111 -0
  53. package/src/admin/editor/panels/settings/ItemList.tsx +34 -1
  54. package/src/admin/editor/panels/settings/MediaPicker.tsx +2 -3
  55. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +178 -0
  56. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -2
  57. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  58. package/src/admin/editor/panels/settings/form-names.ts +7 -11
  59. package/src/admin/editor/panels/settings/length-units.ts +15 -4
  60. package/src/admin/editor/panels/settings/link-rules.ts +19 -0
  61. package/src/admin/editor/panels/settings/number-input.ts +11 -0
  62. package/src/admin/editor/panels/settings/query-style.ts +65 -0
  63. package/src/admin/editor/panels/settings/style-sections.ts +5 -1
  64. package/src/admin/editor/panels/style-target.ts +105 -0
  65. package/src/admin/editor/panels/variable-values.ts +4 -2
  66. package/src/admin/editor/remote-change.ts +67 -0
  67. package/src/admin/editor/section-templates.ts +43 -21
  68. package/src/admin/editor/shortcuts.ts +4 -0
  69. package/src/admin/editor/store.ts +10 -1
  70. package/src/admin/editor/useClipboardActions.ts +1 -1
  71. package/src/admin/editor/useEditorCommands.ts +61 -13
  72. package/src/admin/editor/useEditorData.ts +7 -1
  73. package/src/admin/editor/useEditorShortcuts.ts +23 -15
  74. package/src/admin/editor/useNodeActions.ts +6 -1
  75. package/src/admin/forms-api.ts +17 -6
  76. package/src/admin/icon-uploads-api.ts +18 -0
  77. package/src/admin/index.tsx +3 -1
  78. package/src/admin/media-api.ts +20 -0
  79. package/src/admin/pages/AgentsPage.tsx +274 -0
  80. package/src/admin/theme-api.ts +5 -18
  81. package/src/admin/ui.ts +28 -0
  82. package/src/astro/content-port.ts +24 -0
  83. package/src/astro/floats/runtime.ts +10 -0
  84. package/src/astro/forms/EmVBFormsClient.astro +11 -0
  85. package/src/astro/forms/EmVBFormsRuntime.astro +6 -7
  86. package/src/astro/forms/client.ts +1 -0
  87. package/src/astro/forms-definitions.ts +24 -11
  88. package/src/astro/index.ts +1 -0
  89. package/src/astro/popups/runtime.ts +15 -0
  90. package/src/astro/render-session.ts +85 -0
  91. package/src/astro/request-data.ts +20 -8
  92. package/src/astro/resolve-theme.ts +166 -76
  93. package/src/astro/resolve.ts +57 -16
  94. package/src/astro/tabs/runtime.ts +60 -1
  95. package/src/astro/theme-posts.ts +16 -5
  96. package/src/astro/visitor.ts +67 -5
  97. package/src/constants.ts +1 -1
  98. package/src/core/a11y/audit.ts +202 -26
  99. package/src/core/arrange.ts +71 -38
  100. package/src/core/audience/rules.ts +22 -2
  101. package/src/core/canvas-styles.ts +24 -0
  102. package/src/core/clipboard.ts +11 -32
  103. package/src/core/css/generate.ts +18 -1
  104. package/src/core/css/print.ts +12 -0
  105. package/src/core/css/scope.ts +3 -3
  106. package/src/core/css-keywords.ts +83 -0
  107. package/src/core/data/bindings.ts +4 -6
  108. package/src/core/design/classes.ts +13 -15
  109. package/src/core/design/diff.ts +55 -0
  110. package/src/core/design/merge.ts +127 -0
  111. package/src/core/design/variables.ts +25 -21
  112. package/src/core/elements/dynamic-elements.ts +30 -0
  113. package/src/core/elements/form-elements.ts +20 -3
  114. package/src/core/elements/index.ts +211 -7
  115. package/src/core/forms/binding.ts +4 -13
  116. package/src/core/index.ts +10 -0
  117. package/src/core/local-style.ts +27 -0
  118. package/src/core/migrate/index.ts +9 -4
  119. package/src/core/nesting.ts +4 -23
  120. package/src/core/perf/scripts.ts +9 -6
  121. package/src/core/record.ts +3 -0
  122. package/src/core/render/context.ts +2 -0
  123. package/src/core/render/dynamic-post.ts +22 -7
  124. package/src/core/render/form.ts +145 -15
  125. package/src/core/render/index.ts +195 -14
  126. package/src/core/render/pagination.ts +21 -2
  127. package/src/core/render/vnode.ts +12 -2
  128. package/src/core/sanitize/css.ts +90 -77
  129. package/src/core/sanitize/embed-url.ts +7 -1
  130. package/src/core/sanitize/href.ts +13 -1
  131. package/src/core/sanitize/svg.ts +8 -3
  132. package/src/core/sanitize/url.ts +10 -1
  133. package/src/core/schema/descriptors.ts +4 -1
  134. package/src/core/schema/design.ts +5 -7
  135. package/src/core/schema/layout.ts +160 -181
  136. package/src/core/schema/style.ts +53 -63
  137. package/src/core/share/link.ts +72 -29
  138. package/src/core/tabs/presence.ts +7 -17
  139. package/src/core/theme/dynamic.ts +205 -39
  140. package/src/core/theme/float.ts +1 -1
  141. package/src/core/tree-ops.ts +57 -0
  142. package/src/index.ts +14 -2
  143. package/src/mcp/errors.ts +44 -0
  144. package/src/mcp/index.ts +4 -0
  145. package/src/mcp/ports.ts +78 -0
  146. package/src/mcp/prompts.ts +76 -0
  147. package/src/mcp/publish.ts +60 -0
  148. package/src/mcp/queue.ts +19 -0
  149. package/src/mcp/rate-limit.ts +80 -0
  150. package/src/mcp/read.ts +419 -0
  151. package/src/mcp/refs.ts +84 -0
  152. package/src/mcp/settings.ts +18 -0
  153. package/src/mcp/tools.ts +265 -0
  154. package/src/mcp/write.ts +582 -0
  155. package/src/server/agent-settings.ts +134 -0
  156. package/src/server/design-routes.ts +75 -18
  157. package/src/server/icon-routes.ts +72 -16
  158. package/src/server/mcp-routes.ts +265 -0
  159. package/src/server/plugin.ts +40 -4
  160. package/src/admin/editor/icons/sets/fontawesome.json +0 -1
  161. package/src/admin/editor/icons/sets/lucide.json +0 -1
  162. package/src/admin/editor/icons/sets/remix.json +0 -1
  163. package/src/admin/editor/icons/sets/tabler.json +0 -1
@@ -0,0 +1,134 @@
1
+ import {
2
+ PluginRouteError,
3
+ type ContentPolicyDecision,
4
+ type ContentPolicyEvent,
5
+ type PluginContext,
6
+ type PluginRoute,
7
+ } from "emdash";
8
+ import { z } from "zod";
9
+ import { PAGES_COLLECTION, THEME_PARTS_COLLECTION } from "../constants.ts";
10
+ import { AgentSettings, DEFAULT_AGENT_SETTINGS } from "../mcp/settings.ts";
11
+
12
+ /** Plugin KV key of the agent settings (plan § 4, D-055). */
13
+ const AGENT_SETTINGS_KEY = "agent-settings";
14
+
15
+ /** The agent settings and their revision. Missing or damaged settings read as the safe defaults. */
16
+ export async function readAgentSettings(
17
+ ctx: Pick<PluginContext, "kv">,
18
+ ): Promise<{ settings: AgentSettings; revision: string | null }> {
19
+ const stored = await ctx.kv.getVersioned<unknown>(AGENT_SETTINGS_KEY);
20
+ if (!stored) return { settings: DEFAULT_AGENT_SETTINGS, revision: null };
21
+ const parsed = AgentSettings.safeParse(stored.value);
22
+ return {
23
+ settings: parsed.success ? parsed.data : DEFAULT_AGENT_SETTINGS,
24
+ revision: stored.revision,
25
+ };
26
+ }
27
+
28
+ type LogQuery = {
29
+ query(o: {
30
+ where?: Record<string, unknown>;
31
+ orderBy: Record<string, "asc" | "desc">;
32
+ limit: number;
33
+ }): Promise<{
34
+ items: { id: string; data: unknown }[];
35
+ }>;
36
+ put(id: string, data: unknown): Promise<void>;
37
+ };
38
+ const agentLog = (ctx: PluginContext) => ctx.storage["agentlog"] as unknown as LogQuery;
39
+
40
+ /** Agents tab: the settings, the MCP endpoint and the last 50 agent changes. Admins only. */
41
+ export const agentsRoute: PluginRoute = {
42
+ permission: "plugins:manage",
43
+ handler: async (ctx) => {
44
+ const { settings, revision } = await readAgentSettings(ctx);
45
+ const log = await agentLog(ctx).query({ orderBy: { at: "desc" }, limit: 50 });
46
+ return {
47
+ settings,
48
+ revision,
49
+ endpoint: new URL("/_emdash/api/mcp", ctx.request.url).toString(),
50
+ activity: log.items.map((item) => Object.assign({ id: item.id }, item.data as object)),
51
+ };
52
+ },
53
+ };
54
+
55
+ const PageAgentsInput = z.object({ pageId: z.string().min(1).max(128) });
56
+
57
+ /**
58
+ * W-460: the page's versions an agent saved, for the Timeline's Agent badge and filter. Editors
59
+ * can read this (it carries no settings); the full activity list stays admin-only.
60
+ */
61
+ export const pageAgentVersionsRoute: PluginRoute<z.infer<typeof PageAgentsInput>> = {
62
+ permission: "content:edit_any",
63
+ input: PageAgentsInput,
64
+ handler: async (ctx) => {
65
+ const log = await agentLog(ctx).query({
66
+ where: { pageId: ctx.input.pageId },
67
+ orderBy: { at: "desc" },
68
+ limit: 100,
69
+ });
70
+ const versions = log.items
71
+ .map(
72
+ (item) => item.data as { revisionId?: string; tool: string; summary: string; at: string },
73
+ )
74
+ .filter((entry) => entry.revisionId)
75
+ .map((entry) => ({
76
+ revisionId: entry.revisionId as string,
77
+ tool: entry.tool,
78
+ summary: entry.summary,
79
+ at: entry.at,
80
+ }));
81
+ return { versions };
82
+ },
83
+ };
84
+
85
+ const SaveInput = z.object({ settings: AgentSettings, revision: z.string().nullable() });
86
+
87
+ /** Saves the agent settings (compare-and-set). Admins only; no MCP tool can reach this. */
88
+ export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
89
+ permission: "plugins:manage",
90
+ input: SaveInput,
91
+ handler: async (ctx) => {
92
+ const write = await ctx.kv.compareAndSet(
93
+ AGENT_SETTINGS_KEY,
94
+ ctx.input.revision,
95
+ ctx.input.settings,
96
+ );
97
+ if (!write.applied) {
98
+ throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
99
+ }
100
+ const at = new Date().toISOString();
101
+ const s = ctx.input.settings;
102
+ await agentLog(ctx).put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
103
+ at,
104
+ target: "settings",
105
+ tool: "settings",
106
+ userId: ctx.user?.id ?? null,
107
+ summary: `Agent settings: access ${s.mcpEnabled ? "on" : "off"}, publish pages ${s.publishPages ? "on" : "off"}, publish styles ${s.publishStyles ? "on" : "off"}`,
108
+ });
109
+ return { revision: write.revision };
110
+ },
111
+ };
112
+
113
+ const OWNED = new Set([PAGES_COLLECTION, THEME_PARTS_COLLECTION]);
114
+
115
+ /**
116
+ * D-055: refuse publishing EmVB content through EmDash's own MCP tools (e.g. `content_publish`)
117
+ * unless the admin let agents publish pages. Our `publish_page` tool publishes with a plugin
118
+ * origin after its own settings check.
119
+ */
120
+ export async function beforePublish(
121
+ event: ContentPolicyEvent,
122
+ ctx: PluginContext,
123
+ ): Promise<ContentPolicyDecision> {
124
+ if (!OWNED.has(event.collection)) return undefined;
125
+ const source = event.origin.source === "mcp" || event.actor?.source === "mcp";
126
+ if (!source) return undefined;
127
+ const { settings } = await readAgentSettings(ctx);
128
+ if (settings.mcpEnabled && settings.publishPages) return undefined;
129
+ return {
130
+ cancel: true,
131
+ reason:
132
+ "Agents may not publish EmVB pages on this site. An admin can allow it in Pages VisualBuilder → AI agents.",
133
+ };
134
+ }
@@ -27,7 +27,10 @@ type DesignResponse = {
27
27
  status: "ok" | "empty" | "unreadable";
28
28
  };
29
29
 
30
- const readDesign = async (ctx: RouteContext<unknown>, key: string): Promise<DesignResponse> => {
30
+ export const readDesign = async (
31
+ ctx: RouteContext<unknown>,
32
+ key: string,
33
+ ): Promise<DesignResponse> => {
31
34
  const current = await store(ctx).getVersioned(key);
32
35
  if (!current) return { design: emptyDesign(), revision: null, status: "empty" };
33
36
  const result = validateDesign(current.value);
@@ -49,15 +52,18 @@ export const designDraftRoute: PluginRoute = {
49
52
  const published = await readDesign(ctx, DESIGN_KEY);
50
53
  const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
51
54
  if (draft.status !== "ok") {
55
+ const revision = draft.revision;
52
56
  return {
53
57
  design: published.design,
54
- revision: null,
58
+ published: published.design,
59
+ revision,
55
60
  publishedRevision: published.revision,
56
61
  unpublished: false,
57
62
  };
58
63
  }
59
64
  return {
60
65
  design: draft.design,
66
+ published: published.design,
61
67
  revision: draft.revision,
62
68
  publishedRevision: published.revision,
63
69
  unpublished: JSON.stringify(draft.design) !== JSON.stringify(published.design),
@@ -85,20 +91,62 @@ export const designSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
85
91
  const summary = summarizeIssues(result.issues);
86
92
  throw new PluginRouteError("INVALID_DESIGN", `The design system is invalid. ${summary}`, 422);
87
93
  }
88
- const write = await store(ctx).compareAndSet(
89
- DESIGN_DRAFT_KEY,
90
- ctx.input.revision,
91
- result.design,
92
- );
93
- if (!write.applied) {
94
+ const write = await writeDesignDraft(ctx, result.design, ctx.input.revision, "editor");
95
+ if (!write) {
94
96
  throw PluginRouteError.conflict(
95
97
  "The design system was changed somewhere else. Reload it and try again.",
96
98
  );
97
99
  }
98
- return { revision: write.revision };
100
+ return { revision: write };
99
101
  },
100
102
  };
101
103
 
104
+ /** Keep the last 50 style drafts and publishes (D-057), newest first by key. */
105
+ const DESIGN_HISTORY_LIMIT = 50;
106
+
107
+ type HistoryStore = {
108
+ put(id: string, data: unknown): Promise<void>;
109
+ query(o: { orderBy: Record<string, "asc" | "desc">; limit: number; cursor?: string }): Promise<{
110
+ items: { id: string; data: unknown }[];
111
+ }>;
112
+ deleteMany(ids: string[]): Promise<number>;
113
+ };
114
+
115
+ /** Records a style draft or publish in the design history, then trims it to the limit. */
116
+ async function recordDesign(
117
+ ctx: RouteContext<unknown>,
118
+ design: DesignSystem,
119
+ kind: "draft" | "publish",
120
+ by: "editor" | "agent",
121
+ ) {
122
+ const history = ctx.storage["designhistory"] as unknown as HistoryStore | undefined;
123
+ if (!history) return;
124
+ const at = new Date().toISOString();
125
+ await history.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
126
+ at,
127
+ kind,
128
+ by,
129
+ userId: ctx.user?.id ?? null,
130
+ design,
131
+ });
132
+ const old = await history.query({ orderBy: { at: "desc" }, limit: 100 });
133
+ const extra = old.items.slice(DESIGN_HISTORY_LIMIT).map((item) => item.id);
134
+ if (extra.length > 0) await history.deleteMany(extra);
135
+ }
136
+
137
+ /** Compare-and-set of the style draft, recorded in the history. The new revision, or null on conflict. */
138
+ export async function writeDesignDraft(
139
+ ctx: RouteContext<unknown>,
140
+ design: DesignSystem,
141
+ expectedRevision: string | null,
142
+ by: "editor" | "agent",
143
+ ): Promise<string | null> {
144
+ const write = await store(ctx).compareAndSet(DESIGN_DRAFT_KEY, expectedRevision, design);
145
+ if (!write.applied) return null;
146
+ await recordDesign(ctx, design, "draft", by);
147
+ return write.revision;
148
+ }
149
+
102
150
  const PublishInput = z.object({ publishedRevision: z.string().nullable() });
103
151
 
104
152
  /** Copies the style draft onto the published design. Pages are not republished (W-100). */
@@ -106,20 +154,29 @@ export const designPublishRoute: PluginRoute<z.infer<typeof PublishInput>> = {
106
154
  permission: "content:edit_any",
107
155
  input: PublishInput,
108
156
  handler: async (ctx) => {
109
- const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
110
- if (draft.status !== "ok") {
157
+ const result = await publishDesignDraft(ctx, ctx.input.publishedRevision, "editor");
158
+ if (result === "no-draft") {
111
159
  throw new PluginRouteError("NO_STYLE_DRAFT", "There are no style changes to publish.", 409);
112
160
  }
113
- const write = await store(ctx).compareAndSet(
114
- DESIGN_KEY,
115
- ctx.input.publishedRevision,
116
- draft.design,
117
- );
118
- if (!write.applied) {
161
+ if (result === "conflict") {
119
162
  throw PluginRouteError.conflict(
120
163
  "Site styles were published somewhere else. Reload the editor and try again.",
121
164
  );
122
165
  }
123
- return { revision: write.revision };
166
+ return { revision: result.revision };
124
167
  },
125
168
  };
169
+
170
+ /** Copies the style draft onto the published design (compare-and-set) and records it. */
171
+ export async function publishDesignDraft(
172
+ ctx: RouteContext<unknown>,
173
+ expectedPublishedRevision: string | null,
174
+ by: "editor" | "agent",
175
+ ): Promise<"no-draft" | "conflict" | { revision: string }> {
176
+ const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
177
+ if (draft.status !== "ok") return "no-draft";
178
+ const write = await store(ctx).compareAndSet(DESIGN_KEY, expectedPublishedRevision, draft.design);
179
+ if (!write.applied) return "conflict";
180
+ await recordDesign(ctx, draft.design, "publish", by);
181
+ return { revision: write.revision };
182
+ }
@@ -2,6 +2,8 @@ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
2
  import { z } from "zod";
3
3
  import {
4
4
  prepareUploadedSvg,
5
+ sanitizeSvgMarkup,
6
+ serialize,
5
7
  UPLOAD_SVG_MAX_BYTES,
6
8
  type UploadedIcon,
7
9
  type UploadedIconItem,
@@ -15,7 +17,9 @@ import {
15
17
  */
16
18
 
17
19
  type IconStore = {
20
+ get(id: string): Promise<UploadedIcon | null>;
18
21
  put(id: string, data: UploadedIcon): Promise<void>;
22
+ delete(id: string): Promise<boolean>;
19
23
  query(options?: {
20
24
  orderBy?: Record<string, "asc" | "desc">;
21
25
  limit?: number;
@@ -27,7 +31,31 @@ const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as
27
31
  /** The most recent uploads the picker lists. */
28
32
  const UPLOAD_LIST_LIMIT = 100;
29
33
 
30
- /** Editors and above: the uploaded icons, newest first. */
34
+ /** A file name without its folder or extension, as the icon's label. */
35
+ export const uploadName = (name: string) =>
36
+ name
37
+ .replace(/^.*[\\/]/, "")
38
+ .replace(/\.svg$/i, "")
39
+ .trim()
40
+ .slice(0, 80) || "Uploaded icon";
41
+
42
+ /**
43
+ * One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
44
+ * is left out, so a row written past the upload route cannot carry a script into the picker.
45
+ */
46
+ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIconItem | undefined {
47
+ if (typeof data.svg !== "string") return undefined;
48
+ const tree = sanitizeSvgMarkup(data.svg);
49
+ if (!tree) return undefined;
50
+ return {
51
+ id,
52
+ name: uploadName(typeof data.name === "string" ? data.name : ""),
53
+ svg: serialize(tree),
54
+ uploadedAt: typeof data.uploadedAt === "string" ? data.uploadedAt : "",
55
+ };
56
+ }
57
+
58
+ /** Editors and above: the uploaded icons, newest first. A row that fails the allowlist is omitted. */
31
59
  export const iconsRoute: PluginRoute = {
32
60
  permission: "content:edit_any",
33
61
  handler: async (ctx) => {
@@ -35,25 +63,14 @@ export const iconsRoute: PluginRoute = {
35
63
  orderBy: { uploadedAt: "desc" },
36
64
  limit: UPLOAD_LIST_LIMIT,
37
65
  });
38
- // Only the known fields, whatever else a stored row might carry.
39
- const items: UploadedIconItem[] = page.items.map(({ id, data }) => ({
40
- id,
41
- name: data.name,
42
- svg: data.svg,
43
- uploadedAt: data.uploadedAt,
44
- }));
66
+ const items = page.items.flatMap(({ id, data }) => {
67
+ const item = publicUploadedIcon(id, data);
68
+ return item ? [item] : [];
69
+ });
45
70
  return { items };
46
71
  },
47
72
  };
48
73
 
49
- /** A file name without its folder or extension, as the icon's label. */
50
- export const uploadName = (name: string) =>
51
- name
52
- .replace(/^.*[\\/]/, "")
53
- .replace(/\.svg$/i, "")
54
- .trim()
55
- .slice(0, 80) || "Uploaded icon";
56
-
57
74
  const UploadInput = z.object({
58
75
  name: z.string().max(255),
59
76
  // A JSON string: the file plus escaping room is still bounded by the route body limit.
@@ -77,3 +94,42 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
77
94
  return { item: { id, ...item }, imagesLeftOut: prepared.imagesLeftOut };
78
95
  },
79
96
  };
97
+
98
+ const IdInput = z.object({
99
+ id: z.string().regex(/^[0-9a-f]{16}$/, "Unknown icon"),
100
+ });
101
+
102
+ const RenameInput = IdInput.extend({
103
+ name: z.string().min(1).max(255),
104
+ });
105
+
106
+ /** Editors and above. Renames an upload. Pages keep the SVG they already stored. */
107
+ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
108
+ permission: "content:edit_any",
109
+ input: RenameInput,
110
+ handler: async (ctx) => {
111
+ const current = await store(ctx).get(ctx.input.id);
112
+ if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
113
+ const name = uploadName(ctx.input.name);
114
+ // W-390: answer with the same checked markup the list sends; a row that fails the
115
+ // allowlist is not renamed or echoed back.
116
+ const item = publicUploadedIcon(ctx.input.id, { ...current, name });
117
+ if (!item) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
118
+ await store(ctx).put(ctx.input.id, { ...current, name });
119
+ return { item };
120
+ },
121
+ };
122
+
123
+ /**
124
+ * Editors and above. Removes an upload from My uploads. Icons already placed on a page keep
125
+ * their own copy of the SVG, so those pages do not change.
126
+ */
127
+ export const iconDeleteRoute: PluginRoute<z.infer<typeof IdInput>> = {
128
+ permission: "content:edit_any",
129
+ input: IdInput,
130
+ handler: async (ctx) => {
131
+ const removed = await store(ctx).delete(ctx.input.id);
132
+ if (!removed) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
133
+ return { id: ctx.input.id };
134
+ },
135
+ };
@@ -0,0 +1,265 @@
1
+ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
3
+ import { McpToolError } from "../mcp/errors.ts";
4
+ import type { EmvbPorts, PageRecord, PageSummary } from "../mcp/ports.ts";
5
+ import { callerKey, hitRateLimit, type RateStore } from "../mcp/rate-limit.ts";
6
+ import { runTool, type ToolDef } from "../mcp/tools.ts";
7
+ import { publishDesignDraft, readDesign, writeDesignDraft } from "./design-routes.ts";
8
+ import { readAgentSettings } from "./agent-settings.ts";
9
+
10
+ type Item = {
11
+ id: string;
12
+ slug: string | null;
13
+ status: string;
14
+ data: Record<string, unknown>;
15
+ updatedAt: string;
16
+ publishedAt: string | null;
17
+ draftRevisionId?: string | null;
18
+ liveRevisionId?: string | null;
19
+ };
20
+
21
+ type Content = {
22
+ list(
23
+ c: string,
24
+ o: { limit?: number; cursor?: string },
25
+ ): Promise<{
26
+ items: Item[];
27
+ cursor?: string;
28
+ hasMore: boolean;
29
+ }>;
30
+ getVersioned?(c: string, id: string): Promise<{ item: Item; _rev: string } | null>;
31
+ listRevisions?(
32
+ c: string,
33
+ id: string,
34
+ o: { limit?: number },
35
+ ): Promise<{ id: string; createdAt: string; authorId?: string | null }[]>;
36
+ getRevision?(
37
+ c: string,
38
+ id: string,
39
+ revisionId: string,
40
+ ): Promise<{ data: Record<string, unknown> } | null>;
41
+ update(c: string, id: string, data: Record<string, unknown>): Promise<Item>;
42
+ create(c: string, data: Record<string, unknown>): Promise<Item>;
43
+ publish?(c: string, id: string, o: { _rev: string }): Promise<unknown>;
44
+ };
45
+
46
+ type LogStore = { put(id: string, data: unknown): Promise<void> };
47
+
48
+ const parseJson = (raw: unknown) => {
49
+ if (typeof raw !== "string") return raw;
50
+ try {
51
+ return JSON.parse(raw) as unknown;
52
+ } catch {
53
+ return raw;
54
+ }
55
+ };
56
+
57
+ const summary = (item: Item): PageSummary => ({
58
+ id: item.id,
59
+ title: typeof item.data["title"] === "string" ? item.data["title"] : "Untitled page",
60
+ slug: item.slug ?? "",
61
+ status: item.status,
62
+ hasDraft: Boolean(item.draftRevisionId && item.draftRevisionId !== item.liveRevisionId),
63
+ updatedAt: item.updatedAt,
64
+ });
65
+
66
+ /** The tool core's ports on a plugin route (D-053, R1 save path). */
67
+ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
68
+ const content = ctx.content as unknown as Content | undefined;
69
+ if (!content) throw new McpToolError("FORBIDDEN", "EmVB has no content access on this site.");
70
+ const versioned = (id: string) =>
71
+ content.getVersioned ? content.getVersioned(PAGES_COLLECTION, id) : Promise.resolve(null);
72
+ return {
73
+ caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
74
+ async rateLimit(cls) {
75
+ await hitRateLimit(
76
+ ctx.kv as unknown as RateStore,
77
+ await callerKey(ctx.request, ctx.user?.id ?? null),
78
+ cls,
79
+ );
80
+ },
81
+ async listPages({ cursor, limit }) {
82
+ let result: Awaited<ReturnType<Content["list"]>>;
83
+ try {
84
+ result = await content.list(PAGES_COLLECTION, { limit, ...(cursor ? { cursor } : {}) });
85
+ } catch (error) {
86
+ // W-474: a cursor the agent made up or truncated was an INTERNAL_ERROR.
87
+ if (cursor && /cursor/i.test(String((error as Error)?.message ?? error))) {
88
+ throw new McpToolError(
89
+ "INVALID_INPUT",
90
+ "That cursor isn't valid. Pass nextCursor exactly as list_pages returned it, or leave it out to start again.",
91
+ );
92
+ }
93
+ throw error;
94
+ }
95
+ return {
96
+ pages: result.items.map(summary),
97
+ ...(result.hasMore && result.cursor ? { nextCursor: result.cursor } : {}),
98
+ };
99
+ },
100
+ async getPage(id): Promise<PageRecord | null> {
101
+ const found = content.getVersioned ? await content.getVersioned(PAGES_COLLECTION, id) : null;
102
+ if (!found) return null;
103
+ return {
104
+ ...summary(found.item),
105
+ layout: parseJson(found.item.data["layout"]),
106
+ rev: found["_rev"],
107
+ };
108
+ },
109
+ async listRevisions(id, limit) {
110
+ const list = content.listRevisions
111
+ ? await content.listRevisions(PAGES_COLLECTION, id, { limit })
112
+ : [];
113
+ return list.map((r) => ({ id: r.id, createdAt: r.createdAt, authorId: r.authorId ?? null }));
114
+ },
115
+ async getRevisionData(id, revisionId) {
116
+ const revision = content.getRevision
117
+ ? await content.getRevision(PAGES_COLLECTION, id, revisionId)
118
+ : null;
119
+ return revision?.data ?? null;
120
+ },
121
+ async savePage(id, patch, expectedRev) {
122
+ const current = await versioned(id);
123
+ if (!current) throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
124
+ if (current["_rev"] !== expectedRev) {
125
+ throw new McpToolError("CONFLICT", "The page changed since it was read.", {
126
+ rev: current["_rev"],
127
+ });
128
+ }
129
+ await content.update(PAGES_COLLECTION, id, {
130
+ ...(patch.layout ? { layout: patch.layout } : {}),
131
+ ...(patch.title ? { title: patch.title } : {}),
132
+ });
133
+ const after = await versioned(id);
134
+ return {
135
+ rev: after?.["_rev"] ?? "",
136
+ ...(after?.item.draftRevisionId ? { revisionId: after.item.draftRevisionId } : {}),
137
+ };
138
+ },
139
+ async createPage({ title, layout }) {
140
+ // Plugins can't choose a slug on create; EmDash derives it from the title.
141
+ const item = await content.create(PAGES_COLLECTION, { title, layout });
142
+ const after = await versioned(item.id);
143
+ return { id: item.id, slug: String(item.slug ?? ""), rev: after?.["_rev"] ?? "" };
144
+ },
145
+ async saveDesign(design, expectedRevision) {
146
+ const written = await writeDesignDraft(ctx, design, expectedRevision, "agent");
147
+ if (!written) throw new McpToolError("CONFLICT", "Site styles changed since they were read.");
148
+ return { revision: written };
149
+ },
150
+ async log(entry) {
151
+ const at = new Date().toISOString();
152
+ const store = ctx.storage["agentlog"] as unknown as LogStore;
153
+ await store.put(`${at}-${crypto.randomUUID().slice(0, 8)}`, {
154
+ ...entry,
155
+ at,
156
+ userId: ctx.user?.id ?? null,
157
+ client: (ctx.request.headers.get("user-agent") ?? "").slice(0, 120),
158
+ });
159
+ },
160
+ settings: async () => (await readAgentSettings(ctx)).settings,
161
+ async publishPage(id, expectedRev) {
162
+ if (!content.publish)
163
+ throw new McpToolError("FORBIDDEN", "This site can't publish from plugins.");
164
+ try {
165
+ await content.publish(PAGES_COLLECTION, id, { _rev: expectedRev });
166
+ } catch (error) {
167
+ const code = (error as { code?: string }).code ?? "";
168
+ if (/CONFLICT|REV/i.test(code)) {
169
+ throw new McpToolError(
170
+ "CONFLICT",
171
+ "The page changed since you read it. Call get_layout again.",
172
+ );
173
+ }
174
+ if (/NOT_FOUND/i.test(code))
175
+ throw new McpToolError("NOT_FOUND", `No EmVB page with id ${id}.`);
176
+ throw error;
177
+ }
178
+ const after = await versioned(id);
179
+ return { rev: after?.["_rev"] ?? "" };
180
+ },
181
+ async publishDesign(expectedPublishedRevision) {
182
+ const result = await publishDesignDraft(ctx, expectedPublishedRevision, "agent");
183
+ if (result === "no-draft")
184
+ throw new McpToolError("REFUSED", "There are no style changes to publish.");
185
+ if (result === "conflict") {
186
+ throw new McpToolError(
187
+ "CONFLICT",
188
+ "Site styles were published somewhere else. Call get_site_styles again.",
189
+ );
190
+ }
191
+ return { revision: result.revision };
192
+ },
193
+ async getDesign() {
194
+ const published = await readDesign(ctx, DESIGN_KEY);
195
+ const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
196
+ if (draft.status !== "ok") {
197
+ return {
198
+ design: published.design,
199
+ revision: draft.revision,
200
+ publishedRevision: published.revision,
201
+ unpublished: false,
202
+ };
203
+ }
204
+ return {
205
+ design: draft.design,
206
+ revision: draft.revision,
207
+ publishedRevision: published.revision,
208
+ unpublished: JSON.stringify(draft.design) !== JSON.stringify(published.design),
209
+ };
210
+ },
211
+ };
212
+ }
213
+
214
+ /** W-474: before "Set up EmVB" there is no `emvb_pages` table, and every page tool was an INTERNAL_ERROR. */
215
+ export const NOT_SET_UP_MESSAGE =
216
+ 'EmVB isn\'t set up on this site yet. Ask an admin to open Pages VisualBuilder in the EmDash admin and click "Set up EmVB", then try again.';
217
+
218
+ export const isNotSetUp = (error: unknown) =>
219
+ /no such table:?\s*\W?ec_emvb_|relation "?ec_emvb_\w+"? does not exist|collection "?emvb_(pages|theme_parts)"? (not found|does not exist)/i.test(
220
+ String((error as Error)?.message ?? error),
221
+ );
222
+
223
+ /** Routes `mcp/<tool>`: editors and above (D-056), POST JSON, one per tool (R1 D-054). */
224
+ export function mcpRoutes(tools: readonly ToolDef[]): Record<string, PluginRoute> {
225
+ return Object.fromEntries(
226
+ tools.map((tool) => [
227
+ `mcp/${tool.name}`,
228
+ {
229
+ permission: "content:edit_any",
230
+ input: tool.input,
231
+ handler: async (ctx: RouteContext<unknown>) => {
232
+ try {
233
+ return await runTool(tool, pluginPorts(ctx), ctx.input);
234
+ } catch (error) {
235
+ if (error instanceof McpToolError) {
236
+ throw new PluginRouteError(error.code, error.message, error.status, error.details);
237
+ }
238
+ if (isNotSetUp(error)) {
239
+ throw new PluginRouteError("NOT_SET_UP", NOT_SET_UP_MESSAGE, 409);
240
+ }
241
+ throw error;
242
+ }
243
+ },
244
+ } satisfies PluginRoute,
245
+ ]),
246
+ );
247
+ }
248
+
249
+ /** `definePlugin({ mcp })`: EmDash lists these on /_emdash/api/mcp as `emvb__<name>`. */
250
+ export function mcpToolConfig(tools: readonly ToolDef[]) {
251
+ return {
252
+ tools: Object.fromEntries(
253
+ tools.map((tool) => [
254
+ tool.name,
255
+ {
256
+ description: tool.description,
257
+ route: `mcp/${tool.name}`,
258
+ input: tool.input,
259
+ output: tool.output,
260
+ destructive: tool.destructive,
261
+ },
262
+ ]),
263
+ ),
264
+ };
265
+ }