@markasso/mcp 0.7.0 → 0.7.2

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.
package/README.md CHANGED
@@ -57,7 +57,7 @@ args = ["-y", "@markasso/mcp@latest"]
57
57
 
58
58
  **Drawing live with people:** `live_join` puts the agent in a live session next to you. This needs a [Markasso Cloud](https://markasso.it/cloud) licence: set `MARKASSO_LICENSE` to your key in the server's environment, e.g. `"env": { "MARKASSO_LICENSE": "MKC-…" }` in the entry above. Everything else in this server is free.
59
59
 
60
- **Another Markasso instance:** set `MARKASSO_URL` (default `https://markasso.it`) in the server's environment.
60
+ **Another Markasso instance:** set `MARKASSO_URL` (default `https://markasso.it`) in the server's environment. The licence key is only ever sent to this instance: a live link to any other host is joined without it.
61
61
 
62
62
  ## Build from source
63
63
 
@@ -1352,6 +1352,14 @@ function getBundledIcon(ref) {
1352
1352
  var MAX_AGENT_REPLY_CHARS = 4e3;
1353
1353
  //#endregion
1354
1354
  //#region ../src/core/geometry.ts
1355
+ /**
1356
+ * The same angle within [-π, π): a rotation that keeps accumulating across
1357
+ * drags or remote commands would otherwise leave the ±2π range that
1358
+ * `element_validation` accepts, and the element would be dropped on reload.
1359
+ */
1360
+ function normalizeRotation(rotation) {
1361
+ return rotation - 2 * Math.PI * Math.round(rotation / (2 * Math.PI));
1362
+ }
1355
1363
  /** Returns the top-left corner and positive dimensions of a signed rectangle. */
1356
1364
  function normalizeRect(rect) {
1357
1365
  return {
@@ -3633,6 +3641,37 @@ function getElementBounds(el, allElements) {
3633
3641
  }
3634
3642
  }
3635
3643
  }
3644
+ /**
3645
+ * The axis-aligned box around `box` once turned by the element's rotation,
3646
+ * about the element's center: the extent of something drawn with it, such as
3647
+ * the element or the element with its label.
3648
+ */
3649
+ function rotateBoxOf(el, box) {
3650
+ if (!el.rotation) return box;
3651
+ const [cx, cy] = getElementCenter(el);
3652
+ const cos = Math.cos(el.rotation);
3653
+ const sin = Math.sin(el.rotation);
3654
+ let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
3655
+ for (const [px, py] of [
3656
+ [box.x, box.y],
3657
+ [box.x + box.w, box.y],
3658
+ [box.x + box.w, box.y + box.h],
3659
+ [box.x, box.y + box.h]
3660
+ ]) {
3661
+ const rx = cx + (px - cx) * cos - (py - cy) * sin;
3662
+ const ry = cy + (px - cx) * sin + (py - cy) * cos;
3663
+ minX = Math.min(minX, rx);
3664
+ minY = Math.min(minY, ry);
3665
+ maxX = Math.max(maxX, rx);
3666
+ maxY = Math.max(maxY, ry);
3667
+ }
3668
+ return {
3669
+ x: minX,
3670
+ y: minY,
3671
+ w: maxX - minX,
3672
+ h: maxY - minY
3673
+ };
3674
+ }
3636
3675
  /** Returns the world-space center of any element. */
3637
3676
  function getElementCenter(el) {
3638
3677
  const { x, y, w, h } = getElementBounds(el);
@@ -3833,12 +3872,63 @@ function contrastColor(fill, fallback) {
3833
3872
  if (Number.isNaN(r) || Number.isNaN(g) || Number.isNaN(b)) return fallback;
3834
3873
  return (.299 * r + .587 * g + .114 * b) / 255 > .55 ? "#111111" : "#ffffff";
3835
3874
  }
3875
+ var DARK_DEFAULT_STROKE = "#e2e2ef";
3876
+ var LIGHT_DEFAULT_STROKE = "#000000";
3877
+ /**
3878
+ * The rule behind resolveStrokeColorForTheme for a given theme, without the
3879
+ * DOM: the SVG export applies it for the theme it exports in.
3880
+ */
3881
+ function inkForTheme(strokeColor, light, fillColor) {
3882
+ const c = strokeColor.toLowerCase();
3883
+ if (light) return c === DARK_DEFAULT_STROKE ? LIGHT_DEFAULT_STROKE : strokeColor;
3884
+ return !(!!fillColor && fillColor !== "transparent") && (c === LIGHT_DEFAULT_STROKE || c === "#000") ? DARK_DEFAULT_STROKE : strokeColor;
3885
+ }
3886
+ /** getCodeBlockColors for a given theme, without the DOM. */
3887
+ function codeBlockColors(light) {
3888
+ return light ? {
3889
+ fill: "rgba(0,0,0,0.05)",
3890
+ border: "rgba(0,0,0,0.15)"
3891
+ } : {
3892
+ fill: "rgba(0,0,0,0.55)",
3893
+ border: "rgba(255,255,255,0.15)"
3894
+ };
3895
+ }
3836
3896
  /** Icon stroke width in grid units for an element stroke width. */
3837
3897
  function getIconStrokeWidth(strokeWidth) {
3838
3898
  return Math.min(Math.max(strokeWidth, 1) * 1.5, 3);
3839
3899
  }
3840
3900
  //#endregion
3841
3901
  //#region ../src/rendering/export.ts
3902
+ function svgInk(theme) {
3903
+ if (!theme) return {
3904
+ ink: (color) => color,
3905
+ code: codeBlockColors(false)
3906
+ };
3907
+ const light = theme === "light";
3908
+ return {
3909
+ ink: (color, fill) => inkForTheme(color, light, fill),
3910
+ code: codeBlockColors(light)
3911
+ };
3912
+ }
3913
+ /**
3914
+ * The element with its stroke and label colors as the canvas draws them in
3915
+ * the export's theme: strokes resolve on the element's fill, and so do shape
3916
+ * labels; an icon's label hangs below the icon, off its fill, so it resolves
3917
+ * without it and is set explicitly (it would otherwise take the stroke).
3918
+ */
3919
+ function inked(el, ink) {
3920
+ const labelColor = el.labelColor;
3921
+ if (el.type === "stencil") return {
3922
+ ...el,
3923
+ strokeColor: ink(el.strokeColor, el.fillColor),
3924
+ labelColor: ink(labelColor ?? el.strokeColor)
3925
+ };
3926
+ return {
3927
+ ...el,
3928
+ strokeColor: ink(el.strokeColor, el.fillColor),
3929
+ ...labelColor !== void 0 && { labelColor: ink(labelColor, el.fillColor) }
3930
+ };
3931
+ }
3842
3932
  /**
3843
3933
  * Standalone SVG document of the given elements, cropped to their bounds
3844
3934
  * with a margin; null when there is nothing to export. Pure (no DOM), so
@@ -3853,13 +3943,14 @@ function sceneToSVG(elements, options) {
3853
3943
  const ox = PAD - minX;
3854
3944
  const oy = PAD - minY;
3855
3945
  const canvasColor = escapeXml(options.canvasColor);
3946
+ const ink = svgInk(options.theme);
3856
3947
  const parts = [`<svg xmlns="http://www.w3.org/2000/svg" width="${round(w)}" height="${round(h)}" viewBox="0 0 ${round(w)} ${round(h)}">`];
3857
3948
  if (options.withBackground) parts.push(`<rect width="${round(w)}" height="${round(h)}" fill="${canvasColor}"/>`);
3858
- for (const el of elements) parts.push(elementToSVG(el, ox, oy, elements));
3949
+ for (const el of elements) parts.push(elementToSVG(inked(el, ink.ink), ox, oy, elements, ink));
3859
3950
  const labels = getConnectorLabelBoxes(elements);
3860
3951
  for (const el of elements) {
3861
3952
  const box = labels.get(el.id);
3862
- if (box && (el.type === "line" || el.type === "arrow")) parts.push(connectorLabelToSVG(el, box, ox, oy, canvasColor));
3953
+ if (box && (el.type === "line" || el.type === "arrow")) parts.push(connectorLabelToSVG(el, box, ox, oy, canvasColor, ink.ink(el.labelColor ?? el.strokeColor)));
3863
3954
  }
3864
3955
  parts.push("</svg>");
3865
3956
  return parts.join("\n");
@@ -3867,60 +3958,23 @@ function sceneToSVG(elements, options) {
3867
3958
  function computeBounds(elements) {
3868
3959
  let minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity;
3869
3960
  for (const el of elements) {
3870
- if (el.type === "line" || el.type === "arrow") {
3871
- const b = getElementBounds(el, elements);
3872
- minX = Math.min(minX, b.x);
3873
- minY = Math.min(minY, b.y);
3874
- maxX = Math.max(maxX, b.x + b.w);
3875
- maxY = Math.max(maxY, b.y + b.h);
3876
- continue;
3877
- }
3878
- switch (el.type) {
3879
- case "stencil": {
3880
- const { x, y, w, h } = normalizeRect(el);
3881
- const labelW = el.label ? getStencilLabelWidth(w) : w;
3882
- minX = Math.min(minX, x + w / 2 - labelW / 2);
3883
- minY = Math.min(minY, y);
3884
- maxX = Math.max(maxX, x + w / 2 + labelW / 2);
3885
- maxY = Math.max(maxY, y + h + getStencilLabelHeight(el));
3886
- break;
3887
- }
3888
- case "rectangle":
3889
- case "ellipse":
3890
- case "rhombus":
3891
- case "shape":
3892
- case "text": {
3893
- const { x, y, w, h } = normalizeRect(el);
3894
- minX = Math.min(minX, x);
3895
- minY = Math.min(minY, y);
3896
- maxX = Math.max(maxX, x + w);
3897
- maxY = Math.max(maxY, y + h);
3898
- break;
3899
- }
3900
- case "freehand":
3901
- case "polygon":
3902
- for (const [px, py] of el.points) {
3903
- minX = Math.min(minX, px);
3904
- minY = Math.min(minY, py);
3905
- maxX = Math.max(maxX, px);
3906
- maxY = Math.max(maxY, py);
3907
- }
3908
- break;
3909
- case "curve":
3910
- minX = Math.min(minX, el.x, el.x2, el.cx);
3911
- minY = Math.min(minY, el.y, el.y2, el.cy);
3912
- maxX = Math.max(maxX, el.x, el.x2, el.cx);
3913
- maxY = Math.max(maxY, el.y, el.y2, el.cy);
3914
- break;
3915
- case "image": {
3916
- const { x: ix, y: iy, w, h } = normalizeRect(el);
3917
- minX = Math.min(minX, ix);
3918
- minY = Math.min(minY, iy);
3919
- maxX = Math.max(maxX, ix + w);
3920
- maxY = Math.max(maxY, iy + h);
3921
- break;
3922
- }
3961
+ if ((el.type === "freehand" || el.type === "polygon") && el.points.length === 0) continue;
3962
+ let box = getElementBounds(el, elements);
3963
+ if (el.type === "stencil") {
3964
+ const { x, y, w, h } = box;
3965
+ const labelW = el.label ? getStencilLabelWidth(w) : w;
3966
+ box = {
3967
+ x: x + w / 2 - labelW / 2,
3968
+ y,
3969
+ w: labelW,
3970
+ h: h + getStencilLabelHeight(el)
3971
+ };
3923
3972
  }
3973
+ const b = rotateBoxOf(el, box);
3974
+ minX = Math.min(minX, b.x);
3975
+ minY = Math.min(minY, b.y);
3976
+ maxX = Math.max(maxX, b.x + b.w);
3977
+ maxY = Math.max(maxY, b.y + b.h);
3924
3978
  }
3925
3979
  for (const box of getConnectorLabelBoxes(elements).values()) {
3926
3980
  minX = Math.min(minX, box.x - box.w / 2);
@@ -3935,7 +3989,7 @@ function computeBounds(elements) {
3935
3989
  maxY
3936
3990
  };
3937
3991
  }
3938
- function elementToSVG(el, ox, oy, allElements) {
3992
+ function elementToSVG(el, ox, oy, allElements, ink) {
3939
3993
  if ((el.type === "line" || el.type === "arrow") && el.routing === "elbow") return elbowToSVG(el, resolveConnectorRoute(el, allElements), ox, oy);
3940
3994
  switch (el.type) {
3941
3995
  case "rectangle": return rectToSVG(el, ox, oy);
@@ -3946,26 +4000,22 @@ function elementToSVG(el, ox, oy, allElements) {
3946
4000
  case "line": return lineToSVG(el, ox, oy, allElements);
3947
4001
  case "arrow": return arrowToSVG(el, ox, oy, allElements);
3948
4002
  case "freehand": return freehandToSVG(el, ox, oy);
3949
- case "text": return textToSVG(el, ox, oy);
4003
+ case "text": return el.isCode ? codeToSVG(el, ox, oy, ink.code) : textToSVG(el, ox, oy);
3950
4004
  case "image": return imageToSVG(el, ox, oy);
3951
4005
  case "polygon": {
3952
4006
  if (el.points.length < 2) return "";
3953
- const stroke = el.strokeColor;
3954
- const fill = el.fillColor === "transparent" ? "none" : el.fillColor;
3955
- const sw = el.strokeWidth;
3956
- const dash = el.strokeStyle === "dashed" ? `stroke-dasharray="${sw * 4},${sw * 2}"` : el.strokeStyle === "dotted" ? `stroke-dasharray="${sw},${sw * 2}"` : "";
3957
4007
  const pts = el.points.map(([x, y]) => `${x + ox},${y + oy}`).join(" ");
3958
- return `<${el.closed ? "polygon" : "polyline"} points="${pts}" fill="${escapeXml(fill)}" stroke="${escapeXml(stroke)}" stroke-width="${sw}" opacity="${el.opacity}" ${dash}/>`;
4008
+ return `<${el.closed ? "polygon" : "polyline"} points="${pts}" ${shapeProps(el)}${rotateAttr(el, ox, oy)}/>`;
3959
4009
  }
3960
4010
  case "curve": {
3961
- const stroke = el.strokeColor;
3962
- const sw = el.strokeWidth;
3963
- const dash = el.strokeStyle === "dashed" ? `stroke-dasharray="${sw * 4},${sw * 2}"` : el.strokeStyle === "dotted" ? `stroke-dasharray="${sw},${sw * 2}"` : "";
3964
4011
  const x = el.x + ox;
3965
4012
  const y = el.y + oy;
3966
4013
  const x2 = el.x2 + ox;
3967
4014
  const y2 = el.y2 + oy;
3968
- return `<path d="M ${x} ${y} Q ${el.cx + ox} ${el.cy + oy} ${x2} ${y2}" fill="none" stroke="${escapeXml(stroke)}" stroke-width="${sw}" opacity="${el.opacity}" ${dash}/>`;
4015
+ return `<path d="M ${x} ${y} Q ${el.cx + ox} ${el.cy + oy} ${x2} ${y2}" ${shapeProps({
4016
+ ...el,
4017
+ fillColor: "transparent"
4018
+ })}${rotateAttr(el, ox, oy)}/>`;
3969
4019
  }
3970
4020
  }
3971
4021
  }
@@ -3974,12 +4024,20 @@ function strokeDashAttr(el) {
3974
4024
  if (style === "dashed") return ` stroke-dasharray="${el.strokeWidth * 4 + 4} ${el.strokeWidth * 2 + 2}"`;
3975
4025
  if (style === "dotted") {
3976
4026
  const gap = el.strokeWidth * 3;
3977
- return ` stroke-dasharray="${el.strokeWidth} ${gap}" stroke-linecap="round"`;
4027
+ return ` stroke-dasharray="${el.strokeWidth} ${gap}"`;
3978
4028
  }
3979
4029
  return "";
3980
4030
  }
4031
+ /**
4032
+ * stroke-linecap and stroke-linejoin as drawElement sets them on the canvas:
4033
+ * the element's own, round when unset, and round caps for a dotted stroke,
4034
+ * whose dots they make.
4035
+ */
4036
+ function capJoinAttrs(el) {
4037
+ return `stroke-linecap="${escapeXml(el.strokeStyle === "dotted" ? "round" : el.lineCap ?? "round")}" stroke-linejoin="${escapeXml(el.lineJoin ?? "round")}"`;
4038
+ }
3981
4039
  function shapeProps(el) {
3982
- return `fill="${escapeXml(el.fillColor === "transparent" ? "none" : el.fillColor)}" stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" opacity="${el.opacity}"${strokeDashAttr(el)}`;
4040
+ return `fill="${escapeXml(el.fillColor === "transparent" ? "none" : el.fillColor)}" stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" ${capJoinAttrs(el)} opacity="${el.opacity}"${strokeDashAttr(el)}`;
3983
4041
  }
3984
4042
  function rotateAttr(el, ox, oy) {
3985
4043
  if (!el.rotation) return "";
@@ -3994,31 +4052,74 @@ function rectToSVG(el, ox, oy) {
3994
4052
  const y = top + oy;
3995
4053
  const cr = Math.min(el.cornerRadius ?? 0, w / 2, h / 2);
3996
4054
  const rx = cr > 0 ? ` rx="${round(cr)}"` : "";
3997
- let svg = `<rect x="${round(x)}" y="${round(y)}" width="${round(w)}" height="${round(h)}"${rx} ${shapeProps(el)}${rotateAttr(el, ox, oy)}/>`;
3998
- if (el.label) svg += "\n" + wrappedLabelToSVG(x + w / 2, y + h / 2, getLabelWrapWidth(el, w, h), el.label, el.labelFontSize ?? 16, el.labelFontFamily ?? "Arial, sans-serif", el.labelColor ?? contrastColor(el.fillColor, el.strokeColor), el.opacity);
3999
- return svg;
4055
+ return withLabel(el, `<rect x="${round(x)}" y="${round(y)}" width="${round(w)}" height="${round(h)}"${rx} ${shapeProps(el)}/>`, x + w / 2, y + h / 2, w, h, ox, oy);
4056
+ }
4057
+ /**
4058
+ * A box shape followed by its centered label, turned together when the
4059
+ * element is rotated, as on the canvas.
4060
+ */
4061
+ function withLabel(el, shape, cx, cy, w, h, ox, oy) {
4062
+ const parts = [shape];
4063
+ if (el.label) parts.push(wrappedLabelToSVG(cx, cy, getLabelWrapWidth(el, w, h), el.label, el.labelFontSize ?? 16, el.labelFontFamily ?? "Arial, sans-serif", el.labelColor ?? contrastColor(el.fillColor, el.strokeColor), el.opacity));
4064
+ const rot = rotateAttr(el, ox, oy);
4065
+ return rot ? `<g${rot}>${parts.join("")}</g>` : parts.join("\n");
4000
4066
  }
4001
4067
  function ellipseToSVG(el, ox, oy) {
4002
4068
  const cx = el.x + el.width / 2 + ox;
4003
4069
  const cy = el.y + el.height / 2 + oy;
4004
4070
  const rx = Math.abs(el.width / 2);
4005
4071
  const ry = Math.abs(el.height / 2);
4006
- let svg = `<ellipse cx="${round(cx)}" cy="${round(cy)}" rx="${round(rx)}" ry="${round(ry)}" ${shapeProps(el)}${rotateAttr(el, ox, oy)}/>`;
4007
- if (el.label) svg += "\n" + wrappedLabelToSVG(cx, cy, getLabelWrapWidth(el, rx * 2, ry * 2), el.label, el.labelFontSize ?? 16, el.labelFontFamily ?? "Arial, sans-serif", el.labelColor ?? contrastColor(el.fillColor, el.strokeColor), el.opacity);
4008
- return svg;
4072
+ return withLabel(el, `<ellipse cx="${round(cx)}" cy="${round(cy)}" rx="${round(rx)}" ry="${round(ry)}" ${shapeProps(el)}/>`, cx, cy, rx * 2, ry * 2, ox, oy);
4009
4073
  }
4010
4074
  function rhombusToSVG(el, ox, oy) {
4011
4075
  const { x: left, y: top, w, h } = normalizeRect(el);
4012
4076
  const x = left + ox;
4013
4077
  const y = top + oy;
4014
- let svg = `<polygon points="${[
4078
+ const cr = (el.cornerRadius ?? 0) > 0 ? Math.min(el.cornerRadius ?? 0, w / 4, h / 4) : 0;
4079
+ return withLabel(el, cr > 0 ? `<path d="${roundedRhombusPath(x, y, w, h, cr)}" ${shapeProps(el)}/>` : `<polygon points="${[
4015
4080
  `${round(x + w / 2)},${round(y)}`,
4016
4081
  `${round(x + w)},${round(y + h / 2)}`,
4017
4082
  `${round(x + w / 2)},${round(y + h)}`,
4018
4083
  `${round(x)},${round(y + h / 2)}`
4019
- ].join(" ")}" ${shapeProps(el)}${rotateAttr(el, ox, oy)}/>`;
4020
- if (el.label) svg += "\n" + wrappedLabelToSVG(x + w / 2, y + h / 2, getLabelWrapWidth(el, w, h), el.label, el.labelFontSize ?? 16, el.labelFontFamily ?? "Arial, sans-serif", el.labelColor ?? contrastColor(el.fillColor, el.strokeColor), el.opacity);
4021
- return svg;
4084
+ ].join(" ")}" ${shapeProps(el)}/>`, x + w / 2, y + h / 2, w, h, ox, oy);
4085
+ }
4086
+ /**
4087
+ * The rhombus outline with rounded corners, as drawRhombusPath builds it on
4088
+ * the canvas: at each corner a line to the point `r` along the incoming
4089
+ * edge, then arcTo(corner, next, r), which draws a line to the arc's first
4090
+ * tangent point and the arc of radius `r` to the second.
4091
+ */
4092
+ function roundedRhombusPath(x, y, w, h, cr) {
4093
+ const corners = [
4094
+ [x + w / 2, y],
4095
+ [x + w, y + h / 2],
4096
+ [x + w / 2, y + h],
4097
+ [x, y + h / 2]
4098
+ ];
4099
+ const d = [];
4100
+ for (let i = 0; i < 4; i++) {
4101
+ const prev = corners[(i + 3) % 4];
4102
+ const curr = corners[i];
4103
+ const next = corners[(i + 1) % 4];
4104
+ const d1x = prev[0] - curr[0];
4105
+ const d1y = prev[1] - curr[1];
4106
+ const d2x = next[0] - curr[0];
4107
+ const d2y = next[1] - curr[1];
4108
+ const len1 = Math.hypot(d1x, d1y);
4109
+ const len2 = Math.hypot(d2x, d2y);
4110
+ const r = Math.min(cr, len1 / 2, len2 / 2);
4111
+ const u1x = d1x / len1;
4112
+ const u1y = d1y / len1;
4113
+ const u2x = d2x / len2;
4114
+ const u2y = d2y / len2;
4115
+ d.push(`${i === 0 ? "M" : "L"} ${round(curr[0] + u1x * r)} ${round(curr[1] + u1y * r)}`);
4116
+ const cos = u1x * u2x + u1y * u2y;
4117
+ const t = r * Math.sqrt((1 + cos) / (1 - cos));
4118
+ const sweep = -u1x * u2y + u1y * u2x > 0 ? 1 : 0;
4119
+ d.push(`L ${round(curr[0] + u1x * t)} ${round(curr[1] + u1y * t)}`, `A ${round(r)} ${round(r)} 0 0 ${sweep} ${round(curr[0] + u2x * t)} ${round(curr[1] + u2y * t)}`);
4120
+ }
4121
+ d.push("Z");
4122
+ return d.join(" ");
4022
4123
  }
