@perkyzz/emvb 0.6.0 → 0.8.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 (208) hide show
  1. package/README.md +2 -2
  2. package/THIRD_PARTY_NOTICES.md +1 -1
  3. package/package.json +7 -7
  4. package/src/admin/access/RequireEditor.tsx +7 -7
  5. package/src/admin/access/role.ts +5 -2
  6. package/src/admin/content-api.ts +10 -3
  7. package/src/admin/content-item.ts +1 -1
  8. package/src/admin/editor/A11yCopilot.tsx +104 -56
  9. package/src/admin/editor/CommandPalette.tsx +29 -13
  10. package/src/admin/editor/DialogCloseButton.tsx +16 -0
  11. package/src/admin/editor/Editor.tsx +115 -20
  12. package/src/admin/editor/EditorToasts.tsx +26 -0
  13. package/src/admin/editor/PerfMeter.tsx +92 -73
  14. package/src/admin/editor/SavedSectionDialogs.tsx +169 -0
  15. package/src/admin/editor/ShareLink.tsx +102 -72
  16. package/src/admin/editor/ShortcutsDialog.tsx +37 -18
  17. package/src/admin/editor/Timeline.tsx +250 -160
  18. package/src/admin/editor/TopBar.tsx +71 -14
  19. package/src/admin/editor/canvas/CanvasFrame.tsx +10 -1
  20. package/src/admin/editor/canvas/CanvasTextEdit.tsx +8 -2
  21. package/src/admin/editor/canvas/drop-line.ts +11 -3
  22. package/src/admin/editor/canvas/frame-focus-ring.ts +37 -0
  23. package/src/admin/editor/canvas/use-canvas-dnd.ts +32 -3
  24. package/src/admin/editor/canvas/vnode-react.tsx +7 -0
  25. package/src/admin/editor/collection-previews.ts +10 -0
  26. package/src/admin/editor/dialogs.tsx +41 -28
  27. package/src/admin/editor/dnd/drop-target.ts +26 -1
  28. package/src/admin/editor/edited-noun.ts +15 -0
  29. package/src/admin/editor/editor-chrome.tsx +43 -7
  30. package/src/admin/editor/editor-commands.ts +17 -2
  31. package/src/admin/editor/editor-css.ts +75 -24
  32. package/src/admin/editor/element-chrome.ts +21 -11
  33. package/src/admin/editor/feature-css.ts +56 -14
  34. package/src/admin/editor/focus-when-lost.ts +23 -0
  35. package/src/admin/editor/icons/IconLibraryDialog.tsx +54 -18
  36. package/src/admin/editor/icons/library.ts +1 -1
  37. package/src/admin/editor/icons/use-icon-library.ts +5 -2
  38. package/src/admin/editor/ime.ts +29 -0
  39. package/src/admin/editor/palette-items.ts +27 -3
  40. package/src/admin/editor/panels/AddPanel.tsx +44 -11
  41. package/src/admin/editor/panels/ClassesSection.tsx +18 -7
  42. package/src/admin/editor/panels/ColorControl.tsx +130 -23
  43. package/src/admin/editor/panels/ConditionsEditor.tsx +52 -26
  44. package/src/admin/editor/panels/ElementPanel.tsx +134 -24
  45. package/src/admin/editor/panels/LayersPanel.tsx +61 -20
  46. package/src/admin/editor/panels/LeftPanel.tsx +9 -1
  47. package/src/admin/editor/panels/PageSettings.tsx +66 -35
  48. package/src/admin/editor/panels/SavedSectionsGroup.tsx +246 -0
  49. package/src/admin/editor/panels/SiteStylesDrawer.tsx +224 -42
  50. package/src/admin/editor/panels/TokenScales.tsx +88 -48
  51. package/src/admin/editor/panels/TriggerSettings.tsx +50 -12
  52. package/src/admin/editor/panels/TriggersEditor.tsx +3 -2
  53. package/src/admin/editor/panels/VariableSection.tsx +48 -18
  54. package/src/admin/editor/panels/color-space.ts +23 -29
  55. package/src/admin/editor/panels/settings/AdvancedFields.tsx +12 -2
  56. package/src/admin/editor/panels/settings/AudienceEditor.tsx +87 -74
  57. package/src/admin/editor/panels/settings/BackgroundControls.tsx +55 -11
  58. package/src/admin/editor/panels/settings/BackgroundFill.tsx +3 -2
  59. package/src/admin/editor/panels/settings/BindingsEditor.tsx +15 -18
  60. package/src/admin/editor/panels/settings/BoxControl.tsx +2 -1
  61. package/src/admin/editor/panels/settings/ClassChip.tsx +21 -9
  62. package/src/admin/editor/panels/settings/ClassChipInput.tsx +24 -16
  63. package/src/admin/editor/panels/settings/DraftTextField.tsx +41 -3
  64. package/src/admin/editor/panels/settings/EffectsControls.tsx +38 -14
  65. package/src/admin/editor/panels/settings/FieldBindControl.tsx +46 -28
  66. package/src/admin/editor/panels/settings/FieldControl.tsx +20 -8
  67. package/src/admin/editor/panels/settings/FormBindControl.tsx +2 -2
  68. package/src/admin/editor/panels/settings/HintedSwitch.tsx +33 -0
  69. package/src/admin/editor/panels/settings/IconControls.tsx +33 -13
  70. package/src/admin/editor/panels/settings/IconPicker.tsx +2 -0
  71. package/src/admin/editor/panels/settings/ImageSourcesField.tsx +3 -1
  72. package/src/admin/editor/panels/settings/ItemList.tsx +15 -2
  73. package/src/admin/editor/panels/settings/LengthRow.tsx +8 -6
  74. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +1 -1
  75. package/src/admin/editor/panels/settings/MediaPicker.tsx +127 -23
  76. package/src/admin/editor/panels/settings/MotionControl.tsx +28 -15
  77. package/src/admin/editor/panels/settings/NumberRow.tsx +9 -3
  78. package/src/admin/editor/panels/settings/PanelSelect.tsx +50 -0
  79. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +25 -18
  80. package/src/admin/editor/panels/settings/RequiredFieldsNotice.tsx +66 -1
  81. package/src/admin/editor/panels/settings/StyleRow.tsx +10 -3
  82. package/src/admin/editor/panels/settings/StyleSources.tsx +4 -1
  83. package/src/admin/editor/panels/settings/VariantEditor.tsx +10 -1
  84. package/src/admin/editor/panels/settings/box-link-name.ts +6 -2
  85. package/src/admin/editor/panels/settings/class-suggest.ts +7 -7
  86. package/src/admin/editor/panels/settings/query-style.ts +38 -9
  87. package/src/admin/editor/panels/settings/svg-images.ts +13 -0
  88. package/src/admin/editor/panels/site-list.tsx +20 -6
  89. package/src/admin/editor/panels/variable-values.ts +11 -4
  90. package/src/admin/editor/restore-deleted.ts +21 -2
  91. package/src/admin/editor/section-templates.ts +81 -12
  92. package/src/admin/editor/shortcuts.ts +31 -2
  93. package/src/admin/editor/store.ts +7 -0
  94. package/src/admin/editor/useEditorCommands.ts +61 -15
  95. package/src/admin/editor/useEditorData.ts +4 -2
  96. package/src/admin/editor/useEditorShortcuts.ts +17 -7
  97. package/src/admin/editor/useNodeActions.ts +61 -6
  98. package/src/admin/editor/useSave.ts +22 -7
  99. package/src/admin/editor/useSavedSections.ts +197 -0
  100. package/src/admin/forms-api.ts +2 -0
  101. package/src/admin/image-editor/Canvas.tsx +61 -17
  102. package/src/admin/image-editor/CurvesPanel.tsx +2 -1
  103. package/src/admin/image-editor/ExportDialog.tsx +48 -18
  104. package/src/admin/image-editor/ImageEditorDialog.tsx +179 -8
  105. package/src/admin/image-editor/MetadataPanel.tsx +15 -4
  106. package/src/admin/image-editor/crop-geometry.ts +3 -2
  107. package/src/admin/image-editor/image-editor-css.ts +15 -10
  108. package/src/admin/image-editor/load.ts +9 -2
  109. package/src/admin/image-editor/parts.tsx +69 -19
  110. package/src/admin/image-editor/save.ts +54 -8
  111. package/src/admin/media-api.ts +2 -1
  112. package/src/admin/pages/AgentsPage.tsx +138 -27
  113. package/src/admin/pages/CreateDialog.tsx +97 -30
  114. package/src/admin/pages/NewPageDialog.tsx +21 -3
  115. package/src/admin/pages/NewThemePartDialog.tsx +11 -3
  116. package/src/admin/pages/PageList.tsx +14 -6
  117. package/src/admin/pages/SetupShell.tsx +28 -12
  118. package/src/admin/pages/ThemePartList.tsx +59 -11
  119. package/src/admin/pages/list-kit.tsx +106 -24
  120. package/src/admin/saved-sections-api.ts +51 -0
  121. package/src/admin/search.ts +15 -0
  122. package/src/admin/setup/useSetupStatus.ts +1 -1
  123. package/src/admin/theme-api.ts +16 -5
  124. package/src/admin/ui.ts +82 -22
  125. package/src/astro/floats/runtime.ts +21 -0
  126. package/src/astro/menu/runtime.ts +34 -1
  127. package/src/astro/popups/runtime.ts +41 -9
  128. package/src/astro/render.ts +3 -0
  129. package/src/astro/resolve-theme.ts +53 -11
  130. package/src/astro/resolve.ts +9 -1
  131. package/src/astro/tabs/runtime.ts +12 -0
  132. package/src/astro/theme-posts.ts +2 -2
  133. package/src/astro/visitor.ts +2 -0
  134. package/src/constants.ts +1 -1
  135. package/src/core/a11y/audit.ts +196 -24
  136. package/src/core/arrange.ts +48 -12
  137. package/src/core/audience/rules.ts +5 -1
  138. package/src/core/audience/variants.ts +29 -3
  139. package/src/core/clipboard.ts +7 -0
  140. package/src/core/css/generate.ts +31 -6
  141. package/src/core/css/print.ts +5 -0
  142. package/src/core/data/bindings.ts +8 -1
  143. package/src/core/design/classes.ts +39 -16
  144. package/src/core/design/devices.ts +7 -13
  145. package/src/core/design/diff.ts +6 -0
  146. package/src/core/design/merge.ts +90 -2
  147. package/src/core/design/states.ts +7 -13
  148. package/src/core/design/tokens.ts +16 -2
  149. package/src/core/design/transfer.ts +33 -6
  150. package/src/core/design/variables.ts +30 -9
  151. package/src/core/elements/dynamic-elements.ts +53 -14
  152. package/src/core/elements/form-elements.ts +55 -16
  153. package/src/core/elements/index.ts +84 -39
  154. package/src/core/elements/menu.ts +40 -19
  155. package/src/core/elements/select-prompt.ts +3 -0
  156. package/src/core/elements/svg-ids.ts +39 -0
  157. package/src/core/forms/binding.ts +57 -16
  158. package/src/core/forms/definition.ts +72 -0
  159. package/src/core/history/diff.ts +18 -1
  160. package/src/core/icons/animation-runs.ts +11 -0
  161. package/src/core/icons/catalog.ts +3 -2
  162. package/src/core/image-edit/schema.ts +11 -1
  163. package/src/core/image-edit/summary.ts +6 -3
  164. package/src/core/index.ts +35 -1
  165. package/src/core/limits.ts +12 -1
  166. package/src/core/migrate/index.ts +3 -0
  167. package/src/core/perf/meter.ts +42 -7
  168. package/src/core/recipes/index.ts +5 -4
  169. package/src/core/render/context.ts +8 -0
  170. package/src/core/render/dynamic-post.ts +69 -12
  171. package/src/core/render/extras.ts +77 -4
  172. package/src/core/render/form.ts +140 -6
  173. package/src/core/render/index.ts +156 -20
  174. package/src/core/render/loop.ts +44 -8
  175. package/src/core/render/pagination.ts +18 -4
  176. package/src/core/render/section.ts +27 -0
  177. package/src/core/render/tabs.ts +12 -3
  178. package/src/core/render/vnode.ts +1 -1
  179. package/src/core/sanitize/css.ts +29 -8
  180. package/src/core/sanitize/embed-url.ts +42 -5
  181. package/src/core/sanitize/url.ts +2 -1
  182. package/src/core/saved-sections.ts +318 -0
  183. package/src/core/schema/design.ts +1 -1
  184. package/src/core/schema/layout.ts +16 -7
  185. package/src/core/schema/style.ts +4 -2
  186. package/src/core/stats.ts +2 -1
  187. package/src/core/theme/conditions.ts +3 -1
  188. package/src/core/theme/dynamic.ts +36 -5
  189. package/src/core/theme/float.ts +12 -2
  190. package/src/core/theme/pagination.ts +50 -29
  191. package/src/core/theme/part-types.ts +4 -4
  192. package/src/core/theme/popup-markup.ts +23 -5
  193. package/src/core/theme/popup-rules.ts +1 -0
  194. package/src/core/theme/triggers.ts +3 -2
  195. package/src/core/tree-ops.ts +27 -0
  196. package/src/mcp/ports.ts +22 -1
  197. package/src/mcp/rate-limit.ts +2 -1
  198. package/src/mcp/read.ts +15 -3
  199. package/src/mcp/refs.ts +18 -0
  200. package/src/mcp/sections.ts +183 -0
  201. package/src/mcp/tools.ts +44 -0
  202. package/src/mcp/write.ts +178 -14
  203. package/src/server/agent-settings.ts +1 -1
  204. package/src/server/hooks.ts +5 -3
  205. package/src/server/icon-routes.ts +30 -9
  206. package/src/server/mcp-routes.ts +8 -1
  207. package/src/server/plugin.ts +14 -0
  208. package/src/server/saved-sections.ts +163 -0
