@perkyzz/emvb 1.4.0 → 1.4.1

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 (52) hide show
  1. package/package.json +2 -2
  2. package/src/admin/content-item.ts +3 -0
  3. package/src/admin/copy-rich-text.ts +99 -9
  4. package/src/admin/editor/Editor.tsx +7 -2
  5. package/src/admin/editor/collection-previews.ts +7 -8
  6. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  7. package/src/admin/editor/extensions-context.tsx +16 -1
  8. package/src/admin/editor/feature-css.ts +5 -0
  9. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  10. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  11. package/src/admin/editor/panels/settings/FieldControl.tsx +15 -0
  12. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  13. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  14. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  15. package/src/admin/export-api.ts +2 -0
  16. package/src/admin/extension-outputs.ts +57 -0
  17. package/src/admin/import-forms.ts +133 -0
  18. package/src/admin/pages/ImportElementorDialog.tsx +32 -0
  19. package/src/admin/pages/ImportForms.tsx +71 -0
  20. package/src/admin/setup/plan.ts +2 -0
  21. package/src/admin/ui.ts +7 -0
  22. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  23. package/src/astro/render.ts +6 -0
  24. package/src/astro/resolve.ts +2 -0
  25. package/src/astro/theme-posts.ts +17 -23
  26. package/src/astro/visitor.ts +14 -5
  27. package/src/constants.ts +1 -1
  28. package/src/core/css/generate.ts +6 -1
  29. package/src/core/css/trace.ts +8 -0
  30. package/src/core/data/bindings.ts +7 -4
  31. package/src/core/elements/dynamic-elements.ts +1 -1
  32. package/src/core/elements/element-nouns.ts +48 -0
  33. package/src/core/export/site.ts +3 -0
  34. package/src/core/extensions/index.ts +2 -0
  35. package/src/core/extensions/placeholder.ts +7 -2
  36. package/src/core/extensions/render-ext.ts +49 -15
  37. package/src/core/import/elementor/context.ts +29 -0
  38. package/src/core/import/elementor/index.ts +23 -2
  39. package/src/core/import/elementor/widgets.ts +137 -17
  40. package/src/core/index.ts +9 -0
  41. package/src/core/render/index.ts +15 -2
  42. package/src/core/schema/layout.ts +4 -1
  43. package/src/core/theme/media-value.ts +88 -0
  44. package/src/core/visitor-cookie.ts +91 -0
  45. package/src/index.ts +28 -1
  46. package/src/mcp/agent-defaults.ts +40 -0
  47. package/src/mcp/extensions.ts +138 -0
  48. package/src/mcp/read.ts +55 -19
  49. package/src/mcp/tools.ts +3 -3
  50. package/src/mcp/write.ts +83 -8
  51. package/src/server/extension-routes.ts +37 -0
  52. package/src/server/plugin.ts +7 -1
