@perkyzz/emvb 1.3.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 (161) hide show
  1. package/README.md +2 -2
  2. package/package.json +2 -2
  3. package/src/admin/bulk-api.ts +5 -1
  4. package/src/admin/content-item.ts +3 -0
  5. package/src/admin/copy-rich-text.ts +99 -9
  6. package/src/admin/editor/A11yCopilot.tsx +3 -1
  7. package/src/admin/editor/Editor.tsx +28 -3
  8. package/src/admin/editor/Timeline.tsx +1 -8
  9. package/src/admin/editor/canvas/DeviceBar.tsx +7 -2
  10. package/src/admin/editor/canvas/EmptyCanvas.tsx +11 -2
  11. package/src/admin/editor/canvas/use-canvas-dnd.ts +1 -20
  12. package/src/admin/editor/canvas/vnode-react.tsx +2 -0
  13. package/src/admin/editor/co-design.ts +36 -1
  14. package/src/admin/editor/collection-previews.ts +7 -8
  15. package/src/admin/editor/dnd/dragged-source.ts +22 -0
  16. package/src/admin/editor/dnd/layer-drop.ts +141 -0
  17. package/src/admin/editor/dnd/new-element.ts +16 -0
  18. package/src/admin/editor/editor-css.ts +9 -1
  19. package/src/admin/editor/element-chrome.ts +6 -0
  20. package/src/admin/editor/extensions/ExtensionPanels.tsx +33 -1
  21. package/src/admin/editor/extensions-context.tsx +16 -1
  22. package/src/admin/editor/feature-css.ts +27 -0
  23. package/src/admin/editor/inert-links.ts +8 -0
  24. package/src/admin/editor/panels/ColorControl.tsx +2 -2
  25. package/src/admin/editor/panels/ConditionsEditor.tsx +18 -0
  26. package/src/admin/editor/panels/ElementPanel.tsx +2 -2
  27. package/src/admin/editor/panels/FontFaces.tsx +342 -0
  28. package/src/admin/editor/panels/LayersPanel.tsx +56 -6
  29. package/src/admin/editor/panels/LeftPanel.tsx +153 -29
  30. package/src/admin/editor/panels/SettingsPanel.tsx +1 -0
  31. package/src/admin/editor/panels/SiteStylesDrawer.tsx +5 -0
  32. package/src/admin/editor/panels/TemplatesPanel.tsx +205 -0
  33. package/src/admin/editor/panels/TokenScales.tsx +2 -0
  34. package/src/admin/editor/panels/TriggersEditor.tsx +203 -9
  35. package/src/admin/editor/panels/VariableSection.tsx +111 -7
  36. package/src/admin/editor/panels/color-space.ts +71 -6
  37. package/src/admin/editor/panels/settings/AudienceEditor.tsx +3 -0
  38. package/src/admin/editor/panels/settings/FieldControl.tsx +33 -0
  39. package/src/admin/editor/panels/settings/FormBindControl.tsx +27 -31
  40. package/src/admin/editor/panels/settings/ImageFieldControl.tsx +106 -0
  41. package/src/admin/editor/panels/settings/LoopItemBindControl.tsx +9 -3
  42. package/src/admin/editor/panels/settings/StickyControl.tsx +97 -0
  43. package/src/admin/editor/panels/settings/StyleRow.tsx +14 -0
  44. package/src/admin/editor/panels/settings/loop-context.ts +34 -3
  45. package/src/admin/editor/panels/settings/style-sections.ts +19 -2
  46. package/src/admin/editor/panels/url-rules.ts +43 -0
  47. package/src/admin/editor/panels/use-layers-drop.ts +232 -0
  48. package/src/admin/editor/store.ts +4 -2
  49. package/src/admin/editor/useExtensions.ts +3 -1
  50. package/src/admin/editor/useNodeActions.ts +74 -1
  51. package/src/admin/editor/useSave.ts +116 -85
  52. package/src/admin/export-api.ts +27 -2
  53. package/src/admin/extension-outputs.ts +236 -0
  54. package/src/admin/font-files-api.ts +38 -0
  55. package/src/admin/import-forms.ts +133 -0
  56. package/src/admin/pages/ImportButton.tsx +15 -4
  57. package/src/admin/pages/ImportElementorDialog.tsx +53 -187
  58. package/src/admin/pages/ImportForms.tsx +71 -0
  59. package/src/admin/pages/ImportHtmlDialog.tsx +209 -0
  60. package/src/admin/pages/ImportImageCopies.tsx +167 -0
  61. package/src/admin/pages/ImportReport.tsx +63 -0
  62. package/src/admin/pages/NewPageDialog.tsx +54 -32
  63. package/src/admin/pages/PageList.tsx +9 -0
  64. package/src/admin/pages/ThemePartList.tsx +9 -0
  65. package/src/admin/setup/plan.ts +2 -0
  66. package/src/admin/ui.ts +7 -0
  67. package/src/admin/widgets/ConvertToRichText.tsx +3 -2
  68. package/src/astro/EmVBPage.astro +5 -2
  69. package/src/astro/extension-styles.ts +35 -0
  70. package/src/astro/forms/EmVBFormsClient.astro +3 -0
  71. package/src/astro/forms/enhance.ts +107 -0
  72. package/src/astro/popups/runtime.ts +47 -2
  73. package/src/astro/render.ts +25 -4
  74. package/src/astro/resolve-theme.ts +11 -4
  75. package/src/astro/resolve.ts +2 -0
  76. package/src/astro/theme-posts.ts +17 -23
  77. package/src/astro/visitor.ts +14 -5
  78. package/src/astro/widgets/EmVBStickyRuntime.astro +9 -0
  79. package/src/astro/widgets/EmVBThemeRuntime.astro +9 -0
  80. package/src/astro/widgets/EmVBWidgetRuntimes.astro +12 -0
  81. package/src/astro/widgets/alerts.ts +16 -2
  82. package/src/astro/widgets/carousel.ts +65 -24
  83. package/src/astro/widgets/countdown.ts +18 -7
  84. package/src/astro/widgets/extension-runtimes.ts +27 -0
  85. package/src/astro/widgets/headline.ts +14 -5
  86. package/src/astro/widgets/sticky.ts +87 -0
  87. package/src/astro/widgets/theme.ts +52 -0
  88. package/src/constants.ts +1 -1
  89. package/src/core/a11y/audit.ts +150 -2
  90. package/src/core/arrange.ts +19 -1
  91. package/src/core/css/font-face.ts +72 -0
  92. package/src/core/css/generate.ts +41 -2
  93. package/src/core/css/trace.ts +8 -0
  94. package/src/core/data/bindings.ts +7 -4
  95. package/src/core/elements/dynamic-elements.ts +1 -1
  96. package/src/core/elements/element-nouns.ts +48 -0
  97. package/src/core/elements/form-elements.ts +119 -9
  98. package/src/core/elements/icon-svg.ts +14 -0
  99. package/src/core/elements/index.ts +24 -4
  100. package/src/core/elements/input-limits.ts +44 -0
  101. package/src/core/elements/menu.ts +109 -47
  102. package/src/core/elements/site.ts +108 -0
  103. package/src/core/elements/widgets.ts +13 -3
  104. package/src/core/export/runtimes.generated.ts +7 -5
  105. package/src/core/export/site.ts +53 -4
  106. package/src/core/extensions/classes.ts +114 -0
  107. package/src/core/extensions/index.ts +19 -2
  108. package/src/core/extensions/normalize.ts +13 -0
  109. package/src/core/extensions/placeholder.ts +7 -2
  110. package/src/core/extensions/registry.ts +134 -10
  111. package/src/core/extensions/render-ext.ts +115 -36
  112. package/src/core/extensions/safe-nodes.ts +67 -11
  113. package/src/core/extensions/types.ts +48 -1
  114. package/src/core/fonts/files.ts +74 -0
  115. package/src/core/fonts/google.ts +112 -0
  116. package/src/core/fonts/test-font.ts +9 -0
  117. package/src/core/import/elementor/context.ts +42 -4
  118. package/src/core/import/elementor/index.ts +55 -23
  119. package/src/core/import/elementor/widgets.ts +242 -20
  120. package/src/core/import/html/blocks.ts +602 -0
  121. package/src/core/import/html/index.ts +155 -0
  122. package/src/core/import/html/map.ts +958 -0
  123. package/src/core/import/html/parse.ts +430 -0
  124. package/src/core/index.ts +54 -0
  125. package/src/core/migrate/v18.ts +3 -0
  126. package/src/core/public-attributes.ts +17 -0
  127. package/src/core/render/extras.ts +31 -7
  128. package/src/core/render/form.ts +103 -10
  129. package/src/core/render/index.ts +165 -16
  130. package/src/core/render/section.ts +31 -1
  131. package/src/core/render/spacer-basis.ts +102 -0
  132. package/src/core/render/theme-boot.ts +16 -0
  133. package/src/core/render/vnode.ts +1 -1
  134. package/src/core/sanitize/css.ts +68 -3
  135. package/src/core/sanitize/motion.ts +12 -0
  136. package/src/core/schema/design.ts +40 -0
  137. package/src/core/schema/layout.ts +118 -6
  138. package/src/core/schema/style.ts +28 -0
  139. package/src/core/templates/index.ts +218 -0
  140. package/src/core/templates/pages.ts +29 -0
  141. package/src/core/templates/sections.ts +794 -0
  142. package/src/core/templates/types.ts +9 -0
  143. package/src/core/theme/dynamic.ts +9 -6
  144. package/src/core/theme/media-value.ts +88 -0
  145. package/src/core/theme/popup-markup.ts +21 -2
  146. package/src/core/theme/popup-rules.ts +36 -0
  147. package/src/core/theme/triggers.ts +64 -5
  148. package/src/core/translatable.ts +5 -2
  149. package/src/core/visitor-cookie.ts +91 -0
  150. package/src/extension-build.ts +331 -0
  151. package/src/index.ts +53 -4
  152. package/src/mcp/agent-defaults.ts +40 -0
  153. package/src/mcp/brief.ts +191 -0
  154. package/src/mcp/extensions.ts +138 -0
  155. package/src/mcp/prompts.ts +33 -0
  156. package/src/mcp/read.ts +84 -20
  157. package/src/mcp/tools.ts +42 -3
  158. package/src/mcp/write.ts +124 -9
  159. package/src/server/extension-routes.ts +110 -0
  160. package/src/server/font-routes.ts +301 -0
  161. package/src/server/plugin.ts +15 -0
