@perkyzz/emvb 1.1.0 → 1.2.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 (83) hide show
  1. package/THIRD_PARTY_NOTICES.md +1 -0
  2. package/package.json +10 -9
  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/dnd/new-element.ts +46 -0
  9. package/src/admin/editor/editor-chrome.tsx +9 -0
  10. package/src/admin/editor/element-chrome.ts +22 -0
  11. package/src/admin/editor/panels/ElementPanel.tsx +5 -1
  12. package/src/admin/editor/panels/settings/DraftTextField.tsx +33 -1
  13. package/src/admin/editor/panels/settings/FieldBindControl.tsx +6 -1
  14. package/src/admin/editor/panels/settings/FieldControl.tsx +10 -1
  15. package/src/admin/editor/panels/settings/IconPicker.tsx +4 -1
  16. package/src/admin/editor/panels/settings/ItemList.tsx +36 -2
  17. package/src/admin/editor/panels/settings/advanced-rules.ts +3 -0
  18. package/src/admin/editor/store.ts +7 -1
  19. package/src/admin/editor/useEditorData.ts +4 -0
  20. package/src/admin/editor/useSave.ts +47 -3
  21. package/src/admin/export-api.ts +20 -3
  22. package/src/admin/menus-api.ts +113 -0
  23. package/src/admin/pages/ImportElementorDialog.tsx +25 -1
  24. package/src/astro/EmVBPage.astro +3 -0
  25. package/src/astro/render.ts +43 -18
  26. package/src/astro/request-data.ts +3 -0
  27. package/src/astro/resolve-theme.ts +77 -44
  28. package/src/astro/visitor.ts +23 -4
  29. package/src/astro/widgets/EmVBAlertsRuntime.astro +8 -0
  30. package/src/astro/widgets/EmVBCarouselRuntime.astro +8 -0
  31. package/src/astro/widgets/EmVBLightboxRuntime.astro +8 -0
  32. package/src/astro/widgets/EmVBWidgetRuntimes.astro +19 -0
  33. package/src/astro/widgets/alerts.ts +37 -0
  34. package/src/astro/widgets/carousel.ts +167 -0
  35. package/src/astro/widgets/index.ts +1 -0
  36. package/src/astro/widgets/lightbox.ts +123 -0
  37. package/src/constants.ts +1 -1
  38. package/src/core/a11y/audit.ts +101 -2
  39. package/src/core/arrange.ts +57 -1
  40. package/src/core/bounded-array.ts +16 -13
  41. package/src/core/contract.ts +4 -1
  42. package/src/core/elements/icon-svg.ts +135 -0
  43. package/src/core/elements/index.ts +33 -127
  44. package/src/core/elements/widgets.ts +907 -0
  45. package/src/core/export/runtimes.generated.ts +3 -0
  46. package/src/core/export/site.ts +20 -3
  47. package/src/core/extensions/schema.ts +2 -1
  48. package/src/core/geo-trust.ts +18 -0
  49. package/src/core/icons/social.generated.ts +29 -0
  50. package/src/core/image-edit/schema.ts +2 -1
  51. package/src/core/import/elementor/context.ts +18 -0
  52. package/src/core/import/elementor/index.ts +50 -7
  53. package/src/core/import/elementor/widgets.ts +394 -133
  54. package/src/core/issue-cap.ts +19 -0
  55. package/src/core/limits.ts +6 -0
  56. package/src/core/loop-collections.ts +33 -0
  57. package/src/core/proposals.ts +8 -2
  58. package/src/core/render/index.ts +27 -4
  59. package/src/core/render/vnode.ts +44 -6
  60. package/src/core/sanitize/svg-upload.ts +276 -23
  61. package/src/core/sanitize/svg.ts +3 -3
  62. package/src/core/schema/descriptors.ts +4 -0
  63. package/src/core/schema/design.ts +6 -5
  64. package/src/core/schema/layout.ts +395 -15
  65. package/src/core/schema/style.ts +2 -1
  66. package/src/core/shadowing-ids.ts +41 -0
  67. package/src/core/theme/conditions.ts +2 -1
  68. package/src/core/theme/parse-doc.ts +10 -5
  69. package/src/core/theme/triggers.ts +3 -2
  70. package/src/core/validate.ts +3 -2
  71. package/src/index.ts +23 -2
  72. package/src/mcp/ports.ts +18 -7
  73. package/src/mcp/proposals.ts +36 -11
  74. package/src/mcp/tools.ts +1 -1
  75. package/src/server/agent-settings.ts +12 -1
  76. package/src/server/hooks.ts +41 -6
  77. package/src/server/mcp-routes.ts +11 -5
  78. package/src/server/plugin.ts +27 -2
  79. package/src/server/presence.ts +5 -1
  80. package/src/server/proposals.ts +16 -4
  81. package/src/server/requests.ts +60 -11
  82. package/src/server/site-origin.ts +13 -0
  83. package/src/server/targets.ts +26 -0
