diff --git a/.agent/skills/basalt-html/parts/diagram-export.js b/.agent/skills/basalt-html/parts/diagram-export.js
index e2fb6ce..fc495ea 100644
--- a/.agent/skills/basalt-html/parts/diagram-export.js
+++ b/.agent/skills/basalt-html/parts/diagram-export.js
@@ -1 +1 @@
-(()=>{var G="http://www.w3.org/2000/svg",S=t=>t.replace(/[&<>"']/g,i=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[i]),k=t=>!!t&&t!=="transparent"&&!/rgba\([^)]*,\s*0\)$/.test(t)&&!/\/\s*0\)$/.test(t),h=t=>Math.round(t*100)/100;function z(t){const i=l=>t.querySelector(`:scope > [class$="-${l}"], :scope > [class*="-${l} "]`);return["head","drawing","key"].map(i).filter(l=>!!(l&&l.getClientRects().length))}async function U(t){for(const i of Array.from(document.styleSheets)){let l;try{l=i.cssRules}catch{continue}for(const d of Array.from(l)){if(!(d instanceof CSSFontFaceRule)||d.style.getPropertyValue("font-family").replace(/["']/g,"").trim()!==t)continue;const e=/url\(["']?([^"')]+)["']?\)/.exec(d.style.getPropertyValue("src"))?.[1];if(e){if(e.startsWith("data:"))return e;try{const n=await fetch(new URL(e,i.href??location.href));if(!n.ok)return null;const o=await n.blob();return await new Promise((c,s)=>{const a=new FileReader;a.onload=()=>c(String(a.result)),a.onerror=s,a.readAsDataURL(o)})}catch{return null}}}}return null}function j(t,i,l){const d=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(let e=d.nextNode();e;e=d.nextNode()){const n=e.parentElement;if(!n||!e.textContent?.trim()||n.closest("[aria-hidden='true'] .basalt-visually-hidden, .basalt-visually-hidden, .visually-hidden, [class$='-ruler'], [hidden]"))continue;const o=getComputedStyle(n);if(o.visibility==="hidden"||o.display==="none")continue;const c=e.textContent,s=document.createRange();for(const a of c.matchAll(/\S+/g)){s.setStart(e,a.index),s.setEnd(e,a.index+a[0].length);const m=s.getBoundingClientRect();if(!m.width)continue;const f=Number.parseFloat(o.fontSize),b=m.top-i.top+(m.height-f)/2+f*.8;l.push(`${S(a[0])}`)}}}function D(t,i,l){if(/-(lane|band|felse)(\s|$)/.test(` ${t.getAttribute("class")??""}`))for(const d of["::before","::after"]){const e=getComputedStyle(t,d);if(!e.content||e.content==="none"||e.content==="normal"||e.display==="none"||e.position!=="absolute")continue;const n=t.getBoundingClientRect(),o=getComputedStyle(t),c=n.left+(Number.parseFloat(o.borderLeftWidth)||0)+(Number.parseFloat(e.left)||0)-i.left,s=n.top+(Number.parseFloat(o.borderTopWidth)||0)+(Number.parseFloat(e.top)||0)-i.top,a=Number.parseFloat(e.width)||0,m=Number.parseFloat(e.height)||0,f=Number.parseFloat(e.borderTopWidth)||0,b=e.maskImage&&e.maskImage!=="none"?` stroke-dasharray="${Number.parseFloat(e.maskSize)/2||4} ${Number.parseFloat(e.maskSize)/2||4}"`:"";k(e.backgroundColor)&&a&&m?l.push(``):f&&k(e.borderTopColor)&&l.push(``)}}function O(t,i,l){const d=t.getBoundingClientRect();if(!d.width||!d.height||t.getAttribute("class")?.endsWith("-motion-defs"))return;const e=t.cloneNode(!0),n=[t,...Array.from(t.querySelectorAll("*"))],o=[e,...Array.from(e.querySelectorAll("*"))],c=t.viewBox?.baseVal,s=!!(c&&c.width&&(Math.abs(c.width-d.width)>.5||Math.abs(c.height-d.height)>.5));n.forEach((a,m)=>{const f=getComputedStyle(a),b=o[m];for(const v of["fill","stroke","stroke-width","stroke-dasharray","stroke-linecap","stroke-linejoin","opacity"])b.setAttribute(v,f.getPropertyValue(v));b.removeAttribute("class"),/-reveal-/.test(b.getAttribute("mask")??"")&&b.removeAttribute("mask"),s&&m>0&&b.setAttribute("vector-effect","non-scaling-stroke"),f.display==="none"&&b.setAttribute("display","none")}),e.setAttribute("x",String(h(d.left-i.left))),e.setAttribute("y",String(h(d.top-i.top))),e.setAttribute("width",String(h(d.width))),e.setAttribute("height",String(h(d.height))),e.removeAttribute("style"),l.push(e.outerHTML)}function I(t,i,l){const d=[t,...Array.from(t.querySelectorAll("*"))],e=d.filter(n=>n instanceof SVGSVGElement&&n.closest("svg")===n&&!!n.closest("[class$='-ink']"));for(const n of e)O(n,i,l);for(const n of d){if(n instanceof SVGElement){if(n.tagName.toLowerCase()!=="svg"||n.closest("svg")!==n||e.includes(n))continue;O(n,i,l);continue}const o=getComputedStyle(n);if(o.display==="none"||o.visibility==="hidden")continue;const c=n.getBoundingClientRect();if(!c.width||!c.height)continue;const s=h(c.left-i.left),a=h(c.top-i.top),m=h(c.width),f=h(c.height),b=Number.parseFloat(o.borderTopLeftRadius)||0,v=k(o.backgroundColor)?o.backgroundColor:"none",A=[o.borderTopWidth,o.borderRightWidth,o.borderBottomWidth,o.borderLeftWidth].map(r=>Number.parseFloat(r)||0),x=A.every(r=>r===A[0]);if(!x){const[r,u,p,w]=A,$=(T,R,F,E,L,M)=>{T&&k(R)&&l.push(``)};$(r,o.borderTopColor,s,a+r/2,s+m,a+r/2),$(p,o.borderBottomColor,s,a+f-p/2,s+m,a+f-p/2),$(w,o.borderLeftColor,s+w/2,a,s+w/2,a+f),$(u,o.borderRightColor,s+m-u/2,a,s+m-u/2,a+f)}const g=x?A[0]:0,N=o.borderLeftColor,C=g&&o.borderTopStyle!=="none"&&k(N)?N:"none";if(v!=="none"||C!=="none"){const r=o.borderTopStyle==="dashed"?' stroke-dasharray="4 2"':"";l.push(``),C!=="none"&&!r&&o.borderTopColor!==N&&k(o.borderTopColor)&&l.push(``)}D(n,i,l);const B=/url\(["']?([^"')]+)["']?\)/.exec(o.backgroundImage)?.[1];B&&/-mark$/.test(String(n.getAttribute("class")))&&l.push(``)}}var q=t=>t.querySelector("[class$='-title']")?.textContent?.trim()??"",H=t=>t.querySelector("figcaption")?.textContent?.trim()??"",P=(t,i)=>`${q(t).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"diagram"}.${i}`;async function V(t,i,l){const d=i.theme??"page",e=t.getAttribute("data-theme"),n=["data-lit","data-dim","data-near","data-ahead","data-arrival","data-arrival-out"],o=Array.from(t.querySelectorAll(n.map(r=>`[${r}]`).join(", "))),c=o.map(r=>[r,n.map(u=>r.getAttribute(u))]);o.forEach(r=>{for(const u of n)r.removeAttribute(u)});const s=Array.from(t.querySelectorAll("[class*='-flow'], [class*='-bead'], [class*='-packet']"));s.forEach(r=>{r.dataset.exportHidden=r.style.display,r.style.display="none"});const a=t.getAttribute("data-entrance");a&&a!=="done"&&t.setAttribute("data-entrance","done");const m=t.getAnimations({subtree:!0}).map(r=>({a:r,at:r.currentTime,running:r.playState==="running"}));for(const{a:r}of m){const u=r.effect?.getComputedTiming().endTime;r.pause(),typeof u=="number"&&Number.isFinite(u)&&(r.currentTime=u)}const f=t.getAttribute("data-viewer");f!==null&&t.removeAttribute("data-viewer");const b=[];for(let r=t.parentElement;r;r=r.parentElement){const u=getComputedStyle(r).transform,p=/^matrix\(([^,]+),[^,]+,[^,]+,([^,]+),/.exec(u);p&&(Math.abs(Number(p[1])-1)>1e-6||Math.abs(Number(p[2])-1)>1e-6)&&(b.push([r,r.style.transform]),r.style.transform="none")}d!=="page"&&t.setAttribute("data-theme",d),t.classList.add("basalt-exporting");let v;try{t.offsetWidth;const r=Number.parseFloat(getComputedStyle(t).getPropertyValue("--basalt-space-4"))||16,u=z(t),p=u.map(y=>y.getBoundingClientRect()),w=Math.min(...p.map(y=>y.left)),$=Math.min(...p.map(y=>y.top)),T=Math.max(...p.map(y=>y.right)),R=Math.max(...p.map(y=>y.bottom)),F=new DOMRect(w-r,$-r,0,0),E=Math.ceil(T-w+2*r),L=Math.ceil(R-$+2*r),M=getComputedStyle(t).getPropertyValue("--basalt-surface-page").trim()||getComputedStyle(document.body).backgroundColor,W=[];for(const y of u)I(y,F,W);for(const y of u)j(y,F,W);v={body:W,w:E,h:L,ground:M}}finally{t.classList.remove("basalt-exporting"),d!=="page"&&(e===null?t.removeAttribute("data-theme"):t.setAttribute("data-theme",e));for(const[r,u]of b)r.style.transform=u;f!==null&&t.setAttribute("data-viewer",f);for(const{a:r,at:u,running:p}of m)r.currentTime=u,p&&r.play();a&&a!=="done"&&t.setAttribute("data-entrance",a),s.forEach(r=>{r.style.display=r.dataset.exportHidden??"",delete r.dataset.exportHidden});for(const[r,u]of c)n.forEach((p,w)=>{const $=u[w];$!=null&&r.setAttribute(p,$)})}const{body:A,w:x,h:g,ground:N}=v;let C="";if(l){const r=[];for(const u of["Geist","Geist Mono"]){const p=await U(u);p?r.push(`@font-face{font-family:"${u}";src:url(${p});font-weight:100 900}`):console.warn(`Basalt diagramToSvg: the face "${u}" could not be read, so the file names it`)}r.length&&(C=``)}return{svg:``,w:x,h:g}}async function _(t,i={}){const{svg:l}=await V(t,i,(i.fonts??"embed")==="embed");return new Blob([l],{type:"image/svg+xml"})}async function X(t,i={}){const{svg:l,w:d,h:e}=await V(t,i,!0),n=i.scale??2,o=new Image;o.src=`data:image/svg+xml;charset=utf-8,${encodeURIComponent(l)}`,await o.decode();const c=document.createElement("canvas");c.width=Math.round(d*n),c.height=Math.round(e*n);const s=c.getContext("2d");return s.scale(n,n),s.drawImage(o,0,0,d,e),new Promise((a,m)=>c.toBlob(f=>f?a(f):m(new Error("the PNG could not be made")),"image/png"))}(function(t){"use strict";var i=t._;function l(e,n){var o=document.createElement("a");o.href=URL.createObjectURL(e),o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(function(){URL.revokeObjectURL(o.href)},1e3)}function d(e,n){var o=document.createElement("button");o.type="button",o.className="btn diagram-download",o.setAttribute("data-variant","secondary"),o.setAttribute("data-size","sm");var c=document.createElement("span");return c.textContent=e,o.appendChild(c),o.addEventListener("click",n),o}i.diagramExport=function(e,n){var o=d("Download SVG",function(){_(n).then(function(a){l(a,P(n,"svg"))})}),c=d("Download PNG",function(){X(n).then(function(a){l(a,P(n,"png"))})}),s=e.querySelector(".diagram-clear");return e.insertBefore(o,s),e.insertBefore(c,s),[o,c]}})(window.Basalt)})();
+(()=>{var q="http://www.w3.org/2000/svg",C=t=>t.replace(/[&<>"']/g,s=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[s]),k=t=>!!t&&t!=="transparent"&&!/rgba\([^)]*,\s*0\)$/.test(t)&&!/\/\s*0\)$/.test(t),h=t=>Math.round(t*100)/100;function G(t){const s=l=>t.querySelector(`:scope > [class$="-${l}"], :scope > [class*="-${l} "]`);return["head","drawing","key"].map(s).filter(l=>!!(l&&l.getClientRects().length))}async function j(t){for(const s of Array.from(document.styleSheets)){let l;try{l=s.cssRules}catch{continue}for(const c of Array.from(l)){if(!(c instanceof CSSFontFaceRule)||c.style.getPropertyValue("font-family").replace(/["']/g,"").trim()!==t)continue;const e=/url\(["']?([^"')]+)["']?\)/.exec(c.style.getPropertyValue("src"))?.[1];if(e){if(e.startsWith("data:"))return e;try{const n=await fetch(new URL(e,s.href??location.href));if(!n.ok)return null;const o=await n.blob();return await new Promise((d,i)=>{const a=new FileReader;a.onload=()=>d(String(a.result)),a.onerror=i,a.readAsDataURL(o)})}catch{return null}}}}return null}function I(t,s,l){const c=document.createTreeWalker(t,NodeFilter.SHOW_TEXT);for(let e=c.nextNode();e;e=c.nextNode()){const n=e.parentElement;if(!n||!e.textContent?.trim()||n.closest("[aria-hidden='true'] .basalt-visually-hidden, .basalt-visually-hidden, .visually-hidden, [class$='-ruler'], [hidden]"))continue;const o=getComputedStyle(n);if(o.visibility==="hidden"||o.display==="none")continue;const d=e.textContent,i=document.createRange();for(const a of d.matchAll(/\S+/g)){i.setStart(e,a.index),i.setEnd(e,a.index+a[0].length);const m=i.getBoundingClientRect();if(!m.width)continue;const f=Number.parseFloat(o.fontSize),b=m.top-s.top+(m.height-f)/2+f*.8;l.push(`${C(a[0])}`)}}}function z(t,s,l){if(/-(lane|band|felse)(\s|$)/.test(` ${t.getAttribute("class")??""}`))for(const c of["::before","::after"]){const e=getComputedStyle(t,c);if(!e.content||e.content==="none"||e.content==="normal"||e.display==="none"||e.position!=="absolute")continue;const n=t.getBoundingClientRect(),o=getComputedStyle(t),d=n.left+(Number.parseFloat(o.borderLeftWidth)||0)+(Number.parseFloat(e.left)||0)-s.left,i=n.top+(Number.parseFloat(o.borderTopWidth)||0)+(Number.parseFloat(e.top)||0)-s.top,a=Number.parseFloat(e.width)||0,m=Number.parseFloat(e.height)||0,f=Number.parseFloat(e.borderTopWidth)||0,b=e.maskImage&&e.maskImage!=="none"?` stroke-dasharray="${Number.parseFloat(e.maskSize)/2||4} ${Number.parseFloat(e.maskSize)/2||4}"`:"";k(e.backgroundColor)&&a&&m?l.push(``):f&&k(e.borderTopColor)&&l.push(``)}}function O(t,s,l){const c=t.getBoundingClientRect();if(!c.width||!c.height||t.getAttribute("class")?.endsWith("-motion-defs"))return;const e=t.cloneNode(!0),n=[t,...Array.from(t.querySelectorAll("*"))],o=[e,...Array.from(e.querySelectorAll("*"))],d=t.viewBox?.baseVal,i=!!(d&&d.width&&(Math.abs(d.width-c.width)>.5||Math.abs(d.height-c.height)>.5));n.forEach((a,m)=>{const f=getComputedStyle(a),b=o[m];for(const w of["fill","stroke","stroke-width","stroke-dasharray","stroke-linecap","stroke-linejoin","opacity"])b.setAttribute(w,f.getPropertyValue(w));b.removeAttribute("class"),/-reveal-/.test(b.getAttribute("mask")??"")&&b.removeAttribute("mask"),i&&m>0&&b.setAttribute("vector-effect","non-scaling-stroke"),f.display==="none"&&b.setAttribute("display","none")}),e.setAttribute("x",String(h(c.left-s.left))),e.setAttribute("y",String(h(c.top-s.top))),e.setAttribute("width",String(h(c.width))),e.setAttribute("height",String(h(c.height))),e.removeAttribute("style"),l.push(e.outerHTML)}function D(t,s,l){const c=[t,...Array.from(t.querySelectorAll("*"))],e=c.filter(n=>n instanceof SVGSVGElement&&n.closest("svg")===n&&!!n.closest("[class$='-ink']"));for(const n of e)O(n,s,l);for(const n of c){if(n instanceof SVGElement){if(n.tagName.toLowerCase()!=="svg"||n.closest("svg")!==n||e.includes(n))continue;O(n,s,l);continue}const o=getComputedStyle(n);if(o.display==="none"||o.visibility==="hidden")continue;const d=n.getBoundingClientRect();if(!d.width||!d.height)continue;const i=h(d.left-s.left),a=h(d.top-s.top),m=h(d.width),f=h(d.height),b=Number.parseFloat(o.borderTopLeftRadius)||0,w=k(o.backgroundColor)?o.backgroundColor:"none",S=[o.borderTopWidth,o.borderRightWidth,o.borderBottomWidth,o.borderLeftWidth].map(r=>Number.parseFloat(r)||0),x=S.every(r=>r===S[0]);if(!x){const[r,u,p,v]=S,$=(N,R,L,F,E,M)=>{N&&k(R)&&l.push(``)};$(r,o.borderTopColor,i,a+r/2,i+m,a+r/2),$(p,o.borderBottomColor,i,a+f-p/2,i+m,a+f-p/2),$(v,o.borderLeftColor,i+v/2,a,i+v/2,a+f),$(u,o.borderRightColor,i+m-u/2,a,i+m-u/2,a+f)}const g=x?S[0]:0,T=o.borderLeftColor,A=g&&o.borderTopStyle!=="none"&&k(T)?T:"none";if(w!=="none"||A!=="none"){const r=o.borderTopStyle==="dashed"?' stroke-dasharray="4 2"':"";l.push(``),A!=="none"&&!r&&o.borderTopColor!==T&&k(o.borderTopColor)&&l.push(``)}z(n,s,l);const B=/url\(["']?([^"')]+)["']?\)/.exec(o.backgroundImage)?.[1];B&&/-mark$/.test(String(n.getAttribute("class")))&&l.push(``)}}var P=t=>t.querySelector("[class$='-title']")?.textContent?.trim()??"",H=t=>t.querySelector("figcaption")?.textContent?.trim()??"",U=(t,s)=>`${P(t).toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"diagram"}.${s}`;async function V(t,s,l){const c=s.theme??"page",e=t.getAttribute("data-theme"),n=["data-lit","data-dim","data-near","data-ahead","data-arrival","data-arrival-out"],o=Array.from(t.querySelectorAll(n.map(r=>`[${r}]`).join(", "))),d=o.map(r=>[r,n.map(u=>r.getAttribute(u))]);o.forEach(r=>{for(const u of n)r.removeAttribute(u)});const i=Array.from(t.querySelectorAll("[class*='-flow'], [class*='-bead'], [class*='-packet']"));i.forEach(r=>{r.dataset.exportHidden=r.style.display,r.style.display="none"});const a=t.getAttribute("data-entrance");a&&a!=="done"&&t.setAttribute("data-entrance","done");const m=t.getAnimations({subtree:!0}).map(r=>({a:r,at:r.currentTime,running:r.playState==="running"}));for(const{a:r}of m){const u=r.effect?.getComputedTiming().endTime;r.pause(),typeof u=="number"&&Number.isFinite(u)&&(r.currentTime=u)}const f=t.getAttribute("data-viewer");f!==null&&t.removeAttribute("data-viewer");const b=[];for(let r=t.parentElement;r;r=r.parentElement){const u=getComputedStyle(r).transform,p=/^matrix\(([^,]+),[^,]+,[^,]+,([^,]+),/.exec(u);p&&(Math.abs(Number(p[1])-1)>1e-6||Math.abs(Number(p[2])-1)>1e-6)&&(b.push([r,r.style.transform]),r.style.transform="none")}c!=="page"&&t.setAttribute("data-theme",c),t.classList.add("basalt-exporting");let w;try{t.offsetWidth;const r=Number.parseFloat(getComputedStyle(t).getPropertyValue("--basalt-space-4"))||16,u=G(t),p=u.map(y=>y.getBoundingClientRect()),v=Math.min(...p.map(y=>y.left)),$=Math.min(...p.map(y=>y.top)),N=Math.max(...p.map(y=>y.right)),R=Math.max(...p.map(y=>y.bottom)),L=new DOMRect(v-r,$-r,0,0),F=Math.ceil(N-v+2*r),E=Math.ceil(R-$+2*r),M=getComputedStyle(t).getPropertyValue("--basalt-surface-page").trim()||getComputedStyle(document.body).backgroundColor,W=[];for(const y of u)D(y,L,W);for(const y of u)I(y,L,W);w={body:W,w:F,h:E,ground:M}}finally{t.classList.remove("basalt-exporting"),c!=="page"&&(e===null?t.removeAttribute("data-theme"):t.setAttribute("data-theme",e));for(const[r,u]of b)r.style.transform=u;f!==null&&t.setAttribute("data-viewer",f);for(const{a:r,at:u,running:p}of m)r.currentTime=u,p&&r.play();a&&a!=="done"&&t.setAttribute("data-entrance",a),i.forEach(r=>{r.style.display=r.dataset.exportHidden??"",delete r.dataset.exportHidden});for(const[r,u]of d)n.forEach((p,v)=>{const $=u[v];$!=null&&r.setAttribute(p,$)})}const{body:S,w:x,h:g,ground:T}=w;let A="";if(l){const r=[];for(const u of["Geist","Geist Mono"]){const p=await j(u);p?r.push(`@font-face{font-family:"${u}";src:url(${p});font-weight:100 900}`):console.warn(`Basalt diagramToSvg: the face "${u}" could not be read, so the file names it`)}r.length&&(A=``)}return{svg:``,w:x,h:g}}async function _(t,s={}){const{svg:l}=await V(t,s,(s.fonts??"embed")==="embed");return new Blob([l],{type:"image/svg+xml"})}async function X(t){const s=new Blob([t],{type:"image/svg+xml"});if(typeof createImageBitmap=="function")try{const c=await createImageBitmap(s);return{source:c,done:()=>c.close()}}catch{}const l=[()=>URL.createObjectURL(s),()=>`data:image/svg+xml;charset=utf-8,${encodeURIComponent(t)}`];for(const c of l){const e=c(),n=()=>{e.startsWith("blob:")&&URL.revokeObjectURL(e)},o=new Image;o.src=e;try{return await o.decode(),{source:o,done:n}}catch{n()}}throw new Error("Basalt diagramToPng: the PNG could not be drawn. A canvas draws the figure's SVG through an image, and this page refused it both as a blob: URL and as a data: URL: a content policy allows them with `img-src 'self' blob:` (or `data:`). diagramToSvg needs neither")}async function J(t,s={}){const{svg:l,w:c,h:e}=await V(t,s,!0),n=s.scale??2,{source:o,done:d}=await X(l);try{const i=document.createElement("canvas");i.width=Math.round(c*n),i.height=Math.round(e*n);const a=i.getContext("2d");return a.scale(n,n),a.drawImage(o,0,0,c,e),await new Promise((m,f)=>i.toBlob(b=>b?m(b):f(new Error("Basalt diagramToPng: the PNG could not be made")),"image/png"))}finally{d()}}(function(t){"use strict";var s=t._;function l(e,n){var o=document.createElement("a");o.href=URL.createObjectURL(e),o.download=n,document.body.appendChild(o),o.click(),o.remove(),setTimeout(function(){URL.revokeObjectURL(o.href)},1e3)}function c(e,n){var o=document.createElement("button");o.type="button",o.className="btn diagram-download",o.setAttribute("data-variant","secondary"),o.setAttribute("data-size","sm");var d=document.createElement("span");return d.textContent=e,o.appendChild(d),o.addEventListener("click",n),o}s.diagramExport=function(e,n){var o=c("Download SVG",function(){_(n).then(function(a){l(a,U(n,"svg"))})}),d=c("Download PNG",function(){J(n).then(function(a){l(a,U(n,"png"))})}),i=e.querySelector(".diagram-clear");return e.insertBefore(o,i),e.insertBefore(d,i),[o,d]}})(window.Basalt)})();
diff --git a/.agent/skills/basalt-html/parts/diagram-text.js b/.agent/skills/basalt-html/parts/diagram-text.js
index 9af91f4..05dc9a9 100644
--- a/.agent/skills/basalt-html/parts/diagram-text.js
+++ b/.agent/skills/basalt-html/parts/diagram-text.js
@@ -1,2 +1,2 @@
-(()=>{var B={"&":"&","<":"<",">":">",'"':""","'":"'"},H=u=>u.replace(/[&<>"']/g,h=>B[h]);function z(u){const h=u.nodes,W=u.steps,d=n=>Array.from(n).length,b=h.map(n=>Math.max(8,d(n.name)+4)),r=h.map(()=>0);let _=0;h.forEach((n,t)=>{r[t]=_+Math.floor(b[t]/2),_+=b[t]+4});const A=(n,t,o)=>{const[s,a]=n0)for(let i=a;i0&&A(t-1,t,s+8):A(t,o,s+4)}const M=h.length-1,x=new Map;{let n=0;const t=[],o=(a,f)=>r[a]-Math.floor(b[a]/2)-1+f,s=(a,f)=>r[a]+Math.ceil(b[a]/2)-f;W.forEach((a,f)=>{if("open"in a){t.push({at:f,a:a.a-1,b:a.b-1,inset:n*2,need:d(`[${a.open}]`)+1+d(` ${a.label} `)+2}),n++;return}if("otherwise"in a){const i=t[t.length-1];i&&(i.need=Math.max(i.need,d("[else]")+1+d(` ${a.otherwise} `)+2));return}if("close"in a){n=Math.max(0,n-1);const i=t.pop();if(!i)return;const k=x.get(i.at)??0,m=i.need-(s(i.b,i.inset)-o(i.a,i.inset))-k;if(m>0){if(i.b"n"in n&&n.from===n.to&&(u.byId.get(n.from)?.i??0)===M?d(`${n.n} ${n.label}`)+8:0)),w=(r[M]??0)+Math.ceil((b[M]??8)/2)+S+2+Math.max(0,...x.values()),T=[],p=()=>{const n={ch:Array(w).fill(" "),ink:Array(w).fill("")};return T.push(n),n},l=(n,t,o,s)=>{Array.from(o).forEach((a,f)=>{const i=t+f;i>=0&&iu.bars.some(o=>o.who===h[n].id&&o.from<=t&&o.to>=t);let j=0;const y=n=>h.forEach((t,o)=>l(n,r[o],R(o,j)?"┃":"│",R(o,j)?"working":"life")),D=p(),q=p(),G=p();h.forEach((n,t)=>{const o=r[t]-Math.floor(b[t]/2),s=b[t],[a,f,i,k,m,$]=n.focal?["╔","═","╗","║","╚","╝"]:["┌","─","┐","│","└","┘"],e=n.focal?"focal":"name";l(D,o,a+f.repeat(s-2)+i,e),l(q,o,k,e),l(q,o+s-1,k,e),l(q,o+Math.floor((s-d(n.name))/2),n.name,e),l(G,o,m+f.repeat(s-2)+$,e)});const C=[],v=n=>{for(const t of C)l(n,t.l,"│","frame"),l(n,t.r,"│","frame")},F=()=>{const n=p();return y(n),v(n),n};F();for(const[n,t]of W.entries()){if("band"in t){const e=p(),c=` ${t.band} `;l(e,0,"─".repeat(w),"band"),l(e,Math.max(0,Math.floor((w-d(c))/2)),c,"band"),F();continue}if("open"in t){const e=t.a-1,c=t.b-1,L=C.length*2,g={l:Math.max(0,r[e]-Math.floor(b[e]/2)-1+L),r:Math.min(w-1,r[c]+Math.ceil(b[c]/2)+(c===M&&W.some(I=>"n"in I&&I.from===I.to)?S:0)-L+(x.get(n)??0))},E=p();y(E),v(E),l(E,g.l,"┌"+"─".repeat(g.r-g.l-1)+"┐","frame"),l(E,g.l+1,`[${t.open}]`,"op"),l(E,g.l+d(t.open)+4,` ${t.label} `,"label"),C.push(g),F();continue}if("otherwise"in t){const e=C[C.length-1];if(!e)continue;const c=p();y(c),v(c),l(c,e.l,"├"+"┄".repeat(e.r-e.l-1)+"┤","frame"),l(c,e.l+1,"[else]","op"),l(c,e.l+8,` ${t.otherwise} `,"label"),F();continue}if("close"in t){const e=C.pop();if(!e)continue;const c=p();y(c),v(c),l(c,e.l,"└"+"─".repeat(e.r-e.l-1)+"┘","frame"),F();continue}j=t.n;const o=u.byId.get(t.from)?.i??0,s=u.byId.get(t.to)?.i??0,a=`${t.n} ${t.label}`,f=e=>e==="main"?"━":e==="dashed"?"┄":"─",i=(e,c)=>e==="dashed"?c?"▷":"◁":c?"▶":"◀",k=t.kind==="main"?"main":"plain",m=p(),$=p();if(m.n=t.n,$.n=t.n,y(m),v(m),y($),v($),o===s){const e=o===M&&h.length>1,c=e?r[o]-4:r[o]+1;l(m,c,e?"┌──":"──┐",k),l($,c,e?"└─"+i(t.kind,!0):i(t.kind,!1)+"─┘",k);const L=e?c-d(a)-1:r[o]+5;if(l(m,L,a.slice(0,d(String(t.n))),"num"),l(m,L+d(String(t.n))+1,t.label,"label"),t.note){const g=p();y(g),v(g),l(g,e?c-d(t.note)-1:r[o]+5,t.note,"note")}}else{const e=Math.min(r[o],r[s]),c=Math.max(r[o],r[s]),L=r[s]>r[o],g=e+Math.max(2,Math.floor((c-e-d(a))/2));l(m,g-1," ",""),l(m,g,String(t.n),"num"),l(m,g+d(String(t.n))," "+t.label+" ","label");const E=f(t.kind).repeat(Math.max(1,c-e-2));if(l($,e+1,L?E+i(t.kind,!0):i(t.kind,!1)+E,k),t.note){const I=p();y(I),v(I);const J=e+Math.max(2,Math.floor((c-e-d(t.note))/2));l(I,J-1,` ${t.note} `,"note")}}}return F(),{html:T.map(n=>{const t=n.ch.join("").trimEnd().length;let o="",s="",a=n.ink[0]??"";for(let f=0;f${H(s)}`:H(s),s=""),a=n.ink[f],s+=n.ch[f];return s&&(o+=a?`${H(s)}`:H(s)),n.n?`${o}`:o}).join(`
-`),width:Math.max(...T.map(n=>n.ch.join("").trimEnd().length))}}(function(u){"use strict";u._.diagramText=function(h,W,d,b){var r=h.querySelector(".diagram-text"),_=r&&r.querySelector(".diagram-text-ink");if(_){h.__transcript||(h.__transcript=_.innerHTML);var A=z(W),M=document.createElement("span");M.style.cssText="display:inline-block;white-space:pre",M.textContent="─".repeat(40),r.appendChild(M);var x=M.offsetWidth/40;M.remove();var S=getComputedStyle(r),w=r.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight);b&&b.textWidth&&(b.textWidth(A.width*x+(h.clientWidth-w)+1),w=r.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight));var T=A.width*x<=w+.5,p=T?A.html:h.__transcript;_.innerHTML!==p&&(_.innerHTML=p),r.toggleAttribute("data-art",T)}}})(window.Basalt)})();
+(()=>{var B={"&":"&","<":"<",">":">",'"':""","'":"'"},j=b=>b.replace(/[&<>"']/g,d=>B[d]);function N(b){const d=b.nodes,W=b.steps,h=n=>Array.from(n).length,u=d.map(n=>Math.max(8,h(n.name)+4)),a=d.map(()=>0);let y=0;d.forEach((n,t)=>{a[t]=y+Math.floor(u[t]/2),y+=u[t]+4});const v=(n,t,o)=>{const[s,i]=n0)for(let r=i;r0&&v(t-1,t,s+8):v(t,o,s+4)}const M=d.length-1,x=new Map;{let n=0;const t=[],o=(i,f)=>a[i]-Math.floor(u[i]/2)-1+f,s=(i,f)=>a[i]+Math.ceil(u[i]/2)-f;W.forEach((i,f)=>{if("open"in i){t.push({at:f,a:i.a-1,b:i.b-1,inset:n*2,need:h(`[${i.open}]`)+1+h(` ${i.label} `)+2}),n++;return}if("otherwise"in i){const r=t[t.length-1];r&&(r.need=Math.max(r.need,h("[else]")+1+h(` ${i.otherwise} `)+2));return}if("close"in i){n=Math.max(0,n-1);const r=t.pop();if(!r)return;const k=x.get(r.at)??0,m=r.need-(s(r.b,r.inset)-o(r.a,r.inset))-k;if(m>0){if(r.b"n"in n&&n.from===n.to&&(b.byId.get(n.from)?.i??0)===M?h(`${n.n} ${n.label}`)+8:0)),w=(a[M]??0)+Math.ceil((u[M]??8)/2)+S+2+Math.max(0,...x.values()),C=[],p=()=>{const n={ch:Array(w).fill(" "),ink:Array(w).fill("")};return C.push(n),n},c=(n,t,o,s)=>{Array.from(o).forEach((i,f)=>{const r=t+f;r>=0&&rb.bars.some(o=>o.who===d[n].id&&o.from<=t&&o.to>=t);let q=0;const _=n=>d.forEach((t,o)=>c(n,a[o],R(o,q)?"┃":"│",R(o,q)?"working":"life")),z=p(),H=p(),D=p();d.forEach((n,t)=>{const o=a[t]-Math.floor(u[t]/2),s=u[t],[i,f,r,k,m,$]=n.focal?["╔","═","╗","║","╚","╝"]:["┌","─","┐","│","└","┘"],e=n.focal?"focal":"name";c(z,o,i+f.repeat(s-2)+r,e),c(H,o,k,e),c(H,o+s-1,k,e),c(H,o+Math.floor((s-h(n.name))/2),n.name,e),c(D,o,m+f.repeat(s-2)+$,e)});const F=[],E=n=>{for(const t of F)c(n,t.l,"│","frame"),c(n,t.r,"│","frame")},T=()=>{const n=p();return _(n),E(n),n};T();for(const[n,t]of W.entries()){if("band"in t){const e=p(),l=` ${t.band} `;c(e,0,"─".repeat(w),"band"),c(e,Math.max(0,Math.floor((w-h(l))/2)),l,"band"),T();continue}if("open"in t){const e=t.a-1,l=t.b-1,I=F.length*2,g={l:Math.max(0,a[e]-Math.floor(u[e]/2)-1+I),r:Math.min(w-1,a[l]+Math.ceil(u[l]/2)+(l===M&&W.some(L=>"n"in L&&L.from===L.to)?S:0)-I+(x.get(n)??0))},A=p();_(A),E(A),c(A,g.l,"┌"+"─".repeat(g.r-g.l-1)+"┐","frame"),c(A,g.l+1,`[${t.open}]`,"op"),c(A,g.l+h(t.open)+4,` ${t.label} `,"label"),F.push(g),T();continue}if("otherwise"in t){const e=F[F.length-1];if(!e)continue;const l=p();_(l),E(l),c(l,e.l,"├"+"┄".repeat(e.r-e.l-1)+"┤","frame"),c(l,e.l+1,"[else]","op"),c(l,e.l+8,` ${t.otherwise} `,"label"),T();continue}if("close"in t){const e=F.pop();if(!e)continue;const l=p();_(l),E(l),c(l,e.l,"└"+"─".repeat(e.r-e.l-1)+"┘","frame"),T();continue}q=t.n;const o=b.byId.get(t.from)?.i??0,s=b.byId.get(t.to)?.i??0,i=`${t.n} ${t.label}`,f=e=>e==="main"?"━":e==="dashed"?"┄":"─",r=(e,l)=>e==="dashed"?l?"▷":"◁":l?"▶":"◀",k=t.kind==="main"?"main":"plain",m=p(),$=p();if(m.n=t.n,$.n=t.n,_(m),E(m),_($),E($),o===s){const e=o===M&&d.length>1,l=e?a[o]-4:a[o]+1;c(m,l,e?"┌──":"──┐",k),c($,l,e?"└─"+r(t.kind,!0):r(t.kind,!1)+"─┘",k);const I=e?l-h(i)-1:a[o]+5;if(c(m,I,i.slice(0,h(String(t.n))),"num"),c(m,I+h(String(t.n))+1,t.label,"label"),t.note){const g=p();_(g),E(g),c(g,e?l-h(t.note)-1:a[o]+5,t.note,"note")}}else{const e=Math.min(a[o],a[s]),l=Math.max(a[o],a[s]),I=a[s]>a[o],g=e+Math.max(2,Math.floor((l-e-h(i))/2));c(m,g-1," ",""),c(m,g,String(t.n),"num"),c(m,g+h(String(t.n))," "+t.label+" ","label");const A=f(t.kind).repeat(Math.max(1,l-e-2));if(c($,e+1,I?A+r(t.kind,!0):r(t.kind,!1)+A,k),t.note){const L=p();_(L),E(L);const G=e+Math.max(2,Math.floor((l-e-h(t.note))/2));c(L,G-1,` ${t.note} `,"note")}}}return T(),{html:C.map(n=>{const t=n.ch.join("").trimEnd().length;let o="",s="",i=n.ink[0]??"";for(let f=0;f${j(s)}`:j(s),s=""),i=n.ink[f],s+=n.ch[f];return s&&(o+=i?`${j(s)}`:j(s)),n.n?`${o}`:o}).join(`
+`),width:Math.max(...C.map(n=>n.ch.join("").trimEnd().length))}}(function(b){"use strict";b._.diagramText=function(d,W,h,u){var a=d.querySelector(".diagram-text"),y=a&&a.querySelector(".diagram-text-ink");if(y){var v=N(W),M=document.createElement("span");M.style.cssText="display:inline-block;white-space:pre",M.textContent="─".repeat(40),a.appendChild(M);var x=M.offsetWidth/40;M.remove();var S=getComputedStyle(a),w=a.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight);u&&u.textWidth&&(u.textWidth(v.width*x+(d.clientWidth-w)+1),w=a.clientWidth-parseFloat(S.paddingLeft)-parseFloat(S.paddingRight));var C=v.width*x<=w+.5,p=!!a.__art;C?(p||(a.__transcript=Array.prototype.slice.call(y.childNodes)),(!p||y.innerHTML!==v.html)&&(y.innerHTML=v.html)):p&&a.__transcript&&y.replaceChildren.apply(y,a.__transcript),a.__art=C,a.toggleAttribute("data-art",C)}}})(window.Basalt)})();
diff --git a/.agent/skills/basalt-html/parts/diagram.js b/.agent/skills/basalt-html/parts/diagram.js
index 7287f9b..a91065f 100644
--- a/.agent/skills/basalt-html/parts/diagram.js
+++ b/.agent/skills/basalt-html/parts/diagram.js
@@ -1,6 +1,6 @@
-(()=>{var fn=["top","right","bottom","left"],un=["main","plain","dashed"],we=["one","zero-or-one","one-or-many","zero-or-many"],Ht={one:"Exactly one","zero-or-one":"Zero or one","one-or-many":"One or many","zero-or-many":"Zero or many"},hn=[2,3,4,5,6],ht=t=>t==null||t===""?void 0:String(t),Lt=t=>Object.assign(Object.create(null),t),Ot=(t,e)=>t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;function Wt(t,e={}){const o=e.checks!==!1,c=[],l=$=>{c.push($)},s=[],a=$=>{s.push($)},r=t.legend??{},d={};for(const $ of["main","plain","dashed","focal","group","activation"]){const u=ht(r[$]);u&&(d[$]=u)}const g=t.stepLabel,f=typeof g=="function"?$=>String(g($)):typeof g=="string"?($=>g.replace("{n}",String($))):$=>`Step ${$}`,i=t.shapeLabels??{},h={terminal:ht(i.terminal)??"Start or end",step:ht(i.step)??"Step",decision:ht(i.decision)??"Decision"},b=t.heading===void 0?3:hn.includes(t.heading)?t.heading:(l(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),p=($,u)=>$==null?"plain":un.includes($)?$:(l(`"${String($)}" is not a kind of line (main, plain or dashed): ${u} is drawn plain`),"plain"),m=$=>{if($!=null){if(fn.includes($))return $;l(`"${String($)}" is not a side (top, right, bottom or left): the derived side is used`)}},k=($,u)=>typeof $=="number"&&Number.isInteger($)&&$>=1?$:(t.layout==="auto"&&$==null||l(`${u} is ${JSON.stringify($)}, not a whole number from 1: it is placed at 1`),1),L=[],z=[];let v=[];const O=[],B=[],j=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(j)||l(`"${String(j)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),j==="architecture"||j==="flowchart"){for(const $ of t.nodes??[]){const u=j==="flowchart"&&$.shape==="decision"?"decision":j==="flowchart"&&$.shape==="terminal"?"terminal":"box",w=String($.id??""),C=k($.row,`the row of ${w}`);L.push({id:w,i:L.length,name:String($.name??""),kind:u==="decision"?void 0:ht($.kind),detail:u==="decision"?void 0:ht($.detail),mono:!!$.detailMono,focal:!!$.focal,col:k($.col,`the column of ${w}`),row:C,row2:C,branch:!!$.branch,shape:u,group:j==="architecture"?ht($.group):void 0,mark:j==="architecture"?oe($.mark,l):void 0})}if(j==="architecture"){const $=(t.groups??[]).map(I=>({id:String(I.id??""),label:String(I.label??""),parent:ht(I.parent)})),u=new Map($.map(I=>[I.id,I])),w=I=>{if(!I.parent)return 1;const _=u.get(I.parent);return _?_.parent===I.id||_.id===I.id?(a(`the groups "${I.label}" and "${_.label}" are each other's parent`),I.parent=void 0,1):_.parent?(a(`the group "${I.label}" is a third level: groups nest two deep`),I.parent=void 0,1):2:(a(`the group "${I.label}" names the parent "${I.parent}", which is not a group`),I.parent=void 0,1)},C=$.map(w);$.forEach((I,_)=>O.push({...I,depth:C[_],members:L.filter(X=>X.group===I.id).map(X=>X.id),all:[]}));for(const I of O)I.all=[...I.members,...O.filter(_=>_.parent===I.id).flatMap(_=>_.members)];O.sort((I,_)=>I.depth-_.depth)}}else if(j==="data-flow"){v=(t.lanes??[]).map(u=>({id:String(u.id??""),label:String(u.label??"")}));const $=new Map(v.map((u,w)=>[u.id,w+1]));for(const u of t.nodes??[]){const w=String(u.id??""),C=String(u.lane??""),I=$.get(C);I===void 0&&l(`a node (${w}) names the lane "${C}", which is not in lanes`);const _=L.length+1;L.push({id:w,i:L.length,name:String(u.name??""),kind:f(_),detail:ht(u.detail),mono:!!u.detailMono,focal:!!u.focal,col:k(u.col,`the column of ${w}`),row:I??1,row2:I??1,branch:!1,shape:"box",lane:I??1,laneLabel:v[(I??1)-1]?.label??C,step:_,mark:oe(u.mark)})}}else if(j==="sequence"){(t.participants??[]).forEach((C,I)=>{const _=String(C.name??"");L.push({id:String(C.id??""),i:I,name:_,kind:ht(C.kind),mono:!1,focal:!!C.focal,col:I+1,row:1,row2:1,branch:!1,shape:"participant",short:ht(C.short)??_,mark:oe(C.mark)})});let $=0;const u=new Map(L.map(C=>[C.id,C.col])),w=(C,I)=>{let _=1/0,X=-1/0;for(const V of C??[]){if(!V||typeof V!="object")continue;if("band"in V){I>0&&a(`the band "${String(V.band)}" is inside a frame: a band is the whole figure's`),B.push({band:String(V.band??"")});continue}if("frame"in V){if(I>=2){a("a frame is a third level: frames nest two deep");continue}const $t=V.frame==="alt"||V.frame==="loop"||V.frame==="opt"?V.frame:"opt",bt=$t==="alt"?V.branches??[]:[{label:V.label,steps:V.steps}];$t==="alt"&&bt.length<2&&a("an alt frame has one branch: it needs two or more");const wt=String(bt[0]?.label??"");wt.length>40&&a(`the frame label "${wt}" is over 40 characters`);const vt=B.length;B.push({open:$t,label:wt,depth:I+1,a:0,b:0}),bt.forEach((y,S)=>{if(S){const N=String(y.label??"");N.length>40&&a(`the frame label "${N}" is over 40 characters`),B.push({otherwise:N,depth:I+1})}y.steps?.length||a(`a frame or branch ("${String(y.label??"")}") is empty`);const[E,M]=w(y.steps??[],I+1);_=Math.min(_,E),X=Math.max(X,M);const A=B[vt];A.a=Math.min(A.a||1/0,E),A.b=Math.max(A.b,M)}),B.push({close:I+1});continue}$++;const ft=String(V.label??"");ft.includes(`
-`)&&a(`message ${$}'s label has a break: a message's second line is its note`);const st=String(V.from??""),lt=String(V.to??"");B.push({n:$,from:st,to:lt,label:qt(ft),note:ht(V.note),kind:p(V.kind,`message ${$}`),activate:V.activate===!0||void 0,deactivate:V.deactivate===!0||void 0});const pt=u.get(st)??1,Mt=u.get(lt)??1,ut=pt===Mt?pt===L.length?pt-1:pt+1:pt;_=Math.min(_,pt,Mt,ut),X=Math.max(X,pt,Mt,ut)}return[_,X]};w(t.steps??[],0);for(const C of B)"open"in C&&!Number.isFinite(C.a)&&(C.a=1,C.b=Math.max(1,L.length))}else if(j==="schema")for(const $ of t.tables??[]){const u=String($.name??""),[w,C]=Array.isArray($.row)?$.row:[$.row,$.row],I=k(w,`the row of ${u}`),_=Math.max(I,k(C,`the last row of ${u}`)),X=$.more===void 0||$.more===null?void 0:Number.isInteger($.more)&&$.more>0?$.more:(l(`${u}'s "more" is ${JSON.stringify($.more)}, not a whole number from 1: it is left out`),void 0);L.push({id:u,i:L.length,name:u,mono:!0,focal:!!$.focal,col:k($.col,`the column of ${u}`),row:I,row2:_,branch:!1,shape:"table",more:X,columns:($.columns??[]).map(V=>({name:String(V.name??""),type:ht(V.type),key:V.key==="PK"||V.key==="FK"?V.key:(V.key!==void 0&&V.key!==null&&l(`${u}.${String(V.name)}'s key is "${String(V.key)}", not PK or FK: it is left out`),void 0)}))})}let F=!1;if(t.layout==="auto"&&(j==="architecture"||j==="flowchart"||j==="schema")){const $=j==="schema"?t.tables:t.nodes;o&&($??[]).some(w=>w&&(w.col!==void 0||w.row!==void 0))&&l('a card under layout="auto" has a col or row, which is not read: there are no hints');const u=e.placement?.cells;u||(F=!0);for(const w of L){const C=u?.[w.id];w.col=C?.col??1,w.row=w.row2=C?.row??1}if(u){const w=new Map;for(const C of L){const I=Ot(u,C.id);if(!I){F=!0,l(`the placement has no cell for ${C.id}, so it is not used`);continue}const _=`${I.col},${I.row}`;w.has(_)&&(F=!0,l(`the placement puts ${w.get(_)} and ${C.id} in one cell, so it is not used`)),w.set(_,C.id)}}if(u&&!F)for(const w of O){const C=w.all.map(st=>L.find(lt=>lt.id===st)).filter(Boolean);if(!C.length)continue;const I=Math.min(...C.map(st=>st.col)),_=Math.max(...C.map(st=>st.col)),X=Math.min(...C.map(st=>st.row)),V=Math.max(...C.map(st=>st.row)),ft=L.filter(st=>!w.all.includes(st.id)&&st.col>=I&&st.col<=_&&st.row>=X&&st.row<=V);ft.length&&(F=!0,l(`the placement puts ${ft.map(st=>st.id).join(", ")} inside the box of the group "${w.label}", so it is not used`))}}else t.layout==="auto"&&a(`layout="auto" is for an architecture, a flowchart or a schema, not a ${j}`);((j==="schema"?t.tables:j==="sequence"?t.participants:t.nodes)??[]).forEach(($,u)=>{if(!$||$.href===void 0||$.href===null)return;const w=String($.href);if(j==="sequence"){a(`${L[u]?.id}: a participant cannot be a link (href)`);return}if(!w.trim()){a(`${L[u]?.id}'s href is empty`);return}const C=L[u];C&&(C.href=w,C.blank=$.target==="_blank")});const q=new Map;for(const $ of L)$.id?q.has($.id)&&l(`the id "${$.id}" is used twice`):l("a node has no id"),q.set($.id,$);if(j==="schema"){const $=(w,C)=>{if(w==null)return;const I=w,_=we.includes(I.from)?I.from:void 0;if(!_){a(`${C}'s cardinality "from" is ${JSON.stringify(I.from)}, not one, zero-or-one, one-or-many or zero-or-many: it is left out`);return}return I.to===void 0||I.to===null?{from:_,to:"one"}:I.to==="one"||I.to==="zero-or-one"?{from:_,to:I.to}:(a(`${C}'s cardinality "to" is ${JSON.stringify(I.to)}: a foreign key references one row at most (one or zero-or-one), so it is drawn as one`),{from:_,to:"one"})};(t.tables??[]).forEach(w=>(w.columns??[]).forEach((C,I)=>{const _=ht(C.references);if(!_&&C.cardinality!==void 0&&C.cardinality!==null&&a(`${String(w.name)}.${String(C.name)} states a cardinality but references nothing`),!_)return;const[X,V]=_.split("."),ft=q.get(X??""),st=ft?.columns?.findIndex(Mt=>Mt.name===V)??-1;if(!ft||st<0){l(`${String(w.name)}.${String(C.name)} references ${_}, which is not a shown column`);return}const lt=q.get(String(w.name??""));lt.columns[I].ref={table:X,column:V,row:st};const pt=$(C.cardinality,`${String(w.name)}.${String(C.name)}`);pt&&(lt.columns[I].card=pt),z.push({i:z.length,from:lt.id,to:X,kind:"plain",fromRow:I,toRow:st,fk:!0,card:pt})}));const u=z.filter(w=>w.card).length;u&&u!w.card).map(w=>`${w.from}.${q.get(w.from).columns[w.fromRow].name}`).join(", ")} ${z.length-u===1?"has":"have"} none)`)}else if(j!=="sequence")for(const $ of t.edges??[]){const u=String($.from??""),w=String($.to??"");if(!q.has(u)||!q.has(w)){l(`a line names ${q.has(u)?w:u}, which is not a node`);continue}const C=ht($.label),I=C?.split(`
-`)??[];I.length>2&&a(`the label "${qt(C)}" has more than one break: a label is two lines at most`),I.some(_=>_.length>Me)&&a(`a line of the label "${qt(C)}" is over ${Me} characters: longer words belong in the node or the summary`),z.push({i:z.length,from:u,to:w,kind:p($.kind,`the line from ${u} to ${w}`),label:C,fromSide:m($.fromSide),toSide:m($.toSide),flow:j!=="flowchart"&&$.flow===!0?!0:void 0})}else for(const $ of B)"n"in $&&(!q.has($.from)||!q.has($.to))&&l(`message ${$.n} names ${q.has($.from)?$.to:$.from}, which is not a participant`);if(o&&j!=="sequence"&&!F){const $=new Map;for(const u of L)for(let w=u.row;w<=u.row2;w++){const C=`${u.col}:${w}`;$.has(C)&&l(`${u.id} and ${$.get(C)} share the cell at column ${u.col}, row ${w}`),$.set(C,u.id)}}if(o&&!F){for(const u of O){const w=u.all.map(_=>q.get(_));if(!w.length)continue;const C={c1:Math.min(...w.map(_=>_.col)),c2:Math.max(...w.map(_=>_.col)),r1:Math.min(...w.map(_=>_.row)),r2:Math.max(...w.map(_=>_.row2))};for(const _ of L)!u.all.includes(_.id)&&_.col>=C.c1&&_.col<=C.c2&&_.row>=C.r1&&_.row<=C.r2&&l(`${_.id} is inside the box of the group "${u.label}" but not a member`);const I=w.map(_=>_.i);Math.max(...I)-Math.min(...I)+1!==I.length&&l(`the members of the group "${u.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const u of L)u.group&&!O.some(w=>w.id===u.group)&&l(`${u.id} names the group "${u.group}", which is not in groups`);L.filter(u=>u.focal).length>1&&l("more than one node is focal: a diagram has one at most");const $=new Set(j==="sequence"?B.flatMap(u=>"n"in u?[u.kind]:[]):z.map(u=>u.kind));$.has("main")&&!d.main&&l("main lines are drawn but the legend has no words for them (legend.main)"),$.has("dashed")&&!d.dashed&&l("dashed lines are drawn but the legend has no words for them (legend.dashed)"),L.some(u=>u.focal)&&!d.focal&&l("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const D=j==="architecture"||j==="data-flow",T=$=>Array.isArray($)&&$.length>1?$.map(String):void 0,R=D&&t.packet&&typeof t.packet=="object"?t.packet:void 0,H=R&&T(R.path),Q={animated:t.motion==="animated",pulse:D?T(t.pulse):void 0,packet:H?{path:H,repeat:R.repeat===!0,send:R.send}:void 0,run:j==="sequence"&&t.run===!0,firstVisit:t.entrance==="first-visit"||void 0};if(o)for(const $ of L){const u=$.mark?.says;if(!u?.length)continue;const w=[$.name,$.kind,$.detail,$.laneLabel].filter(Boolean).join(" ").toLowerCase();u.some(C=>w.includes(C.toLowerCase()))||l(`${$.id}'s mark stands for ${u.join(" or ")}, and none of its words say so`)}const at=[];if(j==="sequence"){const $=new Map,u=new Map;for(const w of B)"n"in w&&(u.set(w.from,w.n),u.set(w.to,w.n));for(const w of B)if("n"in w){if(w.activate){const C=$.get(w.to)??[];if(C.length>=3)a(`message ${w.n} opens a fourth bar on ${w.to}: three deep at most`);else{const I={who:w.to,from:w.n,to:w.n,depth:C.length+1};C.push(I),at.push(I),$.set(w.to,C)}}if(w.deactivate){const I=$.get(w.from)?.pop();I?I.to=w.n:a(`message ${w.n} closes a bar on ${w.from}, which has none open`)}}for(const[w,C]of $)for(const I of C)I.to=Math.max(I.from,u.get(w)??I.from)}const it=t.frameLabels??{},yt={opt:ht(it.opt)??"Only if",loop:ht(it.loop)??"Repeats",alt:ht(it.alt)??"One of these",else:ht(it.else)??"Otherwise"},dt=t.layout==="auto"&&!F?e.placement:void 0;let et=Math.max(1,dt?.cols??1,...L.map($=>$.col));if(e.rtl){for(const u of L)u.col=et-u.col+1;const $=u=>u==="left"?"right":u==="right"?"left":u;for(const u of z)u.fromSide=$(u.fromSide),u.toSide=$(u.toSide);for(const u of B)if("open"in u){const[w,C]=[et-u.b+1,et-u.a+1];u.a=w,u.b=C}et=Math.max(1,dt?.cols??1,...L.map(u=>u.col))}const nt=j==="data-flow"?Math.max(1,v.length):Math.max(1,dt?.rows??1,...L.map($=>$.row2)),tt={type:j,title:String(t.title??""),heading:b,legend:d,nodes:L,byId:q,edges:z,groups:O,lanes:v,steps:B,bars:at,frameWords:yt,cols:et,rows:nt,shapeLabels:h,stepWord:f,warnings:c,errors:s,motion:Q,memo:new Map,rtl:e.rtl||void 0,unplaced:F||void 0,text:j==="sequence"&&t.variant==="text"||void 0,marks:z.some($=>$.card)||void 0};if(t.layout==="auto"&&!F&&j!=="schema"&&pn(tt),o)for(const[$,u]of Object.entries(De(tt)))u>=48&&l(`${$} grows to ${u}px to hold the lines on one side: use another side`);return o&&L.length>100&&l(`the figure has ${L.length} cards: more than 100, which automatic layout places on the main thread`),o&&L.length>1&&!F&&!Ut(tt)&&l("some part cannot be reached from another by the arrow keys where the figure is drawn, so its arrows keep the author's order"),tt}function pn(t){const e=new Set(t.nodes.map(a=>`${a.col},${a.row}`)),n=(a,r)=>{const d=[];for(let g=Math.min(a,r)+1;g{const r=t.byId.get(a.from),d=t.byId.get(a.to),g=d.col>r.col?"right":"left",f=d.row>r.row?"bottom":"top",i=d.col>r.col?"left":"right",h=d.row>r.row?"top":"bottom",b=(k,L,z,v)=>n(k,L).map(O=>v?[O,z]:[z,O]);let p;const m=k=>(k==="right"?r.col1:k==="bottom"?r.row1)?[{sides:[k,k],cells:[]}]:[];return r.row===d.row?p=[{sides:[g,i],cells:b(r.col,d.col,r.row,!0)},...m("bottom"),...m("top")]:r.col===d.col?p=[{sides:[f,h],cells:b(r.row,d.row,r.col,!1)},...m("right"),...m("left")]:p=[{sides:[g,h],cells:[...b(r.col,d.col,r.row,!0),[d.col,r.row],...b(r.row,d.row,d.col,!1)]},{sides:[f,i],cells:[...b(r.row,d.row,r.col,!1),[r.col,d.row],...b(r.col,d.col,d.row,!0)]},{sides:[g,i],cells:b(r.col,d.col,r.row,!0)},{sides:[f,h],cells:b(r.row,d.row,r.col,!1)}],p.filter(k=>k.cells.every(([L,z])=>!e.has(`${L},${z}`)))},c=new Map,l=new Set;for(const a of t.edges)if(a.fromSide||a.toSide){const[r,d]=fe(t.byId.get(a.from),t.byId.get(a.to)),g=a.fromSide??r,f=a.toSide??d;l.add(`${a.from}.${g}`);for(const[i,h]of[[a.from,g],[a.to,f]])c.set(`${i}.${h}`,(c.get(`${i}.${h}`)??0)+1)}const s=t.edges.map((a,r)=>r).sort((a,r)=>o(t.edges[a]).length-o(t.edges[r]).length||+(t.edges[r].kind==="main")-+(t.edges[a].kind==="main")||a-r);for(const a of s){const r=t.edges[a];if(r.fromSide||r.toSide)continue;const d=(f,i,h)=>{const b=`${f}.${i}`;return(c.get(b)??0)>=3?!1:t.byId.get(f).shape!=="decision"?!0:h?!c.has(b):!l.has(b)},g=o(r).find(f=>d(r.from,f.sides[0],!0)&&d(r.to,f.sides[1],!1));if(g){l.add(`${r.from}.${g.sides[0]}`);for(const[f,i]of[[r.from,g.sides[0]],[r.to,g.sides[1]]])c.set(`${f}.${i}`,(c.get(`${f}.${i}`)??0)+1);r.fromSide=g.sides[0],r.toSide=g.sides[1]}}}function oe(t,e){if(typeof t=="string")return t?{id:t}:void 0;if(!t||typeof t!="object")return;const n=t,o=ve(ht(n.onLight),e);if(o)return{onLight:o,onDark:ve(ht(n.onDark),e)??o,says:Array.isArray(n.says)?n.says.map(String):void 0}}function ve(t,e){if(t){if(/^data:image\//i.test(t.trim()))return t;try{if(/^https?:$/.test(new URL(t,"https://basalt.invalid/").protocol)&&!/^http:/i.test(t.trim()))return t}catch{}e?.(`a card's mark ${JSON.stringify(t.slice(0,60))} is not a relative path, https or a data: image, so it is not drawn`)}}var xe=t=>`url("${t.replace(/[\\"\n\r\f;]/g,e=>e===`
-`?"\\a ":e==="\r"?"\\d ":e==="\f"?"\\c ":e===";"?"\\3b ":`\\${e}`)}")`;function Rt(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var Me=28,Kt=t=>t.includes(`
-`)?2:1,qt=t=>t.replace(/\n/g," "),Ft=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""};function ke(t,e){return t.legend[e]}function gn(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function mn(t,e){return Rt(t,`sentence:${e.i}`,()=>yn(t,e))}function yn(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const o=(e.columns??[]).filter(l=>l.ref).map(l=>`${l.ref.table} (${l.name}${l.card?`: ${Se(e.id,l.ref.table,l.card)}`:""})`),c=t.edges.filter(l=>l.to===e.id).map(l=>`${l.from} (${t.byId.get(l.from).columns[l.fromRow].name}${l.card?`: ${Se(l.from,l.to,l.card)}`:""})`);o.length&&n.push(`References ${o.join(", ")}.`),c.length&&n.push(`Referenced by ${c.join(", ")}.`)}else if(t.type==="sequence"){const o=t.steps.filter(s=>"n"in s&&s.from===e.id).length,c=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(Ft(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${o} ${o===1?"message":"messages"} and receives ${c}.`);const l=Ee(t,e);l&&n.push(l.trim())}else{const o=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?gn(t,e):e.kind;if(n.push(Ft(o?`${e.name}, ${o}`:e.name)),e.detail&&n.push(Ft(e.detail)),e.group){const s=t.groups.find(r=>r.id===e.group),a=s?.parent?t.groups.find(r=>r.id===s.parent):void 0;s&&n.push(a?`In ${s.label}, in ${a.label}.`:`In ${s.label}.`)}const c=t.edges.filter(s=>s.to===e.id).map(s=>`${t.byId.get(s.from).name}${s.label?` (${qt(s.label)})`:""}`),l=t.edges.filter(s=>s.from===e.id).map(s=>`${t.byId.get(s.to).name}${s.label?` (${qt(s.label)})`:""}`);c.length&&n.push(`From: ${c.join(", ")}.`),l.length&&n.push(`To: ${l.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(Ft(t.legend.focal)),n.join(" ")}var $n=(t,e,n,o)=>[`${Ht[n.from].toLowerCase()} `,o(t),` to ${Ht[n.to].toLowerCase()} `,o(e)],Se=(t,e,n)=>`${Ht[n.from].toLowerCase()} ${t} to ${Ht[n.to].toLowerCase()} ${e}`;function Ee(t,e){const n=t.bars.filter(c=>c.who===e.id&&c.depth===1);return n.length?` ${t.legend.activation??"Working"} during ${n.map(c=>c.from===c.to?`message ${c.from}`:`messages ${c.from} to ${c.to}`).join(" and ")}.`:""}function bn(t,e,n,o){const c=n.pointerType;if(c!=="touch"&&c!=="pen")return;const l=t.querySelector(`.${e}-drawing`),s=n.target;if(!l||!s||!l.contains(s)||!t.querySelector(`.${e}-edge`))return;const a=s.closest(`.${e}-node`);if(!a?.hasAttribute("href"))return a?a.dataset.node===o?null:a.dataset.node??null:o===null?void 0:null}function Ae(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function x(t,e,...n){const o=[];for(const c of n.flat(1/0))c!=null&&c!==!1&&!Array.isArray(c)&&o.push(c);return{t,a:e??{},c:o}}var wn={"&":"&","<":"<",">":">",'"':""","'":"'"},mt=t=>t.replace(/[&<>"']/g,e=>wn[e]),vn=" br img input meta link hr path polygon polyline circle rect line ";function se(t,e={}){if(typeof t=="string")return mt(t);if("slot"in t)return e[t.slot]??"";if(!/^[a-z][a-z0-9]*$/.test(t.t))throw new Error(`diagram: "${t.t}" is not an element name`);let n="";for(const[o,c]of Object.entries(t.a))if(!(c==null||c===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(o))throw new Error(`diagram: "${o}" is not an attribute name`);n+=c===!0?` ${o}`:` ${o}="${mt(String(c))}"`}return vn.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(o=>se(o,e)).join("")}${t.t}>`}var xn=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function Tt(t,e){return!e.layout||e.bare?!1:e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema"}function Mn(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function Zt(t,e){const n=e.all.map(o=>t.byId.get(o));return n.length?{c1:Math.min(...n.map(o=>o.col)),c2:Math.max(...n.map(o=>o.col)),r1:Math.min(...n.map(o=>o.row)),r2:Math.max(...n.map(o=>o.row2))}:null}function Le(t){return Rt(t,"group-edges",()=>{const e=[0,0,0,0];for(const n of t.groups){const o=Zt(t,n);if(!o)continue;[o.r1===1,o.c2===t.cols,o.r2===t.rows,o.c1===1].forEach((l,s)=>{l&&(e[s]=Math.max(e[s],_e(t,n,s)))})}return e})}function _e(t,e,n){const o=Zt(t,e);return t.groups.filter(s=>s.parent===e.id).some(s=>{const a=Zt(t,s);return a&&[a.r1===o.r1,a.c2===o.c2,a.r2===o.r2,a.c1===o.c1][n]})?2:1}function qe(t){const e=Le(t);return e[1]+e[3]}function ae(t){return t.type==="sequence"?t.nodes.length:t.cols}function Ie(t){return Rt(t,"plan",()=>kn(t))}function kn(t){const e=t.nodes,n=m=>t.type==="data-flow"||!e[m].branch,o=t.edges.map(m=>{const k=t.byId.get(m.from).i,L=t.byId.get(m.to).i,v=e.slice(Math.min(k,L)+1,Math.max(k,L)).every(O=>!n(O.i));return L===k+1&&!(n(k)&&!n(L))?"down":L===k-1?"up":L>k&&n(k)&&!n(L)&&v?"trunk":L>k&&n(k)&&n(L)&&v?"rail":L>k?"end-down":"end-up"}),c=t.edges.map((m,k)=>({e:m,k})).filter(({k:m})=>o[m]==="end-down"||o[m]==="end-up"),l=m=>{const k=t.byId.get(m.from).i,L=t.byId.get(m.to).i;return[Math.min(k,L),Math.max(k,L)]},s=(m,k)=>{const[L,z]=l(m),[v,O]=l(k);return L{const k=t.byId.get(m.from).i,[L,z]=l(m);return!n(k)&&e.slice(L+1,z).every(v=>!n(v.i))&&c.every(v=>v.e===m||!s(v.e,m))}),r=c.length>0&&(t.type==="data-flow"||!a),d=m=>{const[k,L]=l(m);return L-k},g=t.edges.map(()=>0);let f=!1;const i=[];for(const m of[...c].sort((k,L)=>d(k.e)-d(L.e)||k.k-L.k)){let k=0;for(const L of i)s(L.e,m.e)&&(k=Math.max(k,g[L.k]+1));g[m.k]=k,k>3&&(f=!0),i.push(m)}const h=Math.max(0,...c.map(({k:m})=>g[m]+1)),b=t.edges.map(()=>.5);for(const m of e){const k=c.filter(({e:v})=>v.from===m.id);if(k.length<2)continue;const L=k.filter(({k:v})=>o[v]==="end-down").sort((v,O)=>d(O.e)-d(v.e)||v.k-O.k);[...k.filter(({k:v})=>o[v]==="end-up").sort((v,O)=>d(v.e)-d(O.e)||O.k-v.k),...L].forEach(({k:v},O,B)=>{b[v]=B.length===2?O===0?1/3:2/3:(O+1)/(B.length+1)})}const p=Lt();for(let m=1;m{const D=o[q],T=t.byId.get(rt.from).i,R=t.byId.get(rt.to).i,H=R===m&&(D==="down"||D==="trunk"||D==="rail"||D==="end-down"),Q=T===m&&R===m-1&&D==="up",at=R===m-1&&D==="end-up";H&&(D==="trunk"||D==="end-down")&&(O=!0),at&&(B=!0),(H||Q||at)&&rt.label&&(z++,v=Math.max(v,D==="trunk"?40:48))}),(z>1||O&&B)&&(v=64);const j=c.filter(({e:rt,k:q})=>o[q]==="end-down"&&t.byId.get(rt.to).i===m).length,F=c.filter(({e:rt,k:q})=>o[q]==="end-up"&&t.byId.get(rt.to).i===m-1).length;v+=20*Math.max(0,j-1)+20*Math.max(0,F-1),p[k.id]=v}return{routes:o,gutter:r,lanes:g,exits:b,gaps:p,third:f,laneCount:h}}var Nt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function Ce(t,e){const n=e==="fk"?"plain":e,o=n==="main"?8:8.5,c=24,l=n==="dashed"?c-1:c-7;return x("svg",{class:`${t}-swatch`,"data-kind":n,...Nt(24,16)},e==="fk"?x("circle",{class:`${t}-dot`,cx:3,cy:o,r:3}):null,x("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${o}H${l}`}),n==="dashed"?x("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${c-8} ${o-4}L${c} ${o}L${c-8} ${o+4}`}):x("path",{class:`${t}-tip`,"data-kind":n,d:`M${c} ${o}L${c-8} ${o-4}L${c-8} ${o+4}Z`}))}function Sn(t,e){const{crow:n,ring:o}=Oe(e,24,8.5,-1);return x("svg",{class:`${t}-swatch`,"data-card":e,...Nt(24,16)},x("path",{class:`${t}-line`,"data-kind":"plain",d:"M0 8.5H24"}),x("path",{class:`${t}-crow`,d:n}),o?x("circle",{class:`${t}-ring`,cx:o.x,cy:o.y,r:o.r}):null)}function Oe(t,e,n,o,c=8,l=6){const s=h=>String(Math.round(h*100)/100),a=h=>e+o*h,r=c/2,d=h=>`M${s(a(h-.5))} ${s(n-r)}V${s(n+r)}`,g=t==="one-or-many"||t==="zero-or-many",f=t==="zero-or-one"||t==="zero-or-many";let i=g?`M${s(e)} ${s(n-r)}L${s(a(7.5))} ${s(n)}L${s(e)} ${s(n+r)}`:d(4);return f||(i+=d(g?11:8)),{crow:i,ring:f?{x:Math.round(a(10.5)*100)/100,y:n,r:l/2}:void 0}}function Dt(t,e){return e==="decision"?x("svg",{class:`${t}-swatch`,"data-shape":e,...Nt(16,16)},x("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?x("svg",{class:`${t}-swatch`,"data-shape":e,...Nt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):x("svg",{class:`${t}-swatch`,"data-shape":e,...Nt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function Be(t,e){return Rt(e,`key:${t}`,()=>An(t,e))}var En=Be;function An(t,e){const n=[],o=(s,a,r={})=>n.push(x("li",{class:`${t}-entry`,...r},s,x("span",null,a)));if(e.type==="schema"){const s=new Set(e.nodes.flatMap(a=>(a.columns??[]).map(r=>r.key)));for(const[a,r]of[["PK","Primary key"],["FK","Foreign key"]])s.has(a)&&n.push(x("li",{class:`${t}-entry`},x("span",{class:`${t}-key-letters`,"aria-hidden":"true"},a),x("span",null,r)))}if(e.type==="flowchart"){const s=new Set(e.nodes.map(a=>a.shape));s.has("terminal")&&o(Dt(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&o(Dt(t,"box"),e.shapeLabels.step),s.has("decision")&&o(Dt(t,"decision"),e.shapeLabels.decision)}const c=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind)),l=(s,a)=>x("span",{class:`${t}-key-glyph`,"data-ink":a,"aria-hidden":"true"},s);for(const s of["main","plain","dashed"]){const a=e.legend[s];c.has(s)&&a&&o(e.text?l(s==="main"?"━━▶":s==="dashed"?"┄┄▷":"──▶",s==="main"?"main":"plain"):Ce(t,s),a,{"data-line":e.text?void 0:""})}if(e.type==="schema"&&e.edges.length){e.edges.some(a=>!a.card)&&o(Ce(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"});const s=new Set(e.edges.flatMap(a=>a.card?[a.card.from,a.card.to]:[]));for(const a of we)s.has(a)&&o(Sn(t,a),Ht[a],{"data-line":"","data-when":"drawn","data-card":a});n.push(x("li",{class:`${t}-entry`,"data-when":"stacked"},x("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},e.rtl?"←":"→"),x("span",null,"The table a foreign key references")))}if(e.type==="sequence"){e.bars.length&&o(e.text?l("┃","working"):x("svg",{class:`${t}-swatch`,"data-shape":"bar",...Nt(16,16)},x("path",{class:`${t}-life`,d:"M8 0V16"}),x("rect",{class:`${t}-bar`,x:4.5,y:2.5,width:7,height:11,rx:1.5})),e.legend.activation??"Working",e.text?{}:{"data-when":"drawn"});const s=new Set(e.steps.flatMap(a=>"open"in a?[a.open]:[]));for(const a of["opt","loop","alt"])s.has(a)&&n.push(x("li",{class:`${t}-entry`},x("span",{class:`${t}-key-letters`,"data-op":"","aria-hidden":"true"},a),x("span",null,e.frameWords[a])))}return e.nodes.some(s=>s.focal)&&e.legend.focal&&o(e.text?l("╔═╗","focal"):Dt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&o(Dt(t,"group"),e.legend.group),n.length?x("div",{class:`${t}-key`},x("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function Ln(t,e){const n=e==="main"?6:6.5;return x("svg",{class:`${t}-arrow`,"data-kind":e,...Nt(20,12)},x("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?x("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):x("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}var It=t=>x("bdi",null,t);function re(t,e){if(!e.href)return It(e.name);const n=e.name.trimEnd().lastIndexOf(" ");return[n<0?"":e.name.slice(0,n+1),x("span",{class:`${t}-name-end`},n<0?e.name:e.name.slice(n+1))]}function _n(t,e,n){if(n.shape==="decision")return[x("span",{class:`${t}-words`},x("span",{class:`${t}-name`},re(t,n)))];const o=[];return e.type==="data-flow"?o.push(x("span",{class:`${t}-kind`},It(n.kind),x("span",{class:`${t}-lane-word`}," · ",It(n.laneLabel??"")))):n.kind&&o.push(x("span",{class:`${t}-kind`},It(n.kind))),o.push(x("span",{class:`${t}-name`},re(t,n))),n.detail&&o.push(x("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.mono?x("span",{class:`${t}-runs`},Pt(n.detail).flatMap((c,l)=>[l?" ":"",x("span",{class:`${t}-run`},c)])):It(n.detail))),o}function qn(t,e,n){return[x("span",{class:`${t}-th`},x("span",{class:`${t}-tname`},re(t,e))),x("span",{class:`${t}-rows`},(e.columns??[]).map((o,c)=>x("span",{class:`${t}-row`,"data-row":c,"data-key":o.key},x("span",{class:`${t}-keyseat`},o.key??""),x("span",{class:`${t}-cname`},o.name),o.ref?x("span",{class:`${t}-ctype`,"data-ref":""},`${n.rtl?"←":"→"} `,It(o.ref.table)):o.type?x("span",{class:`${t}-ctype`},It(o.type)):null))),e.more?x("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var je=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function Jt(t,e,n,o){const{P:c}=t,l=Mn(e,o)||o.keep===n.id,s=Tt(e,o),a=o.layout==="drawn"&&o.rows,r=[`--_c:${n.col}`,`--_r:${a?2*n.row:n.row}`,`--_r2:${a?2*n.row2+1:n.row2+1}`];e.type==="data-flow"&&r.push(`--_lc:${n.col+1}`),e.type==="sequence"&&r.push(`--_c2:${n.col+1}`);const d=t.plan;if(d&&n.i>0){const b=Ot(d.gaps,n.id)??32,p=Ot(o.grow,n.id)??0;r.push(`--_gap:${p?`calc(${je(b)} + var(--basalt-space-4) * ${p})`:je(b)}`)}const g=Ot(o.heights,n.id);g&&r.push(`--_h:${g}px`);const f=Ot(De(e),n.id);f&&r.push(`--_mh:${f}px`);const i=Ot(o.words,n.id);i&&r.push(`--_ww:${i}px`);const h=s?o.stop===n.id?0:-1:o.keep===n.id?-1:void 0;return x(n.href?"a":"div",{class:`${c}-node`,href:n.href,target:n.href&&n.blank?"_blank":void 0,rel:n.href&&n.blank?"noopener noreferrer":void 0,"data-link":n.href?n.blank?"external":"":void 0,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-mark":n.mark?n.mark.id??"":void 0,"data-level":t.level,style:r.join(";"),role:l&&!n.href?"img":void 0,"aria-label":l||n.href?mn(e,n):void 0,tabindex:h},n.shape==="decision"?x("svg",{class:`${c}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},x("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.mark?x("span",{class:`${c}-mark`,"aria-hidden":"true",style:n.mark.onLight?`--_ml:${xe(n.mark.onLight)};--_md:${xe(n.mark.onDark??n.mark.onLight)}`:void 0}):null,n.shape==="table"?qn(c,n,e):_n(c,e,n))}function In(t,e,n){const{P:o}=t,c=[];if(e.type==="data-flow"&&c.push(...e.lanes.map((r,d)=>x("div",{class:`${o}-lane`,style:`--_r:${d+1}`,"aria-hidden":"true"},x("span",{class:`${o}-lane-name`},r.label)))),e.type==="architecture")for(const r of e.groups){const d=Zt(e,r);if(!d)continue;const g=[0,1,2,3].map(f=>_e(e,r,f));c.push(x("div",{class:`${o}-gbox`,"data-group":r.id,"data-depth":r.depth>1?r.depth:void 0,style:`--_c:${d.c1};--_c2:${d.c2+1};--_r:${d.r1};--_r2:${d.r2+1}${g[0]>1?";--_gt:2":""}${g[1]>1?";--_ge:2":""}${g[2]>1?";--_gb:2":""}${g[3]>1?";--_gs:2":""}`,"aria-hidden":"true"},x("span",{class:`${o}-glabel`},It(r.label))))}if(e.text)return[x("pre",{class:`${o}-text`,"aria-hidden":"true","data-art":n.art?"":void 0},x("code",{class:`${o}-text-ink`},Cn(o,e)))];if(e.type==="sequence")return c.push(x("ul",{class:`${o}-cast`},e.nodes.map(r=>x("li",{class:`${o}-actor`,style:e.rtl?`--_ac:${r.col}`:void 0},Jt(t,e,r,n))))),c.push(On(t,e)),c;const l=r=>{const d=r.group?e.groups.find(g=>g.id===r.group):void 0;return d?.parent?e.groups.find(g=>g.id===d.parent):d},s=(r,d,g)=>{const f=t.plan?Ot(n.grow,d[0].id)??0:0,i=d[0],h=t.plan&&i.group===r.id?e.edges.filter((m,k)=>m.to===i.id&&(t.plan.routes[k]==="trunk"||t.plan.routes[k]==="end-down")):[],b=Math.max(0,...h.map(m=>m.label?Kt(m.label):0)),p=[f?`--_ggrow:${f}`:"",b?`--_tl:${b}`:""].filter(Boolean).join(";");return x("div",{class:`${o}-group`,"data-group":r.id,"data-depth":r.depth>1?r.depth:void 0,"data-turn":h.length?"":void 0,style:p||void 0},x("span",{class:`${o}-glabel`,"aria-hidden":"true"},It(r.label)),g)};let a=0;for(;ap.id===g[i].group):void 0;if(!h){f.push(Jt(t,e,g[i],n)),i++;continue}const b=[];for(;iJt(t,e,p,n))))}c.push(s(d,g,f))}return c}function Cn(t,e){const n=[],o=r=>x("span",{class:`${t}-tx-name`},r),c=r=>r==="main"?"━▶":r==="dashed"?"┄▷":"─▶",l=(r,d,g,...f)=>x("span",{class:`${t}-tx-line`,...r,style:g?`--_in:${d+g};--_hang:${g}`:`--_in:${d}`},...f);n.push(l({"data-ink":"names"},0,0,e.nodes.flatMap((r,d)=>[d?" · ":"",o(r.name)])));const s=String(Math.max(1,...e.steps.map(r=>"n"in r?r.n:0))).length;let a=0;for(const r of e.steps){const d=2*a;if("band"in r){n.push(l({"data-ink":"band"},d,0,`── ${r.band} ──`));continue}if("open"in r){n.push(l({"data-ink":"frame"},d,0,x("span",{"data-ink":"op"},`[${r.open}]`),` ${r.label}`)),a++;continue}if("otherwise"in r){n.push(l({"data-ink":"frame"},2*Math.max(0,a-1),0,x("span",{"data-ink":"op"},"[else]"),` ${r.otherwise}`));continue}if("close"in r){a=Math.max(0,a-1),n.push(l({"data-ink":"frame"},2*a,0,"[end]"));continue}const g=e.byId.get(r.from)?.name??r.from,f=e.byId.get(r.to)?.name??r.to,i=s+2;n.push(l({"data-n":r.n},d,i,x("span",{"data-ink":"num"},String(r.n).padStart(s,"0"))," ",o(g)," ",x("span",{class:`${t}-tx-to`},x("span",{"data-ink":r.kind==="main"?"main":"plain"},c(r.kind))," ",f))),n.push(l({"data-n":r.n},d+i,0,x("span",{"data-ink":"label"},r.label))),r.note&&n.push(l({"data-n":r.n},d+i,0,x("span",{"data-ink":"note"},r.note)))}return n}function On(t,e){const{P:n}=t,o=[],c=[],l=()=>c.length?c[c.length-1].el.c:o;let s=null;for(const a of e.steps){if("band"in a){s=null,l().push(x("p",{class:`${n}-band`},x("span",null,a.band)));continue}if("open"in a){s=null;const p=c[c.length-1],m=p?`;--_fis:${a.a===p.a?1:0};--_fie:${a.b===p.b?1:0}`:"",k=x("div",{class:`${n}-frame`,"data-op":a.open,"data-depth":a.depth,style:`--_a:${a.a};--_b:${a.b+1}${m}`},x("span",{class:`${n}-fbox`,"aria-hidden":"true"}),x("p",{class:`${n}-fhead`},x("span",{class:`${n}-ftab`,"aria-hidden":"true"},a.open),x("span",{class:`${n}-flabel`},x("span",{class:t.hidden},`${e.frameWords[a.open]}: `),a.label)));l().push(k),c.push({el:k,a:a.a,b:a.b});continue}if("otherwise"in a){s=null,l().push(x("p",{class:`${n}-felse`},x("span",{class:`${n}-fword`,"aria-hidden":"true"},"else"),x("span",{class:`${n}-flabel`},x("span",{class:t.hidden},`${e.frameWords.else}: `),a.otherwise)));continue}if("close"in a){s=null,c.pop();continue}s||(s=x("ol",{class:`${n}-msgs`,start:a.n}),l().push(s));const r=e.byId.get(a.from),d=e.byId.get(a.to),g=r?.col??1,f=d?.col??1,i=g===f,h=i&&(e.rtl?g!==1:g===e.nodes.length),b=ke(e,a.kind);s.c.push(x("li",{class:`${n}-msg`,"data-kind":a.kind,"data-from":a.from,"data-to":a.to,"data-self":i?h?"start":"end":void 0,style:`--_a:${Math.min(g,f)};--_b:${Math.max(g,f)+1}`},x("span",{class:`${n}-said`},x("span",{class:`${n}-num`},String(a.n)),x("span",{class:`${n}-mlabel`},a.label)),x("span",{class:`${n}-route`},r?.short??a.from," ",x("span",{class:`${n}-to`},Ln(n,a.kind),x("span",{class:t.hidden}," to ")," ",d?.short??a.to,b?` · ${b}`:"")),a.note?x("span",{class:`${n}-note`},a.note):null))}return x("div",{class:`${n}-steps`},o)}function Re(t,e){return Rt(e,`list:${t}`,()=>jn(t,e))}var Bn=Re;function jn(t,e){const n=Math.min(6,e.heading+1),o=f=>x(`h${n}`,{class:`${t}-list-head`},f),c=f=>x("strong",null,f),l=f=>f.href?x("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},c(f.name)):c(f.name),s=f=>x("code",{class:`${t}-code`},f),a=f=>e.byId.get(f)?.name??f,r=f=>{const i=ke(e,f);return i?` (${i})`:""},d=f=>f.focal&&e.legend.focal?` ${Ft(e.legend.focal)}`:"";if(e.type==="architecture"){const f=b=>x("li",null,l(b),b.kind?`, ${b.kind}`:"",b.detail?[". ",b.mono?s(b.detail):b.detail,/[.!?]$/.test(b.detail)?"":"."]:/[.!?]$/.test(b.kind??b.name)?"":".",d(b)),i=[o("Parts")],h=e.nodes.filter(b=>!b.group);h.length&&i.push(x("ul",{class:`${t}-list-items`},h.map(f)));for(const b of e.groups.filter(p=>p.depth===1)){i.push(x("p",{class:`${t}-list-group`},b.label)),b.members.length&&i.push(x("ul",{class:`${t}-list-items`},b.members.map(p=>f(e.byId.get(p)))));for(const p of e.groups.filter(m=>m.parent===b.id))i.push(x("p",{class:`${t}-list-group`,"data-depth":2},p.label)),i.push(x("ul",{class:`${t}-list-items`,"data-depth":2},p.members.map(m=>f(e.byId.get(m)))))}return i.push(o("Connections")),i.push(x("ol",{class:`${t}-list-items`},e.edges.map(b=>x("li",null,c(a(b.from))," to ",c(a(b.to)),b.label?[": ",s(qt(b.label))]:"",`${r(b.kind)}.`)))),i}if(e.type==="flowchart"){const f=i=>(e.byId.get(i)?.i??0)+1;return[x("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const h=e.edges.filter(m=>m.from===i.id),b=i.shape==="decision"?"Decision":i.shape==="terminal"?h.length?"Start":"End":"Step",p=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return x("li",null,l(i),i.detail?[", ",i.mono?s(i.detail):i.detail]:"",`${p}${b}.`,d(i),h.length?x("ul",{class:`${t}-list-exits`},h.map(m=>x("li",null,m.label?`If ${qt(m.label)}: go to ${f(m.to)}, `:`Then: go to ${f(m.to)}, `,c(a(m.to)),r(m.kind)))):null)}))]}if(e.type==="data-flow")return[x("ol",{class:`${t}-list-items`},e.nodes.map(f=>{const i=e.edges.filter(h=>h.from===f.id);return x("li",null,`${f.laneLabel}: `,l(f),f.detail?[", ",f.mono?s(f.detail):f.detail]:"",".",d(f),i.length?[" Then ",...i.flatMap((h,b)=>[b?"; ":"",`to step ${e.byId.get(h.to).step}, `,c(a(h.to)),h.label?[": ",s(qt(h.label))]:"",r(h.kind)]),"."]:"")}))];if(e.type==="sequence"){const f=[o("Participants"),x("ul",{class:`${t}-list-items`},e.nodes.map(h=>x("li",null,c(h.name),h.kind?`, ${h.kind}`:"",".",d(h),Ee(e,h))))];f.push(o("Messages"));let i=null;for(const h of e.steps){if("band"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`},h.band));continue}if("open"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":h.depth>1?h.depth:void 0},`${e.frameWords[h.open]}: ${h.label}`));continue}if("otherwise"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":h.depth>1?h.depth:void 0},`${e.frameWords.else}: ${h.otherwise}`));continue}if("close"in h){i=null;continue}i||(i=x("ol",{class:`${t}-list-items`,start:h.n}),f.push(i)),i.c.push(x("li",null,s(h.label),": ",c(a(h.from))," to ",c(a(h.to)),`${r(h.kind)}.`,h.note?` ${Ft(h.note)}`:""))}return f}const g=[];for(const f of e.nodes)g.push(x(`h${n}`,{class:`${t}-list-group`},f.href?x("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},s(f.name)):s(f.name),d(f))),g.push(x("ul",{class:`${t}-list-items`},[...(f.columns??[]).map(i=>x("li",null,s(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",s(`${i.ref.table}.${i.ref.column}`),i.card?[" (",$n(f.id,i.ref.table,i.card,s),")"]:""]:i.type?`, ${i.type}`:"")),...f.more?[x("li",null,`and ${f.more} more ${f.more===1?"column":"columns"}`)]:[]]));return g}function Te(t,e=!1){const n=t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step";return`${e&&Ut(t)?`Arrow keys move to the nearest ${n} in that direction`:`Arrow keys move to the next or the previous ${n}, in the author's order`}; Home and End go to the ends; Escape clears the trace.${t.nodes.some(c=>c.href)?" Enter opens a part that is a link.":""}`}function ie(t,e=!1){const n=e&&t.type!=="sequence"&&Ut(t)&&t.cols>1&&t.rows>1,o=t.nodes.some(c=>c.href)?[{keys:["Enter"],words:"open"}]:[];return[{keys:n?["←","↑","↓","→"]:["←","→"],words:Ae(t)},{keys:["Home","End"],words:"the ends"},...o,{keys:["Esc"],words:"clear"}]}var Rn=(t,e)=>{for(let n=0;n({col:e.col,rows:[e.row,e.row2]});function Ut(t){return Rt(t,"spatial",()=>{const e=t.nodes.map(l=>({id:l.id,...Tn(t,l)})),n=(l,s)=>{const a=s==="right"||s==="left",r=s==="right"||s==="down",d=b=>a?[b.col,b.col]:b.rows,g=b=>a?b.rows:[b.col,b.col],f=d(l),i=g(l);let h=null;return e.forEach((b,p)=>{if(b===l)return;const m=d(b),k=g(b),L=r?m[0]-f[1]:f[0]-m[1];if(L<1)return;const z=Math.max(0,k[0]-i[1],i[0]-k[1]),v=[z===0?0:1,z===0?L:L+2*z,z,Math.abs(k[0]-i[0]),p];(!h||Rn(v,h.rank))&&(h={id:b.id,rank:v})}),h?.id??null},o=Lt();for(const l of e)o[l.id]={right:n(l,"right"),left:n(l,"left"),down:n(l,"down"),up:n(l,"up")};const c=l=>{const s=new Set([l]),a=[l];for(;a.length;)for(const r of Object.values(o[a.pop()]))r&&!s.has(r)&&(s.add(r),a.push(r));return s.size};return e.every(l=>c(l.id)===e.length)?o:null})}function Xt(t){return Rt(t,"turn-back-lanes",()=>{const e=new Map,n=new Set;if(!le(t))return{lane:e,dropped:n,lanes:0};const o=(r,d)=>(t.byId.get(r)?.row??0)*1e3+d,c=new Map;t.edges.forEach((r,d)=>{const g=`${r.to}.${r.toRow}.${r.card?.to??""}`,f=o(r.from,r.fromRow??0),i=o(r.to,r.toRow??0),h=c.get(g)??{members:[],lo:1/0,hi:-1/0};h.members.push(d),h.lo=Math.min(h.lo,f,i),h.hi=Math.max(h.hi,f,i),c.set(g,h)});const l=[...c.values()].sort((r,d)=>d.hi-d.lo-(r.hi-r.lo)),s=[];let a=0;for(const r of l.reverse()){const d=new Set(s.filter(f=>f.lo<=r.hi&&r.lo<=f.hi).map(f=>f.lane));let g=0;for(;d.has(g);)g++;if(g>1){for(const f of r.members)n.add(f);continue}s.push({lo:r.lo,hi:r.hi,lane:g});for(const f of r.members)e.set(f,g);a=Math.max(a,g+1)}return{lane:e,dropped:n,lanes:a}})}var le=t=>t.type==="schema"&&t.cols===1&&t.edges.length>0;function Yt(t,e,n){const o=n.prefix,c=xn(n.base),l=t.type==="sequence"||t.type==="schema"?null:Ie(t),s={P:o,ids:c,level:n.level,plan:l,hidden:n.hiddenClass},a=e.layout==="drawn",r=Tt(t,e),d=t.type==="sequence"||t.type==="schema"?a:!0,g=`h${t.heading}`,f=[`--_cols:${ae(t)}`];if(t.type==="architecture"&&t.groups.length||a&&e.pad){const i=t.type==="architecture"?Le(t):[0,0,0,0],h=(p,m,k)=>p?p>1?`calc(${p} * var(--basalt-space-${m}))`:`var(--basalt-space-${m})`:k?`var(--basalt-space-${k})`:"0px",b=a&&e.pad?"3":void 0;f.push(`--_gpad:${h(i[0],"8",b)} ${h(i[1],"4")} ${h(i[2],"4",b)} ${h(i[3],"4")}`)}if(l?.gutter&&l.laneCount>2&&f.push(`--_gw:calc(${l.laneCount} * var(--basalt-space-3-5) + var(--basalt-space-3))`),le(t)){const i=t.marks?"var(--basalt-space-6) + var(--basalt-space-1)":"var(--basalt-space-5)",h=Xt(t).lanes>1?`calc(${i} + var(--basalt-space-3))`:t.marks?`calc(${i})`:i;f.push(t.rtl?`--_gpad:0px 0px 0px ${h}`:`--_gpad:0px ${h} 0px 0px`)}return t.type==="schema"&&e.track&&f.push(`--_track:${e.track}px`),x("figure",{class:n.className?`${o} ${n.className}`:o,"aria-labelledby":c.title,"data-type":t.type,"data-cols":ae(t),"data-reach":t.type==="architecture"?qe(t):void 0,"data-gutter":l?.gutter?"":void 0,"data-marks":t.marks?"":void 0,"data-layout":e.layout??(t.unplaced?"stacked":void 0),"data-measured":e.layout?"":void 0,"data-bare":e.bare?"":void 0,"data-motion":t.motion.animated?"animated":void 0,"data-first-visit":t.motion.animated&&t.motion.firstVisit?"":void 0,"data-rtl":t.rtl?"":void 0,"data-viewer":n.viewer?"":void 0,style:f.join(";")},x("div",{class:`${o}-head`},x(g,{id:c.title,class:`${o}-title`},It(t.title)),n.hasSource?x("p",{class:`${o}-source`},x("bdi",null,{slot:"source"})):null),x("div",{class:`${o}-drawing`,style:a&&e.rows?`--_rows:${e.rows};--_row-gap:0px`:void 0,role:d?"group":void 0,"aria-roledescription":d?"diagram":void 0,"aria-labelledby":d?c.title:void 0,"aria-describedby":d?r?`${c.summary} ${c.keys}`:c.summary:void 0,"data-stops":r?"":void 0},In(s,t,e),t.text?null:x("div",{class:`${o}-ink`,"aria-hidden":"true"}),x("span",{class:`${o}-ruler`,"aria-hidden":"true"})),Be(o,t),x("p",{class:`${o}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),Tt(t,e)&&t.type!=="sequence"||a&&t.type==="sequence"?x("p",{class:`${o}-tap-hint`,"aria-hidden":"true"},`Tap ${Ae(t)} to highlight its lines. Tap it again to clear.`):null,x("div",{class:`${o}-foot`},{slot:"toggle"}),x("div",{id:c.list,class:`${o}-list`,hidden:!e.open},Re(o,t)),x("span",{id:c.keys,class:n.hiddenClass},n.viewer?`${Te(t,a)} ${n.viewer}`:Te(t,a)),x("figcaption",{id:c.summary,class:`${o}-summary`},{slot:"summary"}))}function zn(t){const e=getComputedStyle(t),n=(c,l)=>{const s=parseFloat(e.getPropertyValue(`--basalt-${c}`));return Number.isFinite(s)?s:l},o=new Map;return{space:c=>(o.has(c)||o.set(c,n(`space-${c}`,parseFloat(c.replace("-","."))*4)),o.get(c)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4),activation:n("size-diagram-activation",8),foot:n("size-diagram-foot",14)}}var Qt=(t,e)=>t==="main"?e.line:e.hair,xt=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},Ct=(t,e,n=.01)=>t.le.l+n&&t.te.t+n,ce=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function kt(t,e,n){const{l:o,t:c,r:l,b:s}=t.rect,a=(o+l)/2,r=(c+s)/2,d=(l-o)/2,g=(s-c)/2,f=e==="top"||e==="bottom";if(t.shape==="decision"){if(f){const b=n,p=g*Math.max(0,1-Math.abs(b-a)/d);return{x:b,y:e==="top"?r-p:r+p}}const i=n,h=d*Math.max(0,1-Math.abs(i-r)/g);return{x:e==="left"?a-h:a+h,y:i}}if(t.shape==="terminal"){const i=Math.min(d,g);if(f){const m=n,k=Math.min(Math.max(m,o+i),l-i),L=m-k,z=Math.abs(L)>=i?0:Math.sqrt(i*i-L*L);return{x:m,y:Math.abs(L)<1e-6?e==="top"?c:s:e==="top"?r-z:r+z}}const h=n,b=h-r,p=Math.abs(b)>=i?0:Math.sqrt(i*i-b*b);return{x:e==="left"?o+i-p:l-i+p,y:h}}return f?{x:n,y:e==="top"?c:s}:{x:e==="left"?o:l,y:n}}function Nn(t,e,n){const{l:o,t:c,r:l,b:s}=e.rect,a=(o+l)/2,r=(c+s)/2,d=(l-o)/2,g=(s-c)/2;if(e.shape==="decision")return Math.abs(t.x-a)/d+Math.abs(t.y-r)/g<1-n/Math.min(d,g);if(e.shape==="terminal"){const f=Math.min(d,g),i=Math.min(Math.max(t.x,o+f),l-f);return Math.hypot(t.x-i,t.y-r)o+n&&t.xc+n&&t.ymatchMedia("(forced-colors: active)").matches;function Hn(t,e){const n=t.querySelector(`.${e}-ruler`),o=new Map;return(c,l)=>{const s=`${l}|${c}`;return o.has(s)||(n.setAttribute("data-f",l),n.textContent=c,o.set(s,n.getBoundingClientRect().width),n.textContent=""),o.get(s)}}var Pt=t=>t?t.split(/\s+/).filter(Boolean):[];function Dn(t,e,n){const o=e.space;let c=e.node,l=e.table;for(const r of t.nodes){if(r.shape==="table"){for(const p of r.columns??[]){const m=p.ref?`${t.rtl?"←":"→"} ${p.ref.table}`:p.type??"",k=o("6")+n(p.name,"mono")+(m?o("3")+n(m,"mono"):0)+2*o("3")+2*e.hair;l=Math.max(l,Math.ceil(k))}l=Math.max(l,Math.ceil(n(r.name,"table")+2*o("3")+2*e.hair+(r.href?16+o("1-5"):0)));continue}const d=r.shape==="terminal"?2*o("5"):2*o("3"),g=r.mark&&!Fn()?(r.shape==="participant"?2:1)*o("6"):0;let f=0;const i=r.href?16+o("1-5"):0,h=Pt(r.name);if(h.forEach((p,m)=>{f=Math.max(f,n(p,r.shape==="decision"?"name-500":"name")+(r.kind?0:g)+(m===h.length-1?i:0))}),t.type!=="data-flow")for(const p of Pt(r.kind))f=Math.max(f,n(p,"mono")+g);for(const p of Pt(r.detail))f=Math.max(f,n(p,r.mono?"mono":"sans"));const b=r.shape==="decision"?f/.62:f+d+2*e.hair;c=Math.max(c,Math.ceil(b))}const s=ae(t);let a;return t.type==="data-flow"?a=e.lane+s*(c+o("12")):t.type==="schema"?a=s*l+(s-1)*(o("12")+(t.marks?o("3"):0))+(le(t)?(t.marks?o("6")+o("1"):o("5"))+(Xt(t).lanes>1?o("3"):0):0):t.type==="sequence"?a=s*c+(s-1)*o("5"):a=s*c+(s-1)*o("16")+qe(t)*o("4"),{track:c,table:l,least:Math.max(e.wide,a)}}function Ne(t,e,n=!1){const o=n?c=>-Math.round(-c):Math.round;return{x:(c,l)=>l%2===1?o(c+t-.5)+.5-t:o(c+t)-t,y:(c,l)=>l%2===1?Math.round(c+e-.5)+.5-e:Math.round(c+e)-e}}function de(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function We(t,e,n){const o=t.map(l=>({...l}));for(let l=1;l=2){const r=c[c.length-2];if(Math.abs(r.x-a.x)<.01&&Math.abs(a.x-s.x)<.01||Math.abs(r.y-a.y)<.01&&Math.abs(a.y-s.y)<.01){c[c.length-1]=s;continue}}c.push(s)}}return c}var _t=t=>t.slice(1).map((e,n)=>[t[n],e]);function te(t,e,n){const o=[];for(let l=0;lMath.min(p.x,m.x)+.75&&zMath.min(k.y,L.y)+.75&&vl.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),o=(l,s,a)=>{const r=[];let d=s;for(const g of l)r.push([d,d+g]),d+=g+a;return r},c=o(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0);return{cols:o(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:t.style.getPropertyValue("--_rows").trim()?c.filter((l,s)=>s%2===1):c}}var ct=t=>t==="left"||t==="right",Fe={top:"bottom",bottom:"top",left:"right",right:"left"};function fe(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function He(t,e,n){const o=[];t.edges.forEach((l,s)=>{const a=t.byId.get(l.from),r=t.byId.get(l.to),[d,g]=e[s],f=a.row===r.row&&ct(d)&&ct(g)&&d===Fe[g]||a.col===r.col&&!ct(d)&&!ct(g)&&d===Fe[g];o.push({edge:s,end:"from",node:a,side:d,far:r,straight:f,f:.5},{edge:s,end:"to",node:r,side:g,far:a,straight:f,f:.5})});const c=new Map;for(const l of o){const s=`${l.node.id}.${l.side}`;c.has(s)||c.set(s,[]),c.get(s).push(l)}for(const[l,s]of c){if(s[0].node.shape==="decision")continue;const a=p=>ct(p.side)?p.far.row-p.node.row:p.far.col-p.node.col,r=s.filter(p=>p.straight),d=s.filter(p=>!p.straight);if(d.sort((p,m)=>a(p)-a(m)||(ct(p.side)?p.far.col-m.far.col:p.far.row-m.far.row)*(a(p)<0?1:-1)),s.length>3&&n(`${l.replace(".","'s ")} side has ${s.length} lines; more than three is an error: use another side`),!r.length){d.length===2?(d[0].f=.25,d[1].f=.75):d.length===3?(d[0].f=.25,d[1].f=.5,d[2].f=.75):d.length>3&&d.forEach((p,m)=>{p.f=(m+1)/(d.length+1)});continue}const g=new Map;for(const p of r)g.has(p.far.id)||g.set(p.far.id,[]),g.get(p.far.id).push(p);for(const p of g.values())p.length>1&&p.sort((m,k)=>m.edge-k.edge).forEach((m,k)=>{m.f=p.length===2?k===0?.25:.75:(k+1)/(p.length+1)});const f=Math.min(...r.map(p=>p.f)),i=Math.max(...r.map(p=>p.f)),h=d.filter(p=>a(p)<0),b=d.filter(p=>a(p)>=0);h.forEach((p,m)=>{p.f=f*(m+1)/(h.length+1)}),b.forEach((p,m)=>{p.f=i+(1-i)*(m+1)/(b.length+1)})}return o}function De(t,e=8,n=8){return Rt(t,`port-floors:${e}:${n}`,()=>{const o=Lt();if(t.type!=="architecture"&&t.type!=="flowchart"&&t.type!=="data-flow")return o;const c=t.edges.map(s=>{const a=t.byId.get(s.from),r=t.byId.get(s.to),[d,g]=fe(a,r);return[s.fromSide??d,s.toSide??g]}),l=new Map;for(const s of He(t,c,()=>{})){if(!ct(s.side)||s.node.shape!=="box")continue;const a=`${s.node.id}.${s.side}`;l.has(a)||l.set(a,[]),l.get(a).push(s.f)}for(const[s,a]of l){if(a.length<2)continue;const r=a.slice().sort((f,i)=>f-i).filter((f,i,h)=>i===0||f-h[i-1]>1e-9);let d=Math.max(e/r[0],e/(1-r[r.length-1]));for(let f=1;f{const s=t.byId.get(l.dataset.node);s&&c.set(s.id,{id:s.id,rect:xt(l,n),shape:s.shape,i:s.i})}),c}function Ke(t,e){const n=e.head,o=e.head/2,{x:c,y:l}=t.tip;return t.dir==="down"?{l:c-o,r:c+o,t:l-n,b:l}:t.dir==="up"?{l:c-o,r:c+o,t:l,b:l+n}:t.dir==="right"?{l:c-n,r:c,t:l-o,b:l+o}:{l:c,r:c+n,t:l-o,b:l+o}}var ue=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function Ze(t,e,n,o,c=!1){const l=(a,r)=>{const d=a+r-Math.floor(a+r);return d<.005||d>.995?[0]:d<=.5?[-d,1-d]:[1-d,-d]},s=c?l(-t.r,-e).map(a=>-a):l(t.l,e);for(const a of l(t.t,n))for(const r of s){if(!r&&!a)return t;const d={l:t.l+r,r:t.r+r,t:t.t+a,b:t.b+a};if(o(d))return d}return t}function Vn(t,e,n,o,c,l,s,a,r){const d=s.space,g=[],f=[],i=[],h=[],b=d("1"),p=e.filter(m=>t.edges[m.i]?.label).sort((m,k)=>+(t.edges[k.i].kind==="main")-+(t.edges[m.i].kind==="main")||m.i-k.i);for(const m of p){const k=t.edges[m.i].label,L=a(k,"label"),z=16*Kt(k),v=m.pts.length-2,O=[];_t(m.pts).forEach(([q,D],T)=>{const R=Math.abs(q.y-D.y)<.01,H=R?q.x:q.y;let Q=R?D.x:D.y;const at=Math.sign(Q-H)||1;T===v&&(Q-=at*s.head);let it=[[H,Q]];for(const et of c)for(const nt of R?[et.l,et.r]:[et.t,et.b]){const tt=R?q.y:q.x;(R?tt>et.t&&ttet.l&&ttnt>Math.min(u,w)+1&&nt{const tt=(et+nt)/2,$=R?{x:tt,y:q.y}:{x:q.x,y:tt};return!c.some(u=>$.x>u.l&&$.xu.t&&$.y1&&yt(et,nt)?1:0})}),O.sort((q,D)=>D.pri-q.pri||D.len-q.len);let B=null,j=!1;const F=(q,D=!0)=>{const T=ce(q,b);return D&&(q.ll.r||q.tl.b)||n.some(R=>ze(T,R))||g.some(R=>Ct(T,R))||o.heads.some(R=>Ct(T,R))||o.rects.some(R=>Ct(T,R))?!1:!e.some(R=>R.i!==m.i&&_t(R.pts).some(([H,Q])=>Ct(T,ue(H,Q,R.width))))};for(const q of O){for(const D of[1/2,1/3,2/3]){const T=q.p+(q.q-q.p)*D,R=[],H=d("2")+m.width/2;if(q.horiz?(q.len>=L+2*d("1")+d("3-5")&&R.push({box:{l:T-L/2-d("1"),r:T+L/2+d("1"),t:q.c-z/2,b:q.c+z/2},on:!0}),R.push({box:{l:T-L/2,r:T+L/2,t:q.c-H-z,b:q.c-H},on:!1}),R.push({box:{l:T-L/2,r:T+L/2,t:q.c+H,b:q.c+H+z},on:!1})):(q.len>=z+d("3")&&R.push({box:{l:q.c-L/2-d("1"),r:q.c+L/2+d("1"),t:T-z/2,b:T+z/2},on:!0}),R.push({box:{l:q.c+H,r:q.c+H+L,t:T-z/2,b:T+z/2},on:!1}),R.push({box:{l:q.c-H-L,r:q.c-H,t:T-z/2,b:T+z/2},on:!1})),B=R.find(Q=>F(Q.box))??null,B)break;!j&&R.some(Q=>F(Q.box,!1))&&(j=!0)}if(B)break}if(!B){i.push(m.i),j&&h.push(m.i);continue}const rt=Ze(B.box,r.ox,r.oy,q=>F(q));g.push(rt),f.push({i:m.i,text:k,box:rt,on:B.on})}return{labels:f,unseated:i,bounded:h}}function Je(t,e,n,o){const c=[],l=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(s=>{if(s.getClientRects().length===0||getComputedStyle(s).display==="contents")return;const a=xt(s,e);l.push(a),c.push({l:a.l,r:a.r,t:a.t,b:a.t+1},{l:a.l,r:a.r,t:a.b-1,b:a.b},{l:a.l,r:a.l+1,t:a.t,b:a.b},{l:a.r-1,r:a.r,t:a.t,b:a.b});const r=s.querySelector(`:scope > .${n}-glabel`);r&&r.getClientRects().length&&c.push(xt(r,e))}),t.querySelectorAll(`.${n}-lane`).forEach((s,a)=>{if(!s.getClientRects().length)return;const r=xt(s,e);a>0&&c.push({l:r.l,r:r.r,t:r.t-o/2-.5,b:r.t-o/2+.5});const d=s.querySelector(`.${n}-lane-name`);d&&c.push(xt(d,e))}),{obstacles:{rects:c,heads:[]},groups:l}}function Ue(t,e){const{m:o,tk:c,P:l,drawing:s,origin:a,warn:r}=t,d=c.space,g=Ve(o,s,a,l),f=[...g.values()],i=Gn(s),h=a.left-Math.floor(a.left),b=a.top-Math.floor(a.top),p=Ne(h,b),m=s.clientWidth,k=s.clientHeight,L=y=>o.type==="data-flow"?y.col+1:y.col,z=parseFloat(getComputedStyle(s).rowGap)||0,v={w:m,h:k,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:h,oy:b};if(o.type==="sequence")return Zn(t,v,p);let O,B=[];o.type==="schema"?O=o.edges.map(y=>{const S=o.byId.get(y.from),E=o.byId.get(y.to);if(S.col===E.col){const N=!((o.rtl?S.col===1:S.col===o.cols)&&o.cols>1)===!o.rtl?"right":"left";return[N,N]}return E.col>S.col?["right","left"]:["left","right"]}):(O=o.edges.map(y=>{const S=o.byId.get(y.from),E=o.byId.get(y.to),[M,A]=fe(S,E);return[y.fromSide??M,y.toSide??A]}),B=He(o,O,r||(()=>{})));const j=(y,S)=>{const E=s.querySelector(`.${l}-node[data-node="${CSS.escape(y)}"] .${l}-row[data-row="${S}"]`);if(!E)return 0;const M=xt(E,a);return(M.t+M.b)/2},F=new Map;if(o.type==="schema"){const y=new Map;o.edges.forEach((E,M)=>{const A=`${E.to}.${E.toRow}.${O[M][1]}`;y.set(A,[...y.get(A)??[],M])});const S=E=>{const M=o.edges[E].card?.to;return M==="one"?0:M==="zero-or-one"?1:2};for(const E of y.values()){const M=[...new Set(E.map(S))].sort((A,N)=>A-N);if(M.length>1)for(const A of E)F.set(A,(M.indexOf(S(A))-(M.length-1)/2)*d("2"))}}const rt=y=>Math.round(y+h)-h,q=o.edges.map((y,S)=>{const[E,M]=O[S],A=g.get(y.from),N=g.get(y.to),J=Qt(y.kind,c);if(y.fk){const P=j(y.from,y.fromRow),ot=j(y.to,y.toRow)+(F.get(S)??0),gt=p.y(P,J),Bt=p.y(ot,J),Et=E==="right"?A.rect.r:A.rect.l,St=M==="right"?N.rect.r:N.rect.l;return{p1:{x:y.card?rt(Et):Et,y:gt},p2:{x:y.card?rt(St):St,y:Bt},r1:P,r2:Math.abs(gt-Bt)<.01?P:ot}}const K=B.find(P=>P.edge===S&&P.end==="from").f,Y=B.find(P=>P.edge===S&&P.end==="to").f;let U=Ge(A,E,K),Z=Ge(N,M,Y);const W=ct(E)?U.y:U.x;let G=ct(M)?Z.y:Z.x;return ct(E)?U={...U,y:p.y(U.y,J)}:U={...U,x:p.x(U.x,J)},ct(M)?Z={...Z,y:p.y(Z.y,J)}:Z={...Z,x:p.x(Z.x,J)},ct(E)&&ct(M)&&Math.abs(U.y-Z.y)<1.01&&(Z={...Z,y:U.y},G=W),!ct(E)&&!ct(M)&&Math.abs(U.x-Z.x)<1.01&&(Z={...Z,x:U.x},G=W),U=ct(E)?kt(A,E,U.y):kt(A,E,U.x),Z=ct(M)?kt(N,M,Z.y):kt(N,M,Z.x),{p1:U,p2:Z,r1:W,r2:G}}),D=new Set,T=(y,S)=>{D.has(y)||(D.add(y),r?.(`${o.edges[y].from} to ${o.edges[y].to} ${S}, so its line is not drawn; its row still writes the target`))};for(const y of Xt(o).dropped)T(y,"would need a third lane of turn-backs");const R=new Map,H=Lt();o.type==="schema"&&o.edges.forEach((y,S)=>{const E=o.byId.get(y.from),M=o.byId.get(y.to);if(Math.abs(E.col-M.col)<2)return;const A=Math.min(E.col,M.col),N=Math.max(E.col,M.col),J=o.nodes.filter(ot=>ot.col>A&&ot.colgt.row<=ot&>.row2>=ot+1)||Y.push({key:`g${ot}`,y:(K[ot-1][1]+K[ot][0])/2,inner:!0});Y.push({key:"top",y:K[0][0]-d("4"),inner:!1},{key:"bottom",y:K[K.length-1][1]+d("4"),inner:!1});const U=(q[S].r1+q[S].r2)/2,Z=t.pick?.[S]??Y.slice().sort((ot,gt)=>Math.abs(ot.y-U)-Math.abs(gt.y-U)||Number(gt.inner)-Number(ot.inner)||ot.y-gt.y)[0].key;H[S]=Z;const W=O[S][0]==="right"?E.col:E.col-1,G=i.cols[W-1],P=i.cols[W];R.set(S,{corridor:Z,first:G&&P?{key:`c${W}`,span:[G[1],P[0]]}:null,y:0})});const Q=new Map;for(const[y,S]of R){const E=o.edges[y],M=Q.get(S.corridor)??[],A=M.find(N=>{const J=o.edges[N[0]];return J.to===E.to&&J.toRow===E.toRow&&O[N[0]][1]===O[y][1]&&Math.abs(q[N[0]].p2.y-q[y].p2.y)<.5});A?A.push(y):M.length>=2?T(y,"would need a third lane in its corridor"):M.push([y]),Q.set(S.corridor,M)}for(const y of[...R.keys()])D.has(y)&&R.delete(y);const at=y=>{const S=o.edges[y[0]];return Math.abs(o.byId.get(S.from).col-o.byId.get(S.to).col)*1e4+Math.abs(q[y[0]].p1.x-q[y[0]].p2.x)},it=(y,S,E)=>{const M=i.rows;if(y==="top")return M[0][0]-d("4")-S*d("3");if(y==="bottom")return M[M.length-1][1]+d("4")+S*d("3");const A=Number(y.slice(1));return(M[A-1][1]+M[A][0])/2+(S-(E-1)/2)*d("3")},yt=(y,S)=>S.forEach((E,M)=>E.forEach(A=>{R.get(A).y=it(y,M,S.length)})),dt=()=>{for(const[y,S]of Q){const E=S.map(M=>M.filter(A=>R.has(A))).filter(M=>M.length);Q.set(y,E),yt(y,y==="top"||y==="bottom"?E.slice().sort((M,A)=>at(M)-at(A)):E.slice().sort((M,A)=>at(A)-at(M)))}};dt();const et=new Map,nt=new Set,tt=new Map,$=(y,S,E,M,A)=>{et.has(y)||et.set(y,{span:S,vertical:E,members:new Map});const N=et.get(y);N.members.has(M)||N.members.set(M,[]),N.members.get(M).push(A)},u=()=>{et.clear(),nt.clear(),tt.clear(),o.edges.forEach((y,S)=>{if(D.has(S))return;const E=R.get(S);E?.first&&$(E.first.key,E.first.span,!0,`far:${S}`,-(S+1));const[M,A]=O[S],{p1:N,p2:J}=q[S],K=o.byId.get(y.from),Y=o.byId.get(y.to);let U=null,Z=null,W=!1;if(M===A){if(ct(M)){const G=M==="right"?Math.max(L(K),L(Y)):Math.min(L(K),L(Y))-1,P=i.cols[G-1],ot=i.cols[G];P&&ot&&(U=`c${G}`,Z=[P[1],ot[0]],W=!0)}else{const G=M==="bottom"?Math.max(K.row2,Y.row2):Math.min(K.row,Y.row)-1,P=i.rows[G-1],ot=i.rows[G];P&&ot&&(U=`r${G}`,Z=[P[1],ot[0]],W=!1)}U&&nt.add(S)}else if(ct(M)&&ct(A)&&(E||Math.abs(N.y-J.y)>.5)){const G=L(Y),P=A==="left",ot=i.cols[(P?G-1:G)-1],gt=i.cols[(P?G:G+1)-1];ot&>&&(U=`c${P?G-1:G}`,Z=[ot[1],gt[0]],W=!0)}else if(!ct(M)&&!ct(A)&&Math.abs(N.x-J.x)>.5){const P=A==="top"?Y.row-1:Y.row2,ot=i.rows[P-1],gt=i.rows[P];ot&>&&(U=`r${P}`,Z=[ot[1],gt[0]],W=!1)}!U||!Z||(E&&tt.set(S,Z),$(U,Z,W,`${y.to}.${A}.${Math.round(W?J.y:J.x)}`,S))})};u();const w=new Map,C=y=>{const[S,E]=O[y],{p1:M,p2:A}=q[y],N=R.get(y);if(N){const J=tt.get(y),K=w.get(-(y+1))??(N.first?(N.first.span[0]+N.first.span[1])/2:M.x),Y=w.get(y)??(J?(J[0]+J[1])/2:A.x);return[M,{x:K,y:M.y},{x:K,y:N.y},{x:Y,y:N.y},{x:Y,y:A.y},A]}if(ct(S)&&ct(E)){if(S===E){const K=d(o.marks?"6":"4")+(o.type==="schema"&&o.cols===1?(Xt(o).lane.get(y)??0)*d("3"):0),Y=w.get(y)??(S==="right"?Math.max(M.x,A.x)+K:Math.min(M.x,A.x)-K);return[M,{x:Y,y:M.y},{x:Y,y:A.y},A]}if(Math.abs(M.y-A.y)<=.5)return[M,{x:A.x,y:M.y}];const J=w.get(y)??(M.x+A.x)/2;return[M,{x:J,y:M.y},{x:J,y:A.y},A]}if(!ct(S)&&!ct(E)){if(S===E){const K=w.get(y)??(S==="bottom"?Math.max(M.y,A.y)+d("4"):Math.min(M.y,A.y)-d("4"));return[M,{x:M.x,y:K},{x:A.x,y:K},A]}if(Math.abs(M.x-A.x)<=.5)return[M,{x:M.x,y:A.y}];const J=w.get(y)??(M.y+A.y)/2;return[M,{x:M.x,y:J},{x:A.x,y:J},A]}return ct(S)?[M,{x:A.x,y:M.y},A]:[M,{x:M.x,y:A.y},A]},I=y=>{const S=o.edges[y],E=Qt(S.kind,c),M=C(y),A=We(M,E,p);let N;return M.length===A.length&&(N=_t(M).map(([J,K])=>Math.abs(J.y-K.y)<.75?(J.y+K.y)/2:(J.x+K.x)/2),N[0]=q[y].r1,N.length>1&&(N[N.length-1]=q[y].r2)),{i:y,from:S.from,to:S.to,kind:S.kind,pts:A,tip:A[A.length-1],dir:de(A),dot:S.fk&&!S.card?A[0]:void 0,card:S.card,width:E,axes:N}},_=()=>o.edges.flatMap((y,S)=>D.has(S)?[]:[I(S)]);let X=null;const V=y=>{X??(X=_());const S=X.map(E=>y.has(E.i)?I(E.i):E);return{lines:S,score:Kn(S,y)*1e5+te(S,void 0,y).length*1e3+pe(S.filter(E=>y.has(E.i)),f,o).length}},ft=(y,S)=>{const E=y.flatMap(M=>{const A=M<0?-M-1:M,{p1:N,p2:J}=q[A],K=R.get(A);return K?M<0?[N.y,K.y]:[K.y,J.y]:S?[N.y,J.y]:[N.x,J.x]});return[Math.min(...E),Math.max(...E)]},st=y=>y<0?-y-1:y,lt=y=>{const S=[...y.members.values()].map(M=>({members:M,run:ft(M,y.vertical)})).sort((M,A)=>M.run[0]-A.run[0]),E=[];for(const M of S){const A=E[E.length-1];A&&A.some(N=>N.run[0]!(M.length===1&&M[0].members.every(A=>nt.has(A))))},pt=y=>(S,E)=>y[S].run[0]{const S=pt(y),E=[];return y.forEach((M,A)=>{let N=0;for(;E.some((J,K)=>J===N&&S(A,K));)N++;E.push(N)}),E},ut=y=>Math.max(0,...Mt(y))+1;if(o.marks)for(let y=0;y3){S=N.map(J=>J.members.map(st));break}if(!S)break;const E=A=>Math.max(...A),M=S.filter(A=>A.some(N=>R.has(N))).sort((A,N)=>E(N)-E(A))[0]??S.slice().sort((A,N)=>E(N)-E(A))[0];for(const A of M)T(A,"would need a fourth lane in a marked gutter"),R.delete(A);u()}const $t=(y,S,E,M=!1)=>{const A=o.rtl&&M?E-1-S:S,N=y[1]-y[0];if(!o.marks)return y[0]+N/(E+1)*(A+1);const J=c.foot+c.radiusXs,K=E>1?Math.min(N/(E+1),(N-2*J)/(E-1)):0;return(y[0]+y[1])/2+(A-(E-1)/2)*K};dt();for(const[y,S]of Q){if(y==="top"||y==="bottom"||S.length<2)continue;const E=new Set(S.flat());let M=S,A=1/0;for(const N of he(S.slice().sort((J,K)=>at(K)-at(J)))){yt(y,N),X=null;const J=V(E);J.scoreY.members);if(o.marks){const Y=ut(S),U=pt(S),Z=S.length,W=new Set(E.flat().map(st)),G=Et=>Et.forEach((St,zt)=>E[zt].forEach(jt=>w.set(jt,$t(y.span,St,Y,y.vertical))));let P=Mt(S),ot=1/0,gt=null;const Bt=[P];if(Y**Z<=729)for(let Et=0;EtMath.floor(Et/Y**jt)%Y);St.every((zt,jt)=>St.every((ne,Vt)=>Vt<=jt||zt!==ne||!U(jt,Vt)))&&Bt.push(St)}for(const Et of Bt){G(Et);const St=V(W);St.scoreZ.forEach(G=>w.set(G,$t(y.span,W,M,y.vertical))));const U=V(A);U.scoreY.forEach(Z=>w.set(Z,$t(y.span,U,M,y.vertical)))),X=K}if(v.lines=_(),o.marks&&(v.lines=v.lines.filter(y=>{if(!y.card)return!0;const S=_t(y.pts),E=([A,N])=>Math.hypot(N.x-A.x,N.y-A.y),M=S.length===1?2*c.foot:c.foot+c.radiusXs-.5;return E(S[0])>=M&&E(S[S.length-1])>=M?!0:(T(y.i,"has no room for its marks at an end"),R.delete(y.i),!1)})),R.size){const y=new Set([...R.values()].map(E=>E.corridor)),S=[y.has("top")?"var(--basalt-space-8)":"0px"];for(let E=1;E<=o.rows;E++)S.push("auto",EKe(y,c));const vt=Vn(o,v.lines,f,bt,wt,{l:0,t:0,r:m,b:k},c,e,{ox:h,oy:b});return v.labels=vt.labels,v.unseated=vt.unseated,v.bounded=vt.bounded,v.overlaps=[...new Set(Xe(v.lines,null).flat())],v}function Kn(t,e){return Xe(t,e).length}function Xe(t,e){const n=[];for(let o=0;o=a)continue;const[m,k]=i?[r.x,d.x]:[r.y,d.y],[L,z]=i?[g.x,f.x]:[g.y,f.y];Math.min(Math.max(m,k),Math.max(L,z))-Math.max(Math.min(m,k),Math.min(L,z))>1&&n.push([l.i,s.i])}}return n}function*he(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e{const r=a===l.pts.length-1?Math.max(l.width/2,o.head/2):l.width/2;return s.x-r<-.5||s.x+r>e+.5||s.y-r<-.5||s.y+r>n+.5})&&c.push(l.i);return c}function pe(t,e,n){const o=[];for(const c of t){const l=_t(c.pts);e.some(s=>l.some(([a,r])=>Wn(a,r,s)))&&o.push(c.i)}return o}function Zn(t,e,n){const{m:o,tk:c,P:l,drawing:s,origin:a}=t,r=c.space,d=new Map;s.querySelectorAll(`.${l}-node`).forEach(v=>d.set(v.dataset.node,xt(v,a)));const g=s.querySelector(`.${l}-steps`),f=g?xt(g,a).b:e.h,i=v=>{const O=d.get(v);return O?n.x((O.l+O.r)/2,c.hair):0};for(const v of o.nodes){const O=d.get(v.id);O&&e.lifelines.push({x:i(v.id),y1:O.b,y2:f})}const h=v=>d.get(v.id),b=new Map;s.querySelectorAll(`.${l}-msg`).forEach(v=>{const O=xt(v,a);b.set(Number(v.querySelector(`.${l}-num`)?.textContent??0),(O.t+O.b)/2)});const p=c.activation,m=p/2,k=v=>{const O=o.byId.get(v.who);if(!O)return null;const B=i(v.who),F=(O.i===o.nodes.length-1&&o.nodes.length>1?-1:1)*(o.rtl?-1:1),rt=(v.depth-1)*r("1")*F,q=b.get(v.from)??0,D=b.get(v.to)??q,T=v.from===v.to;return{l:n.x(B-m+rt,c.hair),r:n.x(B+m+rt,c.hair),t:n.y(T?q-r("2")-r("1"):q,c.hair),b:n.y(T?q+r("2")+r("1"):D,c.hair)}},L=o.bars.map(v=>({bar:v,rect:k(v)})).filter(v=>v.rect);e.bars=L.map(v=>v.rect);const z=(v,O,B)=>L.filter(({bar:j})=>j.who===v&&j.to>=O&&(B?j.from<=O:j.fromF.bar.depth-j.bar.depth)[0]?.rect;s.querySelectorAll(`.${l}-msg`).forEach(v=>{const O=v.dataset.from,B=v.dataset.to,j=v.dataset.kind??"plain",F=Qt(j,c),rt=xt(v,a),q=n.y((rt.t+rt.b)/2,F),D=Number(v.querySelector(`.${l}-num`)?.textContent??0);let T=i(O),R=i(B),H;if(O===B){const nt=v.dataset.self==="start"?-r("6"):r("6"),tt=z(O,D,!0),$=tt?nt>0?tt.r:tt.l:T,u=n.y(q-r("2"),F),w=n.y(q+r("2"),F);H=[{x:$,y:u},{x:n.x(T+nt,F),y:u},{x:n.x(T+nt,F),y:w},{x:$,y:w}]}else{const nt=R>T?1:-1,tt=z(O,D,!1),$=z(B,D,!0);tt&&(T=nt>0?tt.r:tt.l),$&&(R=nt>0?$.l:$.r),H=[{x:T,y:q},{x:R,y:q}]}e.lines.push({i:D,from:O,to:B,kind:j,pts:H,tip:H[H.length-1],dir:de(H),width:F});const Q=v.querySelector(`.${l}-said`),at=v.querySelector(`.${l}-note`),it=o.byId.get(O),yt=o.byId.get(B);if(!it||!yt)return;const dt=O===B?(()=>{const nt=o.nodes.find($=>$.col===it.col+(v.dataset.self==="start"?-1:1)),tt=nt?i(nt.id):v.dataset.self==="start"?0:e.w;return Math.abs(tt-T)-r("6")-r("2-5")-r("2")})():Math.abs(R-T)-2*r("2");Math.max(Q?Q.getBoundingClientRect().width:0,at?at.getBoundingClientRect().width:0)>dt+.5&&e.unseated.push(D)}),s.querySelectorAll(`.${l}-fhead`).forEach(v=>{const O=v.parentElement?.querySelector(`:scope > .${l}-fbox`);if(!O)return;[...v.children].reduce((j,F)=>j+F.getBoundingClientRect().width,0)+r("3")>O.getBoundingClientRect().width+.5&&(e.misfit??(e.misfit=[])).push(`the frame "${v.querySelector(`.${l}-flabel`)?.textContent??""}" is wider than its participants`)});{const v=[...s.querySelectorAll(`.${l}-fbox`)].flatMap(O=>{const B=xt(O,a);return[{x:B.l+.5,t:B.t,b:B.b},{x:B.r-.5,t:B.t,b:B.b}]});v.length&&s.querySelectorAll(`.${l}-said, .${l}-note, .${l}-band > span`).forEach(O=>{if(!O.getClientRects().length)return;const B=ce(xt(O,a),r("1"));v.some(j=>B.lj.x&&B.tj.t)&&(e.misfit??(e.misfit=[])).push(`"${O.textContent?.trim()??""}" would lie on a frame's side`)})}return e}function Jn(t,e,n,o,c){const l=[];for(const[s,a]of t){if(!a.getClientRects().length)continue;const r=xt(a,n),d=xt(s,n),g=getComputedStyle(a),f=getComputedStyle(s),i={l:r.l+(parseFloat(g.paddingLeft)||0),r:r.r-(parseFloat(g.paddingRight)||0)},h=i.r-i.l,b=d.l+(parseFloat(f.borderLeftWidth)||0),p=d.r-(parseFloat(f.borderRightWidth)||0),m=[];for(const j of e)for(const[F,rt]of _t(j.pts)){const q=ue(F,rt,j.width);q.tr.t&&m.push({l:q.l,r:q.r})}const k=c("2-5"),L=j=>m.every(F=>F.r<=j-k+.01||F.l>=j+h+k-.01);if(L(i.l))continue;const z=m.map(j=>o?i.r-(j.l-k):j.r+k-i.l).filter(j=>j>0).sort((j,F)=>j-F),v=j=>o?i.l-j:i.l+j,O=j=>o?v(j)>=b+c("3")-.01:v(j)+h<=p-c("3")+.01,B=z.find(j=>O(j)&&L(v(j)));if(B===void 0){l.push(a.textContent??"");continue}a.style.setProperty("--_gx",`${Math.round(B*100)/100}px`)}return l}function Qe(t,e,n,o=Lt()){const{m:c,tk:l,P:s,drawing:a,origin:r}=t,d=l.space,g=Ve(c,a,r,s),f=[...g.values()],i=r.left-Math.floor(r.left),h=r.top-Math.floor(r.top),b=Ne(i,h,!!c.rtl),p=a.clientWidth,m=a.clientHeight,k={w:p,h:m,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:i,oy:h},L=Lt();if(c.type==="sequence"||c.type==="schema")return{geo:k,grow:L};const z=!!c.rtl,v=z?-1:1,O=u=>z?u.r:u.l,B=u=>z?u.l:u.r,j=z?"left":"right",F=(u,w,C,I)=>{const _=u+I*v*w,X=_+I*v*C;return{l:Math.min(_,X),r:Math.max(_,X)}},rt=getComputedStyle(a),q=z?parseFloat(rt.paddingLeft)||0:p-(parseFloat(rt.paddingRight)||0),D=(u,w,C)=>{const I=[u];for(let _=1;_<=(Ot(o,w)??0);_++)I.push({...u,t:u.t+C*d("4")*_,b:u.b+C*d("4")*_});return I},T=new Map;a.querySelectorAll(`.${s}-node`).forEach(u=>{const w=u.parentElement,C=xt(w,r),I=getComputedStyle(w);T.set(u.dataset.node,z?C.l+(parseFloat(I.paddingLeft)||0)+(parseFloat(I.borderLeftWidth)||0):C.r-(parseFloat(I.paddingRight)||0)-(parseFloat(I.borderRightWidth)||0))});const R=c.nodes,H=u=>g.get(R[u].id),Q=new Map;a.querySelectorAll(`.${s}-group > .${s}-glabel`).forEach(u=>{u.style.removeProperty("--_gx"),Q.set(u.parentElement,u)});const at=new Map;for(const[u,w]of Q)w.getClientRects().length&&at.set(u,xt(w,r));const it=u=>{const w=a.querySelector(`.${s}-node[data-node="${CSS.escape(u)}"]`),C=w?.parentElement;return!!(C?.matches(`.${s}-group[data-turn]`)&&C.querySelector(`:scope > .${s}-node`)===w)},yt=(u,w,C)=>it(w)?Array.from({length:Math.round(C/16)+1},(I,_)=>({...u,t:u.t-_*d("4"),b:u.b-_*d("4")})):[u],dt=[],et=u=>Qt(c.edges[u].kind,l);c.edges.forEach((u,w)=>{const C=n.routes[w],I=g.get(u.from),_=g.get(u.to),X=et(w);let V=[];const ft=u.label,st=ft?e(ft,"label"):0,lt=ft?16*Kt(ft):16,pt=d("4");if(C==="down"||C==="up"){const ut=Math.max(I.rect.l,_.rect.l),$t=Math.min(I.rect.r,_.rect.r),bt=c.edges.map((S,E)=>({o:S,j:E})).filter(({o:S,j:E})=>(n.routes[E]==="down"||n.routes[E]==="up")&&(S.from===u.from&&S.to===u.to||S.from===u.to&&S.to===u.from)),wt=bt.findIndex(S=>S.j===w),vt=bt.length<2?.5:bt.length===2?wt===0?.25:.75:(wt+1)/(bt.length+1);let y=b.x(ut+($t-ut)*vt,X);if(C==="down"){const S=a.querySelector(`.${s}-node[data-node="${CSS.escape(u.to)}"]`),E=S?.parentElement,M=E&&E.matches(`.${s}-group`)&&E.querySelector(`:scope > .${s}-node`)===S?at.get(E):void 0;if(M&&E&&!E.contains(a.querySelector(`.${s}-node[data-node="${CSS.escape(u.from)}"]`))){const A=d("2-5")+X/2;if(y>M.l-A&&y=ut+d("6"):N<=$t-d("6"))&&(y=b.x(N,X))}}}if(V=C==="down"?[kt(I,"bottom",y),kt(_,"top",y)]:[kt(I,"top",y),kt(_,"bottom",y)],ft){let S=Math.min(V[0].y,V[1].y),E=Math.max(V[0].y,V[1].y);C==="down"?E-=l.head:S+=l.head;const M=[...a.querySelectorAll(`.${s}-group`)].map(K=>xt(K,r));let A=[[S,E]];for(const K of M)for(const Y of[K.t,K.b])A=A.flatMap(([U,Z])=>Y>U+1&&YM.some(U=>(K+Y)/2>U.t&&(K+Y)/2U.l&&y1){const K=A.filter(([U,Z])=>!N(U,Z));[S,E]=(K.length?K:A).reduce((U,Z)=>Z[1]-Z[0]>U[1]-U[0]?Z:U)}const J=[1/2,1/3,2/3].map(K=>{const Y=S+(E-S)*K;return{l:y-st/2-d("1"),r:y+st/2+d("1"),t:Y-lt/2,b:Y+lt/2}});dt.push({k:w,cands:J,on:!0,card:C==="down"?u.to:u.from})}}else if(C==="trunk"||C==="rail"){const ut=C==="rail"?z?Math.min(I.rect.r,_.rect.r):Math.max(I.rect.l,_.rect.l):O(I.rect),$t=b.x(ut+v*d(C==="trunk"?"8":"3"),X),bt=kt(I,"bottom",$t);if(C==="rail"){if(V=[bt,kt(_,"top",$t)],ft){const wt=_.rect.t-d("6");dt.push({k:w,cands:D({...F($t,d("2-5"),st,1),t:wt-lt/2,b:wt+lt/2},u.to,-1),on:!1,card:u.to})}}else{const wt=b.x(O(_.rect)+v*d("6"),X),vt=b.y(_.rect.t-pt,X);V=[bt,{x:$t,y:vt},{x:wt,y:vt},kt(_,"top",wt)];const y={...F(wt,d("2-5"),st,1),t:vt-lt/2,b:vt+lt/2};ft&&dt.push({k:w,cands:[...yt(y,u.to,lt),...D(y,u.to,-1).slice(1)],on:!1,card:u.to})}}else{const ut=Z=>T.get(Z)??(z?0:p),$t=z?Math.max(ut(u.from),ut(u.to)):Math.min(ut(u.from),ut(u.to)),bt=b.x(n.gutter?q+v*(n.lanes[w]+1)*d("3-5"):$t-v*d("2-5"),X),wt=b.y(I.rect.t+(I.rect.b-I.rect.t)*n.exits[w],X),vt=kt(I,j,wt),y=C==="end-down",S=c.edges.map((Z,W)=>({o:Z,j:W})).filter(({o:Z,j:W})=>n.routes[W]===C&&Z.to===u.to).sort((Z,W)=>n.lanes[W.j]-n.lanes[Z.j]||Z.j-W.j),E=Math.max(0,S.findIndex(({j:Z})=>Z===w)),M=B(_.rect)-v*(d("6")+E*d("3")),A=B(_.rect)-v*(d("6")+(S.length-1)*d("3")),N=b.x(M,X),J=y?_.rect.t-pt-E*d("5"):_.rect.b+pt+E*d("5"),K=b.y(J,X);V=[vt,{x:bt,y:vt.y},{x:bt,y:K},{x:N,y:K},kt(_,y?"top":"bottom",N)];const Y=y?u.to:R[_.i+1]?.id??u.to,U={...F(A,d("2-5"),st,-1),t:J-lt/2,b:J+lt/2};ft&&dt.push({k:w,cands:[...y?yt(U,Y,lt):[U],...D(U,Y,y?-1:1).slice(1)],on:!1,card:Y})}const Mt=We(V,X,b);k.lines.push({i:w,from:u.from,to:u.to,kind:u.kind,pts:Mt,tip:Mt[Mt.length-1],dir:de(Mt),width:X})}),k.crossings=te(k.lines),k.through=pe(k.lines,f,c),k.outside=Ye(k.lines,p,m,l),k.seatless=Jn(Q,k.lines,r,z,d);const{obstacles:nt}=Je(a,r,s,0);nt.heads=k.lines.map(u=>Ke(u,l));const tt=[],$={l:0,t:0,r:p,b:m};for(const u of dt){const w=_=>{const X=ce(_,d("1"));return _.l<$.l-.5||_.r>$.r+.5||_.t<$.t-.5||_.b>$.b+.5||f.some(V=>ze(X,V))||tt.some(V=>Ct(X,V))||nt.heads.some(V=>Ct(X,V))||nt.rects.some(V=>Ct(X,V))||k.lines.some(V=>V.i!==u.k&&_t(V.pts).some(([ft,st])=>Ct(X,ue(ft,st,V.width))))},C=u.cands.find(_=>!w(_));C||(L[u.card]=(L[u.card]??0)+1,k.unseated.push(u.k));const I=C?Ze(C,i,h,_=>!w(_),z):u.cands[0];tt.push(I),k.labels.push({i:u.k,text:c.edges[u.k].label,box:I,on:u.on})}return{geo:k,grow:L}}function Pe(t,e,n=0){const o=s=>String(Math.round(s*100)/100);let c=`M${o(t[0].x)} ${o(t[0].y)}`;for(let s=1;s{const{crow:D,ring:T}=Oe(j,F.x,F.y,rt,n.head,n.dot);return`${T?``:""}`};return`${B(e.card.from,v,Math.sign(O.x-v.x)||1,"from")}${B(e.card.to,e.tip,-l.x||1,"to")}`}const s=e.kind==="dashed",a=n.head,r=n.head/2,d=s?1:a-1,g=e.pts.map(v=>({...v})),f=g[g.length-1];f.x-=l.x*d,f.y-=l.y*d;const i=e.tip.x-l.x*a,h=e.tip.y-l.y*a,b=-l.y*r,p=l.x*r,m=v=>Math.round(v*100)/100,k=mt(e.kind),L=s?``:``,z=e.dot?``:"";return`${L}${z}`}function tn(t,e,n,o){const c=new Map,l=new Map;for(const a of e.crossings)l.has(a.under)||l.set(a.under,[]),l.get(a.under).push(a);let s="";for(const[a,r]of l){const d=`${o}-cut-${a}`;c.set(a,d);const g=r.map(f=>{const i=e.lines[f.top],h=e.lines[f.under],b=i.width/2+n.cut,p=h.width/2+1;return f.underVertical?``:``}).join("");s+=`${g}`}return{defs:s,ids:c}}function en(t,e,n,o){const{defs:c,ids:l}=tn(t,e,n,o),s=e.lifelines.map(i=>``).join(""),a=(e.bars??[]).map(i=>``).join(""),r=e.lines.map((i,h)=>Xn(t,i,n,l.get(h)??null,i.from===i.to?n.radiusXs:n.radius)).join(""),g=`${s?``:""}`,f=e.labels.map(i=>`1?' data-lines="2"':""} style="left:${Math.round(i.box.l*100)/100}px;top:${Math.round(i.box.t*100)/100}px;width:${Math.round((i.box.r-i.box.l)*100)/100}px">${i.text.split(`
-`).map(mt).join("
")}`).join("");return g+f}function ge(t,e,n,o,c,l,s,a){const d=t.querySelector(`.${n}-drawing`);if(!d||t.clientWidth===0)return{dyn:c,geo:null,ink:"",tokens:null};const g=zn(t),f=Hn(d,n),i=Dn(e,g,f);a?.(i.least);const h=t.clientWidth,b=(()=>{const q=document.activeElement;return q&&d.contains(q)&&q.dataset.node?q.dataset.node:void 0})(),p=q=>Tt(e,q)?{...q,stop:q.stop&&e.byId.has(q.stop)?q.stop:e.nodes[0]?.id,keep:void 0}:{...q,stop:q.stop??e.nodes[0]?.id,keep:b&&q.layout!=="drawn"?b:void 0};let m=!1;const k=q=>{if(m=!1,e.type!=="flowchart")return q;l({...q,heights:void 0,words:void 0});const D=Lt(),T=Lt();return d.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(R=>{const H=R.querySelector(`.${n}-words`);if(!H)return;const Q=R.getBoundingClientRect(),at=dt=>{const et={w:dt.width+2*g.space("2-5"),h:dt.height+2*g.space("2")},nt=1-et.w/Q.width,tt=nt>.05?et.h/2/nt:et.h*10;return Math.max(g.space("16"),Math.ceil(Q.width/5),Math.ceil(2*tt))},it=H.getBoundingClientRect();let yt=at(it);if(yt>Q.width){const dt=$=>(R.style.setProperty("--_ww",`${$}px`),H.getBoundingClientRect()),et=Math.floor(R.clientWidth-2*g.space("2-5"));let nt=Math.ceil(it.width),tt=it.height;for(;nt1;){const I=$+u>>1;dt(I).heightQ.width&&(m=!0)}),{...q,heights:D,words:Object.keys(T).length?T:void 0}},L=()=>({m:e,tk:g,P:n,drawing:d,origin:d.getBoundingClientRect(),warn:s}),z=c.autoOpen?{open:!1,autoOpen:void 0}:{},v=(q,D)=>D.map(T=>Gt(e,q.lines.find(R=>R.i===T))).join(", ");if(e.text)return{dyn:{...c,layout:"stacked",bare:void 0},geo:null,ink:"",tokens:g,least:i.least};if(h>=i.least&&!e.unplaced){const q=H=>{let Q=p({...c,...z,layout:"drawn",grow:void 0,track:void 0,bare:void 0,pad:H||void 0,rows:void 0});Q=k(Q),l(Q);let at=Ue(L(),f);return at.corridors&&(Q={...Q,rows:at.corridors.rows},l(Q),at=Ue({...L(),pick:at.corridors.pick},f)),{dd:Q,g:at}};let{dd:D,g:T}=q(!1);const R=H=>H.through.length>0||H.outside.length>0||(H.overlaps?.length??0)>0||(H.misfit?.length??0)>0||m;if(!R(T)&&T.unseated.length&&T.unseated.every(H=>T.bounded?.includes(H))){const H=q(!0);!R(H.g)&&!H.g.unseated.length&&({dd:D,g:T}=H)}if(!R(T)&&!T.unseated.length)return T.crossings.length&&s?.(`${T.crossings.length} crossing${T.crossings.length===1?"":"s"} in the drawn layout: ${T.crossings.map(H=>`${Gt(e,T.lines[H.top])} over ${Gt(e,T.lines[H.under])}`).join("; ")}`),{dyn:D,geo:T,ink:en(n,T,g,o),tokens:g,least:i.least};m&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: a decision would be taller than it is wide`),T.misfit?.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${T.misfit.join("; ")}`),T.through.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.through)} would pass through a node`),T.overlaps?.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.overlaps)} would lie on one another`),T.outside.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.outside)} would leave the drawing`),T.unseated.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: no clean seat for ${T.unseated.map(H=>e.type==="sequence"?`message ${H}`:`"${qt(e.edges[H]?.label??"")}"`).join(", ")}`)}let O=p({...c,...z,layout:"stacked",heights:void 0,grow:Lt(),track:e.type==="schema"?i.table:void 0,bare:void 0,pad:void 0,rows:void 0});if(O=k(O),l(O),e.type==="sequence"||e.type==="schema")return{dyn:O,geo:null,ink:"",tokens:g,least:i.least};const B=Ie(e);let j=Qe(L(),f,B,O.grow);for(let q=0;q<6&&Object.keys(j.grow).length;q++){const D=Lt(O.grow);for(const[T,R]of Object.entries(j.grow))D[T]=(Ot(D,T)??0)+R;O={...O,grow:D},l(O),j=Qe(L(),f,B,D)}const F=j.geo;if(!B.third&&B.laneCount>2&&s?.(`the stacked drawing uses ${B.laneCount} end lanes (four at most)`),F.unseated.length>0||F.through.length>0||F.outside.length>0||B.third){F.unseated.length&&s?.(`the stacked drawing has no clean seat for ${[...new Set(F.unseated)].map(T=>`"${qt(e.edges[T]?.label??"")}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),F.through.length&&s?.(`in the stacked drawing ${v(F,F.through)} would pass through a node, so its lines are not drawn`),F.outside.length&&s?.(`in the stacked drawing ${v(F,F.outside)} would leave the drawing, so its lines are not drawn`),B.third&&s?.("the stacked drawing would need a fifth end lane, so its lines are not drawn","error");const q={...F,lines:[],labels:[],crossings:[]};d.querySelectorAll(`.${n}-group > .${n}-glabel`).forEach(T=>T.style.removeProperty("--_gx"));const D=p({...O,grow:Lt(),bare:!0,open:c.bare?c.open:!0,autoOpen:c.bare?c.autoOpen:c.open?void 0:!0});return l(D),{dyn:D,geo:q,ink:"",tokens:g,least:i.least}}return F.seatless?.length&&s?.(`a stacked group's label has no clear seat on its top edge: ${F.seatless.map(q=>`"${q}"`).join(", ")}`),F.crossings.length&&s?.(`${F.crossings.length} crossing${F.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${F.crossings.map(q=>`${Gt(e,F.lines[q.top])} over ${Gt(e,F.lines[q.under])}`).join("; ")}`),{dyn:O,geo:F,ink:en(n,F,g,o),tokens:g,least:i.least}}function Gt(t,e){const n=t.byId.get(e.from)?.name??e.from,o=t.byId.get(e.to)?.name??e.to;return`${n} to ${o}`}function Yn(t,e,n,o,c,l){const s=new Set;if(l){s.add(l);for(const p of n?.lines??[])p.from===l&&s.add(p.to),p.to===l&&s.add(p.from)}if(t.toggleAttribute("data-tracing",!!l),t.querySelectorAll(`.${e}-node`).forEach(p=>p.toggleAttribute("data-near",s.has(p.dataset.node))),!n||!o)return;const a=p=>!!l&&(p.from===l||p.to===l),r=t.querySelector(`.${e}-edges`),d=new Map;t.querySelectorAll(`.${e}-edge`).forEach(p=>d.set(p.getAttribute("data-edge"),p));for(const p of n.lines){const m=d.get(String(p.i));m&&(m.toggleAttribute("data-lit",a(p)),m.toggleAttribute("data-dim",!!l&&!a(p)))}if(t.querySelectorAll(`.${e}-label`).forEach(p=>{const m=n.lines.find(k=>String(k.i)===p.dataset.edge);p.toggleAttribute("data-lit",!!(m&&a(m)))}),r){for(const p of n.lines)if(a(p)){const m=d.get(String(p.i));m&&r.appendChild(m)}}const g=te(n.lines,a),{defs:f,ids:i}=tn(e,{...n,crossings:g},o,c),h=t.querySelector(`.${e}-svg`);if(!h)return;let b=h.querySelector("defs");!b&&f&&(b=document.createElementNS("http://www.w3.org/2000/svg","defs"),h.insertBefore(b,h.firstChild)),b&&(b.innerHTML=f),n.lines.forEach((p,m)=>{const k=d.get(String(p.i))?.querySelector(`.${e}-line`);if(!k)return;const L=i.get(m);L?k.setAttribute("mask",`url(#${L})`):k.removeAttribute("mask")})}var Qn=()=>matchMedia("(prefers-reduced-motion: reduce), (forced-colors: active), print").matches||document.documentElement.getAttribute("data-loops")==="held";function Pn(t,e){const n=t.getAttribute("data-entrance");if(!(n==="running"||n==="done")){if(!e){n&&t.removeAttribute("data-entrance");return}n||t.setAttribute("data-entrance",Qn()||eo(t)?"done":"pending")}}var to=t=>`basalt-diagram-entrance:${location.pathname}#${t.id}`;function eo(t){if(!t.hasAttribute("data-first-visit")||!t.id)return!1;try{return localStorage.getItem(to(t))!==null}catch{return!1}}function nn(t){const e=t.getAttribute("data-entrance");e!=="pending"&&e!=="running"||(t.setAttribute("data-entrance","done"),t.dispatchEvent(new Event("basalt-diagram-settle")))}function no(t,e,n,o=!1,c=!1){const l=o?Ut(t):null;if(l&&n.startsWith("Arrow")){const d={ArrowRight:c?"left":"right",ArrowLeft:c?"right":"left",ArrowDown:"down",ArrowUp:"up"}[n];return d?l[e]?.[d]??null:null}const s=t.byId.get(e)?.i??0,a=t.nodes.length;let r;if(n==="ArrowRight"||n==="ArrowDown")r=s+1;else if(n==="ArrowLeft"||n==="ArrowUp")r=s-1;else if(n==="Home")r=0;else if(n==="End")r=a-1;else return null;return t.nodes[Math.max(0,Math.min(a-1,r))].id}var oo=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden","data-art"],on=["data-layout","data-measured","data-bare","data-motion","data-first-visit","data-rtl","data-cols","data-reach","data-gutter","data-marks"],so=["--_track","--_h","--_ww","--_gap","--_ggrow","--_tl","--_gpad","--_gw","--_mh","--_rows","--_row-gap"],sn=t=>t==null||t===!1;function ao(t,e){if(t.tagName.toLowerCase()!==e.t)return!1;const n=typeof e.a.class=="string"?e.a.class.split(" ")[0]:"";return!n||t.classList.contains(n)}function ee(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const o=n?on:oo;for(const s of o)sn(e.a[s])&&t.removeAttribute(s);for(const[s,a]of Object.entries(e.a)){if(s==="class")continue;if(s==="style"){const d=t.style,g=new Map(String(a??"").split(";").map(f=>{const i=f.indexOf(":");return[f.slice(0,i).trim(),f.slice(i+1).trim()]}).filter(([f])=>f));for(const[f,i]of g)d.getPropertyValue(f).trim()!==i&&d.setProperty(f,i);for(const f of so)g.has(f)||d.removeProperty(f);continue}if(n&&!on.includes(s))continue;if(sn(a)){t.removeAttribute(s);continue}const r=a===!0?"":String(a);t.getAttribute(s)!==r&&t.setAttribute(s,r)}if(e.t==="svg"||typeof e.a.class=="string"&&/-(ink|ruler)$/.test(e.a.class)||e.c.some(s=>typeof s!="string"&&"slot"in s))return;const c=[...t.children];let l=0;for(const s of e.c)if(!(typeof s=="string"||"slot"in s)){for(let a=l;at.querySelector(`.${e}-node[data-node="${CSS.escape(l)}"]`);n&&c(n)?.setAttribute("tabindex","-1"),c(o)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",o=0;function c(i,h,b){return{prefix:n,base:i,hasSource:h.source!==void 0&&h.source!==null&&h.source!=="",hiddenClass:"visually-hidden",viewer:b?b.keys:void 0}}function l(i,h,b,p){var m=function(k){return''+mt(k)+""};return{source:mt(String(h.source||"")),summary:mt(String(h.summary||"")),hint:ie(i).map(function(k){return""+k.keys.map(m).join(" ")+" "+mt(k.words)+""}).join(""),toggle:'"}}function s(i,h,b){for(var p=i.layout==="auto"&&(i.type==="architecture"||i.type==="flowchart"||i.type==="schema"),m=p?Array.isArray(i.placement)?i.placement:i.placement?[i.placement]:[]:[],k=i.direction||(i.type==="flowchart"?"down":"right"),L=null,z=0;z");return{open:B.slice(0,j+1),inner:B.slice(j+1,B.length-9),warnings:v.errors.map(function(F){return"error: "+F}).concat(v.warnings)}}var a=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-marks","data-layout","data-measured","data-bare"],r=["--_cols","--_gpad","--_track"];function d(i,h,b,p){i.__diagram&&i.__diagram.stop();var m=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),k=getComputedStyle(i).direction==="rtl",L=h.layout==="auto"&&(h.type==="architecture"||h.type==="flowchart"||h.type==="schema"),z=L?Array.isArray(h.placement)?h.placement:h.placement?[h.placement]:[]:[];L&&!z.length&&console.warn('Basalt diagram: "layout": "auto" needs a placement, which compose.mjs writes at build time; drawn from script, place it with placeDiagram (@srasyndicate/basalt/diagram-layout) and pass "placement". The figure is stacked');var v=h.direction?[h.direction]:h.type==="flowchart"?["down","right"]:["right","down"],O=function(W){for(var G=0;G .diagram-drawing")){if(!m||!i.querySelector("#"+CSS.escape(m+"-title"))){for(;document.getElementById("dg"+ ++o+"-title"););m="dg"+o}var j=s(h,m,p),F=document.createElement("div");F.innerHTML=j.open+"";var rt=F.firstChild;a.forEach(function(W){i.removeAttribute(W)}),r.forEach(function(W){i.style.removeProperty(W)});for(var q=0;q :not(script[data-diagram])").forEach(function(W){W.remove()}),i.insertAdjacentHTML("beforeend",j.inner)}B.warnings.forEach(function(W){console.warn("Basalt diagram: "+W)}),B.errors.forEach(function(W){console.error("Basalt diagram: "+W)}),B.motion.animated&&B.motion.firstVisit&&!i.id&&console.error('Basalt diagram: "entrance": "first-visit" needs an id on the figure: without one the entrance plays on every visit');var T=c(m,h,p),R={},H=null,Q=null,at=null,it=null,yt=Object.create(null),dt=function(W,G){yt[W]||(yt[W]=1,(G==="error"?console.error:console.warn)("Basalt diagram: "+W))},et=function(W){ee(i,Yt(B,W,T))},nt=i.querySelector(".diagram-ink"),tt=i.querySelector(".diagram-toggle"),$=!p&&B.motion.animated&&typeof e.diagramMotion=="function",u=null,w=null,C=function(){$&&nn(i)};function I(){Yn(i,n,H&&H.geo,H&&H.tokens,m,Q||it||at),V()}var _=null,X=!p&&matchMedia("(hover: none), (pointer: coarse)").matches;function V(){var W=X&&!p&&nt&&nt.innerHTML!=="";if(i.toggleAttribute("data-touch",!!(X&&!p)),W&&!_){var G=i.querySelector(":scope > .diagram-foot");if(!G)return;_=document.createElement("button"),_.type="button",_.className="btn diagram-clear",_.setAttribute("data-variant","secondary"),_.setAttribute("data-size","sm"),_.innerHTML="Clear highlight",_.addEventListener("click",function(){it&&(it=null,I())}),G.appendChild(_)}else!W&&_&&(_.remove(),_=null);_&&_!==_.parentNode.lastElementChild&&document.activeElement!==_&&_.parentNode.appendChild(_),_&&(it?_.removeAttribute("aria-disabled"):_.setAttribute("aria-disabled","true"))}function ft(W){if(!W.defaultPrevented){var G=bn(i,n,W,it);G!==void 0&&(C(),X=!0,it=G,I())}}function st(){tt&&(tt.setAttribute("aria-expanded",String(!!R.open)),tt.firstElementChild.textContent=R.open?"Hide the list":"View as list")}function lt(){if(L&&z.length>1&&!p){for(var W=null,G=[],P=!1,ot=0;ot1&&p&&!h.direction&&p.room){for(var ne=p.room(),Vt=-1,me=null,ye=0;yeVt+1e-6&&(Vt=rn,me=$e)}}}me&&(B=me)}H=(p?p.measure:ge)(i,B,n,m,R,et,dt),R=H.dyn,et(R),st();var be=i.querySelector(":scope > .diagram-hint");if(be){var ln=ie(B,R.layout==="drawn").map(function(At){return""+At.keys.map(function(co){return''+mt(co)+""}).join(" ")+" "+mt(At.words)+""}).join("");be.innerHTML!==ln&&(be.innerHTML=ln)}Tt(B,R)||(at=it=null);var cn=nt&&H.ink!==w;cn&&(nt.innerHTML=H.ink,w=H.ink),I();var lo=B.text?i.querySelector(".diagram-text[data-art]"):null;B.text&&typeof e.diagramText=="function"&&e.diagramText(i,B,h,p);var dn=B.text?i.querySelector(".diagram-text[data-art]"):null;$&&H.tokens&&(Pn(i,!!(H.geo&&H.geo.lines.length)||!!dn),(cn||dn!==lo)&&u&&u.redrawn()),p&&p.onMeasured&&H.tokens&&p.onMeasured(H,i)}function pt(W){R=W,et(R)}function Mt(W){var G=R.stop;R=Object.assign({},R,{stop:W}),ro(i,n,G,W)}var ut=function(W){var G=W&&W.closest?W.closest(".diagram-node"):null;return G&&i.contains(G)?G:null};function $t(W){var G=ut(W.target);if(!(!G||W.defaultPrevented)){if(C(),W.key==="Escape"){!p&&(Q||at||it)&&(W.preventDefault(),Q=at=it=null,I());return}if(Tt(B,R)){var P=no(B,G.getAttribute("data-node"),W.key,R.layout==="drawn");if(P){W.preventDefault(),Mt(P);var ot=i.querySelector('.diagram-node[data-node="'+CSS.escape(P)+'"]');ot&&ot.focus()}}}}function bt(W){var G=ut(W.target);if(G){C();var P=G.getAttribute("data-node");Q=G.matches(":focus-visible")?P:null,Tt(B,R)&&R.stop!==P&&Mt(P),I()}}function wt(W){var G=ut(W.target);G&&(ut(W.relatedTarget)||(Q=null),R.keep===G.getAttribute("data-node")&&pt(Object.assign({},R,{keep:void 0})),I())}function vt(W){if(!(W.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var G=ut(W.target);G&&C();var P=G&&Tt(B,R)?G.getAttribute("data-node"):null;P!==at&&(at=P,I())}}function y(){at&&(at=null,I())}function S(){C(),pt(Object.assign({},R,{open:!R.open,autoOpen:void 0})),st()}i.addEventListener("keydown",$t),i.addEventListener("focusin",bt),i.addEventListener("focusout",wt),i.addEventListener("pointerover",vt),i.addEventListener("pointerleave",y),i.addEventListener("click",ft),tt&&tt.addEventListener("click",S),lt();var E=i.clientWidth,M=0,A=!0,N=new ResizeObserver(function(){Math.abs(i.clientWidth-E)<.5||(E=i.clientWidth,cancelAnimationFrame(M),M=requestAnimationFrame(lt))});N.observe(i),document.fonts&&document.fonts.ready.then(function(){A&<()});var J=matchMedia("(forced-colors: active)"),K=B.nodes.some(function(W){return W.mark});K&&J.addEventListener("change",lt),$&&(u=e.diagramMotion(i,{fig:i,P:n,base:m,model:function(){return B},geo:function(){return H&&H.geo},tokens:function(){return H&&H.tokens}},h));var Y=!p&&h.zoom!==!1&&typeof e.diagramZoom=="function"?e.diagramZoom(i,h,{model:B,settle:C,animated:$}):null,U=i.querySelector(":scope > .diagram-foot"),Z=!p&&h.export===!0&&U&&typeof e.diagramExport=="function"?e.diagramExport(U,i):[];i.__diagram={stop:function(){Y&&Y.destroy(),Z.forEach(function(W){W.remove()}),A=!1,N.disconnect(),cancelAnimationFrame(M),K&&J.removeEventListener("change",lt),u&&u.destroy(),i.removeEventListener("keydown",$t),i.removeEventListener("focusin",bt),i.removeEventListener("focusout",wt),i.removeEventListener("pointerover",vt),i.removeEventListener("pointerleave",y),i.removeEventListener("click",ft),_&&_.remove(),tt&&tt.removeEventListener("click",S)},layout:lt,key:g(h),send:u&&u.sendValue?u.sendValue:null}}function g(i){try{return JSON.stringify(i,function(h,b){return h==="packet"&&b&&typeof b=="object"?Object.assign({},b,{send:void 0}):b})}catch{return null}}function f(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var h=i.querySelector(":scope > script[data-diagram]");if(h)try{d(i,JSON.parse(h.textContent),!0)}catch(b){console.error("Basalt diagram: this figure could not be drawn",b)}}})}e.diagramMarkup=s,e.diagramKit={draw:d,buildModel:Wt,figureKey:En,figureList:Bn,hintEntries:ie,toHtml:se,escapeHtml:mt,settleEntrance:nn,measureFigure:ge},t.diagram=function(i,h){var b=i.__diagram,p=b&&b.send?g(h):null;if(p!==null&&p===b.key){b.send(h.packet?h.packet.send:void 0);return}d(i,h)},e.step(62,"wireDiagrams",f)})(window.Basalt)})();
+(()=>{var fn=["top","right","bottom","left"],un=["main","plain","dashed"],we=["one","zero-or-one","one-or-many","zero-or-many"],Ht={one:"Exactly one","zero-or-one":"Zero or one","one-or-many":"One or many","zero-or-many":"Zero or many"},hn=[2,3,4,5,6],ht=t=>t==null||t===""?void 0:String(t),Lt=t=>Object.assign(Object.create(null),t),Ot=(t,e)=>t&&Object.prototype.hasOwnProperty.call(t,e)?t[e]:void 0;function Nt(t,e={}){const o=e.checks!==!1,c=[],l=$=>{c.push($)},s=[],r=$=>{s.push($)},a=t.legend??{},d={};for(const $ of["main","plain","dashed","focal","group","activation"]){const u=ht(a[$]);u&&(d[$]=u)}const g=t.stepLabel,f=typeof g=="function"?$=>String(g($)):typeof g=="string"?($=>g.replace("{n}",String($))):$=>`Step ${$}`,i=t.shapeLabels??{},h={terminal:ht(i.terminal)??"Start or end",step:ht(i.step)??"Step",decision:ht(i.decision)??"Decision"},b=t.heading===void 0?3:hn.includes(t.heading)?t.heading:(l(`heading ${String(t.heading)} is not a level from 2 to 6: the title is an h3`),3),p=($,u)=>$==null?"plain":un.includes($)?$:(l(`"${String($)}" is not a kind of line (main, plain or dashed): ${u} is drawn plain`),"plain"),m=$=>{if($!=null){if(fn.includes($))return $;l(`"${String($)}" is not a side (top, right, bottom or left): the derived side is used`)}},M=($,u)=>typeof $=="number"&&Number.isInteger($)&&$>=1?$:(t.layout==="auto"&&$==null||l(`${u} is ${JSON.stringify($)}, not a whole number from 1: it is placed at 1`),1),L=[],z=[];let v=[];const O=[],B=[],j=t.type;if(["architecture","flowchart","data-flow","sequence","schema"].includes(j)||l(`"${String(j)}" is not a type of diagram (architecture, flowchart, data-flow, sequence or schema)`),j==="architecture"||j==="flowchart"){for(const $ of t.nodes??[]){const u=j==="flowchart"&&$.shape==="decision"?"decision":j==="flowchart"&&$.shape==="terminal"?"terminal":"box",w=String($.id??""),C=M($.row,`the row of ${w}`);L.push({id:w,i:L.length,name:String($.name??""),kind:u==="decision"?void 0:ht($.kind),detail:u==="decision"?void 0:ht($.detail),mono:!!$.detailMono,focal:!!$.focal,col:M($.col,`the column of ${w}`),row:C,row2:C,branch:!!$.branch,shape:u,group:j==="architecture"?ht($.group):void 0,mark:j==="architecture"?oe($.mark,l):void 0})}if(j==="architecture"){const $=(t.groups??[]).map(I=>({id:String(I.id??""),label:String(I.label??""),parent:ht(I.parent)})),u=new Map($.map(I=>[I.id,I])),w=I=>{if(!I.parent)return 1;const _=u.get(I.parent);return _?_.parent===I.id||_.id===I.id?(r(`the groups "${I.label}" and "${_.label}" are each other's parent`),I.parent=void 0,1):_.parent?(r(`the group "${I.label}" is a third level: groups nest two deep`),I.parent=void 0,1):2:(r(`the group "${I.label}" names the parent "${I.parent}", which is not a group`),I.parent=void 0,1)},C=$.map(w);$.forEach((I,_)=>O.push({...I,depth:C[_],members:L.filter(X=>X.group===I.id).map(X=>X.id),all:[]}));for(const I of O)I.all=[...I.members,...O.filter(_=>_.parent===I.id).flatMap(_=>_.members)];O.sort((I,_)=>I.depth-_.depth)}}else if(j==="data-flow"){v=(t.lanes??[]).map(u=>({id:String(u.id??""),label:String(u.label??"")}));const $=new Map(v.map((u,w)=>[u.id,w+1]));for(const u of t.nodes??[]){const w=String(u.id??""),C=String(u.lane??""),I=$.get(C);I===void 0&&l(`a node (${w}) names the lane "${C}", which is not in lanes`);const _=L.length+1;L.push({id:w,i:L.length,name:String(u.name??""),kind:f(_),detail:ht(u.detail),mono:!!u.detailMono,focal:!!u.focal,col:M(u.col,`the column of ${w}`),row:I??1,row2:I??1,branch:!1,shape:"box",lane:I??1,laneLabel:v[(I??1)-1]?.label??C,step:_,mark:oe(u.mark)})}}else if(j==="sequence"){(t.participants??[]).forEach((C,I)=>{const _=String(C.name??"");L.push({id:String(C.id??""),i:I,name:_,kind:ht(C.kind),mono:!1,focal:!!C.focal,col:I+1,row:1,row2:1,branch:!1,shape:"participant",short:ht(C.short)??_,mark:oe(C.mark)})});let $=0;const u=new Map(L.map(C=>[C.id,C.col])),w=(C,I)=>{let _=1/0,X=-1/0;for(const V of C??[]){if(!V||typeof V!="object")continue;if("band"in V){I>0&&r(`the band "${String(V.band)}" is inside a frame: a band is the whole figure's`),B.push({band:String(V.band??"")});continue}if("frame"in V){if(I>=2){r("a frame is a third level: frames nest two deep");continue}const $t=V.frame==="alt"||V.frame==="loop"||V.frame==="opt"?V.frame:"opt",bt=$t==="alt"?V.branches??[]:[{label:V.label,steps:V.steps}];$t==="alt"&&bt.length<2&&r("an alt frame has one branch: it needs two or more");const wt=String(bt[0]?.label??"");wt.length>40&&r(`the frame label "${wt}" is over 40 characters`);const vt=B.length;B.push({open:$t,label:wt,depth:I+1,a:0,b:0}),bt.forEach((y,S)=>{if(S){const W=String(y.label??"");W.length>40&&r(`the frame label "${W}" is over 40 characters`),B.push({otherwise:W,depth:I+1})}y.steps?.length||r(`a frame or branch ("${String(y.label??"")}") is empty`);const[E,k]=w(y.steps??[],I+1);_=Math.min(_,E),X=Math.max(X,k);const A=B[vt];A.a=Math.min(A.a||1/0,E),A.b=Math.max(A.b,k)}),B.push({close:I+1});continue}$++;const ft=String(V.label??"");ft.includes(`
+`)&&r(`message ${$}'s label has a break: a message's second line is its note`);const st=String(V.from??""),lt=String(V.to??"");B.push({n:$,from:st,to:lt,label:qt(ft),note:ht(V.note),kind:p(V.kind,`message ${$}`),activate:V.activate===!0||void 0,deactivate:V.deactivate===!0||void 0});const pt=u.get(st)??1,kt=u.get(lt)??1,ut=pt===kt?pt===L.length?pt-1:pt+1:pt;_=Math.min(_,pt,kt,ut),X=Math.max(X,pt,kt,ut)}return[_,X]};w(t.steps??[],0);for(const C of B)"open"in C&&!Number.isFinite(C.a)&&(C.a=1,C.b=Math.max(1,L.length))}else if(j==="schema")for(const $ of t.tables??[]){const u=String($.name??""),[w,C]=Array.isArray($.row)?$.row:[$.row,$.row],I=M(w,`the row of ${u}`),_=Math.max(I,M(C,`the last row of ${u}`)),X=$.more===void 0||$.more===null?void 0:Number.isInteger($.more)&&$.more>0?$.more:(l(`${u}'s "more" is ${JSON.stringify($.more)}, not a whole number from 1: it is left out`),void 0);L.push({id:u,i:L.length,name:u,mono:!0,focal:!!$.focal,col:M($.col,`the column of ${u}`),row:I,row2:_,branch:!1,shape:"table",more:X,columns:($.columns??[]).map(V=>({name:String(V.name??""),type:ht(V.type),key:V.key==="PK"||V.key==="FK"?V.key:(V.key!==void 0&&V.key!==null&&l(`${u}.${String(V.name)}'s key is "${String(V.key)}", not PK or FK: it is left out`),void 0)}))})}let F=!1;if(t.layout==="auto"&&(j==="architecture"||j==="flowchart"||j==="schema")){const $=j==="schema"?t.tables:t.nodes;o&&($??[]).some(w=>w&&(w.col!==void 0||w.row!==void 0))&&l('a card under layout="auto" has a col or row, which is not read: there are no hints');const u=e.placement?.cells;u||(F=!0);for(const w of L){const C=u?.[w.id];w.col=C?.col??1,w.row=w.row2=C?.row??1}if(u){const w=new Map;for(const C of L){const I=Ot(u,C.id);if(!I){F=!0,l(`the placement has no cell for ${C.id}, so it is not used`);continue}const _=`${I.col},${I.row}`;w.has(_)&&(F=!0,l(`the placement puts ${w.get(_)} and ${C.id} in one cell, so it is not used`)),w.set(_,C.id)}}if(u&&!F)for(const w of O){const C=w.all.map(st=>L.find(lt=>lt.id===st)).filter(Boolean);if(!C.length)continue;const I=Math.min(...C.map(st=>st.col)),_=Math.max(...C.map(st=>st.col)),X=Math.min(...C.map(st=>st.row)),V=Math.max(...C.map(st=>st.row)),ft=L.filter(st=>!w.all.includes(st.id)&&st.col>=I&&st.col<=_&&st.row>=X&&st.row<=V);ft.length&&(F=!0,l(`the placement puts ${ft.map(st=>st.id).join(", ")} inside the box of the group "${w.label}", so it is not used`))}}else t.layout==="auto"&&r(`layout="auto" is for an architecture, a flowchart or a schema, not a ${j}`);((j==="schema"?t.tables:j==="sequence"?t.participants:t.nodes)??[]).forEach(($,u)=>{if(!$||$.href===void 0||$.href===null)return;const w=String($.href);if(j==="sequence"){r(`${L[u]?.id}: a participant cannot be a link (href)`);return}if(!w.trim()){r(`${L[u]?.id}'s href is empty`);return}const C=L[u];C&&(C.href=w,C.blank=$.target==="_blank")});const q=new Map;for(const $ of L)$.id?q.has($.id)&&l(`the id "${$.id}" is used twice`):l("a node has no id"),q.set($.id,$);if(j==="schema"){const $=(w,C)=>{if(w==null)return;const I=w,_=we.includes(I.from)?I.from:void 0;if(!_){r(`${C}'s cardinality "from" is ${JSON.stringify(I.from)}, not one, zero-or-one, one-or-many or zero-or-many: it is left out`);return}return I.to===void 0||I.to===null?{from:_,to:"one"}:I.to==="one"||I.to==="zero-or-one"?{from:_,to:I.to}:(r(`${C}'s cardinality "to" is ${JSON.stringify(I.to)}: a foreign key references one row at most (one or zero-or-one), so it is drawn as one`),{from:_,to:"one"})};(t.tables??[]).forEach(w=>(w.columns??[]).forEach((C,I)=>{const _=ht(C.references);if(!_&&C.cardinality!==void 0&&C.cardinality!==null&&r(`${String(w.name)}.${String(C.name)} states a cardinality but references nothing`),!_)return;const[X,V]=_.split("."),ft=q.get(X??""),st=ft?.columns?.findIndex(kt=>kt.name===V)??-1;if(!ft||st<0){l(`${String(w.name)}.${String(C.name)} references ${_}, which is not a shown column`);return}const lt=q.get(String(w.name??""));lt.columns[I].ref={table:X,column:V,row:st};const pt=$(C.cardinality,`${String(w.name)}.${String(C.name)}`);pt&&(lt.columns[I].card=pt),z.push({i:z.length,from:lt.id,to:X,kind:"plain",fromRow:I,toRow:st,fk:!0,card:pt})}));const u=z.filter(w=>w.card).length;u&&u!w.card).map(w=>`${w.from}.${q.get(w.from).columns[w.fromRow].name}`).join(", ")} ${z.length-u===1?"has":"have"} none)`)}else if(j!=="sequence")for(const $ of t.edges??[]){const u=String($.from??""),w=String($.to??"");if(!q.has(u)||!q.has(w)){l(`a line names ${q.has(u)?w:u}, which is not a node`);continue}const C=ht($.label),I=C?.split(`
+`)??[];I.length>2&&r(`the label "${qt(C)}" has more than one break: a label is two lines at most`),I.some(_=>_.length>ke)&&r(`a line of the label "${qt(C)}" is over ${ke} characters: longer words belong in the node or the summary`),z.push({i:z.length,from:u,to:w,kind:p($.kind,`the line from ${u} to ${w}`),label:C,fromSide:m($.fromSide),toSide:m($.toSide),flow:j!=="flowchart"&&$.flow===!0?!0:void 0})}else for(const $ of B)"n"in $&&(!q.has($.from)||!q.has($.to))&&l(`message ${$.n} names ${q.has($.from)?$.to:$.from}, which is not a participant`);if(o&&j!=="sequence"&&!F){const $=new Map;for(const u of L)for(let w=u.row;w<=u.row2;w++){const C=`${u.col}:${w}`;$.has(C)&&l(`${u.id} and ${$.get(C)} share the cell at column ${u.col}, row ${w}`),$.set(C,u.id)}}if(o&&!F){for(const u of O){const w=u.all.map(_=>q.get(_));if(!w.length)continue;const C={c1:Math.min(...w.map(_=>_.col)),c2:Math.max(...w.map(_=>_.col)),r1:Math.min(...w.map(_=>_.row)),r2:Math.max(...w.map(_=>_.row2))};for(const _ of L)!u.all.includes(_.id)&&_.col>=C.c1&&_.col<=C.c2&&_.row>=C.r1&&_.row<=C.r2&&l(`${_.id} is inside the box of the group "${u.label}" but not a member`);const I=w.map(_=>_.i);Math.max(...I)-Math.min(...I)+1!==I.length&&l(`the members of the group "${u.label}" are not next to each other in the author's order, so the stacked drawing cannot wrap them in one box`)}for(const u of L)u.group&&!O.some(w=>w.id===u.group)&&l(`${u.id} names the group "${u.group}", which is not in groups`);L.filter(u=>u.focal).length>1&&l("more than one node is focal: a diagram has one at most");const $=new Set(j==="sequence"?B.flatMap(u=>"n"in u?[u.kind]:[]):z.map(u=>u.kind));$.has("main")&&!d.main&&l("main lines are drawn but the legend has no words for them (legend.main)"),$.has("dashed")&&!d.dashed&&l("dashed lines are drawn but the legend has no words for them (legend.dashed)"),L.some(u=>u.focal)&&!d.focal&&l("a focal node is drawn but the legend has no words for what it marks (legend.focal)")}const D=j==="architecture"||j==="data-flow",T=$=>Array.isArray($)&&$.length>1?$.map(String):void 0,R=D&&t.packet&&typeof t.packet=="object"?t.packet:void 0,H=R&&T(R.path),Q={animated:t.motion==="animated",pulse:D?T(t.pulse):void 0,packet:H?{path:H,repeat:R.repeat===!0,send:R.send}:void 0,run:j==="sequence"&&t.run===!0,firstVisit:t.entrance==="first-visit"||void 0};if(o)for(const $ of L){const u=$.mark?.says;if(!u?.length)continue;const w=[$.name,$.kind,$.detail,$.laneLabel].filter(Boolean).join(" ").toLowerCase();u.some(C=>w.includes(C.toLowerCase()))||l(`${$.id}'s mark stands for ${u.join(" or ")}, and none of its words say so`)}const at=[];if(j==="sequence"){const $=new Map,u=new Map;for(const w of B)"n"in w&&(u.set(w.from,w.n),u.set(w.to,w.n));for(const w of B)if("n"in w){if(w.activate){const C=$.get(w.to)??[];if(C.length>=3)r(`message ${w.n} opens a fourth bar on ${w.to}: three deep at most`);else{const I={who:w.to,from:w.n,to:w.n,depth:C.length+1};C.push(I),at.push(I),$.set(w.to,C)}}if(w.deactivate){const I=$.get(w.from)?.pop();I?I.to=w.n:r(`message ${w.n} closes a bar on ${w.from}, which has none open`)}}for(const[w,C]of $)for(const I of C)I.to=Math.max(I.from,u.get(w)??I.from)}const it=t.frameLabels??{},yt={opt:ht(it.opt)??"Only if",loop:ht(it.loop)??"Repeats",alt:ht(it.alt)??"One of these",else:ht(it.else)??"Otherwise"},dt=t.layout==="auto"&&!F?e.placement:void 0;let et=Math.max(1,dt?.cols??1,...L.map($=>$.col));if(e.rtl){for(const u of L)u.col=et-u.col+1;const $=u=>u==="left"?"right":u==="right"?"left":u;for(const u of z)u.fromSide=$(u.fromSide),u.toSide=$(u.toSide);for(const u of B)if("open"in u){const[w,C]=[et-u.b+1,et-u.a+1];u.a=w,u.b=C}et=Math.max(1,dt?.cols??1,...L.map(u=>u.col))}const nt=j==="data-flow"?Math.max(1,v.length):Math.max(1,dt?.rows??1,...L.map($=>$.row2)),tt={type:j,title:String(t.title??""),heading:b,legend:d,nodes:L,byId:q,edges:z,groups:O,lanes:v,steps:B,bars:at,frameWords:yt,cols:et,rows:nt,shapeLabels:h,stepWord:f,warnings:c,errors:s,motion:Q,memo:new Map,rtl:e.rtl||void 0,unplaced:F||void 0,text:j==="sequence"&&t.variant==="text"||void 0,marks:z.some($=>$.card)||void 0};if(t.layout==="auto"&&!F&&j!=="schema"&&pn(tt),o)for(const[$,u]of Object.entries(De(tt)))u>=48&&l(`${$} grows to ${u}px to hold the lines on one side: use another side`);return o&&L.length>100&&l(`the figure has ${L.length} cards: more than 100, which automatic layout places on the main thread`),o&&L.length>1&&!F&&!Ut(tt)&&l("some part cannot be reached from another by the arrow keys where the figure is drawn, so its arrows keep the author's order"),tt}function pn(t){const e=new Set(t.nodes.map(r=>`${r.col},${r.row}`)),n=(r,a)=>{const d=[];for(let g=Math.min(r,a)+1;g{const a=t.byId.get(r.from),d=t.byId.get(r.to),g=d.col>a.col?"right":"left",f=d.row>a.row?"bottom":"top",i=d.col>a.col?"left":"right",h=d.row>a.row?"top":"bottom",b=(M,L,z,v)=>n(M,L).map(O=>v?[O,z]:[z,O]);let p;const m=M=>(M==="right"?a.col1:M==="bottom"?a.row1)?[{sides:[M,M],cells:[]}]:[];return a.row===d.row?p=[{sides:[g,i],cells:b(a.col,d.col,a.row,!0)},...m("bottom"),...m("top")]:a.col===d.col?p=[{sides:[f,h],cells:b(a.row,d.row,a.col,!1)},...m("right"),...m("left")]:p=[{sides:[g,h],cells:[...b(a.col,d.col,a.row,!0),[d.col,a.row],...b(a.row,d.row,d.col,!1)]},{sides:[f,i],cells:[...b(a.row,d.row,a.col,!1),[a.col,d.row],...b(a.col,d.col,d.row,!0)]},{sides:[g,i],cells:b(a.col,d.col,a.row,!0)},{sides:[f,h],cells:b(a.row,d.row,a.col,!1)}],p.filter(M=>M.cells.every(([L,z])=>!e.has(`${L},${z}`)))},c=new Map,l=new Set;for(const r of t.edges)if(r.fromSide||r.toSide){const[a,d]=fe(t.byId.get(r.from),t.byId.get(r.to)),g=r.fromSide??a,f=r.toSide??d;l.add(`${r.from}.${g}`);for(const[i,h]of[[r.from,g],[r.to,f]])c.set(`${i}.${h}`,(c.get(`${i}.${h}`)??0)+1)}const s=t.edges.map((r,a)=>a).sort((r,a)=>o(t.edges[r]).length-o(t.edges[a]).length||+(t.edges[a].kind==="main")-+(t.edges[r].kind==="main")||r-a);for(const r of s){const a=t.edges[r];if(a.fromSide||a.toSide)continue;const d=(f,i,h)=>{const b=`${f}.${i}`;return(c.get(b)??0)>=3?!1:t.byId.get(f).shape!=="decision"?!0:h?!c.has(b):!l.has(b)},g=o(a).find(f=>d(a.from,f.sides[0],!0)&&d(a.to,f.sides[1],!1));if(g){l.add(`${a.from}.${g.sides[0]}`);for(const[f,i]of[[a.from,g.sides[0]],[a.to,g.sides[1]]])c.set(`${f}.${i}`,(c.get(`${f}.${i}`)??0)+1);a.fromSide=g.sides[0],a.toSide=g.sides[1]}}}function oe(t,e){if(typeof t=="string")return t?{id:t}:void 0;if(!t||typeof t!="object")return;const n=t,o=ve(ht(n.onLight),e);if(o)return{onLight:o,onDark:ve(ht(n.onDark),e)??o,says:Array.isArray(n.says)?n.says.map(String):void 0}}function ve(t,e){if(t){if(/^data:image\//i.test(t.trim()))return t;try{if(/^https?:$/.test(new URL(t,"https://basalt.invalid/").protocol)&&!/^http:/i.test(t.trim()))return t}catch{}e?.(`a card's mark ${JSON.stringify(t.slice(0,60))} is not a relative path, https or a data: image, so it is not drawn`)}}var xe=t=>`url("${t.replace(/[\\"\n\r\f;]/g,e=>e===`
+`?"\\a ":e==="\r"?"\\d ":e==="\f"?"\\c ":e===";"?"\\3b ":`\\${e}`)}")`;function Rt(t,e,n){return t.memo.has(e)||t.memo.set(e,n()),t.memo.get(e)}var ke=28,Kt=t=>t.includes(`
+`)?2:1,qt=t=>t.replace(/\n/g," "),Ft=t=>{const e=t.trim();return e?/[.!?]$/.test(e)?e:`${e}.`:""};function Me(t,e){return t.legend[e]}function gn(t,e){return e.shape==="decision"?"decision":e.shape==="terminal"?t.edges.some(n=>n.from===e.id)?"start":"end":e.kind??"step"}function mn(t,e){return Rt(t,`sentence:${e.i}`,()=>yn(t,e))}function yn(t,e){const n=[];if(t.type==="schema"){n.push(`${e.name}, table.`);const o=(e.columns??[]).filter(l=>l.ref).map(l=>`${l.ref.table} (${l.name}${l.card?`: ${Se(e.id,l.ref.table,l.card)}`:""})`),c=t.edges.filter(l=>l.to===e.id).map(l=>`${l.from} (${t.byId.get(l.from).columns[l.fromRow].name}${l.card?`: ${Se(l.from,l.to,l.card)}`:""})`);o.length&&n.push(`References ${o.join(", ")}.`),c.length&&n.push(`Referenced by ${c.join(", ")}.`)}else if(t.type==="sequence"){const o=t.steps.filter(s=>"n"in s&&s.from===e.id).length,c=t.steps.filter(s=>"n"in s&&s.to===e.id).length;n.push(Ft(e.kind?`${e.name}, ${e.kind}`:e.name)),n.push(`Sends ${o} ${o===1?"message":"messages"} and receives ${c}.`);const l=Ee(t,e);l&&n.push(l.trim())}else{const o=t.type==="data-flow"?`${t.stepWord(e.step)} of ${t.nodes.length}, ${e.laneLabel}`:t.type==="flowchart"?gn(t,e):e.kind;if(n.push(Ft(o?`${e.name}, ${o}`:e.name)),e.detail&&n.push(Ft(e.detail)),e.group){const s=t.groups.find(a=>a.id===e.group),r=s?.parent?t.groups.find(a=>a.id===s.parent):void 0;s&&n.push(r?`In ${s.label}, in ${r.label}.`:`In ${s.label}.`)}const c=t.edges.filter(s=>s.to===e.id).map(s=>`${t.byId.get(s.from).name}${s.label?` (${qt(s.label)})`:""}`),l=t.edges.filter(s=>s.from===e.id).map(s=>`${t.byId.get(s.to).name}${s.label?` (${qt(s.label)})`:""}`);c.length&&n.push(`From: ${c.join(", ")}.`),l.length&&n.push(`To: ${l.join(", ")}.`)}return e.focal&&t.legend.focal&&n.push(Ft(t.legend.focal)),n.join(" ")}var $n=(t,e,n,o)=>[`${Ht[n.from].toLowerCase()} `,o(t),` to ${Ht[n.to].toLowerCase()} `,o(e)],Se=(t,e,n)=>`${Ht[n.from].toLowerCase()} ${t} to ${Ht[n.to].toLowerCase()} ${e}`;function Ee(t,e){const n=t.bars.filter(c=>c.who===e.id&&c.depth===1);return n.length?` ${t.legend.activation??"Working"} during ${n.map(c=>c.from===c.to?`message ${c.from}`:`messages ${c.from} to ${c.to}`).join(" and ")}.`:""}function bn(t,e,n,o){const c=n.pointerType;if(c!=="touch"&&c!=="pen")return;const l=t.querySelector(`.${e}-drawing`),s=n.target;if(!l||!s||!l.contains(s)||!t.querySelector(`.${e}-edge`))return;const r=s.closest(`.${e}-node`);if(!r?.hasAttribute("href"))return r?r.dataset.node===o?null:r.dataset.node??null:o===null?void 0:null}function Ae(t){return t.type==="architecture"?"a part":t.type==="sequence"?"a participant":t.type==="schema"?"a table":"a step"}function x(t,e,...n){const o=[];for(const c of n.flat(1/0))c!=null&&c!==!1&&!Array.isArray(c)&&o.push(c);return{t,a:e??{},c:o}}var wn={"&":"&","<":"<",">":">",'"':""","'":"'"},mt=t=>t.replace(/[&<>"']/g,e=>wn[e]),vn=" br img input meta link hr path polygon polyline circle rect line ";function se(t,e={}){if(typeof t=="string")return mt(t);if("slot"in t)return e[t.slot]??"";if(!/^[a-z][a-z0-9]*$/.test(t.t))throw new Error(`diagram: "${t.t}" is not an element name`);let n="";for(const[o,c]of Object.entries(t.a))if(!(c==null||c===!1)){if(!/^[a-z][a-z0-9:-]*$/i.test(o))throw new Error(`diagram: "${o}" is not an attribute name`);n+=c===!0?` ${o}`:` ${o}="${mt(String(c))}"`}return vn.includes(` ${t.t} `)&&!t.c.length?t.t==="path"||t.t==="polygon"||t.t==="polyline"||t.t==="circle"||t.t==="rect"||t.t==="line"?`<${t.t}${n}/>`:`<${t.t}${n}>`:`<${t.t}${n}>${t.c.map(o=>se(o,e)).join("")}${t.t}>`}var xn=t=>({title:`${t}-title`,summary:`${t}-summary`,keys:`${t}-keys`,list:`${t}-list`,toggle:`${t}-toggle`});function Tt(t,e){return!e.layout||e.bare?!1:e.layout==="drawn"?!0:t.type!=="sequence"&&t.type!=="schema"}function kn(t,e){return t.type==="sequence"||t.type==="schema"?e.layout==="drawn":!0}function Zt(t,e){const n=e.all.map(o=>t.byId.get(o));return n.length?{c1:Math.min(...n.map(o=>o.col)),c2:Math.max(...n.map(o=>o.col)),r1:Math.min(...n.map(o=>o.row)),r2:Math.max(...n.map(o=>o.row2))}:null}function Le(t){return Rt(t,"group-edges",()=>{const e=[0,0,0,0];for(const n of t.groups){const o=Zt(t,n);if(!o)continue;[o.r1===1,o.c2===t.cols,o.r2===t.rows,o.c1===1].forEach((l,s)=>{l&&(e[s]=Math.max(e[s],_e(t,n,s)))})}return e})}function _e(t,e,n){const o=Zt(t,e);return t.groups.filter(s=>s.parent===e.id).some(s=>{const r=Zt(t,s);return r&&[r.r1===o.r1,r.c2===o.c2,r.r2===o.r2,r.c1===o.c1][n]})?2:1}function qe(t){const e=Le(t);return e[1]+e[3]}function ae(t){return t.type==="sequence"?t.nodes.length:t.cols}function Ie(t){return Rt(t,"plan",()=>Mn(t))}function Mn(t){const e=t.nodes,n=m=>t.type==="data-flow"||!e[m].branch,o=t.edges.map(m=>{const M=t.byId.get(m.from).i,L=t.byId.get(m.to).i,v=e.slice(Math.min(M,L)+1,Math.max(M,L)).every(O=>!n(O.i));return L===M+1&&!(n(M)&&!n(L))?"down":L===M-1?"up":L>M&&n(M)&&!n(L)&&v?"trunk":L>M&&n(M)&&n(L)&&v?"rail":L>M?"end-down":"end-up"}),c=t.edges.map((m,M)=>({e:m,k:M})).filter(({k:m})=>o[m]==="end-down"||o[m]==="end-up"),l=m=>{const M=t.byId.get(m.from).i,L=t.byId.get(m.to).i;return[Math.min(M,L),Math.max(M,L)]},s=(m,M)=>{const[L,z]=l(m),[v,O]=l(M);return L{const M=t.byId.get(m.from).i,[L,z]=l(m);return!n(M)&&e.slice(L+1,z).every(v=>!n(v.i))&&c.every(v=>v.e===m||!s(v.e,m))}),a=c.length>0&&(t.type==="data-flow"||!r),d=m=>{const[M,L]=l(m);return L-M},g=t.edges.map(()=>0);let f=!1;const i=[];for(const m of[...c].sort((M,L)=>d(M.e)-d(L.e)||M.k-L.k)){let M=0;for(const L of i)s(L.e,m.e)&&(M=Math.max(M,g[L.k]+1));g[m.k]=M,M>3&&(f=!0),i.push(m)}const h=Math.max(0,...c.map(({k:m})=>g[m]+1)),b=t.edges.map(()=>.5);for(const m of e){const M=c.filter(({e:v})=>v.from===m.id);if(M.length<2)continue;const L=M.filter(({k:v})=>o[v]==="end-down").sort((v,O)=>d(O.e)-d(v.e)||v.k-O.k);[...M.filter(({k:v})=>o[v]==="end-up").sort((v,O)=>d(v.e)-d(O.e)||O.k-v.k),...L].forEach(({k:v},O,B)=>{b[v]=B.length===2?O===0?1/3:2/3:(O+1)/(B.length+1)})}const p=Lt();for(let m=1;m{const D=o[q],T=t.byId.get(rt.from).i,R=t.byId.get(rt.to).i,H=R===m&&(D==="down"||D==="trunk"||D==="rail"||D==="end-down"),Q=T===m&&R===m-1&&D==="up",at=R===m-1&&D==="end-up";H&&(D==="trunk"||D==="end-down")&&(O=!0),at&&(B=!0),(H||Q||at)&&rt.label&&(z++,v=Math.max(v,D==="trunk"?40:48))}),(z>1||O&&B)&&(v=64);const j=c.filter(({e:rt,k:q})=>o[q]==="end-down"&&t.byId.get(rt.to).i===m).length,F=c.filter(({e:rt,k:q})=>o[q]==="end-up"&&t.byId.get(rt.to).i===m-1).length;v+=20*Math.max(0,j-1)+20*Math.max(0,F-1),p[M.id]=v}return{routes:o,gutter:a,lanes:g,exits:b,gaps:p,third:f,laneCount:h}}var Wt=(t,e)=>({width:t,height:e,viewBox:`0 0 ${t} ${e}`,"aria-hidden":"true",focusable:"false"});function Ce(t,e){const n=e==="fk"?"plain":e,o=n==="main"?8:8.5,c=24,l=n==="dashed"?c-1:c-7;return x("svg",{class:`${t}-swatch`,"data-kind":n,...Wt(24,16)},e==="fk"?x("circle",{class:`${t}-dot`,cx:3,cy:o,r:3}):null,x("path",{class:`${t}-line`,"data-kind":n,d:`M${e==="fk"?3:0} ${o}H${l}`}),n==="dashed"?x("path",{class:`${t}-tip`,"data-kind":n,"data-open":"",d:`M${c-8} ${o-4}L${c} ${o}L${c-8} ${o+4}`}):x("path",{class:`${t}-tip`,"data-kind":n,d:`M${c} ${o}L${c-8} ${o-4}L${c-8} ${o+4}Z`}))}function Sn(t,e){const{crow:n,ring:o}=Oe(e,24,8.5,-1);return x("svg",{class:`${t}-swatch`,"data-card":e,...Wt(24,16)},x("path",{class:`${t}-line`,"data-kind":"plain",d:"M0 8.5H24"}),x("path",{class:`${t}-crow`,d:n}),o?x("circle",{class:`${t}-ring`,cx:o.x,cy:o.y,r:o.r}):null)}function Oe(t,e,n,o,c=8,l=6){const s=h=>String(Math.round(h*100)/100),r=h=>e+o*h,a=c/2,d=h=>`M${s(r(h-.5))} ${s(n-a)}V${s(n+a)}`,g=t==="one-or-many"||t==="zero-or-many",f=t==="zero-or-one"||t==="zero-or-many";let i=g?`M${s(e)} ${s(n-a)}L${s(r(7.5))} ${s(n)}L${s(e)} ${s(n+a)}`:d(4);return f||(i+=d(g?11:8)),{crow:i,ring:f?{x:Math.round(r(10.5)*100)/100,y:n,r:l/2}:void 0}}function Dt(t,e){return e==="decision"?x("svg",{class:`${t}-swatch`,"data-shape":e,...Wt(16,16)},x("path",{class:`${t}-swatch-shape`,d:"M8 2.5L14.5 8L8 13.5L1.5 8Z"})):e==="terminal"?x("svg",{class:`${t}-swatch`,"data-shape":e,...Wt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:3.5,width:15,height:9,rx:4.5})):x("svg",{class:`${t}-swatch`,"data-shape":e,...Wt(16,16)},x("rect",{class:`${t}-swatch-shape`,x:.5,y:2.5,width:15,height:11,rx:2}))}function Be(t,e){return Rt(e,`key:${t}`,()=>An(t,e))}var En=Be;function An(t,e){const n=[],o=(s,r,a={})=>n.push(x("li",{class:`${t}-entry`,...a},s,x("span",null,r)));if(e.type==="schema"){const s=new Set(e.nodes.flatMap(r=>(r.columns??[]).map(a=>a.key)));for(const[r,a]of[["PK","Primary key"],["FK","Foreign key"]])s.has(r)&&n.push(x("li",{class:`${t}-entry`},x("span",{class:`${t}-key-letters`,"aria-hidden":"true"},r),x("span",null,a)))}if(e.type==="flowchart"){const s=new Set(e.nodes.map(r=>r.shape));s.has("terminal")&&o(Dt(t,"terminal"),e.shapeLabels.terminal),s.has("box")&&o(Dt(t,"box"),e.shapeLabels.step),s.has("decision")&&o(Dt(t,"decision"),e.shapeLabels.decision)}const c=new Set(e.type==="sequence"?e.steps.flatMap(s=>"n"in s?[s.kind]:[]):e.edges.filter(s=>!s.fk).map(s=>s.kind)),l=(s,r)=>x("span",{class:`${t}-key-glyph`,"data-ink":r,"aria-hidden":"true"},s);for(const s of["main","plain","dashed"]){const r=e.legend[s];c.has(s)&&r&&o(e.text?l(s==="main"?"━━▶":s==="dashed"?"┄┄▷":"──▶",s==="main"?"main":"plain"):Ce(t,s),r,{"data-line":e.text?void 0:""})}if(e.type==="schema"&&e.edges.length){e.edges.some(r=>!r.card)&&o(Ce(t,"fk"),e.legend.plain??"A foreign key, to the key it references",{"data-line":"","data-when":"drawn"});const s=new Set(e.edges.flatMap(r=>r.card?[r.card.from,r.card.to]:[]));for(const r of we)s.has(r)&&o(Sn(t,r),Ht[r],{"data-line":"","data-when":"drawn","data-card":r});n.push(x("li",{class:`${t}-entry`,"data-when":"stacked"},x("span",{class:`${t}-fk-mark`,"aria-hidden":"true"},e.rtl?"←":"→"),x("span",null,"The table a foreign key references")))}if(e.type==="sequence"){e.bars.length&&o(e.text?l("┃","working"):x("svg",{class:`${t}-swatch`,"data-shape":"bar",...Wt(16,16)},x("path",{class:`${t}-life`,d:"M8 0V16"}),x("rect",{class:`${t}-bar`,x:4.5,y:2.5,width:7,height:11,rx:1.5})),e.legend.activation??"Working",e.text?{}:{"data-when":"drawn"});const s=new Set(e.steps.flatMap(r=>"open"in r?[r.open]:[]));for(const r of["opt","loop","alt"])s.has(r)&&n.push(x("li",{class:`${t}-entry`},x("span",{class:`${t}-key-letters`,"data-op":"","aria-hidden":"true"},r),x("span",null,e.frameWords[r])))}return e.nodes.some(s=>s.focal)&&e.legend.focal&&o(e.text?l("╔═╗","focal"):Dt(t,"focal"),e.legend.focal,{"data-focal":""}),e.groups.length&&e.legend.group&&o(Dt(t,"group"),e.legend.group),n.length?x("div",{class:`${t}-key`},x("ul",{class:`${t}-legend`,"aria-label":"Key"},n)):null}function Ln(t,e){const n=e==="main"?6:6.5;return x("svg",{class:`${t}-arrow`,"data-kind":e,...Wt(20,12)},x("path",{class:`${t}-line`,"data-kind":e,d:`M0 ${n}H${e==="dashed"?19:13}`}),e==="dashed"?x("path",{class:`${t}-tip`,"data-kind":e,"data-open":"",d:`M12 ${n-4}L20 ${n}L12 ${n+4}`}):x("path",{class:`${t}-tip`,"data-kind":e,d:`M20 ${n}L12 ${n-4}L12 ${n+4}Z`}))}var It=t=>x("bdi",null,t);function re(t,e){if(!e.href)return It(e.name);const n=e.name.trimEnd().lastIndexOf(" ");return[n<0?"":e.name.slice(0,n+1),x("span",{class:`${t}-name-end`},n<0?e.name:e.name.slice(n+1))]}function _n(t,e,n){if(n.shape==="decision")return[x("span",{class:`${t}-words`},x("span",{class:`${t}-name`},re(t,n)))];const o=[];return e.type==="data-flow"?o.push(x("span",{class:`${t}-kind`},It(n.kind),x("span",{class:`${t}-lane-word`}," · ",It(n.laneLabel??"")))):n.kind&&o.push(x("span",{class:`${t}-kind`},It(n.kind))),o.push(x("span",{class:`${t}-name`},re(t,n))),n.detail&&o.push(x("span",{class:`${t}-detail`,"data-mono":n.mono?"":void 0},n.mono?x("span",{class:`${t}-runs`},Pt(n.detail).flatMap((c,l)=>[l?" ":"",x("span",{class:`${t}-run`},c)])):It(n.detail))),o}function qn(t,e,n){return[x("span",{class:`${t}-th`},x("span",{class:`${t}-tname`},re(t,e))),x("span",{class:`${t}-rows`},(e.columns??[]).map((o,c)=>x("span",{class:`${t}-row`,"data-row":c,"data-key":o.key},x("span",{class:`${t}-keyseat`},o.key??""),x("span",{class:`${t}-cname`},o.name),o.ref?x("span",{class:`${t}-ctype`,"data-ref":""},`${n.rtl?"←":"→"} `,It(o.ref.table)):o.type?x("span",{class:`${t}-ctype`},It(o.type)):null))),e.more?x("span",{class:`${t}-more`},`+ ${e.more} more`):null]}var je=t=>{const e={32:"space-8",40:"space-10",48:"space-12",64:"space-16"};return e[t]?`var(--basalt-${e[t]})`:`${t}px`};function Jt(t,e,n,o){const{P:c}=t,l=kn(e,o)||o.keep===n.id,s=Tt(e,o),r=o.layout==="drawn"&&o.rows,a=[`--_c:${n.col}`,`--_r:${r?2*n.row:n.row}`,`--_r2:${r?2*n.row2+1:n.row2+1}`];e.type==="data-flow"&&a.push(`--_lc:${n.col+1}`),e.type==="sequence"&&a.push(`--_c2:${n.col+1}`);const d=t.plan;if(d&&n.i>0){const b=Ot(d.gaps,n.id)??32,p=Ot(o.grow,n.id)??0;a.push(`--_gap:${p?`calc(${je(b)} + var(--basalt-space-4) * ${p})`:je(b)}`)}const g=Ot(o.heights,n.id);g&&a.push(`--_h:${g}px`);const f=Ot(De(e),n.id);f&&a.push(`--_mh:${f}px`);const i=Ot(o.words,n.id);i&&a.push(`--_ww:${i}px`);const h=s?o.stop===n.id?0:-1:o.keep===n.id?-1:void 0;return x(n.href?"a":"div",{class:`${c}-node`,href:n.href,target:n.href&&n.blank?"_blank":void 0,rel:n.href&&n.blank?"noopener noreferrer":void 0,"data-link":n.href?n.blank?"external":"":void 0,"data-node":n.id,"data-shape":n.shape,"data-focal":n.focal?"":void 0,"data-branch":n.branch?"":void 0,"data-mark":n.mark?n.mark.id??"":void 0,"data-level":t.level,style:a.join(";"),role:l&&!n.href?"img":void 0,"aria-label":l||n.href?mn(e,n):void 0,tabindex:h},n.shape==="decision"?x("svg",{class:`${c}-diamond`,viewBox:"0 0 100 100",preserveAspectRatio:"none","aria-hidden":"true",focusable:"false"},x("path",{d:"M50 0L100 50L50 100L0 50Z"})):null,n.mark?x("span",{class:`${c}-mark`,"aria-hidden":"true",style:n.mark.onLight?`--_ml:${xe(n.mark.onLight)};--_md:${xe(n.mark.onDark??n.mark.onLight)}`:void 0}):null,n.shape==="table"?qn(c,n,e):_n(c,e,n))}function In(t,e,n){const{P:o}=t,c=[];if(e.type==="data-flow"&&c.push(...e.lanes.map((a,d)=>x("div",{class:`${o}-lane`,style:`--_r:${d+1}`,"aria-hidden":"true"},x("span",{class:`${o}-lane-name`},a.label)))),e.type==="architecture")for(const a of e.groups){const d=Zt(e,a);if(!d)continue;const g=[0,1,2,3].map(f=>_e(e,a,f));c.push(x("div",{class:`${o}-gbox`,"data-group":a.id,"data-depth":a.depth>1?a.depth:void 0,style:`--_c:${d.c1};--_c2:${d.c2+1};--_r:${d.r1};--_r2:${d.r2+1}${g[0]>1?";--_gt:2":""}${g[1]>1?";--_ge:2":""}${g[2]>1?";--_gb:2":""}${g[3]>1?";--_gs:2":""}`,"aria-hidden":"true"},x("span",{class:`${o}-glabel`},It(a.label))))}if(e.text)return[x("pre",{class:`${o}-text`,"aria-hidden":"true","data-art":n.art?"":void 0},x("code",{class:`${o}-text-ink`},Cn(o,e)))];if(e.type==="sequence")return c.push(x("ul",{class:`${o}-cast`},e.nodes.map(a=>x("li",{class:`${o}-actor`,style:e.rtl?`--_ac:${a.col}`:void 0},Jt(t,e,a,n))))),c.push(On(t,e)),c;const l=a=>{const d=a.group?e.groups.find(g=>g.id===a.group):void 0;return d?.parent?e.groups.find(g=>g.id===d.parent):d},s=(a,d,g)=>{const f=t.plan?Ot(n.grow,d[0].id)??0:0,i=d[0],h=t.plan&&i.group===a.id?e.edges.filter((m,M)=>m.to===i.id&&(t.plan.routes[M]==="trunk"||t.plan.routes[M]==="end-down")):[],b=Math.max(0,...h.map(m=>m.label?Kt(m.label):0)),p=[f?`--_ggrow:${f}`:"",b?`--_tl:${b}`:""].filter(Boolean).join(";");return x("div",{class:`${o}-group`,"data-group":a.id,"data-depth":a.depth>1?a.depth:void 0,"data-turn":h.length?"":void 0,style:p||void 0},x("span",{class:`${o}-glabel`,"aria-hidden":"true"},It(a.label)),g)};let r=0;for(;rp.id===g[i].group):void 0;if(!h){f.push(Jt(t,e,g[i],n)),i++;continue}const b=[];for(;iJt(t,e,p,n))))}c.push(s(d,g,f))}return c}function Cn(t,e){const n=[],o=a=>x("span",{class:`${t}-tx-name`},a),c=a=>a==="main"?"━▶":a==="dashed"?"┄▷":"─▶",l=(a,d,g,...f)=>x("span",{class:`${t}-tx-line`,...a,style:g?`--_in:${d+g};--_hang:${g}`:`--_in:${d}`},...f);n.push(l({"data-ink":"names"},0,0,e.nodes.flatMap((a,d)=>[d?" · ":"",o(a.name)])));const s=String(Math.max(1,...e.steps.map(a=>"n"in a?a.n:0))).length;let r=0;for(const a of e.steps){const d=2*r;if("band"in a){n.push(l({"data-ink":"band"},d,0,`── ${a.band} ──`));continue}if("open"in a){n.push(l({"data-ink":"frame"},d,0,x("span",{"data-ink":"op"},`[${a.open}]`),` ${a.label}`)),r++;continue}if("otherwise"in a){n.push(l({"data-ink":"frame"},2*Math.max(0,r-1),0,x("span",{"data-ink":"op"},"[else]"),` ${a.otherwise}`));continue}if("close"in a){r=Math.max(0,r-1),n.push(l({"data-ink":"frame"},2*r,0,"[end]"));continue}const g=e.byId.get(a.from)?.name??a.from,f=e.byId.get(a.to)?.name??a.to,i=s+2;n.push(l({"data-n":a.n},d,i,x("span",{"data-ink":"num"},String(a.n).padStart(s,"0"))," ",o(g)," ",x("span",{class:`${t}-tx-to`},x("span",{"data-ink":a.kind==="main"?"main":"plain"},c(a.kind))," ",f))),n.push(l({"data-n":a.n},d+i,0,x("span",{"data-ink":"label"},a.label))),a.note&&n.push(l({"data-n":a.n},d+i,0,x("span",{"data-ink":"note"},a.note)))}return n}function On(t,e){const{P:n}=t,o=[],c=[],l=()=>c.length?c[c.length-1].el.c:o;let s=null;for(const r of e.steps){if("band"in r){s=null,l().push(x("p",{class:`${n}-band`},x("span",null,r.band)));continue}if("open"in r){s=null;const p=c[c.length-1],m=p?`;--_fis:${r.a===p.a?1:0};--_fie:${r.b===p.b?1:0}`:"",M=x("div",{class:`${n}-frame`,"data-op":r.open,"data-depth":r.depth,style:`--_a:${r.a};--_b:${r.b+1}${m}`},x("span",{class:`${n}-fbox`,"aria-hidden":"true"}),x("p",{class:`${n}-fhead`},x("span",{class:`${n}-ftab`,"aria-hidden":"true"},r.open),x("span",{class:`${n}-flabel`},x("span",{class:t.hidden},`${e.frameWords[r.open]}: `),r.label)));l().push(M),c.push({el:M,a:r.a,b:r.b});continue}if("otherwise"in r){s=null,l().push(x("p",{class:`${n}-felse`},x("span",{class:`${n}-fword`,"aria-hidden":"true"},"else"),x("span",{class:`${n}-flabel`},x("span",{class:t.hidden},`${e.frameWords.else}: `),r.otherwise)));continue}if("close"in r){s=null,c.pop();continue}s||(s=x("ol",{class:`${n}-msgs`,start:r.n}),l().push(s));const a=e.byId.get(r.from),d=e.byId.get(r.to),g=a?.col??1,f=d?.col??1,i=g===f,h=i&&(e.rtl?g!==1:g===e.nodes.length),b=Me(e,r.kind);s.c.push(x("li",{class:`${n}-msg`,"data-kind":r.kind,"data-from":r.from,"data-to":r.to,"data-self":i?h?"start":"end":void 0,style:`--_a:${Math.min(g,f)};--_b:${Math.max(g,f)+1}`},x("span",{class:`${n}-said`},x("span",{class:`${n}-num`},String(r.n)),x("span",{class:`${n}-mlabel`},r.label)),x("span",{class:`${n}-route`},a?.short??r.from," ",x("span",{class:`${n}-to`},Ln(n,r.kind),x("span",{class:t.hidden}," to ")," ",d?.short??r.to,b?` · ${b}`:"")),r.note?x("span",{class:`${n}-note`},r.note):null))}return x("div",{class:`${n}-steps`},o)}function Re(t,e){return Rt(e,`list:${t}`,()=>jn(t,e))}var Bn=Re;function jn(t,e){const n=Math.min(6,e.heading+1),o=f=>x(`h${n}`,{class:`${t}-list-head`},f),c=f=>x("strong",null,f),l=f=>f.href?x("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},c(f.name)):c(f.name),s=f=>x("code",{class:`${t}-code`},f),r=f=>e.byId.get(f)?.name??f,a=f=>{const i=Me(e,f);return i?` (${i})`:""},d=f=>f.focal&&e.legend.focal?` ${Ft(e.legend.focal)}`:"";if(e.type==="architecture"){const f=b=>x("li",null,l(b),b.kind?`, ${b.kind}`:"",b.detail?[". ",b.mono?s(b.detail):b.detail,/[.!?]$/.test(b.detail)?"":"."]:/[.!?]$/.test(b.kind??b.name)?"":".",d(b)),i=[o("Parts")],h=e.nodes.filter(b=>!b.group);h.length&&i.push(x("ul",{class:`${t}-list-items`},h.map(f)));for(const b of e.groups.filter(p=>p.depth===1)){i.push(x("p",{class:`${t}-list-group`},b.label)),b.members.length&&i.push(x("ul",{class:`${t}-list-items`},b.members.map(p=>f(e.byId.get(p)))));for(const p of e.groups.filter(m=>m.parent===b.id))i.push(x("p",{class:`${t}-list-group`,"data-depth":2},p.label)),i.push(x("ul",{class:`${t}-list-items`,"data-depth":2},p.members.map(m=>f(e.byId.get(m)))))}return i.push(o("Connections")),i.push(x("ol",{class:`${t}-list-items`},e.edges.map(b=>x("li",null,c(r(b.from))," to ",c(r(b.to)),b.label?[": ",s(qt(b.label))]:"",`${a(b.kind)}.`)))),i}if(e.type==="flowchart"){const f=i=>(e.byId.get(i)?.i??0)+1;return[x("ol",{class:`${t}-list-items`},e.nodes.map(i=>{const h=e.edges.filter(m=>m.from===i.id),b=i.shape==="decision"?"Decision":i.shape==="terminal"?h.length?"Start":"End":"Step",p=!i.detail&&/[.!?]$/.test(i.name)?" ":". ";return x("li",null,l(i),i.detail?[", ",i.mono?s(i.detail):i.detail]:"",`${p}${b}.`,d(i),h.length?x("ul",{class:`${t}-list-exits`},h.map(m=>x("li",null,m.label?`If ${qt(m.label)}: go to ${f(m.to)}, `:`Then: go to ${f(m.to)}, `,c(r(m.to)),a(m.kind)))):null)}))]}if(e.type==="data-flow")return[x("ol",{class:`${t}-list-items`},e.nodes.map(f=>{const i=e.edges.filter(h=>h.from===f.id);return x("li",null,`${f.laneLabel}: `,l(f),f.detail?[", ",f.mono?s(f.detail):f.detail]:"",".",d(f),i.length?[" Then ",...i.flatMap((h,b)=>[b?"; ":"",`to step ${e.byId.get(h.to).step}, `,c(r(h.to)),h.label?[": ",s(qt(h.label))]:"",a(h.kind)]),"."]:"")}))];if(e.type==="sequence"){const f=[o("Participants"),x("ul",{class:`${t}-list-items`},e.nodes.map(h=>x("li",null,c(h.name),h.kind?`, ${h.kind}`:"",".",d(h),Ee(e,h))))];f.push(o("Messages"));let i=null;for(const h of e.steps){if("band"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`},h.band));continue}if("open"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":h.depth>1?h.depth:void 0},`${e.frameWords[h.open]}: ${h.label}`));continue}if("otherwise"in h){i=null,f.push(x(`h${Math.min(6,n+1)}`,{class:`${t}-list-group`,"data-depth":h.depth>1?h.depth:void 0},`${e.frameWords.else}: ${h.otherwise}`));continue}if("close"in h){i=null;continue}i||(i=x("ol",{class:`${t}-list-items`,start:h.n}),f.push(i)),i.c.push(x("li",null,s(h.label),": ",c(r(h.from))," to ",c(r(h.to)),`${a(h.kind)}.`,h.note?` ${Ft(h.note)}`:""))}return f}const g=[];for(const f of e.nodes)g.push(x(`h${n}`,{class:`${t}-list-group`},f.href?x("a",{href:f.href,target:f.blank?"_blank":void 0,rel:f.blank?"noopener noreferrer":void 0},s(f.name)):s(f.name),d(f))),g.push(x("ul",{class:`${t}-list-items`},[...(f.columns??[]).map(i=>x("li",null,s(i.name),i.key==="PK"?", primary key":i.key==="FK"?", foreign key":"",i.ref?[", references ",s(`${i.ref.table}.${i.ref.column}`),i.card?[" (",$n(f.id,i.ref.table,i.card,s),")"]:""]:i.type?`, ${i.type}`:"")),...f.more?[x("li",null,`and ${f.more} more ${f.more===1?"column":"columns"}`)]:[]]));return g}function Te(t,e=!1){const n=t.type==="architecture"?"part":t.type==="sequence"?"participant":t.type==="schema"?"table":"step";return`${e&&Ut(t)?`Arrow keys move to the nearest ${n} in that direction`:`Arrow keys move to the next or the previous ${n}, in the author's order`}; Home and End go to the ends; Escape clears the trace.${t.nodes.some(c=>c.href)?" Enter opens a part that is a link.":""}`}function ie(t,e=!1){const n=e&&t.type!=="sequence"&&Ut(t)&&t.cols>1&&t.rows>1,o=t.nodes.some(c=>c.href)?[{keys:["Enter"],words:"open"}]:[];return[{keys:n?["←","↑","↓","→"]:["←","→"],words:Ae(t)},{keys:["Home","End"],words:"the ends"},...o,{keys:["Esc"],words:"clear"}]}var Rn=(t,e)=>{for(let n=0;n({col:e.col,rows:[e.row,e.row2]});function Ut(t){return Rt(t,"spatial",()=>{const e=t.nodes.map(l=>({id:l.id,...Tn(t,l)})),n=(l,s)=>{const r=s==="right"||s==="left",a=s==="right"||s==="down",d=b=>r?[b.col,b.col]:b.rows,g=b=>r?b.rows:[b.col,b.col],f=d(l),i=g(l);let h=null;return e.forEach((b,p)=>{if(b===l)return;const m=d(b),M=g(b),L=a?m[0]-f[1]:f[0]-m[1];if(L<1)return;const z=Math.max(0,M[0]-i[1],i[0]-M[1]),v=[z===0?0:1,z===0?L:L+2*z,z,Math.abs(M[0]-i[0]),p];(!h||Rn(v,h.rank))&&(h={id:b.id,rank:v})}),h?.id??null},o=Lt();for(const l of e)o[l.id]={right:n(l,"right"),left:n(l,"left"),down:n(l,"down"),up:n(l,"up")};const c=l=>{const s=new Set([l]),r=[l];for(;r.length;)for(const a of Object.values(o[r.pop()]))a&&!s.has(a)&&(s.add(a),r.push(a));return s.size};return e.every(l=>c(l.id)===e.length)?o:null})}function Xt(t){return Rt(t,"turn-back-lanes",()=>{const e=new Map,n=new Set;if(!le(t))return{lane:e,dropped:n,lanes:0};const o=(a,d)=>(t.byId.get(a)?.row??0)*1e3+d,c=new Map;t.edges.forEach((a,d)=>{const g=`${a.to}.${a.toRow}.${a.card?.to??""}`,f=o(a.from,a.fromRow??0),i=o(a.to,a.toRow??0),h=c.get(g)??{members:[],lo:1/0,hi:-1/0};h.members.push(d),h.lo=Math.min(h.lo,f,i),h.hi=Math.max(h.hi,f,i),c.set(g,h)});const l=[...c.values()].sort((a,d)=>d.hi-d.lo-(a.hi-a.lo)),s=[];let r=0;for(const a of l.reverse()){const d=new Set(s.filter(f=>f.lo<=a.hi&&a.lo<=f.hi).map(f=>f.lane));let g=0;for(;d.has(g);)g++;if(g>1){for(const f of a.members)n.add(f);continue}s.push({lo:a.lo,hi:a.hi,lane:g});for(const f of a.members)e.set(f,g);r=Math.max(r,g+1)}return{lane:e,dropped:n,lanes:r}})}var le=t=>t.type==="schema"&&t.cols===1&&t.edges.length>0;function Yt(t,e,n){const o=n.prefix,c=xn(n.base),l=t.type==="sequence"||t.type==="schema"?null:Ie(t),s={P:o,ids:c,level:n.level,plan:l,hidden:n.hiddenClass},r=e.layout==="drawn",a=Tt(t,e),d=t.type==="sequence"||t.type==="schema"?r:!0,g=`h${t.heading}`,f=[`--_cols:${ae(t)}`];if(t.type==="architecture"&&t.groups.length||r&&e.pad){const i=t.type==="architecture"?Le(t):[0,0,0,0],h=(p,m,M)=>p?p>1?`calc(${p} * var(--basalt-space-${m}))`:`var(--basalt-space-${m})`:M?`var(--basalt-space-${M})`:"0px",b=r&&e.pad?"3":void 0;f.push(`--_gpad:${h(i[0],"8",b)} ${h(i[1],"4")} ${h(i[2],"4",b)} ${h(i[3],"4")}`)}if(l?.gutter&&l.laneCount>2&&f.push(`--_gw:calc(${l.laneCount} * var(--basalt-space-3-5) + var(--basalt-space-3))`),le(t)){const i=t.marks?"var(--basalt-space-6) + var(--basalt-space-1)":"var(--basalt-space-5)",h=Xt(t).lanes>1?`calc(${i} + var(--basalt-space-3))`:t.marks?`calc(${i})`:i;f.push(t.rtl?`--_gpad:0px 0px 0px ${h}`:`--_gpad:0px ${h} 0px 0px`)}return t.type==="schema"&&e.track&&f.push(`--_track:${e.track}px`),x("figure",{class:n.className?`${o} ${n.className}`:o,"aria-labelledby":c.title,"data-type":t.type,"data-cols":ae(t),"data-reach":t.type==="architecture"?qe(t):void 0,"data-gutter":l?.gutter?"":void 0,"data-marks":t.marks?"":void 0,"data-layout":e.layout??(t.unplaced?"stacked":void 0),"data-measured":e.layout?"":void 0,"data-bare":e.bare?"":void 0,"data-motion":t.motion.animated?"animated":void 0,"data-first-visit":t.motion.animated&&t.motion.firstVisit?"":void 0,"data-rtl":t.rtl?"":void 0,"data-viewer":n.viewer?"":void 0,style:f.join(";")},x("div",{class:`${o}-head`},x(g,{id:c.title,class:`${o}-title`},It(t.title)),n.hasSource?x("p",{class:`${o}-source`},x("bdi",null,{slot:"source"})):null),x("div",{class:`${o}-drawing`,style:r&&e.rows?`--_rows:${e.rows};--_row-gap:0px`:void 0,role:d?"group":void 0,"aria-roledescription":d?"diagram":void 0,"aria-labelledby":d?c.title:void 0,"aria-describedby":d?a?`${c.summary} ${c.keys}`:c.summary:void 0,"data-stops":a?"":void 0},In(s,t,e),t.text?null:x("div",{class:`${o}-ink`,"aria-hidden":"true"}),x("span",{class:`${o}-ruler`,"aria-hidden":"true"})),Be(o,t),x("p",{class:`${o}-hint`,"data-kbd-hint":"","aria-hidden":"true"},{slot:"hint"}),Tt(t,e)&&t.type!=="sequence"||r&&t.type==="sequence"?x("p",{class:`${o}-tap-hint`,"aria-hidden":"true"},`Tap ${Ae(t)} to highlight its lines. Tap it again to clear.`):null,x("div",{class:`${o}-foot`},{slot:"toggle"}),x("div",{id:c.list,class:`${o}-list`,hidden:!e.open},Re(o,t)),x("span",{id:c.keys,class:n.hiddenClass},n.viewer?`${Te(t,r)} ${n.viewer}`:Te(t,r)),x("figcaption",{id:c.summary,class:`${o}-summary`},{slot:"summary"}))}function zn(t){const e=getComputedStyle(t),n=(c,l)=>{const s=parseFloat(e.getPropertyValue(`--basalt-${c}`));return Number.isFinite(s)?s:l},o=new Map;return{space:c=>(o.has(c)||o.set(c,n(`space-${c}`,parseFloat(c.replace("-","."))*4)),o.get(c)),node:n("size-diagram-node",144),table:n("size-diagram-table",224),lane:n("size-diagram-lane",120),step:n("size-diagram-step",56),head:n("size-diagram-head",8),guide:n("size-diagram-guide-dash",4),hair:n("size-hairline",1),line:n("size-chart-line",2),cut:n("size-cut",2),dot:n("size-dot",6),dash:n("size-chart-dash",6),dashGap:n("size-chart-dash-gap",4),wide:n("size-breakpoint-container-lg",640),cap:n("size-breakpoint-container",480),radius:n("radius-md",8),radiusXs:n("radius-xs",4),activation:n("size-diagram-activation",8),foot:n("size-diagram-foot",14)}}var Qt=(t,e)=>t==="main"?e.line:e.hair,xt=(t,e)=>{const n=t.getBoundingClientRect();return{l:n.left-e.left,t:n.top-e.top,r:n.right-e.left,b:n.bottom-e.top}},Ct=(t,e,n=.01)=>t.le.l+n&&t.te.t+n,ce=(t,e)=>({l:t.l-e,r:t.r+e,t:t.t-e,b:t.b+e});function Mt(t,e,n){const{l:o,t:c,r:l,b:s}=t.rect,r=(o+l)/2,a=(c+s)/2,d=(l-o)/2,g=(s-c)/2,f=e==="top"||e==="bottom";if(t.shape==="decision"){if(f){const b=n,p=g*Math.max(0,1-Math.abs(b-r)/d);return{x:b,y:e==="top"?a-p:a+p}}const i=n,h=d*Math.max(0,1-Math.abs(i-a)/g);return{x:e==="left"?r-h:r+h,y:i}}if(t.shape==="terminal"){const i=Math.min(d,g);if(f){const m=n,M=Math.min(Math.max(m,o+i),l-i),L=m-M,z=Math.abs(L)>=i?0:Math.sqrt(i*i-L*L);return{x:m,y:Math.abs(L)<1e-6?e==="top"?c:s:e==="top"?a-z:a+z}}const h=n,b=h-a,p=Math.abs(b)>=i?0:Math.sqrt(i*i-b*b);return{x:e==="left"?o+i-p:l-i+p,y:h}}return f?{x:n,y:e==="top"?c:s}:{x:e==="left"?o:l,y:n}}function Wn(t,e,n){const{l:o,t:c,r:l,b:s}=e.rect,r=(o+l)/2,a=(c+s)/2,d=(l-o)/2,g=(s-c)/2;if(e.shape==="decision")return Math.abs(t.x-r)/d+Math.abs(t.y-a)/g<1-n/Math.min(d,g);if(e.shape==="terminal"){const f=Math.min(d,g),i=Math.min(Math.max(t.x,o+f),l-f);return Math.hypot(t.x-i,t.y-a)o+n&&t.xc+n&&t.ymatchMedia("(forced-colors: active)").matches;function Hn(t,e){const n=t.querySelector(`.${e}-ruler`),o=new Map;return(c,l)=>{const s=`${l}|${c}`;return o.has(s)||(n.setAttribute("data-f",l),n.textContent=c,o.set(s,n.getBoundingClientRect().width),n.textContent=""),o.get(s)}}var Pt=t=>t?t.split(/\s+/).filter(Boolean):[];function Dn(t,e,n){const o=e.space;let c=e.node,l=e.table;for(const a of t.nodes){if(a.shape==="table"){for(const p of a.columns??[]){const m=p.ref?`${t.rtl?"←":"→"} ${p.ref.table}`:p.type??"",M=o("6")+n(p.name,"mono")+(m?o("3")+n(m,"mono"):0)+2*o("3")+2*e.hair;l=Math.max(l,Math.ceil(M))}l=Math.max(l,Math.ceil(n(a.name,"table")+2*o("3")+2*e.hair+(a.href?16+o("1-5"):0)));continue}const d=a.shape==="terminal"?2*o("5"):2*o("3"),g=a.mark&&!Fn()?(a.shape==="participant"?2:1)*o("6"):0;let f=0;const i=a.href?16+o("1-5"):0,h=Pt(a.name);if(h.forEach((p,m)=>{f=Math.max(f,n(p,a.shape==="decision"?"name-500":"name")+(a.kind?0:g)+(m===h.length-1?i:0))}),t.type!=="data-flow")for(const p of Pt(a.kind))f=Math.max(f,n(p,"mono")+g);for(const p of Pt(a.detail))f=Math.max(f,n(p,a.mono?"mono":"sans"));const b=a.shape==="decision"?f/.62:f+d+2*e.hair;c=Math.max(c,Math.ceil(b))}const s=ae(t);let r;return t.type==="data-flow"?r=e.lane+s*(c+o("12")):t.type==="schema"?r=s*l+(s-1)*(o("12")+(t.marks?o("3"):0))+(le(t)?(t.marks?o("6")+o("1"):o("5"))+(Xt(t).lanes>1?o("3"):0):0):t.type==="sequence"?r=s*c+(s-1)*o("5"):r=s*c+(s-1)*o("16")+qe(t)*o("4"),{track:c,table:l,least:Math.max(e.wide,r)}}function We(t,e,n=!1){const o=n?c=>-Math.round(-c):Math.round;return{x:(c,l)=>l%2===1?o(c+t-.5)+.5-t:o(c+t)-t,y:(c,l)=>l%2===1?Math.round(c+e-.5)+.5-e:Math.round(c+e)-e}}function de(t){const e=t[t.length-2],n=t[t.length-1];return Math.abs(e.x-n.x)<.01?n.y>e.y?"down":"up":n.x>e.x?"right":"left"}function Ne(t,e,n){const o=t.map(l=>({...l}));for(let l=1;l=2){const a=c[c.length-2];if(Math.abs(a.x-r.x)<.01&&Math.abs(r.x-s.x)<.01||Math.abs(a.y-r.y)<.01&&Math.abs(r.y-s.y)<.01){c[c.length-1]=s;continue}}c.push(s)}}return c}var _t=t=>t.slice(1).map((e,n)=>[t[n],e]);function te(t,e,n){const o=[];for(let l=0;lMath.min(p.x,m.x)+.75&&zMath.min(M.y,L.y)+.75&&vl.split(/\s+/).map(parseFloat).filter(s=>Number.isFinite(s)),o=(l,s,r)=>{const a=[];let d=s;for(const g of l)a.push([d,d+g]),d+=g+r;return a},c=o(n(e.gridTemplateRows),parseFloat(e.paddingTop)||0,parseFloat(e.rowGap)||0);return{cols:o(n(e.gridTemplateColumns),parseFloat(e.paddingLeft)||0,parseFloat(e.columnGap)||0),rows:t.style.getPropertyValue("--_rows").trim()?c.filter((l,s)=>s%2===1):c}}var ct=t=>t==="left"||t==="right",Fe={top:"bottom",bottom:"top",left:"right",right:"left"};function fe(t,e){return t.row===e.row?e.col>t.col?["right","left"]:["left","right"]:t.col===e.col?e.row>t.row?["bottom","top"]:["top","bottom"]:[e.col>t.col?"right":"left",e.row>t.row?"top":"bottom"]}function He(t,e,n){const o=[];t.edges.forEach((l,s)=>{const r=t.byId.get(l.from),a=t.byId.get(l.to),[d,g]=e[s],f=r.row===a.row&&ct(d)&&ct(g)&&d===Fe[g]||r.col===a.col&&!ct(d)&&!ct(g)&&d===Fe[g];o.push({edge:s,end:"from",node:r,side:d,far:a,straight:f,f:.5},{edge:s,end:"to",node:a,side:g,far:r,straight:f,f:.5})});const c=new Map;for(const l of o){const s=`${l.node.id}.${l.side}`;c.has(s)||c.set(s,[]),c.get(s).push(l)}for(const[l,s]of c){if(s[0].node.shape==="decision")continue;const r=p=>ct(p.side)?p.far.row-p.node.row:p.far.col-p.node.col,a=s.filter(p=>p.straight),d=s.filter(p=>!p.straight);if(d.sort((p,m)=>r(p)-r(m)||(ct(p.side)?p.far.col-m.far.col:p.far.row-m.far.row)*(r(p)<0?1:-1)),s.length>3&&n(`${l.replace(".","'s ")} side has ${s.length} lines; more than three is an error: use another side`),!a.length){d.length===2?(d[0].f=.25,d[1].f=.75):d.length===3?(d[0].f=.25,d[1].f=.5,d[2].f=.75):d.length>3&&d.forEach((p,m)=>{p.f=(m+1)/(d.length+1)});continue}const g=new Map;for(const p of a)g.has(p.far.id)||g.set(p.far.id,[]),g.get(p.far.id).push(p);for(const p of g.values())p.length>1&&p.sort((m,M)=>m.edge-M.edge).forEach((m,M)=>{m.f=p.length===2?M===0?.25:.75:(M+1)/(p.length+1)});const f=Math.min(...a.map(p=>p.f)),i=Math.max(...a.map(p=>p.f)),h=d.filter(p=>r(p)<0),b=d.filter(p=>r(p)>=0);h.forEach((p,m)=>{p.f=f*(m+1)/(h.length+1)}),b.forEach((p,m)=>{p.f=i+(1-i)*(m+1)/(b.length+1)})}return o}function De(t,e=8,n=8){return Rt(t,`port-floors:${e}:${n}`,()=>{const o=Lt();if(t.type!=="architecture"&&t.type!=="flowchart"&&t.type!=="data-flow")return o;const c=t.edges.map(s=>{const r=t.byId.get(s.from),a=t.byId.get(s.to),[d,g]=fe(r,a);return[s.fromSide??d,s.toSide??g]}),l=new Map;for(const s of He(t,c,()=>{})){if(!ct(s.side)||s.node.shape!=="box")continue;const r=`${s.node.id}.${s.side}`;l.has(r)||l.set(r,[]),l.get(r).push(s.f)}for(const[s,r]of l){if(r.length<2)continue;const a=r.slice().sort((f,i)=>f-i).filter((f,i,h)=>i===0||f-h[i-1]>1e-9);let d=Math.max(e/a[0],e/(1-a[a.length-1]));for(let f=1;f{const s=t.byId.get(l.dataset.node);s&&c.set(s.id,{id:s.id,rect:xt(l,n),shape:s.shape,i:s.i})}),c}function Ke(t,e){const n=e.head,o=e.head/2,{x:c,y:l}=t.tip;return t.dir==="down"?{l:c-o,r:c+o,t:l-n,b:l}:t.dir==="up"?{l:c-o,r:c+o,t:l,b:l+n}:t.dir==="right"?{l:c-n,r:c,t:l-o,b:l+o}:{l:c,r:c+n,t:l-o,b:l+o}}var ue=(t,e,n)=>({l:Math.min(t.x,e.x)-n/2,r:Math.max(t.x,e.x)+n/2,t:Math.min(t.y,e.y)-n/2,b:Math.max(t.y,e.y)+n/2});function Ze(t,e,n,o,c=!1){const l=(r,a)=>{const d=r+a-Math.floor(r+a);return d<.005||d>.995?[0]:d<=.5?[-d,1-d]:[1-d,-d]},s=c?l(-t.r,-e).map(r=>-r):l(t.l,e);for(const r of l(t.t,n))for(const a of s){if(!a&&!r)return t;const d={l:t.l+a,r:t.r+a,t:t.t+r,b:t.b+r};if(o(d))return d}return t}function Vn(t,e,n,o,c,l,s,r,a){const d=s.space,g=[],f=[],i=[],h=[],b=d("1"),p=e.filter(m=>t.edges[m.i]?.label).sort((m,M)=>+(t.edges[M.i].kind==="main")-+(t.edges[m.i].kind==="main")||m.i-M.i);for(const m of p){const M=t.edges[m.i].label,L=r(M,"label"),z=16*Kt(M),v=m.pts.length-2,O=[];_t(m.pts).forEach(([q,D],T)=>{const R=Math.abs(q.y-D.y)<.01,H=R?q.x:q.y;let Q=R?D.x:D.y;const at=Math.sign(Q-H)||1;T===v&&(Q-=at*s.head);let it=[[H,Q]];for(const et of c)for(const nt of R?[et.l,et.r]:[et.t,et.b]){const tt=R?q.y:q.x;(R?tt>et.t&&ttet.l&&ttnt>Math.min(u,w)+1&&nt{const tt=(et+nt)/2,$=R?{x:tt,y:q.y}:{x:q.x,y:tt};return!c.some(u=>$.x>u.l&&$.xu.t&&$.y1&&yt(et,nt)?1:0})}),O.sort((q,D)=>D.pri-q.pri||D.len-q.len);let B=null,j=!1;const F=(q,D=!0)=>{const T=ce(q,b);return D&&(q.ll.r||q.tl.b)||n.some(R=>ze(T,R))||g.some(R=>Ct(T,R))||o.heads.some(R=>Ct(T,R))||o.rects.some(R=>Ct(T,R))?!1:!e.some(R=>R.i!==m.i&&_t(R.pts).some(([H,Q])=>Ct(T,ue(H,Q,R.width))))};for(const q of O){for(const D of[1/2,1/3,2/3]){const T=q.p+(q.q-q.p)*D,R=[],H=d("2")+m.width/2;if(q.horiz?(q.len>=L+2*d("1")+d("3-5")&&R.push({box:{l:T-L/2-d("1"),r:T+L/2+d("1"),t:q.c-z/2,b:q.c+z/2},on:!0}),R.push({box:{l:T-L/2,r:T+L/2,t:q.c-H-z,b:q.c-H},on:!1}),R.push({box:{l:T-L/2,r:T+L/2,t:q.c+H,b:q.c+H+z},on:!1})):(q.len>=z+d("3")&&R.push({box:{l:q.c-L/2-d("1"),r:q.c+L/2+d("1"),t:T-z/2,b:T+z/2},on:!0}),R.push({box:{l:q.c+H,r:q.c+H+L,t:T-z/2,b:T+z/2},on:!1}),R.push({box:{l:q.c-H-L,r:q.c-H,t:T-z/2,b:T+z/2},on:!1})),B=R.find(Q=>F(Q.box))??null,B)break;!j&&R.some(Q=>F(Q.box,!1))&&(j=!0)}if(B)break}if(!B){i.push(m.i),j&&h.push(m.i);continue}const rt=Ze(B.box,a.ox,a.oy,q=>F(q));g.push(rt),f.push({i:m.i,text:M,box:rt,on:B.on})}return{labels:f,unseated:i,bounded:h}}function Je(t,e,n,o){const c=[],l=[];return t.querySelectorAll(`.${n}-gbox, .${n}-group`).forEach(s=>{if(s.getClientRects().length===0||getComputedStyle(s).display==="contents")return;const r=xt(s,e);l.push(r),c.push({l:r.l,r:r.r,t:r.t,b:r.t+1},{l:r.l,r:r.r,t:r.b-1,b:r.b},{l:r.l,r:r.l+1,t:r.t,b:r.b},{l:r.r-1,r:r.r,t:r.t,b:r.b});const a=s.querySelector(`:scope > .${n}-glabel`);a&&a.getClientRects().length&&c.push(xt(a,e))}),t.querySelectorAll(`.${n}-lane`).forEach((s,r)=>{if(!s.getClientRects().length)return;const a=xt(s,e);r>0&&c.push({l:a.l,r:a.r,t:a.t-o/2-.5,b:a.t-o/2+.5});const d=s.querySelector(`.${n}-lane-name`);d&&c.push(xt(d,e))}),{obstacles:{rects:c,heads:[]},groups:l}}function Ue(t,e){const{m:o,tk:c,P:l,drawing:s,origin:r,warn:a}=t,d=c.space,g=Ve(o,s,r,l),f=[...g.values()],i=Gn(s),h=r.left-Math.floor(r.left),b=r.top-Math.floor(r.top),p=We(h,b),m=s.clientWidth,M=s.clientHeight,L=y=>o.type==="data-flow"?y.col+1:y.col,z=parseFloat(getComputedStyle(s).rowGap)||0,v={w:m,h:M,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:h,oy:b};if(o.type==="sequence")return Zn(t,v,p);let O,B=[];o.type==="schema"?O=o.edges.map(y=>{const S=o.byId.get(y.from),E=o.byId.get(y.to);if(S.col===E.col){const W=!((o.rtl?S.col===1:S.col===o.cols)&&o.cols>1)===!o.rtl?"right":"left";return[W,W]}return E.col>S.col?["right","left"]:["left","right"]}):(O=o.edges.map(y=>{const S=o.byId.get(y.from),E=o.byId.get(y.to),[k,A]=fe(S,E);return[y.fromSide??k,y.toSide??A]}),B=He(o,O,a||(()=>{})));const j=(y,S)=>{const E=s.querySelector(`.${l}-node[data-node="${CSS.escape(y)}"] .${l}-row[data-row="${S}"]`);if(!E)return 0;const k=xt(E,r);return(k.t+k.b)/2},F=new Map;if(o.type==="schema"){const y=new Map;o.edges.forEach((E,k)=>{const A=`${E.to}.${E.toRow}.${O[k][1]}`;y.set(A,[...y.get(A)??[],k])});const S=E=>{const k=o.edges[E].card?.to;return k==="one"?0:k==="zero-or-one"?1:2};for(const E of y.values()){const k=[...new Set(E.map(S))].sort((A,W)=>A-W);if(k.length>1)for(const A of E)F.set(A,(k.indexOf(S(A))-(k.length-1)/2)*d("2"))}}const rt=y=>Math.round(y+h)-h,q=o.edges.map((y,S)=>{const[E,k]=O[S],A=g.get(y.from),W=g.get(y.to),J=Qt(y.kind,c);if(y.fk){const P=j(y.from,y.fromRow),ot=j(y.to,y.toRow)+(F.get(S)??0),gt=p.y(P,J),Bt=p.y(ot,J),Et=E==="right"?A.rect.r:A.rect.l,St=k==="right"?W.rect.r:W.rect.l;return{p1:{x:y.card?rt(Et):Et,y:gt},p2:{x:y.card?rt(St):St,y:Bt},r1:P,r2:Math.abs(gt-Bt)<.01?P:ot}}const K=B.find(P=>P.edge===S&&P.end==="from").f,Y=B.find(P=>P.edge===S&&P.end==="to").f;let U=Ge(A,E,K),Z=Ge(W,k,Y);const N=ct(E)?U.y:U.x;let G=ct(k)?Z.y:Z.x;return ct(E)?U={...U,y:p.y(U.y,J)}:U={...U,x:p.x(U.x,J)},ct(k)?Z={...Z,y:p.y(Z.y,J)}:Z={...Z,x:p.x(Z.x,J)},ct(E)&&ct(k)&&Math.abs(U.y-Z.y)<1.01&&(Z={...Z,y:U.y},G=N),!ct(E)&&!ct(k)&&Math.abs(U.x-Z.x)<1.01&&(Z={...Z,x:U.x},G=N),U=ct(E)?Mt(A,E,U.y):Mt(A,E,U.x),Z=ct(k)?Mt(W,k,Z.y):Mt(W,k,Z.x),{p1:U,p2:Z,r1:N,r2:G}}),D=new Set,T=(y,S)=>{D.has(y)||(D.add(y),a?.(`${o.edges[y].from} to ${o.edges[y].to} ${S}, so its line is not drawn; its row still writes the target`))};for(const y of Xt(o).dropped)T(y,"would need a third lane of turn-backs");const R=new Map,H=Lt();o.type==="schema"&&o.edges.forEach((y,S)=>{const E=o.byId.get(y.from),k=o.byId.get(y.to);if(Math.abs(E.col-k.col)<2)return;const A=Math.min(E.col,k.col),W=Math.max(E.col,k.col),J=o.nodes.filter(ot=>ot.col>A&&ot.colgt.row<=ot&>.row2>=ot+1)||Y.push({key:`g${ot}`,y:(K[ot-1][1]+K[ot][0])/2,inner:!0});Y.push({key:"top",y:K[0][0]-d("4"),inner:!1},{key:"bottom",y:K[K.length-1][1]+d("4"),inner:!1});const U=(q[S].r1+q[S].r2)/2,Z=t.pick?.[S]??Y.slice().sort((ot,gt)=>Math.abs(ot.y-U)-Math.abs(gt.y-U)||Number(gt.inner)-Number(ot.inner)||ot.y-gt.y)[0].key;H[S]=Z;const N=O[S][0]==="right"?E.col:E.col-1,G=i.cols[N-1],P=i.cols[N];R.set(S,{corridor:Z,first:G&&P?{key:`c${N}`,span:[G[1],P[0]]}:null,y:0})});const Q=new Map;for(const[y,S]of R){const E=o.edges[y],k=Q.get(S.corridor)??[],A=k.find(W=>{const J=o.edges[W[0]];return J.to===E.to&&J.toRow===E.toRow&&O[W[0]][1]===O[y][1]&&Math.abs(q[W[0]].p2.y-q[y].p2.y)<.5});A?A.push(y):k.length>=2?T(y,"would need a third lane in its corridor"):k.push([y]),Q.set(S.corridor,k)}for(const y of[...R.keys()])D.has(y)&&R.delete(y);const at=y=>{const S=o.edges[y[0]];return Math.abs(o.byId.get(S.from).col-o.byId.get(S.to).col)*1e4+Math.abs(q[y[0]].p1.x-q[y[0]].p2.x)},it=(y,S,E)=>{const k=i.rows;if(y==="top")return k[0][0]-d("4")-S*d("3");if(y==="bottom")return k[k.length-1][1]+d("4")+S*d("3");const A=Number(y.slice(1));return(k[A-1][1]+k[A][0])/2+(S-(E-1)/2)*d("3")},yt=(y,S)=>S.forEach((E,k)=>E.forEach(A=>{R.get(A).y=it(y,k,S.length)})),dt=()=>{for(const[y,S]of Q){const E=S.map(k=>k.filter(A=>R.has(A))).filter(k=>k.length);Q.set(y,E),yt(y,y==="top"||y==="bottom"?E.slice().sort((k,A)=>at(k)-at(A)):E.slice().sort((k,A)=>at(A)-at(k)))}};dt();const et=new Map,nt=new Set,tt=new Map,$=(y,S,E,k,A)=>{et.has(y)||et.set(y,{span:S,vertical:E,members:new Map});const W=et.get(y);W.members.has(k)||W.members.set(k,[]),W.members.get(k).push(A)},u=()=>{et.clear(),nt.clear(),tt.clear(),o.edges.forEach((y,S)=>{if(D.has(S))return;const E=R.get(S);E?.first&&$(E.first.key,E.first.span,!0,`far:${S}`,-(S+1));const[k,A]=O[S],{p1:W,p2:J}=q[S],K=o.byId.get(y.from),Y=o.byId.get(y.to);let U=null,Z=null,N=!1;if(k===A){if(ct(k)){const G=k==="right"?Math.max(L(K),L(Y)):Math.min(L(K),L(Y))-1,P=i.cols[G-1],ot=i.cols[G];P&&ot&&(U=`c${G}`,Z=[P[1],ot[0]],N=!0)}else{const G=k==="bottom"?Math.max(K.row2,Y.row2):Math.min(K.row,Y.row)-1,P=i.rows[G-1],ot=i.rows[G];P&&ot&&(U=`r${G}`,Z=[P[1],ot[0]],N=!1)}U&&nt.add(S)}else if(ct(k)&&ct(A)&&(E||Math.abs(W.y-J.y)>.5)){const G=L(Y),P=A==="left",ot=i.cols[(P?G-1:G)-1],gt=i.cols[(P?G:G+1)-1];ot&>&&(U=`c${P?G-1:G}`,Z=[ot[1],gt[0]],N=!0)}else if(!ct(k)&&!ct(A)&&Math.abs(W.x-J.x)>.5){const P=A==="top"?Y.row-1:Y.row2,ot=i.rows[P-1],gt=i.rows[P];ot&>&&(U=`r${P}`,Z=[ot[1],gt[0]],N=!1)}!U||!Z||(E&&tt.set(S,Z),$(U,Z,N,`${y.to}.${A}.${Math.round(N?J.y:J.x)}`,S))})};u();const w=new Map,C=y=>{const[S,E]=O[y],{p1:k,p2:A}=q[y],W=R.get(y);if(W){const J=tt.get(y),K=w.get(-(y+1))??(W.first?(W.first.span[0]+W.first.span[1])/2:k.x),Y=w.get(y)??(J?(J[0]+J[1])/2:A.x);return[k,{x:K,y:k.y},{x:K,y:W.y},{x:Y,y:W.y},{x:Y,y:A.y},A]}if(ct(S)&&ct(E)){if(S===E){const K=d(o.marks?"6":"4")+(o.type==="schema"&&o.cols===1?(Xt(o).lane.get(y)??0)*d("3"):0),Y=w.get(y)??(S==="right"?Math.max(k.x,A.x)+K:Math.min(k.x,A.x)-K);return[k,{x:Y,y:k.y},{x:Y,y:A.y},A]}if(Math.abs(k.y-A.y)<=.5)return[k,{x:A.x,y:k.y}];const J=w.get(y)??(k.x+A.x)/2;return[k,{x:J,y:k.y},{x:J,y:A.y},A]}if(!ct(S)&&!ct(E)){if(S===E){const K=w.get(y)??(S==="bottom"?Math.max(k.y,A.y)+d("4"):Math.min(k.y,A.y)-d("4"));return[k,{x:k.x,y:K},{x:A.x,y:K},A]}if(Math.abs(k.x-A.x)<=.5)return[k,{x:k.x,y:A.y}];const J=w.get(y)??(k.y+A.y)/2;return[k,{x:k.x,y:J},{x:A.x,y:J},A]}return ct(S)?[k,{x:A.x,y:k.y},A]:[k,{x:k.x,y:A.y},A]},I=y=>{const S=o.edges[y],E=Qt(S.kind,c),k=C(y),A=Ne(k,E,p);let W;return k.length===A.length&&(W=_t(k).map(([J,K])=>Math.abs(J.y-K.y)<.75?(J.y+K.y)/2:(J.x+K.x)/2),W[0]=q[y].r1,W.length>1&&(W[W.length-1]=q[y].r2)),{i:y,from:S.from,to:S.to,kind:S.kind,pts:A,tip:A[A.length-1],dir:de(A),dot:S.fk&&!S.card?A[0]:void 0,card:S.card,width:E,axes:W}},_=()=>o.edges.flatMap((y,S)=>D.has(S)?[]:[I(S)]);let X=null;const V=y=>{X??(X=_());const S=X.map(E=>y.has(E.i)?I(E.i):E);return{lines:S,score:Kn(S,y)*1e5+te(S,void 0,y).length*1e3+pe(S.filter(E=>y.has(E.i)),f,o).length}},ft=(y,S)=>{const E=y.flatMap(k=>{const A=k<0?-k-1:k,{p1:W,p2:J}=q[A],K=R.get(A);return K?k<0?[W.y,K.y]:[K.y,J.y]:S?[W.y,J.y]:[W.x,J.x]});return[Math.min(...E),Math.max(...E)]},st=y=>y<0?-y-1:y,lt=y=>{const S=[...y.members.values()].map(k=>({members:k,run:ft(k,y.vertical)})).sort((k,A)=>k.run[0]-A.run[0]),E=[];for(const k of S){const A=E[E.length-1];A&&A.some(W=>W.run[0]!(k.length===1&&k[0].members.every(A=>nt.has(A))))},pt=y=>(S,E)=>y[S].run[0]{const S=pt(y),E=[];return y.forEach((k,A)=>{let W=0;for(;E.some((J,K)=>J===W&&S(A,K));)W++;E.push(W)}),E},ut=y=>Math.max(0,...kt(y))+1;if(o.marks)for(let y=0;y3){S=W.map(J=>J.members.map(st));break}if(!S)break;const E=A=>Math.max(...A),k=S.filter(A=>A.some(W=>R.has(W))).sort((A,W)=>E(W)-E(A))[0]??S.slice().sort((A,W)=>E(W)-E(A))[0];for(const A of k)T(A,"would need a fourth lane in a marked gutter"),R.delete(A);u()}const $t=(y,S,E,k=!1)=>{const A=o.rtl&&k?E-1-S:S,W=y[1]-y[0];if(!o.marks)return y[0]+W/(E+1)*(A+1);const J=c.foot+c.radiusXs,K=E>1?Math.min(W/(E+1),(W-2*J)/(E-1)):0;return(y[0]+y[1])/2+(A-(E-1)/2)*K};dt();for(const[y,S]of Q){if(y==="top"||y==="bottom"||S.length<2)continue;const E=new Set(S.flat());let k=S,A=1/0;for(const W of he(S.slice().sort((J,K)=>at(K)-at(J)))){yt(y,W),X=null;const J=V(E);J.scoreY.members);if(o.marks){const Y=ut(S),U=pt(S),Z=S.length,N=new Set(E.flat().map(st)),G=Et=>Et.forEach((St,zt)=>E[zt].forEach(jt=>w.set(jt,$t(y.span,St,Y,y.vertical))));let P=kt(S),ot=1/0,gt=null;const Bt=[P];if(Y**Z<=729)for(let Et=0;EtMath.floor(Et/Y**jt)%Y);St.every((zt,jt)=>St.every((ne,Vt)=>Vt<=jt||zt!==ne||!U(jt,Vt)))&&Bt.push(St)}for(const Et of Bt){G(Et);const St=V(N);St.scoreZ.forEach(G=>w.set(G,$t(y.span,N,k,y.vertical))));const U=V(A);U.scoreY.forEach(Z=>w.set(Z,$t(y.span,U,k,y.vertical)))),X=K}if(v.lines=_(),o.marks&&(v.lines=v.lines.filter(y=>{if(!y.card)return!0;const S=_t(y.pts),E=([A,W])=>Math.hypot(W.x-A.x,W.y-A.y),k=S.length===1?2*c.foot:c.foot+c.radiusXs-.5;return E(S[0])>=k&&E(S[S.length-1])>=k?!0:(T(y.i,"has no room for its marks at an end"),R.delete(y.i),!1)})),R.size){const y=new Set([...R.values()].map(E=>E.corridor)),S=[y.has("top")?"var(--basalt-space-8)":"0px"];for(let E=1;E<=o.rows;E++)S.push("auto",EKe(y,c));const vt=Vn(o,v.lines,f,bt,wt,{l:0,t:0,r:m,b:M},c,e,{ox:h,oy:b});return v.labels=vt.labels,v.unseated=vt.unseated,v.bounded=vt.bounded,v.overlaps=[...new Set(Xe(v.lines,null).flat())],v}function Kn(t,e){return Xe(t,e).length}function Xe(t,e){const n=[];for(let o=0;o=r)continue;const[m,M]=i?[a.x,d.x]:[a.y,d.y],[L,z]=i?[g.x,f.x]:[g.y,f.y];Math.min(Math.max(m,M),Math.max(L,z))-Math.max(Math.min(m,M),Math.min(L,z))>1&&n.push([l.i,s.i])}}return n}function*he(t){if(t.length<=1){yield t.slice();return}if(t.length>5){yield t.slice();return}for(let e=0;e{const a=r===l.pts.length-1?Math.max(l.width/2,o.head/2):l.width/2;return s.x-a<-.5||s.x+a>e+.5||s.y-a<-.5||s.y+a>n+.5})&&c.push(l.i);return c}function pe(t,e,n){const o=[];for(const c of t){const l=_t(c.pts);e.some(s=>l.some(([r,a])=>Nn(r,a,s)))&&o.push(c.i)}return o}function Zn(t,e,n){const{m:o,tk:c,P:l,drawing:s,origin:r}=t,a=c.space,d=new Map;s.querySelectorAll(`.${l}-node`).forEach(v=>d.set(v.dataset.node,xt(v,r)));const g=s.querySelector(`.${l}-steps`),f=g?xt(g,r).b:e.h,i=v=>{const O=d.get(v);return O?n.x((O.l+O.r)/2,c.hair):0};for(const v of o.nodes){const O=d.get(v.id);O&&e.lifelines.push({x:i(v.id),y1:O.b,y2:f})}const h=v=>d.get(v.id),b=new Map;s.querySelectorAll(`.${l}-msg`).forEach(v=>{const O=xt(v,r);b.set(Number(v.querySelector(`.${l}-num`)?.textContent??0),(O.t+O.b)/2)});const p=c.activation,m=p/2,M=v=>{const O=o.byId.get(v.who);if(!O)return null;const B=i(v.who),F=(O.i===o.nodes.length-1&&o.nodes.length>1?-1:1)*(o.rtl?-1:1),rt=(v.depth-1)*a("1")*F,q=b.get(v.from)??0,D=b.get(v.to)??q,T=v.from===v.to;return{l:n.x(B-m+rt,c.hair),r:n.x(B+m+rt,c.hair),t:n.y(T?q-a("2")-a("1"):q,c.hair),b:n.y(T?q+a("2")+a("1"):D,c.hair)}},L=o.bars.map(v=>({bar:v,rect:M(v)})).filter(v=>v.rect);e.bars=L.map(v=>v.rect);const z=(v,O,B)=>L.filter(({bar:j})=>j.who===v&&j.to>=O&&(B?j.from<=O:j.fromF.bar.depth-j.bar.depth)[0]?.rect;s.querySelectorAll(`.${l}-msg`).forEach(v=>{const O=v.dataset.from,B=v.dataset.to,j=v.dataset.kind??"plain",F=Qt(j,c),rt=xt(v,r),q=n.y((rt.t+rt.b)/2,F),D=Number(v.querySelector(`.${l}-num`)?.textContent??0);let T=i(O),R=i(B),H;if(O===B){const nt=v.dataset.self==="start"?-a("6"):a("6"),tt=z(O,D,!0),$=tt?nt>0?tt.r:tt.l:T,u=n.y(q-a("2"),F),w=n.y(q+a("2"),F);H=[{x:$,y:u},{x:n.x(T+nt,F),y:u},{x:n.x(T+nt,F),y:w},{x:$,y:w}]}else{const nt=R>T?1:-1,tt=z(O,D,!1),$=z(B,D,!0);tt&&(T=nt>0?tt.r:tt.l),$&&(R=nt>0?$.l:$.r),H=[{x:T,y:q},{x:R,y:q}]}e.lines.push({i:D,from:O,to:B,kind:j,pts:H,tip:H[H.length-1],dir:de(H),width:F});const Q=v.querySelector(`.${l}-said`),at=v.querySelector(`.${l}-note`),it=o.byId.get(O),yt=o.byId.get(B);if(!it||!yt)return;const dt=O===B?(()=>{const nt=o.nodes.find($=>$.col===it.col+(v.dataset.self==="start"?-1:1)),tt=nt?i(nt.id):v.dataset.self==="start"?0:e.w;return Math.abs(tt-T)-a("6")-a("2-5")-a("2")})():Math.abs(R-T)-2*a("2");Math.max(Q?Q.getBoundingClientRect().width:0,at?at.getBoundingClientRect().width:0)>dt+.5&&e.unseated.push(D)}),s.querySelectorAll(`.${l}-fhead`).forEach(v=>{const O=v.parentElement?.querySelector(`:scope > .${l}-fbox`);if(!O)return;[...v.children].reduce((j,F)=>j+F.getBoundingClientRect().width,0)+a("3")>O.getBoundingClientRect().width+.5&&(e.misfit??(e.misfit=[])).push(`the frame "${v.querySelector(`.${l}-flabel`)?.textContent??""}" is wider than its participants`)});{const v=[...s.querySelectorAll(`.${l}-fbox`)].flatMap(O=>{const B=xt(O,r);return[{x:B.l+.5,t:B.t,b:B.b},{x:B.r-.5,t:B.t,b:B.b}]});v.length&&s.querySelectorAll(`.${l}-said, .${l}-note, .${l}-band > span`).forEach(O=>{if(!O.getClientRects().length)return;const B=ce(xt(O,r),a("1"));v.some(j=>B.lj.x&&B.tj.t)&&(e.misfit??(e.misfit=[])).push(`"${O.textContent?.trim()??""}" would lie on a frame's side`)})}return e}function Jn(t,e,n,o,c){const l=[];for(const[s,r]of t){if(!r.getClientRects().length)continue;const a=xt(r,n),d=xt(s,n),g=getComputedStyle(r),f=getComputedStyle(s),i={l:a.l+(parseFloat(g.paddingLeft)||0),r:a.r-(parseFloat(g.paddingRight)||0)},h=i.r-i.l,b=d.l+(parseFloat(f.borderLeftWidth)||0),p=d.r-(parseFloat(f.borderRightWidth)||0),m=[];for(const j of e)for(const[F,rt]of _t(j.pts)){const q=ue(F,rt,j.width);q.ta.t&&m.push({l:q.l,r:q.r})}const M=c("2-5"),L=j=>m.every(F=>F.r<=j-M+.01||F.l>=j+h+M-.01);if(L(i.l))continue;const z=m.map(j=>o?i.r-(j.l-M):j.r+M-i.l).filter(j=>j>0).sort((j,F)=>j-F),v=j=>o?i.l-j:i.l+j,O=j=>o?v(j)>=b+c("3")-.01:v(j)+h<=p-c("3")+.01,B=z.find(j=>O(j)&&L(v(j)));if(B===void 0){l.push(r.textContent??"");continue}r.style.setProperty("--_gx",`${Math.round(B*100)/100}px`)}return l}function Qe(t,e,n,o=Lt()){const{m:c,tk:l,P:s,drawing:r,origin:a}=t,d=l.space,g=Ve(c,r,a,s),f=[...g.values()],i=a.left-Math.floor(a.left),h=a.top-Math.floor(a.top),b=We(i,h,!!c.rtl),p=r.clientWidth,m=r.clientHeight,M={w:p,h:m,nodes:f,lines:[],lifelines:[],labels:[],crossings:[],through:[],unseated:[],outside:[],ox:i,oy:h},L=Lt();if(c.type==="sequence"||c.type==="schema")return{geo:M,grow:L};const z=!!c.rtl,v=z?-1:1,O=u=>z?u.r:u.l,B=u=>z?u.l:u.r,j=z?"left":"right",F=(u,w,C,I)=>{const _=u+I*v*w,X=_+I*v*C;return{l:Math.min(_,X),r:Math.max(_,X)}},rt=getComputedStyle(r),q=z?parseFloat(rt.paddingLeft)||0:p-(parseFloat(rt.paddingRight)||0),D=(u,w,C)=>{const I=[u];for(let _=1;_<=(Ot(o,w)??0);_++)I.push({...u,t:u.t+C*d("4")*_,b:u.b+C*d("4")*_});return I},T=new Map;r.querySelectorAll(`.${s}-node`).forEach(u=>{const w=u.parentElement,C=xt(w,a),I=getComputedStyle(w);T.set(u.dataset.node,z?C.l+(parseFloat(I.paddingLeft)||0)+(parseFloat(I.borderLeftWidth)||0):C.r-(parseFloat(I.paddingRight)||0)-(parseFloat(I.borderRightWidth)||0))});const R=c.nodes,H=u=>g.get(R[u].id),Q=new Map;r.querySelectorAll(`.${s}-group > .${s}-glabel`).forEach(u=>{u.style.removeProperty("--_gx"),Q.set(u.parentElement,u)});const at=new Map;for(const[u,w]of Q)w.getClientRects().length&&at.set(u,xt(w,a));const it=u=>{const w=r.querySelector(`.${s}-node[data-node="${CSS.escape(u)}"]`),C=w?.parentElement;return!!(C?.matches(`.${s}-group[data-turn]`)&&C.querySelector(`:scope > .${s}-node`)===w)},yt=(u,w,C)=>it(w)?Array.from({length:Math.round(C/16)+1},(I,_)=>({...u,t:u.t-_*d("4"),b:u.b-_*d("4")})):[u],dt=[],et=u=>Qt(c.edges[u].kind,l);c.edges.forEach((u,w)=>{const C=n.routes[w],I=g.get(u.from),_=g.get(u.to),X=et(w);let V=[];const ft=u.label,st=ft?e(ft,"label"):0,lt=ft?16*Kt(ft):16,pt=d("4");if(C==="down"||C==="up"){const ut=Math.max(I.rect.l,_.rect.l),$t=Math.min(I.rect.r,_.rect.r),bt=c.edges.map((S,E)=>({o:S,j:E})).filter(({o:S,j:E})=>(n.routes[E]==="down"||n.routes[E]==="up")&&(S.from===u.from&&S.to===u.to||S.from===u.to&&S.to===u.from)),wt=bt.findIndex(S=>S.j===w),vt=bt.length<2?.5:bt.length===2?wt===0?.25:.75:(wt+1)/(bt.length+1);let y=b.x(ut+($t-ut)*vt,X);if(C==="down"){const S=r.querySelector(`.${s}-node[data-node="${CSS.escape(u.to)}"]`),E=S?.parentElement,k=E&&E.matches(`.${s}-group`)&&E.querySelector(`:scope > .${s}-node`)===S?at.get(E):void 0;if(k&&E&&!E.contains(r.querySelector(`.${s}-node[data-node="${CSS.escape(u.from)}"]`))){const A=d("2-5")+X/2;if(y>k.l-A&&y=ut+d("6"):W<=$t-d("6"))&&(y=b.x(W,X))}}}if(V=C==="down"?[Mt(I,"bottom",y),Mt(_,"top",y)]:[Mt(I,"top",y),Mt(_,"bottom",y)],ft){let S=Math.min(V[0].y,V[1].y),E=Math.max(V[0].y,V[1].y);C==="down"?E-=l.head:S+=l.head;const k=[...r.querySelectorAll(`.${s}-group`)].map(K=>xt(K,a));let A=[[S,E]];for(const K of k)for(const Y of[K.t,K.b])A=A.flatMap(([U,Z])=>Y>U+1&&Yk.some(U=>(K+Y)/2>U.t&&(K+Y)/2U.l&&y1){const K=A.filter(([U,Z])=>!W(U,Z));[S,E]=(K.length?K:A).reduce((U,Z)=>Z[1]-Z[0]>U[1]-U[0]?Z:U)}const J=[1/2,1/3,2/3].map(K=>{const Y=S+(E-S)*K;return{l:y-st/2-d("1"),r:y+st/2+d("1"),t:Y-lt/2,b:Y+lt/2}});dt.push({k:w,cands:J,on:!0,card:C==="down"?u.to:u.from})}}else if(C==="trunk"||C==="rail"){const ut=C==="rail"?z?Math.min(I.rect.r,_.rect.r):Math.max(I.rect.l,_.rect.l):O(I.rect),$t=b.x(ut+v*d(C==="trunk"?"8":"3"),X),bt=Mt(I,"bottom",$t);if(C==="rail"){if(V=[bt,Mt(_,"top",$t)],ft){const wt=_.rect.t-d("6");dt.push({k:w,cands:D({...F($t,d("2-5"),st,1),t:wt-lt/2,b:wt+lt/2},u.to,-1),on:!1,card:u.to})}}else{const wt=b.x(O(_.rect)+v*d("6"),X),vt=b.y(_.rect.t-pt,X);V=[bt,{x:$t,y:vt},{x:wt,y:vt},Mt(_,"top",wt)];const y={...F(wt,d("2-5"),st,1),t:vt-lt/2,b:vt+lt/2};ft&&dt.push({k:w,cands:[...yt(y,u.to,lt),...D(y,u.to,-1).slice(1)],on:!1,card:u.to})}}else{const ut=Z=>T.get(Z)??(z?0:p),$t=z?Math.max(ut(u.from),ut(u.to)):Math.min(ut(u.from),ut(u.to)),bt=b.x(n.gutter?q+v*(n.lanes[w]+1)*d("3-5"):$t-v*d("2-5"),X),wt=b.y(I.rect.t+(I.rect.b-I.rect.t)*n.exits[w],X),vt=Mt(I,j,wt),y=C==="end-down",S=c.edges.map((Z,N)=>({o:Z,j:N})).filter(({o:Z,j:N})=>n.routes[N]===C&&Z.to===u.to).sort((Z,N)=>n.lanes[N.j]-n.lanes[Z.j]||Z.j-N.j),E=Math.max(0,S.findIndex(({j:Z})=>Z===w)),k=B(_.rect)-v*(d("6")+E*d("3")),A=B(_.rect)-v*(d("6")+(S.length-1)*d("3")),W=b.x(k,X),J=y?_.rect.t-pt-E*d("5"):_.rect.b+pt+E*d("5"),K=b.y(J,X);V=[vt,{x:bt,y:vt.y},{x:bt,y:K},{x:W,y:K},Mt(_,y?"top":"bottom",W)];const Y=y?u.to:R[_.i+1]?.id??u.to,U={...F(A,d("2-5"),st,-1),t:J-lt/2,b:J+lt/2};ft&&dt.push({k:w,cands:[...y?yt(U,Y,lt):[U],...D(U,Y,y?-1:1).slice(1)],on:!1,card:Y})}const kt=Ne(V,X,b);M.lines.push({i:w,from:u.from,to:u.to,kind:u.kind,pts:kt,tip:kt[kt.length-1],dir:de(kt),width:X})}),M.crossings=te(M.lines),M.through=pe(M.lines,f,c),M.outside=Ye(M.lines,p,m,l),M.seatless=Jn(Q,M.lines,a,z,d);const{obstacles:nt}=Je(r,a,s,0);nt.heads=M.lines.map(u=>Ke(u,l));const tt=[],$={l:0,t:0,r:p,b:m};for(const u of dt){const w=_=>{const X=ce(_,d("1"));return _.l<$.l-.5||_.r>$.r+.5||_.t<$.t-.5||_.b>$.b+.5||f.some(V=>ze(X,V))||tt.some(V=>Ct(X,V))||nt.heads.some(V=>Ct(X,V))||nt.rects.some(V=>Ct(X,V))||M.lines.some(V=>V.i!==u.k&&_t(V.pts).some(([ft,st])=>Ct(X,ue(ft,st,V.width))))},C=u.cands.find(_=>!w(_));C||(L[u.card]=(L[u.card]??0)+1,M.unseated.push(u.k));const I=C?Ze(C,i,h,_=>!w(_),z):u.cands[0];tt.push(I),M.labels.push({i:u.k,text:c.edges[u.k].label,box:I,on:u.on})}return{geo:M,grow:L}}function Pe(t,e,n=0){const o=s=>String(Math.round(s*100)/100);let c=`M${o(t[0].x)} ${o(t[0].y)}`;for(let s=1;s{const{crow:D,ring:T}=Oe(j,F.x,F.y,rt,n.head,n.dot);return`${T?``:""}`};return`${B(e.card.from,v,Math.sign(O.x-v.x)||1,"from")}${B(e.card.to,e.tip,-l.x||1,"to")}`}const s=e.kind==="dashed",r=n.head,a=n.head/2,d=s?1:r-1,g=e.pts.map(v=>({...v})),f=g[g.length-1];f.x-=l.x*d,f.y-=l.y*d;const i=e.tip.x-l.x*r,h=e.tip.y-l.y*r,b=-l.y*a,p=l.x*a,m=v=>Math.round(v*100)/100,M=mt(e.kind),L=s?``:``,z=e.dot?``:"";return`${L}${z}`}function tn(t,e,n,o){const c=new Map,l=new Map;for(const r of e.crossings)l.has(r.under)||l.set(r.under,[]),l.get(r.under).push(r);let s="";for(const[r,a]of l){const d=`${o}-cut-${r}`;c.set(r,d);const g=a.map(f=>{const i=e.lines[f.top],h=e.lines[f.under],b=i.width/2+n.cut,p=h.width/2+1;return f.underVertical?``:``}).join("");s+=`${g}`}return{defs:s,ids:c}}function en(t,e,n,o){const{defs:c,ids:l}=tn(t,e,n,o),s=e.lifelines.map(i=>``).join(""),r=(e.bars??[]).map(i=>``).join(""),a=e.lines.map((i,h)=>Xn(t,i,n,l.get(h)??null,i.from===i.to?n.radiusXs:n.radius)).join(""),g=`${s?``:""}`,f=e.labels.map(i=>`1?' data-lines="2"':""}>${i.text.split(`
+`).map(mt).join("
")}`).join("");return g+f}function Yn(t,e,n){const o=t.querySelector(`.${e}-ink`);if(!o||!n)return;const c=s=>`${Math.round(s*100)/100}px`;o.querySelectorAll(`:scope > .${e}-label`).forEach((s,r)=>{const a=n.labels[r];if(!a||s.dataset.edge!==String(a.i))return;const d=[["left",c(a.box.l)],["top",c(a.box.t)],["width",c(a.box.r-a.box.l)]];for(const[g,f]of d)s.style.getPropertyValue(g)!==f&&s.style.setProperty(g,f)})}function ge(t,e,n,o,c,l,s,r){const d=t.querySelector(`.${n}-drawing`);if(!d||t.clientWidth===0)return{dyn:c,geo:null,ink:"",tokens:null};const g=zn(t),f=Hn(d,n),i=Dn(e,g,f);r?.(i.least);const h=t.clientWidth,b=(()=>{const q=document.activeElement;return q&&d.contains(q)&&q.dataset.node?q.dataset.node:void 0})(),p=q=>Tt(e,q)?{...q,stop:q.stop&&e.byId.has(q.stop)?q.stop:e.nodes[0]?.id,keep:void 0}:{...q,stop:q.stop??e.nodes[0]?.id,keep:b&&q.layout!=="drawn"?b:void 0};let m=!1;const M=q=>{if(m=!1,e.type!=="flowchart")return q;l({...q,heights:void 0,words:void 0});const D=Lt(),T=Lt();return d.querySelectorAll(`.${n}-node[data-shape="decision"]`).forEach(R=>{const H=R.querySelector(`.${n}-words`);if(!H)return;const Q=R.getBoundingClientRect(),at=dt=>{const et={w:dt.width+2*g.space("2-5"),h:dt.height+2*g.space("2")},nt=1-et.w/Q.width,tt=nt>.05?et.h/2/nt:et.h*10;return Math.max(g.space("16"),Math.ceil(Q.width/5),Math.ceil(2*tt))},it=H.getBoundingClientRect();let yt=at(it);if(yt>Q.width){const dt=$=>(R.style.setProperty("--_ww",`${$}px`),H.getBoundingClientRect()),et=Math.floor(R.clientWidth-2*g.space("2-5"));let nt=Math.ceil(it.width),tt=it.height;for(;nt1;){const I=$+u>>1;dt(I).heightQ.width&&(m=!0)}),{...q,heights:D,words:Object.keys(T).length?T:void 0}},L=()=>({m:e,tk:g,P:n,drawing:d,origin:d.getBoundingClientRect(),warn:s}),z=c.autoOpen?{open:!1,autoOpen:void 0}:{},v=(q,D)=>D.map(T=>Gt(e,q.lines.find(R=>R.i===T))).join(", ");if(e.text)return{dyn:{...c,layout:"stacked",bare:void 0},geo:null,ink:"",tokens:g,least:i.least};if(h>=i.least&&!e.unplaced){const q=H=>{let Q=p({...c,...z,layout:"drawn",grow:void 0,track:void 0,bare:void 0,pad:H||void 0,rows:void 0});Q=M(Q),l(Q);let at=Ue(L(),f);return at.corridors&&(Q={...Q,rows:at.corridors.rows},l(Q),at=Ue({...L(),pick:at.corridors.pick},f)),{dd:Q,g:at}};let{dd:D,g:T}=q(!1);const R=H=>H.through.length>0||H.outside.length>0||(H.overlaps?.length??0)>0||(H.misfit?.length??0)>0||m;if(!R(T)&&T.unseated.length&&T.unseated.every(H=>T.bounded?.includes(H))){const H=q(!0);!R(H.g)&&!H.g.unseated.length&&({dd:D,g:T}=H)}if(!R(T)&&!T.unseated.length)return T.crossings.length&&s?.(`${T.crossings.length} crossing${T.crossings.length===1?"":"s"} in the drawn layout: ${T.crossings.map(H=>`${Gt(e,T.lines[H.top])} over ${Gt(e,T.lines[H.under])}`).join("; ")}`),{dyn:D,geo:T,ink:en(n,T,g,o),tokens:g,least:i.least};m&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: a decision would be taller than it is wide`),T.misfit?.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${T.misfit.join("; ")}`),T.through.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.through)} would pass through a node`),T.overlaps?.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.overlaps)} would lie on one another`),T.outside.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: ${v(T,T.outside)} would leave the drawing`),T.unseated.length&&s?.(`the drawn layout does not fit at ${Math.round(h)}px: no clean seat for ${T.unseated.map(H=>e.type==="sequence"?`message ${H}`:`"${qt(e.edges[H]?.label??"")}"`).join(", ")}`)}let O=p({...c,...z,layout:"stacked",heights:void 0,grow:Lt(),track:e.type==="schema"?i.table:void 0,bare:void 0,pad:void 0,rows:void 0});if(O=M(O),l(O),e.type==="sequence"||e.type==="schema")return{dyn:O,geo:null,ink:"",tokens:g,least:i.least};const B=Ie(e);let j=Qe(L(),f,B,O.grow);for(let q=0;q<6&&Object.keys(j.grow).length;q++){const D=Lt(O.grow);for(const[T,R]of Object.entries(j.grow))D[T]=(Ot(D,T)??0)+R;O={...O,grow:D},l(O),j=Qe(L(),f,B,D)}const F=j.geo;if(!B.third&&B.laneCount>2&&s?.(`the stacked drawing uses ${B.laneCount} end lanes (four at most)`),F.unseated.length>0||F.through.length>0||F.outside.length>0||B.third){F.unseated.length&&s?.(`the stacked drawing has no clean seat for ${[...new Set(F.unseated)].map(T=>`"${qt(e.edges[T]?.label??"")}"`).join(", ")}, so its lines are not drawn; the list holds every connection`),F.through.length&&s?.(`in the stacked drawing ${v(F,F.through)} would pass through a node, so its lines are not drawn`),F.outside.length&&s?.(`in the stacked drawing ${v(F,F.outside)} would leave the drawing, so its lines are not drawn`),B.third&&s?.("the stacked drawing would need a fifth end lane, so its lines are not drawn","error");const q={...F,lines:[],labels:[],crossings:[]};d.querySelectorAll(`.${n}-group > .${n}-glabel`).forEach(T=>T.style.removeProperty("--_gx"));const D=p({...O,grow:Lt(),bare:!0,open:c.bare?c.open:!0,autoOpen:c.bare?c.autoOpen:c.open?void 0:!0});return l(D),{dyn:D,geo:q,ink:"",tokens:g,least:i.least}}return F.seatless?.length&&s?.(`a stacked group's label has no clear seat on its top edge: ${F.seatless.map(q=>`"${q}"`).join(", ")}`),F.crossings.length&&s?.(`${F.crossings.length} crossing${F.crossings.length===1?"":"s"} in the stacked drawing (each is cut): ${F.crossings.map(q=>`${Gt(e,F.lines[q.top])} over ${Gt(e,F.lines[q.under])}`).join("; ")}`),{dyn:O,geo:F,ink:en(n,F,g,o),tokens:g,least:i.least}}function Gt(t,e){const n=t.byId.get(e.from)?.name??e.from,o=t.byId.get(e.to)?.name??e.to;return`${n} to ${o}`}function Qn(t,e,n,o,c,l){const s=new Set;if(l){s.add(l);for(const p of n?.lines??[])p.from===l&&s.add(p.to),p.to===l&&s.add(p.from)}if(t.toggleAttribute("data-tracing",!!l),t.querySelectorAll(`.${e}-node`).forEach(p=>p.toggleAttribute("data-near",s.has(p.dataset.node))),!n||!o)return;const r=p=>!!l&&(p.from===l||p.to===l),a=t.querySelector(`.${e}-edges`),d=new Map;t.querySelectorAll(`.${e}-edge`).forEach(p=>d.set(p.getAttribute("data-edge"),p));for(const p of n.lines){const m=d.get(String(p.i));m&&(m.toggleAttribute("data-lit",r(p)),m.toggleAttribute("data-dim",!!l&&!r(p)))}if(t.querySelectorAll(`.${e}-label`).forEach(p=>{const m=n.lines.find(M=>String(M.i)===p.dataset.edge);p.toggleAttribute("data-lit",!!(m&&r(m)))}),a){for(const p of n.lines)if(r(p)){const m=d.get(String(p.i));m&&a.appendChild(m)}}const g=te(n.lines,r),{defs:f,ids:i}=tn(e,{...n,crossings:g},o,c),h=t.querySelector(`.${e}-svg`);if(!h)return;let b=h.querySelector("defs");!b&&f&&(b=document.createElementNS("http://www.w3.org/2000/svg","defs"),h.insertBefore(b,h.firstChild)),b&&(b.innerHTML=f),n.lines.forEach((p,m)=>{const M=d.get(String(p.i))?.querySelector(`.${e}-line`);if(!M)return;const L=i.get(m);L?M.setAttribute("mask",`url(#${L})`):M.removeAttribute("mask")})}var Pn=()=>matchMedia("(prefers-reduced-motion: reduce), (forced-colors: active), print").matches||document.documentElement.getAttribute("data-loops")==="held";function to(t,e){const n=t.getAttribute("data-entrance");if(!(n==="running"||n==="done")){if(!e){n&&t.removeAttribute("data-entrance");return}n||t.setAttribute("data-entrance",Pn()||no(t)?"done":"pending")}}var eo=t=>`basalt-diagram-entrance:${location.pathname}#${t.id}`;function no(t){if(!t.hasAttribute("data-first-visit")||!t.id)return!1;try{return localStorage.getItem(eo(t))!==null}catch{return!1}}function nn(t){const e=t.getAttribute("data-entrance");e!=="pending"&&e!=="running"||(t.setAttribute("data-entrance","done"),t.dispatchEvent(new Event("basalt-diagram-settle")))}function oo(t,e,n,o=!1,c=!1){const l=o?Ut(t):null;if(l&&n.startsWith("Arrow")){const d={ArrowRight:c?"left":"right",ArrowLeft:c?"right":"left",ArrowDown:"down",ArrowUp:"up"}[n];return d?l[e]?.[d]??null:null}const s=t.byId.get(e)?.i??0,r=t.nodes.length;let a;if(n==="ArrowRight"||n==="ArrowDown")a=s+1;else if(n==="ArrowLeft"||n==="ArrowUp")a=s-1;else if(n==="Home")a=0;else if(n==="End")a=r-1;else return null;return t.nodes[Math.max(0,Math.min(r-1,a))].id}var so=["data-layout","data-measured","role","aria-roledescription","aria-labelledby","aria-describedby","aria-label","tabindex","data-stops","hidden","data-art"],on=["data-layout","data-measured","data-bare","data-motion","data-first-visit","data-rtl","data-cols","data-reach","data-gutter","data-marks"],ao=["--_track","--_h","--_ww","--_gap","--_ggrow","--_tl","--_gpad","--_gw","--_mh","--_rows","--_row-gap"],sn=t=>t==null||t===!1;function ro(t,e){if(t.tagName.toLowerCase()!==e.t)return!1;const n=typeof e.a.class=="string"?e.a.class.split(" ")[0]:"";return!n||t.classList.contains(n)}function ee(t,e,n=!0){if(typeof e=="string"||"slot"in e)return;const o=n?on:so;for(const s of o)sn(e.a[s])&&t.removeAttribute(s);for(const[s,r]of Object.entries(e.a)){if(s==="class")continue;if(s==="style"){const d=t.style,g=new Map(String(r??"").split(";").map(f=>{const i=f.indexOf(":");return[f.slice(0,i).trim(),f.slice(i+1).trim()]}).filter(([f])=>f));for(const[f,i]of g)d.getPropertyValue(f).trim()!==i&&d.setProperty(f,i);for(const f of ao)g.has(f)||d.removeProperty(f);continue}if(n&&!on.includes(s))continue;if(sn(r)){t.removeAttribute(s);continue}const a=r===!0?"":String(r);t.getAttribute(s)!==a&&t.setAttribute(s,a)}if(e.t==="svg"||typeof e.a.class=="string"&&(/-ruler$/.test(e.a.class)||/-ink$/.test(e.a.class)&&!e.a.class.endsWith("-text-ink"))||e.c.some(s=>typeof s!="string"&&"slot"in s))return;const c=[...t.children];let l=0;for(const s of e.c)if(!(typeof s=="string"||"slot"in s)){for(let r=l;rt.querySelector(`.${e}-node[data-node="${CSS.escape(l)}"]`);n&&c(n)?.setAttribute("tabindex","-1"),c(o)?.setAttribute("tabindex","0")}(function(t){"use strict";var e=t._,n="diagram",o=0;function c(i,h,b){return{prefix:n,base:i,hasSource:h.source!==void 0&&h.source!==null&&h.source!=="",hiddenClass:"visually-hidden",viewer:b?b.keys:void 0}}function l(i,h,b,p){var m=function(M){return''+mt(M)+""};return{source:mt(String(h.source||"")),summary:mt(String(h.summary||"")),hint:ie(i).map(function(M){return""+M.keys.map(m).join(" ")+" "+mt(M.words)+""}).join(""),toggle:'"}}function s(i,h,b){for(var p=i.layout==="auto"&&(i.type==="architecture"||i.type==="flowchart"||i.type==="schema"),m=p?Array.isArray(i.placement)?i.placement:i.placement?[i.placement]:[]:[],M=i.direction||(i.type==="flowchart"?"down":"right"),L=null,z=0;z");return{open:B.slice(0,j+1),inner:B.slice(j+1,B.length-9),warnings:v.errors.map(function(F){return"error: "+F}).concat(v.warnings)}}var r=["aria-labelledby","data-type","data-cols","data-reach","data-gutter","data-marks","data-layout","data-measured","data-bare"],a=["--_cols","--_gpad","--_track"];function d(i,h,b,p){i.__diagram&&i.__diagram.stop();var m=(i.getAttribute("aria-labelledby")||"").replace(/-title$/,"").replace(/[^A-Za-z0-9_-]/g,""),M=getComputedStyle(i).direction==="rtl",L=h.layout==="auto"&&(h.type==="architecture"||h.type==="flowchart"||h.type==="schema"),z=L?Array.isArray(h.placement)?h.placement:h.placement?[h.placement]:[]:[];L&&!z.length&&console.warn('Basalt diagram: "layout": "auto" needs a placement, which compose.mjs writes at build time; drawn from script, place it with placeDiagram (@srasyndicate/basalt/diagram-layout) and pass "placement". The figure is stacked');var v=h.direction?[h.direction]:h.type==="flowchart"?["down","right"]:["right","down"],O=function(N){for(var G=0;G .diagram-drawing")){if(!m||!i.querySelector("#"+CSS.escape(m+"-title"))){for(;document.getElementById("dg"+ ++o+"-title"););m="dg"+o}var j=s(h,m,p),F=document.createElement("div");F.innerHTML=j.open+"";var rt=F.firstChild;r.forEach(function(N){i.removeAttribute(N)}),a.forEach(function(N){i.style.removeProperty(N)});for(var q=0;q :not(script[data-diagram])").forEach(function(N){N.remove()}),i.insertAdjacentHTML("beforeend",j.inner)}B.warnings.forEach(function(N){console.warn("Basalt diagram: "+N)}),B.errors.forEach(function(N){console.error("Basalt diagram: "+N)}),B.motion.animated&&B.motion.firstVisit&&!i.id&&console.error('Basalt diagram: "entrance": "first-visit" needs an id on the figure: without one the entrance plays on every visit');var T=c(m,h,p),R={},H=null,Q=null,at=null,it=null,yt=Object.create(null),dt=function(N,G){yt[N]||(yt[N]=1,(G==="error"?console.error:console.warn)("Basalt diagram: "+N))},et=function(N){ee(i,Yt(B,N,T))},nt=i.querySelector(".diagram-ink"),tt=i.querySelector(".diagram-toggle"),$=!p&&B.motion.animated&&typeof e.diagramMotion=="function",u=null,w=null,C=function(){$&&nn(i)};function I(){Qn(i,n,H&&H.geo,H&&H.tokens,m,Q||it||at),V()}var _=null,X=!p&&matchMedia("(hover: none), (pointer: coarse)").matches;function V(){var N=X&&!p&&nt&&nt.innerHTML!=="";if(i.toggleAttribute("data-touch",!!(X&&!p)),N&&!_){var G=i.querySelector(":scope > .diagram-foot");if(!G)return;_=document.createElement("button"),_.type="button",_.className="btn diagram-clear",_.setAttribute("data-variant","secondary"),_.setAttribute("data-size","sm"),_.innerHTML="Clear highlight",_.addEventListener("click",function(){it&&(it=null,I())}),G.appendChild(_)}else!N&&_&&(_.remove(),_=null);_&&_!==_.parentNode.lastElementChild&&document.activeElement!==_&&_.parentNode.appendChild(_),_&&(it?_.removeAttribute("aria-disabled"):_.setAttribute("aria-disabled","true"))}function ft(N){if(!N.defaultPrevented){var G=bn(i,n,N,it);G!==void 0&&(C(),X=!0,it=G,I())}}function st(){tt&&(tt.setAttribute("aria-expanded",String(!!R.open)),tt.firstElementChild.textContent=R.open?"Hide the list":"View as list")}function lt(){if(L&&z.length>1&&!p){for(var N=null,G=[],P=!1,ot=0;ot1&&p&&!h.direction&&p.room){for(var ne=p.room(),Vt=-1,me=null,ye=0;yeVt+1e-6&&(Vt=rn,me=$e)}}}me&&(B=me)}H=(p?p.measure:ge)(i,B,n,m,R,et,dt),R=H.dyn,et(R),st();var be=i.querySelector(":scope > .diagram-hint");if(be){var ln=ie(B,R.layout==="drawn").map(function(At){return""+At.keys.map(function(fo){return''+mt(fo)+""}).join(" ")+" "+mt(At.words)+""}).join("");be.innerHTML!==ln&&(be.innerHTML=ln)}Tt(B,R)||(at=it=null);var cn=nt&&H.ink!==w;cn&&(nt.innerHTML=H.ink,w=H.ink),Yn(i,n,H.geo),I();var co=B.text?i.querySelector(".diagram-text[data-art]"):null;B.text&&typeof e.diagramText=="function"&&e.diagramText(i,B,h,p);var dn=B.text?i.querySelector(".diagram-text[data-art]"):null;$&&H.tokens&&(to(i,!!(H.geo&&H.geo.lines.length)||!!dn),(cn||dn!==co)&&u&&u.redrawn()),p&&p.onMeasured&&H.tokens&&p.onMeasured(H,i)}function pt(N){R=N,et(R)}function kt(N){var G=R.stop;R=Object.assign({},R,{stop:N}),io(i,n,G,N)}var ut=function(N){var G=N&&N.closest?N.closest(".diagram-node"):null;return G&&i.contains(G)?G:null};function $t(N){var G=ut(N.target);if(!(!G||N.defaultPrevented)){if(C(),N.key==="Escape"){!p&&(Q||at||it)&&(N.preventDefault(),Q=at=it=null,I());return}if(Tt(B,R)){var P=oo(B,G.getAttribute("data-node"),N.key,R.layout==="drawn");if(P){N.preventDefault(),kt(P);var ot=i.querySelector('.diagram-node[data-node="'+CSS.escape(P)+'"]');ot&&ot.focus()}}}}function bt(N){var G=ut(N.target);if(G){C();var P=G.getAttribute("data-node");Q=G.matches(":focus-visible")?P:null,Tt(B,R)&&R.stop!==P&&kt(P),I()}}function wt(N){var G=ut(N.target);G&&(ut(N.relatedTarget)||(Q=null),R.keep===G.getAttribute("data-node")&&pt(Object.assign({},R,{keep:void 0})),I())}function vt(N){if(!(N.pointerType!=="mouse"||!matchMedia("(hover: hover)").matches)){var G=ut(N.target);G&&C();var P=G&&Tt(B,R)?G.getAttribute("data-node"):null;P!==at&&(at=P,I())}}function y(){at&&(at=null,I())}function S(){C(),pt(Object.assign({},R,{open:!R.open,autoOpen:void 0})),st()}i.addEventListener("keydown",$t),i.addEventListener("focusin",bt),i.addEventListener("focusout",wt),i.addEventListener("pointerover",vt),i.addEventListener("pointerleave",y),i.addEventListener("click",ft),tt&&tt.addEventListener("click",S),lt();var E=i.clientWidth,k=0,A=!0,W=new ResizeObserver(function(){Math.abs(i.clientWidth-E)<.5||(E=i.clientWidth,cancelAnimationFrame(k),k=requestAnimationFrame(lt))});W.observe(i),document.fonts&&document.fonts.ready.then(function(){A&<()});var J=matchMedia("(forced-colors: active)"),K=B.nodes.some(function(N){return N.mark});K&&J.addEventListener("change",lt),$&&(u=e.diagramMotion(i,{fig:i,P:n,base:m,model:function(){return B},geo:function(){return H&&H.geo},tokens:function(){return H&&H.tokens}},h));var Y=!p&&h.zoom!==!1&&typeof e.diagramZoom=="function"?e.diagramZoom(i,h,{model:B,settle:C,animated:$}):null,U=i.querySelector(":scope > .diagram-foot"),Z=!p&&h.export===!0&&U&&typeof e.diagramExport=="function"?e.diagramExport(U,i):[];i.__diagram={stop:function(){Y&&Y.destroy(),Z.forEach(function(N){N.remove()}),A=!1,W.disconnect(),cancelAnimationFrame(k),K&&J.removeEventListener("change",lt),u&&u.destroy(),i.removeEventListener("keydown",$t),i.removeEventListener("focusin",bt),i.removeEventListener("focusout",wt),i.removeEventListener("pointerover",vt),i.removeEventListener("pointerleave",y),i.removeEventListener("click",ft),_&&_.remove(),tt&&tt.removeEventListener("click",S)},layout:lt,key:g(h),send:u&&u.sendValue?u.sendValue:null}}function g(i){try{return JSON.stringify(i,function(h,b){return h==="packet"&&b&&typeof b=="object"?Object.assign({},b,{send:void 0}):b})}catch{return null}}function f(){document.querySelectorAll("figure.diagram").forEach(function(i){if(!i.__diagram){var h=i.querySelector(":scope > script[data-diagram]");if(h)try{d(i,JSON.parse(h.textContent),!0)}catch(b){console.error("Basalt diagram: this figure could not be drawn",b)}}})}e.diagramMarkup=s,e.diagramKit={draw:d,buildModel:Nt,figureKey:En,figureList:Bn,hintEntries:ie,toHtml:se,escapeHtml:mt,settleEntrance:nn,measureFigure:ge},t.diagram=function(i,h){var b=i.__diagram,p=b&&b.send?g(h):null;if(p!==null&&p===b.key){b.send(h.packet?h.packet.send:void 0);return}d(i,h)},e.step(62,"wireDiagrams",f)})(window.Basalt)})();
diff --git a/.agent/skills/basalt-html/parts/usage/diagram-export.md b/.agent/skills/basalt-html/parts/usage/diagram-export.md
index 511d845..e555ff9 100644
--- a/.agent/skills/basalt-html/parts/usage/diagram-export.md
+++ b/.agent/skills/basalt-html/parts/usage/diagram-export.md
@@ -3,4 +3,5 @@
Added for you when a diagram's JSON says `"export": true`.
- The figure's foot gets "Download SVG" and "Download PNG", and so does its viewer's (the drawn layout at 100%, whatever the zoom). Each writes the figure in the theme shown: the title and source, the drawing and the key, at rest; native SVG with its words as text and the faces embedded; the PNG at 2x.
+- The PNG is drawn through an image: under a content policy, `img-src` must allow `blob:` or `data:`. Where it allows neither, "Download PNG" makes no file and the console says why; "Download SVG" needs neither.
- Without `"export": true` there are no buttons and no module. Don't add your own.
diff --git a/docs/foundations.md b/docs/foundations.md
index 7b5aa3a..20446ff 100644
--- a/docs/foundations.md
+++ b/docs/foundations.md
@@ -2009,7 +2009,8 @@ over its lifeline; a stacked chip draws the mark before the name.
- Right to left: the figure mirrors and its words do not, drawn and stacked (stacked, the rail and the trunk run down the right, a
branch is indented from the right, and the end lines and the end gutter are on the left). Identifiers are isolated left to right as
runs; named sides swap; the arrow keys stay physical; the text art stays left to right.
-- Export: a linked card's arrow is not drawn in a file.
+- Export: a linked card's arrow is not drawn in a file. A PNG is drawn through an image, so under a content policy `img-src` must allow
+ `blob:` or `data:`; where it allows neither, `diagramToPng` rejects with an error that says so and no file is made (the SVG needs neither).
### Diagram tokens
diff --git a/packages/react/src/architecture-diagram.tsx b/packages/react/src/architecture-diagram.tsx
index b6d0eec..201a7f7 100644
--- a/packages/react/src/architecture-diagram.tsx
+++ b/packages/react/src/architecture-diagram.tsx
@@ -5,7 +5,7 @@ import type { DiagramFigureProps } from "./diagram-figure";
import type { ArchitectureNode, DiagramFlowEdge, DiagramGroup, DiagramPacket, DiagramPlacement, DiagramUnplaced } from "./diagram-core";
export type { ArchitectureNode, DiagramEdge, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./diagram-core";
-export type { DiagramFigureProps } from "./diagram-figure";
+export type { DiagramFigureProps, DiagramLayoutInfo } from "./diagram-figure";
interface ArchitectureDiagramBase extends DiagramFigureProps {
/** The parts, in the author's order: the stacked order, the focus order and the list's. `col` and `row` place each in the drawn layout. */
diff --git a/packages/react/src/diagram-core.ts b/packages/react/src/diagram-core.ts
index d345183..3e1aaee 100644
--- a/packages/react/src/diagram-core.ts
+++ b/packages/react/src/diagram-core.ts
@@ -2943,10 +2943,30 @@ export function inkHtml(P: string, geo: Geo, tk: Tokens, base: string): string {
const lines = geo.lines.map((l, k) => lineMarkup(P, l, tk, ids.get(k) ?? null, l.from === l.to ? tk.radiusXs : tk.radius)).join("");
const under = lifelines ? `` : "";
const svg = `${under}`;
- const labels = geo.labels.map((l) => ` 1 ? ' data-lines="2"' : ""} style="left:${Math.round(l.box.l * 100) / 100}px;top:${Math.round(l.box.t * 100) / 100}px;width:${Math.round((l.box.r - l.box.l) * 100) / 100}px">${l.text.split("\n").map(escapeHtml).join("
")}`).join("");
+ // A label's place is not in the string: a style attribute in markup written as HTML is refused under a strict `style-src` (no 'unsafe-inline'), so
+ // placeLabels sets it through the CSSOM once the ink is in the page.
+ const labels = geo.labels.map((l) => ` 1 ? ' data-lines="2"' : ""}>${l.text.split("\n").map(escapeHtml).join("
")}`).join("");
return svg + labels;
}
+/**
+ * Places the ink's labels (inkHtml writes them with no place): each one's box from the layout, set through the CSSOM, which a content policy allows where
+ * it refuses a style attribute. Called after the ink is written, and after every measure, since a label can move while the ink's string stays the same.
+ * The labels are paired with the layout's in order, and a label whose line is not the layout's is left alone.
+ */
+export function placeLabels(fig: Element, P: string, geo: Geo | null): void {
+ const ink = fig.querySelector(`.${P}-ink`);
+ if (!ink || !geo) return;
+ const r2 = (n: number) => `${Math.round(n * 100) / 100}px`;
+ const els = ink.querySelectorAll(`:scope > .${P}-label`);
+ els.forEach((el, k) => {
+ const l = geo.labels[k];
+ if (!l || el.dataset.edge !== String(l.i)) return;
+ const at: Array<[string, string]> = [["left", r2(l.box.l)], ["top", r2(l.box.t)], ["width", r2(l.box.r - l.box.l)]];
+ for (const [name, value] of at) if (el.style.getPropertyValue(name) !== value) el.style.setProperty(name, value);
+ });
+}
+
// ---- Laying a figure out ----
export interface Measured { dyn: Dyn; geo: Geo | null; ink: string; tokens: Tokens | null; least?: number }
@@ -3242,7 +3262,9 @@ export function syncAttributes(el: Element, v: VNode, root = true): void {
const s = value === true ? "" : String(value);
if (el.getAttribute(k) !== s) el.setAttribute(k, s);
}
- if (v.t === "svg" || (typeof v.a.class === "string" && /-(ink|ruler)$/.test(v.a.class))) return;
+ // The ink and the ruler are written apart from the tree, except a text sequence's transcript (its `-text-ink`): that is the tree's own, and its lines'
+ // indents are styles, which a content policy refuses in markup written as HTML (the page's or a script's), so they are set here through the CSSOM.
+ if (v.t === "svg" || (typeof v.a.class === "string" && (/-ruler$/.test(v.a.class) || (/-ink$/.test(v.a.class) && !v.a.class.endsWith("-text-ink"))))) return;
if (v.c.some((c) => typeof c !== "string" && "slot" in c)) return;
const els = [...el.children];
let at = 0;
diff --git a/packages/react/src/diagram-export.ts b/packages/react/src/diagram-export.ts
index bd5bc9e..d9865b5 100644
--- a/packages/react/src/diagram-export.ts
+++ b/packages/react/src/diagram-export.ts
@@ -249,18 +249,52 @@ export async function diagramToSvg(figure: HTMLElement, options: DiagramExportOp
return new Blob([svg], { type: "image/svg+xml" });
}
-/** The figure as a PNG file, at `scale` (2 by default), always drawn with the faces embedded. */
+/**
+ * The SVG as something a canvas draws. First `createImageBitmap` from the SVG as a Blob, which needs no URL and so no `img-src`, where the browser decodes
+ * SVG that way; then an image from a `blob:` URL, then from a `data:` URL. Under a content policy that allows neither in `img-src` there is no way left,
+ * and the error says so: never a broken or empty file.
+ */
+async function drawable(svg: string): Promise<{ source: CanvasImageSource; done: () => void }> {
+ const blob = new Blob([svg], { type: "image/svg+xml" });
+ if (typeof createImageBitmap === "function") {
+ try {
+ const bitmap = await createImageBitmap(blob);
+ return { source: bitmap, done: () => bitmap.close() };
+ } catch { /* this browser decodes no SVG Blob: an image next */ }
+ }
+ const urls: Array<() => string> = [() => URL.createObjectURL(blob), () => `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`];
+ for (const make of urls) {
+ const url = make();
+ const done = () => { if (url.startsWith("blob:")) URL.revokeObjectURL(url); };
+ const img = new Image();
+ img.src = url;
+ try {
+ await img.decode();
+ return { source: img, done };
+ } catch { done(); }
+ }
+ throw new Error("Basalt diagramToPng: the PNG could not be drawn. A canvas draws the figure's SVG through an image, and this page refused it both as a blob: URL and as a data: URL: a content policy allows them with `img-src 'self' blob:` (or `data:`). diagramToSvg needs neither");
+}
+
+/**
+ * The figure as a PNG file, at `scale` (2 by default), always drawn with the faces embedded.
+ *
+ * A canvas draws SVG only through an image: under a `Content-Security-Policy`, `img-src` must allow `blob:` or `data:` (where the browser decodes an SVG
+ * Blob with `createImageBitmap`, neither is needed). Where the page allows neither, the promise rejects with an error that says so, and no file is made.
+ */
export async function diagramToPng(figure: HTMLElement, options: DiagramExportOptions = {}): Promise {
const { svg, w, h } = await svgText(figure, options, true);
const scale = options.scale ?? 2;
- const img = new Image();
- img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
- await img.decode();
- const canvas = document.createElement("canvas");
- canvas.width = Math.round(w * scale);
- canvas.height = Math.round(h * scale);
- const ctx = canvas.getContext("2d")!;
- ctx.scale(scale, scale);
- ctx.drawImage(img, 0, 0, w, h);
- return new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("the PNG could not be made"))), "image/png"));
+ const { source, done } = await drawable(svg);
+ try {
+ const canvas = document.createElement("canvas");
+ canvas.width = Math.round(w * scale);
+ canvas.height = Math.round(h * scale);
+ const ctx = canvas.getContext("2d")!;
+ ctx.scale(scale, scale);
+ ctx.drawImage(source, 0, 0, w, h);
+ return await new Promise((resolve, reject) => canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("Basalt diagramToPng: the PNG could not be made"))), "image/png"));
+ } finally {
+ done();
+ }
}
diff --git a/packages/react/src/diagram-figure.tsx b/packages/react/src/diagram-figure.tsx
index 3e40636..4032ffd 100644
--- a/packages/react/src/diagram-figure.tsx
+++ b/packages/react/src/diagram-figure.tsx
@@ -4,9 +4,9 @@ import { Kbd } from "./kbd";
import { useShortcutsVisible } from "./keyboard";
import { inLevel, usePanelLevel } from "./layers";
import {
- applyTrace, buildModel, tapTrace, transcript, entranceDrawn, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, settleEntrance, syncAttributes, toHtml,
+ applyTrace, buildModel, placeLabels, tapTrace, transcript, entranceDrawn, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, settleEntrance, syncAttributes, toHtml,
} from "./diagram-core";
-import type { DiagramLegend, DiagramMotion, DiagramPlacement, DiagramSpec, Dyn, Measured, Model, VNode } from "./diagram-core";
+import type { DiagramLegend, DiagramMotion, DiagramPlacement, DiagramSpec, Dyn, Geo, Measured, Model, VNode } from "./diagram-core";
import type { MotionController } from "./diagram-motion-core";
type MotionModule = typeof import("./diagram-motion");
@@ -57,6 +57,24 @@ export interface DiagramFigureProps extends Omit,
zoom?: boolean;
/** `"first-visit"` (DECISIONS 306, 1.5): an animated figure's entrance plays until it has played once on this page; later visits are at rest. Needs an `id`. */
entrance?: "always" | "first-visit";
+ /**
+ * Called with the figure's layout each time it is laid out anew (a new width, the faces arriving, new data), and not again for the same layout. What it
+ * gives is what `exportMeasuredDiagram` from `@srasyndicate/basalt/diagram-interop` takes, so a draw.io, Visio or Lucid file is the layout on screen:
+ * `exportMeasuredDiagram(laid.spec, laid.geo, "drawio", { extras: readMeasuredExtras(laid.figure) })`. It draws nothing.
+ */
+ onLayout?: (laid: DiagramLayoutInfo) => void;
+}
+
+/** A figure's layout as it is on screen (`onLayout`). */
+export interface DiagramLayoutInfo {
+ /** The figure's data; under `layout: "auto"`, with the placement it is drawn on. */
+ spec: DiagramSpec;
+ /** The measured geometry: every card's box, every line's route and every label's seat, in CSS pixels from the drawing's corner. */
+ geo: Geo;
+ /** Whether the figure is drawn or stacked at this width. */
+ layout: "drawn" | "stacked";
+ /** The figure element: `readMeasuredExtras` reads its groups, lanes, bands, frames and table rows when the file is made. */
+ figure: HTMLElement;
}
const P = "basalt-diagram";
@@ -78,9 +96,10 @@ function styleObject(style: string): Record {
/**
* The engine's tree as React elements; slots are React's own, the ink is set as HTML (it is the same string the skill writes). `ink` is one object for one
* string: React writes the HTML again whenever the object changes, and the motion module's overlays and masks live inside it, so a render that draws the
- * same lines must hand React the same object.
+ * same lines must hand React the same object. `null` is a text sequence's transcript, which is the tree's own and is drawn as elements: its lines' indents
+ * are styles, which a content policy refuses in markup set as HTML (the art has none). Keyed apart, so React makes a new element when one becomes the other.
*/
-function toReact(v: VNode, slots: Record, ink: { __html: string }, root?: Record): React.ReactNode {
+function toReact(v: VNode, slots: Record, ink: { __html: string } | null, root?: Record): React.ReactNode {
if (typeof v === "string") return v;
if ("slot" in v) return slots[v.slot] ?? null;
const props: Record = {};
@@ -90,9 +109,12 @@ function toReact(v: VNode, slots: Record, ink: { __html
else props[CAMEL[k] ?? k] = value === true ? (k === "hidden" ? true : "") : value;
}
if (typeof v.a.class === "string" && v.a.class.endsWith("-ink")) {
- // sink: the figure's ink, serialised by diagram-core's h() from the model; every text and attribute is escaped there; test/repo-review.test.mjs (a diagram's hostile labels)
- props.dangerouslySetInnerHTML = ink;
- return React.createElement(v.t, props);
+ if (ink) {
+ // sink: the figure's ink, serialised by diagram-core's h() from the model; every text and attribute is escaped there; test/repo-review.test.mjs (a diagram's hostile labels)
+ props.dangerouslySetInnerHTML = ink;
+ return React.createElement(v.t, { ...props, key: "html" });
+ }
+ props.key = "nodes";
}
if (root) Object.assign(props, root, { className: [props.className, root.className].filter(Boolean).join(" "), style: { ...(props.style as object), ...(root.style as object) } });
return React.createElement(v.t, props, ...v.c.map((c) => toReact(c, slots, ink)));
@@ -128,7 +150,7 @@ export interface DiagramFigureInternalProps extends DiagramFigureProps {
viewer?: DiagramViewerMode;
}
-export function DiagramFigure({ spec, component, viewer, zoom = true, entrance: _entrance, title: _title, heading: _heading, legend: _legend, motion: _motion, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ref: callerRef, ...props }: DiagramFigureInternalProps) {
+export function DiagramFigure({ spec, component, viewer, zoom = true, onLayout, entrance: _entrance, title: _title, heading: _heading, legend: _legend, motion: _motion, source, summary, className, style, onKeyDown, onFocus, onBlur, onPointerOver, onPointerLeave, ref: callerRef, ...props }: DiagramFigureInternalProps) {
const base = `dg${React.useId().replace(/[^a-zA-Z0-9_-]/g, "")}`;
const level = usePanelLevel();
// The key hint is a data-kbd-hint legend, hidden on touch until a hardware key is pressed: this installs the listener that reveals it.
@@ -180,6 +202,9 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, entrance:
const [textModule, setTextModule] = React.useState(null);
const inkHtml = React.useMemo(() => ({ __html: ink }), [ink]);
const measured = React.useRef(null);
+ const onLayoutRef = React.useRef(onLayout);
+ onLayoutRef.current = onLayout;
+ const laidOut = React.useRef<{ key: string; spec: DiagramSpec } | null>(null);
const dynRef = React.useRef(dyn);
dynRef.current = dyn;
const [motionModule, setMotionModule] = React.useState(null);
@@ -305,10 +330,22 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, entrance:
result.ink = html;
}
measured.current = result;
+ // The app's own record of the layout (onLayout): once for each layout, so a callback that sets state never lays the figure out again.
+ const told = onLayoutRef.current;
+ if (told && result.geo && !viewer) {
+ const key = `${result.dyn.layout ?? "stacked"}|${JSON.stringify(result.geo)}`;
+ if (laidOut.current?.key !== key || laidOut.current.spec !== spec) {
+ laidOut.current = { key, spec };
+ const placed = auto ? placementFor(dirAt) : undefined;
+ told({ spec: placed ? { ...spec, placement: placed } : spec, geo: result.geo, layout: result.dyn.layout === "drawn" ? "drawn" : "stacked", figure: fig });
+ }
+ }
// The same layout is the same state: a measure that changes nothing renders nothing.
// (A layout is plain data that the engine builds in one order, so its text is a fair test.)
if (JSON.stringify(dynRef.current) !== JSON.stringify(result.dyn)) { dynRef.current = result.dyn; setDyn(result.dyn); }
setInk(result.ink);
+ // A label can move while the ink's string stays the same (its place is not in it): placed now, and again below once React writes a new ink.
+ placeLabels(fig, P, result.geo);
// A layout with no stops traces nothing: a pointer resting on a node as the figure narrows into one leaves no trace behind.
if (!hasStops(model, result.dyn)) { setHoverTrace(null); setTouchTrace(null); }
// A figure hidden (the viewer's list is open) was not measured: the viewer keeps the drawing's size and place it had. A text figure's art is in the DOM
@@ -345,6 +382,11 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, entrance:
return () => { live = false; observer.disconnect(); cancelAnimationFrame(frame); if (marks) forced.removeEventListener("change", measure); };
}, [measure, model]);
+ // The labels of an ink React has just written, placed before the trace and the motion read them.
+ React.useLayoutEffect(() => {
+ const fig = figRef.current;
+ if (fig) placeLabels(fig, P, measured.current?.geo ?? null);
+ }, [ink]);
// An animated text figure builds by ink (1.2) as a drawn figure's entrance plays: the motion module plays it when it comes into view, settles it as it
// settles any entrance, and keeps the first visit's mark (below, its art counts as its lines).
const trace = focusTrace ?? touchTrace ?? hoverTrace;
@@ -510,8 +552,10 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, entrance:
{entry.keys.map((k, i) => {i ? " " : null}{k})} {entry.words}
));
const tree = figureTree(model, dyn, options);
+ // A text sequence's transcript is drawn as the tree's elements; its art, and any drawing's ink, as HTML.
+ const inkProp = model.text && !dyn.art ? null : inkHtml;
// The viewer's figure shows its drawing alone: its head, key, hint and foot are the dialog's.
- if (viewer) return toReact(tree, { source, summary, hint: null, toggle: null }, inkHtml, root) as React.ReactElement;
+ if (viewer) return toReact(tree, { source, summary, hint: null, toggle: null }, inkProp, root) as React.ReactElement;
// The foot (1.9, and DECISIONS 310, 9.1): "View as list", "Expand", then the run button and "Pause animations", which the motion module draws when it has loaded.
const Foot = motionModule?.MotionFoot;
const expand = zoom && scripted ? (
@@ -548,5 +592,5 @@ export function DiagramFigure({ spec, component, viewer, zoom = true, entrance:
) : null;
const foot = <>{toggle}{expand}{Foot && controller ? : null}{clear}>;
- return toReact(tree, { source, summary, hint, toggle: foot }, inkHtml, root) as React.ReactElement;
+ return toReact(tree, { source, summary, hint, toggle: foot }, inkProp, root) as React.ReactElement;
}
diff --git a/packages/react/src/index.ts b/packages/react/src/index.ts
index ff705bf..255314f 100644
--- a/packages/react/src/index.ts
+++ b/packages/react/src/index.ts
@@ -94,7 +94,7 @@ export { ChartGroup, TimeChart } from "./chart";
export { trailingMean } from "./trailing-mean";
export type { ChartGroupProps, ChartKind, ChartLaneGeometry, ChartPlan, ChartSeries, TimeChartProps } from "./chart";
export { ArchitectureDiagram } from "./architecture-diagram";
-export type { ArchitectureDiagramProps, ArchitectureNode, DiagramEdge, DiagramFigureProps, DiagramFlowEdge, DiagramGroup, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./architecture-diagram";
+export type { ArchitectureDiagramProps, ArchitectureNode, DiagramEdge, DiagramFigureProps, DiagramFlowEdge, DiagramGroup, DiagramLayoutInfo, DiagramLegend, DiagramLineKind, DiagramMark, DiagramMotion, DiagramNode, DiagramPacket, DiagramPlacement, DiagramSide, DiagramUnplaced } from "./architecture-diagram";
export { FlowchartDiagram } from "./flowchart-diagram";
export type { DiagramShapeLabels, FlowchartDiagramProps, FlowchartNode } from "./flowchart-diagram";
export { DataFlowDiagram } from "./data-flow-diagram";
diff --git a/packages/react/test/content-policy.test.mjs b/packages/react/test/content-policy.test.mjs
index 9743e7e..06c8124 100644
--- a/packages/react/test/content-policy.test.mjs
+++ b/packages/react/test/content-policy.test.mjs
@@ -24,7 +24,7 @@ window.show = (provider) => {
};`;
/** A page served under `policy`, with the head files, the shipped sheet and the fixture as files of its own origin. `inline` is an inline script in the head. */
-async function policyPage(policy, { inline = "", storage = {}, viewport = { width: 1440, height: 900 } } = {}) {
+async function policyPage(policy, { inline = "", storage = {}, viewport = { width: 1440, height: 900 }, fixture = FIXTURE } = {}) {
const context = await browser.newContext({ viewport });
// Before any page script, and outside the policy: what a returning visitor has stored, and a log of every refusal.
await context.addInitScript((stored) => {
@@ -32,13 +32,13 @@ async function policyPage(policy, { inline = "", storage = {}, viewport = { widt
window.__refused = [];
document.addEventListener("securitypolicyviolation", (event) => window.__refused.push(`${event.effectiveDirective} ${event.blockedURI}`));
}, storage);
- const fixture = await bundleFixture(FIXTURE);
+ const bundled = await bundleFixture(fixture);
const files = {
"/": ["text/html", `${inline ? `` : ""}`],
"/styles.css": ["text/css", fs.readFileSync(path.join(dist, "styles.css"), "utf8")],
"/head/theme.js": ["text/javascript", fs.readFileSync(path.join(dist, "head", "theme.js"), "utf8")],
"/head/loops.js": ["text/javascript", fs.readFileSync(path.join(dist, "head", "loops.js"), "utf8")],
- "/fixture.js": ["text/javascript", fixture],
+ "/fixture.js": ["text/javascript", bundled],
};
await context.route(`${ORIGIN}/**`, (route) => {
const file = files[new URL(route.request().url()).pathname];
@@ -159,3 +159,95 @@ describe("Base UI's inline style under style-src 'self'", () => {
assert.deepEqual(boxes[1], boxes[0]);
});
});
+
+// A diagram under a strict style-src (CIMIP's adoption, DECISIONS 365, item 1): the line labels were placed by a style attribute in the ink's HTML, which the
+// policy refuses, so each landed in the drawing's corner, on the page and in the viewer. They are placed through the CSSOM now; a text sequence's transcript
+// (its lines' indents are styles) is drawn as elements in React and put back as its own nodes in the skill.
+const DIAGRAMS = `
+const arch = { title: "Arch", summary: "Three parts.", legend: { main: "Request" },
+ nodes: [{ id: "a", kind: "client", name: "Browser", col: 1, row: 1 }, { id: "b", kind: "service", name: "API", col: 2, row: 1 }, { id: "c", kind: "store", name: "Database", col: 3, row: 1 }],
+ edges: [{ from: "a", to: "b", kind: "main", label: "HTTPS" }, { from: "b", to: "c", label: "SQL" }] };
+const seq = { title: "Seq", summary: "A run.", variant: "text", participants: [{ id: "u", name: "User" }, { id: "s", name: "Service" }],
+ steps: [{ from: "u", to: "s", label: "asks" }, { frame: "opt", label: "when cached", steps: [{ from: "s", to: "u", kind: "dashed", label: "answers" }] }] };
+window.showDiagrams = () => createRoot(document.getElementById("root")).render(<>
+
+
+>);`;
+const DP = "basalt-diagram";
+const frames = (page, n = 3) => page.evaluate((n) => new Promise((resolve) => { let k = 0; const step = () => (++k >= n ? resolve() : requestAnimationFrame(step)); requestAnimationFrame(step); }), n);
+/** Each label's box in its drawing, and each transcript line's indent: what the policy refused before. */
+const placed = (page, root) => page.evaluate(({ P, root }) => {
+ const fig = document.querySelector(root);
+ const drawing = fig.querySelector(`.${P}-drawing`).getBoundingClientRect();
+ return [...fig.querySelectorAll(`.${P}-ink > .${P}-label`)].map((el) => {
+ const r = el.getBoundingClientRect();
+ return { text: el.textContent, x: Math.round(r.left - drawing.left), y: Math.round(r.top - drawing.top), w: Math.round(r.width) };
+ });
+}, { P: DP, root });
+const indents = (page) => page.evaluate((P) => [...document.querySelectorAll(`#seq .${P}-tx-line`)].map((el) => getComputedStyle(el).paddingInlineStart), DP);
+
+describe("a diagram under style-src 'self'", () => {
+ test("its line labels sit where an unrestricted page puts them, on the page and in the viewer, and the policy refuses nothing", async () => {
+ const read = async (policy) => {
+ const { page, context, errors } = await policyPage(policy, { fixture: DIAGRAMS });
+ try {
+ await page.evaluate(() => window.showDiagrams());
+ await page.waitForSelector(`#arch[data-layout="drawn"] .${DP}-ink > .${DP}-label`);
+ await frames(page);
+ const onPage = await placed(page, "#arch");
+ await page.locator(`#arch .${DP}-expand`).click();
+ await page.waitForSelector(`dialog.${DP}-viewer[open] .${DP}[data-layout="drawn"] .${DP}-ink > .${DP}-label`);
+ await frames(page);
+ const inViewer = await placed(page, `dialog.${DP}-viewer .${DP}`);
+ return { onPage, inViewer, refused: await refused(page), errors, indents: await indents(page) };
+ } finally {
+ await context.close();
+ }
+ };
+ const strict = await read(SELF);
+ const open = await read("default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'");
+ assert.deepEqual(strict.refused, []);
+ assert.deepEqual(strict.errors, []);
+ assert.equal(strict.onPage.length, 2);
+ // Off the corner: each label is on its line, past the first card.
+ for (const label of [...strict.onPage, ...strict.inViewer]) assert.ok(label.x > 100 && label.w > 0, `${label.text} is placed (${JSON.stringify(label)})`);
+ assert.deepEqual(strict.onPage, open.onPage);
+ assert.deepEqual(strict.inViewer, open.inViewer);
+ // The transcript's lines keep their indents: a message's label hangs under its sender, as it does with the policy open.
+ assert.ok(strict.indents.some((v) => Number.parseFloat(v) > 0), `indents ${strict.indents}`);
+ assert.deepEqual(strict.indents, open.indents);
+ });
+});
+
+// The PNG under a content policy (DECISIONS 365, item 2): a canvas draws the SVG through an image, which `img-src 'self'` refuses as a data: URL and as a
+// blob: URL. Where the policy allows neither, diagramToPng rejects with an error that names the fix, and makes no file; with `blob:` allowed it draws.
+const EXPORT = `${DIAGRAMS}
+import { diagramToPng } from "./dist/diagram-export.js";
+window.png = () => diagramToPng(document.getElementById("arch")).then(
+ (blob) => createImageBitmap(blob).then((image) => ({ type: blob.type, width: image.width, height: image.height })),
+ (error) => ({ error: error.message }));`;
+
+describe("a diagram's PNG under img-src", () => {
+ for (const [name, images, drawn] of [["'self'", "'self'", false], ["'self' blob:", "'self' blob:", true], ["'self' data:", "'self' data:", true]]) {
+ test(`img-src ${name}: ${drawn ? "the PNG is drawn at 2x" : "it rejects with an error that names img-src, and makes no file"}`, async () => {
+ const { page, context, errors } = await policyPage(`default-src 'self'; script-src 'self'; style-src 'self'; img-src ${images}`, { fixture: EXPORT });
+ try {
+ await page.evaluate(() => window.showDiagrams());
+ await page.waitForSelector(`#arch[data-layout="drawn"] .${DP}-ink > .${DP}-label`);
+ await frames(page);
+ const got = await page.evaluate(() => window.png());
+ const width = await page.evaluate(() => document.getElementById("arch").getBoundingClientRect().width);
+ if (drawn) {
+ assert.equal(got.type, "image/png");
+ assert.ok(got.width >= 2 * width, `${got.width} is at 2x of ${width}`);
+ } else {
+ assert.match(got.error, /img-src 'self' blob:/);
+ assert.equal(got.width, undefined);
+ }
+ assert.deepEqual(errors, []);
+ } finally {
+ await context.close();
+ }
+ });
+ }
+});
diff --git a/packages/react/test/diagram-interop-browser.test.mjs b/packages/react/test/diagram-interop-browser.test.mjs
index 26ec1aa..68e4d12 100644
--- a/packages/react/test/diagram-interop-browser.test.mjs
+++ b/packages/react/test/diagram-interop-browser.test.mjs
@@ -340,3 +340,57 @@ describe("live DOM measured Geo entry and B2 exact geometry (Chromium)", () => {
}
});
});
+
+// `onLayout` (DECISIONS 365, item 3): a figure hands the app its layout as it is on screen, which exportMeasuredDiagram takes, so an app's draw.io, Visio or
+// Lucid file is the layout the reader sees and not the headless approximation. Once for each layout: a callback that sets state never lays it out again.
+describe("onLayout", () => {
+ test("gives the on-screen layout, once for each, and exportMeasuredDiagram writes it; an automatic figure's spec carries its placement", async () => {
+ const autoArchPlaced = await interop.placeAutoDiagram(CIMIP_B.autoArchitecture);
+ const HOST = `
+ import data from "./test/fixtures/cimip-diagrams.json";
+ import { exportMeasuredDiagram, readMeasuredExtras } from "./dist/diagram-interop.js";
+ window.__laid = { arch: [], auto: [] };
+ window.__files = {};
+ function Host() {
+ // A new callback every render, and one that sets state: the figure is not laid out again for it.
+ const [count, setCount] = React.useState(0);
+ const { type: _a, ...arch } = data.architecture;
+ const { type: _b, ...auto } = ${JSON.stringify(autoArchPlaced)};
+ const on = (key) => (laid) => {
+ window.__laid[key].push({ layout: laid.layout, nodes: laid.geo.nodes.length, placement: Boolean(laid.spec.placement), figure: laid.figure.id });
+ window.__files[key] = exportMeasuredDiagram(laid.spec, laid.geo, "drawio", { extras: readMeasuredExtras(laid.figure) });
+ setCount((n) => n + 1);
+ };
+ return
+
+
+ ;
+ }
+ createRoot(document.getElementById("root")).render();
+ `;
+ const browser = await launch();
+ try {
+ const { page, errors } = await fixturePage(browser, HOST, { theme: "light", viewport: { width: 1280, height: 1200 }, standards: true });
+ await page.evaluate(() => document.fonts.ready);
+ await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r)))));
+ const got = await page.evaluate(() => ({ laid: window.__laid, files: window.__files, names: [...document.querySelectorAll("#fig-arch .basalt-diagram-node")].length }));
+ assert.deepEqual(errors, []);
+ for (const key of ["arch", "auto"]) {
+ const list = got.laid[key];
+ assert.ok(list.length >= 1 && list.length <= 3, `${key}: laid out ${list.length} times, not in a loop`);
+ assert.equal(list.at(-1).layout, "drawn");
+ assert.equal(list.at(-1).figure, `fig-${key}`);
+ assertValidDrawio(got.files[key], key === "arch" ? CIMIP.architecture : autoArchPlaced, `onLayout/${key}`);
+ }
+ assert.equal(got.laid.arch.at(-1).nodes, got.names);
+ assert.equal(got.laid.auto.at(-1).placement, true);
+ // A resize lays it out anew, and onLayout says so.
+ const before = await page.evaluate(() => window.__laid.arch.length);
+ await page.evaluate(() => { document.querySelector("main").style.width = "1000px"; });
+ await page.evaluate(() => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => requestAnimationFrame(r)))));
+ assert.ok(await page.evaluate(() => window.__laid.arch.length) > before);
+ } finally {
+ await browser.close();
+ }
+ });
+});
diff --git a/packages/react/test/export-sizes.json b/packages/react/test/export-sizes.json
index f73fce5..5bf138f 100644
--- a/packages/react/test/export-sizes.json
+++ b/packages/react/test/export-sizes.json
@@ -18,7 +18,7 @@
"AppHeader": 1285,
"AppShell": 104323,
"AppTile": 1112,
- "ArchitectureDiagram": 103233,
+ "ArchitectureDiagram": 104061,
"ArrowDownGlyph": 2868,
"ArrowLeftGlyph": 2869,
"ArrowRightGlyph": 2859,
@@ -70,7 +70,7 @@
"CopyGlyph": 2884,
"Countdown": 3016,
"CoverageStrip": 1570,
- "DataFlowDiagram": 103178,
+ "DataFlowDiagram": 104002,
"DateAge": 2527,
"DescriptionColumns": 216,
"DescriptionItem": 593,
@@ -105,7 +105,7 @@
"Fieldset": 6390,
"FilterResult": 698,
"FilterToolbar": 774,
- "FlowchartDiagram": 103199,
+ "FlowchartDiagram": 104023,
"Form": 8730,
"FormGrid": 438,
"FormGridItem": 628,
@@ -232,7 +232,7 @@
"STAGE_WORDS": 149,
"STATUS_MESSAGE_MS": 26,
"SandboxesGlyph": 2963,
- "SchemaDiagram": 103147,
+ "SchemaDiagram": 103971,
"SearchDialog": 89508,
"SearchField": 18500,
"SearchGlyph": 3183,
@@ -251,7 +251,7 @@
"SelectableList": 821,
"SelectionBar": 25913,
"Separator": 4531,
- "SequenceDiagram": 103175,
+ "SequenceDiagram": 103999,
"SettingsGlyph": 3100,
"ShareBar": 1411,
"Sheet": 70793,
@@ -433,8 +433,8 @@
}
},
"package": {
- "bytes": 951429,
- "gzip": 317152
+ "bytes": 952285,
+ "gzip": 317439
},
"styles": {
"bytes": 470470,
diff --git a/scripts/check-sinks.mjs b/scripts/check-sinks.mjs
index 62233b3..0c6a512 100644
--- a/scripts/check-sinks.mjs
+++ b/scripts/check-sinks.mjs
@@ -11,7 +11,7 @@
// - in tools/html-skill/src, where every module is a string builder, the file's count is in tools/html-skill/src/sinks.allowed.json with what the
// file takes ("takes"), why it is safe ("safe") and whether it takes data ("data": a data-taking module is in the hostile-input probe);
// - anywhere else, a comment in the block just above the line: `sink: ; ; `
-// (tools/review, whose pages are synthetic, may leave out the test).
+// (tools/review, whose pages are synthetic, may leave out the test). A `//` reason may run on over the `//` lines straight under it.
// A count that is off, an entry with no reason, a comment with no reason, and a `sink:` comment above no sink all fail. A file that does not parse fails:
// the check never passes what it could not read. The skill's sources hold build placeholders (%duration-confirm%); they are read as numbers in place.
import fs from "node:fs";
@@ -106,6 +106,7 @@ export function sinksIn(file, text) {
const lang = file.endsWith(".tsx") ? "tsx" : file.endsWith(".ts") ? "ts" : file.endsWith(".jsx") ? "jsx" : "js";
const parsed = parseSync(file, source, { lang, sourceType: "module" });
if (parsed.errors.length) throw new Error(`${file}: does not parse (${parsed.errors[0].message}); the sink check reads no file it cannot parse`);
+ const lines = source.split("\n");
const starts = [0];
for (let i = 0; i < source.length; i++) if (source[i] === "\n") starts.push(i + 1);
const lineOf = (offset) => { let lo = 0, hi = starts.length - 1; while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (starts[mid] <= offset) lo = mid; else hi = mid - 1; } return lo + 1; };
@@ -164,7 +165,29 @@ export function sinksIn(file, text) {
stack.shift();
};
descend(parsed.program);
- return { found, comments: parsed.comments.map((c) => ({ text: c.value, line: lineOf(c.start), end: lineOf(c.end) })) };
+ return { found, comments: joinLineComments(parsed.comments.map((c) => ({ text: c.value, line: lineOf(c.start), end: lineOf(c.end), line1: c.type === "Line" && /^\s*\/\//.test(lines[lineOf(c.start) - 1] ?? "") }))) };
+}
+
+/**
+ * A `//` reason may go on over the lines under it: a `sink:` line comment takes each `//` comment on the lines straight after it (each on a line of its own,
+ * until a line that is not one, or another `sink:`), as one comment, so a reason too long for a line is read whole and not as one with no test.
+ */
+function joinLineComments(comments) {
+ const out = [];
+ for (let k = 0; k < comments.length; k++) {
+ const c = comments[k];
+ if (!c.line1 || !/^\s*sink:/.test(c.text)) { out.push(c); continue; }
+ const joined = { ...c };
+ while (k + 1 < comments.length) {
+ const next = comments[k + 1];
+ if (!next.line1 || next.line !== joined.end + 1 || /^\s*sink:/.test(next.text)) break;
+ joined.text += ` ${next.text.trim()}`;
+ joined.end = next.line;
+ k++;
+ }
+ out.push(joined);
+ }
+ return out.map(({ line1: _, ...c }) => c);
}
const REASON = /\bsink:\s*([^;]*?)\s*;\s*([^;]*?)\s*(?:;\s*(.*?))?\s*(?:\*\/)?$/;
diff --git a/tools/html-skill/src/modules/diagram-text.js b/tools/html-skill/src/modules/diagram-text.js
index 716acda..4bd0adb 100644
--- a/tools/html-skill/src/modules/diagram-text.js
+++ b/tools/html-skill/src/modules/diagram-text.js
@@ -10,7 +10,6 @@ import { textArt } from "../../../../packages/react/src/diagram-text.ts";
var pre = figure.querySelector('.diagram-text');
var code = pre && pre.querySelector('.diagram-text-ink');
if (!code) return;
- if (!figure.__transcript) figure.__transcript = code.innerHTML;
var made = textArt(model);
// A glyph's width at 100%: offsetWidth, which no transform scales (the viewer's layer is zoomed when this runs), on one unbreakable run.
var probe = document.createElement('span');
@@ -27,8 +26,16 @@ import { textArt } from "../../../../packages/react/src/diagram-text.ts";
room = pre.clientWidth - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight);
}
var art = made.width * cw <= room + 0.5;
- var html = art ? made.html : figure.__transcript;
- if (code.innerHTML !== html) code.innerHTML = html;
+ // The transcript is kept as its own nodes while the art is shown, and put back as they are: written again as HTML, its lines' indents (styles) would
+ // be refused under a strict style-src. The art has no style. What is shown is the module's own note: a redraw's attributes take data-art off.
+ var showing = Boolean(pre.__art);
+ if (art) {
+ if (!showing) pre.__transcript = Array.prototype.slice.call(code.childNodes);
+ if (!showing || code.innerHTML !== made.html) code.innerHTML = made.html;
+ } else if (showing && pre.__transcript) {
+ code.replaceChildren.apply(code, pre.__transcript);
+ }
+ pre.__art = art;
pre.toggleAttribute('data-art', art);
// Under "motion": "animated" the art builds by ink when it comes into view: the diagram-motion module's, as a drawn figure's entrance is.
};
diff --git a/tools/html-skill/src/modules/diagram.js b/tools/html-skill/src/modules/diagram.js
index 421332a..5f081a4 100644
--- a/tools/html-skill/src/modules/diagram.js
+++ b/tools/html-skill/src/modules/diagram.js
@@ -4,7 +4,7 @@
and draw the same pixels. compose.mjs runs `Basalt._.diagramMarkup` at build time and writes each figure's words into the page, so it
reads before any script runs; this script then measures it, draws its lines and labels, and wires the keys, the trace and the list.
Source: tools/html-skill/src/modules/diagram.js (do not edit the copy in the skill folder). */
-import { applyTrace, tapTrace, buildModel, entranceDrawn, escapeHtml, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, moveStop, settleEntrance, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts";
+import { applyTrace, tapTrace, buildModel, entranceDrawn, escapeHtml, figureKey, figureList, figureTree, hasStops, hintEntries, keyTarget, measureFigure, moveStop, placeLabels, settleEntrance, syncAttributes, toHtml } from "../../../../packages/react/src/diagram-core.ts";
(function (B) {
'use strict';
@@ -189,6 +189,9 @@ import { applyTrace, tapTrace, buildModel, entranceDrawn, escapeHtml, figureKey,
if (!hasStops(model, state)) hoverTrace = touchTrace = null;
var fresh = ink && measured.ink !== drawn;
if (fresh) { ink.innerHTML = measured.ink; drawn = measured.ink; }
+ // The labels' places are not in the ink's string (a content policy refuses a style attribute in it): set through the CSSOM after every measure, since
+ // a label can move while the string stays the same.
+ placeLabels(figure, P, measured.geo);
retrace();
// In the frame an animated figure's lines are first drawn it is pending; after that the motion module follows a drawing that changed.
// The text variant (DECISIONS 306, 1.2): the art where its widest line fits the block (the diagram-text module's), the transcript otherwise; in the
diff --git a/tools/html-skill/src/sinks.allowed.json b/tools/html-skill/src/sinks.allowed.json
index 0b598f5..d860446 100644
--- a/tools/html-skill/src/sinks.allowed.json
+++ b/tools/html-skill/src/sinks.allowed.json
@@ -8,7 +8,7 @@
"modules/copy.js": { "count": 3, "data": false, "takes": "the button's own markup, and the copied or failed state's glyph and words", "safe": "markup the button already held, and constants" },
"modules/diagram-motion.js": { "count": 1, "data": false, "takes": "the pause button's seat with the pause glyph's two forms", "safe": "constant markup and a drawing from the glyph set" },
"modules/diagram.js": { "count": 4, "data": true, "takes": "a diagram's figure, its words and its ink, from the page's diagram JSON, and its key hint", "safe": "React's diagram engine (diagram-core.ts) writes them, escaping every text and attribute; a card's mark is a path compose.mjs read into a data: image; the hint's keys and words are the engine's own, through escapeHtml" },
- "modules/diagram-text.js": { "count": 1, "data": true, "takes": "a text sequence's art or its transcript, from the page's diagram JSON", "safe": "the engine's textArt and transcript write them, every name, label and note through escapeHtml; the transcript is the figure's own markup read back" },
+ "modules/diagram-text.js": { "count": 1, "data": true, "takes": "a text sequence's art, from the page's diagram JSON", "safe": "the engine's textArt writes it, every name, label and note through escapeHtml; the transcript is never written as HTML: its own nodes are kept and put back" },
"modules/diagram-zoom.js": { "count": 2, "data": true, "takes": "the viewer dialog's frame (its title, source and summary, its key and hint) and the figure's list, from the page's diagram JSON", "safe": "the title, source, summary and the hint's words go through esc; the key and the list are the engine's figureKey and figureList through toHtml, which escapes every text and attribute; ids are the module's own" },
"modules/filter.js": { "count": 1, "data": true, "takes": "its element helper's markup: the Clear button's word and the chip's glyphs", "safe": "constants only; the group's label and each value's label are set as textContent" },
"modules/framed-art.js": { "count": 1, "data": true, "takes": "the art's alt text, shown when the image fails", "safe": "the text goes through esc" },
diff --git a/tools/html-skill/src/usage/diagram-export.md b/tools/html-skill/src/usage/diagram-export.md
index 511d845..e555ff9 100644
--- a/tools/html-skill/src/usage/diagram-export.md
+++ b/tools/html-skill/src/usage/diagram-export.md
@@ -3,4 +3,5 @@
Added for you when a diagram's JSON says `"export": true`.
- The figure's foot gets "Download SVG" and "Download PNG", and so does its viewer's (the drawn layout at 100%, whatever the zoom). Each writes the figure in the theme shown: the title and source, the drawing and the key, at rest; native SVG with its words as text and the faces embedded; the PNG at 2x.
+- The PNG is drawn through an image: under a content policy, `img-src` must allow `blob:` or `data:`. Where it allows neither, "Download PNG" makes no file and the console says why; "Download SVG" needs neither.
- Without `"export": true` there are no buttons and no module. Don't add your own.
diff --git a/tools/html-skill/test/sinks.test.mjs b/tools/html-skill/test/sinks.test.mjs
index 782e8f3..b300d7e 100644
--- a/tools/html-skill/test/sinks.test.mjs
+++ b/tools/html-skill/test/sinks.test.mjs
@@ -70,6 +70,15 @@ describe("the sink check", () => {
fails("// sink: a; b; c\nconst quiet = 1;", /above no sink/);
assert.deepEqual(checkSource("tools/review/round99.tsx", "// sink: a synthetic page; built at review time\nel.innerHTML = v;"), []);
});
+ test("a `//` reason may go on over the lines under it (CIMIP's port, DECISIONS 365): read whole, up to a line that is not one or another sink:", () => {
+ passes("// sink: the figure's ink, from the model;\n// every text and attribute is escaped there;\n// test/repo-review.test.mjs\nel.innerHTML = v;");
+ passes("const a = 1;\n // sink: a value from props; escaped by escapeHtml\n // in the builder; test/x.test.mjs\n el.innerHTML = v;");
+ // The lines after the reason are part of it only while they run on: a line of code ends it, and so does a second reason.
+ fails("// sink: from props;\nconst x = 1; // escaped; test/x.test.mjs\nel.innerHTML = v;", /with no `sink:` reason|needs `sink:/);
+ fails("// sink: from props; escaped\n// sink: a; b; c\nel.innerHTML = v;", /needs `sink:|above no sink/);
+ // A block comment was always read whole; it still is.
+ passes("/* sink: from props;\n escaped; test/x.test.mjs */\nel.innerHTML = v;");
+ });
test("a file it cannot parse fails: the check never passes what it could not read", () => {
assert.throws(() => checkSource(file, "el.innerHTML = ;"), /does not parse/);
});