package/src/mcp/write.ts CHANGED
@@ -4,6 +4,7 @@ import {
4
4
  defaultElement,
5
5
  findNode,
6
6
  MAX_LAYOUT_BYTES,
7
+ nameKey,
7
8
  nestingIssues,
8
9
  recipeNode,
9
10
  SECTION_RECIPES,
@@ -15,23 +16,28 @@ import {
15
16
  type Layout,
16
17
  type LayoutNode,
17
18
  } from "../core/index.ts";
19
+ import { stableJson } from "../core/stable-json.ts";
18
20
  import { addNode, moveNode, withFreshIds } from "../core/arrange.ts";
19
21
  import { ELEMENT_DESCRIPTORS } from "../core/elements/index.ts";
20
- import { nodeChildren, removeNode, slugify, starterLayout, updateNode } from "../core/tree-ops.ts";
22
+ import { nodeChildren, pageSlug, removeNode, starterLayout, updateNode } from "../core/tree-ops.ts";
23
+ import { isSafeFontStack } from "../core/sanitize/css.ts";
21
24
  import { sanitizeMediaUrl } from "../core/sanitize/media-url.ts";
25
+ import { sanitizeHref } from "../core/sanitize/href.ts";
26
+ import { isSafeSvgMarkup } from "../core/sanitize/svg.ts";
27
+ import { clipText, MAX_DEPTH } from "../core/limits.ts";
22
28
  import { McpToolError } from "./errors.ts";
23
29
  import type { EmvbPorts } from "./ports.ts";
24
30
  import { queued } from "./queue.ts";
25
- import { resolveDesignRefs } from "./refs.ts";
31
+ import { nestsDeeperThan, resolveDesignRefs } from "./refs.ts";
26
32
  import {
27
33
  findVariableUsages,
28
34
  findVariableUsagesInDesign,
29
35
  type VariableKind,
30
36
  } from "../core/design/variables.ts";
31
37
 
32
- const PageId = z.string().min(1).max(128);
33
- const NodeIdInput = z.string().min(1).max(64);
34
- const Rev = z.string().min(1).max(256);
38
+ export const PageId = z.string().min(1).max(128);
39
+ export const NodeIdInput = z.string().min(1).max(64);
40
+ export const Rev = z.string().min(1).max(256);
35
41
 
36
42
  /** The editor's save checks, run here because plugin writes skip `content:beforeSave` (R1 P0b). */
37
43
  function checkLayout(candidate: unknown): Layout {
@@ -81,7 +87,7 @@ export const WriteOutput = z.object({
81
87
  * Read → apply → validate → save with `_rev`, one write per page at a time (D-058). Without
82
88
  * `expectedRev`, a conflict re-reads and re-applies the operation once; with it, never.
83
89
  */
84
- async function mutatePage(
90
+ export async function mutatePage(
85
91
  ports: EmvbPorts,
86
92
  tool: string,
87
93
  pageId: string,
@@ -111,7 +117,14 @@ async function mutatePage(
111
117
  }
112
118
  const next = apply(current.layout);
113
119
  refuseUnsafeImageSources(current.layout, next.layout);
120
+ refuseUnsafeLinks(current.layout, next.layout);
121
+ refuseUnsafeSvg(current.layout, next.layout);
114
122
  const layout = checkLayout(next.layout);
123
+ // W-562: a write that changes nothing (an empty set, the same value, a move to its own
124
+ // spot) saved a new version and rev anyway, cluttering the timeline and the agent log.
125
+ if (stableJson(layout) === stableJson(current.layout)) {
126
+ return { pageId, rev: page.rev, changed: [], summary: `Nothing changed (${tool})` };
127
+ }
115
128
  try {
116
129
  const saved = await ports.savePage(pageId, { layout }, page.rev);
117
130
  await ports.log({
@@ -135,12 +148,85 @@ const refused = (reason: string): never => {
135
148
  throw new McpToolError("REFUSED", reason);
136
149
  };
137
150
 
151
+ /**
152
+ * W-755: these checks run before the layout is validated, so a write that set `props` to null (or
153
+ * a list) reached them as is and failed as an internal error instead of an invalid layout.
154
+ */
155
+ const isRecord = (v: unknown): v is Record<string, unknown> =>
156
+ typeof v === "object" && v !== null && !Array.isArray(v);
157
+
158
+ const propsOf = (node: LayoutNode): Record<string, unknown> =>
159
+ isRecord(node.props) ? node.props : {};
160
+
161
+ /** Link props (the element's `href` fields) on each node, keyed by node and prop. */
162
+ function linkValues(root: LayoutNode): Map<string, string> {
163
+ const found = new Map<string, string>();
164
+ const walk = (node: LayoutNode) => {
165
+ const fields = ELEMENT_DESCRIPTORS.find((d) => d.type === node.type)?.fields ?? [];
166
+ const props = propsOf(node);
167
+ for (const field of fields) {
168
+ const value = props[field.key];
169
+ if (field.kind === "href" && typeof value === "string")
170
+ found.set(`${node.id}.${field.key}`, value);
171
+ }
172
+ for (const child of nodeChildren(node)) walk(child);
173
+ };
174
+ walk(root);
175
+ return found;
176
+ }
177
+
178
+ /**
179
+ * W-563: as W-499 for images, a `javascript:` (or other unsafe) link passed validation and the
180
+ * page published the element without it, with nothing telling the agent. Links the write adds
181
+ * or changes must pass the page's link check; ones already stored are left alone.
182
+ */
183
+ function refuseUnsafeLinks(before: Layout, after: Layout) {
184
+ const old = linkValues(before.root);
185
+ for (const [key, href] of linkValues(after.root)) {
186
+ if (href.trim() === "" || old.get(key) === href || sanitizeHref(href) !== undefined) continue;
187
+ const [id, prop] = key.split(".");
188
+ refused(
189
+ `Element ${id} has the ${prop} ${JSON.stringify(clipText(href, 80))}, which pages can't link to. Use an https:// URL, a path on this site such as /pricing, #section, mailto: or tel:.`,
190
+ );
191
+ }
192
+ }
193
+
194
+ /** SVG markup props (an SVG element's `markup`, an icon's `iconSvg`), keyed by node and prop. */
195
+ function svgValues(root: LayoutNode): Map<string, string> {
196
+ const found = new Map<string, string>();
197
+ const walk = (node: LayoutNode) => {
198
+ const props = propsOf(node);
199
+ if (node.type === "svg" && typeof props["markup"] === "string")
200
+ found.set(`${node.id}.markup`, props["markup"]);
201
+ if (typeof props["iconSvg"] === "string") found.set(`${node.id}.iconSvg`, props["iconSvg"]);
202
+ for (const child of nodeChildren(node)) walk(child);
203
+ };
204
+ walk(root);
205
+ return found;
206
+ }
207
+
208
+ /**
209
+ * W-566: SVG with an `onload` handler (or a script, foreignObject, style…) was stored as given and
210
+ * the page then rendered nothing for it, with nothing telling the agent. Markup the write adds or
211
+ * changes must pass the same check the renderer uses; ones already stored are left alone.
212
+ */
213
+ function refuseUnsafeSvg(before: Layout, after: Layout) {
214
+ const old = svgValues(before.root);
215
+ for (const [key, markup] of svgValues(after.root)) {
216
+ if (markup.trim() === "" || old.get(key) === markup || isSafeSvgMarkup(markup)) continue;
217
+ const [id, prop] = key.split(".");
218
+ refused(
219
+ `Element ${id} has ${prop} the page can't show. Use plain SVG: no scripts, event handlers such as onload, foreignObject, style blocks, links or external images.`,
220
+ );
221
+ }
222
+ }
223
+
138
224
  /** Image sources (src and srcset widths) on a node, keyed for comparison. */
139
225
  function imageSources(root: LayoutNode): Map<string, string[]> {
140
226
  const found = new Map<string, string[]>();
141
227
  const walk = (node: LayoutNode) => {
142
228
  if (node.type === "image") {
143
- const props = node.props as { src?: unknown; sources?: unknown };
229
+ const props = propsOf(node) as { src?: unknown; sources?: unknown };
144
230
  const list = typeof props.src === "string" ? [props.src] : [];
145
231
  if (Array.isArray(props.sources)) {
146
232
  for (const source of props.sources as { src?: unknown }[]) {
@@ -185,6 +271,23 @@ const ElementSpec: z.ZodType<ElementSpecT> = z.lazy(() =>
185
271
  );
186
272
  type ElementSpecT = { type: string; props?: Record<string, unknown>; children?: ElementSpecT[] };
187
273
 
274
+ /**
275
+ * W-652: the recursive spec is checked by recursion, so an element nested a few thousand levels
276
+ * overflowed the stack while the input was validated and the call failed as an internal error.
277
+ * Pages allow 24 levels of elements; anything past a generous bound is refused up front.
278
+ */
279
+ const BoundedElementSpec = z.preprocess((value, ctx) => {
280
+ if (nestsDeeperThan(value, MAX_DEPTH * 8)) {
281
+ ctx.addIssue({
282
+ code: "custom",
283
+ message: `Elements can be nested at most ${MAX_DEPTH} levels deep.`,
284
+ input: value,
285
+ });
286
+ return z.NEVER;
287
+ }
288
+ return value;
289
+ }, ElementSpec);
290
+
188
291
  function buildNode(spec: ElementSpecT): LayoutNode {
189
292
  if (!KNOWN_TYPES.has(spec.type)) {
190
293
  refused(`Unknown element type ${spec.type}. Call list_element_types.`);
@@ -237,9 +340,22 @@ function promoteHeroHeading(layout: Layout, title: string): Layout {
237
340
  );
238
341
  }
239
342
 
343
+ /** Whether any page already has this slug, paging past the first 50 (W-537, at most 1000). */
344
+ async function slugTaken(ports: EmvbPorts, slug: string): Promise<boolean> {
345
+ let cursor: string | undefined;
346
+ for (let i = 0; i < 20; i++) {
347
+ // oxlint-disable-next-line no-await-in-loop -- cursor paging is sequential
348
+ const batch = await ports.listPages({ limit: 50, ...(cursor ? { cursor } : {}) });
349
+ if (batch.pages.some((page) => page.slug === slug)) return true;
350
+ if (!batch.nextCursor) return false;
351
+ cursor = batch.nextCursor;
352
+ }
353
+ return false;
354
+ }
355
+
240
356
  export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreatePageInput>) {
241
357
  // EmDash derives the slug from the title; refuse a title whose slug is already taken.
242
- const slug = slugify(input.title);
358
+ const slug = pageSlug(input.title);
243
359
  if (!slug) refused("Give the page a title with letters or digits.");
244
360
  const { design } = await ports.getDesign();
245
361
  let layout = starterLayout(input.title);
@@ -265,8 +381,7 @@ export async function createPage(ports: EmvbPorts, input: z.infer<typeof CreateP
265
381
  }
266
382
  if (recipes[0] === "hero") layout = promoteHeroHeading(layout, input.title);
267
383
  const checked = checkLayout(layout);
268
- const taken = await ports.listPages({ limit: 50 });
269
- if (taken.pages.some((page) => page.slug === slug)) {
384
+ if (await slugTaken(ports, slug)) {
270
385
  throw new McpToolError("REFUSED", `The slug "${slug}" is taken. Choose another title.`);
271
386
  }
272
387
  const created = await ports.createPage({ title: input.title, layout: checked });
@@ -286,7 +401,7 @@ export const AddElementInput = z.strictObject({
286
401
  pageId: PageId,
287
402
  parentId: NodeIdInput,
288
403
  index: z.number().int().min(0).optional(),
289
- element: ElementSpec,
404
+ element: BoundedElementSpec,
290
405
  expectedRev: Rev.optional(),
291
406
  });
292
407
 
@@ -360,9 +475,6 @@ export const UpdateElementInput = z.strictObject({
360
475
  expectedRev: Rev.optional(),
361
476
  });
362
477
 
363
- const isRecord = (v: unknown): v is Record<string, unknown> =>
364
- typeof v === "object" && v !== null && !Array.isArray(v);
365
-
366
478
  /**
367
479
  * W-510: a new `src` merged into an image's props kept the old picture's extra sizes (the
368
480
  * browser went on showing the old picture from srcset), its image-editor record and its media
@@ -596,6 +708,15 @@ export async function updateSiteStyles(
596
708
  defaults?: Record<string, unknown>;
597
709
  };
598
710
  const changes: string[] = [];
711
+ // W-547: a font stack the site CSS can't carry was saved, then dropped from the page.
712
+ for (const font of (input.variables?.fonts ?? []) as { id?: unknown; value?: unknown }[]) {
713
+ if (typeof font.value === "string" && !isSafeFontStack(font.value)) {
714
+ throw new McpToolError(
715
+ "INVALID_INPUT",
716
+ `Font ${String(font.id)}: "${font.value.slice(0, 60)}" can't be used in the site CSS. Use names of letters, digits, spaces, - and _, quoted or not, separated by commas.`,
717
+ );
718
+ }
719
+ }
599
720
  for (const kind of VARIABLE_KINDS) {
600
721
  const items = input.variables?.[kind] as Item[] | undefined;
601
722
  if (items?.length) {
@@ -603,6 +724,21 @@ export async function updateSiteStyles(
603
724
  changes.push(`${items.length} ${kind}`);
604
725
  }
605
726
  }
727
+ // W-564: removing an id the styles don't have "succeeded" with a removed summary.
728
+ const unknown = [
729
+ ...(input.removeVariables ?? [])
730
+ .filter(({ kind, id }) => !(draft.variables[kind] ?? []).some((v) => v.id === id))
731
+ .map(({ kind, id }) => `${kind} ${id}`),
732
+ ...(input.removeClasses ?? [])
733
+ .filter((id) => !(draft.classes ?? []).some((c) => c.id === id))
734
+ .map((id) => `class ${id}`),
735
+ ];
736
+ if (unknown.length > 0) {
737
+ throw new McpToolError(
738
+ "NOT_FOUND",
739
+ `Nothing to remove for ${unknown.join(", ")}. Call get_site_styles for the ids.`,
740
+ );
741
+ }
606
742
  if (!input.force && (input.removeVariables?.length || input.removeClasses?.length)) {
607
743
  const layouts = await allLayouts(ports);
608
744
  const inUse = [
@@ -648,6 +784,30 @@ export async function updateSiteStyles(
648
784
  draft["direction"] = input.direction;
649
785
  changes.push(`direction ${input.direction}`);
650
786
  }
787
+ // W-573: the editor keeps class names, and variable names within a kind, unique (W-277,
788
+ // W-278); an agent's new or renamed one can't take another's name either.
789
+ const clash = (list: Item[] | undefined, touched: unknown[] | undefined, what: string) => {
790
+ const ids = new Set((touched ?? []).map((item) => (item as { id?: unknown }).id));
791
+ const seen = new Map<string, Item>();
792
+ for (const item of list ?? []) {
793
+ const name = (item as { name?: unknown }).name;
794
+ if (typeof name !== "string") continue;
795
+ const key = nameKey(name);
796
+ const other = seen.get(key);
797
+ if (other && (ids.has(item.id) || ids.has(other.id))) {
798
+ const taken = String((other as { name?: unknown }).name);
799
+ throw new McpToolError(
800
+ "INVALID_INPUT",
801
+ `${what} ${item.id} and ${other.id} would both be named "${taken}". Pick another name.`,
802
+ );
803
+ }
804
+ if (!other) seen.set(key, item);
805
+ }
806
+ };
807
+ clash(draft.classes, input.classes, "Classes");
808
+ for (const kind of VARIABLE_KINDS) {
809
+ clash(draft.variables[kind], input.variables?.[kind], `Variables (${kind})`);
810
+ }
651
811
  if (changes.length === 0) refused("Nothing to change.");
652
812
  const result = validateDesign(draft);
653
813
  if (!result.ok) {
@@ -656,6 +816,10 @@ export async function updateSiteStyles(
656
816
  `The site styles would be invalid. ${summarizeIssues(result.issues)}`,
657
817
  );
658
818
  }
819
+ // W-564: the same values again save no new draft revision.
820
+ if (stableJson(result.design) === stableJson(state.design) && state.revision) {
821
+ return { revision: state.revision, summary: "Nothing changed in the site styles draft" };
822
+ }
659
823
  const saved = await ports.saveDesign(result.design as DesignSystem, state.revision);
660
824
  const summary = `Site styles draft: ${changes.join(", ")}`;
661
825
  await ports.log({ target: "styles", tool: "update_site_styles", summary });
@@ -122,7 +122,7 @@ export const agentsSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
122
122
  ctx.input.settings,
123
123
  );
124
124
  if (!write.applied) {
125
- throw PluginRouteError.conflict("The agent settings changed somewhere else. Reload them.");
125
+ throw PluginRouteError.conflict("The agent settings changed somewhere else.");
126
126
  }
127
127
  const s = ctx.input.settings;
128
128
  await appendAgentLog(agentLog(ctx), {
@@ -25,7 +25,7 @@ type FieldValidation =
25
25
  | { ok: false; issues: { code: string; message: string }[] };
26
26
 
27
27
  /** Theme-part fields validated on save, besides the layout (R-061). */
28
- const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation][] = [
28
+ const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation, string?][] = [
29
29
  [
30
30
  "conditions",
31
31
  (raw) => {
@@ -46,6 +46,8 @@ const THEME_PART_FIELDS: [string, (raw: unknown) => FieldValidation][] = [
46
46
  const result = validateFloatSettings(raw);
47
47
  return result.ok ? { ok: true, value: result.settings } : result;
48
48
  },
49
+ // W-678: the message read "The theme part float are invalid."
50
+ "float settings",
49
51
  ],
50
52
  ];
51
53
 
@@ -95,7 +97,7 @@ export async function beforeSave(
95
97
  }
96
98
 
97
99
  if (event.collection === THEME_PARTS_COLLECTION) {
98
- for (const [field, validate] of THEME_PART_FIELDS) {
100
+ for (const [field, validate, label = field] of THEME_PART_FIELDS) {
99
101
  if (event.content[field] === undefined) continue;
100
102
  const result = validate(parseJsonField(event.content[field]));
101
103
  if (!result.ok) {
@@ -104,7 +106,7 @@ export async function beforeSave(
104
106
  code: result.issues[0]?.code ?? `invalid_${field}`,
105
107
  });
106
108
  throw new ContentSaveRejectedError(
107
- `The theme part ${field} are invalid. ${result.issues
109
+ `The theme part ${label} are invalid. ${result.issues
108
110
  .slice(0, 3)
109
111
  .map((i) => i.message)
110
112
  .join("; ")}`,
@@ -29,19 +29,32 @@ type IconStore = {
29
29
 
30
30
  const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as IconStore;
31
31
 
32
- /** The most recent uploads the picker lists. */
33
- const UPLOAD_LIST_LIMIT = 100;
32
+ /**
33
+ * The uploads the picker lists, and the most My uploads holds (W-535): past it the oldest
34
+ * uploads dropped off the list and could no longer be seen or deleted.
35
+ */
36
+ export const UPLOAD_LIST_LIMIT = 100;
34
37
 
35
- /** A file name without its folder or extension, as the icon's label. */
36
- export const uploadName = (name: string) =>
38
+ /** An icon's label as typed: trimmed and capped (W-655: a rename may hold a slash, as in "AC/DC"). */
39
+ // W-656: control characters become spaces and invisible or direction-changing marks go, so a
40
+ // name like "evil\u202Egvs.exe" can't show reversed in the picker.
41
+ const iconLabel = (name: string) =>
37
42
  clipText(
38
- name
39
- .replace(/^.*[\\/]/, "")
40
- .replace(/\.svg$/i, "")
43
+ Array.from(name.normalize("NFC"), (ch) => {
44
+ const code = ch.charCodeAt(0);
45
+ return code < 32 || (code >= 127 && code <= 159) ? " " : ch;
46
+ })
47
+ .join("")
48
+ .replace(/[\u200B\u2060\uFEFF\u200E\u200F\u202A-\u202E\u2066-\u2069]/g, "")
49
+ .replace(/ {2,}/g, " ")
41
50
  .trim(),
42
51
  80,
43
52
  ).trim() || "Uploaded icon";
44
53
 
54
+ /** A file name without its folder or extension, as the icon's label. */
55
+ export const uploadName = (name: string) =>
56
+ iconLabel(name.replace(/^.*[\\/]/, "").replace(/\.svg$/i, ""));
57
+
45
58
  /**
46
59
  * One stored upload safe to send to the editor. Markup that no longer passes the SVG allowlist
47
60
  * is left out, so a row written past the upload route cannot carry a script into the picker.
@@ -52,7 +65,7 @@ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIcon
52
65
  if (!tree) return undefined;
53
66
  return {
54
67
  id,
55
- name: uploadName(typeof data.name === "string" ? data.name : ""),
68
+ name: iconLabel(typeof data.name === "string" ? data.name : ""),
56
69
  svg: serialize(tree),
57
70
  uploadedAt: typeof data.uploadedAt === "string" ? data.uploadedAt : "",
58
71
  };
@@ -87,6 +100,14 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
87
100
  handler: async (ctx) => {
88
101
  const prepared = prepareUploadedSvg(ctx.input.svg);
89
102
  if (!prepared.ok) throw new PluginRouteError("INVALID_SVG", prepared.message, 422);
103
+ const held = await store(ctx).query({ limit: UPLOAD_LIST_LIMIT });
104
+ if (held.items.length >= UPLOAD_LIST_LIMIT) {
105
+ throw new PluginRouteError(
106
+ "UPLOADS_FULL",
107
+ `My uploads holds up to ${UPLOAD_LIST_LIMIT} icons. Delete one you no longer use, then upload again.`,
108
+ 409,
109
+ );
110
+ }
90
111
  const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
91
112
  const item: UploadedIcon = {
92
113
  name: uploadName(ctx.input.name),
@@ -113,7 +134,7 @@ export const iconRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
113
134
  handler: async (ctx) => {
114
135
  const current = await store(ctx).get(ctx.input.id);
115
136
  if (!current) throw new PluginRouteError("NOT_FOUND", "That upload is not in My uploads.", 404);
116
- const name = uploadName(ctx.input.name);
137
+ const name = iconLabel(ctx.input.name.trim().replace(/\.svg$/i, ""));
117
138
  // W-390: answer with the same checked markup the list sends; a row that fails the
118
139
  // allowlist is not renamed or echoed back.
119
140
  const item = publicUploadedIcon(ctx.input.id, { ...current, name });
@@ -1,4 +1,5 @@
1
1
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { portOf } from "./saved-sections.ts";
2
3
  import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
3
4
  import { McpToolError } from "../mcp/errors.ts";
4
5
  import type { RequiredFieldInfo } from "../core/index.ts";
@@ -55,7 +56,11 @@ const parseJson = (raw: unknown) => {
55
56
 
56
57
  const summary = (item: Item): PageSummary => ({
57
58
  id: item.id,
58
- title: typeof item.data["title"] === "string" ? item.data["title"] : "Untitled page",
59
+ // W-679: a blank title read as "" here while the admin list said "Untitled page".
60
+ title:
61
+ typeof item.data["title"] === "string" && item.data["title"].trim()
62
+ ? item.data["title"]
63
+ : "Untitled page",
59
64
  slug: item.slug ?? "",
60
65
  status: item.status,
61
66
  hasDraft: Boolean(item.draftRevisionId && item.draftRevisionId !== item.liveRevisionId),
@@ -96,6 +101,7 @@ async function loadFormFieldsFromSite(
96
101
  name: raw.name,
97
102
  label: typeof raw.label === "string" ? raw.label : raw.name,
98
103
  required: raw.required === true,
104
+ ...(typeof raw.type === "string" ? { type: raw.type } : {}),
99
105
  });
100
106
  }
101
107
  }
@@ -130,6 +136,7 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
130
136
  };
131
137
  return {
132
138
  caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
139
+ savedSections: portOf(ctx),
133
140
  formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
134
141
  async rateLimit(cls) {
135
142
  await hitRateLimit(
@@ -6,6 +6,13 @@ import {
6
6
  designRoute,
7
7
  designSaveRoute,
8
8
  } from "./design-routes.ts";
9
+ import {
10
+ savedSectionDeleteRoute,
11
+ savedSectionGetRoute,
12
+ savedSectionRenameRoute,
13
+ savedSectionSaveRoute,
14
+ savedSectionsRoute,
15
+ } from "./saved-sections.ts";
9
16
  import { iconDeleteRoute, iconRenameRoute, iconUploadRoute, iconsRoute } from "./icon-routes.ts";
10
17
  import { beforeSave } from "./hooks.ts";
11
18
  import {
@@ -37,6 +44,8 @@ export function createPlugin(options: { canvasStyles?: unknown } = {}) {
37
44
  // D-057: agent changes and the site styles history.
38
45
  agentlog: { indexes: ["at", "pageId"] },
39
46
  designhistory: { indexes: ["at"] },
47
+ // W-875 (D-060): saved sections, by name, per site.
48
+ emvb_saved_sections: { indexes: ["updatedAt"] },
40
49
  },
41
50
  hooks: {
42
51
  "content:beforeSave": { handler: beforeSave, errorPolicy: "abort" },
@@ -64,6 +73,11 @@ export function createPlugin(options: { canvasStyles?: unknown } = {}) {
64
73
  "design/save": designSaveRoute,
65
74
  "design/publish": designPublishRoute,
66
75
  icons: iconsRoute,
76
+ "saved-sections": savedSectionsRoute,
77
+ "saved-sections/get": savedSectionGetRoute,
78
+ "saved-sections/save": savedSectionSaveRoute,
79
+ "saved-sections/rename": savedSectionRenameRoute,
80
+ "saved-sections/delete": savedSectionDeleteRoute,
67
81
  "icons/upload": iconUploadRoute,
68
82
  "icons/rename": iconRenameRoute,
69
83
  "icons/delete": iconDeleteRoute,
@@ -0,0 +1,163 @@
1
+ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { z } from "zod";
3
+ import {
4
+ MAX_SAVED_SECTIONS,
5
+ readSavedSection,
6
+ savedSectionName,
7
+ savedSectionRecord,
8
+ SAVED_SECTION_REASONS,
9
+ type SavedSectionRecord,
10
+ type SavedSectionSummary,
11
+ } from "../core/index.ts";
12
+ import type { SavedSectionsPort } from "../mcp/ports.ts";
13
+ import { queued } from "../mcp/queue.ts";
14
+
15
+ /**
16
+ * Saved sections (W-875, D-060): named copies of an element kept per site in plugin storage
17
+ * `emvb_saved_sections`. Every row read goes through `readSavedSection`, so an old save comes
18
+ * back upgraded and a damaged or hand-written one is never inserted. Writes take the same
19
+ * per-isolate queue as the MCP tools.
20
+ */
21
+ const SAVED_SECTIONS_COLLECTION = "emvb_saved_sections";
22
+
23
+ type SavedSectionStore = {
24
+ get(id: string): Promise<unknown>;
25
+ put(id: string, data: SavedSectionRecord): Promise<void>;
26
+ delete(id: string): Promise<boolean>;
27
+ query(options?: {
28
+ orderBy?: Record<string, "asc" | "desc">;
29
+ limit?: number;
30
+ }): Promise<{ items: Array<{ id: string; data: unknown }>; hasMore: boolean }>;
31
+ };
32
+
33
+ const QUEUE = "saved-sections";
34
+ const ID = /^[0-9a-f]{16}$/;
35
+ const FULL_REASON = `My sections holds up to ${MAX_SAVED_SECTIONS} sections. Delete one you no longer use, then save again.`;
36
+
37
+ function summaryOf(id: string, data: unknown): SavedSectionSummary {
38
+ const read = readSavedSection(data);
39
+ if (read.ok) {
40
+ const { name, updatedAt, classes } = read.section;
41
+ return { id, name, updatedAt, classCount: classes.length };
42
+ }
43
+ const raw = (data ?? {}) as { name?: unknown; updatedAt?: unknown };
44
+ return {
45
+ id,
46
+ name: (typeof raw.name === "string" && savedSectionName(raw.name)) || "Damaged section",
47
+ updatedAt: typeof raw.updatedAt === "string" ? raw.updatedAt : "",
48
+ classCount: 0,
49
+ damaged: true,
50
+ };
51
+ }
52
+
53
+ /** The port the routes and the MCP tools share, on a plugin storage collection. */
54
+ function savedSectionsPort(store: SavedSectionStore): SavedSectionsPort {
55
+ const all = () => store.query({ orderBy: { updatedAt: "desc" }, limit: MAX_SAVED_SECTIONS });
56
+ return {
57
+ async list() {
58
+ const page = await all();
59
+ return page.items.map(({ id, data }) => summaryOf(id, data));
60
+ },
61
+ async get(id) {
62
+ if (!ID.test(id)) return null;
63
+ const data = await store.get(id);
64
+ if (data === null || data === undefined) return null;
65
+ const read = readSavedSection(data);
66
+ return read.ok ? read.section : read;
67
+ },
68
+ create: (record) =>
69
+ queued(QUEUE, async () => {
70
+ const read = readSavedSection(record);
71
+ if (!read.ok) return read;
72
+ if ((await all()).items.length >= MAX_SAVED_SECTIONS) {
73
+ return { ok: false as const, reason: FULL_REASON };
74
+ }
75
+ const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
76
+ await store.put(id, savedSectionRecord(read.section));
77
+ return { id };
78
+ }),
79
+ rename: (id, rawName) =>
80
+ queued(QUEUE, async () => {
81
+ if (!ID.test(id)) return null;
82
+ const data = await store.get(id);
83
+ if (data === null || data === undefined) return null;
84
+ const name = savedSectionName(rawName);
85
+ if (!name) return { ok: false as const, reason: SAVED_SECTION_REASONS.name };
86
+ const read = readSavedSection(data);
87
+ if (!read.ok) return read;
88
+ const section = { ...read.section, name, updatedAt: new Date().toISOString() };
89
+ await store.put(id, savedSectionRecord(section));
90
+ return summaryOf(id, savedSectionRecord(section));
91
+ }),
92
+ remove: (id) => queued(QUEUE, async () => ID.test(id) && (await store.delete(id))),
93
+ };
94
+ }
95
+
96
+ export const portOf = (ctx: RouteContext<unknown>) =>
97
+ savedSectionsPort(ctx.storage[SAVED_SECTIONS_COLLECTION] as unknown as SavedSectionStore);
98
+
99
+ const NOT_FOUND = "That section is not in My sections.";
100
+ const refusedError = (reason: string) => new PluginRouteError("REFUSED", reason, 422);
101
+
102
+ /** Editors and above: the saved sections, newest first, by name. */
103
+ export const savedSectionsRoute: PluginRoute = {
104
+ permission: "content:edit_any",
105
+ handler: async (ctx) => ({ items: await portOf(ctx).list() }),
106
+ };
107
+
108
+ const IdInput = z.object({ id: z.string().regex(ID, "Unknown section") });
109
+
110
+ /** Editors and above: one section, read and upgraded, ready for `prepareSavedSection`. */
111
+ export const savedSectionGetRoute: PluginRoute<z.infer<typeof IdInput>> = {
112
+ permission: "content:edit_any",
113
+ input: IdInput,
114
+ handler: async (ctx) => {
115
+ const section = await portOf(ctx).get(ctx.input.id);
116
+ if (!section) throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
117
+ if ("ok" in section) throw refusedError(section.reason);
118
+ return { section };
119
+ },
120
+ };
121
+
122
+ /** A record from the editor; the server checks it again, whatever the client did. */
123
+ const SaveInput = z.object({ record: z.record(z.string(), z.unknown()) });
124
+
125
+ export const savedSectionSaveRoute: PluginRoute<z.infer<typeof SaveInput>> = {
126
+ permission: "content:edit_any",
127
+ input: SaveInput,
128
+ handler: async (ctx) => {
129
+ const now = new Date().toISOString();
130
+ const record = { ...ctx.input.record, createdAt: now, updatedAt: now };
131
+ const made = await portOf(ctx).create(record as SavedSectionRecord);
132
+ if ("ok" in made) {
133
+ const full = made.reason === FULL_REASON;
134
+ throw new PluginRouteError(full ? "SECTIONS_FULL" : "REFUSED", made.reason, full ? 409 : 422);
135
+ }
136
+ return { id: made.id };
137
+ },
138
+ };
139
+
140
+ const RenameInput = IdInput.extend({ name: z.string().min(1).max(255) });
141
+
142
+ export const savedSectionRenameRoute: PluginRoute<z.infer<typeof RenameInput>> = {
143
+ permission: "content:edit_any",
144
+ input: RenameInput,
145
+ handler: async (ctx) => {
146
+ const item = await portOf(ctx).rename(ctx.input.id, ctx.input.name);
147
+ if (!item) throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
148
+ if ("ok" in item) throw refusedError(item.reason);
149
+ return { item };
150
+ },
151
+ };
152
+
153
+ /** Pages that already hold an inserted copy keep it: a copy is not linked to its source. */
154
+ export const savedSectionDeleteRoute: PluginRoute<z.infer<typeof IdInput>> = {
155
+ permission: "content:edit_any",
156
+ input: IdInput,
157
+ handler: async (ctx) => {
158
+ if (!(await portOf(ctx).remove(ctx.input.id))) {
159
+ throw new PluginRouteError("NOT_FOUND", NOT_FOUND, 404);
160
+ }
161
+ return { id: ctx.input.id };
162
+ },
163
+ };