@@ -7,14 +7,19 @@
7
7
  * and the renderer look them up by id.
8
8
  */
9
9
 
10
+ import { cleanExtensionAssets, normalizeClasses } from "./classes.ts";
10
11
  import { normalizeExtension } from "./normalize.ts";
11
- import type { EmVBExtension, ExtensionManifest } from "./types.ts";
12
+ import type { EmVBExtension, ExtensionAssets, ExtensionManifest } from "./types.ts";
12
13
 
13
14
  const KEY = Symbol.for("emvb.extensions.v1");
14
15
 
15
16
  type Store = {
16
17
  byId: Map<string, EmVBExtension>;
17
18
  manifests: ExtensionManifest[];
19
+ /** W-1086: stylesheet and runtime text read at build time, by extension id. */
20
+ assets?: Map<string, ExtensionAssets>;
21
+ /** W-1086: each extension's class allowlist as a set, by extension id. */
22
+ allow?: Map<string, ReadonlySet<string>>;
18
23
  };
19
24
 
20
25
  function store(): Store {
@@ -23,6 +28,26 @@ function store(): Store {
23
28
  return g[KEY];
24
29
  }
25
30
 
31
+ function assetsMap(): Map<string, ExtensionAssets> {
32
+ const s = store();
33
+ s.assets ??= new Map();
34
+ return s.assets;
35
+ }
36
+
37
+ function allowMap(): Map<string, ReadonlySet<string>> {
38
+ const s = store();
39
+ s.allow ??= new Map();
40
+ return s.allow;
41
+ }
42
+
43
+ function rememberManifest(manifest: ExtensionManifest): void {
44
+ const s = store();
45
+ s.manifests = s.manifests.filter((m) => m.id !== manifest.id);
46
+ s.manifests.push(manifest);
47
+ if (manifest.classes) allowMap().set(manifest.id, new Set(manifest.classes.allow));
48
+ else allowMap().delete(manifest.id);
49
+ }
50
+
26
51
  /** Register live extensions from `emvb({ extensions })`. Returns serializable manifests. */
27
52
  export function rememberExtensions(input: unknown): ExtensionManifest[] {
28
53
  const list = Array.isArray(input) ? input : [];
@@ -33,16 +58,91 @@ export function rememberExtensions(input: unknown): ExtensionManifest[] {
33
58
  if (!normalized) continue;
34
59
  s.byId.set(normalized.live.id, normalized.live);
35
60
  // Replace an existing manifest for the same id (re-import / HMR).
36
- s.manifests = s.manifests.filter((m) => m.id !== normalized.manifest.id);
37
- s.manifests.push(normalized.manifest);
61
+ rememberManifest(normalized.manifest);
38
62
  manifests.push(normalized.manifest);
39
63
  }
40
64
  return manifests;
41
65
  }
42
66
 
43
- /** Manifests currently remembered (for editor/config). */
67
+ /**
68
+ * W-1086: called by the server entry the integration generates (extension-build.ts). Each pair is
69
+ * an extension module's namespace and the extension id it exports; the export whose
70
+ * `extensionApi` and `id` match is registered, so render functions reach Workers and production
71
+ * builds, where astro.config never runs.
72
+ */
73
+ export function registerBundledExtensions(entries: readonly (readonly [unknown, string])[]): void {
74
+ const found: unknown[] = [];
75
+ for (const [namespace, id] of entries) {
76
+ if (!namespace || typeof namespace !== "object") continue;
77
+ const match = Object.values(namespace).find(
78
+ (value) =>
79
+ !!value &&
80
+ typeof value === "object" &&
81
+ (value as { extensionApi?: unknown }).extensionApi === 1 &&
82
+ (value as { id?: unknown }).id === id,
83
+ );
84
+ if (match) found.push(match);
85
+ }
86
+ rememberExtensions(found);
87
+ }
88
+
89
+ /**
90
+ * W-1086: keep the build-time stylesheet and runtime text of extension `id`. Text that fails the
91
+ * checks in classes.ts is dropped.
92
+ */
93
+ export function rememberExtensionAssets(id: string, assets: unknown): void {
94
+ const clean = cleanExtensionAssets(assets);
95
+ if (clean) assetsMap().set(id, clean);
96
+ else assetsMap().delete(id);
97
+ }
98
+
99
+ /** W-1086: the build-time stylesheet and runtime text of extension `id`, if any. */
100
+ export function extensionAssets(id: string): ExtensionAssets | undefined {
101
+ return store().assets?.get(id);
102
+ }
103
+
104
+ /**
105
+ * W-1086: the stylesheets of extensions `ids` (each once, by id), as one sheet. Pages and theme
106
+ * parts that render apart (`renderPage` with `separateExtensionCss`) collect the ids they used
107
+ * and write this once per document.
108
+ */
109
+ export function extensionStylesheets(ids: Iterable<string>): string {
110
+ return [...new Set(ids)]
111
+ .toSorted()
112
+ .flatMap((id) => {
113
+ const css = extensionAssets(id)?.css;
114
+ return css ? [`/* ${id} */\n${css}\n`] : [];
115
+ })
116
+ .join("");
117
+ }
118
+
119
+ /** W-1086: the class allowlist of extension `id` (empty when it declares none). */
120
+ export function extensionClassAllowlist(id: string): ReadonlySet<string> | undefined {
121
+ return store().allow?.get(id);
122
+ }
123
+
124
+ /**
125
+ * W-1086: the admin has manifests (from editor/config) but no live extension code. Remembering
126
+ * them gives the editor canvas and the HTML export the class allowlists and assets.
127
+ */
128
+ export function rememberExtensionManifests(input: readonly unknown[]): void {
129
+ for (const item of input) {
130
+ if (!item || typeof item !== "object") continue;
131
+ const m = item as ExtensionManifest;
132
+ if (m.extensionApi !== 1 || typeof m.id !== "string" || !Array.isArray(m.elements)) continue;
133
+ const classes = normalizeClasses(m.classes);
134
+ const { assets, ...rest } = m;
135
+ rememberManifest({ ...rest, ...(classes ? { classes } : {}) });
136
+ rememberExtensionAssets(m.id, assets);
137
+ }
138
+ }
139
+
140
+ /** Manifests currently remembered (for editor/config), with their build-time assets. */
44
141
  export function listedExtensionManifests(): ExtensionManifest[] {
45
- return store().manifests.slice();
142
+ return store().manifests.map((m) => {
143
+ const assets = extensionAssets(m.id);
144
+ return assets ? Object.assign({}, m, { assets }) : m;
145
+ });
46
146
  }
47
147
 
48
148
  /** Live extension by package id. */
@@ -75,20 +175,44 @@ export function clearExtensions(): void {
75
175
  const s = store();
76
176
  s.byId.clear();
77
177
  s.manifests = [];
178
+ s.assets?.clear();
179
+ s.allow?.clear();
78
180
  }
79
181
 
80
182
  /** Rebuild manifests from options.extensions after createPlugin (ids only or full manifests). */
81
183
  export function manifestsFromOptions(input: unknown): ExtensionManifest[] {
82
184
  if (!Array.isArray(input)) return listedExtensionManifests();
83
- // Prefer live registry order; fall back to whatever was serialized.
84
- const live = listedExtensionManifests();
85
- if (live.length > 0) return live;
185
+ // W-1086: the integration read `css` and `runtime` at build time and passed their text in the
186
+ // serialized options; a Workers or production server has no files to read them from.
187
+ for (const item of input) {
188
+ if (!item || typeof item !== "object") continue;
189
+ const { id, assets } = item as { id?: unknown; assets?: unknown };
190
+ if (typeof id === "string" && assets !== undefined) rememberExtensionAssets(id, assets);
191
+ }
192
+ // W-1086: a Worker or production server has live code only for the extensions the generated
193
+ // entry bundled (those that name their `module`). Every other extension still has its serialized
194
+ // manifest, so merge by id: the live manifest wins, the serialized one fills the gaps.
195
+ const live = new Map(listedExtensionManifests().map((m) => [m.id, m]));
86
196
  const out: ExtensionManifest[] = [];
197
+ const seen = new Set<string>();
87
198
  for (const item of input) {
88
199
  if (!item || typeof item !== "object") continue;
89
200
  const m = item as ExtensionManifest;
90
- if (m.extensionApi !== 1 || typeof m.id !== "string") continue;
91
- out.push(m);
201
+ if (m.extensionApi !== 1 || typeof m.id !== "string" || !Array.isArray(m.elements)) continue;
202
+ if (seen.has(m.id)) continue;
203
+ seen.add(m.id);
204
+ const own = live.get(m.id);
205
+ if (own) {
206
+ out.push(own);
207
+ continue;
208
+ }
209
+ const { assets: _assets, ...rest } = m;
210
+ const classes = normalizeClasses(m.classes);
211
+ const manifest = { ...rest, ...(classes ? { classes } : {}) };
212
+ if (classes) allowMap().set(m.id, new Set(classes.allow));
213
+ const assets = extensionAssets(m.id);
214
+ out.push(assets ? { ...manifest, assets } : manifest);
92
215
  }
216
+ for (const [id, manifest] of live) if (!seen.has(id)) out.push(manifest);
93
217
  return out;
94
218
  }
@@ -5,12 +5,13 @@
5
5
 
6
6
  import type { LayoutNode } from "../schema/layout.ts";
7
7
  import type { VNode } from "../render/vnode.ts";
8
- import { liveElement, liveExtension } from "./registry.ts";
8
+ import { extensionClassAllowlist, liveElement, liveExtension } from "./registry.ts";
9
9
  import { validateExtensionProps } from "./schema.ts";
10
10
  import { safeExtensionOutput } from "./safe-nodes.ts";
11
11
  import { extensionPlaceholderVNode } from "./placeholder.ts";
12
12
  import type { ExtensionRenderContext } from "./types.ts";
13
13
  import { parseExtensionType } from "./namespace.ts";
14
+ import { cleanBoundText } from "../data/bindings.ts";
14
15
 
15
16
  export type ExtensionRenderMode = "public" | "editor";
16
17
 
@@ -18,23 +19,24 @@ function isThenable(value: unknown): value is Promise<unknown> {
18
19
  return !!value && typeof (value as { then?: unknown }).then === "function";
19
20
  }
20
21
 
21
- function cleanSourceRecord(raw: Readonly<Record<string, string>>): Record<string, string> {
22
+ /** Longest source value kept, in UTF-16 code units. */
23
+ const MAX_SOURCE_VALUE = 2000;
24
+ /** Values kept per source. */
25
+ const MAX_SOURCE_FIELDS = 32;
26
+
27
+ /**
28
+ * A source's result with bad keys and non-string values dropped, and each value cleaned like a
29
+ * bound value (control characters and bidi overrides removed, length capped; W-1088).
30
+ */
31
+ function cleanSourceRecord(raw: unknown): Record<string, string> {
22
32
  const out: Record<string, string> = {};
33
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return out;
23
34
  let n = 0;
24
- for (const [key, value] of Object.entries(raw)) {
25
- if (n >= 32) break;
26
- if (typeof key !== "string" || !/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(key)) continue;
35
+ for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
36
+ if (n >= MAX_SOURCE_FIELDS) break;
37
+ if (!/^[a-zA-Z][a-zA-Z0-9_.-]{0,63}$/.test(key)) continue;
27
38
  if (typeof value !== "string") continue;
28
- let cleaned = "";
29
- for (const char of value) {
30
- const code = char.codePointAt(0) ?? 0;
31
- if (code === 9) cleaned += " ";
32
- else if (code === 10 || (code >= 32 && code !== 127 && !(code >= 0x80 && code <= 0x9f))) {
33
- cleaned += char;
34
- }
35
- if (cleaned.length >= 2000) break;
36
- }
37
- out[key] = cleaned.trim();
39
+ out[key] = cleanBoundText(value, MAX_SOURCE_VALUE);
38
40
  n += 1;
39
41
  }
40
42
  return out;
@@ -52,7 +54,7 @@ export function syncSourceValues(pkg: string): Record<string, Record<string, str
52
54
  try {
53
55
  const result = source.resolve();
54
56
  if (result && typeof result === "object" && !Array.isArray(result) && !isThenable(result)) {
55
- out[source.name] = cleanSourceRecord(result as Readonly<Record<string, string>>);
57
+ out[source.name] = cleanSourceRecord(result);
56
58
  } else {
57
59
  out[source.name] = {};
58
60
  }
@@ -63,8 +65,91 @@ export function syncSourceValues(pkg: string): Record<string, Record<string, str
63
65
  return out;
64
66
  }
65
67
 
68
+ /** How long the editor waits for one source (W-1088). */
69
+ const SOURCE_TIMEOUT_MS = 5000;
70
+
71
+ /**
72
+ * W-1088 (#36): one source's values for the editor's extension panels, awaited (a source may be
73
+ * async), cleaned like bound values. Undefined when the extension or source isn't live here, the
74
+ * resolver throws, or it takes longer than `timeoutMs`.
75
+ */
76
+ export async function resolveExtensionSource(
77
+ pkg: string,
78
+ name: string,
79
+ timeoutMs = SOURCE_TIMEOUT_MS,
80
+ ): Promise<Record<string, string> | undefined> {
81
+ const source = liveExtension(pkg)?.sources?.find((s) => s.name === name);
82
+ if (!source) return undefined;
83
+ let timer: ReturnType<typeof setTimeout> | undefined;
84
+ try {
85
+ const result = await Promise.race([
86
+ Promise.resolve().then(() => source.resolve()),
87
+ new Promise<undefined>((resolve) => {
88
+ timer = setTimeout(() => resolve(undefined), timeoutMs);
89
+ }),
90
+ ]);
91
+ if (!result || typeof result !== "object" || Array.isArray(result)) return undefined;
92
+ return cleanSourceRecord(result);
93
+ } catch {
94
+ return undefined;
95
+ } finally {
96
+ if (timer) clearTimeout(timer);
97
+ }
98
+ }
99
+
66
100
  export type VisitChildren = (nodes: LayoutNode[]) => VNode[];
67
101
 
102
+ const propsOf = (node: { props?: unknown }): Record<string, unknown> =>
103
+ node.props && typeof node.props === "object" && !Array.isArray(node.props)
104
+ ? (node.props as Record<string, unknown>)
105
+ : {};
106
+
107
+ /** Stable JSON: object keys sorted, so equal props give equal keys. */
108
+ function stableJson(value: unknown): string {
109
+ if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
110
+ if (value && typeof value === "object") {
111
+ const entries = Object.entries(value as Record<string, unknown>)
112
+ .filter(([, v]) => v !== undefined)
113
+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
114
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableJson(v)}`).join(",")}}`;
115
+ }
116
+ return JSON.stringify(value) ?? "null";
117
+ }
118
+
119
+ /**
120
+ * W-1086: the key of one extension element's output: its type and props. The admin has no
121
+ * extension code, so the editor canvas and the HTML export ask the server for outputs by key.
122
+ */
123
+ export function extensionOutputKey(node: { type: string; props?: unknown }): string {
124
+ return `${node.type}\n${stableJson(propsOf(node))}`;
125
+ }
126
+
127
+ /** Raw render output per `extensionOutputKey`, rendered by the server for the admin. */
128
+ export type ExtensionOutputs = ReadonlyMap<string, unknown>;
129
+
130
+ /**
131
+ * Run the live render() of a stored extension element and check its output. Undefined when the
132
+ * extension is missing here, render throws, or nothing legal is left.
133
+ */
134
+ export function liveExtensionOutput(node: {
135
+ type: string;
136
+ props?: unknown;
137
+ }): LayoutNode[] | undefined {
138
+ const parsed = parseExtensionType(node.type);
139
+ const found = parsed ? liveElement(node.type) : undefined;
140
+ if (!parsed || !found) return undefined;
141
+ const checked = validateExtensionProps(found.manifest.schema, propsOf(node));
142
+ const ctx: ExtensionRenderContext = { sources: syncSourceValues(parsed.pkg) };
143
+ let raw: unknown;
144
+ try {
145
+ raw = found.element.render(checked.props, ctx);
146
+ } catch {
147
+ return undefined;
148
+ }
149
+ const safe = safeExtensionOutput(raw, Math.random, extensionClassAllowlist(parsed.pkg));
150
+ return safe.length > 0 ? safe : undefined;
151
+ }
152
+
68
153
  /**
69
154
  * Build the VNode for a stored extension element. Always returns a node (placeholder
70
155
  * on failure) so siblings keep rendering.
@@ -73,6 +158,10 @@ export function renderExtensionNode(
73
158
  node: LayoutNode,
74
159
  mode: ExtensionRenderMode,
75
160
  visitChildren: VisitChildren,
161
+ /** W-1086: server-rendered outputs (the admin's canvas and export), by `extensionOutputKey`. */
162
+ outputs?: ExtensionOutputs,
163
+ /** W-1086: told the package id whenever one of its elements renders. */
164
+ rendered?: (pkg: string) => void,
76
165
  ): VNode {
77
166
  const id = typeof node.id === "string" ? node.id : undefined;
78
167
  const type = node.type;
@@ -81,29 +170,19 @@ export function renderExtensionNode(
81
170
  return extensionPlaceholderVNode(type, id, mode);
82
171
  }
83
172
 
84
- const found = liveElement(type);
85
- if (!found) {
86
- return extensionPlaceholderVNode(type, id, mode);
173
+ let safe = liveExtensionOutput(node);
174
+ if (!safe && !liveElement(type) && outputs?.has(extensionOutputKey(node))) {
175
+ // The server's output is checked again here, with the allowlist the admin was sent.
176
+ safe = safeExtensionOutput(
177
+ outputs.get(extensionOutputKey(node)),
178
+ Math.random,
179
+ extensionClassAllowlist(parsed.pkg),
180
+ );
87
181
  }
88
-
89
- const storedProps =
90
- node.props && typeof node.props === "object" && !Array.isArray(node.props)
91
- ? (node.props as Record<string, unknown>)
92
- : {};
93
- const checked = validateExtensionProps(found.manifest.schema, storedProps);
94
- const ctx: ExtensionRenderContext = { sources: syncSourceValues(parsed.pkg) };
95
-
96
- let raw: unknown;
97
- try {
98
- raw = found.element.render(checked.props, ctx);
99
- } catch {
100
- return extensionPlaceholderVNode(type, id, mode);
101
- }
102
-
103
- const safe = safeExtensionOutput(raw);
104
- if (safe.length === 0) {
182
+ if (!safe || safe.length === 0) {
105
183
  return extensionPlaceholderVNode(type, id, mode);
106
184
  }
185
+ rendered?.(parsed.pkg);
107
186
 
108
187
  const children = visitChildren(safe);
109
188
  return {
@@ -10,6 +10,20 @@ import { KNOWN_ELEMENT_TYPES } from "../schema/layout.ts";
10
10
  import { validateLayout } from "../validate.ts";
11
11
  import { newNodeId } from "../tree-ops.ts";
12
12
  import { isExtensionType } from "./namespace.ts";
13
+ import { filterExtensionClasses } from "./classes.ts";
14
+
15
+ /**
16
+ * W-1086: the extension classes each validated output node keeps. Render output only: they ride
17
+ * beside the node, never in it, so the stored layout schema and its validation are unchanged.
18
+ */
19
+ const EXT_CLASSES = new WeakMap<object, readonly string[]>();
20
+
21
+ /** The allowlisted extension classes of an output node (none for every other node). */
22
+ export function extensionClassesOf(node: object): readonly string[] | undefined {
23
+ return EXT_CLASSES.get(node);
24
+ }
25
+
26
+ type Coerced = { node: Record<string, unknown>; classes: string[]; children?: Coerced[] };
13
27
 
14
28
  const KNOWN = new Set<string>(KNOWN_ELEMENT_TYPES);
15
29
  const MAX_NODES = 32;
@@ -20,7 +34,8 @@ function coerce(
20
34
  depth: number,
21
35
  budget: { left: number },
22
36
  random: () => number,
23
- ): Record<string, unknown> | undefined {
37
+ allow: ReadonlySet<string> | undefined,
38
+ ): Coerced | undefined {
24
39
  if (budget.left <= 0 || depth > MAX_DEPTH) return undefined;
25
40
  if (typeof value === "string") return undefined; // raw HTML / text — refused
26
41
  if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
@@ -39,24 +54,56 @@ function coerce(
39
54
  typeof node.id === "string" && /^[A-Za-z0-9_-]{4,24}$/.test(node.id)
40
55
  ? node.id
41
56
  : newNodeId(random);
42
- let children: Record<string, unknown>[] | undefined;
57
+ let children: Coerced[] | undefined;
43
58
  if (Array.isArray(node.children)) {
44
59
  children = [];
45
60
  for (const child of node.children) {
46
- const ok = coerce(child, depth + 1, budget, random);
61
+ const ok = coerce(child, depth + 1, budget, random, allow);
47
62
  if (ok) children.push(ok);
48
63
  }
49
64
  }
50
65
  // Drop style/attributes from extension output: only props + children of built-ins.
51
66
  // (Extensions style through the host element's own style on the wrapper.)
52
67
  return {
53
- id,
54
- type: node.type,
55
- props: { ...(node.props as Record<string, unknown>) },
68
+ node: {
69
+ id,
70
+ type: node.type,
71
+ props: { ...(node.props as Record<string, unknown>) },
72
+ ...(children ? { children: children.map((c) => c.node) } : {}),
73
+ },
74
+ classes: filterExtensionClasses(node.extClasses, allow),
56
75
  ...(children ? { children } : {}),
57
76
  };
58
77
  }
59
78
 
79
+ /** Pair each validated node with the classes its coerced twin kept (same tree shape). */
80
+ function attachClasses(validated: LayoutNode, coerced: Coerced): void {
81
+ if (coerced.classes.length > 0) EXT_CLASSES.set(validated, coerced.classes);
82
+ const kids = (validated as { children?: LayoutNode[] }).children;
83
+ if (!Array.isArray(kids) || !coerced.children || kids.length !== coerced.children.length) return;
84
+ kids.forEach((kid, i) => {
85
+ const twin = coerced.children?.[i];
86
+ if (twin) attachClasses(kid, twin);
87
+ });
88
+ }
89
+
90
+ /**
91
+ * W-1086: output nodes as plain JSON with their extension classes back in `extClasses`, for the
92
+ * editor route; the admin runs them through `safeExtensionOutput` again with its allowlist.
93
+ */
94
+ export function withExtensionClasses(nodes: readonly LayoutNode[]): unknown[] {
95
+ const copy = (node: LayoutNode): Record<string, unknown> => {
96
+ const classes = EXT_CLASSES.get(node);
97
+ const kids = (node as { children?: LayoutNode[] }).children;
98
+ return {
99
+ ...node,
100
+ ...(Array.isArray(kids) ? { children: kids.map(copy) } : {}),
101
+ ...(classes ? { extClasses: [...classes] } : {}),
102
+ };
103
+ };
104
+ return nodes.map(copy);
105
+ }
106
+
60
107
  /**
61
108
  * Normalize a render() return value to validated built-in nodes.
62
109
  * Illegal shapes, schema failures and empty output yield `[]` (caller shows the placeholder).
@@ -64,16 +111,18 @@ function coerce(
64
111
  export function safeExtensionOutput(
65
112
  raw: unknown,
66
113
  random: () => number = Math.random,
114
+ /** W-1086: the extension's class allowlist; without one every `extClasses` entry drops. */
115
+ allow?: ReadonlySet<string>,
67
116
  ): LayoutNode[] {
68
117
  const budget = { left: MAX_NODES };
69
- const coerced: Record<string, unknown>[] = [];
118
+ const coerced: Coerced[] = [];
70
119
  if (Array.isArray(raw)) {
71
120
  for (const item of raw) {
72
- const node = coerce(item, 0, budget, random);
121
+ const node = coerce(item, 0, budget, random, allow);
73
122
  if (node) coerced.push(node);
74
123
  }
75
124
  } else {
76
- const one = coerce(raw, 0, budget, random);
125
+ const one = coerce(raw, 0, budget, random, allow);
77
126
  if (one) coerced.push(one);
78
127
  }
79
128
  if (coerced.length === 0) return [];
@@ -84,10 +133,17 @@ export function safeExtensionOutput(
84
133
  id: "root0001",
85
134
  type: "container",
86
135
  props: {},
87
- children: coerced,
136
+ children: coerced.map((c) => c.node),
88
137
  },
89
138
  };
90
139
  const result = validateLayout(page);
91
140
  if (!result.ok) return [];
92
- return result.layout.root.children.slice();
141
+ const out = result.layout.root.children.slice();
142
+ if (out.length === coerced.length) {
143
+ out.forEach((node, i) => {
144
+ const twin = coerced[i];
145
+ if (twin) attachClasses(node, twin);
146
+ });
147
+ }
148
+ return out;
93
149
  }
@@ -59,6 +59,23 @@ export type ExtensionField = Pick<
59
59
  "key" | "kind" | "label" | "options" | "message" | "optional" | "max" | "min"
60
60
  >;
61
61
 
62
+ /**
63
+ * W-1086: a node an extension's render() returns. Built-in node fields, plus `extClasses`: class
64
+ * names from the extension's own `classes.allow` list. Names not on the list are dropped. This is
65
+ * render output only; it is never stored in a layout.
66
+ */
67
+ export type ExtensionOutputNode = LayoutNode & { extClasses?: readonly string[] };
68
+
69
+ /**
70
+ * W-1086: the static class allowlist an extension declares. Every name starts with `prefix`
71
+ * (lowercase letters, digits and hyphens, ending in `-`, never `emvb…`), so extension classes
72
+ * can't clash with EmVB's `emvb-*` classes or a site's own design classes.
73
+ */
74
+ export type ExtensionClasses = {
75
+ prefix: string;
76
+ allow: readonly string[];
77
+ };
78
+
62
79
  /** Context passed to an element render function (read-only source values). */
63
80
  export type ExtensionRenderContext = {
64
81
  /** Resolved values from this extension's sources, keyed by source name then field. */
@@ -80,7 +97,7 @@ export type ExtensionElement = {
80
97
  render: (
81
98
  props: Record<string, unknown>,
82
99
  ctx: ExtensionRenderContext,
83
- ) => LayoutNode | readonly LayoutNode[];
100
+ ) => ExtensionOutputNode | readonly ExtensionOutputNode[];
84
101
  };
85
102
 
86
103
  /**
@@ -118,6 +135,32 @@ export type EmVBExtension = {
118
135
  elements?: readonly ExtensionElement[];
119
136
  panels?: readonly ExtensionPanel[];
120
137
  sources?: readonly ExtensionSource[];
138
+ /**
139
+ * W-1086: the module that exports this extension, as `import.meta.url`. EmVB bundles it into
140
+ * the site's server build (Cloudflare Workers and production builds included), and resolves
141
+ * `css` and `runtime` against it at build time.
142
+ */
143
+ module?: string;
144
+ /** W-1086: class names render() may put on its nodes through `extClasses`. */
145
+ classes?: ExtensionClasses;
146
+ /**
147
+ * W-1086: a stylesheet in the extension's own package, relative to `module` (`"./hello.css"`).
148
+ * Read once at build time; written on pages (and in the editor canvas) that render one of the
149
+ * extension's elements.
150
+ */
151
+ css?: string;
152
+ /**
153
+ * W-1086: a self-contained browser script in the extension's own package, relative to
154
+ * `module` (`"./runtime.js"`): no `import` or `export`. Read once at build time; loaded only on
155
+ * public pages that render one of the extension's elements, never in the admin.
156
+ */
157
+ runtime?: string;
158
+ };
159
+
160
+ /** W-1086: the file contents EmVB read at build time for `css` and `runtime`. */
161
+ export type ExtensionAssets = {
162
+ css?: string;
163
+ runtime?: string;
121
164
  };
122
165
 
123
166
  /**
@@ -156,4 +199,8 @@ export type ExtensionManifest = {
156
199
  elements: readonly ExtensionElementManifest[];
157
200
  panels: readonly ExtensionPanelManifest[];
158
201
  sources: readonly ExtensionSourceManifest[];
202
+ /** W-1086: the checked class allowlist; absent when the extension declares none. */
203
+ classes?: ExtensionClasses;
204
+ /** W-1086: stylesheet and runtime text read at build time; absent when there are none. */
205
+ assets?: ExtensionAssets;
159
206
  };
@@ -0,0 +1,74 @@
1
+ /**
2
+ * W-1072: custom font files. EmDash's media library (1.4 and 1.5) refuses `font/woff2` uploads
3
+ * (its default upload allowlist has images, video, audio and PDF only), so EmVB keeps font files
4
+ * in its own plugin storage and serves them from a public route with a long cache.
5
+ */
6
+
7
+ /**
8
+ * The largest font file EmVB stores: 1 MiB. Base64 in a plugin storage row, that stays under
9
+ * Cloudflare D1's 2 MB row limit. A Latin WOFF2 is usually 15 to 150 KB.
10
+ */
11
+ export const FONT_MAX_BYTES = 1024 * 1024;
12
+
13
+ /** The most font files a site keeps (uploads and Google downloads together). */
14
+ export const FONT_FILE_LIMIT = 300;
15
+
16
+ /** A stored font file's id: the first 16 hex digits of the SHA-256 of its bytes. */
17
+ export const FONT_ID = /^[0-9a-f]{16}$/;
18
+
19
+ /** The public URL a stored font file is served from (the plugin id is `emvb`). */
20
+ export const fontFileUrl = (id: string) => `/_emdash/api/plugins/emvb/font?id=${id}`;
21
+
22
+ const WOFF2_HEADER_BYTES = 48;
23
+ /** sfnt flavours: TrueType (0x00010000), CFF (`OTTO`) and collections (`ttcf`). */
24
+ const FLAVORS = new Set([0x00010000, 0x4f54544f, 0x74746366]);
25
+
26
+ /**
27
+ * A real WOFF2 file: the `wOF2` signature, a known sfnt flavour, and a header length that matches
28
+ * the file. Anything else (a renamed TTF, an HTML error page, a truncated download) is refused.
29
+ */
30
+ export function isWoff2(bytes: Uint8Array): boolean {
31
+ if (bytes.byteLength < WOFF2_HEADER_BYTES) return false;
32
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
33
+ return (
34
+ view.getUint32(0) === 0x774f4632 &&
35
+ FLAVORS.has(view.getUint32(4)) &&
36
+ view.getUint32(8) === bytes.byteLength
37
+ );
38
+ }
39
+
40
+ /** Why a font file is refused, or undefined when it can be stored. */
41
+ export function fontFileProblem(bytes: Uint8Array): string | undefined {
42
+ if (bytes.byteLength > FONT_MAX_BYTES) {
43
+ return `This font is ${Math.ceil(bytes.byteLength / 1024)} KB. Use a WOFF2 file up to ${FONT_MAX_BYTES / 1024} KB.`;
44
+ }
45
+ if (!isWoff2(bytes)) return "This isn't a WOFF2 font file. Convert the font to WOFF2 first.";
46
+ return undefined;
47
+ }
48
+
49
+ /** The id a font file is stored under (content-addressed, so the same file is stored once). */
50
+ export async function fontFileId(bytes: Uint8Array): Promise<string> {
51
+ const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
52
+ return [...new Uint8Array(digest).slice(0, 8)]
53
+ .map((b) => b.toString(16).padStart(2, "0"))
54
+ .join("");
55
+ }
56
+
57
+ const CHUNK = 0x8000;
58
+
59
+ export function bytesToBase64(bytes: Uint8Array): string {
60
+ let binary = "";
61
+ for (let i = 0; i < bytes.byteLength; i += CHUNK) {
62
+ binary += String.fromCharCode(...bytes.subarray(i, i + CHUNK));
63
+ }
64
+ return btoa(binary);
65
+ }
66
+
67
+ /** The bytes of a base64 string, or undefined when it isn't base64. */
68
+ export function base64ToBytes(text: string): Uint8Array | undefined {
69
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(text) || text.length % 4 !== 0) return undefined;
70
+ const binary = atob(text);
71
+ const bytes = new Uint8Array(binary.length);
72
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
73
+ return bytes;
74
+ }