@perkyzz/emvb 1.1.0 → 1.3.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 (99) hide show
  1. package/THIRD_PARTY_NOTICES.md +3 -2
  2. package/package.json +11 -10
  3. package/src/admin/agents-api.ts +5 -1
  4. package/src/admin/content-api.ts +29 -0
  5. package/src/admin/editor/Editor.tsx +6 -1
  6. package/src/admin/editor/ScheduleDialog.tsx +167 -0
  7. package/src/admin/editor/TopBar.tsx +33 -1
  8. package/src/admin/editor/canvas/vnode-react.tsx +3 -0
  9. package/src/admin/editor/dnd/new-element.ts +106 -0
  10. package/src/admin/editor/editor-chrome.tsx +9 -0
  11. package/src/admin/editor/element-chrome.ts +50 -0
  12. package/src/admin/editor/panels/ElementPanel.tsx +5 -1
  13. package/src/admin/editor/panels/settings/DraftTextField.tsx +33 -1
  14. package/src/admin/editor/panels/settings/FieldBindControl.tsx +6 -1
  15. package/src/admin/editor/panels/settings/FieldControl.tsx +10 -1
  16. package/src/admin/editor/panels/settings/IconPicker.tsx +4 -1
  17. package/src/admin/editor/panels/settings/ItemList.tsx +69 -2
  18. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  19. package/src/admin/editor/store.ts +7 -1
  20. package/src/admin/editor/useEditorData.ts +4 -0
  21. package/src/admin/editor/useSave.ts +47 -3
  22. package/src/admin/export-api.ts +20 -3
  23. package/src/admin/menus-api.ts +113 -0
  24. package/src/admin/pages/ImportElementorDialog.tsx +25 -1
  25. package/src/astro/EmVBPage.astro +3 -0
  26. package/src/astro/render.ts +43 -18
  27. package/src/astro/request-data.ts +9 -0
  28. package/src/astro/resolve-theme.ts +77 -44
  29. package/src/astro/resolve.ts +9 -0
  30. package/src/astro/visitor.ts +23 -4
  31. package/src/astro/widgets/EmVBAlertsRuntime.astro +8 -0
  32. package/src/astro/widgets/EmVBCarouselRuntime.astro +8 -0
  33. package/src/astro/widgets/EmVBCountdownRuntime.astro +8 -0
  34. package/src/astro/widgets/EmVBCounterRuntime.astro +8 -0
  35. package/src/astro/widgets/EmVBHeadlineRuntime.astro +9 -0
  36. package/src/astro/widgets/EmVBLightboxRuntime.astro +8 -0
  37. package/src/astro/widgets/EmVBMapRuntime.astro +8 -0
  38. package/src/astro/widgets/EmVBShareRuntime.astro +9 -0
  39. package/src/astro/widgets/EmVBWidgetRuntimes.astro +29 -0
  40. package/src/astro/widgets/alerts.ts +37 -0
  41. package/src/astro/widgets/carousel.ts +167 -0
  42. package/src/astro/widgets/countdown.ts +80 -0
  43. package/src/astro/widgets/counter.ts +98 -0
  44. package/src/astro/widgets/headline.ts +90 -0
  45. package/src/astro/widgets/index.ts +1 -0
  46. package/src/astro/widgets/lightbox.ts +123 -0
  47. package/src/astro/widgets/map.ts +37 -0
  48. package/src/astro/widgets/share.ts +21 -0
  49. package/src/constants.ts +1 -1
  50. package/src/core/a11y/audit.ts +127 -5
  51. package/src/core/arrange.ts +109 -1
  52. package/src/core/bounded-array.ts +16 -13
  53. package/src/core/canvas-collections.ts +28 -0
  54. package/src/core/contract.ts +4 -1
  55. package/src/core/elements/counter-format.ts +15 -0
  56. package/src/core/elements/icon-svg.ts +135 -0
  57. package/src/core/elements/index.ts +63 -127
  58. package/src/core/elements/marketing.ts +1490 -0
  59. package/src/core/elements/widgets.ts +932 -0
  60. package/src/core/export/runtimes.generated.ts +8 -0
  61. package/src/core/export/site.ts +25 -3
  62. package/src/core/extensions/schema.ts +2 -1
  63. package/src/core/geo-trust.ts +18 -0
  64. package/src/core/icons/social.generated.ts +29 -0
  65. package/src/core/image-edit/schema.ts +2 -1
  66. package/src/core/import/elementor/context.ts +18 -0
  67. package/src/core/import/elementor/index.ts +50 -7
  68. package/src/core/import/elementor/widgets.ts +783 -385
  69. package/src/core/issue-cap.ts +19 -0
  70. package/src/core/limits.ts +12 -0
  71. package/src/core/loop-collections.ts +33 -0
  72. package/src/core/proposals.ts +8 -2
  73. package/src/core/render/index.ts +48 -5
  74. package/src/core/render/vnode.ts +44 -6
  75. package/src/core/sanitize/svg-upload.ts +276 -23
  76. package/src/core/sanitize/svg.ts +3 -3
  77. package/src/core/schema/descriptors.ts +4 -0
  78. package/src/core/schema/design.ts +6 -5
  79. package/src/core/schema/layout.ts +798 -15
  80. package/src/core/schema/style.ts +2 -1
  81. package/src/core/shadowing-ids.ts +41 -0
  82. package/src/core/theme/conditions.ts +2 -1
  83. package/src/core/theme/dynamic.ts +2 -0
  84. package/src/core/theme/parse-doc.ts +10 -5
  85. package/src/core/theme/triggers.ts +3 -2
  86. package/src/core/validate.ts +3 -2
  87. package/src/index.ts +23 -2
  88. package/src/mcp/ports.ts +18 -7
  89. package/src/mcp/proposals.ts +36 -11
  90. package/src/mcp/tools.ts +1 -1
  91. package/src/server/agent-settings.ts +12 -1
  92. package/src/server/hooks.ts +41 -6
  93. package/src/server/mcp-routes.ts +11 -5
  94. package/src/server/plugin.ts +29 -3
  95. package/src/server/presence.ts +5 -1
  96. package/src/server/proposals.ts +16 -4
  97. package/src/server/requests.ts +60 -11
  98. package/src/server/site-origin.ts +13 -0
  99. package/src/server/targets.ts +26 -0
