@perkyzz/emvb 0.9.0 → 1.1.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 (187) hide show
  1. package/README.md +10 -1
  2. package/package.json +2 -2
  3. package/src/admin/agents-api.ts +45 -0
  4. package/src/admin/bulk-api.ts +67 -0
  5. package/src/admin/content-api.ts +10 -6
  6. package/src/admin/copy-rich-text.ts +119 -0
  7. package/src/admin/dialog-tab-wrap.ts +78 -0
  8. package/src/admin/editor/A11yCopilot.tsx +3 -1
  9. package/src/admin/editor/Editor.tsx +311 -250
  10. package/src/admin/editor/Timeline.tsx +8 -3
  11. package/src/admin/editor/TopBar.tsx +29 -7
  12. package/src/admin/editor/canvas/CanvasFrame.tsx +7 -2
  13. package/src/admin/editor/canvas/DeviceBar.tsx +31 -10
  14. package/src/admin/editor/canvas/canvas-scale.ts +3 -3
  15. package/src/admin/editor/canvas/use-canvas-session.ts +2 -2
  16. package/src/admin/editor/co-design.ts +190 -0
  17. package/src/admin/editor/dnd/new-element.ts +48 -4
  18. package/src/admin/editor/editor-chrome.tsx +8 -6
  19. package/src/admin/editor/editor-commands.ts +15 -4
  20. package/src/admin/editor/editor-css.ts +2 -1
  21. package/src/admin/editor/element-chrome.ts +3 -1
  22. package/src/admin/editor/extension-manifests.ts +20 -0
  23. package/src/admin/editor/extensions/ExtensionPanels.tsx +26 -0
  24. package/src/admin/editor/extensions-context.tsx +27 -0
  25. package/src/admin/editor/feature-css.ts +17 -0
  26. package/src/admin/editor/palette-items.ts +2 -2
  27. package/src/admin/editor/panels/AddPanel.tsx +31 -1
  28. package/src/admin/editor/panels/AgentRequestBox.tsx +116 -0
  29. package/src/admin/editor/panels/ClassesSection.tsx +9 -6
  30. package/src/admin/editor/panels/CoDesignPanel.tsx +170 -0
  31. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  32. package/src/admin/editor/panels/ElementPanel.tsx +68 -20
  33. package/src/admin/editor/panels/LanguagesSection.tsx +152 -0
  34. package/src/admin/editor/panels/LayersPanel.tsx +10 -6
  35. package/src/admin/editor/panels/LeftPanel.tsx +33 -5
  36. package/src/admin/editor/panels/PageSettings.tsx +4 -0
  37. package/src/admin/editor/panels/SettingsPanel.tsx +21 -2
  38. package/src/admin/editor/panels/SiteStylesDrawer.tsx +7 -7
  39. package/src/admin/editor/panels/settings/BackgroundControls.tsx +72 -15
  40. package/src/admin/editor/panels/settings/BackgroundFill.tsx +8 -6
  41. package/src/admin/editor/panels/settings/BoxControl.tsx +5 -5
  42. package/src/admin/editor/panels/settings/EffectsControls.tsx +183 -10
  43. package/src/admin/editor/panels/settings/FieldControl.tsx +9 -3
  44. package/src/admin/editor/panels/settings/IconControls.tsx +25 -11
  45. package/src/admin/editor/panels/settings/LengthRow.tsx +63 -19
  46. package/src/admin/editor/panels/settings/LoopControl.tsx +269 -0
  47. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +19 -1
  48. package/src/admin/editor/panels/settings/MotionControl.tsx +12 -11
  49. package/src/admin/editor/panels/settings/QueryStyleRows.tsx +7 -4
  50. package/src/admin/editor/panels/settings/StyleRow.tsx +120 -13
  51. package/src/admin/editor/panels/settings/TextMarksControl.tsx +247 -0
  52. package/src/admin/editor/panels/settings/VariableBinding.tsx +2 -2
  53. package/src/admin/editor/panels/settings/background-mode.ts +14 -11
  54. package/src/admin/editor/panels/settings/box-link-name.ts +1 -1
  55. package/src/admin/editor/panels/settings/box-sides.ts +22 -14
  56. package/src/admin/editor/panels/settings/heading-warning.ts +5 -1
  57. package/src/admin/editor/panels/settings/length-units.ts +68 -4
  58. package/src/admin/editor/panels/settings/query-style.ts +3 -3
  59. package/src/admin/editor/panels/settings/style-sections.ts +52 -10
  60. package/src/admin/editor/panels/style-target.ts +22 -7
  61. package/src/admin/editor/presence.ts +60 -0
  62. package/src/admin/editor/section-templates.ts +26 -4
  63. package/src/admin/editor/store.ts +14 -4
  64. package/src/admin/editor/useCoDesign.ts +177 -0
  65. package/src/admin/editor/useEditorCommands.ts +7 -5
  66. package/src/admin/editor/useExtensions.ts +45 -0
  67. package/src/admin/editor/useNodeActions.ts +18 -7
  68. package/src/admin/editor/useProposals.ts +81 -0
  69. package/src/admin/export-api.ts +221 -0
  70. package/src/admin/index.tsx +6 -1
  71. package/src/admin/languages-api.ts +61 -0
  72. package/src/admin/pages/AgentSetup.tsx +148 -0
  73. package/src/admin/pages/AgentsPage.tsx +9 -26
  74. package/src/admin/pages/CreateDialog.tsx +15 -0
  75. package/src/admin/pages/ExportDialog.tsx +395 -0
  76. package/src/admin/pages/ImportButton.tsx +18 -0
  77. package/src/admin/pages/ImportElementorDialog.tsx +669 -0
  78. package/src/admin/pages/ImportPageLinks.tsx +86 -0
  79. package/src/admin/pages/PageList.tsx +82 -3
  80. package/src/admin/pages/ThemePartList.tsx +52 -2
  81. package/src/admin/pages/bulk.tsx +303 -0
  82. package/src/admin/pages/section-head.tsx +27 -0
  83. package/src/admin/proposals-api.ts +91 -0
  84. package/src/admin/search.ts +20 -0
  85. package/src/admin/theme-api.ts +4 -0
  86. package/src/admin/ui.ts +50 -4
  87. package/src/admin/widgets/CanvasField.tsx +8 -0
  88. package/src/admin/widgets/ConvertToRichText.tsx +136 -0
  89. package/src/admin/widgets/ExportEntryHtml.tsx +92 -0
  90. package/src/admin/widgets/convert-body.ts +73 -2
  91. package/src/astro/content-port.ts +14 -1
  92. package/src/astro/render.ts +6 -6
  93. package/src/astro/resolve-theme.ts +25 -8
  94. package/src/astro/resolve.ts +89 -2
  95. package/src/astro/tabs/runtime.ts +16 -6
  96. package/src/constants.ts +1 -1
  97. package/src/core/a11y/audit.ts +45 -14
  98. package/src/core/arrange.ts +5 -1
  99. package/src/core/bounded-array.ts +31 -0
  100. package/src/core/clipboard.ts +9 -0
  101. package/src/core/contract.ts +305 -0
  102. package/src/core/css/generate.ts +151 -20
  103. package/src/core/css/scope.ts +10 -2
  104. package/src/core/css/trace.ts +47 -13
  105. package/src/core/css-keywords.ts +51 -1
  106. package/src/core/design/cascade.ts +12 -9
  107. package/src/core/design/classes.ts +28 -9
  108. package/src/core/design/devices.ts +89 -13
  109. package/src/core/design/states.ts +5 -3
  110. package/src/core/design/transfer.ts +5 -0
  111. package/src/core/design/variables.ts +31 -5
  112. package/src/core/elements/dynamic-elements.ts +3 -3
  113. package/src/core/elements/index.ts +73 -9
  114. package/src/core/export/runtimes.generated.ts +9 -0
  115. package/src/core/export/site.ts +562 -0
  116. package/src/core/export/zip.ts +95 -0
  117. package/src/core/extensions/define.ts +13 -0
  118. package/src/core/extensions/index.ts +41 -0
  119. package/src/core/extensions/namespace.ts +82 -0
  120. package/src/core/extensions/normalize.ts +141 -0
  121. package/src/core/extensions/placeholder.ts +41 -0
  122. package/src/core/extensions/registry.ts +94 -0
  123. package/src/core/extensions/render-ext.ts +118 -0
  124. package/src/core/extensions/safe-nodes.ts +93 -0
  125. package/src/core/extensions/schema.ts +112 -0
  126. package/src/core/extensions/types.ts +159 -0
  127. package/src/core/forms/binding.ts +1 -1
  128. package/src/core/history/diff.ts +26 -1
  129. package/src/core/import/elementor/atomic.ts +1608 -0
  130. package/src/core/import/elementor/classes.ts +127 -0
  131. package/src/core/import/elementor/context.ts +429 -0
  132. package/src/core/import/elementor/counter-steps.ts +72 -0
  133. package/src/core/import/elementor/css.ts +445 -0
  134. package/src/core/import/elementor/html.ts +500 -0
  135. package/src/core/import/elementor/index.ts +967 -0
  136. package/src/core/import/elementor/inline-marks.ts +81 -0
  137. package/src/core/import/elementor/snapshots.ts +48 -0
  138. package/src/core/import/elementor/style.ts +429 -0
  139. package/src/core/import/elementor/values.ts +241 -0
  140. package/src/core/import/elementor/widgets.ts +1897 -0
  141. package/src/core/index.ts +96 -0
  142. package/src/core/json-schema.ts +114 -0
  143. package/src/core/limits.ts +19 -0
  144. package/src/core/migrate/index.ts +6 -1
  145. package/src/core/migrate/v18.ts +222 -0
  146. package/src/core/perf/meter.ts +42 -24
  147. package/src/core/portable-text-export.ts +243 -0
  148. package/src/core/proposals-safety.ts +102 -0
  149. package/src/core/proposals.ts +357 -0
  150. package/src/core/public-attributes.ts +30 -0
  151. package/src/core/recipes/index.ts +2 -2
  152. package/src/core/render/extras.ts +3 -3
  153. package/src/core/render/index.ts +222 -23
  154. package/src/core/render/loop.ts +1 -1
  155. package/src/core/render/section.ts +4 -4
  156. package/src/core/render/tabs.ts +18 -11
  157. package/src/core/render/vnode.ts +1 -1
  158. package/src/core/sanitize/css.ts +151 -10
  159. package/src/core/sanitize/motion.ts +116 -0
  160. package/src/core/saved-sections.ts +6 -0
  161. package/src/core/schema/descriptors.ts +3 -1
  162. package/src/core/schema/design.ts +4 -3
  163. package/src/core/schema/layout.ts +92 -16
  164. package/src/core/schema/style.ts +296 -112
  165. package/src/core/search-text.ts +70 -0
  166. package/src/core/text-marks.ts +227 -0
  167. package/src/core/theme/dynamic.ts +9 -4
  168. package/src/core/theme/float.ts +2 -0
  169. package/src/core/theme/popup-rules.ts +33 -1
  170. package/src/core/translatable.ts +34 -0
  171. package/src/core/validate.ts +13 -1
  172. package/src/index.ts +24 -0
  173. package/src/mcp/errors.ts +3 -1
  174. package/src/mcp/ports.ts +67 -0
  175. package/src/mcp/prompts.ts +1 -11
  176. package/src/mcp/proposals.ts +281 -0
  177. package/src/mcp/read.ts +10 -10
  178. package/src/mcp/tools.ts +71 -3
  179. package/src/mcp/write.ts +66 -11
  180. package/src/server/agent-settings.ts +5 -1
  181. package/src/server/icon-routes.ts +52 -12
  182. package/src/server/mcp-routes.ts +15 -0
  183. package/src/server/plugin.ts +35 -2
  184. package/src/server/presence.ts +78 -0
  185. package/src/server/proposals.ts +261 -0
  186. package/src/server/requests.ts +196 -0
  187. package/src/server/tools-served.ts +45 -0
