vizmatic 0.7.1 → 0.7.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/PROMPT.md +25 -1
- package/ROADMAP.md +1 -1
- package/dist/{chunk-DTD35LPT.js → chunk-F6QI6QJY.js} +60 -2
- package/dist/chunk-QVYHYC7T.js +88 -0
- package/dist/cli.js +10 -9
- package/dist/index.cjs +70 -3
- package/dist/index.d.cts +4 -2
- package/dist/index.d.ts +4 -2
- package/dist/index.js +14 -3
- package/dist/scene-cli.js +1 -1
- package/dist/stage-browser/browser.d.ts +144 -5
- package/dist/stage-browser/stage.js +5 -5
- package/dist/stage-export.cjs +67 -1
- package/dist/stage-export.d.cts +5 -1
- package/dist/stage-export.d.ts +5 -1
- package/dist/stage-export.js +11 -1
- package/dist/stage.cjs +286 -22
- package/dist/stage.d.cts +146 -7
- package/dist/stage.d.ts +146 -7
- package/dist/stage.js +268 -9
- package/dist/{svg-import-Djj2q7Pc.d.cts → svg-import-5_oTbEJR.d.cts} +2 -2
- package/dist/{svg-import-Djj2q7Pc.d.ts → svg-import-5_oTbEJR.d.ts} +2 -2
- package/dist/{video-CcHW1qhV.d.cts → video-BSwNJZkn.d.cts} +25 -1
- package/dist/{video-CcHW1qhV.d.ts → video-BSwNJZkn.d.ts} +25 -1
- package/examples/_teaching/categorical-tail-loss.ts +3 -3
- package/examples/_teaching/teaching-byte-diff.ts +3 -3
- package/examples/_teaching/teaching-routed-transfer.ts +3 -3
- package/examples/_teaching/teaching-token-history.ts +2 -2
- package/examples/_teaching/teaching-weighted-vector.ts +3 -3
- package/examples/films/attention.ts +5 -4
- package/examples/films/fourier-epicycles.ts +5 -2
- package/examples/films/pythagoras.ts +2 -2
- package/examples/films/taylor-series.ts +3 -2
- package/package.json +1 -1
- package/dist/chunk-3LQLKLGH.js +0 -79
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import{__export}from"./chunk-PSBF4TEK.js";var DENSITY_NAMES=["dense","compact","comfortable","presentation"];var DEFAULT_DENSITY="dense";function half(value){return Math.round(value*2)/2}function quarter(value){return Math.round(value*4)/4}var curves={dense:{f:size=>Math.max(9,half(size<=14?size*.9:12.6+(size-14)*.75)),s:size=>quarter(size*.6),w:width=>Math.max(.75,quarter(width*.6)),r:radius=>Math.min(5,half(radius*.5)),g:size=>quarter(size*.8),arrow:5.5,scale:.86},compact:{f:size=>Math.max(9.5,half(size<=14?size*.95:13.3+(size-14)*.88)),s:size=>quarter(size*.8),w:width=>Math.max(.9,quarter(width*.75)),r:radius=>Math.min(7,half(radius*.7)),g:size=>quarter(size*.9),arrow:5.5,scale:.93},comfortable:{f:size=>size,s:size=>size,w:width=>width,r:radius=>Math.min(10,radius),g:size=>size,arrow:5,scale:1},presentation:{f:size=>half(size*1.5),s:size=>quarter(size*1.4),w:width=>quarter(width*1.4),r:radius=>half(radius*1.2),g:size=>quarter(size*1.5),arrow:4.5,scale:1.5}};function numericCurve(scale){return{f:size=>Math.max(8,half(size*scale)),s:size=>quarter(size*Math.pow(scale,1.2)),w:width=>Math.max(.6,quarter(width*scale)),r:radius=>half(radius*scale),g:size=>quarter(size*scale),arrow:5,scale}}function buildTokens(name,curve){const{f,s,w,r,g}=curve;return{name,scale:curve.scale,type:{micro:f(10),small:f(11),body:f(13),label:f(14),heading:f(16),subtitle:f(20),title:f(28),metric:f(24)},space:{hair:s(2),xs:s(4),sm:s(8),md:s(12),lg:s(16),xl:s(24),canvas:s(40)},stroke:{hair:w(1),line:w(1.5),strong:w(2),heavy:w(3)},radius:{sm:r(4),md:r(8),lg:r(12)},arrow:curve.arrow,f,s,w,r,g}}var tokenCache=new Map;function assertDensity(density){if(typeof density==="number"?!Number.isFinite(density)||density<=0:!DENSITY_NAMES.includes(density)){throw new Error(`Unknown density ${JSON.stringify(density)}. Use ${DENSITY_NAMES.join(", ")}, or a positive number.`)}}function parseDensity(value){const parsed=typeof value==="string"&&value.trim()!==""&&!Number.isNaN(Number(value))?Number(value):value;assertDensity(parsed);return parsed}function densityTokens(density=DEFAULT_DENSITY){const cached=tokenCache.get(density);if(cached)return cached;assertDensity(density);const tokens=typeof density==="number"?buildTokens("custom",numericCurve(density)):buildTokens(density,curves[density]);tokenCache.set(density,tokens);return tokens}var sharedKey=Symbol.for("vizmatic.density");var globals=globalThis;var shared=globals[sharedKey]??={resolvers:new Set};function setDefaultDensity(density){if(density!==void 0)assertDensity(density);shared.ambient=density}function setDensityResolver(resolver){shared.resolvers.add(resolver)}function currentRenderDensity(){for(const resolver of shared.resolvers){const density=resolver();if(density!==void 0)return density}return void 0}function densityOf(c){return densityTokens(c?.density??currentRenderDensity()??shared.ambient??DEFAULT_DENSITY)}function withDensity(c,density){assertDensity(density);return{...c,density}}function detectBackgroundColor(pixels){const r=pixels[0];const g=pixels[1];const b=pixels[2];const a=pixels[3];if(a<10){return"transparent"}return`#${r.toString(16).padStart(2,"0")}${g.toString(16).padStart(2,"0")}${b.toString(16).padStart(2,"0")}`}function parseHexColor(hex){const h=hex.startsWith("#")?hex.slice(1):hex;return[parseInt(h.slice(0,2),16),parseInt(h.slice(2,4),16),parseInt(h.slice(4,6),16)]}function createBackgroundMatcher(bgColor,tolerance=6){if(bgColor==="transparent"){return(_r,_g,_b,a)=>a<10}const[bgR,bgG,bgB]=parseHexColor(bgColor);return(r,g,b,a)=>{if(a<10)return true;return Math.abs(r-bgR)<=tolerance&&Math.abs(g-bgG)<=tolerance&&Math.abs(b-bgB)<=tolerance}}function detectContentBounds(pixels,width,height,bgColor,padding=20){const isBackground=createBackgroundMatcher(bgColor);let minX=width;let minY=height;let maxX=0;let maxY=0;for(let y=0;y<height;y++){for(let x=0;x<width;x++){const idx=(y*width+x)*4;const r=pixels[idx];const g=pixels[idx+1];const b=pixels[idx+2];const a=pixels[idx+3];if(!isBackground(r,g,b,a)){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;if(y>maxY)maxY=y}}}if(minX>maxX||minY>maxY){return{x:0,y:0,width,height}}const cropX=Math.max(0,minX-padding);const cropY=Math.max(0,minY-padding);const cropRight=Math.min(width,maxX+1+padding);const cropBottom=Math.min(height,maxY+1+padding);return{x:cropX,y:cropY,width:cropRight-cropX,height:cropBottom-cropY}}function cropPixels(pixels,srcWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const srcOffset=((region.y+y)*srcWidth+region.x)*4;const dstOffset=y*region.width*4;out.set(pixels.subarray(srcOffset,srcOffset+region.width*4),dstOffset)}return out}function detectOverflow(pixels,width,height,bgColor,edgeTolerance=3,minDensity=.05,alphaThreshold=10){const isBackground=createBackgroundMatcher(bgColor);function isContentPixel(x,y){const idx=(y*width+x)*4;const a=pixels[idx+3];if(a<alphaThreshold)return false;return!isBackground(pixels[idx],pixels[idx+1],pixels[idx+2],a)}function checkEdge(scanFn,length){for(let offset=0;offset<edgeTolerance;offset++){let contentCount=0;for(let i=0;i<length;i++){const[x,y]=scanFn(i,offset);if(x>=0&&x<width&&y>=0&&y<height&&isContentPixel(x,y)){contentCount++}}if(contentCount/length>=minDensity){return true}}return false}const bottom=checkEdge((i,off)=>[i,height-1-off],width);const right=checkEdge((i,off)=>[width-1-off,i],height);const top=checkEdge((i,off)=>[i,off],width);const left=checkEdge((i,off)=>[off,i],height);const overflowEdges=[];if(top)overflowEdges.push("top");if(right)overflowEdges.push("right");if(bottom)overflowEdges.push("bottom");if(left)overflowEdges.push("left");const overflows=overflowEdges.length>0;const message=overflows?`Content overflows canvas at: ${overflowEdges.join(", ")}. Increase the illustration dimensions.`:"";return{overflows,edges:{top,right,bottom,left},message}}function detectLayoutOverflow(nodes,width,height){const edges={top:false,right:false,bottom:false,left:false};for(const node of nodes){if(!String(node.textContent??"").trim()||node.width<=0||node.height<=0)continue;const style=node.props.style;if(style?.transform)continue;edges.top||=node.top+node.height<0;edges.left||=node.left+node.width<0;edges.bottom||=node.top+node.height>height+1;edges.right||=node.left+node.width>width+1}const names=Object.keys(edges).filter(edge=>edges[edge]);return{overflows:names.length>0,edges,message:names.length>0?`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`:""}}import{Resvg}from"@resvg/resvg-js";import{homedir}from"os";import{readFile,writeFile,mkdir}from"fs/promises";import{dirname,join}from"path";import{existsSync}from"fs";import{fileURLToPath}from"url";import{brotliDecompressSync}from"zlib";import React from"react";var DEFAULT_WATERMARK_TEXT="Vizmatic";var WATERMARK_COLOR_DARK="#a5a7ad";var WATERMARK_COLOR_LIGHT="#5e5a50";function VizmaticIcon({size=14,color}){return React.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:size,height:size,viewBox:"0 0 28 28",fill:"none"},React.createElement("rect",{x:2.5,y:2.5,width:23,height:23,rx:6.5,stroke:color,strokeWidth:2,opacity:.54}),React.createElement("rect",{x:7,y:7,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.35}),React.createElement("rect",{x:15.5,y:7,width:5.5,height:5.5,rx:1.8,fill:color}),React.createElement("rect",{x:7,y:15.5,width:5.5,height:5.5,rx:1.8,fill:color,opacity:.82}),React.createElement("rect",{x:15.5,y:15.5,width:5.5,height:5.5,rx:1.8,stroke:color,strokeWidth:1.5,opacity:.72}),React.createElement("path",{d:"M9.75 9.75h8.5M9.75 18.25h8.5M9.75 9.75v8.5M18.25 9.75v8.5",stroke:color,strokeWidth:1.6,strokeLinecap:"round",opacity:.88}))}function normalizeWatermark(watermark){if(watermark==null||watermark===false)return void 0;if(watermark===true)return{};if(typeof watermark==="string")return{text:watermark};if(React.isValidElement(watermark)){if(watermark.type!==Watermark)return{element:watermark};const{children,...props}=watermark.props;return{...props,element:children??props.element}}return watermark}function Watermark(_props){return null}function positionStyle(position){switch(position){case"top-left":return{top:8,left:10};case"bottom-left":return{bottom:8,left:10};case"bottom-right":return{bottom:8,right:10};case"top-right":default:return{top:8,right:10}}}function imageNode(image){if(!image)return void 0;const imageOptions=typeof image==="string"?{src:image}:image;return React.createElement("img",{src:imageOptions.src,alt:imageOptions.alt??"",width:imageOptions.width??14,height:imageOptions.height??14,style:{display:"block",width:imageOptions.width??14,height:imageOptions.height??14,objectFit:"contain"}})}function iconNode(icon,color){if(icon===false)return void 0;if(icon==null)return React.createElement(VizmaticIcon,{size:13,color});if(typeof icon!=="string")return icon;return React.createElement("div",{style:{minWidth:13,height:13,display:"flex",alignItems:"center",justifyContent:"center",color,fontSize:icon.length>2?8:10,fontWeight:800,fontFamily:"Inter",lineHeight:1}},icon)}function wrapWithWatermark(element,width,height,theme="dark",watermark=true){const isDark=theme==="dark";const options=normalizeWatermark(watermark);const color=options?.color??(isDark?WATERMARK_COLOR_DARK:WATERMARK_COLOR_LIGHT);const position=options?.position??"top-right";const opacity=options?.opacity??(isDark?.55:.4);const icon=options?imageNode(options.image)??iconNode(options.icon,color):void 0;const text=options?.text??DEFAULT_WATERMARK_TEXT;const content=options?.element??[icon,text!==false&&text&&React.createElement("div",{key:"text",style:{fontSize:11,fontWeight:600,color,fontFamily:"Inter",letterSpacing:.3}},text)];return React.createElement("div",{style:{width,height,display:"flex",position:"relative"}},element,options&&React.createElement("div",{style:{position:"absolute",...positionStyle(position),display:"flex",alignItems:"center",gap:5,opacity}},content))}function wrapWithBrand(element,width,height,theme="dark",label=DEFAULT_WATERMARK_TEXT){return wrapWithWatermark(element,width,height,theme,label)}import{AsyncLocalStorage}from"async_hooks";var RENDER_CONTEXT_KEY=Symbol.for("vizmatic.renderContext");var globalRenderContext=globalThis;var renderContext=globalRenderContext[RENDER_CONTEXT_KEY]??=new AsyncLocalStorage;setDensityResolver(()=>renderContext.getStore()?.density);function getRenderBackground(){return renderContext.getStore()?.background??"transparent"}async function withRenderContext(context,render){const parent=renderContext.getStore();return renderContext.run({...parent,...context},render)}import*as satoriModule from"./satori.cjs";import React2,{isValidElement}from"react";var CANVAS_CHART_COMPONENT=Symbol.for("vizmatic.canvasChartComponent");var CHART_FRAME_COMPONENT=Symbol.for("vizmatic.chartFrameComponent");var FIT_PROP="__vizmaticCanvasChartFit";var SCOPE_PROP="data-vizmatic-chart-fit-scope";var VIEWPORT_PROP="data-vizmatic-chart-fit-viewport";function isCanvasChart(component){return typeof component==="function"&&Boolean(component[CANVAS_CHART_COMPONENT])}function CanvasChartFit({children,width,height}){let chart=children;for(let depth=0;isValidElement(chart)&&typeof chart.type==="function"&&depth<16;depth+=1){if(chart.type[CHART_FRAME_COMPONENT]){const props=chart.props;const padding=typeof props.padding==="number"?props.padding:16;chart=React2.cloneElement(chart,{...props,width:typeof props.width==="number"?props.width+2*(padding+1):props.width,height:void 0});break}chart=chart.type(chart.props)}return React2.createElement("div",{[FIT_PROP]:{width,height},style:{position:"relative",display:"flex",width,height,flexShrink:0}},React2.createElement("div",{style:{position:"absolute",left:0,top:0,display:"flex",alignItems:"flex-start"}},chart))}function prepareChartFits(element){const sizes=new Map;const hasText=node=>{if(typeof node==="string"||typeof node==="number"||typeof node==="bigint")return true;if(Array.isArray(node))return node.some(hasText);return isValidElement(node)&&node.type===React2.Fragment&&hasText(node.props.children)};const visit=(node,scope)=>{if(Array.isArray(node))return node.map(child=>visit(child,scope));if(!isValidElement(node))return node;const forwarded=node.type;const render=typeof node.type==="function"?node.type:forwarded?.$$typeof===Symbol.for("react.forward_ref")?forwarded.render:void 0;if(render){const resolved=visit(render(node.props),scope);return node.key!=null&&isValidElement(resolved)?React2.cloneElement(resolved,{key:node.key}):resolved}const size=node.props[FIT_PROP];const props={...node.props};delete props[FIT_PROP];let childScope=scope;if(size){const id=String(sizes.size);sizes.set(id,size);props[VIEWPORT_PROP]=id;childScope=id}else if(scope!==void 0&&typeof node.type==="string"){props[SCOPE_PROP]=scope}const children=node.props.children;const preparedChildren=children===void 0?void 0:visit(children,childScope);if(typeof node.type==="string"){const style=node.props.style;props.style={minWidth:0,minHeight:0,...style?.flex===void 0?{flexShrink:hasText(preparedChildren)?1:0}:{},...style}}return children===void 0?React2.cloneElement(node,props):React2.cloneElement(node,props,preparedChildren)};return{element:visit(element),sizes}}function fittedTree(element,geometry){if(Array.isArray(element))return element.map(child=>fittedTree(child,geometry));if(!isValidElement(element))return element;const id=element.props[VIEWPORT_PROP];const children=element.props.children;if(typeof id==="string"){const fit=geometry.get(id);const content=React2.Children.only(children);return React2.cloneElement(element,{},React2.cloneElement(content,{style:{...content.props.style,left:fit.left,top:fit.top,transform:`scale(${fit.scale})`,transformOrigin:"top left"}}))}return children===void 0?element:React2.cloneElement(element,{},fittedTree(children,geometry))}async function renderWithCanvasChartFit(render,element,options){const prepared=prepareChartFits(element);if(!prepared.sizes.size)return render(prepared.element,options);const viewports=new Map;const bounds=new Map;await render(prepared.element,{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")viewports.set(viewport,node);const id=node.props[SCOPE_PROP];if(typeof id!=="string"||node.width<0||node.height<0)return;const prior=bounds.get(id);bounds.set(id,{left:Math.min(prior?.left??Infinity,node.left),top:Math.min(prior?.top??Infinity,node.top),right:Math.max(prior?.right??-Infinity,node.left+node.width),bottom:Math.max(prior?.bottom??-Infinity,node.top+node.height)})}});const geometry=new Map;for(const[id,size]of prepared.sizes){const viewport=viewports.get(id);const measured=bounds.get(id);if(!viewport||!measured)throw new Error("Could not measure the chart inside CanvasItem.");const width=measured.right-measured.left,height=measured.bottom-measured.top;const scale=Math.min(size.width/width,size.height/height);if(!Number.isFinite(scale)||scale<=0)throw new Error("CanvasItem charts require positive, finite dimensions.");geometry.set(id,{...size,scale,left:(size.width-width*scale)/2-(measured.left-viewport.left)*scale,top:(size.height-height*scale)/2-(measured.top-viewport.top)*scale})}const finalViewports=new Map;return render(fittedTree(prepared.element,geometry),{...options,onNodeDetected(node){const viewport=node.props[VIEWPORT_PROP];if(typeof viewport==="string")finalViewports.set(viewport,node);const id=node.props[SCOPE_PROP];const fit=typeof id==="string"?geometry.get(id):void 0;const origin=typeof id==="string"?finalViewports.get(id):void 0;if(fit&&origin){const left=origin.left+fit.left,top=origin.top+fit.top;const style=node.props.style??{};options.onNodeDetected?.({...node,left:left+(node.left-left)*fit.scale,top:top+(node.top-top)*fit.scale,width:node.width*fit.scale,height:node.height*fit.scale,props:{...node.props,style:{...style,...typeof style.fontSize==="number"?{fontSize:style.fontSize*fit.scale}:{}}}})}else options.onNodeDetected?.(node)}})}function resolveSatori(api){if(typeof api==="function")return api;if(api&&typeof api==="object"){const fallback=api.default;if(typeof fallback==="function")return fallback;if(fallback&&typeof fallback==="object"){const nestedFallback=fallback.default;if(typeof nestedFallback==="function")return nestedFallback}}throw new Error("satori export could not be resolved")}var renderSatori=resolveSatori(satoriModule);var satori=(element,options)=>renderWithCanvasChartFit(renderSatori,element,options);import{cloneElement,isValidElement as isValidElement2}from"react";var SVG_ACCESSIBILITY_COMPONENT=Symbol.for("vizmatic.svgAccessibilityComponent");function chartAccessibilityAttributes({id,ariaLabel,description}){const title=ariaLabel?.trim()||"Chart";return{role:"img","aria-label":title,"aria-description":description,"data-vizmatic-chart-id":id,"data-vizmatic-chart-title":title,"data-vizmatic-chart-description":description}}function chartDescription(description,entries2){return[description,entries2.length?`${entries2.join("; ")}.`:"No data."].filter(Boolean).join(" ")}function componentHasSvgMetadata(type){return typeof type==="function"&&type[SVG_ACCESSIBILITY_COMPONENT]===true}function svgToken(value){if(value.length===0)return"empty";return Array.from(value,character=>{const codePoint=character.codePointAt(0)??0;return/^[A-Za-z0-9.-]$/.test(character)?character:`_u${codePoint.toString(16)}_`}).join("")}function textProperty(props,name){const value=props[name];return typeof value==="string"?value:""}function encodedTextProperty(props,name){const value=textProperty(props,name);try{return decodeURIComponent(value)}catch{return value}}function prepareAccessibleSvg(element){const graphs=[];const explicitIds=new Set;const visit=(node,graph)=>{if(Array.isArray(node))return node.map(child=>visit(child,graph));if(!isValidElement2(node))return node;const component=node.type;if(componentHasSvgMetadata(component)){return visit(component(node.props),graph)}const props=node.props;const title=textProperty(props,"data-vizmatic-svg-title");const isGraphRoot=title.length>0;let activeGraph=graph;let elementKey=node.key;if(isGraphRoot){const explicitId=textProperty(props,"data-vizmatic-svg-id");if(explicitId){if(explicitIds.has(explicitId)){throw new Error(`GraphDiagram SVG id "${explicitId}" must be unique in one exported SVG.`)}explicitIds.add(explicitId)}const index=graphs.length;const token=explicitId?`id-${svgToken(explicitId)}`:`index-${index}`;activeGraph={index,token,detectionKey:`vizmatic-graph-${index}`,title,description:textProperty(props,"data-vizmatic-svg-description"),nodes:[],edges:[]};graphs.push(activeGraph);elementKey=activeGraph.detectionKey}let nextProps;if(activeGraph&&Object.hasOwn(props,"data-vizmatic-graph-node-id")){const id=textProperty(props,"data-vizmatic-graph-node-id");const label=textProperty(props,"data-vizmatic-graph-node-label")||id;const detail=textProperty(props,"data-vizmatic-graph-node-detail");activeGraph.nodes.push({id,label,detail,title:textProperty(props,"data-vizmatic-graph-node-title")||label,href:textProperty(props,"data-vizmatic-graph-node-href")||void 0});elementKey=`${activeGraph.detectionKey}-node-${svgToken(id)}`}else if(activeGraph&&textProperty(props,"data-vizmatic-graph-edge-id")){const id=encodedTextProperty(props,"data-vizmatic-graph-edge-id");activeGraph.edges.push({id,from:encodedTextProperty(props,"data-vizmatic-graph-edge-from"),to:encodedTextProperty(props,"data-vizmatic-graph-edge-to"),label:encodedTextProperty(props,"data-vizmatic-graph-edge-label"),title:encodedTextProperty(props,"data-vizmatic-graph-edge-title"),path:textProperty(props,"d"),href:encodedTextProperty(props,"data-vizmatic-graph-edge-href")||void 0});elementKey=`${activeGraph.detectionKey}-edge-${svgToken(id)}`}const children=props.children;if(children===void 0){if(isGraphRoot){nextProps={...props,"data-vizmatic-svg-instance":activeGraph?.token};return cloneElement(node,{...nextProps,key:elementKey})}return node}const preparedChildren=visit(children,activeGraph);nextProps=isGraphRoot?{...props,"data-vizmatic-svg-instance":activeGraph?.token}:{...props};return cloneElement(node,{...nextProps,key:elementKey},preparedChildren)};return{element:visit(element),graphs}}function escapeXml(value){return value.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}function attribute(name,value){return`${name}="${escapeXml(value)}"`}function graphBaseId(graph){return`vizmatic-graph-${graph.token}`}function nodeId(graph,node){return`${graphBaseId(graph)}-node-${svgToken(node.id)}`}function edgeId(graph,edge){return`${graphBaseId(graph)}-edge-${svgToken(edge.id)}`}function labelForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return edge.title||(edge.label?`${from} to ${to}: ${edge.label}`:`${from} to ${to}`)}function descriptionForEdge(graph,edge){const nodes=new Map(graph.nodes.map(node=>[node.id,node.label]));const from=nodes.get(edge.from)??edge.from;const to=nodes.get(edge.to)??edge.to;return`Relationship from ${from} to ${to}${edge.label?`, labeled ${edge.label}`:""}.`}function nodeGroup(graph,node,layout){const id=nodeId(graph,node);const label=node.detail?`${node.label}: ${node.detail}`:node.label;const description=node.detail||node.label;const titleId=`${id}-title`;const descriptionId=`${id}-description`;const accessible=`<g ${attribute("id",id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(node.title||node.label)}</title><desc id="${descriptionId}">${escapeXml(description)}</desc>`;if(!layout)return`${accessible}</g>`;const rect=`<rect x="${layout.left}" y="${layout.top}" width="${layout.width}" height="${layout.height}" fill="transparent" pointer-events="all"/>`;const hitTarget=node.href?`<a ${attribute("href",node.href)} role="link" tabindex="0" ${attribute("aria-label",label)}>${rect}</a>`:rect;return`${accessible}${hitTarget}</g>`}function edgeGroup(graph,edge,root){const id=edgeId(graph,edge);const title=labelForEdge(graph,edge);const titleId=`${id}-title`;const descriptionId=`${id}-description`;const accessible=`<g ${attribute("id",id)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(title)}</title><desc id="${descriptionId}">${escapeXml(descriptionForEdge(graph,edge))}</desc>`;if(!root||!edge.path)return`${accessible}</g>`;const path=`<path d="${escapeXml(edge.path)}" transform="translate(${root.left} ${root.top})" fill="none" stroke="transparent" stroke-width="14" stroke-linecap="round" pointer-events="stroke"/>`;const hitTarget=edge.href?`<a ${attribute("href",edge.href)} role="link" tabindex="0" ${attribute("aria-label",title)}>${path}</a>`:path;return`${accessible}${hitTarget}</g>`}function addSvgAccessibility(svg,graphs,layoutNodes){const chartIds=new Set;const charts=layoutNodes.filter(node=>textProperty(node.props,"data-vizmatic-chart-title")).map((node,index)=>{const id=textProperty(node.props,"data-vizmatic-chart-id");if(id&&chartIds.has(id))throw new Error(`Chart SVG id "${id}" must be unique in one exported SVG.`);if(id)chartIds.add(id);return{token:id?`id-${svgToken(id)}`:`index-${index}`,title:textProperty(node.props,"data-vizmatic-chart-title"),description:textProperty(node.props,"data-vizmatic-chart-description")}});if(graphs.length===0&&charts.length===0)return svg;const items=[...graphs,...charts];const title=items.map(item=>item.title).join(". ");const description=items.map(item=>`${item.title}. ${item.description}`).join(" ");const hasLinks=graphs.some(graph=>graph.nodes.some(node=>node.href)||graph.edges.some(edge=>edge.href));const rootTitleId="vizmatic-svg-title";const rootDescriptionId="vizmatic-svg-description";const groupMarkup=graphs.map(graph=>{const baseId=graphBaseId(graph);const titleId=`${baseId}-title`;const descriptionId=`${baseId}-description`;const root=layoutNodes.find(node=>node.key===graph.detectionKey);const nodes=graph.nodes.map(item=>{const layout=layoutNodes.find(node=>node.key===`${graph.detectionKey}-node-${svgToken(item.id)}`);if(item.href&&!layout){throw new Error(`Could not resolve GraphDiagram node "${item.id}" bounds for SVG link export.`)}return nodeGroup(graph,item,layout)}).join("");const edges=graph.edges.map(item=>{if(item.href&&!root){throw new Error(`Could not resolve GraphDiagram bounds for SVG edge link export: "${item.id}".`)}return edgeGroup(graph,item,root)}).join("");return`<g ${attribute("id",baseId)} role="group" aria-labelledby="${titleId}" aria-describedby="${descriptionId}"><title id="${titleId}">${escapeXml(graph.title)}</title><desc id="${descriptionId}">${escapeXml(graph.description)}</desc>${nodes}${edges}</g>`}).join("");const chartMarkup=charts.map(chart=>{const id=`vizmatic-chart-${chart.token}`;return`<g ${attribute("id",id)} role="group" aria-labelledby="${id}-title" aria-describedby="${id}-description"><title id="${id}-title">${escapeXml(chart.title)}</title><desc id="${id}-description">${escapeXml(chart.description)}</desc></g>`}).join("");const metadata=`<title id="${rootTitleId}">${escapeXml(title)}</title><desc id="${rootDescriptionId}">${escapeXml(description)}</desc>`;return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>`<svg${attrs} role="${hasLinks?"group":"img"}" aria-labelledby="${rootTitleId}" aria-describedby="${rootDescriptionId}">${metadata}`).replace(/<\/svg>\s*$/,`${groupMarkup}${chartMarkup}</svg>`)}var FONT_CACHE_DIR=process.env.VIZMATIC_FONT_DIR??join(process.env.XDG_CACHE_HOME??join(homedir(),".cache"),"vizmatic","fonts");var NETWORK_FALLBACK_DISABLED=process.env.VIZMATIC_DISABLE_NETWORK==="1"||process.env.VIZMATIC_OFFLINE==="1";function moduleDirectory(){if(typeof __dirname!=="undefined")return __dirname;return dirname(fileURLToPath(import.meta.url))}function unique(values){return[...new Set(values.filter(value=>Boolean(value)))]}function resolveAssetDir(){const moduleDir=moduleDirectory();const candidates=unique([process.env.VIZMATIC_ASSET_DIR,join(moduleDir,"..","assets"),join(moduleDir,"assets"),join(process.cwd(),"assets")]);return candidates.find(candidate=>existsSync(candidate))}var ASSET_DIR=resolveAssetDir();var VENDORED_FONT_DIR=ASSET_DIR?join(ASSET_DIR,"fonts"):void 0;var VENDORED_EMOJI_DIR=ASSET_DIR?join(ASSET_DIR,"emoji"):void 0;var VENDORED_EMOJI_BUNDLE=ASSET_DIR?join(ASSET_DIR,"emoji.json.br"):void 0;var FONT_URLS={interRegular:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuLyfMZg.ttf",interSemiBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuGKYMZg.ttf",interBold:"https://fonts.gstatic.com/s/inter/v20/UcCO3FwrK3iLTeHuS_nVMrMxCp50SjIw2boKoduKmMEVuFuYMZg.ttf",jetbrainsMono:"https://fonts.gstatic.com/s/jetbrainsmono/v24/tDbY2o-flEEny0FZhsfKu5WU4zr3E_BX0PnT8RD8yKxjPQ.ttf",notoSans:"https://fonts.gstatic.com/s/notosans/v42/o-0mIpQlx3QUlC5A4PNB6Ryti20_6n1iPHjcz6L1SoM-jCpoiyD9A99d.ttf",notoSansMath:"https://fonts.gstatic.com/s/notosansmath/v18/7Aump_cpkSecTWaHRlH2hyV5UHkG.ttf",instrumentSerifRegular:"https://raw.githubusercontent.com/google/fonts/main/ofl/instrumentserif/InstrumentSerif-Regular.ttf",instrumentSerifItalic:"https://raw.githubusercontent.com/google/fonts/main/ofl/instrumentserif/InstrumentSerif-Italic.ttf"};function fontReadPaths(filename){return unique([process.env.VIZMATIC_FONT_DIR?join(process.env.VIZMATIC_FONT_DIR,filename):void 0,VENDORED_FONT_DIR?join(VENDORED_FONT_DIR,filename):void 0,join(FONT_CACHE_DIR,filename)])}async function ensureFont(filename,url){for(const localPath of fontReadPaths(filename)){if(existsSync(localPath))return readFile(localPath)}if(NETWORK_FALLBACK_DISABLED){throw new Error(`Font ${filename} was not found in local Vizmatic assets and network fallback is disabled`)}console.log(` \u2193 Downloading font: ${filename}`);const response=await fetch(url);if(!response.ok){throw new Error(`Failed to download font ${filename}: ${response.statusText}`)}const buffer=Buffer.from(await response.arrayBuffer());await mkdir(FONT_CACHE_DIR,{recursive:true});await writeFile(join(FONT_CACHE_DIR,filename),buffer);return buffer}function toArrayBuffer(buffer){return buffer.buffer.slice(buffer.byteOffset,buffer.byteOffset+buffer.byteLength)}async function loadFonts(){await mkdir(FONT_CACHE_DIR,{recursive:true});const fonts=[];try{const[regular,semiBold,bold]=await Promise.all([ensureFont("Inter-Regular.ttf",FONT_URLS.interRegular),ensureFont("Inter-SemiBold.ttf",FONT_URLS.interSemiBold),ensureFont("Inter-Bold.ttf",FONT_URLS.interBold)]);fonts.push({name:"Inter",data:toArrayBuffer(regular),weight:400,style:"normal"},{name:"Inter",data:toArrayBuffer(semiBold),weight:600,style:"normal"},{name:"Inter",data:toArrayBuffer(bold),weight:700,style:"normal"})}catch(e){console.warn("Warning: Could not load Inter font:",e)}try{const jetbrains=await ensureFont("JetBrainsMono-Regular.ttf",FONT_URLS.jetbrainsMono);fonts.push({name:"JetBrains Mono",data:toArrayBuffer(jetbrains),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load JetBrains Mono font:",e)}try{const[serif,serifItalic]=await Promise.all([ensureFont("InstrumentSerif-Regular.ttf",FONT_URLS.instrumentSerifRegular),ensureFont("InstrumentSerif-Italic.ttf",FONT_URLS.instrumentSerifItalic)]);fonts.push({name:"Instrument Serif",data:toArrayBuffer(serif),weight:400,style:"normal"},{name:"Instrument Serif",data:toArrayBuffer(serifItalic),weight:400,style:"italic"})}catch(e){console.warn("Warning: Could not load Instrument Serif font:",e)}try{const notoSans=await ensureFont("NotoSans-Regular.ttf",FONT_URLS.notoSans);fonts.push({name:"Noto Sans",data:toArrayBuffer(notoSans),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans font:",e)}try{const notoMath=await ensureFont("NotoSansMath-Regular.ttf",FONT_URLS.notoSansMath);fonts.push({name:"Noto Sans Math",data:toArrayBuffer(notoMath),weight:400,style:"normal"})}catch(e){console.warn("Warning: Could not load Noto Sans Math font:",e)}return fonts}var EMOJI_CACHE_DIR=join(FONT_CACHE_DIR,"emoji");function emojiCodepoints(segment){return[...segment].map(c=>c.codePointAt(0).toString(16))}function emojiFilenames(segment){const codepoints=emojiCodepoints(segment);const full=codepoints.join("-");const withoutVariationSelectors=codepoints.filter(cp=>cp!=="fe0f").join("-");return unique([full,withoutVariationSelectors]).map(codepoints2=>`${codepoints2}.svg`)}async function svgFileToDataUri(path){const svgData=await readFile(path,"utf8");return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}var bundledEmoji;async function loadBundledEmoji(filename){if(!VENDORED_EMOJI_BUNDLE||!existsSync(VENDORED_EMOJI_BUNDLE))return void 0;bundledEmoji??=JSON.parse(brotliDecompressSync(await readFile(VENDORED_EMOJI_BUNDLE)).toString("utf8"));const svg=bundledEmoji[filename];return svg?`data:image/svg+xml;base64,${Buffer.from(svg).toString("base64")}`:void 0}async function loadEmoji(segment){const filenames=emojiFilenames(segment);for(const filename2 of filenames){const paths=unique([VENDORED_EMOJI_DIR?join(VENDORED_EMOJI_DIR,filename2):void 0,join(EMOJI_CACHE_DIR,filename2)]);for(const localPath of paths){if(existsSync(localPath))return svgFileToDataUri(localPath)}const bundled=await loadBundledEmoji(filename2);if(bundled)return bundled}if(NETWORK_FALLBACK_DISABLED){console.warn(`Warning: Emoji asset not found locally: ${filenames.join(" or ")}`);return""}const filename=filenames[0];if(!filename)return"";const url=`https://cdn.jsdelivr.net/npm/@twemoji/svg@15.0.0/${filename}`;try{console.log(` \u2193 Downloading emoji: ${filename}`);const response=await fetch(url);if(!response.ok){console.warn(`Warning: Could not download emoji ${filename}: ${response.statusText}`);return""}const svgData=await response.text();await mkdir(EMOJI_CACHE_DIR,{recursive:true});await writeFile(join(EMOJI_CACHE_DIR,filename),svgData);return`data:image/svg+xml;base64,${Buffer.from(svgData).toString("base64")}`}catch(e){console.warn(`Warning: Could not fetch emoji ${filename}:`,e);return""}}async function loadAdditionalAsset(code,segment){if(code==="emoji"){return loadEmoji(segment)}return[]}var cachedFonts=null;async function getFonts(){if(!cachedFonts){cachedFonts=await loadFonts()}return cachedFonts}function sanitizeSvg(svg){return svg.replace(/width="0"/g,'width="1"').replace(/height="0"/g,'height="1"')}var AUTOCROP_PADDING=24;var CROP_THRESHOLD_PERCENT=10;function replaceSvgAttribute(attrs,name,value){const pattern=new RegExp(`\\s${name}="[^"]*"`);if(pattern.test(attrs))return attrs.replace(pattern,` ${name}="${value}"`);return`${attrs} ${name}="${value}"`}function cropSvgViewport(svg,region){const x=Math.max(0,Math.floor(region.x));const y=Math.max(0,Math.floor(region.y));const width=Math.max(1,Math.ceil(region.width));const height=Math.max(1,Math.ceil(region.height));return svg.replace(/^<svg\b([^>]*)>/,(_match,attrs)=>{let nextAttrs=attrs;nextAttrs=replaceSvgAttribute(nextAttrs,"width",String(width));nextAttrs=replaceSvgAttribute(nextAttrs,"height",String(height));nextAttrs=replaceSvgAttribute(nextAttrs,"viewBox",`${x} ${y} ${width} ${height}`);return`<svg${nextAttrs}>`})}function cropLayoutNodes(nodes,region){return nodes.flatMap(node=>{const left=Math.max(node.left,region.x);const top=Math.max(node.top,region.y);const right=Math.min(node.left+node.width,region.x+region.width);const bottom=Math.min(node.top+node.height,region.y+region.height);if(right<=left||bottom<=top)return[];return[{...node,left:left-region.x,top:top-region.y,width:right-left,height:bottom-top}]})}var CanvasOverflowError=class extends Error{width;height;overflow;animation;constructor(width,height,overflow,animation){const position=animation?[animation.sceneIndex!=null?`scene ${animation.sceneIndex+1}`:void 0,animation.frameIndex!=null?`frame ${animation.frameIndex+1}${animation.frameCount?`/${animation.frameCount}`:""}`:void 0,animation.time!=null?`${Math.round(animation.time)}ms`:void 0,animation.label?JSON.stringify(animation.label):void 0].filter(Boolean).join(", "):"";super(`Canvas overflow detected (${width}\xD7${height})${position?` at ${position}`:""}: ${overflow.message}`);this.name="CanvasOverflowError";this.width=width;this.height=height;this.overflow=overflow;this.animation=animation}};function resolveWatermark(options){return options.watermark??options.brand}function shouldCropHeight(crop){return crop!==false}function shouldCropViewport(crop){return crop!==false&&crop!=="height"}async function renderToPng(element,options,createFn,theme){await renderToPngWithOutput(element,options,createFn,theme)}async function renderToPngWithOutput(element,options,createFn,theme){return withRenderContext({background:options.background??"transparent",...options.density!==void 0?{density:options.density}:{}},()=>renderToPngInContext(element,options,createFn,theme))}async function renderToPngInContext(element,options,createFn,theme){const fonts=await getFonts();const renderTheme=options.theme??theme??"dark";const detectionNodes=[];let svg=await satori(element,{width:options.width,height:options.height,fonts,loadAdditionalAsset,onNodeDetected:node=>detectionNodes.push(node)});svg=sanitizeSvg(svg);const detectResvg=new Resvg(svg,{fitTo:{mode:"width",value:options.width},background:"rgba(0, 0, 0, 0)"});const detectResult=detectResvg.render();const detectPixels=detectResult.pixels;const pixelData=new Uint8Array(detectPixels.buffer);const detectedBg=detectBackgroundColor(pixelData);const bounds=detectContentBounds(pixelData,options.width,detectResult.height,detectedBg,AUTOCROP_PADDING);const overflow=detectOverflow(pixelData,options.width,detectResult.height,detectedBg);if(overflow.overflows){throw new CanvasOverflowError(options.width,options.height,overflow)}const layoutOverflow=detectLayoutOverflow(detectionNodes,options.width,options.height);if(layoutOverflow.overflows){throw new CanvasOverflowError(options.width,options.height,layoutOverflow)}let finalWidth=options.width;let finalHeight=options.height;let finalElement=element;const croppedHeight=bounds.y+bounds.height;const heightSaved=options.height-croppedHeight;const heightSavedPercent=heightSaved/options.height*100;if(shouldCropHeight(options.crop)&&heightSavedPercent>=CROP_THRESHOLD_PERCENT){finalHeight=croppedHeight;if(createFn&&theme){finalElement=createFn(theme)}}const watermark=resolveWatermark(options);const renderFinalSvg=async(targetElement,targetWidth,targetHeight)=>{const layoutNodes=[];const outputElement=watermark?wrapWithWatermark(targetElement,targetWidth,targetHeight,renderTheme,watermark):targetElement;const renderedSvg=await satori(outputElement,{width:targetWidth,height:targetHeight,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected?node=>layoutNodes.push(node):void 0});return{svg:sanitizeSvg(renderedSvg),layoutNodes}};let finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);let finalSvg=finalRender.svg;if(finalHeight<options.height){const cropCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const cropPixels2=new Uint8Array(cropCheck.pixels.buffer);const cropBg=detectBackgroundColor(cropPixels2);const cropOverflow=detectOverflow(cropPixels2,finalWidth,cropCheck.height,cropBg);if(cropOverflow.overflows){finalHeight=options.height;finalElement=element;finalRender=await renderFinalSvg(finalElement,finalWidth,finalHeight);finalSvg=finalRender.svg}}if(shouldCropViewport(options.crop)){const viewportCheck=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth},background:"rgba(0, 0, 0, 0)"}).render();const viewportPixels=new Uint8Array(viewportCheck.pixels.buffer);const viewportBg=detectBackgroundColor(viewportPixels);const viewportBounds=detectContentBounds(viewportPixels,finalWidth,viewportCheck.height,viewportBg,AUTOCROP_PADDING);if(viewportBounds.width<finalWidth||viewportBounds.height<viewportCheck.height){finalSvg=cropSvgViewport(finalSvg,viewportBounds);finalRender.layoutNodes=cropLayoutNodes(finalRender.layoutNodes,viewportBounds);finalWidth=viewportBounds.width;finalHeight=viewportBounds.height}}if(options.onNodeDetected){finalRender.layoutNodes.forEach(options.onNodeDetected)}const resvg=new Resvg(finalSvg,{fitTo:{mode:"width",value:finalWidth*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();const outputPixels=new Uint8Array(pngData.pixels.buffer);const outputBackground=detectBackgroundColor(outputPixels);const physicalContentBounds=detectContentBounds(outputPixels,pngData.width,pngData.height,outputBackground,0);const outputScale=pngData.width/finalWidth;const contentBounds={x:physicalContentBounds.x/outputScale,y:physicalContentBounds.y/outputScale,width:physicalContentBounds.width/outputScale,height:physicalContentBounds.height/outputScale};const pngBuffer=pngData.asPng();await mkdir(dirname(options.outputPath),{recursive:true});await writeFile(options.outputPath,pngBuffer);return{width:finalWidth,height:finalHeight,pixelWidth:pngData.width,pixelHeight:pngData.height,contentBounds}}async function renderToBuffer(element,width,height,options={}){return withRenderContext({background:options.background??"transparent",...options.density!==void 0?{density:options.density}:{}},()=>renderToBufferInContext(element,width,height,options))}async function renderToBufferInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;let svg=await satori(outputElement,{width,height,fonts,loadAdditionalAsset,onNodeDetected:options.onNodeDetected});svg=sanitizeSvg(svg);const resvg=new Resvg(svg,{fitTo:{mode:"width",value:width*(options.scale??2)},background:"rgba(0, 0, 0, 0)"});const pngData=resvg.render();return Buffer.from(pngData.asPng())}async function renderToSvg(element,width,height,options={}){return withRenderContext({background:options.background??"transparent",...options.density!==void 0?{density:options.density}:{}},()=>renderToSvgInContext(element,width,height,options))}async function renderToSvgInContext(element,width,height,options){const fonts=await getFonts();const watermark=resolveWatermark(options);const outputElement=watermark?wrapWithWatermark(element,width,height,options.theme??"dark",watermark):element;const prepared=prepareAccessibleSvg(outputElement);const layoutNodes=[];const svg=await satori(prepared.element,{width,height,fonts,loadAdditionalAsset,onNodeDetected:node=>{layoutNodes.push(node);options.onNodeDetected?.(node)}});return addSvgAccessibility(sanitizeSvg(svg),prepared.graphs,layoutNodes)}import{spawn}from"child_process";import{randomUUID}from"crypto";import{chmod,mkdir as mkdir2,open,rename,rm,stat,writeFile as writeFile2}from"fs/promises";import{basename,dirname as dirname2,join as join2,resolve}from"path";import{Resvg as Resvg2}from"@resvg/resvg-js";import parseCssColor2 from"parse-css-color";import parseCssColor from"parse-css-color";var darkColors={bg:"#0b0c10",bgCard:"#13151a",bgCardAlt:"#191c22",bgHover:"#21252c",bgSubtle:"#0f1014",primary:"#2f8fc4",primaryLight:"#5cc4f0",primaryDark:"#1f6f9e",secondary:"#2f8fc4",secondaryLight:"#5cc4f0",secondaryDark:"#1f6f9e",positive:"#4f9e4a",positiveLight:"#8fe08a",positiveDark:"#3a7a36",warning:"#b98a2e",warningLight:"#f2b84b",warningDark:"#8a6620",critical:"#c94a4a",criticalLight:"#ff6b6b",criticalDark:"#9c3535",info:"#2fa394",infoLight:"#4fd8c4",infoDark:"#237d72",accent:"#c7618f",accentLight:"#ff8fc0",violet:"#7f6bd0",violetLight:"#b49cff",violetDark:"#5f4cab",neutral:"#363a43",neutralLight:"#4a4f5a",neutralDark:"#22252c",textPrimary:"#f2efe6",textSecondary:"#a5a7ad",textMuted:"#95989f",textOnColor:"#ffffff",border:"#2c3038",borderSubtle:"#1f2228",borderLight:"#3d424c",shadow:"rgba(0, 0, 0, 0)"};var lightColors={bg:"#f7f3ea",bgCard:"#fbf8f1",bgCardAlt:"#efe9db",bgHover:"#e7e0cf",bgSubtle:"#f2ede1",primary:"#1f6fb2",primaryLight:"#1f6fb2",primaryDark:"#165689",secondary:"#1f6fb2",secondaryLight:"#1f6fb2",secondaryDark:"#165689",positive:"#3f8a35",positiveLight:"#357a2c",positiveDark:"#2c6524",warning:"#a8740a",warningLight:"#8a5f07",warningDark:"#7a5406",critical:"#c62f2f",criticalLight:"#b92a2a",criticalDark:"#962222",info:"#0b7d70",infoLight:"#0b7468",infoDark:"#095e55",accent:"#c2387e",accentLight:"#b03271",violet:"#6a4bc4",violetLight:"#6246b6",violetDark:"#4f3896",neutral:"#cdc5b3",neutralLight:"#a29c8d",neutralDark:"#e2dbca",textPrimary:"#1d1b16",textSecondary:"#5e5a50",textMuted:"#696459",textOnColor:"#ffffff",border:"#d9d2c1",borderSubtle:"#e6dfd0",borderLight:"#c4bba6",shadow:"rgba(0, 0, 0, 0)"};var defaultStyleTokens={preset:"default",fontSans:"Inter",fontMono:"JetBrains Mono",fontSerif:"Instrument Serif"};var engineeringColors={...lightColors,bg:"#f4f4f5",bgCard:"#ffffff",bgCardAlt:"#ececee",bgHover:"#e4e4e7",bgSubtle:"#eeeeef",primary:"#632ca6",primaryLight:"#6d28d9",primaryDark:"#4c1d95",violet:"#632ca6",violetLight:"#6d28d9",violetDark:"#4c1d95",secondary:"#124fc7",secondaryLight:"#1556d1",secondaryDark:"#123d96",positive:"#087a55",positiveLight:"#0a8060",positiveDark:"#05543c",warning:"#c96c00",warningLight:"#d97800",warningDark:"#9a4f00",critical:"#b83232",criticalLight:"#c43d3d",criticalDark:"#8f2626",info:"#0b7185",infoLight:"#0d7d92",infoDark:"#075565",accent:"#a83c76",accentLight:"#b74583",neutral:"#52525b",neutralLight:"#71717a",neutralDark:"#3f3f46",textPrimary:"#101012",textSecondary:"#3f3f46",textMuted:"#68686f",textOnColor:"#ffffff",border:"#3f3f46",borderSubtle:"#d4d4d8",borderLight:"#a1a1aa",shadow:"rgba(0, 0, 0, 0)"};function getThemeColors(mode,preset="default",options={}){const colors2=preset==="engineering"?{...engineeringColors,preset,fontSans:"Inter",fontMono:"JetBrains Mono",fontSerif:"Instrument Serif"}:{...mode==="light"?lightColors:darkColors,...defaultStyleTokens};return options.density!==void 0?withDensity(colors2,options.density):colors2}var colors={...darkColors,...defaultStyleTokens};var flat=color=>`linear-gradient(135deg, ${color}, ${color})`;var gradients={purple:flat("#5f4cab"),blue:flat("#1f6f9e"),green:flat("#2f7a3a"),warm:flat("#8a6620"),cyan:flat("#1d7a6e"),pink:flat("#a04672"),sunset:flat("#9c5526"),ocean:flat("#1d5f86"),dark:flat("#22252c")};var toneGradients={blue:gradients.blue,purple:gradients.purple,green:gradients.green,warm:gradients.warm,cyan:gradients.cyan,pink:gradients.pink,red:gradients.warm,critical:gradients.warm,neutral:gradients.dark,sunset:gradients.sunset,ocean:gradients.ocean,dark:gradients.dark};function getToneGradient(tone){return toneGradients[tone]}function getToneColor(tone,c){return{blue:c.secondaryLight,purple:c.violetLight,green:c.positiveLight,warm:c.warningLight,cyan:c.infoLight,pink:c.accentLight,red:c.criticalLight,critical:c.criticalLight,neutral:c.textSecondary,sunset:c.warningLight,ocean:c.infoLight,dark:c.textSecondary}[tone]}function getReadableToneColor(tone,c,background=c.bgCard,backdrop=c.bgCard){const semanticColor={blue:"secondary",purple:"violet",green:"positive",warm:"warning",cyan:"info",pink:"accent",red:"critical",critical:"critical",neutral:"neutral",sunset:"warning",ocean:"info",dark:"neutral"};const color=getReadableColor(semanticColor[tone],c);return colorContrast(color,background,backdrop)>=4.5?color:getReadableTextColor(background,c,backdrop)}function getToneFill(tone,c){if(c.preset!=="engineering")return withColorAlpha(getToneColor(tone,c),22/255);return{blue:"#cddcfa",purple:"#dfcff8",green:"#d5ede4",warm:"#fde7ce",cyan:"#d7edf1",pink:"#f3d9e7",red:"#f4d7d7",critical:"#f4d7d7",neutral:"#e4e4e7",sunset:"#fde1d6",ocean:"#d8e2f6",dark:"#dedee2"}[tone]}var typography={title:{fontSize:28,fontWeight:700,fontFamily:"Inter"},subtitle:{fontSize:20,fontWeight:600,fontFamily:"Inter"},label:{fontSize:16,fontWeight:600,fontFamily:"Inter"},body:{fontSize:14,fontWeight:400,fontFamily:"Inter"},small:{fontSize:12,fontWeight:500,fontFamily:"Inter"},tiny:{fontSize:11,fontWeight:500,fontFamily:"Inter"},code:{fontSize:13,fontWeight:400,fontFamily:"JetBrains Mono"},annotation:{fontSize:12,fontWeight:500,fontFamily:"Inter",fontStyle:"italic"}};function hasShadow(c){const parsed=parseCssColor(c.shadow);return!!parsed&&parsed.alpha>0}function typeOf(c,variant){const base=typography[variant];return{...base,fontSize:densityOf(c).f(base.fontSize),fontWeight:Math.min(base.fontWeight,600)}}var canvas={standard:{width:800,height:500},wide:{width:1e3,height:400},square:{width:600,height:600},tall:{width:600,height:800}};function getStyles(c){return{canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:c.bg,fontFamily:c.fontSans,padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:c.bgCard,borderRadius:8,border:`1px solid ${c.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}}}var styles={canvas:{width:"100%",height:"100%",display:"flex",flexDirection:"column",backgroundColor:colors.bg,fontFamily:"Inter",padding:40},card:{display:"flex",flexDirection:"column",backgroundColor:colors.bgCard,borderRadius:8,border:`1px solid ${colors.borderSubtle}`,padding:20},pill:{display:"flex",alignItems:"center",justifyContent:"center",borderRadius:999,padding:"6px 16px",fontSize:13,fontWeight:600,fontFamily:"Inter"}};function getColor(name,c){if(c)return c[name];return colors[name]}function getReadableColor(name,c){const variants={primary:[c.primaryLight,c.primary,c.primaryDark],secondary:[c.secondaryLight,c.secondary,c.secondaryDark],positive:[c.positiveLight,c.positive,c.positiveDark],warning:[c.warningLight,c.warning,c.warningDark],critical:[c.criticalLight,c.critical,c.criticalDark],info:[c.infoLight,c.info,c.infoDark],accent:[c.accentLight,c.accent,"#be185d"],violet:[c.violetLight,c.violet,c.violetDark],neutral:[c.textSecondary,c.neutralLight,c.neutral,c.neutralDark]};return variants[name].reduce((best,candidate)=>colorContrast(candidate,c.bgCard)>colorContrast(best,c.bgCard)?candidate:best)}function parseColor(color){const parsed=parseCssColor(color);if(!parsed||parsed.values.length<3)return void 0;if(parsed.type!=="hsl"){return{channels:[parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0],alpha:parsed.alpha}}const hue=((parsed.values[0]??0)%360+360)%360;const saturation=(parsed.values[1]??0)/100;const lightness=(parsed.values[2]??0)/100;const chroma=(1-Math.abs(2*lightness-1))*saturation;const segment=hue/60;const intermediate=chroma*(1-Math.abs(segment%2-1));let channels;if(segment<1)channels=[chroma,intermediate,0];else if(segment<2)channels=[intermediate,chroma,0];else if(segment<3)channels=[0,chroma,intermediate];else if(segment<4)channels=[0,intermediate,chroma];else if(segment<5)channels=[intermediate,0,chroma];else channels=[chroma,0,intermediate];const offset=lightness-chroma/2;return{channels:channels.map(channel=>Math.round((channel+offset)*255)),alpha:parsed.alpha}}function withColorAlpha(color,opacity){if(typeof color!=="string"||!Number.isFinite(opacity))return"transparent";const parsed=parseColor(color);if(!parsed)return"transparent";const alpha=Math.min(1,Math.max(0,parsed.alpha*Math.min(1,Math.max(0,opacity))));const hex=color.trim();if(/^#[\da-f]{6}$/i.test(hex)){return`${hex}${Math.round(alpha*255).toString(16).padStart(2,"0")}`}return`rgba(${parsed.channels.join(", ")}, ${Number(alpha.toFixed(6))})`}function colorLuminance(color,backdrop){const parsed=parseColor(color);if(!parsed)return void 0;let channels=parsed.channels;if(parsed.alpha<1){const backdropColor=backdrop?parseColor(backdrop):void 0;if(!backdropColor)return void 0;channels=channels.map((channel,index)=>Math.round(channel*parsed.alpha+backdropColor.channels[index]*(1-parsed.alpha)))}const[r,g,b]=channels.map(channel=>{const normalized=channel/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4});return .2126*r+.7152*g+.0722*b}function compositeColor(foreground,background){const front=parseColor(foreground),back=parseColor(background);if(!front||!back)throw new Error("Color compositing requires valid CSS colors");const alpha=front.alpha+back.alpha*(1-front.alpha);if(alpha===0)return"transparent";const channels=front.channels.map((value,index)=>Math.round((value*front.alpha+back.channels[index]*back.alpha*(1-front.alpha))/alpha));return alpha===1?`rgb(${channels.join(", ")})`:`rgba(${channels.join(", ")}, ${Number(alpha.toFixed(6))})`}function colorContrast(left,right,rightBackdrop){const leftLuminance=colorLuminance(left);const rightLuminance=colorLuminance(right,rightBackdrop);if(leftLuminance==null||rightLuminance==null)return 0;return(Math.max(leftLuminance,rightLuminance)+.05)/(Math.min(leftLuminance,rightLuminance)+.05)}function getReadableTextColor(background,c,backdrop=c.bgCard){if(colorLuminance(background,backdrop)==null)return c.textPrimary;const candidates=[c.textPrimary,c.textOnColor,c.bg,"#000000"];const readable=candidates.find(candidate=>colorContrast(candidate,background,backdrop)>=4.5);if(readable)return readable;return candidates.reduce((best,candidate)=>colorContrast(candidate,background,backdrop)>colorContrast(best,background,backdrop)?candidate:best)}function getGradient(name){const map={primary:gradients.blue,violet:gradients.purple,secondary:gradients.blue,positive:gradients.green,warning:gradients.warm,critical:gradients.warm,info:gradients.cyan,accent:gradients.pink,neutral:gradients.dark};return map[name]}function heatColor(value){const v=Math.max(0,Math.min(1,value));if(v<.5)return lerpColor("#1b2430","#1f6f9e",v/.5);if(v<.8)return lerpColor("#1f6f9e","#c89a3c",(v-.5)/.3);return lerpColor("#c89a3c","#d9573f",(v-.8)/.2)}function lerpColor(a,b,t){const ah=parseInt(a.slice(1),16);const bh=parseInt(b.slice(1),16);const ar=ah>>16&255,ag=ah>>8&255,ab=ah&255;const br=bh>>16&255,bg=bh>>8&255,bb=bh&255;const rr=Math.round(ar+(br-ar)*t);const rg=Math.round(ag+(bg-ag)*t);const rb=Math.round(ab+(bb-ab)*t);return`#${(rr<<16|rg<<8|rb).toString(16).padStart(6,"0")}`}var MIN_FPS=1;var MAX_FPS=50;var DEFAULT_FPS=20;function assertDuration(duration,context){if(!Number.isFinite(duration)||duration<=0){throw new Error(`${context} duration must be a positive finite number`)}}function assertFps(fps){if(!Number.isFinite(fps)||!Number.isInteger(fps)||fps<MIN_FPS||fps>MAX_FPS){throw new Error(`Animation fps must be an integer from ${MIN_FPS} to ${MAX_FPS}`)}}function clampProgress(progress){return Math.max(0,Math.min(1,progress))}function easingValue(easing="linear",progress){const amount=clampProgress(progress);let result;if(typeof easing==="function"){result=easing(amount)}else if(easing==="ease-in"){result=amount*amount*amount}else if(easing==="ease-out"){result=1-(1-amount)**3}else if(easing==="ease-in-out"){result=amount<.5?4*amount*amount*amount:1-(-2*amount+2)**3/2}else if(easing==="linear"){result=amount}else{throw new Error(`Unknown animation easing: ${String(easing)}`)}if(!Number.isFinite(result))throw new Error("Animation easing must return a finite number");return clampProgress(result)}function hold(duration,label){return{type:"hold",duration,label}}function keyframe(value,label){return{type:"keyframe",value,label}}function tween(to,options){return{type:"tween",to,...options}}function parallel(tracks,label){return{type:"parallel",tracks,label}}function propertyStepDuration(step){return step.type==="keyframe"?0:step.duration}function parallelDuration(step){return Math.max(0,...Object.values(step.tracks).map(track=>track?.reduce((total,item)=>total+propertyStepDuration(item),0)??0))}function timelineStepDuration(step){if(step.type==="keyframe")return 0;if(step.type==="parallel")return parallelDuration(step);return step.duration}function validatePropertySteps(steps,context){for(const step of steps){if(step.type!=="keyframe")assertDuration(step.duration,context);if(step.type==="tween")easingValue(step.easing,.5)}}function validateTimeline(timeline){if(timeline.length===0)throw new Error("Animation timeline requires at least one step");let duration=0;timeline.forEach((step,index)=>{if(step.type==="parallel"){const tracks=Object.entries(step.tracks);if(tracks.length===0)throw new Error(`Animation parallel step ${index} requires at least one track`);tracks.forEach(([name,track])=>{if(!track)return;validatePropertySteps(track,`Animation parallel track ${JSON.stringify(name)}`)});assertDuration(parallelDuration(step),`Animation parallel step ${index}`)}else if(step.type!=="keyframe"){assertDuration(step.duration,`Animation step ${index}`);if(step.type==="tween")easingValue(step.easing,.5)}duration+=timelineStepDuration(step)});if(duration<=0)throw new Error("Animation timeline requires at least one timed step");return duration}function defineAnimation(definition){const fps=definition.fps??DEFAULT_FPS;assertFps(fps);const duration=validateTimeline(definition.timeline);validateAnimationValues(definition.initial,definition.timeline);return{...definition,kind:"vizmatic.animation",duration,fps}}function interpolateValue(from,to,progress,interpolate){if(interpolate)return interpolate(from,to,progress);if(typeof from==="number"&&typeof to==="number"&&Number.isFinite(from)&&Number.isFinite(to)){return from+(to-from)*progress}throw new Error("Animation tweens require finite numeric values or a custom interpolate function")}function validatePropertyInterpolation(initial,steps){let value=initial;for(const step of steps){if(step.type==="keyframe")value=step.value;if(step.type==="tween"){interpolateValue(value,step.to,.5,step.interpolate);value=step.to}}return value}function validateAnimationValues(initial,timeline){let state={...initial};for(const step of timeline){if(step.type==="keyframe"){state={...state,...step.value}}else if(step.type==="tween"){interpolateState(state,step,.5);state={...state,...step.to}}else if(step.type==="parallel"){const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)result[key]=validatePropertyInterpolation(state[key],track)}state=result}}}function interpolateState(from,step,progress){if(step.interpolate){const fromPatch=Object.fromEntries(Object.keys(step.to).map(key=>[key,from[key]]));return{...from,...step.interpolate(fromPatch,step.to,progress)}}const patch={};for(const key of Object.keys(step.to)){const target=step.to[key];if(target===void 0)continue;patch[key]=interpolateValue(from[key],target,progress)}return{...from,...patch}}function finalState(state,step){if(step.type==="keyframe")return{...state,...step.value};if(step.type==="tween")return{...state,...step.to};if(step.type!=="parallel")return state;const result={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(!track)continue;let value=state[key];for(const item of track){if(item.type==="keyframe"||item.type==="tween")value=item.type==="keyframe"?item.value:item.to}result[key]=value}return result}function evaluatePropertyTrack(initial,steps,time){let value=initial;let cursor=0;for(const step of steps){if(step.type==="keyframe"){value=step.value;continue}const end=cursor+step.duration;if(time<end){if(step.type==="hold")return value;const progress=easingValue(step.easing,(time-cursor)/step.duration);return interpolateValue(value,step.to,progress,step.interpolate)}if(step.type==="tween")value=step.to;cursor=end}return value}function evaluateAnimation(animation,requestedTime){const time=Math.max(0,Math.min(animation.duration,requestedTime));let state={...animation.initial};let cursor=0;for(let index=0;index<animation.timeline.length;index+=1){const step=animation.timeline[index];if(step.type==="keyframe"){state={...state,...step.value};continue}const duration=timelineStepDuration(step);const end=cursor+duration;if(time<end){const rawProgress=(time-cursor)/duration;if(step.type==="hold"){return{state,step:index,stepProgress:rawProgress,label:step.label}}if(step.type==="tween"){const progress=easingValue(step.easing,rawProgress);return{state:interpolateState(state,step,progress),step:index,stepProgress:rawProgress,label:step.label}}const parallelState={...state};for(const key of Object.keys(step.tracks)){const track=step.tracks[key];if(track)parallelState[key]=evaluatePropertyTrack(state[key],track,time-cursor)}return{state:parallelState,step:index,stepProgress:rawProgress,label:step.label}}state=finalState(state,step);cursor=end}const lastIndex=animation.timeline.length-1;return{state,step:lastIndex,stepProgress:1,label:animation.timeline[lastIndex]?.label}}function sampleAnimation(animation,time){if(!Number.isFinite(time))throw new Error("Animation sample time must be finite");return evaluateAnimation(animation,time).state}function sampleAnimationFrame(animation,requestedTime,timing){if(!Number.isFinite(requestedTime))throw new Error("Animation sample time must be finite");const time=Math.max(0,Math.min(animation.duration,requestedTime));const evaluated=evaluateAnimation(animation,time);return{state:evaluated.state,frame:{...timing,time,duration:animation.duration,progress:time/animation.duration,step:evaluated.step,stepProgress:evaluated.stepProgress,label:evaluated.label}}}function animationCadence(duration,fps){const interval=1e3/fps;const times=[0];for(let time=interval;time<duration;time+=interval)times.push(time);if(times.at(-1)!==duration)times.push(duration);const boundaries=times.map(time=>Math.round(time/10)*10);const delays=times.map((_,index)=>index===times.length-1?20:Math.max(20,boundaries[index+1]-boundaries[index]));const targetDuration=Math.max(Math.round(duration/10)*10,delays.length*20);let excess=delays.reduce((total,delay)=>total+delay,0)-targetDuration;for(let index=delays.length-2;index>=0&&excess>0;index-=1){const reduction=Math.min(excess,delays[index]-20);delays[index]-=reduction;excess-=reduction}return{times,delays}}function analyzeAnimationCadence(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);return{fps,duration:animation.duration,frameCount:cadence.times.length,encodedDuration:cadence.delays.reduce((total,delay)=>total+delay,0),targetInterval:1e3/fps,minDelay:Math.min(...cadence.delays),maxDelay:Math.max(...cadence.delays)}}function sampleAnimationFrames(animation,options={}){const fps=options.fps??animation.fps;assertFps(fps);const cadence=animationCadence(animation.duration,fps);const count=cadence.times.length;return cadence.times.map((time,index)=>sampleAnimationFrame(animation,time,{index,count,delay:cadence.delays[index],fps}))}function chapterMetadata(title,chapters,duration){const escape=value=>value.replace(/[\\=;#]/g,c=>`\\${c}`).replace(/\r?\n/g," ");const marks=chapters.filter(chapter=>Number.isFinite(chapter.time)&&chapter.time<duration).map(chapter=>({title:chapter.title,time:Math.max(0,chapter.time)})).sort((a,b)=>a.time-b.time);if(marks.length>0)marks[0].time=0;let out=";FFMETADATA1\n";if(title)out+=`title=${escape(title)}
|
|
2
|
+
`;marks.forEach((mark,index)=>{const end=index+1<marks.length?marks[index+1].time:duration;out+=`[CHAPTER]
|
|
3
|
+
TIMEBASE=1/1000
|
|
4
|
+
START=${Math.round(mark.time*1e3)}
|
|
5
|
+
END=${Math.round(end*1e3)}
|
|
6
|
+
title=${escape(mark.title)}
|
|
7
|
+
`});return out}function captionsToSrt(captions,duration){const stamp=seconds=>{const ms=Math.round(seconds*1e3);const pad=(value,size=2)=>String(value).padStart(size,"0");return`${pad(Math.floor(ms/36e5))}:${pad(Math.floor(ms/6e4)%60)}:${pad(Math.floor(ms/1e3)%60)},${pad(ms%1e3,3)}`};return captions.filter(cue=>cue.t1>0&&cue.t0<duration&&cue.t1>cue.t0&&cue.text.trim().length>0).sort((a,b)=>a.t0-b.t0).map((cue,index)=>`${index+1}
|
|
8
|
+
${stamp(Math.max(0,cue.t0))} --> ${stamp(Math.min(duration,cue.t1))}
|
|
9
|
+
${cue.text.trim()}
|
|
10
|
+
`).join("\n")}var MAX_STDERR_CHARS=8192;var COLOR_FILTER="scale=in_range=pc:out_range=tv:out_color_matrix=bt709:flags=lanczos+accurate_rnd+full_chroma_int,format=yuv420p,setparams=range=tv:color_primaries=bt709:color_trc=bt709:colorspace=bt709";var COLOR_TAGS=["-colorspace","bt709","-color_primaries","bt709","-color_trc","bt709","-color_range","tv"];function validateTiming(duration,fps){if(!Number.isFinite(duration)||duration<=0){throw new Error("duration must be a positive finite number")}if(!Number.isInteger(fps)||fps<1||fps>120){throw new Error("fps must be an integer between 1 and 120")}const count=Math.round(duration*fps/1e3);if(!Number.isSafeInteger(count)||count<1){throw new Error("duration must round to at least one frame and no more than Number.MAX_SAFE_INTEGER frames")}return{count,duration:count*1e3/fps}}function frameInfo(index,schedule,fps){return{index,count:schedule.count,time:index*1e3/fps,duration:schedule.duration,progress:index/schedule.count,fps}}function*videoFrameSchedule(duration,fps=30){const schedule=validateTiming(duration,fps);for(let index=0;index<schedule.count;index++){yield frameInfo(index,schedule,fps)}}async function renderAnimationVideo(animation,options){const scale=options.scale??1;if(!Number.isFinite(options.width)||options.width<=0||!Number.isFinite(options.height)||options.height<=0){throw new Error("Animation width and height must be positive finite numbers")}if(!Number.isFinite(scale)||scale<=0)throw new Error("scale must be a positive finite number");const theme=options.theme??"dark";const background=options.background??"theme";const backgroundColor=background==="theme"?getThemeColors(theme).bg:background;const parsedBackground=parseCssColor2(backgroundColor);if(!parsedBackground||parsedBackground.alpha!==1){throw new Error('MP4 requires an opaque background; use "theme" or an opaque CSS color')}return renderRgbaVideo(async info=>{const sampled=sampleAnimationFrame(animation,info.time,{index:info.index,count:info.count,delay:1e3/info.fps,fps:info.fps});const edges={top:false,right:false,bottom:false,left:false};const svg=await renderToSvg(animation.render(sampled.state,sampled.frame),options.width,options.height,{theme,background,watermark:options.watermark??options.brand,onNodeDetected:node=>{edges.top||=node.top<-.5;edges.right||=node.left+node.width>options.width+.5;edges.bottom||=node.top+node.height>options.height+.5;edges.left||=node.left<-.5}});const names=Object.keys(edges).filter(edge=>edges[edge]);if(names.length){const overflow={overflows:true,edges,message:`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`};throw new CanvasOverflowError(options.width,options.height,overflow,{frameIndex:info.index,frameCount:info.count,time:info.time,label:sampled.frame.label})}const rendered=new Resvg2(svg,{fitTo:{mode:"width",value:options.width*scale},background:backgroundColor}).render();if(rendered.width!==options.width*scale||rendered.height!==options.height*scale){throw new Error("All video frames must match the scaled canvas dimensions")}return rendered.pixels},{...options,width:options.width*scale,height:options.height*scale,duration:animation.duration})}function abortError(){const error=new Error("Video export was aborted.");error.name="AbortError";return error}function withAbort(promise,signal){if(!signal)return promise;if(signal.aborted)return Promise.reject(abortError());return new Promise((resolvePromise,rejectPromise)=>{const cleanup=()=>signal.removeEventListener("abort",onAbort);const onAbort=()=>{cleanup();rejectPromise(abortError())};signal.addEventListener("abort",onAbort,{once:true});promise.then(value=>{cleanup();resolvePromise(value)},error=>{cleanup();rejectPromise(error)})})}function formatSeconds(durationMs){return(durationMs/1e3).toFixed(12).replace(/0+$/,"").replace(/\.$/,"")}function describeExit(code,signal,stderr){const status=signal?`signal ${signal}`:`exit code ${code}`;const detail=stderr.trim();return new Error(`FFmpeg failed (${status})${detail?`: ${detail}`:""}`)}async function stopEncoder(child,exited){if(child.exitCode!==null||child.signalCode!==null)return;child.kill("SIGTERM");let timer;const terminated=await Promise.race([exited.then(()=>true),new Promise(resolvePromise=>{timer=setTimeout(()=>resolvePromise(false),1e3)})]);if(timer)clearTimeout(timer);if(!terminated){child.kill("SIGKILL");await exited}}async function renderRgbaVideo(renderFrame,options){const fps=options.fps??30;const schedule=validateTiming(options.duration,fps);const{width,height}=options;if(!Number.isSafeInteger(width)||width<=0||width%2!==0){throw new Error("width must be a positive even integer")}if(!Number.isSafeInteger(height)||height<=0||height%2!==0){throw new Error("height must be a positive even integer")}const expectedBytes=width*height*4;if(!Number.isSafeInteger(expectedBytes)){throw new Error("frame dimensions are too large")}if(typeof renderFrame!=="function")throw new Error("renderFrame must be a function");if(typeof options.outputPath!=="string"||options.outputPath.length===0){throw new Error("outputPath must be a non-empty path")}const ffmpegPath=options.ffmpegPath??"ffmpeg";const codec=options.codec??"h264";if(codec!=="h264"&&codec!=="vp9")throw new Error("codec must be h264 or vp9");const preset=options.preset??"fast";const crf=options.crf??(codec==="vp9"?30:18);const threads=options.threads??4;if(typeof ffmpegPath!=="string"||ffmpegPath.length===0)throw new Error("ffmpegPath must be a non-empty path");if(typeof preset!=="string"||preset.length===0)throw new Error("preset must be a non-empty string");const maxCrf=codec==="vp9"?63:51;if(!Number.isInteger(crf)||crf<0||crf>maxCrf)throw new Error(`crf must be an integer between 0 and ${maxCrf}`);if(options.tune!==void 0&&(typeof options.tune!=="string"||options.tune.length===0)){throw new Error("tune must be a non-empty string when provided")}if(options.audioOffset!==void 0&&(!Number.isFinite(options.audioOffset)||options.audioOffset<0)){throw new Error("audioOffset must be a non-negative finite number of seconds")}if(!Number.isSafeInteger(threads)||threads<1)throw new Error("threads must be a positive safe integer");if(options.audioPath!==void 0&&(typeof options.audioPath!=="string"||options.audioPath.length===0)){throw new Error("audioPath must be a non-empty path when provided")}if(options.signal?.aborted)throw abortError();const outputPath=resolve(options.outputPath);const outputDirectory=dirname2(outputPath);await mkdir2(outputDirectory,{recursive:true});const extension=codec==="vp9"?"webm":"mp4";const tempPath=join2(outputDirectory,`.${basename(outputPath)}.${randomUUID()}.tmp.${extension}`);const tempFile=await open(tempPath,"wx",384);try{await tempFile.close()}catch(error){await rm(tempPath,{force:true});throw error}const seconds=formatSeconds(schedule.duration);const args=["-hide_banner","-loglevel","error","-nostdin","-y","-f","rawvideo","-pixel_format","rgba","-video_size",`${width}x${height}`,"-framerate",String(fps),"-i","pipe:0"];let inputs=1;let audioInput=-1;if(options.audioPath){if(options.audioOffset)args.push("-ss",String(options.audioOffset));args.push("-i",resolve(options.audioPath));audioInput=inputs++}const sidecars=[];let metadataInput=-1,captionInput=-1;if(codec==="h264"){const chapters=options.chapters??[];if(options.title||chapters.length>0){const path=join2(outputDirectory,`.${basename(outputPath)}.${randomUUID()}.tmp.ffmeta`);await writeFile2(path,chapterMetadata(options.title,chapters,schedule.duration),{mode:384});sidecars.push(path);args.push("-f","ffmetadata","-i",path);metadataInput=inputs++}const srt=captionsToSrt(options.captions??[],schedule.duration);if(srt){const path=join2(outputDirectory,`.${basename(outputPath)}.${randomUUID()}.tmp.srt`);await writeFile2(path,srt,{mode:384});sidecars.push(path);args.push("-f","srt","-i",path);captionInput=inputs++}}args.push("-map","0:v:0");if(options.audioPath)args.push("-map",`${audioInput}:a:0`,"-af",`asetpts=PTS-STARTPTS,apad,atrim=duration=${seconds}`);if(captionInput>=0)args.push("-map",`${captionInput}:0`,"-c:s","mov_text","-metadata:s:s:0","language=eng");if(metadataInput>=0)args.push("-map_metadata",String(metadataInput),"-map_chapters",String(metadataInput));args.push("-frames:v",String(schedule.count),"-t",seconds,"-vf",COLOR_FILTER);if(codec==="vp9"){args.push("-c:v","libvpx-vp9","-crf",String(crf),"-b:v","0","-deadline","good","-cpu-used","2","-row-mt","1","-threads:v",String(threads))}else{args.push("-c:v","libx264","-preset",preset);if(options.tune)args.push("-tune",options.tune);if(options.tune==="animation"||/slow|placebo/.test(preset))args.push("-refs","4");args.push("-crf",String(crf),"-threads:v",String(threads))}args.push("-pix_fmt","yuv420p",...COLOR_TAGS);if(options.audioPath){if(codec==="vp9")args.push("-c:a","libopus","-b:a","160k","-ar","48000","-ac","2");else args.push("-c:a","aac","-b:a","192k","-ar","48000","-ac","2")}if(codec==="h264")args.push("-movflags","+faststart");args.push(tempPath);let stderr="";let inputError;let child;try{child=spawn(ffmpegPath,args,{stdio:["pipe","ignore","pipe"]})}catch(error){await rm(tempPath,{force:true});for(const path of sidecars)await rm(path,{force:true});throw error}child.stderr?.on("data",chunk=>{stderr+=chunk.toString();if(stderr.length>MAX_STDERR_CHARS)stderr=stderr.slice(-MAX_STDERR_CHARS)});child.stdin?.on("error",error=>{inputError=error});let exitResult;const exited=new Promise(resolvePromise=>{child.once("error",error=>{exitResult={code:null,signal:null,error};resolvePromise(exitResult)});child.once("close",(code,signal)=>{exitResult={code,signal};resolvePromise(exitResult)})});function observeEncoder(operation,index,finishAfterSuccess){const lastFrame=index===schedule.count-1;const completed=exit=>{if(!exit.error&&exit.code===0&&lastFrame){return finishAfterSuccess?Promise.resolve(void 0):operation}if(exit.error)return Promise.reject(new Error(`Unable to start FFmpeg: ${exit.error.message}`,{cause:exit.error}));return Promise.reject(describeExit(exit.code,exit.signal,stderr))};if(exitResult)return completed(exitResult);return new Promise((resolvePromise,rejectPromise)=>{const cleanup=()=>{child.removeListener("error",onError);child.removeListener("close",onClose)};const onError=error=>{cleanup();rejectPromise(new Error(`Unable to start FFmpeg: ${error.message}`,{cause:error}))};const onClose=(code,signal)=>{cleanup();void completed({code,signal}).then(resolvePromise,rejectPromise)};child.once("error",onError);child.once("close",onClose);operation.then(value=>{cleanup();resolvePromise(value)},error=>{cleanup();rejectPromise(error)})})}try{const input=child.stdin;if(!input)throw new Error("FFmpeg did not provide a frame input stream");for(let index=0;index<schedule.count;index++){const info=frameInfo(index,schedule,fps);const rendered=await withAbort(observeEncoder(Promise.resolve(renderFrame(info)),index,false),options.signal);if(!(rendered instanceof Uint8Array)||rendered.byteLength!==expectedBytes){throw new Error(`Frame ${index} must contain exactly ${expectedBytes} RGBA bytes`)}if(inputError)throw describeExit(null,null,inputError.message||stderr);const pixels=Buffer.from(rendered.buffer,rendered.byteOffset,rendered.byteLength);const write=new Promise((resolvePromise,rejectPromise)=>{input.write(pixels,error=>error?rejectPromise(error):resolvePromise())});await withAbort(observeEncoder(write,index,true),options.signal);if(options.onProgress){await withAbort(observeEncoder(Promise.resolve(options.onProgress(info)),index,false),options.signal)}}input.end();const exit=await withAbort(exited,options.signal);if(exit.error)throw new Error(`Unable to start FFmpeg: ${exit.error.message}`,{cause:exit.error});if(exit.code!==0)throw describeExit(exit.code,exit.signal,stderr);const outputStat=await stat(tempPath);await chmod(tempPath,420);await rename(tempPath,outputPath);return{width,height,frameCount:schedule.count,duration:schedule.duration,fps,bytes:outputStat.size,outputPath,audioIncluded:options.audioPath!==void 0}}catch(error){await stopEncoder(child,exited);if(inputError&&error instanceof Error&&(error.message==="write EPIPE"||error.code==="EPIPE")){throw describeExit(null,null,stderr||inputError.message)}throw error}finally{await rm(tempPath,{force:true});for(const path of sidecars)await rm(path,{force:true})}}function readJsxTag(source,start){if(source.startsWith("<>",start))return{closing:false,end:start+2,selfClosing:false};if(source.startsWith("</>",start))return{closing:true,end:start+3,selfClosing:false};const head=source.slice(start).match(/^<\s*(\/\s*)?[A-Za-z][\w.:$-]*/);if(!head)return void 0;const closing=Boolean(head[1]);let quote;let braces=0;let escaped=false;for(let index=start+head[0].length;index<source.length;index+=1){const character=source[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{"){braces+=1;continue}if(character==="}"){braces=Math.max(0,braces-1);continue}if(character!==">"||braces>0)continue;const beforeClose=source.slice(start,index).trimEnd();return{closing,end:index+1,selfClosing:!closing&&beforeClose.endsWith("/")}}return void 0}function skipJsxExpression(source,start){let depth=0;let quote;let escaped=false;let blockComment=false;let lineComment=false;for(let index=start;index<source.length;index+=1){const character=source[index];const next=source[index+1];if(lineComment){if(character==="\n")lineComment=false;continue}if(blockComment){if(character==="*"&&next==="/"){blockComment=false;index+=1}continue}if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==="/"&&next==="/"){lineComment=true;index+=1;continue}if(character==="/"&&next==="*"){blockComment=true;index+=1;continue}if(character==='"'||character==="'"||character==="`"){quote=character;continue}if(character==="{")depth+=1;else if(character==="}"&&--depth===0)return index+1}return void 0}function findJsxEnd(source,start){let depth=0;for(let index=start;index<source.length;index+=1){if(source[index]==="{"){const expressionEnd=skipJsxExpression(source,index);if(expressionEnd==null)return void 0;index=expressionEnd-1;continue}if(source[index]!=="<")continue;const tag=readJsxTag(source,index);if(!tag)continue;if(tag.closing)depth-=1;else if(!tag.selfClosing)depth+=1;index=tag.end-1;if(depth===0)return tag.end}return void 0}function hasOnlyTrailingSyntax(source){let index=0;while(index<source.length){const rest=source.slice(index);const whitespace=rest.match(/^[\s;)]*/)?.[0].length??0;index+=whitespace;if(source.startsWith("//",index)){const newline=source.indexOf("\n",index+2);index=newline<0?source.length:newline+1;continue}if(source.startsWith("/*",index)){const end=source.indexOf("*/",index+2);if(end<0)return false;index=end+2;continue}return index>=source.length}return true}function extractRootJsx(source){const body=source.replace(/^(?:\s*\()+\s*/,"");const end=findJsxEnd(body,0);return(end==null?body:body.slice(0,end)).trim()}function findBareRootJsxStart(source,allowNativeTags=false){const candidates=source.matchAll(allowNativeTags?/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Za-z]|>))/g:/(^|\n)([\t ]*)(?:(?:export\s+default\s+)?(?:\(\s*)*)(<(?:[A-Z]|>))/g);for(const candidate of candidates){if(candidate.index==null)continue;const lineStart=candidate.index+(candidate[1]?.length??0);const expressionStart=lineStart+(candidate[2]?.length??0);const jsxStart=candidate.index+candidate[0].lastIndexOf(candidate[3]??"<");const jsxEnd=findJsxEnd(source,jsxStart);if(jsxEnd!=null&&hasOnlyTrailingSyntax(source.slice(jsxEnd)))return expressionStart}return-1}var SCENE_RUNTIME_VERSION="vizmatic-scene/1";var SCENE_LIMITS=Object.freeze({sourceBytes:131072,graphBytes:2097152,nodes:2e3,depth:64,stringLength:65536,canvasEdge:1920,canvasPixels:2073600,duration:120,frames:3600,memoryBytes:64*1024*1024,stackBytes:256*1024,evaluationMs:250});var unsafeKeys=new Set(["__proto__","prototype","constructor"]);function isUnsafeSceneKey(key){return unsafeKeys.has(key)}function normalizeSceneRequest(request){if(!request||typeof request!=="object")throw new Error("A scene request is required.");if(typeof request.source!=="string"||!request.source.trim()||new TextEncoder().encode(request.source).byteLength>SCENE_LIMITS.sourceBytes){throw new Error(`Scene source must contain between 1 and ${SCENE_LIMITS.sourceBytes} UTF-8 bytes.`)}for(const name of["width","height"]){const value=request[name];if(!Number.isInteger(value)||value<2||value>SCENE_LIMITS.canvasEdge||value%2!==0){throw new Error(`Scene ${name} must be an even integer from 2 to ${SCENE_LIMITS.canvasEdge}.`)}}if(request.width*request.height>SCENE_LIMITS.canvasPixels){throw new Error(`Scene canvas supports at most ${SCENE_LIMITS.canvasPixels} pixels.`)}if(!Number.isFinite(request.duration)||request.duration<=0||request.duration>SCENE_LIMITS.duration){throw new Error(`Scene duration must be greater than 0 and at most ${SCENE_LIMITS.duration} seconds.`)}const fps=request.fps??24;if(!Number.isInteger(fps)||fps<1||fps>60)throw new Error("Scene fps must be an integer from 1 to 60.");const frameCount=Math.round(request.duration*fps);if(frameCount<1||frameCount>SCENE_LIMITS.frames){throw new Error(`Scene duration must round to between 1 and ${SCENE_LIMITS.frames} frames.`)}const theme=request.theme??"dark";if(theme!=="dark"&&theme!=="light")throw new Error("Scene theme must be dark or light.");const seed=request.seed??0;if(!Number.isInteger(seed)||seed<0||seed>4294967295)throw new Error("Scene seed must be a uint32 integer.");const cues=Object.create(null);if(request.cues!==void 0&&(!request.cues||typeof request.cues!=="object"||Array.isArray(request.cues))){throw new Error("Scene cues must be an object containing times in seconds.")}const cueEntries=Object.entries(request.cues??{});if(cueEntries.length>128)throw new Error("Scene supports at most 128 cues.");for(const[name,time]of cueEntries.sort(([a],[b])=>a<b?-1:a>b?1:0)){if(!/^[A-Za-z][\w.-]{0,79}$/.test(name)||isUnsafeSceneKey(name)||!Number.isFinite(time)||time<0||time>request.duration){throw new Error(`Invalid scene cue ${JSON.stringify(name)}. Cue times must be within the requested duration.`)}cues[name]=time}return{source:request.source,width:request.width,height:request.height,duration:request.duration,fps,theme,cues,seed,frameCount}}function normalizeSceneTime(time,duration){const value=time??0;if(!Number.isFinite(value)||value<0||value>duration){throw new Error("Scene time must be within its duration, in seconds.")}return value}async function sceneSha256(value){const bytes=typeof value==="string"?new TextEncoder().encode(value):value;const digest=await globalThis.crypto.subtle.digest("SHA-256",Uint8Array.from(bytes));return[...new Uint8Array(digest)].map(byte=>byte.toString(16).padStart(2,"0")).join("")}import React21 from"react";import{readFile as readFile2,mkdir as mkdir3,open as open2,rename as rename2,rm as rm2}from"fs/promises";import{createReadStream}from"fs";import{dirname as dirname3,join as join3,resolve as resolve2}from"path";import{fileURLToPath as fileURLToPath2}from"url";import{createHash,randomUUID as randomUUID2}from"crypto";import{brotliDecompressSync as brotliDecompressSync2}from"zlib";import{Resvg as Resvg3}from"@resvg/resvg-js";var primitives_exports={};__export(primitives_exports,{Arrow:()=>Arrow,ArrowMarkerDef:()=>ArrowMarkerDef,AttentionMatrix:()=>AttentionMatrix,AxisPlot:()=>AxisPlot,Badge:()=>Badge,BadgePill:()=>BadgePill,BarChart:()=>BarChart,Board:()=>Board,Box:()=>Box,CANVAS_ITEM_COMPONENT:()=>CANVAS_ITEM_COMPONENT,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DashedLine:()=>DashedLine,DataTable:()=>DataTable,DataflowDiagram:()=>DataflowDiagram,DeploymentDiagram:()=>DeploymentDiagram,DetailList:()=>DetailList,DiagramLegend:()=>DiagramLegend,DonutChart:()=>DonutChart,DotPoint:()=>DotPoint,ELEMENT_SYMBOLS:()=>ELEMENT_SYMBOLS,EntityRelationshipDiagram:()=>EntityRelationshipDiagram,EquationCard:()=>EquationCard,FactRows:()=>FactRows,Flow:()=>Flow,FlowArrow:()=>FlowArrow,FreeBodyDiagram:()=>FreeBodyDiagram,GeometryDiagram:()=>GeometryDiagram,GradientChip:()=>GradientChip,GraphDiagram:()=>GraphDiagram,Grid:()=>Grid,Heatmap:()=>Heatmap,Icon:()=>Icon,InlineBar:()=>InlineBar,IntervalPlot:()=>IntervalPlot,KeyValueList:()=>KeyValueList,LayeredNetwork:()=>LayeredNetwork,Legend:()=>Legend,LineChart:()=>LineChart,MathText:()=>MathText,Matrix:()=>Matrix,MetricCard:()=>MetricCard,MetricStrip:()=>MetricStrip,MiniBarChart:()=>MiniBarChart,MoleculeDiagram:()=>MoleculeDiagram,NumberLine:()=>NumberLine,Panel:()=>Panel,ParetoBarChart:()=>ParetoBarChart,ParetoChart:()=>ParetoChart,PieChart:()=>PieChart,Pipeline:()=>Pipeline,PixelGrid:()=>PixelGrid,ProgressList:()=>ProgressList,ProgressRow:()=>ProgressRow,QuadrantChart:()=>QuadrantChart,ReactionEnergyDiagram:()=>ReactionEnergyDiagram,ReactionEquation:()=>ReactionEquation,Row:()=>Row,ScatterPlot:()=>ScatterPlot,Scene:()=>Scene,SequenceDiagram:()=>SequenceDiagram,SmallMultiples:()=>SmallMultiples,Sparkline:()=>Sparkline,Stack:()=>Stack,StackedBar:()=>StackedBar,StatusDot:()=>StatusDot,StatusList:()=>StatusList,StatusRow:()=>StatusRow,StepCard:()=>StepCard,SvgFrame:()=>SvgFrame,SvgMathText:()=>SvgMathText,SvgPoint:()=>SvgPoint,TagList:()=>TagList,TextLabel:()=>TextLabel,Tile:()=>Tile,TileGrid:()=>TileGrid,TiledMatrix:()=>TiledMatrix,Timeline:()=>Timeline,TitleBar:()=>TitleBar,ToneStrip:()=>ToneStrip,TransformerTopology:()=>TransformerTopology,TreeDiagram:()=>TreeDiagram,ValuePill:()=>ValuePill,VectorArrow:()=>VectorArrow,VectorSegment:()=>VectorSegment,WaveDiagram:()=>WaveDiagram,WindowFrame:()=>WindowFrame,createPlotArea:()=>createPlotArea,cropRgbImage:()=>cropRgbImage,cropRgbRaster:()=>cropRgbRaster,crossCorrelate2d:()=>crossCorrelate2d,decodeRgbPng:()=>decodeRgbPng,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,encodeRgbPng:()=>encodeRgbPng,estimateTextWidth:()=>estimateTextWidth,flattenRgbImage:()=>flattenRgbImage,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,gaussianBlurRgb:()=>gaussianBlurRgb,gaussianKernel:()=>gaussianKernel,geometryBounds:()=>geometryBounds,getToneColor:()=>getToneColor,getToneGradient:()=>getToneGradient,mapNumberLine:()=>mapNumberLine,multiplyMatrices:()=>multiplyMatrices,reactionBalance:()=>reactionBalance,rgbChannel:()=>rgbChannel,sampleWave:()=>sampleWave,scaledDotProductAttention:()=>scaledDotProductAttention,scopeDensity:()=>scopeDensity,statusColor:()=>statusColor,sumForces:()=>sumForces,transposeMatrix:()=>transposeMatrix,waveValue:()=>waveValue});import React3 from"react";function defineIllustration(build,defaultTheme="dark"){return{create(theme){return build(getThemeColors(theme))},default:build(getThemeColors(defaultTheme))}}function Canvas({children,c,padding,justify="center",background}){const renderBackground=getRenderBackground();const canvasBackground=background??(renderBackground==="theme"?c.bg:renderBackground);return React3.createElement("div",{style:{width:"100%",height:"100%",boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:justify,backgroundColor:canvasBackground,fontFamily:c.fontSans,padding:padding??densityOf(c).space.canvas}},children)}function TitleBar({title,subtitle,c,titleFont="sans",align="left"}){const engineering=c.preset==="engineering";const d=densityOf(c);const serif=titleFont==="serif";return React3.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",gap:d.s(4),width:"100%",marginBottom:d.s(16)}},React3.createElement("div",{style:{fontFamily:serif?c.fontSerif:c.fontSans,fontSize:serif?d.f(34):engineering?d.f(34):d.type.title,fontWeight:serif?400:600,lineHeight:1.12,letterSpacing:serif?0:`${-.012}em`,color:c.textPrimary}},title),subtitle&&React3.createElement("div",{style:{fontFamily:c.fontSans,fontSize:d.type.body,fontWeight:400,lineHeight:1.35,color:c.textSecondary}},subtitle))}function flexAlign(align){return{start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"}[align]}function flexJustify(justify){return{start:"flex-start",center:"center",end:"flex-end","space-between":"space-between","space-around":"space-around"}[justify]}function textFitStyle(align="left"){return{minWidth:0,maxWidth:"100%",whiteSpace:"normal",overflowWrap:"break-word",textAlign:align}}function compactChildren(children){return children.filter(child=>child!==void 0&&child!==null&&child!==false)}function scopeDensity(node,density,theme){if(Array.isArray(node))return node.map(child=>scopeDensity(child,density,theme));if(!React3.isValidElement(node))return node;const props=node.props;const next={};if(props.c?props.c.density===void 0:typeof node.type==="function"&&theme){next.c=withDensity(props.c??theme,density)}if(props.children!==void 0)next.children=scopeDensity(props.children,density,theme);return Object.keys(next).length?React3.cloneElement(node,next):node}function Scene({c:baseTheme,children,title,subtitle,padding,gap,justify="flex-start",align="stretch",contentWidth="100%",background,contentStyle,density,titleFont,titleAlign}){const c=density!==void 0?withDensity(baseTheme,density):baseTheme;const d=densityOf(c);return React3.createElement(Canvas,{c,padding,justify,background},...compactChildren([title&&React3.createElement(TitleBar,{c,title,subtitle,titleFont,align:titleAlign}),React3.createElement("div",{style:{width:contentWidth,display:"flex",flexDirection:"column",alignItems:flexAlign(align),gap:gap??d.s(24),...contentStyle}},density!==void 0?scopeDensity(children,density,baseTheme):children)]))}function flexBox(direction,{children,gap:gapProp,align="center",justify=direction==="row"?"start":"center",wrap=false,width,height,style}){const gap=gapProp??densityOf().s(12);return React3.createElement("div",{style:{display:"flex",flexDirection:direction,alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...wrap?{flexWrap:"wrap"}:{},...width!=null?{width}:{},...height!=null?{height}:{},...style}},children)}function Row(props){return flexBox("row",props)}function Column(props){return flexBox("column",props)}function ToneStrip({tone,width=7,height=7}){return React3.createElement("span",{style:{display:"flex",width,height,borderRadius:Math.min(2,Math.min(width,height)/2),backgroundImage:getToneGradient(tone),flexShrink:0}},"")}var iconShapes={agent:[{tag:"rect",attrs:{x:5,y:7,width:14,height:12,rx:4}},{tag:"path",attrs:{d:"M12 7V4"}},{tag:"circle",attrs:{cx:12,cy:3,r:1}},{tag:"circle",attrs:{cx:9,cy:13,r:1}},{tag:"circle",attrs:{cx:15,cy:13,r:1}},{tag:"path",attrs:{d:"M9 17h6"}}],bucket:[{tag:"path",attrs:{d:"M5 7c0-2 14-2 14 0s-14 2-14 0Z"}},{tag:"path",attrs:{d:"M6 7l1 13h10l1-13"}}],browser:[{tag:"rect",attrs:{x:3,y:4,width:18,height:16,rx:2}},{tag:"path",attrs:{d:"M3 8h18"}},{tag:"circle",attrs:{cx:7,cy:6,r:.75}},{tag:"circle",attrs:{cx:10,cy:6,r:.75}},{tag:"circle",attrs:{cx:13,cy:6,r:.75}}],cache:[{tag:"rect",attrs:{x:5,y:4,width:14,height:16,rx:3}},{tag:"path",attrs:{d:"M8 9h8"}},{tag:"path",attrs:{d:"M8 13h8"}},{tag:"path",attrs:{d:"M8 17h5"}}],chart:[{tag:"path",attrs:{d:"M4 19V5"}},{tag:"path",attrs:{d:"M4 19h16"}},{tag:"polyline",attrs:{points:"7 15 11 11 14 13 19 7"}}],check:[{tag:"polyline",attrs:{points:"20 6 9 17 4 12"}}],cluster:[{tag:"path",attrs:{d:"M12 8v4M10 13l-4 2M14 13l4 2"}},{tag:"circle",attrs:{cx:12,cy:5,r:3}},{tag:"circle",attrs:{cx:6,cy:17,r:3}},{tag:"circle",attrs:{cx:18,cy:17,r:3}}],code:[{tag:"polyline",attrs:{points:"8 9 4 12 8 15"}},{tag:"polyline",attrs:{points:"16 9 20 12 16 15"}},{tag:"path",attrs:{d:"M13 5l-2 14"}}],cloud:[{tag:"path",attrs:{d:"M7 18h11a4 4 0 0 0 .5-7.97A6.5 6.5 0 0 0 6.2 8.5 4.8 4.8 0 0 0 7 18Z"}}],container:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:1}},{tag:"path",attrs:{d:"M8 5v14M16 5v14"}}],database:[{tag:"path",attrs:{d:"M4 7c0-2 16-2 16 0s-16 2-16 0Z"}},{tag:"path",attrs:{d:"M4 7v5c0 2 16 2 16 0V7"}},{tag:"path",attrs:{d:"M4 12v5c0 2 16 2 16 0v-5"}}],file:[{tag:"path",attrs:{d:"M6 3h8l4 4v14H6Z"}},{tag:"path",attrs:{d:"M14 3v5h5"}},{tag:"path",attrs:{d:"M9 13h6"}},{tag:"path",attrs:{d:"M9 17h4"}}],firewall:[{tag:"path",attrs:{d:"M5 4h14v16H5Z"}},{tag:"path",attrs:{d:"M5 9h14M5 14h14"}},{tag:"path",attrs:{d:"M9 4v5M15 4v5M12 9v5M8 14v6M17 14v6"}}],gateway:[{tag:"path",attrs:{d:"M4 20V5h16v15"}},{tag:"path",attrs:{d:"M8 20v-7h8v7"}},{tag:"polyline",attrs:{points:"9 9 12 6 15 9"}},{tag:"path",attrs:{d:"M12 6v7"}}],git:[{tag:"circle",attrs:{cx:6,cy:6,r:2}},{tag:"circle",attrs:{cx:18,cy:18,r:2}},{tag:"circle",attrs:{cx:6,cy:18,r:2}},{tag:"path",attrs:{d:"M8 6h3a5 5 0 0 1 5 5v5"}},{tag:"path",attrs:{d:"M6 8v8"}}],globe:[{tag:"circle",attrs:{cx:12,cy:12,r:9}},{tag:"path",attrs:{d:"M3 12h18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 1 0 18"}},{tag:"path",attrs:{d:"M12 3a14 14 0 0 0 0 18"}}],image:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:3}},{tag:"circle",attrs:{cx:9,cy:10,r:1.5}},{tag:"polyline",attrs:{points:"7 17 11 13 14 16 16 14 20 18"}}],layers:[{tag:"path",attrs:{d:"M12 3 3 8l9 5 9-5Z"}},{tag:"path",attrs:{d:"m3 13 9 5 9-5"}},{tag:"path",attrs:{d:"m3 18 9 5 9-5"}}],lock:[{tag:"rect",attrs:{x:5,y:10,width:14,height:10,rx:2}},{tag:"path",attrs:{d:"M8 10V7a4 4 0 0 1 8 0v3"}}],"load-balancer":[{tag:"rect",attrs:{x:8,y:8,width:8,height:8,rx:2}},{tag:"path",attrs:{d:"M4 12h4M16 7h4M16 12h4M16 17h4"}},{tag:"polyline",attrs:{points:"6 10 4 12 6 14"}}],mobile:[{tag:"rect",attrs:{x:6,y:2,width:12,height:20,rx:2}},{tag:"path",attrs:{d:"M10 5h4"}},{tag:"circle",attrs:{cx:12,cy:18,r:1}}],monitor:[{tag:"rect",attrs:{x:3,y:4,width:18,height:13,rx:2}},{tag:"path",attrs:{d:"M8 21h8M12 17v4"}}],network:[{tag:"path",attrs:{d:"M7 10l3-3M14 7l3 3M17 14l-3 3M10 17l-3-3M7 12h10M12 7v10"}},{tag:"circle",attrs:{cx:5,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:5,r:2}},{tag:"circle",attrs:{cx:19,cy:12,r:2}},{tag:"circle",attrs:{cx:12,cy:19,r:2}}],play:[{tag:"path",attrs:{d:"M8 5v14l11-7Z"}}],queue:[{tag:"rect",attrs:{x:4,y:5,width:16,height:14,rx:2}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:12,cy:12,r:1}},{tag:"circle",attrs:{cx:16,cy:12,r:1}}],server:[{tag:"rect",attrs:{x:4,y:4,width:16,height:16,rx:2}},{tag:"path",attrs:{d:"M4 9h16M4 15h16"}},{tag:"circle",attrs:{cx:8,cy:7,r:1}},{tag:"circle",attrs:{cx:8,cy:12,r:1}},{tag:"circle",attrs:{cx:8,cy:18,r:1}}],spark:[{tag:"path",attrs:{d:"M12 3l1.8 5.2L19 10l-5.2 1.8L12 17l-1.8-5.2L5 10l5.2-1.8Z"}},{tag:"path",attrs:{d:"M5 16l.8 2.2L8 19l-2.2.8L5 22l-.8-2.2L2 19l2.2-.8Z"}}],storage:[{tag:"rect",attrs:{x:4,y:6,width:16,height:12,rx:2}},{tag:"circle",attrs:{cx:12,cy:12,r:3}},{tag:"path",attrs:{d:"M7 18h10"}}],stream:[{tag:"path",attrs:{d:"M4 7h13"}},{tag:"polyline",attrs:{points:"14 4 17 7 14 10"}},{tag:"path",attrs:{d:"M20 17H7"}},{tag:"polyline",attrs:{points:"10 14 7 17 10 20"}}],terminal:[{tag:"polyline",attrs:{points:"5 7 10 12 5 17"}},{tag:"path",attrs:{d:"M12 17h7"}}],tool:[{tag:"path",attrs:{d:"M14 6a5 5 0 0 0 6 6L11 21l-6-6 9-9Z"}},{tag:"path",attrs:{d:"M8 18l-2-2"}}],user:[{tag:"circle",attrs:{cx:12,cy:7,r:3.5}},{tag:"path",attrs:{d:"M5 20a7 7 0 0 1 14 0"}}],warning:[{tag:"path",attrs:{d:"M12 4 22 20H2Z"}},{tag:"path",attrs:{d:"M12 9v5"}},{tag:"path",attrs:{d:"M12 17h.01"}}]};function Icon({c,name,tone="blue",color,size=24,strokeWidth=2,label,muted=false}){const stroke=muted?c.textMuted:color??getToneColor(tone,c);const shapes=iconShapes[name];return React3.createElement("svg",{width:size,height:size,viewBox:"0 0 24 24",fill:"none",stroke,strokeWidth,strokeLinecap:"round",strokeLinejoin:"round",role:label?"img":void 0,"aria-hidden":label?void 0:"true","aria-label":label,style:{flex:`0 0 ${size}px`}},shapes.map((shape,index)=>React3.createElement(shape.tag,{key:`${name}-${index}`,...shape.attrs})))}function Panel({title,c,children,subtitle,tone,footer,width,minWidth,height,minHeight,padding:paddingProp,radius:radiusProp,gap:gapProp,align="stretch",justify="start",shadow=false,background,borderColor,titleFontSize,accentWidth,accentHeight,bodyStyle}){const padding=paddingProp??densityOf(c).s(14);const radius=radiusProp??densityOf(c).r(8);const gap=gapProp??densityOf(c).s(10);const engineering=c.preset==="engineering";return React3.createElement("div",{"data-vizmatic-layout-container":"panel",style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:radius,border:`1px solid ${borderColor??c.borderSubtle}`,backgroundColor:background??c.bgCard,...shadow&&!engineering&&hasShadow(c)?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([React3.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap:densityOf(c).s(subtitle?5:0)}},...compactChildren([React3.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),color:c.textPrimary,...typeOf(c,"small"),fontFamily:c.fontSans,...textFitStyle(),fontSize:titleFontSize??densityOf(c).type.label,fontWeight:600,lineHeight:1.2}},...compactChildren([tone&&ToneStrip({tone,width:accentWidth,height:accentHeight}),title])),subtitle&&React3.createElement("div",{style:{display:"flex",color:c.textSecondary,...typeOf(c,"tiny"),fontFamily:engineering?c.fontMono:typography.tiny.fontFamily,...textFitStyle(),lineHeight:1.35}},subtitle)])),React3.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",flexDirection:"column",gap,...bodyStyle}},children),footer&&React3.createElement("div",{"data-vizmatic-layout-content":"panel",style:{width:"100%",display:"flex",color:c.textMuted,...typeOf(c,"tiny"),...textFitStyle()}},footer)]))}function readScriptValue(text,start){if(text[start]==="{"){const end=text.indexOf("}",start+1);if(end!==-1)return{value:text.slice(start+1,end),next:end+1}}let next=start;while(next<text.length&&/[A-Za-z0-9+\-]/.test(text[next]))next+=1;if(next===start)next+=1;return{value:text.slice(start,next),next}}function parseMathText(text){const parts=[];let buffer="";let index=0;while(index<text.length){const char=text[index];if((char==="_"||char==="^")&&index+1<text.length){if(buffer){parts.push({kind:"text",value:buffer});buffer=""}const script=readScriptValue(text,index+1);parts.push({kind:char==="_"?"sub":"sup",value:script.value});index=script.next;continue}buffer+=char;index+=1}if(buffer)parts.push({kind:"text",value:buffer});return parts}var subscriptChars={"0":"\u2080","1":"\u2081","2":"\u2082","3":"\u2083","4":"\u2084","5":"\u2085","6":"\u2086","7":"\u2087","8":"\u2088","9":"\u2089","+":"\u208A","-":"\u208B","=":"\u208C","(":"\u208D",")":"\u208E",a:"\u2090",e:"\u2091",h:"\u2095",i:"\u1D62",j:"\u2C7C",k:"\u2096",l:"\u2097",m:"\u2098",n:"\u2099",o:"\u2092",p:"\u209A",r:"\u1D63",s:"\u209B",t:"\u209C",u:"\u1D64",v:"\u1D65",x:"\u2093"};var superscriptChars={"0":"\u2070","1":"\xB9","2":"\xB2","3":"\xB3","4":"\u2074","5":"\u2075","6":"\u2076","7":"\u2077","8":"\u2078","9":"\u2079","+":"\u207A","-":"\u207B","=":"\u207C","(":"\u207D",")":"\u207E",A:"\u1D2C",B:"\u1D2E",D:"\u1D30",E:"\u1D31",G:"\u1D33",H:"\u1D34",I:"\u1D35",J:"\u1D36",K:"\u1D37",L:"\u1D38",M:"\u1D39",N:"\u1D3A",O:"\u1D3C",P:"\u1D3E",R:"\u1D3F",T:"\u1D40",U:"\u1D41",V:"\u2C7D",W:"\u1D42",a:"\u1D43",b:"\u1D47",c:"\u1D9C",d:"\u1D48",e:"\u1D49",f:"\u1DA0",g:"\u1D4D",h:"\u02B0",i:"\u2071",j:"\u02B2",k:"\u1D4F",l:"\u02E1",m:"\u1D50",n:"\u207F",o:"\u1D52",p:"\u1D56",r:"\u02B3",s:"\u02E2",t:"\u1D57",u:"\u1D58",v:"\u1D5B",w:"\u02B7",x:"\u02E3",y:"\u02B8",z:"\u1DBB"};var superscriptWords={alpha:"\u1D45",beta:"\u1D5D",gamma:"\u1D5E",theta:"\u1DBF"};function scriptText(value,kind){const words=kind==="sup"?superscriptWords:{};const chars=kind==="sub"?subscriptChars:superscriptChars;if(words[value])return words[value];if((value.startsWith("-")||value.startsWith("+"))&&words[value.slice(1)]){return`${chars[value[0]]}${words[value.slice(1)]}`}return Array.from(value).map(char=>chars[char]??char).join("")}function formatMathText(text){return parseMathText(text).map(part=>part.kind==="text"?part.value:scriptText(part.value,part.kind)).join("")}function MathText({text}){return formatMathText(text)}function TextLabel({text,c,variant="body",color,fontSize,fontWeight,width,align="left",math=false,mono=false}){const base=typeOf(c,variant);return React3.createElement("div",{style:{display:"flex",...width!==void 0?{width}:{},...base,...textFitStyle(align),color:color??c.textSecondary,fontSize:fontSize??base.fontSize,fontWeight:fontWeight??base.fontWeight,fontFamily:mono?"JetBrains Mono":base.fontFamily,justifyContent:align==="right"?"flex-end":align==="center"?"center":"flex-start",lineHeight:1.35}},math?formatMathText(text):text)}function svgMathTextBaselineOffset(dominantBaseline){switch(dominantBaseline.toLowerCase()){case"hanging":case"text-before-edge":case"before-edge":case"top":return"0";case"text-after-edge":case"after-edge":case"bottom":case"alphabetic":case"baseline":case"ideographic":case"auto":return"-100%";default:return"-50%"}}function SvgMathText({text,x,y,fill,fontSize:fontSizeProp,fontFamily="JetBrains Mono",fontWeight=800,textAnchor="middle",dominantBaseline="middle",opacity=1}){const fontSize=fontSizeProp??densityOf().f(13);const anchorOffset=textAnchor==="start"?"0":textAnchor==="end"?"-100%":"-50%";const baselineOffset=svgMathTextBaselineOffset(dominantBaseline);return React3.createElement("div",{"data-vizmatic-svg-math-text":true,style:{position:"absolute",left:x,top:y,display:"flex",color:fill,fontSize,fontFamily,fontWeight,lineHeight:1,whiteSpace:"nowrap",pointerEvents:"none",opacity,transform:`translate(${anchorOffset}, ${baselineOffset})`}},formatMathText(text))}function clamp(value,min,max){return Math.min(max,Math.max(min,value))}import React4 from"react";function Box({label,c,color="primary",width,height,fontSize:fontSizeProp,gradient=false,sublabel,icon,radius:radiusProp,outlined=false}){const fontSize=fontSizeProp??densityOf(c).f(14);const radius=radiusProp??densityOf(c).r(8);const d=densityOf(c);const solidColor=getColor(color,c);const gradientBg=getGradient(color);const solidTextColor=getReadableTextColor(solidColor,c);const style={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",borderRadius:radius,padding:`${densityOf(c).s(12)}px ${densityOf(c).s(20)}px`,gap:densityOf(c).s(4),...width?{width}:{},...height?{height}:{}};if(outlined){style.border=`${d.w(2)}px solid ${solidColor}`;style.backgroundColor="transparent"}else if(gradient){style.backgroundImage=gradientBg}else{style.backgroundColor=solidColor}return React4.createElement("div",{style},icon&&React4.createElement("div",{style:{fontSize:fontSize+4}},icon),React4.createElement("div",{style:{fontSize,fontWeight:700,color:outlined?solidColor:gradient?c.textOnColor:solidTextColor,fontFamily:c.fontSans,textAlign:"center",lineHeight:1.3}},label),sublabel&&React4.createElement("div",{style:{fontSize:fontSize-2,fontWeight:400,color:outlined?c.textMuted:gradient?withColorAlpha(c.textOnColor,179/255):solidTextColor,fontFamily:c.fontMono,textAlign:"center"}},sublabel))}function Arrow({direction="down",label,length=40,c,color}){const arrowColor=color||c.textMuted;const isVertical=direction==="down"||direction==="up";const d=densityOf(c);const headLong=d.f(9),headWide=d.f(8);const arrowHead={down:{width:headWide,height:headLong,points:`0,0 ${headWide},0 ${headWide/2},${headLong}`},up:{width:headWide,height:headLong,points:`0,${headLong} ${headWide},${headLong} ${headWide/2},0`},right:{width:headLong,height:headWide,points:`0,0 ${headLong},${headWide/2} 0,${headWide}`},left:{width:headLong,height:headWide,points:`${headLong},0 0,${headWide/2} ${headLong},${headWide}`}}[direction];const shaft=d.w(1.5);const line=React4.createElement("div",{style:{...isVertical?{width:shaft,flexGrow:1,minHeight:1}:{height:shaft,flexGrow:1,minWidth:1},backgroundColor:arrowColor}});const head=React4.createElement("svg",{width:arrowHead.width,height:arrowHead.height,viewBox:`0 0 ${arrowHead.width} ${arrowHead.height}`,style:{flexShrink:0}},React4.createElement("polygon",{points:arrowHead.points,fill:arrowColor}));return React4.createElement("div",{style:{position:"relative",display:"flex",flexDirection:isVertical?"column":"row",alignItems:"center",justifyContent:"center",gap:densityOf(c).s(0),...isVertical?{height:length}:{width:length}}},...direction==="up"||direction==="left"?[head,line]:[line,head],label&&React4.createElement("div",{style:{fontSize:densityOf(c).f(11),color:c.textMuted,fontFamily:c.fontSans,fontWeight:500,position:"absolute",...isVertical?{left:8}:{bottom:12}}},label))}function FlowArrow({direction="right",label,length=40,c,tone="blue",color}){return Arrow({direction,label,length,c,color:color??getToneColor(tone,c)})}function Connector(props){return FlowArrow(props)}function VectorArrow({key,x1,y1,x2,y2,color,strokeWidth=2,arrowSize=2.2,opacity=1}){const dx=x2-x1;const dy=y2-y1;const len=Math.sqrt(dx*dx+dy*dy);if(len<.001){return React4.createElement("g",null)}const ux=dx/len;const uy=dy/len;const px=-uy;const py=ux;const requestedHeadLen=strokeWidth*arrowSize;const headLen=Math.min(requestedHeadLen,len);const headWidth=headLen<requestedHeadLen?Math.max(headLen*.6,strokeWidth*1.5):headLen*.6;const backX=x2-ux*headLen;const backY=y2-uy*headLen;const points=`${x2},${y2} ${backX+px*headWidth/2},${backY+py*headWidth/2} ${backX-px*headWidth/2},${backY-py*headWidth/2}`;return React4.createElement("g",{key,opacity},len>headLen&&React4.createElement("line",{x1,y1,x2:backX,y2:backY,stroke:color,strokeWidth,strokeLinecap:"round"}),React4.createElement("polygon",{points,fill:color}))}function VectorSegment({key,x1,y1,x2,y2,color,strokeWidth=4,opacity=1,showStartDot=false,showEndDot=true,dotRadius=4.5}){return React4.createElement("g",{key,opacity},React4.createElement("line",{x1,y1,x2,y2,stroke:color,strokeWidth,strokeLinecap:"round"}),showStartDot&&React4.createElement("circle",{cx:x1,cy:y1,r:dotRadius,fill:color}),showEndDot&&React4.createElement("circle",{cx:x2,cy:y2,r:dotRadius,fill:color}))}function SvgFrame({key,x=0,y=0,width,height,c,rx=8,fill,stroke,strokeWidth=1,opacity}){return React4.createElement("rect",{key,x,y,width,height,rx,fill:fill??c.bgSubtle,stroke:stroke??c.borderSubtle,strokeWidth,...opacity!==void 0?{opacity}:{}})}function SvgPoint({key,cx,cy,r=5,fill,stroke,strokeWidth,opacity}){return React4.createElement("circle",{key,cx,cy,r,fill,...stroke?{stroke}:{},...strokeWidth?{strokeWidth}:{},...opacity!==void 0?{opacity}:{}})}function ArrowMarkerDef({id,color,size=5,direction="end"}){const isStart=direction==="start";return React4.createElement("marker",{id,viewBox:"0 0 10 10",refX:isStart?.5:9.5,refY:5,markerWidth:size,markerHeight:size,orient:"auto"},React4.createElement("path",{d:isStart?"M 10 0 L 0 5 L 10 10 z":"M 0 0 L 10 5 L 0 10 z",fill:color}))}import React5 from"react";function Stack({direction="vertical",gap:gapProp,align="center",wrap=false,children}){const gap=gapProp??densityOf().s(12);const alignMap={start:"flex-start",center:"center",end:"flex-end",stretch:"stretch"};return React5.createElement("div",{style:{display:"flex",flexDirection:direction==="vertical"?"column":"row",alignItems:alignMap[align],gap,...wrap?{flexWrap:"wrap"}:{}}},children)}function Card({children,c,title,subtitle,tone,footer,width,minWidth,height,minHeight,padding:paddingProp,radius:radiusProp,gap,align="stretch",justify="start",shadow=false,background,borderColor,bodyStyle}){const padding=paddingProp??densityOf(c).s(20);const radius=radiusProp??densityOf(c).r(8);const hasHeader=title||subtitle||tone;const engineering=c.preset==="engineering";return React5.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:flexAlign(align),justifyContent:flexJustify(justify),gap:gap??(hasHeader||footer?10:0),backgroundColor:background??c.bgCard,borderRadius:engineering?Math.min(radius,5):radius,border:`1px solid ${borderColor??c.borderSubtle}`,padding,...width!==void 0?{width}:{},...minWidth!==void 0?{minWidth}:{},...height!==void 0?{height}:{},...minHeight!==void 0?{minHeight}:{},...shadow&&!engineering&&hasShadow(c)?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([hasHeader&&React5.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:densityOf(c).s(subtitle?5:0)}},...compactChildren([(title||tone)&&React5.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),color:c.textPrimary,...typeOf(c,"small"),fontFamily:c.fontSans,...textFitStyle(),fontWeight:600,lineHeight:1.2}},...compactChildren([tone&&ToneStrip({tone}),title])),subtitle&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,...typeOf(c,"tiny"),fontFamily:c.fontSans,...textFitStyle(),lineHeight:1.35}},subtitle)])),React5.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",...bodyStyle}},children),footer&&React5.createElement("div",{style:{width:"100%",display:"flex",color:c.textMuted,...typeOf(c,"tiny"),fontFamily:c.fontSans,...textFitStyle()}},footer)]))}function renderMaybeMath(node,math){return math&&typeof node==="string"?formatMathText(node):node}function ValuePill({label,value,c,tone,detail,width,math=false}){const d=densityOf(c);return React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:d.s(3),...width!=null?{width}:{},padding:`${d.s(8)}px ${d.s(11)}px`,borderRadius:d.r(8),border:`1px solid ${tone?withColorAlpha(getToneColor(tone,c),.5):c.border}`,backgroundColor:c.bgCard}},React5.createElement("div",{style:{display:"flex",color:c.textMuted,fontFamily:c.fontSans,fontSize:d.type.micro,lineHeight:1.2}},renderMaybeMath(label,math)),React5.createElement("div",{style:{display:"flex",color:tone?getReadableToneColor(tone,c):c.textPrimary,fontFamily:c.fontMono,fontSize:d.f(20),lineHeight:1.05}},renderMaybeMath(value,math)),...compactChildren([detail&&React5.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:c.fontSans,fontSize:d.type.micro,lineHeight:1.3}},renderMaybeMath(detail,math))]))}function EquationCard({title,formula,c,tone,result,detail,width,height,math=false,align="left"}){const accent=tone?getReadableToneColor(tone,c):c.textPrimary;const textAlign=align;return Card({c,tone,width,height,padding:densityOf(c).s(16),radius:10,shadow:true,title,children:React5.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(8),alignItems:align==="center"?"center":"flex-start"}},React5.createElement("div",{style:{color:c.textPrimary,fontFamily:c.fontMono,fontSize:densityOf(c).f(15),fontWeight:600,lineHeight:1.3,textAlign}},renderMaybeMath(formula,math)),result&&React5.createElement("div",{style:{color:accent,fontFamily:c.fontMono,fontSize:densityOf(c).f(28),fontWeight:600,lineHeight:1,textAlign}},renderMaybeMath(result,math)),detail&&React5.createElement("div",{style:{color:c.textSecondary,...typeOf(c,"tiny"),lineHeight:1.35,textAlign}},renderMaybeMath(detail,math)))})}function BadgePill({text,c,tone="neutral",width,minWidth,height,padding:paddingProp,radius:radiusProp,fontSize:fontSizeProp,mono=false,filled=false,math=false}){const padding=paddingProp??`${densityOf(c).s(0)}px ${densityOf(c).s(8)}px`;const radius=radiusProp??densityOf(c).r(6);const fontSize=fontSizeProp??densityOf(c).f(11);const accent=getToneColor(tone,c);const accentText=getReadableToneColor(tone,c);const engineering=c.preset==="engineering";const resolvedHeight=height??densityOf(c).f(20);return React5.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},height:resolvedHeight,padding,borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c)}:filled?{backgroundImage:getToneGradient(tone)}:{backgroundColor:tone==="neutral"?"transparent":withColorAlpha(accent,16/255)},border:`1px solid ${engineering?accent:filled?withColorAlpha(accent,0):tone==="neutral"?c.border:withColorAlpha(accent,85/255)}`,color:engineering?c.textPrimary:filled?c.textOnColor:tone==="neutral"?c.textSecondary:accentText,fontSize,fontWeight:400,lineHeight:1,fontFamily:mono?c.fontMono:c.fontSans,boxSizing:"border-box",whiteSpace:"nowrap"}},renderMaybeMath(text,math))}function GradientChip({title,c,subtitle,tone="blue",gradient,width,minWidth,height,minHeight:minHeightProp,padding:paddingProp,radius:radiusProp,shadow=false,align="left",subtitleMono=false,math=false}){const d=densityOf(c);const minHeight=minHeightProp??d.s(60);const padding=paddingProp??`${d.s(8)}px ${d.s(14)}px`;const radius=radiusProp??d.r(8);const textAlign=align;const explicitFill=gradient!=null;const engineering=c.preset==="engineering"&&!explicitFill;const flat2=!explicitFill;const accent=getToneColor(tone,c);const textColor=flat2?c.textPrimary:c.textOnColor;return React5.createElement("div",{style:{...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},boxSizing:"border-box",borderRadius:engineering?Math.min(radius,5):radius,...engineering?{backgroundColor:getToneFill(tone,c),border:`1px solid ${accent}`}:flat2?{backgroundColor:withColorAlpha(accent,20/255),border:`1px solid ${withColorAlpha(accent,.45)}`}:{backgroundImage:gradient},color:textColor,display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:d.s(4),padding,...shadow&&hasShadow(c)?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},React5.createElement("div",{style:{fontFamily:c.fontSans,fontSize:d.type.label,color:textColor,fontWeight:600,lineHeight:1.15,textAlign}},renderMaybeMath(title,math)),subtitle&&React5.createElement("div",{style:{fontSize:d.type.small,color:flat2?c.textSecondary:"rgba(255,255,255,0.86)",lineHeight:1.25,textAlign,fontFamily:subtitleMono?c.fontMono:c.fontSans}},renderMaybeMath(subtitle,math)))}function StepCard({title,c,subtitle,eyebrow,tone,width,minWidth,minHeight:minHeightProp,padding:paddingProp,radius:radiusProp,shadow=false,align="center",math=false}){const d=densityOf(c);const minHeight=minHeightProp??d.s(66);const padding=paddingProp??`${d.s(10)}px ${d.s(14)}px`;const radius=radiusProp??d.r(8);const accent=getToneColor(tone??"blue",c);const engineering=c.preset==="engineering";const textAlign=align;return Card({c,width:width??d.f(200),minWidth,minHeight,padding,radius:engineering?5:radius,justify:"center",shadow:engineering?false:shadow,background:engineering?getToneFill(tone??"blue",c):void 0,borderColor:engineering?accent:tone?withColorAlpha(accent,.5):c.borderLight,children:React5.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:subtitle?d.s(3):d.s(2)}},eyebrow&&React5.createElement("div",{style:{fontFamily:c.fontSans,fontSize:d.type.micro,color:tone?getReadableToneColor(tone,c):c.textMuted,fontWeight:400,...textFitStyle(textAlign),lineHeight:1.2}},renderMaybeMath(eyebrow,math)),React5.createElement("div",{style:{fontFamily:c.fontSans,fontSize:d.type.label,color:c.textPrimary,fontWeight:600,lineHeight:1.2,...textFitStyle(textAlign)}},renderMaybeMath(title,math)),subtitle&&React5.createElement("div",{style:{fontFamily:engineering?c.fontMono:c.fontSans,fontSize:d.type.small,color:c.textSecondary,lineHeight:1.25,...textFitStyle(textAlign)}},renderMaybeMath(subtitle,math)))})}function MetricCard({label,value,c,tone,detail,width,minWidth,minHeight,padding:paddingProp,radius:radiusProp,shadow=false,align="left",math=false,valueMono=true,valueFontSize,valueColor}){const d=densityOf(c);const padding=paddingProp??`${d.s(9)}px ${d.s(12)}px`;const radius=radiusProp??d.r(8);const accent=getToneColor(tone??"blue",c);const textAlign=align;return Card({c,width,minWidth,minHeight,padding,radius,shadow,justify:"center",borderColor:tone?withColorAlpha(accent,.45):c.border,children:React5.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:align==="center"?"center":"flex-start",gap:d.s(3)}},...compactChildren([React5.createElement("div",{style:{fontSize:d.type.micro,fontWeight:400,color:c.textMuted,fontFamily:c.fontSans,lineHeight:1.2,...textFitStyle(textAlign)}},renderMaybeMath(label,math)),React5.createElement("div",{style:{fontSize:valueFontSize??d.f(22),fontWeight:400,color:valueColor??(tone?getReadableToneColor(tone,c):c.textPrimary),lineHeight:1.1,...textFitStyle(textAlign),fontFamily:valueMono?c.fontMono:c.fontSans}},renderMaybeMath(value,math)),detail&&React5.createElement("div",{style:{fontSize:d.type.micro,fontFamily:c.fontSans,color:c.textSecondary,lineHeight:1.25,...textFitStyle(textAlign)}},renderMaybeMath(detail,math))]))})}import React6 from"react";var INTER_REGULAR=[281,288,466,633,642,982,644,300,365,365,501,662,288,460,288,360,631,407,610,618,646,593,620,566,619,620,288,302,662,662,662,511,966,690,654,730,722,601,590,746,743,269,571,672,565,903,753,765,639,765,644,642,646,744,690,985,682,679,629,365,360,365,471,456,323,562,612,571,612,583,370,613,591,242,242,549,242,876,591,600,612,612,376,528,327,591,562,818,546,562,552,426,333,426,662];var INTER_SEMIBOLD=[252,321,523,644,650,1004,663,326,373,373,540,673,319,465,319,379,660,423,623,636,666,612,640,576,640,640,319,329,673,673,673,543,999,728,659,737,722,605,588,749,746,277,580,703,565,922,759,769,645,773,652,650,660,736,728,1020,720,713,652,373,379,373,481,469,351,574,624,583,624,591,389,625,612,262,262,569,262,900,612,609,624,624,397,549,353,612,587,839,569,588,566,455,359,455,673];function estimateTextWidth(text,fontSize,options={}){if(options.mono)return Array.from(text).length*fontSize*.6;const table=(options.weight??400)>=600?INTER_SEMIBOLD:INTER_REGULAR;let units=0;for(const char of text){const code=char.codePointAt(0)??0;if(code>=32&&code<127)units+=table[code-32];else units+=code>11904?1e3:600}return units/1e3*fontSize}function statusColor(status,c){if(status==="ok")return c.positiveLight;if(status==="warn")return c.warningLight;if(status==="error")return c.criticalLight;if(status==="idle")return c.textMuted;return getToneColor(status,c)}function StatusDot({status="ok",c,size}){const resolved=size??densityOf(c).f(8);return React6.createElement("div",{style:{display:"flex",flexShrink:0,width:resolved,height:resolved,borderRadius:999,backgroundColor:statusColor(status,c)}})}function Sparkline({values,c,width,height,tone,color,area=false,endDot=true,min,max,strokeWidth,...accessibility}){const d=densityOf(c);const w=width??d.f(72);const h=height??d.f(18);const stroke=color??(tone?getToneColor(tone,c):c.textSecondary);const line=strokeWidth??d.w(1.5);const finite4=values.filter(Number.isFinite);const low=min??Math.min(...finite4),high=max??Math.max(...finite4);const range=high-low||1;const inset=endDot?d.g(3):line;const x=index=>inset+(values.length<=1?0:index/(values.length-1)*(w-inset*2));const y=value=>inset+(1-(value-low)/range)*(h-inset*2);const path=values.map((value,index)=>`${index===0?"M":"L"} ${x(index).toFixed(2)} ${y(value).toFixed(2)}`).join(" ");const last=values.length-1;const chart=React6.createElement("svg",{width:w,height:h,viewBox:`0 0 ${w} ${h}`,"aria-hidden":"true",style:{display:"flex",flexShrink:0}},...compactChildren([area&&values.length>1&&React6.createElement("path",{key:"area",d:`${path} L ${x(last).toFixed(2)} ${h} L ${x(0).toFixed(2)} ${h} Z`,fill:withColorAlpha(stroke,.14)}),React6.createElement("path",{key:"line",d:path,fill:"none",stroke,strokeWidth:line,strokeLinecap:"round",strokeLinejoin:"round"}),endDot&&values.length>0&&React6.createElement("circle",{key:"dot",cx:x(last),cy:y(values[last]),r:d.g(2.25),fill:stroke})]));if(!accessibility.ariaLabel&&!accessibility.description)return chart;return React6.createElement("div",{...chartAccessibilityAttributes({...accessibility,ariaLabel:accessibility.ariaLabel??"Sparkline",description:chartDescription(accessibility.description,values.map((value,index)=>`Point ${index+1}: ${value}`))}),style:{display:"flex",width:w,height:h,flexShrink:0}},chart)}function InlineBar({value,c,width="100%",height,tone,color,warnAt}){const d=densityOf(c);const fraction=Math.max(0,Math.min(1,value));const fill=color??(warnAt!=null&&fraction>=warnAt?c.warningLight:tone?getToneColor(tone,c):c.textSecondary);return React6.createElement("div",{style:{display:"flex",width,height:height??Math.max(2,d.g(3)),borderRadius:1,backgroundColor:c.borderSubtle,overflow:"hidden"}},React6.createElement("div",{style:{display:"flex",width:`${Math.round(fraction*1e3)/10}%`,height:"100%",backgroundColor:fill}}))}function FactRows({rows,c,width="100%",fontSize,mono=true,gap}){const d=densityOf(c);const size=fontSize??d.type.micro;return React6.createElement("div",{style:{display:"flex",flexDirection:"column",width,gap:gap??d.s(2)}},...rows.map((row,index)=>React6.createElement("div",{key:`fact-${index}`,style:{display:"flex",flexDirection:"column",width:"100%",gap:1}},React6.createElement("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"baseline",width:"100%",gap:d.s(8),lineHeight:1.25}},React6.createElement("div",{style:{display:"flex",flexShrink:0,color:c.textMuted,fontFamily:c.fontSans,fontSize:size}},row.key),React6.createElement("div",{style:{display:"flex",color:row.tone?getReadableToneColor(row.tone,c):c.textPrimary,fontFamily:mono?c.fontMono:c.fontSans,fontSize:size,textAlign:"right"}},row.value)),...compactChildren([row.bar!=null&&InlineBar({value:row.bar,c,tone:row.tone,warnAt:.85})]))))}function MetricStrip({metrics,c,width="100%",direction="row",sparkWidth}){const d=densityOf(c);return React6.createElement("div",{style:{display:"flex",flexDirection:direction,width,gap:direction==="row"?d.s(14):d.s(6)}},...metrics.map((metric,index)=>React6.createElement("div",{key:`metric-${index}`,style:{display:"flex",flexDirection:"column",flex:direction==="row"?1:void 0,minWidth:0,gap:d.s(1)}},React6.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:d.s(2),lineHeight:1.1}},React6.createElement("div",{style:{display:"flex",color:metric.tone?getReadableToneColor(metric.tone,c):c.textPrimary,fontFamily:c.fontMono,fontSize:d.f(14)}},metric.value),...compactChildren([metric.unit!=null&&React6.createElement("div",{key:"unit",style:{display:"flex",color:c.textMuted,fontFamily:c.fontSans,fontSize:d.type.micro}},metric.unit)])),React6.createElement("div",{style:{display:"flex",color:c.textMuted,fontFamily:c.fontSans,fontSize:d.type.micro,lineHeight:1.2}},metric.label),...compactChildren([metric.spark&&Sparkline({values:metric.spark,c,tone:metric.tone,width:sparkWidth??d.f(56),height:d.f(14)}),metric.bar!=null&&InlineBar({value:metric.bar,c,tone:metric.tone,warnAt:.85})]))))}function TagList({tags,c,tone}){const d=densityOf(c);return React6.createElement("div",{style:{display:"flex",flexWrap:"wrap",gap:d.s(3)}},...tags.map((tag,index)=>React6.createElement("div",{key:`tag-${index}`,style:{display:"flex",padding:`${Math.max(1,d.s(1.5))}px ${d.s(5)}px`,border:`1px solid ${tone?withColorAlpha(getToneColor(tone,c),.5):c.border}`,borderRadius:d.r(4),color:tone?getReadableToneColor(tone,c):c.textSecondary,fontFamily:c.fontSans,fontSize:d.type.micro,lineHeight:1.1,whiteSpace:"nowrap"}},tag)))}function DiagramLegend({items,c,title,width}){const d=densityOf(c);const sample=d.f(18);return React6.createElement("div",{style:{display:"flex",flexWrap:"wrap",alignItems:"center",gap:`${d.s(3)}px ${d.s(12)}px`,...width!=null?{width}:{},color:c.textSecondary,fontFamily:c.fontSans,fontSize:d.type.micro,lineHeight:1.2}},...compactChildren([title!=null&&React6.createElement("div",{key:"title",style:{display:"flex",color:c.textMuted}},title),...items.map((item,index)=>{const color=item.color??(item.tone?getToneColor(item.tone,c):c.textSecondary);const style=item.style??"solid";const mark=style==="swatch"||style==="dot"?React6.createElement("div",{style:{display:"flex",width:d.g(8),height:d.g(8),flexShrink:0,borderRadius:style==="dot"?999:2,backgroundColor:color}}):React6.createElement("svg",{width:sample,height:d.g(8),viewBox:`0 0 ${sample} ${d.g(8)}`,style:{display:"flex",flexShrink:0}},React6.createElement("line",{x1:0,x2:sample,y1:d.g(4),y2:d.g(4),stroke:color,strokeWidth:d.w(2),strokeDasharray:style==="dashed"?"5 3":style==="dotted"?"1.5 3":void 0,strokeLinecap:style==="dotted"?"round":"butt"}));return React6.createElement("div",{key:`legend-${index}`,style:{display:"flex",alignItems:"center",gap:d.s(5)}},mark,React6.createElement("div",{style:{display:"flex"}},item.label))})]))}function SmallMultiples({items,c,columns,cellWidth,cellHeight,sharedScale=false,area=true}){const d=densityOf(c);const width=cellWidth??d.f(118);const height=cellHeight??d.f(30);const perRow=columns??Math.min(items.length,6);const all=items.flatMap(item=>[...item.values,...item.reference!=null?[item.reference]:[]]);const sharedMin=sharedScale?Math.min(...all):void 0;const sharedMax=sharedScale?Math.max(...all):void 0;const rows=[];for(let i=0;i<items.length;i+=perRow)rows.push(items.slice(i,i+perRow));return React6.createElement("div",{style:{display:"flex",flexDirection:"column",gap:d.s(10)}},...rows.map((row,rowIndex)=>React6.createElement("div",{key:`multiples-row-${rowIndex}`,style:{display:"flex",gap:d.s(16)}},...row.map((item,index)=>{const low=sharedMin??Math.min(...item.values,...item.reference!=null?[item.reference]:[]);const high=sharedMax??Math.max(...item.values,...item.reference!=null?[item.reference]:[]);const range=high-low||1;const referenceY=item.reference!=null?d.g(3)+(1-(item.reference-low)/range)*(height-d.g(6)):void 0;return React6.createElement("div",{key:`multiple-${index}`,style:{display:"flex",flexDirection:"column",width,gap:d.s(2)}},React6.createElement("div",{style:{display:"flex",alignItems:"baseline",justifyContent:"space-between",gap:d.s(6),lineHeight:1.2}},React6.createElement("div",{style:{display:"flex",alignItems:"center",gap:d.s(4),minWidth:0,color:c.textSecondary,fontFamily:c.fontSans,fontSize:d.type.micro,whiteSpace:"nowrap",overflow:"hidden"}},...compactChildren([item.status&&React6.createElement(React6.Fragment,{key:"dot"},StatusDot({status:item.status,c,size:d.g(6)})),item.label])),item.value!=null&&React6.createElement("div",{style:{display:"flex",flexShrink:0,alignItems:"baseline",gap:d.s(2),color:item.tone?getReadableToneColor(item.tone,c):c.textPrimary,fontFamily:c.fontMono,fontSize:d.type.small}},...compactChildren([item.value,item.unit!=null&&React6.createElement("span",{key:"unit",style:{display:"flex",color:c.textMuted,fontFamily:c.fontSans,fontSize:d.type.micro}},item.unit)]))),React6.createElement("div",{style:{display:"flex",position:"relative",width,height,borderBottom:`1px solid ${c.borderSubtle}`}},...compactChildren([referenceY!=null&&React6.createElement("svg",{key:"reference",width,height,viewBox:`0 0 ${width} ${height}`,style:{position:"absolute",left:0,top:0}},React6.createElement("line",{x1:0,x2:width,y1:referenceY,y2:referenceY,stroke:c.borderLight,strokeWidth:d.stroke.hair,strokeDasharray:`${d.s(4)} ${d.s(4)}`})),Sparkline({values:item.values,c,tone:item.tone,width,height,area,min:low,max:high})])))}))))}import React7 from"react";function ProgressRow({label,value,valueLabel,tone="blue",muted=false,c,labelWidth=42,valueWidth=38,barHeight:barHeightProp,fontSize:fontSizeProp}){const barHeight=barHeightProp??Math.max(3,densityOf(c).g(6));const fontSize=fontSizeProp??densityOf(c).f(11);const accent=muted?c.textMuted:getToneColor(tone,c);const accentText=muted?c.textMuted:getReadableToneColor(tone,c);const pct=Math.round(Math.max(0,Math.min(1,value))*100);return React7.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),width:"100%"}},React7.createElement("div",{style:{width:labelWidth,color:muted?c.textMuted:c.textPrimary,fontSize,fontWeight:400,lineHeight:1}},label),React7.createElement("div",{style:{display:"flex",flex:1,height:barHeight,borderRadius:1,backgroundColor:c.borderSubtle,overflow:"hidden"}},React7.createElement("div",{style:{width:`${pct}%`,height:"100%",backgroundColor:accent,opacity:muted?.62:1}})),React7.createElement("div",{style:{width:valueWidth,color:accentText,fontSize,fontWeight:400,fontFamily:"JetBrains Mono",lineHeight:1,textAlign:"right"}},valueLabel??`${pct}%`))}function ProgressList({rows,c,gap:gapProp,labelWidth,valueWidth,barHeight,fontSize}){const gap=gapProp??densityOf(c).s(8);return Column({gap,align:"stretch",children:rows.map((row,index)=>React7.createElement(React7.Fragment,{key:`progress-${index}`},ProgressRow({...row,c,labelWidth,valueWidth,barHeight,fontSize})))})}function MiniBarChart({data,c,max,minBarHeight=3,height=92,barWidth:barWidthProp,gap:gapProp,radius:radiusProp,fontSize:fontSizeProp,showValues=false,...accessibility}){const gap=gapProp??densityOf(c).s(10);const radius=radiusProp??densityOf(c).r(3);const fontSize=fontSizeProp??densityOf(c).type.micro;const barWidth=barWidthProp??densityOf(c).f(20);const requestedMax=max!=null&&max>0?max:void 0;const safeMax=requestedMax??Math.max(1,...data.map(item=>Math.max(0,item.value)));const barMaxHeight=Math.max(minBarHeight,height-(showValues?34:20));return React7.createElement("div",{...chartAccessibilityAttributes({...accessibility,ariaLabel:accessibility.ariaLabel??"Mini bar chart",description:chartDescription(accessibility.description,data.map((item,index)=>{const label=typeof item.label==="string"||typeof item.label==="number"?item.label:`Item ${index+1}`;const value=typeof item.valueLabel==="string"||typeof item.valueLabel==="number"?item.valueLabel:item.value;return`${label}: ${value}`}))}),style:{display:"flex",alignItems:"flex-end",justifyContent:"center",gap,height,width:"100%",padding:`${densityOf(c).s(0)}px ${densityOf(c).s(4)}px`,boxSizing:"border-box"}},...data.map((item,index)=>{const tone=item.tone??"blue";const barHeight=Math.max(minBarHeight,Math.round(Math.max(0,item.value)/safeMax*barMaxHeight));const fill=item.color??getToneColor(tone,c);return React7.createElement("div",{key:`mini-bar-${index}-${String(item.label)}`,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-end",gap:densityOf(c).s(5),height:"100%",minWidth:barWidth}},...compactChildren([showValues&&React7.createElement("div",{style:{display:"flex",color:getReadableToneColor(tone,c),fontFamily:"JetBrains Mono",fontSize,fontWeight:600,lineHeight:1}},item.valueLabel??item.value),React7.createElement("div",{style:{display:"flex",width:barWidth,height:barHeight,borderRadius:`${radius}px ${radius}px 0 0`,...fill.startsWith("linear-gradient")?{backgroundImage:fill}:{backgroundColor:fill},opacity:item.opacity??1}}),React7.createElement("div",{style:{display:"flex",color:c.textMuted,fontFamily:"JetBrains Mono",fontSize,fontWeight:700,lineHeight:1,minHeight:fontSize+2}},item.label)]))}))}function DetailList({items,c,tone,gap:gapProp,padding:paddingProp,fontSize:fontSizeProp,mono=false,math=false}){const gap=gapProp??densityOf(c).s(7);const padding=paddingProp??`${densityOf(c).s(7)}px ${densityOf(c).s(8)}px`;const fontSize=fontSizeProp??densityOf(c).f(11);const accent=tone?getToneColor(tone,c):c.borderSubtle;return Column({gap,align:"stretch",children:items.map((item,index)=>React7.createElement("div",{key:`detail-${index}`,style:{display:"flex",padding,...index===0?{}:{borderTop:`1px solid ${tone?withColorAlpha(accent,51/255):c.borderSubtle}`},color:c.textSecondary,fontSize,lineHeight:1.3,fontFamily:mono?"JetBrains Mono":"Inter"}},renderMaybeMath(item,math)))})}function Tile({title,subtitle,eyebrow,icon,tone,lines,children,width,minHeight,c,align="left",padding:paddingProp,radius:radiusProp,shadow=false,math=false}){const padding=paddingProp??`${densityOf(c).s(10)}px ${densityOf(c).s(12)}px`;const radius=radiusProp??densityOf(c).r(8);const accent=getToneColor(tone??"neutral",c);const textAlign=align;const crossAlign=align==="center"?"center":"flex-start";const detailLines=(lines??[]).map((line,index)=>React7.createElement("div",{key:`tile-line-${index}`,style:{display:"flex",alignItems:"center",justifyContent:align==="center"?"center":"flex-start",gap:densityOf(c).s(6),...typeOf(c,"tiny"),color:c.textSecondary,lineHeight:1.3,textAlign}},React7.createElement("span",{style:{display:"flex",width:3,height:3,borderRadius:999,backgroundColor:tone?accent:c.textMuted,flexShrink:0}}),renderMaybeMath(line,math)));return Card({c,width,minHeight,padding,radius,shadow,borderColor:tone?withColorAlpha(accent,.5):c.border,children:React7.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",justifyContent:"center",alignItems:crossAlign,gap:densityOf(c).s(4)}},...compactChildren([icon!=null&&React7.createElement("div",{style:{display:"flex",fontSize:densityOf(c).f(22),lineHeight:1}},icon),eyebrow!=null&&React7.createElement("div",{style:{...typeOf(c,"tiny"),color:tone?getReadableToneColor(tone,c):c.textMuted,fontWeight:400,lineHeight:1.2,textAlign}},renderMaybeMath(eyebrow,math)),React7.createElement("div",{style:{...typeOf(c,"label"),color:c.textPrimary,fontWeight:600,lineHeight:1.15,textAlign}},renderMaybeMath(title,math)),subtitle!=null&&React7.createElement("div",{style:{...typeOf(c,"tiny"),color:c.textSecondary,lineHeight:1.3,textAlign}},renderMaybeMath(subtitle,math)),detailLines.length>0&&React7.createElement("div",{style:{width:"100%",display:"flex",flexDirection:"column",gap:densityOf(c).s(4),marginTop:densityOf(c).s(2)}},...detailLines),children]))})}function TileGrid({tiles,c,columns,gap:gapProp,tileWidth,minHeight,align="left",math=false}){const gap=gapProp??densityOf(c).s(12);const renderTile=(tile,index)=>React7.createElement(React7.Fragment,{key:`tile-${index}`},Tile({...tile,c,align,math,width:tile.width??tileWidth,minHeight:tile.minHeight??minHeight}));if(!columns||columns>=tiles.length){return Row({gap,align:"stretch",justify:"start",wrap:true,children:tiles.map(renderTile)})}const rows=[];for(let i=0;i<tiles.length;i+=columns){rows.push(tiles.slice(i,i+columns))}return Column({gap,align:"stretch",children:rows.map((rowTiles,rowIndex)=>React7.createElement(React7.Fragment,{key:`tile-row-${rowIndex}`},Row({gap,align:"stretch",justify:"start",children:rowTiles.map((tile,colIndex)=>renderTile(tile,rowIndex*columns+colIndex))})))})}function isCodeLineSpec(line){return typeof line==="object"&&line!==null&&!React7.isValidElement(line)&&"text"in line}function CodeBlock({lines,c,title,tone,width,minWidth,fontSize:fontSizeProp,showLineNumbers=false,padding:paddingProp,radius:radiusProp,background,shadow=false,math=false}){const fontSize=fontSizeProp??densityOf(c).f(12);const padding=paddingProp??densityOf(c).s(14);const radius=radiusProp??densityOf(c).r(10);const headerAccent=tone?getToneColor(tone,c):c.textMuted;const numberWidth=String(lines.length).length*(fontSize*.62)+8;const lineElements=lines.map((line,index)=>{const spec=isCodeLineSpec(line)?line:{text:line};const accent=spec.tone?getToneColor(spec.tone,c):void 0;const accentText=spec.tone&&accent?getReadableToneColor(spec.tone,c,withColorAlpha(accent,31/255),background??c.bgSubtle):void 0;const textColor=spec.dim?c.textMuted:accentText??c.textSecondary;return React7.createElement("div",{key:`code-line-${index}`,style:{display:"flex",alignItems:"flex-start",gap:densityOf(c).s(8),width:"100%",padding:accent?"3px 7px":"1px 0",borderRadius:accent?5:0,...accent?{backgroundColor:withColorAlpha(accent,31/255)}:{},boxSizing:"border-box"}},...compactChildren([showLineNumbers&&React7.createElement("div",{style:{display:"flex",width:numberWidth,flexShrink:0,justifyContent:"flex-end",color:accent?c.textSecondary:c.textMuted,fontFamily:"JetBrains Mono",fontSize:fontSize-1,lineHeight:1.5}},String(index+1)),spec.prefix!=null&&React7.createElement("div",{style:{display:"flex",flexShrink:0,color:accentText??c.textMuted,fontFamily:"JetBrains Mono",fontWeight:600,fontSize,lineHeight:1.5}},spec.prefix),React7.createElement("div",{style:{display:"flex",flex:1,color:textColor,fontFamily:"JetBrains Mono",fontWeight:400,fontSize,lineHeight:1.45,whiteSpace:"pre-wrap"}},math&&typeof spec.text==="string"?formatMathText(spec.text):spec.text)]))});return React7.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(8),...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},padding,borderRadius:radius,backgroundColor:background??c.bgSubtle,border:`1px solid ${tone?withColorAlpha(headerAccent,68/255):c.borderSubtle}`,boxSizing:"border-box",...shadow&&hasShadow(c)?{boxShadow:`0 9px 24px ${c.shadow}`}:{}}},...compactChildren([title!=null&&React7.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),paddingBottom:densityOf(c).s(8),borderBottom:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:fontSize-1,fontWeight:400}},React7.createElement("span",{style:{display:"flex",width:8,height:8,borderRadius:999,backgroundColor:headerAccent,flexShrink:0}}),renderMaybeMath(title,math)),React7.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(2),width:"100%"}},...lineElements)]))}function renderComparisonDivider(divider,c,key){const label=divider===true?"vs":divider;return React7.createElement("div",{key,style:{display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",alignSelf:"stretch",flexShrink:0}},React7.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",minWidth:densityOf(c).f(26),height:densityOf(c).f(22),padding:`0 ${densityOf(c).s(6)}px`,borderRadius:999,backgroundColor:c.bgCard,border:`1px solid ${c.borderLight}`,color:c.textMuted,fontFamily:"Inter",fontSize:densityOf(c).type.micro,fontWeight:400}},label))}function Comparison({sides:sides2,c,divider=false,gap:gapProp,sideWidth,minHeight,align="stretch",math=false}){const gap=gapProp??densityOf(c).s(14);const children=sides2.flatMap((side,index)=>{const tone=side.tone;const panel=React7.createElement(React7.Fragment,{key:`comparison-side-${index}`},Panel({c,tone,title:side.title,subtitle:side.subtitle,footer:side.footer,width:side.width??sideWidth,minHeight,bodyStyle:{gap:8},children:side.eyebrow!=null?React7.createElement("div",{style:{display:"flex",flexDirection:"column",gap:8}},React7.createElement("div",{style:{...typeOf(c,"tiny"),color:c.textMuted,fontWeight:400}},renderMaybeMath(side.eyebrow,math)),side.children??DetailList({items:side.lines??[],c,tone,math})):side.children??DetailList({items:side.lines??[],c,tone,math})}));if(divider&&index<sides2.length-1){return[panel,renderComparisonDivider(divider,c,`comparison-divider-${index}`)]}return[panel]});return Row({gap,align,justify:"center",children})}function KeyValueList({rows,c,title,width,minWidth,keyWidth,gap:gapProp,fontSize:fontSizeProp,divider=true,keyMono=false,math=false}){const gap=gapProp??densityOf(c).s(0);const fontSize=fontSizeProp??densityOf(c).type.small;const rowElements=rows.map((row,index)=>{const accent=row.tone?getReadableToneColor(row.tone,c):void 0;const isLast=index===rows.length-1;const valueMono=row.valueMono??true;return React7.createElement("div",{key:`kv-row-${index}`,style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:densityOf(c).s(14),width:"100%",padding:`${divider?densityOf(c).s(5):densityOf(c).s(2)}px 0`,...divider&&!isLast?{borderBottom:`1px solid ${c.borderSubtle}`}:{},boxSizing:"border-box"}},React7.createElement("div",{style:{display:"flex",...keyWidth!=null?{width:keyWidth,flexShrink:0}:{},color:c.textSecondary,fontFamily:keyMono?"JetBrains Mono":"Inter",fontSize,fontWeight:400,lineHeight:1.3}},renderMaybeMath(row.key,math)),React7.createElement("div",{style:{display:"flex",flex:1,justifyContent:"flex-end",textAlign:"right",color:accent??c.textPrimary,fontFamily:valueMono?"JetBrains Mono":"Inter",fontSize,fontWeight:400,lineHeight:1.3}},renderMaybeMath(row.value,math)))});return React7.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{},...minWidth!=null?{minWidth}:{}}},...compactChildren([title!=null&&React7.createElement("div",{style:{display:"flex",...typeOf(c,"small"),color:c.textPrimary,fontWeight:600,paddingBottom:densityOf(c).s(4)}},renderMaybeMath(title,math)),...rowElements]))}function WindowFrame({c,children,title,variant="window",tone="blue",dots=true,width,minWidth,height,minHeight,padding:paddingProp,radius:radiusProp,shadow=false,background,bodyStyle}){const padding=paddingProp??densityOf(c).s(16);const radius=radiusProp??densityOf(c).r(10);const isTerminal=variant==="terminal";const surface=background??(isTerminal?c.bgSubtle:c.bgCard);const titleColor=isTerminal?getReadableToneColor(tone,c,c.bgHover):c.textSecondary;const trafficDot=(color,key)=>React7.createElement("span",{key,style:{display:"flex",width:densityOf(c).g(9),height:densityOf(c).g(9),borderRadius:999,backgroundColor:color}});const titleBar=React7.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(10),width:"100%",padding:`${densityOf(c).s(8)}px ${densityOf(c).s(12)}px`,backgroundColor:isTerminal?c.bg==="transparent"?c.bgHover:c.bgHover:c.bgSubtle,borderBottom:`1px solid ${c.borderSubtle}`,boxSizing:"border-box"}},...compactChildren([dots&&React7.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(6),flexShrink:0}},trafficDot(c.borderLight,"dot-r"),trafficDot(c.borderLight,"dot-y"),trafficDot(c.borderLight,"dot-g")),title!=null&&(variant==="browser"?React7.createElement("div",{style:{display:"flex",flex:1,alignItems:"center",height:densityOf(c).f(22),padding:`0 ${densityOf(c).s(12)}px`,borderRadius:densityOf(c).r(6),backgroundColor:c.bgCard,border:`1px solid ${c.borderSubtle}`,color:c.textSecondary,fontFamily:"JetBrains Mono",fontSize:densityOf(c).f(11),fontWeight:600,lineHeight:1}},title):React7.createElement("div",{style:{display:"flex",flex:1,justifyContent:dots?"center":"flex-start",color:titleColor,fontFamily:isTerminal?"JetBrains Mono":"Inter",fontSize:densityOf(c).type.small,fontWeight:400,lineHeight:1}},title)),dots&&title!=null&&variant!=="browser"&&React7.createElement("div",{style:{display:"flex",width:52,flexShrink:0}},"")]));return React7.createElement("div",{style:{display:"flex",flexDirection:"column",...width!=null?{width}:{},...minWidth!=null?{minWidth}:{},...height!=null?{height}:{},...minHeight!=null?{minHeight}:{},borderRadius:radius,border:`1px solid ${c.borderSubtle}`,backgroundColor:surface,overflow:"hidden",boxSizing:"border-box",...shadow&&hasShadow(c)?{boxShadow:`0 12px 30px ${c.shadow}`}:{}}},titleBar,React7.createElement("div",{style:{display:"flex",flexDirection:"column",width:"100%",padding,boxSizing:"border-box",...isTerminal?{fontFamily:"JetBrains Mono",color:c.textSecondary}:{},...bodyStyle}},children))}import React8 from"react";var statusGlyphs={check:"\u2713",cross:"\u2717",warn:"!",info:"i",pending:"\u2013",dot:""};var statusTones={check:"green",cross:"red",warn:"warm",info:"blue",pending:"neutral",dot:"blue"};function StatusRow({label,detail,status="check",tone,c,boxed=false,fontSize:fontSizeProp,width,math=false}){const fontSize=fontSizeProp??densityOf(c).f(11);const resolvedTone=tone??statusTones[status];const accent=getToneColor(resolvedTone,c);const markerAlpha=38/255;const rowAlpha=boxed?18/255:0;const markerBackgroundAlpha=Math.round((rowAlpha+markerAlpha*(1-rowAlpha))*255);const markerBackground=withColorAlpha(accent,markerBackgroundAlpha/255);const accentText=getReadableToneColor(resolvedTone,c,markerBackground,c.bgCard);const glyph=statusGlyphs[status];const marker=React8.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",width:densityOf(c).f(16),height:densityOf(c).f(16),flexShrink:0,borderRadius:999,backgroundColor:status==="dot"?accent:withColorAlpha(accent,32/255),border:`1px solid ${withColorAlpha(accent,.7)}`,color:accentText,fontFamily:"Inter",fontSize:status==="warn"||status==="info"?12:11,fontWeight:600,lineHeight:1}},glyph);return React8.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(9),width:width??"100%",boxSizing:"border-box",...boxed?{padding:`${densityOf(c).s(7)}px ${densityOf(c).s(10)}px`,borderRadius:densityOf(c).r(8),backgroundColor:withColorAlpha(accent,18/255),border:`1px solid ${withColorAlpha(accent,58/255)}`}:{padding:"3px 0"}}},marker,React8.createElement("div",{style:{display:"flex",flex:1,color:c.textPrimary,fontFamily:"Inter",fontSize,fontWeight:600,lineHeight:1.3}},renderMaybeMath(label,math)),detail!=null&&React8.createElement("div",{style:{display:"flex",flexShrink:0,color:c.textSecondary,fontFamily:"Inter",fontSize:fontSize-1,lineHeight:1.3,textAlign:"right"}},renderMaybeMath(detail,math)))}function StatusList({rows,c,gap:gapProp,boxed=false,fontSize,width,math=false}){const gap=gapProp??densityOf(c).s(7);return Column({gap,align:"stretch",...width!=null?{width}:{},children:rows.map((row,index)=>React8.createElement(React8.Fragment,{key:`status-${index}`},StatusRow({...row,c,boxed,fontSize,math})))})}function renderTimelineCard(event,c,math,width){const resolvedTone=event.tone??statusTones[event.status??"dot"];const accentText=getReadableToneColor(resolvedTone,c);const resolvedWidth=event.width??width;return React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(5),...resolvedWidth!=null?{width:resolvedWidth}:{},...typeof resolvedWidth==="string"?{minWidth:0}:{},padding:`${densityOf(c).s(4)}px 0`,boxSizing:"border-box"}},...compactChildren([event.time!=null&&React8.createElement("div",{style:{display:"flex",color:event.tone||event.status?accentText:c.textMuted,fontFamily:"JetBrains Mono",fontSize:densityOf(c).type.micro,fontWeight:400,lineHeight:1.15}},renderMaybeMath(event.time,math)),React8.createElement("div",{style:{display:"flex",color:c.textPrimary,fontFamily:"Inter",fontSize:densityOf(c).f(14),fontWeight:600,lineHeight:1.18,...textFitStyle()}},renderMaybeMath(event.title,math)),event.detail!=null&&React8.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:densityOf(c).f(11),fontWeight:500,lineHeight:1.35,...textFitStyle()}},renderMaybeMath(event.detail,math))]))}function Timeline({events,c,title,subtitle,direction="vertical",width,eventWidth,gap:gapProp,markerSize:markerSizeProp,math=false}){const markerSize=markerSizeProp??densityOf(c).g(9);const gap=gapProp??densityOf(c).s(12);const header=(title!=null||subtitle!=null)&&React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:"100%"}},...compactChildren([title!=null&&React8.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),color:c.textPrimary,fontFamily:"Inter",fontSize:densityOf(c).f(16),fontWeight:600,lineHeight:1.2}},renderMaybeMath(title,math)),subtitle!=null&&React8.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:densityOf(c).f(11),fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));if(direction==="horizontal"){return React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React8.createElement("div",{style:{display:"flex",alignItems:"stretch",gap:densityOf(c).s(0),width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React8.createElement("div",{key:`timeline-h-${index}`,style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(8),...eventWidth==null?{flex:1}:{},...(event.width??eventWidth)!=null?{width:event.width??eventWidth}:{},minWidth:0}},React8.createElement("div",{style:{display:"flex",alignItems:"center",width:"100%"}},React8.createElement("div",{style:{display:"flex",flex:1,height:1,backgroundColor:c.border,opacity:index===0?0:1}}),React8.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,flexShrink:0}}),React8.createElement("div",{style:{display:"flex",flex:1,height:1,backgroundColor:c.border,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math,eventWidth))}))]))}return React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap,...width!=null?{width}:{}}},...compactChildren([header,React8.createElement("div",{style:{display:"flex",flexDirection:"column",gap,width:"100%"}},...events.map((event,index)=>{const accent=getToneColor(event.tone??statusTones[event.status??"dot"],c);return React8.createElement("div",{key:`timeline-v-${index}`,style:{display:"flex",alignItems:"stretch",gap:densityOf(c).s(11),width:"100%"}},React8.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",width:markerSize+8,flexShrink:0}},React8.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:1,backgroundColor:c.border,opacity:index===0?0:1}}),React8.createElement("div",{style:{display:"flex",width:markerSize,height:markerSize,borderRadius:999,backgroundColor:accent,flexShrink:0}}),React8.createElement("div",{style:{display:"flex",flex:1,minHeight:4,width:1,backgroundColor:c.border,opacity:index===events.length-1?0:1}})),renderTimelineCard(event,c,math))}))]))}function renderFlowStage(stage,c,math){const tone=stage.tone;const hasDetails=Boolean(stage.children||stage.lines?.length);if(!hasDetails){return StepCard({title:stage.title,subtitle:stage.subtitle,eyebrow:stage.eyebrow,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding,math})}return Panel({title:stage.title,subtitle:stage.subtitle,tone,c,width:stage.width,minWidth:stage.minWidth,minHeight:stage.minHeight,padding:stage.padding??12,bodyStyle:{gap:8},children:stage.children??DetailList({items:stage.lines??[],c,tone,math})})}function Flow({stages,c,direction="horizontal",gap:gapProp,connectorLength:connectorLengthProp,connectorTone="neutral",align="center",math=false}){const connectorLength=connectorLengthProp??densityOf(c).s(32);const gap=gapProp??densityOf(c).s(10);const isHorizontal=direction==="horizontal";const children=stages.flatMap((stage,index)=>{const elements=[React8.createElement(React8.Fragment,{key:`stage-${index}`},renderFlowStage(stage,c,math))];if(index<stages.length-1){elements.push(React8.createElement(React8.Fragment,{key:`connector-${index}`},FlowArrow({direction:isHorizontal?"right":"down",length:connectorLength,c,tone:connectorTone})))}return elements});return(isHorizontal?Row:Column)({gap,align,justify:isHorizontal?"start":"center",children})}import React9 from"react";import dagre from"@dagrejs/dagre";var EPSILON=.001;var MAX_GRID_POINTS=18e3;var MAX_SEARCH_STATES=54e3;var MAX_TOTAL_SEARCH_STATES=16e4;var MAX_ROUTED_EDGES=256;var MAX_OBSTACLES=64;var sides=["right","bottom","left","top"];function box(node,clearance=0){return{left:node.cx-node.width/2-clearance,right:node.cx+node.width/2+clearance,top:node.cy-node.height/2-clearance,bottom:node.cy+node.height/2+clearance}}function inside(point,obstacle){return point.x>obstacle.left+EPSILON&&point.x<obstacle.right-EPSILON&&point.y>obstacle.top+EPSILON&&point.y<obstacle.bottom-EPSILON}function routingSegmentBlocked(a,b,obstacle){if(Math.abs(a.y-b.y)<EPSILON){return a.y>obstacle.top+EPSILON&&a.y<obstacle.bottom-EPSILON&&Math.max(a.x,b.x)>obstacle.left+EPSILON&&Math.min(a.x,b.x)<obstacle.right-EPSILON}if(Math.abs(a.x-b.x)<EPSILON){return a.x>obstacle.left+EPSILON&&a.x<obstacle.right-EPSILON&&Math.max(a.y,b.y)>obstacle.top+EPSILON&&Math.min(a.y,b.y)<obstacle.bottom-EPSILON}return true}function preferredSide(from,to){if(Math.abs(to.cx-from.cx)>=Math.abs(to.cy-from.cy))return to.cx>=from.cx?"right":"left";return to.cy>=from.cy?"bottom":"top"}function routingAnchor(node,side,offset=.5){const bounds=box(node);if(side==="left"||side==="right")return{x:bounds[side],y:bounds.top+node.height*offset};return{x:bounds.left+node.width*offset,y:bounds[side]}}function outward(point,side,distance){return{x:point.x+(side==="right"?distance:side==="left"?-distance:0),y:point.y+(side==="bottom"?distance:side==="top"?-distance:0)}}function simplify(points){const result=[];for(const point of points){const last=result[result.length-1];if(last&&Math.abs(last.x-point.x)<EPSILON&&Math.abs(last.y-point.y)<EPSILON)continue;const previous=result[result.length-2];if(previous&&last&&(previous.x===last.x&&last.x===point.x||previous.y===last.y&&last.y===point.y)){result[result.length-1]=point}else result.push(point)}return result}function overlappingLength(a,b,c,d){if(a.y===b.y&&c.y===d.y&&Math.abs(a.y-c.y)<EPSILON){return Math.max(0,Math.min(Math.max(a.x,b.x),Math.max(c.x,d.x))-Math.max(Math.min(a.x,b.x),Math.min(c.x,d.x)))}if(a.x===b.x&&c.x===d.x&&Math.abs(a.x-c.x)<EPSILON){return Math.max(0,Math.min(Math.max(a.y,b.y),Math.max(c.y,d.y))-Math.max(Math.min(a.y,b.y),Math.min(c.y,d.y)))}return 0}var MinQueue=class{items=[];get length(){return this.items.length}push(value){const items=this.items;items.push(value);let index=items.length-1;while(index>0){const parent=index-1>>1;if(items[parent].priority<=value.priority)break;items[index]=items[parent];index=parent}items[index]=value}pop(){const items=this.items;const first=items[0];const last=items.pop();if(items.length===0)return first;let index=0;while(index*2+1<items.length){const left=index*2+1;const right=left+1;const child=right<items.length&&items[right].priority<items[left].priority?right:left;if(items[child].priority>=last.priority)break;items[index]=items[child];index=child}items[index]=last;return first}};function findPath(start,end,obstacles,width,height,previousRoutes,gap,budget){const within=point=>point.x>=0&&point.x<=width&&point.y>=0&&point.y<=height;if(!within(start)||!within(end)||obstacles.some(obstacle=>inside(start,obstacle)||inside(end,obstacle))){return{reason:"an endpoint has no clear exit inside the canvas"}}const xs=new Set([0,width,start.x,end.x]);const ys=new Set([0,height,start.y,end.y]);for(const obstacle of obstacles){if(obstacle.left>=0&&obstacle.left<=width)xs.add(obstacle.left);if(obstacle.right>=0&&obstacle.right<=width)xs.add(obstacle.right);if(obstacle.top>=0&&obstacle.top<=height)ys.add(obstacle.top);if(obstacle.bottom>=0&&obstacle.bottom<=height)ys.add(obstacle.bottom)}for(const route of previousRoutes.slice(-8))for(const point of route){for(const offset of[-gap,gap]){if(point.x+offset>=0&&point.x+offset<=width)xs.add(point.x+offset);if(point.y+offset>=0&&point.y+offset<=height)ys.add(point.y+offset)}}const xValues=[...xs].sort((a,b)=>a-b);const yValues=[...ys].sort((a,b)=>a-b);const columns=xValues.length;const gridSize=columns*yValues.length;if(gridSize>MAX_GRID_POINTS)return{reason:`routing grid exceeds ${MAX_GRID_POINTS} points; simplify the graph`};const startIndex=yValues.indexOf(start.y)*columns+xValues.indexOf(start.x);const endIndex=yValues.indexOf(end.y)*columns+xValues.indexOf(end.x);const pointAt=index=>({x:xValues[index%columns],y:yValues[Math.floor(index/columns)]});const costs=new Float64Array(gridSize*3).fill(Infinity);const parents=new Int32Array(gridSize*3).fill(-1);const queue=new MinQueue;costs[startIndex*3]=0;queue.push({state:startIndex*3,cost:0,priority:0});let visits=0;while(queue.length>0){if(--budget.remaining<0)return{reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`};if(++visits>MAX_SEARCH_STATES)return{reason:`routing search exceeds ${MAX_SEARCH_STATES} states; simplify the graph`};const current=queue.pop();if(current.cost!==costs[current.state])continue;const index=Math.floor(current.state/3);const axis=current.state%3;if(index===endIndex){const points=[];for(let state=current.state;state>=0;state=parents[state])points.push(pointAt(Math.floor(state/3)));return{points:simplify(points.reverse())}}const a=pointAt(index);const column=index%columns;const row=Math.floor(index/columns);const neighbors=[column>0?index-1:-1,column<columns-1?index+1:-1,row>0?index-columns:-1,row<yValues.length-1?index+columns:-1];for(const neighbor of neighbors){if(neighbor<0)continue;const b=pointAt(neighbor);if(obstacles.some(obstacle=>routingSegmentBlocked(a,b,obstacle)))continue;const nextAxis=a.y===b.y?1:2;const state=neighbor*3+nextAxis;let overlap=0;for(const route of previousRoutes)for(let i=1;i<route.length;i++)overlap+=overlappingLength(a,b,route[i-1],route[i]);const cost=current.cost+Math.abs(b.x-a.x)+Math.abs(b.y-a.y)+(axis!==0&&axis!==nextAxis?18:0)+overlap*5;if(cost>=costs[state])continue;costs[state]=cost;parents[state]=current.state;queue.push({state,cost,priority:cost+Math.abs(end.x-b.x)+Math.abs(end.y-b.y)})}}return{reason:"no obstacle-free route exists inside the canvas"}}function endpoint(node,other,portId,requestedSide,selfLoop,target,ordinal,count,gap){const port=node.ports?.find(candidate=>candidate.id===portId);const side=port?.side??requestedSide??(selfLoop?target?"top":"right":preferredSide(node,other));const length=side==="left"||side==="right"?node.height:node.width;const separation=count>1?Math.min(gap,length*.7/(count-1)):0;const offset=port?port.offset??.5:.5+(ordinal-(count-1)/2)*separation/length;return{side,anchor:routingAnchor(node,side,offset),explicit:portId!=null||requestedSide!=null}}function straightGraphRoute(from,to,edge){return[endpoint(from,to,edge.fromPort,edge.fromSide,false,false,0,1,0).anchor,endpoint(to,from,edge.toPort,edge.toSide,false,true,0,1,0).anchor]}function routeOrthogonalGraph(nodes,edges,width,height,clearance=12,gap=14,extraObstacles=[]){const routes=new Map;const failures=[];const byId=new Map(nodes.map(node=>[node.id,node]));const obstacles=[...nodes.map(node=>box(node,clearance)),...extraObstacles.map(obstacle=>({left:obstacle.left-clearance,right:obstacle.right+clearance,top:obstacle.top-clearance,bottom:obstacle.bottom+clearance}))];const routeKey=edge=>[edge.from,edge.to].sort().join("\0");const counts=new Map;for(const edge of edges)counts.set(routeKey(edge),(counts.get(routeKey(edge))??0)+1);const occurrences=new Map;const previous=new Map;const budget={remaining:MAX_TOTAL_SEARCH_STATES};edges.forEach((edge,index)=>{if(index>=MAX_ROUTED_EDGES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_ROUTED_EDGES} edges per diagram`});return}if(obstacles.length>MAX_OBSTACLES){failures.push({index,reason:`orthogonal routing supports at most ${MAX_OBSTACLES} node and header obstacles per diagram`});return}if(budget.remaining<0){failures.push({index,reason:`diagram routing budget exceeds ${MAX_TOTAL_SEARCH_STATES} search states; simplify the graph`});return}const from=byId.get(edge.from);const to=byId.get(edge.to);const key=routeKey(edge);const ordinal=occurrences.get(key)??0;occurrences.set(key,ordinal+1);const count=counts.get(key)??1;const source=endpoint(from,to,edge.fromPort,edge.fromSide,from===to,false,ordinal,count,gap);const target=endpoint(to,from,edge.toPort,edge.toSide,from===to,true,ordinal,count,gap);const sourceSides=source.explicit?[source.side]:[source.side,...sides.filter(side=>side!==source.side)];const targetSides=target.explicit?[target.side]:[target.side,...sides.filter(side=>side!==target.side)];let failure="no obstacle-free route exists inside the canvas";for(const sourceSide of sourceSides){for(const targetSide of targetSides){const start=sourceSide===source.side?source.anchor:routingAnchor(from,sourceSide);const end=targetSide===target.side?target.anchor:routingAnchor(to,targetSide);if(from===to&&start.x===end.x&&start.y===end.y){failure="a self-loop requires distinct endpoint anchors";continue}const leadStart=outward(start,sourceSide,clearance);const leadEnd=outward(end,targetSide,clearance);if(obstacles.some((obstacle,obstacleIndex)=>obstacleIndex!==nodes.indexOf(from)&&routingSegmentBlocked(start,leadStart,obstacle)||obstacleIndex!==nodes.indexOf(to)&&routingSegmentBlocked(leadEnd,end,obstacle))){failure="another obstacle blocks an endpoint exit";continue}const result=findPath(leadStart,leadEnd,obstacles,width,height,previous.get(key)??[],Math.max(1,gap),budget);if(!result.points){failure=result.reason;if(/routing (grid|search|budget)/.test(failure)){failures.push({index,reason:failure});return}continue}const points=simplify([start,...result.points,end]);if(points.length<2)continue;const repeated=(previous.get(key)??[]).some(route=>route.length===points.length&&(route.every((point,position)=>point.x===points[position].x&&point.y===points[position].y)||route.every((point,position)=>point.x===points[points.length-1-position].x&&point.y===points[points.length-1-position].y)));if(repeated){failure="parallel connectors have no separate lane at the requested clearance";continue}routes.set(index,points);previous.set(key,[...previous.get(key)??[],points]);return}}failures.push({index,reason:failure})});return{routes,failures}}var SIDE_DIRECTION={right:{x:1,y:0},left:{x:-1,y:0},top:{x:0,y:-1},bottom:{x:0,y:1}};function fmt(value){return Math.round(value*100)/100}function sampleCubic(p0,p1,p2,p3,out,steps=14){for(let i=1;i<=steps;i++){const t=i/steps,u=1-t;out.push({x:u*u*u*p0.x+3*u*u*t*p1.x+3*u*t*t*p2.x+t*t*t*p3.x,y:u*u*u*p0.y+3*u*u*t*p1.y+3*u*t*t*p2.y+t*t*t*p3.y})}}function smoothConnector(start,end,startSide,endSide,waypoints=[]){const out=SIDE_DIRECTION[startSide],into=SIDE_DIRECTION[endSide];const points=[start,...waypoints,end];const tangents=points.map((_,index)=>{if(index===0)return out;if(index===points.length-1)return{x:-into.x,y:-into.y};const previous=points[index-1],next=points[index+1];const dx=next.x-previous.x,dy=next.y-previous.y;const length=Math.hypot(dx,dy)||1;return{x:dx/length,y:dy/length}});const samples=[start];let d=`M ${fmt(start.x)} ${fmt(start.y)}`;for(let i=0;i+1<points.length;i++){const a=points[i],b=points[i+1];const ta=tangents[i],tb=tangents[i+1];const dx=b.x-a.x,dy=b.y-a.y;const distance=Math.hypot(dx,dy);const along=tangent=>Math.abs(dx*tangent.x+dy*tangent.y);const handle=tangent=>Math.min(along(tangent)*.5+(distance-along(tangent))*.12,distance*.6);const c1={x:a.x+ta.x*handle(ta),y:a.y+ta.y*handle(ta)};const c2={x:b.x-tb.x*handle(tb),y:b.y-tb.y*handle(tb)};d+=` C ${fmt(c1.x)} ${fmt(c1.y)}, ${fmt(c2.x)} ${fmt(c2.y)}, ${fmt(b.x)} ${fmt(b.y)}`;sampleCubic(a,c1,c2,b,samples)}return{d,samples}}function roundedPolylinePath(points,radius){if(points.length===0)return{d:"",samples:[]};const samples=[points[0]];let d=`M ${fmt(points[0].x)} ${fmt(points[0].y)}`;for(let i=1;i<points.length;i++){const corner=points[i];const next=points[i+1];if(!next){d+=` L ${fmt(corner.x)} ${fmt(corner.y)}`;samples.push(corner);break}const previous=points[i-1];const inLength=Math.hypot(corner.x-previous.x,corner.y-previous.y);const outLength=Math.hypot(next.x-corner.x,next.y-corner.y);const r=Math.min(radius,inLength/2,outLength/2);if(r<.5){d+=` L ${fmt(corner.x)} ${fmt(corner.y)}`;samples.push(corner);continue}const before={x:corner.x+(previous.x-corner.x)*r/inLength,y:corner.y+(previous.y-corner.y)*r/inLength};const after={x:corner.x+(next.x-corner.x)*r/outLength,y:corner.y+(next.y-corner.y)*r/outLength};d+=` L ${fmt(before.x)} ${fmt(before.y)} Q ${fmt(corner.x)} ${fmt(corner.y)}, ${fmt(after.x)} ${fmt(after.y)}`;samples.push(before,corner,after)}return{d,samples}}function samplesHitBox(samples,obstacle){for(let i=1;i<samples.length;i++){const a=samples[i-1],b=samples[i];const steps=Math.max(1,Math.ceil(Math.hypot(b.x-a.x,b.y-a.y)/6));for(let k=0;k<=steps;k++){const x=a.x+(b.x-a.x)*k/steps,y=a.y+(b.y-a.y)*k/steps;if(x>obstacle.left&&x<obstacle.right&&y>obstacle.top&&y<obstacle.bottom)return true}}return false}function pointAlongSamples(samples,fraction){let total=0;for(let i=1;i<samples.length;i++)total+=Math.hypot(samples[i].x-samples[i-1].x,samples[i].y-samples[i-1].y);let remaining=total*fraction;for(let i=1;i<samples.length;i++){const a=samples[i-1],b=samples[i];const length=Math.hypot(b.x-a.x,b.y-a.y);if(remaining<=length&&length>0){const t=remaining/length;return{x:a.x+(b.x-a.x)*t,y:a.y+(b.y-a.y)*t}}remaining-=length}return samples[samples.length-1]??{x:0,y:0}}function distributeValues(count,start,end){if(count<=0)return[];if(count===1)return[(start+end)/2];const step=(end-start)/(count-1);return Array.from({length:count},(_,index)=>start+index*step)}function LayeredNetwork({c,layers,ariaLabel="Layered network diagram",activePath=[],annotations=[],formula,legend="highlighted path",width=900,height=400,nodeSize=56,showFormula=true}){const radius=nodeSize/2;const top=82;const bottom=showFormula||formula?height-118:height-42;const layerXs=distributeValues(layers.length,82,width-82);const nodeLayout=layers.map((layer,layerIndex)=>({...layer,x:layerXs[layerIndex],ys:distributeValues(layer.nodes.length,top,bottom),tone:layer.tone??"purple"}));const connectionElements=nodeLayout.slice(0,-1).flatMap((from,layerIndex)=>{const to=nodeLayout[layerIndex+1];return from.ys.flatMap((fromY,fromIndex)=>to.ys.map((toY,toIndex)=>{const active=activePath[layerIndex]===fromIndex&&activePath[layerIndex+1]===toIndex;return React9.createElement("line",{key:`connection-${layerIndex}-${fromIndex}-${toIndex}`,x1:from.x+radius+4,y1:fromY,x2:to.x-radius-4,y2:toY,stroke:active?c.warningLight:c.borderLight,strokeWidth:active?3.6:1.2,strokeOpacity:active?.98:.42,strokeLinecap:"round"})}))});const label=(key,text,x,y,labelWidth,color,fontSize=densityOf(c).f(13),fontWeight=600,fontFamily="Inter")=>React9.createElement("div",{key,style:{position:"absolute",left:x-labelWidth/2,top:y,width:labelWidth,display:"flex",justifyContent:"center",color,fontSize,fontWeight,fontFamily,lineHeight:1.15,textAlign:"center"}},formatMathText(text));const titleElements=nodeLayout.map(layer=>label(`title-${layer.title}`,layer.title,layer.x,20,120,getReadableToneColor(layer.tone,c),16,900));const nodeElements=nodeLayout.flatMap((layer,layerIndex)=>layer.ys.flatMap((y,nodeIndex)=>{const active=activePath[layerIndex]===nodeIndex;const color=getToneColor(layer.tone,c);return[active&&React9.createElement("div",{key:`halo-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius-14,top:y-radius-14,width:nodeSize+28,height:nodeSize+28,borderRadius:999,backgroundColor:withColorAlpha(c.warningLight,46/255),border:`4px solid ${c.warningLight}`,boxSizing:"border-box",boxShadow:`0 0 18px ${withColorAlpha(c.warningLight,102/255)}`}}),React9.createElement("div",{key:`node-${layerIndex}-${nodeIndex}`,style:{position:"absolute",left:layer.x-radius,top:y-radius,width:nodeSize,height:nodeSize,borderRadius:999,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,color:getReadableTextColor(color,c),border:active?`3px solid ${c.warningLight}`:`1.5px solid ${color}`,boxSizing:"border-box",boxShadow:active?`0 0 16px ${withColorAlpha(c.warningLight,112/255)}`:`0 8px 14px ${c.shadow}`,fontFamily:"JetBrains Mono",fontSize:densityOf(c).f(16),fontWeight:600,lineHeight:1}},formatMathText(layer.nodes[nodeIndex]))]}).filter(Boolean));const annotationY=showFormula||formula?height-84:height-26;const annotationElements=annotations.slice(0,Math.max(0,layerXs.length-1)).map((annotation,index)=>label(`annotation-${index}`,annotation,(layerXs[index]+layerXs[index+1])/2,annotationY,132,c.textMuted,13,800,"JetBrains Mono"));const formulaElement=(showFormula||formula)&&formula?React9.createElement("div",{key:"formula-wrap",style:{position:"absolute",left:width/2-244,top:height-52,width:488,height:44,borderRadius:densityOf(c).r(10),border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard,display:"flex",alignItems:"center",justifyContent:"center",color:c.textPrimary,fontFamily:"Inter",fontSize:densityOf(c).f(15),fontWeight:600,...hasShadow(c)?{boxShadow:`0 8px 18px ${c.shadow}`}:{}}},formatMathText(formula)):null;const legendElement=(showFormula||formula)&&formula?React9.createElement("div",{key:"legend-wrap",style:{position:"absolute",left:width-184,top:height-43,width:160,display:"flex",alignItems:"center",gap:densityOf(c).s(14),color:c.textSecondary,fontFamily:"Inter",fontSize:densityOf(c).f(12),fontWeight:600}},React9.createElement("div",{style:{width:42,height:5,borderRadius:999,backgroundColor:c.warningLight}}),legend):null;return React9.createElement("div",{role:"img","aria-label":ariaLabel,style:{width,height,maxWidth:"100%",position:"relative",display:"flex",alignSelf:"center",flexShrink:0}},React9.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,style:{position:"absolute",inset:0,overflow:"visible"}},...connectionElements),...titleElements,...nodeElements,...annotationElements,formulaElement,legendElement)}function defineDiagramIcon(id,render){return{id,render}}function defineIconRegistry(icons){return icons}function manualGraphLayout(nodes,sizes,width,height,padding){return new Map(nodes.map(node=>{const{width:resolvedWidth,height:resolvedHeight}=sizes.get(node.id);const minCx=resolvedWidth/2;const maxCx=width-resolvedWidth/2;const minCy=resolvedHeight/2;const maxCy=height-resolvedHeight/2;const requestedCx=padding+clamp(node.x??.5,0,1)*(width-padding*2);const requestedCy=padding+clamp(node.y??.5,0,1)*(height-padding*2);return[node.id,{...node,width:resolvedWidth,height:resolvedHeight,cx:minCx<=maxCx?clamp(requestedCx,minCx,maxCx):width/2,cy:minCy<=maxCy?clamp(requestedCy,minCy,maxCy):height/2}]}))}function segmentCrosses(a1,a2,b1,b2){const cross=(origin,first,second)=>(first.x-origin.x)*(second.y-origin.y)-(first.y-origin.y)*(second.x-origin.x);const d1=cross(a1,a2,b1);const d2=cross(a1,a2,b2);const d3=cross(b1,b2,a1);const d4=cross(b1,b2,a2);const epsilon=.01;if(Math.abs(d1)<epsilon&&Math.abs(d2)<epsilon)return false;return d1*d2<=epsilon&&d3*d4<=epsilon&&(d1*d2<-epsilon||d3*d4<-epsilon||Math.abs(d1*d2)<=epsilon&&Math.abs(d3*d4)<=epsilon)}function connectorCrossings(edges){let crossings=0;for(let leftIndex=0;leftIndex<edges.length;leftIndex+=1){const left=edges[leftIndex];for(let rightIndex=leftIndex+1;rightIndex<edges.length;rightIndex+=1){const right=edges[rightIndex];if(left.from===right.from||left.from===right.to||left.to===right.from||left.to===right.to)continue;let crosses=false;for(let leftSegment=0;leftSegment<left.points.length-1&&!crosses;leftSegment+=1){for(let rightSegment=0;rightSegment<right.points.length-1;rightSegment+=1){if(segmentCrosses(left.points[leftSegment],left.points[leftSegment+1],right.points[rightSegment],right.points[rightSegment+1])){crosses=true;break}}}if(crosses)crossings+=1}}return crossings}function rectanglesOverlap(left,right,padding=0){return left.left<right.right+padding&&left.right>right.left-padding&&left.top<right.bottom+padding&&left.bottom>right.top-padding}function labelRect(edge){return{left:edge.labelX-edge.labelWidth/2,right:edge.labelX+edge.labelWidth/2,top:edge.labelY-edge.labelHeight/2,bottom:edge.labelY+edge.labelHeight/2}}function nodeRect(node){return{left:node.cx-node.width/2,right:node.cx+node.width/2,top:node.cy-node.height/2,bottom:node.cy+node.height/2}}function connectorLabelCollisions(edges,nodes,headers=[]){const labels=edges.filter(edge=>edge.label).map(labelRect);let collisions=0;for(let index=0;index<labels.length;index+=1){for(let otherIndex=index+1;otherIndex<labels.length;otherIndex+=1){if(rectanglesOverlap(labels[index],labels[otherIndex],2))collisions+=1}for(const node of nodes.values()){if(rectanglesOverlap(labels[index],nodeRect(node)))collisions+=1}for(const header of headers){if(rectanglesOverlap(labels[index],header))collisions+=1}}return collisions}function labelCrossings(edges,headers){let crossings=0;for(const edge of edges){for(const other of edges){if(other===edge||!other.label)continue;if(samplesHitBox(edge.points,labelRect(other)))crossings+=1}for(const header of headers){if(samplesHitBox(edge.points,header))crossings+=1}}return crossings}function crowdedConnectorEndpoints(edges){const degrees=new Map;for(const edge of edges){degrees.set(edge.from,(degrees.get(edge.from)??0)+1);degrees.set(edge.to,(degrees.get(edge.to)??0)+1)}return Array.from(degrees.values()).filter(degree=>degree>8).length}function parallelConnectorGroups(edges){const routes=new Map;for(const edge of edges){const key=`${edge.from}\0${edge.to}`;routes.set(key,(routes.get(key)??0)+1)}return Array.from(routes.values()).filter(count=>count>1).length}function validateGraphDiagramSpec(nodes,edges,groups,layoutMode){const nodeIds=new Set;for(const node of nodes){if(nodeIds.has(node.id))throw new Error(`GraphDiagram received duplicate node id "${node.id}".`);nodeIds.add(node.id);const portIds=new Set;for(const port of node.ports??[]){if(typeof port.id!=="string"||port.id.trim().length===0){throw new Error(`GraphDiagram node "${node.id}" port id must be a non-empty string.`)}if(portIds.has(port.id))throw new Error(`GraphDiagram node "${node.id}" received duplicate port "${port.id}".`);portIds.add(port.id);if(!["top","right","bottom","left"].includes(port.side)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" must use side "top", "right", "bottom", or "left".`)}if(port.offset!=null&&(!Number.isFinite(port.offset)||port.offset<0||port.offset>1)){throw new Error(`GraphDiagram node "${node.id}" port "${port.id}" offset must be between 0 and 1.`)}}}const groupsById=new Map;for(const group of groups){if(nodeIds.has(group.id)||groupsById.has(group.id)){throw new Error(`GraphDiagram node and group ids must be unique; received duplicate id "${group.id}".`)}groupsById.set(group.id,group)}for(const group of groups){if(group.parent!=null&&!groupsById.has(group.parent)){throw new Error(`GraphDiagram group "${group.id}" references missing parent group "${group.parent}".`)}const visited=new Set([group.id]);let parent=group.parent;while(parent!=null){if(visited.has(parent))throw new Error(`GraphDiagram groups contain a parent cycle at "${parent}".`);visited.add(parent);parent=groupsById.get(parent)?.parent}}const occupiedGroups=new Set;for(const node of nodes){if(node.group!=null&&!groupsById.has(node.group)){throw new Error(`GraphDiagram node "${node.id}" references missing group "${node.group}".`)}let groupId=node.group;while(groupId!=null){occupiedGroups.add(groupId);groupId=groupsById.get(groupId)?.parent}}for(const group of groups){if(!occupiedGroups.has(group.id))throw new Error(`GraphDiagram group "${group.id}" contains no nodes.`)}const edgeIds=new Set;for(const edge of edges){if(!nodeIds.has(edge.from)||!nodeIds.has(edge.to)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}if(edge.id!=null){if(edgeIds.has(edge.id))throw new Error(`GraphDiagram received duplicate edge id "${edge.id}".`);edgeIds.add(edge.id)}for(const side of["from","to"]){const reference=side==="from"?edge.fromPort:edge.toPort;const endpointSide=side==="from"?edge.fromSide:edge.toSide;const node=nodes.find(candidate=>candidate.id===edge[side]);if(reference!=null&&!node.ports?.some(port=>port.id===reference)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" references missing ${side} port "${reference}" on node "${node.id}".`)}if(endpointSide!=null&&!["top","right","bottom","left"].includes(endpointSide)){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" ${side}Side must be "top", "right", "bottom", or "left".`)}if(reference!=null&&endpointSide!=null){throw new Error(`GraphDiagram edge "${edge.from}" -> "${edge.to}" cannot combine ${side}Port and ${side}Side.`)}}validateDiagramHref(edge.href,`edge "${edge.id??`${edge.from}" -> "${edge.to}`}"`)}for(const node of nodes){validateDiagramHref(node.href,`node "${node.id}"`)}if(groups.length>0&&layoutMode==="manual"){throw new Error('GraphDiagram groups require automatic layout; omit node coordinates and layout="manual".')}}function validateDiagramHref(href,owner){if(href==null)return;const normalized=href.trim().replace(/[\u0000- \u007f]/g,"");const scheme=/^([a-z][a-z\d+.-]*):/i.exec(normalized)?.[1]?.toLowerCase();if(scheme&&!["http","https","mailto","tel"].includes(scheme)){throw new Error(`GraphDiagram ${owner} has an unsupported link scheme "${scheme}:".`)}}function graphAccessibleText(value){if(typeof value==="string"||typeof value==="number")return String(value).trim();if(Array.isArray(value))return value.map(graphAccessibleText).filter(Boolean).join(" ");if(React9.isValidElement(value)){const props=value.props;return graphAccessibleText(props.children)}return""}function graphDescription(nodes,edges){const labels=new Map(nodes.map(node=>[node.id,graphAccessibleText(node.label)||node.id]));const parts=[`${nodes.length} nodes and ${edges.length} relationships.`];const relationships=edges.slice(0,8).map(edge=>{const from=labels.get(edge.from)??edge.from;const to=labels.get(edge.to)??edge.to;return edge.label?`${from} ${edge.label} ${to}`:`${from} to ${to}`});if(relationships.length)parts.push(relationships.join("; "));if(edges.length>relationships.length)parts.push(`${edges.length-relationships.length} more relationships`);return parts.join(" ")}function graphGroupDepth(group,groupsById){let depth=0;let parent=group.parent;while(parent!=null){depth+=1;parent=groupsById.get(parent)?.parent}return depth}function resolvedGraphEdgeStyle(edge){if(edge.style)return edge.style;if(edge.dashed)return"dashed";if(edge.kind==="async"||edge.kind==="dependency")return"dashed";if(edge.kind==="event")return"dotted";return"solid"}function resolvedGraphEdgeArrow(edge){return edge.arrow??(edge.kind==="association"?"none":"forward")}function lineCount(text,size,available,weight=400){if(!text)return 0;const words=text.split(/\s+/);let lines=1,current=0;const space=estimateTextWidth(" ",size,{weight});for(const word of words){const width=estimateTextWidth(word,size,{weight});if(current>0&¤t+space+width>available){lines+=1;current=width}else{current+=(current>0?space:0)+width}}return lines}function measureGraphNode(node,fixedWidth,minHeight,m,d){const label=graphAccessibleText(node.label)||node.id;const detail=graphAccessibleText(node.detail);const hasIcon=node.icon!=null;const measuredIcon=Math.min(node.iconSize??m.iconSize,d.f(48));const iconSpace=hasIcon?measuredIcon+d.s(9):0;const statusSpace=node.status?d.g(8)+d.s(6):0;const versionWidth=node.version?estimateTextWidth(node.version,m.micro,{mono:true})+d.s(8):0;const rowsWidth=Math.max(0,...(node.rows??[]).map(row=>estimateTextWidth(graphAccessibleText(row.key),m.micro)+d.s(10)+estimateTextWidth(graphAccessibleText(row.value),m.micro,{mono:true})));const metricCells=(node.metrics??[]).map(metric=>Math.max(estimateTextWidth(graphAccessibleText(metric.value),d.f(14),{mono:true})+(metric.unit!=null?estimateTextWidth(graphAccessibleText(metric.unit),m.micro)+d.s(3):0),estimateTextWidth(graphAccessibleText(metric.label),m.micro)));const metricsWidth=metricCells.length?Math.max(...metricCells)*metricCells.length+d.s(14)*(metricCells.length-1):0;const footerText=[node.owner,graphAccessibleText(node.footer)].filter(Boolean).join(" \xB7 ");const footerWidth=estimateTextWidth(footerText,m.micro);const headerWidth=iconSpace+statusSpace+versionWidth+Math.max(estimateTextWidth(label,m.labelSize,{weight:600}),estimateTextWidth(detail,m.detailSize));const natural=Math.ceil(Math.max(headerWidth,rowsWidth,metricsWidth,footerWidth)*1.04)+m.padX*2+4;const minimum=d.f(92);const maximum=d.f(300);const width=node.width??fixedWidth??clamp(natural,minimum,maximum);const inner=width-m.padX*2-2-iconSpace-statusSpace-versionWidth;const labelLines=lineCount(label,m.labelSize,inner,600);const detailLines=lineCount(detail,m.detailSize,inner);const rich=Boolean(node.rows?.length||node.metrics?.length||node.tags?.length||node.footer||node.owner||node.spark);let content=labelLines*m.labelSize*1.2;if(detailLines)content+=d.s(3)+detailLines*m.detailSize*1.25;if(hasIcon)content=Math.max(content,measuredIcon);if(node.rows?.length)content+=m.gap*2+1+node.rows.length*m.microLine+(node.rows.length-1)*d.s(2)+node.rows.filter(row=>row.bar!=null).length*(Math.max(2,d.g(3))+1);if(node.metrics?.length){const hasSpark=node.metrics.some(metric=>metric.spark);const hasBar=node.metrics.some(metric=>metric.bar!=null);content+=m.gap+d.f(14)*1.1+d.s(1)+m.micro*1.2+(hasSpark?d.f(14)+d.s(1):0)+(hasBar?Math.max(2,d.g(3))+d.s(1):0)}if(node.spark)content+=m.gap+d.f(18);if(node.tags?.length){const tagWidths=node.tags.map(tag=>estimateTextWidth(graphAccessibleText(tag),m.micro)+d.s(10)+2);let tagLines=1,current=0;for(const tagWidth of tagWidths){if(current>0&¤t+d.s(3)+tagWidth>width-m.padX*2-2){tagLines+=1;current=tagWidth}else current+=(current>0?d.s(3):0)+tagWidth}content+=m.gap+tagLines*(m.micro*1.1+Math.max(1,d.s(1.5))*2+2)+(tagLines-1)*d.s(3)}if(footerText)content+=m.gap+m.microLine;const natural_height=Math.ceil(content)+m.padY*2+2+(rich?d.s(2):0);const floor=minHeight??d.f(rich?0:38);return{width,height:node.height??Math.max(floor,natural_height)}}function layoutGroupedGraph(nodes,edges,groups,sizes,options){const groupById=new Map(groups.map(group=>[group.id,group]));const chain=nodeId2=>{const node=nodes.find(entry=>entry.id===nodeId2);const out=[];for(let group=node?.group;group!=null;group=groupById.get(group)?.parent)out.push(group);return out};const chains=new Map(nodes.map(node=>[node.id,chain(node.id)]));const isHorizontal=direction=>direction==="LR"||direction==="RL";const childIn=(nodeId2,scope)=>{const ancestors=chains.get(nodeId2)??[];if(scope===null)return ancestors.length?ancestors[ancestors.length-1]:nodeId2;const index=ancestors.indexOf(scope);if(index<0)return void 0;return index===0?nodeId2:ancestors[index-1]};const place=(scope,order2)=>{const direction=scope===null?options.direction:options.groupDirection;const horizontal=isHorizontal(direction);const nodeChildren=nodes.filter(node=>(node.group??null)===scope).map(node=>node.id);const groupChildren=groups.filter(group=>(group.parent??null)===scope).map(group=>group.id);const childIds=[...groupChildren,...nodeChildren].map((id,index)=>({id,index,key:order2.get(id)??index})).sort((left,right)=>left.key-right.key||left.index-right.index).map(entry=>entry.id);const inner=new Map(groupChildren.map(id=>[id,place(id,order2)]));const sizeOf=id=>inner.get(id)??sizes.get(id);const links=new Map;for(const edge of edges){const from=childIn(edge.from,scope),to=childIn(edge.to,scope);if(!from||!to||from===to)continue;const key=`${from}\0${to}`;const previous=links.get(key);const label=edge.label&&(!previous?.label||edge.label.length>previous.label.length)?edge.label:previous?.label;links.set(key,{from,to,...label?{label}:{}})}const centers=new Map;if(links.size===0&&childIds.length>options.wrapAt){const lines=Math.ceil(childIds.length/options.wrapAt);const perLine=Math.ceil(childIds.length/lines);let offset=0;for(let line=0;line<lines;line+=1){const members=childIds.slice(line*perLine,(line+1)*perLine);const across=Math.max(...members.map(id=>horizontal?sizeOf(id).width:sizeOf(id).height));let along=0;for(const id of members){const size=sizeOf(id);const span=horizontal?size.height:size.width;centers.set(id,horizontal?{x:offset+across/2,y:along+span/2}:{x:along+span/2,y:offset+across/2});along+=span+options.nodeGap}offset+=across+options.nodeGap}}else{const graph=new dagre.graphlib.Graph({multigraph:false}).setGraph({rankdir:direction,nodesep:options.nodeGap,ranksep:options.rankGap,edgesep:options.edgeGap,marginx:0,marginy:0}).setDefaultEdgeLabel(()=>({}));for(const id of childIds)graph.setNode(id,{width:sizeOf(id).width,height:sizeOf(id).height});for(const link of links.values()){const size=link.label?options.measureLabel(link.label):{width:0,height:0};graph.setEdge(link.from,link.to,{width:size.width,height:size.height})}dagre.layout(graph);for(const id of childIds){const position=graph.node(id);centers.set(id,{x:position?.x??0,y:position?.y??0})}}let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const id of childIds){const size=sizeOf(id),center=centers.get(id);minX=Math.min(minX,center.x-size.width/2);minY=Math.min(minY,center.y-size.height/2);maxX=Math.max(maxX,center.x+size.width/2);maxY=Math.max(maxY,center.y+size.height/2)}if(minX===Infinity){minX=0;minY=0;maxX=0;maxY=0}const framed=scope!==null;const pad=framed?options.groupPad:0;const header=framed?options.headerHeight:0;const originX=pad-minX;const originY=pad+header-minY;const placedNodes=new Map;const placedGroups=new Map;for(const id of childIds){const center=centers.get(id),size=sizeOf(id);const left=center.x-size.width/2+originX;const top=center.y-size.height/2+originY;const child=inner.get(id);if(child){placedGroups.set(id,{left,top,right:left+size.width,bottom:top+size.height});for(const[nodeId2,point]of child.nodes)placedNodes.set(nodeId2,{x:point.x+left,y:point.y+top});for(const[groupId,rect]of child.groups){placedGroups.set(groupId,{left:rect.left+left,right:rect.right+left,top:rect.top+top,bottom:rect.bottom+top})}}else{placedNodes.set(id,{x:center.x+originX,y:center.y+originY})}}return{width:maxX-minX+pad*2,height:maxY-minY+pad*2+header,nodes:placedNodes,groups:placedGroups}};const first=place(null,new Map);const perpendicular=id=>{const point=first.nodes.get(id);return point?isHorizontal(options.direction)?point.y:point.x:0};const pull=new Map;for(const edge of edges){;(pull.get(edge.from)??pull.set(edge.from,[]).get(edge.from)).push(perpendicular(edge.to));(pull.get(edge.to)??pull.set(edge.to,[]).get(edge.to)).push(perpendicular(edge.from))}const mean=values=>values.reduce((sum,value)=>sum+value,0)/values.length;const order=new Map;for(const node of nodes){const values=pull.get(node.id);order.set(node.id,values?.length?mean(values):perpendicular(node.id))}for(const group of[...groups].sort((left,right)=>graphGroupDepth(right,groupById)-graphGroupDepth(left,groupById))){const members=nodes.filter(node=>chains.get(node.id)?.includes(group.id)).map(node=>order.get(node.id)??0);order.set(group.id,members.length?mean(members):0)}const second=place(null,order);return{positions:second.nodes,rects:second.groups}}var OPPOSITE={left:"right",right:"left",top:"bottom",bottom:"top"};function chooseSides(from,to,horizontal){const dx=to.cx-from.cx,dy=to.cy-from.cy;const separatedX=Math.abs(dx)>(from.width+to.width)/2+4;const separatedY=Math.abs(dy)>(from.height+to.height)/2+4;const useX=horizontal?separatedX||!separatedY:separatedX&&!separatedY;if(useX){const side2=dx>=0?"right":"left";return[side2,OPPOSITE[side2]]}const side=dy>=0?"bottom":"top";return[side,OPPOSITE[side]]}function GraphDiagram({nodes,edges,groups=[],c:baseTheme,width,height,nodeWidth,nodeHeight,labelFontSize,detailFontSize,arrowSize,padding:paddingProp,layout:requestedLayout,direction="LR",groupDirection,nodeGap:nodeGapProp,rankGap:rankGapProp,edgeGap:edgeGapProp,routing="dagre",routingClearance:routingClearanceProp,sizing="content",iconSize:iconSizeProp,id,ariaLabel,title,description,legend,annotations=[],density,crossingBudget}){const c=density!==void 0?withDensity(baseTheme,density):baseTheme;const d=densityOf(c);const padding=paddingProp??d.s(28);const nodeGap=nodeGapProp??d.s(40);const rankGap=rankGapProp??d.s(72);const edgeGap=edgeGapProp??d.s(14);const routingClearance=routingClearanceProp??d.s(12);const iconSize=iconSizeProp??d.f(20);const engineering=c.preset==="engineering";if(id!=null&&id.trim().length===0)throw new Error("GraphDiagram id must not be empty.");if(!["dagre","straight","orthogonal"].includes(routing))throw new Error('GraphDiagram routing must be "dagre", "straight", or "orthogonal".');if(!Number.isFinite(routingClearance)||routingClearance<=0)throw new Error("GraphDiagram routingClearance must be a finite positive number.");const fullyPositioned=nodes.filter(node=>node.x!=null&&node.y!=null).length;const partiallyPositioned=nodes.some(node=>node.x==null!==(node.y==null));if(partiallyPositioned||fullyPositioned>0&&fullyPositioned<nodes.length){throw new Error("GraphDiagram nodes must either all define both x and y, or all omit coordinates for automatic layout.")}const layoutMode=requestedLayout??(fullyPositioned===nodes.length&&nodes.length>0?"manual":"auto");if(layoutMode==="manual"&&fullyPositioned!==nodes.length){throw new Error('GraphDiagram layout="manual" requires x and y on every node.')}validateGraphDiagramSpec(nodes,edges,groups,layoutMode);const edgeOccurrences=new Map;const stableEdgeIds=edges.map(edge=>{if(edge.id!=null)return`custom-${edge.id}`;const route=`${edge.from}\0${edge.to}`;const occurrence=edgeOccurrences.get(route)??0;edgeOccurrences.set(route,occurrence+1);return`route-${edge.from}-to-${edge.to}-${occurrence}`});if(new Set(stableEdgeIds).size!==stableEdgeIds.length){throw new Error("GraphDiagram edge ids must not collide with generated relationship ids.")}const svgTitle=title?.trim()||ariaLabel?.trim()||"Graph diagram";const svgDescription=description??graphDescription(nodes,edges);const metrics={labelSize:labelFontSize??d.type.label,detailSize:detailFontSize??d.type.small,iconSize,padX:d.s(11),padY:d.s(8),gap:d.s(7),lineHeight:1.2,micro:d.type.micro,microLine:d.type.micro*1.25};const sizes=new Map(nodes.map(node=>[node.id,measureGraphNode(node,nodeWidth,nodeHeight,metrics,d)]));const edgeLabelSize=d.type.micro;const edgeLabelPad={x:d.s(5),y:Math.max(1,d.s(2))};const measureEdgeLabel=label=>({width:Math.ceil(estimateTextWidth(label,edgeLabelSize,{mono:engineering}))+edgeLabelPad.x*2+2,height:Math.ceil(edgeLabelSize*1.15)+edgeLabelPad.y*2});let resolvedWidth=width??0;let resolvedHeight=height??0;let layout;let groupLayout=[];let autoEdgePoints=new Map;const groupHeaderHeight=d.type.small*1.25+d.s(8);const groupPad=d.s(12);if(layoutMode==="auto"){const boxes=new Map;const groupsById=new Map(groups.map(group=>[group.id,group]));if(groups.length>0){const grouped=layoutGroupedGraph(nodes,edges,groups,sizes,{direction,groupDirection:groupDirection??direction,nodeGap,rankGap,edgeGap,groupPad,headerHeight:groupHeaderHeight,wrapAt:5,measureLabel:measureEdgeLabel});layout=new Map(nodes.map(node=>{const point=grouped.positions.get(node.id)??{x:0,y:0};return[node.id,{...node,width:sizes.get(node.id).width,height:sizes.get(node.id).height,cx:point.x,cy:point.y}]}));for(const[id2,rect]of grouped.rects)boxes.set(id2,rect)}else{const graph=new dagre.graphlib.Graph({multigraph:true}).setGraph({rankdir:direction,nodesep:nodeGap,ranksep:rankGap,edgesep:edgeGap,marginx:padding,marginy:padding}).setDefaultEdgeLabel(()=>({}));for(const node of nodes){graph.setNode(node.id,{width:sizes.get(node.id).width,height:sizes.get(node.id).height})}edges.forEach((edge,index)=>{const size=edge.label?measureEdgeLabel(edge.label):{width:0,height:0};graph.setEdge(edge.from,edge.to,{width:size.width,height:size.height},`edge-${index}`)});dagre.layout(graph);layout=new Map(nodes.map(node=>{const position=graph.node(node.id);return[node.id,{...node,width:sizes.get(node.id).width,height:sizes.get(node.id).height,cx:position?.x??0,cy:position?.y??0}]}));autoEdgePoints=new Map(edges.map((edge,index)=>{const placed=graph.edge({v:edge.from,w:edge.to,name:`edge-${index}`});return[index,(placed?.points??[]).map(point=>({x:point.x,y:point.y}))]}))}groupLayout=groups.map(group=>{const rect=boxes.get(group.id)??{left:0,right:0,top:0,bottom:0};return{...group,width:rect.right-rect.left,height:rect.bottom-rect.top,cx:(rect.left+rect.right)/2,cy:(rect.top+rect.bottom)/2,depth:graphGroupDepth(group,groupsById),headerX:rect.left+d.s(8),headerY:rect.top+d.s(4)}}).sort((left,right)=>left.depth-right.depth);let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;const extend=rect=>{minX=Math.min(minX,rect.left);minY=Math.min(minY,rect.top);maxX=Math.max(maxX,rect.right);maxY=Math.max(maxY,rect.bottom)};for(const node of layout.values())extend(nodeRect(node));for(const rect of boxes.values())extend(rect);for(const points of autoEdgePoints.values())for(const point of points)extend({left:point.x,right:point.x,top:point.y,bottom:point.y});if(minX===Infinity){minX=0;minY=0;maxX=0;maxY=0}const notes=annotations.length?d.s(26)+d.type.micro*1.3*3+4:0;const contentWidth=Math.ceil(maxX-minX+padding*2);const contentHeight=Math.ceil(maxY-minY+padding*2+notes*2);if(sizing==="content"){resolvedWidth=Math.max(width??0,contentWidth);resolvedHeight=Math.max(height??0,contentHeight)}else{resolvedWidth=width??contentWidth;resolvedHeight=height??contentHeight}const offsetX=(resolvedWidth-(maxX-minX))/2-minX;const offsetY=(resolvedHeight-(maxY-minY))/2-minY;for(const node of layout.values()){node.cx+=offsetX;node.cy+=offsetY}for(const group of groupLayout){group.cx+=offsetX;group.cy+=offsetY;group.headerX+=offsetX;group.headerY+=offsetY}for(const points of autoEdgePoints.values()){for(const point of points){point.x+=offsetX;point.y+=offsetY}}}else{resolvedWidth=width??520;resolvedHeight=height??420;layout=manualGraphLayout(nodes,sizes,resolvedWidth,resolvedHeight,padding)}const anchored=edge=>edge.fromPort!=null||edge.toPort!=null||edge.fromSide!=null||edge.toSide!=null;const groupOf=new Map(nodes.map(node=>[node.id,node.group]));const flowIsHorizontal=edge=>{const sameGroup=groupOf.get(edge.from)!=null&&groupOf.get(edge.from)===groupOf.get(edge.to);const flow=sameGroup?groupDirection??direction:direction;return flow==="LR"||flow==="RL"};const headerRects=new Map(groupLayout.map(group=>[group.id,{left:group.headerX,right:Math.min(group.cx+group.width/2-d.s(6),group.headerX+groupHeaderWidth(group,d)),top:group.headerY,bottom:group.headerY+groupHeaderHeight-d.s(4)}]));const orthogonalEdges=edges.flatMap((edge,index)=>routing==="orthogonal"||routing==="dagre"&&anchored(edge)||routing==="straight"&&edge.from===edge.to?[{edge,index}]:[]);const routeWith=subset=>routeOrthogonalGraph(Array.from(layout.values()),subset.map(({edge})=>edge),resolvedWidth,resolvedHeight,routingClearance,edgeGap,Array.from(headerRects.values()));const routed=routeWith(orthogonalEdges);const orthogonalPoints=new Map(Array.from(routed.routes,([index,points])=>[orthogonalEdges[index].index,points]));const failedIndexes=new Set(routed.failures.map(failure=>orthogonalEdges[failure.index].index));const routingFailures=routed.failures.map(failure=>{const{edge}=orthogonalEdges[failure.index];return`Connector "${edge.from}" -> "${edge.to}" was not drawn: ${failure.reason}.`});const slotOffsets=new Map;if(routing==="dagre"){const sideUsers=new Map;edges.forEach((edge,index)=>{if(edge.from===edge.to||orthogonalPoints.has(index)||failedIndexes.has(index))return;const from=layout.get(edge.from),to=layout.get(edge.to);if(!from||!to)return;const[fromSide,toSide]=chooseSides(from,to,flowIsHorizontal(edge));const coordinate=(node,side)=>side==="left"||side==="right"?node.cy:node.cx;const add=(node,side,other,end)=>{const key=`${node.id}\0${side}`;const list=sideUsers.get(key)??[];list.push({key:`${index}\0${end}`,other:coordinate(other,side)+index*.001,length:side==="left"||side==="right"?node.height:node.width});sideUsers.set(key,list)};add(from,fromSide,to,"from");add(to,toSide,from,"to")});for(const users of sideUsers.values()){users.sort((left,right)=>left.other-right.other);const length=users[0].length;const spacing=users.length>1?Math.min(d.s(12)+edgeLabelSize*.2,length*.78/(users.length-1)):0;users.forEach((user,position)=>slotOffsets.set(user.key,(position-(users.length-1)/2)*spacing))}}const sideAnchor=(node,side,offset)=>{if(side==="left")return{x:node.cx-node.width/2,y:node.cy+offset};if(side==="right")return{x:node.cx+node.width/2,y:node.cy+offset};if(side==="top")return{x:node.cx+offset,y:node.cy-node.height/2};return{x:node.cx+offset,y:node.cy+node.height/2}};const placedLabels=[];const nodeRects=Array.from(layout.values()).map(node=>({id:node.id,rect:nodeRect(node)}));const rawEdgeLayouts=edges.flatMap((edge,index)=>{if(failedIndexes.has(index))return[];const from=layout.get(edge.from);const to=layout.get(edge.to);if(!from||!to)return[];const automatic=autoEdgePoints.get(index);const selfLoop=edge.from===edge.to;if(!selfLoop&&from.cx===to.cx&&from.cy===to.cy&&!automatic?.length)return[];const color=edge.muted?c.textMuted:edge.tone!=null?getToneColor(edge.tone,c):engineering?c.textSecondary:c.textMuted;const markerBaseId=`graph-arrow-${edge.from}-${edge.to}-${index}-${arrowSize??d.arrow}-${color}`.replace(/[^a-zA-Z0-9_-]/g,"-");const loopClearance=Math.max(d.s(24),d.arrow*3);const routedPoints=orthogonalPoints.get(index);let path;let samples;let route;if(routedPoints){const rounded=roundedPolylinePath(routedPoints,d.s(8));path=rounded.d;samples=rounded.samples;route=routedPoints}else if(routing==="straight"){route=straightGraphRoute(from,to,edge);path=route.map((point,position)=>`${position===0?"M":"L"} ${point.x} ${point.y}`).join(" ");samples=route}else if(selfLoop){const right=from.cx+from.width/2,top=from.cy-from.height/2;const start={x:right,y:from.cy-d.s(8)};const corner1={x:right+loopClearance,y:from.cy-d.s(8)};const corner2={x:right+loopClearance,y:top-loopClearance};const corner3={x:from.cx+d.s(10),y:top-loopClearance};const end={x:from.cx+d.s(10),y:top};const rounded=roundedPolylinePath([start,corner1,corner2,corner3,end],d.s(8));path=rounded.d;samples=rounded.samples;route=[start,corner1,corner2,corner3,end]}else{const[fromSide,toSide]=chooseSides(from,to,flowIsHorizontal(edge));const start=sideAnchor(from,fromSide,slotOffsets.get(`${index}\0from`)??0);const end=sideAnchor(to,toSide,slotOffsets.get(`${index}\0to`)??0);let smooth=smoothConnector(start,end,fromSide,toSide);let hit=false;const clearance=2;const hitsAnything=candidate=>nodeRects.some(({id:nodeId2,rect})=>nodeId2!==edge.from&&nodeId2!==edge.to&&samplesHitBox(candidate.samples,{left:rect.left-clearance,right:rect.right+clearance,top:rect.top-clearance,bottom:rect.bottom+clearance}));if(hitsAnything(smooth)){const interior=automatic&&automatic.length>2?automatic.slice(1,-1).filter(point=>{const clearOf=rect=>!(point.x>rect.left-6&&point.x<rect.right+6&&point.y>rect.top-6&&point.y<rect.bottom+6);return clearOf(nodeRect(from))&&clearOf(nodeRect(to))}):[];const guided=smoothConnector(start,end,fromSide,toSide,interior);if(interior.length>0&&!hitsAnything(guided))smooth=guided;else hit=true}if(hit){const detour=routeOrthogonalGraph(Array.from(layout.values()),[{...edge,fromSide,toSide}],resolvedWidth,resolvedHeight,Math.min(routingClearance,d.s(8)),edgeGap,[]);const points=detour.routes.get(0);if(points){const rounded=roundedPolylinePath(points,d.s(8));path=rounded.d;samples=rounded.samples;route=points}else{path=smooth.d;samples=smooth.samples;route=smooth.samples}}else{path=smooth.d;samples=smooth.samples;route=smooth.samples}}const labelSize=edge.label?measureEdgeLabel(edge.label):{width:0,height:0};return[{...edge,index,stableId:stableEdgeIds[index],color,markerStartId:`${markerBaseId}-start`,markerEndId:`${markerBaseId}-end`,points:samples,route,path,labelWidth:labelSize.width,labelHeight:labelSize.height}]});const headerList=Array.from(headerRects.values());const edgeLayouts=rawEdgeLayouts.map(edge=>{if(!edge.label){const mid=pointAlongSamples(edge.points,.5);return{...edge,labelX:mid.x,labelY:mid.y}}const candidates=[.5,.42,.58,.34,.66,.26,.74,.18,.82];let best={x:0,y:0,score:Infinity};candidates.forEach((fraction,order)=>{const point=pointAlongSamples(edge.points,fraction);const rect={left:point.x-edge.labelWidth/2,right:point.x+edge.labelWidth/2,top:point.y-edge.labelHeight/2,bottom:point.y+edge.labelHeight/2};let score=order*.2;for(const{rect:box2}of nodeRects)if(rectanglesOverlap(rect,box2,1))score+=40;for(const header of headerList)if(rectanglesOverlap(rect,header,1))score+=20;for(const placed of placedLabels)if(rectanglesOverlap(rect,placed,2))score+=30;for(const other of rawEdgeLayouts)if(other!==edge&&samplesHitBox(other.points,rect))score+=8;if(rect.left<0||rect.right>resolvedWidth||rect.top<0||rect.bottom>resolvedHeight)score+=15;if(score<best.score)best={x:point.x,y:point.y,score}});placedLabels.push({left:best.x-edge.labelWidth/2,right:best.x+edge.labelWidth/2,top:best.y-edge.labelHeight/2,bottom:best.y+edge.labelHeight/2});return{...edge,labelX:best.x,labelY:best.y}});for(const group of groupLayout){const rect=headerRects.get(group.id);if(!rect)continue;const width2=rect.right-rect.left,headerHeight=rect.bottom-rect.top;const left=group.cx-group.width/2,right=group.cx+group.width/2;const top=group.cy-group.height/2;const options=[{x:left+d.s(8),y:top+d.s(4)},{x:right-width2-d.s(8),y:top+d.s(4)}];const clear=options.find(option=>!edgeLayouts.some(edge=>samplesHitBox(edge.points,{left:option.x,right:option.x+width2,top:option.y,bottom:option.y+headerHeight})));const chosen=clear??options[0];group.headerX=chosen.x;group.headerY=chosen.y;group.headerFlipped=chosen===options[1];headerRects.set(group.id,{left:chosen.x,right:chosen.x+width2,top:chosen.y,bottom:chosen.y+headerHeight})}const finalHeaders=Array.from(headerRects.values());const crossings=connectorCrossings(edgeLayouts);const labelCollisions=connectorLabelCollisions(edgeLayouts,layout,finalHeaders);const crossedLabels=labelCrossings(edgeLayouts,finalHeaders);const crowdedEndpoints=crowdedConnectorEndpoints(edgeLayouts);const parallelGroups=parallelConnectorGroups(edgeLayouts.filter(edge=>!orthogonalPoints.has(edge.index)));const groupElements=groupLayout.map(group=>{const accent=group.muted?c.textMuted:getToneColor(group.tone??"neutral",c);return React9.createElement("div",{key:`graph-group-${group.id}`,"data-vizmatic-graph-group":group.id,style:{position:"absolute",left:group.cx-group.width/2,top:group.cy-group.height/2,width:group.width,height:group.height,display:"flex",boxSizing:"border-box",borderRadius:engineering?6:d.r(10),border:`1px ${group.muted?"dashed":"solid"} ${group.tone?withColorAlpha(accent,(group.muted?85:119)/255):c.border}`,backgroundColor:group.tone?withColorAlpha(accent,(engineering?8:7)/255):withColorAlpha(c.textPrimary,.012),opacity:group.muted?.68:1}})});const groupHeaderElements=groupLayout.map(group=>{const rect=headerRects.get(group.id);const outerLeft=group.cx-group.width/2+d.s(8);const outerRight=group.cx+group.width/2-d.s(8);const spansGroup=group.summary!=null;return React9.createElement("div",{key:`graph-group-header-${group.id}`,"data-vizmatic-graph-group-header":group.id,style:{position:"absolute",left:spansGroup?outerLeft:group.headerX,top:group.headerY,width:Math.max(0,spansGroup?outerRight-outerLeft:rect.right-rect.left),height:rect.bottom-rect.top,display:"flex",flexDirection:group.headerFlipped&&spansGroup?"row-reverse":"row",alignItems:"baseline",justifyContent:"space-between",gap:d.s(10),color:group.muted?c.textMuted:c.textPrimary,fontFamily:c.fontSans,lineHeight:1.25,whiteSpace:"nowrap",opacity:group.muted?.75:1}},React9.createElement("div",{style:{display:"flex",alignItems:"baseline",gap:d.s(7),minWidth:0,overflow:"hidden",backgroundColor:c.bg,padding:`0 ${d.s(3)}px`}},React9.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",fontSize:d.type.small,fontWeight:600,color:group.tone&&!group.muted?getReadableToneColor(group.tone,c):void 0}},group.label),group.detail&&React9.createElement("div",{style:{minWidth:0,overflow:"hidden",textOverflow:"ellipsis",color:c.textMuted,fontFamily:c.fontSans,fontSize:d.type.micro,fontWeight:400}},group.detail)),group.summary!=null&&React9.createElement("div",{style:{display:"flex",flexShrink:0,color:c.textSecondary,fontFamily:c.fontMono,fontSize:d.type.micro,backgroundColor:c.bg,padding:`0 ${d.s(3)}px`}},group.summary))});const annotationElements=[];const leaderLines=[];const annotationSize=d.type.micro;annotations.forEach((annotation,index)=>{const node=layout.get(annotation.target);if(!node)throw new Error(`GraphDiagram annotation references missing node "${annotation.target}".`);const text=graphAccessibleText(annotation.text);const boxWidth=annotation.width??Math.min(d.f(190),Math.ceil(estimateTextWidth(text,annotationSize))+4);const lines=lineCount(text,annotationSize,boxWidth);const boxHeight=Math.ceil(lines*annotationSize*1.3)+2;const reach=d.s(26);const cost=rect=>{let score=0;for(const{rect:box2}of nodeRects)if(rectanglesOverlap(rect,box2,3))score+=40;for(const box2 of finalHeaders)if(rectanglesOverlap(rect,box2,3))score+=20;for(const box2 of placedLabels)if(rectanglesOverlap(rect,box2,2))score+=20;for(const edge of edgeLayouts)if(samplesHitBox(edge.points,rect))score+=6;for(const group of groupLayout){const box2={left:group.cx-group.width/2,right:group.cx+group.width/2,top:group.cy-group.height/2,bottom:group.cy+group.height/2};const inside2=rect.left>=box2.left&&rect.right<=box2.right&&rect.top>=box2.top&&rect.bottom<=box2.bottom;if(!inside2&&rectanglesOverlap(rect,box2,0))score+=8}if(rect.left<0||rect.top<0||rect.right>resolvedWidth||rect.bottom>resolvedHeight)score+=60;return score};const rectFor=(side,out,along)=>{const distance=reach*out;if(side==="top"||side==="bottom"){const left2=node.cx-boxWidth/2+along*boxWidth;const top2=side==="top"?node.cy-node.height/2-distance-boxHeight:node.cy+node.height/2+distance;return{left:left2,right:left2+boxWidth,top:top2,bottom:top2+boxHeight}}const top=node.cy-boxHeight/2+along*boxHeight;const left=side==="right"?node.cx+node.width/2+distance:node.cx-node.width/2-distance-boxWidth;return{left,right:left+boxWidth,top,bottom:top+boxHeight}};const sides2=annotation.side?[annotation.side]:["top","bottom","right","left"];const options=[];for(const side of sides2){for(const out of[1,1.7,2.6]){for(const along of[0,.42,-.42]){const rect=rectFor(side,out,along);options.push({side,rect,score:cost(rect)+(out-1)*2+Math.abs(along)*2})}}}const placed=options.reduce((best,option)=>option.score<best.score?option:best);placedLabels.push(placed.rect);const color=annotation.tone?getToneColor(annotation.tone,c):c.textMuted;const anchor=sideAnchor(node,placed.side,0);const clampTo=(value,low,high)=>Math.max(low,Math.min(high,value));const tipX=clampTo(node.cx,placed.rect.left+2,placed.rect.right-2);const tipY=clampTo(node.cy,placed.rect.top+2,placed.rect.bottom-2);const tip=placed.side==="top"?{x:tipX,y:placed.rect.bottom}:placed.side==="bottom"?{x:tipX,y:placed.rect.top}:placed.side==="right"?{x:placed.rect.left,y:tipY}:{x:placed.rect.right,y:tipY};leaderLines.push(React9.createElement("line",{key:`leader-${index}`,x1:anchor.x,y1:anchor.y,x2:tip.x,y2:tip.y,stroke:color,strokeWidth:d.stroke.hair}),React9.createElement("circle",{key:`leader-dot-${index}`,cx:anchor.x,cy:anchor.y,r:d.g(2),fill:color}));annotationElements.push(React9.createElement("div",{key:`graph-annotation-${index}`,"data-vizmatic-graph-annotation":annotation.target,style:{position:"absolute",left:placed.rect.left,top:placed.rect.top,width:boxWidth,display:"flex",color:annotation.tone?getReadableToneColor(annotation.tone,c):c.textSecondary,backgroundColor:c.bg,fontFamily:c.fontSans,fontSize:annotationSize,fontStyle:"italic",lineHeight:1.3,...textFitStyle()}},annotation.text))});const kindLabels={sync:"synchronous",async:"asynchronous",event:"event",data:"data",dependency:"dependency",association:"association"};const legendItems=legend===true?[...new Set(edges.map(edge=>edge.kind).filter(kind=>kind!=null))].map(kind=>({label:kindLabels[kind],style:resolvedGraphEdgeStyle({from:"",to:"",kind})})):Array.isArray(legend)?legend:[];const legendHeight=legendItems.length?d.type.micro*1.4+d.s(8):0;const strokeFor=edge=>{if(edge.muted)return d.w(1.25);if(edge.emphasis)return d.w(2.5);return engineering?1.7:d.w(2)};const graphElement=React9.createElement("div",{key:"vizmatic-graph-root",role:"img","aria-label":ariaLabel??svgTitle,"data-vizmatic-svg-title":svgTitle,"data-vizmatic-svg-description":svgDescription,"data-vizmatic-svg-id":id,"data-vizmatic-connector-crossings":crossings,"data-vizmatic-connector-crossing-budget":crossingBudget??Math.floor(edges.length/6),"data-vizmatic-connector-label-collisions":labelCollisions,"data-vizmatic-connector-label-crossings":crossedLabels,"data-vizmatic-crowded-connector-endpoints":crowdedEndpoints,"data-vizmatic-parallel-connector-groups":parallelGroups,"data-vizmatic-unrouted-connectors":routingFailures.length,"data-vizmatic-routing-failures":routingFailures.length?JSON.stringify(routingFailures):void 0,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight+legendHeight,...sizing==="content"?{}:{maxWidth:"100%"},flexShrink:0}},...groupElements,React9.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React9.createElement("defs",{},...edgeLayouts.flatMap(edge=>{const arrow2=resolvedGraphEdgeArrow(edge);return[...arrow2==="backward"||arrow2==="both"?[ArrowMarkerDef({id:edge.markerStartId,color:edge.color,size:arrowSize??d.arrow,direction:"start"})]:[],...arrow2==="forward"||arrow2==="both"?[ArrowMarkerDef({id:edge.markerEndId,color:edge.color,size:arrowSize??d.arrow})]:[]]})),...edgeLayouts.map(edge=>React9.createElement("path",{key:`graph-edge-${edge.index}`,"data-vizmatic-graph-edge-id":encodeURIComponent(edge.stableId),"data-vizmatic-graph-edge-from":encodeURIComponent(edge.from),"data-vizmatic-graph-edge-to":encodeURIComponent(edge.to),"data-vizmatic-graph-edge-label":encodeURIComponent(edge.label??""),"data-vizmatic-graph-edge-title":encodeURIComponent(edge.title??""),"data-vizmatic-graph-edge-href":edge.href==null?void 0:encodeURIComponent(edge.href),"data-vizmatic-graph-edge-route":JSON.stringify(edge.route.length<=24?edge.route:[]),d:edge.path,fill:"none",stroke:edge.color,strokeWidth:strokeFor(edge),strokeDasharray:resolvedGraphEdgeStyle(edge)==="dashed"?`${d.s(7)} ${d.s(6)}`:resolvedGraphEdgeStyle(edge)==="dotted"?`${d.w(2)} ${d.s(6)}`:void 0,strokeLinecap:resolvedGraphEdgeStyle(edge)==="dotted"?"round":"butt",opacity:edge.muted?.6:1,markerStart:resolvedGraphEdgeArrow(edge)==="backward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerStartId})`:void 0,markerEnd:resolvedGraphEdgeArrow(edge)==="forward"||resolvedGraphEdgeArrow(edge)==="both"?`url(#${edge.markerEndId})`:void 0})),...leaderLines),...edgeLayouts.flatMap(edge=>edge.label?[React9.createElement("div",{key:`graph-edge-label-${edge.index}`,style:{position:"absolute",left:edge.labelX,top:edge.labelY,transform:"translate(-50%, -50%)",padding:`${edgeLabelPad.y}px ${edgeLabelPad.x}px`,borderRadius:engineering?0:d.r(3),backgroundColor:c.bg,color:edge.muted?c.textMuted:edge.tone&&!engineering?getReadableToneColor(edge.tone,c,c.bg,c.bg):c.textSecondary,fontFamily:engineering?c.fontMono:c.fontSans,fontSize:edgeLabelSize,fontWeight:400,lineHeight:1.15,...engineering?{textTransform:"uppercase",letterSpacing:"0.02em"}:{},whiteSpace:"nowrap"}},edge.label)]:[]),...groupHeaderElements,...annotationElements,...Array.from(layout.values()).map(node=>renderGraphNode(node,{c,d,metrics,labelFontSize,detailFontSize,iconSize,engineering})),...legendItems.length?[React9.createElement("div",{key:"graph-legend",style:{position:"absolute",left:padding,top:resolvedHeight+d.s(4),display:"flex"}},DiagramLegend({items:legendItems,c}))]:[]);return graphElement}Object.defineProperty(GraphDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});function groupHeaderWidth(group,d){const label=graphAccessibleText(group.label);const detail=graphAccessibleText(group.detail);return Math.ceil(estimateTextWidth(label,d.type.small,{weight:600})+(detail?d.s(7)+estimateTextWidth(detail,d.type.micro):0))+d.s(6)+2}function renderGraphNode(node,{c,d,metrics,labelFontSize,detailFontSize,iconSize,engineering}){const toned=node.tone!=null;const tone=node.tone??"neutral";const accent=node.muted?c.textMuted:getToneColor(tone,c);const fill=getToneFill(tone,c);const resolvedIconSize=clamp(node.iconSize??iconSize,8,Math.max(8,Math.min(node.width,node.height)-metrics.padY*2-2));const iconLabel=typeof node.label==="string"?`${node.label} icon`:void 0;const iconElement=typeof node.icon==="string"?Icon({c,name:node.icon,color:toned?accent:c.textSecondary,size:resolvedIconSize,label:iconLabel,muted:node.muted}):React9.isValidElement(node.icon)?node.icon:node.icon?.render({c,color:accent,size:resolvedIconSize,label:iconLabel});const icon=iconElement&&React9.createElement("div",{"data-vizmatic-graph-icon":node.id,style:{width:resolvedIconSize,height:resolvedIconSize,display:"flex",alignItems:"center",justifyContent:"center",flex:`0 0 ${resolvedIconSize}px`,overflow:"hidden"}},iconElement);const hasBody=Boolean(node.rows?.length||node.metrics?.length||node.tags?.length||node.footer||node.owner||node.spark);const leftAligned=Boolean(icon)||hasBody||Boolean(node.status)||Boolean(node.version);const title=React9.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:leftAligned?"flex-start":"center",gap:node.detail?d.s(3):0,minWidth:0,flex:1}},React9.createElement("div",{style:{fontFamily:c.fontSans,fontSize:labelFontSize??metrics.labelSize,fontWeight:600,lineHeight:1.2,color:node.muted?c.textMuted:c.textPrimary,...textFitStyle(leftAligned?"left":"center")}},node.label),node.detail&&React9.createElement("div",{style:{color:engineering?c.textMuted:c.textSecondary,fontFamily:engineering?c.fontMono:c.fontSans,fontSize:detailFontSize??metrics.detailSize,fontWeight:400,lineHeight:1.25,...textFitStyle(leftAligned?"left":"center")}},node.detail));const trailing=compactChildren([node.version&&React9.createElement("div",{key:"version",style:{display:"flex",flexShrink:0,color:c.textMuted,fontFamily:c.fontMono,fontSize:metrics.micro,lineHeight:1.2}},node.version),node.status&&React9.createElement(React9.Fragment,{key:"status"},StatusDot({status:node.status,c}))]);const divider=()=>React9.createElement("div",{style:{display:"flex",width:"100%",height:1,backgroundColor:c.borderSubtle,flexShrink:0}});const footerParts=compactChildren([node.owner,node.footer]);return React9.createElement("div",{key:`graph-node-${node.id}`,"data-vizmatic-graph-node-id":node.id,"data-vizmatic-graph-node-label":graphAccessibleText(node.label)||node.id,"data-vizmatic-graph-node-detail":graphAccessibleText(node.detail),"data-vizmatic-graph-node-title":node.title??"","data-vizmatic-graph-node-href":node.href,style:{position:"absolute",left:node.cx-node.width/2,top:node.cy-node.height/2,width:node.width,height:node.height,display:"flex",flexDirection:"column",alignItems:"stretch",justifyContent:hasBody?"flex-start":"center",gap:metrics.gap,padding:`${metrics.padY}px ${metrics.padX}px`,boxSizing:"border-box",borderRadius:engineering?5:d.r(8),backgroundColor:node.muted?c.bgSubtle:engineering?fill:c.bgCard,border:`1px solid ${node.muted?c.borderLight:engineering?accent:toned?withColorAlpha(accent,.55):c.borderLight}`,opacity:node.muted?.62:1,color:c.textPrimary}},React9.createElement("div",{style:{display:"flex",alignItems:leftAligned&&!node.detail?"center":leftAligned?"flex-start":"center",justifyContent:leftAligned?"flex-start":"center",gap:d.s(9),width:"100%"}},...compactChildren([icon,title,...trailing])),...compactChildren([node.rows?.length?React9.createElement(React9.Fragment,{key:"rows"},divider(),FactRows({rows:node.rows,c})):void 0,node.metrics?.length?React9.createElement(React9.Fragment,{key:"metrics"},MetricStrip({metrics:node.metrics,c})):void 0,node.spark?React9.createElement(React9.Fragment,{key:"spark"},Sparkline({values:node.spark,c,tone:node.tone,width:node.width-metrics.padX*2-2,height:d.f(18),area:true})):void 0,node.tags?.length?React9.createElement(React9.Fragment,{key:"tags"},TagList({tags:node.tags,c})):void 0,footerParts.length?React9.createElement("div",{key:"footer",style:{display:"flex",gap:d.s(6),color:c.textMuted,fontFamily:c.fontSans,fontSize:metrics.micro,lineHeight:1.25,whiteSpace:"nowrap",overflow:"hidden"}},...footerParts.map((part,index)=>React9.createElement("div",{key:`footer-${index}`,style:{display:"flex"}},part))):void 0]))}function countTreeLeaves(node){if(!node.children?.length)return 1;return node.children.reduce((sum,child)=>sum+countTreeLeaves(child),0)}function maxTreeDepth(node){if(!node.children?.length)return 0;return 1+Math.max(...node.children.map(maxTreeDepth))}function TreeDiagram({root,c,ariaLabel,title,subtitle,width,height,nodeWidth:nodeWidthProp,nodeHeight:nodeHeightProp,levelGap:levelGapProp,siblingGap:siblingGapProp,padding:paddingProp,math=false}){const nodeWidth=nodeWidthProp??densityOf(c).f(150);const nodeHeight=nodeHeightProp??densityOf(c).f(50);const levelGap=levelGapProp??densityOf(c).s(58);const siblingGap=siblingGapProp??densityOf(c).s(20);const padding=paddingProp??densityOf(c).s(28);const explicitIds=new Set;const validateIds=node=>{if(node.id){if(explicitIds.has(node.id))throw new Error(`TreeDiagram received duplicate node id "${node.id}".`);explicitIds.add(node.id)}node.children?.forEach(validateIds)};validateIds(root);const leafCount=Math.max(1,countTreeLeaves(root));const depthCount=maxTreeDepth(root);const resolvedWidth=width??Math.max(520,padding*2+leafCount*nodeWidth+Math.max(0,leafCount-1)*siblingGap);const resolvedHeight=height??padding*2+(depthCount+1)*nodeHeight+depthCount*levelGap;const levelStep=depthCount===0?0:Math.max(nodeHeight+18,(resolvedHeight-padding*2-nodeHeight)/depthCount);const usableWidth=Math.max(0,resolvedWidth-padding*2-nodeWidth);const leafStep=leafCount<=1?0:usableWidth/(leafCount-1);const positioned=[];const edges=[];let nextLeaf=0;const placeWithEdges=(node,depth,path)=>{const children=node.children??[];let centerIndex;const childPlacements=[];if(!children.length){centerIndex=nextLeaf;nextLeaf+=1}else{for(let index=0;index<children.length;index+=1){const child=children[index];childPlacements.push({node:child,index,center:placeWithEdges(child,depth+1,`${path}-${index}`)})}centerIndex=childPlacements.reduce((sum,child)=>sum+child.center,0)/childPlacements.length}const placed={...node,key:node.id??path,depth,cx:leafCount<=1?resolvedWidth/2:padding+nodeWidth/2+centerIndex*leafStep,cy:padding+nodeHeight/2+depth*levelStep};positioned.push(placed);for(const childPlacement of childPlacements){const childKey=childPlacement.node.id??`${path}-${childPlacement.index}`;const childNode=positioned.find(candidate=>candidate.key===childKey);if(childNode)edges.push({key:`${placed.key}-${childNode.key}`,from:placed,to:childNode})}return centerIndex};placeWithEdges(root,0,"root");const header=(title!=null||subtitle!=null)&&React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap:subtitle!=null?4:0,width:resolvedWidth,maxWidth:"100%"}},...compactChildren([title!=null&&React9.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),color:c.textPrimary,fontFamily:"Inter",fontSize:densityOf(c).f(16),fontWeight:600,lineHeight:1.2}},...compactChildren([root.tone&&ToneStrip({tone:root.tone}),renderMaybeMath(title,math)])),subtitle!=null&&React9.createElement("div",{style:{display:"flex",color:c.textSecondary,fontFamily:"Inter",fontSize:densityOf(c).f(11),fontWeight:500,lineHeight:1.35}},renderMaybeMath(subtitle,math))]));return React9.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(header?10:0),width:resolvedWidth,maxWidth:"100%"}},...compactChildren([header,React9.createElement("div",{role:"img","aria-label":ariaLabel??(typeof title==="string"?title:"Tree diagram"),style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},React9.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},...edges.map(edge=>{const color=c.borderLight;const startY=edge.from.cy+nodeHeight/2;const endY=edge.to.cy-nodeHeight/2;const midY=startY+(endY-startY)/2;return React9.createElement("path",{key:`tree-edge-${edge.key}`,d:`M ${edge.from.cx} ${startY} C ${edge.from.cx} ${midY}, ${edge.to.cx} ${midY}, ${edge.to.cx} ${endY}`,fill:"none",stroke:color,strokeWidth:densityOf(c).w(edge.to.muted?1.5:2),strokeLinecap:"round",opacity:edge.to.muted?.5:1})})),...positioned.map(node=>{const accent=node.muted?c.textMuted:getToneColor(node.tone??"neutral",c);const accentText=node.muted?c.textMuted:c.textPrimary;return React9.createElement("div",{key:`tree-node-${node.key}`,style:{position:"absolute",left:node.cx-nodeWidth/2,top:node.cy-nodeHeight/2,width:nodeWidth,height:nodeHeight,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:densityOf(c).s(node.detail?4:0),padding:`${densityOf(c).s(8)}px ${densityOf(c).s(10)}px`,boxSizing:"border-box",borderRadius:densityOf(c).r(8),backgroundColor:node.muted?c.bgSubtle:c.bgCard,border:`1px solid ${node.muted?c.borderLight:node.tone?withColorAlpha(accent,.55):c.borderLight}`,...!node.muted&&hasShadow(c)?{boxShadow:`0 8px 18px ${c.shadow}`}:{},opacity:node.muted?.62:1,color:accentText,textAlign:"center"}},React9.createElement("div",{style:{color:accentText,fontFamily:"Inter",fontSize:densityOf(c).f(13),fontWeight:600,lineHeight:1.15,...textFitStyle("center")}},renderMaybeMath(node.label,math)),node.detail!=null&&React9.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:densityOf(c).f(11),fontWeight:650,lineHeight:1.2,...textFitStyle("center")}},renderMaybeMath(node.detail,math)))}))]))}function CalloutCard({c,children,title,detail,tone="blue",width,minHeight,padding:paddingProp,titleFontSize,detailFontSize,filled=true,align="left"}){const d=densityOf(c);const padding=paddingProp??`${d.s(9)}px ${d.s(13)}px`;const accent=getToneColor(tone,c);const engineering=c.preset==="engineering";const textAlign=align;return React9.createElement("div",{style:{...width!=null?{width}:{},...minHeight!=null?{minHeight}:{},padding,borderRadius:engineering?5:d.r(8),boxSizing:"border-box",...engineering?{backgroundColor:getToneFill(tone,c),color:c.textPrimary,border:`1px solid ${accent}`}:filled?{backgroundColor:withColorAlpha(accent,18/255),color:c.textPrimary,border:`1px solid ${withColorAlpha(accent,.4)}`}:{backgroundColor:c.bgCard,color:c.textPrimary,border:`1px solid ${c.border}`},display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",justifyContent:"center",gap:detail?d.s(3):0,textAlign}},...compactChildren([title&&React9.createElement("div",{style:{fontSize:titleFontSize??d.type.body,color:c.textPrimary,fontFamily:c.fontSans,fontWeight:600,lineHeight:1.2,textAlign}},title),detail&&React9.createElement("div",{style:{fontSize:detailFontSize??d.type.small,color:c.textSecondary,fontFamily:engineering?c.fontMono:c.fontSans,lineHeight:1.3,textAlign}},detail),children&&React9.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:align==="center"?"center":"flex-start",fontSize:d.type.small,fontWeight:400,lineHeight:1.3,textAlign}},children)]))}function Pipeline({stages,c,title}){return React9.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:"center",gap:densityOf(c).s(20)}},title&&React9.createElement("div",{style:{...typeOf(c,"label"),color:c.textPrimary}},title),React9.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(0)}},...stages.flatMap((stage,i)=>{const elements=[];elements.push(Box({label:stage.label,sublabel:stage.sublabel,icon:stage.icon,color:stage.color||"primary",gradient:true,c,fontSize:densityOf(c).f(13)}));if(i<stages.length-1){elements.push(Arrow({direction:"right",length:36,c}))}return elements})))}import React10 from"react";var sequenceFragmentKinds=["alt","loop","parallel"];var sequenceMessageKinds=["sync","async","return"];function isFragment(item){return!("from"in item)&&(!("type"in item)||item.type!=="note"&&item.type!=="activation")}function isActivation(item){return"type"in item&&item.type==="activation"}function isNote(item){return"type"in item&&item.type==="note"}function sequenceFragmentKind(fragment){const kind=fragment.kind;if(kind==null||!sequenceFragmentKinds.includes(kind)){throw new Error(`SequenceDiagram fragment must define kind as "alt", "loop", or "parallel".`)}return kind}function sequenceMessageKind(message){const kind=message.kind;if(kind==null)return"sync";if(!sequenceMessageKinds.includes(kind)){throw new Error(`SequenceDiagram message kind must be "sync", "async", or "return".`)}return kind}function sequenceNoteText(note){return note.text}function sequenceContainerItems(container){if(container.items)return container.items;return[...container.messages??[],...container.notes??[],...container.fragments??[]]}function participantReferences(note){const references=note.over??[];if(note.participant&&!references.includes(note.participant))return[note.participant,...references];return references}function validateSequenceItems(items,participantIds,path){for(let index=0;index<items.length;index+=1){const item=items[index];const itemPath=`${path}[${index}]`;if(isFragment(item)){const kind=sequenceFragmentKind(item);const branches=item.branches??[];if((kind==="alt"||kind==="parallel")&&branches.length<2){throw new Error(`SequenceDiagram ${kind} fragment at ${itemPath} requires at least two branches.`)}if(branches.some(branch=>!branch||typeof branch!=="object")){throw new Error(`SequenceDiagram fragment at ${itemPath} contains an invalid branch.`)}for(let branchIndex=0;branchIndex<branches.length;branchIndex+=1){validateSequenceItems(sequenceContainerItems(branches[branchIndex]),participantIds,`${itemPath}.branches[${branchIndex}]`)}if(!branches.length){validateSequenceItems(sequenceContainerItems(item),participantIds,`${itemPath}.items`)}continue}if(isActivation(item)){if(!participantIds.has(item.participant)){throw new Error(`SequenceDiagram activation references missing participant "${item.participant}".`)}continue}if(isNote(item)){for(const participant of participantReferences(item)){if(!participantIds.has(participant)){throw new Error(`SequenceDiagram note references missing participant "${participant}".`)}}continue}if(!participantIds.has(item.from)||!participantIds.has(item.to)){throw new Error(`SequenceDiagram message "${item.from}" -> "${item.to}" references a missing participant.`)}sequenceMessageKind(item)}}function validateSequenceSpec(participants,items){const ids=new Set;for(const participant of participants){if(!participant.id.trim())throw new Error("SequenceDiagram participant ids must not be empty.");if(ids.has(participant.id))throw new Error(`SequenceDiagram received duplicate participant id "${participant.id}".`);ids.add(participant.id)}validateSequenceItems(items,ids,"items")}function branchLabel(branch,index){return branch.label??(index===0?"case":"else")}function flattenSequenceItems(items){const rows=[];const spans=[];const appendItems=(nextItems,depth,path)=>{nextItems.forEach((item,index)=>{if(!isFragment(item)){rows.push({key:item.id??`${path}-${index}`,item,depth});return}const fragmentId=item.id??`${path}-fragment-${index}`;const start=rows.length;const branchStarts=[];const branches=item.branches??[];if(branches.length){branches.forEach((branch,branchIndex)=>{const row=rows.length;branchStarts.push({row,label:branchLabel(branch,branchIndex)});rows.push({key:`${fragmentId}-branch-${branchIndex}`,marker:{fragment:item,branch,branchIndex},depth});appendItems(sequenceContainerItems(branch),depth+1,`${fragmentId}-branch-${branchIndex}`)})}else{rows.push({key:`${fragmentId}-start`,marker:{fragment:item},depth});appendItems(sequenceContainerItems(item),depth+1,fragmentId)}if(rows.length===start)rows.push({key:`${fragmentId}-empty`,marker:{fragment:item},depth});spans.push({id:fragmentId,start,end:Math.max(start,rows.length-1),depth,fragment:item,branchStarts})})};appendItems(items,0,"sequence");return{rows,spans}}function readableNodeText(value){if(typeof value==="string"||typeof value==="number")return String(value);return""}function sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop){if(!selfLoop)return`M ${fromX} ${y} L ${toX} ${y}`;const loopWidth=34;const right=fromX+loopWidth;const bottom=y+rowHeight*.52;return`M ${fromX} ${y} L ${right} ${y} L ${right} ${bottom} L ${fromX+10} ${bottom} L ${fromX+10} ${y+1}`}function sequenceNoteBounds(note,xs,chartWidth,noteWidth,padding){const references=participantReferences(note).filter(id=>xs.has(id));if(references.length>=2||note.side==="over"){const values=references.map(id=>xs.get(id)??chartWidth/2);const left2=Math.max(padding,Math.min(...values)-noteWidth/2);const right=Math.min(chartWidth-padding,Math.max(...values)+noteWidth/2);return{left:left2,width:Math.max(82,right-left2)}}const anchor=references.length?xs.get(references[0])??chartWidth/2:chartWidth/2;const left=note.side==="left"?anchor-noteWidth-18:note.side==="right"?anchor+18:anchor-noteWidth/2;return{left:Math.max(padding,Math.min(chartWidth-padding-noteWidth,left)),width:noteWidth}}function activationReference(value,rows,fallback,end){if(value==null)return fallback;if(typeof value==="number"){if(!Number.isInteger(value)||value<0||value>=Math.max(rows.length,1)){throw new Error(`SequenceDiagram activation row reference ${value} is outside rendered rows.`)}return value}const index=rows.findIndex(row=>row.key===value||row.item!=null&&row.item.id===value);if(index<0)throw new Error(`SequenceDiagram activation references missing row "${value}".`);return end?index:index}function SequenceDiagram({c,participants,messages=[],notes=[],activations=[],fragments=[],items,title,subtitle,ariaLabel,width,height,padding:paddingProp,participantWidth=132,participantGap=42,rowHeight=56,fragmentIndent=12,noteWidth=156,lifelineDash="5 5"}){const padding=paddingProp??densityOf(c).s(24);const orderedItems=items??sequenceContainerItems({messages,notes,fragments});validateSequenceSpec(participants,activations.length?[...orderedItems,...activations]:orderedItems);const flattened=flattenSequenceItems(orderedItems);const rows=flattened.rows.length?flattened.rows:[{key:"sequence-empty",depth:0}];const minimumWidth=padding*2+participantWidth*participants.length+participantGap*Math.max(0,participants.length-1);const resolvedWidth=width??Math.max(560,minimumWidth);if(width!=null&&width<minimumWidth){throw new Error(`SequenceDiagram width ${width} is too small for ${participants.length} participants; use at least ${minimumWidth}.`)}const headerHeight=92;const minimumHeight=padding+headerHeight+rows.length*rowHeight+padding;const resolvedHeight=height??minimumHeight;if(height!=null&&height<minimumHeight){throw new Error(`SequenceDiagram height ${height} is too small for ${rows.length} rows; use at least ${minimumHeight}.`)}const availableParticipantWidth=resolvedWidth-padding*2;const step=participants.length>1?(availableParticipantWidth-participantWidth)/(participants.length-1):0;const firstX=participants.length>1?padding+participantWidth/2:resolvedWidth/2;const participantXs=new Map(participants.map((participant,index)=>[participant.id,firstX+index*step]));const bodyTop=padding+headerHeight;const rowCenter=index=>bodyTop+index*rowHeight+rowHeight/2;const labelText2=ariaLabel??readableNodeText(title)??"Sequence diagram";const accessibleLabel=labelText2||"Sequence diagram";const markerDefinitions=participants.flatMap((participant,participantIndex)=>{const color=getToneColor(participant.tone??"blue",c);return sequenceMessageKindsForMarkers(orderedItems).map(kind=>ArrowMarkerDef({id:`sequence-arrow-${participantIndex}-${kind}`,color,size:5}))});const fragmentElements=flattened.spans.map(span=>{const tone=span.fragment.tone??(span.fragment.kind==="loop"?"purple":span.fragment.kind==="parallel"?"cyan":"warm");const accent=span.fragment.muted?c.textMuted:getToneColor(tone,c);const top=bodyTop+span.start*rowHeight+4;const spanHeight=Math.max(rowHeight-8,(span.end-span.start+1)*rowHeight-8);const left=padding+span.depth*fragmentIndent;const fragmentWidth=Math.max(0,resolvedWidth-left-padding-span.depth*fragmentIndent);return React10.createElement("div",{key:`sequence-fragment-${span.id}`,"data-vizmatic-sequence-fragment":span.id,style:{position:"absolute",left,top,width:fragmentWidth,height:spanHeight,display:"flex",boxSizing:"border-box",border:`1.25px ${span.fragment.muted?"dotted":"dashed"} ${withColorAlpha(accent,(span.fragment.muted?85:153)/255)}`,backgroundColor:withColorAlpha(accent,11/255),borderRadius:c.preset==="engineering"?4:8,pointerEvents:"none"}},React10.createElement("div",{style:{position:"absolute",left:8,top:-9,display:"flex",alignItems:"center",gap:densityOf(c).s(5),padding:`${densityOf(c).s(1)}px ${densityOf(c).s(5)}px`,backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:densityOf(c).f(11),fontWeight:600,lineHeight:1.1,textTransform:"uppercase"}},span.fragment.kind,span.fragment.label!=null&&" \xB7 ",span.fragment.label),...span.branchStarts.map(branch=>React10.createElement("div",{key:`sequence-branch-${span.id}-${branch.row}`,style:{position:"absolute",left:Math.max(8,span.depth*fragmentIndent),top:branch.row*rowHeight-span.start*rowHeight+5,padding:`${densityOf(c).s(2)}px ${densityOf(c).s(5)}px`,backgroundColor:c.bg,color:span.fragment.muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:c.fontMono,fontSize:densityOf(c).f(11),fontWeight:700,lineHeight:1.1}},branch.label)))});const lifelineElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;return React10.createElement("line",{key:`sequence-lifeline-${participant.id}`,x1:x,y1:bodyTop-14,x2:x,y2:bodyTop+rows.length*rowHeight,stroke:participant.muted?c.textMuted:c.borderLight,strokeWidth:participant.muted?1:1.35,strokeDasharray:lifelineDash,opacity:participant.muted?.46:.8})});const activationElements=[...activations,...orderedItems.filter(isActivation)].map((activation,index)=>{const participantX=participantXs.get(activation.participant);if(participantX==null)return null;const startValue=activation.start??activation.fromMessage;const endValue=activation.end??activation.toMessage;const start=activationReference(startValue,rows,0,false);const end=activationReference(endValue,rows,rows.length-1,true);if(end<start)throw new Error(`SequenceDiagram activation for "${activation.participant}" ends before it starts.`);const depth=Math.max(0,activation.depth??0);const accent=activation.muted?c.textMuted:getToneColor(activation.tone??"blue",c);const top=rowCenter(start)-rowHeight/2+5;const activationHeight=Math.max(14,(end-start+1)*rowHeight-10);return React10.createElement("div",{key:`sequence-activation-${activation.id??index}`,"data-vizmatic-sequence-activation":activation.participant,style:{position:"absolute",left:participantX-5+depth*7,top,width:10,height:activationHeight,boxSizing:"border-box",borderRadius:densityOf(c).r(3),backgroundColor:getToneFill(activation.tone??"blue",c),border:`1.5px solid ${accent}`,opacity:activation.muted?.52:.94,pointerEvents:"none"}})}).filter(Boolean);const messageLabels=[];const messageElements=rows.map((row,rowIndex)=>{if(!row.item||isFragment(row.item)||isActivation(row.item)||isNote(row.item))return null;const message=row.item;const fromX=participantXs.get(message.from)??resolvedWidth/2;const toX=participantXs.get(message.to)??resolvedWidth/2;const kind=sequenceMessageKind(message);const tone=message.tone??(kind==="return"?"neutral":kind==="async"?"cyan":"blue");const color=message.muted?c.textMuted:getToneColor(tone,c);const markerId=`sequence-arrow-${participants.findIndex(participant=>participant.id===message.to)}-${kind}`;const y=rowCenter(rowIndex);const selfLoop=message.from===message.to;if(message.label!=null){messageLabels.push(React10.createElement("div",{key:`sequence-message-label-${message.id??row.key}`,style:{position:"absolute",left:selfLoop?fromX+34:(fromX+toX)/2,top:y-18,transform:"translate(-50%, -50%)",maxWidth:Math.max(74,Math.abs(toX-fromX)-28),padding:`${densityOf(c).s(2)}px ${densityOf(c).s(5)}px`,backgroundColor:c.bg,color:message.muted?c.textMuted:c.textPrimary,fontFamily:c.fontMono,fontSize:densityOf(c).f(11),fontWeight:650,lineHeight:1.1,whiteSpace:"nowrap",...textFitStyle("center")}},message.label))}return React10.createElement("path",{key:`sequence-message-${message.id??row.key}`,d:sequenceMarkerPath(fromX,toX,y,rowHeight,selfLoop),fill:"none",stroke:color,strokeWidth:message.muted?1.25:2,strokeDasharray:kind==="sync"?void 0:"7 5",strokeLinecap:"round",opacity:message.muted?.48:.9,markerEnd:`url(#${markerId})`})}).filter(Boolean);const noteElements=rows.map((row,rowIndex)=>{if(!row.item||!isNote(row.item))return null;const note=row.item;const bounds=sequenceNoteBounds(note,participantXs,resolvedWidth,noteWidth,padding);const tone=note.tone??"warm";const accent=note.muted?c.textMuted:getToneColor(tone,c);return React10.createElement("div",{key:`sequence-note-${note.id??row.key}`,"data-vizmatic-sequence-note":note.id??row.key,style:{position:"absolute",left:bounds.left,top:rowCenter(rowIndex)-17,width:bounds.width,minHeight:34,boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"center",padding:`${densityOf(c).s(6)}px ${densityOf(c).s(9)}px`,borderRadius:c.preset==="engineering"?3:7,backgroundColor:note.muted?c.bgSubtle:getToneFill(tone,c),border:`1px solid ${withColorAlpha(accent,(note.muted?102:153)/255)}`,color:note.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),fontFamily:c.fontSans,fontSize:densityOf(c).f(11),fontWeight:700,lineHeight:1.2,textAlign:"center",...textFitStyle("center")}},sequenceNoteText(note))}).filter(Boolean);const participantElements=participants.map(participant=>{const x=participantXs.get(participant.id)??resolvedWidth/2;const tone=participant.tone??"blue";const accent=participant.muted?c.textMuted:getToneColor(tone,c);const icon=participant.icon&&Icon({c,name:participant.icon,color:accent,size:16,muted:participant.muted,label:readableNodeText(participant.label)?`${readableNodeText(participant.label)} icon`:void 0});return React10.createElement("div",{key:`sequence-participant-${participant.id}`,"data-vizmatic-sequence-participant":participant.id,style:{position:"absolute",left:x-participantWidth/2,top:padding,width:participantWidth,minHeight:54,boxSizing:"border-box",display:"flex",flexDirection:icon?"row":"column",alignItems:"center",justifyContent:"center",gap:icon?7:participant.detail?3:0,padding:`${densityOf(c).s(7)}px ${densityOf(c).s(8)}px`,borderRadius:c.preset==="engineering"?4:8,backgroundColor:participant.muted?c.bgSubtle:getToneFill(tone,c),border:`1.25px solid ${participant.muted?c.borderLight:accent}`,color:participant.muted?c.textMuted:getReadableTextColor(getToneFill(tone,c),c),opacity:participant.muted?.62:1,textAlign:icon?"left":"center"}},icon,React10.createElement("div",{style:{display:"flex",flexDirection:"column",alignItems:icon?"flex-start":"center",minWidth:0,gap:densityOf(c).s(participant.detail?3:0)}},React10.createElement("div",{style:{fontFamily:c.fontSans,fontSize:densityOf(c).f(12),fontWeight:600,lineHeight:1.15,...textFitStyle(icon?"left":"center")}},participant.label),participant.detail!=null&&React10.createElement("div",{style:{color:c.textMuted,fontFamily:c.fontMono,fontSize:densityOf(c).f(11),fontWeight:550,lineHeight:1.1,...textFitStyle(icon?"left":"center")}},participant.detail)))});return React10.createElement("div",{role:"img","aria-label":accessibleLabel,"data-vizmatic-sequence-row-count":rows.length,style:{position:"relative",display:"flex",width:resolvedWidth,height:resolvedHeight,maxWidth:"100%",flexShrink:0}},...fragmentElements,React10.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",inset:0,overflow:"visible"}},React10.createElement("defs",{},...markerDefinitions),...lifelineElements,...messageElements),...activationElements,...messageLabels,...noteElements,...participantElements,title!=null&&React10.createElement("div",{style:{position:"absolute",left:padding,top:2,color:c.textPrimary,fontFamily:c.fontSans,fontSize:densityOf(c).f(14),fontWeight:600}},title),subtitle!=null&&React10.createElement("div",{style:{position:"absolute",left:padding,top:20,color:c.textSecondary,fontFamily:c.fontSans,fontSize:densityOf(c).f(11),fontWeight:550}},subtitle))}function sequenceMessageKindsForMarkers(items){const kinds=new Set;const visit=nextItems=>{for(const item of nextItems){if(isFragment(item)){if(item.branches)item.branches.forEach(branch=>visit(sequenceContainerItems(branch)));else visit(sequenceContainerItems(item))}else if(!isNote(item)&&!isActivation(item)){kinds.add(sequenceMessageKind(item))}}};visit(items);if(!kinds.size)kinds.add("sync");return Array.from(kinds)}import React11 from"react";var nodeKinds=["source","transform","store","sink"];var edgeModes=["batch","stream"];var defaultNodeTones={source:"blue",transform:"purple",store:"green",sink:"warm"};var defaultNodeIcons={source:"file",transform:"tool",store:"database",sink:"bucket"};function nodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds.includes(kind)){throw new Error(`DataflowDiagram node "${node.id}" must define kind as "source", "transform", "store", or "sink".`)}return kind}function edgeMode(edge){const mode=edge.mode??"batch";if(!edgeModes.includes(mode)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" must use mode "batch" or "stream".`)}return mode}function validateSchema(schema,owner){if(schema==null||typeof schema==="string")return;const fields=new Set;const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));for(const field of fieldList){if(!field.name.trim())throw new Error(`DataflowDiagram schema for "${owner}" contains an empty field name.`);if(fields.has(field.name))throw new Error(`DataflowDiagram schema for "${owner}" contains duplicate field "${field.name}".`);fields.add(field.name)}}function schemaLabel(schema){if(schema==null)return void 0;if(typeof schema==="string")return schema;const prefix=[schema.name,schema.version].filter(Boolean).join(" ");const fieldList=Array.isArray(schema.fields)?schema.fields:Object.entries(schema.fields).map(([name,type])=>({name,type,required:false}));const fields=fieldList.map(field=>`${field.name}${field.type?`: ${field.type}`:""}${field.required?" *":""}`).join(", ");return[prefix,fields?`{ ${fields} }`:void 0].filter(Boolean).join(" ")}function detailWithSchema(detail,schema){const renderedSchema=schemaLabel(schema);if(!renderedSchema)return detail;if(detail==null)return renderedSchema;if(typeof detail==="string"||typeof detail==="number")return`${detail} \xB7 ${renderedSchema}`;return React11.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf().s(3),minWidth:0}},React11.createElement("div",null,detail),React11.createElement("div",{style:{fontFamily:"inherit",fontSize:"inherit",fontWeight:"inherit"}},renderedSchema))}function validateDataflowSpec(spec){const boundaries=spec.boundaries??[];const ids=new Set;for(const node of spec.nodes){if(!node.id.trim())throw new Error("DataflowDiagram node ids must not be empty.");if(ids.has(node.id))throw new Error(`DataflowDiagram received duplicate id "${node.id}".`);ids.add(node.id);nodeKind(node);validateSchema(node.schema,node.id)}for(const boundary of boundaries){if(!boundary.id.trim())throw new Error("DataflowDiagram boundary ids must not be empty.");if(ids.has(boundary.id))throw new Error(`DataflowDiagram received duplicate id "${boundary.id}".`);ids.add(boundary.id)}const boundariesById=new Map(boundaries.map(boundary=>[boundary.id,boundary]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundariesById.has(boundary.parent)){throw new Error(`DataflowDiagram boundary "${boundary.id}" references missing parent "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DataflowDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundariesById.get(parent)?.parent}}for(const node of spec.nodes){const boundary=node.boundary;if(boundary!=null&&!boundariesById.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}}for(const edge of spec.edges){if(!ids.has(edge.from)||!ids.has(edge.to)||!spec.nodes.some(node=>node.id===edge.from)||!spec.nodes.some(node=>node.id===edge.to)){throw new Error(`DataflowDiagram edge "${edge.from}" -> "${edge.to}" references a missing node.`)}edgeMode(edge);validateSchema(edge.schema,`${edge.from} -> ${edge.to}`)}const occupied=new Set;for(const node of spec.nodes){let boundary=node.boundary;while(boundary!=null){occupied.add(boundary);boundary=boundariesById.get(boundary)?.parent}}for(const boundary of boundaries){if(!occupied.has(boundary.id))throw new Error(`DataflowDiagram boundary "${boundary.id}" contains no nodes.`)}return{boundaries}}function compileDataflow(spec){const{boundaries}=validateDataflowSpec(spec);const boundaryIds=new Set(boundaries.map(boundary=>boundary.id));const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail,parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=nodeKind(node);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DataflowDiagram node "${node.id}" references missing boundary "${boundary}".`)}return{id:node.id,label:node.label,detail:detailWithSchema(node.detail,node.schema),href:node.href,title:node.title,tone:node.tone??defaultNodeTones[kind],icon:node.icon??defaultNodeIcons[kind],muted:node.muted,group:boundary,width:node.width,height:node.height}});const edges=spec.edges.map(edge=>{const mode=edgeMode(edge);const schema=schemaLabel(edge.schema);return{id:edge.id,from:edge.from,to:edge.to,label:edge.label??schema??mode,href:edge.href,title:edge.title,tone:edge.tone??(mode==="stream"?"cyan":"blue"),muted:edge.muted,kind:mode==="stream"?"async":"data",style:mode==="stream"?"dashed":"solid",arrow:"forward"}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Dataflow diagram"}}function DataflowDiagram({c,nodes,edges,boundaries,ariaLabel,id,title,description,width,height,nodeWidth=158,nodeHeight=70,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize}){const compiled=compileDataflow({nodes,edges,boundaries,ariaLabel});return GraphDiagram({c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel,id,title,description,width,height,nodeWidth,nodeHeight,labelFontSize,detailFontSize,arrowSize,padding,direction,nodeGap,rankGap,edgeGap,routing,routingClearance,sizing,iconSize})}Object.defineProperty(DataflowDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var boundaryKindLabels={region:"REGION",zone:"ZONE",vpc:"VPC",subnet:"SUBNET",namespace:"NAMESPACE",host:"HOST",cluster:"CLUSTER",trust:"TRUST"};var nodeKindLabels={user:"USER",client:"CLIENT",external:"EXTERNAL",gateway:"GATEWAY","load-balancer":"LOAD BALANCER",service:"SERVICE",api:"API",function:"FUNCTION",lambda:"LAMBDA",worker:"WORKER",container:"CONTAINER",pod:"POD",host:"HOST",vm:"VM",cluster:"CLUSTER",database:"DATABASE",cache:"CACHE",queue:"QUEUE",storage:"STORAGE","object-store":"OBJECT STORE",registry:"REGISTRY","message-broker":"MESSAGE BROKER",firewall:"FIREWALL",network:"NETWORK",internet:"INTERNET",device:"DEVICE",custom:"NODE"};var nodeKindIcons={user:"user",client:"browser",external:"globe",gateway:"gateway","load-balancer":"load-balancer",service:"container",api:"gateway",function:"agent",lambda:"agent",worker:"agent",container:"container",pod:"cluster",host:"server",vm:"server",cluster:"cluster",database:"database",cache:"cache",queue:"queue",storage:"storage","object-store":"bucket",registry:"storage","message-broker":"queue",firewall:"firewall",network:"network",internet:"globe",device:"mobile"};var connectionTones={ingress:"cyan",egress:"warm",internal:"blue","cross-boundary":"purple"};var boundaryKinds=["region","zone","vpc","subnet","namespace","host","cluster","trust"];var nodeKinds2=["user","client","external","gateway","load-balancer","service","api","function","lambda","worker","container","pod","host","vm","cluster","database","cache","queue","storage","object-store","registry","message-broker","firewall","network","internet","device","custom"];var connectionKinds=["ingress","egress","internal","cross-boundary"];function assertIdentifier(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`DeploymentDiagram ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier(id,seen,what){assertIdentifier(id,what);if(seen.has(id))throw new Error(`DeploymentDiagram received duplicate ${what} id "${id}".`);seen.add(id)}function portIdentity(port){if(typeof port==="string"||typeof port==="number")return String(port);return port.id}function portText(port){if(typeof port==="string"||typeof port==="number")return String(port);if(port.label)return port.label;const endpoint2=port.port??port.id;return[port.protocol,endpoint2==null?void 0:String(endpoint2)].filter(Boolean).join("/")||port.direction||"port"}function portForReference(node,reference){if(reference==null)return void 0;return node.ports?.find(port=>portIdentity(port)===String(reference))}function resolveConnectionKind(connection){const kind=connection.kind??"internal";if(!connectionKinds.includes(kind)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" must use kind "ingress", "egress", "internal", or "cross-boundary".`)}return kind}function resolveBoundaryKind(boundary){const kind=boundary.kind;if(kind==null||!boundaryKinds.includes(kind)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" must define kind as "region", "zone", "vpc", "subnet", "namespace", "host", "cluster", or "trust".`)}return kind}function resolveNodeKind(node){const kind=node.kind;if(kind==null||!nodeKinds2.includes(kind)){throw new Error(`DeploymentDiagram node "${node.id}" must define kind as a supported deployment node kind.`)}return kind}function connectionPortReference(connection,side){return side==="from"?connection.fromPort:connection.toPort}function connectionLabel(connection,sourcePort,targetPort){if(connection.label!=null)return connection.label;const declaredPort=connection.port;const portLabel=declaredPort!=null?portText(declaredPort):sourcePort!=null?portText(sourcePort):targetPort!=null?portText(targetPort):void 0;const protocol=connection.protocol??(typeof sourcePort==="object"&&sourcePort!=null?sourcePort.protocol:void 0)??(typeof targetPort==="object"&&targetPort!=null?targetPort.protocol:void 0);if(protocol&&portLabel&&!portLabel.toLowerCase().startsWith(protocol.toLowerCase())){return`${protocol}/${portLabel}`}return protocol??portLabel}function validateDeploymentSpec(boundaries,nodes,connections){const ids=new Set;const boundaryIds=new Set;for(const boundary of boundaries){assertUniqueIdentifier(boundary.id,ids,"boundary");resolveBoundaryKind(boundary);boundaryIds.add(boundary.id)}const nodeIds=new Set;const portsByNode=new Map;for(const node of nodes){assertUniqueIdentifier(node.id,ids,"node");nodeIds.add(node.id);const boundary=node.boundary;if(boundary!=null&&!boundaryIds.has(boundary)){throw new Error(`DeploymentDiagram node "${node.id}" references missing boundary "${boundary}".`)}const ports=new Map;node.ports?.forEach(port=>{const identity=portIdentity(port);if(ports.has(identity))throw new Error(`DeploymentDiagram node "${node.id}" received duplicate port "${identity}".`);ports.set(identity,port)});portsByNode.set(node.id,ports)}const boundaryParents=new Map(boundaries.map(boundary=>[boundary.id,boundary.parent]));for(const boundary of boundaries){if(boundary.parent!=null&&!boundaryIds.has(boundary.parent)){throw new Error(`DeploymentDiagram boundary "${boundary.id}" references missing parent boundary "${boundary.parent}".`)}const visited=new Set([boundary.id]);let parent=boundary.parent;while(parent!=null){if(visited.has(parent))throw new Error(`DeploymentDiagram boundaries contain a parent cycle at "${parent}".`);visited.add(parent);parent=boundaryParents.get(parent)}}const connectionIds=new Set;for(const connection of connections){if(connection.id!=null)assertUniqueIdentifier(connection.id,connectionIds,"connection");if(!nodeIds.has(connection.from)||!nodeIds.has(connection.to)){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references a missing node.`)}resolveConnectionKind(connection);for(const side of["from","to"]){const reference=connectionPortReference(connection,side);if(reference==null)continue;const nodeId2=side==="from"?connection.from:connection.to;const ports=portsByNode.get(nodeId2);if(ports!=null&&ports.size>0&&!ports.has(String(reference))){throw new Error(`DeploymentDiagram connection "${connection.from}" -> "${connection.to}" references missing ${side} port "${reference}" on node "${nodeId2}".`)}}}}function graphConnectionKind(kind){if(kind==="internal")return"data";if(kind==="ingress")return"sync";return"dependency"}function graphConnectionStyle(kind){if(kind==="cross-boundary")return"dotted";if(kind==="egress")return"dashed";return"solid"}function compileDeployment(spec){const boundaries=spec.boundaries??[];const connections=spec.connections??[];validateDeploymentSpec(boundaries,spec.nodes,connections);const anchorPorts=spec.routing!=null&&spec.routing!=="dagre";const incomingSide=spec.direction==="TB"?"top":spec.direction==="BT"?"bottom":spec.direction==="RL"?"right":"left";const outgoingSide=spec.direction==="TB"?"bottom":spec.direction==="BT"?"top":spec.direction==="RL"?"left":"right";const groups=boundaries.map(boundary=>({id:boundary.id,label:boundary.label,detail:boundary.detail??boundaryKindLabels[resolveBoundaryKind(boundary)],parent:boundary.parent,tone:boundary.tone,muted:boundary.muted}));const nodes=spec.nodes.map(node=>{const kind=resolveNodeKind(node);const nodePorts=node.ports??[];const generatedDetail=nodePorts.length>0?`ports: ${nodePorts.map(portText).join(", ")}`:nodeKindLabels[kind];return{id:node.id,label:node.label,detail:node.detail??generatedDetail,href:node.href,title:node.title,x:node.x,y:node.y,tone:node.tone,muted:node.muted,width:node.width,height:node.height,group:node.boundary,icon:node.icon??nodeKindIcons[kind],iconSize:node.iconSize,ports:anchorPorts?nodePorts.map((port,index)=>{const incoming=typeof port==="object"?port.direction==="ingress":false;const targetOnly=connections.some(connection=>connection.to===node.id&&String(connection.toPort)===portIdentity(port))&&!connections.some(connection=>connection.from===node.id&&String(connection.fromPort)===portIdentity(port));return{id:portIdentity(port),side:typeof port==="object"&&port.side!=null?port.side:incoming||targetOnly?incomingSide:outgoingSide,offset:typeof port==="object"&&port.offset!=null?port.offset:(index+1)/(nodePorts.length+1)}}):void 0}});const edges=connections.map(connection=>{const kind=resolveConnectionKind(connection);const fromReference=connectionPortReference(connection,"from");const toReference=connectionPortReference(connection,"to");const sourceNode=spec.nodes.find(node=>node.id===connection.from);const targetNode=spec.nodes.find(node=>node.id===connection.to);const sourcePort=sourceNode?portForReference(sourceNode,fromReference):void 0;const targetPort=targetNode?portForReference(targetNode,toReference):void 0;const fallbackFromPort=fromReference!=null&&!sourceNode?.ports?.length?fromReference:void 0;const fallbackToPort=toReference!=null&&!targetNode?.ports?.length?toReference:void 0;return{id:connection.id,from:connection.from,to:connection.to,tone:connection.tone??connectionTones[kind],muted:connection.muted,kind:graphConnectionKind(kind),style:connection.style??graphConnectionStyle(kind),arrow:connection.arrow??"forward",label:connectionLabel(connection,sourcePort??fallbackFromPort,targetPort??fallbackToPort),href:connection.href,title:connection.title,fromPort:anchorPorts&&fromReference!=null?String(fromReference):void 0,toPort:anchorPorts&&toReference!=null?String(toReference):void 0,fromSide:connection.fromSide,toSide:connection.toSide}});return{nodes,edges,groups,ariaLabel:spec.ariaLabel??"Deployment diagram"}}function DeploymentDiagram({c,boundaries,nodes,connections,ariaLabel="Deployment diagram",...graphProps}){const compiled=compileDeployment({nodes,boundaries,connections,ariaLabel,direction:graphProps.direction,routing:graphProps.routing});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,groups:compiled.groups,ariaLabel:compiled.ariaLabel})}Object.defineProperty(DeploymentDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});import React12 from"react";import dagre2 from"@dagrejs/dagre";var cardinalityWords={one:"exactly one","zero-or-one":"zero or one","one-or-many":"one or more","zero-or-many":"zero or more"};var legendLines=["PK primary key \xB7 FK foreign key \xB7 UQ unique \xB7 ? nullable","|| one \xB7 o| zero or one \xB7 |< one or more \xB7 o< zero or more"];function requiredText(value,label){if(typeof value!=="string"||!value.trim())throw new Error(`EntityRelationshipDiagram ${label} must be a non-empty string.`)}function positive(value,label,allowZero=false){if(!Number.isFinite(value)||(allowZero?value<0:value<=0)){throw new RangeError(`EntityRelationshipDiagram ${label} must be a finite ${allowZero?"non-negative":"positive"} number.`)}}function endpointAttributes(endpoint2){return endpoint2.attribute===void 0?[]:typeof endpoint2.attribute==="string"?[endpoint2.attribute]:endpoint2.attribute}function attributeDescription(attribute2){const constraints=[attribute2.primaryKey&&"primary key",attribute2.foreignKey&&"foreign key",attribute2.unique&&"unique",attribute2.nullable?"nullable":"not null"].filter(Boolean);return`${attribute2.name} (${attribute2.type}, ${constraints.join(", ")})`}function endpointDescription(endpoint2,entities){const entity=entities.get(endpoint2.entity);const attributes=endpointAttributes(endpoint2);return`${entity.label??entity.id}${attributes.length?` [${attributes.join(", ")}]`:""}`}function validate(entities,relationships){if(!entities.length)throw new Error("EntityRelationshipDiagram requires at least one entity.");const byId=new Map;for(const entity of entities){requiredText(entity.id,"entity id");if(byId.has(entity.id))throw new Error(`EntityRelationshipDiagram has duplicate entity id "${entity.id}".`);if(entity.label!==void 0)requiredText(entity.label,`entity "${entity.id}" label`);const names=new Set;for(const attribute2 of entity.attributes){requiredText(attribute2.name,`entity "${entity.id}" attribute name`);requiredText(attribute2.type,`attribute "${entity.id}.${attribute2.name}" type`);if(names.has(attribute2.name))throw new Error(`EntityRelationshipDiagram has duplicate attribute "${entity.id}.${attribute2.name}".`);if(attribute2.primaryKey&&attribute2.nullable)throw new Error(`EntityRelationshipDiagram primary key "${entity.id}.${attribute2.name}" cannot be nullable.`);names.add(attribute2.name)}byId.set(entity.id,entity)}const ids=new Set;for(const relationship of relationships){requiredText(relationship.id,"relationship id");if(ids.has(relationship.id))throw new Error(`EntityRelationshipDiagram has duplicate relationship id "${relationship.id}".`);ids.add(relationship.id);for(const endpoint2 of[relationship.from,relationship.to]){const entity=byId.get(endpoint2.entity);if(!entity)throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" references missing entity "${endpoint2.entity}".`);if(!Object.hasOwn(cardinalityWords,endpoint2.cardinality))throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" has invalid cardinality "${endpoint2.cardinality}".`);const attributes=endpointAttributes(endpoint2);if(endpoint2.attribute!==void 0&&attributes.length===0)throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" needs at least one endpoint attribute.`);if(new Set(attributes).size!==attributes.length)throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" repeats an endpoint attribute.`);for(const name of attributes){if(!entity.attributes.some(attribute2=>attribute2.name===name))throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" references missing attribute "${entity.id}.${name}".`)}}const from=endpointAttributes(relationship.from),to=endpointAttributes(relationship.to);if(from.length&&to.length&&from.length!==to.length)throw new Error(`EntityRelationshipDiagram relationship "${relationship.id}" has mismatched composite attribute counts.`)}return byId}function cardinalitySize(cardinality,scale){const many=cardinality.endsWith("many"),optional=cardinality.startsWith("zero");return{length:((optional?many?25:19:many?20:12)+.75)*scale,halfWidth:((many?6:5)+.75)*scale}}function cardinalityBounds(cardinality,point,toward,scale){const size=cardinalitySize(cardinality,scale);const horizontal=point.y===toward.y;const end={x:point.x+Math.sign(toward.x-point.x)*size.length,y:point.y+Math.sign(toward.y-point.y)*size.length};return{left:Math.min(point.x,end.x)-(horizontal?.75*scale:size.halfWidth),right:Math.max(point.x,end.x)+(horizontal?.75*scale:size.halfWidth),top:Math.min(point.y,end.y)-(horizontal?size.halfWidth:.75*scale),bottom:Math.max(point.y,end.y)+(horizontal?size.halfWidth:.75*scale)}}function cardinalityGlyph(cardinality,point,toward,color,background,scale,key){const length=Math.hypot(toward.x-point.x,toward.y-point.y);const ux=(toward.x-point.x)/length,uy=(toward.y-point.y)/length;const at=(along,across=0)=>({x:point.x+(ux*along-uy*across)*scale,y:point.y+(uy*along+ux*across)*scale});const bar=along=>{const a=at(along,-5),b=at(along,5);return`M ${a.x} ${a.y} L ${b.x} ${b.y}`};const many=cardinality.endsWith("many");const optional=cardinality.startsWith("zero");const middle=at(13),top=at(0,-6),bottom=at(0,6);const path=many?`M ${top.x} ${top.y} L ${middle.x} ${middle.y} L ${bottom.x} ${bottom.y} M ${point.x} ${point.y} L ${middle.x} ${middle.y}`:bar(5);const circle=at(many?21:15);return React12.createElement("g",{key,"data-er-cardinality":cardinality},React12.createElement("path",{d:`${path}${optional?"":` ${bar(many?20:12)}`}`,fill:"none",stroke:color,strokeWidth:1.5*scale}),optional&&React12.createElement("circle",{cx:circle.x,cy:circle.y,r:4*scale,fill:background,stroke:color,strokeWidth:1.5*scale}))}function EntityRelationshipDiagram({c:baseTheme,entities,relationships=[],title,description,id,direction="LR",width,height,entityWidth,fontSize,padding:paddingProp,gap:gapProp,showLegend=true,density}){const c=density===void 0?baseTheme:withDensity(baseTheme,density);const d=densityOf(c);const visibleTitle=title?.trim();const svgTitle=visibleTitle||"Entity relationship diagram";const textSize=fontSize??d.type.small;const headerSize=Math.max(textSize,d.type.label);const padding=paddingProp??d.s(32);const gap=gapProp??d.s(100);positive(textSize,"fontSize");positive(padding,"padding",true);positive(gap,"gap");if(width!==void 0)positive(width,"width");if(height!==void 0)positive(height,"height");if(entityWidth!==void 0)positive(entityWidth,"entityWidth");if(id!==void 0)requiredText(id,"id");if(!["LR","RL","TB","BT"].includes(direction))throw new Error("EntityRelationshipDiagram direction must be LR, RL, TB, or BT.");const byId=validate(entities,relationships);const lineScale=Math.max(.8,textSize/12);const markerSizes=relationships.flatMap(relationship=>[cardinalitySize(relationship.from.cardinality,lineScale),cardinalitySize(relationship.to.cardinality,lineScale)]);const markerLength=Math.max(0,...markerSizes.map(size=>size.length));const markerPitch=Math.max(0,...markerSizes.map(size=>size.halfWidth*2))+Math.max(d.s(4),lineScale*1.5);const baseClearance=Math.max(28,d.s(28));const routingClearance=Math.max(baseClearance,markerLength+d.s(4)+Math.max(2,d.s(2)));const enlargedMarkers=routingClearance>baseClearance;const bodyPadding=enlargedMarkers&&relationships.some(relationship=>relationship.from.entity===relationship.to.entity)?Math.max(padding,routingClearance+d.s(4)):padding;const anchorRow=endpoint2=>{const entity=byId.get(endpoint2.entity),names=endpointAttributes(endpoint2);return names.length?Math.round(names.reduce((sum,name)=>sum+entity.attributes.findIndex(attribute2=>attribute2.name===name),0)/names.length):Math.floor(Math.max(0,entity.attributes.length-1)/2)};const rowEndpointCounts=new Map(entities.map(entity=>[entity.id,new Map]));const entityEndpointCounts=new Map;for(const relationship of relationships)for(const endpoint2 of[relationship.from,relationship.to]){const counts=rowEndpointCounts.get(endpoint2.entity),row=anchorRow(endpoint2);counts.set(row,(counts.get(row)??0)+1);entityEndpointCounts.set(endpoint2.entity,(entityEndpointCounts.get(endpoint2.entity)??0)+1)}const rowHeight=Math.ceil(Math.max(d.s(25),textSize*1.7));const headerHeight=Math.ceil(Math.max(d.s(35),headerSize*2));const inset=d.s(12);const keyWidth=Math.ceil(estimateTextWidth("PK FK UQ",textSize,{mono:true}))+inset;const titleHeight=visibleTitle?Math.ceil(d.type.heading*1.5+d.s(12)):0;const legendHeight=showLegend?Math.ceil(textSize*3.2+d.s(12)):0;const legendWidth=showLegend?Math.max(480,...legendLines.map(line=>estimateTextWidth(line,textSize)+padding*2)):0;const labelPadding=relationships.some(relationship=>relationship.label)?Math.ceil(textSize*2+d.s(8)):0;const graph=new dagre2.graphlib.Graph({multigraph:true}).setGraph({rankdir:direction,nodesep:enlargedMarkers?Math.max(gap*.75,routingClearance*2+markerPitch):gap*.75,ranksep:Math.max(gap,74,routingClearance*2+markerPitch),edgesep:d.s(26),marginx:0,marginy:0}).setDefaultEdgeLabel(()=>({}));const measures=new Map(entities.map(entity=>{const nameWidth=Math.max(30,...entity.attributes.map(attribute2=>estimateTextWidth(attribute2.name,textSize,{mono:true})));const typeWidth=Math.max(24,...entity.attributes.map(attribute2=>estimateTextWidth(attribute2.type+(attribute2.nullable?"?":""),textSize,{mono:true})));const rowHeights=Array.from({length:Math.max(1,entity.attributes.length)},(_,index)=>Math.max(rowHeight,Math.ceil((rowEndpointCounts.get(entity.id).get(index)??0)*markerPitch)));let rowY=headerHeight;const rowCenters=rowHeights.map(height2=>{const center=rowY+height2/2;rowY+=height2;return center});const measured={width:Math.ceil(Math.max(entityWidth??d.s(210),estimateTextWidth(entity.label??entity.id,headerSize,{weight:600})+inset*2,keyWidth+nameWidth+typeWidth+inset*4,direction==="TB"||direction==="BT"?markerPitch*((entityEndpointCounts.get(entity.id)??0)+1):0)),height:rowY,rowHeights,rowCenters,typeWidth:Math.ceil(typeWidth)};graph.setNode(entity.id,{width:measured.width,height:measured.height});return[entity.id,measured]}));for(const relationship of relationships)graph.setEdge(relationship.from.entity,relationship.to.entity,{width:relationship.label?estimateTextWidth(relationship.label,textSize)+d.s(64):0,height:relationship.label?textSize*2:0,labelpos:"c"},relationship.id);dagre2.layout(graph);const graphWidth=graph.graph().width??0,graphHeight=graph.graph().height??0;const minWidth=Math.ceil(Math.max(graphWidth+(bodyPadding+labelPadding)*2,legendWidth,visibleTitle?estimateTextWidth(visibleTitle,d.type.heading,{weight:600})+padding*2:0));const minHeight=Math.ceil(graphHeight+(bodyPadding+labelPadding)*2+titleHeight+legendHeight);if(width!==void 0&&width<minWidth)throw new RangeError(`EntityRelationshipDiagram width needs at least ${minWidth}px to keep entity text readable.`);if(height!==void 0&&height<minHeight)throw new RangeError(`EntityRelationshipDiagram height needs at least ${minHeight}px to keep entity text readable.`);const resolvedWidth=width??minWidth,resolvedHeight=height??minHeight;const offsetX=(resolvedWidth-graphWidth)/2;const offsetY=bodyPadding+titleHeight+labelPadding+(resolvedHeight-minHeight)/2;const nodes=entities.map(entity=>{const node=graph.node(entity.id),measure=measures.get(entity.id);return{id:entity.id,cx:node.x+offsetX,cy:node.y+offsetY,width:measure.width,height:measure.height,ports:[]}});const nodeById=new Map(nodes.map(node=>[node.id,node]));const portRequests=[];const endpointPort=(endpoint2,other,port)=>{const node=nodeById.get(endpoint2.entity),target=nodeById.get(other.entity);const horizontal=direction==="LR"||direction==="RL";const side=node===target?"right":horizontal?target.cx>=node.cx?"right":"left":target.cy>=node.cy?"bottom":"top";const desired=side==="top"||side==="bottom"?node.width/2:measures.get(node.id).rowCenters[anchorRow(endpoint2)];portRequests.push({node,id:port,side,desired})};const edges=relationships.map((relationship,index)=>{const fromPort=`from-${index}`,toPort=`to-${index}`;endpointPort(relationship.from,relationship.to,fromPort);endpointPort(relationship.to,relationship.from,toPort);return{from:relationship.from.entity,to:relationship.to.entity,fromPort,toPort}});for(const node of nodes)for(const side of["left","right","top","bottom"]){const requests=portRequests.filter(request=>request.node===node&&request.side===side).sort((a,b)=>a.desired-b.desired);const extent=side==="left"||side==="right"?node.height:node.width;const positions=[];for(let start=0;start<requests.length;){let end=start+1;while(end<requests.length&&requests[end].desired===requests[start].desired)end++;for(let index=start;index<end;index++)positions[index]=requests[index].desired+(index-start-(end-start-1)/2)*markerPitch;start=end}for(let index=0;index<positions.length;index++)positions[index]=Math.max(positions[index],index?positions[index-1]+markerPitch:markerPitch/2);for(let index=positions.length-1;index>=0;index--)positions[index]=Math.min(positions[index],index===positions.length-1?extent-markerPitch/2:positions[index+1]-markerPitch);requests.forEach((request,index)=>node.ports.push({id:request.id,side,offset:positions[index]/extent}))}const routed=routeOrthogonalGraph(nodes,edges,resolvedWidth,resolvedHeight-legendHeight,routingClearance,Math.max(d.s(18),markerPitch));if(routed.failures.length)throw new Error(`EntityRelationshipDiagram could not route relationship "${relationships[routed.failures[0].index].id}": ${routed.failures[0].reason}`);const relationshipText=relationship=>`${endpointDescription(relationship.from,byId)} (${cardinalityWords[relationship.from.cardinality]}) to ${endpointDescription(relationship.to,byId)} (${cardinalityWords[relationship.to.cardinality]})${relationship.label?`: ${relationship.label}`:""}${relationship.identifying?", identifying relationship":", non-identifying relationship"}.`;const schemaSummary=`${entities.length} entities and ${relationships.length} relationships. ${entities.map(entity=>`${entity.label??entity.id}: ${entity.attributes.map(attributeDescription).join("; ")||"no attributes shown"}.`).join(" ")} ${relationships.map(relationshipText).join(" ")}`;const lineColor=c.textSecondary;const labels=[];const placedLabels=[];const markerBoxes=relationships.flatMap((relationship,index)=>{const points=routed.routes.get(index);return[cardinalityBounds(relationship.from.cardinality,points[0],points[1],lineScale),cardinalityBounds(relationship.to.cardinality,points.at(-1),points.at(-2),lineScale)]});const occupied=nodes.map(node=>({left:node.cx-node.width/2-3,right:node.cx+node.width/2+3,top:node.cy-node.height/2-3,bottom:node.cy+node.height/2+3}));const paths=relationships.flatMap((relationship,index)=>{const points=routed.routes.get(index);const path=roundedPolylinePath(points,d.s(4)).d;if(relationship.label){const segments=points.slice(1).map((point,at)=>({a:points[at],b:point,length:Math.hypot(point.x-points[at].x,point.y-points[at].y)}));const labelWidth=Math.ceil(estimateTextWidth(relationship.label,textSize))+d.s(10);const labelHeight=Math.ceil(textSize*1.4)+4;const candidates=segments.sort((a,b)=>b.length-a.length).flatMap(segment=>{return[.5,.25,.75].flatMap(fraction=>[1,2,3].flatMap(distance=>[-1,1].map(side=>{const x=segment.a.x+(segment.b.x-segment.a.x)*fraction;const y=segment.a.y+(segment.b.y-segment.a.y)*fraction;const horizontal=segment.a.y===segment.b.y;const cx=x+(horizontal?0:side*(labelWidth/2+d.s(6))*distance);const cy=y+(horizontal?side*(labelHeight/2+d.s(6))*distance:0);return{left:cx-labelWidth/2,right:cx+labelWidth/2,top:cy-labelHeight/2,bottom:cy+labelHeight/2}})))});const label=candidates.find(box2=>box2.left>=0&&box2.right<=resolvedWidth&&box2.top>=padding+titleHeight&&box2.bottom<=resolvedHeight-padding-legendHeight&&![...occupied,...markerBoxes,...placedLabels].some(other=>box2.left<other.right&&box2.right>other.left&&box2.top<other.bottom&&box2.bottom>other.top)&&![...routed.routes.values()].some(route=>samplesHitBox(route,box2)));if(!label)throw new Error(`EntityRelationshipDiagram could not place label for relationship "${relationship.id}" without covering the schema. Increase gap or canvas size.`);placedLabels.push(label);labels.push(React12.createElement("div",{key:`label-${relationship.id}`,style:{position:"absolute",left:label.left,top:label.top,width:labelWidth,height:labelHeight,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:c.bg,color:c.textSecondary,fontSize:textSize,fontFamily:c.fontSans,whiteSpace:"nowrap"}},relationship.label))}return[React12.createElement("path",{key:`path-${relationship.id}`,d:path,fill:"none",stroke:lineColor,strokeWidth:d.w(1.5),strokeDasharray:relationship.identifying?void 0:`${d.s(5)} ${d.s(4)}`,"data-vizmatic-graph-edge-id":encodeURIComponent(relationship.id),"data-vizmatic-graph-edge-from":encodeURIComponent(relationship.from.entity),"data-vizmatic-graph-edge-to":encodeURIComponent(relationship.to.entity),"data-vizmatic-graph-edge-label":encodeURIComponent(relationship.label??""),"data-vizmatic-graph-edge-title":encodeURIComponent(relationshipText(relationship))}),cardinalityGlyph(relationship.from.cardinality,points[0],points[1],lineColor,c.bg,lineScale,`from-${relationship.id}`),cardinalityGlyph(relationship.to.cardinality,points.at(-1),points.at(-2),lineColor,c.bg,lineScale,`to-${relationship.id}`)]});return React12.createElement("div",{role:"img","aria-label":svgTitle,"data-vizmatic-svg-id":id,"data-vizmatic-svg-title":svgTitle,"data-vizmatic-svg-description":[description,schemaSummary].filter(Boolean).join(" "),style:{display:"flex",position:"relative",flexShrink:0,width:resolvedWidth,height:resolvedHeight}},visibleTitle&&React12.createElement("div",{style:{position:"absolute",left:padding,top:padding,fontFamily:c.fontSans,fontSize:d.type.heading,fontWeight:600,color:c.textPrimary}},visibleTitle),React12.createElement("svg",{width:resolvedWidth,height:resolvedHeight,viewBox:`0 0 ${resolvedWidth} ${resolvedHeight}`,style:{position:"absolute",left:0,top:0}},...paths),...labels,...entities.map(entity=>{const node=nodeById.get(entity.id),measure=measures.get(entity.id);const keyColor=getReadableToneColor(entity.tone??"blue",c,c.bgCard,c.bgCard);return React12.createElement("div",{key:entity.id,"data-vizmatic-graph-node-id":entity.id,"data-vizmatic-graph-node-label":entity.label??entity.id,"data-vizmatic-graph-node-detail":entity.attributes.map(attributeDescription).join("; "),style:{position:"absolute",left:node.cx-node.width/2,top:node.cy-node.height/2,display:"flex",flexDirection:"column",width:node.width,height:node.height,border:`1px solid ${c.borderLight}`,borderRadius:d.r(4),backgroundColor:c.bgCard,overflow:"hidden"}},React12.createElement("div",{style:{display:"flex",alignItems:"center",height:headerHeight,flexShrink:0,padding:`0 ${inset}px`,fontFamily:c.fontSans,fontSize:headerSize,fontWeight:600,color:keyColor,backgroundColor:c.bgCardAlt,borderBottom:`1px solid ${c.borderLight}`}},entity.label??entity.id),...entity.attributes.map((attribute2,index)=>React12.createElement("div",{key:attribute2.name,style:{display:"flex",alignItems:"center",height:measure.rowHeights[index],flexShrink:0,padding:`0 ${inset}px`,gap:inset,fontFamily:c.fontMono,fontSize:textSize,color:c.textPrimary}},React12.createElement("span",{style:{width:keyWidth-inset,flexShrink:0,color:keyColor}},[attribute2.primaryKey&&"PK",attribute2.foreignKey&&"FK",attribute2.unique&&"UQ"].filter(Boolean).join(" ")),React12.createElement("span",{style:{flexGrow:1,whiteSpace:"nowrap"}},attribute2.name),React12.createElement("span",{style:{width:measure.typeWidth,flexShrink:0,textAlign:"right",color:c.textSecondary}},attribute2.type+(attribute2.nullable?"?":"")))),!entity.attributes.length&&React12.createElement("div",{style:{display:"flex",alignItems:"center",padding:`0 ${inset}px`,height:measure.rowHeights[0],fontSize:textSize,color:c.textSecondary,fontFamily:c.fontSans}},"No attributes shown"))}),showLegend&&React12.createElement("div",{style:{position:"absolute",left:padding,right:padding,bottom:padding,display:"flex",flexDirection:"column",gap:d.s(5),fontSize:textSize,lineHeight:1.3,fontFamily:c.fontSans,color:c.textSecondary}},...legendLines.map(line=>React12.createElement("div",{key:line,style:{display:"flex",whiteSpace:"nowrap",flexShrink:0}},line))))}Object.defineProperty(EntityRelationshipDiagram,SVG_ACCESSIBILITY_COMPONENT,{value:true});var blockLabels={embedding:"Embedding",attention:"Attention",norm:"Norm",mlp:"MLP",residual:"Residual",router:"Router",output:"Output",custom:"Block"};var blockTones={embedding:"cyan",attention:"purple",norm:"neutral",mlp:"blue",residual:"warm",router:"pink",output:"green",custom:"ocean"};var blockIcons={embedding:"layers",attention:"network",norm:"tool",mlp:"code",residual:"git",router:"gateway",output:"check",custom:"spark"};var routeTones={activation:"blue",residual:"warm","kv-cache":"cyan",expert:"pink",collective:"purple"};var blockKinds=["embedding","attention","norm","mlp","residual","router","output","custom"];var routeKinds=["activation","residual","kv-cache","expert","collective"];function assertIdentifier2(id,what){if(typeof id!=="string"||id.trim().length===0){throw new Error(`TransformerTopology ${what} id must be a non-empty string.`)}}function assertUniqueIdentifier2(id,seen,what){assertIdentifier2(id,what);if(seen.has(id))throw new Error(`TransformerTopology received duplicate ${what} id "${id}".`);seen.add(id)}function isTensorShapeArray(shape){return Array.isArray(shape)}function formatTensorShape(shape){if(shape==null)return void 0;if(typeof shape==="string")return shape;const dimensions2=isTensorShapeArray(shape)?shape:shape.dims;const label=isTensorShapeArray(shape)?void 0:shape.label;const formatted=dimensions2?.length?`[${dimensions2.join(" \xD7 ")}]`:void 0;const base=label??formatted;if(!base)return void 0;const metadata=!isTensorShapeArray(shape)?[shape.dtype,shape.layout].filter(Boolean).join(" \xB7 "):"";return metadata?`${base} \xB7 ${metadata}`:base}function resolveBlockKind(block){const kind=block.kind;if(kind==null||!blockKinds.includes(kind)){throw new Error(`TransformerTopology block "${block.id}" must define kind as "embedding", "attention", "norm", "mlp", "residual", "router", "output", or "custom".`)}return kind}function resolveRouteKind(route){const kind=route.kind??"activation";if(!routeKinds.includes(kind)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" must use kind "activation", "residual", "kv-cache", "expert", or "collective".`)}return kind}function resolveRepeat(block){const repeat=block.repeat??1;if(!Number.isInteger(repeat)||repeat<1){throw new Error(`TransformerTopology block "${block.id}" repeat must be a positive integer.`)}return repeat}function blockShapeText(block){const shape=block.shape;const input=formatTensorShape(block.inputShape);const output=formatTensorShape(block.outputShape);const primary=formatTensorShape(shape);if(input||output){return[input,output&&input?`\u2192 ${output}`:output].filter(Boolean).join(" ")}return primary}function blockDetail(block,kind,repeat){const shape=blockShapeText(block);const repetition=repeat>1?`\xD7${repeat}`:void 0;if(block.detail!=null){if(typeof block.detail==="string"){return[block.detail,repetition,shape].filter(Boolean).join(" \xB7 ")}return block.detail}return[repetition,shape,repeat===1?blockLabels[kind].toUpperCase():void 0].filter(Boolean).join(" \xB7 ")||void 0}function routeShapeText(route){return formatTensorShape(route.shape)}function routeLabel(route,kind){if(route.label!=null)return route.label;const kindLabel=kind==="kv-cache"?"KV cache":kind;const qualifiers=[kindLabel,route.expert==null?void 0:`expert ${route.expert}`,route.collective,routeShapeText(route)].filter(Boolean);return qualifiers.join(" \xB7 ")}function graphRouteKind(kind){if(kind==="activation"||kind==="expert")return"data";if(kind==="kv-cache")return"event";return"dependency"}function graphRouteStyle(kind){if(kind==="kv-cache")return"dotted";if(kind==="residual"||kind==="collective")return"dashed";return"solid"}function validateTransformerSpec(blocks,routes,expandRepeats){const blockIds=new Set;const repeatCounts=new Map;for(const block of blocks){assertUniqueIdentifier2(block.id,blockIds,"block");resolveBlockKind(block);repeatCounts.set(block.id,resolveRepeat(block))}const routeIds=new Set;const graphIds=new Set(blockIds);if(expandRepeats){for(const block of blocks){const repeat=repeatCounts.get(block.id)??1;if(repeat===1)continue;for(let index=1;index<=repeat;index+=1){const expandedId=`${block.id}-${index}`;if(graphIds.has(expandedId)){throw new Error(`TransformerTopology repeated block "${block.id}" generates duplicate node id "${expandedId}".`)}graphIds.add(expandedId)}}}for(const route of routes){if(route.id!=null)assertUniqueIdentifier2(route.id,routeIds,"route");if(!blockIds.has(route.from)||!blockIds.has(route.to)){throw new Error(`TransformerTopology route "${route.from}" -> "${route.to}" references a missing block.`)}resolveRouteKind(route)}return repeatCounts}function expandedNodeId(id,repeat,index){return repeat>1?`${id}-${index+1}`:id}function expandedRouteEndpoints(route,repeatCounts,expandRepeats){if(!expandRepeats)return[{from:route.from,to:route.to}];const fromRepeat=repeatCounts.get(route.from)??1;const toRepeat=repeatCounts.get(route.to)??1;if(route.from===route.to&&fromRepeat>1){return Array.from({length:fromRepeat-1},(_,index)=>({from:expandedNodeId(route.from,fromRepeat,index),to:expandedNodeId(route.to,toRepeat,index+1)}))}return[{from:expandedNodeId(route.from,fromRepeat,fromRepeat-1),to:expandedNodeId(route.to,toRepeat,0)}]}function compileTransformer(spec){const routes=spec.routes??[];const expandRepeats=spec.expandRepeats??false;const repeatCounts=validateTransformerSpec(spec.blocks,routes,expandRepeats);const nodes=[];for(const block of spec.blocks){const kind=resolveBlockKind(block);const repeat=repeatCounts.get(block.id)??1;const count=expandRepeats?repeat:1;for(let index=0;index<count;index+=1){const id=expandRepeats?expandedNodeId(block.id,repeat,index):block.id;const label=block.label??blockLabels[kind];const repetitionDetail=expandRepeats&&repeat>1?[blockDetail(block,kind,repeat),`${index+1}/${repeat}`].filter(Boolean).join(" \xB7 "):blockDetail(block,kind,repeat);nodes.push({id,label,detail:repetitionDetail,href:block.href,title:block.title,x:block.x,y:block.y,tone:block.tone??blockTones[kind],muted:block.muted,width:block.width,height:block.height,icon:block.icon??blockIcons[kind],iconSize:block.iconSize})}}const edges=[];for(const route of routes){const kind=resolveRouteKind(route);const endpoints=expandedRouteEndpoints(route,repeatCounts,expandRepeats);for(const[index,endpoint2]of endpoints.entries()){edges.push({id:route.id==null?void 0:endpoints.length===1?route.id:`${route.id}-${index+1}`,from:endpoint2.from,to:endpoint2.to,tone:route.tone??routeTones[kind],muted:route.muted,kind:graphRouteKind(kind),style:route.style??graphRouteStyle(kind),arrow:route.arrow??(kind==="residual"?"both":"forward"),label:routeLabel(route,kind),href:route.href,title:route.title})}}return{nodes,edges,ariaLabel:spec.ariaLabel??"Transformer topology diagram"}}function TransformerTopology({c,blocks,routes,expandRepeats=false,ariaLabel="Transformer topology diagram",...graphProps}){const compiled=compileTransformer({blocks,routes,expandRepeats,ariaLabel});return GraphDiagram({...graphProps,c,nodes:compiled.nodes,edges:compiled.edges,ariaLabel:compiled.ariaLabel})}Object.defineProperty(TransformerTopology,SVG_ACCESSIBILITY_COMPONENT,{value:true});import React13 from"react";function Matrix({data,c,rowLabels,colLabels,labels,title,cellSize:cellSizeProp,cellWidth,cellHeight,rowLabelWidth,format="decimal",colorize=true,colorScale="heat",fontSize:fontSizeProp,highlightRow,highlightCol,highlightCell,highlightColor=c.info,colorDomain,...accessibility}){const cellSize=cellSizeProp??densityOf(c).f(38);const fontSize=fontSizeProp??densityOf(c).type.small;if(!Number.isFinite(fontSize)||fontSize<=0){throw new Error("Matrix fontSize must be a positive finite number")}if(highlightRow!==void 0&&(!Number.isInteger(highlightRow)||highlightRow<0||highlightRow>=data.length)){throw new Error("Matrix highlightRow must be an integer row index inside the data")}if(highlightCol!==void 0&&(!Number.isInteger(highlightCol)||highlightCol<0||!data.some(row=>Object.hasOwn(row,highlightCol)))){throw new Error("Matrix highlightCol must be an integer column index inside the data")}if(highlightCell!==void 0){if(!highlightCell||!Number.isInteger(highlightCell.row)||!Number.isInteger(highlightCell.col)||highlightCell.row<0||highlightCell.row>=data.length||highlightCell.col<0||!Object.hasOwn(data[highlightCell.row]??[],highlightCell.col)){throw new Error("Matrix highlightCell must point to a cell inside the data")}}if(highlightColor!==c.info){try{compositeColor(highlightColor,c.bgCard)}catch{throw new Error("Matrix highlightColor must be a valid CSS color")}}if(colorDomain!==void 0){if(!Array.isArray(colorDomain)||colorDomain.length!==2||!Number.isFinite(colorDomain[0])||!Number.isFinite(colorDomain[1])||colorDomain[0]>=colorDomain[1]){throw new Error("Matrix colorDomain must contain finite [min, max] values where min is less than max")}for(const row of data){for(let columnIndex=0;columnIndex<row.length;columnIndex+=1){if(!Number.isFinite(row[columnIndex])){throw new Error("Matrix data must contain only finite values when colorDomain is set")}}}}const resolvedCellWidth=cellWidth??cellSize;const resolvedCellHeight=cellHeight??cellSize;const resolvedRowLabelWidth=rowLabelWidth??cellSize;const formatValue=v=>{if(format==="percent")return`${Math.round(v*100)}%`;if(format==="integer")return`${Math.round(v)}`;return v.toFixed(2)};const cellColor=value=>{const colorValue2=colorDomain?Math.max(0,Math.min(1,(value-colorDomain[0])/(colorDomain[1]-colorDomain[0]))):value;if(colorScale==="heat")return heatColor(colorValue2);if(colorValue2<.34)return c.bgHover;if(colorValue2<.67)return c.infoDark;return c.positiveDark};const cellDescriptions=data.flatMap((row,rowIndex)=>row.map((value,columnIndex)=>{const label=labels?.[rowIndex]?.[columnIndex];const text=typeof label==="string"||typeof label==="number"?label:formatValue(value);return`${rowLabels?.[rowIndex]??`Row ${rowIndex+1}`}, ${colLabels?.[columnIndex]??`column ${columnIndex+1}`}: ${text}`}));return React13.createElement("div",{...chartAccessibilityAttributes({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Matrix",description:chartDescription(accessibility.description,cellDescriptions)}),style:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:densityOf(c).s(8)}},title&&React13.createElement("div",{style:{...typeOf(c,"label"),color:c.textPrimary}},title),React13.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(2)}},colLabels&&React13.createElement("div",{style:{display:"flex",gap:densityOf(c).s(2),marginLeft:rowLabels?resolvedRowLabelWidth+4:0}},...colLabels.map((label,i)=>React13.createElement("div",{key:`col-${i}`,style:{width:resolvedCellWidth,textAlign:"center",fontSize,fontWeight:400,color:c.textMuted,fontFamily:c.fontSans}},label))),...data.map((row,ri)=>React13.createElement("div",{key:`row-${ri}`,style:{display:"flex",gap:densityOf(c).s(2),alignItems:"center"}},rowLabels&&React13.createElement("div",{style:{width:resolvedRowLabelWidth,textAlign:"right",paddingRight:4,fontSize,fontWeight:400,color:c.textMuted,fontFamily:c.fontSans}},rowLabels[ri]),...row.map((value,ci)=>{const baseBackgroundColor=colorize?cellColor(value):c.bgCard;const highlighted=ri===highlightRow||ci===highlightCol;const backgroundColor=highlighted?compositeColor(withColorAlpha(highlightColor,.24),baseBackgroundColor):baseBackgroundColor;const exactCell=ri===highlightCell?.row&&ci===highlightCell?.col;return React13.createElement("div",{key:`cell-${ri}-${ci}`,style:{width:resolvedCellWidth,height:resolvedCellHeight,display:"flex",alignItems:"center",justifyContent:"center",backgroundColor,borderRadius:densityOf(c).r(3),...exactCell?{boxShadow:`inset 0 0 0 3px ${highlightColor}`}:highlighted?{boxShadow:`inset 0 0 0 1px ${withColorAlpha(highlightColor,.88)}`}:{},fontSize,fontWeight:400,color:colorize||highlighted?getReadableTextColor(backgroundColor,c):c.textPrimary,fontFamily:"JetBrains Mono"}},labels?.[ri]?.[ci]??formatValue(value))})))))}function Heatmap({data,xLabels,yLabels,c,labels,title,cellSize=52,cellWidth,cellHeight,rowLabelWidth,colorScale,fontSize,highlightRow,highlightCol,highlightCell,highlightColor,colorDomain,...accessibility}){return Matrix({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Heatmap",data,colLabels:xLabels,rowLabels:yLabels,c,labels,title,colorize:true,cellSize,cellWidth,cellHeight,rowLabelWidth,colorScale,fontSize,highlightRow,highlightCol,highlightCell,highlightColor,colorDomain})}function TiledMatrix({rows,cols,c,ariaLabel,regions=[],title,subtitle,cellSize=24,gap:gapProp,tone="blue",muted=false,crossedOut=false,id,description}){const gap=gapProp??densityOf(c).s(3);const safeRows=Math.max(1,Math.floor(rows));const safeCols=Math.max(1,Math.floor(cols));const baseAccent=getToneColor(tone,c);const cellRows=Array.from({length:safeRows},(_,row)=>React13.createElement("div",{key:`tiled-matrix-row-${row}`,style:{display:"flex",gap}},...Array.from({length:safeCols},(_2,col)=>{const regionIndex=regions.findIndex(region2=>row>=region2.rowStart&&row<region2.rowEnd&&col>=region2.colStart&&col<region2.colEnd);const region=regionIndex>=0?regions[regionIndex]:void 0;const accent=getToneColor(region?.tone??tone,c);return React13.createElement("div",{key:`tiled-matrix-cell-${row}-${col}`,"data-region":regionIndex>=0?regionIndex:void 0,style:{width:cellSize,height:cellSize,boxSizing:"border-box",borderRadius:Math.max(2,Math.min(6,Math.round(cellSize*.18))),backgroundColor:region?withColorAlpha(accent,66/255):muted?c.bgSubtle:withColorAlpha(baseAccent,15/255),border:`1px solid ${region?withColorAlpha(accent,170/255):c.borderSubtle}`,opacity:muted?.55:1}})})));const grid=React13.createElement("div",{"data-crossed-out":crossedOut?"true":void 0,style:{position:"relative",display:"flex",flexDirection:"column",gap,padding:gap,borderRadius:densityOf(c).r(10),backgroundColor:c.bgSubtle,border:`1px solid ${c.borderLight}`,...hasShadow(c)?{boxShadow:`0 8px 18px ${c.shadow}`}:{},overflow:"hidden"}},...cellRows,...crossedOut?[React13.createElement("div",{key:"cross-forward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}}),React13.createElement("div",{key:"cross-backward",style:{position:"absolute",left:"-12%",top:"50%",width:"124%",height:4,borderRadius:999,backgroundColor:c.criticalLight,transform:"rotate(-36deg)",transformOrigin:"center",boxShadow:`0 0 0 1px ${c.bgCard}`}})]:[]);return React13.createElement("div",{...chartAccessibilityAttributes({id,ariaLabel:ariaLabel??(typeof title==="string"?title:"Tiled matrix"),description:chartDescription(description,[`${safeRows} rows by ${safeCols} columns`,...regions.map((region,index)=>`Region ${index+1}: rows ${region.rowStart+1} to ${region.rowEnd+1}, columns ${region.colStart+1} to ${region.colEnd+1}`)])}),style:{display:"flex",flexDirection:"column",alignItems:"center",gap:densityOf(c).s(7)}},...compactChildren([title&&React13.createElement("div",{style:{color:muted?c.textMuted:getReadableToneColor(tone,c),fontFamily:"Inter",fontSize:densityOf(c).f(13),fontWeight:600,lineHeight:1.1,textAlign:"center"}},title),subtitle&&React13.createElement("div",{style:{color:c.textMuted,fontFamily:"JetBrains Mono",fontSize:densityOf(c).f(11),fontWeight:700,lineHeight:1.1,textAlign:"center"}},subtitle),grid]))}function DataTable({rows,c,cellWidth,firstColWidth,cellHeight,gap:gapProp,headerRows=1,headerCols=1,fontSize:fontSizeProp,math=false,align,width}){const d=densityOf(c);const gap=gapProp??d.s(14);const fontSize=fontSizeProp??d.type.small;const rowHeight=cellHeight??Math.ceil(fontSize*1.25)+d.s(7);const renderCell=cell=>math&&typeof cell==="string"?formatMathText(cell):cell;const columnCount=Math.max(0,...rows.map(row=>row.length));const columnWidth=colIndex=>{if(colIndex===0&&firstColWidth!=null)return firstColWidth;if(cellWidth!=null)return colIndex===0?firstColWidth??cellWidth:cellWidth;return Math.ceil(Math.max(d.f(24),...rows.map((row,rowIndex)=>{const cell=row[colIndex];const text=typeof cell==="string"||typeof cell==="number"?String(cell):"";const header=rowIndex<headerRows||colIndex<headerCols;return estimateTextWidth(text,fontSize,{mono:!header,weight:header?600:400})})))};const widths=Array.from({length:columnCount},(_,index)=>columnWidth(index));const alignmentOf=colIndex=>align?.[colIndex]??(colIndex<headerCols?"left":"right");return React13.createElement("div",{style:{display:"flex",flexDirection:"column",...width!=null?{width}:{}}},...rows.map((row,rowIndex)=>React13.createElement("div",{key:`${rowIndex}-${row.map(String).join("|")}`,style:{display:"flex",gap,height:rowHeight,alignItems:"center",borderBottom:`1px solid ${rowIndex===headerRows-1?c.borderLight:c.borderSubtle}`}},...row.map((cell,colIndex)=>{const isHeaderRow=rowIndex<headerRows;const isHeaderCol=colIndex<headerCols;const alignment=alignmentOf(colIndex);return React13.createElement("div",{key:`${rowIndex}-${colIndex}-${String(cell)}`,style:{...width!=null&&colIndex===0?{flex:1}:{width:widths[colIndex]},display:"flex",alignItems:"center",justifyContent:alignment==="left"?"flex-start":alignment==="right"?"flex-end":"center",color:isHeaderRow?c.textMuted:isHeaderCol?c.textPrimary:c.textSecondary,fontFamily:isHeaderRow||isHeaderCol?c.fontSans:c.fontMono,fontSize,fontWeight:isHeaderCol&&!isHeaderRow?600:400,lineHeight:1.15,...textFitStyle(alignment)}},renderCell(cell))}))))}function isGridCell(cell){return typeof cell==="object"&&cell!==null&&!React13.isValidElement(cell)&&("label"in cell||"tone"in cell||"color"in cell||"backgroundColor"in cell||"borderColor"in cell||"opacity"in cell)}function Grid({rows,c,cellWidth:cellWidthProp,cellHeight:cellHeightProp,gap:gapProp,radius:radiusProp,fontSize:fontSizeProp,math=false,headerRows=0,headerCols=0}){const cellWidth=cellWidthProp??densityOf(c).f(34);const cellHeight=cellHeightProp??densityOf(c).f(26);const gap=gapProp??densityOf(c).s(3);const radius=radiusProp??densityOf(c).r(4);const fontSize=fontSizeProp??densityOf(c).type.small;const renderCellLabel=cell=>{const label=isGridCell(cell)?cell.label:cell;return math&&typeof label==="string"?formatMathText(label):label};const cellStyle=(cell,rowIndex,colIndex)=>{const config=isGridCell(cell)?cell:{};const toneColor=config.tone?getToneColor(config.tone,c):void 0;const isHeader=rowIndex<headerRows||colIndex<headerCols;const backgroundColor=config.backgroundColor??(toneColor?withColorAlpha(toneColor,26/255):isHeader?"transparent":c.bgCard);const toneTextColor=config.tone?getReadableToneColor(config.tone,c,backgroundColor,c.bgHover):void 0;return{width:cellWidth,height:cellHeight,display:"flex",alignItems:"center",justifyContent:"center",borderRadius:radius,backgroundColor,border:`1px solid ${config.borderColor??(toneColor?withColorAlpha(toneColor,85/255):isHeader?"transparent":c.borderSubtle)}`,color:config.color??(toneTextColor??(isHeader?c.textMuted:c.textSecondary)),...config.opacity!==void 0?{opacity:config.opacity}:{},fontFamily:"JetBrains Mono",fontSize,fontWeight:400,lineHeight:1.15,...textFitStyle("center")}};return React13.createElement("div",{style:{display:"flex",flexDirection:"column",gap,alignItems:"center"}},...rows.map((row,rowIndex)=>React13.createElement("div",{key:`grid-row-${rowIndex}`,style:{display:"flex",gap}},...row.map((cell,colIndex)=>React13.createElement("div",{key:`grid-cell-${rowIndex}-${colIndex}`,style:cellStyle(cell,rowIndex,colIndex)},renderCellLabel(cell))))))}function AxisPlot({c,width,height,xMin=-1,xMax=1,yMin=-1,yMax=1,padding:paddingProp,showFrame=true,showAxes=true,showGrid=false,gridCount=5,frameRx=8,frameFill,frameStroke,axisColor,points=[],vectors=[],paths=[],xAxisLabel,yAxisLabel,children,...accessibility}){const padding=paddingProp??densityOf(c).s(18);const innerWidth=Math.max(1,width-padding*2);const innerHeight=Math.max(1,height-padding*2);const xRange=xMax===xMin?1:xMax-xMin;const yRange=yMax===yMin?1:yMax-yMin;const sx=x=>padding+(x-xMin)/xRange*innerWidth;const sy=y=>padding+innerHeight-(y-yMin)/yRange*innerHeight;const xAxisY=yMin<=0&&yMax>=0?sy(0):padding+innerHeight/2;const yAxisX=xMin<=0&&xMax>=0?sx(0):padding+innerWidth/2;const axisStroke=axisColor??c.borderLight;const gridIndexes=Array.from({length:Math.max(0,gridCount)},(_,index)=>index+1);const elements=[];if(showFrame){elements.push(SvgFrame({key:"axis-frame",x:padding/2,y:padding/2,width:width-padding,height:height-padding,rx:frameRx,c,fill:frameFill,stroke:frameStroke}))}if(showGrid&&gridCount>0){elements.push(...gridIndexes.flatMap(index=>{const x=padding+innerWidth*index/(gridCount+1);const y=padding+innerHeight*index/(gridCount+1);return[React13.createElement("line",{key:`axis-grid-x-${index}`,x1:x,y1:padding,x2:x,y2:padding+innerHeight,stroke:c.borderSubtle,strokeWidth:1,opacity:.75}),React13.createElement("line",{key:`axis-grid-y-${index}`,x1:padding,y1:y,x2:padding+innerWidth,y2:y,stroke:c.borderSubtle,strokeWidth:1,opacity:.75})]}))}if(showAxes){elements.push(React13.createElement("line",{key:"axis-x",x1:padding,y1:xAxisY,x2:padding+innerWidth,y2:xAxisY,stroke:axisStroke,strokeWidth:1.6,opacity:.85}),React13.createElement("line",{key:"axis-y",x1:yAxisX,y1:padding,x2:yAxisX,y2:padding+innerHeight,stroke:axisStroke,strokeWidth:1.6,opacity:.85}))}elements.push(...paths.flatMap((path,index)=>{if(path.points.length<2)return[];const[first,...rest]=path.points;const commands=[`M ${sx(first.x)} ${sy(first.y)}`];for(const point of rest){if(path.interpolation==="step-after"){commands.push(`H ${sx(point.x)} V ${sy(point.y)}`)}else{commands.push(`L ${sx(point.x)} ${sy(point.y)}`)}}return[React13.createElement("path",{key:`axis-path-${index}`,d:commands.join(" "),fill:"none",stroke:path.color??getToneColor(path.tone??"blue",c),strokeWidth:path.strokeWidth??3,strokeLinecap:"round",strokeLinejoin:"round",strokeDasharray:path.dashed?"8 7":void 0,opacity:path.opacity??1})]}));elements.push(...vectors.map((vector,index)=>{const color=vector.color??getToneColor(vector.tone??"blue",c);const x1=sx(vector.x1);const y1=sy(vector.y1);const x2=sx(vector.x2);const y2=sy(vector.y2);if(vector.arrow){return VectorArrow({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,arrowSize:vector.arrowSize,opacity:vector.opacity})}return VectorSegment({key:`axis-vector-${index}`,x1,y1,x2,y2,color,strokeWidth:vector.strokeWidth,opacity:vector.opacity,showStartDot:vector.showStartDot,showEndDot:vector.showEndDot,dotRadius:vector.dotRadius})}));elements.push(...points.map((point,index)=>SvgPoint({key:`axis-point-${index}`,cx:sx(point.x),cy:sy(point.y),r:point.r??5,fill:point.fill??getToneColor(point.tone??"blue",c),stroke:point.stroke,strokeWidth:point.strokeWidth,opacity:point.opacity})));elements.push(...React13.Children.toArray(children).filter(React13.isValidElement));const accessible=chartAccessibilityAttributes({...accessibility,ariaLabel:accessibility.ariaLabel??"Axis plot",description:chartDescription(accessibility.description,[`${xAxisLabel??"x"} range ${xMin} to ${xMax}, ${yAxisLabel??"y"} range ${yMin} to ${yMax}`,...points.map((point,index)=>`Point ${index+1}: x ${point.x}, y ${point.y}`),...vectors.map((vector,index)=>`Vector ${index+1}: (${vector.x1}, ${vector.y1}) to (${vector.x2}, ${vector.y2})`),...paths.map((path,index)=>`Path ${index+1}: ${path.points.map(point=>`(${point.x}, ${point.y})`).join(", ")}`)])});const svg=React13.createElement("svg",{...!xAxisLabel&&!yAxisLabel?accessible:{},width,height,viewBox:`0 0 ${width} ${height}`},...elements);if(!xAxisLabel&&!yAxisLabel)return svg;return React13.createElement("div",{...accessible,style:{position:"relative",width,height,display:"flex"}},svg,xAxisLabel&&React13.createElement("div",{key:"axis-x-label",style:{position:"absolute",left:width/2,bottom:0,width:width-padding*2,transform:"translateX(-50%)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:densityOf(c).f(11),fontWeight:750}},xAxisLabel),yAxisLabel&&React13.createElement("div",{key:"axis-y-label",style:{position:"absolute",left:0,top:height/2,width:height-padding*2,transform:"translate(-50%, -50%) rotate(-90deg)",textAlign:"center",color:c.textMuted,fontFamily:"Inter",fontSize:densityOf(c).f(11),fontWeight:750}},yAxisLabel))}import React14 from"react";var chartPalette=["primary","warning","positive","violet","info","accent","critical"];function isColorName(value){return chartPalette.includes(value)||value==="neutral"||value==="secondary"}function chartColor(color,c,index=0){const resolved=color??chartPalette[index%chartPalette.length];if(!isColorName(resolved))return resolved;return getReadableColor(resolved,c)}function formatChartValue(value,format="decimal"){if(typeof format==="function")return format(value);if(format==="percent")return`${Math.round(value*100)}%`;if(format==="integer")return`${Math.round(value)}`;if(format==="compact"){const magnitude=Math.abs(value);if(magnitude>=999950)return`${(value/1e6).toFixed(1)}M`;if(magnitude>=999.95)return`${(value/1e3).toFixed(1)}k`;return`${Math.round(value)}`}return Number.isInteger(value)?`${value}`:value.toFixed(2)}function chartDomain(values,min,max){const rawMin=min??Math.min(0,...values);const rawMax=max??Math.max(...values,1);const range=rawMax===rawMin?1:rawMax-rawMin;return{min:rawMin,max:rawMax,range}}function chartTicks(min,max,count=4){if(count<=1||max===min)return[min];const step=(max-min)/(count-1);return Array.from({length:count},(_,index)=>min+step*index)}function niceChartScale(values,min,max,count=4){const domain=chartDomain([...values],min,max);if(min!==void 0&&max!==void 0)return{domain,ticks:chartTicks(domain.min,domain.max,count)};const span=domain.max-domain.min;const rough=span/Math.max(1,count-1);const power=Math.pow(10,Math.floor(Math.log10(rough||1)));const unit=rough/power;const step=(unit<=1?1:unit<=2?2:unit<=2.5?2.5:unit<=5?5:10)*power;const low=min??Math.floor(domain.min/step+1e-9)*step;const high=max??Math.ceil(domain.max/step-1e-9)*step;const ticks=[];for(let tick=low;tick<=high+step*1e-6;tick+=step)ticks.push(Math.round(tick/step)*step);return{domain:{min:low,max:high,range:high-low||1},ticks:ticks.length>1?ticks:chartTicks(low,high,count)}}function axisTextStyle(c){return{fontFamily:c.fontSans,fontSize:densityOf(c).type.micro,fontWeight:400,color:c.textMuted,lineHeight:1}}function createPlotArea(width,height,margin){const innerWidth=Math.max(1,width-margin.left-margin.right);const innerHeight=Math.max(1,height-margin.top-margin.bottom);return{width,height,margin,x:margin.left,y:margin.top,right:width-margin.right,bottom:height-margin.bottom,innerWidth,innerHeight}}function scaleToRange(value,min,range,outputStart,outputLength){return outputStart+(value-min)/range*outputLength}function xInPlot(value,domain,plot){return scaleToRange(value,domain.min,domain.range,plot.x,plot.innerWidth)}function yInPlot(value,domain,plot){return plot.y+plot.innerHeight-(value-domain.min)/domain.range*plot.innerHeight}function chartLabel(key,text,x,y,c,options={}){const align=options.align??"center";const width=options.width??72;const fontSize=options.fontSize??densityOf(c).type.micro;const labelHeight=options.height??Math.ceil(fontSize*1.4);let left=x;let top=y;let transform2=options.transform??(align==="center"?"translate(-50%, -50%)":align==="right"?"translate(-100%, -50%)":"translate(0, -50%)");if(options.bounds){const padding=options.bounds.padding??4;const idealLeft=align==="center"?x-width/2:align==="right"?x-width:x;const idealTop=y-labelHeight/2;left=clamp(idealLeft,options.bounds.x+padding,options.bounds.x+options.bounds.width-width-padding);top=clamp(idealTop,options.bounds.y+padding,options.bounds.y+options.bounds.height-labelHeight-padding);transform2=void 0}return React14.createElement("div",{key,style:{position:"absolute",left,top,width,...transform2!==void 0?{transform:transform2}:{},display:"flex",justifyContent:align==="right"?"flex-end":align==="left"?"flex-start":"center",...textFitStyle(align),pointerEvents:"none",...axisTextStyle(c),color:options.color??c.textMuted,fontFamily:options.fontFamily??c.fontSans,fontWeight:options.fontWeight??400,fontSize,lineHeight:1.15}},text)}function pointLabelPlacement(x,y,plot,index,width=70){const nearTop=y<plot.y+58;const nearBottom=y>plot.bottom-34;const nearLeft=x<plot.x+76;const nearRight=x>plot.right-76;const align=nearLeft?"left":nearRight?"right":"center";const verticalOffset=nearTop?18:nearBottom?-18:index%2===0?-16:18;return{x,y:y+verticalOffset,align,width,bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:4}}}function ChartFrame(props){return React14.createElement(ChartFrameContent,props)}function ChartFrameContent({children,c,title,subtitle,legend,footer,width="100%",height,padding:paddingProp,framed=false,id,ariaLabel,description}){const d=densityOf(c);const padding=paddingProp??(framed?d.s(14):0);return React14.createElement("div",{...chartAccessibilityAttributes({id,ariaLabel:ariaLabel??title??"Chart",description:[subtitle,description].filter(Boolean).join(" ")}),style:{width,...height?{height}:{},boxSizing:"border-box",display:"flex",flexDirection:"column",gap:d.s(8),padding,...framed?{borderRadius:d.r(8),border:`1px solid ${c.borderSubtle}`,backgroundColor:c.bgCard}:{}}},(title||subtitle)&&React14.createElement("div",{style:{display:"flex",flexDirection:"column",gap:d.s(2),minWidth:0,maxWidth:"100%"}},title&&React14.createElement("div",{style:{...typeOf(c,"label"),...textFitStyle(),color:c.textPrimary,fontWeight:600}},title),subtitle&&React14.createElement("div",{style:{...typeOf(c,"tiny"),...textFitStyle(),color:c.textSecondary,lineHeight:1.35}},subtitle)),children,(legend||footer)&&React14.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:legend?"space-between":"flex-end",gap:d.s(12)}},legend&&React14.createElement("div",{style:{display:"flex",alignItems:"center",gap:d.s(12),flexWrap:"wrap",minWidth:0}},...legend.map((item,index)=>React14.createElement("div",{key:`${item.label}-${index}`,style:{display:"flex",alignItems:"center",gap:d.s(6),minWidth:0}},React14.createElement("span",{style:{width:d.f(12),height:Math.max(2,d.w(2)),backgroundColor:chartColor(item.color,c,index),display:"flex"}}),React14.createElement("span",{style:{...typeOf(c,"tiny"),...textFitStyle(),color:c.textSecondary}},item.label)))),footer&&React14.createElement("div",{style:{...typeOf(c,"tiny"),...textFitStyle("right"),color:c.textMuted}},footer)))}Object.defineProperty(ChartFrameContent,CHART_FRAME_COMPONENT,{value:true});function polarPoint(cx,cy,radius,angleDegrees){const radians=angleDegrees*Math.PI/180;return{x:cx+radius*Math.cos(radians),y:cy+radius*Math.sin(radians)}}function donutArcPath(cx,cy,outerRadius,innerRadius,startAngle,endAngle){const span=Math.min(359.99,Math.max(.01,endAngle-startAngle));const safeEnd=startAngle+span;const outerStart=polarPoint(cx,cy,outerRadius,startAngle);const outerEnd=polarPoint(cx,cy,outerRadius,safeEnd);const innerEnd=polarPoint(cx,cy,innerRadius,safeEnd);const innerStart=polarPoint(cx,cy,innerRadius,startAngle);const largeArc=span>180?1:0;return[`M ${outerStart.x} ${outerStart.y}`,`A ${outerRadius} ${outerRadius} 0 ${largeArc} 1 ${outerEnd.x} ${outerEnd.y}`,`L ${innerEnd.x} ${innerEnd.y}`,`A ${innerRadius} ${innerRadius} 0 ${largeArc} 0 ${innerStart.x} ${innerStart.y}`,"Z"].join(" ")}function validateNonNegativeSegments(segments,chartName){let total=0;for(const segment of segments){if(!Number.isFinite(segment.value)||segment.value<0){throw new RangeError(`${chartName} values must be finite, non-negative numbers.`)}total+=segment.value;if(!Number.isFinite(total)){throw new RangeError(`${chartName} total must be finite.`)}}return total}function pieSectorPath(cx,cy,radius,startAngle,endAngle){const span=endAngle-startAngle;const start=polarPoint(cx,cy,radius,startAngle);if(span>=359.999){const opposite=polarPoint(cx,cy,radius,startAngle+180);return[`M ${cx} ${cy}`,`L ${start.x} ${start.y}`,`A ${radius} ${radius} 0 1 1 ${opposite.x} ${opposite.y}`,`A ${radius} ${radius} 0 1 1 ${start.x} ${start.y}`,"Z"].join(" ")}const end=polarPoint(cx,cy,radius,endAngle);const largeArc=span>180?1:0;return`M ${cx} ${cy} L ${start.x} ${start.y} A ${radius} ${radius} 0 ${largeArc} 1 ${end.x} ${end.y} Z`}function PieChart({segments,c,title,subtitle,width=360,height=240,size,format="decimal",showLegend=true,footer,...accessibility}){const total=validateNonNegativeSegments(segments,"PieChart");const positiveSegments=segments.filter(segment=>segment.value>0);const resolvedSize=size??Math.min(184,Math.max(132,height-44),Math.max(132,width*.5));const radius=resolvedSize/2-2;const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const paths=positiveSegments.map((segment,index)=>{const span=total>0?segment.value/total*360:0;const start=cursor;const end=index===positiveSegments.length-1?270:cursor+span;cursor+=span;return React14.createElement("path",{key:`pie-segment-${segment.label}-${index}`,d:pieSectorPath(cx,cy,radius,start,end),fill:chartColor(segment.color,c,index),stroke:c.bgCard,strokeWidth:positiveSegments.length>1?2:0,"data-pie-label":segment.label,"data-pie-value":segment.value,"data-pie-share":total>0?segment.value/total:0})});const legend=showLegend&&positiveSegments.length>0&&React14.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(8),flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>{const formattedValue=formatChartValue(segment.value,format);const share=formatChartValue(segment.value/total,"percent");const label=segment.valueLabel??(format==="percent"?formattedValue:`${formattedValue} \xB7 ${share}`);return React14.createElement("div",{key:`pie-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:8,minWidth:0}},React14.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:densityOf(c).r(3),backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React14.createElement("span",{style:{...typeOf(c,"tiny"),...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React14.createElement("span",{style:{...typeOf(c,"tiny"),color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:600,flexShrink:0}},label))}));return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Pie chart",description:chartDescription(accessibility.description,valueDescriptions(segments,format)),c,title,subtitle,footer,width,children:React14.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:densityOf(c).s(18),minHeight:resolvedSize,width:"100%"}},React14.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`,role:"img","aria-label":title??"Pie chart"},positiveSegments.length===0?React14.createElement("circle",{cx,cy,r:radius,fill:"none",stroke:c.borderLight,strokeWidth:2}):paths),legend)})}function DonutChart({segments,c,title,subtitle,width=360,height=230,size,thickness,format="decimal",centerLabel,centerValue,showLegend=true,footer,...accessibility}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);const resolvedSize=size??Math.min(162,Math.max(128,height-44),Math.max(128,width*.48));const resolvedThickness=thickness??Math.max(20,Math.round(resolvedSize*.18));const outerRadius=resolvedSize/2-2;const innerRadius=Math.max(18,outerRadius-resolvedThickness);const cx=resolvedSize/2;const cy=resolvedSize/2;let cursor=-90;const resolvedCenterValue=centerValue??(centerLabel!=null?formatChartValue(total,format):void 0);const paths=positiveSegments.map((segment,index)=>{const rawSpan=total>0?segment.value/total*360:0;const gap=positiveSegments.length>1?Math.min(1.5,rawSpan*.28):0;const start=cursor+gap/2;const end=cursor+rawSpan-gap/2;cursor+=rawSpan;if(end<=start)return null;return React14.createElement("path",{key:`donut-segment-${segment.label}-${index}`,d:donutArcPath(cx,cy,outerRadius,innerRadius,start,end),fill:chartColor(segment.color,c,index)})}).filter(Boolean);const legend=showLegend&&positiveSegments.length>0&&React14.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(8),flex:1,minWidth:112}},...positiveSegments.map((segment,index)=>React14.createElement("div",{key:`donut-legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:densityOf(c).s(8),minWidth:0}},React14.createElement("span",{style:{display:"flex",width:10,height:10,borderRadius:densityOf(c).r(3),backgroundColor:chartColor(segment.color,c,index),flexShrink:0}}),React14.createElement("span",{style:{...typeOf(c,"tiny"),...textFitStyle(),color:c.textSecondary,flex:1}},segment.label),React14.createElement("span",{style:{...typeOf(c,"tiny"),color:c.textPrimary,fontFamily:"JetBrains Mono",fontWeight:600,flexShrink:0}},segment.valueLabel??formatChartValue(segment.value,format)))));return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Donut chart",description:chartDescription(accessibility.description,valueDescriptions(positiveSegments,format)),c,title,subtitle,footer,width,height,padding:densityOf(c).s(16),children:React14.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:showLegend?"space-between":"center",gap:densityOf(c).s(18),minHeight:resolvedSize,width:"100%"}},React14.createElement("div",{style:{position:"relative",display:"flex",width:resolvedSize,height:resolvedSize,flexShrink:0}},React14.createElement("svg",{width:resolvedSize,height:resolvedSize,viewBox:`0 0 ${resolvedSize} ${resolvedSize}`},positiveSegments.length===0?React14.createElement("circle",{cx,cy,r:(outerRadius+innerRadius)/2,fill:"none",stroke:c.borderLight,strokeWidth:resolvedThickness}):paths),(centerLabel!=null||resolvedCenterValue!=null)&&React14.createElement("div",{style:{position:"absolute",top:resolvedThickness,left:resolvedThickness,width:Math.max(0,resolvedSize-resolvedThickness*2),height:Math.max(0,resolvedSize-resolvedThickness*2),display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:densityOf(c).s(3),textAlign:"center"}},resolvedCenterValue!=null&&React14.createElement("div",{style:{...typeOf(c,"small"),color:c.textPrimary,fontFamily:"JetBrains Mono",fontSize:densityOf(c).f(18),fontWeight:600,lineHeight:1.05,...textFitStyle("center")}},resolvedCenterValue),centerLabel!=null&&React14.createElement("div",{style:{...typeOf(c,"tiny"),color:c.textMuted,lineHeight:1.2,...textFitStyle("center")}},centerLabel))),legend)})}function valueDescriptions(data,format="decimal"){return data.map(item=>`${item.label}: ${item.valueLabel??formatChartValue(item.value,format)}`)}function StackedBar({segments,c,width=480,height=68,title,subtitle,showLegend=true,...accessibility}){const positiveSegments=segments.filter(segment=>segment.value>0);const total=positiveSegments.reduce((sum,segment)=>sum+segment.value,0);return React14.createElement("div",{...chartAccessibilityAttributes({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Stacked bar",description:chartDescription([subtitle,accessibility.description].filter(Boolean).join(" "),valueDescriptions(positiveSegments))}),style:{width,display:"flex",flexDirection:"column",gap:densityOf(c).s(10)}},(title||subtitle)&&React14.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(3)}},title&&React14.createElement("div",{style:{...typeOf(c,"label"),color:c.textPrimary,fontWeight:600}},title),subtitle&&React14.createElement("div",{style:{...typeOf(c,"tiny"),color:c.textSecondary}},subtitle)),React14.createElement("div",{style:{width,height,display:"flex",overflow:"hidden",borderRadius:densityOf(c).r(14),border:`1px solid ${c.borderLight}`,backgroundColor:c.bgCard,...hasShadow(c)?{boxShadow:`0 8px 22px ${c.shadow}`}:{}}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;const segmentWidth=width*share;const color=chartColor(segment.color,c,index);return React14.createElement("div",{key:`${segment.label}-${index}`,style:{width:`${share*100}%`,height:"100%",display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:color,...index<positiveSegments.length-1?{borderRight:`2px solid ${c.bgSubtle}`}:{}}},segmentWidth>=64&&React14.createElement("span",{style:{...typeOf(c,"small"),color:getReadableTextColor(color,c),fontWeight:600,whiteSpace:"nowrap"}},segment.valueLabel??formatChartValue(share,"percent")))})),showLegend&&React14.createElement("div",{style:{display:"flex",alignItems:"center",gap:densityOf(c).s(16),flexWrap:"wrap"}},...positiveSegments.map((segment,index)=>{const share=total>0?segment.value/total:0;return React14.createElement("div",{key:`legend-${segment.label}-${index}`,style:{display:"flex",alignItems:"center",gap:7}},React14.createElement("span",{style:{width:12,height:12,borderRadius:densityOf(c).r(4),display:"flex",backgroundColor:chartColor(segment.color,c,index)}}),React14.createElement("span",{style:{...typeOf(c,"tiny"),color:c.textSecondary}},`${segment.label} ${segment.valueLabel??formatChartValue(share,"percent")}`))})))}function BarChart({data,c,title,subtitle,width=320,height=220,min,max,format="decimal",showGrid=true,showValues=true,yAxisLabel,footer,...accessibility}){const d=densityOf(c);const margin={top:d.f(16),right:d.g(8),bottom:d.f(26),left:d.f(yAxisLabel?62:34)};const plot=createPlotArea(width,height,margin);const{domain,ticks}=niceChartScale(data.map(item=>item.value),min,max);const barSlot=plot.innerWidth/Math.max(data.length,1);const barWidth=Math.max(4,Math.min(d.f(60),barSlot*.62));const zeroY=yInPlot(0,domain,plot);const baselineY=clamp(zeroY,plot.y,plot.bottom);const barGeometries=data.map((item,index)=>{const x=plot.x+index*barSlot+(barSlot-barWidth)/2;const valueY=clamp(yInPlot(item.value,domain,plot),plot.y,plot.bottom);const distance=Math.abs(baselineY-valueY);const barHeight=Math.min(plot.innerHeight,Math.max(4,distance));const growsUp=valueY<baselineY||valueY===baselineY&&item.value>=0;const y=growsUp?Math.max(plot.y,baselineY-barHeight):Math.min(plot.bottom-barHeight,baselineY);return{item,index,x,y,barHeight,valueY,color:chartColor(item.color,c,0)}});return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Bar chart",description:chartDescription(accessibility.description,valueDescriptions(data,format)),c,title,subtitle,width,footer,children:React14.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React14.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React14.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React14.createElement("line",{key:`tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:d.stroke.hair})})),React14.createElement("line",{x1:plot.x,y1:baselineY,x2:plot.right,y2:baselineY,stroke:c.borderLight,strokeWidth:d.stroke.hair}),...barGeometries.map(({item,index,x,y,barHeight,color})=>React14.createElement("rect",{key:`${item.label}-${index}`,x,y,width:barWidth,height:barHeight,rx:d.r(3),fill:color}))),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`tick-label-${tick}`,formatChartValue(tick,format),plot.x-d.s(8),y,c,{align:"right",width:d.f(36)})}),yAxisLabel&&chartLabel("y-axis-label",yAxisLabel,d.f(9),plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,transform:"translate(-50%, -50%) rotate(-90deg)"}),...barGeometries.flatMap(({item,index,x,y,barHeight,valueY})=>[...showValues?[chartLabel(`bar-value-${index}`,item.valueLabel??formatChartValue(item.value,format),x+barWidth/2,item.value<0?y+barHeight+d.f(10):clamp(valueY-d.g(8),d.g(8),height-d.f(26)),c,{color:c.textPrimary,width:d.f(54),fontFamily:c.fontMono,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]:[],chartLabel(`bar-label-${index}`,item.label,x+barWidth/2,height-d.f(12),c,{width:barSlot})]))})}function ParetoBarChart({data,c,title,subtitle,width=520,height=300,format="integer",showGrid=true,showValues=true,footer,...accessibility}){let total=0;for(const item of data){if(!Number.isFinite(item.value)||item.value<0){throw new RangeError("ParetoBarChart values must be finite, non-negative numbers.")}total+=item.value;if(!Number.isFinite(total)){throw new RangeError("ParetoBarChart total must be finite.")}}const sorted=data.map((item,index)=>({item,index})).sort((left,right)=>right.item.value-left.item.value||left.index-right.index);const maximum=Math.max(1,...sorted.map(({item})=>item.value));const d=densityOf(c);const margin={top:d.f(20),right:d.f(38),bottom:d.f(36),left:d.f(38)};const plot=createPlotArea(width,height,margin);const valueDomain={min:0,range:maximum>Number.MAX_VALUE/1.16?maximum:maximum*1.16};const countTicks=chartTicks(0,maximum,4);const slot=plot.innerWidth/Math.max(sorted.length,1);const barWidth=Math.max(6,Math.min(68,slot*.68));let accumulated=0;const bars=sorted.map(({item,index},order)=>{accumulated+=item.value;const cumulative=total===0?0:order===sorted.length-1?1:accumulated/total;const x=plot.x+order*slot+(slot-barWidth)/2;const top=yInPlot(item.value,valueDomain,plot);return{item,sourceIndex:index,order,x,y:top,height:Math.max(0,plot.bottom-top),color:chartColor(item.color,c,order),centerX:x+barWidth/2,cumulative,cumulativeY:plot.bottom-cumulative*plot.innerHeight}});const cumulativePath=bars.map(({centerX,cumulativeY},index)=>`${index===0?"M":"L"} ${centerX.toFixed(1)} ${cumulativeY.toFixed(1)}`).join(" ");return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Pareto bar chart",description:chartDescription(accessibility.description,bars.map(({item,cumulative})=>`${item.label}: ${item.valueLabel??formatChartValue(item.value,format)}, cumulative ${formatChartValue(cumulative,"percent")}`)),c,title,subtitle,width,footer,children:React14.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React14.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,role:"img","aria-label":title??"Pareto bar chart"},showGrid&&React14.createElement("g",{},...countTicks.map(tick=>{const y=yInPlot(tick,valueDomain,plot);return React14.createElement("line",{key:`pareto-count-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React14.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:d.stroke.hair}),...bars.map(({item,order,x,y,height:barHeight,color})=>React14.createElement("rect",{key:`pareto-bar-${item.label}-${order}`,x,y,width:barWidth,height:barHeight,rx:d.r(3),fill:color,"data-pareto-bar":item.label,"data-pareto-value":item.value,"data-pareto-order":order})),cumulativePath&&React14.createElement("path",{d:cumulativePath,fill:"none",stroke:chartColor("critical",c),strokeWidth:d.w(2.5),strokeLinecap:"round",strokeLinejoin:"round","data-pareto-cumulative-line":true}),...bars.map(({item,sourceIndex,centerX,cumulativeY,cumulative,order})=>React14.createElement("circle",{key:`pareto-cumulative-point-${order}`,cx:centerX,cy:cumulativeY,r:d.g(3.5),fill:chartColor("critical",c),"data-pareto-category":item.label,"data-pareto-source-index":sourceIndex,"data-pareto-cumulative-percent":cumulative*100}))),...countTicks.map(tick=>chartLabel(`pareto-count-label-${tick}`,formatChartValue(tick,format),plot.x-d.s(8),yInPlot(tick,valueDomain,plot),c,{align:"right",width:d.f(36)})),...[0,.5,1].map(share=>chartLabel(`pareto-percent-label-${share}`,`${Math.round(share*100)}%`,plot.right+d.s(8),plot.bottom-share*plot.innerHeight,c,{align:"left",width:d.f(38)})),...bars.flatMap(({item,order,centerX,y})=>[...showValues?[chartLabel(`pareto-value-${order}`,item.valueLabel??formatChartValue(item.value,format),centerX,clamp(y-8,plot.y+8,plot.bottom-12),c,{color:c.textPrimary,fontFamily:c.fontMono,width:Math.min(slot,d.f(64)),bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight}})]:[],chartLabel(`pareto-category-${order}`,item.label,centerX,height-d.f(14),c,{width:Math.max(1,Math.min(96,slot-2)),bounds:{x:plot.x,y:plot.bottom+1,width:plot.innerWidth,height:Math.max(1,height-plot.bottom-2),padding:0}})]))})}function LineChart({series,c,title,subtitle,width=420,height=240,labels,min,max,format="decimal",showGrid=true,showPoints=true,directLabels,yAxisLabel,footer,...accessibility}){const d=densityOf(c);const direct=directLabels??series.length>1;const labelRoom=direct?Math.min(width*.28,Math.max(...series.map(item=>estimateTextWidth(item.name,d.type.micro)))+d.s(10)):d.f(12);const margin={top:d.f(12),right:labelRoom,bottom:d.f(labels?24:12),left:d.f(yAxisLabel?62:34)};const plot=createPlotArea(width,height,margin);const allValues=series.flatMap(item=>item.points);const{domain,ticks}=niceChartScale(allValues,min,max);const maxPoints=Math.max(labels?.length??0,...series.map(item=>item.points.length),1);const xInset=maxPoints<=1?0:d.g(8);const xStart=maxPoints<=1?plot.x+plot.innerWidth/2:plot.x+xInset;const xSpan=maxPoints<=1?0:Math.max(1,plot.innerWidth-xInset*2);const xStep=maxPoints<=1?0:xSpan/(maxPoints-1);const pointFor=(value,index)=>{const x=xStart+index*xStep;const markerInset=showPoints?d.g(4):2;const y=clamp(yInPlot(value,domain,plot),plot.y+markerInset,plot.bottom-markerInset);return{x,y}};const pathFor=points=>points.map((value,index)=>{const point=pointFor(value,index);return`${index===0?"M":"L"} ${point.x.toFixed(1)} ${point.y.toFixed(1)}`}).join(" ");return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Line chart",description:chartDescription(accessibility.description,series.map(item=>`${item.name}: ${item.points.map((value,index)=>`${labels?.[index]??`Point ${index+1}`}: ${formatChartValue(value,format)}`).join(", ")}`)),c,title,subtitle,width,footer,...direct?{}:{legend:series.length>1?series.map((item,index)=>({label:item.name,color:item.color??chartPalette[index%chartPalette.length]})):void 0},children:React14.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React14.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React14.createElement("g",{},...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return React14.createElement("line",{key:`line-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:d.stroke.hair})})),React14.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:d.stroke.hair}),...series.flatMap((item,seriesIndex)=>{if(item.points.length===0)return[];const color=chartColor(item.color,c,seriesIndex);const linePath=pathFor(item.points);let areaPath="";if(item.area&&item.points.length>1){const firstPoint=pointFor(item.points[0],0);const lastPoint=pointFor(item.points[item.points.length-1],item.points.length-1);areaPath=`${linePath} L ${lastPoint.x} ${plot.bottom} L ${firstPoint.x} ${plot.bottom} Z`}const elements=[];if(areaPath){elements.push(React14.createElement("path",{key:`${item.name}-area`,d:areaPath,fill:color,opacity:.1}))}elements.push(React14.createElement("path",{key:`${item.name}-line`,d:linePath,fill:"none",stroke:color,strokeWidth:d.w(2.5),strokeLinecap:"round",strokeLinejoin:"round"}));if(showPoints){elements.push(...item.points.map((value,index)=>{const point=pointFor(value,index);return React14.createElement("circle",{key:`${item.name}-point-${index}`,cx:point.x,cy:point.y,r:d.g(3),fill:color})}))}return elements})),...ticks.map(tick=>{const y=yInPlot(tick,domain,plot);return chartLabel(`line-tick-label-${tick}`,formatChartValue(tick,format),plot.x-d.s(8),y,c,{align:"right",width:d.f(36)})}),yAxisLabel&&chartLabel("line-y-axis-label",yAxisLabel,d.f(9),plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,transform:"translate(-50%, -50%) rotate(-90deg)"}),...(labels??[]).map((label,index)=>{const x=xStart+index*xStep;return chartLabel(`line-x-${label}`,label,x,height-d.g(9),c,{width:Math.max(d.f(36),xStep*.96)})}),...direct?directSeriesLabels(series,pointFor,plot,c):[])})}function directSeriesLabels(series,pointFor,plot,c){const d=densityOf(c);const height=d.type.micro*1.25;const ends=series.flatMap((item,seriesIndex)=>{if(item.points.length===0)return[];const end=pointFor(item.points[item.points.length-1],item.points.length-1);return[{item,seriesIndex,x:end.x,y:end.y}]}).sort((left,right)=>left.y-right.y);for(let i=1;i<ends.length;i+=1){ends[i].y=Math.max(ends[i].y,ends[i-1].y+height)}return ends.map(({item,seriesIndex,x,y})=>chartLabel(`line-direct-${seriesIndex}`,item.name,x+d.s(8),y,c,{align:"left",width:Math.max(8,plot.right+plot.margin.right-x-d.s(8)),color:chartColor(item.color,c,seriesIndex)}))}for(const chart of[PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}import React15 from"react";for(const chart of[ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot]){Object.defineProperty(chart,CANVAS_CHART_COMPONENT,{value:true})}function xTickLabelAlign(index,count){if(index===0)return"left";if(index===count-1)return"right";return"center"}function pointDescription(point,index,formatX,formatY,xLabel="x",yLabel="y"){return`${point.label??`Point ${index+1}`}: ${xLabel} ${formatChartValue(point.x,formatX)}, ${yLabel} ${formatChartValue(point.y,formatY)}`}function pointDescriptions(points,formatX,formatY,xLabel="x",yLabel="y"){return points.map((point,index)=>pointDescription(point,index,formatX,formatY,xLabel,yLabel))}function ScatterPlot({points,c,title,subtitle,width=380,height=260,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,footer,...accessibility}){const margin={top:20,right:24,bottom:xAxisLabel?46:34,left:yAxisLabel?54:42};const plot=createPlotArea(width,height,margin);const xDomain=chartDomain(points.map(item=>item.x),xMin,xMax);const yDomain=chartDomain(points.map(item=>item.y),yMin,yMax);const xTicks=chartTicks(xDomain.min,xDomain.max,4);const yTicks=chartTicks(yDomain.min,yDomain.max,4);const pointFor=(xValue,yValue)=>({x:xInPlot(xValue,xDomain,plot),y:yInPlot(yValue,yDomain,plot)});const pointGeometries=points.map((item,index)=>{const point=pointFor(item.x,item.y);return{item,index,point,color:chartColor(item.color,c,index)}});return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Scatter plot",description:chartDescription(accessibility.description,pointDescriptions(points,formatX,formatY,xAxisLabel,yAxisLabel)),c,title,subtitle,width,footer,children:React15.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React15.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React15.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React15.createElement("line",{key:`x-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React15.createElement("line",{key:`y-tick-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React15.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),...pointGeometries.map(({item,index,point,color})=>React15.createElement("circle",{key:`${item.label??"point"}-${index}`,cx:point.x,cy:point.y,r:item.size??7,fill:color,opacity:.92,stroke:c.bgCard,strokeWidth:2}))),...xTicks.map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:44})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:36})}),xAxisLabel&&chartLabel("scatter-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("scatter-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({item,index,point,color})=>{if(!item.label)return[];const placement=pointLabelPlacement(point.x,point.y,plot,index);return[chartLabel(`scatter-point-label-${index}`,item.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color,fontWeight:600})]}))})}function pointDominates(candidate,point,xObjective,yObjective){const xNoWorse=xObjective==="minimize"?candidate.x<=point.x:candidate.x>=point.x;const yNoWorse=yObjective==="minimize"?candidate.y<=point.y:candidate.y>=point.y;const xBetter=xObjective==="minimize"?candidate.x<point.x:candidate.x>point.x;const yBetter=yObjective==="minimize"?candidate.y<point.y:candidate.y>point.y;return xNoWorse&&yNoWorse&&(xBetter||yBetter)}function paretoFrontierIndices(points,xObjective,yObjective){const frontier=new Set;for(const candidate of points){const dominated=points.some(({point})=>pointDominates(point,candidate.point,xObjective,yObjective));if(!dominated)frontier.add(candidate.index)}return frontier}function positiveLogDomain(values,min,max){const positiveValues=values.filter(value=>Number.isFinite(value)&&value>0);const positiveMin=min!==void 0&&Number.isFinite(min)&&min>0?min:Math.min(...positiveValues,1);const fallbackMax=Math.max(...positiveValues,positiveMin*10);const positiveMax=max!==void 0&&Number.isFinite(max)&&max>0?max:fallbackMax;const safeMin=Math.max(Number.MIN_VALUE,positiveMin);const safeMax=positiveMax>safeMin?positiveMax:safeMin*10;return{min:safeMin,max:safeMax,range:Math.log(safeMax)-Math.log(safeMin)}}function logChartTicks(min,max,count=5){if(!(min>0)||!(max>min)||count<=1)return[min];const startPower=Math.ceil(Math.log10(min));const endPower=Math.floor(Math.log10(max));const powers=Array.from({length:Math.max(0,endPower-startPower+1)},(_,index)=>10**(startPower+index)).filter(value=>value>=min&&value<=max);if(powers.length>=4)return powers;return Array.from({length:count},(_,index)=>min*(max/min)**(index/(count-1)))}function ParetoChart({points,c,title,subtitle,width=640,height=360,xMin,xMax,yMin,yMax,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showGrid=true,xScale="linear",xObjective="minimize",yObjective="maximize",frontierColor,showGoal=true,goalLabel,footer,...accessibility}){const margin={top:22,right:26,bottom:xAxisLabel?48:36,left:yAxisLabel?56:44};const plot=createPlotArea(width,height,margin);const validPoints=points.map((point,index)=>({point,index})).filter(({point})=>Number.isFinite(point.x)&&Number.isFinite(point.y)&&(xScale!=="log"||point.x>0));const frontierIndices=paretoFrontierIndices(validPoints,xObjective,yObjective);const xDomain=xScale==="log"?positiveLogDomain(validPoints.map(({point})=>point.x),xMin,xMax):chartDomain(validPoints.map(({point})=>point.x),xMin,xMax);const yDomain=chartDomain(validPoints.map(({point})=>point.y),yMin,yMax);const xTicks=xScale==="log"?logChartTicks(xDomain.min,xDomain.max):chartTicks(xDomain.min,xDomain.max,5);const yTicks=chartTicks(yDomain.min,yDomain.max,5);const frontier=chartColor(frontierColor??"positive",c,0);const pointFor=(xValue,yValue)=>{const x=xScale==="log"?plot.x+(Math.log(xValue>0?xValue:xDomain.min)-Math.log(xDomain.min))/xDomain.range*plot.innerWidth:xInPlot(xValue,xDomain,plot);return{x:clamp(x,plot.x,plot.right),y:clamp(yInPlot(yValue,yDomain,plot),plot.y,plot.bottom)}};const pointGeometries=validPoints.map(({point,index})=>{const pointPosition=pointFor(point.x,point.y);const isFrontier=frontierIndices.has(index);return{point,index,x:pointPosition.x,y:pointPosition.y,color:chartColor(point.color??(isFrontier?frontier:"neutral"),c,index),frontier:isFrontier}});const frontierGeometries=pointGeometries.filter(geometry=>geometry.frontier).sort((left,right)=>left.point.x-right.point.x);const frontierPath=frontierGeometries.length>1?frontierGeometries.map((geometry,index)=>`${index===0?"M":"L"} ${geometry.x.toFixed(1)} ${geometry.y.toFixed(1)}`).join(" "):void 0;const goalText=goalLabel??`goal: ${xObjective==="minimize"?"lower x":"higher x"} \xB7 ${yObjective==="maximize"?"higher y":"lower y"}`;const goalXStart=plot.right-72;const goalY=plot.y+18;const goalXEnd=xObjective==="minimize"?goalXStart-26:goalXStart+26;const goalYStart=plot.y+52;const goalYEnd=yObjective==="maximize"?goalYStart-26:goalYStart+26;const arrowSize=5;return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Pareto frontier",description:chartDescription(accessibility.description,[`${xObjective} ${xAxisLabel??"x"}, ${yObjective} ${yAxisLabel??"y"}`,...pointGeometries.map(({point,index,frontier:frontier2})=>`${pointDescription(point,index,formatX,formatY,xAxisLabel,yAxisLabel)}, ${frontier2?"on the Pareto frontier":"dominated"}`),...pointGeometries.length?[]:["No points"]]),c,title,subtitle,width,footer,legend:[{label:"Pareto frontier",color:frontier},{label:"dominated",color:"neutral"}],children:React15.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React15.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},showGrid&&React15.createElement("g",{},...xTicks.map(tick=>{const x=pointFor(tick,yDomain.min).x;return React15.createElement("line",{key:`pareto-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React15.createElement("line",{key:`pareto-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React15.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:6}),showGoal&&React15.createElement("g",{"data-pareto-goal":true,stroke:frontier,fill:"none",strokeWidth:2,strokeLinecap:"round"},React15.createElement("line",{x1:goalXStart,y1:goalY,x2:goalXEnd,y2:goalY}),React15.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY-arrowSize}),React15.createElement("line",{x1:goalXEnd,y1:goalY,x2:goalXEnd+(xObjective==="minimize"?arrowSize:-arrowSize),y2:goalY+arrowSize}),React15.createElement("line",{x1:goalXStart,y1:goalYStart,x2:goalXStart,y2:goalYEnd}),React15.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart-arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)}),React15.createElement("line",{x1:goalXStart,y1:goalYEnd,x2:goalXStart+arrowSize,y2:goalYEnd+(yObjective==="maximize"?arrowSize:-arrowSize)})),frontierPath&&React15.createElement("path",{"data-pareto-frontier":true,d:frontierPath,fill:"none",stroke:frontier,strokeWidth:3,strokeLinecap:"round",strokeLinejoin:"round"}),...pointGeometries.filter(geometry=>!geometry.frontier).concat(pointGeometries.filter(geometry=>geometry.frontier)).map(({point,index,x,y,color,frontier:isFrontier})=>React15.createElement("circle",{key:`pareto-point-${point.label??"point"}-${index}`,"data-pareto-status":isFrontier?"frontier":"dominated",cx:x,cy:y,r:Math.max(4,Math.min(20,point.size??(isFrontier?8:7))),fill:color,opacity:isFrontier?1:.38,stroke:isFrontier?frontier:c.bgCard,strokeWidth:isFrontier?3:2}))),...xTicks.map((tick,index)=>{const x=pointFor(tick,yDomain.min).x;return chartLabel(`pareto-x-tick-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:52})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`pareto-y-tick-${tick}`,formatChartValue(tick,formatY),plot.x-8,y,c,{align:"right",width:42})}),showGoal&&chartLabel("pareto-goal-label",goalText,plot.right-2,plot.y+9,c,{align:"right",width:170,color:frontier,fontWeight:600,fontSize:densityOf(c).f(11),bounds:{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,padding:4}}),xAxisLabel&&chartLabel("pareto-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("pareto-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}),...pointGeometries.flatMap(({point,index,x,y,color,frontier:isFrontier})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`pareto-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:placement.width,bounds:placement.bounds,color:isFrontier?color:c.textMuted,fontWeight:isFrontier?850:600})]}))})}function QuadrantChart({points,regions,c,title,subtitle,width=700,height=360,xMin,xMax,yMin,yMax,xThreshold,yThreshold,xAxisLabel,yAxisLabel,formatX="decimal",formatY="decimal",showTicks=false,showGrid=false,footer,...accessibility}){const margin={top:18,right:20,bottom:xAxisLabel?showTicks?58:46:showTicks?36:24,left:yAxisLabel?showTicks?72:54:showTicks?48:24};const plot=createPlotArea(width,height,margin);const xDomain=xMin===void 0&&xMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.x),xMin,xMax);const yDomain=yMin===void 0&&yMax===void 0?{min:0,max:1,range:1}:chartDomain(points.map(point=>point.y),yMin,yMax);const resolvedXThreshold=clamp(xThreshold??xDomain.min+xDomain.range/2,xDomain.min,xDomain.max);const resolvedYThreshold=clamp(yThreshold??yDomain.min+yDomain.range/2,yDomain.min,yDomain.max);const midX=xInPlot(resolvedXThreshold,xDomain,plot);const midY=yInPlot(resolvedYThreshold,yDomain,plot);const xTicks=showTicks||showGrid?chartTicks(xDomain.min,xDomain.max,5):[];const yTicks=showTicks||showGrid?chartTicks(yDomain.min,yDomain.max,5):[];const regionEntries=[{key:"top-left",region:regions.topLeft,x:plot.x,y:plot.y,width:midX-plot.x,height:midY-plot.y},{key:"top-right",region:regions.topRight,x:midX,y:plot.y,width:plot.right-midX,height:midY-plot.y},{key:"bottom-left",region:regions.bottomLeft,x:plot.x,y:midY,width:midX-plot.x,height:plot.bottom-midY},{key:"bottom-right",region:regions.bottomRight,x:midX,y:midY,width:plot.right-midX,height:plot.bottom-midY}];const pointGeometries=points.map((point,index)=>({point,index,x:xInPlot(clamp(point.x,xDomain.min,xDomain.max),xDomain,plot),y:yInPlot(clamp(point.y,yDomain.min,yDomain.max),yDomain,plot),color:chartColor(point.color,c,index)}));return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Quadrant chart",description:chartDescription(accessibility.description,[`Thresholds: ${xAxisLabel??"x"} ${formatChartValue(resolvedXThreshold,formatX)}, ${yAxisLabel??"y"} ${formatChartValue(resolvedYThreshold,formatY)}`,...regionEntries.map(({key,region})=>`${key}: ${region.label}`),...pointDescriptions(points,formatX,formatY,xAxisLabel,yAxisLabel),...points.length?[]:["No points"]]),c,title,subtitle,width,footer,children:React15.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React15.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...regionEntries.map(({key,region,x,y,width:regionWidth,height:regionHeight},index)=>{const color=chartColor(region.color,c,index);const emphasized=region.emphasis===true;return React15.createElement("rect",{key:`quadrant-${key}`,x,y,width:regionWidth,height:regionHeight,fill:color,opacity:emphasized?.2:.1,stroke:emphasized?color:"transparent",strokeWidth:emphasized?2:0})}),showGrid&&React15.createElement("g",{},...xTicks.map(tick=>{const x=xInPlot(tick,xDomain,plot);return React15.createElement("line",{key:`quadrant-x-grid-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),...yTicks.map(tick=>{const y=yInPlot(tick,yDomain,plot);return React15.createElement("line",{key:`quadrant-y-grid-${tick}`,x1:plot.x,y1:y,x2:plot.right,y2:y,stroke:c.borderSubtle,strokeWidth:1})})),React15.createElement("rect",{x:plot.x,y:plot.y,width:plot.innerWidth,height:plot.innerHeight,fill:"transparent",stroke:c.borderLight,strokeWidth:1.2,rx:8}),React15.createElement("line",{x1:midX,y1:plot.y,x2:midX,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.4}),React15.createElement("line",{x1:plot.x,y1:midY,x2:plot.right,y2:midY,stroke:c.borderLight,strokeWidth:1.4}),...(showTicks?xTicks:[]).map(tick=>{const x=xInPlot(tick,xDomain,plot);return React15.createElement("line",{key:`quadrant-x-tick-${tick}`,x1:x,y1:plot.bottom,x2:x,y2:plot.bottom+5,stroke:c.textMuted,strokeWidth:1.2})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return React15.createElement("line",{key:`quadrant-y-tick-${tick}`,x1:plot.x-5,y1:y,x2:plot.x,y2:y,stroke:c.textMuted,strokeWidth:1.2})}),...pointGeometries.map(({point,index,x,y,color})=>React15.createElement("circle",{key:`quadrant-point-${point.label??index}`,cx:x,cy:y,r:point.size??8,fill:color,stroke:c.bgCard,strokeWidth:3}))),...regionEntries.flatMap(({key,region,x,y,width:regionWidth},index)=>{const color=chartColor(region.color,c,index);return[chartLabel(`quadrant-label-${key}`,region.label,x+regionWidth/2,y+18,c,{width:Math.max(1,regionWidth-24),color,fontFamily:"Inter",fontWeight:600,fontSize:densityOf(c).f(11)}),...region.detail?[chartLabel(`quadrant-detail-${key}`,region.detail,x+regionWidth/2,y+34,c,{width:Math.max(1,regionWidth-24),color:c.textMuted,fontSize:densityOf(c).f(11)})]:[]]}),...(showTicks?xTicks:[]).map((tick,index)=>{const x=xInPlot(tick,xDomain,plot);return chartLabel(`quadrant-x-tick-label-${tick}`,formatChartValue(tick,formatX),x,plot.bottom+18,c,{align:xTickLabelAlign(index,xTicks.length),width:54})}),...(showTicks?yTicks:[]).map(tick=>{const y=yInPlot(tick,yDomain,plot);return chartLabel(`quadrant-y-tick-label-${tick}`,formatChartValue(tick,formatY),plot.x-9,y,c,{align:"right",width:48})}),...pointGeometries.flatMap(({point,index,x,y,color})=>{if(!point.label)return[];const placement=pointLabelPlacement(x,y,plot,index,110);return[chartLabel(`quadrant-point-label-${index}`,point.label,placement.x,placement.y,c,{align:placement.align,width:110,bounds:placement.bounds,color,fontFamily:"Inter",fontWeight:600,fontSize:densityOf(c).f(11)})]}),xAxisLabel&&chartLabel("quadrant-x-axis-label",xAxisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),yAxisLabel&&chartLabel("quadrant-y-axis-label",yAxisLabel,12,plot.y+plot.innerHeight/2,c,{width:plot.innerHeight,fontFamily:"Inter",fontWeight:700,transform:"translate(-50%, -50%) rotate(-90deg)"}))})}function IntervalPlot({data,c,title,subtitle,width=640,height=220,min,max,format="decimal",axisLabel,footer,...accessibility}){const margin={top:22,right:28,bottom:axisLabel?44:30,left:96};const plot=createPlotArea(width,height,margin);const rowGap=data.length<=1?0:plot.innerHeight/data.length;const domain=chartDomain(data.flatMap(item=>[item.low,item.mid,item.high]),min,max);const ticks=chartTicks(domain.min,domain.max,5);const scaleX=value=>xInPlot(value,domain,plot);const rows=data.map((item,index)=>{const y=data.length<=1?plot.y+plot.innerHeight/2:plot.y+rowGap*index+rowGap/2;return{item,index,y,color:chartColor(item.color,c,index),lowX:scaleX(item.low),midX:scaleX(item.mid),highX:scaleX(item.high)}});return ChartFrame({...accessibility,ariaLabel:accessibility.ariaLabel??title??"Interval plot",description:chartDescription(accessibility.description,data.map(item=>`${item.label}: low ${item.lowLabel??formatChartValue(item.low,format)}, midpoint ${item.midLabel??formatChartValue(item.mid,format)}, high ${item.highLabel??formatChartValue(item.high,format)}`)),c,title,subtitle,width,footer,children:React15.createElement("div",{style:{position:"relative",width,height,display:"flex"}},React15.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...ticks.map(tick=>{const x=scaleX(tick);return React15.createElement("line",{key:`interval-tick-${tick}`,x1:x,y1:plot.y,x2:x,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:1})}),React15.createElement("line",{x1:plot.x,y1:plot.bottom,x2:plot.right,y2:plot.bottom,stroke:c.borderLight,strokeWidth:1.2}),...rows.flatMap(({item,index,y,color,lowX,midX,highX})=>[React15.createElement("line",{key:`${item.label}-range-${index}`,x1:lowX,y1:y,x2:highX,y2:y,stroke:color,strokeWidth:9,strokeLinecap:"round",opacity:.9}),React15.createElement("circle",{key:`${item.label}-mid-${index}`,cx:midX,cy:y,r:10,fill:c.bgCard,stroke:color,strokeWidth:4})])),...ticks.map((tick,index)=>{const x=scaleX(tick);return chartLabel(`interval-tick-label-${tick}`,formatChartValue(tick,format),x,height-margin.bottom+17,c,{align:xTickLabelAlign(index,ticks.length),width:48})}),axisLabel&&chartLabel("interval-axis-label",axisLabel,plot.x+plot.innerWidth/2,height-8,c,{width:plot.innerWidth,fontFamily:"Inter",fontWeight:700}),...rows.flatMap(({item,index,y,lowX,midX,highX})=>[chartLabel(`interval-row-label-${index}`,item.label,plot.x-12,y,c,{align:"right",width:84,color:c.textPrimary,fontFamily:"Inter",fontWeight:600}),chartLabel(`interval-low-${index}`,item.lowLabel??formatChartValue(item.low,format),lowX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}}),chartLabel(`interval-mid-${index}`,item.midLabel??formatChartValue(item.mid,format),midX,y-16,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height},color:c.textPrimary,fontWeight:600}),chartLabel(`interval-high-${index}`,item.highLabel??formatChartValue(item.high,format),highX,y+25,c,{width:48,bounds:{x:plot.x,y:0,width:plot.innerWidth,height}})]))})}function Badge({label,c,color="primary"}){const solidColor=getReadableColor(color,c);return React15.createElement("div",{style:{display:"flex",alignItems:"center",justifyContent:"center",backgroundColor:withColorAlpha(solidColor,32/255),color:solidColor,borderRadius:999,padding:`${densityOf(c).s(4)}px ${densityOf(c).s(12)}px`,fontSize:densityOf(c).f(11),fontWeight:600,fontFamily:"Inter",border:`1px solid ${withColorAlpha(solidColor,64/255)}`}},label)}function DotPoint({x,y,label,color,c,size=12,labelOffset}){const offX=labelOffset?.x??0;const offY=labelOffset?.y??-22;return[React15.createElement("div",{key:`dot-${label}`,style:{position:"absolute",left:x-size/2,top:y-size/2,width:size,height:size,borderRadius:"50%",backgroundColor:color,boxShadow:`0 0 14px ${withColorAlpha(color,80/255)}`,display:"flex"}}),React15.createElement("div",{key:`label-${label}`,style:{position:"absolute",left:x+offX-30,top:y+offY,fontSize:densityOf(c).f(13),fontWeight:600,color:c.textPrimary,fontFamily:"JetBrains Mono",textAlign:"center",width:60}},label)]}function DashedLine({x1,y1,x2,y2,color,dotSpacing=8,dotSize=2}){const dx=x2-x1;const dy=y2-y1;const length=Math.sqrt(dx*dx+dy*dy);const numDots=Math.max(1,Math.floor(length/dotSpacing));const dots=[];for(let i=0;i<numDots;i++){if(i%2===1)continue;const t=i/numDots;dots.push(React15.createElement("div",{key:`dash-${i}`,style:{position:"absolute",left:x1+t*dx-dotSize/2,top:y1+t*dy-dotSize/2,width:dotSize,height:dotSize,borderRadius:"50%",backgroundColor:color}}))}return dots}function Legend({items,c,title}){return React15.createElement("div",{style:{display:"flex",flexDirection:"column",gap:densityOf(c).s(10),backgroundColor:c.bgCard,borderRadius:densityOf(c).r(8),border:`1px solid ${c.borderSubtle}`,padding:`${densityOf(c).s(14)}px ${densityOf(c).s(16)}px`}},title&&React15.createElement("div",{style:{fontSize:densityOf(c).f(11),fontWeight:700,color:c.textSecondary,textTransform:"uppercase",letterSpacing:1,fontFamily:"Inter"}},title),...items.map((item,i)=>React15.createElement("div",{key:`legend-${i}`,style:{display:"flex",alignItems:"center",gap:8}},React15.createElement("div",{style:{width:16,height:item.style==="dashed"?0:2,backgroundColor:item.color,...item.style==="dashed"?{borderTop:`2px dashed ${item.color}`}:{}}}),React15.createElement("div",{style:{fontSize:densityOf(c).f(11),color:c.textMuted,fontFamily:"Inter"}},item.label))))}import React16 from"react";var CANVAS_ITEM_COMPONENT=Symbol.for("vizmatic.canvas-item");function dimension(value,name){if(value!==void 0&&(!Number.isFinite(value)||value<=0||value>8192)){throw new Error(`${name} must be a finite number greater than 0 and at most 8192.`)}return value}function Board({children,c,width=960,height=540,background}){return React16.createElement("div",{style:{display:"flex",position:"relative",width:dimension(width,"Board width"),height:dimension(height,"Board height"),overflow:"hidden",backgroundColor:background??"transparent",color:c.textPrimary}},children)}function CanvasItem({children,x,y,width,height}){if(!Number.isFinite(x)||!Number.isFinite(y))throw new Error("CanvasItem x and y must be finite numbers.");const sizedChildren=React16.Children.map(children,child=>{if(!React16.isValidElement(child))return child;if(width!==void 0&&height!==void 0&&isCanvasChart(child.type)){const chart=React16.cloneElement(child,{width:child.props.width??width,height:child.props.height??height});return React16.createElement(CanvasChartFit,{width,height,__vizmaticTextScope:child.props.__vizmaticTextScope},chart)}return React16.cloneElement(child,{...width!==void 0?{width}:{},...height!==void 0?{height}:{}})});return React16.createElement("div",{style:{display:"flex",position:"absolute",left:x,top:y,width:dimension(width,"CanvasItem width"),height:dimension(height,"CanvasItem height"),alignItems:"stretch"}},sizedChildren)}Object.defineProperty(CanvasItem,CANVAS_ITEM_COMPONENT,{value:true});import React17 from"react";var MAX_SVG_SIZE=4096;var FONT_SIZE=13;function finite(value,name){if(!Number.isFinite(value))throw new TypeError(`${name} must be finite.`);return value}function positive2(value,name){finite(value,name);if(value<=0)throw new RangeError(`${name} must be greater than zero.`);return value}function increasing(min,max,name){finite(min,`${name} minimum`);finite(max,`${name} maximum`);const range=max-min;if(!Number.isFinite(range)||range<=0)throw new RangeError(`${name} must have a finite increasing domain.`);return range}function dimensions(width,height,name,minimumHeight=360){finite(width,`${name} width`);finite(height,`${name} height`);if(width<600||height<minimumHeight)throw new RangeError(`${name} width must be at least 600 pixels and height at least ${minimumHeight} pixels.`);if(width>MAX_SVG_SIZE||height>MAX_SVG_SIZE)throw new RangeError(`${name} dimensions cannot exceed ${MAX_SVG_SIZE} pixels.`)}function bounded(items,maximum,name,minimum=0){if(!Array.isArray(items))throw new TypeError(`${name} must be an array.`);if(items.length<minimum||items.length>maximum){throw new RangeError(`${name} must contain between ${minimum} and ${maximum} items.`)}}function labelText(value,name,maxLength=80){if(typeof value!=="string"||value.trim().length===0)throw new TypeError(`${name} must be a non-empty string.`);if(value.length>maxLength)throw new RangeError(`${name} cannot exceed ${maxLength} characters.`);return value}function idValue(value,name){labelText(value,name,64);if(!/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value))throw new TypeError(`${name} must use letters, numbers, dots, underscores, colons, or hyphens.`);return value}function uniqueIds(values,name){const ids=new Set;for(const id of values){if(ids.has(id))throw new TypeError(`${name} contains duplicate id "${id}".`);ids.add(id)}}function colorValue(value,fallback,name){if(value===void 0)return fallback;if(typeof value!=="string"||value.length>64||!/^(#(?:[0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})|[a-z]{3,24}|rgba?\([0-9.,%\s]+\)|hsla?\([0-9.,%\s]+\))$/i.test(value)){throw new TypeError(`${name} must be a CSS color value.`)}return value}function textWidth(text,size=FONT_SIZE){return Math.max(size*1.6,text.length*size*.62)}function boundedTextX(preferred,width,text,anchor,margin=18,size=FONT_SIZE){const measured=textWidth(text,size);if(anchor==="start")return clamp2(preferred,margin,width-margin-measured);if(anchor==="end")return clamp2(preferred,margin+measured,width-margin);return clamp2(preferred,margin+measured/2,width-margin-measured/2)}function clamp2(value,min,max){return Math.min(max,Math.max(min,value))}var UNNAMED_TITLES=new Set(["Number line","Geometry diagram","Free-body diagram","Wave diagram"]);function svgShell({c,width,height,title,ariaLabel,description,children}){const d=densityOf(c);const overlays=[];const svgChildren=[React17.createElement("title",{key:"title"},title),React17.createElement("desc",{key:"description"},description)];for(const[index,child]of children.entries()){if(React17.isValidElement(child)&&child.type==="text"){const textProps=child.props;const text=React17.Children.toArray(textProps.children).map(part=>String(part)).join("");overlays.push(React17.createElement(SvgMathText,{key:`label-${index}`,text,x:textProps.x,y:textProps.y,fill:textProps.fill??c.textPrimary,fontFamily:textProps.fontFamily??c.fontSans,fontSize:d.f(textProps.fontSize??FONT_SIZE),fontWeight:Math.min(textProps.fontWeight??400,600),textAnchor:textProps.textAnchor??"start",dominantBaseline:"auto"}))}else{svgChildren.push(child)}}if(!UNNAMED_TITLES.has(title)){overlays.unshift(React17.createElement(SvgMathText,{key:"diagram-title",text:title,x:0,y:d.f(16),fill:c.textPrimary,fontFamily:c.fontSans,fontSize:d.type.label,fontWeight:600,textAnchor:"start",dominantBaseline:"auto"}))}return React17.createElement("div",{role:"img","aria-label":ariaLabel??title,"aria-description":description,style:{position:"relative",width,height,display:"flex",flexShrink:0}},React17.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,"aria-hidden":true,style:{position:"absolute",inset:0}},...svgChildren),...overlays)}function formatNumber(value){if(Object.is(value,-0)||value===0)return"0";if(Math.abs(value)>=1e5||Math.abs(value)<.001)return value.toExponential(2);return Number(value.toPrecision(4)).toString()}function mapNumberLine(value,min,max,width,padding=56){finite(value,"NumberLine value");const range=increasing(min,max,"NumberLine");finite(width,"NumberLine width");finite(padding,"NumberLine padding");if(padding<0)throw new RangeError("NumberLine padding cannot be negative.");positive2(width-padding*2,"NumberLine drawable width");if(value<min||value>max)throw new RangeError("NumberLine value must lie within its domain.");return padding+(value-min)/range*(width-padding*2)}function NumberLine({c,min,max,ticks,markers=[],interval,title="Number line",ariaLabel,width=720,height=400}){const range=increasing(min,max,"NumberLine");dimensions(width,height,"NumberLine",120);labelText(title,"NumberLine title",32);bounded(markers,128,"NumberLine markers");const resolvedTicks=ticks??[min,min+range/2,max].filter((value,index,all)=>all.indexOf(value)===index).map(value=>({value}));bounded(resolvedTicks,128,"NumberLine ticks");const tickValues=resolvedTicks.map((tick,index)=>{finite(tick.value,`NumberLine tick ${index} value`);if(tick.value<min||tick.value>max)throw new RangeError(`NumberLine tick ${index} must lie within its domain.`);if(tick.label!==void 0)labelText(tick.label,`NumberLine tick ${index} label`,32);return tick.value});if(new Set(tickValues).size!==tickValues.length)throw new TypeError("NumberLine ticks cannot repeat values.");uniqueIds(markers.map(marker=>idValue(marker.id,"NumberLine marker id")),"NumberLine markers");markers.forEach((marker,index)=>{finite(marker.value,`NumberLine marker ${index} value`);if(marker.value<min||marker.value>max)throw new RangeError(`NumberLine marker "${marker.id}" must lie within its domain.`);labelText(marker.label,`NumberLine marker "${marker.id}" label`,32);colorValue(marker.color,c.accent,`NumberLine marker "${marker.id}" color`)});if(interval){if(height<180)throw new RangeError("NumberLine intervals require at least 180 pixels of height.");if(interval.label&&height<220)throw new RangeError("Labeled NumberLine intervals require at least 220 pixels of height.");finite(interval.from,"NumberLine interval start");finite(interval.to,"NumberLine interval end");if(interval.from<min||interval.from>max||interval.to<min||interval.to>max||interval.from>interval.to){throw new RangeError("NumberLine interval must be ordered and lie within its domain.")}if(interval.from===interval.to&&(interval.includeFrom===false||interval.includeTo===false)){throw new RangeError("A zero-width NumberLine interval must include both endpoints.")}if(interval.label!==void 0)labelText(interval.label,"NumberLine interval label",32);colorValue(interval.color,c.info,"NumberLine interval color")}const x=value=>mapNumberLine(value,min,max,width);const axisY=Math.round(height*(interval&&height<220?.45:.56));const elements=[React17.createElement("line",{key:"axis",x1:56,y1:axisY,x2:width-56,y2:axisY,stroke:c.textSecondary,strokeWidth:densityOf(c).w(2)}),React17.createElement("path",{key:"left-arrow",d:`M 56 ${axisY} l 9 -5 v 10 z`,fill:c.textSecondary}),React17.createElement("path",{key:"right-arrow",d:`M ${width-56} ${axisY} l -9 -5 v 10 z`,fill:c.textSecondary})];if(interval){const fromX=x(interval.from);const toX=x(interval.to);const color=colorValue(interval.color,c.info,"NumberLine interval color");const includeFrom=interval.includeFrom!==false;const includeTo=interval.includeTo!==false;const intervalY=axisY+52;elements.push(React17.createElement("line",{key:"interval",x1:fromX,y1:intervalY,x2:toX,y2:intervalY,stroke:color,strokeWidth:densityOf(c).w(8),strokeLinecap:"round",opacity:.62}),React17.createElement("circle",{key:"interval-from",cx:fromX,cy:intervalY,r:7,fill:includeFrom?color:c.bgSubtle,stroke:color,strokeWidth:densityOf(c).w(3)}),React17.createElement("circle",{key:"interval-to",cx:toX,cy:intervalY,r:7,fill:includeTo?color:c.bgSubtle,stroke:color,strokeWidth:densityOf(c).w(3)}));if(interval.label){const label=interval.label;const labelX=clamp2((fromX+toX)/2,56+textWidth(label)/2,width-56-textWidth(label)/2);elements.push(React17.createElement("text",{key:"interval-label",x:labelX,y:axisY+82,textAnchor:"middle",fill:c.textSecondary,fontFamily:c.fontSans,fontSize:FONT_SIZE},label))}}for(const[index,tick]of resolvedTicks.entries()){const tickX=x(tick.value);elements.push(React17.createElement("line",{key:`tick-${index}`,x1:tickX,y1:axisY-9,x2:tickX,y2:axisY+9,stroke:c.textSecondary,strokeWidth:densityOf(c).w(2)}),React17.createElement("text",{key:`tick-label-${index}`,x:tickX,y:axisY+34,textAnchor:"middle",fill:c.textSecondary,fontFamily:c.fontMono,fontSize:12},tick.label??formatNumber(tick.value)))}markers.forEach((marker,index)=>{const markerX=x(marker.value);const color=colorValue(marker.color,c.accent,`NumberLine marker "${marker.id}" color`);const lane=index%4;const labelY=Math.max(66,axisY-54-lane*30);const labelX=clamp2(markerX,56+textWidth(marker.label,12)/2,width-56-textWidth(marker.label,12)/2);elements.push(React17.createElement("line",{key:`marker-line-${marker.id}`,x1:markerX,y1:axisY-4,x2:markerX,y2:labelY+7,stroke:color,strokeWidth:densityOf(c).w(1.5),strokeDasharray:"4 4",opacity:.8}),React17.createElement("circle",{key:`marker-point-${marker.id}`,cx:markerX,cy:axisY,r:7,fill:color,stroke:c.bgCard,strokeWidth:densityOf(c).w(2)}),React17.createElement("text",{key:`marker-label-${marker.id}`,x:labelX,y:labelY,textAnchor:"middle",fill:c.textPrimary,fontFamily:c.fontSans,fontSize:12,fontWeight:650},marker.label))});const intervalDescription=interval?` The highlighted interval is ${interval.includeFrom===false?"(":"["}${formatNumber(interval.from)}, ${formatNumber(interval.to)}${interval.includeTo===false?")":"]"}${interval.label?`, labeled ${interval.label}`:""}.`:"";return svgShell({c,width,height,title,ariaLabel,description:`A numeric axis from ${formatNumber(min)} to ${formatNumber(max)} with ${resolvedTicks.length} explicit ticks and ${markers.length} labeled markers.${intervalDescription}`,children:elements})}function geometryBounds(points){bounded(points,128,"GeometryDiagram points",1);points.forEach((point,index)=>{finite(point.x,`GeometryDiagram point ${index} x`);finite(point.y,`GeometryDiagram point ${index} y`)});const xs=points.map(({x})=>x);const ys=points.map(({y})=>y);const minX=Math.min(...xs);const maxX=Math.max(...xs);const minY=Math.min(...ys);const maxY=Math.max(...ys);const width=maxX-minX;const height=maxY-minY;if(!Number.isFinite(width)||!Number.isFinite(height))throw new RangeError("GeometryDiagram point bounds must be finite.");return{minX,maxX,minY,maxY,width,height}}function GeometryDiagram({c,points,segments=[],angles=[],title="Geometry diagram",ariaLabel,width=720,height=440}){const bounds=geometryBounds(points);dimensions(width,height,"GeometryDiagram");labelText(title,"GeometryDiagram title",32);bounded(segments,256,"GeometryDiagram segments");bounded(angles,64,"GeometryDiagram angles");uniqueIds(points.map(point=>idValue(point.id,"GeometryDiagram point id")),"GeometryDiagram points");const pointById=new Map(points.map(point=>[point.id,point]));points.forEach(point=>{if(point.label!==void 0)labelText(point.label,`GeometryDiagram point "${point.id}" label`,32)});segments.forEach((segment,index)=>{idValue(segment.from,`GeometryDiagram segment ${index} start`);idValue(segment.to,`GeometryDiagram segment ${index} end`);if(segment.from===segment.to)throw new RangeError(`GeometryDiagram segment ${index} must connect two different points.`);const from=pointById.get(segment.from);const to=pointById.get(segment.to);if(!from||!to)throw new TypeError(`GeometryDiagram segment ${index} references a missing point.`);if(from.x===to.x&&from.y===to.y)throw new RangeError(`GeometryDiagram segment ${index} has zero length.`);if(segment.label!==void 0)labelText(segment.label,`GeometryDiagram segment ${index} label`,32);colorValue(segment.color,c.secondary,`GeometryDiagram segment ${index} color`)});angles.forEach((angle,index)=>{const vertex=pointById.get(idValue(angle.vertex,`GeometryDiagram angle ${index} vertex`));const from=pointById.get(idValue(angle.from,`GeometryDiagram angle ${index} first ray`));const to=pointById.get(idValue(angle.to,`GeometryDiagram angle ${index} second ray`));if(!vertex||!from||!to)throw new TypeError(`GeometryDiagram angle ${index} references a missing point.`);if(angle.from===angle.to||angle.from===angle.vertex||angle.to===angle.vertex){throw new RangeError(`GeometryDiagram angle ${index} must use three distinct point ids.`)}const ax=from.x-vertex.x;const ay=from.y-vertex.y;const bx=to.x-vertex.x;const by=to.y-vertex.y;const lengths=Math.hypot(ax,ay)*Math.hypot(bx,by);if(!Number.isFinite(lengths)||lengths===0)throw new RangeError(`GeometryDiagram angle ${index} has a zero-length ray.`);const cross=ax*by-ay*bx;const dot=ax*bx+ay*by;if(!Number.isFinite(cross)||!Number.isFinite(dot)||Math.abs(cross)<=lengths*1e-12&&dot>0){throw new RangeError(`GeometryDiagram angle ${index} is degenerate.`)}if(angle.label!==void 0)labelText(angle.label,`GeometryDiagram angle ${index} label`,32);if(angle.radius!==void 0){positive2(angle.radius,`GeometryDiagram angle ${index} radius`);if(angle.radius>120)throw new RangeError(`GeometryDiagram angle ${index} radius cannot exceed 120 pixels.`)}colorValue(angle.color,c.accent,`GeometryDiagram angle ${index} color`)});const padding=80;const maxRange=Math.max(bounds.width,bounds.height);const scale=maxRange===0?Math.min(width-padding*2,height-padding*2):Math.min((width-padding*2)/maxRange,(height-padding*2)/maxRange);const centerX=bounds.minX/2+bounds.maxX/2;const centerY=bounds.minY/2+bounds.maxY/2;if(!Number.isFinite(centerX)||!Number.isFinite(centerY)||!Number.isFinite(scale)||scale<=0){throw new RangeError("GeometryDiagram coordinates cannot be mapped into the viewport.")}const map=point=>({x:width/2+(point.x-centerX)*scale,y:height/2-(point.y-centerY)*scale});angles.forEach((angle,index)=>{const vertex=map(pointById.get(angle.vertex));const radius=angle.radius??32;if(vertex.x-radius<22||vertex.x+radius>width-22||vertex.y-radius<40||vertex.y+radius>height-22){throw new RangeError(`GeometryDiagram angle ${index} arc would clip the viewport.`)}});const elements=[];const figureCenter=(()=>{const mapped=points.map(map);return{x:mapped.reduce((sum,point)=>sum+point.x,0)/mapped.length,y:mapped.reduce((sum,point)=>sum+point.y,0)/mapped.length}})();segments.forEach((segment,index)=>{const from=map(pointById.get(segment.from));const to=map(pointById.get(segment.to));const color=colorValue(segment.color,c.secondary,`GeometryDiagram segment ${index} color`);elements.push(React17.createElement("line",{key:`segment-${index}`,x1:from.x,y1:from.y,x2:to.x,y2:to.y,stroke:color,strokeWidth:densityOf(c).w(3),strokeDasharray:segment.dashed?"7 6":void 0,strokeLinecap:"round"}));if(segment.label){const midX=(from.x+to.x)/2,midY=(from.y+to.y)/2;const length=Math.hypot(to.x-from.x,to.y-from.y)||1;let normalX=-(to.y-from.y)/length,normalY=(to.x-from.x)/length;if(normalX*(midX-figureCenter.x)+normalY*(midY-figureCenter.y)<0){normalX=-normalX;normalY=-normalY}const halfWidth=textWidth(segment.label)/2;const clearance=8+Math.abs(normalX)*halfWidth+Math.abs(normalY)*FONT_SIZE*.45;const labelX=clamp2(midX+normalX*clearance,24+halfWidth,width-24-halfWidth);const labelY=clamp2(midY+normalY*clearance+FONT_SIZE*.35,58,height-22);elements.push(React17.createElement("text",{key:`segment-label-${index}`,x:labelX,y:labelY,textAnchor:"middle",fill:c.textSecondary,fontFamily:c.fontSans,fontSize:FONT_SIZE},segment.label))}});angles.forEach((angle,index)=>{const vertex=pointById.get(angle.vertex);const from=pointById.get(angle.from);const to=pointById.get(angle.to);const v=map(vertex);const a1=Math.atan2(from.y-vertex.y,from.x-vertex.x);let delta=Math.atan2((from.x-vertex.x)*(to.y-vertex.y)-(from.y-vertex.y)*(to.x-vertex.x),(from.x-vertex.x)*(to.x-vertex.x)+(from.y-vertex.y)*(to.y-vertex.y));if(!Number.isFinite(delta))throw new RangeError(`GeometryDiagram angle ${index} cannot be rendered.`);const radius=angle.radius??32;const samples=18;const arc=Array.from({length:samples+1},(_,sample)=>{const theta=a1+delta*sample/samples;return{x:v.x+radius*Math.cos(theta),y:v.y-radius*Math.sin(theta)}});const path=arc.map((point,part)=>`${part===0?"M":"L"} ${point.x.toFixed(2)} ${point.y.toFixed(2)}`).join(" ");const color=colorValue(angle.color,c.accent,`GeometryDiagram angle ${index} color`);elements.push(React17.createElement("path",{key:`angle-${index}`,d:path,fill:"none",stroke:color,strokeWidth:densityOf(c).w(2.5),strokeLinecap:"round"}));if(angle.label){const middle=a1+delta/2;const labelX=clamp2(v.x+(radius+18)*Math.cos(middle),28+textWidth(angle.label)/2,width-28-textWidth(angle.label)/2);const labelY=clamp2(v.y-(radius+18)*Math.sin(middle)+4,58,height-20);elements.push(React17.createElement("text",{key:`angle-label-${index}`,x:labelX,y:labelY,textAnchor:"middle",fill:c.textPrimary,fontFamily:c.fontSans,fontSize:FONT_SIZE,fontWeight:650},angle.label))}});points.forEach(point=>{const position=map(point);elements.push(React17.createElement("circle",{key:`point-${point.id}`,cx:position.x,cy:position.y,r:5.5,fill:c.primary,stroke:c.bgCard,strokeWidth:densityOf(c).w(2)}));if(point.label){const label=point.label;const labelWidth=textWidth(label);const awayX=position.x-figureCenter.x,awayY=position.y-figureCenter.y;const placeRight=awayX>=0?position.x+12+labelWidth<width-16:position.x-12-labelWidth<16;const baseX=position.x+(placeRight?12:-12);const labelX=boundedTextX(baseX,width,label,placeRight?"start":"end");const labelY=clamp2(awayY>0?position.y+FONT_SIZE+6:position.y-10,58,height-20);elements.push(React17.createElement("text",{key:`point-label-${point.id}`,x:labelX,y:labelY,textAnchor:placeRight?"start":"end",fill:c.textPrimary,fontFamily:c.fontSans,fontSize:FONT_SIZE,fontWeight:650},label))}});return svgShell({c,width,height,title,ariaLabel,description:`${points.length} explicitly defined points, ${segments.length} segments, and ${angles.length} angle arcs. Coordinates use one equal-unit scale; no geometric properties are inferred.`,children:elements})}function sumForces(forces){bounded(forces,32,"FreeBodyDiagram forces",1);let x=0;let y=0;for(const[index,force]of forces.entries()){finite(force.x,`FreeBodyDiagram force ${index} x component`);finite(force.y,`FreeBodyDiagram force ${index} y component`);x+=force.x;y+=force.y;if(!Number.isFinite(x)||!Number.isFinite(y))throw new RangeError("FreeBodyDiagram resultant components must be finite.")}const magnitude=Math.hypot(x,y);if(!Number.isFinite(magnitude))throw new RangeError("FreeBodyDiagram resultant magnitude must be finite.");return{x,y,magnitude}}function FreeBodyDiagram({c,forces,showResultant=true,showComponents=false,title="Free-body diagram",ariaLabel,width=720,height=440}){dimensions(width,height,"FreeBodyDiagram");labelText(title,"FreeBodyDiagram title",32);bounded(forces,32,"FreeBodyDiagram forces",1);uniqueIds(forces.map(force=>idValue(force.id,"FreeBodyDiagram force id")),"FreeBodyDiagram forces");forces.forEach((force,index)=>{labelText(force.label,`FreeBodyDiagram force "${force.id}" label`,32);finite(force.x,`FreeBodyDiagram force ${index} x component`);finite(force.y,`FreeBodyDiagram force ${index} y component`);const magnitude=Math.hypot(force.x,force.y);if(!Number.isFinite(magnitude)||magnitude===0)throw new RangeError(`FreeBodyDiagram force "${force.id}" must have a finite, non-zero magnitude.`);colorValue(force.color,c.secondary,`FreeBodyDiagram force "${force.id}" color`)});const resultant=sumForces(forces);const largestMagnitude=Math.max(resultant.magnitude,...forces.map(force=>Math.hypot(force.x,force.y)));if(!Number.isFinite(largestMagnitude)||largestMagnitude<=0)throw new RangeError("FreeBodyDiagram must have a non-zero finite vector scale.");const center={x:width/2,y:height*.56};const available=Math.min(width*.29,height*.31);const scale=available/largestMagnitude;if(!Number.isFinite(scale)||scale<=0)throw new RangeError("FreeBodyDiagram vector magnitudes cannot be mapped into the viewport.");const mapVector=(x,y)=>({x:center.x+x*scale,y:center.y-y*scale});const elements=[React17.createElement("line",{key:"x-axis",x1:center.x-available-28,y1:center.y,x2:center.x+available+28,y2:center.y,stroke:c.borderSubtle,strokeWidth:densityOf(c).w(1.3)}),React17.createElement("line",{key:"y-axis",x1:center.x,y1:center.y-available-28,x2:center.x,y2:center.y+available+28,stroke:c.borderSubtle,strokeWidth:densityOf(c).w(1.3)}),React17.createElement("circle",{key:"body",cx:center.x,cy:center.y,r:6,fill:c.bgCard,stroke:c.textPrimary,strokeWidth:densityOf(c).w(2)})];forces.forEach(force=>{const color=colorValue(force.color,c.secondary,`FreeBodyDiagram force "${force.id}" color`);const end=mapVector(force.x,force.y);if(showComponents){const xEnd=mapVector(force.x,0);const yStart=mapVector(force.x,0);if(force.x!==0)elements.push(React17.createElement("line",{key:`component-x-${force.id}`,x1:center.x,y1:center.y,x2:xEnd.x,y2:xEnd.y,stroke:color,strokeWidth:densityOf(c).w(1.6),strokeDasharray:"5 5",opacity:.56}));if(force.y!==0)elements.push(React17.createElement("line",{key:`component-y-${force.id}`,x1:yStart.x,y1:yStart.y,x2:end.x,y2:end.y,stroke:color,strokeWidth:densityOf(c).w(1.6),strokeDasharray:"5 5",opacity:.56}))}elements.push(arrow(center,end,color,`force-${force.id}`,3));const direction=Math.sign(end.x-center.x)||1;const anchor=direction>0?"start":"end";const labelX=boundedTextX(end.x+direction*12,width,force.label,anchor,20);const labelY=clamp2(end.y-11,60,height-20);elements.push(React17.createElement("text",{key:`force-label-${force.id}`,x:labelX,y:labelY,textAnchor:anchor,fill:c.textPrimary,fontFamily:c.fontSans,fontSize:FONT_SIZE,fontWeight:650},force.label))});if(showResultant&&(resultant.x!==0||resultant.y!==0)){const end=mapVector(resultant.x,resultant.y);elements.push(arrow(center,end,c.positive,"resultant",4));const label=`R = ${formatNumber(resultant.magnitude)}`;const direction=Math.sign(end.x-center.x)||1;const anchor=direction>0?"start":"end";elements.push(React17.createElement("text",{key:"resultant-label",x:boundedTextX(end.x+direction*12,width,label,anchor,20),y:clamp2(end.y+20,60,height-20),textAnchor:anchor,fill:c.textPrimary,fontFamily:c.fontSans,fontSize:FONT_SIZE,fontWeight:700},label))}else if(showResultant){elements.push(React17.createElement("text",{key:"zero-resultant",x:center.x+38,y:center.y+38,fill:c.textPrimary,fontFamily:c.fontSans,fontSize:FONT_SIZE,fontWeight:700},"R = 0"))}elements.push(React17.createElement("text",{key:"positive-x",x:width-42,y:center.y-8,textAnchor:"end",fill:c.textSecondary,fontFamily:c.fontMono,fontSize:12},"+x"),React17.createElement("text",{key:"positive-y",x:center.x-12,y:72,textAnchor:"end",fill:c.textSecondary,fontFamily:c.fontMono,fontSize:12},"+y"));return svgShell({c,width,height,title,ariaLabel,description:`${forces.length} physical force vectors use one scale. The resultant is the vector sum ${formatNumber(resultant.x)} x plus ${formatNumber(resultant.y)} y. The vertical axis points upward in physical coordinates.`,children:elements})}function arrow(start,end,color,key,strokeWidth){const dx=end.x-start.x;const dy=end.y-start.y;const length=Math.hypot(dx,dy);const head=Math.min(13,Math.max(6,length*.24));const angle=Math.atan2(dy,dx);const left={x:end.x-head*Math.cos(angle-Math.PI/6),y:end.y-head*Math.sin(angle-Math.PI/6)};const right={x:end.x-head*Math.cos(angle+Math.PI/6),y:end.y-head*Math.sin(angle+Math.PI/6)};return React17.createElement("g",{key,"data-vector-role":key==="resultant"?"resultant":"force","data-vector-id":key.startsWith("force-")?key.slice("force-".length):void 0},React17.createElement("line",{x1:start.x,y1:start.y,x2:end.x,y2:end.y,stroke:color,strokeWidth,strokeLinecap:"round"}),React17.createElement("path",{d:`M ${left.x} ${left.y} L ${end.x} ${end.y} L ${right.x} ${right.y}`,fill:"none",stroke:color,strokeWidth,strokeLinecap:"round",strokeLinejoin:"round"}))}function validateWave(wave,index,c){positive2(wave.amplitude,`WaveDiagram wave ${index} amplitude`);positive2(wave.wavelength,`WaveDiagram wave ${index} wavelength`);finite(wave.phase??0,`WaveDiagram wave ${index} phase`);finite(wave.speed??0,`WaveDiagram wave ${index} speed`);if(wave.label!==void 0)labelText(wave.label,`WaveDiagram wave ${index} label`,22);if(c)colorValue(wave.color,c.secondary,`WaveDiagram wave ${index} color`)}function waveValue(wave,x,time){validateWave(wave,0);finite(x,"WaveDiagram position");finite(time,"WaveDiagram time");const phase=2*Math.PI*(x-(wave.speed??0)*time)/wave.wavelength+(wave.phase??0);if(!Number.isFinite(phase))throw new RangeError("WaveDiagram phase must remain finite.");const value=wave.amplitude*Math.sin(phase);if(!Number.isFinite(value))throw new RangeError("WaveDiagram displacement must remain finite.");return value}function sampleWave(wave,xMin,xMax,time,sampleCount=192){const range=increasing(xMin,xMax,"WaveDiagram x domain");finite(time,"WaveDiagram time");if(!Number.isInteger(sampleCount)||sampleCount<128||sampleCount>256){throw new RangeError("WaveDiagram sample count must be an integer from 128 to 256.")}validateWave(wave,0);return Array.from({length:sampleCount},(_,index)=>{const x=xMin+range*index/(sampleCount-1);return{x,y:waveValue(wave,x,time)}})}function WaveDiagram({c,waves,time,xMin,xMax,yMin,yMax,showComponents=true,showSum=true,probeX,sampleCount=192,title="Wave superposition",ariaLabel,width=800,height=440}){const xRange=increasing(xMin,xMax,"WaveDiagram x domain");finite(time,"WaveDiagram time");dimensions(width,height,"WaveDiagram");labelText(title,"WaveDiagram title",32);bounded(waves,8,"WaveDiagram waves",1);if(!Number.isInteger(sampleCount)||sampleCount<128||sampleCount>256){throw new RangeError("WaveDiagram sample count must be an integer from 128 to 256.")}if(!showComponents&&!showSum)throw new RangeError("WaveDiagram must show component waves, their sum, or both.");waves.forEach((wave,index)=>validateWave(wave,index,c));const componentBound=Math.max(...waves.map(wave=>wave.amplitude));const sumBound=waves.reduce((sum,wave)=>sum+wave.amplitude,0);if(!Number.isFinite(sumBound)||sumBound<=0)throw new RangeError("WaveDiagram amplitude bound must be finite and positive.");const cycles=xRange/Math.min(...waves.map(wave=>wave.wavelength));if(!Number.isFinite(cycles)||cycles*12>sampleCount-1){throw new RangeError("WaveDiagram sample count must provide at least 12 samples per shortest wavelength.")}const requiredBound=showSum?sumBound:showComponents?componentBound:0;const resolvedYMin=yMin??-Math.max(1,requiredBound)*1.08;const resolvedYMax=yMax??Math.max(1,requiredBound)*1.08;const yRange=increasing(resolvedYMin,resolvedYMax,"WaveDiagram y scale");if(showSum&&(resolvedYMin>-sumBound||resolvedYMax<sumBound)){throw new RangeError("WaveDiagram y scale must include the full possible sum amplitude to avoid clipping.")}if(showComponents&&(resolvedYMin>-componentBound||resolvedYMax<componentBound)){throw new RangeError("WaveDiagram y scale must include each full component amplitude to avoid clipping.")}if(probeX!==void 0){finite(probeX,"WaveDiagram probe position");if(probeX<xMin||probeX>xMax)throw new RangeError("WaveDiagram probe must lie within the x domain.");if(!showSum)throw new RangeError("WaveDiagram probe requires the summed curve to be visible.")}const samples=waves.map(wave=>sampleWave(wave,xMin,xMax,time,sampleCount));const sumSamples=Array.from({length:sampleCount},(_,index)=>{const x=xMin+xRange*index/(sampleCount-1);const y=waves.reduce((sum,wave)=>sum+waveValue(wave,x,time),0);if(!Number.isFinite(y)||y<resolvedYMin||y>resolvedYMax)throw new RangeError("WaveDiagram summed curve falls outside its y scale.");return{x,y}});const plot={left:70,right:width-34,top:136,bottom:height-56};const sx=x=>plot.left+(x-xMin)/xRange*(plot.right-plot.left);const sy=y=>plot.bottom-(y-resolvedYMin)/yRange*(plot.bottom-plot.top);const elements=[];const gridCount=4;for(let index=0;index<=gridCount;index++){const xValue=xMin+xRange*index/gridCount;const yValue=resolvedYMin+yRange*index/gridCount;const gridX=sx(xValue);const gridY=sy(yValue);elements.push(React17.createElement("line",{key:`grid-x-${index}`,x1:gridX,y1:plot.top,x2:gridX,y2:plot.bottom,stroke:c.borderSubtle,strokeWidth:densityOf(c).w(1)}),React17.createElement("line",{key:`grid-y-${index}`,x1:plot.left,y1:gridY,x2:plot.right,y2:gridY,stroke:c.borderSubtle,strokeWidth:densityOf(c).w(1)}),React17.createElement("text",{key:`x-label-${index}`,x:gridX,y:plot.bottom+22,textAnchor:"middle",fill:c.textSecondary,fontFamily:c.fontMono,fontSize:11},formatNumber(xValue)),React17.createElement("text",{key:`y-label-${index}`,x:plot.left-10,y:gridY+4,textAnchor:"end",fill:c.textSecondary,fontFamily:c.fontMono,fontSize:11},formatNumber(yValue)))}elements.push(React17.createElement("line",{key:"x-axis",x1:plot.left,y1:sy(0),x2:plot.right,y2:sy(0),stroke:c.textSecondary,strokeWidth:densityOf(c).w(1.7)}),React17.createElement("line",{key:"y-axis",x1:plot.left,y1:plot.top,x2:plot.left,y2:plot.bottom,stroke:c.textSecondary,strokeWidth:densityOf(c).w(1.7)}),React17.createElement("text",{key:"axis-x-label",x:plot.right,y:height-18,textAnchor:"end",fill:c.textSecondary,fontFamily:c.fontSans,fontSize:12},"position x"),React17.createElement("text",{key:"axis-y-label",x:plot.left+8,y:plot.top-9,fill:c.textSecondary,fontFamily:c.fontSans,fontSize:12},"displacement y"),React17.createElement("text",{key:"time-label",x:24,y:60,fill:c.textSecondary,fontFamily:c.fontMono,fontSize:12},`t = ${formatNumber(time)}`));const pathFor=points=>points.map((point,index)=>`${index===0?"M":"L"} ${sx(point.x).toFixed(2)} ${sy(point.y).toFixed(2)}`).join(" ");if(showComponents){samples.forEach((waveSamples,index)=>{const wave=waves[index];const color=colorValue(wave.color,c.secondary,`WaveDiagram wave ${index} color`);elements.push(React17.createElement("path",{key:`component-${index}`,d:pathFor(waveSamples),fill:"none",stroke:color,strokeWidth:densityOf(c).w(2),opacity:showSum?.68:1,strokeLinecap:"round",strokeLinejoin:"round"}))})}if(showSum)elements.push(React17.createElement("path",{key:"sum",d:pathFor(sumSamples),fill:"none",stroke:c.textPrimary,strokeWidth:densityOf(c).w(3.5),strokeLinecap:"round",strokeLinejoin:"round"}));waves.forEach((wave,index)=>{const label=wave.label??`wave ${index+1}`;const color=colorValue(wave.color,c.secondary,`WaveDiagram wave ${index} color`);const column=Math.floor(index/4);const row=index%4;const legendX=plot.left+column*(plot.right-plot.left)/2;const legendY=plot.top-58+row*14;elements.push(React17.createElement("line",{key:`legend-swatch-${index}`,x1:legendX,y1:legendY-4,x2:legendX+10,y2:legendY-4,stroke:color,strokeWidth:densityOf(c).w(3),strokeLinecap:"round"}));elements.push(React17.createElement("text",{key:`legend-${index}`,x:boundedTextX(legendX+16,width,label,"start",20,11),y:legendY,fill:c.textPrimary,fontFamily:c.fontSans,fontSize:densityOf(c).f(11),fontWeight:650},label))});if(showSum)elements.push(React17.createElement("text",{key:"sum-legend",x:width-24,y:60,textAnchor:"end",fill:c.textPrimary,fontFamily:c.fontSans,fontSize:12,fontWeight:750},"sum"));if(probeX!==void 0){const probeY=waves.reduce((sum,wave)=>sum+waveValue(wave,probeX,time),0);const probePosition={x:sx(probeX),y:sy(probeY)};const label=`\u03A3y = ${formatNumber(probeY)}`;elements.push(React17.createElement("line",{key:"probe-line",x1:probePosition.x,y1:plot.top,x2:probePosition.x,y2:plot.bottom,stroke:c.warning,strokeWidth:densityOf(c).w(1.5),strokeDasharray:"5 5"}),React17.createElement("circle",{key:"probe-point",cx:probePosition.x,cy:probePosition.y,r:6,fill:c.warning,stroke:c.bgCard,strokeWidth:densityOf(c).w(2)}),React17.createElement("text",{key:"probe-label",x:clamp2(probePosition.x+10,plot.left+8,plot.right-textWidth(label)),y:clamp2(probePosition.y-12,plot.top+40,plot.bottom-10),fill:c.textPrimary,fontFamily:c.fontSans,fontSize:12,fontWeight:650},label))}const summary=waves.map((wave,index)=>`${wave.label??`wave ${index+1}`} (A=${formatNumber(wave.amplitude)}, \u03BB=${formatNumber(wave.wavelength)}, \u03C6=${formatNumber(wave.phase??0)}, v=${formatNumber(wave.speed??0)})`).join("; ");return svgShell({c,width,height,title,ariaLabel,description:`At time ${formatNumber(time)}, each displacement follows y = A sin(2\u03C0(x \u2212 vt)/\u03BB + \u03C6). Signed component waves are ${summary}; their summed displacement is the pointwise sum. The fixed y scale is ${formatNumber(resolvedYMin)} to ${formatNumber(resolvedYMax)}.`,children:elements})}import React18 from"react";function overlayText(key,props){return React18.createElement(React18.Fragment,{key},SvgMathText(props))}var ELEMENTS=new Set(["H","He","Li","Be","B","C","N","O","F","Ne","Na","Mg","Al","Si","P","S","Cl","Ar","K","Ca","Sc","Ti","V","Cr","Mn","Fe","Co","Ni","Cu","Zn","Ga","Ge","As","Se","Br","Kr","Rb","Sr","Y","Zr","Nb","Mo","Tc","Ru","Rh","Pd","Ag","Cd","In","Sn","Sb","Te","I","Xe","Cs","Ba","La","Ce","Pr","Nd","Pm","Sm","Eu","Gd","Tb","Dy","Ho","Er","Tm","Yb","Lu","Hf","Ta","W","Re","Os","Ir","Pt","Au","Hg","Tl","Pb","Bi","Po","At","Rn","Fr","Ra","Ac","Th","Pa","U","Np","Pu","Am","Cm","Bk","Cf","Es","Fm","Md","No","Lr","Rf","Db","Sg","Bh","Hs","Mt","Ds","Rg","Cn","Nh","Fl","Mc","Lv","Ts","Og"]);var ELEMENT_SYMBOLS=Object.freeze(Array.from(ELEMENTS));var MOLECULE_LIMITS={atoms:64,bonds:96,width:[300,1200],height:[240,900]};function finiteNumber(value,description){if(typeof value!=="number"||!Number.isFinite(value)){throw new TypeError(`${description} must be a finite number.`)}}function boundedDimension(value,label,min,max){finiteNumber(value,`${label}`);if(value<min||value>max)throw new RangeError(`${label} must be between ${min} and ${max} pixels.`);return value}function isElementSymbol(value){return typeof value==="string"&&ELEMENTS.has(value)}function validateMolecule(atoms,bonds){if(!Array.isArray(atoms)||atoms.length<1)throw new TypeError("MoleculeDiagram needs at least one atom.");if(atoms.length>MOLECULE_LIMITS.atoms)throw new RangeError(`MoleculeDiagram supports at most ${MOLECULE_LIMITS.atoms} atoms.`);if(!Array.isArray(bonds))throw new TypeError("MoleculeDiagram bonds must be an array.");if(bonds.length>MOLECULE_LIMITS.bonds)throw new RangeError(`MoleculeDiagram supports at most ${MOLECULE_LIMITS.bonds} bonds.`);const ids=new Set;const positions=new Map;for(const[index,atom]of atoms.entries()){if(!atom||typeof atom!=="object")throw new TypeError(`MoleculeDiagram atom ${index} must be an object.`);if(typeof atom.id!=="string"||atom.id.trim().length===0)throw new TypeError(`MoleculeDiagram atom ${index} needs a non-empty ID.`);if(ids.has(atom.id))throw new TypeError(`MoleculeDiagram atom ID "${atom.id}" is duplicated.`);ids.add(atom.id);if(!isElementSymbol(atom.element))throw new TypeError(`MoleculeDiagram atom "${atom.id}" has an invalid element symbol.`);finiteNumber(atom.x,`MoleculeDiagram atom "${atom.id}" x`);finiteNumber(atom.y,`MoleculeDiagram atom "${atom.id}" y`);if(atom.charge!==void 0&&(!Number.isSafeInteger(atom.charge)||Math.abs(atom.charge)>99)){throw new TypeError(`MoleculeDiagram atom "${atom.id}" charge must be an integer between -99 and 99.`)}if(atom.isotope!==void 0&&(!Number.isSafeInteger(atom.isotope)||atom.isotope<=0||atom.isotope>300)){throw new TypeError(`MoleculeDiagram atom "${atom.id}" isotope must be a positive integer no greater than 300.`)}if(atom.label!==void 0&&(typeof atom.label!=="string"||atom.label.length>32)){throw new TypeError(`MoleculeDiagram atom "${atom.id}" label must be a string of at most 32 characters.`)}const positionKey=`${atom.x},${atom.y}`;const existing=positions.get(positionKey);if(existing)throw new TypeError(`MoleculeDiagram atoms "${existing}" and "${atom.id}" have coincident coordinates.`);positions.set(positionKey,atom.id)}const bondPairs=new Set;for(const[index,bond]of bonds.entries()){if(!bond||typeof bond!=="object")throw new TypeError(`MoleculeDiagram bond ${index} must be an object.`);if(typeof bond.from!=="string"||typeof bond.to!=="string")throw new TypeError(`MoleculeDiagram bond ${index} needs atom IDs for both endpoints.`);if(!ids.has(bond.from))throw new TypeError(`MoleculeDiagram bond ${index} references unknown atom "${bond.from}".`);if(!ids.has(bond.to))throw new TypeError(`MoleculeDiagram bond ${index} references unknown atom "${bond.to}".`);if(bond.from===bond.to)throw new TypeError(`MoleculeDiagram bond ${index} cannot connect an atom to itself.`);if(![1,1.5,2,3].includes(bond.order))throw new TypeError(`MoleculeDiagram bond ${index} order must be 1, 1.5, 2, or 3.`);const pairKey=bond.from<bond.to?`${bond.from}\0${bond.to}`:`${bond.to}\0${bond.from}`;if(bondPairs.has(pairKey))throw new TypeError(`MoleculeDiagram bond "${bond.from}"\u2013"${bond.to}" is duplicated.`);bondPairs.add(pairKey)}}function moleculeLayout(atoms,width,height,titleInset){const left=42;const right=width-42;const top=titleInset;const bottom=height-42;const maxAbs=Math.max(...atoms.flatMap(atom=>[Math.abs(atom.x),Math.abs(atom.y)]));if(maxAbs===0)return new Map(atoms.map(atom=>[atom.id,{x:width/2,y:(top+bottom)/2}]));const normalized=atoms.map(atom=>({atom,x:atom.x/maxAbs,y:atom.y/maxAbs}));const minX=Math.min(...normalized.map(point=>point.x));const maxX=Math.max(...normalized.map(point=>point.x));const minY=Math.min(...normalized.map(point=>point.y));const maxY=Math.max(...normalized.map(point=>point.y));const spanX=maxX-minX;const spanY=maxY-minY;const plotWidth=right-left;const plotHeight=bottom-top;const scale=spanX===0&&spanY===0?1:Math.min(spanX===0?Number.POSITIVE_INFINITY:plotWidth/spanX,spanY===0?Number.POSITIVE_INFINITY:plotHeight/spanY);const centerX=(minX+maxX)/2;const centerY=(minY+maxY)/2;return new Map(normalized.map(({atom,x,y})=>[atom.id,{x:(left+right)/2+(x-centerX)*scale,y:(top+bottom)/2-(y-centerY)*scale}]))}function bondSegments(from,to,order,atomRadius=19){const dx=to.x-from.x;const dy=to.y-from.y;const length=Math.hypot(dx,dy);if(!Number.isFinite(length)||length<=atomRadius*2){throw new RangeError("MoleculeDiagram bond endpoints must be far enough apart to draw atom labels.")}const ux=dx/length;const uy=dy/length;const nx=-uy;const ny=ux;const offsets=order===1?[0]:order===3?[-4.6,0,4.6]:[-3.2,3.2];const start=atomRadius+1;const end=length-atomRadius-1;return offsets.map((offset,index)=>({x1:from.x+ux*start+nx*offset,y1:from.y+uy*start+ny*offset,x2:from.x+ux*end+nx*offset,y2:from.y+uy*end+ny*offset,dashed:order===1.5&&index===1}))}function atomColor(element,c){if(element==="O"||element==="S"||element==="Se")return getReadableColor("critical",c);if(element==="N"||element==="P")return getReadableColor("info",c);if(element==="F"||element==="Cl"||element==="Br"||element==="I")return getReadableColor("positive",c);if(element==="C")return c.textPrimary;return getReadableColor("secondary",c)}function MoleculeDiagram({c,atoms,bonds,width=520,height=360,title}){if(title!==void 0&&(typeof title!=="string"||title.length>64)){throw new TypeError("MoleculeDiagram title must be a string of at most 64 characters.")}validateMolecule(atoms,bonds);const svgWidth=boundedDimension(width,"MoleculeDiagram width",...MOLECULE_LIMITS.width);const svgHeight=boundedDimension(height,"MoleculeDiagram height",...MOLECULE_LIMITS.height);const points=moleculeLayout(atoms,svgWidth,svgHeight,title?60:48);const accessibleTitle=title??"Molecule diagram";const description=`${atoms.length} explicitly positioned atoms and ${bonds.length} explicit bonds. Bond order does not imply inferred valence, three-dimensional geometry, or stereochemistry.`;const bondNodes=bonds.flatMap((bond,bondIndex)=>{const from=points.get(bond.from);const to=points.get(bond.to);return bondSegments(from,to,bond.order).map((segment,segmentIndex)=>React18.createElement("line",{key:`bond-${bondIndex}-${segmentIndex}`,x1:segment.x1,y1:segment.y1,x2:segment.x2,y2:segment.y2,stroke:c.textSecondary,strokeWidth:bond.order===1?2.5:2,strokeLinecap:"round",...segment.dashed?{strokeDasharray:"3 4"}:{},"data-bond-from":bond.from,"data-bond-to":bond.to,"data-bond-order":bond.order,"data-bond-line-index":segmentIndex,"aria-hidden":true}))});const atomNodes=atoms.map(atom=>{const point=points.get(atom.id);const accent=atomColor(atom.element,c);return React18.createElement("g",{key:atom.id,"data-atom-id":atom.id,"data-element":atom.element},React18.createElement("circle",{cx:point.x,cy:point.y,r:19,fill:c.bgCard,stroke:accent,strokeWidth:densityOf(c).w(2)}))});const textNodes=atoms.flatMap(atom=>{const point=points.get(atom.id);const labelY=point.y+34<=svgHeight-10?point.y+34:point.y-25;return[overlayText(`atom-${atom.id}-element`,{text:atom.element,x:point.x,y:point.y+1,fill:atomColor(atom.element,c),fontSize:atom.element.length===1?17:14,fontFamily:c.fontSans,fontWeight:700}),...atom.isotope===void 0?[]:[overlayText(`atom-${atom.id}-isotope`,{text:String(atom.isotope),x:point.x-15,y:point.y-12,fill:c.textPrimary,fontSize:densityOf(c).f(10),fontFamily:c.fontSans,fontWeight:700,textAnchor:"end"})],...atom.charge===void 0||atom.charge===0?[]:[overlayText(`atom-${atom.id}-charge`,{text:`${Math.abs(atom.charge)}${atom.charge>0?"+":"\u2212"}`,x:point.x+15,y:point.y-12,fill:c.textPrimary,fontSize:densityOf(c).f(10),fontFamily:c.fontSans,fontWeight:700,textAnchor:"start"})],...atom.label?[overlayText(`atom-${atom.id}-label`,{text:atom.label,x:point.x,y:labelY,fill:c.textSecondary,fontSize:densityOf(c).f(10),fontFamily:c.fontSans,textAnchor:"middle"})]:[]]});const geometry=React18.createElement("svg",{width:svgWidth,height:svgHeight,viewBox:`0 0 ${svgWidth} ${svgHeight}`,"aria-hidden":true,style:{position:"absolute",left:0,top:0,display:"block"}},React18.createElement("rect",{x:0,y:0,width:svgWidth,height:svgHeight,rx:14,fill:c.bgCard,stroke:c.borderSubtle}),...bondNodes,...atomNodes);return React18.createElement("div",{role:"img","aria-label":accessibleTitle,"aria-description":description,title:accessibleTitle,"data-vizmatic-component":"MoleculeDiagram",style:{position:"relative",width:svgWidth,height:svgHeight,overflow:"hidden"}},geometry,...title?[overlayText("molecule-title",{text:title,x:svgWidth/2,y:24,fill:c.textPrimary,fontSize:densityOf(c).f(15),fontFamily:c.fontSans,fontWeight:700})]:[],...textNodes)}var MAX_REACTION_TERMS=16;var MAX_FORMULA_LENGTH=256;function validateComposition(composition,description){if(!composition||typeof composition!=="object"||Array.isArray(composition)){throw new TypeError(`${description} must be an element-count object.`)}const entries2=Object.entries(composition);if(entries2.length===0)throw new TypeError(`${description} must contain at least one explicit element count.`);for(const[element,count]of entries2){if(!isElementSymbol(element))throw new TypeError(`${description} contains invalid element symbol "${element}".`);if(typeof count!=="number"||!Number.isSafeInteger(count)||count<=0||count>1e6){throw new TypeError(`${description} count for ${element} must be a positive integer no greater than 1000000.`)}}}function validateReactionTerms(terms,side){if(!Array.isArray(terms)||terms.length===0)throw new TypeError(`ReactionEquation ${side} must contain at least one term.`);if(terms.length>MAX_REACTION_TERMS)throw new RangeError(`ReactionEquation ${side} supports at most ${MAX_REACTION_TERMS} terms.`);for(const[index,term]of terms.entries()){if(!term||typeof term!=="object")throw new TypeError(`ReactionEquation ${side}[${index}] must be an object.`);if(typeof term.formula!=="string"||term.formula.trim().length===0){throw new TypeError(`ReactionEquation ${side}[${index}] formula must be a non-empty string.`)}if(term.formula.length>MAX_FORMULA_LENGTH){throw new RangeError(`ReactionEquation ${side}[${index}] formula must be at most ${MAX_FORMULA_LENGTH} characters.`)}if(term.coefficient!==void 0&&(!Number.isSafeInteger(term.coefficient)||term.coefficient<=0||term.coefficient>1e6)){throw new TypeError(`ReactionEquation ${side}[${index}] coefficient must be a positive integer no greater than 1000000.`)}if(term.state!==void 0&&!["s","l","g","aq"].includes(term.state)){throw new TypeError(`ReactionEquation ${side}[${index}] state must be s, l, g, or aq.`)}if(term.charge!==void 0&&(!Number.isSafeInteger(term.charge)||Math.abs(term.charge)>1e6)){throw new TypeError(`ReactionEquation ${side}[${index}] charge must be an integer between -1000000 and 1000000.`)}if(term.composition!==void 0)validateComposition(term.composition,`ReactionEquation ${side}[${index}] composition`)}}function reactionBalance(reactants,products){validateReactionTerms(reactants,"reactants");validateReactionTerms(products,"products");const compositionByFormula=new Map;for(const term of[...reactants,...products]){if(!term.composition)continue;const signature=JSON.stringify(Object.fromEntries(Object.entries(term.composition).sort(([left],[right])=>left.localeCompare(right))));const prior=compositionByFormula.get(term.formula);if(prior!==void 0&&prior!==signature){throw new TypeError(`ReactionEquation composition maps for literal formula "${term.formula}" are inconsistent.`)}compositionByFormula.set(term.formula,signature)}const missingTerms=[...reactants.flatMap((term,index)=>term.composition?[]:[`reactants[${index}]`]),...products.flatMap((term,index)=>term.composition?[]:[`products[${index}]`])];if(missingTerms.length>0)return{status:"unavailable",reason:"composition_missing",missingTerms};const deltas={};let chargeDelta=0;const addSide=(terms,sign)=>{for(const term of terms){const coefficient=term.coefficient??1;for(const[element,count]of Object.entries(term.composition)){const symbol=element;deltas[symbol]=(deltas[symbol]??0)+sign*coefficient*count}chargeDelta+=sign*coefficient*(term.charge??0)}};addSide(reactants,-1);addSide(products,1);const balanced=Object.values(deltas).every(delta=>delta===0)&&chargeDelta===0;return{status:balanced?"balanced":"unbalanced",balanced,elementDeltas:deltas,chargeDelta}}function equationTerm(term,index,c){return React18.createElement("span",{key:`term-${index}-${term.formula}`,style:{display:"inline-flex",flexWrap:"wrap",alignItems:"baseline",minWidth:0,maxWidth:"100%",overflowWrap:"anywhere",color:c.textPrimary}},term.coefficient&&term.coefficient!==1?React18.createElement("span",{style:{color:getReadableColor("primary",c),fontWeight:700,marginRight:5}},`${term.coefficient}`):null,React18.createElement("span",{style:{overflowWrap:"anywhere"}},term.formula),term.state?React18.createElement("span",{style:{marginLeft:5,color:c.textSecondary,fontSize:"0.9em"}},`(${term.state})`):null)}function equationSide(terms,label,c){const children=[];terms.forEach((term,index)=>{if(index>0)children.push(React18.createElement("span",{key:`plus-${index}`,style:{color:c.textSecondary,padding:"0 7px",flex:"0 0 auto"},"aria-hidden":true},"+"));children.push(equationTerm(term,index,c))});return React18.createElement("div",{role:"group","aria-label":label,style:{display:"flex",flexWrap:"wrap",alignItems:"baseline",alignContent:"center",gap:"8px 0",flex:"1 1 0",minWidth:0,lineHeight:1.5,fontSize:densityOf(c).f(20)}},...children)}function ReactionEquation({c,reactants,products,conditions,reversible=false,width=760}){validateReactionTerms(reactants,"reactants");validateReactionTerms(products,"products");const equationWidth=boundedDimension(width,"ReactionEquation width",420,1400);if(conditions!==void 0&&typeof conditions!=="string")throw new TypeError("ReactionEquation conditions must be a string.");if(conditions!==void 0&&conditions.length>240)throw new RangeError("ReactionEquation conditions must be at most 240 characters.");const balance=reactionBalance(reactants,products);const accessibleEquation=`${reactants.map(term=>`${term.coefficient&&term.coefficient!==1?`${term.coefficient} `:""}${term.formula}${term.state?` (${term.state})`:""}`).join(" + ")} ${reversible?"reversibly yields":"yields"} ${products.map(term=>`${term.coefficient&&term.coefficient!==1?`${term.coefficient} `:""}${term.formula}${term.state?` (${term.state})`:""}`).join(" + ")}`;const balanceText=balance.status==="unavailable"?"Balance unavailable: provide a complete composition map for every term.":balance.balanced?"Balanced by supplied composition and charge.":`Not balanced by supplied composition and charge: ${Object.entries(balance.elementDeltas).filter(([,delta])=>delta!==0).map(([element,delta])=>`${element} ${delta>0?"+":""}${delta}`).join(", ")||"elements conserved"}, charge ${balance.chargeDelta>0?"+":""}${balance.chargeDelta}.`;return React18.createElement("div",{role:"img","aria-label":`${accessibleEquation}. ${balanceText}${conditions?` Conditions: ${conditions}.`:""}`,"data-vizmatic-component":"ReactionEquation",style:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:densityOf(c).s(12),width:equationWidth,maxWidth:"100%",padding:densityOf(c).s(18),border:`1px solid ${c.borderSubtle}`,borderRadius:densityOf(c).r(14),background:c.bgCard,color:c.textPrimary,fontFamily:c.fontSans}},React18.createElement("div",{style:{display:"flex",alignItems:"center",gap:12,minWidth:0}},equationSide(reactants,"Reactants",c),React18.createElement("span",{style:{flex:"0 0 auto",color:c.primaryLight,fontSize:densityOf(c).f(26),fontWeight:700,padding:"0 2px"},"aria-hidden":true},reversible?"\u21CC":"\u2192"),equationSide(products,"Products",c)),conditions!==void 0&&conditions.length>0?React18.createElement("div",{style:{color:c.textSecondary,fontSize:densityOf(c).f(13)}},`Conditions: ${conditions}`):null,React18.createElement("div",{style:{paddingTop:8,borderTop:`1px solid ${c.borderSubtle}`,color:balance.status==="balanced"?getReadableColor("positive",c):balance.status==="unbalanced"?getReadableColor("critical",c):c.textSecondary,fontSize:densityOf(c).f(13),lineHeight:1.4}},balanceText))}var ENERGY_LIMITS={width:[520,1200],height:[320,900],absValue:1e9};function energyText(value){if(Object.is(value,-0)||value===0)return"0";return Number.isInteger(value)?String(value):String(Number(value.toFixed(2)))}function signedEnergyText(value){return value>0?`+${energyText(value)}`:value<0?`\u2212${energyText(Math.abs(value))}`:"0"}function validateEnergyValue(value,label){finiteNumber(value,`ReactionEnergyDiagram ${label}`);if(Math.abs(value)>ENERGY_LIMITS.absValue){throw new RangeError(`ReactionEnergyDiagram ${label} must be between -${ENERGY_LIMITS.absValue} and ${ENERGY_LIMITS.absValue}.`)}}function energyPath(x0,y0,xPeak,yPeak,x1,y1){const leftControl=x0+(xPeak-x0)*.58;const rightControl=xPeak+(x1-xPeak)*.42;const leftStartControl=x0+(xPeak-x0)*.42;const rightEndControl=xPeak+(x1-xPeak)*.58;return`M ${x0} ${y0} C ${leftStartControl} ${y0}, ${leftControl} ${yPeak}, ${xPeak} ${yPeak} C ${rightControl} ${yPeak}, ${rightEndControl} ${y1}, ${x1} ${y1}`}function measurement(x,y1,y2,color,key,label){const top=Math.min(y1,y2);const bottom=Math.max(y1,y2);const cap=5;return React18.createElement("g",{key,"data-measurement":label,"aria-hidden":true},React18.createElement("line",{x1:x,y1:top,x2:x,y2:bottom,stroke:color,strokeWidth:densityOf().w(1.5),strokeDasharray:"3 3"}),React18.createElement("line",{x1:x-cap,y1:top,x2:x+cap,y2:top,stroke:color,strokeWidth:densityOf().w(1.5)}),React18.createElement("line",{x1:x-cap,y1:bottom,x2:x+cap,y2:bottom,stroke:color,strokeWidth:densityOf().w(1.5)}))}function ReactionEnergyDiagram({c,ariaLabel,reactants,products,barrier,catalyzedBarrier,unit="energy units",reactantLabel="Reactants",productLabel="Products",width=760,height=400,progress=1}){validateEnergyValue(reactants,"reactants");validateEnergyValue(products,"products");validateEnergyValue(barrier,"barrier");if(catalyzedBarrier!==void 0)validateEnergyValue(catalyzedBarrier,"catalyzedBarrier");if(barrier<Math.max(reactants,products)){throw new RangeError("ReactionEnergyDiagram barrier must be at least the higher endpoint energy.")}if(catalyzedBarrier!==void 0&&catalyzedBarrier<Math.max(reactants,products)){throw new RangeError("ReactionEnergyDiagram catalyzedBarrier must be at least the higher endpoint energy.")}if(catalyzedBarrier!==void 0&&catalyzedBarrier>=barrier){throw new RangeError("ReactionEnergyDiagram catalyzedBarrier must be lower than the uncatalyzed barrier.")}if(typeof unit!=="string"||unit.trim().length===0||unit.length>32){throw new TypeError("ReactionEnergyDiagram unit must be a non-empty string of at most 32 characters.")}if(typeof reactantLabel!=="string"||reactantLabel.trim().length===0||reactantLabel.length>24){throw new TypeError("ReactionEnergyDiagram reactantLabel must be a non-empty string of at most 24 characters.")}if(typeof productLabel!=="string"||productLabel.trim().length===0||productLabel.length>24){throw new TypeError("ReactionEnergyDiagram productLabel must be a non-empty string of at most 24 characters.")}if(ariaLabel!==void 0&&(typeof ariaLabel!=="string"||ariaLabel.trim().length===0||ariaLabel.length>100)){throw new TypeError("ReactionEnergyDiagram ariaLabel must be a non-empty string of at most 100 characters.")}if(typeof progress!=="number"||!Number.isFinite(progress)||progress<0||progress>1){throw new RangeError("ReactionEnergyDiagram progress must be a finite number from 0 to 1.")}const svgWidth=boundedDimension(width,"ReactionEnergyDiagram width",...ENERGY_LIMITS.width);const svgHeight=boundedDimension(height,"ReactionEnergyDiagram height",...ENERGY_LIMITS.height);const plotLeft=82;const plotRight=svgWidth-82;const plotTop=54;const plotBottom=svgHeight-118;const x0=plotLeft+14;const x1=plotRight-14;const xPeak=(x0+x1)/2;const lowest=Math.min(reactants,products);const highest=Math.max(barrier,catalyzedBarrier??barrier);const rawRange=highest-lowest;const range=rawRange===0?2:rawRange;const padding=rawRange===0?0:range*.16;const scaleMin=rawRange===0?lowest-1:lowest-padding;const scaleMax=rawRange===0?highest+1:highest+padding;const yFor=value=>plotBottom-(value-scaleMin)/(scaleMax-scaleMin)*(plotBottom-plotTop);const yReactants=yFor(reactants);const yProducts=yFor(products);const yBarrier=yFor(barrier);const yCatalyzed=catalyzedBarrier===void 0?void 0:yFor(catalyzedBarrier);const path=energyPath(x0,yReactants,xPeak,yBarrier,x1,yProducts);const catalyzedPath=yCatalyzed===void 0?void 0:energyPath(x0,yReactants,xPeak,yCatalyzed,x1,yProducts);const delta=products-reactants;const activation=barrier-reactants;const catalyzedActivation=catalyzedBarrier===void 0?void 0:catalyzedBarrier-reactants;const chartTitle="Reaction energy diagram";const desc=`${reactantLabel} energy ${energyText(reactants)} ${unit}; product energy ${energyText(products)} ${unit}; uncatalyzed activation energy ${energyText(activation)} ${unit}; reaction energy change \u0394E ${signedEnergyText(delta)} ${unit}.${catalyzedBarrier===void 0?"":` Catalyzed activation energy ${energyText(catalyzedActivation)} ${unit}; endpoints are unchanged.`}`;const readableInk=getReadableTextColor(c.bgCard,c);const activationX=plotLeft+24;const catalyzedActivationX=plotLeft+38;const deltaX=plotRight+16;const revealClipId=`reaction-energy-reveal-${svgWidth}-${svgHeight}-${String(progress).replace(".","-")}`;const revealWidth=progress===0?0:(x1-x0)*progress+8;const gridValues=[scaleMin,(scaleMin+scaleMax)/2,scaleMax];const svgNodes=[React18.createElement("rect",{key:"background",x:0,y:0,width:svgWidth,height:svgHeight,rx:14,fill:c.bgCard,stroke:c.borderSubtle}),React18.createElement("defs",{key:"reveal-defs"},React18.createElement("clipPath",{id:revealClipId,clipPathUnits:"userSpaceOnUse"},React18.createElement("rect",{x:x0-4,y:plotTop,width:revealWidth,height:plotBottom-plotTop}))),React18.createElement("line",{key:"y-axis",x1:plotLeft,y1:plotTop,x2:plotLeft,y2:plotBottom,stroke:c.borderLight,strokeWidth:densityOf(c).w(1.4)}),React18.createElement("line",{key:"x-axis",x1:plotLeft,y1:plotBottom,x2:plotRight,y2:plotBottom,stroke:c.borderLight,strokeWidth:densityOf(c).w(1.4)}),...gridValues.map((value,index)=>React18.createElement("line",{key:`grid-${index}`,x1:plotLeft,y1:yFor(value),x2:plotRight,y2:yFor(value),stroke:c.borderSubtle,strokeWidth:densityOf(c).w(1),strokeDasharray:"3 5"})),React18.createElement("path",{key:"uncatalyzed-path",d:path,fill:"none",stroke:c.critical,strokeWidth:densityOf(c).w(4),strokeLinecap:"round",strokeLinejoin:"round",clipPath:`url(#${revealClipId})`,"data-energy-path":"uncatalyzed","data-progress":progress}),catalyzedPath===void 0?null:React18.createElement("path",{key:"catalyzed-path",d:catalyzedPath,fill:"none",stroke:c.positive,strokeWidth:densityOf(c).w(4),strokeLinecap:"round",strokeLinejoin:"round",clipPath:`url(#${revealClipId})`,"data-energy-path":"catalyzed","data-progress":progress}),measurement(activationX,yReactants,yBarrier,c.critical,"activation-uncatalyzed","activation-uncatalyzed"),yCatalyzed===void 0?null:measurement(catalyzedActivationX,yReactants,yCatalyzed,c.positive,"activation-catalyzed","activation-catalyzed"),measurement(deltaX,yReactants,yProducts,c.secondary,"reaction-energy-change","reaction-energy-change")];const overlayNodes=[overlayText("title",{text:`${chartTitle} \xB7 ${unit}`,x:svgWidth/2,y:24,fill:c.textPrimary,fontSize:densityOf(c).f(16),fontFamily:c.fontSans,fontWeight:700}),React18.createElement("div",{key:"energy-label",style:{position:"absolute",left:22,top:(plotTop+plotBottom)/2,display:"flex",color:c.textSecondary,fontSize:densityOf(c).f(12),fontFamily:c.fontSans,lineHeight:1,whiteSpace:"nowrap",transform:"translate(-50%, -50%) rotate(-90deg)"}},"Energy"),...gridValues.map((value,index)=>overlayText(`grid-label-${index}`,{text:energyText(value),x:plotLeft-8,y:yFor(value)+4,fill:readableInk,fontSize:densityOf(c).f(12),fontFamily:c.fontSans,textAnchor:"end"})),overlayText("reactant-label",{text:reactantLabel,x:x0,y:plotBottom+25,fill:c.textPrimary,fontSize:densityOf(c).f(13),fontFamily:c.fontSans,fontWeight:600}),overlayText("product-label",{text:productLabel,x:x1,y:plotBottom+25,fill:c.textPrimary,fontSize:densityOf(c).f(13),fontFamily:c.fontSans,fontWeight:600}),overlayText("activation-value",{text:`Ea (uncatalyzed) = ${energyText(activation)} ${unit}`,x:svgWidth/2,y:svgHeight-(catalyzedActivation===void 0?45:57),fill:getReadableColor("critical",c),fontSize:densityOf(c).f(12),fontFamily:c.fontSans}),...catalyzedActivation===void 0?[]:[overlayText("catalyzed-activation-value",{text:`Ea (catalyzed) = ${energyText(catalyzedActivation)} ${unit}`,x:svgWidth/2,y:svgHeight-39,fill:getReadableColor("positive",c),fontSize:densityOf(c).f(12),fontFamily:c.fontSans})],overlayText("delta-value",{text:`\u0394E = ${signedEnergyText(delta)} ${unit}`,x:svgWidth/2,y:svgHeight-21,fill:getReadableColor("secondary",c),fontSize:densityOf(c).f(12),fontFamily:c.fontSans})];const geometry=React18.createElement("svg",{width:svgWidth,height:svgHeight,viewBox:`0 0 ${svgWidth} ${svgHeight}`,"aria-hidden":true,style:{position:"absolute",left:0,top:0,display:"block"}},...svgNodes);return React18.createElement("div",{role:"img","aria-label":ariaLabel??`${chartTitle} (${unit})`,"aria-description":desc,title:`${chartTitle} (${unit})`,"data-vizmatic-component":"ReactionEnergyDiagram",style:{position:"relative",width:svgWidth,height:svgHeight,overflow:"hidden"}},geometry,...overlayNodes)}import React19 from"react";function finite2(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function finiteValues(values,name){values.forEach(value=>finite2(value,name))}function seededRandom(seed){if(!Number.isSafeInteger(seed))throw new Error("Random seed must be a safe integer");let state=seed>>>0;return()=>{state=state+1831565813>>>0;let value=Math.imul(state^state>>>15,1|state);value^=value+Math.imul(value^value>>>7,61|value);return((value^value>>>14)>>>0)/4294967296}}function lerpArray(from,to,progress){if(from.length!==to.length)throw new Error("Interpolation vectors must have equal lengths");finite2(progress,"Interpolation progress");finiteValues(from,"Interpolation value");finiteValues(to,"Interpolation value");const result=from.map((value,index)=>{const end=to[index];const blended=value*(1-progress)+end*progress;if(Number.isFinite(blended))return blended;const scale=Math.max(Math.abs(value),Math.abs(end));return(value/scale+(end/scale-value/scale)*progress)*scale});finiteValues(result,"Interpolation result");return result}function dotProduct(left,right){if(left.length!==right.length)throw new Error("Dot product vectors must have equal lengths");finiteValues(left,"Dot product value");finiteValues(right,"Dot product value");const result=left.reduce((sum,value,index)=>sum+value*right[index],0);finite2(result,"Dot product result");return result}function matrixWidth(matrix,name){const width=matrix[0]?.length??0;for(const row of matrix){if(row.length!==width)throw new Error(`${name} rows must be rectangular`);finiteValues(row,`${name} value`)}return width}function multiplyMatrices(left,right){const inner=matrixWidth(left,"Left matrix");const columns=matrixWidth(right,"Right matrix");if(inner!==right.length)throw new Error("Matrix inner dimensions must match");return left.map(row=>Array.from({length:columns},(_,column)=>{const result=row.reduce((sum,value,index)=>sum+value*right[index][column],0);finite2(result,"Matrix product value");return result}))}function stableSoftmax(values,temperature=1){finite2(temperature,"Softmax temperature");if(temperature<=0)throw new Error("Softmax temperature must be positive");finiteValues(values,"Softmax logit");if(!values.length)return[];const maximum=values.reduce((largest,value)=>Math.max(largest,value),-Infinity);const weights=values.map(value=>Math.exp((value-maximum)/temperature));const total=weights.reduce((sum,value)=>sum+value,0);return weights.map(value=>value/total)}function entropy(probabilities,base=2){finite2(base,"Entropy base");if(base<=0||base===1)throw new Error("Entropy base must be positive and different from one");finiteValues(probabilities,"Entropy probability");if(!probabilities.length)return 0;if(probabilities.some(value=>value<0||value>1)){throw new Error("Entropy probabilities must lie between zero and one")}const total=probabilities.reduce((sum,value)=>sum+value,0);if(Math.abs(total-1)>1e-9)throw new Error("Entropy probabilities must sum to one");return-probabilities.reduce((sum,value)=>value===0?sum:sum+value*Math.log(value),0)/Math.log(base)}function normalizeVector(values){finiteValues(values,"Vector value");const scale=values.reduce((largest,value)=>Math.max(largest,Math.abs(value)),0);if(scale===0)return values.map(()=>0);const scaled=values.map(value=>value/scale);const length=Math.sqrt(scaled.reduce((sum,value)=>sum+value*value,0));return scaled.map(value=>value/length)}function sampleFunction(fn,low,high,count=100){finite2(low,"Sample domain start");finite2(high,"Sample domain end");if(high<=low)throw new Error("Sample domain must increase");if(!Number.isSafeInteger(count)||count<2)throw new Error("Sample count must be an integer of at least two");return Array.from({length:count},(_,index)=>{const amount=index/(count-1);const x=low*(1-amount)+high*amount;const y=fn(x);finite2(y,"Sampled function value");return{x,y}})}function gaussian(mean,sigma,x){finite2(mean,"Gaussian mean");finite2(sigma,"Gaussian standard deviation");finite2(x,"Gaussian x");if(sigma<=0)throw new Error("Gaussian standard deviation must be positive");const z=(x-mean)/sigma;const density=Math.exp(-.5*z*z)/sigma/Math.sqrt(2*Math.PI);finite2(density,"Gaussian density");return density}function sampleGaussian(random){const first=random();const second=random();if(!Number.isFinite(first)||!Number.isFinite(second)||first<0||first>=1||second<0||second>=1){throw new Error("Gaussian random draws must lie in [0, 1)")}return Math.sqrt(-2*Math.log(1-first))*Math.cos(2*Math.PI*second)}function matrixShape(matrix,name){if(!matrix.length||matrix.length>128||!matrix[0]?.length||matrix[0].length>256){throw new Error(`${name} must contain 1\u2013128 nonempty rows with at most 256 columns`)}const columns=matrix[0].length;if(matrix.some(row=>row.length!==columns||row.some(value=>!Number.isFinite(value)))){throw new Error(`${name} must be rectangular and finite`)}return columns}function validateMask(mask,rows,columns){if(mask&&(mask.length!==rows||mask.some(row=>row.length!==columns||row.some(value=>typeof value!=="boolean")))){throw new Error("Attention mask dimensions must match queries and keys and contain booleans")}}function scaledDotProductAttention(queries,keys,values,options={}){const dimension2=matrixShape(queries,"Queries");if(matrixShape(keys,"Keys")!==dimension2)throw new Error("Queries and keys must have the same feature dimension");const valueDimension=matrixShape(values,"Values");if(values.length!==keys.length)throw new Error("Values must have one row per key");validateMask(options.mask,queries.length,keys.length);const scores=[];const weights=[];const output=[];for(const[i,query]of queries.entries()){const row=keys.map((key,j)=>{if(options.causal&&j>i||options.mask?.[i][j]===false)return null;const score=query.reduce((sum,value,k)=>sum+value*key[k],0)/Math.sqrt(dimension2);if(!Number.isFinite(score))throw new Error("Attention score must be finite");return score});const visible=row.filter(value=>value!==null);if(!visible.length)throw new Error(`Attention query ${i} is fully masked`);const probabilities=stableSoftmax(visible);let visibleIndex=0;const distribution=row.map(value=>value===null?0:probabilities[visibleIndex++]);const result=Array.from({length:valueDimension},(_,column)=>distribution.reduce((sum,weight,j)=>sum+weight*values[j][column],0));if(result.some(value=>!Number.isFinite(value)))throw new Error("Attention output must be finite");scores.push(row);weights.push(distribution);output.push(result)}return{scores,weights,output}}function AttentionMatrix({c,weights,queryLabels,keyLabels,mask,activeQuery,activeKey,title="Attention probabilities",width=760,height=420}){const columns=matrixShape(weights,"Attention weights");const rows=weights.length;if(rows>32||columns>32)throw new Error("AttentionMatrix supports at most 32 queries and 32 keys");validateMask(mask,rows,columns);for(const[i,row]of weights.entries()){if(row.some((value,j)=>value<0||value>1||mask?.[i][j]===false&&value!==0)){throw new Error("Attention weights must be probabilities with zero at masked entries")}const total=row.reduce((sum,value)=>sum+value,0);const fullyMasked=mask?.[i].every(value=>!value)??false;if(Math.abs(total-(fullyMasked?0:1))>1e-6)throw new Error("Each visible attention row must sum to one")}const labels=(input,count,prefix)=>{if(input&&(input.length!==count||input.some(value=>typeof value!=="string"||value.length>24))){throw new Error("Attention labels must match the matrix dimensions and contain at most 24 characters")}return input?[...input]:Array.from({length:count},(_,i)=>`${prefix}${i+1}`)};const queryNames=labels(queryLabels,rows,"q");const keyNames=labels(keyLabels,columns,"k");for(const[name,value,count]of[["activeQuery",activeQuery,rows],["activeKey",activeKey,columns]]){if(value!==void 0&&(!Number.isInteger(value)||value<0||value>=count))throw new Error(`${name} is outside the attention matrix`)}if(![width,height].every(Number.isFinite)||width<280||height<240)throw new Error("AttentionMatrix requires finite width >= 280 and height >= 240");const left=Math.max(70,Math.max(...queryNames.map(value=>value.length))*9+24);const top=106;const right=76;const bottom=64;const cellWidth=(width-left-right)/columns;const cellHeight=(height-top-bottom)/rows;if(cellWidth<24||cellHeight<20||keyNames.some(value=>value.length*7>cellWidth-6)){throw new Error("AttentionMatrix dimensions must leave room for readable cells and labels")}const text=(key,value,x,y,size=14,fill=c.textPrimary,anchor="middle",background)=>{const label=SvgMathText({text:value,x,y,fill,fontSize:size,fontFamily:c.fontSans,fontWeight:500,textAnchor:anchor,dominantBaseline:"alphabetic"});const style=label.props.style;return React19.cloneElement(label,{key,...background?{style:{...style,backgroundColor:background}}:{}})};const marks=[React19.createElement("title",{key:"title"},title),React19.createElement("desc",{key:"description"},"Rows are queries and columns are keys. Visible rows sum to one. Crosses denote masked keys. Values are attention probabilities, not explanations of model reasoning."),text("heading",title,22,30,20,c.textPrimary,"start"),text("keys","KEYS",left+(width-left-right)/2,58,12,c.textSecondary),text("query-heading","QUERY",22,81,12,c.textSecondary,"start"),text("sum-heading","\u03A3",width-30,81,16,c.textSecondary)];keyNames.forEach((label,j)=>marks.push(text(`key-${j}`,label,left+(j+.5)*cellWidth,top-13,14,activeKey===j?getReadableColor("primary",c):c.textSecondary)));weights.forEach((row,i)=>{const y=top+i*cellHeight;marks.push(text(`query-${i}`,queryNames[i],left-14,y+cellHeight/2+5,14,activeQuery===i?getReadableColor("primary",c):c.textSecondary,"end"));row.forEach((weight,j)=>{const x=left+j*cellWidth;const masked=mask?.[i][j]===false;const selected=activeQuery===i&&(activeKey===void 0||activeKey===j);const fill=masked?c.bgCardAlt:compositeColor(withColorAlpha(c.primary,.12+.88*weight),c.bg);marks.push(React19.createElement("rect",{key:`cell-${i}-${j}`,x:x+2,y:y+2,width:cellWidth-4,height:cellHeight-4,rx:4,fill,stroke:selected?c.primary:c.borderSubtle,strokeWidth:selected?2.5:1}));if(masked){const centerX=x+cellWidth/2,centerY=y+cellHeight/2;marks.push(React19.createElement("path",{key:`mask-${i}-${j}`,d:`M${centerX-4},${centerY-4}l8,8m-8,0l8,-8`,stroke:c.textMuted,strokeWidth:1.4}))}else{const label=weight.toFixed(2);if(cellWidth>=38&&cellHeight>=24)marks.push(text(`value-${i}-${j}`,label,x+cellWidth/2,y+cellHeight/2+5,14,getReadableTextColor(fill,c,c.bg),"middle",fill))}});const total=row.reduce((sum,value)=>sum+value,0);marks.push(text(`sum-${i}`,total.toFixed(0),width-30,y+cellHeight/2+5,14,c.textSecondary))});marks.push(text("footer","Probability per query \xB7 \xD7 masked \xB7 shared color scale 0\u20131",22,height-22,13,c.textSecondary,"start"));const isLabel=node=>React19.isValidElement(node)&&node.type==="div";return React19.createElement("div",{role:"img","aria-label":title,style:{position:"relative",display:"flex",width,height,backgroundColor:c.bg,flexShrink:0}},React19.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`},...marks.filter(node=>!isLabel(node))),...marks.filter(isLabel))}function validateMatrix(matrix,name){if(!Array.isArray(matrix)){throw new Error(`${name} must be a rectangular matrix`)}const columns=matrix[0]?.length??0;for(let rowIndex=0;rowIndex<matrix.length;rowIndex+=1){const row=matrix[rowIndex];if(!Array.isArray(row)||row.length!==columns){throw new Error(`${name} must be rectangular`)}for(let columnIndex=0;columnIndex<columns;columnIndex+=1){if(!Number.isFinite(row[columnIndex])){throw new Error(`${name} values must be finite numbers`)}}}return columns}function transposeMatrix(matrix){const columns=validateMatrix(matrix,"Matrix");return Array.from({length:columns},(_,columnIndex)=>matrix.map(row=>row[columnIndex]))}import React20 from"react";var MAX_IMAGE_AXIS=128;var MAX_IMAGE_PIXELS=1024;var MAX_COMPONENT_SIZE=32768;function validateRgbImage(pixels){if(!Array.isArray(pixels)||pixels.length===0){throw new Error("RGB image must contain at least one nonempty row")}if(pixels.length>MAX_IMAGE_AXIS){throw new Error(`RGB image dimensions must be at most ${MAX_IMAGE_AXIS} rows and ${MAX_IMAGE_AXIS} columns`)}const firstRow=pixels[0];if(!Array.isArray(firstRow)||firstRow.length===0){throw new Error("RGB image must contain at least one nonempty row")}const columns=firstRow.length;if(columns>MAX_IMAGE_AXIS){throw new Error(`RGB image dimensions must be at most ${MAX_IMAGE_AXIS} rows and ${MAX_IMAGE_AXIS} columns`)}if(pixels.length*columns>MAX_IMAGE_PIXELS){throw new Error(`RGB image must contain at most ${MAX_IMAGE_PIXELS} pixels`)}for(const[rowIndex,row]of pixels.entries()){if(!Array.isArray(row)||row.length!==columns){throw new Error("RGB image rows must be rectangular and nonempty")}for(const[columnIndex,pixel]of row.entries()){if(!Array.isArray(pixel)||pixel.length!==3){throw new Error(`RGB pixel at row ${rowIndex}, column ${columnIndex} must contain exactly three channels`)}for(const[channelIndex,value]of pixel.entries()){if(!Number.isInteger(value)||value<0||value>255){throw new Error(`RGB channel ${channelIndex} at row ${rowIndex}, column ${columnIndex} must be an integer from 0 to 255`)}}}}return{rows:pixels.length,columns}}function validateChannel(channel){if(channel!=="rgb"&&channel!=="red"&&channel!=="green"&&channel!=="blue"){throw new Error("RGB channel must be 'rgb', 'red', 'green', or 'blue'")}}function validateRegion(region,shape){if(!region||typeof region!=="object")throw new Error("Pixel region must be an object with integer bounds");const{row,column,rows,columns}=region;if(![row,column,rows,columns].every(Number.isInteger)||row<0||column<0||rows<1||columns<1){throw new Error("Pixel region row and column must be nonnegative integers, with positive integer rows and columns")}if(row+rows>shape.rows||column+columns>shape.columns){throw new Error("Pixel region must lie within the RGB image bounds")}}function validateCell(cell,shape){if(!cell||typeof cell!=="object")throw new Error("Active pixel cell must be an object with integer coordinates");if(!Number.isInteger(cell.row)||!Number.isInteger(cell.column)||cell.row<0||cell.column<0||cell.row>=shape.rows||cell.column>=shape.columns){throw new Error("Active pixel cell must lie within the RGB image bounds")}}function rgbChannel(pixels,channel){const{columns}=validateRgbImage(pixels);if(channel!=="red"&&channel!=="green"&&channel!=="blue"){throw new Error("RGB matrix channel must be 'red', 'green', or 'blue'")}const channelIndex=channel==="red"?0:channel==="green"?1:2;return pixels.map(row=>Array.from({length:columns},(_,column)=>row[column][channelIndex]))}function cropRgbImage(pixels,region){const shape=validateRgbImage(pixels);validateRegion(region,shape);return pixels.slice(region.row,region.row+region.rows).map(row=>row.slice(region.column,region.column+region.columns).map(pixel=>[pixel[0],pixel[1],pixel[2]]))}function flattenRgbImage(pixels,layout="HWC",normalize=false){validateRgbImage(pixels);if(layout!=="HWC"&&layout!=="CHW")throw new Error("RGB tensor layout must be 'HWC' or 'CHW'");if(typeof normalize!=="boolean")throw new Error("RGB tensor normalization must be a boolean");const values=layout==="HWC"?pixels.flatMap(row=>row.flatMap(pixel=>[pixel[0],pixel[1],pixel[2]])):Array.from({length:3},(_,channel)=>pixels.flatMap(row=>row.map(pixel=>pixel[channel]))).flat();return normalize?values.map(value=>value/255):values}function PixelGrid({pixels,c=getThemeColors("dark"),width=320,height=320,channel="rgb",region,activeCell,highlightColor}){const shape=validateRgbImage(pixels);validateChannel(channel);if(![width,height].every(value=>Number.isFinite(value)&&value>0&&value<=MAX_COMPONENT_SIZE)){throw new Error(`PixelGrid width and height must be finite values greater than 0 and at most ${MAX_COMPONENT_SIZE}`)}if(region!==void 0)validateRegion(region,shape);if(activeCell!==void 0)validateCell(activeCell,shape);if(highlightColor!==void 0&&(typeof highlightColor!=="string"||highlightColor.trim().length===0)){throw new Error("PixelGrid highlightColor must be a nonempty color string")}const pixelSize=Math.min(width/shape.columns,height/shape.rows);const imageWidth=pixelSize*shape.columns;const imageHeight=pixelSize*shape.rows;const offsetX=(width-imageWidth)/2;const offsetY=(height-imageHeight)/2;const colorFor=pixel=>{const rgb=channel==="red"?[pixel[0],0,0]:channel==="green"?[0,pixel[1],0]:channel==="blue"?[0,0,pixel[2]]:pixel;return`rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`};const cells=pixels.flatMap((row,rowIndex)=>row.map((pixel,columnIndex)=>React20.createElement("rect",{key:`pixel-${rowIndex}-${columnIndex}`,x:offsetX+columnIndex*pixelSize,y:offsetY+rowIndex*pixelSize,width:pixelSize,height:pixelSize,fill:colorFor(pixel)})));const strokeWidth=pixelSize*.16;const marks=[...cells];if(region){marks.push(React20.createElement("rect",{key:"region-highlight",x:offsetX+region.column*pixelSize+strokeWidth/2,y:offsetY+region.row*pixelSize+strokeWidth/2,width:region.columns*pixelSize-strokeWidth,height:region.rows*pixelSize-strokeWidth,fill:"none",stroke:highlightColor??c.primary,strokeWidth,strokeDasharray:`${pixelSize*.32} ${pixelSize*.2}`}))}if(activeCell){marks.push(React20.createElement("rect",{key:"active-cell-highlight",x:offsetX+activeCell.column*pixelSize+strokeWidth/2,y:offsetY+activeCell.row*pixelSize+strokeWidth/2,width:pixelSize-strokeWidth,height:pixelSize-strokeWidth,fill:"none",stroke:c.warning,strokeWidth}))}const channelLabel=channel==="rgb"?"RGB":`${channel} channel`;return React20.createElement("div",{role:"img","aria-label":`${shape.rows} by ${shape.columns} pixel image, ${channelLabel}`,style:{position:"relative",display:"flex",width,height,backgroundColor:c.bgCard,flexShrink:0}},React20.createElement("svg",{width,height,viewBox:`0 0 ${width} ${height}`,preserveAspectRatio:"xMidYMid meet",shapeRendering:"crispEdges"},...marks))}function validateMatrix2(matrix,name){if(!Array.isArray(matrix)||matrix.length===0||!Array.isArray(matrix[0])||matrix[0].length===0){throw new Error(`${name} must be a nonempty rectangular matrix`)}const columns=matrix[0].length;for(let rowIndex=0;rowIndex<matrix.length;rowIndex+=1){const row=matrix[rowIndex];if(!Array.isArray(row)||row.length!==columns){throw new Error(`${name} must be rectangular`)}for(let columnIndex=0;columnIndex<columns;columnIndex+=1){if(!Number.isFinite(row[columnIndex])){throw new Error(`${name} values must be finite numbers`)}}}return{rows:matrix.length,columns}}function crossCorrelate2d(input,kernel,options={}){const inputShape=validateMatrix2(input,"Input image");const kernelShape=validateMatrix2(kernel,"Kernel");const stride=options.stride??1;const padding=options.padding??"valid";if(!Number.isSafeInteger(stride)||stride<1){throw new Error("Kernel stride must be a positive integer")}if(padding!=="valid"&&padding!=="same"){throw new Error("Kernel padding must be 'valid' or 'same'")}const outputRows=padding==="same"?Math.ceil(inputShape.rows/stride):Math.floor((inputShape.rows-kernelShape.rows)/stride)+1;const outputColumns=padding==="same"?Math.ceil(inputShape.columns/stride):Math.floor((inputShape.columns-kernelShape.columns)/stride)+1;if(outputRows<1||outputColumns<1){throw new Error("Kernel must fit inside the input image when padding is 'valid'")}const totalPaddingRows=Math.max((outputRows-1)*stride+kernelShape.rows-inputShape.rows,0);const totalPaddingColumns=Math.max((outputColumns-1)*stride+kernelShape.columns-inputShape.columns,0);const topPadding=Math.floor(totalPaddingRows/2);const leftPadding=Math.floor(totalPaddingColumns/2);const result=Array.from({length:outputRows},(_,outputRow)=>Array.from({length:outputColumns},(_2,outputColumn)=>{let sum=0;for(let kernelRow=0;kernelRow<kernelShape.rows;kernelRow+=1){const inputRow=outputRow*stride+kernelRow-topPadding;if(inputRow<0||inputRow>=inputShape.rows)continue;for(let kernelColumn=0;kernelColumn<kernelShape.columns;kernelColumn+=1){const inputColumn=outputColumn*stride+kernelColumn-leftPadding;if(inputColumn<0||inputColumn>=inputShape.columns)continue;sum+=input[inputRow][inputColumn]*kernel[kernelRow][kernelColumn]}}if(!Number.isFinite(sum)){throw new Error("Kernel output values must be finite numbers")}return sum}));return result}function gaussianKernel(size,sigma){if(!Number.isSafeInteger(size)||size<1||size%2===0){throw new Error("Gaussian kernel size must be a positive odd integer")}if(!Number.isFinite(sigma)||sigma<=0){throw new Error("Gaussian sigma must be a positive finite number")}const radius=Math.floor(size/2);const weights=Array.from({length:size},(_,row)=>Array.from({length:size},(_2,column)=>{const x=column-radius;const y=row-radius;const normalizedX=x/sigma;const normalizedY=y/sigma;return Math.exp(-(normalizedX*normalizedX+normalizedY*normalizedY)/2)}));const total=weights.flat().reduce((sum,value)=>sum+value,0);return weights.map(row=>row.map(value=>value/total))}import{Unzlib as Inflator,unzlibSync}from"fflate";function decode(bytes,encoding="utf8"){const decoder=new TextDecoder(encoding);return decoder.decode(bytes)}var encoder=new TextEncoder;function encode(str){return encoder.encode(str)}var defaultByteLength=1024*8;var hostBigEndian=(()=>{const array=new Uint8Array(4);const view=new Uint32Array(array.buffer);return!((view[0]=1)&array[0])})();var typedArrays={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};var IOBuffer=class _IOBuffer{buffer;byteLength;byteOffset;length;offset;lastWrittenByte;littleEndian;_data;_mark;_marks;constructor(data=defaultByteLength,options={}){let dataIsGiven=false;if(typeof data==="number"){data=new ArrayBuffer(data)}else{dataIsGiven=true;this.lastWrittenByte=data.byteLength}const offset=options.offset?options.offset>>>0:0;const byteLength=data.byteLength-offset;let dvOffset=offset;if(ArrayBuffer.isView(data)||data instanceof _IOBuffer){if(data.byteLength!==data.buffer.byteLength){dvOffset=data.byteOffset+offset}data=data.buffer}if(dataIsGiven){this.lastWrittenByte=byteLength}else{this.lastWrittenByte=0}this.buffer=data;this.length=byteLength;this.byteLength=byteLength;this.byteOffset=dvOffset;this.offset=0;this.littleEndian=true;this._data=new DataView(this.buffer,dvOffset,byteLength);this._mark=0;this._marks=[]}available(byteLength=1){return this.offset+byteLength<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){this.littleEndian=true;return this}isBigEndian(){return!this.littleEndian}setBigEndian(){this.littleEndian=false;return this}skip(n=1){this.offset+=n;return this}back(n=1){this.offset-=n;return this}seek(offset){this.offset=offset;return this}mark(){this._mark=this.offset;return this}reset(){this.offset=this._mark;return this}pushMark(){this._marks.push(this.offset);return this}popMark(){const offset=this._marks.pop();if(offset===void 0){throw new Error("Mark stack empty")}this.seek(offset);return this}rewind(){this.offset=0;return this}ensureAvailable(byteLength=1){if(!this.available(byteLength)){const lengthNeeded=this.offset+byteLength;const newLength=lengthNeeded*2;const newArray=new Uint8Array(newLength);newArray.set(new Uint8Array(this.buffer));this.buffer=newArray.buffer;this.length=newLength;this.byteLength=newLength;this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(n=1){return this.readArray(n,"uint8")}readArray(size,type){const bytes=typedArrays[type].BYTES_PER_ELEMENT*size;const offset=this.byteOffset+this.offset;const slice=this.buffer.slice(offset,offset+bytes);if(this.littleEndian===hostBigEndian&&type!=="uint8"&&type!=="int8"){const slice2=new Uint8Array(this.buffer.slice(offset,offset+bytes));slice2.reverse();const returnArray2=new typedArrays[type](slice2.buffer);this.offset+=bytes;returnArray2.reverse();return returnArray2}const returnArray=new typedArrays[type](slice);this.offset+=bytes;return returnArray}readInt16(){const value=this._data.getInt16(this.offset,this.littleEndian);this.offset+=2;return value}readUint16(){const value=this._data.getUint16(this.offset,this.littleEndian);this.offset+=2;return value}readInt32(){const value=this._data.getInt32(this.offset,this.littleEndian);this.offset+=4;return value}readUint32(){const value=this._data.getUint32(this.offset,this.littleEndian);this.offset+=4;return value}readFloat32(){const value=this._data.getFloat32(this.offset,this.littleEndian);this.offset+=4;return value}readFloat64(){const value=this._data.getFloat64(this.offset,this.littleEndian);this.offset+=8;return value}readBigInt64(){const value=this._data.getBigInt64(this.offset,this.littleEndian);this.offset+=8;return value}readBigUint64(){const value=this._data.getBigUint64(this.offset,this.littleEndian);this.offset+=8;return value}readChar(){return String.fromCharCode(this.readInt8())}readChars(n=1){let result="";for(let i=0;i<n;i++){result+=this.readChar()}return result}readUtf8(n=1){return decode(this.readBytes(n))}decodeText(n=1,encoding="utf8"){return decode(this.readBytes(n),encoding)}writeBoolean(value){this.writeUint8(value?255:0);return this}writeInt8(value){this.ensureAvailable(1);this._data.setInt8(this.offset++,value);this._updateLastWrittenByte();return this}writeUint8(value){this.ensureAvailable(1);this._data.setUint8(this.offset++,value);this._updateLastWrittenByte();return this}writeByte(value){return this.writeUint8(value)}writeBytes(bytes){this.ensureAvailable(bytes.length);for(let i=0;i<bytes.length;i++){this._data.setUint8(this.offset++,bytes[i])}this._updateLastWrittenByte();return this}writeInt16(value){this.ensureAvailable(2);this._data.setInt16(this.offset,value,this.littleEndian);this.offset+=2;this._updateLastWrittenByte();return this}writeUint16(value){this.ensureAvailable(2);this._data.setUint16(this.offset,value,this.littleEndian);this.offset+=2;this._updateLastWrittenByte();return this}writeInt32(value){this.ensureAvailable(4);this._data.setInt32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeUint32(value){this.ensureAvailable(4);this._data.setUint32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeFloat32(value){this.ensureAvailable(4);this._data.setFloat32(this.offset,value,this.littleEndian);this.offset+=4;this._updateLastWrittenByte();return this}writeFloat64(value){this.ensureAvailable(8);this._data.setFloat64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeBigInt64(value){this.ensureAvailable(8);this._data.setBigInt64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeBigUint64(value){this.ensureAvailable(8);this._data.setBigUint64(this.offset,value,this.littleEndian);this.offset+=8;this._updateLastWrittenByte();return this}writeChar(str){return this.writeUint8(str.charCodeAt(0))}writeChars(str){for(let i=0;i<str.length;i++){this.writeUint8(str.charCodeAt(i))}return this}writeUtf8(str){return this.writeBytes(encode(str))}toArray(){return new Uint8Array(this.buffer,this.byteOffset,this.lastWrittenByte)}getWrittenByteLength(){return this.lastWrittenByte-this.byteOffset}_updateLastWrittenByte(){if(this.offset>this.lastWrittenByte){this.lastWrittenByte=this.offset}}};var crcTable=[];for(let n=0;n<256;n++){let c=n;for(let k=0;k<8;k++){if(c&1){c=3988292384^c>>>1}else{c=c>>>1}}crcTable[n]=c}var initialCrc=4294967295;function updateCrc(currentCrc,data,length){let c=currentCrc;for(let n=0;n<length;n++){c=crcTable[(c^data[n])&255]^c>>>8}return c}function crc(data,length){return(updateCrc(initialCrc,data,length)^initialCrc)>>>0}function checkCrc(buffer,crcLength,chunkName){const expectedCrc=buffer.readUint32();const actualCrc=crc(new Uint8Array(buffer.buffer,buffer.byteOffset+buffer.offset-crcLength-4,crcLength),crcLength);if(actualCrc!==expectedCrc){throw new Error(`CRC mismatch for chunk ${chunkName}. Expected ${expectedCrc}, found ${actualCrc}`)}}function writeCrc(buffer,length){buffer.writeUint32(crc(new Uint8Array(buffer.buffer,buffer.byteOffset+buffer.offset-length,length),length))}function unfilterNone(currentLine,newLine,bytesPerLine){for(let i=0;i<bytesPerLine;i++){newLine[i]=currentLine[i]}}function unfilterSub(currentLine,newLine,bytesPerLine,bytesPerPixel){let i=0;for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+newLine[i-bytesPerPixel]&255}}function unfilterUp(currentLine,newLine,prevLine,bytesPerLine){let i=0;if(prevLine.length===0){for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]}}else{for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+prevLine[i]&255}}}function unfilterAverage(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel){let i=0;if(prevLine.length===0){for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+(newLine[i-bytesPerPixel]>>1)&255}}else{for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]+(prevLine[i]>>1)&255}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+(newLine[i-bytesPerPixel]+prevLine[i]>>1)&255}}}function unfilterPaeth(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel){let i=0;if(prevLine.length===0){for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+newLine[i-bytesPerPixel]&255}}else{for(;i<bytesPerPixel;i++){newLine[i]=currentLine[i]+prevLine[i]&255}for(;i<bytesPerLine;i++){newLine[i]=currentLine[i]+paethPredictor(newLine[i-bytesPerPixel],prevLine[i],prevLine[i-bytesPerPixel])&255}}}function paethPredictor(a,b,c){const p=a+b-c;const pa=Math.abs(p-a);const pb=Math.abs(p-b);const pc=Math.abs(p-c);if(pa<=pb&&pa<=pc)return a;else if(pb<=pc)return b;else return c}function applyUnfilter(filterType,currentLine,newLine,prevLine,passLineBytes,bytesPerPixel){switch(filterType){case 0:unfilterNone(currentLine,newLine,passLineBytes);break;case 1:unfilterSub(currentLine,newLine,passLineBytes,bytesPerPixel);break;case 2:unfilterUp(currentLine,newLine,prevLine,passLineBytes);break;case 3:unfilterAverage(currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);break;case 4:unfilterPaeth(currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);break;default:throw new Error(`Unsupported filter: ${filterType}`)}}var uint16=new Uint16Array([255]);var uint8=new Uint8Array(uint16.buffer);var osIsLittleEndian=uint8[0]===255;function decodeInterlaceAdam7(params){const{data,width,height,channels,depth}=params;const passes=[{x:0,y:0,xStep:8,yStep:8},{x:4,y:0,xStep:8,yStep:8},{x:0,y:4,xStep:4,yStep:8},{x:2,y:0,xStep:4,yStep:4},{x:0,y:2,xStep:2,yStep:4},{x:1,y:0,xStep:2,yStep:2},{x:0,y:1,xStep:1,yStep:2}];const bytesPerPixel=Math.ceil(depth/8)*channels;const resultData=new Uint8Array(height*width*bytesPerPixel);let offset=0;for(let passIndex=0;passIndex<7;passIndex++){const pass=passes[passIndex];const passWidth=Math.ceil((width-pass.x)/pass.xStep);const passHeight=Math.ceil((height-pass.y)/pass.yStep);if(passWidth<=0||passHeight<=0)continue;const passLineBytes=passWidth*bytesPerPixel;const prevLine=new Uint8Array(passLineBytes);for(let y=0;y<passHeight;y++){const filterType=data[offset++];const currentLine=data.subarray(offset,offset+passLineBytes);offset+=passLineBytes;const newLine=new Uint8Array(passLineBytes);applyUnfilter(filterType,currentLine,newLine,prevLine,passLineBytes,bytesPerPixel);prevLine.set(newLine);for(let x=0;x<passWidth;x++){const outputX=pass.x+x*pass.xStep;const outputY=pass.y+y*pass.yStep;if(outputX>=width||outputY>=height)continue;for(let i=0;i<bytesPerPixel;i++){resultData[(outputY*width+outputX)*bytesPerPixel+i]=newLine[x*bytesPerPixel+i]}}}}if(depth===16){const uint16Data=new Uint16Array(resultData.buffer);if(osIsLittleEndian){for(let k=0;k<uint16Data.length;k++){uint16Data[k]=swap16(uint16Data[k])}}return uint16Data}else{return resultData}}function swap16(val){return(val&255)<<8|val>>8&255}var uint162=new Uint16Array([255]);var uint82=new Uint8Array(uint162.buffer);var osIsLittleEndian2=uint82[0]===255;var empty=new Uint8Array(0);function decodeInterlaceNull(params){const{data,width,height,channels,depth}=params;const bytesPerPixel=Math.ceil(depth/8)*channels;const bytesPerLine=Math.ceil(depth/8*channels*width);const newData=new Uint8Array(height*bytesPerLine);let prevLine=empty;let offset=0;let currentLine;let newLine;for(let i=0;i<height;i++){currentLine=data.subarray(offset+1,offset+1+bytesPerLine);newLine=newData.subarray(i*bytesPerLine,(i+1)*bytesPerLine);switch(data[offset]){case 0:unfilterNone(currentLine,newLine,bytesPerLine);break;case 1:unfilterSub(currentLine,newLine,bytesPerLine,bytesPerPixel);break;case 2:unfilterUp(currentLine,newLine,prevLine,bytesPerLine);break;case 3:unfilterAverage(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel);break;case 4:unfilterPaeth(currentLine,newLine,prevLine,bytesPerLine,bytesPerPixel);break;default:throw new Error(`Unsupported filter: ${data[offset]}`)}prevLine=newLine;offset+=bytesPerLine+1}if(depth===16){const uint16Data=new Uint16Array(newData.buffer);if(osIsLittleEndian2){for(let k=0;k<uint16Data.length;k++){uint16Data[k]=swap162(uint16Data[k])}}return uint16Data}else{return newData}}function swap162(val){return(val&255)<<8|val>>8&255}var pngSignature=Uint8Array.of(137,80,78,71,13,10,26,10);function writeSignature(buffer){buffer.writeBytes(pngSignature)}function checkSignature(buffer){if(!hasPngSignature(buffer.readBytes(pngSignature.length))){throw new Error("wrong PNG signature")}}function hasPngSignature(array){if(array.length<pngSignature.length){return false}for(let i=0;i<pngSignature.length;i++){if(array[i]!==pngSignature[i]){return false}}return true}var textChunkName="tEXt";var NULL=0;var latin1Decoder=new TextDecoder("latin1");function validateKeyword(keyword){validateLatin1(keyword);if(keyword.length===0||keyword.length>79){throw new Error("keyword length must be between 1 and 79")}}var latin1Regex=/^[\u0000-\u00FF]*$/;function validateLatin1(text){if(!latin1Regex.test(text)){throw new Error("invalid latin1 text")}}function decodetEXt(text,buffer,length){const keyword=readKeyword(buffer);text[keyword]=readLatin1(buffer,length-keyword.length-1)}function encodetEXt(buffer,keyword,text){validateKeyword(keyword);validateLatin1(text);const length=keyword.length+1+text.length;buffer.writeUint32(length);buffer.writeChars(textChunkName);buffer.writeChars(keyword);buffer.writeByte(NULL);buffer.writeChars(text);writeCrc(buffer,length+4)}function readKeyword(buffer){buffer.mark();while(buffer.readByte()!==NULL){}const end=buffer.offset;buffer.reset();const keyword=latin1Decoder.decode(buffer.readBytes(end-buffer.offset-1));buffer.skip(1);validateKeyword(keyword);return keyword}function readLatin1(buffer,length){return latin1Decoder.decode(buffer.readBytes(length))}var ColorType={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6};var CompressionMethod={UNKNOWN:-1,DEFLATE:0};var FilterMethod={UNKNOWN:-1,ADAPTIVE:0};var InterlaceMethod={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1};var DisposeOpType={NONE:0,BACKGROUND:1,PREVIOUS:2};var BlendOpType={SOURCE:0,OVER:1};var PngDecoder=class extends IOBuffer{_checkCrc;_inflator;_png;_apng;_end;_hasPalette;_palette;_hasTransparency;_transparency;_compressionMethod;_filterMethod;_interlaceMethod;_colorType;_isAnimated;_numberOfFrames;_numberOfPlays;_frames;_writingDataChunks;_chunks;_inflatorResult;constructor(data,options={}){super(data);const{checkCrc:checkCrc2=false}=options;this._checkCrc=checkCrc2;this._inflator=new Inflator((chunk,final)=>{this._chunks.push(chunk);if(final){const totalLength=this._chunks.reduce((sum,c)=>sum+c.length,0);this._inflatorResult=new Uint8Array(totalLength);let offset=0;for(const chunk2 of this._chunks){this._inflatorResult.set(chunk2,offset);offset+=chunk2.length}this._chunks=[]}});this._chunks=[];this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}};this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]};this._end=false;this._hasPalette=false;this._palette=[];this._hasTransparency=false;this._transparency=new Uint16Array(0);this._compressionMethod=CompressionMethod.UNKNOWN;this._filterMethod=FilterMethod.UNKNOWN;this._interlaceMethod=InterlaceMethod.UNKNOWN;this._colorType=ColorType.UNKNOWN;this._isAnimated=false;this._numberOfFrames=1;this._numberOfPlays=0;this._frames=[];this._writingDataChunks=false;this._inflatorResult=new Uint8Array(0);this.setBigEndian()}decode(){checkSignature(this);while(!this._end){const length=this.readUint32();const type=this.readChars(4);this.decodeChunk(length,type)}this._inflator.push(new Uint8Array(0),true);this.decodeImage();return this._png}decodeApng(){checkSignature(this);while(!this._end){const length=this.readUint32();const type=this.readChars(4);this.decodeApngChunk(length,type)}this.decodeApngImage();return this._apng}decodeChunk(length,type){const offset=this.offset;switch(type){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(length);break;case"IDAT":this.decodeIDAT(length);break;case"IEND":this._end=true;break;case"tRNS":this.decodetRNS(length);break;case"iCCP":this.decodeiCCP(length);break;case textChunkName:decodetEXt(this._png.text,this,length);break;case"pHYs":this.decodepHYs();break;default:this.skip(length);break}if(this.offset-offset!==length){throw new Error(`Length mismatch while decoding chunk ${type}`)}if(this._checkCrc){checkCrc(this,length+4,type)}else{this.skip(4)}}decodeApngChunk(length,type){const offset=this.offset;if(type!=="fdAT"&&type!=="IDAT"&&this._writingDataChunks){this.pushDataToFrame()}switch(type){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(length);break;default:this.decodeChunk(length,type);this.offset=offset+length;break}if(this.offset-offset!==length){throw new Error(`Length mismatch while decoding chunk ${type}`)}if(this._checkCrc){checkCrc(this,length+4,type)}else{this.skip(4)}}decodeIHDR(){const image=this._png;image.width=this.readUint32();image.height=this.readUint32();image.depth=checkBitDepth(this.readUint8());const colorType=this.readUint8();this._colorType=colorType;let channels;switch(colorType){case ColorType.GREYSCALE:channels=1;break;case ColorType.TRUECOLOUR:channels=3;break;case ColorType.INDEXED_COLOUR:channels=1;break;case ColorType.GREYSCALE_ALPHA:channels=2;break;case ColorType.TRUECOLOUR_ALPHA:channels=4;break;case ColorType.UNKNOWN:default:throw new Error(`Unknown color type: ${colorType}`)}this._png.channels=channels;this._compressionMethod=this.readUint8();if(this._compressionMethod!==CompressionMethod.DEFLATE){throw new Error(`Unsupported compression method: ${this._compressionMethod}`)}this._filterMethod=this.readUint8();this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32();this._numberOfPlays=this.readUint32();this._isAnimated=true}decodeFCTL(){const image={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(image)}decodePLTE(length){if(length%3!==0){throw new RangeError(`PLTE field length must be a multiple of 3. Got ${length}`)}const l=length/3;this._hasPalette=true;const palette=[];this._palette=palette;for(let i=0;i<l;i++){palette.push([this.readUint8(),this.readUint8(),this.readUint8()])}}decodeIDAT(length){this._writingDataChunks=true;const dataLength=length;const dataOffset=this.offset+this.byteOffset;try{this._inflator.push(new Uint8Array(this.buffer,dataOffset,dataLength),false)}catch(error){throw new Error("Error while decompressing the data:",{cause:error})}this.skip(length)}decodeFDAT(length){this._writingDataChunks=true;let dataLength=length;let dataOffset=this.offset+this.byteOffset;dataOffset+=4;dataLength-=4;try{this._inflator.push(new Uint8Array(this.buffer,dataOffset,dataLength),false)}catch(error){throw new Error("Error while decompressing the data:",{cause:error})}this.skip(length)}decodetRNS(length){switch(this._colorType){case ColorType.GREYSCALE:case ColorType.TRUECOLOUR:{if(length%2!==0){throw new RangeError(`tRNS chunk length must be a multiple of 2. Got ${length}`)}if(length/2>this._png.width*this._png.height){throw new Error(`tRNS chunk contains more alpha values than there are pixels (${length/2} vs ${this._png.width*this._png.height})`)}this._hasTransparency=true;this._transparency=new Uint16Array(length/2);for(let i=0;i<length/2;i++){this._transparency[i]=this.readUint16()}break}case ColorType.INDEXED_COLOUR:{if(length>this._palette.length){throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${length} vs ${this._palette.length})`)}let i=0;for(;i<length;i++){const alpha=this.readByte();this._palette[i].push(alpha)}for(;i<this._palette.length;i++){this._palette[i].push(255)}break}case ColorType.UNKNOWN:case ColorType.GREYSCALE_ALPHA:case ColorType.TRUECOLOUR_ALPHA:default:{throw new Error(`tRNS chunk is not supported for color type ${this._colorType}`)}}}decodeiCCP(length){const name=readKeyword(this);const compressionMethod=this.readUint8();if(compressionMethod!==CompressionMethod.DEFLATE){throw new Error(`Unsupported iCCP compression method: ${compressionMethod}`)}const compressedProfile=this.readBytes(length-name.length-2);this._png.iccEmbeddedProfile={name,profile:unzlibSync(compressedProfile)}}decodepHYs(){const ppuX=this.readUint32();const ppuY=this.readUint32();const unitSpecifier=this.readByte();this._png.resolution={x:ppuX,y:ppuY,unit:unitSpecifier}}decodeApngImage(){this._apng.width=this._png.width;this._apng.height=this._png.height;this._apng.channels=this._png.channels;this._apng.depth=this._png.depth;this._apng.numberOfFrames=this._numberOfFrames;this._apng.numberOfPlays=this._numberOfPlays;this._apng.text=this._png.text;this._apng.resolution=this._png.resolution;for(let i=0;i<this._numberOfFrames;i++){const newFrame={sequenceNumber:this._frames[i].sequenceNumber,delayNumber:this._frames[i].delayNumber,delayDenominator:this._frames[i].delayDenominator,data:this._apng.depth===8?new Uint8Array(this._apng.width*this._apng.height*this._apng.channels):new Uint16Array(this._apng.width*this._apng.height*this._apng.channels)};const frame=this._frames.at(i);if(frame){frame.data=decodeInterlaceNull({data:frame.data,width:frame.width,height:frame.height,channels:this._apng.channels,depth:this._apng.depth});if(this._hasPalette){this._apng.palette=this._palette}if(this._hasTransparency){this._apng.transparency=this._transparency}if(i===0||frame.xOffset===0&&frame.yOffset===0&&frame.width===this._png.width&&frame.height===this._png.height){newFrame.data=frame.data}else{const prevFrame=this._apng.frames.at(i-1);this.disposeFrame(frame,prevFrame,newFrame);this.addFrameDataToCanvas(newFrame,frame)}this._apng.frames.push(newFrame)}}return this._apng}disposeFrame(frame,prevFrame,imageFrame){switch(frame.disposeOp){case DisposeOpType.NONE:break;case DisposeOpType.BACKGROUND:for(let row=0;row<this._png.height;row++){for(let col=0;col<this._png.width;col++){const index=(row*frame.width+col)*this._png.channels;for(let channel=0;channel<this._png.channels;channel++){imageFrame.data[index+channel]=0}}}break;case DisposeOpType.PREVIOUS:imageFrame.data.set(prevFrame.data);break;default:throw new Error("Unknown disposeOp")}}addFrameDataToCanvas(imageFrame,frame){const maxValue=1<<this._png.depth;const calculatePixelIndices=(row,col)=>{const index=((row+frame.yOffset)*this._png.width+frame.xOffset+col)*this._png.channels;const frameIndex=(row*frame.width+col)*this._png.channels;return{index,frameIndex}};switch(frame.blendOp){case BlendOpType.SOURCE:for(let row=0;row<frame.height;row++){for(let col=0;col<frame.width;col++){const{index,frameIndex}=calculatePixelIndices(row,col);for(let channel=0;channel<this._png.channels;channel++){imageFrame.data[index+channel]=frame.data[frameIndex+channel]}}}break;case BlendOpType.OVER:for(let row=0;row<frame.height;row++){for(let col=0;col<frame.width;col++){const{index,frameIndex}=calculatePixelIndices(row,col);for(let channel=0;channel<this._png.channels;channel++){const sourceAlpha=frame.data[frameIndex+this._png.channels-1]/maxValue;const foregroundValue=channel%(this._png.channels-1)===0?1:frame.data[frameIndex+channel];const value=Math.floor(sourceAlpha*foregroundValue+(1-sourceAlpha)*imageFrame.data[index+channel]);imageFrame.data[index+channel]+=value}}}break;default:throw new Error("Unknown blendOp")}}decodeImage(){const data=this._inflatorResult;if(this._filterMethod!==FilterMethod.ADAPTIVE){throw new Error(`Filter method ${this._filterMethod} not supported`)}if(this._interlaceMethod===InterlaceMethod.NO_INTERLACE){this._png.data=decodeInterlaceNull({data,width:this._png.width,height:this._png.height,channels:this._png.channels,depth:this._png.depth})}else if(this._interlaceMethod===InterlaceMethod.ADAM7){this._png.data=decodeInterlaceAdam7({data,width:this._png.width,height:this._png.height,channels:this._png.channels,depth:this._png.depth})}else{throw new Error(`Interlace method ${this._interlaceMethod} not supported`)}if(this._hasPalette){this._png.palette=this._palette}if(this._hasTransparency){this._png.transparency=this._transparency}}pushDataToFrame(){this._inflator.push(new Uint8Array(0),true);const result=this._inflatorResult;const lastFrame=this._frames.at(-1);if(lastFrame){lastFrame.data=result}else{this._frames.push({sequenceNumber:0,width:this._png.width,height:this._png.height,xOffset:0,yOffset:0,delayNumber:0,delayDenominator:0,disposeOp:DisposeOpType.NONE,blendOp:BlendOpType.SOURCE,data:result})}this._inflator=new Inflator((chunk,final)=>{this._chunks.push(chunk);if(final){const totalLength=this._chunks.reduce((sum,c)=>sum+c.length,0);this._inflatorResult=new Uint8Array(totalLength);let offset=0;for(const chunk2 of this._chunks){this._inflatorResult.set(chunk2,offset);offset+=chunk2.length}this._chunks=[]}});this._chunks=[];this._writingDataChunks=false}};function checkBitDepth(value){if(value!==1&&value!==2&&value!==4&&value!==8&&value!==16){throw new Error(`invalid bit depth: ${value}`)}return value}import{zlibSync}from"fflate";var defaultZlibOptions={level:3};var PngEncoder=class extends IOBuffer{_png;_zlibOptions;_colorType;_interlaceMethod;constructor(data,options={}){super();this._colorType=ColorType.UNKNOWN;this._zlibOptions={...defaultZlibOptions,...options.zlib};this._png=this._checkData(data);this._interlaceMethod=(options.interlace==="Adam7"?InterlaceMethod.ADAM7:InterlaceMethod.NO_INTERLACE)??InterlaceMethod.NO_INTERLACE;this.setBigEndian()}encode(){writeSignature(this);this.encodeIHDR();if(this._png.palette){this.encodePLTE();if(this._png.palette[0].length===4){this.encodeTRNS()}}this.encodeData();if(this._png.text){for(const[keyword,text]of Object.entries(this._png.text)){encodetEXt(this,keyword,text)}}this.encodeIEND();return this.toArray()}encodeIHDR(){this.writeUint32(13);this.writeChars("IHDR");this.writeUint32(this._png.width);this.writeUint32(this._png.height);this.writeByte(this._png.depth);this.writeByte(this._colorType);this.writeByte(CompressionMethod.DEFLATE);this.writeByte(FilterMethod.ADAPTIVE);this.writeByte(this._interlaceMethod);writeCrc(this,17)}encodeIEND(){this.writeUint32(0);this.writeChars("IEND");writeCrc(this,4)}encodePLTE(){const paletteLength=this._png.palette?.length*3;this.writeUint32(paletteLength);this.writeChars("PLTE");for(const color of this._png.palette){this.writeByte(color[0]);this.writeByte(color[1]);this.writeByte(color[2])}writeCrc(this,4+paletteLength)}encodeTRNS(){const alpha=this._png.palette.filter(color=>{return color.at(-1)!==255});this.writeUint32(alpha.length);this.writeChars("tRNS");for(const el of alpha){this.writeByte(el.at(-1))}writeCrc(this,4+alpha.length)}encodeIDAT(data){this.writeUint32(data.length);this.writeChars("IDAT");this.writeBytes(data);writeCrc(this,data.length+4)}encodeData(){const{width,height,channels,depth,data}=this._png;const slotsPerLine=depth<=8?Math.ceil(width*depth/8)*channels:Math.ceil(width*depth/8*channels/2);const newData=new IOBuffer().setBigEndian();let offset=0;if(this._interlaceMethod===InterlaceMethod.NO_INTERLACE){for(let i=0;i<height;i++){newData.writeByte(0);if(depth===16){offset=writeDataUint16(data,newData,slotsPerLine,offset)}else{offset=writeDataBytes(data,newData,slotsPerLine,offset)}}}else if(this._interlaceMethod===InterlaceMethod.ADAM7){offset=writeDataInterlaced(this._png,data,newData,offset)}const buffer=newData.toArray();const compressed=zlibSync(buffer,this._zlibOptions);this.encodeIDAT(compressed)}_checkData(data){const{colorType,channels,depth}=getColorType(data,data.palette);const png={width:checkInteger(data.width,"width"),height:checkInteger(data.height,"height"),channels,data:data.data,depth,text:data.text,palette:data.palette};this._colorType=colorType;const expectedSize=depth<8?Math.ceil(png.width*depth/8)*png.height*channels:png.width*png.height*channels;if(png.data.length!==expectedSize){throw new RangeError(`wrong data size. Found ${png.data.length}, expected ${expectedSize}`)}return png}};function checkInteger(value,name){if(Number.isInteger(value)&&value>0){return value}throw new TypeError(`${name} must be a positive integer`)}function getColorType(data,palette){const{channels=4,depth=8}=data;if(channels!==4&&channels!==3&&channels!==2&&channels!==1){throw new RangeError(`unsupported number of channels: ${channels}`)}const returnValue={channels,depth,colorType:ColorType.UNKNOWN};switch(channels){case 4:returnValue.colorType=ColorType.TRUECOLOUR_ALPHA;break;case 3:returnValue.colorType=ColorType.TRUECOLOUR;break;case 1:if(palette){returnValue.colorType=ColorType.INDEXED_COLOUR}else{returnValue.colorType=ColorType.GREYSCALE}break;case 2:returnValue.colorType=ColorType.GREYSCALE_ALPHA;break;default:throw new Error("unsupported number of channels")}return returnValue}function writeDataBytes(data,newData,slotsPerLine,offset){for(let j=0;j<slotsPerLine;j++){newData.writeByte(data[offset++])}return offset}function writeDataInterlaced(imageData,data,newData,offset){const passes=[{x:0,y:0,xStep:8,yStep:8},{x:4,y:0,xStep:8,yStep:8},{x:0,y:4,xStep:4,yStep:8},{x:2,y:0,xStep:4,yStep:4},{x:0,y:2,xStep:2,yStep:4},{x:1,y:0,xStep:2,yStep:2},{x:0,y:1,xStep:1,yStep:2}];const{width,height,channels,depth}=imageData;let pixelSize;if(depth===16){pixelSize=channels*depth/8/2}else{pixelSize=channels*depth/8}for(let passIndex=0;passIndex<7;passIndex++){const pass=passes[passIndex];const passWidth=Math.floor((width-pass.x+pass.xStep-1)/pass.xStep);const passHeight=Math.floor((height-pass.y+pass.yStep-1)/pass.yStep);if(passWidth<=0||passHeight<=0)continue;const passLineBytes=passWidth*pixelSize;for(let y=0;y<passHeight;y++){const imageY=pass.y+y*pass.yStep;const rawScanline=depth<=8?new Uint8Array(passLineBytes):new Uint16Array(passLineBytes);let rawOffset=0;for(let x=0;x<passWidth;x++){const imageX=pass.x+x*pass.xStep;if(imageX<width&&imageY<height){const srcPos=(imageY*width+imageX)*pixelSize;for(let i=0;i<pixelSize;i++){rawScanline[rawOffset++]=data[srcPos+i]}}}newData.writeByte(0);if(depth===8){newData.writeBytes(rawScanline)}else if(depth===16){for(const value of rawScanline){newData.writeByte(value>>8&255);newData.writeByte(value&255)}}}}return offset}function writeDataUint16(data,newData,slotsPerLine,offset){for(let j=0;j<slotsPerLine;j++){newData.writeUint16(data[offset++])}return offset}function convertIndexedToRgb(decodedImage){const palette=decodedImage.palette;const depth=decodedImage.depth;if(!palette){throw new Error("Color palette is undefined.")}checkDataSize(decodedImage);const indexSize=decodedImage.width*decodedImage.height;const resSize=indexSize*palette[0].length;const res=new Uint8Array(resSize);let indexPos=0;let offset=0;const indexes=new Uint8Array(indexSize);let bit=255;switch(depth){case 1:bit=128;break;case 2:bit=192;break;case 4:bit=240;break;case 8:bit=255;break;default:throw new Error("Incorrect depth value")}for(const byte of decodedImage.data){let bit2=bit;let shift=8;while(bit2){shift-=depth;indexes[indexPos++]=(byte&bit2)>>shift;bit2=bit2>>depth;if(indexPos%decodedImage.width===0){break}}}if(decodedImage.palette){for(const index of indexes){const color=decodedImage.palette.at(index);if(!color){throw new Error("Incorrect index of palette color")}res.set(color,offset);offset+=color.length}}return res}function checkDataSize(image){const expectedSize=image.depth<8?Math.ceil(image.width*image.depth/8)*image.height*image.channels:image.width*image.height*image.channels;if(image.data.length!==expectedSize){throw new RangeError(`wrong data size. Found ${image.data.length}, expected ${expectedSize}`)}}function decodePng(data,options){const decoder=new PngDecoder(data,options);return decoder.decode()}function encodePng(png,options){const encoder2=new PngEncoder(png,options);return encoder2.encode()}import{Unzlib}from"fflate";var MAX_PIXELS=1048576;var MAX_PNG_BYTES=2*1024*1024;var PNG_PREFIX="data:image/png;base64,";var PNG_SIGNATURE=[137,80,78,71,13,10,26,10];function validateDimensions(width,height){if(!Number.isSafeInteger(width)||!Number.isSafeInteger(height)||width<1||height<1||width*height>MAX_PIXELS){throw new Error(`RGB raster dimensions must be positive integers containing at most ${MAX_PIXELS} pixels`)}return width*height}function validateRaster(image){if(!image||typeof image!=="object")throw new Error("An RGB raster is required");const pixels=validateDimensions(image.width,image.height);if(!(image.data instanceof Uint8Array||image.data instanceof Float64Array)||image.data.length!==pixels*3){throw new Error("RGB raster data must contain exactly three channels per pixel in a Uint8Array or Float64Array")}if(image.data instanceof Float64Array){for(const value of image.data){if(!Number.isFinite(value)||value<0||value>255){throw new Error("RGB raster channels must be finite numbers from 0 to 255")}}}return pixels}function base64Bytes(source){if(typeof source!=="string"||!source.startsWith(PNG_PREFIX)){throw new Error("PNG input must be a data:image/png;base64 URI")}const encoded=source.slice(PNG_PREFIX.length);if(!encoded.length||encoded.length>Math.ceil(MAX_PNG_BYTES/3)*4||encoded.length%4||!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)){throw new Error(`PNG base64 data must be valid and contain at most ${MAX_PNG_BYTES} bytes`)}const binary=atob(encoded);if(binary.length>MAX_PNG_BYTES)throw new Error(`PNG input exceeds ${MAX_PNG_BYTES} bytes`);return Uint8Array.from(binary,character=>character.charCodeAt(0))}function pngDataUri(bytes){const parts=[];for(let index=0;index<bytes.length;index+=8192){parts.push(String.fromCharCode(...bytes.subarray(index,index+8192)))}return PNG_PREFIX+btoa(parts.join(""))}function inspectPng(bytes){if(bytes.length<33||PNG_SIGNATURE.some((value,index)=>bytes[index]!==value)){throw new Error("Invalid PNG signature or header")}const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const chunkName=offset2=>String.fromCharCode(...bytes.subarray(offset2+4,offset2+8));if(view.getUint32(8)!==13||chunkName(8)!=="IHDR")throw new Error("PNG must start with one IHDR chunk");const width=view.getUint32(16),height=view.getUint32(20);validateDimensions(width,height);if(bytes[24]!==8)throw new Error("RGB raster decoding supports only 8-bit PNG images");const colorType=bytes[25];const channels=colorType===0||colorType===3?1:colorType===2?3:colorType===4?2:colorType===6?4:0;if(!channels||bytes[26]!==0||bytes[27]!==0||bytes[28]!==0){throw new Error("Unsupported PNG color, compression, filter, or interlace format")}const expectedBytes=height*(1+width*channels);let inflatedBytes=0,hasData=false,dataEnded=false,hasPalette=false,ended=false;const inflater=new Unzlib(chunk=>{inflatedBytes+=chunk.length;if(inflatedBytes>expectedBytes)throw new Error("PNG inflated data exceeds its image dimensions")});let offset=8;while(offset+12<=bytes.length){const length=view.getUint32(offset),type=chunkName(offset);const end=offset+length+12;if(end>bytes.length)throw new Error("PNG chunk exceeds the input length");if(type==="IHDR"&&offset!==8)throw new Error("PNG must contain only one IHDR chunk");if(["iCCP","acTL","fcTL","fdAT"].includes(type)){throw new Error("Compressed ICC profiles and animated PNG images are not supported")}if(type==="PLTE"){if(hasData||hasPalette||length<3||length>768||length%3)throw new Error("Invalid PNG palette chunk");hasPalette=true}if(type==="IDAT"){if(dataEnded||colorType===3&&!hasPalette)throw new Error("Invalid PNG image data order");hasData=true;for(let cursor=offset+8;cursor<end-4;cursor+=1024){inflater.push(bytes.subarray(cursor,Math.min(cursor+1024,end-4)),false)}}else if(hasData){dataEnded=true}if(type==="IEND"){if(length!==0||end!==bytes.length)throw new Error("Invalid PNG end chunk");ended=true;break}if(type!=="IHDR"&&type!=="PLTE"&&type!=="IDAT"&&type[0]>="A"&&type[0]<="Z"){throw new Error(`Unsupported critical PNG chunk: ${type}`)}offset=end}if(!ended||!hasData)throw new Error("PNG image data or end chunk is missing");inflater.push(new Uint8Array(0),true);if(inflatedBytes!==expectedBytes)throw new Error("PNG inflated data does not match its image dimensions");return{width,height,colorType}}function decodeRgbPng(source){const bytes=base64Bytes(source);const{width,height,colorType}=inspectPng(bytes);const decoded=decodePng(bytes,{checkCrc:true});const pixels=width*height;const indexed=colorType===3;const channels=indexed?decoded.palette[0].length:decoded.channels;const input=indexed?convertIndexedToRgb(decoded):decoded.data;if(input.length!==pixels*channels)throw new Error("PNG decoded data does not match its image dimensions");const data=new Uint8Array(pixels*3);const transparent=decoded.transparency;for(let pixel=0;pixel<pixels;pixel+=1){const at=pixel*channels;const gray=channels<3;const red=input[at],green=gray?red:input[at+1],blue=gray?red:input[at+2];if((channels===2||channels===4)&&input[at+channels-1]!==255||!indexed&&transparent?.length&&(gray?red===transparent[0]:red===transparent[0]&&green===transparent[1]&&blue===transparent[2])){throw new Error("RGB raster decoding requires opaque PNG pixels")}data[pixel*3]=red;data[pixel*3+1]=green;data[pixel*3+2]=blue}return{width,height,data}}function encodeRgbPng(image){validateRaster(image);const data=Uint8Array.from(image.data,value=>Math.round(value));return pngDataUri(encodePng({width:image.width,height:image.height,data,depth:8,channels:3}))}function cropRgbRaster(image,region){validateRaster(image);if(!region||![region.row,region.column,region.rows,region.columns].every(Number.isSafeInteger)||region.row<0||region.column<0||region.rows<1||region.columns<1||region.row+region.rows>image.height||region.column+region.columns>image.width){throw new Error("RGB raster crop must be a nonempty integer region inside the image")}const count=region.rows*region.columns*3;const data=image.data instanceof Float64Array?new Float64Array(count):new Uint8Array(count);for(let row=0;row<region.rows;row+=1){const start=((region.row+row)*image.width+region.column)*3;data.set(image.data.subarray(start,start+region.columns*3),row*region.columns*3)}return{width:region.columns,height:region.rows,data}}function gaussianBlurRgb(image,options){validateRaster(image);const{sigma,radius=Math.ceil(3*sigma)}=options;if(!Number.isFinite(sigma)||sigma<0)throw new Error("Gaussian sigma must be a nonnegative finite number");if(!Number.isSafeInteger(radius)||radius<0||radius>64)throw new Error("Gaussian radius must be an integer from 0 to 64");const width=image.width-2*radius,height=image.height-2*radius;if(width<1||height<1)throw new Error("Gaussian kernel must fit inside the RGB image");const weights=Float64Array.from({length:2*radius+1},(_,index)=>{const distance=index-radius;return sigma===0?Number(distance===0):Math.exp(-.5*(distance/sigma)**2)});const total=weights.reduce((sum,value)=>sum+value,0);const horizontal=new Float64Array(width*image.height*3);for(let row=0;row<image.height;row+=1)for(let column=0;column<width;column+=1){for(let channel=0;channel<3;channel+=1){const base=image.data[(row*image.width+column+radius)*3+channel];let difference=0;for(let tap=0;tap<weights.length;tap+=1){difference+=weights[tap]*(image.data[(row*image.width+column+tap)*3+channel]-base)}horizontal[(row*width+column)*3+channel]=base+difference/total}}const data=new Float64Array(width*height*3);for(let row=0;row<height;row+=1)for(let column=0;column<width;column+=1){for(let channel=0;channel<3;channel+=1){const base=horizontal[((row+radius)*width+column)*3+channel];let difference=0;for(let tap=0;tap<weights.length;tap+=1){difference+=weights[tap]*(horizontal[((row+tap)*width+column)*3+channel]-base)}data[(row*width+column)*3+channel]=Math.min(255,Math.max(0,base+difference/total))}}return{width,height,data}}import{getQuickJS}from"quickjs-emscripten";import{transform}from"sucrase";var SCENE_COMPONENT_NAMES=Object.freeze(["Arrow","ArrowMarkerDef","AttentionMatrix","AxisPlot","Badge","BadgePill","BarChart","Board","Box","CalloutCard","Canvas","CanvasItem","Card","ChartFrame","CodeBlock","Column","Comparison","Connector","DashedLine","DataTable","DataflowDiagram","DeploymentDiagram","DetailList","DiagramLegend","DonutChart","DotPoint","EntityRelationshipDiagram","EquationCard","FactRows","Flow","FlowArrow","FreeBodyDiagram","GeometryDiagram","GradientChip","GraphDiagram","Grid","Heatmap","Icon","InlineBar","IntervalPlot","KeyValueList","LayeredNetwork","Legend","LineChart","MathText","Matrix","MetricCard","MetricStrip","MiniBarChart","MoleculeDiagram","NumberLine","Panel","ParetoBarChart","ParetoChart","PieChart","Pipeline","PixelGrid","ProgressList","ProgressRow","QuadrantChart","ReactionEnergyDiagram","ReactionEquation","Row","ScatterPlot","Scene","SequenceDiagram","SmallMultiples","Sparkline","Stack","StackedBar","StatusDot","StatusList","StatusRow","StepCard","SvgFrame","SvgMathText","SvgPoint","TagList","TextLabel","Tile","TileGrid","TiledMatrix","Timeline","TitleBar","ToneStrip","TransformerTopology","TreeDiagram","ValuePill","VectorArrow","VectorSegment","WaveDiagram","WindowFrame"]);var SCENE_DOM_TAGS=Object.freeze(["div","span","p","strong","em","b","i","br","svg","g","path","rect","circle","ellipse","line","polyline","polygon","text","tspan","defs","clipPath","linearGradient","radialGradient","stop","pattern","marker","mask","title","desc","use"]);function integer(value,name,min,max){if(typeof value!=="number"||!Number.isInteger(value)||value<min||value>max){throw new Error(`Editable scene ${name} must be an integer from ${min} to ${max}.`)}return value}function finite3(value,name){if(typeof value!=="number"||!Number.isFinite(value)||Math.abs(value)>32768){throw new Error(`Editable scene ${name} must be finite and within 32768 canvas units.`)}return value}function entries(value,name,max){if(value===void 0)return[];if(!Array.isArray(value)||value.length>max)throw new Error(`Editable scene ${name} supports at most ${max} entries.`);return value}function record(value,name){if(!value||typeof value!=="object"||Array.isArray(value))throw new Error(`Editable scene ${name} must be an object.`);return value}function validateSceneComponentProps(name,props){let values=0;const check=(value,key)=>{if(++values>8192)throw new Error(`Editable scene ${name} props exceed their value budget.`);if(typeof value==="number"){if(/^(?:width|height|x|y|x1|y1|x2|y2|cx|cy|r|rx|ry|radius|length|padding|gap|nodeWidth|nodeHeight|entityWidth|cellSize|cellWidth|cellHeight|fontSize|nodeSize|tileWidth|minHeight)$/i.test(key))finite3(value,`${name}.${key}`);if(/^(?:rows|cols|columns|count|repeat|gridCount|tickCount)$/i.test(key))integer(value,`${name}.${key}`,key==="gridCount"?0:1,2e3)}if(Array.isArray(value))value.forEach(item=>check(item,""));else if(value&&typeof value==="object"){if(value.kind!=="vizmatic.element")Object.entries(value).forEach(([property,item])=>check(item,property))}};Object.entries(props).forEach(([key,value])=>check(value,key));if(name==="DashedLine"){const x1=finite3(props.x1,"DashedLine.x1"),y1=finite3(props.y1,"DashedLine.y1");const x2=finite3(props.x2,"DashedLine.x2"),y2=finite3(props.y2,"DashedLine.y2");const spacing=props.dotSpacing??8;if(typeof spacing!=="number"||!Number.isFinite(spacing)||spacing<=0||Math.hypot(x2-x1,y2-y1)/spacing>2e3){throw new Error("Editable scene DashedLine requires positive dotSpacing and at most 2000 dots.")}}if(name==="TileGrid"&&props.columns!==void 0)integer(props.columns,"TileGrid.columns",1,2e3);if(name==="TiledMatrix"){const rows=integer(props.rows,"TiledMatrix.rows",1,2e3);const cols=integer(props.cols,"TiledMatrix.cols",1,2e3);if(rows*cols>2e3)throw new Error("Editable scene TiledMatrix supports at most 2000 cells.")}if(name==="AxisPlot"&&props.gridCount!==void 0)integer(props.gridCount,"AxisPlot.gridCount",0,100);if(["GraphDiagram","DataflowDiagram","DeploymentDiagram","TransformerTopology"].includes(name)){for(const key of["nodes","groups","boundaries","blocks"])entries(props[key],`${name}.${key}`,128);for(const key of["edges","connections","routes"])entries(props[key],`${name}.${key}`,256)}if(name==="EntityRelationshipDiagram"){entries(props.entities,"EntityRelationshipDiagram.entities",128).forEach(entity=>{entries(record(entity,"Entity relationship entity").attributes,"EntityRelationshipDiagram.attributes",64)});entries(props.relationships,"EntityRelationshipDiagram.relationships",256)}if(name==="TransformerTopology"&&props.expandRepeats){const blocks=entries(props.blocks,"TransformerTopology.blocks",128);const total=blocks.reduce((sum,block)=>sum+integer(record(block,"Transformer block").repeat??1,"Transformer block.repeat",1,128),0);if(total>128)throw new Error("Editable scene TransformerTopology expands to at most 128 nodes.")}if(name==="LayeredNetwork"){const layers=entries(props.layers,"LayeredNetwork.layers",16);const counts=layers.map(layer=>entries(record(layer,"Network layer").nodes,"Network layer.nodes",32).length);const edges=counts.reduce((sum,count,index)=>sum+count*(counts[index-1]??0),0);if(edges>1024)throw new Error("Editable scene LayeredNetwork supports at most 1024 connections.")}if(name==="TreeDiagram"&&props.root!==void 0){let count=0;const tree=node=>{if(++count>128)throw new Error("Editable scene TreeDiagram supports at most 128 nodes.");entries(record(node,"Tree node").children,"Tree node.children",128).forEach(tree)};tree(props.root)}if(name==="ParetoChart")entries(props.points,"ParetoChart.points",512);if(name==="NumberLine"){entries(props.ticks,"NumberLine.ticks",128);entries(props.markers,"NumberLine.markers",64)}if(name==="GeometryDiagram"){entries(props.points,"GeometryDiagram.points",128);entries(props.segments,"GeometryDiagram.segments",256);entries(props.angles,"GeometryDiagram.angles",64)}if(name==="FreeBodyDiagram")entries(props.forces,"FreeBodyDiagram.forces",32);if(name==="WaveDiagram"){entries(props.waves,"WaveDiagram.waves",8);if(props.sampleCount!==void 0)integer(props.sampleCount,"WaveDiagram.sampleCount",2,512)}if(name==="MoleculeDiagram"){entries(props.atoms,"MoleculeDiagram.atoms",64);entries(props.bonds,"MoleculeDiagram.bonds",96)}if(name==="ReactionEquation"){entries(props.reactants,"ReactionEquation.reactants",16);entries(props.products,"ReactionEquation.products",16)}if(name==="AttentionMatrix"){for(const row of entries(props.weights,"AttentionMatrix.weights",32))entries(row,"AttentionMatrix row",32);for(const row of entries(props.mask,"AttentionMatrix.mask",32))entries(row,"AttentionMatrix mask row",32)}if(name==="PixelGrid"){const rows=entries(props.pixels,"PixelGrid.pixels",128);const cells=rows.reduce((sum,row)=>sum+entries(row,"PixelGrid row",128).length,0);if(cells>1024)throw new Error("Editable scene PixelGrid supports at most 1024 pixels.")}}var componentNames=new Set(SCENE_COMPONENT_NAMES);var domTags=new Set(SCENE_DOM_TAGS);var localReference=/^#[A-Za-z_][\w:.-]*$/;var localPaint=/^url\(\s*#[A-Za-z_][\w:.-]*\s*\)$/;var resourceKeys=/^(?:background(?:image)?|fill|stroke|filter|clippath|mask(?:image)?|borderimage(?:source)?|liststyle(?:image)?|cursor|content)$/i;function validateResource(value,key,inStyle){if(/^(?:src|href|xlinkhref|xlink:href|srcset|poster|action|formaction)$/i.test(key)&&!localReference.test(value)){throw new Error("Scene resource references must be local SVG fragment IDs. External assets are disabled.")}if((inStyle||resourceKeys.test(key)||/gradient$/i.test(key))&&(/\\|\/\*/.test(value)||/(?:https?|file|ftp|data|blob|javascript):|\/\//i.test(value)||/url\s*\(/i.test(value)&&!localPaint.test(value))){throw new Error("Scene CSS cannot load external resources or escaped resource expressions.")}}function validateResolvedSceneResources(props){let values=0;const visit=(input,key,style,depth)=>{if(++values>32e3||depth>SCENE_LIMITS.depth*2)throw new Error("Resolved scene props exceed their value budget.");if(typeof input==="string"){validateResource(input,key,style);return}if(Array.isArray(input)){input.forEach(item=>visit(item,key,style,depth+1));return}if(input&&typeof input==="object"){for(const[property,value]of Object.entries(input)){if(property==="children")continue;if(property==="dangerouslySetInnerHTML"||property==="__html")throw new Error("Resolved scene cannot contain raw HTML.");visit(value,property,style||/style$/i.test(property),depth+1)}}};visit(props,"",false,0)}function validateSceneGraph(value){let nodes=0;const visit=(input,depth,key="",inStyle=false)=>{if(depth>SCENE_LIMITS.depth)throw new Error(`Scene graph exceeds depth ${SCENE_LIMITS.depth}.`);if(++nodes>SCENE_LIMITS.nodes*32)throw new Error("Scene graph contains too many values.");if(input===null||typeof input==="boolean")return input;if(typeof input==="number"){if(!Number.isFinite(input)||Math.abs(input)>1e9)throw new Error("Scene numbers must be finite and bounded.");return input}if(typeof input==="string"){if(input.length>SCENE_LIMITS.stringLength)throw new Error("Scene string exceeds its length limit.");validateResource(input,key,inStyle);return input}if(Array.isArray(input))return input.map(item=>visit(item,depth+1,key,inStyle));if(!input||typeof input!=="object"||Object.getPrototypeOf(input)!==Object.prototype&&Object.getPrototypeOf(input)!==null)throw new Error("Scene props must be plain JSON values.");const record2=input;const output=Object.create(null);for(const[property,item]of Object.entries(record2)){if(isUnsafeSceneKey(property)||/^on/i.test(property)||/^(?:xml:base|xmlBase)$/i.test(property)||property==="dangerouslySetInnerHTML"||property==="ref"||property==="__html")throw new Error(`Scene property ${JSON.stringify(property)} is not allowed.`);output[property]=visit(item,depth+1,property,inStyle||/style$/i.test(property))}if(record2.kind==="vizmatic.element"){if(typeof record2.type!=="string"||!componentNames.has(record2.type)&&!domTags.has(record2.type)){throw new Error(`Scene component ${JSON.stringify(record2.type)} is not supported.`)}if(!record2.props||typeof record2.props!=="object"||Array.isArray(record2.props)||!Array.isArray(record2.children)||Object.keys(record2).some(name=>!["kind","type","props","children"].includes(name))){throw new Error("Invalid scene element.")}if(componentNames.has(record2.type))validateSceneComponentProps(record2.type,output.props)}return output};const graph=visit(value,0);let elementCount=0;const checkChildren=child=>{if(Array.isArray(child)){child.forEach(checkChildren);return}if(child===null||typeof child!=="object")return;if(child.kind!=="vizmatic.element")throw new Error("Scene children must be JSX elements, text or numbers.");if(++elementCount>SCENE_LIMITS.nodes)throw new Error(`Scene graph exceeds ${SCENE_LIMITS.nodes} elements.`);const element=child;element.children.forEach(checkChildren);const checkProps=prop=>{if(Array.isArray(prop)){prop.forEach(checkProps);return}if(prop&&typeof prop==="object"){if(prop.kind==="vizmatic.element")checkChildren(prop);else Object.values(prop).forEach(checkProps)}};Object.values(element.props).forEach(checkProps)};checkChildren(graph);return graph}var bootstrap=String.raw`
|
|
11
|
+
const __jsonStringify = JSON.stringify.bind(JSON);
|
|
12
|
+
const __objectEntries = Object.entries.bind(Object);
|
|
13
|
+
const __isArray = Array.isArray.bind(Array);
|
|
14
|
+
const __isFinite = Number.isFinite.bind(Number);
|
|
15
|
+
const __Error = Error;
|
|
16
|
+
const __ownDescriptor = Object.getOwnPropertyDescriptor.bind(Object);
|
|
17
|
+
const __freeze = (value) => {
|
|
18
|
+
if (value && typeof value === 'object') {
|
|
19
|
+
for (const child of Object.values(value)) __freeze(child);
|
|
20
|
+
Object.freeze(value);
|
|
21
|
+
}
|
|
22
|
+
return value;
|
|
23
|
+
};
|
|
24
|
+
const clamp = (value, min = 0, max = 1) => Math.max(min, Math.min(max, value));
|
|
25
|
+
const lerp = (from, to, amount) => from + (to - from) * amount;
|
|
26
|
+
const ease = (amount) => { const x = clamp(amount); return x * x * (3 - 2 * x); };
|
|
27
|
+
const easeInOut = ease;
|
|
28
|
+
const easeOut = (amount) => 1 - Math.pow(1 - clamp(amount), 3);
|
|
29
|
+
const cue = (name, span = 1) => {
|
|
30
|
+
if (!Object.hasOwn(cues, name)) throw new __Error('Unknown scene cue: ' + name);
|
|
31
|
+
if (!__isFinite(span) || span <= 0) throw new __Error('Cue span must be positive seconds.');
|
|
32
|
+
return clamp((time - cues[name]) / span);
|
|
33
|
+
};
|
|
34
|
+
let __randomState = seed >>> 0;
|
|
35
|
+
Math.random = () => {
|
|
36
|
+
__randomState = (__randomState + 0x6D2B79F5) >>> 0;
|
|
37
|
+
let v = Math.imul(__randomState ^ (__randomState >>> 15), 1 | __randomState);
|
|
38
|
+
v ^= v + Math.imul(v ^ (v >>> 7), 61 | v);
|
|
39
|
+
return ((v ^ (v >>> 14)) >>> 0) / 4294967296;
|
|
40
|
+
};
|
|
41
|
+
globalThis.Date = undefined;
|
|
42
|
+
globalThis.performance = undefined;
|
|
43
|
+
const __fragment = '__vizmatic_fragment';
|
|
44
|
+
const __jsx = (type, props, ...children) => {
|
|
45
|
+
const attributes = props == null ? {} : { ...props };
|
|
46
|
+
const descendants = children.length ? children : Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
|
|
47
|
+
delete attributes.children;
|
|
48
|
+
if (type === __fragment) return descendants;
|
|
49
|
+
if (typeof type === 'function') return type({ ...attributes, children: descendants.length === 1 ? descendants[0] : descendants });
|
|
50
|
+
if (typeof type !== 'string') throw new __Error('Invalid scene JSX component.');
|
|
51
|
+
return { kind: 'vizmatic.element', type, props: attributes, children: descendants };
|
|
52
|
+
};
|
|
53
|
+
const React = __freeze({ createElement: __jsx, Fragment: __fragment });
|
|
54
|
+
const Fragment = __fragment;
|
|
55
|
+
const __primitive = (type) => (props) => {
|
|
56
|
+
const attributes = { ...props };
|
|
57
|
+
const children = Object.hasOwn(attributes, 'children') ? [attributes.children] : [];
|
|
58
|
+
delete attributes.children;
|
|
59
|
+
return { kind: 'vizmatic.element', type, props: attributes, children };
|
|
60
|
+
};
|
|
61
|
+
const __serialize = (value) => {
|
|
62
|
+
let values = 0;
|
|
63
|
+
return __jsonStringify(value, (key, item) => {
|
|
64
|
+
if (++values > 64000) throw new __Error('Scene graph contains too many values.');
|
|
65
|
+
if (typeof item === 'function' || typeof item === 'symbol' || typeof item === 'bigint') {
|
|
66
|
+
throw new __Error('Scene props cannot contain functions, symbols or bigint.');
|
|
67
|
+
}
|
|
68
|
+
if (typeof item === 'number' && !__isFinite(item)) throw new __Error('Scene props must be finite.');
|
|
69
|
+
if (item && typeof item === 'object' && typeof item.then === 'function') throw new __Error('Async scene values are not supported.');
|
|
70
|
+
return item;
|
|
71
|
+
});
|
|
72
|
+
};
|
|
73
|
+
`;function prepareSceneSource(source){if(/^\s*(?:import|export)\b|\bimport\s*(?:[('"{*]|\/\*)/m.test(source)){throw new Error("Editable scenes use bare TSX. Imports and exports are disabled; Vizmatic components are provided automatically.")}const start=findBareRootJsxStart(source,true);if(start<0)throw new Error("Scene source needs one root JSX element after its local declarations.");const setup=source.slice(0,start);const jsx=extractRootJsx(source.slice(start).trim());return transform(`(() => {
|
|
74
|
+
${setup}
|
|
75
|
+
return (
|
|
76
|
+
${jsx}
|
|
77
|
+
);
|
|
78
|
+
})()`,{transforms:["typescript","jsx"],jsxPragma:"React.createElement",jsxFragmentPragma:"React.Fragment",production:true,disableESTransforms:true}).code}async function prepareScene(request){const normalized=Object.freeze(normalizeSceneRequest(request));Object.freeze(normalized.cues);const code=prepareSceneSource(normalized.source);const sourceSha256=await sceneSha256(normalized.source);const inputSha256=await sceneSha256(JSON.stringify({runtimeVersion:SCENE_RUNTIME_VERSION,...normalized}));const QuickJS=await getQuickJS();const colors2=getThemeColors(normalized.theme);const components=`const { ${SCENE_COMPONENT_NAMES.join(", ")} } = Object.fromEntries(${JSON.stringify(SCENE_COMPONENT_NAMES)}.map(name => [name, __primitive(name)]));`;const evaluate=async requestedTime=>{const time=normalizeSceneTime(requestedTime,normalized.duration);const runtime=QuickJS.newRuntime();runtime.setMemoryLimit(SCENE_LIMITS.memoryBytes);runtime.setMaxStackSize(SCENE_LIMITS.stackBytes);const deadline=Date.now()+SCENE_LIMITS.evaluationMs;runtime.setInterruptHandler(()=>Date.now()>deadline);runtime.removeModuleLoader();const vm=runtime.newContext();const context={width:normalized.width,height:normalized.height,duration:normalized.duration,fps:normalized.fps,time,t:time,progress:time/normalized.duration,frame:Math.floor(time*normalized.fps+1e-9),theme:normalized.theme,cues:normalized.cues,seed:normalized.seed,c:colors2};const declaration=`const { ${Object.keys(context).join(", ")} } = ${JSON.stringify(context)};`;try{const result=vm.evalCode(`(() => { 'use strict';
|
|
79
|
+
${declaration}
|
|
80
|
+
${bootstrap}
|
|
81
|
+
__freeze(c); __freeze(cues);
|
|
82
|
+
${components}
|
|
83
|
+
try { return __serialize(${code}); } catch (error) {
|
|
84
|
+
if (typeof error === 'string') throw error.slice(0, 1024);
|
|
85
|
+
const message = error && typeof error === 'object' ? __ownDescriptor(error, 'message')?.value : undefined;
|
|
86
|
+
throw typeof message === 'string' ? message.slice(0, 1024) : 'Scene evaluation failed.';
|
|
87
|
+
}
|
|
88
|
+
})()`,"scene.tsx");if(result.error){const error=result.error;try{const message=vm.typeof(error)==="string"?vm.getString(error):"Scene evaluation failed or exceeded its CPU, stack or memory limit.";throw new Error(message.slice(0,1024))}finally{error.dispose()}}const handle=result.value;try{if(vm.typeof(handle)!=="string")throw new Error("Scene source must return synchronous JSX.");const length=vm.getProp(handle,"length");try{if(vm.getNumber(length)>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.")}finally{length.dispose()}const json=vm.getString(handle);if(new TextEncoder().encode(json).byteLength>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.");const graph=validateSceneGraph(JSON.parse(json));return{graph,request:normalized,time,runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256,inputSha256:await sceneSha256(JSON.stringify({sceneInputSha256:inputSha256,time}))}}finally{handle.dispose()}}finally{vm.dispose();runtime.dispose()}};return{request:normalized,sourceSha256,inputSha256,evaluate}}async function evaluateSceneSource(request){return(await prepareScene(request)).evaluate(request.time)}function outputSettings(prepared,outputScale=1,previewFps){if(!Number.isFinite(outputScale)||outputScale<.25||outputScale>1){throw new Error("Scene outputScale must be from 0.25 to 1.")}const{width:logicalWidth,height:logicalHeight,fps:logicalFps,duration}=prepared.request;const width=logicalWidth*outputScale,height=logicalHeight*outputScale;if(![width,height].every(value=>Number.isInteger(value)&&value>=2&&value%2===0)){throw new Error("Scaled scene width and height must be positive even integers.")}const fps=previewFps===void 0?logicalFps:previewFps;if(!Number.isInteger(fps)||fps<1||fps>logicalFps){throw new Error("Scene previewFps must be an integer from 1 to the logical scene fps.")}const frameCount=Math.round(duration*fps);if(frameCount<1)throw new Error("Scene preview duration must round to at least one output frame.");return{width,height,fps,frameCount,outputScale,preview:outputScale!==1||fps!==logicalFps}}var assetPins={"fonts/Inter-Regular.ttf":"1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba","fonts/Inter-SemiBold.ttf":"e7a1aaf7eda9f2fad4131725fa556265ec75ca7b2d756260173a040363e8d4f7","fonts/Inter-Bold.ttf":"b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c","fonts/JetBrainsMono-Regular.ttf":"44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3","fonts/NotoSans-Regular.ttf":"5be701a9511117e73603bdab95947feef4f18bd1851dbddc30659370b26c69f1","fonts/NotoSansMath-Regular.ttf":"3cbaf44af13f592bc7f7172a50edab4c73ac2f3d19af2d697a01ebd3288e322d","fonts/InstrumentSerif-Regular.ttf":"498efd461f6ddfcb7a111bf9a565709d2085d48201d501ead960d93e84ffbb88","fonts/InstrumentSerif-Italic.ttf":"08939b8bdf534afec24ae0ef5e03f948940cd9a8fe08e7fecbad040e62327385","emoji.json.br":"4911e822be2ed684fe811cadf036139e3efe353ffe2990311e1763f38ae7daab"};var assetsPromise;async function sceneAssets(){assetsPromise??=loadSceneAssets().catch(error=>{assetsPromise=void 0;throw error});return assetsPromise}async function loadSceneAssets(){const moduleDir=typeof __dirname!=="undefined"?__dirname:dirname3(fileURLToPath2(import.meta.url));const assetDir=join3(moduleDir,"..","assets");const files=new Map;for(const[name,expected]of Object.entries(assetPins)){const bytes=await readFile2(join3(assetDir,name));if(await sceneSha256(bytes)!==expected)throw new Error(`Pinned scene asset does not match: ${name}`);files.set(name,bytes)}const fontDefinitions=[["Inter","Inter-Regular.ttf",400],["Inter","Inter-SemiBold.ttf",600],["Inter","Inter-Bold.ttf",700],["JetBrains Mono","JetBrainsMono-Regular.ttf",400],["Noto Sans","NotoSans-Regular.ttf",400],["Noto Sans Math","NotoSansMath-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Italic.ttf",400,"italic"]];return{fonts:fontDefinitions.map(([name,filename,weight,style])=>({name,weight,style:style??"normal",data:Uint8Array.from(files.get(`fonts/${filename}`)).buffer})),fontFiles:fontDefinitions.map(([,filename])=>join3(assetDir,"fonts",filename)),emoji:JSON.parse(brotliDecompressSync2(files.get("emoji.json.br")).toString("utf8")),sha256:await sceneSha256(JSON.stringify(assetPins))}}var trustedComponents=Object.fromEntries(SCENE_COMPONENT_NAMES.map(name=>[name,primitives_exports[name]]));var svgTags=new Set(SCENE_DOM_TAGS.filter(name=>!["div","span","p","strong","em","b","i","br"].includes(name)));function isElement(value){return Boolean(value&&!Array.isArray(value)&&typeof value==="object"&&value.kind==="vizmatic.element")}var xml=value=>String(value).replace(/[&<>"']/g,character=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[character]);function svgAttribute(name){if(name==="className")return"class";if(name==="xlinkHref")return"href";if(/^(?:viewBox|preserveAspectRatio|gradientUnits|gradientTransform|patternUnits|patternContentUnits|patternTransform|markerWidth|markerHeight|markerUnits|refX|refY|textLength|lengthAdjust|clipPathUnits)$/.test(name))return name;return name.replace(/[A-Z]/g,character=>`-${character.toLowerCase()}`)}function serializeSvg(node,budget,depth=0){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(depth>SCENE_LIMITS.depth*2)throw new Error("Resolved SVG exceeds its depth limit.");const emit=chunk=>{budget.svgBytes+=Buffer.byteLength(chunk);if(budget.svgBytes>SCENE_LIMITS.graphBytes*4)throw new Error("Resolved SVG exceeds its serialized byte budget.");return chunk};if(node===null||node===void 0||typeof node==="boolean")return"";if(typeof node==="string"||typeof node==="number")return emit(xml(node));if(Array.isArray(node))return node.map(child=>serializeSvg(child,budget,depth+1)).join("");if(!React21.isValidElement(node))throw new Error("Invalid resolved SVG child.");if(node.type===React21.Fragment)return serializeSvg(node.props.children,budget,depth+1);if(node.type===SvgMathText){const{text,x,y,fill,fontSize=13,fontFamily="JetBrains Mono",fontWeight=700,textAnchor="middle",dominantBaseline="middle",opacity=1}=node.props;return serializeSvg(React21.createElement("text",{x,y,fill,fontSize,fontFamily,fontWeight,textAnchor,dominantBaseline,opacity},String(text)),budget,depth+1)}if(typeof node.type==="function"){return serializeSvg(node.type(node.props),budget,depth+1)}if(typeof node.type!=="string"||!svgTags.has(node.type))throw new Error("Only SVG components may be placed inside an SVG scene.");validateResolvedSceneResources(node.props);const attributes=Object.entries(node.props).filter(([key,value])=>key!=="children"&&key!=="key"&&value!==void 0&&value!==null).map(([key,value])=>{if(key==="style"&&typeof value==="object"){const style=Object.entries(value).map(([property,item])=>`${svgAttribute(property)}:${String(item)}`).join(";");return` style="${xml(style)}"`}if(!/^[A-Za-z_][\w:.-]*$/.test(key)||typeof value==="object"||typeof value==="function")throw new Error("Unsupported SVG attribute.");return` ${svgAttribute(key)}="${xml(String(value))}"`}).join("");return emit(`<${node.type}${attributes}>`)+serializeSvg(node.props.children,budget,depth+1)+emit(`</${node.type}>`)}function graphToReact(value,theme){if(Array.isArray(value))return value.map(child=>graphToReact(child,theme));if(!isElement(value))return value;const convertProp=prop=>{if(isElement(prop))return graphToReact(prop,theme);if(Array.isArray(prop))return prop.map(convertProp);if(prop&&typeof prop==="object")return Object.fromEntries(Object.entries(prop).map(([key,item])=>[key,convertProp(item)]));return prop};const props=Object.fromEntries(Object.entries(value.props).map(([name,prop])=>[name,convertProp(prop)]));const component=trustedComponents[value.type];if(component)props.c??=theme;return React21.createElement(component??value.type,props,...value.children.map(child=>graphToReact(child,theme)))}function renderSvgImage(element,assets,width,height,budget,outputScale=1,includePng=true){const root=React21.cloneElement(element,{xmlns:"http://www.w3.org/2000/svg",width,height});const svg=serializeSvg(root,budget);const image=new Resvg3(svg,{font:{loadSystemFonts:false,fontFiles:assets.fontFiles,defaultFontFamily:"Inter"},background:"rgba(0,0,0,0)",...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("SVG frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}}function rasterizeNestedSvg(node,assets,defaultWidth,defaultHeight,budget){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(Array.isArray(node))return node.map(child=>rasterizeNestedSvg(child,assets,defaultWidth,defaultHeight,budget));if(!React21.isValidElement(node))return node;if(node.type==="svg"){const width=typeof node.props.width==="number"?node.props.width:defaultWidth;const height=typeof node.props.height==="number"?node.props.height:defaultHeight;if(!Number.isInteger(width)||!Number.isInteger(height)||width<1||height<1||width>SCENE_LIMITS.canvasEdge||height>SCENE_LIMITS.canvasEdge||width*height>SCENE_LIMITS.canvasPixels){throw new Error("Nested SVG dimensions exceed the scene canvas limits.")}budget.pixels+=width*height;budget.count+=1;if(budget.pixels>defaultWidth*defaultHeight*4||budget.count>16){throw new Error("Nested SVG rasterization exceeds the per-frame pixel or image budget.")}const{png}=renderSvgImage(node,assets,width,height,budget);return React21.createElement("img",{width,height,src:`data:image/png;base64,${Buffer.from(png).toString("base64")}`,style:{display:"flex",flexShrink:0,...node.props.style}})}if(typeof node.type==="function")return rasterizeNestedSvg(node.type(node.props),assets,defaultWidth,defaultHeight,budget);validateResolvedSceneResources(node.props);return React21.cloneElement(node,{},rasterizeNestedSvg(node.props.children,assets,defaultWidth,defaultHeight,budget))}async function renderPreparedFrame(prepared,assets,time,outputScale,includePng){const evaluated=await prepared.evaluate(time);const{width,height,theme}=prepared.request;const c=getThemeColors(theme);let element=graphToReact(evaluated.graph,c);if(React21.isValidElement(element)&&element.type==="svg"){const image=renderSvgImage(React21.cloneElement(element,{children:[React21.createElement("rect",{key:"__scene_background",width,height,fill:c.bg}),element.props.children]}),assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0},outputScale,includePng);return image}element=React21.createElement("div",{style:{display:"flex",position:"relative",width,height,backgroundColor:c.bg,fontFamily:"Inter",color:c.textPrimary}},element);return withRenderContext({background:"theme"},async()=>{element=rasterizeNestedSvg(element,assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0});const accessible=prepareAccessibleSvg(element);const layoutNodes=[];const rendered=await satori(accessible.element,{width,height,fonts:assets.fonts,loadAdditionalAsset:async(code,segment)=>{if(code!=="emoji")return[];const points=[...segment].map(character=>character.codePointAt(0).toString(16));const candidates=[points.join("-"),points.filter(point=>point!=="fe0f").join("-")];const svg2=candidates.map(name=>assets.emoji[`${name}.svg`]).find(Boolean);if(!svg2)throw new Error("A scene glyph is not available in the pinned offline font and emoji assets.");return`data:image/svg+xml;base64,${Buffer.from(svg2).toString("base64")}`},onNodeDetected:node=>layoutNodes.push(node)});const svg=addSvgAccessibility(rendered,accessible.graphs,layoutNodes);const image=new Resvg3(svg,{background:c.bg,font:{loadSystemFonts:false,fontFiles:assets.fontFiles},...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("Layout frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}})}async function outputMetadata(prepared,assets,settings,outputPath,bytes,kind,time){const{width,height,duration,fps,frameCount}=prepared.request;const digest=createHash("sha256");for await(const chunk of createReadStream(outputPath))digest.update(chunk);return{runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256:prepared.sourceSha256,inputSha256:await sceneSha256(JSON.stringify({requestSha256:prepared.inputSha256,fontAssetsSha256:assets.sha256,kind,...time!==void 0?{time}:{},...settings.preview?{outputScale:settings.outputScale,width:settings.width,height:settings.height,fps:settings.fps,frameCount:settings.frameCount}:{}})),assetSha256:digest.digest("hex"),fontAssetsSha256:assets.sha256,width:settings.width,height:settings.height,duration,fps:settings.fps,frameCount:settings.frameCount,bytes,outputPath:resolve2(outputPath),...settings.preview?{outputScale:settings.outputScale,...kind==="mp4"?{previewFps:settings.fps}:{},logicalWidth:width,logicalHeight:height,logicalFps:fps,logicalFrameCount:frameCount}:{}}}async function atomicWrite(outputPath,bytes){const target=resolve2(outputPath);await mkdir3(dirname3(target),{recursive:true});const temporary=join3(dirname3(target),`.vizmatic-scene-${randomUUID2()}.tmp`);const file=await open2(temporary,"wx",384);try{await file.writeFile(bytes);await file.close();await rename2(temporary,target)}catch(error){await file.close().catch(()=>{});await rm2(temporary,{force:true});throw error}}async function renderSceneFrame(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale);const time=normalizeSceneTime(options.time,prepared.request.duration);const assets=await sceneAssets();const image=await renderPreparedFrame(prepared,assets,time,settings.outputScale,true);await atomicWrite(options.outputPath,image.png);return{...await outputMetadata(prepared,assets,settings,options.outputPath,image.png.byteLength,"png",time),time}}async function renderSceneVideo(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale,options.previewFps);const assets=await sceneAssets();const{duration}=prepared.request;const output=await renderRgbaVideo(async frame=>(await renderPreparedFrame(prepared,assets,frame.time/1e3,settings.outputScale,false)).pixels,{width:settings.width,height:settings.height,duration:duration*1e3,fps:settings.fps,outputPath:options.outputPath,signal:options.signal});return{...await outputMetadata(prepared,assets,settings,options.outputPath,output.bytes,"mp4"),encodedDuration:output.duration/1e3}}export{DENSITY_NAMES,DEFAULT_DENSITY,assertDensity,parseDensity,densityTokens,setDefaultDensity,setDensityResolver,densityOf,withDensity,getThemeColors,colors,gradients,toneGradients,getToneGradient,getToneColor,getReadableToneColor,getToneFill,typography,hasShadow,typeOf,canvas,getStyles,styles,getColor,getReadableColor,withColorAlpha,compositeColor,getReadableTextColor,getGradient,heatColor,withRenderContext,defineIllustration,Canvas,TitleBar,scopeDensity,Scene,Row,Column,ToneStrip,Icon,Panel,formatMathText,MathText,TextLabel,SvgMathText,Box,Arrow,FlowArrow,Connector,VectorArrow,VectorSegment,SvgFrame,SvgPoint,ArrowMarkerDef,Stack,Card,ValuePill,EquationCard,BadgePill,GradientChip,StepCard,MetricCard,estimateTextWidth,statusColor,StatusDot,Sparkline,InlineBar,FactRows,MetricStrip,TagList,DiagramLegend,SmallMultiples,ProgressRow,ProgressList,MiniBarChart,DetailList,Tile,TileGrid,CodeBlock,Comparison,KeyValueList,WindowFrame,StatusRow,StatusList,Timeline,Flow,routingSegmentBlocked,routeOrthogonalGraph,pointAlongSamples,LayeredNetwork,defineDiagramIcon,defineIconRegistry,GraphDiagram,TreeDiagram,CalloutCard,Pipeline,SequenceDiagram,DataflowDiagram,DeploymentDiagram,EntityRelationshipDiagram,formatTensorShape,TransformerTopology,Matrix,Heatmap,TiledMatrix,DataTable,Grid,AxisPlot,createPlotArea,ChartFrame,PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart,ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot,Badge,DotPoint,DashedLine,Legend,CANVAS_ITEM_COMPONENT,Board,CanvasItem,mapNumberLine,NumberLine,geometryBounds,GeometryDiagram,sumForces,FreeBodyDiagram,waveValue,sampleWave,WaveDiagram,ELEMENT_SYMBOLS,MoleculeDiagram,reactionBalance,ReactionEquation,ReactionEnergyDiagram,seededRandom,lerpArray,dotProduct,multiplyMatrices,stableSoftmax,entropy,normalizeVector,sampleFunction,gaussian,sampleGaussian,scaledDotProductAttention,AttentionMatrix,transposeMatrix,rgbChannel,cropRgbImage,flattenRgbImage,PixelGrid,crossCorrelate2d,gaussianKernel,encodePng,decodeRgbPng,encodeRgbPng,cropRgbRaster,gaussianBlurRgb,primitives_exports,normalizeWatermark,Watermark,wrapWithWatermark,wrapWithBrand,detectBackgroundColor,detectContentBounds,cropPixels,detectOverflow,detectLayoutOverflow,satori,loadAdditionalAsset,getFonts,CanvasOverflowError,renderToPng,renderToPngWithOutput,renderToBuffer,renderToSvg,hold,keyframe,tween,parallel,defineAnimation,sampleAnimation,sampleAnimationFrame,analyzeAnimationCadence,sampleAnimationFrames,chapterMetadata,captionsToSrt,videoFrameSchedule,renderAnimationVideo,renderRgbaVideo,extractRootJsx,findBareRootJsxStart,SCENE_RUNTIME_VERSION,SCENE_LIMITS,prepareScene,evaluateSceneSource,renderSceneFrame,renderSceneVideo};
|