@@ -0,0 +1,19 @@
1
+ /** S-03: at most this many issues come back from one validation. */
2
+ const MAX_REPORTED_ISSUES = 50;
3
+
4
+ type Issue = { path: string; code: string; message: string };
5
+
6
+ /**
7
+ * The first issues, mapped, then one "…and N more" in place of the rest, so a document full of
8
+ * bad items can't make a response, a log line or the editor's list grow with it.
9
+ */
10
+ export function capIssues<I>(
11
+ issues: readonly I[],
12
+ map: (issue: I) => Issue,
13
+ path: string,
14
+ ): Issue[] {
15
+ if (issues.length <= MAX_REPORTED_ISSUES) return issues.map(map);
16
+ const kept = issues.slice(0, MAX_REPORTED_ISSUES - 1).map(map);
17
+ const more = issues.length - kept.length;
18
+ return [...kept, { path, code: "too_many_issues", message: `…and ${more} more problems.` }];
19
+ }
@@ -7,6 +7,18 @@ export const MAX_NODES = 2000;
7
7
  export const MAX_TEXT_LENGTH = 2000;
8
8
  /** Tabs show at most this many panels; the CSS-only switcher has a rule per tab. */
9
9
  export const MAX_TABS = 12;
10
+ /** W-1024: most links one Social icons element holds. */
11
+ export const MAX_SOCIAL_LINKS = 20;
12
+ /** W-1019: most pictures one Gallery holds. */
13
+ export const MAX_GALLERY_IMAGES = 60;
14
+ /** W-1018: most slides one Carousel holds. */
15
+ export const MAX_CAROUSEL_SLIDES = 20;
16
+ /** W-1043: most rows one Price list holds. */
17
+ export const MAX_PRICE_ITEMS = 50;
18
+ /** W-1047: most share links one Share buttons element holds. */
19
+ export const MAX_SHARE_LINKS = 12;
20
+ /** W-1048: most markers one Hotspots picture holds. */
21
+ export const MAX_HOTSPOTS = 20;
10
22
 
11
23
  /**
12
24
  * W-509: `text` cut to at most `max` UTF-16 units, as schema limits count, without leaving half
@@ -0,0 +1,33 @@
1
+ /**
2
+ * S-11 (W-1000): `emvb({ loopCollections })`, the collections Loops may list on the public site.
3
+ * Unset, every collection with published entries can be listed (as before 1.1.2). Kept on
4
+ * globalThis for the same reason as the geo-header setting (core/geo-trust.ts).
5
+ */
6
+ const KEY = Symbol.for("emvb.loopCollections");
7
+ const SLUG = /^[a-z][a-z0-9_]{0,62}$/;
8
+ const MAX = 100;
9
+
10
+ type Holder = { [KEY]?: readonly string[] };
11
+
12
+ /** The allowlist from the option: collection slugs, or undefined when the option isn't a list. */
13
+ export function loopCollectionSlugs(input: unknown): string[] | undefined {
14
+ if (!Array.isArray(input)) return undefined;
15
+ const out: string[] = [];
16
+ for (const item of input) {
17
+ if (typeof item !== "string") continue;
18
+ const slug = item.trim();
19
+ if (SLUG.test(slug) && !out.includes(slug)) out.push(slug);
20
+ if (out.length === MAX) break;
21
+ }
22
+ return out;
23
+ }
24
+
25
+ export function setLoopCollections(input: unknown): void {
26
+ (globalThis as Holder)[KEY] = loopCollectionSlugs(input);
27
+ }
28
+
29
+ /** True when a Loop may list `collection` on this site. */
30
+ export function loopCollectionAllowed(collection: string): boolean {
31
+ const allowed = (globalThis as Holder)[KEY];
32
+ return allowed === undefined || allowed.includes(collection);
33
+ }
@@ -21,7 +21,8 @@ import { proposalSafetyRefusal } from "./proposals-safety.ts";
21
21
  const Revision = z.string().min(1).max(256);
22
22
  export const ProposalTarget = z.strictObject({
23
23
  collection: z.string().regex(/^[a-z][a-z0-9_-]{0,127}$/),
24
- id: z.string().min(1).max(128),
24
+ // S-01: EmDash ids are ULIDs; anything else (newlines included) is refused.
25
+ id: z.string().regex(/^[A-Za-z0-9_-]{1,128}$/),
25
26
  });
26
27
  const Value = z.record(z.string(), z.unknown());
27
28
  const Position = { parentId: NodeId, index: z.number().int().min(0).max(2000) };
@@ -54,7 +55,12 @@ export type ProposalBase = {
54
55
  designRevision: string | null;
55
56
  design: unknown;
56
57
  };