@@ -24,16 +24,40 @@ type IconStore = {
24
24
  query(options?: {
25
25
  orderBy?: Record<string, "asc" | "desc">;
26
26
  limit?: number;
27
- }): Promise<{ items: Array<{ id: string; data: UploadedIcon }>; hasMore: boolean }>;
27
+ cursor?: string;
28
+ }): Promise<{
29
+ items: Array<{ id: string; data: UploadedIcon }>;
30
+ hasMore: boolean;
31
+ cursor?: string;
32
+ }>;
28
33
  };
29
34
 
30
35
  const store = (ctx: RouteContext<unknown>) => ctx.storage["icons"] as unknown as IconStore;
31
36
 
32
37
  /**
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.
38
+ * The most My uploads holds, and the uploads the picker lists (W-535; 500 since W-972). EmDash
39
+ * returns plugin storage 100 rows at a time, so the list is read page by page.
35
40
  */
36
- export const UPLOAD_LIST_LIMIT = 100;
41
+ export const UPLOAD_LIST_LIMIT = 500;
42
+ const STORAGE_PAGE = 100;
43
+
44
+ /** Every upload, newest first, up to the limit, following EmDash's storage cursor (W-972). */
45
+ async function allUploads(ctx: RouteContext<unknown>) {
46
+ const items: Array<{ id: string; data: UploadedIcon }> = [];
47
+ let cursor: string | undefined;
48
+ for (let page = 0; page < UPLOAD_LIST_LIMIT / STORAGE_PAGE; page += 1) {
49
+ // oxlint-disable-next-line no-await-in-loop -- each page needs the previous page's cursor
50
+ const result = await store(ctx).query({
51
+ orderBy: { uploadedAt: "desc" },
52
+ limit: STORAGE_PAGE,
53
+ ...(cursor ? { cursor } : {}),
54
+ });
55
+ items.push(...result.items);
56
+ if (!result.hasMore || !result.cursor) break;
57
+ cursor = result.cursor;
58
+ }
59
+ return items.slice(0, UPLOAD_LIST_LIMIT);
60
+ }
37
61
 