@@ -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,3 +1,4 @@
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
4
  import type { TextMark } from "../schema/layout.ts";
@@ -15,6 +16,7 @@ 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";
18
20
  import { controlId } from "../elements/field-id.ts";
19
21
  import { layoutHasForm } from "../forms/binding.ts";
20
22
  import { nodeChildren, someNode } from "../tree-ops.ts";
@@ -75,7 +77,7 @@ export { FORMS_SUBMIT_PATH } from "./form.ts";
75
77
 
76
78
  export type RenderWarning = {
77
79
  nodeId: string;
78
- code: "unknown-type" | "rejected-style" | "unknown-variable";
80
+ code: "unknown-type" | "rejected-style" | "unknown-variable" | "refused-markup";
79
81
  detail: string;
80
82
  };
81
83
  export type RenderResult = {
@@ -86,6 +88,11 @@ export type RenderResult = {
86
88
  needsTabsRuntime: boolean;
87
89
  /** A Menu has a dropdown: hosts load `EmVBMenuRuntime` (W-197). */
88
90
  needsMenuRuntime: boolean;
91
+ /**
92
+ * W-1025: the opt-in widget scripts the page's elements asked for, sorted; empty for most
93
+ * pages. `EmVBPage` loads them; a theme part's go to `EmVBWidgetRuntimes`.
94
+ */
95
+ runtimes: WidgetRuntime[];
89
96
  /** The site's text direction when set in Site styles, for the host's `<html dir>` (W-230). */
90
97
  dir?: "ltr" | "rtl" | "auto";
91
98
  warnings: RenderWarning[];
@@ -313,6 +320,8 @@ export function renderPage(
313
320
  const renderedHeadings: { id: string; text: string; tocClass?: string }[] = [];
314
321
  const emittedIds = new Set<string>();
315
322
  const tocNodes: { node: LayoutNode; vnode: VNode }[] = [];
323
+ // S-02: markup the serializer refuses empties its element instead of failing the whole page.
324
+ const elementIds = new WeakMap<VNode, string>();
316
325
  const knownVariables = new Set(design.variables.colors.map((c) => c.id));
317
326
  let backgroundVideo = false;
318
327
  /** W-952: any List drawn as numbered steps, so their rules are sent. */
@@ -323,6 +332,7 @@ export function renderPage(
323
332
  // W-253: runtimes follow what renders, including synced section and loop item contents,
324
333
  // which the page's own layout doesn't hold.
325
334
  const rendered = { form: false, tabs: false, menuDropdown: false };
335
+ const runtimes = new Set<WidgetRuntime>();
326
336
  let sectionBudget = MAX_SECTION_ELEMENTS;
327
337
  const ctx: RenderContext = {
328
338
  takeSectionBudget: (nodes) => {
@@ -589,7 +599,7 @@ export function renderPage(
589
599
  const attrs: Record<string, string> = { class: classes.join(" "), ...customAttributes(node) };
590
600
  if (mode === "editor" && id) attrs["data-emvb-id"] = id;
591
601
  const htmlId =
592
- node.htmlId && HTML_ID.test(node.htmlId)
602
+ node.htmlId && HTML_ID.test(node.htmlId) && !isShadowingId(node.htmlId)
593
603
  ? node.htmlId
594
604
  : node.type === "heading" && id && layoutHasToc
595
605
  ? `emvb-h-${id}`
@@ -642,6 +652,8 @@ export function renderPage(
642
652
  if (isFormNode(node) && node.props.formId.trim()) rendered.form = true;
643
653
  if (isTabsNode(node)) rendered.tabs = true;
644
654
  if (type === "menu-item" && hasChildren(node)) rendered.menuDropdown = true;
655
+ const runtime = nodeRuntime(node as LayoutNode);
656
+ if (runtime) runtimes.add(runtime);
645
657
  const ruleId = id === undefined ? undefined : ruleIdFor(id, dynamic?.idOrigin ?? "");
646
658
  const attrs = nodeAttrs(node, isRoot, id, nodeId, ruleId);
647
659
  if (mode === "editor" && hasBindings(stored)) attrs["data-emvb-bound"] = "";
@@ -739,7 +751,9 @@ export function renderPage(
739
751
  if (!vnode) return undefined;
740
752
  const src = videoOf(node);
741
753
  if (src) backgroundVideo = true;
742
- return applyBackgroundVideo(applyBoxLink(node, vnode), src);
754
+ const out = applyBackgroundVideo(applyBoxLink(node, vnode), src);
755
+ elementIds.set(out, node.id);
756
+ return out;
743
757
  }
744
758
 
745
759
  function bindingData(dynamic: ThemeDynamicData | undefined): BindingData {
@@ -780,7 +794,15 @@ export function renderPage(
780
794
  const vnode = scope
781
795
  ? { tag: "div", attrs: { class: scopeClassName(scope) }, children: [page] }
782
796
  : page;
783
- const html = serialize(vnode);
797
+ const html = serialize(vnode, {
798
+ isElement: (node) => elementIds.has(node),
799
+ onRefused: (element, error) =>
800
+ warnings.push({
801
+ nodeId: elementIds.get(element) ?? "(page)",
802
+ code: "refused-markup",
803
+ detail: error.message,
804
+ }),
805
+ });
784
806
  return {
785
807
  vnode,
786
808
  html,
@@ -788,6 +810,7 @@ export function renderPage(
788
810
  needsFormsRuntime: rendered.form || layoutHasForm(layout),
789
811
  needsTabsRuntime: rendered.tabs || layoutHasTabs(layout),
790
812
  needsMenuRuntime: rendered.menuDropdown || layoutHasMenuDropdown(layout),
813
+ runtimes: [...runtimes].toSorted(),
791
814
  ...(design.direction ? { dir: design.direction } : {}),
792
815
  warnings,
793
816
  baseTypes: [...usedTypes],
@@ -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|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);
@@ -4,6 +4,8 @@ export type FieldKind =
4
4
  | "textarea"
5
5
  | "number"
6
6
  | "int"
7
+ /** W-1023: a plain number with decimals (no unit), from `min` (unset 0) to `max`. */
8
+ | "decimal"
7
9
  | "select"
8
10
  | "boolean"
9
11
  | "href"
@@ -28,6 +30,8 @@ export type FieldDescriptor = {
28
30
  max?: number;
29
31
  /** Lowest value a whole-number field accepts; unset is 1 (W-388). */
30
32
  min?: number;
33
+ /** W-1023: the prop that holds this field's maximum, when another field sets it; `max` is its default. */
34
+ maxProp?: string;
31
35
  /** Props that hold this field's tablet and mobile values (W-139); unset follows the wider device. */
32
36
  devices?: { tablet: string; mobile: string };
33
37
  };
@@ -1,3 +1,4 @@
1
+ import { boundedArray } from "../bounded-array.ts";
1
2
  import { z } from "zod";
2
3
  import { HEX_COLOR } from "../css-keywords.ts";
3
4
  import { DeviceStyles, HiddenOn, OwnStyle, StyleProps, StyleStates } from "./style.ts";
@@ -75,12 +76,12 @@ const StyleClass = z.strictObject({
75
76
  export const DesignSystem = z.strictObject({
76
77
  schemaVersion: z.literal(DESIGN_SCHEMA_VERSION),
77
78
  variables: z.strictObject({
78
- colors: z.array(ColorVariable).max(200),
79
- fonts: z.array(FontVariable).max(50).optional(),
80
- fontSizes: z.array(LengthVariable).max(50).optional(),
81
- spacings: z.array(LengthVariable).max(100).optional(),
79
+ colors: boundedArray(ColorVariable, 200),
80
+ fonts: boundedArray(FontVariable, 50).optional(),
81
+ fontSizes: boundedArray(LengthVariable, 50).optional(),
82
+ spacings: boundedArray(LengthVariable, 100).optional(),
82
83
  }),
83
- classes: z.array(StyleClass).max(100).optional(),
84
+ classes: boundedArray(StyleClass, 100).optional(),
84
85
  fluidRange: FluidRange.optional(),
85
86
  /**
86
87
  * Site text direction (W-230). Unset is left to right. Rendered as `dir` on every EmVB root