57
- export type ProposalRecord = { proposal: Proposal; createdAt: string };
58
+ export type ProposalRecord = {
59
+ proposal: Proposal;
60
+ createdAt: string;
61
+ /** S-09 (W-998): who proposed it; records from before 1.1.2 have none. */
62
+ createdBy?: string;
63
+ };
58
64
  export type ProposalRefusal = Refusal & {
59
65
  code: "INVALID_PROPOSAL" | "STALE_BASE" | "NOT_FOUND" | "PROPOSALS_FULL";
60
66
  opIndex?: number;
@@ -1,6 +1,7 @@
1
+ import { isShadowingId } from "../shadowing-ids.ts";
1
2
  import { renderableDesign, renderableDynamic, renderableLayout } from "../contract.ts";
2
3
  import { markColors } from "../text-marks.ts";
3
- import type { TextMark } from "../schema/layout.ts";
4
+ import type { HotspotNode, ShareLinkNode, TextMark } from "../schema/layout.ts";
4
5
  import { LIST_MARKERS } from "../css-keywords.ts";
5
6
  import { MAX_NODES } from "../limits.ts";
6
7
  import { loneAbTests, variantShows } from "../audience/variants.ts";
@@ -15,6 +16,8 @@ import {
15
16
  scopeWrapperCss,
16
17
  } from "../css/scope.ts";
17
18
  import { ELEMENTS } from "../elements/index.ts";
19
+ import { nodeRuntime, type WidgetRuntime } from "../elements/widgets.ts";
20
+ import { hotspotPlace, shareLinkVNode } from "../elements/marketing.ts";
18
21
  import { controlId } from "../elements/field-id.ts";
19
22
  import { layoutHasForm } from "../forms/binding.ts";
20
23
  import { nodeChildren, someNode } from "../tree-ops.ts";
@@ -75,7 +78,7 @@ export { FORMS_SUBMIT_PATH } from "./form.ts";
75
78
 
76
79
  export type RenderWarning = {
77
80
  nodeId: string;
78
- code: "unknown-type" | "rejected-style" | "unknown-variable";
81
+ code: "unknown-type" | "rejected-style" | "unknown-variable" | "refused-markup";
79
82
  detail: string;
80
83
  };
81
84
  export type RenderResult = {
@@ -86,6 +89,11 @@ export type RenderResult = {
86
89
  needsTabsRuntime: boolean;
87
90
  /** A Menu has a dropdown: hosts load `EmVBMenuRuntime` (W-197). */
88
91
  needsMenuRuntime: boolean;
92
+ /**
93
+ * W-1025: the opt-in widget scripts the page's elements asked for, sorted; empty for most
94
+ * pages. `EmVBPage` loads them; a theme part's go to `EmVBWidgetRuntimes`.
95
+ */
96
+ runtimes: WidgetRuntime[];
89
97
  /** The site's text direction when set in Site styles, for the host's `<html dir>` (W-230). */
90
98
  dir?: "ltr" | "rtl" | "auto";
91
99
  warnings: RenderWarning[];
@@ -313,6 +321,8 @@ export function renderPage(
313
321
  const renderedHeadings: { id: string; text: string; tocClass?: string }[] = [];
314
322
  const emittedIds = new Set<string>();
315
323
  const tocNodes: { node: LayoutNode; vnode: VNode }[] = [];
324
+ // S-02: markup the serializer refuses empties its element instead of failing the whole page.
325
+ const elementIds = new WeakMap<VNode, string>();
316
326
  const knownVariables = new Set(design.variables.colors.map((c) => c.id));
317
327
  let backgroundVideo = false;
318
328
  /** W-952: any List drawn as numbered steps, so their rules are sent. */
@@ -323,6 +333,7 @@ export function renderPage(
323
333
  // W-253: runtimes follow what renders, including synced section and loop item contents,
324
334
  // which the page's own layout doesn't hold.
325
335
  const rendered = { form: false, tabs: false, menuDropdown: false };
336
+ const runtimes = new Set<WidgetRuntime>();
326
337
  let sectionBudget = MAX_SECTION_ELEMENTS;
327
338
  const ctx: RenderContext = {
328
339
  takeSectionBudget: (nodes) => {
@@ -477,6 +488,13 @@ export function renderPage(
477
488
  declarations.push({ property: "gap", value: `${gap}px` });
478
489
  }
479
490
  }
491
+ if (node.type === "hotspot") {
492
+ // W-1048: each marker sits at its own place on the picture, per device.
493
+ const place = hotspotPlace(node.props as HotspotNode["props"]);
494
+ declarations.push(...placeAt(place.desktop));
495
+ if (place.tablet.length > 0) tablet.declarations.unshift(...placeAt(place.tablet));
496
+ if (place.mobile.length > 0) mobile.declarations.unshift(...placeAt(place.mobile));
497
+ }
480
498
  const queryStyle = node.query ? styleDeclarations(node.query.style) : undefined;
481
499
  for (const key of queryStyle?.rejected ?? []) {
482
500
  warnings.push({ nodeId, code: "rejected-style", detail: key });
@@ -589,7 +607,7 @@ export function renderPage(
589
607
  const attrs: Record<string, string> = { class: classes.join(" "), ...customAttributes(node) };
590
608
  if (mode === "editor" && id) attrs["data-emvb-id"] = id;
591
609
  const htmlId =
592
- node.htmlId && HTML_ID.test(node.htmlId)
610
+ node.htmlId && HTML_ID.test(node.htmlId) && !isShadowingId(node.htmlId)
593
611
  ? node.htmlId
594
612
  : node.type === "heading" && id && layoutHasToc
595
613
  ? `emvb-h-${id}`
@@ -642,6 +660,8 @@ export function renderPage(
642
660
  if (isFormNode(node) && node.props.formId.trim()) rendered.form = true;
643
661
  if (isTabsNode(node)) rendered.tabs = true;
644
662
  if (type === "menu-item" && hasChildren(node)) rendered.menuDropdown = true;
663
+ const runtime = nodeRuntime(node as LayoutNode);
664
+ if (runtime) runtimes.add(runtime);
645
665
  const ruleId = id === undefined ? undefined : ruleIdFor(id, dynamic?.idOrigin ?? "");
646
666
  const attrs = nodeAttrs(node, isRoot, id, nodeId, ruleId);
647
667
  if (mode === "editor" && hasBindings(stored)) attrs["data-emvb-bound"] = "";
@@ -672,6 +692,12 @@ export function renderPage(
672
692
  );
673
693
  }
674
694
  if (isTabsNode(node)) return finish(node, renderTabs(node, id, attrs, ctx, dynamic));
695
+ // W-1047: share links point at this page; a public page without its address shows none.
696
+ if (node.type === "share-link") {
697
+ const url = dynamic?.pageUrl ?? (mode === "editor" ? "https://example.com/" : undefined);
698
+ if (!url) return undefined;
699
+ return finish(node, shareLinkVNode(node as ShareLinkNode, attrs, url));
700
+ }
675
701
  if (node.type === "language-switcher") {
676
702
  const links = languageLinks(dynamic?.translations, mode);
677
703
  // W-937: a page in one language has nothing to switch to; the public page shows nothing.
@@ -739,7 +765,9 @@ export function renderPage(
739
765
  if (!vnode) return undefined;
740
766
  const src = videoOf(node);
741
767
  if (src) backgroundVideo = true;
742
- return applyBackgroundVideo(applyBoxLink(node, vnode), src);
768
+ const out = applyBackgroundVideo(applyBoxLink(node, vnode), src);
769
+ elementIds.set(out, node.id);
770
+ return out;
743
771
  }
744
772
 
745
773
  function bindingData(dynamic: ThemeDynamicData | undefined): BindingData {
@@ -780,7 +808,15 @@ export function renderPage(
780
808
  const vnode = scope
781
809
  ? { tag: "div", attrs: { class: scopeClassName(scope) }, children: [page] }
782
810
  : page;
783
- const html = serialize(vnode);
811
+ const html = serialize(vnode, {
812
+ isElement: (node) => elementIds.has(node),
813
+ onRefused: (element, error) =>
814
+ warnings.push({
815
+ nodeId: elementIds.get(element) ?? "(page)",
816
+ code: "refused-markup",
817
+ detail: error.message,
818
+ }),
819
+ });
784
820
  return {
785
821
  vnode,
786
822
  html,
@@ -788,6 +824,7 @@ export function renderPage(
788
824
  needsFormsRuntime: rendered.form || layoutHasForm(layout),
789
825
  needsTabsRuntime: rendered.tabs || layoutHasTabs(layout),
790
826
  needsMenuRuntime: rendered.menuDropdown || layoutHasMenuDropdown(layout),
827
+ runtimes: [...runtimes].toSorted(),
791
828
  ...(design.direction ? { dir: design.direction } : {}),
792
829
  warnings,
793
830
  baseTypes: [...usedTypes],
@@ -828,6 +865,12 @@ const columnCount = (tracks: unknown, columns: unknown): number | undefined =>
828
865
  : undefined;
829
866
 
830
867
  /** A grid's column count on desktop, tablet and mobile; unset follows the next wider device. */
868
+ /** W-1048: a Hotspot marker's left and top. */
869
+ const placeAt = ([left, top]: string[]) => [
870
+ { property: "left", value: left ?? "50%" },
871
+ { property: "top", value: top ?? "50%" },
872
+ ];
873
+
831
874
  function gridColumnCounts(grid: LayoutNode): [number, number, number] {
832
875
  const props = grid.props as Record<string, unknown>;
833
876
  const desktop = columnCount(props["columnTracks"], props["columns"]) ?? 1;
@@ -78,20 +78,58 @@ const TAGS = new Set([
78
78
  const VOID = new Set(["hr", "img", "input", "br"]);
79
79
  // iframe/video are not void — they need closing tags.
80
80
  const ATTR_NAME =
81
- /^(?:class|id|href|src|srcset|sizes|alt|width|height|loading|decoding|fetchpriority|dir|lang|hreflang|role|type|checked|target|rel|aria-[a-z][a-z0-9-]*|title|allow|referrerpolicy|preload|controls|allowfullscreen|sandbox|xmlns|viewBox|fill|stroke|stroke-width|stroke-linecap|stroke-linejoin|stroke-dasharray|stroke-opacity|fill-opacity|opacity|transform|focusable|d|cx|cy|r|x|y|x1|y1|x2|y2|points|rx|ry|xlink:href|preserveAspectRatio|gradientUnits|gradientTransform|offset|stop-color|stop-opacity|clipPathUnits|maskUnits|maskContentUnits|patternUnits|patternContentUnits|patternTransform|markerUnits|markerWidth|markerHeight|refX|refY|orient|font-size|font-family|font-weight|text-anchor|dominant-baseline|dx|dy|clip-path|method|action|name|value|placeholder|for|tabindex|autocomplete|open|datetime|muted|loop|playsinline|autoplay|required|novalidate|minlength|maxlength|min|max|pattern|step|start|data-[a-z][a-z0-9-]*)$/;
81
+ /^(?:class|id|href|src|srcset|sizes|alt|width|height|loading|decoding|fetchpriority|dir|lang|hreflang|role|type|checked|target|rel|aria-[a-z][a-z0-9-]*|title|allow|referrerpolicy|preload|controls|allowfullscreen|sandbox|xmlns|viewBox|fill|stroke|stroke-width|stroke-linecap|stroke-linejoin|stroke-dasharray|stroke-opacity|fill-opacity|opacity|transform|focusable|d|cx|cy|r|x|y|x1|y1|x2|y2|points|rx|ry|xlink:href|preserveAspectRatio|gradientUnits|gradientTransform|offset|stop-color|stop-opacity|clipPathUnits|maskUnits|maskContentUnits|patternUnits|patternContentUnits|patternTransform|markerUnits|markerWidth|markerHeight|refX|refY|orient|font-size|font-family|font-weight|text-anchor|dominant-baseline|dx|dy|clip-path|mask|method|action|name|value|placeholder|for|tabindex|autocomplete|open|popover|popovertarget|popovertargetaction|datetime|muted|loop|playsinline|autoplay|required|novalidate|minlength|maxlength|min|max|pattern|step|start|data-[a-z][a-z0-9-]*)$/;
82
82
 
83
83
  export const isAllowedTag = (tag: string) => TAGS.has(tag);
84
84
  export const isAllowedAttr = (name: string) => ATTR_NAME.test(name);
85
85
 
86
- /** Serializes a VNode tree. Text and attribute values are always escaped; tags and attribute names are allowlisted. */
87
- export function serialize(node: VNode | string): string {
86
+ /** A tag or attribute name outside the allowlist. */
87
+ class RefusedMarkup extends Error {}
88
+
89
+ /** How `serialize` handles refused markup inside a page instead of throwing (S-02). */
90
+ export type SoftSerialize = {
91
+ /** True for the root node of a layout element: refused markup empties the nearest one. */
92
+ isElement: (node: VNode) => boolean;
93
+ onRefused: (element: VNode, error: Error) => void;
94
+ };
95
+
96
+ function write(node: VNode | string, inner: (child: VNode | string) => string): string {
88
97
  if (typeof node === "string") return escapeText(node);
89
- if (!TAGS.has(node.tag)) throw new Error(`EmVB: tag "${node.tag}" is not allowed`);
98
+ if (!TAGS.has(node.tag)) throw new RefusedMarkup(`EmVB: tag "${node.tag}" is not allowed`);
90
99
  let attrs = "";
91
100
  for (const [name, value] of Object.entries(node.attrs)) {
92
- if (!ATTR_NAME.test(name)) throw new Error(`EmVB: attribute "${name}" is not allowed`);
101
+ if (!ATTR_NAME.test(name)) throw new RefusedMarkup(`EmVB: attribute "${name}" is not allowed`);
93
102
  attrs += ` ${name}="${escapeAttr(value)}"`;
94
103
  }
95
104
  if (VOID.has(node.tag)) return `<${node.tag}${attrs}>`;
96
- return `<${node.tag}${attrs}>${node.children.map(serialize).join("")}</${node.tag}>`;
105
+ return `<${node.tag}${attrs}>${node.children.map(inner).join("")}</${node.tag}>`;
106
+ }
107
+
108
+ const strict = (node: VNode | string): string => write(node, strict);
109
+
110
+ function softWrite(node: VNode | string, soft: SoftSerialize): string {
111
+ return write(node, (child) =>
112
+ typeof child !== "string" && soft.isElement(child)
113
+ ? guarded(child, soft)
114
+ : softWrite(child, soft),
115
+ );
116
+ }
117
+
118
+ function guarded(node: VNode, soft: SoftSerialize): string {
119
+ try {
120
+ return softWrite(node, soft);
121
+ } catch (error) {
122
+ if (!(error instanceof RefusedMarkup)) throw error;
123
+ soft.onRefused(node, error);
124
+ return "";
125
+ }
126
+ }
127
+
128
+ /**
129
+ * Serializes a VNode tree. Text and attribute values are always escaped; tags and attribute names
130
+ * are allowlisted. A refused name throws, or with `soft` empties the element that holds it.
131
+ */
132
+ export function serialize(node: VNode | string, soft?: SoftSerialize): string {
133
+ if (!soft || typeof node === "string") return strict(node);
134
+ return guarded(node, soft);
97
135
  }
@@ -48,7 +48,15 @@ const STYLE_VALUE =
48
48
 
49
49
  /** `style="fill:#f00;stroke:none"` → ` fill="#f00" stroke="none"`, skipping attributes already set. */
50
50
  function styleToAttrs(tag: string): string {
51
- const has = (name: string) => new RegExp(`\\s${name}\\s*=`, "i").test(tag);
51
+ const seen = new Map<string, boolean>();
52
+ const has = (name: string) => {
53
+ let found = seen.get(name);
54
+ if (found === undefined) {
55
+ found = new RegExp(`\\s${name}\\s*=`, "i").test(tag);
56
+ seen.set(name, found);
57
+ }
58
+ return found;
59
+ };
52
60
  return tag.replace(/\sstyle\s*=\s*("([^"]*)"|'([^']*)')/i, (_match, _quoted, dq, sq) => {
53
61
  let out = "";
54
62
  for (const decl of String(dq ?? sq ?? "").split(";")) {
@@ -63,28 +71,267 @@ function styleToAttrs(tag: string): string {
63
71
  });
64
72
  }
65
73
 
66
- /** What design tools add around the drawing: prolog, comments, doctype, editor metadata. */
67
- export function tidyUploadedSvg(raw: string): string {
68
- let text = raw.replace(/^\uFEFF/, "");
69
- text = text.replace(/<\?[\s\S]*?\?>/g, "");
70
- text = text.replace(/<!--[\s\S]*?-->/g, "");
71
- text = text.replace(/<!DOCTYPE[^[>]*(?:\[[\s\S]*?\])?\s*>/gi, "");
72
- text = text.replace(/<metadata\b[\s\S]*?<\/metadata\s*>/gi, "");
73
- text = text.replace(/<metadata\b[^>]*\/>/gi, "");
74
- // The Icon's title names it; a file's own <title>/<desc> would add a stray tooltip.
75
- text = text.replace(/<(title|desc)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "");
76
- // Editor elements (sodipodi:namedview, inkscape:grid, …): any prefixed element but svg/xlink.
77
- text = text.replace(/<((?!svg:|xlink:)[a-z][\w.-]*:[\w.-]+)\b[^>]*\/>/gi, "");
78
- text = text.replace(/<((?!svg:|xlink:)[a-z][\w.-]*:[\w.-]+)\b[^>]*>[\s\S]*?<\/\1\s*>/gi, "");
79
- // Prefixed attributes and namespace declarations, except xlink:href and xml:space.
80
- text = text.replace(/<[a-z][^>]*>/gi, (tag) =>
81
- styleToAttrs(
82
- tag.replace(
83
- /\s(?!xlink:href\b|xml:space\b)[a-z][\w.-]*:[\w.-]+\s*=\s*("[^"]*"|'[^']*')/gi,
84
- "",
85
- ),
86
- ),
87
- );
74
+ /*
75
+ * S-07: the tidy step scans left to right with indexOf, so a crafted file costs time in
76
+ * proportion to its size. Lazy regexes rescanned to the end of the file for every unclosed
77
+ * opener (seconds per 256 KB request). A construct that never closes means the file isn't well
78
+ * formed, and it's refused.
79
+ */
80
+
81
+ const WORD = /\w/;
82
+ const SPACE = /\s/;
83
+ const NAME_CHAR = /[\w.-]/;
84
+ const isWord = (c: string | undefined) => c !== undefined && WORD.test(c);
85
+
86
+ /** A file that isn't well formed. */
87
+ const MALFORMED = Symbol("malformed");
88
+ type Pass = string | typeof MALFORMED;
89
+
90
+ /** Removes every `open … close` (shortest match). */
91
+ function removeBetween(s: string, open: string, close: string): Pass {
92
+ let out = "";
93
+ let pos = 0;
94
+ for (;;) {
95
+ const start = s.indexOf(open, pos);
96
+ if (start < 0) return out + s.slice(pos);
97
+ const end = s.indexOf(close, start + open.length);
98
+ if (end < 0) return MALFORMED;
99
+ out += s.slice(pos, start);
100
+ pos = end + close.length;
101
+ }
102
+ }
103
+
104
+ /** The end of `</name\s*>` (its `>`) at or after `from`, case-insensitively, or -1. */
105
+ function closerEnd(s: string, lower: string, name: string, from: number): number {
106
+ const opener = `</${name}`;
107
+ for (let at = lower.indexOf(opener, from); at >= 0; at = lower.indexOf(opener, at + 1)) {
108
+ let k = at + opener.length;
109
+ while (k < s.length && SPACE.test(s.charAt(k))) k++;
110
+ if (s.charAt(k) === ">") return k;
111
+ }
112
+ return -1;
113
+ }
114
+
115
+ /** `<!DOCTYPE …>`, with or without an internal subset in brackets. */
116
+ function removeDoctype(s: string): Pass {
117
+ const lower = s.toLowerCase();
118
+ let out = "";
119
+ let pos = 0;
120
+ for (;;) {
121
+ const start = lower.indexOf("<!doctype", pos);
122
+ if (start < 0) return out + s.slice(pos);
123
+ let k = start + 9;
124
+ while (k < s.length && s[k] !== "[" && s[k] !== ">") k++;
125
+ if (k >= s.length) return MALFORMED;
126
+ if (s[k] === "[") {
127
+ let end = -1;
128
+ for (let close = s.indexOf("]", k + 1); close >= 0; close = s.indexOf("]", close + 1)) {
129
+ let m = close + 1;
130
+ while (m < s.length && SPACE.test(s.charAt(m))) m++;
131
+ if (s[m] === ">") {
132
+ end = m;
133
+ break;
134
+ }
135
+ }
136
+ if (end < 0) return MALFORMED;
137
+ k = end;
138
+ }
139
+ out += s.slice(pos, start);
140
+ pos = k + 1;
141
+ }
142
+ }
143
+
144
+ /** The next `<name` at or after `from` that ends on a word boundary, or -1. */
145
+ function nextOpener(s: string, lower: string, name: string, from: number): number {
146
+ for (let at = lower.indexOf(`<${name}`, from); at >= 0; at = lower.indexOf(`<${name}`, at + 1))
147
+ if (!isWord(s[at + name.length + 1])) return at;
148
+ return -1;
149
+ }
150
+
151
+ /** `<metadata>…</metadata>` and `<metadata/>`. */
152
+ function removeMetadata(s: string): Pass {
153
+ let lower = s.toLowerCase();
154
+ let out = "";
155
+ let pos = 0;
156
+ for (;;) {
157
+ const start = nextOpener(s, lower, "metadata", pos);
158
+ if (start < 0) break;
159
+ const end = closerEnd(s, lower, "metadata", start + 9);
160
+ if (end < 0) break;
161
+ out += s.slice(pos, start);
162
+ pos = end + 1;
163
+ }
164
+ const paired = out + s.slice(pos);
165
+ lower = paired.toLowerCase();
166
+ out = "";
167
+ pos = 0;
168
+ for (let from = 0; ;) {
169
+ const start = nextOpener(paired, lower, "metadata", from);
170
+ if (start < 0) return out + paired.slice(pos);
171
+ const gt = paired.indexOf(">", start + 9);
172
+ if (gt < 0 || paired[gt - 1] !== "/" || gt - 1 < start + 9) return MALFORMED;
173
+ out += paired.slice(pos, start);
174
+ pos = gt + 1;
175
+ from = pos;
176
+ }
177
+ }
178
+
179
+ /** `<title>…</title>` and `<desc>…</desc>`: the Icon's title names it. */
180
+ function removeTitles(s: string): Pass {
181
+ const lower = s.toLowerCase();
182
+ let out = "";
183
+ let pos = 0;
184
+ let title = -1;
185
+ let desc = -1;
186
+ const next = (name: string, at: number) => {
187
+ // A search starts where the last match ended, so a far opener isn't searched for again.
188
+ if (at >= pos) return at;
189
+ const found = nextOpener(s, lower, name, pos);
190
+ return found < 0 ? Number.POSITIVE_INFINITY : found;
191
+ };
192
+ for (;;) {
193
+ title = next("title", title);
194
+ desc = next("desc", desc);
195
+ const start = Math.min(title, desc);
196
+ if (start === Number.POSITIVE_INFINITY) return out + s.slice(pos);
197
+ const name = start === title ? "title" : "desc";
198
+ const gt = s.indexOf(">", start + name.length + 1);
199
+ if (gt < 0) return MALFORMED;
200
+ const end = closerEnd(s, lower, name, gt + 1);
201
+ if (end < 0) return MALFORMED;
202
+ out += s.slice(pos, start);
203
+ pos = end + 1;
204
+ }
205
+ }
206
+
207
+ /**
208
+ * An editor element's name at `<` (sodipodi:namedview, inkscape:grid, …: any prefixed name but
209
+ * svg: and xlink:), as the names it can be read as, longest first; empty when there is none.
210
+ */
211
+ function prefixedNames(s: string, lt: number): string[] {
212
+ const first = lt + 1;
213
+ if (!/[a-z]/i.test(s.charAt(first))) return [];
214
+ if (/^(?:svg|xlink):/i.test(s.slice(first, first + 6))) return [];
215
+ let colon = first + 1;
216
+ while (colon < s.length && NAME_CHAR.test(s.charAt(colon))) colon++;
217
+ if (s[colon] !== ":") return [];
218
+ let end = colon + 1;
219
+ while (end < s.length && NAME_CHAR.test(s.charAt(end))) end++;
220
+ const names: string[] = [];
221
+ for (let k = end; k > colon + 1; k--)
222
+ if (isWord(s[k - 1]) !== isWord(s[k])) names.push(s.slice(first, k));
223
+ return names;
224
+ }
225
+
226
+ /** Every `</name\s*>` of the text: lower-cased name → the positions of its `<` and `>`. */
227
+ function closersByName(s: string): Map<string, { at: number; end: number }[]> {
228
+ const closers = new Map<string, { at: number; end: number }[]>();
229
+ for (let at = s.indexOf("</"); at >= 0; at = s.indexOf("</", at + 2)) {
230
+ let k = at + 2;
231
+ while (k < s.length && !SPACE.test(s.charAt(k)) && s[k] !== ">" && s[k] !== "<") k++;
232
+ const name = s.slice(at + 2, k).toLowerCase();
233
+ while (k < s.length && SPACE.test(s.charAt(k))) k++;
234
+ if (s[k] !== ">" || !name) continue;
235
+ const list = closers.get(name);
236
+ if (list) list.push({ at, end: k });
237
+ else closers.set(name, [{ at, end: k }]);
238
+ }
239
+ return closers;
240
+ }
241
+
242
+ /** The first closer that starts after `from`. */
243
+ function firstAfter(list: { at: number; end: number }[] | undefined, from: number) {
244
+ if (!list) return undefined;
245
+ let low = 0;
246
+ let high = list.length;
247
+ while (low < high) {
248
+ const mid = (low + high) >> 1;
249
+ if ((list[mid]?.at ?? 0) > from) high = mid;
250
+ else low = mid + 1;
251
+ }
252
+ return list[low];
253
+ }
254
+
255
+ /** Editor elements: `<inkscape:grid/>`, then `<inkscape:grid>…</inkscape:grid>`. */
256
+ function removePrefixedElements(s: string): Pass {
257
+ let out = "";
258
+ let pos = 0;
259
+ let gt = -1;
260
+ for (let lt = s.indexOf("<"); lt >= 0; lt = s.indexOf("<", lt + 1)) {
261
+ const name = prefixedNames(s, lt)[0];
262
+ if (name === undefined) continue;
263
+ if (gt < lt) gt = s.indexOf(">", lt);
264
+ if (gt < 0) break;
265
+ if (s[gt - 1] !== "/" || gt - 1 < lt + 1 + name.length) continue;
266
+ out += s.slice(pos, lt);
267
+ pos = gt + 1;
268
+ lt = gt;
269
+ }
270
+ const kept = out + s.slice(pos);
271
+ const closers = closersByName(kept);
272
+ out = "";
273
+ pos = 0;
274
+ gt = -1;
275
+ for (let lt = kept.indexOf("<"); lt >= 0; lt = kept.indexOf("<", lt + 1)) {
276
+ const names = prefixedNames(kept, lt);
277
+ if (names.length === 0) continue;
278
+ if (gt < lt) gt = kept.indexOf(">", lt);
279
+ if (gt < 0) return MALFORMED;
280
+ let closer: { at: number; end: number } | undefined;
281
+ for (const name of names) {
282
+ closer = firstAfter(closers.get(name.toLowerCase()), gt);
283
+ if (closer) break;
284
+ }
285
+ if (!closer) return MALFORMED;
286
+ out += kept.slice(pos, lt);
287
+ pos = closer.end + 1;
288
+ lt = closer.end;
289
+ }
290
+ return out + kept.slice(pos);
291
+ }
292
+
293
+ /** Prefixed attributes and namespace declarations go, except xlink:href and xml:space. */
294
+ function tidyTags(s: string): Pass {
295
+ let out = "";
296
+ let pos = 0;
297
+ for (let lt = s.indexOf("<"); lt >= 0; lt = s.indexOf("<", lt + 1)) {
298
+ if (!/[a-z]/i.test(s.charAt(lt + 1))) continue;
299
+ const gt = s.indexOf(">", lt);
300
+ if (gt < 0) return MALFORMED;
301
+ const tag = s.slice(lt, gt + 1);
302
+ out +=
303
+ s.slice(pos, lt) +
304
+ styleToAttrs(
305
+ tag.replace(
306
+ /\s(?!xlink:href\b|xml:space\b)[a-z][\w.-]*:[\w.-]+\s*=\s*("[^"]*"|'[^']*')/gi,
307
+ "",
308
+ ),
309
+ );
310
+ pos = gt + 1;
311
+ lt = gt;
312
+ }
313
+ return out + s.slice(pos);
314
+ }
315
+
316
+ /**
317
+ * What design tools add around the drawing: prolog, comments, doctype, editor metadata.
318
+ * Undefined when the file isn't well formed.
319
+ */
320
+ export function tidyUploadedSvg(raw: string): string | undefined {
321
+ let text: Pass = raw.replace(/^/, "");
322
+ const passes: ((s: string) => Pass)[] = [
323
+ (s) => removeBetween(s, "<?", "?>"),
324
+ (s) => removeBetween(s, "<!--", "-->"),
325
+ removeDoctype,
326
+ removeMetadata,
327
+ removeTitles,
328
+ removePrefixedElements,
329
+ tidyTags,
330
+ ];
331
+ for (const pass of passes) {
332
+ text = pass(text);
333
+ if (text === MALFORMED) return undefined;
334
+ }
88
335
  return text.trim();
89
336
  }
90
337
 
@@ -172,6 +419,12 @@ export function prepareUploadedSvg(raw: string): PreparedSvg {
172
419
  message: `This file is ${kb(size)}. Upload an SVG up to ${kb(UPLOAD_SVG_MAX_BYTES)}.`,
173
420
  };
174
421
  const text = tidyUploadedSvg(raw);
422
+ if (text === undefined)
423
+ return {
424
+ ok: false,
425
+ message:
426
+ "This SVG is not well formed: a tag, comment or declaration in it never closes. Export it again as plain SVG and retry.",
427
+ };
175
428
  // The sanitizer refuses markup over its limit outright; say it's the size.
176
429
  if (text.length > ICON_SVG_MAX) return tooBig(utf8(text));
177
430
  const report = sanitizeSvgReport(text);
@@ -9,7 +9,7 @@ import type { VNode } from "../render/vnode.ts";
9
9
  * iframe, style elements/attrs, event handlers, and javascript:/data: urls.
10
10
  */
11
11
 
12
- const SVG_TAGS = new Set([
12
+ export const SVG_TAGS: ReadonlySet<string> = new Set([
13
13
  "svg",
14
14
  "g",
15
15
  "path",
@@ -36,7 +36,7 @@ const SVG_TAGS = new Set([
36
36
  "tspan",
37
37
  ]);
38
38
 
39
- const ATTR_ALLOW = new Set([
39
+ export const SVG_ATTRS: ReadonlySet<string> = new Set([
40
40
  "viewBox",
41
41
  "xmlns",
42
42
  "fill",
@@ -217,7 +217,7 @@ function parseAttrs(tag: string, raw: string): ParsedAttrs | undefined {
217
217
  let match: RegExpExecArray | null;
218
218
  while ((match = re.exec(raw))) {
219
219
  const name = match[1] ?? "";
220
- if (!ATTR_ALLOW.has(name)) continue;
220
+ if (!SVG_ATTRS.has(name)) continue;
221
221
  const value = decodeEntities(match[2] ?? match[3] ?? "");
222
222
  if (/[<>`]|javascript:/i.test(value)) return undefined;
223
223
  const imageHref = tag === "image" && isHrefName(name);