@markasso/mcp 0.7.0 → 0.7.3

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.
@@ -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.3";
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",
@@ -4361,7 +4481,6 @@ function createAppState() {
4361
4481
  gridSize: 20,
4362
4482
  gridType: "dot",
4363
4483
  strokeStyle: "solid",
4364
- justCreatedText: false,
4365
4484
  toolLocked: false,
4366
4485
  shapeKind: "terminator",
4367
4486
  lineRouting: "straight",
@@ -4396,13 +4515,9 @@ var EPHEMERAL_COMMANDS = /* @__PURE__ */ new Set([
4396
4515
  "CLEAR_SELECTION",
4397
4516
  "SET_TOOL",
4398
4517
  "SET_STROKE_COLOR",
4399
- "SET_FILL_COLOR",
4400
- "SET_STROKE_WIDTH",
4401
4518
  "TOGGLE_GRID",
4402
4519
  "SET_GRID_TYPE",
4403
- "SET_TOOL_LOCK",
4404
- "CLEAR_JUST_CREATED_TEXT",
4405
- "SET_JUST_CREATED_TEXT"
4520
+ "SET_TOOL_LOCK"
4406
4521
  ]);
4407
4522
  function isEphemeralCommand(type) {
4408
4523
  return EPHEMERAL_COMMANDS.has(type);
@@ -4505,6 +4620,14 @@ function applyPatch(scene, command) {
4505
4620
  } }
4506
4621
  };
4507
4622
  }