38
62
  /** An icon's label as typed: trimmed and capped (W-655: a rename may hold a slash, as in "AC/DC"). */
39
63
  // W-656: control characters become spaces and invisible or direction-changing marks go, so a
@@ -75,11 +99,7 @@ export function publicUploadedIcon(id: string, data: UploadedIcon): UploadedIcon
75
99
  export const iconsRoute: PluginRoute = {
76
100
  permission: "content:edit_any",
77
101
  handler: async (ctx) => {
78
- const page = await store(ctx).query({
79
- orderBy: { uploadedAt: "desc" },
80
- limit: UPLOAD_LIST_LIMIT,
81
- });
82
- const items = page.items.flatMap(({ id, data }) => {
102
+ const items = (await allUploads(ctx)).flatMap(({ id, data }) => {
83
103
  const item = publicUploadedIcon(id, data);
84
104
  return item ? [item] : [];
85
105
  });
@@ -100,15 +120,27 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
100
120
  handler: async (ctx) => {
101
121
  const prepared = prepareUploadedSvg(ctx.input.svg);
102
122
  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) {
123
+ const held = await allUploads(ctx);
124
+ // W-972: the same SVG uploaded again (twice at once from two tabs, or later) is the icon
125
+ // already in My uploads; the check runs on the sanitized markup, so it is the same drawing.
126
+ const same = held.find(({ data }) => data.svg === prepared.svg);
127
+ if (same) {
128
+ return {
129
+ item: { id: same.id, ...same.data },
130
+ imagesLeftOut: prepared.imagesLeftOut,
131
+ duplicate: true,
132
+ };
133
+ }
134
+ if (held.length >= UPLOAD_LIST_LIMIT) {
105
135
  throw new PluginRouteError(
106
136
  "UPLOADS_FULL",
107
137
  `My uploads holds up to ${UPLOAD_LIST_LIMIT} icons. Delete one you no longer use, then upload again.`,
108
138
  409,
109
139
  );
110
140
  }
111
- const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
141
+ // W-972: the id is the drawing's hash, so two uploads of the same SVG at the same moment
142
+ // land on one row instead of two.
143
+ const id = await svgId(prepared.svg);
112
144
  const item: UploadedIcon = {
113
145
  name: uploadName(ctx.input.name),
114
146
  svg: prepared.svg,
@@ -119,6 +151,14 @@ export const iconUploadRoute: PluginRoute<z.infer<typeof UploadInput>> = {
119
151
  },
120
152
  };
121
153
 
154
+ /** The first 16 hex digits of the SHA-256 of the sanitized markup. */
155
+ async function svgId(svg: string): Promise<string> {
156
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(svg));
157
+ return [...new Uint8Array(digest).slice(0, 8)]
158
+ .map((b) => b.toString(16).padStart(2, "0"))
159
+ .join("");
160
+ }
161
+
122
162
  const IdInput = z.object({
123
163
  id: z.string().regex(/^[0-9a-f]{16}$/, "Unknown icon"),
124
164
  });
@@ -1,5 +1,9 @@
1
1
  import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
2
  import { portOf } from "./saved-sections.ts";
3
+ import { proposalPortOf } from "./proposals.ts";
4
+ import { requestsPortOf } from "./requests.ts";
5
+ import { noteServed, toolListFingerprint, viaEmDashMcp } from "./tools-served.ts";
6
+ import { isOpenInEditor } from "./presence.ts";
3
7
  import { PAGES_COLLECTION, DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
4
8
  import { McpToolError } from "../mcp/errors.ts";
5
9
  import type { RequiredFieldInfo } from "../core/index.ts";
@@ -137,6 +141,13 @@ function pluginPorts(ctx: RouteContext<unknown>): EmvbPorts {
137
141
  return {
138
142
  caller: { userId: ctx.user?.id ?? null, role: Number(ctx.user?.role ?? 0) },
139
143
  savedSections: portOf(ctx),
144
+ proposals: proposalPortOf(ctx),
145
+ requests: requestsPortOf(ctx),
146
+ pageOpen: (id) =>
147
+ isOpenInEditor(ctx.kv as unknown as Parameters<typeof isOpenInEditor>[0], {
148
+ collection: PAGES_COLLECTION,
149
+ id,
150
+ }),
140
151
  formFields: (formIds) => loadFormFieldsFromSite(ctx.request.url, formIds),
141
152
  async rateLimit(cls) {
142
153
  await hitRateLimit(
@@ -287,6 +298,7 @@ export const isNotSetUp = (error: unknown) =>
287
298
 
288
299
  /** Routes `mcp/<tool>`: editors and above (D-056), POST JSON, one per tool (R1 D-054). */
289
300
  export function mcpRoutes(tools: readonly ToolDef[]): Record<string, PluginRoute> {
301
+ const fingerprint = toolListFingerprint(tools);
290
302
  return Object.fromEntries(
291
303
  tools.map((tool) => [
292
304
  `mcp/${tool.name}`,
@@ -295,6 +307,9 @@ export function mcpRoutes(tools: readonly ToolDef[]): Record<string, PluginRoute
295
307
  input: tool.input,
296
308
  handler: async (ctx: RouteContext<unknown>) => {
297
309
  try {
310
+ // W-932: EmDash served this tool, so it approved the current tool list.
311
+ if (viaEmDashMcp(ctx.request))
312
+ await noteServed(ctx.kv as never, fingerprint).catch(() => undefined);
298
313
  return await runTool(tool, pluginPorts(ctx), ctx.input);
299
314
  } catch (error) {
300
315
  if (error instanceof McpToolError) {
@@ -1,3 +1,12 @@
1
+ import {
2
+ proposalCreateRoute,
3
+ proposalGetRoute,
4
+ proposalsRoute,
5
+ proposalAcceptedRoute,
6
+ proposalWithdrawRoute,
7
+ } from "./proposals.ts";
8
+ import { presenceRoute } from "./presence.ts";
9
+ import { requestCancelRoute, requestCreateRoute, requestsRoute } from "./requests.ts";
1
10
  import { definePlugin } from "emdash";
2
11
  import { ADMIN_ENTRY, PLUGIN_ID, PLUGIN_VERSION } from "../constants.ts";
3
12
  import {
@@ -23,14 +32,20 @@ import {
23
32
  } from "./agent-settings.ts";
24
33
  import { canvasStyleUrls } from "../core/canvas-styles.ts";
25
34
  import { canvasCollectionSlugs } from "../core/canvas-collections.ts";
35
+ import { manifestsFromOptions } from "../core/extensions/index.ts";
26
36
  import { TOOLS } from "../mcp/tools.ts";
27
37
  import { mcpRoutes, mcpToolConfig } from "./mcp-routes.ts";
28
38
 
29
39
  export function createPlugin(
30
- options: { canvasStyles?: unknown; canvasCollections?: unknown } = {},
40
+ options: {
41
+ canvasStyles?: unknown;
42
+ canvasCollections?: unknown;
43
+ extensions?: unknown;
44
+ } = {},
31
45
  ) {
32
46
  const canvasStyles = canvasStyleUrls(options.canvasStyles);
33
47
  const canvasCollections = canvasCollectionSlugs(options.canvasCollections);
48
+ const extensions = manifestsFromOptions(options.extensions);
34
49
  return definePlugin({
35
50
  id: PLUGIN_ID,
36
51
  version: PLUGIN_VERSION,
@@ -52,6 +67,9 @@ export function createPlugin(
52
67
  designhistory: { indexes: ["at"] },
53
68
  // W-875 (D-060): saved sections, by name, per site.
54
69
  emvb_saved_sections: { indexes: ["updatedAt"] },
70
+ emvb_proposals: { indexes: ["createdAt"] },
71
+ // W-931: prompt relay requests for bring-your-own agents.
72
+ emvb_requests: { indexes: ["createdAt"] },
55
73
  },
56
74
  hooks: {
57
75
  "content:beforeSave": {
@@ -82,13 +100,28 @@ export function createPlugin(
82
100
  handler: async () => ({ ok: true, plugin: PLUGIN_ID, version: PLUGIN_VERSION }),
83
101
  },
84
102
  // W-327: what the editor needs from the host's `emvb()` options.
85
- "editor/config": { handler: async () => ({ canvasStyles, canvasCollections }) },
103
+ "editor/config": {
104
+ handler: async () => ({
105
+ canvasStyles,
106
+ canvasCollections,
107
+ extensions,
108
+ }),
109
+ },
86
110
  design: designRoute,
87
111
  "design/draft": designDraftRoute,
88
112
  "design/save": designSaveRoute,
89
113
  "design/publish": designPublishRoute,
90
114
  icons: iconsRoute,
91
115
  "saved-sections": savedSectionsRoute,
116
+ proposals: proposalsRoute,
117
+ "proposals/get": proposalGetRoute,
118
+ "proposals/create": proposalCreateRoute,
119
+ "proposals/withdraw": proposalWithdrawRoute,
120
+ "proposals/accepted": proposalAcceptedRoute,
121
+ presence: presenceRoute,
122
+ requests: requestsRoute,
123
+ "requests/create": requestCreateRoute,
124
+ "requests/cancel": requestCancelRoute,
92
125
  "saved-sections/get": savedSectionGetRoute,
93
126
  "saved-sections/save": savedSectionSaveRoute,
94
127
  "saved-sections/rename": savedSectionRenameRoute,
@@ -0,0 +1,78 @@
1
+ import type { PluginRoute, RouteContext } from "emdash";
2
+ import { z } from "zod";
3
+ import { isRecord } from "../core/record.ts";
4
+ import { ProposalTarget } from "../core/proposals.ts";
5
+
6
+ /**
7
+ * W-929 (D-064): which pages are open in the EmVB editor right now. EmVB's editor is a plugin page,
8
+ * so it holds no EmDash edit lock, and plugin content writes skip that lock anyway. The editor
9
+ * renews a short lease here instead; agent writes to a page with a live lease are refused and
10
+ * pointed at propose_changes, so the person editing reviews them.
11
+ */
12
+
13
+ /** A closed tab frees the page within this long. The editor renews at a third of it. */
14
+ export const PRESENCE_LEASE_MS = 90_000;
15
+ const MAX_HOLDERS = 20;
16
+
17
+ type Holders = Record<string, number>;
18
+ type Kv = {
19
+ get<T>(key: string): Promise<T | null>;
20
+ set(key: string, value: unknown): Promise<void>;
21
+ delete(key: string): Promise<boolean>;
22
+ };
23
+
24
+ const keyOf = (target: z.infer<typeof ProposalTarget>) =>
25
+ `presence:${target.collection}:${target.id}`;
26
+
27
+ function live(raw: unknown, now: number): Holders {
28
+ if (!isRecord(raw)) return {};
29
+ const out: Holders = {};
30
+ for (const [user, until] of Object.entries(raw)) {
31
+ if (typeof until === "number" && until > now && until <= now + PRESENCE_LEASE_MS)
32
+ out[user] = until;
33
+ }
34
+ return out;
35
+ }
36
+
37
+ /** Renews (open) or ends (closed) `userId`'s lease on a page. */
38
+ export async function setPresence(
39
+ kv: Kv,
40
+ target: z.infer<typeof ProposalTarget>,
41
+ userId: string,
42
+ open: boolean,
43
+ now = Date.now(),
44
+ ): Promise<void> {
45
+ const key = keyOf(target);
46
+ const holders = live(await kv.get<unknown>(key), now);
47
+ if (open) holders[userId] = now + PRESENCE_LEASE_MS;
48
+ else delete holders[userId];
49
+ const kept = Object.entries(holders)
50
+ .toSorted(([, a], [, b]) => b - a)
51
+ .slice(0, MAX_HOLDERS);
52
+ if (kept.length === 0) await kv.delete(key);
53
+ else await kv.set(key, Object.fromEntries(kept));
54
+ }
55
+
56
+ /** True while someone has the page open in the EmVB editor. */
57
+ export async function isOpenInEditor(
58
+ kv: Kv,
59
+ target: z.infer<typeof ProposalTarget>,
60
+ now = Date.now(),
61
+ ): Promise<boolean> {
62
+ return Object.keys(live(await kv.get<unknown>(keyOf(target)), now)).length > 0;
63
+ }
64
+
65
+ const PresenceInput = z.strictObject({ target: ProposalTarget, open: z.boolean() });
66
+
67
+ /** The editor's heartbeat: `open: true` every PRESENCE_LEASE_MS / 3, `open: false` on close. */
68
+ export const presenceRoute: PluginRoute<z.infer<typeof PresenceInput>> = {
69
+ permission: "content:edit_any",
70
+ input: PresenceInput,
71
+ handler: async (ctx: RouteContext<z.infer<typeof PresenceInput>>) => {
72
+ const userId = ctx.user?.id;
73
+ if (userId) {
74
+ await setPresence(ctx.kv as unknown as Kv, ctx.input.target, userId, ctx.input.open);
75
+ }
76
+ return { leaseMs: PRESENCE_LEASE_MS };
77
+ },
78
+ };
@@ -0,0 +1,261 @@
1
+ import { PluginRouteError, type PluginRoute, type RouteContext } from "emdash";
2
+ import { z } from "zod";
3
+ import { DESIGN_DRAFT_KEY, DESIGN_KEY } from "../constants.ts";
4
+ import { MAX_PENDING_PER_PAGE, MAX_PROPOSAL_OPS, MAX_PROPOSALS } from "../core/limits.ts";
5
+ import {
6
+ applyProposal,
7
+ ProposalTarget,
8
+ readProposal,
9
+ type Proposal,
10
+ type ProposalBase,
11
+ type ProposalRecord,
12
+ type ProposalRefusal,
13
+ } from "../core/proposals.ts";
14
+ import { isRecord } from "../core/record.ts";
15
+ import type { ProposalsPort } from "../mcp/ports.ts";
16
+ import { queued } from "../mcp/queue.ts";
17
+ import { agentLog, appendAgentLog } from "./agent-settings.ts";
18
+ import { readDesign } from "./design-routes.ts";
19
+
20
+ const COLLECTION = "emvb_proposals";
21
+ const ID = /^[0-9a-f]{16}$/;
22
+ type ProposalStore = {
23
+ get(id: string): Promise<unknown>;
24
+ put(id: string, data: ProposalRecord): Promise<void>;
25
+ delete(id: string): Promise<boolean>;
26
+ query(options: { orderBy: Record<string, "asc" | "desc">; limit: number }): Promise<{
27
+ items: { id: string; data: unknown }[];
28
+ hasMore: boolean;
29
+ }>;
30
+ };
31
+
32
+ function readRecord(raw: unknown): { ok: true; record: ProposalRecord } | ProposalRefusal {
33
+ if (
34
+ !isRecord(raw) ||
35
+ typeof raw.createdAt !== "string" ||
36
+ !Number.isFinite(Date.parse(raw.createdAt))
37
+ ) {
38
+ return { ok: false, code: "INVALID_PROPOSAL", reason: "Damaged proposal record." };
39
+ }
40
+ const read = readProposal(raw.proposal);
41
+ return read.ok
42
+ ? { ok: true, record: { proposal: read.proposal, createdAt: raw.createdAt } }
43
+ : read;
44
+ }
45
+
46
+ /** Same per-isolate write queue as saved sections. Content/design are read-only dependencies. */
47
+ export function proposalsPort(
48
+ store: ProposalStore,
49
+ readBase: (target: Proposal["target"]) => Promise<ProposalBase | null>,
50
+ ): ProposalsPort {
51
+ const all = () => store.query({ orderBy: { createdAt: "desc" }, limit: MAX_PROPOSALS });
52
+ const get: ProposalsPort["get"] = async (id) => {
53
+ if (!ID.test(id)) return null;
54
+ const raw = await store.get(id);
55
+ if (raw === undefined || raw === null) return null;
56
+ const read = readRecord(raw);
57
+ return read.ok ? { ...read, id } : read;
58
+ };
59
+ return {
60
+ get,
61
+ async list(target) {
62
+ const items: { id: string; record: ProposalRecord }[] = [];
63
+ for (const row of (await all()).items) {
64
+ const read = readRecord(row.data);
65
+ if (
66
+ read.ok &&
67
+ read.record.proposal.target.collection === target.collection &&
68
+ read.record.proposal.target.id === target.id
69
+ )
70
+ items.push({ id: row.id, record: read.record });
71
+ }
72
+ return items;
73
+ },
74
+ create: (raw) =>
75
+ queued("proposals", async () => {
76
+ const read = readProposal(raw);
77
+ if (!read.ok) return read;
78
+ const base = await readBase(read.proposal.target);
79
+ if (!base)
80
+ return { ok: false, code: "NOT_FOUND", reason: "No target page with a readable layout." };
81
+ const applied = applyProposal(base, read.proposal);
82
+ if (!applied.ok) return applied;
83
+ const page = await all();
84
+ const forPage = page.items.filter((row) => {
85
+ const target =
86
+ isRecord(row.data) && isRecord(row.data.proposal)
87
+ ? row.data.proposal.target
88
+ : undefined;
89
+ return (
90
+ isRecord(target) &&
91
+ target.collection === read.proposal.target.collection &&
92
+ target.id === read.proposal.target.id
93
+ );
94
+ }).length;
95
+ if (forPage >= MAX_PENDING_PER_PAGE)
96
+ return {
97
+ ok: false,
98
+ code: "PROPOSALS_FULL",
99
+ reason: `This page already has ${MAX_PENDING_PER_PAGE} proposals waiting for review. Withdraw one, or wait until the person editing reviews them.`,
100
+ };
101
+ if (page.hasMore || page.items.length >= MAX_PROPOSALS)
102
+ return {
103
+ ok: false,
104
+ code: "PROPOSALS_FULL",
105
+ reason: `At most ${MAX_PROPOSALS} proposals are kept. Withdraw an old one and try again.`,
106
+ };
107
+ const latest = await readBase(read.proposal.target);
108
+ if (!latest)
109
+ return {
110
+ ok: false,
111
+ code: "NOT_FOUND",
112
+ reason: "The target page is no longer available.",
113
+ };
114
+ const rechecked = applyProposal(latest, read.proposal);
115
+ if (!rechecked.ok) return rechecked;
116
+ const id = crypto.randomUUID().replaceAll("-", "").slice(0, 16);
117
+ const record = { proposal: read.proposal, createdAt: new Date().toISOString() };
118
+ await store.put(id, record);
119
+ return { ok: true, id, record };
120
+ }),
121
+ withdraw: (id) => queued("proposals", async () => ID.test(id) && (await store.delete(id))),
122
+ async base(target) {
123
+ const found = await readBase(target);
124
+ return found ? { revision: found.revision, designRevision: found.designRevision } : null;
125
+ },
126
+ async prepare(id, selected) {
127
+ const read = await get(id);
128
+ if (!read || !read.ok) return read;
129
+ const base = await readBase(read.record.proposal.target);
130
+ if (!base)
131
+ return { ok: false, code: "NOT_FOUND", reason: "The target page is no longer available." };
132
+ return applyProposal(base, read.record.proposal, selected);
133
+ },
134
+ };
135
+ }
136
+
137
+ export function proposalPortOf(ctx: RouteContext<unknown>): ProposalsPort {
138
+ return proposalsPort(ctx.storage[COLLECTION] as unknown as ProposalStore, async (target) => {
139
+ const found = await ctx.content?.getVersioned?.(target.collection, target.id);
140
+ if (!found) return null;
141
+ let layout: unknown = found.item.data["layout"];
142
+ if (typeof layout === "string") {
143
+ try {
144
+ layout = JSON.parse(layout);
145
+ } catch {
146
+ return null;
147
+ }
148
+ }
149
+ const draft = await readDesign(ctx, DESIGN_DRAFT_KEY);
150
+ const published = await readDesign(ctx, DESIGN_KEY);
151
+ const styles = draft.status === "empty" ? published : draft;
152
+ return {
153
+ revision: found["_rev"],
154
+ layout,
155
+ design: styles.status === "unreadable" ? null : styles.design,
156
+ designRevision: styles.revision,
157
+ };
158
+ });
159
+ }
160
+
161
+ function unwrap<T extends { ok: boolean }>(result: T | null): Extract<T, { ok: true }> {
162
+ if (!result) throw new PluginRouteError("NOT_FOUND", "No such proposal.", 404);
163
+ if (!result.ok) {
164
+ const refusal = result as unknown as ProposalRefusal;
165
+ throw new PluginRouteError(
166
+ refusal.code,
167
+ refusal.reason,
168
+ refusal.code === "STALE_BASE" || refusal.code === "PROPOSALS_FULL"
169
+ ? 409
170
+ : refusal.code === "NOT_FOUND"
171
+ ? 404
172
+ : 422,
173
+ );
174
+ }
175
+ return result as Extract<T, { ok: true }>;
176
+ }
177
+
178
+ // Plugin-local editor transport, not a public API. Agents use the MCP tools (W-929).
179
+ export const proposalsRoute: PluginRoute<z.infer<typeof ProposalTarget>> = {
180
+ permission: "content:edit_any",
181
+ input: ProposalTarget,
182
+ handler: async (ctx) => ({ items: await proposalPortOf(ctx).list(ctx.input) }),
183
+ };
184
+ const IdInput = z.strictObject({ id: z.string().regex(ID) });
185
+ export const proposalGetRoute: PluginRoute<z.infer<typeof IdInput>> = {
186
+ permission: "content:edit_any",
187
+ input: IdInput,
188
+ handler: async (ctx) => unwrap(await proposalPortOf(ctx).get(ctx.input.id)),
189
+ };
190
+ const CreateInput = z.strictObject({ proposal: z.unknown() });
191
+ export const proposalCreateRoute: PluginRoute<z.infer<typeof CreateInput>> = {
192
+ permission: "content:edit_any",
193
+ input: CreateInput,
194
+ handler: async (ctx) => unwrap(await proposalPortOf(ctx).create(ctx.input.proposal)),
195
+ };
196
+ const WithdrawInput = IdInput.extend({
197
+ /** W-933: the person's review, when the editor closes a proposal it decided. */
198
+ decision: z
199
+ .strictObject({
200
+ accepted: z.number().int().min(0).max(MAX_PROPOSAL_OPS),
201
+ rejected: z.number().int().min(0).max(MAX_PROPOSAL_OPS),
202
+ })
203
+ .optional(),
204
+ });
205
+ export const proposalWithdrawRoute: PluginRoute<z.infer<typeof WithdrawInput>> = {
206
+ permission: "content:edit_any",
207
+ input: WithdrawInput,
208
+ handler: async (ctx) => {
209
+ const port = proposalPortOf(ctx);
210
+ const found = await port.get(ctx.input.id);
211
+ if (!(await port.withdraw(ctx.input.id)))
212
+ throw new PluginRouteError("NOT_FOUND", "No such proposal.", 404);
213
+ const decision = ctx.input.decision;
214
+ if (decision && found?.ok) {
215
+ await appendAgentLog(agentLog(ctx as never), {
216
+ target: "page",
217
+ tool: "review_proposal",
218
+ pageId: found.record.proposal.target.id,
219
+ proposalId: ctx.input.id,
220
+ changes: found.record.proposal.ops.length,
221
+ summary: `Reviewed a proposal: ${decision.accepted} accepted, ${decision.rejected} rejected`,
222
+ userId: ctx.user?.id ?? null,
223
+ });
224
+ }
225
+ return { id: ctx.input.id };
226
+ },
227
+ };
228
+
229
+ const AcceptedInput = z.strictObject({
230
+ target: ProposalTarget,
231
+ accepted: z.number().int().min(1).max(MAX_PROPOSAL_OPS),
232
+ });
233
+
234
+ /**
235
+ * W-930: after Save draft, the editor notes that the new version holds changes accepted from an
236
+ * agent proposal. The version itself is a normal save by the person; the log entry only labels it
237
+ * "Via agent" in the timeline. The newest revision is read here, never taken from the browser.
238
+ */
239
+ export const proposalAcceptedRoute: PluginRoute<z.infer<typeof AcceptedInput>> = {
240
+ permission: "content:edit_any",
241
+ input: AcceptedInput,
242
+ handler: async (ctx) => {
243
+ const { target, accepted } = ctx.input;
244
+ const content = ctx.content as unknown as {
245
+ listRevisions?(c: string, id: string, o: { limit?: number }): Promise<{ id: string }[]>;
246
+ };
247
+ const [latest] = content.listRevisions
248
+ ? await content.listRevisions(target.collection, target.id, { limit: 1 })
249
+ : [];
250
+ if (!latest) throw new PluginRouteError("NOT_FOUND", "No saved version to label.", 404);
251
+ await appendAgentLog(agentLog(ctx as never), {
252
+ target: "page",
253
+ tool: "accept_proposal",
254
+ pageId: target.id,
255
+ revisionId: latest.id,
256
+ summary: `Saved ${accepted} ${accepted === 1 ? "change" : "changes"} accepted from an agent proposal`,
257
+ userId: ctx.user?.id ?? null,
258
+ });
259
+ return { revisionId: latest.id };
260
+ },
261
+ };