4023
4124
  function stencilToSVG(el, ox, oy) {
4024
4125
  const { x: left, y: top, w, h } = normalizeRect(el);
@@ -4039,7 +4140,7 @@ function stencilToSVG(el, ox, oy) {
4039
4140
  const fill = el.fillColor === "transparent" ? "none" : el.fillColor;
4040
4141
  const inner = [];
4041
4142
  if (icon.fill && fill !== "none") inner.push(`<path d="${shapeCommandsToPathData(icon.fill, 0, 0)}" fill="${escapeXml(fill)}" stroke="none"/>`);
4042
- inner.push(`<path d="${shapeCommandsToPathData(icon.strokes, 0, 0)}" fill="none" stroke="${stroke}" stroke-width="${getIconStrokeWidth(el.strokeWidth)}" stroke-linecap="round" stroke-linejoin="round"/>`);
4143
+ inner.push(`<path d="${shapeCommandsToPathData(icon.strokes, 0, 0)}" fill="none" stroke="${stroke}" stroke-width="${getIconStrokeWidth(el.strokeWidth)}" ${capJoinAttrs(el)}/>`);
4043
4144
  parts.push(`<g opacity="${el.opacity}" transform="translate(${round(tx)} ${round(ty)}) scale(${round(scale)})">${inner.join("")}</g>`);
4044
4145
  } else parts.push(`<rect x="${round(x)}" y="${round(y)}" width="${round(w)}" height="${round(h)}" fill="none" stroke="${escapeXml(el.strokeColor)}" stroke-dasharray="4 4"/>`);
4045
4146
  }