4623
+ /**
4624
+ * The elements a selection command acts on: its explicit `ids` (baked in by
4625
+ * History, see withTargets) or, for commands from older clients without
4626
+ * them, the local selection.
4627
+ */
4628
+ function targetIds(scene, ids) {
4629
+ return ids ? new Set(ids) : scene.selectedIds;
4630
+ }
4508
4631
  function reducer(scene, command, isRemote = false) {
4509
4632
  switch (command.type) {
4510
4633
  case "CREATE_ELEMENT": return {
@@ -4557,7 +4680,7 @@ function reducer(scene, command, isRemote = false) {
4557
4680
  ...y !== void 0 && { y },
4558
4681
  ...width !== void 0 && { width },
4559
4682
  ...height !== void 0 && { height },
4560
- ...fontSize !== void 0 && el.type === "text" && { fontSize }
4683
+ ...fontSize !== void 0 && el.type === "text" && { fontSize: Math.min(1e3, Math.max(1, fontSize)) }
4561
4684
  };
4562
4685
  if (el.type === "curve") {
4563
4686
  const patch = {};
@@ -4703,30 +4826,19 @@ function reducer(scene, command, isRemote = false) {
4703
4826
  strokeColor: command.color
4704
4827
  }
4705
4828
  };
4706
- case "SET_FILL_COLOR": return {
4707
- ...scene,
4708
- appState: {
4709
- ...scene.appState,
4710
- fillColor: command.color
4711
- }
4712
- };
4713
- case "SET_STROKE_WIDTH": return {
4714
- ...scene,
4715
- appState: {
4716
- ...scene.appState,
4717
- strokeWidth: command.width
4718
- }
4719
- };
4720
4829
  case "SET_FONT_FAMILY": return {
4721
4830
  ...scene,
4722
4831
  appState: isRemote ? scene.appState : {
4723
4832
  ...scene.appState,
4724
4833
  fontFamily: command.family
4725
4834
  },
4726
- elements: scene.elements.map((el) => scene.selectedIds.has(el.id) && el.type === "text" ? {
4727
- ...el,
4728
- fontFamily: command.family
4729
- } : el)
4835
+ elements: (() => {
4836
+ const targets = targetIds(scene, command.ids);
4837
+ return scene.elements.map((el) => targets.has(el.id) && el.type === "text" ? {
4838
+ ...el,
4839
+ fontFamily: command.family
4840
+ } : el);
4841
+ })()
4730
4842
  };
4731
4843
  case "SET_FONT_SIZE": return {
4732
4844
  ...scene,
@@ -4734,12 +4846,20 @@ function reducer(scene, command, isRemote = false) {
4734
4846
  ...scene.appState,
4735
4847
  fontSize: command.size
4736
4848
  },
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)
4849
+ elements: (() => {
4850
+ const targets = targetIds(scene, command.ids);
4851
+ const measured = new Map((command.bounds ?? []).map((b) => [b.id, b]));
4852
+ return scene.elements.map((el) => {
4853
+ if (!targets.has(el.id) || el.type !== "text") return el;
4854
+ const box = command.bounds ? measured.get(el.id) : command;
4855
+ return {
4856
+ ...el,
4857
+ fontSize: command.size,
4858
+ ...box?.width !== void 0 && { width: box.width },
4859
+ ...box?.height !== void 0 && { height: box.height }
4860
+ };
4861
+ });
4862
+ })()
4743
4863
  };
4744
4864
  case "TOGGLE_GRID": return {
4745
4865
  ...scene,
@@ -4759,19 +4879,12 @@ function reducer(scene, command, isRemote = false) {
4759
4879
  ...scene,
4760
4880
  elements: scene.elements.map((el) => el.id === command.id && !(el.type === "stencil" && !isRotatableStencil(el)) ? {
4761
4881
  ...el,
4762
- rotation: command.rotation
4882
+ rotation: normalizeRotation(command.rotation)
4763
4883
  } : el)
4764
4884
  };
4765
- case "SET_STROKE_STYLE": return {
4766
- ...scene,
4767
- appState: {
4768
- ...scene.appState,
4769
- strokeStyle: command.style
4770
- }
4771
- };
4772
4885
  case "REORDER_ELEMENTS": {
4773
4886
  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);
4887
+ const moving = scene.elements.filter((el) => idSet.has(el.id));
4775
4888
  const rest = scene.elements.filter((el) => !idSet.has(el.id));
4776
4889
  const clampedIdx = Math.max(0, Math.min(command.targetIndex, rest.length));
4777
4890
  const reordered = [
@@ -4784,25 +4897,11 @@ function reducer(scene, command, isRemote = false) {
4784
4897
  elements: reordered
4785
4898
  };
4786
4899
  }
4787
- case "TOGGLE_ELEMENT_VISIBILITY": return {
4788
- ...scene,
4789
- elements: scene.elements.map((el) => el.id === command.id ? {
4790
- ...el,
4791
- visible: el.visible === false
4792
- } : el)
4793
- };
4794
- case "RENAME_LAYER": return {
4795
- ...scene,
4796
- elements: scene.elements.map((el) => el.id === command.id ? {
4797
- ...el,
4798
- layerName: command.name
4799
- } : el)
4800
- };
4801
4900
  case "LOAD_SCENE": return {
4802
4901
  ...scene,
4803
4902
  elements: command.elements,
4804
4903
  selectedIds: /* @__PURE__ */ new Set(),
4805
- viewport: command.viewport
4904
+ viewport: isRemote ? scene.viewport : command.viewport
4806
4905
  };
4807
4906
  case "GROUP_ELEMENTS": {
4808
4907
  const groupSet = new Set(command.ids);
@@ -4842,20 +4941,6 @@ function reducer(scene, command, isRemote = false) {
4842
4941
  } : el)
4843
4942
  };
4844
4943
  }
4845
- case "CLEAR_JUST_CREATED_TEXT": return {
4846
- ...scene,
4847
- appState: {
4848
- ...scene.appState,
4849
- justCreatedText: false
4850
- }
4851
- };
4852
- case "SET_JUST_CREATED_TEXT": return {
4853
- ...scene,
4854
- appState: {
4855
- ...scene.appState,
4856
- justCreatedText: true
4857
- }
4858
- };
4859
4944
  case "SET_TOOL_LOCK": return {
4860
4945
  ...scene,
4861
4946
  appState: {
@@ -4863,17 +4948,20 @@ function reducer(scene, command, isRemote = false) {
4863
4948
  toolLocked: command.locked
4864
4949
  }
4865
4950
  };
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
- };
4951
+ case "SET_TEXT_MODE": {
4952
+ const targets = targetIds(scene, command.ids);
4953
+ return {
4954
+ ...scene,
4955
+ appState: isRemote ? scene.appState : {
4956
+ ...scene.appState,
4957
+ textMode: command.mode
4958
+ },
4959
+ elements: scene.elements.map((el) => targets.has(el.id) && el.type === "text" ? {
4960
+ ...el,
4961
+ isCode: command.mode === "code"
4962
+ } : el)
4963
+ };
4964
+ }
4877
4965
  case "APPLY_STYLE": {
4878
4966
  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
4967
  const patch = {};
@@ -5147,18 +5235,30 @@ function buildRevertPatch(change, current, direction) {
5147
5235
  //#endregion
5148
5236
  //#region ../src/engine/history.ts
5149
5237
  /**
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.
5238
+ * Bakes the target elements into the commands that act on "the selection"
5239
+ * (APPLY_STYLE and the text font and mode commands) when they carry no `ids`.
5240
+ * In a shared session every client then changes the same elements, never
5241
+ * each peer's own selection. APPLY_STYLE without a selection targets the
5242
+ * last-created element.
5154
5243
  */
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
- };
5244
+ function withTargets(scene, command) {
5245
+ switch (command.type) {
5246
+ case "APPLY_STYLE": {
5247
+ if (command.ids !== void 0) return command;
5248
+ const ids = scene.selectedIds.size > 0 ? [...scene.selectedIds] : scene.appState.lastCreatedId ? [scene.appState.lastCreatedId] : [];
5249
+ return {
5250
+ ...command,
5251
+ ids
5252
+ };
5253
+ }
5254
+ case "SET_FONT_FAMILY":
5255
+ case "SET_FONT_SIZE":
5256
+ case "SET_TEXT_MODE": return command.ids !== void 0 ? command : {
5257
+ ...command,
5258
+ ids: [...scene.selectedIds]
5259
+ };
5260
+ default: return command;
5261
+ }
5162
5262
  }
5163
5263
  /**
5164
5264
  * Undo/redo stack plus the single entry point for state changes.
@@ -5195,6 +5295,10 @@ var History = class {
5195
5295
  get present() {
5196
5296
  return this._present;
5197
5297
  }
5298
+ /** True between beginDrag and endDrag (or cancelDrag). */
5299
+ get isDragging() {
5300
+ return this.drag !== null;
5301
+ }
5198
5302
  /** Call at the start of a drag (move/resize/rotate). Every command until
5199
5303
  * endDrag folds into one undo step, so the drag undoes in a single Ctrl+Z. */
5200
5304
  beginDrag() {
@@ -5217,6 +5321,7 @@ var History = class {
5217
5321
  this.drag = null;
5218
5322
  if (!drag.touched) {
5219
5323
  this.future = drag.future;
5324
+ if (drag.future.length > 0) this.notify();
5220
5325
  return;
5221
5326
  }
5222
5327
  rebaseIndices(drag.change, drag.sceneBefore, this._present);
@@ -5225,6 +5330,7 @@ var History = class {
5225
5330
  appStateBefore: drag.appStateBefore,
5226
5331
  appStateAfter: this._present.appState
5227
5332
  });
5333
+ this.notify();
5228
5334
  }
5229
5335
  /** Cancel an in-progress drag and revert what it changed. Edits peers made
5230
5336
  * during the drag are kept, and the revert is broadcast. */
@@ -5253,32 +5359,49 @@ var History = class {
5253
5359
  this._present = next;
5254
5360
  this.notify();
5255
5361
  }
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. */
5362
+ /**
5363
+ * Replaces the board with the room's (used when joining or rejoining a live
5364
+ * room: the room's log is authoritative), then notifies once. Clears undo.
5365
+ *
5366
+ * Only the board is replaced: the tool, the default style and the grid are
5367
+ * this user's own and survive a join or a reconnect. The viewport survives
5368
+ * too unless `keepViewport` is false.
5369
+ */
5258
5370
  resetForLiveReplay(commands, keepViewport = true) {
5259
5371
  if (this.readOnly) return;
5260
- const viewport = this._present.viewport;
5372
+ const { viewport, appState } = this._present;
5261
5373
  this.past = [];
5262
5374
  this.future = [];
5263
5375
  this.drag = null;
5264
- this._present = createScene();
5265
- if (keepViewport) this._present = {
5266
- ...this._present,
5267
- viewport
5376
+ const fresh = createScene();
5377
+ let scene = {
5378
+ ...fresh,
5379
+ appState: {
5380
+ ...appState,
5381
+ lastCreatedId: null
5382
+ },
5383
+ viewport: keepViewport ? viewport : fresh.viewport
5268
5384
  };
5269
- for (const command of commands) this.applyRemote(command);
5385
+ for (const command of commands) try {
5386
+ scene = reducer(scene, command, true);
5387
+ } catch (error) {
5388
+ console.error("Skipped a live command that failed to apply", error);
5389
+ }
5390
+ this._present = scene;
5391
+ this.notify();
5270
5392
  }
5271
5393
  dispatch(command) {
5272
- if (this.readOnly && (!isEphemeralCommand(command.type) || command.type === "SET_JUST_CREATED_TEXT")) return;
5273
- const resolved = withApplyStyleTargets(this._present, command);
5394
+ if (this.readOnly && !isEphemeralCommand(command.type)) return;
5395
+ const resolved = withTargets(this._present, command);
5274
5396
  const next = reducer(this._present, resolved);
5275
5397
  if (next === this._present) return;
5276
5398
  if (!isEphemeralCommand(resolved.type)) {
5277
5399
  const step = diffScenes(this._present, next);
5400
+ const undoable = isUndoableChange(step, this._present, next);
5278
5401
  if (this.drag) {
5279
5402
  composeChange(this.drag.change, step);
5280
- this.drag.touched = true;
5281
- } else {
5403
+ if (undoable) this.drag.touched = true;
5404
+ } else if (undoable) {
5282
5405
  this.past.push({
5283
5406
  change: step,
5284
5407
  appStateBefore: this._present.appState,
@@ -5339,28 +5462,64 @@ var History = class {
5339
5462
  }
5340
5463
  };
5341
5464
  /**
5465
+ * appState fields undo and redo leave as they are now: the tool and the
5466
+ * default style, which the tool switch and the style panel also set without
5467
+ * an undo step (SET_TOOL inherits the selection's style and sets the shape
5468
+ * kind), and view settings. Restoring them would undo choices the user made
5469
+ * after the step. The text defaults (font size and family, alignment, mode)
5470
+ * and the line routing are restored.
5471
+ */
5472
+ var KEPT_ON_UNDO = [
5473
+ "activeTool",
5474
+ "strokeColor",
5475
+ "fillColor",
5476
+ "strokeWidth",
5477
+ "opacity",
5478
+ "roughness",
5479
+ "strokeStyle",
5480
+ "shapeKind",
5481
+ "gridVisible",
5482
+ "gridType",
5483
+ "toolLocked"
5484
+ ];
5485
+ var KEPT_ON_UNDO_SET = /* @__PURE__ */ new Set([...KEPT_ON_UNDO, "lastCreatedId"]);
5486
+ /**
5487
+ * Whether a change is worth an undo step: it touches elements or their order,
5488
+ * or an appState field that undo restores. An element change the diff leaves
5489
+ * out (a type-only change: the type is identity there) still counts, so the
5490
+ * board is never changed without a step.
5491
+ */
5492
+ function isUndoableChange(change, prev, next) {
5493
+ if (change.elements.size > 0 || change.order) return true;
5494
+ if (!sameElements(prev.elements, next.elements)) return true;
5495
+ const before = prev.appState;
5496
+ const after = next.appState;
5497
+ return Object.keys(after).some((key) => !KEPT_ON_UNDO_SET.has(key) && after[key] !== before[key]);
5498
+ }
5499
+ /** Same elements in the same order, by value (unchanged ones keep identity). */
5500
+ function sameElements(a, b) {
5501
+ if (a === b) return true;
5502
+ if (a.length !== b.length) return false;
5503
+ return a.every((el, i) => el === b[i] || deepEqual(el, b[i]));
5504
+ }
5505
+ /**
5342
5506
  * 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.
5507
+ * default a command changed), keeping the fields in KEPT_ON_UNDO as they are
5508
+ * now. The selection stays as-is unless `selectedIds` is given (cancelled
5509
+ * drag); either way it is limited to elements that still exist.
5346
5510
  */
5347
5511
  function restoreLocalState(scene, appState, selectedIds = scene.selectedIds) {
5348
5512
  const elementIds = new Set(scene.elements.map((element) => element.id));
5349
5513
  const current = scene.appState;
5514
+ const kept = {};
5515
+ for (const key of KEPT_ON_UNDO) kept[key] = current[key];
5350
5516
  const currentLastCreatedId = current.lastCreatedId;
5351
5517
  return {
5352
5518
  ...scene,
5353
5519
  selectedIds: new Set([...selectedIds].filter((id) => elementIds.has(id))),
5354
5520
  appState: {
5355
5521
  ...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,
5522
+ ...kept,
5364
5523
  lastCreatedId: currentLastCreatedId && elementIds.has(currentLastCreatedId) ? currentLastCreatedId : null
5365
5524
  }
5366
5525
  };
@@ -5410,7 +5569,7 @@ var ARROW_HEADS = /* @__PURE__ */ new Set([
5410
5569
  var SHAPE_KIND_SET = new Set(SHAPE_KINDS);
5411
5570
  var ROUTINGS = new Set(CONNECTOR_ROUTINGS);
5412
5571
  var HEAD_STYLES = new Set(ARROW_HEAD_STYLES);
5413
- function isRecord(value) {
5572
+ function isRecord$1(value) {
5414
5573
  return typeof value === "object" && value !== null;
5415
5574
  }
5416
5575
  function isFiniteNumber(value) {
@@ -5419,11 +5578,11 @@ function isFiniteNumber(value) {
5419
5578
  function isFiniteNumberInRange(value, min, max) {
5420
5579
  return isFiniteNumber(value) && value >= min && value <= max;
5421
5580
  }
5422
- function isString(value, maxLength = 1e4) {
5581
+ function isString$1(value, maxLength = 1e4) {
5423
5582
  return typeof value === "string" && value.length <= maxLength;
5424
5583
  }
5425
5584
  function isOptionalString(value, maxLength = 1e4) {
5426
- return value === void 0 || isString(value, maxLength);
5585
+ return value === void 0 || isString$1(value, maxLength);
5427
5586
  }
5428
5587
  function isOptionalBoolean(value) {
5429
5588
  return value === void 0 || typeof value === "boolean";
@@ -5435,7 +5594,7 @@ function isOptionalEnum(value, values) {
5435
5594
  return value === void 0 || typeof value === "string" && values.has(value);
5436
5595
  }
5437
5596
  function isCssColor(value) {
5438
- if (!isString(value, 128)) return false;
5597
+ if (!isString$1(value, 128)) return false;
5439
5598
  if (value === "transparent" || value === "none") return true;
5440
5599
  if (/^#[\da-f]{3,8}$/i.test(value)) return true;
5441
5600
  if (/^[a-z]+$/i.test(value)) return true;
@@ -5444,11 +5603,11 @@ function isCssColor(value) {
5444
5603
  function isOptionalCssColor(value) {
5445
5604
  return value === void 0 || isCssColor(value);
5446
5605
  }
5447
- function isPoint(value) {
5606
+ function isPoint$1(value) {
5448
5607
  return Array.isArray(value) && value.length === 2 && isFiniteNumberInRange(value[0], -1e7, 1e7) && isFiniteNumberInRange(value[1], -1e7, 1e7);
5449
5608
  }
5450
5609
  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);
5610
+ 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) && 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
5611
  }
5453
5612
  function hasBoxFields(el) {
5454
5613
  return isFiniteNumberInRange(el.width, -1e7, 1e7) && isFiniteNumberInRange(el.height, -1e7, 1e7);
@@ -5457,40 +5616,40 @@ function hasShapeLabelFields(el) {
5457
5616
  return isOptionalString(el.label) && isOptionalFiniteNumber(el.labelFontSize, 1, 1e3) && isOptionalString(el.labelFontFamily, 256) && isOptionalCssColor(el.labelColor);
5458
5617
  }
5459
5618
  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);
5619
+ if (!isRecord$1(value)) return false;
5620
+ if (value.kind === "builtin") return isString$1(value.ref, 128) && isValidStencilRef(value.ref);
5621
+ if (value.kind === "embedded") return isString$1(value.src, 65536) && isValidEmbeddedSvg(value.src) && isString$1(value.pack, 128) && isString$1(value.name, 256);
5463
5622
  return false;
5464
5623
  }
5465
5624
  function hasEndpointFields(el) {
5466
5625
  return isFiniteNumberInRange(el.x2, -1e7, 1e7) && isFiniteNumberInRange(el.y2, -1e7, 1e7);
5467
5626
  }
5468
5627
  function isOptionalAnchor(value) {
5469
- return value === void 0 || isRecord(value) && isFiniteNumberInRange(value.x, 0, 1) && isFiniteNumberInRange(value.y, 0, 1);
5628
+ return value === void 0 || isRecord$1(value) && isFiniteNumberInRange(value.x, 0, 1) && isFiniteNumberInRange(value.y, 0, 1);
5470
5629
  }
5471
5630
  function hasConnectorFields(el) {
5472
5631
  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
5632
  }
5474
5633
  function hasPointFields(el) {
5475
- return Array.isArray(el.points) && el.points.length >= 2 && el.points.length <= 1e5 && el.points.every(isPoint);
5634
+ return Array.isArray(el.points) && el.points.length >= 2 && el.points.length <= 1e5 && el.points.every(isPoint$1);
5476
5635
  }
5477
5636
  function isImageSource(value) {
5478
- return isString(value, 1e7) && /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);base64,/i.test(value);
5637
+ return isString$1(value, 1e7) && /^data:image\/(?:png|jpe?g|gif|webp|svg\+xml);base64,/i.test(value);
5479
5638
  }
5480
5639
  function isValidElement(value) {
5481
- if (!isRecord(value) || !hasValidBaseFields(value)) return false;
5640
+ if (!isRecord$1(value) || !hasValidBaseFields(value)) return false;
5482
5641
  switch (value.type) {
5483
5642
  case "rectangle":
5484
5643
  case "ellipse":
5485
5644
  case "rhombus": return hasBoxFields(value) && hasShapeLabelFields(value) && isOptionalFiniteNumber(value.cornerRadius, 0, 1e3);
5486
5645
  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);
5646
+ 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
5647
  case "line": return hasEndpointFields(value) && hasConnectorFields(value) && isOptionalFiniteNumber(value.cx) && isOptionalFiniteNumber(value.cy) && isOptionalEnum(value.arrowHead, ARROW_HEADS) && isOptionalEnum(value.startHeadStyle, HEAD_STYLES);
5489
5648
  case "arrow": return hasEndpointFields(value) && hasConnectorFields(value);
5490
5649
  case "curve": return hasEndpointFields(value) && isFiniteNumberInRange(value.cx, -1e7, 1e7) && isFiniteNumberInRange(value.cy, -1e7, 1e7);
5491
5650
  case "polygon": return hasPointFields(value) && typeof value.closed === "boolean";
5492
5651
  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);
5652
+ 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
5653
  case "image": return hasBoxFields(value) && isImageSource(value.src) && isFiniteNumberInRange(value.naturalWidth, 1, 1e5) && isFiniteNumberInRange(value.naturalHeight, 1, 1e5);
5495
5654
  }
5496
5655
  return false;
@@ -5517,6 +5676,15 @@ function validateElements(value) {
5517
5676
  }
5518
5677
  return valid.length > 0 ? valid : null;
5519
5678
  }
5679
+ function validateViewport(value) {
5680
+ if (!isRecord$1(value)) return null;
5681
+ if (!isFiniteNumberInRange(value.offsetX, -1e7, 1e7) || !isFiniteNumberInRange(value.offsetY, -1e7, 1e7) || !isFiniteNumberInRange(value.zoom, .05, 30)) return null;
5682
+ return {
5683
+ offsetX: value.offsetX,
5684
+ offsetY: value.offsetY,
5685
+ zoom: value.zoom
5686
+ };
5687
+ }
5520
5688
  //#endregion
5521
5689
  //#region src/sizing.ts
5522
5690
  /**
@@ -6327,6 +6495,273 @@ function describeDiagram(diagram) {
6327
6495
  return lines.join("\n");
6328
6496
  }
6329
6497
  //#endregion
6498
+ //#region ../src/io/command_validation.ts
6499
+ function isRecord(value) {
6500
+ return typeof value === "object" && value !== null && !Array.isArray(value);
6501
+ }
6502
+ function isId(value) {
6503
+ return typeof value === "string" && value.length > 0 && value.length <= 128;
6504
+ }
6505
+ function isIdList(value) {
6506
+ return Array.isArray(value) && value.length <= 5e3 && value.every(isId);
6507
+ }
6508
+ function isNumber(value) {
6509
+ return typeof value === "number" && Number.isFinite(value);
6510
+ }
6511
+ var optional = (check) => (value) => value === void 0 || check(value);
6512
+ var isString = (value) => typeof value === "string";
6513
+ var isBoolean = (value) => typeof value === "boolean";
6514
+ var optionalNumber = optional(isNumber);
6515
+ var optionalString = optional(isString);
6516
+ var optionalBoolean = optional(isBoolean);
6517
+ var optionalIdList = optional(isIdList);
6518
+ function isPoint(value) {
6519
+ return Array.isArray(value) && value.length === 2 && isNumber(value[0]) && isNumber(value[1]);
6520
+ }
6521
+ /** A connector end: an element id to attach to, or null to detach. */
6522
+ var isEndTarget = optional((value) => value === null || isId(value));
6523
+ /** A pinned connector end, or null to let it float along the border. */
6524
+ var isAnchor = optional((value) => value === null || isRecord(value) && isNumber(value.x) && isNumber(value.y));
6525
+ /**
6526
+ * A partial element, as UPDATE_ELEMENT and PATCH_ELEMENTS carry it. An
6527
+ * element never changes identity or type after creation, and the two fields
6528
+ * that hold content from outside the app keep the rules of a whole element:
6529
+ * an image source stays an inline image, a stencil source a known one.
6530
+ */
6531
+ function isElementPatch(value) {
6532
+ if (!isRecord(value)) return false;
6533
+ if ("id" in value || "type" in value) return false;
6534
+ if ("src" in value && !isImageSource(value.src)) return false;
6535
+ if ("source" in value && !isValidStencilSource(value.source)) return false;
6536
+ return true;
6537
+ }
6538
+ function isElementList(value) {
6539
+ return Array.isArray(value) && value.length <= 5e3 && value.every(isValidElement);
6540
+ }
6541
+ function isListOf(value, check) {
6542
+ return Array.isArray(value) && value.length <= 5e3 && value.every((item) => isRecord(item) && check(item));
6543
+ }
6544
+ var TEXT_MODES = /* @__PURE__ */ new Set(["text", "code"]);
6545
+ var STYLE_STRINGS = [
6546
+ "strokeColor",
6547
+ "fillColor",
6548
+ "labelColor",
6549
+ "strokeStyle",
6550
+ "lineCap",
6551
+ "lineJoin",
6552
+ "shadowColor",
6553
+ "textAlign",
6554
+ "arrowHead",
6555
+ "shapeKind",
6556
+ "routing",
6557
+ "startHeadStyle",
6558
+ "endHeadStyle"
6559
+ ];
6560
+ var STYLE_NUMBERS = [
6561
+ "strokeWidth",
6562
+ "opacity",
6563
+ "roughness",
6564
+ "shadowBlur",
6565
+ "shadowOffsetX",
6566
+ "shadowOffsetY",
6567
+ "cornerRadius"
6568
+ ];
6569
+ var STYLE_BOOLEANS = [
6570
+ "bold",
6571
+ "italic",
6572
+ "underline",
6573
+ "strikethrough"
6574
+ ];
6575
+ var RESIZE_NUMBERS = [
6576
+ "x",
6577
+ "y",
6578
+ "width",
6579
+ "height",
6580
+ "x2",
6581
+ "y2",
6582
+ "cx",
6583
+ "cy",
6584
+ "fontSize"
6585
+ ];
6586
+ /** One check per relayed command type; a type missing here is refused. */
6587
+ var CHECKS = {
6588
+ CREATE_ELEMENT: (c) => isValidElement(c.element) && optionalBoolean(c.select),
6589
+ CREATE_ELEMENTS: (c) => isElementList(c.elements),
6590
+ UPDATE_ELEMENT: (c) => isId(c.id) && isElementPatch(c.props),
6591
+ MOVE_ELEMENT: (c) => isId(c.id) && isNumber(c.dx) && isNumber(c.dy),
6592
+ MOVE_ELEMENTS: (c) => isIdList(c.ids) && isNumber(c.dx) && isNumber(c.dy),
6593
+ 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),
6594
+ DELETE_ELEMENTS: (c) => isIdList(c.ids),
6595
+ 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),
6596
+ EDIT_TEXT: (c) => isId(c.id) && isString(c.content),
6597
+ SET_SHAPE_LABEL: (c) => isId(c.id) && isString(c.label) && optionalNumber(c.labelFontSize) && optionalString(c.labelFontFamily),
6598
+ SET_FONT_FAMILY: (c) => isString(c.family) && optionalIdList(c.ids),
6599
+ 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),
6600
+ SET_ROTATION: (c) => isId(c.id) && isNumber(c.rotation),
6601
+ REORDER_ELEMENTS: (c) => isIdList(c.ids) && isNumber(c.targetIndex),
6602
+ LOAD_SCENE: (c) => isElementList(c.elements) && validateViewport(c.viewport) !== null,
6603
+ GROUP_ELEMENTS: (c) => isIdList(c.ids) && isId(c.groupId),
6604
+ UNGROUP_ELEMENTS: (c) => isId(c.groupId),
6605
+ LOCK_ELEMENTS: (c) => isIdList(c.ids),
6606
+ UNLOCK_ELEMENTS: (c) => isIdList(c.ids),
6607
+ SET_TEXT_MODE: (c) => TEXT_MODES.has(c.mode) && optionalIdList(c.ids),
6608
+ ALIGN_ELEMENTS: (c) => isListOf(c.moves, (move) => isId(move.id) && isNumber(move.x) && isNumber(move.y)),
6609
+ 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]))
6610
+ };
6611
+ new Set(Object.keys(CHECKS));
6612
+ /**
6613
+ * Whether `value` is a command a live room may relay and a client may apply:
6614
+ * a relayed type with the fields the reducer needs. Ephemeral commands and
6615
+ * unknown types are refused.
6616
+ */
6617
+ function isValidSessionCommand(value) {
6618
+ if (!isRecord(value) || typeof value.type !== "string") return false;
6619
+ if (!Object.hasOwn(CHECKS, value.type)) return false;
6620
+ return CHECKS[value.type](value);
6621
+ }
6622
+ //#endregion
6623
+ //#region ../src/io/live_outbox.ts
6624
+ var LiveOutbox = class {
6625
+ send;
6626
+ intervalMs;
6627
+ maxPerWindow;
6628
+ windowMs;
6629
+ queue = [];
6630
+ timer = null;
6631
+ /** Send times in the current window, oldest first. */
6632
+ sent = [];
6633
+ constructor(options) {
6634
+ this.send = options.send;
6635
+ this.intervalMs = options.intervalMs ?? 50;
6636
+ this.maxPerWindow = options.maxPerWindow ?? 150;
6637
+ this.windowMs = options.windowMs ?? 5e3;
6638
+ }
6639
+ /** True while commands are waiting to be sent. */
6640
+ get pending() {
6641
+ return this.queue.length > 0;
6642
+ }
6643
+ push(command) {
6644
+ const last = this.queue.at(-1);
6645
+ const merged = last ? mergeCommands(last, command) : null;
6646
+ if (merged) this.queue[this.queue.length - 1] = merged;
6647
+ else this.queue.push(command);
6648
+ if (this.timer === null) this.flush();
6649
+ }
6650
+ /** Sends what the quota allows now, and schedules the rest. */
6651
+ flush() {
6652
+ if (this.timer !== null) {
6653
+ clearTimeout(this.timer);
6654
+ this.timer = null;
6655
+ }
6656
+ const now = Date.now();
6657
+ this.sent = this.sent.filter((time) => now - time < this.windowMs);
6658
+ while (this.queue.length > 0 && this.sent.length < this.maxPerWindow) {
6659
+ const command = this.queue.shift();
6660
+ this.sent.push(now);
6661
+ this.send(command);
6662
+ }
6663
+ const wait = this.queue.length > 0 && this.sent.length >= this.maxPerWindow ? Math.max(this.intervalMs, (this.sent[0] ?? now) + this.windowMs - now) : this.intervalMs;
6664
+ this.timer = setTimeout(() => {
6665
+ this.timer = null;
6666
+ if (this.queue.length > 0) this.flush();
6667
+ }, wait);
6668
+ }
6669
+ /**
6670
+ * Sends what is waiting before a voluntary leave, where nothing is sent
6671
+ * later: as much as the quota allows now, and the rest is dropped. The
6672
+ * queue is merged, so after a gesture it is short; without this, an edit
6673
+ * made just before leaving (an undo, say) never reached the peers.
6674
+ */
6675
+ drain() {
6676
+ this.flush();
6677
+ this.clear();
6678
+ }
6679
+ /**
6680
+ * Resolves once everything waiting has been sent, or after `timeoutMs`:
6681
+ * for a leave that can wait, so an editing burst held back by the quota
6682
+ * still reaches the room.
6683
+ */
6684
+ async idle(timeoutMs) {
6685
+ const deadline = Date.now() + timeoutMs;
6686
+ while (this.pending && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, this.intervalMs));
6687
+ }
6688
+ /** Drops what is waiting, e.g. when the connection is gone. */
6689
+ clear() {
6690
+ if (this.timer !== null) clearTimeout(this.timer);
6691
+ this.timer = null;
6692
+ this.queue = [];
6693
+ }
6694
+ };
6695
+ var sameIds = (a, b) => a.length === b.length && a.every((id, index) => id === b[index]);
6696
+ /**
6697
+ * `next` folded into `last`, or null when they cannot be merged. A merged
6698
+ * command gives the same scene as the two applied in order (moves add up:
6699
+ * the peers may differ from the sender in the last bits of a coordinate).
6700
+ */
6701
+ function mergeCommands(last, next) {
6702
+ if (last.type === "MOVE_ELEMENTS" && next.type === "MOVE_ELEMENTS") {
6703
+ if (!sameIds(last.ids, next.ids)) return null;
6704
+ return {
6705
+ ...last,
6706
+ dx: last.dx + next.dx,
6707
+ dy: last.dy + next.dy
6708
+ };
6709
+ }
6710
+ if (last.type === "MOVE_ELEMENT" && next.type === "MOVE_ELEMENT") {
6711
+ if (last.id !== next.id) return null;
6712
+ return {
6713
+ ...last,
6714
+ dx: last.dx + next.dx,
6715
+ dy: last.dy + next.dy
6716
+ };
6717
+ }
6718
+ if (last.type === "RESIZE_ELEMENT" && next.type === "RESIZE_ELEMENT") {
6719
+ if (last.id !== next.id) return null;
6720
+ return {
6721
+ ...last,
6722
+ ...next
6723
+ };
6724
+ }
6725
+ if (last.type === "SET_ROTATION" && next.type === "SET_ROTATION") return last.id === next.id ? next : null;
6726
+ return null;
6727
+ }
6728
+ /** Elements per CREATE_ELEMENTS, well under the validation limit (5,000). */
6729
+ var PIECE_ELEMENTS = 1e3;
6730
+ /** Size of one CREATE_ELEMENTS, under the room's message limit (512 KB). */
6731
+ var PIECE_CHARS = 4e5;
6732
+ /**
6733
+ * Elements as CREATE_ELEMENTS commands a room accepts: each one within the
6734
+ * room's message and validation limits. Used to publish a board to a room
6735
+ * (the app's and the agent's seed) and by the room to compact its log.
6736
+ *
6737
+ * With `validOnly`, elements the room would refuse are left out first: one
6738
+ * of them would make the room refuse its whole piece. An element too large
6739
+ * for any message goes alone in its piece, which the room then refuses.
6740
+ */
6741
+ function createCommands(elements, { validOnly = false } = {}) {
6742
+ const commands = [];
6743
+ let piece = [];
6744
+ let pieceChars = 0;
6745
+ const flush = () => {
6746
+ if (piece.length === 0) return;
6747
+ commands.push({
6748
+ type: "CREATE_ELEMENTS",
6749
+ elements: piece
6750
+ });
6751
+ piece = [];
6752
+ pieceChars = 0;
6753
+ };
6754
+ for (const element of elements) {
6755
+ if (validOnly && !isValidElement(element)) continue;
6756
+ const chars = JSON.stringify(element).length;
6757
+ if (piece.length >= PIECE_ELEMENTS || piece.length > 0 && pieceChars + chars > PIECE_CHARS) flush();
6758
+ piece.push(element);
6759
+ pieceChars += chars;
6760
+ }
6761
+ flush();
6762
+ return commands;
6763
+ }
6764
+ //#endregion
6330
6765
  //#region src/storage.ts
6331
6766
  /** Markasso instance used for share links and live rooms. */
6332
6767
  function markassoBaseUrl() {
@@ -6433,6 +6868,23 @@ var LICENCE_MESSAGE = "Drawing live with an AI agent needs a Markasso Cloud lice
6433
6868
  var LiveError = class extends Error {
6434
6869
  name = "LiveError";
6435
6870
  };
6871
+ /**
6872
+ * Whether a live link points at the Markasso instance this server is set up
6873
+ * for (`MARKASSO_URL`, default markasso.it). The licence key is a paid
6874
+ * credential and the link is untrusted input (it can come from a document, a
6875
+ * label or a live request), so the key is only ever sent to that instance.
6876
+ */
6877
+ function isConfiguredInstance(origin) {
6878
+ try {
6879
+ return new URL(origin).origin === new URL(markassoBaseUrl()).origin;
6880
+ } catch {
6881
+ return false;
6882
+ }
6883
+ }
6884
+ function licenceMessage(origin) {
6885
+ 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.`;
6886
+ return LICENCE_MESSAGE;
6887
+ }
6436
6888
  /** Room id and app origin from a live link (`...?live=<room>`) or a bare id. */
6437
6889
  function parseLiveLink(link) {
6438
6890
  const trimmed = link.trim();
@@ -6561,6 +7013,11 @@ var LiveLink = class LiveLink {
6561
7013
  if (this.inbox.length > MAX_INBOX) this.inbox.shift();
6562
7014
  this.wakeWaiters();
6563
7015
  }
7016
+ /** Scene commands, paced to the room's quota (see LiveOutbox). */
7017
+ outbox = new LiveOutbox({ send: (command) => this.send({
7018
+ type: "command",
7019
+ command
7020
+ }) });
6564
7021
  send(message) {
6565
7022
  if (this.socket?.readyState === WebSocket.OPEN) this.socket.send(JSON.stringify(message));
6566
7023
  }
@@ -6576,7 +7033,7 @@ var LiveLink = class LiveLink {
6576
7033
  }, JOIN_TIMEOUT_MS);
6577
7034
  socket.addEventListener("open", () => {
6578
7035
  const license = process.env.MARKASSO_LICENSE?.trim();
6579
- if (license) this.send({
7036
+ if (license && isConfiguredInstance(origin)) this.send({
6580
7037
  type: "auth",
6581
7038
  license
6582
7039
  });
@@ -6602,22 +7059,13 @@ var LiveLink = class LiveLink {
6602
7059
  let discarded = 0;
6603
7060
  if (msg.commands.length > 0) {
6604
7061
  discarded = local.length;
6605
- history.resetForLiveReplay(msg.commands);
7062
+ history.resetForLiveReplay(msg.commands.filter(isValidSessionCommand));
6606
7063
  } else if (local.length > 0) {
6607
- this.send({
6608
- type: "command",
6609
- command: {
6610
- type: "CREATE_ELEMENTS",
6611
- elements: local
6612
- }
6613
- });
7064
+ for (const command of createCommands(local, { validOnly: true })) this.outbox.push(command);
6614
7065
  seeded = true;
6615
7066
  }
6616
7067
  history.setOnCommand((command) => {
6617
- if (this.open && isSessionCommand(command)) this.send({
6618
- type: "command",
6619
- command
6620
- });
7068
+ if (this.open && isSessionCommand(command)) this.outbox.push(command);
6621
7069
  });
6622
7070
  this.open = true;
6623
7071
  resolve({
@@ -6625,18 +7073,23 @@ var LiveLink = class LiveLink {
6625
7073
  discarded
6626
7074
  });
6627
7075
  } else if (msg.type === "apply") {
6628
- if (isSessionCommand(msg.command)) history.applyRemote(msg.command);
7076
+ if (isSessionCommand(msg.command) && isValidSessionCommand(msg.command)) try {
7077
+ history.applyRemote(msg.command);
7078
+ } catch (error) {
7079
+ console.error("Skipped a live command that failed to apply", error);
7080
+ }
6629
7081
  } else if (msg.type === "presence") this.peers = msg.peers;
6630
7082
  else if (msg.type === "request") this.receiveRequest(msg);
6631
7083
  else if (msg.type === "error" && !this.open) {
6632
7084
  clearTimeout(timer);
6633
- reject(new LiveError(msg.error === "licence required" ? LICENCE_MESSAGE : `The live room refused to join: ${msg.error}.`));
7085
+ reject(new LiveError(msg.error === "licence required" ? licenceMessage(origin) : `The live room refused to join: ${msg.error}.`));
6634
7086
  }
6635
7087
  });
6636
7088
  socket.addEventListener("close", (event) => {
6637
7089
  clearTimeout(timer);
6638
- if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? LICENCE_MESSAGE : "The live room closed the connection."));
7090
+ if (!this.open) reject(new LiveError(event.code === CLOSE_LICENCE_REQUIRED ? licenceMessage(origin) : "The live room closed the connection."));
6639
7091
  this.open = false;
7092
+ this.outbox.clear();
6640
7093
  history.setOnCommand(void 0);
6641
7094
  this.wakeWaiters();
6642
7095
  });
@@ -6659,12 +7112,33 @@ var LiveLink = class LiveLink {
6659
7112
  });
6660
7113
  }
6661
7114
  leave() {
7115
+ this.outbox.drain();
6662
7116
  this.open = false;
6663
7117
  this.wakeWaiters();
6664
7118
  this.diagram.history.setOnCommand(void 0);
6665
7119
  this.socket?.close();
6666
7120
  this.socket = null;
6667
7121
  }
7122
+ /**
7123
+ * Leaves once every edit held back by the room's quota is sent, then
7124
+ * waits for the socket to close (at most `timeoutMs`), so the last edits
7125
+ * leave the process before it exits. A lost connection clears the queue,
7126
+ * which ends the wait; the 60 s cap (twelve quota windows, about 1,800
7127
+ * unmerged commands) only bounds a pathological burst.
7128
+ */
7129
+ async leaveAndWait(timeoutMs = 1e3) {
7130
+ await this.outbox.idle(6e4);
7131
+ const socket = this.socket;
7132
+ const closed = socket && socket.readyState !== 3 ? new Promise((resolve) => {
7133
+ const timer = setTimeout(resolve, timeoutMs);
7134
+ socket.addEventListener("close", () => {
7135
+ clearTimeout(timer);
7136
+ resolve();
7137
+ });
7138
+ }) : Promise.resolve();
7139
+ this.leave();
7140
+ await closed;
7141
+ }
6668
7142
  };
6669
7143
  //#endregion
6670
7144
  //#region src/warnings.ts
@@ -7028,8 +7502,34 @@ function formatRequests(requests) {
7028
7502
  ].join("\n");
7029
7503
  }
7030
7504
  /** Runs a tool body and turns thrown errors into MCP tool errors. */
7031
- function guarded(run) {
7505
+ /** Tool calls still running; shutting down waits for them. */
7506
+ var inFlight = 0;
7507
+ var onIdle = [];
7508
+ /** Counts a tool call while it runs (see shutDown). */
7509
+ function tracked(run) {
7032
7510
  return async (args) => {
7511
+ inFlight++;
7512
+ try {
7513
+ return await run(args);
7514
+ } finally {
7515
+ inFlight--;
7516
+ if (inFlight === 0) for (const resolve of onIdle.splice(0)) resolve();
7517
+ }
7518
+ };
7519
+ }
7520
+ /** Resolves when no tool call is running, or after `timeoutMs`. */
7521
+ function callsDone(timeoutMs) {
7522
+ if (inFlight === 0) return Promise.resolve();
7523
+ return new Promise((resolve) => {
7524
+ const timer = setTimeout(resolve, timeoutMs);
7525
+ onIdle.push(() => {
7526
+ clearTimeout(timer);
7527
+ resolve();
7528
+ });
7529
+ });
7530
+ }
7531
+ function guarded(run) {
7532
+ return tracked(async (args) => {
7033
7533
  let result;
7034
7534
  try {
7035
7535
  result = text(await run(args));
@@ -7042,7 +7542,7 @@ function guarded(run) {
7042
7542
  if (first) first.text += `\n${formatRequests(requests)}`;
7043
7543
  }
7044
7544
  return result;
7045
- };
7545
+ });
7046
7546
  }
7047
7547
  function liveSuffix() {
7048
7548
  if (!live) return "";
@@ -7240,13 +7740,13 @@ server.registerTool("diagram_export_png", {
7240
7740
  returnImage: z.boolean().optional().describe("Return the image (default true). false with a path only writes the file and answers in text.")
7241
7741
  },
7242
7742
  annotations: { readOnlyHint: true }
7243
- }, async (args) => {
7743
+ }, tracked(async (args) => {
7244
7744
  try {
7245
7745
  return { content: await exportPng(diagram, args) };
7246
7746
  } catch (error) {
7247
7747
  return failure(error);
7248
7748
  }
7249
- });
7749
+ }));
7250
7750
  server.registerTool("diagram_share", {
7251
7751
  title: "Share link",
7252
7752
  description: "Publish the diagram and return a markasso.it link anyone can open. The answer says when the link expires.",
@@ -7311,5 +7811,26 @@ server.registerTool("live_reply", {
7311
7811
  return "Reply sent.";
7312
7812
  }));
7313
7813
  await server.connect(new StdioServerTransport());
7814
+ /**
7815
+ * The client ends the session by closing stdin; the stdio transport does not
7816
+ * notice, and an open live socket would keep the process running as a ghost
7817
+ * peer in the room. Let running tool calls finish (a file being saved, an
7818
+ * answer being written), leave the room, then exit. Signals end it the same
7819
+ * way.
7820
+ */
7821
+ var shuttingDown = false;
7822
+ async function shutDown() {
7823
+ if (shuttingDown) return;
7824
+ shuttingDown = true;
7825
+ try {
7826
+ await callsDone(1e4);
7827
+ await live?.leaveAndWait();
7828
+ } finally {
7829
+ process.exit(0);
7830
+ }
7831
+ }
7832
+ process.stdin.on("end", () => void shutDown());
7833
+ process.stdin.on("close", () => void shutDown());
7834
+ for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => void shutDown());
7314
7835
  //#endregion
7315
7836
  export {};