@@ -0,0 +1,88 @@
1
+ /**
2
+ * W-1090 (#32): reading an EmDash image field's value. EmDash's admin stores a local upload as
3
+ * `{ id, provider: "local", meta: { storageKey }, mimeType }` with no `src`, and builds its URL
4
+ * at render time, so a reader that only looked at `src` found no image at all.
5
+ */
6
+
7
+ /** EmDash's own route for local media files (its `INTERNAL_MEDIA_PREFIX`). */
8
+ const LOCAL_MEDIA = "/_emdash/api/media/file/";
9
+ /** The field EmVB has always read when a Loop names none. */
10
+ export const DEFAULT_IMAGE_FIELD = "featured_image";
11
+ const IMAGE_PATH = /\.(?:avif|gif|jpe?g|png|svg|webp)(?:[?#]|$)/i;
12
+
13
+ type MediaLike = {
14
+ id?: unknown;
15
+ provider?: unknown;
16
+ src?: unknown;
17
+ url?: unknown;
18
+ previewUrl?: unknown;
19
+ mimeType?: unknown;
20
+ meta?: unknown;
21
+ };
22
+
23
+ const text = (value: unknown): string | undefined =>
24
+ typeof value === "string" && value.trim() ? value.trim() : undefined;
25
+
26
+ /** A storage key as a path under the media route, or undefined for one that leaves it. */
27
+ function keyPath(key: string): string | undefined {
28
+ const segments = key.split("/");
29
+ if (segments.some((s) => s === "" || s === "." || s === "..")) return undefined;
30
+ return segments.map(encodeURIComponent).join("/");
31
+ }
32
+
33
+ /** The URL an EmDash media value points at: its own URL, else a local file's route. */
34
+ export function mediaUrlOf(value: unknown): string | undefined {
35
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
36
+ const media = value as MediaLike;
37
+ const direct = text(media.src) ?? text(media.url) ?? text(media.previewUrl);
38
+ if (direct) return direct;
39
+ const provider = text(media.provider);
40
+ if (provider && provider !== "local") return undefined;
41
+ const meta = media.meta && typeof media.meta === "object" ? (media.meta as MediaLike) : {};
42
+ const storageKey = text((meta as { storageKey?: unknown }).storageKey);
43
+ const path = storageKey ? keyPath(storageKey) : undefined;
44
+ if (path) return `${LOCAL_MEDIA}${path}`;
45
+ // As EmDash's own image component: a local item without a storage key goes by its id.
46
+ const id = text(media.id);
47
+ return id ? `${LOCAL_MEDIA}${encodeURIComponent(id)}` : undefined;
48
+ }
49
+
50
+ /** True for an image field's value: a media value with an image type or an image file name. */
51
+ export function isImageValue(value: unknown): boolean {
52
+ const url = mediaUrlOf(value);
53
+ if (!url) return false;
54
+ const mimeType = text((value as MediaLike).mimeType);
55
+ if (mimeType) return mimeType.toLowerCase().startsWith("image/");
56
+ return IMAGE_PATH.test(url) || url.startsWith(LOCAL_MEDIA);
57
+ }
58
+
59
+ /**
60
+ * The image an entry shows when its Loop or post names no field: `featured_image` when it has
61
+ * one, else the entry's first field holding an image (the collection's first image field).
62
+ */
63
+ export function automaticImageField(data: Record<string, unknown>): string | undefined {
64
+ if (isImageValue(data[DEFAULT_IMAGE_FIELD])) return DEFAULT_IMAGE_FIELD;
65
+ return Object.keys(data).find((key) => isImageValue(data[key]));
66
+ }
67
+
68
+ /** The image value an entry shows: the named field's, or the automatic one's. */
69
+ export function entryImageValue(data: Record<string, unknown>, field?: string): unknown {
70
+ if (field) return data[field];
71
+ const auto = automaticImageField(data);
72
+ return auto ? data[auto] : undefined;
73
+ }
74
+
75
+ /**
76
+ * The image fields a collection's schema lists, for the editor's picker: `featured_image` first
77
+ * when it is one, as the automatic choice reads it first.
78
+ */
79
+ export function imageFieldsOf(
80
+ fields: readonly { slug: string; type: string; label?: string | null }[],
81
+ ): { slug: string; label: string }[] {
82
+ const images = fields
83
+ .filter((f) => f.type === "image")
84
+ .map((f) => ({ slug: f.slug, label: f.label?.trim() || f.slug }));
85
+ const preferred = images.findIndex((f) => f.slug === DEFAULT_IMAGE_FIELD);
86
+ if (preferred > 0) images.unshift(...images.splice(preferred, 1));
87
+ return images;
88
+ }
@@ -0,0 +1,91 @@
1
+ /**
2
+ * W-1092 (#34): when EmVB may set the `emvb_seen` cookie that new/returning Visitors rules use.
3
+ * Set from `emvb({ visitorCookie, visitorCookieConsent })` when the plugin starts; read when a
4
+ * page with such a rule renders. Kept on globalThis for the same reason as the geo-header setting
5
+ * (core/geo-trust.ts): the plugin and the page renderer can load this module twice.
6
+ *
7
+ * - `"always"` (default, as before 1.4.1): set it on a first visit to a page with such a rule.
8
+ * - `"consent"`: only when the request carries the site's own consent cookie with an accepted
9
+ * value. Without consent, EmVB neither reads nor sets it and everyone counts as new.
10
+ * - `"never"`: never read or set; everyone counts as new.
11
+ */
12
+ export type VisitorCookieMode = "always" | "consent" | "never";
13
+
14
+ /** The first-party cookie a site's consent banner sets, and the value(s) that mean "yes". */
15
+ export type VisitorCookieConsent = { cookie: string; value?: string | string[] };
16
+
17
+ export type VisitorCookieSetting = {
18
+ mode: VisitorCookieMode;
19
+ /** Only in "consent" mode; without a valid one, "consent" behaves as "never". */
20
+ consent?: { cookie: string; values: string[] };
21
+ };
22
+
23
+ /** Values that count as consent when the site doesn't name its own (compared case-insensitively). */
24
+ const DEFAULT_CONSENT_VALUES = new Set(["1", "true", "yes", "granted", "accepted", "allow", "all"]);
25
+
26
+ /** A cookie name (an RFC 6265 token), as a site owner would type it. */
27
+ const COOKIE_NAME = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]{1,128}$/;
28
+ const MAX_VALUES = 20;
29
+ const MAX_VALUE_LENGTH = 256;
30
+
31
+ const KEY = Symbol.for("emvb.visitorCookie");
32
+ type Holder = { [KEY]?: VisitorCookieSetting };
33
+
34
+ /** The setting from the two options; anything unrecognised falls back to the safe reading. */
35
+ export function visitorCookieSetting(mode: unknown, consent?: unknown): VisitorCookieSetting {
36
+ if (mode === "never") return { mode: "never" };
37
+ if (mode !== "consent") return { mode: "always" };
38
+ const parsed = consentOption(consent);
39
+ return parsed ? { mode: "consent", consent: parsed } : { mode: "never" };
40
+ }
41
+
42
+ function consentOption(input: unknown): VisitorCookieSetting["consent"] {
43
+ if (!input || typeof input !== "object") return undefined;
44
+ const { cookie, value } = input as { cookie?: unknown; value?: unknown };
45
+ if (typeof cookie !== "string" || !COOKIE_NAME.test(cookie.trim())) return undefined;
46
+ const given = (Array.isArray(value) ? value : [value])
47
+ .filter((v): v is string => typeof v === "string")
48
+ .filter((v) => v.length > 0 && v.length <= MAX_VALUE_LENGTH)
49
+ .slice(0, MAX_VALUES);
50
+ if (value !== undefined && given.length === 0) return undefined;
51
+ return { cookie: cookie.trim(), values: value === undefined ? [] : given };
52
+ }
53
+
54
+ /** The options as `emvb()` passes them to the plugin: only what was set, and only when valid. */
55
+ export function visitorCookieOptions(
56
+ mode: unknown,
57
+ consent: unknown,
58
+ ): { visitorCookie?: VisitorCookieMode; visitorCookieConsent?: VisitorCookieConsent } {
59
+ if (mode !== "always" && mode !== "consent" && mode !== "never") return {};
60
+ const setting = visitorCookieSetting(mode, consent);
61
+ if (setting.mode !== "consent" || !setting.consent) return { visitorCookie: setting.mode };
62
+ const { cookie, values } = setting.consent;
63
+ return {
64
+ visitorCookie: "consent",
65
+ visitorCookieConsent: values.length > 0 ? { cookie, value: values } : { cookie },
66
+ };
67
+ }
68
+
69
+ export function setVisitorCookie(mode: unknown, consent?: unknown): void {
70
+ (globalThis as Holder)[KEY] = visitorCookieSetting(mode, consent);
71
+ }
72
+
73
+ export function visitorCookie(): VisitorCookieSetting {
74
+ return (globalThis as Holder)[KEY] ?? { mode: "always" };
75
+ }
76
+
77
+ /**
78
+ * Whether this request may read and set `emvb_seen`. `readCookie` returns a cookie as the
79
+ * browser sent it. The site's named values match exactly; the defaults ignore case.
80
+ */
81
+ export function visitorCookieAllowed(
82
+ setting: VisitorCookieSetting,
83
+ readCookie: (name: string) => string | undefined,
84
+ ): boolean {
85
+ if (setting.mode === "always") return true;
86
+ if (setting.mode === "never" || !setting.consent) return false;
87
+ const sent = readCookie(setting.consent.cookie);
88
+ if (sent === undefined) return false;
89
+ if (setting.consent.values.length > 0) return setting.consent.values.includes(sent);
90
+ return DEFAULT_CONSENT_VALUES.has(sent.trim().toLowerCase());
91
+ }
package/src/index.ts CHANGED
@@ -3,6 +3,11 @@ import { ADMIN_ENTRY, PACKAGE_NAME, PLUGIN_ID, PLUGIN_VERSION } from "./constant
3
3
  import { canvasCollectionSlugs } from "./core/canvas-collections.ts";
4
4
  import { canvasStyleUrls } from "./core/canvas-styles.ts";
5
5
  import { loopCollectionSlugs } from "./core/loop-collections.ts";
6
+ import {
7
+ visitorCookieOptions,
8
+ type VisitorCookieConsent,
9
+ type VisitorCookieMode,
10
+ } from "./core/visitor-cookie.ts";
6
11
  import {
7
12
  listedExtensionManifests,
8
13
  rememberExtensions,
@@ -45,6 +50,20 @@ export type EmVBOptions = {
45
50
  * any collection, so set it if you keep a collection published but not meant to be listed.
46
51
  */
47
52
  loopCollections?: string[];
53
+ /**
54
+ * W-1092 (#34): when EmVB may keep the `emvb_seen` cookie (one year, first-party, HttpOnly)
55
+ * that tells new visitors from returning ones. Only pages with a new/returning Visitors rule
56
+ * ever read or set it. `"always"` (default) sets it on a first visit; `"consent"` only once
57
+ * the request carries `visitorCookieConsent`; `"never"` never. When it isn't allowed, everyone
58
+ * counts as a new visitor and a cookie left from before is cleared.
59
+ */
60
+ visitorCookie?: VisitorCookieMode;
61
+ /**
62
+ * W-1092: for `visitorCookie: "consent"`, the first-party cookie your consent banner sets, and
63
+ * the value (or values) that mean "accepted". Without `value`, `1`, `true`, `yes`, `granted`,
64
+ * `accepted`, `allow` or `all` count (any case). Missing or invalid, "consent" acts as "never".
65
+ */
66
+ visitorCookieConsent?: VisitorCookieConsent;
48
67
  };
49
68
 
50
69
  /** Descriptor that host sites add to `emdash({ plugins: [...] })` in astro.config. */
@@ -63,6 +82,13 @@ export function emvb(options: EmVBOptions = {}): PluginDescriptor {
63
82
  // oxlint-disable-next-line no-console -- build-time notice for the site owner (W-1086)
64
83
  console.warn(`[emvb] extension ${warning}`);
65
84
  }
85
+ const cookie = visitorCookieOptions(options.visitorCookie, options.visitorCookieConsent);
86
+ if (options.visitorCookie === "consent" && cookie.visitorCookie !== "consent") {
87
+ // oxlint-disable-next-line no-console -- build-time notice for the site owner (W-1092)
88
+ console.warn(
89
+ '[emvb] visitorCookie: "consent" needs visitorCookieConsent: { cookie: "<name>" }; until then the visitor cookie is never set',
90
+ );
91
+ }
66
92
  const ids = new Set(accepted.map((m) => m.id));
67
93
  const extensions = listedExtensionManifests().filter((m) => ids.has(m.id));
68
94
  return {
@@ -82,6 +108,7 @@ export function emvb(options: EmVBOptions = {}): PluginDescriptor {
82
108
  ...(typeof options.trustGeoHeaders === "boolean"
83
109
  ? { trustGeoHeaders: options.trustGeoHeaders }
84
110
  : {}),
111
+ ...cookie,
85
112
  },
86
113
  };
87
114
  }
@@ -93,7 +120,7 @@ export { createPlugin };
93
120
  /** W-1086: used by the server entry `emvb()` generates for extensions; not for site code. */
94
121
  export { registerBundledExtensions } from "./core/extensions/index.ts";
95
122
 
96
- export type { EmVBExtension, ExtensionManifest };
123
+ export type { EmVBExtension, ExtensionManifest, VisitorCookieConsent, VisitorCookieMode };
97
124
  export {
98
125
  defineExtension,
99
126
  EXTENSION_API_VERSION,
@@ -0,0 +1,40 @@
1
+ import { defaultElement, type ElementType, type LayoutNode } from "../core/index.ts";
2
+
3
+ /**
4
+ * W-1089 (#29): optional props whose Add-panel default is sample content (words, prices, links,
5
+ * a place, a ribbon). People get them as a starting point to edit; an element an agent adds
6
+ * keeps only what the agent set, so a price table with a title and a price doesn't also show
7
+ * "For growing teams.", a crossed-out "Custom domain" and a Featured ribbon. Required props keep
8
+ * their defaults, so the element stays valid.
9
+ */
10
+ export const AGENT_SAMPLE_PROPS: Readonly<Partial<Record<ElementType, readonly string[]>>> = {
11
+ alert: ["title"],
12
+ testimonial: ["role"],
13
+ counter: ["suffix", "title"],
14
+ progress: ["label"],
15
+ countdown: ["title"],
16
+ map: ["lat", "lng"],
17
+ "price-table": [
18
+ "description",
19
+ "currency",
20
+ "period",
21
+ "features",
22
+ "excluded",
23
+ "buttonText",
24
+ "buttonHref",
25
+ "featured",
26
+ ],
27
+ cta: ["text", "buttonText", "href"],
28
+ "flip-box": ["frontText", "backTitle", "backText", "buttonText", "href"],
29
+ headline: ["before", "after", "rotate"],
30
+ };
31
+
32
+ /** The element an agent's add starts from: the type's defaults without sample content. */
33
+ export function agentDefaultElement(type: ElementType, id: string): LayoutNode {
34
+ const base = defaultElement(type, id) as LayoutNode & { props?: Record<string, unknown> };
35
+ const sample = AGENT_SAMPLE_PROPS[type];
36
+ if (!sample || !base.props) return base;
37
+ const props = { ...base.props };
38
+ for (const key of sample) delete props[key];
39
+ return { ...base, props } as LayoutNode;
40
+ }
@@ -0,0 +1,138 @@
1
+ import {
2
+ listedExtensionManifests,
3
+ liveElement,
4
+ validateExtensionProps,
5
+ type ExtensionPropSchema,
6
+ } from "../core/index.ts";
7
+ import { MAX_TEXT_LENGTH } from "../core/limits.ts";
8
+ import { McpToolError } from "./errors.ts";
9
+
10
+ /**
11
+ * W-1089 (#38): extension elements (`ext:<pkg>/<name>`) for agents' direct tools. Only elements
12
+ * whose extension is registered on this site are listed or accepted, and their props are checked
13
+ * by the extension's own schema: invalid props are refused, never replaced by defaults.
14
+ */
15
+
16
+ /** The registered extension elements, as their manifests describe them. */
17
+ export function registeredExtensionElements() {
18
+ return listedExtensionManifests().flatMap((manifest) =>
19
+ manifest.elements
20
+ .filter((element) => liveElement(element.type) !== undefined)
21
+ .map((element) => Object.assign({ extensionId: manifest.id }, element)),
22
+ );
23
+ }
24
+
25
+ const withDefault = (out: Record<string, unknown>, value: unknown) =>
26
+ value === undefined ? out : Object.assign(out, { default: value });
27
+
28
+ /** JSON Schema for an extension's declarative prop schema, with EmVB's caps (as schema.ts). */
29
+ export function extensionJsonSchema(schema: ExtensionPropSchema): Record<string, unknown> {
30
+ switch (schema.type) {
31
+ case "string":
32
+ return withDefault(
33
+ {
34
+ type: "string",
35
+ maxLength: Math.min(schema.maxLength ?? MAX_TEXT_LENGTH, MAX_TEXT_LENGTH),
36
+ ...(schema.minLength ? { minLength: schema.minLength } : {}),
37
+ },
38
+ schema.default,
39
+ );
40
+ case "number":
41
+ return withDefault(
42
+ {
43
+ type: schema.integer ? "integer" : "number",
44
+ ...(schema.min !== undefined ? { minimum: schema.min } : {}),
45
+ ...(schema.max !== undefined ? { maximum: schema.max } : {}),
46
+ },
47
+ schema.default,
48
+ );
49
+ case "boolean":
50
+ return withDefault({ type: "boolean" }, schema.default);
51
+ case "enum":
52
+ return withDefault({ type: "string", enum: [...schema.values] }, schema.default);
53
+ case "array":
54
+ return withDefault(
55
+ {
56
+ type: "array",
57
+ items: extensionJsonSchema(schema.items),
58
+ maxItems: Math.min(schema.maxItems ?? 32, 32),
59
+ },
60
+ schema.default,
61
+ );
62
+ case "object":
63
+ return {
64
+ type: "object",
65
+ properties: Object.fromEntries(
66
+ Object.entries(schema.properties).map(([key, prop]) => [key, extensionJsonSchema(prop)]),
67
+ ),
68
+ ...(schema.required?.length ? { required: [...schema.required] } : {}),
69
+ additionalProperties: false,
70
+ };
71
+ default:
72
+ return {};
73
+ }
74
+ }
75
+
76
+ /** What a prop must be, in words, for a refusal. */
77
+ function expected(schema: ExtensionPropSchema): string {
78
+ switch (schema.type) {
79
+ case "string":
80
+ return `text of at most ${Math.min(schema.maxLength ?? MAX_TEXT_LENGTH, MAX_TEXT_LENGTH)} characters${schema.minLength ? ` and at least ${schema.minLength}` : ""}`;
81
+ case "number":
82
+ return `${schema.integer ? "a whole number" : "a number"}${schema.min !== undefined ? ` from ${schema.min}` : ""}${schema.max !== undefined ? ` up to ${schema.max}` : ""}`;
83
+ case "boolean":
84
+ return "true or false";
85
+ case "enum":
86
+ return `one of ${schema.values.join(", ")}`;
87
+ case "array":
88
+ return `a list of at most ${Math.min(schema.maxItems ?? 32, 32)} items`;
89
+ default:
90
+ return "an object";
91
+ }
92
+ }
93
+
94
+ /** Each prop that breaks the schema, in words. */
95
+ function propIssues(schema: ExtensionPropSchema, props: Record<string, unknown>): string[] {
96
+ if (schema.type !== "object") return ["its props don't match its schema"];
97
+ const issues: string[] = [];
98
+ for (const [key, value] of Object.entries(props)) {
99
+ const prop = schema.properties[key];
100
+ if (!prop) {
101
+ issues.push(`${key} isn't one of its props (${Object.keys(schema.properties).join(", ")})`);
102
+ } else if (
103
+ !validateExtensionProps({ type: "object", properties: { [key]: prop } }, { [key]: value }).ok
104
+ ) {
105
+ issues.push(`${key} must be ${expected(prop)}`);
106
+ }
107
+ }
108
+ for (const key of schema.required ?? []) {
109
+ const prop = schema.properties[key];
110
+ if (props[key] === undefined && !(prop && "default" in prop && prop.default !== undefined))
111
+ issues.push(`${key} is required`);
112
+ }
113
+ return issues;
114
+ }
115
+
116
+ /**
117
+ * The props an extension element may store: checked by its schema, with the schema's defaults
118
+ * for props left out. REFUSED when the extension isn't registered, INVALID_INPUT naming each
119
+ * wrong prop otherwise.
120
+ */
121
+ export function checkedExtensionProps(type: string, props: unknown): Record<string, unknown> {
122
+ const live = liveElement(type);
123
+ if (!live) {
124
+ throw new McpToolError(
125
+ "REFUSED",
126
+ `Unknown element type ${type}: no extension on this site provides it. Call list_element_types.`,
127
+ );
128
+ }
129
+ const given = props && typeof props === "object" && !Array.isArray(props) ? props : {};
130
+ const result = validateExtensionProps(live.element.schema, given);
131
+ if (result.ok) return result.props;
132
+ const issues = propIssues(live.element.schema, given as Record<string, unknown>);
133
+ throw new McpToolError(
134
+ "INVALID_INPUT",
135
+ `Invalid props for ${type}: ${(issues.length ? issues : ["they don't match its schema"]).join("; ")}. Call list_element_types with this type for its props.`,
136
+ { issues },
137
+ );
138
+ }
package/src/mcp/read.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  SECTION_RECIPES,
13
13
  SECTION_TEMPLATES,
14
14
  siteTokens,
15
+ validateExtensionProps,
15
16
  validateLayout,
16
17
  type DesignSystem,
17
18
  type ElementType,
@@ -26,6 +27,7 @@ import { requiredFieldIssues, requiredFieldIssueText } from "../core/forms/bindi
26
27
  import { isFormNode } from "../core/schema/layout.ts";
27
28
  import { forEachNode, nodeChildren } from "../core/tree-ops.ts";
28
29
  import { McpToolError } from "./errors.ts";
30
+ import { extensionJsonSchema, registeredExtensionElements } from "./extensions.ts";
29
31
  import type { EmvbPorts, PageRecord } from "./ports.ts";
30
32
 
31
33
  /** A stored layout the tools can work on, or a NOT_FOUND / INVALID_LAYOUT error the agent can read. */
@@ -157,9 +159,8 @@ const SCHEMAS = new Map(
157
159
  const sample = (type: string): LayoutNode =>
158
160
  Object.assign({}, defaultElement(type as ElementType, "sample"), { id: "sample" }) as LayoutNode;
159
161
 
160
- /** Which parent types accept `type`, by the same rule drag-and-drop and save use (W-354). */
161
- function allowedParents(type: string): string[] {
162
- const child = sample(type);
162
+ /** Which parent types accept `child`, by the same rule drag-and-drop and save use (W-354). */
163
+ function allowedParents(child: LayoutNode): string[] {
163
164
  return ELEMENT_DESCRIPTORS.map((d) => d.type).filter((parentType) => {
164
165
  const parent = sample(parentType);
165
166
  if (!isParentNode(parent)) return false;
@@ -181,6 +182,9 @@ export const ListElementTypesOutput = z.object({
181
182
  props: z.unknown(),
182
183
  example: z.unknown(),
183
184
  notes: z.string().optional(),
185
+ /** W-1089 (#38): an extension element's inspector fields and its extension's id. */
186
+ fields: z.unknown().optional(),
187
+ extension: z.string().optional(),
184
188
  }),
185
189
  ),
186
190
  });
@@ -205,29 +209,61 @@ const ELEMENT_NOTES: Record<string, string> = {
205
209
  "Use one per page band. props.contentWidth caps the inner width (for example 1200 px) while the background spans the screen.",
206
210
  };
207
211
 
212
+ /**
213
+ * W-1089 (#38): the extension elements registered on this site, as `ext:<pkg>/<name>` with the
214
+ * extension's prop schema (as JSON Schema), its inspector fields and its schema defaults.
215
+ */
216
+ function extensionEntries(type: string | undefined) {
217
+ return registeredExtensionElements()
218
+ .filter((element) => type === undefined || element.type === type)
219
+ .map((element) => {
220
+ const example = {
221
+ id: "sample",
222
+ type: element.type,
223
+ props: validateExtensionProps(element.schema, {}).props,
224
+ } as LayoutNode;
225
+ return {
226
+ type: element.type,
227
+ name: element.label,
228
+ group: element.group,
229
+ container: false,
230
+ allowedParents: allowedParents(example),
231
+ props: extensionJsonSchema(element.schema),
232
+ example: { type: element.type, props: example.props },
233
+ fields: element.fields,
234
+ extension: element.extensionId,
235
+ notes: `An extension element from ${element.extensionId}. Its props are checked by the extension's schema; it holds no children.`,
236
+ };
237
+ });
238
+ }
239
+
208
240
  export function listElementTypes(input: z.infer<typeof ListElementTypesInput>) {
209
241
  const descriptors = input.type
210
242
  ? ELEMENT_DESCRIPTORS.filter((d) => d.type === input.type)
211
243
  : ELEMENT_DESCRIPTORS;
212
- if (input.type && descriptors.length === 0) {
244
+ const extensions = extensionEntries(input.type);
245
+ if (input.type && descriptors.length === 0 && extensions.length === 0) {
213
246
  throw new McpToolError("NOT_FOUND", `Unknown element type ${input.type}.`);
214
247
  }
215
248
  return {
216
- elements: descriptors.map((d) => {
217
- const props = SCHEMAS.get(d.type);
218
- const example = sample(d.type);
219
- const entry: Record<string, unknown> = {
220
- type: d.type,
221
- name: d.name,
222
- group: d.group,
223
- container: isParentNode(example),
224
- allowedParents: allowedParents(d.type),
225
- props: props ? z.toJSONSchema(props, { unrepresentable: "any" }) : {},
226
- example: { type: example.type, props: (example as { props?: unknown }).props ?? {} },
227
- };
228
- if (ELEMENT_NOTES[d.type]) entry["notes"] = ELEMENT_NOTES[d.type];
229
- return entry;
230
- }),
249
+ elements: [
250
+ ...descriptors.map((d) => {
251
+ const props = SCHEMAS.get(d.type);
252
+ const example = sample(d.type);
253
+ const entry: Record<string, unknown> = {
254
+ type: d.type,
255
+ name: d.name,
256
+ group: d.group,
257
+ container: isParentNode(example),
258
+ allowedParents: allowedParents(example),
259
+ props: props ? z.toJSONSchema(props, { unrepresentable: "any" }) : {},
260
+ example: { type: example.type, props: (example as { props?: unknown }).props ?? {} },
261
+ };
262
+ if (ELEMENT_NOTES[d.type]) entry["notes"] = ELEMENT_NOTES[d.type];
263
+ return entry;
264
+ }),
265
+ ...extensions,
266
+ ],
231
267
  };
232
268
  }
233
269
 
package/src/mcp/tools.ts CHANGED
@@ -64,7 +64,7 @@ const READ_TOOLS: ToolDef[] = [
64
64
  name: "list_element_types",
65
65
  title: "List element types",
66
66
  description:
67
- "Lists every EmVB element type with its props JSON Schema, whether it holds children, which parents accept it and a default example. Never invent element types.",
67
+ "Lists every EmVB element type with its props JSON Schema, whether it holds children, which parents accept it and a default example, plus the extension elements registered on this site (ext:<package>/<name>, with their fields). Never invent element types.",
68
68
  input: read.ListElementTypesInput,
69
69
  output: read.ListElementTypesOutput,
70
70
  readOnly: true,
@@ -155,7 +155,7 @@ const WRITE_TOOLS: ToolDef[] = [
155
155
  name: "create_page",
156
156
  title: "Create a page",
157
157
  description:
158
- "Creates a new unpublished EmVB page with a starter layout, optionally followed by section recipes (hero, features, …), or from a starter page template (template: see list_templates). Returns the page id and rev.",
158
+ "Creates a new unpublished EmVB page with a starter layout, optionally followed by section recipes (hero, features, …), or from a starter page template (template: see list_templates). Without a template or a hero recipe the page starts with an H1 of its title: titleHeading false leaves it out, and an element with an H1 added later replaces it while it is unchanged. Returns the page id and rev.",
159
159
  input: write.CreatePageInput,
160
160
  output: write.CreatePageOutput,
161
161
  readOnly: false,
@@ -166,7 +166,7 @@ const WRITE_TOOLS: ToolDef[] = [
166
166
  name: "add_element",
167
167
  title: "Add an element",
168
168
  description:
169
- "Adds an element (with optional children) into parentId at index (default: last). Unset props take the type's defaults; ids are generated. Refused with the editor's reason when the parent can't hold it.",
169
+ "Adds an element (with optional children) into parentId at index (default: last). Unset required props take the type's defaults; optional props you leave out stay unset (no sample text, links or prices); ids are generated. Refused with the editor's reason when the parent can't hold it.",
170
170
  input: write.AddElementInput,
171
171
  output: write.WriteOutput,
172
172
  readOnly: false,