@@ -4092,7 +4193,7 @@ function headShapeToSVG(shape, attrs) {
4092
4193
  */
4093
4194
  function connectorToSVG(el, shaft, heads, rot) {
4094
4195
  const color = escapeXml(el.strokeColor);
4095
- const base = `stroke="${color}" stroke-width="${el.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" opacity="${el.opacity}"`;
4196
+ const base = `stroke="${color}" stroke-width="${el.strokeWidth}" ${capJoinAttrs(el)} opacity="${el.opacity}"`;
4096
4197
  const shapes = heads.map((h) => ({
4097
4198
  h,
4098
4199
  shape: getArrowHeadShape(h.style, h.fromX, h.fromY, h.tipX, h.tipY, el.strokeWidth)
@@ -4101,7 +4202,7 @@ function connectorToSVG(el, shaft, heads, rot) {
4101
4202
  const parts = [];
4102
4203
  if (closed.length > 0) {
4103
4204
  const id = `mh-${el.id.replace(/[^\w-]/g, "")}`;
4104
- const cutouts = closed.map(({ shape }) => headShapeToSVG(shape, "fill=\"black\"")).join("");
4205
+ const cutouts = closed.map(({ shape }) => headShapeToSVG(shape, `fill="black"${rot}`)).join("");
4105
4206
  parts.push(`<mask id="${id}" maskUnits="userSpaceOnUse" ${EVERYTHING_BOX}><rect ${EVERYTHING_BOX} fill="white"/>${cutouts}</mask>`, `<g mask="url(#${id})">${shaft}</g>`);
4106
4207
  } else parts.push(shaft);
4107
4208
  for (const { shape } of shapes) {
@@ -4114,23 +4215,24 @@ function lineToSVG(el, ox, oy, allElements) {
4114
4215
  const pts = resolveArrowEndpoints(el, allElements);
4115
4216
  const x1 = pts.x + ox, y1 = pts.y + oy;
4116
4217
  const x2 = pts.x2 + ox, y2 = pts.y2 + oy;
4117
- const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" opacity="${el.opacity}"${strokeDashAttr(el)}`;
4218
+ const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" ${capJoinAttrs(el)} fill="none" opacity="${el.opacity}"${strokeDashAttr(el)}`;
4118
4219
  const rot = rotateAttr(el, ox, oy);
4119
4220
  return [connectorToSVG(el, el.cx !== void 0 && el.cy !== void 0 ? `<path d="M ${round(x1)} ${round(y1)} Q ${round(el.cx + ox)} ${round(el.cy + oy)} ${round(x2)} ${round(y2)}" ${sp}${rot}/>` : `<line x1="${round(x1)}" y1="${round(y1)}" x2="${round(x2)}" y2="${round(y2)}" ${sp}${rot}/>`, getConnectorHeads(el, (placement) => offsetVector(getArrowHeadVector(pts, el, placement), ox, oy)), rot)].join("\n");
4120
4221
  }
4121
4222
  /** Orthogonal connector: one polyline plus heads on the end segments. */
4122
4223
  function elbowToSVG(el, route, ox, oy) {
4123
4224
  if (route.length < 2) return "";
4124
- const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" opacity="${el.opacity}"${strokeDashAttr(el)}`;
4225
+ const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" ${capJoinAttrs(el)} fill="none" opacity="${el.opacity}"${strokeDashAttr(el)}`;
4125
4226
  const points = route.map(([x, y]) => `${round(x + ox)},${round(y + oy)}`).join(" ");
4126
4227
  const heads = getConnectorHeads(el, (placement) => offsetVector(getRouteHeadVector(route, placement), ox, oy));
4127
- return [connectorToSVG(el, `<polyline points="${points}" ${sp}/>`, heads, "")].join("\n");
4228
+ const rot = rotateAttr(el, ox, oy);
4229
+ return [connectorToSVG(el, `<polyline points="${points}" ${sp}${rot}/>`, heads, rot)].join("\n");
4128
4230
  }
4129
4231
  function arrowToSVG(el, ox, oy, allElements) {
4130
4232
  const pts = resolveArrowEndpoints(el, allElements);
4131
4233
  const x1 = pts.x + ox, y1 = pts.y + oy;
4132
4234
  const x2 = pts.x2 + ox, y2 = pts.y2 + oy;
4133
- const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" stroke-linecap="round" stroke-linejoin="round" fill="none" opacity="${el.opacity}"`;
4235
+ const sp = `stroke="${escapeXml(el.strokeColor)}" stroke-width="${el.strokeWidth}" ${capJoinAttrs(el)} fill="none" opacity="${el.opacity}"`;
4134
4236
  const rot = rotateAttr(el, ox, oy);
4135
4237
  return [connectorToSVG(el, `<line x1="${round(x1)}" y1="${round(y1)}" x2="${round(x2)}" y2="${round(y2)}" ${sp}${rot}/>`, getConnectorHeads(el, (placement) => offsetVector(getArrowHeadVector(pts, {}, placement), ox, oy)), rot)].join("\n");
4136
4238
  }
@@ -4169,10 +4271,27 @@ function textToSVG(el, ox, oy) {
4169
4271
  const tspans = lines.map((line, i) => `<tspan x="${round(x)}" y="${round(box.y + oy + i * lineHeight)}">${escapeXml(line)}</tspan>`).join("");
4170
4272
  const weight = el.bold ? " font-weight=\"bold\"" : "";
4171
4273
  const style = el.italic ? " font-style=\"italic\"" : "";
4172
- return `${el.fillColor === "transparent" ? "" : `<rect x="${round(el.x + ox)}" y="${round(el.y + oy)}" width="${round(el.width)}" height="${round(el.height)}" fill="${escapeXml(el.fillColor)}" opacity="${el.opacity}"${rotateAttr(el, ox, oy)}/>`}<text font-family="${escapeXml(el.fontFamily)}" font-size="${el.fontSize}"${weight}${style} fill="${escapeXml(el.strokeColor)}" opacity="${el.opacity}" text-anchor="${anchor}" dominant-baseline="text-before-edge"${rotateAttr(el, ox, oy)}>${tspans}</text>`;
4274
+ const decorations = [el.underline && "underline", el.strikethrough && "line-through"].filter(Boolean);
4275
+ const decoration = decorations.length > 0 ? ` text-decoration="${decorations.join(" ")}"` : "";
4276
+ return `${el.fillColor === "transparent" ? "" : `<rect x="${round(el.x + ox)}" y="${round(el.y + oy)}" width="${round(el.width)}" height="${round(el.height)}" fill="${escapeXml(el.fillColor)}" opacity="${el.opacity}"${rotateAttr(el, ox, oy)}/>`}<text font-family="${escapeXml(el.fontFamily)}" font-size="${el.fontSize}"${weight}${style}${decoration} fill="${escapeXml(el.strokeColor)}" opacity="${el.opacity}" text-anchor="${anchor}" dominant-baseline="text-before-edge"${rotateAttr(el, ox, oy)}>${tspans}</text>`;
4277
+ }
4278
+ /**
4279
+ * A code block as drawCode paints it: a rounded box in the theme's code
4280
+ * colors, unwrapped lines 1.3 apart with a 10 px padding, spaces kept.
4281
+ */
4282
+ function codeToSVG(el, ox, oy, colors) {
4283
+ const PAD = 10;
4284
+ const x = el.x + ox;
4285
+ const y = el.y + oy;
4286
+ const align = el.textAlign ?? "left";
4287
+ const textX = align === "center" ? x + el.width / 2 : align === "right" ? x + el.width - PAD : x + PAD;
4288
+ const anchor = align === "center" ? "middle" : align === "right" ? "end" : "start";
4289
+ const rot = rotateAttr(el, ox, oy);
4290
+ const tspans = el.content.split("\n").map((line, i) => `<tspan x="${round(textX)}" y="${round(y + PAD + i * el.fontSize * 1.3)}">${escapeXml(line)}</tspan>`).join("");
4291
+ return [`<rect x="${round(x)}" y="${round(y)}" width="${round(el.width)}" height="${round(el.height)}" rx="6" fill="${colors.fill}" stroke="${colors.border}" stroke-width="1" opacity="${el.opacity}"${rot}/>`, `<text xml:space="preserve" font-family="${escapeXml(el.fontFamily)}" font-size="${el.fontSize}" fill="${escapeXml(el.strokeColor)}" opacity="${el.opacity}" text-anchor="${anchor}" dominant-baseline="text-before-edge"${rot}>${tspans}</text>`].join("");
4173
4292
  }
4174
4293
  /** Connector label on a box of the canvas color (see connector_labels.ts). */
4175
- function connectorLabelToSVG(el, box, ox, oy, canvasColor) {
4294
+ function connectorLabelToSVG(el, box, ox, oy, canvasColor, color) {
4176
4295
  if (!el.label) return "";
4177
4296
  const cx = box.x + ox;
4178
4297
  const cy = box.y + oy;
@@ -4180,7 +4299,7 @@ function connectorLabelToSVG(el, box, ox, oy, canvasColor) {
4180
4299
  const fontSize = el.labelFontSize ?? 12;
4181
4300
  const fontFamily = el.labelFontFamily ?? "Arial, sans-serif";
4182
4301
  const lines = el.label.split("\n");
4183
- return [`<rect x="${round(cx - w / 2)}" y="${round(cy - h / 2)}" width="${round(w)}" height="${round(h)}" fill="${canvasColor}"/>`, shapeLabelToSVG(cx, cy, lines, fontSize, fontFamily, el.labelColor ?? el.strokeColor, el.opacity)].join("\n");
4302
+ return [`<rect x="${round(cx - w / 2)}" y="${round(cy - h / 2)}" width="${round(w)}" height="${round(h)}" fill="${canvasColor}"/>`, shapeLabelToSVG(cx, cy, lines, fontSize, fontFamily, color, el.opacity)].join("\n");
4184
4303
  }
4185
4304
  /** Shape label wrapped like the canvas does (`drawShapeLabel`). */
4186
4305
  function wrappedLabelToSVG(cx, cy, maxWidth, label, fontSize, fontFamily, color, opacity) {
@@ -4207,7 +4326,7 @@ function escapeXml(str) {
4207
4326
  }
4208
4327
  //#endregion
4209
4328
  //#region package.json
4210
- var version = "0.7.0";
4329
+ var version = "0.7.2";
4211
4330
  //#endregion
4212
4331
  //#region ../src/core/layout.ts
4213
4332
  /** Orders vertices without recursion, preserving input order when unconstrained. */
@@ -4346,11 +4465,12 @@ function layeredLayout(nodes, edges, options = {}) {
4346
4465
  //#endregion
4347
4466
  //#region ../src/core/app_state.ts
4348
4467
  function createAppState() {
4468
+ const { document: doc, window: win } = globalThis;
4349
4469
  return {
4350
4470
  activeTool: "select",
4351
- strokeColor: (typeof document !== "undefined" ? document.documentElement.getAttribute("data-theme") : null) === "light" ? "#000000" : "#e2e2ef",
4471
+ strokeColor: doc?.documentElement.getAttribute("data-theme") === "light" ? "#000000" : "#e2e2ef",
4352
4472
  fillColor: "transparent",
4353
- strokeWidth: typeof window !== "undefined" && window.matchMedia("(pointer: coarse)").matches ? 4 : 1,
4473
+ strokeWidth: win?.matchMedia("(pointer: coarse)").matches ?? false ? 4 : 1,
4354
4474
  fontSize: 20,
4355
4475
  fontFamily: "Arial, sans-serif",
4356
4476
  textAlign: "left",
@@ -4505,6 +4625,14 @@ function applyPatch(scene, command) {
4505
4625
  } }
4506
4626
  };
4507
4627
  }
4628
+ /**
4629
+ * The elements a selection command acts on: its explicit `ids` (baked in by
4630
+ * History, see withTargets) or, for commands from older clients without
4631
+ * them, the local selection.
4632
+ */
4633
+ function targetIds(scene, ids) {
4634
+ return ids ? new Set(ids) : scene.selectedIds;
4635
+ }
4508
4636
  function reducer(scene, command, isRemote = false) {
4509
4637
  switch (command.type) {
4510
4638
  case "CREATE_ELEMENT": return {
@@ -4557,7 +4685,7 @@ function reducer(scene, command, isRemote = false) {
4557
4685
  ...y !== void 0 && { y },
4558
4686
  ...width !== void 0 && { width },
4559
4687
  ...height !== void 0 && { height },
4560
- ...fontSize !== void 0 && el.type === "text" && { fontSize }
4688
+ ...fontSize !== void 0 && el.type === "text" && { fontSize: Math.min(1e3, Math.max(1, fontSize)) }
4561
4689
  };
4562
4690
  if (el.type === "curve") {
4563
4691
  const patch = {};
@@ -4723,10 +4851,13 @@ function reducer(scene, command, isRemote = false) {
4723
4851
  ...scene.appState,
4724
4852
  fontFamily: command.family
4725
4853
  },
4726
- elements: scene.elements.map((el) => scene.selectedIds.has(el.id) && el.type === "text" ? {
4727
- ...el,
4728
- fontFamily: command.family
4729
- } : el)
4854
+ elements: (() => {
4855
+ const targets = targetIds(scene, command.ids);
4856
+ return scene.elements.map((el) => targets.has(el.id) && el.type === "text" ? {
4857
+ ...el,
4858
+ fontFamily: command.family
4859
+ } : el);
4860
+ })()
4730
4861
  };
4731
4862
  case "SET_FONT_SIZE": return {
4732
4863
  ...scene,
@@ -4734,12 +4865,20 @@ function reducer(scene, command, isRemote = false) {
4734
4865
  ...scene.appState,
4735
4866
  fontSize: command.size
4736
4867
  },
4737
- elements: scene.elements.map((el) => scene.selectedIds.has(el.id) && el.type === "text" ? {
4738
- ...el,
4739
- fontSize: command.size,
4740
- ...command.width !== void 0 && { width: command.width },
4741
- ...command.height !== void 0 && { height: command.height }
4742
- } : el)
4868
+ elements: (() => {
4869
+ const targets = targetIds(scene, command.ids);
4870
+ const measured = new Map((command.bounds ?? []).map((b) => [b.id, b]));
4871
+ return scene.elements.map((el) => {
4872
+ if (!targets.has(el.id) || el.type !== "text") return el;
4873
+ const box = command.bounds ? measured.get(el.id) : command;
4874
+ return {
4875
+ ...el,
4876
+ fontSize: command.size,
4877
+ ...box?.width !== void 0 && { width: box.width },
4878
+ ...box?.height !== void 0 && { height: box.height }
4879
+ };
4880
+ });
4881
+ })()
4743
4882
  };
4744
4883
  case "TOGGLE_GRID": return {
4745
4884
  ...scene,
@@ -4759,7 +4898,7 @@ function reducer(scene, command, isRemote = false) {
4759
4898
  ...scene,
4760
4899
  elements: scene.elements.map((el) => el.id === command.id && !(el.type === "stencil" && !isRotatableStencil(el)) ? {
4761
4900
  ...el,
4762
- rotation: command.rotation
4901
+ rotation: normalizeRotation(command.rotation)
4763
4902
  } : el)
4764
4903
  };
4765
4904
  case "SET_STROKE_STYLE": return {
@@ -4771,7 +4910,7 @@ function reducer(scene, command, isRemote = false) {
4771
4910
  };
4772
4911
  case "REORDER_ELEMENTS": {
4773
4912
  const idSet = new Set(command.ids);
4774
- const moving = command.ids.map((id) => scene.elements.find((el) => el.id === id)).filter((el) => el !== void 0);
4913
+ const moving = scene.elements.filter((el) => idSet.has(el.id));
4775
4914
  const rest = scene.elements.filter((el) => !idSet.has(el.id));
4776
4915
  const clampedIdx = Math.max(0, Math.min(command.targetIndex, rest.length));
4777
4916
  const reordered = [
@@ -4802,7 +4941,7 @@ function reducer(scene, command, isRemote = false) {
4802
4941
  ...scene,
4803
4942
  elements: command.elements,
4804
4943
  selectedIds: /* @__PURE__ */ new Set(),
4805
- viewport: command.viewport
4944
+ viewport: isRemote ? scene.viewport : command.viewport
4806
4945
  };
4807
4946
  case "GROUP_ELEMENTS": {
4808
4947
  const groupSet = new Set(command.ids);
@@ -4863,17 +5002,20 @@ function reducer(scene, command, isRemote = false) {
4863
5002
  toolLocked: command.locked
4864
5003
  }
4865
5004
  };
4866
- case "SET_TEXT_MODE": return {
4867
- ...scene,
4868
- appState: {
4869
- ...scene.appState,
4870
- textMode: command.mode
4871
- },
4872
- elements: scene.elements.map((el) => scene.selectedIds.has(el.id) && el.type === "text" ? {
4873
- ...el,
4874
- isCode: command.mode === "code"
4875
- } : el)
4876
- };
5005
+ case "SET_TEXT_MODE": {
5006
+ const targets = targetIds(scene, command.ids);
5007
+ return {
5008
+ ...scene,
5009
+ appState: isRemote ? scene.appState : {
5010
+ ...scene.appState,
5011
+ textMode: command.mode
5012
+ },
5013
+ elements: scene.elements.map((el) => targets.has(el.id) && el.type === "text" ? {
5014
+ ...el,
5015
+ isCode: command.mode === "code"
5016
+ } : el)
5017
+ };
5018
+ }
4877
5019
  case "APPLY_STYLE": {
4878
5020
  const { strokeColor, fillColor, labelColor, strokeWidth, opacity, roughness, strokeStyle, lineCap, lineJoin, shadowBlur, shadowColor, shadowOffsetX, shadowOffsetY, cornerRadius, textAlign, bold, italic, underline, strikethrough, arrowHead, shapeKind, routing, startHeadStyle, endHeadStyle } = command;
4879
5021
  const patch = {};
@@ -5147,18 +5289,30 @@ function buildRevertPatch(change, current, direction) {
5147
5289
  //#endregion
5148
5290
  //#region ../src/engine/history.ts
5149
5291
  /**
5150
- * For APPLY_STYLE commands without explicit `ids`, resolve the target elements
5151
- * from the current selection (or the last-created element when nothing is
5152
- * selected) and bake them into the command. This keeps the command
5153
- * deterministic across a shared session.
5292
+ * Bakes the target elements into the commands that act on "the selection"
5293
+ * (APPLY_STYLE and the text font and mode commands) when they carry no `ids`.
5294
+ * In a shared session every client then changes the same elements, never
5295
+ * each peer's own selection. APPLY_STYLE without a selection targets the
5296
+ * last-created element.
5154
5297
  */
5155
- function withApplyStyleTargets(scene, command) {
5156
- if (command.type !== "APPLY_STYLE" || command.ids !== void 0) return command;
5157
- const ids = scene.selectedIds.size > 0 ? [...scene.selectedIds] : scene.appState.lastCreatedId ? [scene.appState.lastCreatedId] : [];
5158
- return {
5159
- ...command,
5160
- ids
5161
- };
5298
+ function withTargets(scene, command) {
5299
+ switch (command.type) {
5300
+ case "APPLY_STYLE": {
5301
+ if (command.ids !== void 0) return command;
5302
+ const ids = scene.selectedIds.size > 0 ? [...scene.selectedIds] : scene.appState.lastCreatedId ? [scene.appState.lastCreatedId] : [];
5303
+ return {
5304
+ ...command,
5305
+ ids
5306
+ };
5307
+ }
5308
+ case "SET_FONT_FAMILY":
5309
+ case "SET_FONT_SIZE":
5310
+ case "SET_TEXT_MODE": return command.ids !== void 0 ? command : {
5311
+ ...command,
5312
+ ids: [...scene.selectedIds]
5313
+ };
5314
+ default: return command;
5315
+ }
5162
5316
  }
5163
5317
  /**
5164
5318
  * Undo/redo stack plus the single entry point for state changes.
@@ -5195,6 +5349,10 @@ var History = class {
5195
5349
  get present() {
5196
5350
  return this._present;
5197
5351
  }
5352
+ /** True between beginDrag and endDrag (or cancelDrag). */
5353
+ get isDragging() {
5354
+ return this.drag !== null;
5355
+ }
5198
5356
  /** Call at the start of a drag (move/resize/rotate). Every command until
5199
5357
  * endDrag folds into one undo step, so the drag undoes in a single Ctrl+Z. */
5200
5358
  beginDrag() {
@@ -5217,6 +5375,7 @@ var History = class {
5217
5375
  this.drag = null;
5218
5376
  if (!drag.touched) {
5219
5377
  this.future = drag.future;
5378
+ if (drag.future.length > 0) this.notify();
5220
5379
  return;
5221
5380
  }
5222
5381
  rebaseIndices(drag.change, drag.sceneBefore, this._present);
@@ -5225,6 +5384,7 @@ var History = class {
5225
5384
  appStateBefore: drag.appStateBefore,
5226
5385
  appStateAfter: this._present.appState
5227
5386
  });
5387
+ this.notify();
5228
5388
  }
5229
5389
  /** Cancel an in-progress drag and revert what it changed. Edits peers made
5230
5390
  * during the drag are kept, and the revert is broadcast. */
@@ -5253,32 +5413,50 @@ var History = class {
5253
5413
  this._present = next;
5254
5414
  this.notify();
5255
5415
  }
5256
- /** Reset the scene to a fresh board, then replay a list of commands (used when
5257
- * joining a live room: the room's log is authoritative). Does not touch undo. */
5416
+ /**
5417
+ * Replaces the board with the room's (used when joining or rejoining a live
5418
+ * room: the room's log is authoritative), then notifies once. Clears undo.
5419
+ *
5420
+ * Only the board is replaced: the tool, the default style and the grid are
5421
+ * this user's own and survive a join or a reconnect. The viewport survives
5422
+ * too unless `keepViewport` is false.
5423
+ */
5258
5424
  resetForLiveReplay(commands, keepViewport = true) {
5259
5425
  if (this.readOnly) return;
5260
- const viewport = this._present.viewport;
5426
+ const { viewport, appState } = this._present;
5261
5427
  this.past = [];
5262
5428
  this.future = [];
5263
5429
  this.drag = null;
5264
- this._present = createScene();
5265
- if (keepViewport) this._present = {
5266
- ...this._present,
5267
- viewport
5430
+ const fresh = createScene();
5431
+ let scene = {
5432
+ ...fresh,
5433
+ appState: {
5434
+ ...appState,
5435
+ lastCreatedId: null,
5436
+ justCreatedText: false
5437
+ },
5438
+ viewport: keepViewport ? viewport : fresh.viewport
5268
5439
  };
5269
- for (const command of commands) this.applyRemote(command);
5440
+ for (const command of commands) try {
5441
+ scene = reducer(scene, command, true);
5442
+ } catch (error) {
5443
+ console.error("Skipped a live command that failed to apply", error);
5444
+ }
5445
+ this._present = scene;
5446
+ this.notify();
5270
5447
  }
5271
5448
  dispatch(command) {
5272
5449
  if (this.readOnly && (!isEphemeralCommand(command.type) || command.type === "SET_JUST_CREATED_TEXT")) return;
5273
- const resolved = withApplyStyleTargets(this._present, command);
5450
+ const resolved = withTargets(this._present, command);
5274
5451
  const next = reducer(this._present, resolved);
5275
5452
  if (next === this._present) return;
5276
5453
  if (!isEphemeralCommand(resolved.type)) {
5277
5454
  const step = diffScenes(this._present, next);
5455
+ const undoable = isUndoableChange(step, this._present, next);
5278
5456
  if (this.drag) {
5279
5457
  composeChange(this.drag.change, step);
5280
- this.drag.touched = true;
5281
- } else {
5458
+ if (undoable) this.drag.touched = true;
5459
+ } else if (undoable) {
5282
5460
  this.past.push({
5283
5461
  change: step,
5284
5462
  appStateBefore: this._present.appState,
@@ -5339,28 +5517,65 @@ var History = class {
5339
5517
  }
5340
5518
  };
5341
5519
  /**
5520
+ * appState fields undo and redo leave as they are now: the tool and the
5521
+ * default style, which the tool switch and the style panel also set without
5522
+ * an undo step (SET_TOOL inherits the selection's style and sets the shape
5523
+ * kind), and view settings. Restoring them would undo choices the user made
5524
+ * after the step. The text defaults (font size and family, alignment, mode)
5525
+ * and the line routing are restored.
5526
+ */
5527
+ var KEPT_ON_UNDO = [
5528
+ "activeTool",
5529
+ "strokeColor",
5530
+ "fillColor",
5531
+ "strokeWidth",
5532
+ "opacity",
5533
+ "roughness",
5534
+ "strokeStyle",
5535
+ "shapeKind",
5536
+ "gridVisible",
5537
+ "gridType",
5538
+ "toolLocked",
5539
+ "justCreatedText"
5540
+ ];
5541
+ var KEPT_ON_UNDO_SET = /* @__PURE__ */ new Set([...KEPT_ON_UNDO, "lastCreatedId"]);
5542
+ /**
5543
+ * Whether a change is worth an undo step: it touches elements or their order,
5544
+ * or an appState field that undo restores. An element change the diff leaves
5545
+ * out (a type-only change: the type is identity there) still counts, so the
5546
+ * board is never changed without a step.
5547
+ */
5548
+ function isUndoableChange(change, prev, next) {
5549
+ if (change.elements.size > 0 || change.order) return true;
5550
+ if (!sameElements(prev.elements, next.elements)) return true;
5551
+ const before = prev.appState;
5552
+ const after = next.appState;
5553
+ return Object.keys(after).some((key) => !KEPT_ON_UNDO_SET.has(key) && after[key] !== before[key]);
5554
+ }
5555
+ /** Same elements in the same order, by value (unchanged ones keep identity). */
5556
+ function sameElements(a, b) {
5557
+ if (a === b) return true;
5558
+ if (a.length !== b.length) return false;
5559
+ return a.every((el, i) => el === b[i] || deepEqual(el, b[i]));
5560
+ }
5561
+ /**
5342
5562
  * Restore the per-user appState recorded with an undo step (e.g. the font size
5343
- * default a command changed), keeping view and tool state as they are now.
5344
- * The selection stays as-is unless `selectedIds` is given (cancelled drag);
5345
- * either way it is limited to elements that still exist.
5563
+ * default a command changed), keeping the fields in KEPT_ON_UNDO as they are
5564
+ * now. The selection stays as-is unless `selectedIds` is given (cancelled
5565
+ * drag); either way it is limited to elements that still exist.
5346
5566
  */
5347
5567
  function restoreLocalState(scene, appState, selectedIds = scene.selectedIds) {
5348
5568
  const elementIds = new Set(scene.elements.map((element) => element.id));
5349
5569
  const current = scene.appState;
5570
+ const kept = {};
5571
+ for (const key of KEPT_ON_UNDO) kept[key] = current[key];
5350
5572
  const currentLastCreatedId = current.lastCreatedId;
5351
5573
  return {
5352
5574
  ...scene,
5353
5575
  selectedIds: new Set([...selectedIds].filter((id) => elementIds.has(id))),
5354
5576
  appState: {
5355
5577
  ...appState,
5356
- activeTool: current.activeTool,
5357
- strokeColor: current.strokeColor,
5358
- fillColor: current.fillColor,
5359
- strokeWidth: current.strokeWidth,
5360
- gridVisible: current.gridVisible,
5361
- gridType: current.gridType,
5362
- toolLocked: current.toolLocked,
5363
- justCreatedText: current.justCreatedText,
5578
+ ...kept,
5364
5579
  lastCreatedId: currentLastCreatedId && elementIds.has(currentLastCreatedId) ? currentLastCreatedId : null
5365
5580
  }
5366
5581
  };
@@ -5381,7 +5596,7 @@ var ELEMENT_TYPES = /* @__PURE__ */ new Set([
5381
5596
  "text",
5382
5597
  "image"
5383
5598
  ]);
5384
- var STROKE_STYLES = /* @__PURE__ */ new Set([
5599
+ var STROKE_STYLES$1 = /* @__PURE__ */ new Set([
5385
5600
  "solid",
5386
5601
  "dashed",
5387
5602
  "dotted"
@@ -5410,7 +5625,7 @@ var ARROW_HEADS = /* @__PURE__ */ new Set([
5410
5625
  var SHAPE_KIND_SET = new Set(SHAPE_KINDS);
5411
5626
  var ROUTINGS = new Set(CONNECTOR_ROUTINGS);
5412
5627
  var HEAD_STYLES = new Set(ARROW_HEAD_STYLES);
5413
- function isRecord(value) {
5628
+ function isRecord$1(value) {
5414
5629
  return typeof value === "object" && value !== null;
5415
5630
  }
5416
5631
  function isFiniteNumber(value) {
@@ -5419,11 +5634,11 @@ function isFiniteNumber(value) {
5419
5634
  function isFiniteNumberInRange(value, min, max) {
5420
5635
  return isFiniteNumber(value) && value >= min && value <= max;
5421
5636
  }
5422
- function isString(value, maxLength = 1e4) {
5637
+ function isString$1(value, maxLength = 1e4) {
5423
5638
  return typeof value === "string" && value.length <= maxLength;
5424
5639
  }
5425
5640
  function isOptionalString(value, maxLength = 1e4) {
5426
- return value === void 0 || isString(value, maxLength);
5641
+ return value === void 0 || isString$1(value, maxLength);
5427
5642
  }
5428
5643
  function isOptionalBoolean(value) {
5429
5644
  return value === void 0 || typeof value === "boolean";
@@ -5435,7 +5650,7 @@ function isOptionalEnum(value, values) {
5435
5650
  return value === void 0 || typeof value === "string" && values.has(value);
5436
5651
  }
5437
5652
  function isCssColor(value) {
5438
- if (!isString(value, 128)) return false;
5653
+ if (!isString$1(value, 128)) return false;
5439
5654
  if (value === "transparent" || value === "none") return true;
5440
5655
  if (/^#[\da-f]{3,8}$/i.test(value)) return true;
5441
5656
  if (/^[a-z]+$/i.test(value)) return true;
@@ -5444,11 +5659,11 @@ function isCssColor(value) {
5444
5659
  function isOptionalCssColor(value) {
5445
5660
  return value === void 0 || isCssColor(value);
5446
5661
  }
5447
- function isPoint(value) {
5662
+ function isPoint$1(value) {
5448
5663
  return Array.isArray(value) && value.length === 2 && isFiniteNumberInRange(value[0], -1e7, 1e7) && isFiniteNumberInRange(value[1], -1e7, 1e7);
5449
5664
  }
5450
5665
  function hasValidBaseFields(el) {
5451
- return isString(el.id, 128) && el.id.length > 0 && typeof el.type === "string" && ELEMENT_TYPES.has(el.type) && isFiniteNumberInRange(el.x, -1e7, 1e7) && isFiniteNumberInRange(el.y, -1e7, 1e7) && isCssColor(el.strokeColor) && isCssColor(el.fillColor) && isFiniteNumberInRange(el.strokeWidth, 0, 1e3) && isFiniteNumberInRange(el.opacity, 0, 1) && isFiniteNumberInRange(el.roughness, 0, 10) && isOptionalFiniteNumber(el.rotation, -Math.PI * 2, Math.PI * 2) && isOptionalEnum(el.strokeStyle, STROKE_STYLES) && isOptionalEnum(el.lineCap, LINE_CAPS) && isOptionalEnum(el.lineJoin, LINE_JOINS) && isOptionalFiniteNumber(el.shadowBlur, 0, 1e3) && isOptionalCssColor(el.shadowColor) && isOptionalFiniteNumber(el.shadowOffsetX) && isOptionalFiniteNumber(el.shadowOffsetY) && isOptionalBoolean(el.visible) && isOptionalString(el.layerName, 1e3) && isOptionalBoolean(el.locked) && isOptionalString(el.groupId, 128);
5666
+ return isString$1(el.id, 128) && el.id.length > 0 && typeof el.type === "string" && ELEMENT_TYPES.has(el.type) && isFiniteNumberInRange(el.x, -1e7, 1e7) && isFiniteNumberInRange(el.y, -1e7, 1e7) && isCssColor(el.strokeColor) && isCssColor(el.fillColor) && isFiniteNumberInRange(el.strokeWidth, 0, 1e3) && isFiniteNumberInRange(el.opacity, 0, 1) && isFiniteNumberInRange(el.roughness, 0, 10) && isOptionalFiniteNumber(el.rotation, -Math.PI * 2, Math.PI * 2) && isOptionalEnum(el.strokeStyle, STROKE_STYLES$1) && isOptionalEnum(el.lineCap, LINE_CAPS) && isOptionalEnum(el.lineJoin, LINE_JOINS) && isOptionalFiniteNumber(el.shadowBlur, 0, 1e3) && isOptionalCssColor(el.shadowColor) && isOptionalFiniteNumber(el.shadowOffsetX) && isOptionalFiniteNumber(el.shadowOffsetY) && isOptionalBoolean(el.visible) && isOptionalString(el.layerName, 1e3) && isOptionalBoolean(el.locked) && isOptionalString(el.groupId, 128);
5452
5667
  }
5453
5668
  function hasBoxFields(el) {
5454
5669
  return isFiniteNumberInRange(el.width, -1e7, 1e7) && isFiniteNumberInRange(el.height, -1e7, 1e7);
@@ -5457,40 +5672,40 @@ function hasShapeLabelFields(el) {
5457
5672
  return isOptionalString(el.label) && isOptionalFiniteNumber(el.labelFontSize, 1, 1e3) && isOptionalString(el.labelFontFamily, 256) && isOptionalCssColor(el.labelColor);
5458
5673
  }
5459
5674
  function isValidStencilSource(value) {
5460
- if (!isRecord(value)) return false;
5461
- if (value.kind === "builtin") return isString(value.ref, 128) && isValidStencilRef(value.ref);
5462
- if (value.kind === "embedded") return isString(value.src, 65536) && isValidEmbeddedSvg(value.src) && isString(value.pack, 128) && isString(value.name, 256);
5675
+ if (!isRecord$1(value)) return false;
5676
+ if (value.kind === "builtin") return isString$1(value.ref, 128) && isValidStencilRef(value.ref);
5677
+ if (value.kind === "embedded") return isString$1(value.src, 65536) && isValidEmbeddedSvg(value.src) && isString$1(value.pack, 128) && isString$1(value.name, 256);
5463
5678
  return false;
5464
5679
  }
5465
5680
  function hasEndpointFields(el) {
5466
5681
  return isFiniteNumberInRange(el.x2, -1e7, 1e7) && isFiniteNumberInRange(el.y2, -1e7, 1e7);
5467
5682
  }
5468
5683
  function isOptionalAnchor(value) {
5469
- return value === void 0 || isRecord(value) && isFiniteNumberInRange(value.x, 0, 1) && isFiniteNumberInRange(value.y, 0, 1);
5684
+ return value === void 0 || isRecord$1(value) && isFiniteNumberInRange(value.x, 0, 1) && isFiniteNumberInRange(value.y, 0, 1);
5470
5685
  }
5471
5686
  function hasConnectorFields(el) {
5472
5687
  return isOptionalString(el.startElementId, 128) && isOptionalString(el.endElementId, 128) && isOptionalAnchor(el.startAnchor) && isOptionalAnchor(el.endAnchor) && isOptionalEnum(el.routing, ROUTINGS) && isOptionalEnum(el.endHeadStyle, HEAD_STYLES) && hasShapeLabelFields(el);
5473
5688
  }
5474
5689
  function hasPointFields(el) {
5475
- return Array.isArray(el.points) && el.points.length >= 2 && el.points.length <= 1e5 && el.points.every(isPoint);
5690
+ return Array.isArray(el.points) && el.points.length >= 2 && el.points.length <= 1e5 && el.points.every(isPoint$1);
5476
5691
  }
5477
5692
  function isImageSource(value) {
5478
- return isString(value, 1e7) && /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);base64,/i.test(value);
5693
+ return isString$1(value, 1e7) && /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);base64,/i.test(value);
5479
5694
  }
5480
5695
  function isValidElement(value) {
5481
- if (!isRecord(value) || !hasValidBaseFields(value)) return false;
5696
+ if (!isRecord$1(value) || !hasValidBaseFields(value)) return false;
5482
5697
  switch (value.type) {
5483
5698
  case "rectangle":
5484
5699
  case "ellipse":
5485
5700
  case "rhombus": return hasBoxFields(value) && hasShapeLabelFields(value) && isOptionalFiniteNumber(value.cornerRadius, 0, 1e3);
5486
5701
  case "shape": return hasBoxFields(value) && hasShapeLabelFields(value) && typeof value.kind === "string" && SHAPE_KIND_SET.has(value.kind);
5487
- case "stencil": return hasBoxFields(value) && hasShapeLabelFields(value) && isValidStencilSource(value.source) && !(isRecord(value.source) && value.source.kind === "embedded" && value.rotation !== void 0 && value.rotation !== 0);
5702
+ case "stencil": return hasBoxFields(value) && hasShapeLabelFields(value) && isValidStencilSource(value.source) && !(isRecord$1(value.source) && value.source.kind === "embedded" && value.rotation !== void 0 && value.rotation !== 0);
5488
5703
  case "line": return hasEndpointFields(value) && hasConnectorFields(value) && isOptionalFiniteNumber(value.cx) && isOptionalFiniteNumber(value.cy) && isOptionalEnum(value.arrowHead, ARROW_HEADS) && isOptionalEnum(value.startHeadStyle, HEAD_STYLES);
5489
5704
  case "arrow": return hasEndpointFields(value) && hasConnectorFields(value);
5490
5705
  case "curve": return hasEndpointFields(value) && isFiniteNumberInRange(value.cx, -1e7, 1e7) && isFiniteNumberInRange(value.cy, -1e7, 1e7);
5491
5706
  case "polygon": return hasPointFields(value) && typeof value.closed === "boolean";
5492
5707
  case "freehand": return hasPointFields(value) && (value.pressures === void 0 || Array.isArray(value.pressures) && value.pressures.length === value.points.length && value.pressures.every((pressure) => isFiniteNumberInRange(pressure, 0, 1)));
5493
- case "text": return hasBoxFields(value) && isString(value.content) && isOptionalFiniteNumber(value.padding, 0, 1e3) && isFiniteNumberInRange(value.fontSize, 1, 1e3) && isString(value.fontFamily, 256) && isOptionalEnum(value.textAlign, TEXT_ALIGNS) && isOptionalBoolean(value.isCode) && isOptionalBoolean(value.bold) && isOptionalBoolean(value.italic) && isOptionalBoolean(value.underline) && isOptionalBoolean(value.strikethrough);
5708
+ case "text": return hasBoxFields(value) && isString$1(value.content) && isOptionalFiniteNumber(value.padding, 0, 1e3) && isFiniteNumberInRange(value.fontSize, 1, 1e3) && isString$1(value.fontFamily, 256) && isOptionalEnum(value.textAlign, TEXT_ALIGNS) && isOptionalBoolean(value.isCode) && isOptionalBoolean(value.bold) && isOptionalBoolean(value.italic) && isOptionalBoolean(value.underline) && isOptionalBoolean(value.strikethrough);
5494
5709
  case "image": return hasBoxFields(value) && isImageSource(value.src) && isFiniteNumberInRange(value.naturalWidth, 1, 1e5) && isFiniteNumberInRange(value.naturalHeight, 1, 1e5);
5495
5710
  }
5496
5711
  return false;
@@ -5517,6 +5732,15 @@ function validateElements(value) {
5517
5732
  }
5518
5733
  return valid.length > 0 ? valid : null;
5519
5734
  }
5735
+ function validateViewport(value) {
5736
+ if (!isRecord$1(value)) return null;
5737
+ if (!isFiniteNumberInRange(value.offsetX, -1e7, 1e7) || !isFiniteNumberInRange(value.offsetY, -1e7, 1e7) || !isFiniteNumberInRange(value.zoom, .05, 30)) return null;
5738
+ return {
5739
+ offsetX: value.offsetX,
5740
+ offsetY: value.offsetY,
5741
+ zoom: value.zoom
5742
+ };
5743
+ }
5520
5744
  //#endregion
5521
5745
  //#region src/sizing.ts
5522
5746
  /**
@@ -6327,6 +6551,272 @@ function describeDiagram(diagram) {
6327
6551
  return lines.join("\n");
6328
6552
  }
6329
6553
  //#endregion
6554
+ //#region ../src/io/command_validation.ts
6555
+ function isRecord(value) {
6556
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6557
+ }
6558
+ function isId(value) {
6559
+ return typeof value === "string" && value.length > 0 && value.length <= 128;
6560
+ }
6561
+ function isIdList(value) {
6562
+ return Array.isArray(value) && value.length <= 5e3 && value.every(isId);
6563
+ }
6564
+ function isNumber(value) {
6565
+ return typeof value === "number" && Number.isFinite(value);
6566
+ }
6567
+ var optional = (check) => (value) => value === void 0 || check(value);
6568
+ var isString = (value) => typeof value === "string";
6569
+ var isBoolean = (value) => typeof value === "boolean";
6570
+ var optionalNumber = optional(isNumber);
6571
+ var optionalString = optional(isString);
6572
+ var optionalBoolean = optional(isBoolean);
6573
+ var optionalIdList = optional(isIdList);
6574
+ function isPoint(value) {
6575
+ return Array.isArray(value) && value.length === 2 && isNumber(value[0]) && isNumber(value[1]);
6576
+ }
6577
+ /** A connector end: an element id to attach to, or null to detach. */
6578
+ var isEndTarget = optional((value) => value === null || isId(value));
6579
+ /** A pinned connector end, or null to let it float along the border. */
6580
+ var isAnchor = optional((value) => value === null || isRecord(value) && isNumber(value.x) && isNumber(value.y));
6581
+ /**
6582
+ * A partial element, as UPDATE_ELEMENT and PATCH_ELEMENTS carry it. An
6583
+ * element never changes identity or type after creation, and the two fields
6584
+ * that hold content from outside the app keep the rules of a whole element:
6585
+ * an image source stays an inline image, a stencil source a known one.
6586
+ */
6587
+ function isElementPatch(value) {
6588
+ if (!isRecord(value)) return false;
6589
+ if ("id" in value || "type" in value) return false;
6590
+ if ("src" in value && !isImageSource(value.src)) return false;
6591
+ if ("source" in value && !isValidStencilSource(value.source)) return false;
6592
+ return true;
6593
+ }
6594
+ function isElementList(value) {
6595
+ return Array.isArray(value) && value.length <= 5e3 && value.every(isValidElement);
6596
+ }
6597
+ function isListOf(value, check) {
6598
+ return Array.isArray(value) && value.length <= 5e3 && value.every((item) => isRecord(item) && check(item));
6599
+ }
6600
+ var STROKE_STYLES = /* @__PURE__ */ new Set([
6601
+ "solid",
6602
+ "dashed",
6603
+ "dotted"
6604
+ ]);
6605
+ var TEXT_MODES = /* @__PURE__ */ new Set(["text", "code"]);
6606
+ var STYLE_STRINGS = [
6607
+ "strokeColor",
6608
+ "fillColor",
6609
+ "labelColor",
6610
+ "strokeStyle",
6611
+ "lineCap",
6612
+ "lineJoin",
6613
+ "shadowColor",
6614
+ "textAlign",
6615
+ "arrowHead",
6616
+ "shapeKind",
6617
+ "routing",
6618
+ "startHeadStyle",
6619
+ "endHeadStyle"
6620
+ ];
6621
+ var STYLE_NUMBERS = [
6622
+ "strokeWidth",
6623
+ "opacity",
6624
+ "roughness",
6625
+ "shadowBlur",
6626
+ "shadowOffsetX",
6627
+ "shadowOffsetY",
6628
+ "cornerRadius"
6629
+ ];
6630
+ var STYLE_BOOLEANS = [
6631
+ "bold",
6632
+ "italic",
6633
+ "underline",
6634
+ "strikethrough"
6635
+ ];
6636
+ var RESIZE_NUMBERS = [
6637
+ "x",
6638
+ "y",
6639
+ "width",
6640
+ "height",
6641
+ "x2",
6642
+ "y2",
6643
+ "cx",
6644
+ "cy",
6645
+ "fontSize"
6646
+ ];
6647
+ /** One check per relayed command type; a type missing here is refused. */
6648
+ var CHECKS = {
6649
+ CREATE_ELEMENT: (c) => isValidElement(c.element) && optionalBoolean(c.select),
6650
+ CREATE_ELEMENTS: (c) => isElementList(c.elements),
6651
+ UPDATE_ELEMENT: (c) => isId(c.id) && isElementPatch(c.props),
6652
+ MOVE_ELEMENT: (c) => isId(c.id) && isNumber(c.dx) && isNumber(c.dy),
6653
+ MOVE_ELEMENTS: (c) => isIdList(c.ids) && isNumber(c.dx) && isNumber(c.dy),
6654
+ RESIZE_ELEMENT: (c) => isId(c.id) && RESIZE_NUMBERS.every((key) => optionalNumber(c[key])) && optional((points) => Array.isArray(points) && points.length <= 1e5 && points.every(isPoint))(c.points) && isEndTarget(c.startElementId) && isEndTarget(c.endElementId) && isAnchor(c.startAnchor) && isAnchor(c.endAnchor),
6655
+ DELETE_ELEMENTS: (c) => isIdList(c.ids),
6656
+ PATCH_ELEMENTS: (c) => optional((create) => isListOf(create, (item) => isValidElement(item.element) && Number.isInteger(item.index) && item.index >= 0))(c.create) && optional((update) => isListOf(update, (item) => isId(item.id) && isElementPatch(item.set) && optional((unset) => Array.isArray(unset) && unset.every(isString))(item.unset)))(c.update) && optionalIdList(c.delete) && optionalIdList(c.order),
6657
+ EDIT_TEXT: (c) => isId(c.id) && isString(c.content),
6658
+ SET_SHAPE_LABEL: (c) => isId(c.id) && isString(c.label) && optionalNumber(c.labelFontSize) && optionalString(c.labelFontFamily),
6659
+ SET_FONT_FAMILY: (c) => isString(c.family) && optionalIdList(c.ids),
6660
+ SET_FONT_SIZE: (c) => isNumber(c.size) && optionalIdList(c.ids) && optional((bounds) => isListOf(bounds, (box) => isId(box.id) && isNumber(box.width) && isNumber(box.height)))(c.bounds) && optionalNumber(c.width) && optionalNumber(c.height),
6661
+ SET_ROTATION: (c) => isId(c.id) && isNumber(c.rotation),
6662
+ SET_STROKE_STYLE: (c) => STROKE_STYLES.has(c.style),
6663
+ REORDER_ELEMENTS: (c) => isIdList(c.ids) && isNumber(c.targetIndex),
6664
+ TOGGLE_ELEMENT_VISIBILITY: (c) => isId(c.id),
6665
+ RENAME_LAYER: (c) => isId(c.id) && isString(c.name),
6666
+ LOAD_SCENE: (c) => isElementList(c.elements) && validateViewport(c.viewport) !== null,
6667
+ GROUP_ELEMENTS: (c) => isIdList(c.ids) && isId(c.groupId),
6668
+ UNGROUP_ELEMENTS: (c) => isId(c.groupId),
6669
+ LOCK_ELEMENTS: (c) => isIdList(c.ids),
6670
+ UNLOCK_ELEMENTS: (c) => isIdList(c.ids),
6671
+ SET_TEXT_MODE: (c) => TEXT_MODES.has(c.mode) && optionalIdList(c.ids),
6672
+ ALIGN_ELEMENTS: (c) => isListOf(c.moves, (move) => isId(move.id) && isNumber(move.x) && isNumber(move.y)),
6673
+ APPLY_STYLE: (c) => optionalIdList(c.ids) && STYLE_STRINGS.every((key) => optionalString(c[key])) && STYLE_NUMBERS.every((key) => optionalNumber(c[key])) && STYLE_BOOLEANS.every((key) => optionalBoolean(c[key]))
6674
+ };
6675
+ new Set(Object.keys(CHECKS));
6676
+ /**
6677
+ * Whether `value` is a command a live room may relay and a client may apply:
6678
+ * a relayed type with the fields the reducer needs. Ephemeral commands and
6679
+ * unknown types are refused.
6680
+ */
6681
+ function isValidSessionCommand(value) {
6682
+ if (!isRecord(value) || typeof value.type !== "string") return false;
6683
+ if (!Object.hasOwn(CHECKS, value.type)) return false;
6684
+ return CHECKS[value.type](value);
6685
+ }
6686
+ //#endregion
6687
+ //#region ../src/io/live_outbox.ts
6688
+ var LiveOutbox = class {
6689
+ send;
6690
+ intervalMs;
6691
+ maxPerWindow;
6692
+ windowMs;
6693
+ queue = [];
6694
+ timer = null;
6695
+ /** Send times in the current window, oldest first. */
6696
+ sent = [];
6697
+ constructor(options) {
6698
+ this.send = options.send;
6699
+ this.intervalMs = options.intervalMs ?? 50;
6700
+ this.maxPerWindow = options.maxPerWindow ?? 150;
6701
+ this.windowMs = options.windowMs ?? 5e3;
6702
+ }
6703
+ /** True while commands are waiting to be sent. */
6704
+ get pending() {
6705
+ return this.queue.length > 0;
6706
+ }
6707
+ push(command) {
6708
+ const last = this.queue.at(-1);
6709
+ const merged = last ? mergeCommands(last, command) : null;
6710
+ if (merged) this.queue[this.queue.length - 1] = merged;
6711
+ else this.queue.push(command);
6712
+ if (this.timer === null) this.flush();
6713
+ }
6714
+ /** Sends what the quota allows now, and schedules the rest. */
6715
+ flush() {
6716
+ if (this.timer !== null) {
6717
+ clearTimeout(this.timer);
6718
+ this.timer = null;
6719
+ }
6720
+ const now = Date.now();
6721
+ this.sent = this.sent.filter((time) => now - time < this.windowMs);
6722
+ while (this.queue.length > 0 && this.sent.length < this.maxPerWindow) {
6723
+ const command = this.queue.shift();
6724
+ this.sent.push(now);
6725
+ this.send(command);
6726
+ }
6727
+ const wait = this.queue.length > 0 && this.sent.length >= this.maxPerWindow ? Math.max(this.intervalMs, (this.sent[0] ?? now) + this.windowMs - now) : this.intervalMs;
6728
+ this.timer = setTimeout(() => {
6729
+ this.timer = null;
6730
+ if (this.queue.length > 0) this.flush();
6731
+ }, wait);
6732
+ }
6733
+ /**
6734
+ * Sends what is waiting before a voluntary leave, where nothing is sent
6735
+ * later: as much as the quota allows now, and the rest is dropped. The
6736
+ * queue is merged, so after a gesture it is short; without this, an edit
6737
+ * made just before leaving (an undo, say) never reached the peers.
6738
+ */
6739
+ drain() {
6740
+ this.flush();
6741
+ this.clear();
6742
+ }
6743
+ /** Drops what is waiting, e.g. when the connection is gone. */
6744
+ clear() {
6745
+ if (this.timer !== null) clearTimeout(this.timer);
6746
+ this.timer = null;
6747
+ this.queue = [];
6748
+ }
6749
+ };
6750
+ var sameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
6751
+ /**
6752
+ * `next` folded into `last`, or null when they cannot be merged. A merged
6753
+ * command gives the same scene as the two applied in order (moves add up:
6754
+ * the peers may differ from the sender in the last bits of a coordinate).
6755
+ */
6756
+ function mergeCommands(last, next) {
6757
+ if (last.type === "MOVE_ELEMENTS" && next.type === "MOVE_ELEMENTS") {
6758
+ if (!sameIds(last.ids, next.ids)) return null;
6759
+ return {
6760
+ ...last,
6761
+ dx: last.dx + next.dx,
6762
+ dy: last.dy + next.dy
6763
+ };
6764
+ }
6765
+ if (last.type === "MOVE_ELEMENT" && next.type === "MOVE_ELEMENT") {
6766
+ if (last.id !== next.id) return null;
6767
+ return {
6768
+ ...last,
6769
+ dx: last.dx + next.dx,
6770
+ dy: last.dy + next.dy
6771
+ };
6772
+ }
6773
+ if (last.type === "RESIZE_ELEMENT" && next.type === "RESIZE_ELEMENT") {
6774
+ if (last.id !== next.id) return null;
6775
+ return {
6776
+ ...last,
6777
+ ...next
6778
+ };
6779
+ }
6780
+ if (last.type === "SET_ROTATION" && next.type === "SET_ROTATION") return last.id === next.id ? next : null;
6781
+ return null;
6782
+ }
6783
+ /** Elements per CREATE_ELEMENTS, well under the validation limit (5,000). */
6784
+ var PIECE_ELEMENTS = 1e3;
6785
+ /** Size of one CREATE_ELEMENTS, under the room's message limit (512 KB). */
6786
+ var PIECE_CHARS = 4e5;
6787
+ /**
6788
+ * Elements as CREATE_ELEMENTS commands a room accepts: each one within the
6789
+ * room's message and validation limits. Used to publish a board to a room
6790
+ * (the app's and the agent's seed) and by the room to compact its log.
6791
+ *
6792
+ * With `validOnly`, elements the room would refuse are left out first: one
6793
+ * of them would make the room refuse its whole piece. An element too large
6794
+ * for any message goes alone in its piece, which the room then refuses.
6795
+ */
6796
+ function createCommands(elements, { validOnly = false } = {}) {
6797
+ const commands = [];
6798
+ let piece = [];
6799
+ let pieceChars = 0;
6800
+ const flush = () => {
6801
+ if (piece.length === 0) return;
6802
+ commands.push({
6803
+ type: "CREATE_ELEMENTS",
6804
+ elements: piece
6805
+ });
6806
+ piece = [];
6807
+ pieceChars = 0;
6808
+ };
6809
+ for (const element of elements) {
6810
+ if (validOnly && !isValidElement(element)) continue;
6811
+ const chars = JSON.stringify(element).length;
6812
+ if (piece.length >= PIECE_ELEMENTS || piece.length > 0 && pieceChars + chars > PIECE_CHARS) flush();
6813
+ piece.push(element);
6814
+ pieceChars += chars;
6815
+ }
6816
+ flush();
6817
+ return commands;
6818
+ }
6819
+ //#endregion
6330
6820
  //#region src/storage.ts
6331
6821
  /** Markasso instance used for share links and live rooms. */
6332
6822
  function markassoBaseUrl() {
@@ -6433,6 +6923,23 @@ var LICENCE_MESSAGE = "Drawing live with an AI agent needs a Markasso Cloud lice
6433
6923
  var LiveError = class extends Error {
6434
6924
  name = "LiveError";
6435
6925
  };
6926
+ /**
6927
+ * Whether a live link points at the Markasso instance this server is set up
6928
+ * for (`MARKASSO_URL`, default markasso.it). The licence key is a paid
6929
+ * credential and the link is untrusted input (it can come from a document, a
6930
+ * label or a live request), so the key is only ever sent to that instance.
6931
+ */
6932
+ function isConfiguredInstance(origin) {
6933
+ try {
6934
+ return new URL(origin).origin === new URL(markassoBaseUrl()).origin;
6935
+ } catch {
6936
+ return false;
6937
+ }
6938
+ }
6939
+ function licenceMessage(origin) {
6940
+ if (process.env.MARKASSO_LICENSE?.trim() && !isConfiguredInstance(origin)) return `This room needs a Markasso Cloud licence, and the key in MARKASSO_LICENSE was not sent because the link points to ${origin}, not to ${markassoBaseUrl()}. If that is your own Markasso instance, set MARKASSO_URL to it in this MCP server's environment.`;
6941
+ return LICENCE_MESSAGE;
6942
+ }
6436
6943
  /** Room id and app origin from a live link (`...?live=<room>`) or a bare id. */
6437
6944
  function parseLiveLink(link) {
6438
6945
  const trimmed = link.trim();
@@ -6561,6 +7068,11 @@ var LiveLink = class LiveLink {
6561
7068
  if (this.inbox.length > MAX_INBOX) this.inbox.shift();
6562
7069
  this.wakeWaiters();
6563
7070
  }
7071
+ /** Scene commands, paced to the room's quota (see LiveOutbox). */
7072
+ outbox = new LiveOutbox({ send: (command) => this.send({
7073
+ type: "command",
7074
+ command
7075
+ }) });
6564
7076
  send(message) {
6565
7077
  if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(message));
6566
7078
  }
@@ -6576,7 +7088,7 @@ var LiveLink = class LiveLink {
6576
7088
  }, JOIN_TIMEOUT_MS);
6577
7089
  socket.addEventListener("open", () => {
6578
7090
  const license = process.env.MARKASSO_LICENSE?.trim();
6579
- if (license) this.send({
7091
+ if (license && isConfiguredInstance(origin)) this.send({
6580
7092
  type: "auth",
6581
7093
  license
6582
7094
  });
@@ -6602,22 +7114,13 @@ var LiveLink = class LiveLink {
6602
7114
  let discarded = 0;
6603
7115
  if (msg.commands.length > 0) {
6604
7116
  discarded = local.length;
6605
- history.resetForLiveReplay(msg.commands);
7117
+ history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
6606
7118
  } else if (local.length > 0) {
6607
- this.send({
6608
- type: "command",
6609
- command: {
6610
- type: "CREATE_ELEMENTS",
6611
- elements: local
6612
- }
6613
- });
7119
+ for (const command of createCommands(local, { validOnly: true })) this.outbox.push(command);
6614
7120
  seeded = true;
6615
7121
  }
6616
7122
  history.setOnCommand((command) => {
6617
- if (this.open && isSessionCommand(command)) this.send({
6618
- type: "command",
6619
- command
6620
- });
7123
+ if (this.open && isSessionCommand(command)) this.outbox.push(command);
6621
7124
  });
6622
7125
  this.open = true;
6623
7126
  resolve({
@@ -6625,18 +7128,23 @@ var LiveLink = class LiveLink {
6625
7128
  discarded
6626
7129
  });
6627
7130
  } else if (msg.type === "apply") {
6628
- if (isSessionCommand(msg.command)) history.applyRemote(msg.command);
7131
+ if (isSessionCommand(msg.command) && isValidSessionCommand(msg.command)) try {
7132
+ history.applyRemote(msg.command);
7133
+ } catch (error) {
7134
+ console.error("Skipped a live command that failed to apply", error);
7135
+ }
6629
7136
  } else if (msg.type === "presence") this.peers = msg.peers;
6630
7137
  else if (msg.type === "request") this.receiveRequest(msg);
6631
7138
  else if (msg.type === "error" && !this.open) {
6632
7139
  clearTimeout(timer);
6633
- reject(new LiveError(msg.error === "licence required" ? LICENCE_MESSAGE : `The live room refused to join: ${msg.error}.`));
7140
+ reject(new LiveError(msg.error === "licence required" ? licenceMessage(origin) : `The live room refused to join: ${msg.error}.`));
6634
7141
  }
6635
7142
  });
6636
7143
  socket.addEventListener("close", (event) => {
6637
7144
  clearTimeout(timer);
6638
- if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? LICENCE_MESSAGE : "The live room closed the connection."));
7145
+ if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? licenceMessage(origin) : "The live room closed the connection."));
6639
7146
  this.open = false;
7147
+ this.outbox.clear();
6640
7148
  history.setOnCommand(void 0);
6641
7149
  this.wakeWaiters();
6642
7150
  });
@@ -6659,6 +7167,7 @@ var LiveLink = class LiveLink {
6659
7167
  });
6660
7168
  }
6661
7169
  leave() {
7170
+ this.outbox.drain();
6662
7171
  this.open = false;
6663
7172
  this.wakeWaiters();
6664
7173
  this.diagram.history.setOnCommand(void 0);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@markasso/mcp",
3
- "version": "0.7.0",
3
+ "version": "0.7.2",
4
4
  "description": "MCP server that lets AI agents create, read and edit Markasso diagrams, offline or live on a shared board",
5
5
  "type": "module",
6
6
  "repository": {