vizmatic 0.7.3 → 0.8.1

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/dist/cli.js CHANGED
@@ -1,7 +1,16 @@
1
1
  #!/usr/bin/env node
2
- import{Arrow,ArrowMarkerDef,AttentionMatrix,AxisPlot,Badge,BadgePill,BarChart,Board,Box,CANVAS_ITEM_COMPONENT,CalloutCard,Canvas,CanvasItem,CanvasOverflowError,Card,ChartFrame,CodeBlock,Column,Comparison,Connector,DEFAULT_DENSITY,DENSITY_NAMES,DashedLine,DataTable,DataflowDiagram,DeploymentDiagram,DetailList,DiagramLegend,DonutChart,DotPoint,ELEMENT_SYMBOLS,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,SCENE_LIMITS,SCENE_RUNTIME_VERSION,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,Watermark,WaveDiagram,WindowFrame,analyzeAnimationCadence,assertDensity,canvas,captionsToSrt,chapterMetadata,colors,compositeColor,createPlotArea,cropPixels,cropRgbImage,cropRgbRaster,crossCorrelate2d,decodeRgbPng,defineAnimation,defineDiagramIcon,defineIconRegistry,defineIllustration,densityOf,densityTokens,detectBackgroundColor,detectContentBounds,detectLayoutOverflow,detectOverflow,dotProduct,encodePng,encodeRgbPng,entropy,estimateTextWidth,evaluateSceneSource,extractRootJsx,findBareRootJsxStart,flattenRgbImage,formatMathText,formatTensorShape,gaussian,gaussianBlurRgb,gaussianKernel,geometryBounds,getColor,getFonts,getGradient,getReadableColor,getReadableTextColor,getReadableToneColor,getStyles,getThemeColors,getToneColor,getToneFill,getToneGradient,gradients,hasShadow,heatColor,hold,keyframe,lerpArray,loadAdditionalAsset,mapNumberLine,multiplyMatrices,normalizeVector,normalizeWatermark,parallel,parseDensity,pointAlongSamples,prepareScene,primitives_exports,reactionBalance,renderAnimationVideo,renderRgbaVideo,renderSceneFrame,renderSceneVideo,renderToBuffer,renderToPng,renderToPngWithOutput,renderToSvg,rgbChannel,routeOrthogonalGraph,routingSegmentBlocked,sampleAnimation,sampleAnimationFrame,sampleAnimationFrames,sampleFunction,sampleGaussian,sampleWave,satori,scaledDotProductAttention,scopeDensity,seededRandom,setDefaultDensity,setDensityResolver,stableSoftmax,statusColor,styles,sumForces,toneGradients,transposeMatrix,tween,typeOf,typography,videoFrameSchedule,waveValue,withColorAlpha,withDensity,withRenderContext,wrapWithBrand,wrapWithWatermark}from"./chunk-QVYHYC7T.js";import{renderMathSvg}from"./chunk-3F2VQ7NW.js";import{__export}from"./chunk-PSBF4TEK.js";import{existsSync as existsSync2}from"fs";import{mkdir as mkdir4,mkdtemp as mkdtemp2,readFile,readdir,rm as rm2,writeFile as writeFile4}from"fs/promises";import{randomUUID}from"crypto";import{createRequire as createRequire2,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename as basename2,dirname as dirname4,extname as extname2,isAbsolute,join as join3,relative as relative2,resolve as resolve3,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React,{isValidElement as isValidElement2}from"react";import{Resvg as Resvg2}from"@resvg/resvg-js";var index_exports={};__export(index_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,CHECK_DIAGNOSTIC_CODES:()=>CHECK_DIAGNOSTIC_CODES,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,CanvasOverflowError:()=>CanvasOverflowError,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DEFAULT_DENSITY:()=>DEFAULT_DENSITY,DENSITY_NAMES:()=>DENSITY_NAMES,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,SCENE_LIMITS:()=>SCENE_LIMITS,SCENE_RUNTIME_VERSION:()=>SCENE_RUNTIME_VERSION,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,Watermark:()=>Watermark,WaveDiagram:()=>WaveDiagram,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,arcSwap:()=>arcSwap,assertDensity:()=>assertDensity,assertTokenHistoryTransition:()=>assertTokenHistoryTransition,byteDifferenceState:()=>byteDifferenceState,cameraSvgTransform:()=>cameraSvgTransform,canvas:()=>canvas,captionsToSrt:()=>captionsToSrt,categoricalSampling:()=>categoricalSampling,chapterMetadata:()=>chapterMetadata,checkFrame:()=>checkFrame,colors:()=>colors,compareByteSequences:()=>compareByteSequences,compositeColor:()=>compositeColor,createCanvasComponents:()=>createCanvasComponents,createCueTrack:()=>createCueTrack,createFocusDirector:()=>createFocusDirector,createPlotArea:()=>createPlotArea,createPolylineMorph:()=>createPolylineMorph,createTeachingByteDifference:()=>createTeachingByteDifference,createTeachingCanvas:()=>createTeachingCanvas,createTeachingCategoricalSampling:()=>createTeachingCategoricalSampling,createTeachingFocus:()=>createTeachingFocus,createTeachingRoutedTransfer:()=>createTeachingRoutedTransfer,createTeachingTokenHistory:()=>createTeachingTokenHistory,createTeachingValueChange:()=>createTeachingValueChange,createTeachingVectorAccumulation:()=>createTeachingVectorAccumulation,cropPixels:()=>cropPixels,cropRgbImage:()=>cropRgbImage,cropRgbRaster:()=>cropRgbRaster,crossCorrelate2d:()=>crossCorrelate2d,decodeRgbPng:()=>decodeRgbPng,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,densityOf:()=>densityOf,densityTokens:()=>densityTokens,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectLayoutOverflow:()=>detectLayoutOverflow,detectOverflow:()=>detectOverflow,dotProduct:()=>dotProduct,encodeRgbPng:()=>encodeRgbPng,entropy:()=>entropy,escapedByte:()=>escapedByte,estimateTextWidth:()=>estimateTextWidth,evaluateSceneSource:()=>evaluateSceneSource,flattenRgbImage:()=>flattenRgbImage,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,gaussian:()=>gaussian,gaussianBlurRgb:()=>gaussianBlurRgb,gaussianKernel:()=>gaussianKernel,geometryBounds:()=>geometryBounds,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,hasShadow:()=>hasShadow,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,interpolateCamera:()=>interpolateCamera,keyframe:()=>keyframe,layoutAllocation:()=>layoutAllocation,layoutByteDifference:()=>layoutByteDifference,layoutCellGrid:()=>layoutCellGrid,layoutTokenRow:()=>layoutTokenRow,lerpArray:()=>lerpArray,loadAdditionalAsset:()=>loadAdditionalAsset,mapNumberLine:()=>mapNumberLine,mergeFocusRegions:()=>mergeFocusRegions,morphPolyline:()=>morphPolyline,multiplyMatrices:()=>multiplyMatrices,normalizeVector:()=>normalizeVector,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,parseDensity:()=>parseDensity,planTeachingRoutedTransfer:()=>planTeachingRoutedTransfer,pointAlongPath:()=>pointAlongPath,prepareScene:()=>prepareScene,projectWorldPoint:()=>projectWorldPoint,reactionBalance:()=>reactionBalance,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderAnimationVideo:()=>renderAnimationVideo,renderMathSvg:()=>renderMathSvg,renderRgbaVideo:()=>renderRgbaVideo,renderSceneFrame:()=>renderSceneFrame,renderSceneVideo:()=>renderSceneVideo,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,rgbChannel:()=>rgbChannel,sampleAnimation:()=>sampleAnimation,sampleAnimationFrame:()=>sampleAnimationFrame,sampleAnimationFrames:()=>sampleAnimationFrames,sampleFunction:()=>sampleFunction,sampleGaussian:()=>sampleGaussian,sampleWave:()=>sampleWave,scaledDotProductAttention:()=>scaledDotProductAttention,scopeDensity:()=>scopeDensity,seededRandom:()=>seededRandom,setDefaultDensity:()=>setDefaultDensity,setDensityResolver:()=>setDensityResolver,smoothstep:()=>smoothstep,stableSoftmax:()=>stableSoftmax,statusColor:()=>statusColor,styles:()=>styles,sumForces:()=>sumForces,tokenHistoryState:()=>tokenHistoryState,toneGradients:()=>toneGradients,tracePolyline:()=>tracePolyline,transposeMatrix:()=>transposeMatrix,tween:()=>tween,typeOf:()=>typeOf,typography:()=>typography,valueChangeState:()=>valueChangeState,videoFrameSchedule:()=>videoFrameSchedule,waveValue:()=>waveValue,weightedVectorState:()=>weightedVectorState,withColorAlpha:()=>withColorAlpha,withDensity:()=>withDensity,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import{Resvg}from"@resvg/resvg-js";import{mkdir,writeFile}from"fs/promises";import{dirname}from"path";import*as gifenc from"gifenc";import parseCssColor from"parse-css-color";function resolveGifenc(api){if(typeof api.GIFEncoder==="function"&&typeof api.applyPalette==="function"&&typeof api.quantize==="function"){return api}const fallback=api.default;if(fallback&&typeof fallback.GIFEncoder==="function"&&typeof fallback.applyPalette==="function"&&typeof fallback.quantize==="function"){return fallback}throw new Error("gifenc exports could not be resolved")}var{GIFEncoder,applyPalette,quantize}=resolveGifenc(gifenc);var MAX_PALETTE_SAMPLE_PIXELS=1e6;var MAX_TIMELINE_PALETTE_FRAMES=24;async function renderToPixels(element,width,height,scale,theme,background,overflowContext){const fonts2=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts:fonts2,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg(svg,{fitTo:{mode:"width",value:width*scale},background:rasterBackground(background,theme)});const rendered=resvg.render();const output={pixels:rendered.pixels,width:rendered.width,height:rendered.height};if(overflowContext){const overflow=detectLayoutOverflow2(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow2(nodes,width,height){const epsilon=.5;const edges={top:nodes.some(node=>node.top<-epsilon),right:nodes.some(node=>node.left+node.width>width+epsilon),bottom:nodes.some(node=>node.top+node.height>height+epsilon),left:nodes.some(node=>node.left<-epsilon)};const names=Object.entries(edges).filter(([,overflows])=>overflows).map(([edge])=>edge);return{overflows:names.length>0,edges,message:names.length?`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`:""}}function blendPixels(base,overlay,opacity){const result=new Uint8Array(base.length);const inverse=1-opacity;for(let index=0;index<base.length;index+=4){const baseAlpha=base[index+3]/255*inverse;const overlayAlpha=overlay[index+3]/255*opacity;const outputAlpha=baseAlpha+overlayAlpha;if(outputAlpha===0)continue;result[index]=Math.round((base[index]*baseAlpha+overlay[index]*overlayAlpha)/outputAlpha);result[index+1]=Math.round((base[index+1]*baseAlpha+overlay[index+1]*overlayAlpha)/outputAlpha);result[index+2]=Math.round((base[index+2]*baseAlpha+overlay[index+2]*overlayAlpha)/outputAlpha);result[index+3]=Math.round(outputAlpha*255)}return result}function hslToRgb(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/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=l-chroma/2;return[Math.round((channels[0]+offset)*255),Math.round((channels[1]+offset)*255),Math.round((channels[2]+offset)*255)]}function colorForBackground(background,theme){const value=background==="theme"?getThemeColors(theme).bg:background;const parsed=parseCssColor(value);if(!parsed)throw new Error(`Invalid animation background color: ${value}`);const[r,g,b]=parsed.type==="hsl"?hslToRgb(parsed.values[0],parsed.values[1],parsed.values[2]):[parsed.values[0],parsed.values[1],parsed.values[2]];return{r,g,b,a:Math.round(parsed.alpha*255)}}function rasterBackground(background,theme){const{r,g,b,a}=colorForBackground(background,theme);return`rgba(${r}, ${g}, ${b}, ${a/255})`}function backgroundPixels(width,height,theme,background){const buffer=new Uint8Array(width*height*4);const color=colorForBackground(background,theme);for(let index=0;index<buffer.length;index+=4){buffer[index]=color.r;buffer[index+1]=color.g;buffer[index+2]=color.b;buffer[index+3]=color.a}return buffer}function samplePixels(pixels,limit){const pixelCount=pixels.length/4;if(pixelCount<=limit)return pixels.slice();const sample=new Uint8Array(limit*4);for(let index=0;index<limit;index+=1){const sourcePixel=Math.floor((index+.5)*pixelCount/limit);sample.set(pixels.subarray(sourcePixel*4,sourcePixel*4+4),index*4)}return sample}function sharedPalette(frames){if(frames.length===0)throw new Error("No GIF frames to quantize");const pixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/frames.length));const samples=frames.map(frame=>samplePixels(frame.pixels,pixelsPerFrame));const length=samples.reduce((total,sample)=>total+sample.length,0);const combined=new Uint8Array(length);let offset=0;for(const sample of samples){combined.set(sample,offset);offset+=sample.length}return quantize(combined,256,{format:"rgba4444",oneBitAlpha:true})}function changedBounds(previous,current,width,height){let minX=width;let minY=height;let maxX=-1;let maxY=-1;for(let index=0;index<current.length;index+=4){if(previous[index]===current[index]&&previous[index+1]===current[index+1]&&previous[index+2]===current[index+2]&&previous[index+3]===current[index+3])continue;const pixel=index/4;const x=pixel%width;const y=Math.floor(pixel/width);minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y)}return maxX<minX?void 0:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropFramePixels(pixels,canvasWidth,region){const output=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y+=1){const source=((region.y+y)*canvasWidth+region.x)*4;output.set(pixels.subarray(source,source+region.width*4),y*region.width*4)}return output}function deltaPixelFrame(frame,previous,enabled){if(!enabled||!previous)return frame;const bounds4=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds4||bounds4.width===frame.width&&bounds4.height===frame.height)return frame;return{...frame,x:bounds4.x,y:bounds4.y,delta:true,width:bounds4.width,height:bounds4.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds4)}}function encodeGif(frames,loop,deltaFrames){if(frames.length===0)throw new Error("No GIF frames to encode");const firstFrame=frames[0];const gif=GIFEncoder();const palette=sharedPalette(frames);let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;let pending2;for(const frame of frames){if(frame.width!==firstFrame.width||frame.height!==firstFrame.height){throw new Error("All GIF frames must have matching dimensions")}if(pending2&&pixelsEqual(pending2.pixels,frame.pixels)){pending2.delay+=frame.delay;continue}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending2={...frame}}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1}gif.finish();return{bytes:gif.bytes(),encodedFrameCount,deltaFrameCount}}var DEFAULT_TRANSITION_FPS=20;var MIN_TRANSITION_FRAMES=3;function sceneTransitionFps(fps){const resolved=fps??DEFAULT_TRANSITION_FPS;if(!Number.isInteger(resolved)||resolved<1||resolved>50){throw new Error("Animation fps must be an integer from 1 to 50")}return resolved}function transitionFrameDelays(duration,count){const totalCentiseconds=Math.max(count*2,Math.round(duration/10));let previous=0;return Array.from({length:count},(_,index)=>{const cumulative=Math.round((index+1)/count*totalCentiseconds);const delay2=(cumulative-previous)*10;previous=cumulative;return delay2})}async function scenesToFrames(scenes,options){if(scenes.length===0)throw new Error("Animated GIF requires at least one scene");for(const[index,scene]of scenes.entries()){if(!Number.isFinite(scene.duration)||scene.duration<=0){throw new Error(`Animated scene ${index+1} duration must be a positive finite number`)}if(scene.transition!=null&&!["none","fade","appear"].includes(scene.transition)){throw new Error(`Animated scene ${index+1} has unknown transition "${scene.transition}"`)}if(scene.transitionDuration!=null&&(!Number.isFinite(scene.transitionDuration)||scene.transitionDuration<=0)){throw new Error(`Animated scene ${index+1} transitionDuration must be a positive finite number`)}}const fps=sceneTransitionFps(options.fps);const renderedScenes=await Promise.all(scenes.map((scene,sceneIndex)=>{const watermark=options.watermark??options.brand;const element=watermark?wrapWithWatermark(scene.element,options.width,options.height,options.theme,watermark):scene.element;return renderToPixels(element,options.width,options.height,options.scale,options.theme,options.background,{sceneIndex,label:scene.label})}));const frames=[];const scaledWidth=renderedScenes[0].width;const scaledHeight=renderedScenes[0].height;for(let index=0;index<scenes.length;index+=1){const scene=scenes[index];const current=renderedScenes[index];const transition=scene.transition??"none";const transitionDuration=scene.transitionDuration??400;if(transition!=="none"){const previous=index>0?renderedScenes[index-1]:{pixels:backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),width:scaledWidth,height:scaledHeight};const transitionFrames=Math.max(MIN_TRANSITION_FRAMES,Math.round(transitionDuration/1e3*fps));const frameDelays=transitionFrameDelays(transitionDuration,transitionFrames);for(let frameIndex=0;frameIndex<transitionFrames;frameIndex+=1){const amount2=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount2):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount2);frames.push({pixels,delay:frameDelays[frameIndex],width:scaledWidth,height:scaledHeight})}}frames.push({pixels:current.pixels,delay:scene.duration,width:scaledWidth,height:scaledHeight})}return frames}async function renderAnimatedGif(scenes,options){if(!Array.isArray(scenes)){await renderAnimationGifWithOutput(scenes,options)}else{await renderAnimatedGifWithOutput(scenes,options)}}async function renderAnimatedGifWithOutput(scenes,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};await mkdir(dirname(options.outputPath),{recursive:true});const frames=await scenesToFrames(scenes,normalized);const encoded=encodeGif(frames,normalized.loop,normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255);await writeFile(options.outputPath,encoded.bytes);return{width:frames[0].width,height:frames[0].height,frameCount:frames.length,encodedFrameCount:encoded.encodedFrameCount,deltaFrameCount:encoded.deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.delay,0),bytes:encoded.bytes.length}}function pixelsEqual(left,right){if(left.length!==right.length)return false;for(let index=0;index<left.length;index+=1){if(left[index]!==right[index])return false}return true}function writeGifFrame(gif,frame,loop,palette,first,delta){const index=applyPalette(frame.pixels,palette,"rgba4444");const transparentIndex=palette.findIndex(color=>color[3]===0);let remainingDelay=frame.delay;let includePalette=first;do{const delay2=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay2),repeat:loop,transparent:transparentIndex>=0,transparentIndex,dispose:delta&&frame.delta?1:void 0});if((frame.x??0)!==0||(frame.y??0)!==0){const bytes=gif.bytesView();const descriptor=frameStart+8;if(bytes[descriptor]!==44)throw new Error("GIF image descriptor was not written");const x=frame.x??0;const y=frame.y??0;bytes[descriptor+1]=x&255;bytes[descriptor+2]=x>>8&255;bytes[descriptor+3]=y&255;bytes[descriptor+4]=y>>8&255}includePalette=false;remainingDelay-=delay2}while(remainingDelay>0)}function representativeFrameIndexes(frameCount){const count=Math.min(frameCount,MAX_TIMELINE_PALETTE_FRAMES);if(count===frameCount)return Array.from({length:count},(_,index)=>index);return Array.from({length:count},(_,index)=>Math.round(index*(frameCount-1)/(count-1)))}async function renderAnimationGif(animation,options){await renderAnimationGifWithOutput(animation,options)}async function renderAnimationGifWithOutput(animation,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};const frames=sampleAnimationFrames(animation,{fps:options.fps});const paletteFrames=[];const paletteIndexes=representativeFrameIndexes(frames.length);const palettePixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/paletteIndexes.length));for(const index of paletteIndexes){const sampled=frames[index];const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background);paletteFrames.push({...rendered,pixels:samplePixels(rendered.pixels,palettePixelsPerFrame),delay:sampled.frame.delay})}const palette=sharedPalette(paletteFrames);const gif=GIFEncoder();let pending2;let dimensions;let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;const useDeltaFrames=normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255;for(const sampled of frames){const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background,{frameIndex:sampled.frame.index,frameCount:sampled.frame.count,time:sampled.frame.time,label:sampled.frame.label});dimensions??={width:rendered.width,height:rendered.height};if(rendered.width!==dimensions.width||rendered.height!==dimensions.height){throw new Error("All GIF frames must have matching dimensions")}if(pending2&&pixelsEqual(pending2.pixels,rendered.pixels)){pending2.delay+=sampled.frame.delay;continue}if(pending2){const encoded2=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending2={...rendered,delay:sampled.frame.delay}}if(!pending2||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir(dirname(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}var DEFAULT_ARC_LIFT=80;function assertFiniteProgress(progress){if(!Number.isFinite(progress))throw new Error("Motion progress must be finite")}function clampProgress(progress){assertFiniteProgress(progress);return Math.max(0,Math.min(1,progress))}function assertPoint(point,context){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} coordinates must be finite`)}}function interpolate(from,to2,progress){return{x:from.x*(1-progress)+to2.x*progress,y:from.y*(1-progress)+to2.y*progress}}function smoothstep(progress){const amount2=clampProgress(progress);return amount2*amount2*(3-2*amount2)}function arcSwap(from,to2,progress,options={}){assertPoint(from,"Arc swap start");assertPoint(to2,"Arc swap end");const amount2=clampProgress(progress);const lift=options.lift??DEFAULT_ARC_LIFT;if(!Number.isFinite(lift))throw new Error("Arc swap lift must be finite");if(amount2===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(amount2===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Motion easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(t===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const dx=to2.x-from.x;const dy=to2.y-from.y;const length=Math.hypot(dx,dy);if(!Number.isFinite(length))throw new Error("Arc swap distance must be finite");if(length===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];const normalX=-dy/length;const normalY=dx/length;const arcHeight=4*(1-t)*t*lift;const firstBase=interpolate(from,to2,t);const secondBase=interpolate(to2,from,t);const first={x:firstBase.x+normalX*arcHeight,y:firstBase.y+normalY*arcHeight};const second={x:secondBase.x-normalX*arcHeight,y:secondBase.y-normalY*arcHeight};assertPoint(first,"Arc swap result");assertPoint(second,"Arc swap result");return[first,second]}function pathLengths(points){const lengths=[];let total=0;for(let index=0;index<points.length;index+=1){const point=points[index];assertPoint(point,`Path point ${index}`);if(index===0)continue;const previous=points[index-1];const length=Math.hypot(point.x-previous.x,point.y-previous.y);if(!Number.isFinite(length))throw new Error("Path segment length must be finite");total+=length;if(!Number.isFinite(total))throw new Error("Path length must be finite");lengths.push(length)}return lengths}function tracePolyline(points,progress){const amount2=clampProgress(progress);if(points.length===0)return[];const lengths=pathLengths(points);if(amount2===1)return points.map(({x,y})=>({x,y}));const traced2=[{x:points[0].x,y:points[0].y}];if(amount2===0||lengths.length===0)return traced2;const total=lengths.reduce((sum,length)=>sum+length,0);if(total===0)return traced2;const target=total*amount2;let travelled=0;for(let index=0;index<lengths.length;index+=1){const segmentLength=lengths[index];const next=points[index+1];if(segmentLength===0)continue;const segmentEnd=travelled+segmentLength;if(target>=segmentEnd){traced2.push({x:next.x,y:next.y});travelled=segmentEnd;continue}const segmentProgress=(target-travelled)/segmentLength;const point=interpolate(points[index],next,segmentProgress);assertPoint(point,"Polyline trace result");const previous=traced2[traced2.length-1];if(point.x!==previous.x||point.y!==previous.y)traced2.push(point);return traced2}return traced2}function pointAlongPath(points,progress){if(points.length===0)throw new Error("Cannot find a point along an empty path");const traced2=tracePolyline(points,progress);return{...traced2[traced2.length-1]}}function finite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative(value,name){finite(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function positive(value,name){finite(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function normalizedOpacity(value,name="Canvas opacity"){finite(value,name);return Math.max(0,Math.min(1,value))}function validateBounds(bounds4){finite(bounds4.x,"Canvas x");finite(bounds4.y,"Canvas y");positive(bounds4.width,"Canvas width");positive(bounds4.height,"Canvas height");nonnegative(bounds4.radius??14,"Canvas radius")}function layoutTokenRow(values,options={}){const{advance=24,gap=16,minWidth=64,paddingX=17,width}=options;nonnegative(advance,"Token advance");nonnegative(gap,"Token gap");positive(minWidth,"Token minimum width");nonnegative(paddingX,"Token horizontal padding");if(width!==void 0)positive(width,"Token width");if(options.x!==void 0)finite(options.x,"Token x");if(options.centerX!==void 0)finite(options.centerX,"Token center x");const items=values.map(value=>{const text2=String(value);return{text:text2,x:0,width:width??Math.max(minWidth,text2.length*advance+2*paddingX)}});const totalWidth=items.reduce((total,item)=>total+item.width,0)+Math.max(0,items.length-1)*gap;let x=options.x??(options.centerX??0)-totalWidth/2;finite(x,"Token row origin");for(const item of items){item.x=x;x+=item.width+gap;finite(x,"Token row extent")}return items}function createCanvasComponents(painter){function fade2(alpha3,draw2){const amount2=normalizedOpacity(alpha3);if(amount2>0)painter.opacity(amount2,draw2)}function panel(options,draw2){validateBounds(options);const{x,y,width,height,fill,stroke,radius=14,padding=10,id,scope="container",opacity=1}=options;nonnegative(padding,"Canvas padding");const alpha3=normalizedOpacity(opacity);if(scope!=="container"&&scope!=="label")throw new Error("Canvas scope must be container or label");let shape2;const paint=()=>painter.opacity(alpha3,()=>{shape2=painter.rect(x,y,width,height,fill,stroke,radius);if(draw2){const bounds4={x,y,width,height,radius};const scopeOptions={padding,id};if(scope==="label")painter.labelScope(bounds4,draw2,scopeOptions);else painter.container(bounds4,draw2,scopeOptions)}});if(options.focusTarget&&painter.target)painter.target(options.focusTarget,paint);else paint();return shape2}function card(options){const{label,x,y,width,height,fontSize=32,font="sans",textColor,baselineOffset=fontSize*.34,labelOpacity=1}=options;positive(fontSize,"Canvas font size");finite(baselineOffset,"Canvas text baseline offset");const labelAlpha=normalizedOpacity(labelOpacity,"Canvas label opacity");return panel(options,()=>{fade2(labelAlpha,()=>{painter.text(String(label),x+width/2,y+height/2+baselineOffset,fontSize,textColor,"center",font)})})}function matrix2(options){const{values,x,y,cellSize=112,gap=8,inset:inset2=0,format=String,style={},cellStyle}=options;finite(x,"Matrix x");finite(y,"Matrix y");positive(cellSize,"Matrix cell size");nonnegative(gap,"Matrix gap");finite(inset2,"Matrix inset");if(gap>=cellSize)throw new Error("Matrix gap must be smaller than cell size");const columns=values[0]?.length??0;for(const row of values){if(!Array.isArray(row)||row.length!==columns)throw new Error("Canvas matrix rows must be rectangular")}const shapes=[];for(let row=0;row<values.length;row+=1){for(let column=0;column<columns;column+=1){const value=values[row][column];const cell={...style,...cellStyle?.(value,row,column)};finite(cell.opacity??1,"Canvas opacity");if((cell.opacity??1)<=0)continue;const shape2=card({...cell,x:x+column*cellSize+inset2,y:y+row*cellSize+inset2,width:cellSize-gap,height:cellSize-gap,label:format(value,row,column)});shapes.push(shape2)}}return shapes}function tokenRow(options){const{values,y,height=68,reveal:reveal2=1,opacity=1,...style}=options;finite(y,"Token row y");positive(height,"Token height");finite(reveal2,"Token reveal");const alpha3=normalizedOpacity(opacity);const items=layoutTokenRow(values,options);const shapes=[];for(let index=0;index<items.length;index+=1){const amount2=Math.max(0,Math.min(1,reveal2*items.length-index))*alpha3;if(amount2<=0)continue;const{text:label,x,width}=items[index];const shape2=card({...style,label,x,y,width,height,opacity:amount2});shapes.push(shape2)}return shapes}function particle(options){const{points,progress,radius=9,fill,stroke,strokeWidth=3}=options;finite(progress,"Particle progress");positive(radius,"Particle radius");nonnegative(strokeWidth,"Particle stroke width");if(progress<=0||progress>=1)return null;const point=pointAlongPath(points,progress);painter.circle(point.x,point.y,radius,fill,stroke,strokeWidth);return point}return{panel,card,matrix:matrix2,tokenRow,particle,fade:fade2}}function nonnegative2(value,name){if(!Number.isFinite(value)||value<0)throw new Error(`${name} must be finite and nonnegative`)}function alpha(value){if(!Number.isFinite(value))throw new Error("Transfer opacity must be finite");return Math.max(0,Math.min(1,value))}function bounds(shape2){if(![shape2.x,shape2.y,shape2.width,shape2.height].every(Number.isFinite)||shape2.width<=0||shape2.height<=0){throw new Error("Transfer endpoints require finite positive rectangular bounds")}nonnegative2(shape2.radius??0,"Transfer corner radius")}function center(shape2){return{x:shape2.x+shape2.width/2,y:shape2.y+shape2.height/2}}function edgeDistance(shape2,ux,uy){const halfWidth=shape2.width/2,halfHeight=shape2.height/2;const limit=Math.min(ux===0?Infinity:halfWidth/Math.abs(ux),uy===0?Infinity:halfHeight/Math.abs(uy));const radius=Math.min(shape2.radius??0,halfWidth,halfHeight);if(radius===0)return limit;const outside=distance=>Math.hypot(Math.max(0,Math.abs(ux*distance)-(halfWidth-radius)),Math.max(0,Math.abs(uy*distance)-(halfHeight-radius)))>radius;if(!outside(limit))return limit;let low=0,high=limit;for(let index=0;index<32;index+=1){const middle=(low+high)/2;if(outside(middle))high=middle;else low=middle}return low}function safeGap(shape2,ux,uy,clearance,edge){const expanded2=Math.min(ux===0?Infinity:(shape2.width/2+clearance)/Math.abs(ux),uy===0?Infinity:(shape2.height/2+clearance)/Math.abs(uy));return expanded2-edge}function createTeachingTransfer(painter){return options=>{const{source,target,color="#63DEEC",width=3,margin=2,progress,particle}=options;bounds(source.shape);bounds(target.shape);nonnegative2(width,"Transfer stroke width");if(width===0)throw new Error("Transfer stroke width must be positive");nonnegative2(margin,"Transfer margin");const opacity=Math.min(alpha(source.opacity),alpha(target.opacity),alpha(options.opacity??1));for(const gap of[options.gap,options.fromGap,options.toGap]){if(gap!==void 0)nonnegative2(gap,"Transfer gap")}if(progress!==void 0&&!Number.isFinite(progress))throw new Error("Transfer progress must be finite");if(particle&&progress===void 0)throw new Error("Transfer particle requires progress");const radius=particle?.radius??7,strokeWidth=particle?.strokeWidth??3;nonnegative2(radius,"Transfer particle radius");if(radius===0)throw new Error("Transfer particle radius must be positive");nonnegative2(strokeWidth,"Transfer particle stroke width");if(opacity===0)return null;const a=center(source.shape),z=center(target.shape);const distance=Math.hypot(z.x-a.x,z.y-a.y);if(!Number.isFinite(distance)||distance===0)throw new Error("Transfer endpoints must have distinct finite centers");const ux=(z.x-a.x)/distance,uy=(z.y-a.y)/distance;const sourceEdge=edgeDistance(source.shape,ux,uy),targetEdge=edgeDistance(target.shape,ux,uy);const markerRadius=progress===void 0?0:radius+(particle?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerRadius)+margin;const fromGap=Math.max(options.fromGap??options.gap??0,safeGap(source.shape,ux,uy,clearance,sourceEdge));const toGap=Math.max(options.toGap??options.gap??0,safeGap(target.shape,ux,uy,clearance,targetEdge));if(distance<=sourceEdge+targetEdge+fromGap+toGap)throw new Error("Transfer endpoints leave no room for the requested clearance");let route;painter.opacity(opacity,()=>{route=painter.connect(source.shape,target.shape,{color,width,fromGap,toGap});if(progress!==void 0&&progress>0&&progress<1){const x=route.from.x*(1-progress)+route.to.x*progress;const y=route.from.y*(1-progress)+route.to.y*progress;painter.circle(x,y,radius,particle?.fill??color,particle?.stroke,strokeWidth)}});return route}}function positive2(value,name){if(!Number.isFinite(value)||value<=0)throw new Error(`${name} must be finite and positive`)}function layoutCellGrid(options){const{x,y,width,height,rows,columns}=options;if(![x,y,x+width,y+height].every(Number.isFinite))throw new Error("Grid bounds must be finite");positive2(width,"Grid width");positive2(height,"Grid height");if(![rows,columns,rows*columns].every(Number.isSafeInteger)||rows<=0||columns<=0){throw new Error("Grid rows and columns must be positive safe integers")}const bounds4={x,y,width,height};const cells=Array.from({length:rows},(_,row)=>Array.from({length:columns},(_2,column)=>({x:x+column*width/columns,y:y+row*height/rows,width:width/columns,height:height/rows})));return{bounds:bounds4,cells,cell(row,column){if(!Number.isSafeInteger(row)||!Number.isSafeInteger(column)||row<0||row>=rows||column<0||column>=columns){throw new Error("Grid cell index is outside the grid")}return cells[row][column]}}}function createTeachingGrid(painter){const components=createCanvasComponents(painter);return options=>{const layout=layoutCellGrid(options);const{x,y,width,height,rows,columns,fill="#18283B",stroke="#63DEEC",lineWidth=1,labels,highlights=[],fontSize=28,textColor="#FFFFFF",padding=4}=options;positive2(lineWidth,"Grid line width");if(lineWidth>=Math.min(width/columns,height/rows))throw new Error("Grid line width must be smaller than a cell");positive2(fontSize,"Grid font size");if(!Number.isFinite(padding)||padding<0)throw new Error("Grid padding must be finite and nonnegative");if(labels&&(labels.length!==rows||labels.some(row=>row.length!==columns))){throw new Error("Grid labels must match rows and columns")}for(const highlight of highlights){layout.cell(highlight.row,highlight.column);if(!Number.isFinite(highlight.opacity??1))throw new Error("Grid highlight opacity must be finite")}const cellFocusTarget=painter.target?options.cellFocusTarget:void 0;const shape2=components.panel({...layout.bounds,fill:cellFocusTarget?"transparent":fill,stroke,radius:0,padding:0},()=>{const drawLabel=(r,column)=>{if(!labels)return;const cell=layout.cell(r,column),value=String(labels[r][column]);const baseline=cell.y+cell.height/2+fontSize*.34-(value.split("\n").length-1)*fontSize*.7;painter.labelScope(cell,()=>painter.text(value,cell.x+cell.width/2,baseline,fontSize,textColor,"center"),{padding})};if(cellFocusTarget)for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){const named=cellFocusTarget(row,column),ids=typeof named==="string"?[named]:named??[];const draw2=()=>{const cell=layout.cell(row,column),inset3=lineWidth/2;painter.rect(cell.x+inset3,cell.y+inset3,cell.width-lineWidth,cell.height-lineWidth,fill,void 0,0);for(const highlight of highlights.filter(item=>item.row===row&&item.column===column)){const pad2=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>painter.rect(cell.x+pad2,cell.y+pad2,cell.width-pad2*2,cell.height-pad2*2,highlight.fill,highlight.stroke,0))}drawLabel(row,column)};const scoped=index=>{if(index<ids.length&&painter.target)painter.target(ids[index],()=>scoped(index+1));else draw2()};scoped(0)}for(const highlight of cellFocusTarget?[]:highlights){const cell=layout.cell(highlight.row,highlight.column);const inset3=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>{painter.rect(cell.x+inset3,cell.y+inset3,cell.width-2*inset3,cell.height-2*inset3,highlight.fill,highlight.stroke,0)})}const inset2=lineWidth/2;for(let column=1;column<columns;column+=1){const left=x+column*width/columns;painter.path([{x:left,y:y+inset2},{x:left,y:y+height-inset2}],{color:stroke,width:lineWidth})}for(let row=1;row<rows;row+=1){const top=y+row*height/rows;painter.path([{x:x+inset2,y:top},{x:x+width-inset2,y:top}],{color:stroke,width:lineWidth})}if(!cellFocusTarget)labels?.forEach((row,r)=>row.forEach((_,column)=>drawLabel(r,column)))});return{...layout,shape:shape2}}}function createTeachingTimeline(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,domain:[lo,hi],lanes,intervals,time=hi,ticks:ticks2=[lo,hi],formatTime=String,labelWidth=180,laneGap=18,fontSize=28,color="#8D9CB9",trackColor="#18283B",cursorColor="#FFCE73"}=options;if(![x,y,x+width,y+height,lo,hi,hi-lo,time,labelWidth,laneGap,fontSize].every(Number.isFinite))throw new Error("Timeline values must be finite");if(width<=0||height<=0||hi<=lo||time<lo||time>hi)throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");if(fontSize<=0||labelWidth<=12||labelWidth>=width-6||laneGap<0||!lanes.length)throw new Error("Timeline needs positive label space, font size, and at least one lane");const ids=new Set(lanes.map(lane=>lane.id));if(ids.size!==lanes.length||lanes.some(lane=>!lane.id))throw new Error("Timeline lane IDs must be nonempty and unique");const intervalIds=new Set;for(const interval of intervals){if(!interval.id||intervalIds.has(interval.id)||!ids.has(interval.lane))throw new Error("Timeline intervals need unique IDs and an existing lane");intervalIds.add(interval.id);if(![interval.start,interval.end,interval.opacity??1].every(Number.isFinite)||interval.start<lo||interval.end>hi||interval.end<=interval.start)throw new Error("Timeline intervals must have finite positive durations inside the domain")}for(const lane of lanes){const ordered=intervals.filter(interval=>interval.lane===lane.id).sort((a,b)=>a.start-b.start);if(ordered.some((interval,i)=>i>0&&interval.start<ordered[i-1].end))throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`)}if(ticks2.some(tick=>!Number.isFinite(tick)||tick<lo||tick>hi))throw new Error("Timeline ticks must lie inside the domain");const axisHeight=Math.max(36,fontSize*2+18);const laneHeight=(height-axisHeight-(lanes.length-1)*laneGap)/lanes.length;const labelHeight=fontSize*1.5,barHeight=laneHeight-labelHeight;if(barHeight<12)throw new Error("Timeline height cannot fit lane labels and interval bars");const left=x+labelWidth+3,plotWidth=width-labelWidth-6;const point=value=>{if(!Number.isFinite(value)||value<lo||value>hi)throw new Error("Timeline point must lie inside the domain");return left+(value-lo)/(hi-lo)*plotWidth};const bounds4={x,y,width,height};const result={bounds:bounds4,time,point,lanes:Object.create(null),intervals:Object.create(null)};painter.container(bounds4,()=>{lanes.forEach((lane,index)=>target(lane.focusTarget,()=>{const top=y+index*(laneHeight+laneGap);const track={x:left-2,y:top+labelHeight,width:plotWidth+4,height:barHeight};const shape2=painter.rect(track.x,track.y,track.width,track.height,trackColor,color,0);result.lanes[lane.id]={shape:shape2,bounds:track};painter.labelScope({x,y:top,width:labelWidth-12,height:laneHeight},()=>{painter.text(lane.label,x,top+laneHeight/2+fontSize*.34,fontSize,color,"left")},{padding:0});for(const interval of intervals.filter(item=>item.lane===lane.id)){const visibleEnd=Math.max(interval.start,Math.min(time,interval.end));const elapsed=visibleEnd-interval.start;const bar={x:point(interval.start),y:track.y+2,width:point(visibleEnd)-point(interval.start),height:barHeight-4};const opacity=Math.max(0,Math.min(1,interval.opacity??1));const item={id:interval.id,shape:null,bounds:bar,elapsed,opacity,complete:time>=interval.end};result.intervals[interval.id]=item;if(elapsed===0||opacity===0)continue;target(interval.focusTarget,()=>painter.opacity(opacity,()=>{painter.container(track,()=>{item.shape=painter.rect(bar.x,bar.y,bar.width,bar.height,interval.color??"#63DEEC",void 0,0)},{padding:0});if(interval.label){const labelBounds={x:point(interval.start),y:top,width:point(interval.end)-point(interval.start),height:labelHeight};painter.labelScope(labelBounds,()=>painter.text(interval.label,labelBounds.x+labelBounds.width/2,top+fontSize,fontSize,interval.color??"#63DEEC","center"),{padding:2})}}))}}));const axisY=y+height-axisHeight+Math.max(10,fontSize*.5);painter.line(left,axisY,left+plotWidth,axisY,color,2);for(const tick of ticks2){const px=point(tick);painter.line(px,axisY,px,axisY+6,color,2);painter.labelScope({x:left-labelWidth,y:axisY+8,width:plotWidth+labelWidth,height:fontSize*1.5},()=>{painter.text(formatTime(tick),px,axisY+fontSize*1.4,fontSize,color,tick===hi?"right":tick===lo?"left":"center")},{padding:0})}painter.line(point(time),axisY-8,point(time),axisY+8,cursorColor,3)},{padding:0});return result}}var COLORS=["#63DEEC","#79A6FF","#D6A0FF","#FFCE73"];function layoutAllocation(options){const{x,y,width,height,capacity,parts}=options;if(![x,y,x+width,y+height,capacity].every(Number.isFinite)||width<=0||height<=0||capacity<=0)throw new Error("Allocation needs finite positive bounds and capacity");const ids=new Set;let used=0;for(const part of parts){if(!part.id||ids.has(part.id))throw new Error("Allocation part IDs must be nonempty and unique");ids.add(part.id);if(!Number.isFinite(part.value)||part.value<0)throw new Error("Allocation values must be finite and nonnegative");used+=part.value}if(!Number.isFinite(used)||used-capacity>Number.EPSILON*Math.max(used,capacity)*8)throw new Error("Allocation exceeds capacity");used=Math.min(used,capacity);let offset=0;const segments=parts.map(part=>{const start=Math.min(offset,capacity);offset+=part.value;return{id:part.id,value:part.value,bounds:{x:x+width*(start/capacity),y,width:width*((Math.min(offset,capacity)-start)/capacity),height}}});const remaining=Math.max(0,capacity-used);return{bounds:{x,y,width,height},used,remaining,parts:segments,freeBounds:{x:x+width*(used/capacity),y,width:width*(remaining/capacity),height}}}function createTeachingAllocation(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,fontSize=28,unit="",format=String,color="#8D9CB9",trackColor="#18283B"}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Allocation font size must be finite and positive");const header=fontSize*1.7,barHeight=fontSize*2,rowHeight=fontSize*1.65,gap=fontSize*.6;if(height<header+barHeight+gap+(options.parts.length+1)*rowHeight||width<=6||width*.67<=fontSize)throw new Error("Allocation bounds cannot fit the strip and ledger");const layout=layoutAllocation({...options,x:x+3,y:y+header+3,width:width-6,height:barHeight-6});const suffix=unit?` ${unit}`:"",shapes=[];let shape2;painter.container({x,y,width,height},()=>{painter.labelScope({x,y,width,height:header},()=>painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`,x,y+fontSize,fontSize,color,"left"),{padding:0});const strip={x:x+1,y:y+header+1,width:width-2,height:barHeight-2};shape2=painter.rect(strip.x,strip.y,strip.width,strip.height,trackColor,color,0);painter.container(strip,()=>{layout.parts.forEach((part,index)=>shapes.push(part.bounds.width===0?null:target(options.parts[index].focusTarget,()=>painter.rect(part.bounds.x,part.bounds.y,part.bounds.width,part.bounds.height,options.parts[index].color??COLORS[index%COLORS.length],void 0,0))))},{padding:0});const rows=[...options.parts,{id:"free",label:"Free",value:layout.remaining,color,focusTarget:options.freeFocusTarget}];rows.forEach((part,index)=>target(part.focusTarget,()=>{const top=y+header+barHeight+gap+index*rowHeight,baseline=top+rowHeight/2+fontSize*.34;painter.rect(x,top+(rowHeight-fontSize*.6)/2,fontSize*.6,fontSize*.6,part.color??COLORS[index%COLORS.length],void 0,0);painter.labelScope({x:x+fontSize,y:top,width:width*.67-fontSize,height:rowHeight},()=>painter.text(part.label,x+fontSize,baseline,fontSize,color,"left"),{padding:0});painter.labelScope({x:x+width*.7,y:top,width:width*.3,height:rowHeight},()=>painter.text(`${format(part.value)}${suffix}`,x+width,baseline,fontSize,color,"right"),{padding:0})}))},{padding:0});return{...layout,shapes,shape:shape2}}}var clamp=value=>Math.max(0,Math.min(1,value));var smooth=value=>value*value*(3-2*value);function valueChangeState(options){for(const name of["from","to","progress"]){if(!Number.isFinite(options[name]))throw new Error(`Value change ${name} must be finite`)}if(options.emphasis!==void 0&&!Number.isFinite(options.emphasis))throw new Error("Value change emphasis must be finite");const{from,to:to2}=options;const progress=clamp(options.progress);const changed=from!==to2;const emphasis=changed?clamp(options.emphasis??smooth(clamp(progress/.12))*(1-smooth(clamp((progress-.65)/.35)))):0;const value=from*(1-progress)+to2*progress;const delta=to2-from;if(!Number.isFinite(value)||!Number.isFinite(delta))throw new Error("Value change result must be finite");return{value,previous:from,target:to2,delta,changed,emphasis}}function createTeachingValueChange(painter){function changeCue(options,draw2){const{x,y,width,height,color="#F4D477",restColor="#E9EFFF",fill=color,radius=10}=options;if(![x,y,width,height,radius].every(Number.isFinite)||width<=0||height<=0||radius<0){throw new Error("Value change bounds must be finite with positive dimensions and nonnegative radius")}const state=valueChangeState({from:options.from,to:options.to,progress:options.progress,...options.emphasis===void 0?{}:{emphasis:options.emphasis}});if(state.emphasis>0){painter.opacity(state.emphasis*.12,()=>painter.rect(x,y,width,height,fill,void 0,radius));painter.opacity(state.emphasis,()=>painter.rect(x,y,width,height,"transparent",color,radius))}const result={...state,color:state.emphasis>0?color:restColor};draw2?.(result);return result}function valueChange(options){const{x,y,width,height,label,format=value=>value.toFixed(1),fontSize=36,showDelta=true}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Value change font size must be positive");const lines=1+Number(Boolean(label))+Number(showDelta);if(height<fontSize*(lines===1?1.4:lines===2?2.3:3))throw new Error("Value change height must contain its label and delta");return changeCue(options,state=>painter.labelScope({x,y,width,height},()=>{const center2=x+width/2;if(label)painter.text(label,center2,y+fontSize*.7,fontSize*.55,options.restColor??"#E9EFFF","center");const baseline=label?y+height*(showDelta?.5:.65)+fontSize*.2:showDelta?y+fontSize*1.05:y+height/2+fontSize*.34;painter.text(format(state.value),center2,baseline,fontSize,state.color,"center","mono");if(showDelta){const sign=state.delta>0?"+":"";painter.text(`${format(state.previous)} \u2192 ${format(state.target)} \xB7 \u0394 ${sign}${format(state.delta)}`,center2,y+height-fontSize*.3,fontSize*.46,options.restColor??"#E9EFFF","center","mono")}},{padding:4}))}return{changeCue,valueChange}}function mergeFocusRegions(parts,gap=12){const regions=[];for(const part of parts){let current={...part},index=0;while(index<regions.length){const other=regions[index];if(current.x<=other.x+other.width+gap&&other.x<=current.x+current.width+gap&&current.y<=other.y+other.height+gap&&other.y<=current.y+current.height+gap){const x=Math.min(current.x,other.x),y=Math.min(current.y,other.y);current={x,y,width:Math.max(current.x+current.width,other.x+other.width)-x,height:Math.max(current.y+current.height,other.y+other.height)-y};regions.splice(index,1);index=0}else index++}regions.push(current)}return regions}function createFocusDirector(painter,options={}){const{cues,strict=false,contextOpacity=.52,minimumContextAlpha=0}=options;if(!Number.isFinite(contextOpacity)||contextOpacity<0||contextOpacity>1)throw new Error("Focus context opacity must be between zero and one");if(!Number.isFinite(minimumContextAlpha)||minimumContextAlpha<0||minimumContextAlpha>1)throw new Error("Minimum context alpha must be between zero and one");const active=Object.values(cues??{}).filter(cue2=>cue2.active&&cue2.strength>0).sort((a,b)=>b.start-a.start||b.id.localeCompare(a.id))[0];const stack=[];function cue(id){const value=cues&&Object.hasOwn(cues,id)?cues[id]:void 0;if(!value&&strict)throw new Error(`Unknown narration cue: ${id}`);return value}function opacity(amount2,draw2){if(amount2===1)return draw2();let result;painter.opacity(amount2,()=>{result=draw2()});return result}return{active,cue,progress(id,fallback=0){return cue(id)?.progress??fallback},visible(id){return cue(id)?.phase!=="before"},reveal(id,draw2){return opacity(cue(id)?.reveal??1,draw2)},target(id,draw2){stack.push(id);try{return draw2()}finally{stack.pop()}},paint(draw2,originalAlpha=1){const focused=!active||stack.some(id=>active.targets.includes(id));let amount2=focused?1:1-(1-contextOpacity)*active.strength;if(!focused&&originalAlpha>0)amount2=Math.max(amount2,Math.min(originalAlpha,minimumContextAlpha)/originalAlpha);return opacity(amount2,draw2)}}}function createTeachingFocus(painter){function focusFrame(options){const{bounds:bounds4,strength,color="#63DEEC",padding=8,clip}=options;if(![bounds4.x,bounds4.y,bounds4.width,bounds4.height,strength,padding].every(Number.isFinite)||bounds4.width<=0||bounds4.height<=0||padding<0||strength<0||strength>1)throw new Error("Invalid focus frame geometry or strength");if(strength===0)return;const corners=offset=>{const x=bounds4.x-offset,y=bounds4.y-offset,w=bounds4.width+offset*2,h=bounds4.height+offset*2;const corner=Math.min(24,w/4,h/4);return[[x,y,1,1],[x+w,y,-1,1],[x,y+h,1,-1],[x+w,y+h,-1,-1]].map(([cx,cy,sx,sy])=>[{x:cx+sx*corner,y:cy},{x:cx,y:cy},{x:cx,y:cy+sy*corner}])};const clear=points=>points.slice(1).every((point,index)=>{const previous=points[index],x=Math.min(previous.x,point.x)-2,y=Math.min(previous.y,point.y)-2;const right=Math.max(previous.x,point.x)+2,bottom=Math.max(previous.y,point.y)+2;return(!clip||x>=clip.x&&y>=clip.y&&right<=clip.x+clip.width&&bottom<=clip.y+clip.height)&&!(options.avoid??[]).some(label=>x<label.x+label.width&&right>label.x&&y<label.y+label.height&&bottom>label.y)});let paths=corners(padding);if(!paths.every(clear)){const alternatives=[padding+6,padding+12,padding+20].map(corners);paths=alternatives.find(candidate=>candidate.every(clear))??paths.filter(clear)}if(paths.length<2)return;painter.opacity(strength*.7,()=>{for(const[index,points]of paths.entries()){painter.path(points,{id:options.id&&`${options.id}:${index}`,color,width:3,clip})}})}return{focusFrame}}var clamp2=value=>Math.max(0,Math.min(1,value));var cleanZero=value=>value===0?0:value;function finite2(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`);return value}function vector(values,dimensions,name){if(values.length!==dimensions)throw new Error(`${name} must have ${dimensions} coordinates`);return values.map(value=>cleanZero(finite2(value,name)))}function add(left,right){return left.map((value,index)=>cleanZero(finite2(value+right[index],"Weighted vector sum")))}function weightedVectorState(options){const progress=clamp2(finite2(options.progress,"Weighted vector progress"));const dimensions=options.initial?.length??options.terms[0]?.values.length??0;if(!dimensions)throw new Error("Weighted vectors require at least one coordinate; an empty sum needs an initial vector");const initial=options.initial?vector(options.initial,dimensions,"Initial vector"):Array(dimensions).fill(0);const ids=new Set;let prefix2=[...initial];const position2=progress*options.terms.length;const completedCount=Math.min(options.terms.length,Math.floor(position2));const terms=options.terms.map((term,index)=>{if(typeof term.id!=="string"||!term.id.trim()||term.id!==term.id.trim()||ids.has(term.id)){throw new Error("Weighted vector terms require distinct nonempty IDs without surrounding whitespace")}ids.add(term.id);const label=term.label??term.id;if(typeof label!=="string"||!label.trim())throw new Error("Weighted vector labels must be nonempty");const weight=finite2(term.weight,"Vector weight");const values=vector(term.values,dimensions,`Vector ${term.id}`);const contribution=values.map(value=>cleanZero(finite2(weight*value,"Weighted vector contribution")));const start=[...prefix2],end=add(start,contribution);prefix2=end;const fraction=clamp2(position2-index);const status=fraction===1?"completed":index===completedCount&&progress<1?"current":"pending";const applied=contribution.map(value=>cleanZero(value*fraction));return{...term,label,values,weight,status,progress:fraction,contribution,applied,start,end,currentEnd:add(start,applied),zero:contribution.every(value=>value===0)}});const completedSum=completedCount?[...terms[completedCount-1].end]:[...initial];const current=terms.find(term=>term.status==="current")??null;return{progress,dimensions,initial,terms,completedCount,current,completedSum,sum:current?[...current.currentEnd]:[...completedSum],total:[...prefix2]}}function positive3(value,name){if(finite2(value,name)<=0)throw new Error(`${name} must be positive`)}function bounds2(value,name){finite2(value.x,`${name} x`);finite2(value.y,`${name} y`);positive3(value.width,`${name} width`);positive3(value.height,`${name} height`)}function createTeachingVectorAccumulation(painter){return options=>{const state=weightedVectorState(options);const{plot,ledger,projection,fontSize=28,color="#63DEEC",restColor="#8D9CB9",completedOpacity=.45,width=4,endpointRadius=5,revealTotal=false,totalLabel="Accumulated vector",format=value=>String(Number(value.toPrecision(4)))}=options;bounds2(plot.bounds,"Vector plot");bounds2(ledger,"Vector ledger");positive3(fontSize,"Vector font size");positive3(width,"Vector stroke width");positive3(endpointRadius,"Vector endpoint radius");finite2(completedOpacity,"Completed vector opacity");if(completedOpacity<0||completedOpacity>1)throw new Error("Completed vector opacity must lie between zero and one");const[x0,x1]=plot.xDomain,[y0,y1]=plot.yDomain;for(const value of[x0,x1,y0,y1])finite2(value,"Vector plot domain");if(x1<=x0||y1<=y0)throw new Error("Vector plot domains must increase");const sx=plot.bounds.width/(x1-x0),sy=plot.bounds.height/(y1-y0);if(!Number.isFinite(sx)||!Number.isFinite(sy)||sx<=0||sy<=0||Math.abs(sx-sy)>Math.max(sx,sy)*1e-9){throw new Error("Weighted vector drawing requires equal-unit plot geometry")}if(state.dimensions!==2&&!projection)throw new Error("Weighted vector drawing requires 2D values or an explicit projection");if(projection&&!projection.label.trim())throw new Error("Vector projection requires a visible declaration");const rowHeight=fontSize*2.5,headerHeight=fontSize*1.6;if(ledger.height<headerHeight+state.terms.length*rowHeight+fontSize*1.8){throw new Error("Vector ledger height must contain the identities, contributions and result")}const point=values=>{const projected=projection?projection.point([...values]):values;if(projected.length!==2)throw new Error("Vector projection must return exactly two coordinates");const[x,y]=projected;finite2(x,"Projected vector x");finite2(y,"Projected vector y");if(x<x0||x>x1||y<y0||y>y1)throw new Error("Vector endpoints must lie inside the declared plot domains");const p=plot.point(x,y);finite2(p.x,"Vector endpoint x");finite2(p.y,"Vector endpoint y");const expectedX=finite2(plot.bounds.x+(x-x0)*sx,"Declared vector endpoint x");const expectedY=finite2(plot.bounds.y+plot.bounds.height-(y-y0)*sy,"Declared vector endpoint y");const tolerance=Math.max(1,Math.abs(expectedX),Math.abs(expectedY),plot.bounds.width,plot.bounds.height)*1e-9;if(Math.abs(p.x-expectedX)>tolerance||Math.abs(p.y-expectedY)>tolerance){throw new Error("Vector plot mapping must match its declared equal-unit transform")}return p};const segments=[];for(const term of state.terms){const from=point(term.start);point(term.end);const to2=point(term.currentEnd);if(term.status!=="pending")segments.push({id:term.id,status:term.status,from,to:to2,zero:Math.hypot(to2.x-from.x,to2.y-from.y)<1e-9})}const endpoint=point(state.sum);const vectorText=values=>`(${values.map(value=>format(value)).join(", ")})`;const target=(id,draw2)=>painter.target?painter.target(id,draw2):draw2();const paintedTerms=state.terms.map((term,index)=>({term,index,input:`${term.label}: ${format(term.weight)} \xD7 ${vectorText(term.values)}`,detail:term.status==="pending"?"pending":`${term.status}: ${vectorText(term.applied)}`}));const totalText=`${totalLabel}: ${revealTotal?vectorText(state.sum):"?"}`;for(const segment of segments){const term=state.terms.find(term2=>term2.id===segment.id);const ink=term.color??color;target(term.id,()=>painter.opacity(term.status==="completed"?completedOpacity:1,()=>{if(segment.zero)painter.circle(segment.to.x,segment.to.y,endpointRadius,"transparent",ink,width);else painter.arrow(segment.from.x,segment.from.y,segment.to.x,segment.to.y,ink,width)}))}if(revealTotal){const mark=()=>{painter.circle(endpoint.x,endpoint.y,endpointRadius*1.5,color)};if(options.totalTarget)target(options.totalTarget,mark);else mark()}painter.labelScope(ledger,()=>{painter.text(projection?`Projection: ${projection.label}`:"Weighted contributions",ledger.x+12,ledger.y+fontSize,fontSize*.85,restColor);for(const{term,index,input,detail}of paintedTerms)target(term.id,()=>{const ink=term.color??color;const y=ledger.y+headerHeight+index*rowHeight;painter.text(input,ledger.x+12,y+fontSize,fontSize,term.status==="pending"?restColor:ink);painter.text(detail,ledger.x+12,y+fontSize*1.9,fontSize*.8,restColor)});const result=()=>{painter.text(totalText,ledger.x+12,ledger.y+headerHeight+state.terms.length*rowHeight+fontSize,fontSize,revealTotal?color:restColor)};if(options.totalTarget)target(options.totalTarget,result);else result()},{padding:4});return{state,segments,endpoint}}}function categoricalSampling(options){if(options.normalization!=="probabilities"&&options.normalization!=="weights")throw new Error("Sampling requires an explicit mass normalization contract");if(!options.categories.length)throw new Error("Sampling needs at least one category");const ids=new Set;let total=0;for(const category of options.categories){if(!category.id||ids.has(category.id)||!category.label.trim())throw new Error("Sampling category IDs must be unique and labels nonempty");if(!Number.isFinite(category.mass)||category.mass<0)throw new Error("Sampling masses must be finite and nonnegative");ids.add(category.id);total+=category.mass}if(!Number.isFinite(total)||total<=0)throw new Error("Sampling total mass must be finite and positive");if(options.normalization==="probabilities"&&Math.abs(total-1)>1e-12)throw new Error("Sampling probabilities must sum to one within 1e-12");let cumulative=0;let lastPositive=0;options.categories.forEach((category,index)=>{if(category.mass>0)lastPositive=index});const categories=options.categories.map((category,index)=>{const lower=cumulative,probability=category.mass/total;cumulative=index===lastPositive?1:Math.min(1,cumulative+probability);if(category.mass>0&&(probability===0||cumulative<=lower))throw new Error("Positive category is too small for cumulative floating-point precision");return{...category,probability,lower,upper:cumulative,count:0,empiricalProbability:null}});ids.clear();const draws=options.draws.map(draw2=>{if(!draw2.id||ids.has(draw2.id))throw new Error("Sampling draw IDs must be nonempty and unique");if(!Number.isFinite(draw2.uniform)||draw2.uniform<0||draw2.uniform>=1)throw new Error("Supplied uniform draws must be finite inside [0, 1)");ids.add(draw2.id);const categoryIndex=categories.findIndex(category=>category.mass>0&&draw2.uniform>=category.lower&&draw2.uniform<category.upper);if(categoryIndex<0)throw new Error("Supplied draw could not be represented by the normalized intervals");categories[categoryIndex].count+=1;return{...draw2,categoryId:categories[categoryIndex].id,categoryIndex}});if(draws.length)categories.forEach(category=>{category.empiricalProbability=category.count/draws.length});return{inputTotal:total,normalization:options.normalization,categories,draws}}var COLORS2=["#79A6FF","#FF8DC3","#63DEEC","#FFCE73","#A6DF91"];function createTeachingCategoricalSampling(painter){return options=>{const model=categoricalSampling(options);const{x,y,width,height,fontSize=28,color="#DEE7F5",trackColor="#18283B",visibleDraws=0,drawProgress=0,showEmpirical=false,formatProbability=value=>value.toFixed(3)}=options;if(![x,y,x+width,y+height,fontSize].every(Number.isFinite)||fontSize<=0||width<=0||height<=0)throw new Error("Sampling needs finite positive bounds and font size");if(!Number.isInteger(visibleDraws)||visibleDraws<0||visibleDraws>model.draws.length)throw new Error("Visible sample count must be an integer inside the supplied draw count");if(!Number.isFinite(drawProgress)||drawProgress<0||drawProgress>1||visibleDraws===model.draws.length&&drawProgress!==0)throw new Error("Sampling progress must be inside [0, 1] for an available next draw");if(showEmpirical&&visibleDraws!==model.draws.length)throw new Error("Empirical reveal requires every supplied sample to be retained");const columns=options.columns??Math.max(1,Math.min(8,model.draws.length));if(!Number.isInteger(columns)||columns<1)throw new Error("Sampling columns must be a positive integer");const railWidth=fontSize*2,contentWidth=width-railWidth;const gap=fontSize*.5,cellWidth=(contentWidth-4-(columns-1)*gap)/columns,cellHeight=fontSize*1.9;const legendColumns=Math.min(3,model.categories.length),legendRows=Math.ceil(model.categories.length/legendColumns),legendHeight=legendRows*fontSize*1.7;const bandY=y+fontSize*4,bandHeight=fontSize*1.3,legendY=bandY+bandHeight+fontSize*1.5;const captionY=legendY+legendHeight+fontSize*.5,poolY=captionY+fontSize*3.3,rows=Math.ceil(model.draws.length/columns),empiricalY=poolY+Math.max(1,rows)*(cellHeight+gap)+fontSize*2;if(cellWidth<fontSize*2||contentWidth/legendColumns<fontSize*5||empiricalY+bandHeight+fontSize*1.7>y+height)throw new Error("Sampling bounds cannot fit probability labels, sample IDs and empirical strip");const inset2=fontSize*.22+2,stripX=x+inset2,stripWidth=contentWidth-inset2*2;const point=u=>stripX+u*stripWidth;const categoryColor=index=>model.categories[index].color??COLORS2[index%COLORS2.length];const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const label=(value,bounds4,align="left",ink=color,size=fontSize)=>painter.labelScope(bounds4,()=>painter.text(value,align==="center"?bounds4.x+bounds4.width/2:align==="right"?bounds4.x+bounds4.width:bounds4.x,bounds4.y+size*1.05,size,ink,align),{padding:0});const strip=(top,empirical)=>{painter.rect(stripX,top,stripWidth,bandHeight,trackColor,void 0,0);let cumulative=0;model.categories.forEach((category,index)=>{const probability=empirical?category.empiricalProbability??0:category.probability;const left=cumulative;cumulative+=probability;if(probability>0)target(category.focusTarget,()=>painter.rect(point(left),top,stripWidth*probability,bandHeight,categoryColor(index),void 0,0))})};const sampleBounds=model.draws.map((_draw,index)=>({x:x+2+index%columns*(cellWidth+gap),y:poolY+Math.floor(index/columns)*(cellHeight+gap),width:cellWidth,height:cellHeight}));const shapes=[];painter.container({x,y,width,height},()=>{label(options.normalization==="weights"?"Original probabilities \xB7 normalized supplied weights":"Original probabilities \xB7 supplied distribution",{x,y,width:contentWidth,height:fontSize*1.6});strip(bandY,false);label("0",{x,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"left",color,fontSize*.8);label("1",{x:x+contentWidth-fontSize*2,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"right",color,fontSize*.8);model.categories.forEach((category,index)=>{const bounds4={x:x+index%legendColumns*contentWidth/legendColumns,y:legendY+Math.floor(index/legendColumns)*fontSize*1.7,width:contentWidth/legendColumns-gap,height:fontSize*1.5};target(category.focusTarget,()=>label(`${category.label}: ${formatProbability(category.probability)}`,bounds4,"left",categoryColor(index)))});label(`Supplied samples \xB7 ${visibleDraws} retained / ${model.draws.length}`,{x,y:poolY-fontSize*1.8,width:contentWidth,height:fontSize*1.5});for(let index=0;index<visibleDraws;index+=1)target(options.sampleFocusTarget,()=>{const draw2=model.draws[index],bounds4=sampleBounds[index];shapes.push(painter.rect(bounds4.x,bounds4.y,bounds4.width,bounds4.height,trackColor,categoryColor(draw2.categoryIndex),4));label(draw2.id,bounds4,"center",categoryColor(draw2.categoryIndex))});if(drawProgress>0&&visibleDraws<model.draws.length)target(options.sampleFocusTarget,()=>{const draw2=model.draws[visibleDraws],destination=sampleBounds[visibleDraws],landed=drawProgress>=.4;const from={x:point(draw2.uniform),y:bandY-fontSize*1.2},onBand={x:point(draw2.uniform),y:bandY+bandHeight/2};const progress=landed?(drawProgress-.4)/.6:drawProgress/.4;const destinationPoint={x:destination.x+destination.width/2,y:destination.y+destination.height/2};const railX=x+width-inset2;const route=landed?[onBand,from,{x:railX,y:from.y},{x:railX,y:destinationPoint.y},destinationPoint]:[from,onBand];const lengths=route.slice(1).map((point2,index)=>Math.hypot(point2.x-route[index].x,point2.y-route[index].y));let remaining=progress*lengths.reduce((sum,length)=>sum+length,0);let marker=route[route.length-1];for(let index=0;index<lengths.length;index+=1){const length=lengths[index];if(remaining<=length&&length>0){const ratio=remaining/length;marker={x:route[index].x+(route[index+1].x-route[index].x)*ratio,y:route[index].y+(route[index+1].y-route[index].y)*ratio};break}remaining-=length}const ink=landed?categoryColor(draw2.categoryIndex):color;painter.circle(marker.x,marker.y,fontSize*.22,ink,trackColor,3);const caption=`${landed?"Copy":"Draw"} ${draw2.id} \xB7 supplied u=${draw2.uniform.toFixed(3)}`;label(caption,{x,y:captionY,width:contentWidth,height:fontSize*1.3},"left",ink,fontSize*.8)});if(showEmpirical){label(model.draws.length?"Empirical frequencies \xB7 supplied sample only":"No samples \xB7 empirical distribution undefined",{x,y:empiricalY-fontSize*1.7,width:contentWidth,height:fontSize*1.5});if(model.draws.length){strip(empiricalY,true);const text2=model.categories.map(category=>`${category.label}: ${category.count}/${model.draws.length}`).join(" \xB7 ");label(text2,{x,y:empiricalY+bandHeight+fontSize*.25,width:contentWidth,height:fontSize*1.3},"left",color,fontSize*.8)}}},{padding:0});return{model,sampleBounds,shapes,point,visibleDraws}}}function finite3(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative3(value,name){finite3(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function bounds3(value,name){for(const field of["x","y","width","height"])finite3(value[field],`${name} ${field}`);if(value.width<=0||value.height<=0)throw new Error(`${name} dimensions must be positive`);finite3(value.x+value.width,`${name} right edge`);finite3(value.y+value.height,`${name} bottom edge`)}function identifier(id,name){if(typeof id!=="string"||!id.trim())throw new Error(`${name} must be a nonempty ID`)}function alpha2(value){finite3(value,"Routed transfer opacity");return Math.max(0,Math.min(1,value))}function expanded(box,clearance){return{left:box.x-clearance,top:box.y-clearance,right:box.x+box.width+clearance,bottom:box.y+box.height+clearance}}function lengthOf(points){let sum=0;for(let i=1;i<points.length;i++)sum+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);return sum}function trimLeads(points,amount2){const length=lengthOf(points);if(length<=2*amount2)throw new Error("endpoint spacing leaves no positive-length clear transfer");const result=[pointAlongSamples(points,amount2/length)];let distance=0;for(let i=1;i<points.length;i++){distance+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);if(distance>amount2+1e-6&&distance<length-amount2-1e-6)result.push(points[i])}result.push(pointAlongSamples(points,1-amount2/length));return result}function parameters(options){identifier(options.id,"Routed transfer ID");identifier(options.source.id,"Routed transfer source");identifier(options.target.id,"Routed transfer target");if(options.source.id===options.target.id)throw new Error("Routed transfer source and target IDs must differ");bounds3(options.source.shape,"Routed transfer source");bounds3(options.target.shape,"Routed transfer target");bounds3(options.corridor,"Routed transfer corridor");const ids=new Set([options.source.id,options.target.id]);for(const obstacle of options.obstacles){identifier(obstacle.id,"Routed transfer obstacle");if(ids.has(obstacle.id))throw new Error(`Duplicate routed transfer object ID: ${obstacle.id}`);ids.add(obstacle.id);bounds3(obstacle.bounds,`Routed transfer obstacle ${obstacle.id}`)}const width=options.width??3,margin=options.margin??2;nonnegative3(width,"Routed transfer width");if(width===0)throw new Error("Routed transfer width must be positive");nonnegative3(margin,"Routed transfer margin");if(options.progress!==void 0)finite3(options.progress,"Routed transfer progress");if(options.marker&&options.progress===void 0)throw new Error("Routed transfer marker requires progress");const radius=options.marker?.radius??7,strokeWidth=options.marker?.strokeWidth??3;nonnegative3(radius,"Routed transfer marker radius");if(radius===0)throw new Error("Routed transfer marker radius must be positive");nonnegative3(strokeWidth,"Routed transfer marker stroke width");const markerInk=options.progress===void 0?0:radius+(options.marker?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerInk)+margin;const opacity=Math.min(alpha2(options.source.opacity),alpha2(options.target.opacity),alpha2(options.opacity??1));return{width,margin,radius,strokeWidth,clearance,opacity}}function planTeachingRoutedTransfer(options){const{clearance}=parameters(options);const fail=reason=>{throw new Error(`Cannot route transfer ${options.id} (${options.source.id} \u2192 ${options.target.id}): ${reason}`)};const guard=clearance+.01,corridor=options.corridor;if(corridor.width<=2*guard||corridor.height<=2*guard)fail("corridor is too small for the requested ink clearance");const origin={x:corridor.x+guard,y:corridor.y+guard};const toLocal=shape2=>{const x=shape2.x-origin.x,y=shape2.y-origin.y;finite3(x,"Routed transfer local x");finite3(y,"Routed transfer local y");return{x:Number(x.toFixed(6)),y:Number(y.toFixed(6)),width:shape2.width,height:shape2.height}};const endpoints=[options.source,options.target];const nodes=endpoints.map(endpoint=>{const b=toLocal(endpoint.shape);return{id:endpoint.id,cx:b.x+b.width/2,cy:b.y+b.height/2,width:b.width,height:b.height}});const obstacles=options.obstacles.map(obstacle=>expanded(toLocal(obstacle.bounds),0));const result=routeOrthogonalGraph(nodes,[{from:options.source.id,to:options.target.id,fromSide:options.source.side,toSide:options.target.side}],corridor.width-2*guard,corridor.height-2*guard,guard,14,obstacles);const raw=result.routes.get(0);if(!raw)return fail(result.failures[0]?.reason??"no legal route was returned");const points=(()=>{try{return trimLeads(raw,guard).map(point=>({x:point.x+origin.x,y:point.y+origin.y}))}catch(error){return fail(error instanceof Error?error.message:String(error))}})();const occupied=[...endpoints.map(endpoint=>expanded(endpoint.shape,clearance)),...options.obstacles.map(obstacle=>expanded(obstacle.bounds,clearance))];for(const point of points){if(point.x<corridor.x+clearance||point.x>corridor.x+corridor.width-clearance||point.y<corridor.y+clearance||point.y>corridor.y+corridor.height-clearance)fail("route ink leaves the permitted corridor")}for(let i=1;i<points.length;i++){if(occupied.some(obstacle=>routingSegmentBlocked(points[i-1],points[i],obstacle)))fail("a complete route segment violates object clearance")}const immutable=Object.freeze(points.map(point=>Object.freeze(point)));return{id:options.id,source:options.source,target:options.target,points:immutable,length:lengthOf(immutable),clearance,positionAt(progress){finite3(progress,"Routed transfer progress");return pointAlongSamples(immutable,Math.max(0,Math.min(1,progress)))}}}function createTeachingRoutedTransfer(painter){return options=>{const{width,radius,strokeWidth,opacity}=parameters(options);if(opacity===0)return null;const route=planTeachingRoutedTransfer(options),color=options.color??"#63DEEC";const paint=()=>painter.opacity(opacity,()=>{painter.path(route.points,{id:`${options.id}:route`,color,width});if(options.progress!==void 0&&options.progress>0&&options.progress<1){const point=route.positionAt(options.progress);painter.circle(point.x,point.y,radius,options.marker?.fill??color,options.marker?.stroke,strokeWidth)}});if(painter.target)painter.target(options.focusTarget??options.id,paint);else paint();return route}}function compareByteSequences(before,after){if(!(before instanceof Uint8Array)||!(after instanceof Uint8Array)){throw new Error("Byte comparison requires two Uint8Arrays")}const left=Array.from(before),right=Array.from(after);let commonPrefix=0,commonSuffix=0;while(commonPrefix<Math.min(left.length,right.length)&&left[commonPrefix]===right[commonPrefix])commonPrefix++;while(commonSuffix<Math.min(left.length,right.length)-commonPrefix&&left[left.length-commonSuffix-1]===right[right.length-commonSuffix-1])commonSuffix++;const columns=[];const add2=(oldOffset,newOffset)=>{const oldByte=oldOffset===null?null:{offset:oldOffset,value:left[oldOffset]};const newByte=newOffset===null?null:{offset:newOffset,value:right[newOffset]};const kind=!oldByte?"insert":!newByte?"delete":oldByte.value===newByte.value?"equal":"replace";columns.push({id:`before:${oldOffset??"none"}|after:${newOffset??"none"}`,kind,before:oldByte,after:newByte})};for(let offset=0;offset<commonPrefix;offset++)add2(offset,offset);const leftMiddle=left.length-commonPrefix-commonSuffix;const rightMiddle=right.length-commonPrefix-commonSuffix;for(let offset=0;offset<Math.max(leftMiddle,rightMiddle);offset++){add2(offset<leftMiddle?commonPrefix+offset:null,offset<rightMiddle?commonPrefix+offset:null)}for(let offset=0;offset<commonSuffix;offset++){add2(left.length-commonSuffix+offset,right.length-commonSuffix+offset)}return{algorithm:"common-prefix/suffix with positional middle",beforeLength:left.length,afterLength:right.length,commonPrefix,commonSuffix,equal:left.length===right.length&&commonPrefix===left.length,columns}}function escapedByte(value){if(!Number.isInteger(value)||value<0||value>255)throw new Error("A byte must be an integer from 0 through 255");if(value===0)return"\\0";if(value===9)return"\\t";if(value===10)return"\\n";if(value===13)return"\\r";if(value===32)return"space";if(value===92)return"\\\\";if(value>=33&&value<=126)return String.fromCharCode(value);return`\\x${value.toString(16).padStart(2,"0").toUpperCase()}`}function byteDifferenceState(options){if(!Number.isFinite(options.scanProgress))throw new Error("Byte scan progress must be finite");const comparison=compareByteSequences(options.before,options.after);const progress=Math.max(0,Math.min(1,options.scanProgress));const scannedColumns=Math.floor(progress*comparison.columns.length);return{comparison,progress,scannedColumns,scanComplete:progress===1,verdict:options.revealVerdict?comparison.equal?"equal":"different":null}}function layoutByteDifference(options){const{x,y,width,height,fontSize=28,maxColumns=10}=options;if(![x,y,width,height,fontSize,x+width,y+height].every(Number.isFinite)||width<=0||height<=0||fontSize<=0){throw new Error("Byte strip bounds and font size must be finite with positive dimensions")}if(fontSize<24)throw new Error("Byte strip font size must be at least 24 px for checked label padding");if(!Number.isSafeInteger(maxColumns)||maxColumns<1)throw new Error("Byte window size must be a positive safe integer");const state=byteDifferenceState(options),all=state.comparison.columns;const start=options.startColumn??Math.max(0,state.comparison.commonPrefix-2);if(!Number.isSafeInteger(start)||start<0||start>all.length||all.length>0&&start===all.length){throw new Error("Byte window start is outside the alignment")}const columns=all.slice(start,start+maxColumns),count=Math.max(1,columns.length);const gutter=fontSize*5.2,cellWidth=(width-gutter)/count;const longest=Math.max(5,...columns.flatMap(column=>[column.before,column.after].map(byte=>byte?String(byte.offset).length+1:5)));if(cellWidth<fontSize*.65*longest+12||height<fontSize*10){throw new Error("Byte strip cannot fit its byte labels and offsets")}const headerHeight=fontSize*1.7,footerHeight=fontSize*1.7,rowHeight=(height-headerHeight-footerHeight)/2;if(cellWidth<=4||rowHeight<=4||gutter-8<=8||headerHeight<=8||footerHeight<=8||rowHeight*.3<=8){throw new Error("Byte strip cannot fit positive cell insets and checked label padding")}const cells=columns.map((column,index)=>({column,alignmentIndex:start+index,beforeBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight,width:cellWidth,height:rowHeight},afterBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight+rowHeight,width:cellWidth,height:rowHeight}}));return{...state,bounds:{x,y,width,height},cells,gutter,headerHeight,footerHeight,rowHeight,omittedLeading:start,omittedTrailing:all.length-start-columns.length}}function createTeachingByteDifference(painter){return options=>{const layout=layoutByteDifference(options);const{x,y,width,height,fontSize=28,fill="#101820",stroke="#516376",textColor="#E9EFFF",mutedColor="#91A3B8",scanColor="#63DEEC",changeColor="#F4D477",beforeLabel="Before",afterLabel="After"}=options;const label=(value,bounds4,size,color=textColor)=>painter.labelScope(bounds4,()=>{painter.text(value,bounds4.x+bounds4.width/2,bounds4.y+bounds4.height/2+size*.34,size,color,"center","mono")},{padding:4});painter.container(layout.bounds,()=>{label("Prefix/suffix alignment; positional middle; not minimum edits",{x,y,width,height:layout.headerHeight},fontSize*.63,mutedColor);for(const[row,name]of[beforeLabel,afterLabel].entries()){label(name,{x,y:y+layout.headerHeight+row*layout.rowHeight,width:layout.gutter-8,height:layout.rowHeight},fontSize*.72)}for(const cell of layout.cells){const visited=cell.alignmentIndex<layout.scannedColumns;const color=visited?cell.column.kind==="equal"?mutedColor:changeColor:stroke;for(const[byte,bounds4]of[[cell.column.before,cell.beforeBounds],[cell.column.after,cell.afterBounds]]){painter.rect(bounds4.x+2,bounds4.y+2,bounds4.width-4,bounds4.height-4,fill,color,0);label(byte?`@${byte.offset}`:"none",{...bounds4,height:bounds4.height*.3},fontSize*.65,mutedColor);label(byte?byte.value.toString(16).padStart(2,"0").toUpperCase():"--",{...bounds4,y:bounds4.y+bounds4.height*.3,height:bounds4.height*.35},fontSize,visited?textColor:mutedColor);label(byte?escapedByte(byte.value):"no byte",{...bounds4,y:bounds4.y+bounds4.height*.65,height:bounds4.height*.35},fontSize*.7,mutedColor)}}if(!layout.cells.length){for(const row of[0,1])label("empty",{x:x+layout.gutter,y:y+layout.headerHeight+row*layout.rowHeight,width:width-layout.gutter,height:layout.rowHeight},fontSize,mutedColor)}const scanPosition=layout.progress*layout.comparison.columns.length-layout.omittedLeading;if(layout.cells.length&&scanPosition>=0&&scanPosition<=layout.cells.length){const cellWidth=layout.cells[0].beforeBounds.width;const cursor=Math.max(1,Math.min(width-layout.gutter-1,scanPosition*cellWidth));painter.rect(x+layout.gutter+cursor-1,y+layout.headerHeight-7,2,5,scanColor,void 0,0)}const verdict=layout.verdict===null?"Verdict held":layout.verdict==="equal"?"Bytes equal":"Bytes differ";label(`${layout.omittedLeading} columns before window; ${layout.omittedTrailing} after \xB7 ${verdict}`,{x,y:y+height-layout.footerHeight,width,height:layout.footerHeight},fontSize*.66,layout.verdict===null?mutedColor:textColor)},{padding:0});return layout}}function tokens(input,name){if(!Array.isArray(input))throw new Error(`Token history ${name} must be an array`);return Object.freeze(input.map(item=>{if(!item||typeof item.id!=="string"||!item.id.trim()||item.id!==item.id.trim()){throw new Error("Token occurrence IDs must be nonempty without surrounding whitespace")}if(!(typeof item.token==="string"&&item.token.trim())&&!(typeof item.token==="number"&&Number.isSafeInteger(item.token)&&item.token>=0)){throw new Error("History tokens require nonempty text or a nonnegative safe integer vocabulary ID")}return Object.freeze({id:item.id,token:item.token})}))}function equal(left,right){return left.id===right.id&&left.token===right.token}function prefix(part,whole,name){if(part.length>whole.length||part.some((token,index)=>!equal(token,whole[index]))){throw new Error(`Token history ${name} must preserve the exact ordered occurrence prefix`)}}function tokenHistoryState(options){const prompt=tokens(options.prompt,"prompt"),accepted=tokens(options.accepted,"accepted");const processed=tokens(options.processed,"processed"),emitted=tokens(options.emitted,"emitted");const history=Object.freeze([...prompt,...accepted]);if(new Set(history.map(token=>token.id)).size!==history.length){throw new Error("Token history requires distinct occurrence IDs, including repeated vocabulary tokens")}prefix(processed,history,"processed");prefix(emitted,accepted,"emitted");if(accepted.length&&processed.length<prompt.length)throw new Error("Accepted output requires the complete processed prompt");if(accepted.length&&processed.length<prompt.length+accepted.length-1){throw new Error("Ordinary decoding permits at most one accepted token awaiting processing")}const phase=options.phase??"resident";if(!["resident","dropped","replay"].includes(phase))throw new Error("Unknown token history phase");if(phase==="replay"&&options.replayProgress===void 0)throw new Error("Replay requires explicit progress");const replayProgress=options.replayProgress??0;if(!Number.isFinite(replayProgress)||replayProgress<0||replayProgress>1){throw new Error("Replay progress must be finite between zero and one")}const position2=replayProgress*processed.length;const completed=phase==="resident"?processed.length:phase==="dropped"?0:Math.floor(position2);const fraction=position2-Math.floor(position2);const moving=phase==="replay"&&fraction>0&&completed<processed.length?Object.freeze({token:processed[completed],position:completed,progress:fraction}):null;return Object.freeze({prompt,accepted,processed,emitted,history,phase,replayProgress,kv:Object.freeze(processed.slice(0,completed)),pendingAccepted:Object.freeze(accepted.filter((_,index)=>prompt.length+index>=processed.length)),moving})}function assertTokenHistoryTransition(before,after){before=tokenHistoryState(before);after=tokenHistoryState(after);prefix(before.prompt,after.prompt,"prompt transition");if(before.prompt.length!==after.prompt.length)throw new Error("A request prompt cannot change during its history");prefix(before.accepted,after.accepted,"accepted transition");prefix(before.emitted,after.emitted,"emitted transition");if(before.phase!=="resident"||after.phase!=="resident"){if(before.accepted.length!==after.accepted.length||before.emitted.length!==after.emitted.length){throw new Error("Drop and replay transitions cannot sample or emit new output")}prefix(before.processed,after.processed,"replay target");if(before.processed.length!==after.processed.length)throw new Error("Replay must rebuild the retained processed prefix")}else if(after.processed.length<before.processed.length){throw new Error("Resident processed history cannot shrink without an explicit drop or replay")}}function createTeachingTokenHistory(painter){return options=>{const state=tokenHistoryState(options);const{x,y,width,height,fontSize=28,gap=8,labelWidth=245,focusPrefix}=options;if(![x,y,x+width,y+height,width,height,fontSize,gap,labelWidth].every(Number.isFinite)||width<=0||height<=0||fontSize<=0||gap<0||labelWidth<=0){throw new Error("Token history drawing bounds and sizes must be finite and positive")}const columns=Math.max(1,state.history.length),top=fontSize*1.9,bottom=fontSize*2;const cellWidth=(width-labelWidth-gap*(columns-1)-4)/columns;const laneHeight=(height-top-bottom)/5,cellHeight=laneHeight-gap;if(cellWidth<fontSize*2.2||cellHeight<fontSize*1.6||labelWidth<fontSize*5){throw new Error("Token history bounds must fit its occurrence columns and five readable lanes")}const color={prompt:"#7FA7FF",accepted:"#92E28C",processed:"#63DEEC",kv:"#63DEEC",emitted:"#92E28C",pending:"#FFD75E",empty:"#586278",text:"#F2EFE6",fill:"#141820",...options.colors};const lanes=[{id:"prompt",label:"Prompt",tokens:state.prompt,offset:0},{id:"accepted",label:"Accepted output",tokens:state.accepted,offset:state.prompt.length},{id:"processed",label:"Processed prefix",tokens:state.processed,offset:0},{id:"kv",label:"Resident KV",tokens:state.kv,offset:0},{id:"emitted",label:"Already delivered",tokens:state.emitted,offset:state.prompt.length}];const pending2=new Set(state.pendingAccepted.map(token=>token.id));const bounds4={x,y,width,height};const target=(id,draw2)=>{if(id&&painter.target)painter.target(id,draw2);else draw2()};const cell=(position2,row)=>({x:x+labelWidth+1+position2*(cellWidth+gap),y:y+top+row*laneHeight,width:cellWidth,height:cellHeight});const paintToken=(token,shape2,stroke,fill=color.fill)=>{painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,fill,stroke,7);painter.labelScope(shape2,()=>painter.text(String(token.token),shape2.x+shape2.width/2,shape2.y+shape2.height/2+fontSize*.34,fontSize,color.text,"center","mono"),{padding:5})};painter.container(bounds4,()=>{for(let position2=0;position2<state.history.length;position2+=1){const shape2=cell(position2,0);painter.labelScope({...shape2,y,height:top},()=>painter.text(`position ${position2}`,shape2.x+shape2.width/2,y+fontSize,fontSize*.7,color.empty,"center"),{padding:3})}lanes.forEach((lane,row)=>target(focusPrefix?`${focusPrefix}-${lane.id}`:void 0,()=>{const labelBounds={x,y:y+top+row*laneHeight,width:labelWidth-gap,height:cellHeight};painter.labelScope(labelBounds,()=>painter.text(lane.label,x+5,labelBounds.y+cellHeight/2+fontSize*.34,fontSize*.82,color[lane.id]),{padding:3});for(let position2=0;position2<columns;position2+=1){const shape2=cell(position2,row),token=lane.tokens[position2-lane.offset];if(token){const isPending=lane.id==="accepted"&&pending2.has(token.id);target(isPending&&focusPrefix?`${focusPrefix}-pending`:void 0,()=>paintToken(token,shape2,isPending?color.pending:color[lane.id],lane.id==="processed"?"transparent":color.fill))}else painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,"transparent",color.empty,7)}}));if(state.moving){const from=cell(state.moving.position,2),to2=cell(state.moving.position,3);const progress=state.moving.progress;const settle=Math.max(0,(progress-.65)/.35);const grow2=Math.max(0,(progress-.8)/.2);const measuredWidth=painter.measureText?.(String(state.moving.token.token),fontSize,"mono");if(measuredWidth!==void 0&&(!Number.isFinite(measuredWidth)||measuredWidth<0)){throw new Error("Token history measured text width must be finite and nonnegative")}const copyWidth=Math.min(from.width,Math.max(fontSize*3,measuredWidth===void 0?from.width:measuredWidth+10));const copyHeight=Math.min(from.height,fontSize*1.8);const movingWidth=copyWidth+(from.width-copyWidth)*grow2;const movingHeight=copyHeight+(from.height-copyHeight)*grow2;const startInset=Math.min(7,from.width-copyWidth);const startCenterX=from.x+startInset+copyWidth/2;const centerX=startCenterX+(from.x+from.width/2-startCenterX)*settle;const centerY=from.y+from.height/2+(to2.y-from.y)*progress;const moving={x:centerX-movingWidth/2,y:centerY-movingHeight/2,width:movingWidth,height:movingHeight};target(focusPrefix?`${focusPrefix}-replay`:void 0,()=>paintToken(state.moving.token,moving,color.kv))}const pendingText=state.pendingAccepted.map(token=>String(token.token)).join(", ");const message=state.phase==="replay"?"Replay rebuilds KV; no sampling or delivery":state.phase==="dropped"?"KV released; accepted and delivered history retained":pendingText?`Accepted but unprocessed: ${pendingText}`:"All accepted positions are processed";painter.labelScope({x,y:y+height-bottom,width,height:bottom},()=>painter.text(message,x+width/2,y+height-fontSize*.6,fontSize*.82,state.phase==="replay"?color.kv:color.pending,"center"),{padding:3})},{padding:0});return state}}var INK="#8D9CB9";var ACCENT="#63DEEC";var PANEL="#18283B";function finite4(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function positive4(value,name){finite4(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function boundsOf(options){finite4(options.x,"Teaching x");finite4(options.y,"Teaching y");positive4(options.width,"Teaching width");positive4(options.height,"Teaching height");return{x:options.x,y:options.y,width:options.width,height:options.height}}function amount(value,name="Teaching progress"){finite4(value,name);return Math.max(0,Math.min(1,value))}function domainOf(domain,name){finite4(domain[0],`${name} start`);finite4(domain[1],`${name} end`);if(domain[1]<=domain[0]||!Number.isFinite(domain[1]-domain[0])){throw new Error(`${name} must have a finite positive span`)}return[domain[0],domain[1]]}function createTeachingCanvas(painter){const components=createCanvasComponents(painter);function axes2(options){let bounds4=boundsOf(options);const xDomain=domainOf(options.xDomain,"Plot x domain");const yDomain=domainOf(options.yDomain,"Plot y domain");if(options.equalUnits){const xSpan=xDomain[1]-xDomain[0];const ySpan=yDomain[1]-yDomain[0];const pixelsPerUnit=Math.min(bounds4.width/xSpan,bounds4.height/ySpan);const width2=xSpan*pixelsPerUnit;const height2=ySpan*pixelsPerUnit;bounds4=boundsOf({x:bounds4.x+(bounds4.width-width2)/2,y:bounds4.y+(bounds4.height-height2)/2,width:width2,height:height2})}const{x,y,width,height}=bounds4;const{color=INK,gridColor,fontSize=28,xTicks=[],yTicks=[],formatX=String,formatY=String}=options;positive4(fontSize,"Axis font size");xTicks.forEach(tick=>finite4(tick,"Axis x tick"));yTicks.forEach(tick=>finite4(tick,"Axis y tick"));const plot={bounds:bounds4,xDomain,yDomain,point(px,py){finite4(px,"Plot point x");finite4(py,"Plot point y");const point={x:x+(px-xDomain[0])/(xDomain[1]-xDomain[0])*width,y:y+height-(py-yDomain[0])/(yDomain[1]-yDomain[0])*height};finite4(point.x,"Mapped point x");finite4(point.y,"Mapped point y");return point}};for(const tick of xTicks){if(tick<xDomain[0]||tick>xDomain[1])continue;const point=plot.point(tick,yDomain[0]);if(gridColor)painter.path([{x:point.x,y},{x:point.x,y:y+height}],{color:gridColor,width:1,clip:bounds4});painter.line(point.x,y+height,point.x,y+height+7,color,2);painter.text(formatX(tick),point.x,y+height+36,fontSize,color,"center")}for(const tick of yTicks){if(tick<yDomain[0]||tick>yDomain[1])continue;const point=plot.point(xDomain[0],tick);if(gridColor)painter.path([{x,y:point.y},{x:x+width,y:point.y}],{color:gridColor,width:1,clip:bounds4});painter.line(x-7,point.y,x,point.y,color,2);painter.text(formatY(tick),x-18,point.y+9,fontSize,color,"right")}painter.line(x,y+height,x+width,y+height,color,2);painter.line(x,y,x,y+height,color,2);if(options.xLabel)painter.text(options.xLabel,x+width/2,y+height+72,30,color,"center");if(options.yLabel)painter.text(options.yLabel,x,y-26,30,color,"left");return plot}function curve2(options){const{plot,points,color,width=4,progress=1}=options;positive4(width,"Curve width");const mapped=points.map(point=>plot.point(point.x,point.y));const visible=tracePolyline(mapped,progress);if(visible.length>1)painter.path(visible,{color,width,clip:plot.bounds});return visible}function scatter2(options){const{plot,points,color=ACCENT,radius=7,opacity=1}=options;positive4(radius,"Scatter radius");const alpha3=amount(opacity,"Scatter opacity");const projected=points.map(point=>{positive4(point.radius??radius,"Scatter point radius");return{...plot.point(point.x,point.y),radius:point.radius??radius,color:point.color??color,inDomain:point.x>=plot.xDomain[0]&&point.x<=plot.xDomain[1]&&point.y>=plot.yDomain[0]&&point.y<=plot.yDomain[1]}});const shapes=[];if(alpha3===0)return shapes;painter.opacity(alpha3,()=>{for(const point of projected){if(!point.inDomain)continue;shapes.push(painter.circle(point.x,point.y,point.radius,point.color))}});return shapes}function bars(options){const bounds4=boundsOf(options);const{x,y,width,height}=bounds4;const{values,labels,colors:colors2,color=ACCENT,progress=1,showValues=false,format=String,fontSize=28,gap=20}=options;positive4(fontSize,"Bar font size");finite4(gap,"Bar gap");if(gap<0)throw new Error("Bar gap must be nonnegative");values.forEach(value=>{finite4(value,"Bar value");if(value<0)throw new Error("Bar values must be nonnegative")});if(labels&&labels.length!==values.length)throw new Error("Bar labels must match values");if(colors2&&colors2.length!==values.length)throw new Error("Bar colors must match values");const maximumValue=values.reduce((maximum2,value)=>Math.max(maximum2,value),0);const maximum=options.max??(maximumValue||1);positive4(maximum,"Bar maximum");if(maximum<maximumValue)throw new Error("Bar maximum must contain every value");const reveal2=amount(progress);if(!values.length)return{bars:[],slots:[],bounds:bounds4};const barWidth=(width-gap*(values.length-1))/values.length;positive4(barWidth,"Bar width after gaps");const shapes=[];const slots=[];values.forEach((value,index)=>{const left=x+index*(barWidth+gap);const barHeight=value/maximum*height*reveal2;slots.push({x:left,y,width:barWidth,height});shapes.push(barHeight>0?painter.rect(left,y+height-barHeight,barWidth,barHeight,colors2?.[index]??color,void 0,Math.min(8,barWidth/2,barHeight/2)):null);if(labels)painter.text(labels[index],left+barWidth/2,y+height+38,fontSize,INK,"center");if(showValues&&reveal2>0)painter.text(format(value),left+barWidth/2,y+height-barHeight-14,fontSize,colors2?.[index]??color,"center")});return{bars:shapes,slots,bounds:bounds4}}function flowGraph(options){const{nodes,edges,stroke=ACCENT,fill=PANEL,textColor="#FFFFFF",padding=12}=options;finite4(padding,"Flow node padding");if(padding<0)throw new Error("Flow node padding must be nonnegative");const descriptors=Object.create(null);for(const node of nodes){if(!node.id||Object.hasOwn(descriptors,node.id))throw new Error("Flow node IDs must be nonempty and unique");const bounds4=boundsOf(node);positive4(node.fontSize??30,"Flow node font size");finite4(node.radius??14,"Flow node radius");if((node.radius??14)<0)throw new Error("Flow node radius must be nonnegative");descriptors[node.id]={...bounds4,radius:node.radius??14}}for(const edge of edges){if(!Object.hasOwn(descriptors,edge.from)||!Object.hasOwn(descriptors,edge.to))throw new Error("Flow edge must reference existing nodes");if(edge.from===edge.to)throw new Error("Flow edges must connect distinct nodes");if(edge.progress!==void 0)amount(edge.progress);if(edge.width!==void 0)positive4(edge.width,"Flow edge width");for(const gap of[edge.gap,edge.fromGap,edge.toGap]){if(gap!==void 0)finite4(gap,"Flow edge gap")}}const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const routes=edges.map(edge=>target(edge.focusTarget,()=>{const{from,to:to2,progress,focusTarget:_focusTarget,...style}=edge;const route=painter.connect(descriptors[from],descriptors[to2],{color:stroke,...style});if(progress!==void 0)components.particle({points:[route.from,route.to],progress,radius:7,fill:style.color??stroke});return route}));for(const node of nodes){const shape2=target(node.focusTarget,()=>components.card({...descriptors[node.id],label:node.label,id:node.id,fill:node.fill??fill,stroke:node.color??stroke,textColor,fontSize:node.fontSize??30,padding}));Object.assign(descriptors[node.id],shape2)}return{nodes:descriptors,routes}}return{axes:axes2,curve:curve2,scatter:scatter2,bars,flowGraph,transfer:createTeachingTransfer(painter),routedTransfer:createTeachingRoutedTransfer(painter),grid:createTeachingGrid(painter),timeline:createTeachingTimeline(painter),allocation:createTeachingAllocation(painter),vectorAccumulation:createTeachingVectorAccumulation(painter),categoricalSampling:createTeachingCategoricalSampling(painter),byteDifference:createTeachingByteDifference(painter),tokenHistory:createTeachingTokenHistory(painter),...createTeachingValueChange(painter),...createTeachingFocus(painter)}}function position(beat,progress){if(!Number.isSafeInteger(beat)||beat<0)throw new Error("Cue beat must be a nonnegative safe integer");if(!Number.isFinite(progress)||progress<0||progress>1)throw new Error("Cue progress must be between zero and one");if(progress===1){if(!Number.isSafeInteger(beat+1))throw new Error("Cue position exceeds the safe integer range");return{beat:beat+1,beatP:0}}return{beat,beatP:progress}}function compare(left,right){return left.beat===right.beat?left.beatP-right.beatP:left.beat-right.beat}function createCueTrack(options){const ids=new Set;const entry=({id,snapshot})=>{if(typeof id!=="string"||!id.trim()||ids.has(id))throw new Error("Cue IDs must be nonempty and unique");ids.add(id);return Object.freeze({id,snapshot})};const initial=entry(options.initial);const cues=options.cues.map(cue=>({position:position(cue.beat,cue.at),value:entry(cue)}));for(let index=1;index<cues.length;index+=1){if(compare(cues[index-1].position,cues[index].position)>=0){throw new Error("Cue positions must be strictly increasing")}}return Object.freeze({sample(current){const at=position(current.beat,current.beatP);let low=0,high=cues.length;while(low<high){const middle=Math.floor((low+high)/2);if(compare(cues[middle].position,at)<=0)low=middle+1;else high=middle}return low===0?initial:cues[low-1].value}})}function clampProgress2(progress){if(!Number.isFinite(progress))throw new Error("Camera progress must be finite");return Math.max(0,Math.min(1,progress))}function assertCamera(camera,context){if(!Number.isFinite(camera.x)||!Number.isFinite(camera.y)){throw new Error(`${context} coordinates must be finite`)}if(!Number.isFinite(camera.zoom)||camera.zoom<=0){throw new Error(`${context} zoom must be finite and greater than zero`)}}function assertViewport(viewport){if(!Number.isFinite(viewport.width)||viewport.width<=0){throw new Error("Camera viewport width must be finite and greater than zero")}if(!Number.isFinite(viewport.height)||viewport.height<=0){throw new Error("Camera viewport height must be finite and greater than zero")}}function assertZoomConstraints(options){const{minZoom,maxZoom}=options;if(minZoom!==void 0&&(!Number.isFinite(minZoom)||minZoom<=0)){throw new Error("Camera minZoom must be finite and greater than zero")}if(maxZoom!==void 0&&(!Number.isFinite(maxZoom)||maxZoom<=0)){throw new Error("Camera maxZoom must be finite and greater than zero")}if(minZoom!==void 0&&maxZoom!==void 0&&minZoom>maxZoom){throw new Error("Camera minZoom cannot exceed maxZoom")}}function assertZoomInRange(camera,options){if(options.minZoom!==void 0&&camera.zoom<options.minZoom||options.maxZoom!==void 0&&camera.zoom>options.maxZoom){throw new Error("Camera zoom is outside the configured range")}}function interpolateLinear(from,to2,progress){return from*(1-progress)+to2*progress}function interpolateCamera(from,to2,progress,options={}){assertCamera(from,"Camera start");assertCamera(to2,"Camera end");assertZoomConstraints(options);assertZoomInRange(from,options);assertZoomInRange(to2,options);const amount2=clampProgress2(progress);if(amount2===0)return{...from};if(amount2===1)return{...to2};const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Camera easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return{...from};if(t===1)return{...to2};const camera={x:interpolateLinear(from.x,to2.x,t),y:interpolateLinear(from.y,to2.y,t),zoom:Math.exp(Math.log(from.zoom)*(1-t)+Math.log(to2.zoom)*t)};assertCamera(camera,"Camera result");assertZoomInRange(camera,options);return camera}function cameraSvgTransform(camera,viewport){assertCamera(camera,"Camera");assertViewport(viewport);return`translate(${viewport.width/2} ${viewport.height/2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`}function projectWorldPoint(point,camera,viewport){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error("World point coordinates must be finite")}assertCamera(camera,"Camera");assertViewport(viewport);const projected={x:viewport.width/2+(point.x-camera.x)*camera.zoom,y:viewport.height/2+(point.y-camera.y)*camera.zoom};if(!Number.isFinite(projected.x)||!Number.isFinite(projected.y)){throw new Error("Projected world point coordinates must be finite")}return projected}var DEFAULT_MORPH_SAMPLES=64;var MAX_MORPH_SAMPLES=4096;function clampProgress3(progress){if(!Number.isFinite(progress))throw new Error("Polyline morph progress must be finite");return Math.max(0,Math.min(1,progress))}function validatePolyline(points,context){if(!Array.isArray(points)||points.length===0){throw new Error(`${context} polyline must be a non-empty array`)}for(let index=0;index<points.length;index+=1){const point=points[index];if(!point||!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} point ${index} coordinates must be finite`)}}}function validateSamples(samples){if(!Number.isInteger(samples)||samples<2){throw new Error("Polyline morph samples must be an integer of at least 2")}if(samples>MAX_MORPH_SAMPLES){throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`)}}function resamplePolyline(points,samples){const lengths=points.slice(1).map((point,index)=>Math.hypot(point.x-points[index].x,point.y-points[index].y));const total=lengths.reduce((sum,length)=>sum+length,0);if(!Number.isFinite(total))throw new Error("Polyline morph arc length must be finite");if(total===0)return Array.from({length:samples},()=>({...points[0]}));let segment=0;let offset=0;return Array.from({length:samples},(_,index)=>{if(index===samples-1)return{...points[points.length-1]};const distance=total*(index/(samples-1));while(segment<lengths.length-1&&(lengths[segment]===0||distance>offset+lengths[segment])){offset+=lengths[segment++]}const t=(distance-offset)/lengths[segment];const from=points[segment],to2=points[segment+1];return{x:from.x*(1-t)+to2.x*t,y:from.y*(1-t)+to2.y*t}})}function createPolylineMorph(from,to2,options={}){validatePolyline(from,"Start");validatePolyline(to2,"End");const samples=options.samples??DEFAULT_MORPH_SAMPLES;validateSamples(samples);const startSamples=resamplePolyline(from,samples);const endSamples=resamplePolyline(to2,samples);const easing=options.easing??smoothstep;return progress=>{const amount2=clampProgress3(progress);const eased=amount2===0||amount2===1?amount2:easing(amount2);if(!Number.isFinite(eased))throw new Error("Polyline morph easing must return a finite number");const t=Math.max(0,Math.min(1,eased));return startSamples.map((start,index)=>{const end=endSamples[index];return{x:start.x*(1-t)+end.x*t,y:start.y*(1-t)+end.y*t}})}}function morphPolyline(from,to2,progress,options={}){return createPolylineMorph(from,to2,options)(progress)}function graphImportResult(source,graph2,diagnostics){if(graph2.nodes.length===0&&diagnostics.every(({severity})=>severity!=="error")){diagnostics.push({code:"import.empty",severity:"error",message:"The source contains no graph nodes to import.",line:1,column:1,excerpt:""})}const ok=diagnostics.every(({severity})=>severity!=="error");return ok?{source,ok,graph:graph2,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line2,code,severity,message,column=1){diagnostics.push({code,severity,message,line:line2,column,excerpt:(sourceLines[line2-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line2,index){while(index<line2.length&&/\s/.test(line2[index]??""))index++;return index}function readDelimited(line2,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line2.length;index++){const character=line2[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line2.startsWith(close,index)){return{value:line2.slice(start,index),next:index+close.length}}}return void 0}function decodeLabel(raw){const value=raw.trim();if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}function labelHasUnsupportedMarkup(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label)}function readEndpoint(line2,from){let index=skipWhitespace(line2,from);const id=line2.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line2,index);if(afterId>=line2.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line2.slice(afterId);const delimiters=[{open:"[(",close:")]",lossy:true},{open:"([",close:"])",lossy:true},{open:"((",close:"))",lossy:true},{open:"{{",close:"}}",lossy:true},{open:"[",close:"]",lossy:false},{open:"(",close:")",lossy:true},{open:"{",close:"}",lossy:true}];const delimiter=delimiters.find(({open})=>rest.startsWith(open));if(!delimiter)return{id,label:id,shape:"rectangle",next:index};const content=readDelimited(line2,afterId+delimiter.open.length,delimiter.close);if(!content)return void 0;const label=decodeLabel(content.value);if(label===void 0)return void 0;return{id,label,shape:delimiter.lossy?"lossy":"rectangle",next:content.next}}function addNode(state,endpoint,groupId,line2,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint.id)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint.label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint.label}else{state.nodeIndexes.set(endpoint.id,state.nodes.length);state.nodes.push({id:endpoint.id,label:endpoint.label,...groupId?{group:groupId}:{}})}if(endpoint.shape==="lossy"&&!state.warnedShapes.has(endpoint.id)){state.warnedShapes.add(endpoint.id);addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line2,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line2,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line2,first.next);const hasConnector=CONNECTORS.some(connector2=>line2.startsWith(connector2,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line2,cursor);if(cursor>=line2.length)return;const connector2=CONNECTORS.find(candidate=>line2.startsWith(candidate,cursor));if(!connector2){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",cursor+1);return}cursor+=connector2.length;cursor=skipWhitespace(line2,cursor);let edgeLabel;if(line2[cursor]==="|"){const end=line2.indexOf("|",cursor+1);if(end<0){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid edge label is missing its closing |.",cursor+1);return}edgeLabel=line2.slice(cursor+1,end).trim();cursor=skipWhitespace(line2,end+1);if(labelHasUnsupportedMarkup(edgeLabel)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",cursor+1);return}}const next=readEndpoint(line2,cursor);if(!next){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid connection has no supported target node.",cursor+1);return}if(!addNode(state,next,groupId,lineNumber,sourceLines,diagnostics,false))return;const edge={from:previous.id,to:next.id,...edgeLabel!==void 0?{label:edgeLabel}:{},...connector2==="---"?{arrow:"none"}:connector2==="-.->"?{arrow:"forward",style:"dotted"}:{arrow:"forward"}};state.edges.push(edge);state.edgeReferences.push({id:previous.id,line:lineNumber},{id:next.id,line:lineNumber});previous=next;cursor=next.next}}function importMermaidGraph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const state={nodes:[],nodeIndexes:new Map,groups:[],groupIds:new Set,edges:[],edgeReferences:[],warnedShapes:new Set};let direction2="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(line2.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line2.startsWith("%%"))continue;if(!sawHeader){const header=line2.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);if(!header){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error",'Expected a Mermaid flowchart or graph header such as "flowchart LR".');sawHeader=true;continue}sawHeader=true;const sourceDirection=header[1]?.toUpperCase();direction2=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line2.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);if(subgraph){if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Nested Mermaid subgraphs are not imported.");continue}const id=subgraph[1];if(!id)continue;if(state.groupIds.has(id)||state.nodeIndexes.has(id)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph id "${id}" conflicts with an existing group or node.`);continue}const rawLabel=subgraph[2];const label=rawLabel===void 0?id:decodeLabel(rawLabel);if(label===void 0||labelHasUnsupportedMarkup(label)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);continue}currentGroup=id;state.groupIds.add(id);state.groups.push({id,label});continue}if(/^subgraph\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");continue}if(/^end\s*$/i.test(line2)){if(!currentGroup)addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid end has no matching subgraph.");else currentGroup=void 0;continue}if(/^direction\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,currentGroup?"import.unsupported_semantics":"import.parse_error","error",currentGroup?"Per-subgraph Mermaid direction cannot be represented by GraphDiagram.":"Set Mermaid graph direction in the flowchart or graph header.");continue}if(/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line2,currentGroup,lineNumber,sourceLines,state,diagnostics)}if(!sawHeader){addImportDiagnostic(diagnostics,sourceLines,1,"import.parse_error","error","Missing Mermaid flowchart or graph header.")}if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,sourceLines.length,"import.parse_error","error",`Mermaid subgraph "${currentGroup}" has no matching end.`)}for(const reference of state.edgeReferences){if(state.groupIds.has(reference.id)){addImportDiagnostic(diagnostics,sourceLines,reference.line,"import.unsupported_semantics","error",`Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`)}}const graph2={nodes:state.nodes,edges:state.edges,groups:state.groups,direction:direction2};return graphImportResult("mermaid",graph2,diagnostics)}function decodeD2Label(raw){const value=raw.trim();if(value.startsWith('"')){if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}if(value.startsWith("'")){if(!value.endsWith("'"))return void 0;return value.slice(1,-1).replace(/\\(['\\])/g,"$1")}return value}function hasMarkdownFormatting(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label)}function hasUnquotedHash(line2){let quote;let escaped=false;for(const character of line2){if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'")quote=character;else if(character==="#")return true}return false}function addNode2(nodes,id,label,line2,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`);return false}const existing=nodes.get(id);if(existing){if(explicitLabel){existing.node.label=label}}else{nodes.set(id,{node:{id,label}})}return true}function reportUnsupported(diagnostics,sourceLines,line2,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line2,code,"error",message,column)}function importD2Graph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const nodesById=new Map;const edges=[];const shapes=new Map;let direction2="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(containerDepth>0){const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,containerDepth+opens-closes);continue}if(line2.startsWith("#"))continue;if(hasUnquotedHash(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line2.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line2.includes("{")||line2.includes("}")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.","import.unsupported_semantics");const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,opens-closes);continue}const directionMatch=line2.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction2=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape2=decodeD2Label(shapeMatch[2]??"");if(!id||shape2===void 0||shape2===""){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 shape declaration needs a simple identifier and a shape value.","import.parse_error");continue}if(!nodesById.has(id))addNode2(nodesById,id,id,lineNumber,sourceLines,diagnostics,false);shapes.set(id,{value:shape2,line:lineNumber});continue}const edgeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);if(edgeMatch){const from=edgeMatch[1];const connector2=edgeMatch[2];const to2=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector2||!to2)continue;let label;if(rawLabel!==void 0){label=decodeD2Label(rawLabel);if(label===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection label has invalid quotes.","import.parse_error");continue}if(hasMarkdownFormatting(label)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.","import.unsupported_semantics");continue}}addNode2(nodesById,from,from,lineNumber,sourceLines,diagnostics,false);addNode2(nodesById,to2,to2,lineNumber,sourceLines,diagnostics,false);edges.push({from,to:to2,...label!==void 0?{label}:{},arrow:connector2==="<->"?"both":connector2==="<-"?"backward":connector2==="--"?"none":"forward"});continue}const nodeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);if(nodeMatch){const id=nodeMatch[1];const rawLabel=nodeMatch[2];if(!id)continue;let label=id;let explicitLabel=false;if(rawLabel!==void 0){const decoded=decodeD2Label(rawLabel);if(decoded===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,`D2 label for "${id}" has invalid quotes.`,"import.parse_error");continue}label=decoded;explicitLabel=true}addNode2(nodesById,id,label,lineNumber,sourceLines,diagnostics,explicitLabel);continue}if(line2.includes(".style")||line2.includes(".width")||line2.includes(".height")||line2.includes(".near")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 styling, sizing, and positioning fields are not imported.","import.unsupported_semantics")}else if(/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.")}else{reportUnsupported(diagnostics,sourceLines,lineNumber,"Could not parse this D2 statement in the supported subset.","import.parse_error")}}if(containerDepth>0){reportUnsupported(diagnostics,sourceLines,sourceLines.length,"D2 object-property block has no matching closing brace.","import.parse_error")}for(const[id,{value,line:line2}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`)}return graphImportResult("d2",{nodes:[...nodesById.values()].map(({node})=>node),edges,groups:[],direction:direction2},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage}from"async_hooks";import{tmpdir}from"os";import{join}from"path";import parseCssColor2 from"parse-css-color";import{Children,isValidElement}from"react";var CHECK_DIAGNOSTIC_CODES=["accessibility.low_contrast","api.unsupported_prop","asset.warning","frame.load_error","frame.unknown_preset","layout.auto_size","layout.connector_congestion","layout.connector_unroutable","layout.overflow","layout.text_overlap","layout.text_overflow","layout.whitespace_imbalance","readability.small_text","render.error","render.svg_context","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=8.5;var SVG_ONLY_ELEMENTS=new Set(["circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","symbol","text","textPath","tspan","use"]);function hslToRgb2(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/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=l-chroma/2;return channels.map(channel=>Math.round((channel+offset)*255))}function colorFromCss(value){if(typeof value!=="string")return void 0;const parsed=parseCssColor2(value);if(!parsed||parsed.values.length<3)return void 0;const[r,g,b]=parsed.type==="hsl"?hslToRgb2(parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0):[parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0];return{r,g,b,alpha:parsed.alpha}}function compositeOver(foreground,background){if(foreground.alpha>=1||!background)return foreground;const alpha3=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha3<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha3,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha3,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha3,alpha:alpha3}}function isUnresolvedColor(value){if(typeof value!=="string"||value.trim()===""||colorFromCss(value))return false;return!["inherit","initial","revert","unset"].includes(value.trim().toLowerCase())}function channelLuminance(value){const normalized=value/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4}function relativeLuminance(color){return .2126*channelLuminance(color.r)+.7152*channelLuminance(color.g)+.0722*channelLuminance(color.b)}function contrastRatio(foreground,background){const lighter=Math.max(relativeLuminance(foreground),relativeLuminance(background));const darker=Math.min(relativeLuminance(foreground),relativeLuminance(background));return(lighter+.05)/(darker+.05)}function numericFontWeight(value){if(typeof value==="number")return value;if(value==="bold")return 700;if(typeof value==="string"&&/^\d+$/.test(value))return Number(value);return void 0}function fontSizePixels(value,inherited){if(typeof value==="number")return value;if(typeof value!=="string")return inherited;const match=value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);if(!match?.[1])return inherited;const amount2=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount2*4/3;if(unit==="rem")return amount2*16;if(unit==="em")return amount2*(inherited??16);if(unit==="%")return amount2/100*(inherited??16);return amount2}function requiredContrast(context){const large=(context.fontSize??16)>=24||(context.fontSize??16)>=18.66&&(context.fontWeight??400)>=700;return large?3:4.5}function styleRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return value}function hasDirectText(children){return Children.toArray(children).some(child=>typeof child==="string"||typeof child==="number")}function elementId(props){const value=props.id??props["data-vizmatic-id"];return typeof value==="string"&&value.trim()!==""?value.trim():void 0}function resolveFunctionComponent(node,trustedComponents){if(!isValidElement(node)||typeof node.type!=="function"||trustedComponents.has(node.type))return void 0;const component=node.type;if(component.__vizmaticPrimitive)return void 0;if(component.prototype?.isReactComponent)return void 0;try{return component(node.props)}catch{return void 0}}function analyzeScene(element,theme,trustedComponents,rootBackground2,svgComponents){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path,namespace){if(visited++>=MAX_CONTRAST_NODES||!isValidElement(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path,namespace);return}const props=node.props;const svgShape=svgComponents?.shapes.get(node.type)??(svgComponents&&typeof node.type==="string"&&SVG_ONLY_ELEMENTS.has(node.type)?`<${node.type}>`:void 0);if(namespace==="html"&&svgShape){diagnostics.push({code:"render.svg_context",severity:"error",theme,message:`${svgShape} requires an <svg> ancestor at ${path}; its SVG geometry will not render in an HTML layout.`,suggestion:"Place the element inside a native <svg> or an SVG container such as AxisPlot.",elementId:elementId(props),location:{path}})}const childNamespace=typeof node.type==="string"?node.type==="svg"?"svg":node.type==="foreignObject"?"html":namespace:typeof node.type==="function"?svgComponents?.children.get(node.type):namespace;const style=typeof node.type==="string"?styleRecord(props.style):{};const backgroundImage=typeof style.backgroundImage==="string"?style.backgroundImage.trim().toLowerCase():"";const backgroundShorthand=typeof style.background==="string"?style.background.trim():"";const isBackgroundWrapper=typeof node.type==="function"&&(trustedComponents.has(node.type)||Boolean(node.type.__vizmaticPrimitive));const wrapperBackground=isBackgroundWrapper?props.background:void 0;const hasUnresolvedBackground=backgroundImage!==""&&backgroundImage!=="none"||isUnresolvedColor(style.backgroundColor)||backgroundShorthand!==""&&backgroundShorthand.toLowerCase()!=="none"&&!colorFromCss(backgroundShorthand)||isUnresolvedColor(wrapperBackground);const ownBackground=colorFromCss(style.backgroundColor)??colorFromCss(style.background)??colorFromCss(wrapperBackground);const baseBackground=path==="root"&&isBackgroundWrapper&&colorFromCss(wrapperBackground)?void 0:inherited.background;const background=hasUnresolvedBackground?void 0:ownBackground?compositeOver(ownBackground,baseBackground):baseBackground;const color=typeof style.color==="string"&&style.color.trim().toLowerCase()==="currentcolor"?inherited.color:isUnresolvedColor(style.color)?void 0:colorFromCss(style.color)??inherited.color;const fontSize=fontSizePixels(style.fontSize,inherited.fontSize);const fontWeight=numericFontWeight(style.fontWeight)??inherited.fontWeight;const context={background,color,fontSize,fontWeight};if(typeof node.type==="string"&&hasDirectText(props.children)&&color&&background!==void 0&&background.alpha>=1){const renderedColor=compositeOver(color,background);const ratio=contrastRatio(renderedColor,background);const required=requiredContrast(context);if(ratio<required){const rounded=Math.round(ratio*100)/100;const key=`${rounded}:${required}:${path}`;if(!seen.has(key)){seen.add(key);diagnostics.push({code:"accessibility.low_contrast",severity:"warning",theme,message:`Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,suggestion:"Use a stronger text or background color token.",elementId:elementId(props),location:{path}})}}}Children.forEach(props.children,(child,index)=>visit(child,context,`${path}.${index}`,childNamespace))}visit(element,{background:colorFromCss(rootBackground2)},"root","html");return diagnostics}function containsLayoutNode(parent,child){const epsilon=.5;return child.left>=parent.left-epsilon&&child.top>=parent.top-epsilon&&child.left+child.width<=parent.left+parent.width+epsilon&&child.top+child.height<=parent.top+parent.height+epsilon}function textUnits(text2){return Array.from(text2.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0)}function renderedTextNodes(nodes){const textNodes=[];const ancestors=[];for(const node of nodes){while(ancestors.length>0&&!containsLayoutNode(ancestors[ancestors.length-1].node,node)){ancestors.pop()}const inherited=ancestors[ancestors.length-1];const style=styleRecord(node.props.style);const fontSize=fontSizePixels(style.fontSize,inherited?.fontSize)??16;const textAlign=typeof style.textAlign==="string"?style.textAlign:inherited?.textAlign??"left";const text2=String(node.textContent??"").trim();if(text2&&typeof style.transform==="string"&&style.transform.includes("rotate"))continue;if(text2&&node.width>0&&node.height>0){const estimatedLines=Math.max(1,Math.round(node.height/Math.max(fontSize*1.5,1)));const paintHeight=Math.min(node.height,fontSize*.9+(estimatedLines-1)*fontSize*1.25);const unwrappedWidth=textUnits(text2)*fontSize*.56;const paintWidth=Math.min(node.width,unwrappedWidth);const horizontalInset=textAlign==="center"?(node.width-paintWidth)/2:textAlign==="right"||textAlign==="end"?node.width-paintWidth:0;textNodes.push({text:text2,elementId:elementId(node.props),left:node.left,top:node.top,width:node.width,height:node.height,paintLeft:node.left+horizontalInset,paintTop:node.top+(node.height-paintHeight)/2,paintWidth,paintHeight,fontSize})}else if(node.width>0&&node.height>0){ancestors.push({node,fontSize,textAlign})}}return textNodes}function textExcerpt(text2){const normalized=text2.replace(/\s+/g," ").trim();return normalized.length>40?`${normalized.slice(0,37)}...`:normalized}function meaningfulOverlap(a,b){const width=Math.min(a.paintLeft+a.paintWidth,b.paintLeft+b.paintWidth)-Math.max(a.paintLeft,b.paintLeft);const height=Math.min(a.paintTop+a.paintHeight,b.paintTop+b.paintHeight)-Math.max(a.paintTop,b.paintTop);if(width<2||height<2)return false;if(a.text===b.text&&a.left===b.left&&a.top===b.top&&a.width===b.width&&a.height===b.height)return false;const overlapArea=width*height;const smallerArea=Math.min(a.paintWidth*a.paintHeight,b.paintWidth*b.paintHeight);return overlapArea/smallerArea>=.08}function overlapCandidates(nodes){const cellSize=96;const buckets=new Map;const pairs=[];for(let index=0;index<nodes.length&&pairs.length<MAX_DIAGNOSTICS_PER_RULE;index+=1){const node=nodes[index];const minX=Math.floor(node.paintLeft/cellSize);const maxX=Math.floor((node.paintLeft+node.paintWidth)/cellSize);const minY=Math.floor(node.paintTop/cellSize);const maxY=Math.floor((node.paintTop+node.paintHeight)/cellSize);const candidates=new Set;for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const bucket=buckets.get(`${x}:${y}`);bucket?.forEach(candidate=>candidates.add(candidate))}}for(const candidate of candidates){if(meaningfulOverlap(nodes[candidate],node))pairs.push([nodes[candidate],node]);if(pairs.length>=MAX_DIAGNOSTICS_PER_RULE)break}for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const key=`${x}:${y}`;const bucket=buckets.get(key)??[];bucket.push(index);buckets.set(key,bucket)}}}return pairs}function analyzeRenderedLayout(nodes,theme){const diagnostics=[];const textNodes=renderedTextNodes(nodes);const seenSmallText=new Set;let smallTextCount=0;for(const node of textNodes){if(node.fontSize>=MIN_TEXT_SIZE)continue;const excerpt=textExcerpt(node.text);const key=`${excerpt}:${node.fontSize}`;if(seenSmallText.has(key))continue;seenSmallText.add(key);diagnostics.push({code:"readability.small_text",severity:"warning",theme,message:`Text "${excerpt}" renders at ${node.fontSize}px.`,suggestion:`Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,elementId:node.elementId,location:{x:node.left,y:node.top,width:node.width,height:node.height}});smallTextCount+=1;if(smallTextCount>=MAX_DIAGNOSTICS_PER_RULE)break}for(const[left,right]of overlapCandidates(textNodes)){diagnostics.push({code:"layout.text_overlap",severity:"warning",theme,message:`Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,suggestion:"Increase spacing or canvas size, shorten labels, or move one label.",elementId:left.elementId,relatedElementIds:right.elementId?[right.elementId]:void 0,location:{x:left.left,y:left.top,width:left.width,height:left.height}})}const maxDataNumber=attribute=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute];return typeof value==="number"?value:Number(value)||0}));for(const source of nodes.filter(node=>Number(node.props["data-vizmatic-unrouted-connectors"])>0)){const messages=JSON.parse(String(source.props["data-vizmatic-routing-failures"]));for(const message of messages.slice(0,MAX_DIAGNOSTICS_PER_RULE))diagnostics.push({code:"layout.connector_unroutable",severity:"error",theme,message,suggestion:"Increase canvas size or spacing, reduce routingClearance, or choose a different endpoint side or port.",elementId:elementId(source.props),location:{x:source.left,y:source.top,width:source.width,height:source.height}})}const connectorSource=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>Number(node.props["data-vizmatic-connector-crossing-budget"]??0));const connectorCrossings=connectorSource?Number(connectorSource.props["data-vizmatic-connector-crossings"]):0;if(connectorCrossings>0){const source=connectorSource;diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings} connector crossing${connectorCrossings===1?"":"s"} detected.`,suggestion:"Use automatic layout, change graph direction, or simplify the edge set.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const labelCollisions=maxDataNumber("data-vizmatic-connector-label-collisions");if(labelCollisions>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-collisions"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${labelCollisions} connector label collision${labelCollisions===1?"":"s"} detected.`,suggestion:"Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crossedLabels=maxDataNumber("data-vizmatic-connector-label-crossings");if(crossedLabels>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"info",theme,message:`${crossedLabels} connector${crossedLabels===1?" passes":"s pass"} behind a label or group title. The label masks it, but the line appears broken.`,suggestion:'Shorten or move the label, change graph direction, or route the connector with routing="orthogonal".',elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crowdedEndpoints=maxDataNumber("data-vizmatic-crowded-connector-endpoints");if(crowdedEndpoints>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-crowded-connector-endpoints"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${crowdedEndpoints} node${crowdedEndpoints===1?"":"s"} connect more than eight edges.`,suggestion:"Group related branches, add an intermediate hub, or change graph direction.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const parallelGroups=maxDataNumber("data-vizmatic-parallel-connector-groups");if(parallelGroups>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-parallel-connector-groups"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${parallelGroups} connector route${parallelGroups===1?"":"s"} contain parallel edges.`,suggestion:"Merge duplicate relationships, label one combined edge, or separate the routes.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}let overflowCount=0;const graphNodes=nodes.filter(node=>typeof node.props["data-vizmatic-graph-node-id"]==="string");for(const box of graphNodes){for(const text2 of nodes){if(overflowCount>=MAX_DIAGNOSTICS_PER_RULE)break;if(!String(text2.textContent??"").trim()||text2===box)continue;const startsInside=text2.left>=box.left-1&&text2.left<box.left+box.width&&text2.top>=box.top-1&&text2.top<box.top+box.height;if(!startsInside)continue;const spillsRight=text2.left+text2.width>box.left+box.width+1;const spillsDown=text2.top+text2.height>box.top+box.height+1;if(!spillsRight&&!spillsDown)continue;diagnostics.push({code:"layout.text_overflow",severity:"warning",theme,message:`Text "${textExcerpt(String(text2.textContent))}" spills out of node "${String(box.props["data-vizmatic-graph-node-id"])}".`,suggestion:"Omit the fixed node width and height so the node sizes to its content, or shorten the text.",elementId:elementId(box.props),location:{x:text2.left,y:text2.top,width:text2.width,height:text2.height}});overflowCount+=1;break}}let whitespaceCount=0;for(const container of nodes.filter(node=>node.props["data-vizmatic-layout-container"]==="panel")){const contentNodes=nodes.filter(node=>node.props["data-vizmatic-layout-content"]==="panel"&&node.width>0&&node.height>0&&node.left>=container.left&&node.top>=container.top&&node.left+node.width<=container.left+container.width&&node.top+node.height<=container.top+container.height);if(contentNodes.length===0)continue;const contentTop=Math.min(...contentNodes.map(node=>node.top));const contentBottom=Math.max(...contentNodes.map(node=>node.top+node.height));const topGutter=contentTop-container.top;const bottomGutter=container.top+container.height-contentBottom;const difference=Math.abs(bottomGutter-topGutter);if(difference<=48||difference/container.height<=.18)continue;const largerSide=bottomGutter>topGutter?"below":"above";const smallerSide=largerSide==="below"?"above":"below";diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,suggestion:"Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",elementId:elementId(container.props),location:{x:container.left,y:container.top,width:container.width,height:container.height}});whitespaceCount+=1;if(whitespaceCount>=MAX_DIAGNOSTICS_PER_RULE)break}return diagnostics}function analyzeWhitespaceBalance(bounds4,width,height,theme){const gutters={left:bounds4.x,right:width-bounds4.x-bounds4.width,top:bounds4.y,bottom:height-bounds4.y-bounds4.height};const diagnostics=[];const horizontalDifference=Math.abs(gutters.left-gutters.right);const verticalDifference=Math.abs(gutters.top-gutters.bottom);if(horizontalDifference>48&&horizontalDifference/width>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.height}})}if(verticalDifference>48&&verticalDifference/height>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.height}})}return diagnostics}function diagnosticFromMessage(message,severity,theme){if(/unknown preset/i.test(message)){return{code:"frame.unknown_preset",severity,theme,message,suggestion:'Use "default" or "engineering".'}}if(/unsupported prop|unknown prop|does not recognize (?:the )?.* prop/i.test(message)){return{code:"api.unsupported_prop",severity,theme,message,suggestion:"Remove the prop or use one documented for this Vizmatic primitive."}}if(/invalid value for css property|unsupported (?:css|style)|not supported.*css/i.test(message)){return{code:"style.unsupported",severity,theme,message,suggestion:"Use CSS supported by Satori or a Vizmatic primitive."}}if(/font|emoji|image asset|failed to (?:download|fetch)|asset .*not found/i.test(message)){return{code:"asset.warning",severity,theme,message,suggestion:"Use a reachable asset or install it locally before rendering offline."}}return{code:severity==="error"?"render.error":"render.warning",severity,theme,message}}var DEFAULT_WIDTH=960;var DEFAULT_HEIGHT=540;var MAX_WIDTH=1920;var MAX_HEIGHT=1440;var GROWTH=1.25;var MAX_AUTO_SIZE_ATTEMPTS=6;var TRUSTED_COMPONENTS=new Set(Object.values(primitives_exports));var SVG_CONTEXT_COMPONENTS={shapes:new Map([[SvgFrame,"SvgFrame"],[SvgPoint,"SvgPoint"],[VectorArrow,"VectorArrow"],[VectorSegment,"VectorSegment"],[ArrowMarkerDef,"ArrowMarkerDef"]]),children:new Map([...[Board,CanvasItem,Canvas,Scene,Row,Column,Panel,Stack,Card,Tile,WindowFrame,CalloutCard,ChartFrame].map(component=>[component,"html"]),[AxisPlot,"svg"]])};var consoleCaptureContext=new AsyncLocalStorage;var activeConsoleCaptures=0;var originalConsoleMethods;function formatConsoleArgs(args){return args.map(value=>{if(value instanceof Error)return value.message;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}).join(" ")}function installConsoleCapture(){if(activeConsoleCaptures===0){originalConsoleMethods={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};const original=originalConsoleMethods;const intercept=(method,severity)=>(...args)=>{const messages=consoleCaptureContext.getStore();if(messages){if(severity)messages.push({severity,message:formatConsoleArgs(args)});return}Reflect.apply(original[method],console,args)};console.debug=intercept("debug");console.error=intercept("error","error");console.info=intercept("info");console.log=intercept("log");console.warn=intercept("warn","warning")}activeConsoleCaptures+=1;let restored=false;return()=>{if(restored)return;restored=true;activeConsoleCaptures-=1;if(activeConsoleCaptures===0&&originalConsoleMethods){console.debug=originalConsoleMethods.debug;console.error=originalConsoleMethods.error;console.info=originalConsoleMethods.info;console.log=originalConsoleMethods.log;console.warn=originalConsoleMethods.warn;originalConsoleMethods=void 0}}}async function captureConsole(run2){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run2);return{value,messages}}catch(error){return{error,messages}}finally{uninstall()}}function normalizeAutoSize(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value)return{width:value.width??defaults.width,height:value.height??defaults.height};return defaults}function overflowEdges(error){if(!(error instanceof CanvasOverflowError))return void 0;return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}function nextDimension(value,maximum){return Math.min(maximum,Math.ceil(value*GROWTH/10)*10)}function nextAutoSize(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?nextDimension(width,MAX_WIDTH):width;const nextHeight=growHeight?nextDimension(height,MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrame(create,theme,options){let width=options.width;let height=options.height;for(let attempt=0;attempt<MAX_AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const output=await renderToPngWithOutput(create(theme),{width,height,outputPath:options.outputPath,crop:true,scale:1,background:options.background,onNodeDetected:node=>layoutNodes.push(node)},create,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges(error);const next=edges?nextAutoSize(width,height,options.autoSize,edges):void 0;if(!next||attempt===MAX_AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function counts(themes){const diagnostics=themes.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{errors:diagnostics.filter(({severity})=>severity==="error").length,warnings:diagnostics.filter(({severity})=>severity==="warning").length,info:diagnostics.filter(({severity})=>severity==="info").length}}function fails(diagnostics,policy){if(policy==="never")return false;const threshold={error:0,warning:1,info:2}[policy];const levels={error:0,warning:1,info:2};return diagnostics.some(({severity})=>levels[severity]<=threshold)}function messageDiagnostics(messages,theme){return messages.map(({message,severity})=>diagnosticFromMessage(message,severity,theme))}function rootBackground(background,theme){if(background==="theme")return getThemeColors(theme).bg;if(background==="transparent"||background===void 0)return void 0;return background}async function checkFrame(input,options={}){const themes=options.themes??["dark","light"];if(themes.length===0)throw new TypeError("checkFrame requires at least one theme");const width=input.width??DEFAULT_WIDTH;const height=input.height??DEFAULT_HEIGHT;if(!Number.isFinite(width)||width<=0||!Number.isFinite(height)||height<=0){throw new TypeError("checkFrame width and height must be positive finite numbers")}const autoSize=normalizeAutoSize(input.autoSize,{width:input.width==null,height:input.height==null});const create=input.create??(()=>input.scene);const failOn=options.failOn??"error";const tempDir=await mkdtemp(join(tmpdir(),"vizmatic-check-"));const reports=[];try{for(const[themeIndex,theme]of themes.entries()){const inputDimensions={width,height};const diagnostics2=[];const prepared=await captureConsole(async()=>{const element=create(theme);const background=rootBackground(options.background,theme);return analyzeScene(element,theme,TRUSTED_COMPONENTS,background,SVG_CONTEXT_COMPONENTS)});diagnostics2.push(...messageDiagnostics(prepared.messages,theme));if(!prepared.value){diagnostics2.push(diagnosticFromMessage(prepared.error instanceof Error?prepared.error.message:String(prepared.error),"error",theme));reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2});continue}diagnostics2.push(...prepared.value);const rendered=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize,background:options.background,outputPath:join(tempDir,`${themeIndex}.png`)}));diagnostics2.push(...messageDiagnostics(rendered.messages,theme));if(rendered.value){diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes,theme));if(rendered.value.contentBounds){diagnostics2.push(...analyzeWhitespaceBalance(rendered.value.contentBounds,rendered.value.logicalOutputWidth,rendered.value.logicalOutputHeight,theme))}if(rendered.value.width!==width||rendered.value.height!==height){diagnostics2.push({code:"layout.auto_size",severity:"info",theme,message:`Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,suggestedDimensions:{width:rendered.value.width,height:rendered.value.height}})}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions,resolved:{width:rendered.value.width,height:rendered.value.height},output:{width:rendered.value.outputWidth,height:rendered.value.outputHeight}},diagnostics:diagnostics2});continue}const edges=overflowEdges(rendered.error);if(edges){const suggestion=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize:{width:true,height:true},background:options.background,outputPath:join(tempDir,`${themeIndex}-suggestion.png`)}));const suggestedDimensions=suggestion.value?{width:suggestion.value.width,height:suggestion.value.height}:void 0;diagnostics2.push({code:"layout.overflow",severity:"error",theme,edges,message:rendered.error instanceof Error?rendered.error.message:String(rendered.error),suggestion:suggestedDimensions?`Increase the canvas to at least ${suggestedDimensions.width}\xD7${suggestedDimensions.height}, or remove fixed dimensions to enable auto-sizing.`:"Increase the canvas dimensions or remove fixed dimensions to enable auto-sizing.",suggestedDimensions})}else{diagnostics2.push(diagnosticFromMessage(rendered.error instanceof Error?rendered.error.message:String(rendered.error),"error",theme))}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2})}}finally{await rm(tempDir,{recursive:true,force:true})}const summary=counts(reports);const diagnostics=reports.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{schemaVersion:1,source:input.source,ok:!fails(diagnostics,failOn),rendered:reports.every(({dimensions})=>dimensions.resolved!==void 0),autoSize,themes:reports,summary}}import parseCssColor3 from"parse-css-color";var themeColorKeys=Object.freeze(Object.keys(getThemeColors("dark")).filter(key=>key!=="preset"&&key!=="fontSans"&&key!=="fontMono"&&key!=="fontSerif"&&key!=="density"));var themeColorKeySet=new Set(themeColorKeys);function validatePlaygroundThemeColors(value){if(value==null||typeof value!=="object"||Array.isArray(value)){throw new Error("themeColors must be a JSON object of CSS colors.")}const colors2={};for(const[key,color]of Object.entries(value)){if(!themeColorKeySet.has(key)){throw new Error(`Unknown themeColors key ${JSON.stringify(key)}.`)}if(typeof color!=="string"||!parseCssColor3(color.trim())){throw new Error(`themeColors.${key} must be a valid CSS color.`)}colors2[key]=color.trim()}return colors2}function parseThemeColorsMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error("themeColors must be a single-line JSON object of CSS colors.");let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error("themeColors must be a single-line JSON object of CSS colors.")}return validatePlaygroundThemeColors(parsed)}function parseBackgroundMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.');let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.')}return validatePlaygroundBackground(parsed)}function isBackgroundMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]/.test(line2)}function validatePlaygroundBackground(value){if(typeof value!=="string"){throw new Error('background must be "theme", "transparent", or a valid CSS color.')}const background=value.trim();if(background==="theme"||background==="transparent"||parseCssColor3(background))return background;throw new Error('background must be "theme", "transparent", or a valid CSS color.')}function isThemeColorsMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]/.test(line2)}function mergePlaygroundThemeColors(mode,preset,overrides){return{...getThemeColors(mode,preset),...overrides}}function stripTrailingLineComment(line2){let quoted=false;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[index];if(quoted){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')quoted=false;continue}if(character==='"')quoted=true;else if(character==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}function readPresetLine(line2){const candidate=stripLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=candidate.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?preset(?:\s*:\s*ThemePreset)?\s*[:=]\s*(.+)$/i);if(!match?.[1])return void 0;const expression=match[1].trim().replace(/;\s*$/,"").trim();const quoted=expression.match(/^(['"])(.*)\1$/);const requested=(quoted?.[2]??expression).trim();const normalized=requested.toLowerCase();const preset=quoted&&(normalized==="default"||normalized==="engineering")?normalized:void 0;return{preset,requested}}function readAnimationLine(line2){const match=line2.match(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?(animationDuration|animationFps)\s*[:=]\s*(.*?)\s*;?\s*(?:\/\/.*)?$/);if(!match)return void 0;const expression=match[2].replace(/;\s*$/,"").trim();if(!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(expression)){throw new Error(`${match[1]} must be a numeric literal.`)}return{name:match[1],value:Number(expression)}}function stripLineComment(line2){let quote;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0}else if(character==='"'||character==="'")quote=character;else if(character==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}import parseCssColor4 from"parse-css-color";function validatePlaygroundAnimation(animation){if(!Number.isFinite(animation.duration)||animation.duration<=0||animation.duration>10){throw new Error("animationDuration must be greater than 0 and at most 10 seconds.")}if(!Number.isInteger(animation.fps)||animation.fps<1||animation.fps>30){throw new Error("animationFps must be an integer from 1 to 30.")}return{duration:animation.duration,fps:animation.fps}}import{existsSync}from"fs";import{mkdir as mkdir3,stat as stat2,writeFile as writeFile3}from"fs/promises";import{basename,dirname as dirname3,extname,join as join2,relative,resolve as resolve2}from"path";import{mkdir as mkdir2,stat,writeFile as writeFile2}from"fs/promises";import{totalmem}from"os";import{dirname as dirname2,resolve}from"path";import*as gifenc2 from"gifenc";import parseCssColor5 from"parse-css-color";var midnight={name:"midnight",dark:true,background:"#0b0c10",bloom:.2,colors:{bg:"#0b0c10",surface:"#15171d",ink:"#f2efe6",dim:"#a5a7ad",faint:"#5c5f68",grid:"#23303d",gridStrong:"#3d5266",blue:"#5cc4f0",teal:"#4fd8c4",green:"#8fe08a",yellow:"#ffd75e",gold:"#f2b84b",orange:"#ff9d57",red:"#ff6b6b",pink:"#ff8fc0",purple:"#b49cff"}};var paper={name:"paper",dark:false,background:"#f7f3ea",bloom:0,colors:{bg:"#f7f3ea",surface:"#efe9db",ink:"#1d1b16",dim:"#5e5a50",faint:"#a29c8d",grid:"#e2dbca",gridStrong:"#c4bba6",blue:"#1f6fb2",teal:"#0d8577",green:"#3f8a35",yellow:"#b98500",gold:"#a8740a",orange:"#cf5d12",red:"#c62f2f",pink:"#c2387e",purple:"#6a4bc4"}};var blueprint={name:"blueprint",dark:true,background:"#0b2340",bloom:.16,colors:{bg:"#0b2340",surface:"#123054",ink:"#eaf6ff",dim:"#9cc0dc",faint:"#5d86a8",grid:"#1a3f66",gridStrong:"#2c5f8e",blue:"#7fd4ff",teal:"#6fe6d6",green:"#9de8a4",yellow:"#ffe27a",gold:"#f5c566",orange:"#ffb27a",red:"#ff8d8d",pink:"#ffa8cf",purple:"#c5b4ff"}};var chalk={name:"chalk",dark:true,background:"#10201b",bloom:.1,colors:{bg:"#10201b",surface:"#172c25",ink:"#f4f1e4",dim:"#b1b9a9",faint:"#67786d",grid:"#20392f",gridStrong:"#355547",blue:"#8ccbe8",teal:"#7dd9c1",green:"#a9dc8f",yellow:"#f6dd7c",gold:"#e6bf62",orange:"#f2a874",red:"#ee8a80",pink:"#efa2c2",purple:"#bfa9e6"}};var neon={name:"neon",dark:true,background:"#050507",bloom:.4,colors:{bg:"#050507",surface:"#101016",ink:"#ffffff",dim:"#a9a9b8",faint:"#55555f",grid:"#1a1f2e",gridStrong:"#2f3a55",blue:"#3fb2ff",teal:"#21f0d0",green:"#6dff8e",yellow:"#fff04d",gold:"#ffc22e",orange:"#ff8a2e",red:"#ff4560",pink:"#ff5fb0",purple:"#a56bff"}};var LOOKS={midnight,paper,blueprint,chalk,neon};function resolveLook(look){if(look===void 0)return midnight;if(typeof look!=="string")return look;const found=LOOKS[look];if(!found)throw new Error(`Unknown look: ${JSON.stringify(look)}. Use one of: ${Object.keys(LOOKS).join(", ")}.`);return found}var TRANSPARENT=[0,0,0,0];var cache=new Map;var tokens2=midnight.colors;function setColorTokens(next){tokens2=next}function parseColor(input){const token=tokens2[input];const value=token??input;const cached=cache.get(value);if(cached)return cached;const parsed=parseCssColor5(value);if(!parsed)throw new Error(`Unknown color: ${JSON.stringify(input)}. Use a look token such as "blue" or a CSS color.`);let[r,g,b]=parsed.values;if(parsed.type==="hsl")[r,g,b]=hslToRgb3(r,g,b);const result=[r,g,b,parsed.alpha];cache.set(value,result);return result}function hslToRgb3(h,s,l){const a=s/100*Math.min(l/100,1-l/100);const f=n=>{const k=(n+h/30)%12;return 255*(l/100-a*Math.max(-1,Math.min(k-3,9-k,1)))};return[f(0),f(8),f(4)]}function toPaint(input){if(typeof input==="string")return parseColor(input);return input}function isGradient(paint){return!Array.isArray(paint)}function css(color,alpha3=1){const a=color[3]*alpha3;const r=Math.round(color[0]),g=Math.round(color[1]),b=Math.round(color[2]);if(a>=1)return`rgb(${r},${g},${b})`;return`rgba(${r},${g},${b},${Math.round(a*1e3)/1e3})`}function srgbToLinear(v){const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)}function linearToSrgb(v){const x=v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055;return Math.max(0,Math.min(255,x*255))}function toOklab(c){const r=srgbToLinear(c[0]),g=srgbToLinear(c[1]),b=srgbToLinear(c[2]);const l=Math.cbrt(.4122214708*r+.5363325363*g+.0514459929*b);const m=Math.cbrt(.2119034982*r+.6806995451*g+.1073969566*b);const s=Math.cbrt(.0883024619*r+.2817188376*g+.6299787005*b);return[.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s]}function fromOklab(lab,alpha3){const l=lab[0]+.3963377774*lab[1]+.2158037573*lab[2];const m=lab[0]-.1055613458*lab[1]-.0638541728*lab[2];const s=lab[0]-.0894841775*lab[1]-1.291485548*lab[2];const ll=l*l*l,mm=m*m*m,ss=s*s*s;return[linearToSrgb(4.0767416621*ll-3.3077115913*mm+.2309699292*ss),linearToSrgb(-1.2684380046*ll+2.6097574011*mm-.3413193965*ss),linearToSrgb(-.0041960863*ll-.7034186147*mm+1.707614701*ss),alpha3]}function mixColor(a,b,t){if(t<=0)return a;if(t>=1)return b;const x=toOklab(a),y=toOklab(b);return fromOklab([x[0]+(y[0]-x[0])*t,x[1]+(y[1]-x[1])*t,x[2]+(y[2]-x[2])*t],a[3]+(b[3]-a[3])*t)}function mixPaint(a,b,t){if(t<=0)return a;if(t>=1)return b;const ga=isGradient(a),gb=isGradient(b);if(!ga&&!gb)return mixColor(a,b,t);if(ga&&gb&&a.type===b.type&&a.stops.length===b.stops.length){const stops=a.stops.map((stop,i)=>[stop[0]+(b.stops[i][0]-stop[0])*t,mixColor(stop[1],b.stops[i][1],t)]);if(a.type==="linear"&&b.type==="linear"){return{type:"linear",stops,from:[a.from[0]+(b.from[0]-a.from[0])*t,a.from[1]+(b.from[1]-a.from[1])*t],to:[a.to[0]+(b.to[0]-a.to[0])*t,a.to[1]+(b.to[1]-a.to[1])*t]}}if(a.type==="radial"&&b.type==="radial"){return{type:"radial",stops,center:[a.center[0]+(b.center[0]-a.center[0])*t,a.center[1]+(b.center[1]-a.center[1])*t],radius:a.radius+(b.radius-a.radius)*t}}return{type:"along",stops}}const solidA=ga?sampleStops(a.stops,.5):a;const solidB=gb?sampleStops(b.stops,.5):b;return mixColor(solidA,solidB,t)}function sampleStops(stops,at){if(stops.length===0)return TRANSPARENT;if(at<=stops[0][0])return stops[0][1];for(let i=1;i<stops.length;i++){if(at<=stops[i][0]){const[p0,c0]=stops[i-1],[p1,c1]=stops[i];return mixColor(c0,c1,p1>p0?(at-p0)/(p1-p0):0)}}return stops[stops.length-1][1]}function normalizeStops(colors2){const count=colors2.length;return colors2.map((entry,i)=>{if(Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="number"){return[entry[0],solid(entry[1])]}return[count===1?0:i/(count-1),solid(entry)]})}function solid(input){const paint=toPaint(input);return isGradient(paint)?sampleStops(paint.stops,.5):paint}function linearGradient(from,to2,colors2){return{type:"linear",from,to:to2,stops:normalizeStops(colors2)}}function radialGradient(center2,radius,colors2){return{type:"radial",center:center2,radius,stops:normalizeStops(colors2)}}function along(...colors2){return{type:"along",stops:normalizeStops(colors2)}}function ramp(count,...colors2){const stops=normalizeStops(colors2);return Array.from({length:count},(_,i)=>sampleStops(stops,count===1?0:i/(count-1)))}var IDENTITY=[1,0,0,1,0,0];var EMPTY_BOUNDS={x:0,y:0,width:0,height:0};var KAPPA=.5522847498307936;var LUT_STEPS=10;function mul(m,n){return[m[0]*n[0]+m[2]*n[1],m[1]*n[0]+m[3]*n[1],m[0]*n[2]+m[2]*n[3],m[1]*n[2]+m[3]*n[3],m[0]*n[4]+m[2]*n[5]+m[4],m[1]*n[4]+m[3]*n[5]+m[5]]}function invert(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return IDENTITY;const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function apply(m,x,y){return[m[0]*x+m[2]*y+m[4],m[1]*x+m[3]*y+m[5]]}function compose(x,y,rotation,sx,sy,px,py){const cos=rotation===0?1:Math.cos(rotation);const sin=rotation===0?0:Math.sin(rotation);const a=cos*sx;const b=sin*sx;const c=-sin*sy;const d=cos*sy;return[a,b,c,d,x-a*px-c*py,y-b*px-d*py]}function matScale(m){return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2]))}function ring(points,closed=false){return{p:points instanceof Float64Array?points:Float64Array.from(points),closed}}function segmentCount(r){return Math.max(0,(r.p.length-2)/6)}function lineInto(out,x0,y0,x1,y1){out.push(x0+(x1-x0)/3,y0+(y1-y0)/3,x0+(x1-x0)*2/3,y0+(y1-y0)*2/3,x1,y1)}function linePath(a,b){const out=[a[0],a[1]];lineInto(out,a[0],a[1],b[0],b[1]);return[ring(out)]}function polyPath(points,closed=false){if(points.length===0)return[];const first=points[0];const out=[first[0],first[1]];for(let i=1;i<points.length;i++)lineInto(out,points[i-1][0],points[i-1][1],points[i][0],points[i][1]);if(closed){const last=points[points.length-1];if(last[0]!==first[0]||last[1]!==first[1])lineInto(out,last[0],last[1],first[0],first[1])}return[ring(out,closed)]}function smoothPath(points,closed=false,tension=1/6){const n=points.length;if(n===0)return[];if(n<3)return polyPath(points,closed);const at=i=>closed?points[(i+n)%n]:points[Math.max(0,Math.min(n-1,i))];const out=[points[0][0],points[0][1]];const count=closed?n:n-1;for(let i=0;i<count;i++){const p0=at(i-1),p1=at(i),p2=at(i+1),p3=at(i+2);out.push(p1[0]+(p2[0]-p0[0])*tension,p1[1]+(p2[1]-p0[1])*tension,p2[0]-(p3[0]-p1[0])*tension,p2[1]-(p3[1]-p1[1])*tension,p2[0],p2[1])}return[ring(out,closed)]}function arcPath(cx,cy,rx,ry,from,to2){const sweep=to2-from;if(sweep===0)return[];const closed=Math.abs(Math.abs(sweep)-Math.PI*2)<1e-9;const count=Math.max(1,Math.ceil(Math.abs(sweep)/(Math.PI/4)-1e-9));const step=sweep/count;const k=4/3*Math.tan(step/4);const out=[cx+Math.cos(from)*rx,cy+Math.sin(from)*ry];for(let i=0;i<count;i++){const a0=from+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);out.push(cx+(c0-k*s0)*rx,cy+(s0+k*c0)*ry,cx+(c1+k*s1)*rx,cy+(s1-k*c1)*ry,cx+c1*rx,cy+s1*ry)}if(closed){out[out.length-2]=out[0];out[out.length-1]=out[1]}return[ring(out,closed)]}function circlePath(cx,cy,r){return arcPath(cx,cy,r,r,0,Math.PI*2)}function rectPath(x,y,width,height,radius=0){const r=Math.max(0,Math.min(radius,Math.abs(width)/2,Math.abs(height)/2));if(r===0)return polyPath([[x,y],[x+width,y],[x+width,y+height],[x,y+height]],true);const k=r*(1-KAPPA);const right=x+width,bottom=y+height;const out=[x+r,y];lineInto(out,x+r,y,right-r,y);out.push(right-k,y,right,y+k,right,y+r);lineInto(out,right,y+r,right,bottom-r);out.push(right,bottom-k,right-k,bottom,right-r,bottom);lineInto(out,right-r,bottom,x+r,bottom);out.push(x+k,bottom,x,bottom-k,x,bottom-r);lineInto(out,x,bottom-r,x,y+r);out.push(x,y+k,x+k,y,x+r,y);return[ring(out,true)]}function parametricPath(f,from,to2,samples=64){const count=Math.max(2,Math.floor(samples));const points=[];for(let i=0;i<=count;i++)points.push(f(from+(to2-from)*i/count));return curveThrough(points)}function curveThrough(points){const rings=[];let run2=[];const flush=()=>{if(run2.length>=2)rings.push(...smoothPath(run2));run2=[]};for(const point of points){if(Number.isFinite(point[0])&&Number.isFinite(point[1]))run2.push(point);else flush()}flush();return rings}function concat(...paths){return paths.flat()}function transformPath(path,m){if(m===IDENTITY)return path;const out=new Array(path.length);for(let r=0;r<path.length;r++){const src=path[r].p;const dst=new Float64Array(src.length);for(let i=0;i<src.length;i+=2){const x=src[i],y=src[i+1];dst[i]=m[0]*x+m[2]*y+m[4];dst[i+1]=m[1]*x+m[3]*y+m[5]}out[r]={p:dst,closed:path[r].closed}}return out}function warpPath(path,f,subdivisions=4){const dense=subdivisions>1?path.map(r=>subdivideEach(r,subdivisions)):path;return dense.map(r=>{const count=segmentCount(r);const anchors=[];for(let i=0;i<=count;i++){const mapped=f(r.p[i*6],r.p[i*6+1]);anchors.push(mapped)}const out=[anchors[0][0],anchors[0][1]];for(let i=0;i<count;i++){const c1=f(r.p[i*6+2],r.p[i*6+3]);const c2=f(r.p[i*6+4],r.p[i*6+5]);out.push(c1[0],c1[1],c2[0],c2[1],anchors[i+1][0],anchors[i+1][1])}return ring(out,r.closed)})}function splitInto(src,o,t,left,right){const x0=src[o],y0=src[o+1],x1=src[o+2],y1=src[o+3];const x2=src[o+4],y2=src[o+5],x3=src[o+6],y3=src[o+7];const ax=x0+(x1-x0)*t,ay=y0+(y1-y0)*t;const bx=x1+(x2-x1)*t,by=y1+(y2-y1)*t;const cx=x2+(x3-x2)*t,cy=y2+(y3-y2)*t;const dx=ax+(bx-ax)*t,dy=ay+(by-ay)*t;const ex=bx+(cx-bx)*t,ey=by+(cy-by)*t;const fx=dx+(ex-dx)*t,fy=dy+(ey-dy)*t;left.push(ax,ay,dx,dy,fx,fy);right.length=0;right.push(fx,fy,ex,ey,cx,cy,x3,y3)}function subdivideEach(r,n){const count=segmentCount(r);if(n<=1||count===0)return r;const out=[r.p[0],r.p[1]];for(let i=0;i<count;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));for(let k=n;k>1;k--){const rest=[];splitInto(seg,0,1/k,out,rest);seg=rest}out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,r.closed)}var measures=new WeakMap;function measure(r){const cached=measures.get(r);if(cached)return cached;const count=segmentCount(r);const total=new Float64Array(count);const lut=new Float64Array(count*LUT_STEPS);let sum=0;const p=r.p;for(let i=0;i<count;i++){const o=i*6;const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3],x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];let lastX=x0,lastY=y0,acc=0;for(let k=1;k<=LUT_STEPS;k++){const t=k/LUT_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;acc+=Math.hypot(x-lastX,y-lastY);lut[i*LUT_STEPS+k-1]=acc;lastX=x;lastY=y}sum+=acc;total[i]=sum}const result={total,lut,length:sum};measures.set(r,result);return result}function ringLength(r){return measure(r).length}function pathLength(path){let sum=0;for(const r of path)sum+=measure(r).length;return sum}function locate(m,distance){const count=m.total.length;if(count===0)return[0,0];if(distance<=0)return[0,0];if(distance>=m.length)return[count-1,1];let lo=0,hi=count-1;while(lo<hi){const mid=lo+hi>>1;if(m.total[mid]<distance)lo=mid+1;else hi=mid}const before=lo===0?0:m.total[lo-1];const local=distance-before;const base=lo*LUT_STEPS;let k=0;while(k<LUT_STEPS-1&&m.lut[base+k]<local)k++;const start=k===0?0:m.lut[base+k-1];const end=m.lut[base+k];const fraction=end>start?(local-start)/(end-start):0;return[lo,(k+fraction)/LUT_STEPS]}function trimRing(r,from,to2){const count=segmentCount(r);if(count===0)return null;const a=Math.max(0,Math.min(1,from));const b=Math.max(0,Math.min(1,to2));if(b<=a)return null;if(a===0&&b===1)return r;const m=measure(r);if(m.length===0)return null;const[i0,t0]=locate(m,a*m.length);const[i1,t1]=locate(m,b*m.length);const out=[];for(let i=i0;i<=i1;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));const start=i===i0?t0:0;const end=i===i1?t1:1;if(start>0){const rest=[];splitInto(seg,0,start,[],rest);seg=rest}if(end<1){const left=[];const rest=[];const scaled=start>0?(end-start)/(1-start):end;splitInto(seg,0,scaled,left,rest);seg=[seg[0],seg[1],...left]}if(out.length===0)out.push(seg[0],seg[1]);out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,false)}function trimPath(path,from,to2,each=false){if(from<=0&&to2>=1)return path;const out=[];if(each){for(const r of path){const piece=trimRing(r,from,to2);if(piece)out.push(piece)}return out}const total=pathLength(path);if(total===0)return[];let travelled=0;for(const r of path){const length=ringLength(r);const start=(from*total-travelled)/(length||1);const end=(to2*total-travelled)/(length||1);travelled+=length;if(end<=0||start>=1)continue;const piece=trimRing(r,Math.max(0,start),Math.min(1,end));if(piece)out.push(piece)}return out}function pointAt(path,fraction){const total=pathLength(path);if(total===0){const first=path[0]?.p;return first?[first[0],first[1]]:[0,0]}let remaining=Math.max(0,Math.min(1,fraction))*total;for(let i=0;i<path.length;i++){const r=path[i];const length=ringLength(r);if(remaining<=length||i===path.length-1){const[segment,t]=locate(measure(r),remaining);return evaluate(r.p,segment*6,t)}remaining-=length}return[0,0]}function tangentAt(path,fraction){const delta=.002;const a=pointAt(path,Math.max(0,fraction-delta));const b=pointAt(path,Math.min(1,fraction+delta));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return[(b[0]-a[0])/length,(b[1]-a[1])/length]}function evaluate(p,o,t){const u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;return[a*p[o]+b*p[o+2]+c*p[o+4]+d*p[o+6],a*p[o+1]+b*p[o+3]+c*p[o+5]+d*p[o+7]]}function extendCubicAxis(range,p0,p1,p2,p3){range[0]=Math.min(range[0],p0,p3);range[1]=Math.max(range[1],p0,p3);if(p1>=range[0]&&p1<=range[1]&&p2>=range[0]&&p2<=range[1])return;const a=-p0+3*p1-3*p2+p3;const b=2*(p0-2*p1+p2);const c=p1-p0;const roots=[];if(Math.abs(a)<1e-9){if(Math.abs(b)>1e-9)roots.push(-c/b)}else{const disc=b*b-4*a*c;if(disc>=0){const s=Math.sqrt(disc);roots.push((-b+s)/(2*a),(-b-s)/(2*a))}}for(const t of roots){if(t<=0||t>=1)continue;const u=1-t;const value=u*u*u*p0+3*u*u*t*p1+3*u*t*t*p2+t*t*t*p3;range[0]=Math.min(range[0],value);range[1]=Math.max(range[1],value)}}var ringBounds=new WeakMap;function boundsOfRing(r){const cached=ringBounds.get(r);if(cached)return cached;const p=r.p;if(p.length<2)return EMPTY_BOUNDS;const xs=[p[0],p[0]];const ys=[p[1],p[1]];for(let o=0;o+7<p.length;o+=6){extendCubicAxis(xs,p[o],p[o+2],p[o+4],p[o+6]);extendCubicAxis(ys,p[o+1],p[o+3],p[o+5],p[o+7])}const bounds4={x:xs[0],y:ys[0],width:xs[1]-xs[0],height:ys[1]-ys[0]};ringBounds.set(r,bounds4);return bounds4}function pathBounds(path){if(path.length===0)return null;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const r of path){if(r.p.length<2)continue;const b=boundsOfRing(r);minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height)}if(minX===Infinity)return null;return{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}function unionBounds(a,b){if(!a)return b;if(!b)return a;const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function signedArea(r){const p=r.p;let sum=0;for(let o=0;o+7<p.length;o+=6){sum+=p[o]*p[o+7]-p[o+6]*p[o+1]}return sum/2}function ringCenter(r){const b=boundsOfRing(r);return[b.x+b.width/2,b.y+b.height/2]}function reverseRing(r){const p=r.p;const out=new Float64Array(p.length);for(let i=0;i<p.length;i+=2){out[i]=p[p.length-2-i];out[i+1]=p[p.length-1-i]}return{p:out,closed:r.closed}}function parseSvgPath(d){const tokens5=d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);if(!tokens5)return[];const rings=[];let out=[];let i=0,x=0,y=0,startX=0,startY=0;let lastCmd="",lastCx=0,lastCy=0;const num=()=>Number(tokens5[i++]);const flags=()=>{const token=tokens5[i];if(token.length>1&&(token[0]==="0"||token[0]==="1")&&!token.startsWith("0.")&&!token.startsWith("1.")){tokens5[i]=token.slice(1);return Number(token[0])}i++;return Number(token)};const flush=closed=>{if(out.length>=8)rings.push(ring(out,closed));out=[]};const begin=(px,py)=>{if(out.length===0)out.push(px,py)};let cmd="";while(i<tokens5.length){const token=tokens5[i];if(/^[a-zA-Z]$/.test(token)){cmd=token;i++}else if(cmd==="M"){cmd="L"}else if(cmd==="m"){cmd="l"}else if(cmd===""){throw new Error(`Invalid SVG path data: ${d.slice(0,40)}`)}const rel=cmd>="a";switch(cmd.toUpperCase()){case"M":{flush(false);x=(rel?x:0)+num();y=(rel?y:0)+num();startX=x;startY=y;out.push(x,y);break}case"L":{const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,nx,ny);x=nx;y=ny;break}case"H":{const nx=(rel?x:0)+num();begin(x,y);lineInto(out,x,y,nx,y);x=nx;break}case"V":{const ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,x,ny);y=ny;break}case"C":{const ox=rel?x:0,oy=rel?y:0;const c1x=ox+num(),c1y=oy+num(),c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"S":{const ox=rel?x:0,oy=rel?y:0;const smooth3="CScs".includes(lastCmd);const c1x=smooth3?2*x-lastCx:x,c1y=smooth3?2*y-lastCy:y;const c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"Q":{const ox=rel?x:0,oy=rel?y:0;const qx=ox+num(),qy=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"T":{const ox=rel?x:0,oy=rel?y:0;const smooth3="QTqt".includes(lastCmd);const qx=smooth3?2*x-lastCx:x,qy=smooth3?2*y-lastCy:y;const nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"A":{const rx=num(),ry=num(),angle=num(),large=flags(),sweep=flags();const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);arcInto(out,x,y,rx,ry,angle,large===1,sweep===1,nx,ny);x=nx;y=ny;break}case"Z":{if(out.length>0){if(x!==startX||y!==startY)lineInto(out,x,y,startX,startY);flush(true)}x=startX;y=startY;break}default:throw new Error(`Unsupported SVG path command: ${cmd}`)}lastCmd=cmd}flush(false);return rings}function arcInto(out,x0,y0,rxIn,ryIn,degrees,large,sweep,x1,y1){let rx=Math.abs(rxIn),ry=Math.abs(ryIn);if(rx===0||ry===0||x0===x1&&y0===y1){lineInto(out,x0,y0,x1,y1);return}const phi=degrees*Math.PI/180;const cos=Math.cos(phi),sin=Math.sin(phi);const dx=(x0-x1)/2,dy=(y0-y1)/2;const xp=cos*dx+sin*dy,yp=-sin*dx+cos*dy;const lambda=xp*xp/(rx*rx)+yp*yp/(ry*ry);if(lambda>1){const scale=Math.sqrt(lambda);rx*=scale;ry*=scale}const numerator=rx*rx*ry*ry-rx*rx*yp*yp-ry*ry*xp*xp;const denominator=rx*rx*yp*yp+ry*ry*xp*xp;const factor=(large===sweep?-1:1)*Math.sqrt(Math.max(0,numerator/denominator));const cxp=factor*rx*yp/ry,cyp=-factor*ry*xp/rx;const cx=cos*cxp-sin*cyp+(x0+x1)/2;const cy=sin*cxp+cos*cyp+(y0+y1)/2;const start=Math.atan2((yp-cyp)/ry,(xp-cxp)/rx);let delta=Math.atan2((-yp-cyp)/ry,(-xp-cxp)/rx)-start;if(sweep&&delta<0)delta+=Math.PI*2;if(!sweep&&delta>0)delta-=Math.PI*2;const count=Math.max(1,Math.ceil(Math.abs(delta)/(Math.PI/2)-1e-9));const step=delta/count;const k=4/3*Math.tan(step/4);for(let i=0;i<count;i++){const a0=start+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);const q1x=(c0-k*s0)*rx,q1y=(s0+k*c0)*ry;const q2x=(c1+k*s1)*rx,q2y=(s1-k*c1)*ry;const ex=c1*rx,ey=s1*ry;out.push(cos*q1x-sin*q1y+cx,sin*q1x+cos*q1y+cy,cos*q2x-sin*q2y+cx,sin*q2x+cos*q2y+cy,i===count-1?x1:cos*ex-sin*ey+cx,i===count-1?y1:sin*ex+cos*ey+cy)}}function fmt(value){const rounded=Math.round(value*100)/100;return rounded===0?"0":String(rounded)}function pathToD(path){const parts=[];for(const r of path){const p=r.p;if(p.length<2)continue;parts.push("M",fmt(p[0])," ",fmt(p[1]));if(r.straight){for(let o=2;o+5<p.length;o+=6)parts.push("L",fmt(p[o+4])," ",fmt(p[o+5]));if(r.closed)parts.push("Z");continue}for(let o=2;o+5<p.length;o+=6){parts.push("C",fmt(p[o])," ",fmt(p[o+1])," ",fmt(p[o+2])," ",fmt(p[o+3])," ",fmt(p[o+4])," ",fmt(p[o+5]))}if(r.closed)parts.push("Z")}return parts.join("")}var clock={now:0,mode:"free",frame:0,capture:null};var Track=class{constructor(initial){this.initial=initial}initial;keys=[];sample(t){const keys=this.keys;let lo=0,hi=keys.length-1,index=-1;while(lo<=hi){const mid=lo+hi>>1;if(keys[mid].t0<=t){index=mid;lo=mid+1}else{hi=mid-1}}if(index<0)return this.initial;const key=keys[index];if(t>=key.t1||!key.at)return key.to;const span=key.t1-key.t0;const raw=span>0?(t-key.t0)/span:1;return key.at(key.ease?key.ease(raw):raw)}add(key){const keys=this.keys;let index=keys.length;while(index>0&&keys[index-1].t0>key.t0)index--;keys.splice(index,0,key)}step(t,value){this.add({t0:t,t1:t,ease:null,to:value,at:null})}get end(){let end=0;for(const key of this.keys)if(key.t1>end)end=key.t1;return end}};var clockNow=()=>clock.now;var ALONG_PIECE_LENGTH=14;var MAX_ALONG_PIECES=96;function worldPaint(paint,m){if(!paint||!isGradient(paint))return paint;if(paint.type==="linear"){return{...paint,from:apply(m,paint.from[0],paint.from[1]),to:apply(m,paint.to[0],paint.to[1])}}if(paint.type==="radial"){return{...paint,center:apply(m,paint.center[0],paint.center[1]),radius:paint.radius*matScale(m)}}return paint}function sameMatrix(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]}var worldCache=new WeakMap;function toWorld(node,path,m){const cached=worldCache.get(node);if(cached&&cached.path===path&&sameMatrix(cached.matrix,m))return cached.world;const world=transformPath(path,m);worldCache.set(node,{path,matrix:m,world});return world}function emit(node,path,m,alpha3,ops){const fill=node.get("fill");const stroke=node.get("stroke");const fillAlpha=fill?alpha3*node.get("fillOpacity"):0;const strokeAlpha=stroke?alpha3*node.get("strokeOpacity"):0;const glow=node.get("glow");if(fillAlpha<=.002&&strokeAlpha<=.002&&glow<=0)return;const world=toWorld(node,path,m);const scale=matScale(m);const trimFrom=node.get("trimFrom"),trimTo=node.get("trimTo");let strokePath=world;if(trimFrom>0||trimTo<1)strokePath=trimPath(world,trimFrom,trimTo,node.get("trimEach"));if(strokePath.length===0&&fillAlpha<=.002)return;const dash=node.get("dash");const op={kind:"path",path:world,strokePath,fill:fillAlpha>.002?worldPaint(fill,m):null,fillAlpha,stroke:strokeAlpha>.002?worldPaint(stroke,m):null,strokeAlpha,strokeWidth:node.get("strokeWidth")*scale,cap:node.get("cap"),join:node.get("join"),dash:dash?dash.map(value=>value*scale):null,dashOffset:node.get("dashOffset")*scale,glow:glow*scale,glowColor:node.get("glowColor"),blend:node.get("blend"),node};if(op.stroke&&isGradient(op.stroke)&&op.stroke.type==="along")splitAlong(op,op.stroke,ops);else ops.push(op)}function splitAlong(op,paint,ops){ops.push({...op,stroke:null,strokeAlpha:0});const glowless={...op,fill:null,fillAlpha:0,glow:0};const length=pathLength(op.strokePath);const full=pathLength(op.path);if(length===0)return;const fraction=full>0?Math.min(1,length/full):1;const pieces=Math.min(MAX_ALONG_PIECES,Math.max(2,Math.ceil(length/ALONG_PIECE_LENGTH)));const overlap=.6/pieces;for(let i=0;i<pieces;i++){const from=i/pieces,to2=Math.min(1,(i+1)/pieces+overlap);const piece=trimPath(op.strokePath,from,to2);if(piece.length===0)continue;ops.push({...glowless,strokePath:piece,path:piece,stroke:sampleStops(paint.stops,(i+.5)/pieces*fraction),cap:i===0||i===pieces-1?op.cap:"butt"})}}function walk(node,parent,screen,alpha3,ops){if(!node.get("visible"))return;const opacity=node.get("opacity")*alpha3;if(opacity<=.002)return;const base=node.get("fixed")?screen:parent;const m=mul(base,node.localMatrix());const path=node.get("path");if(path&&path.length>0)emit(node,path,m,opacity,ops);const image2=node.get("image");if(image2)ops.push({kind:"image",image:image2,matrix:m,alpha:opacity});if(node.rawOps)node.rawOps(m,opacity,ops);if(node.draw){const built=node.draw(clockNow());if(built){const list3=Array.isArray(built)?built:[built];for(const child of list3)walk(child,m,screen,opacity,ops)}}const children=node.children;if(children.length===0)return;let sorted=false;for(let i=0;i<children.length;i++){if(children[i].get("z")!==0){sorted=true;break}}const ordered=sorted?children.map((child,index)=>({child,index,z:child.get("z")})).sort((a,b)=>a.z-b.z||a.index-b.index).map(entry=>entry.child):children;for(const child of ordered)walk(child,m,screen,opacity,ops)}function buildOps(root,camera,width,height){const screen=[1,0,0,1,width/2,height/2];const view=mul(screen,compose(0,0,-camera.rotation,camera.zoom,camera.zoom,camera.x,camera.y));const ops=[];walk(root,view,screen,1,ops);return ops}var GLOW_PASSES=7;function glowPasses(glow,width){const out=[];for(let i=GLOW_PASSES;i>=1;i--){const k=i/GLOW_PASSES;out.push({width:width+glow*2*k,alpha:.16*(1-k)*(1-k)+.018})}return out}function glowOf(op){if(op.glowColor)return op.glowColor;const paint=op.stroke??op.fill;if(!paint)return null;return isGradient(paint)?sampleStops(paint.stops,.5):paint}var dCache=new WeakMap;function pathData(path){let d=dCache.get(path);if(d===void 0){d=pathToD(path);dCache.set(path,d)}return d}function fmt2(value){return String(Math.round(value*1e3)/1e3)}function gradientDef(id,paint){const stops=paint.stops.map(([at,color])=>`<stop offset="${fmt2(at)}" stop-color="${css([color[0],color[1],color[2],1])}"${color[3]<1?` stop-opacity="${fmt2(color[3])}"`:""}/>`).join("");if(paint.type==="linear"){return`<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`}if(paint.type==="radial"){return`<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`}return""}function strokeAttrs(op){let attrs=` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;if(op.dash)attrs+=` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;return attrs}function escapeAttr(value){return value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}function frameToSvg(frame,options={}){const scale=options.scale??1;const w=frame.width,h=frame.height;const defs=[];const body=[];let gradientCount=0;const paintAttr=(paint,attr,alpha3)=>{if(isGradient(paint)){const id=`g${gradientCount++}`;defs.push(gradientDef(id,paint));return`${attr}="url(#${id})"${alpha3<1?` ${attr}-opacity="${fmt2(alpha3)}"`:""}`}const rgba=paint;const a=rgba[3]*alpha3;return`${attr}="${css([rgba[0],rgba[1],rgba[2],1])}"${a<1?` ${attr}-opacity="${fmt2(a)}"`:""}`};if(frame.background&&!options.transparent)body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);for(const op of frame.ops){if(op.kind==="image"){const m=op.matrix;body.push(`<image href="${escapeAttr(op.image.src)}" width="${op.image.width}" height="${op.image.height}" transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha<1?` opacity="${fmt2(op.alpha)}"`:""} preserveAspectRatio="none"/>`);continue}const style=op.blend!=="normal"?` style="mix-blend-mode:${op.blend}"`:"";if(op.glow>0){const color=glowOf(op);const glowD=pathData(op.strokePath.length?op.strokePath:op.path);if(color&&glowD){const base=Math.max(op.fillAlpha,op.strokeAlpha);const mode=frame.dark?' style="mix-blend-mode:screen"':"";const passes=glowPasses(op.glow,op.stroke?op.strokeWidth:0).map(pass=>`<path d="${glowD}" fill="none" stroke="${css([color[0],color[1],color[2],1])}" stroke-opacity="${fmt2(pass.alpha*base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");body.push(`<g${mode}>${passes}</g>`)}}if(op.fill&&op.stroke&&op.strokePath===op.path){body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)} ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);continue}if(op.fill)body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)}${style}/>`);if(op.stroke&&op.strokePath.length){body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`)}}const defsBlock=defs.length?`<defs>${defs.join("")}</defs>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${w*scale}" height="${h*scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`}var path2dCache=new WeakMap;function ringsToPath2D(path){let cached=path2dCache.get(path);if(cached)return cached;cached=new Path2D;for(const r of path){const p=r.p;if(p.length<2)continue;cached.moveTo(p[0],p[1]);if(r.straight)for(let o=2;o+5<p.length;o+=6)cached.lineTo(p[o+4],p[o+5]);else for(let o=2;o+5<p.length;o+=6)cached.bezierCurveTo(p[o],p[o+1],p[o+2],p[o+3],p[o+4],p[o+5]);if(r.closed)cached.closePath()}path2dCache.set(path,cached);return cached}function canvasPaint(ctx,paint){if(!isGradient(paint))return css(paint);const gradient=paint.type==="linear"?ctx.createLinearGradient(paint.from[0],paint.from[1],paint.to[0],paint.to[1]):paint.type==="radial"?ctx.createRadialGradient(paint.center[0],paint.center[1],0,paint.center[0],paint.center[1],paint.radius):null;if(!gradient)return css(sampleStops(paint.stops,.5));for(const[at,color]of paint.stops)gradient.addColorStop(at,css(color));return gradient}var BLEND={normal:"source-over",screen:"screen",multiply:"multiply",overlay:"overlay"};function paintFrame(ctx,frame,scale=1,images){ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over";ctx.clearRect(0,0,frame.width*scale,frame.height*scale);ctx.setTransform(scale,0,0,scale,0,0);if(frame.background){ctx.fillStyle=frame.background;ctx.fillRect(0,0,frame.width,frame.height)}for(const op of frame.ops){if(op.kind==="image"){const source=images?.(op.image);if(!source)continue;const m=op.matrix;ctx.save();ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]);ctx.globalAlpha=op.alpha;ctx.drawImage(source,0,0,op.image.width,op.image.height);ctx.restore();continue}ctx.globalCompositeOperation=BLEND[op.blend];if(op.glow>0){const color=glowOf(op);if(color){const base=Math.max(op.fillAlpha,op.strokeAlpha);const previous=ctx.globalCompositeOperation;if(frame.dark)ctx.globalCompositeOperation="screen";ctx.strokeStyle=css([color[0],color[1],color[2],1]);ctx.lineCap="round";ctx.lineJoin="round";ctx.setLineDash([]);const glowPath=ringsToPath2D(op.strokePath.length?op.strokePath:op.path);for(const pass of glowPasses(op.glow,op.stroke?op.strokeWidth:0)){ctx.globalAlpha=pass.alpha*base;ctx.lineWidth=pass.width;ctx.stroke(glowPath)}ctx.globalCompositeOperation=previous}}if(op.fill){ctx.globalAlpha=op.fillAlpha;ctx.fillStyle=canvasPaint(ctx,op.fill);ctx.fill(ringsToPath2D(op.path))}if(op.stroke&&op.strokePath.length){ctx.globalAlpha=op.strokeAlpha;ctx.strokeStyle=canvasPaint(ctx,op.stroke);ctx.lineWidth=op.strokeWidth;ctx.lineCap=op.cap;ctx.lineJoin=op.join;ctx.setLineDash(op.dash?[...op.dash]:[]);ctx.lineDashOffset=op.dashOffset;ctx.stroke(ringsToPath2D(op.strokePath))}}ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over"}function frameInkBounds(frame){let result=null;for(const op of frame.ops){if(op.kind!=="path")continue;const b=pathBounds(op.path);if(!b)continue;const pad2=op.stroke?op.strokeWidth/2:0;const next={x:b.x-pad2,y:b.y-pad2,width:b.width+pad2*2,height:b.height+pad2*2};if(!result)result=next;else{const x=Math.min(result.x,next.x),y=Math.min(result.y,next.y);result={x,y,width:Math.max(result.x+result.width,next.x+next.width)-x,height:Math.max(result.y+result.height,next.y+next.height)-y}}}return result}import{createRequire}from"module";import{cpus}from"os";import{Worker}from"worker_threads";import{fileURLToPath}from"url";var RASTER_WORKER_SOURCE=String.raw`
2
+ import{Arrow,ArrowMarkerDef,AttentionMatrix,AxisPlot,Badge,BadgePill,BarChart,Board,Box,CANVAS_ITEM_COMPONENT,CalloutCard,Canvas,CanvasItem,CanvasOverflowError,Card,ChartFrame,CodeBlock,Column,Comparison,Connector,DEFAULT_DENSITY,DENSITY_NAMES,DashedLine,DataTable,DataflowDiagram,DeploymentDiagram,DetailList,DiagramLegend,DonutChart,DotPoint,ELEMENT_SYMBOLS,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,SCENE_LIMITS,SCENE_RUNTIME_VERSION,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,Watermark,WaveDiagram,WindowFrame,analyzeAnimationCadence,assertDensity,canvas,captionsToSrt,chapterMetadata,colors,compositeColor,createPlotArea,cropPixels,cropRgbImage,cropRgbRaster,crossCorrelate2d,decodePng,decodeRgbPng,defineAnimation,defineDiagramIcon,defineIconRegistry,defineIllustration,densityOf,densityTokens,detectBackgroundColor,detectContentBounds,detectLayoutOverflow,detectOverflow,dotProduct,encodePng,encodeRgbPng,entropy,estimateTextWidth,evaluateSceneSource,extractRootJsx,findBareRootJsxStart,flattenRgbImage,formatMathText,formatTensorShape,gaussian,gaussianBlurRgb,gaussianKernel,geometryBounds,getColor,getFonts,getGradient,getReadableColor,getReadableTextColor,getReadableToneColor,getStyles,getThemeColors,getToneColor,getToneFill,getToneGradient,gradients,hasShadow,heatColor,hold,keyframe,lerpArray,loadAdditionalAsset,mapNumberLine,multiplyMatrices,normalizeVector,normalizeWatermark,parallel,parseDensity,pointAlongSamples,prepareScene,primitives_exports,reactionBalance,renderAnimationVideo,renderRgbaVideo,renderSceneFrame,renderSceneVideo,renderToBuffer,renderToPng,renderToPngWithOutput,renderToSvg,rgbChannel,routeOrthogonalGraph,routingSegmentBlocked,sampleAnimation,sampleAnimationFrame,sampleAnimationFrames,sampleFunction,sampleGaussian,sampleWave,satori,scaledDotProductAttention,scopeDensity,seededRandom,setDefaultDensity,setDensityResolver,stableSoftmax,statusColor,styles,sumForces,toneGradients,transposeMatrix,tween,typeOf,typography,videoFrameSchedule,waveValue,withColorAlpha,withDensity,withRenderContext,wrapWithBrand,wrapWithWatermark}from"./chunk-6N6P2GJG.js";import{renderMathSvg}from"./chunk-3F2VQ7NW.js";import{__export}from"./chunk-PSBF4TEK.js";import{existsSync as existsSync2}from"fs";import{mkdir as mkdir4,mkdtemp as mkdtemp2,readFile,readdir,rm as rm2,writeFile as writeFile4}from"fs/promises";import{randomUUID}from"crypto";import{createRequire as createRequire2,Module}from"module";import{tmpdir as tmpdir2}from"os";import{basename as basename2,dirname as dirname4,extname as extname2,isAbsolute,join as join3,relative as relative2,resolve as resolve3,sep}from"path";import{fileURLToPath as fileURLToPath2,pathToFileURL}from"url";import React,{isValidElement as isValidElement2}from"react";import{Resvg as Resvg2}from"@resvg/resvg-js";var index_exports={};__export(index_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,CHECK_DIAGNOSTIC_CODES:()=>CHECK_DIAGNOSTIC_CODES,CalloutCard:()=>CalloutCard,Canvas:()=>Canvas,CanvasItem:()=>CanvasItem,CanvasOverflowError:()=>CanvasOverflowError,Card:()=>Card,ChartFrame:()=>ChartFrame,CodeBlock:()=>CodeBlock,Column:()=>Column,Comparison:()=>Comparison,Connector:()=>Connector,DEFAULT_DENSITY:()=>DEFAULT_DENSITY,DENSITY_NAMES:()=>DENSITY_NAMES,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,SCENE_LIMITS:()=>SCENE_LIMITS,SCENE_RUNTIME_VERSION:()=>SCENE_RUNTIME_VERSION,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,Watermark:()=>Watermark,WaveDiagram:()=>WaveDiagram,WindowFrame:()=>WindowFrame,analyzeAnimationCadence:()=>analyzeAnimationCadence,arcSwap:()=>arcSwap,assertDensity:()=>assertDensity,assertTokenHistoryTransition:()=>assertTokenHistoryTransition,byteDifferenceState:()=>byteDifferenceState,cameraSvgTransform:()=>cameraSvgTransform,canvas:()=>canvas,captionsToSrt:()=>captionsToSrt,categoricalSampling:()=>categoricalSampling,chapterMetadata:()=>chapterMetadata,checkFrame:()=>checkFrame,colors:()=>colors,compareByteSequences:()=>compareByteSequences,compositeColor:()=>compositeColor,createCanvasComponents:()=>createCanvasComponents,createCueTrack:()=>createCueTrack,createFocusDirector:()=>createFocusDirector,createPlotArea:()=>createPlotArea,createPolylineMorph:()=>createPolylineMorph,createTeachingByteDifference:()=>createTeachingByteDifference,createTeachingCanvas:()=>createTeachingCanvas,createTeachingCategoricalSampling:()=>createTeachingCategoricalSampling,createTeachingFocus:()=>createTeachingFocus,createTeachingRoutedTransfer:()=>createTeachingRoutedTransfer,createTeachingTokenHistory:()=>createTeachingTokenHistory,createTeachingValueChange:()=>createTeachingValueChange,createTeachingVectorAccumulation:()=>createTeachingVectorAccumulation,cropPixels:()=>cropPixels,cropRgbImage:()=>cropRgbImage,cropRgbRaster:()=>cropRgbRaster,crossCorrelate2d:()=>crossCorrelate2d,decodeRgbPng:()=>decodeRgbPng,defineAnimation:()=>defineAnimation,defineDiagramIcon:()=>defineDiagramIcon,defineIconRegistry:()=>defineIconRegistry,defineIllustration:()=>defineIllustration,densityOf:()=>densityOf,densityTokens:()=>densityTokens,detectBackgroundColor:()=>detectBackgroundColor,detectContentBounds:()=>detectContentBounds,detectLayoutOverflow:()=>detectLayoutOverflow,detectOverflow:()=>detectOverflow,dotProduct:()=>dotProduct,encodeRgbPng:()=>encodeRgbPng,entropy:()=>entropy,escapedByte:()=>escapedByte,estimateTextWidth:()=>estimateTextWidth,evaluateSceneSource:()=>evaluateSceneSource,flattenRgbImage:()=>flattenRgbImage,formatMathText:()=>formatMathText,formatTensorShape:()=>formatTensorShape,gaussian:()=>gaussian,gaussianBlurRgb:()=>gaussianBlurRgb,gaussianKernel:()=>gaussianKernel,geometryBounds:()=>geometryBounds,getColor:()=>getColor,getFonts:()=>getFonts,getGradient:()=>getGradient,getReadableColor:()=>getReadableColor,getReadableTextColor:()=>getReadableTextColor,getReadableToneColor:()=>getReadableToneColor,getStyles:()=>getStyles,getThemeColors:()=>getThemeColors,getToneColor:()=>getToneColor,getToneFill:()=>getToneFill,getToneGradient:()=>getToneGradient,gradients:()=>gradients,hasShadow:()=>hasShadow,heatColor:()=>heatColor,hold:()=>hold,importD2Graph:()=>importD2Graph,importMermaidGraph:()=>importMermaidGraph,interpolateCamera:()=>interpolateCamera,keyframe:()=>keyframe,layoutAllocation:()=>layoutAllocation,layoutByteDifference:()=>layoutByteDifference,layoutCellGrid:()=>layoutCellGrid,layoutTokenRow:()=>layoutTokenRow,lerpArray:()=>lerpArray,loadAdditionalAsset:()=>loadAdditionalAsset,mapNumberLine:()=>mapNumberLine,mergeFocusRegions:()=>mergeFocusRegions,morphPolyline:()=>morphPolyline,multiplyMatrices:()=>multiplyMatrices,normalizeVector:()=>normalizeVector,normalizeWatermark:()=>normalizeWatermark,parallel:()=>parallel,parseDensity:()=>parseDensity,planTeachingRoutedTransfer:()=>planTeachingRoutedTransfer,pointAlongPath:()=>pointAlongPath,prepareScene:()=>prepareScene,projectWorldPoint:()=>projectWorldPoint,reactionBalance:()=>reactionBalance,renderAnimatedGif:()=>renderAnimatedGif,renderAnimatedGifWithOutput:()=>renderAnimatedGifWithOutput,renderAnimationGif:()=>renderAnimationGif,renderAnimationGifWithOutput:()=>renderAnimationGifWithOutput,renderAnimationVideo:()=>renderAnimationVideo,renderMathSvg:()=>renderMathSvg,renderRgbaVideo:()=>renderRgbaVideo,renderSceneFrame:()=>renderSceneFrame,renderSceneVideo:()=>renderSceneVideo,renderToBuffer:()=>renderToBuffer,renderToPng:()=>renderToPng,renderToPngWithOutput:()=>renderToPngWithOutput,renderToSvg:()=>renderToSvg,rgbChannel:()=>rgbChannel,sampleAnimation:()=>sampleAnimation,sampleAnimationFrame:()=>sampleAnimationFrame,sampleAnimationFrames:()=>sampleAnimationFrames,sampleFunction:()=>sampleFunction,sampleGaussian:()=>sampleGaussian,sampleWave:()=>sampleWave,scaledDotProductAttention:()=>scaledDotProductAttention,scopeDensity:()=>scopeDensity,seededRandom:()=>seededRandom,setDefaultDensity:()=>setDefaultDensity,setDensityResolver:()=>setDensityResolver,smoothstep:()=>smoothstep,stableSoftmax:()=>stableSoftmax,statusColor:()=>statusColor,styles:()=>styles,sumForces:()=>sumForces,tokenHistoryState:()=>tokenHistoryState,toneGradients:()=>toneGradients,tracePolyline:()=>tracePolyline,transposeMatrix:()=>transposeMatrix,tween:()=>tween,typeOf:()=>typeOf,typography:()=>typography,valueChangeState:()=>valueChangeState,videoFrameSchedule:()=>videoFrameSchedule,waveValue:()=>waveValue,weightedVectorState:()=>weightedVectorState,withColorAlpha:()=>withColorAlpha,withDensity:()=>withDensity,wrapWithBrand:()=>wrapWithBrand,wrapWithWatermark:()=>wrapWithWatermark});import{Resvg}from"@resvg/resvg-js";import{mkdir,writeFile}from"fs/promises";import{dirname}from"path";import*as gifenc from"gifenc";import parseCssColor from"parse-css-color";function resolveGifenc(api){if(typeof api.GIFEncoder==="function"&&typeof api.applyPalette==="function"&&typeof api.quantize==="function"){return api}const fallback=api.default;if(fallback&&typeof fallback.GIFEncoder==="function"&&typeof fallback.applyPalette==="function"&&typeof fallback.quantize==="function"){return fallback}throw new Error("gifenc exports could not be resolved")}var{GIFEncoder,applyPalette,quantize}=resolveGifenc(gifenc);var MAX_PALETTE_SAMPLE_PIXELS=1e6;var MAX_TIMELINE_PALETTE_FRAMES=24;async function renderToPixels(element,width,height,scale,theme,background,overflowContext){const fonts2=await getFonts();const layoutNodes=[];const svg=await withRenderContext({background},()=>satori(element,{width,height,fonts:fonts2,loadAdditionalAsset,onNodeDetected:overflowContext?node=>layoutNodes.push(node):void 0}));const resvg=new Resvg(svg,{fitTo:{mode:"width",value:width*scale},background:rasterBackground(background,theme)});const rendered=resvg.render();const output={pixels:rendered.pixels,width:rendered.width,height:rendered.height};if(overflowContext){const overflow=detectLayoutOverflow2(layoutNodes,width,height);if(overflow.overflows)throw new CanvasOverflowError(width,height,overflow,overflowContext)}return output}function detectLayoutOverflow2(nodes,width,height){const epsilon=.5;const edges={top:nodes.some(node=>node.top<-epsilon),right:nodes.some(node=>node.left+node.width>width+epsilon),bottom:nodes.some(node=>node.top+node.height>height+epsilon),left:nodes.some(node=>node.left<-epsilon)};const names=Object.entries(edges).filter(([,overflows])=>overflows).map(([edge])=>edge);return{overflows:names.length>0,edges,message:names.length?`Content overflows canvas at: ${names.join(", ")}. Increase the illustration dimensions.`:""}}function blendPixels(base,overlay,opacity){const result=new Uint8Array(base.length);const inverse=1-opacity;for(let index=0;index<base.length;index+=4){const baseAlpha=base[index+3]/255*inverse;const overlayAlpha=overlay[index+3]/255*opacity;const outputAlpha=baseAlpha+overlayAlpha;if(outputAlpha===0)continue;result[index]=Math.round((base[index]*baseAlpha+overlay[index]*overlayAlpha)/outputAlpha);result[index+1]=Math.round((base[index+1]*baseAlpha+overlay[index+1]*overlayAlpha)/outputAlpha);result[index+2]=Math.round((base[index+2]*baseAlpha+overlay[index+2]*overlayAlpha)/outputAlpha);result[index+3]=Math.round(outputAlpha*255)}return result}function hslToRgb(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/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=l-chroma/2;return[Math.round((channels[0]+offset)*255),Math.round((channels[1]+offset)*255),Math.round((channels[2]+offset)*255)]}function colorForBackground(background,theme){const value=background==="theme"?getThemeColors(theme).bg:background;const parsed=parseCssColor(value);if(!parsed)throw new Error(`Invalid animation background color: ${value}`);const[r,g,b]=parsed.type==="hsl"?hslToRgb(parsed.values[0],parsed.values[1],parsed.values[2]):[parsed.values[0],parsed.values[1],parsed.values[2]];return{r,g,b,a:Math.round(parsed.alpha*255)}}function rasterBackground(background,theme){const{r,g,b,a}=colorForBackground(background,theme);return`rgba(${r}, ${g}, ${b}, ${a/255})`}function backgroundPixels(width,height,theme,background){const buffer=new Uint8Array(width*height*4);const color=colorForBackground(background,theme);for(let index=0;index<buffer.length;index+=4){buffer[index]=color.r;buffer[index+1]=color.g;buffer[index+2]=color.b;buffer[index+3]=color.a}return buffer}function samplePixels(pixels,limit){const pixelCount=pixels.length/4;if(pixelCount<=limit)return pixels.slice();const sample=new Uint8Array(limit*4);for(let index=0;index<limit;index+=1){const sourcePixel=Math.floor((index+.5)*pixelCount/limit);sample.set(pixels.subarray(sourcePixel*4,sourcePixel*4+4),index*4)}return sample}function sharedPalette(frames){if(frames.length===0)throw new Error("No GIF frames to quantize");const pixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/frames.length));const samples=frames.map(frame=>samplePixels(frame.pixels,pixelsPerFrame));const length=samples.reduce((total,sample)=>total+sample.length,0);const combined=new Uint8Array(length);let offset=0;for(const sample of samples){combined.set(sample,offset);offset+=sample.length}return quantize(combined,256,{format:"rgba4444",oneBitAlpha:true})}function changedBounds(previous,current,width,height){let minX=width;let minY=height;let maxX=-1;let maxY=-1;for(let index=0;index<current.length;index+=4){if(previous[index]===current[index]&&previous[index+1]===current[index+1]&&previous[index+2]===current[index+2]&&previous[index+3]===current[index+3])continue;const pixel=index/4;const x=pixel%width;const y=Math.floor(pixel/width);minX=Math.min(minX,x);minY=Math.min(minY,y);maxX=Math.max(maxX,x);maxY=Math.max(maxY,y)}return maxX<minX?void 0:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropFramePixels(pixels,canvasWidth,region){const output=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y+=1){const source=((region.y+y)*canvasWidth+region.x)*4;output.set(pixels.subarray(source,source+region.width*4),y*region.width*4)}return output}function deltaPixelFrame(frame,previous,enabled){if(!enabled||!previous)return frame;const bounds4=changedBounds(previous,frame.pixels,frame.width,frame.height);if(!bounds4||bounds4.width===frame.width&&bounds4.height===frame.height)return frame;return{...frame,x:bounds4.x,y:bounds4.y,delta:true,width:bounds4.width,height:bounds4.height,pixels:cropFramePixels(frame.pixels,frame.width,bounds4)}}function encodeGif(frames,loop,deltaFrames){if(frames.length===0)throw new Error("No GIF frames to encode");const firstFrame=frames[0];const gif=GIFEncoder();const palette=sharedPalette(frames);let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;let pending2;for(const frame of frames){if(frame.width!==firstFrame.width||frame.height!==firstFrame.height){throw new Error("All GIF frames must have matching dimensions")}if(pending2&&pixelsEqual(pending2.pixels,frame.pixels)){pending2.delay+=frame.delay;continue}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;first=false}pending2={...frame}}if(pending2){const encoded=deltaPixelFrame(pending2,previousPixels,deltaFrames);writeGifFrame(gif,encoded,loop,palette,first,deltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1}gif.finish();return{bytes:gif.bytes(),encodedFrameCount,deltaFrameCount}}var DEFAULT_TRANSITION_FPS=20;var MIN_TRANSITION_FRAMES=3;function sceneTransitionFps(fps){const resolved=fps??DEFAULT_TRANSITION_FPS;if(!Number.isInteger(resolved)||resolved<1||resolved>50){throw new Error("Animation fps must be an integer from 1 to 50")}return resolved}function transitionFrameDelays(duration,count){const totalCentiseconds=Math.max(count*2,Math.round(duration/10));let previous=0;return Array.from({length:count},(_,index)=>{const cumulative=Math.round((index+1)/count*totalCentiseconds);const delay2=(cumulative-previous)*10;previous=cumulative;return delay2})}async function scenesToFrames(scenes,options){if(scenes.length===0)throw new Error("Animated GIF requires at least one scene");for(const[index,scene]of scenes.entries()){if(!Number.isFinite(scene.duration)||scene.duration<=0){throw new Error(`Animated scene ${index+1} duration must be a positive finite number`)}if(scene.transition!=null&&!["none","fade","appear"].includes(scene.transition)){throw new Error(`Animated scene ${index+1} has unknown transition "${scene.transition}"`)}if(scene.transitionDuration!=null&&(!Number.isFinite(scene.transitionDuration)||scene.transitionDuration<=0)){throw new Error(`Animated scene ${index+1} transitionDuration must be a positive finite number`)}}const fps=sceneTransitionFps(options.fps);const renderedScenes=await Promise.all(scenes.map((scene,sceneIndex)=>{const watermark=options.watermark??options.brand;const element=watermark?wrapWithWatermark(scene.element,options.width,options.height,options.theme,watermark):scene.element;return renderToPixels(element,options.width,options.height,options.scale,options.theme,options.background,{sceneIndex,label:scene.label})}));const frames=[];const scaledWidth=renderedScenes[0].width;const scaledHeight=renderedScenes[0].height;for(let index=0;index<scenes.length;index+=1){const scene=scenes[index];const current=renderedScenes[index];const transition=scene.transition??"none";const transitionDuration=scene.transitionDuration??400;if(transition!=="none"){const previous=index>0?renderedScenes[index-1]:{pixels:backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),width:scaledWidth,height:scaledHeight};const transitionFrames=Math.max(MIN_TRANSITION_FRAMES,Math.round(transitionDuration/1e3*fps));const frameDelays=transitionFrameDelays(transitionDuration,transitionFrames);for(let frameIndex=0;frameIndex<transitionFrames;frameIndex+=1){const amount2=(frameIndex+1)/transitionFrames;const pixels=transition==="fade"?blendPixels(previous.pixels,current.pixels,amount2):blendPixels(backgroundPixels(scaledWidth,scaledHeight,options.theme,options.background),current.pixels,amount2);frames.push({pixels,delay:frameDelays[frameIndex],width:scaledWidth,height:scaledHeight})}}frames.push({pixels:current.pixels,delay:scene.duration,width:scaledWidth,height:scaledHeight})}return frames}async function renderAnimatedGif(scenes,options){if(!Array.isArray(scenes)){await renderAnimationGifWithOutput(scenes,options)}else{await renderAnimatedGifWithOutput(scenes,options)}}async function renderAnimatedGifWithOutput(scenes,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};await mkdir(dirname(options.outputPath),{recursive:true});const frames=await scenesToFrames(scenes,normalized);const encoded=encodeGif(frames,normalized.loop,normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255);await writeFile(options.outputPath,encoded.bytes);return{width:frames[0].width,height:frames[0].height,frameCount:frames.length,encodedFrameCount:encoded.encodedFrameCount,deltaFrameCount:encoded.deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.delay,0),bytes:encoded.bytes.length}}function pixelsEqual(left,right){if(left.length!==right.length)return false;for(let index=0;index<left.length;index+=1){if(left[index]!==right[index])return false}return true}function writeGifFrame(gif,frame,loop,palette,first,delta){const index=applyPalette(frame.pixels,palette,"rgba4444");const transparentIndex=palette.findIndex(color=>color[3]===0);let remainingDelay=frame.delay;let includePalette=first;do{const delay2=Math.min(655350,remainingDelay);const frameStart=gif.bytesView().length;gif.writeFrame(index,frame.width,frame.height,{...includePalette?{palette}:{},delay:Math.max(20,delay2),repeat:loop,transparent:transparentIndex>=0,transparentIndex,dispose:delta&&frame.delta?1:void 0});if((frame.x??0)!==0||(frame.y??0)!==0){const bytes=gif.bytesView();const descriptor=frameStart+8;if(bytes[descriptor]!==44)throw new Error("GIF image descriptor was not written");const x=frame.x??0;const y=frame.y??0;bytes[descriptor+1]=x&255;bytes[descriptor+2]=x>>8&255;bytes[descriptor+3]=y&255;bytes[descriptor+4]=y>>8&255}includePalette=false;remainingDelay-=delay2}while(remainingDelay>0)}function representativeFrameIndexes(frameCount){const count=Math.min(frameCount,MAX_TIMELINE_PALETTE_FRAMES);if(count===frameCount)return Array.from({length:count},(_,index)=>index);return Array.from({length:count},(_,index)=>Math.round(index*(frameCount-1)/(count-1)))}async function renderAnimationGif(animation,options){await renderAnimationGifWithOutput(animation,options)}async function renderAnimationGifWithOutput(animation,options){const normalized={...options,loop:options.loop??0,scale:options.scale??1,theme:options.theme??"dark",background:options.background??"theme",deltaFrames:options.deltaFrames??true};const frames=sampleAnimationFrames(animation,{fps:options.fps});const paletteFrames=[];const paletteIndexes=representativeFrameIndexes(frames.length);const palettePixelsPerFrame=Math.max(1,Math.floor(MAX_PALETTE_SAMPLE_PIXELS/paletteIndexes.length));for(const index of paletteIndexes){const sampled=frames[index];const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background);paletteFrames.push({...rendered,pixels:samplePixels(rendered.pixels,palettePixelsPerFrame),delay:sampled.frame.delay})}const palette=sharedPalette(paletteFrames);const gif=GIFEncoder();let pending2;let dimensions;let first=true;let encodedFrameCount=0;let deltaFrameCount=0;let previousPixels;const useDeltaFrames=normalized.deltaFrames&&colorForBackground(normalized.background,normalized.theme).a===255;for(const sampled of frames){const rawElement=animation.render(sampled.state,sampled.frame);const watermark=normalized.watermark??normalized.brand;const element=watermark?wrapWithWatermark(rawElement,normalized.width,normalized.height,normalized.theme,watermark):rawElement;const rendered=await renderToPixels(element,normalized.width,normalized.height,normalized.scale,normalized.theme,normalized.background,{frameIndex:sampled.frame.index,frameCount:sampled.frame.count,time:sampled.frame.time,label:sampled.frame.label});dimensions??={width:rendered.width,height:rendered.height};if(rendered.width!==dimensions.width||rendered.height!==dimensions.height){throw new Error("All GIF frames must have matching dimensions")}if(pending2&&pixelsEqual(pending2.pixels,rendered.pixels)){pending2.delay+=sampled.frame.delay;continue}if(pending2){const encoded2=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded2,normalized.loop,palette,first,useDeltaFrames);previousPixels=pending2.pixels;encodedFrameCount+=1;if(encoded2.delta)deltaFrameCount+=1;first=false}pending2={...rendered,delay:sampled.frame.delay}}if(!pending2||!dimensions)throw new Error("Animated GIF requires at least one frame");const encoded=deltaPixelFrame(pending2,previousPixels,useDeltaFrames);writeGifFrame(gif,encoded,normalized.loop,palette,first,useDeltaFrames);encodedFrameCount+=1;if(encoded.delta)deltaFrameCount+=1;gif.finish();await mkdir(dirname(options.outputPath),{recursive:true});const bytes=gif.bytes();await writeFile(options.outputPath,bytes);return{...dimensions,frameCount:frames.length,encodedFrameCount,deltaFrameCount,duration:frames.reduce((total,frame)=>total+frame.frame.delay,0),bytes:bytes.length}}var DEFAULT_ARC_LIFT=80;function assertFiniteProgress(progress){if(!Number.isFinite(progress))throw new Error("Motion progress must be finite")}function clampProgress(progress){assertFiniteProgress(progress);return Math.max(0,Math.min(1,progress))}function assertPoint(point,context){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} coordinates must be finite`)}}function interpolate(from,to2,progress){return{x:from.x*(1-progress)+to2.x*progress,y:from.y*(1-progress)+to2.y*progress}}function smoothstep(progress){const amount2=clampProgress(progress);return amount2*amount2*(3-2*amount2)}function arcSwap(from,to2,progress,options={}){assertPoint(from,"Arc swap start");assertPoint(to2,"Arc swap end");const amount2=clampProgress(progress);const lift=options.lift??DEFAULT_ARC_LIFT;if(!Number.isFinite(lift))throw new Error("Arc swap lift must be finite");if(amount2===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(amount2===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Motion easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];if(t===1)return[{x:to2.x,y:to2.y},{x:from.x,y:from.y}];const dx=to2.x-from.x;const dy=to2.y-from.y;const length=Math.hypot(dx,dy);if(!Number.isFinite(length))throw new Error("Arc swap distance must be finite");if(length===0)return[{x:from.x,y:from.y},{x:to2.x,y:to2.y}];const normalX=-dy/length;const normalY=dx/length;const arcHeight=4*(1-t)*t*lift;const firstBase=interpolate(from,to2,t);const secondBase=interpolate(to2,from,t);const first={x:firstBase.x+normalX*arcHeight,y:firstBase.y+normalY*arcHeight};const second={x:secondBase.x-normalX*arcHeight,y:secondBase.y-normalY*arcHeight};assertPoint(first,"Arc swap result");assertPoint(second,"Arc swap result");return[first,second]}function pathLengths(points){const lengths=[];let total=0;for(let index=0;index<points.length;index+=1){const point=points[index];assertPoint(point,`Path point ${index}`);if(index===0)continue;const previous=points[index-1];const length=Math.hypot(point.x-previous.x,point.y-previous.y);if(!Number.isFinite(length))throw new Error("Path segment length must be finite");total+=length;if(!Number.isFinite(total))throw new Error("Path length must be finite");lengths.push(length)}return lengths}function tracePolyline(points,progress){const amount2=clampProgress(progress);if(points.length===0)return[];const lengths=pathLengths(points);if(amount2===1)return points.map(({x,y})=>({x,y}));const traced2=[{x:points[0].x,y:points[0].y}];if(amount2===0||lengths.length===0)return traced2;const total=lengths.reduce((sum,length)=>sum+length,0);if(total===0)return traced2;const target=total*amount2;let travelled=0;for(let index=0;index<lengths.length;index+=1){const segmentLength=lengths[index];const next=points[index+1];if(segmentLength===0)continue;const segmentEnd=travelled+segmentLength;if(target>=segmentEnd){traced2.push({x:next.x,y:next.y});travelled=segmentEnd;continue}const segmentProgress=(target-travelled)/segmentLength;const point=interpolate(points[index],next,segmentProgress);assertPoint(point,"Polyline trace result");const previous=traced2[traced2.length-1];if(point.x!==previous.x||point.y!==previous.y)traced2.push(point);return traced2}return traced2}function pointAlongPath(points,progress){if(points.length===0)throw new Error("Cannot find a point along an empty path");const traced2=tracePolyline(points,progress);return{...traced2[traced2.length-1]}}function finite(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative(value,name){finite(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function positive(value,name){finite(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function normalizedOpacity(value,name="Canvas opacity"){finite(value,name);return Math.max(0,Math.min(1,value))}function validateBounds(bounds4){finite(bounds4.x,"Canvas x");finite(bounds4.y,"Canvas y");positive(bounds4.width,"Canvas width");positive(bounds4.height,"Canvas height");nonnegative(bounds4.radius??14,"Canvas radius")}function layoutTokenRow(values,options={}){const{advance=24,gap=16,minWidth=64,paddingX=17,width}=options;nonnegative(advance,"Token advance");nonnegative(gap,"Token gap");positive(minWidth,"Token minimum width");nonnegative(paddingX,"Token horizontal padding");if(width!==void 0)positive(width,"Token width");if(options.x!==void 0)finite(options.x,"Token x");if(options.centerX!==void 0)finite(options.centerX,"Token center x");const items=values.map(value=>{const text2=String(value);return{text:text2,x:0,width:width??Math.max(minWidth,text2.length*advance+2*paddingX)}});const totalWidth=items.reduce((total,item)=>total+item.width,0)+Math.max(0,items.length-1)*gap;let x=options.x??(options.centerX??0)-totalWidth/2;finite(x,"Token row origin");for(const item of items){item.x=x;x+=item.width+gap;finite(x,"Token row extent")}return items}function createCanvasComponents(painter){function fade2(alpha3,draw2){const amount2=normalizedOpacity(alpha3);if(amount2>0)painter.opacity(amount2,draw2)}function panel(options,draw2){validateBounds(options);const{x,y,width,height,fill,stroke,radius=14,padding=10,id,scope="container",opacity=1}=options;nonnegative(padding,"Canvas padding");const alpha3=normalizedOpacity(opacity);if(scope!=="container"&&scope!=="label")throw new Error("Canvas scope must be container or label");let shape2;const paint=()=>painter.opacity(alpha3,()=>{shape2=painter.rect(x,y,width,height,fill,stroke,radius);if(draw2){const bounds4={x,y,width,height,radius};const scopeOptions={padding,id};if(scope==="label")painter.labelScope(bounds4,draw2,scopeOptions);else painter.container(bounds4,draw2,scopeOptions)}});if(options.focusTarget&&painter.target)painter.target(options.focusTarget,paint);else paint();return shape2}function card(options){const{label,x,y,width,height,fontSize=32,font="sans",textColor,baselineOffset=fontSize*.34,labelOpacity=1}=options;positive(fontSize,"Canvas font size");finite(baselineOffset,"Canvas text baseline offset");const labelAlpha=normalizedOpacity(labelOpacity,"Canvas label opacity");return panel(options,()=>{fade2(labelAlpha,()=>{painter.text(String(label),x+width/2,y+height/2+baselineOffset,fontSize,textColor,"center",font)})})}function matrix2(options){const{values,x,y,cellSize=112,gap=8,inset:inset2=0,format=String,style={},cellStyle}=options;finite(x,"Matrix x");finite(y,"Matrix y");positive(cellSize,"Matrix cell size");nonnegative(gap,"Matrix gap");finite(inset2,"Matrix inset");if(gap>=cellSize)throw new Error("Matrix gap must be smaller than cell size");const columns=values[0]?.length??0;for(const row of values){if(!Array.isArray(row)||row.length!==columns)throw new Error("Canvas matrix rows must be rectangular")}const shapes=[];for(let row=0;row<values.length;row+=1){for(let column=0;column<columns;column+=1){const value=values[row][column];const cell={...style,...cellStyle?.(value,row,column)};finite(cell.opacity??1,"Canvas opacity");if((cell.opacity??1)<=0)continue;const shape2=card({...cell,x:x+column*cellSize+inset2,y:y+row*cellSize+inset2,width:cellSize-gap,height:cellSize-gap,label:format(value,row,column)});shapes.push(shape2)}}return shapes}function tokenRow(options){const{values,y,height=68,reveal:reveal2=1,opacity=1,...style}=options;finite(y,"Token row y");positive(height,"Token height");finite(reveal2,"Token reveal");const alpha3=normalizedOpacity(opacity);const items=layoutTokenRow(values,options);const shapes=[];for(let index=0;index<items.length;index+=1){const amount2=Math.max(0,Math.min(1,reveal2*items.length-index))*alpha3;if(amount2<=0)continue;const{text:label,x,width}=items[index];const shape2=card({...style,label,x,y,width,height,opacity:amount2});shapes.push(shape2)}return shapes}function particle(options){const{points,progress,radius=9,fill,stroke,strokeWidth=3}=options;finite(progress,"Particle progress");positive(radius,"Particle radius");nonnegative(strokeWidth,"Particle stroke width");if(progress<=0||progress>=1)return null;const point=pointAlongPath(points,progress);painter.circle(point.x,point.y,radius,fill,stroke,strokeWidth);return point}return{panel,card,matrix:matrix2,tokenRow,particle,fade:fade2}}function nonnegative2(value,name){if(!Number.isFinite(value)||value<0)throw new Error(`${name} must be finite and nonnegative`)}function alpha(value){if(!Number.isFinite(value))throw new Error("Transfer opacity must be finite");return Math.max(0,Math.min(1,value))}function bounds(shape2){if(![shape2.x,shape2.y,shape2.width,shape2.height].every(Number.isFinite)||shape2.width<=0||shape2.height<=0){throw new Error("Transfer endpoints require finite positive rectangular bounds")}nonnegative2(shape2.radius??0,"Transfer corner radius")}function center(shape2){return{x:shape2.x+shape2.width/2,y:shape2.y+shape2.height/2}}function edgeDistance(shape2,ux,uy){const halfWidth=shape2.width/2,halfHeight=shape2.height/2;const limit=Math.min(ux===0?Infinity:halfWidth/Math.abs(ux),uy===0?Infinity:halfHeight/Math.abs(uy));const radius=Math.min(shape2.radius??0,halfWidth,halfHeight);if(radius===0)return limit;const outside=distance=>Math.hypot(Math.max(0,Math.abs(ux*distance)-(halfWidth-radius)),Math.max(0,Math.abs(uy*distance)-(halfHeight-radius)))>radius;if(!outside(limit))return limit;let low=0,high=limit;for(let index=0;index<32;index+=1){const middle=(low+high)/2;if(outside(middle))high=middle;else low=middle}return low}function safeGap(shape2,ux,uy,clearance,edge){const expanded2=Math.min(ux===0?Infinity:(shape2.width/2+clearance)/Math.abs(ux),uy===0?Infinity:(shape2.height/2+clearance)/Math.abs(uy));return expanded2-edge}function createTeachingTransfer(painter){return options=>{const{source,target,color="#63DEEC",width=3,margin=2,progress,particle}=options;bounds(source.shape);bounds(target.shape);nonnegative2(width,"Transfer stroke width");if(width===0)throw new Error("Transfer stroke width must be positive");nonnegative2(margin,"Transfer margin");const opacity=Math.min(alpha(source.opacity),alpha(target.opacity),alpha(options.opacity??1));for(const gap of[options.gap,options.fromGap,options.toGap]){if(gap!==void 0)nonnegative2(gap,"Transfer gap")}if(progress!==void 0&&!Number.isFinite(progress))throw new Error("Transfer progress must be finite");if(particle&&progress===void 0)throw new Error("Transfer particle requires progress");const radius=particle?.radius??7,strokeWidth=particle?.strokeWidth??3;nonnegative2(radius,"Transfer particle radius");if(radius===0)throw new Error("Transfer particle radius must be positive");nonnegative2(strokeWidth,"Transfer particle stroke width");if(opacity===0)return null;const a=center(source.shape),z=center(target.shape);const distance=Math.hypot(z.x-a.x,z.y-a.y);if(!Number.isFinite(distance)||distance===0)throw new Error("Transfer endpoints must have distinct finite centers");const ux=(z.x-a.x)/distance,uy=(z.y-a.y)/distance;const sourceEdge=edgeDistance(source.shape,ux,uy),targetEdge=edgeDistance(target.shape,ux,uy);const markerRadius=progress===void 0?0:radius+(particle?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerRadius)+margin;const fromGap=Math.max(options.fromGap??options.gap??0,safeGap(source.shape,ux,uy,clearance,sourceEdge));const toGap=Math.max(options.toGap??options.gap??0,safeGap(target.shape,ux,uy,clearance,targetEdge));if(distance<=sourceEdge+targetEdge+fromGap+toGap)throw new Error("Transfer endpoints leave no room for the requested clearance");let route;painter.opacity(opacity,()=>{route=painter.connect(source.shape,target.shape,{color,width,fromGap,toGap});if(progress!==void 0&&progress>0&&progress<1){const x=route.from.x*(1-progress)+route.to.x*progress;const y=route.from.y*(1-progress)+route.to.y*progress;painter.circle(x,y,radius,particle?.fill??color,particle?.stroke,strokeWidth)}});return route}}function positive2(value,name){if(!Number.isFinite(value)||value<=0)throw new Error(`${name} must be finite and positive`)}function layoutCellGrid(options){const{x,y,width,height,rows,columns}=options;if(![x,y,x+width,y+height].every(Number.isFinite))throw new Error("Grid bounds must be finite");positive2(width,"Grid width");positive2(height,"Grid height");if(![rows,columns,rows*columns].every(Number.isSafeInteger)||rows<=0||columns<=0){throw new Error("Grid rows and columns must be positive safe integers")}const bounds4={x,y,width,height};const cells=Array.from({length:rows},(_,row)=>Array.from({length:columns},(_2,column)=>({x:x+column*width/columns,y:y+row*height/rows,width:width/columns,height:height/rows})));return{bounds:bounds4,cells,cell(row,column){if(!Number.isSafeInteger(row)||!Number.isSafeInteger(column)||row<0||row>=rows||column<0||column>=columns){throw new Error("Grid cell index is outside the grid")}return cells[row][column]}}}function createTeachingGrid(painter){const components=createCanvasComponents(painter);return options=>{const layout=layoutCellGrid(options);const{x,y,width,height,rows,columns,fill="#18283B",stroke="#63DEEC",lineWidth=1,labels,highlights=[],fontSize=28,textColor="#FFFFFF",padding=4}=options;positive2(lineWidth,"Grid line width");if(lineWidth>=Math.min(width/columns,height/rows))throw new Error("Grid line width must be smaller than a cell");positive2(fontSize,"Grid font size");if(!Number.isFinite(padding)||padding<0)throw new Error("Grid padding must be finite and nonnegative");if(labels&&(labels.length!==rows||labels.some(row=>row.length!==columns))){throw new Error("Grid labels must match rows and columns")}for(const highlight of highlights){layout.cell(highlight.row,highlight.column);if(!Number.isFinite(highlight.opacity??1))throw new Error("Grid highlight opacity must be finite")}const cellFocusTarget=painter.target?options.cellFocusTarget:void 0;const shape2=components.panel({...layout.bounds,fill:cellFocusTarget?"transparent":fill,stroke,radius:0,padding:0},()=>{const drawLabel=(r,column)=>{if(!labels)return;const cell=layout.cell(r,column),value=String(labels[r][column]);const baseline=cell.y+cell.height/2+fontSize*.34-(value.split("\n").length-1)*fontSize*.7;painter.labelScope(cell,()=>painter.text(value,cell.x+cell.width/2,baseline,fontSize,textColor,"center"),{padding})};if(cellFocusTarget)for(let row=0;row<rows;row++)for(let column=0;column<columns;column++){const named=cellFocusTarget(row,column),ids=typeof named==="string"?[named]:named??[];const draw2=()=>{const cell=layout.cell(row,column),inset3=lineWidth/2;painter.rect(cell.x+inset3,cell.y+inset3,cell.width-lineWidth,cell.height-lineWidth,fill,void 0,0);for(const highlight of highlights.filter(item=>item.row===row&&item.column===column)){const pad2=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>painter.rect(cell.x+pad2,cell.y+pad2,cell.width-pad2*2,cell.height-pad2*2,highlight.fill,highlight.stroke,0))}drawLabel(row,column)};const scoped=index=>{if(index<ids.length&&painter.target)painter.target(ids[index],()=>scoped(index+1));else draw2()};scoped(0)}for(const highlight of cellFocusTarget?[]:highlights){const cell=layout.cell(highlight.row,highlight.column);const inset3=Math.min(2,cell.width/4,cell.height/4);components.fade(highlight.opacity??1,()=>{painter.rect(cell.x+inset3,cell.y+inset3,cell.width-2*inset3,cell.height-2*inset3,highlight.fill,highlight.stroke,0)})}const inset2=lineWidth/2;for(let column=1;column<columns;column+=1){const left=x+column*width/columns;painter.path([{x:left,y:y+inset2},{x:left,y:y+height-inset2}],{color:stroke,width:lineWidth})}for(let row=1;row<rows;row+=1){const top=y+row*height/rows;painter.path([{x:x+inset2,y:top},{x:x+width-inset2,y:top}],{color:stroke,width:lineWidth})}if(!cellFocusTarget)labels?.forEach((row,r)=>row.forEach((_,column)=>drawLabel(r,column)))});return{...layout,shape:shape2}}}function createTeachingTimeline(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,domain:[lo,hi],lanes,intervals,time=hi,ticks:ticks2=[lo,hi],formatTime=String,labelWidth=180,laneGap=18,fontSize=28,color="#8D9CB9",trackColor="#18283B",cursorColor="#FFCE73"}=options;if(![x,y,x+width,y+height,lo,hi,hi-lo,time,labelWidth,laneGap,fontSize].every(Number.isFinite))throw new Error("Timeline values must be finite");if(width<=0||height<=0||hi<=lo||time<lo||time>hi)throw new Error("Timeline needs positive bounds and a current time inside its increasing domain");if(fontSize<=0||labelWidth<=12||labelWidth>=width-6||laneGap<0||!lanes.length)throw new Error("Timeline needs positive label space, font size, and at least one lane");const ids=new Set(lanes.map(lane=>lane.id));if(ids.size!==lanes.length||lanes.some(lane=>!lane.id))throw new Error("Timeline lane IDs must be nonempty and unique");const intervalIds=new Set;for(const interval of intervals){if(!interval.id||intervalIds.has(interval.id)||!ids.has(interval.lane))throw new Error("Timeline intervals need unique IDs and an existing lane");intervalIds.add(interval.id);if(![interval.start,interval.end,interval.opacity??1].every(Number.isFinite)||interval.start<lo||interval.end>hi||interval.end<=interval.start)throw new Error("Timeline intervals must have finite positive durations inside the domain")}for(const lane of lanes){const ordered=intervals.filter(interval=>interval.lane===lane.id).sort((a,b)=>a.start-b.start);if(ordered.some((interval,i)=>i>0&&interval.start<ordered[i-1].end))throw new Error(`Timeline intervals overlap in lane ${lane.id}; use separate lanes for concurrent work`)}if(ticks2.some(tick=>!Number.isFinite(tick)||tick<lo||tick>hi))throw new Error("Timeline ticks must lie inside the domain");const axisHeight=Math.max(36,fontSize*2+18);const laneHeight=(height-axisHeight-(lanes.length-1)*laneGap)/lanes.length;const labelHeight=fontSize*1.5,barHeight=laneHeight-labelHeight;if(barHeight<12)throw new Error("Timeline height cannot fit lane labels and interval bars");const left=x+labelWidth+3,plotWidth=width-labelWidth-6;const point=value=>{if(!Number.isFinite(value)||value<lo||value>hi)throw new Error("Timeline point must lie inside the domain");return left+(value-lo)/(hi-lo)*plotWidth};const bounds4={x,y,width,height};const result={bounds:bounds4,time,point,lanes:Object.create(null),intervals:Object.create(null)};painter.container(bounds4,()=>{lanes.forEach((lane,index)=>target(lane.focusTarget,()=>{const top=y+index*(laneHeight+laneGap);const track={x:left-2,y:top+labelHeight,width:plotWidth+4,height:barHeight};const shape2=painter.rect(track.x,track.y,track.width,track.height,trackColor,color,0);result.lanes[lane.id]={shape:shape2,bounds:track};painter.labelScope({x,y:top,width:labelWidth-12,height:laneHeight},()=>{painter.text(lane.label,x,top+laneHeight/2+fontSize*.34,fontSize,color,"left")},{padding:0});for(const interval of intervals.filter(item=>item.lane===lane.id)){const visibleEnd=Math.max(interval.start,Math.min(time,interval.end));const elapsed=visibleEnd-interval.start;const bar={x:point(interval.start),y:track.y+2,width:point(visibleEnd)-point(interval.start),height:barHeight-4};const opacity=Math.max(0,Math.min(1,interval.opacity??1));const item={id:interval.id,shape:null,bounds:bar,elapsed,opacity,complete:time>=interval.end};result.intervals[interval.id]=item;if(elapsed===0||opacity===0)continue;target(interval.focusTarget,()=>painter.opacity(opacity,()=>{painter.container(track,()=>{item.shape=painter.rect(bar.x,bar.y,bar.width,bar.height,interval.color??"#63DEEC",void 0,0)},{padding:0});if(interval.label){const labelBounds={x:point(interval.start),y:top,width:point(interval.end)-point(interval.start),height:labelHeight};painter.labelScope(labelBounds,()=>painter.text(interval.label,labelBounds.x+labelBounds.width/2,top+fontSize,fontSize,interval.color??"#63DEEC","center"),{padding:2})}}))}}));const axisY=y+height-axisHeight+Math.max(10,fontSize*.5);painter.line(left,axisY,left+plotWidth,axisY,color,2);for(const tick of ticks2){const px=point(tick);painter.line(px,axisY,px,axisY+6,color,2);painter.labelScope({x:left-labelWidth,y:axisY+8,width:plotWidth+labelWidth,height:fontSize*1.5},()=>{painter.text(formatTime(tick),px,axisY+fontSize*1.4,fontSize,color,tick===hi?"right":tick===lo?"left":"center")},{padding:0})}painter.line(point(time),axisY-8,point(time),axisY+8,cursorColor,3)},{padding:0});return result}}var COLORS=["#63DEEC","#79A6FF","#D6A0FF","#FFCE73"];function layoutAllocation(options){const{x,y,width,height,capacity,parts}=options;if(![x,y,x+width,y+height,capacity].every(Number.isFinite)||width<=0||height<=0||capacity<=0)throw new Error("Allocation needs finite positive bounds and capacity");const ids=new Set;let used=0;for(const part of parts){if(!part.id||ids.has(part.id))throw new Error("Allocation part IDs must be nonempty and unique");ids.add(part.id);if(!Number.isFinite(part.value)||part.value<0)throw new Error("Allocation values must be finite and nonnegative");used+=part.value}if(!Number.isFinite(used)||used-capacity>Number.EPSILON*Math.max(used,capacity)*8)throw new Error("Allocation exceeds capacity");used=Math.min(used,capacity);let offset=0;const segments=parts.map(part=>{const start=Math.min(offset,capacity);offset+=part.value;return{id:part.id,value:part.value,bounds:{x:x+width*(start/capacity),y,width:width*((Math.min(offset,capacity)-start)/capacity),height}}});const remaining=Math.max(0,capacity-used);return{bounds:{x,y,width,height},used,remaining,parts:segments,freeBounds:{x:x+width*(used/capacity),y,width:width*(remaining/capacity),height}}}function createTeachingAllocation(painter){const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();return options=>{const{x,y,width,height,fontSize=28,unit="",format=String,color="#8D9CB9",trackColor="#18283B"}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Allocation font size must be finite and positive");const header=fontSize*1.7,barHeight=fontSize*2,rowHeight=fontSize*1.65,gap=fontSize*.6;if(height<header+barHeight+gap+(options.parts.length+1)*rowHeight||width<=6||width*.67<=fontSize)throw new Error("Allocation bounds cannot fit the strip and ledger");const layout=layoutAllocation({...options,x:x+3,y:y+header+3,width:width-6,height:barHeight-6});const suffix=unit?` ${unit}`:"",shapes=[];let shape2;painter.container({x,y,width,height},()=>{painter.labelScope({x,y,width,height:header},()=>painter.text(`Used ${format(layout.used)} / ${format(options.capacity)}${suffix}`,x,y+fontSize,fontSize,color,"left"),{padding:0});const strip={x:x+1,y:y+header+1,width:width-2,height:barHeight-2};shape2=painter.rect(strip.x,strip.y,strip.width,strip.height,trackColor,color,0);painter.container(strip,()=>{layout.parts.forEach((part,index)=>shapes.push(part.bounds.width===0?null:target(options.parts[index].focusTarget,()=>painter.rect(part.bounds.x,part.bounds.y,part.bounds.width,part.bounds.height,options.parts[index].color??COLORS[index%COLORS.length],void 0,0))))},{padding:0});const rows=[...options.parts,{id:"free",label:"Free",value:layout.remaining,color,focusTarget:options.freeFocusTarget}];rows.forEach((part,index)=>target(part.focusTarget,()=>{const top=y+header+barHeight+gap+index*rowHeight,baseline=top+rowHeight/2+fontSize*.34;painter.rect(x,top+(rowHeight-fontSize*.6)/2,fontSize*.6,fontSize*.6,part.color??COLORS[index%COLORS.length],void 0,0);painter.labelScope({x:x+fontSize,y:top,width:width*.67-fontSize,height:rowHeight},()=>painter.text(part.label,x+fontSize,baseline,fontSize,color,"left"),{padding:0});painter.labelScope({x:x+width*.7,y:top,width:width*.3,height:rowHeight},()=>painter.text(`${format(part.value)}${suffix}`,x+width,baseline,fontSize,color,"right"),{padding:0})}))},{padding:0});return{...layout,shapes,shape:shape2}}}var clamp=value=>Math.max(0,Math.min(1,value));var smooth=value=>value*value*(3-2*value);function valueChangeState(options){for(const name of["from","to","progress"]){if(!Number.isFinite(options[name]))throw new Error(`Value change ${name} must be finite`)}if(options.emphasis!==void 0&&!Number.isFinite(options.emphasis))throw new Error("Value change emphasis must be finite");const{from,to:to2}=options;const progress=clamp(options.progress);const changed=from!==to2;const emphasis=changed?clamp(options.emphasis??smooth(clamp(progress/.12))*(1-smooth(clamp((progress-.65)/.35)))):0;const value=from*(1-progress)+to2*progress;const delta=to2-from;if(!Number.isFinite(value)||!Number.isFinite(delta))throw new Error("Value change result must be finite");return{value,previous:from,target:to2,delta,changed,emphasis}}function createTeachingValueChange(painter){function changeCue(options,draw2){const{x,y,width,height,color="#F4D477",restColor="#E9EFFF",fill=color,radius=10}=options;if(![x,y,width,height,radius].every(Number.isFinite)||width<=0||height<=0||radius<0){throw new Error("Value change bounds must be finite with positive dimensions and nonnegative radius")}const state=valueChangeState({from:options.from,to:options.to,progress:options.progress,...options.emphasis===void 0?{}:{emphasis:options.emphasis}});if(state.emphasis>0){painter.opacity(state.emphasis*.12,()=>painter.rect(x,y,width,height,fill,void 0,radius));painter.opacity(state.emphasis,()=>painter.rect(x,y,width,height,"transparent",color,radius))}const result={...state,color:state.emphasis>0?color:restColor};draw2?.(result);return result}function valueChange(options){const{x,y,width,height,label,format=value=>value.toFixed(1),fontSize=36,showDelta=true}=options;if(!Number.isFinite(fontSize)||fontSize<=0)throw new Error("Value change font size must be positive");const lines=1+Number(Boolean(label))+Number(showDelta);if(height<fontSize*(lines===1?1.4:lines===2?2.3:3))throw new Error("Value change height must contain its label and delta");return changeCue(options,state=>painter.labelScope({x,y,width,height},()=>{const center2=x+width/2;if(label)painter.text(label,center2,y+fontSize*.7,fontSize*.55,options.restColor??"#E9EFFF","center");const baseline=label?y+height*(showDelta?.5:.65)+fontSize*.2:showDelta?y+fontSize*1.05:y+height/2+fontSize*.34;painter.text(format(state.value),center2,baseline,fontSize,state.color,"center","mono");if(showDelta){const sign=state.delta>0?"+":"";painter.text(`${format(state.previous)} \u2192 ${format(state.target)} \xB7 \u0394 ${sign}${format(state.delta)}`,center2,y+height-fontSize*.3,fontSize*.46,options.restColor??"#E9EFFF","center","mono")}},{padding:4}))}return{changeCue,valueChange}}function mergeFocusRegions(parts,gap=12){const regions=[];for(const part of parts){let current={...part},index=0;while(index<regions.length){const other=regions[index];if(current.x<=other.x+other.width+gap&&other.x<=current.x+current.width+gap&&current.y<=other.y+other.height+gap&&other.y<=current.y+current.height+gap){const x=Math.min(current.x,other.x),y=Math.min(current.y,other.y);current={x,y,width:Math.max(current.x+current.width,other.x+other.width)-x,height:Math.max(current.y+current.height,other.y+other.height)-y};regions.splice(index,1);index=0}else index++}regions.push(current)}return regions}function createFocusDirector(painter,options={}){const{cues,strict=false,contextOpacity=.52,minimumContextAlpha=0}=options;if(!Number.isFinite(contextOpacity)||contextOpacity<0||contextOpacity>1)throw new Error("Focus context opacity must be between zero and one");if(!Number.isFinite(minimumContextAlpha)||minimumContextAlpha<0||minimumContextAlpha>1)throw new Error("Minimum context alpha must be between zero and one");const active=Object.values(cues??{}).filter(cue2=>cue2.active&&cue2.strength>0).sort((a,b)=>b.start-a.start||b.id.localeCompare(a.id))[0];const stack=[];function cue(id){const value=cues&&Object.hasOwn(cues,id)?cues[id]:void 0;if(!value&&strict)throw new Error(`Unknown narration cue: ${id}`);return value}function opacity(amount2,draw2){if(amount2===1)return draw2();let result;painter.opacity(amount2,()=>{result=draw2()});return result}return{active,cue,progress(id,fallback=0){return cue(id)?.progress??fallback},visible(id){return cue(id)?.phase!=="before"},reveal(id,draw2){return opacity(cue(id)?.reveal??1,draw2)},target(id,draw2){stack.push(id);try{return draw2()}finally{stack.pop()}},paint(draw2,originalAlpha=1){const focused=!active||stack.some(id=>active.targets.includes(id));let amount2=focused?1:1-(1-contextOpacity)*active.strength;if(!focused&&originalAlpha>0)amount2=Math.max(amount2,Math.min(originalAlpha,minimumContextAlpha)/originalAlpha);return opacity(amount2,draw2)}}}function createTeachingFocus(painter){function focusFrame(options){const{bounds:bounds4,strength,color="#63DEEC",padding=8,clip}=options;if(![bounds4.x,bounds4.y,bounds4.width,bounds4.height,strength,padding].every(Number.isFinite)||bounds4.width<=0||bounds4.height<=0||padding<0||strength<0||strength>1)throw new Error("Invalid focus frame geometry or strength");if(strength===0)return;const corners=offset=>{const x=bounds4.x-offset,y=bounds4.y-offset,w=bounds4.width+offset*2,h=bounds4.height+offset*2;const corner=Math.min(24,w/4,h/4);return[[x,y,1,1],[x+w,y,-1,1],[x,y+h,1,-1],[x+w,y+h,-1,-1]].map(([cx,cy,sx,sy])=>[{x:cx+sx*corner,y:cy},{x:cx,y:cy},{x:cx,y:cy+sy*corner}])};const clear=points=>points.slice(1).every((point,index)=>{const previous=points[index],x=Math.min(previous.x,point.x)-2,y=Math.min(previous.y,point.y)-2;const right=Math.max(previous.x,point.x)+2,bottom=Math.max(previous.y,point.y)+2;return(!clip||x>=clip.x&&y>=clip.y&&right<=clip.x+clip.width&&bottom<=clip.y+clip.height)&&!(options.avoid??[]).some(label=>x<label.x+label.width&&right>label.x&&y<label.y+label.height&&bottom>label.y)});let paths=corners(padding);if(!paths.every(clear)){const alternatives=[padding+6,padding+12,padding+20].map(corners);paths=alternatives.find(candidate=>candidate.every(clear))??paths.filter(clear)}if(paths.length<2)return;painter.opacity(strength*.7,()=>{for(const[index,points]of paths.entries()){painter.path(points,{id:options.id&&`${options.id}:${index}`,color,width:3,clip})}})}return{focusFrame}}var clamp2=value=>Math.max(0,Math.min(1,value));var cleanZero=value=>value===0?0:value;function finite2(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`);return value}function vector(values,dimensions,name){if(values.length!==dimensions)throw new Error(`${name} must have ${dimensions} coordinates`);return values.map(value=>cleanZero(finite2(value,name)))}function add(left,right){return left.map((value,index)=>cleanZero(finite2(value+right[index],"Weighted vector sum")))}function weightedVectorState(options){const progress=clamp2(finite2(options.progress,"Weighted vector progress"));const dimensions=options.initial?.length??options.terms[0]?.values.length??0;if(!dimensions)throw new Error("Weighted vectors require at least one coordinate; an empty sum needs an initial vector");const initial=options.initial?vector(options.initial,dimensions,"Initial vector"):Array(dimensions).fill(0);const ids=new Set;let prefix2=[...initial];const position2=progress*options.terms.length;const completedCount=Math.min(options.terms.length,Math.floor(position2));const terms=options.terms.map((term,index)=>{if(typeof term.id!=="string"||!term.id.trim()||term.id!==term.id.trim()||ids.has(term.id)){throw new Error("Weighted vector terms require distinct nonempty IDs without surrounding whitespace")}ids.add(term.id);const label=term.label??term.id;if(typeof label!=="string"||!label.trim())throw new Error("Weighted vector labels must be nonempty");const weight=finite2(term.weight,"Vector weight");const values=vector(term.values,dimensions,`Vector ${term.id}`);const contribution=values.map(value=>cleanZero(finite2(weight*value,"Weighted vector contribution")));const start=[...prefix2],end=add(start,contribution);prefix2=end;const fraction=clamp2(position2-index);const status=fraction===1?"completed":index===completedCount&&progress<1?"current":"pending";const applied=contribution.map(value=>cleanZero(value*fraction));return{...term,label,values,weight,status,progress:fraction,contribution,applied,start,end,currentEnd:add(start,applied),zero:contribution.every(value=>value===0)}});const completedSum=completedCount?[...terms[completedCount-1].end]:[...initial];const current=terms.find(term=>term.status==="current")??null;return{progress,dimensions,initial,terms,completedCount,current,completedSum,sum:current?[...current.currentEnd]:[...completedSum],total:[...prefix2]}}function positive3(value,name){if(finite2(value,name)<=0)throw new Error(`${name} must be positive`)}function bounds2(value,name){finite2(value.x,`${name} x`);finite2(value.y,`${name} y`);positive3(value.width,`${name} width`);positive3(value.height,`${name} height`)}function createTeachingVectorAccumulation(painter){return options=>{const state=weightedVectorState(options);const{plot,ledger,projection,fontSize=28,color="#63DEEC",restColor="#8D9CB9",completedOpacity=.45,width=4,endpointRadius=5,revealTotal=false,totalLabel="Accumulated vector",format=value=>String(Number(value.toPrecision(4)))}=options;bounds2(plot.bounds,"Vector plot");bounds2(ledger,"Vector ledger");positive3(fontSize,"Vector font size");positive3(width,"Vector stroke width");positive3(endpointRadius,"Vector endpoint radius");finite2(completedOpacity,"Completed vector opacity");if(completedOpacity<0||completedOpacity>1)throw new Error("Completed vector opacity must lie between zero and one");const[x0,x1]=plot.xDomain,[y0,y1]=plot.yDomain;for(const value of[x0,x1,y0,y1])finite2(value,"Vector plot domain");if(x1<=x0||y1<=y0)throw new Error("Vector plot domains must increase");const sx=plot.bounds.width/(x1-x0),sy=plot.bounds.height/(y1-y0);if(!Number.isFinite(sx)||!Number.isFinite(sy)||sx<=0||sy<=0||Math.abs(sx-sy)>Math.max(sx,sy)*1e-9){throw new Error("Weighted vector drawing requires equal-unit plot geometry")}if(state.dimensions!==2&&!projection)throw new Error("Weighted vector drawing requires 2D values or an explicit projection");if(projection&&!projection.label.trim())throw new Error("Vector projection requires a visible declaration");const rowHeight=fontSize*2.5,headerHeight=fontSize*1.6;if(ledger.height<headerHeight+state.terms.length*rowHeight+fontSize*1.8){throw new Error("Vector ledger height must contain the identities, contributions and result")}const point=values=>{const projected=projection?projection.point([...values]):values;if(projected.length!==2)throw new Error("Vector projection must return exactly two coordinates");const[x,y]=projected;finite2(x,"Projected vector x");finite2(y,"Projected vector y");if(x<x0||x>x1||y<y0||y>y1)throw new Error("Vector endpoints must lie inside the declared plot domains");const p=plot.point(x,y);finite2(p.x,"Vector endpoint x");finite2(p.y,"Vector endpoint y");const expectedX=finite2(plot.bounds.x+(x-x0)*sx,"Declared vector endpoint x");const expectedY=finite2(plot.bounds.y+plot.bounds.height-(y-y0)*sy,"Declared vector endpoint y");const tolerance=Math.max(1,Math.abs(expectedX),Math.abs(expectedY),plot.bounds.width,plot.bounds.height)*1e-9;if(Math.abs(p.x-expectedX)>tolerance||Math.abs(p.y-expectedY)>tolerance){throw new Error("Vector plot mapping must match its declared equal-unit transform")}return p};const segments=[];for(const term of state.terms){const from=point(term.start);point(term.end);const to2=point(term.currentEnd);if(term.status!=="pending")segments.push({id:term.id,status:term.status,from,to:to2,zero:Math.hypot(to2.x-from.x,to2.y-from.y)<1e-9})}const endpoint=point(state.sum);const vectorText=values=>`(${values.map(value=>format(value)).join(", ")})`;const target=(id,draw2)=>painter.target?painter.target(id,draw2):draw2();const paintedTerms=state.terms.map((term,index)=>({term,index,input:`${term.label}: ${format(term.weight)} \xD7 ${vectorText(term.values)}`,detail:term.status==="pending"?"pending":`${term.status}: ${vectorText(term.applied)}`}));const totalText=`${totalLabel}: ${revealTotal?vectorText(state.sum):"?"}`;for(const segment of segments){const term=state.terms.find(term2=>term2.id===segment.id);const ink=term.color??color;target(term.id,()=>painter.opacity(term.status==="completed"?completedOpacity:1,()=>{if(segment.zero)painter.circle(segment.to.x,segment.to.y,endpointRadius,"transparent",ink,width);else painter.arrow(segment.from.x,segment.from.y,segment.to.x,segment.to.y,ink,width)}))}if(revealTotal){const mark=()=>{painter.circle(endpoint.x,endpoint.y,endpointRadius*1.5,color)};if(options.totalTarget)target(options.totalTarget,mark);else mark()}painter.labelScope(ledger,()=>{painter.text(projection?`Projection: ${projection.label}`:"Weighted contributions",ledger.x+12,ledger.y+fontSize,fontSize*.85,restColor);for(const{term,index,input,detail}of paintedTerms)target(term.id,()=>{const ink=term.color??color;const y=ledger.y+headerHeight+index*rowHeight;painter.text(input,ledger.x+12,y+fontSize,fontSize,term.status==="pending"?restColor:ink);painter.text(detail,ledger.x+12,y+fontSize*1.9,fontSize*.8,restColor)});const result=()=>{painter.text(totalText,ledger.x+12,ledger.y+headerHeight+state.terms.length*rowHeight+fontSize,fontSize,revealTotal?color:restColor)};if(options.totalTarget)target(options.totalTarget,result);else result()},{padding:4});return{state,segments,endpoint}}}function categoricalSampling(options){if(options.normalization!=="probabilities"&&options.normalization!=="weights")throw new Error("Sampling requires an explicit mass normalization contract");if(!options.categories.length)throw new Error("Sampling needs at least one category");const ids=new Set;let total=0;for(const category of options.categories){if(!category.id||ids.has(category.id)||!category.label.trim())throw new Error("Sampling category IDs must be unique and labels nonempty");if(!Number.isFinite(category.mass)||category.mass<0)throw new Error("Sampling masses must be finite and nonnegative");ids.add(category.id);total+=category.mass}if(!Number.isFinite(total)||total<=0)throw new Error("Sampling total mass must be finite and positive");if(options.normalization==="probabilities"&&Math.abs(total-1)>1e-12)throw new Error("Sampling probabilities must sum to one within 1e-12");let cumulative=0;let lastPositive=0;options.categories.forEach((category,index)=>{if(category.mass>0)lastPositive=index});const categories=options.categories.map((category,index)=>{const lower=cumulative,probability=category.mass/total;cumulative=index===lastPositive?1:Math.min(1,cumulative+probability);if(category.mass>0&&(probability===0||cumulative<=lower))throw new Error("Positive category is too small for cumulative floating-point precision");return{...category,probability,lower,upper:cumulative,count:0,empiricalProbability:null}});ids.clear();const draws=options.draws.map(draw2=>{if(!draw2.id||ids.has(draw2.id))throw new Error("Sampling draw IDs must be nonempty and unique");if(!Number.isFinite(draw2.uniform)||draw2.uniform<0||draw2.uniform>=1)throw new Error("Supplied uniform draws must be finite inside [0, 1)");ids.add(draw2.id);const categoryIndex=categories.findIndex(category=>category.mass>0&&draw2.uniform>=category.lower&&draw2.uniform<category.upper);if(categoryIndex<0)throw new Error("Supplied draw could not be represented by the normalized intervals");categories[categoryIndex].count+=1;return{...draw2,categoryId:categories[categoryIndex].id,categoryIndex}});if(draws.length)categories.forEach(category=>{category.empiricalProbability=category.count/draws.length});return{inputTotal:total,normalization:options.normalization,categories,draws}}var COLORS2=["#79A6FF","#FF8DC3","#63DEEC","#FFCE73","#A6DF91"];function createTeachingCategoricalSampling(painter){return options=>{const model=categoricalSampling(options);const{x,y,width,height,fontSize=28,color="#DEE7F5",trackColor="#18283B",visibleDraws=0,drawProgress=0,showEmpirical=false,formatProbability=value=>value.toFixed(3)}=options;if(![x,y,x+width,y+height,fontSize].every(Number.isFinite)||fontSize<=0||width<=0||height<=0)throw new Error("Sampling needs finite positive bounds and font size");if(!Number.isInteger(visibleDraws)||visibleDraws<0||visibleDraws>model.draws.length)throw new Error("Visible sample count must be an integer inside the supplied draw count");if(!Number.isFinite(drawProgress)||drawProgress<0||drawProgress>1||visibleDraws===model.draws.length&&drawProgress!==0)throw new Error("Sampling progress must be inside [0, 1] for an available next draw");if(showEmpirical&&visibleDraws!==model.draws.length)throw new Error("Empirical reveal requires every supplied sample to be retained");const columns=options.columns??Math.max(1,Math.min(8,model.draws.length));if(!Number.isInteger(columns)||columns<1)throw new Error("Sampling columns must be a positive integer");const railWidth=fontSize*2,contentWidth=width-railWidth;const gap=fontSize*.5,cellWidth=(contentWidth-4-(columns-1)*gap)/columns,cellHeight=fontSize*1.9;const legendColumns=Math.min(3,model.categories.length),legendRows=Math.ceil(model.categories.length/legendColumns),legendHeight=legendRows*fontSize*1.7;const bandY=y+fontSize*4,bandHeight=fontSize*1.3,legendY=bandY+bandHeight+fontSize*1.5;const captionY=legendY+legendHeight+fontSize*.5,poolY=captionY+fontSize*3.3,rows=Math.ceil(model.draws.length/columns),empiricalY=poolY+Math.max(1,rows)*(cellHeight+gap)+fontSize*2;if(cellWidth<fontSize*2||contentWidth/legendColumns<fontSize*5||empiricalY+bandHeight+fontSize*1.7>y+height)throw new Error("Sampling bounds cannot fit probability labels, sample IDs and empirical strip");const inset2=fontSize*.22+2,stripX=x+inset2,stripWidth=contentWidth-inset2*2;const point=u=>stripX+u*stripWidth;const categoryColor=index=>model.categories[index].color??COLORS2[index%COLORS2.length];const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const label=(value,bounds4,align="left",ink=color,size=fontSize)=>painter.labelScope(bounds4,()=>painter.text(value,align==="center"?bounds4.x+bounds4.width/2:align==="right"?bounds4.x+bounds4.width:bounds4.x,bounds4.y+size*1.05,size,ink,align),{padding:0});const strip=(top,empirical)=>{painter.rect(stripX,top,stripWidth,bandHeight,trackColor,void 0,0);let cumulative=0;model.categories.forEach((category,index)=>{const probability=empirical?category.empiricalProbability??0:category.probability;const left=cumulative;cumulative+=probability;if(probability>0)target(category.focusTarget,()=>painter.rect(point(left),top,stripWidth*probability,bandHeight,categoryColor(index),void 0,0))})};const sampleBounds=model.draws.map((_draw,index)=>({x:x+2+index%columns*(cellWidth+gap),y:poolY+Math.floor(index/columns)*(cellHeight+gap),width:cellWidth,height:cellHeight}));const shapes=[];painter.container({x,y,width,height},()=>{label(options.normalization==="weights"?"Original probabilities \xB7 normalized supplied weights":"Original probabilities \xB7 supplied distribution",{x,y,width:contentWidth,height:fontSize*1.6});strip(bandY,false);label("0",{x,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"left",color,fontSize*.8);label("1",{x:x+contentWidth-fontSize*2,y:bandY+bandHeight+2,width:fontSize*2,height:fontSize*1.2},"right",color,fontSize*.8);model.categories.forEach((category,index)=>{const bounds4={x:x+index%legendColumns*contentWidth/legendColumns,y:legendY+Math.floor(index/legendColumns)*fontSize*1.7,width:contentWidth/legendColumns-gap,height:fontSize*1.5};target(category.focusTarget,()=>label(`${category.label}: ${formatProbability(category.probability)}`,bounds4,"left",categoryColor(index)))});label(`Supplied samples \xB7 ${visibleDraws} retained / ${model.draws.length}`,{x,y:poolY-fontSize*1.8,width:contentWidth,height:fontSize*1.5});for(let index=0;index<visibleDraws;index+=1)target(options.sampleFocusTarget,()=>{const draw2=model.draws[index],bounds4=sampleBounds[index];shapes.push(painter.rect(bounds4.x,bounds4.y,bounds4.width,bounds4.height,trackColor,categoryColor(draw2.categoryIndex),4));label(draw2.id,bounds4,"center",categoryColor(draw2.categoryIndex))});if(drawProgress>0&&visibleDraws<model.draws.length)target(options.sampleFocusTarget,()=>{const draw2=model.draws[visibleDraws],destination=sampleBounds[visibleDraws],landed=drawProgress>=.4;const from={x:point(draw2.uniform),y:bandY-fontSize*1.2},onBand={x:point(draw2.uniform),y:bandY+bandHeight/2};const progress=landed?(drawProgress-.4)/.6:drawProgress/.4;const destinationPoint={x:destination.x+destination.width/2,y:destination.y+destination.height/2};const railX=x+width-inset2;const route=landed?[onBand,from,{x:railX,y:from.y},{x:railX,y:destinationPoint.y},destinationPoint]:[from,onBand];const lengths=route.slice(1).map((point2,index)=>Math.hypot(point2.x-route[index].x,point2.y-route[index].y));let remaining=progress*lengths.reduce((sum,length)=>sum+length,0);let marker=route[route.length-1];for(let index=0;index<lengths.length;index+=1){const length=lengths[index];if(remaining<=length&&length>0){const ratio=remaining/length;marker={x:route[index].x+(route[index+1].x-route[index].x)*ratio,y:route[index].y+(route[index+1].y-route[index].y)*ratio};break}remaining-=length}const ink=landed?categoryColor(draw2.categoryIndex):color;painter.circle(marker.x,marker.y,fontSize*.22,ink,trackColor,3);const caption=`${landed?"Copy":"Draw"} ${draw2.id} \xB7 supplied u=${draw2.uniform.toFixed(3)}`;label(caption,{x,y:captionY,width:contentWidth,height:fontSize*1.3},"left",ink,fontSize*.8)});if(showEmpirical){label(model.draws.length?"Empirical frequencies \xB7 supplied sample only":"No samples \xB7 empirical distribution undefined",{x,y:empiricalY-fontSize*1.7,width:contentWidth,height:fontSize*1.5});if(model.draws.length){strip(empiricalY,true);const text2=model.categories.map(category=>`${category.label}: ${category.count}/${model.draws.length}`).join(" \xB7 ");label(text2,{x,y:empiricalY+bandHeight+fontSize*.25,width:contentWidth,height:fontSize*1.3},"left",color,fontSize*.8)}}},{padding:0});return{model,sampleBounds,shapes,point,visibleDraws}}}function finite3(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function nonnegative3(value,name){finite3(value,name);if(value<0)throw new Error(`${name} must be nonnegative`)}function bounds3(value,name){for(const field of["x","y","width","height"])finite3(value[field],`${name} ${field}`);if(value.width<=0||value.height<=0)throw new Error(`${name} dimensions must be positive`);finite3(value.x+value.width,`${name} right edge`);finite3(value.y+value.height,`${name} bottom edge`)}function identifier(id,name){if(typeof id!=="string"||!id.trim())throw new Error(`${name} must be a nonempty ID`)}function alpha2(value){finite3(value,"Routed transfer opacity");return Math.max(0,Math.min(1,value))}function expanded(box,clearance){return{left:box.x-clearance,top:box.y-clearance,right:box.x+box.width+clearance,bottom:box.y+box.height+clearance}}function lengthOf(points){let sum=0;for(let i=1;i<points.length;i++)sum+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);return sum}function trimLeads(points,amount2){const length=lengthOf(points);if(length<=2*amount2)throw new Error("endpoint spacing leaves no positive-length clear transfer");const result=[pointAlongSamples(points,amount2/length)];let distance=0;for(let i=1;i<points.length;i++){distance+=Math.hypot(points[i].x-points[i-1].x,points[i].y-points[i-1].y);if(distance>amount2+1e-6&&distance<length-amount2-1e-6)result.push(points[i])}result.push(pointAlongSamples(points,1-amount2/length));return result}function parameters(options){identifier(options.id,"Routed transfer ID");identifier(options.source.id,"Routed transfer source");identifier(options.target.id,"Routed transfer target");if(options.source.id===options.target.id)throw new Error("Routed transfer source and target IDs must differ");bounds3(options.source.shape,"Routed transfer source");bounds3(options.target.shape,"Routed transfer target");bounds3(options.corridor,"Routed transfer corridor");const ids=new Set([options.source.id,options.target.id]);for(const obstacle of options.obstacles){identifier(obstacle.id,"Routed transfer obstacle");if(ids.has(obstacle.id))throw new Error(`Duplicate routed transfer object ID: ${obstacle.id}`);ids.add(obstacle.id);bounds3(obstacle.bounds,`Routed transfer obstacle ${obstacle.id}`)}const width=options.width??3,margin=options.margin??2;nonnegative3(width,"Routed transfer width");if(width===0)throw new Error("Routed transfer width must be positive");nonnegative3(margin,"Routed transfer margin");if(options.progress!==void 0)finite3(options.progress,"Routed transfer progress");if(options.marker&&options.progress===void 0)throw new Error("Routed transfer marker requires progress");const radius=options.marker?.radius??7,strokeWidth=options.marker?.strokeWidth??3;nonnegative3(radius,"Routed transfer marker radius");if(radius===0)throw new Error("Routed transfer marker radius must be positive");nonnegative3(strokeWidth,"Routed transfer marker stroke width");const markerInk=options.progress===void 0?0:radius+(options.marker?.stroke?strokeWidth/2:0);const clearance=Math.max(width/2,markerInk)+margin;const opacity=Math.min(alpha2(options.source.opacity),alpha2(options.target.opacity),alpha2(options.opacity??1));return{width,margin,radius,strokeWidth,clearance,opacity}}function planTeachingRoutedTransfer(options){const{clearance}=parameters(options);const fail2=reason=>{throw new Error(`Cannot route transfer ${options.id} (${options.source.id} \u2192 ${options.target.id}): ${reason}`)};const guard=clearance+.01,corridor=options.corridor;if(corridor.width<=2*guard||corridor.height<=2*guard)fail2("corridor is too small for the requested ink clearance");const origin={x:corridor.x+guard,y:corridor.y+guard};const toLocal=shape2=>{const x=shape2.x-origin.x,y=shape2.y-origin.y;finite3(x,"Routed transfer local x");finite3(y,"Routed transfer local y");return{x:Number(x.toFixed(6)),y:Number(y.toFixed(6)),width:shape2.width,height:shape2.height}};const endpoints=[options.source,options.target];const nodes=endpoints.map(endpoint=>{const b=toLocal(endpoint.shape);return{id:endpoint.id,cx:b.x+b.width/2,cy:b.y+b.height/2,width:b.width,height:b.height}});const obstacles=options.obstacles.map(obstacle=>expanded(toLocal(obstacle.bounds),0));const result=routeOrthogonalGraph(nodes,[{from:options.source.id,to:options.target.id,fromSide:options.source.side,toSide:options.target.side}],corridor.width-2*guard,corridor.height-2*guard,guard,14,obstacles);const raw=result.routes.get(0);if(!raw)return fail2(result.failures[0]?.reason??"no legal route was returned");const points=(()=>{try{return trimLeads(raw,guard).map(point=>({x:point.x+origin.x,y:point.y+origin.y}))}catch(error){return fail2(error instanceof Error?error.message:String(error))}})();const occupied=[...endpoints.map(endpoint=>expanded(endpoint.shape,clearance)),...options.obstacles.map(obstacle=>expanded(obstacle.bounds,clearance))];for(const point of points){if(point.x<corridor.x+clearance||point.x>corridor.x+corridor.width-clearance||point.y<corridor.y+clearance||point.y>corridor.y+corridor.height-clearance)fail2("route ink leaves the permitted corridor")}for(let i=1;i<points.length;i++){if(occupied.some(obstacle=>routingSegmentBlocked(points[i-1],points[i],obstacle)))fail2("a complete route segment violates object clearance")}const immutable=Object.freeze(points.map(point=>Object.freeze(point)));return{id:options.id,source:options.source,target:options.target,points:immutable,length:lengthOf(immutable),clearance,positionAt(progress){finite3(progress,"Routed transfer progress");return pointAlongSamples(immutable,Math.max(0,Math.min(1,progress)))}}}function createTeachingRoutedTransfer(painter){return options=>{const{width,radius,strokeWidth,opacity}=parameters(options);if(opacity===0)return null;const route=planTeachingRoutedTransfer(options),color=options.color??"#63DEEC";const paint=()=>painter.opacity(opacity,()=>{painter.path(route.points,{id:`${options.id}:route`,color,width});if(options.progress!==void 0&&options.progress>0&&options.progress<1){const point=route.positionAt(options.progress);painter.circle(point.x,point.y,radius,options.marker?.fill??color,options.marker?.stroke,strokeWidth)}});if(painter.target)painter.target(options.focusTarget??options.id,paint);else paint();return route}}function compareByteSequences(before,after){if(!(before instanceof Uint8Array)||!(after instanceof Uint8Array)){throw new Error("Byte comparison requires two Uint8Arrays")}const left=Array.from(before),right=Array.from(after);let commonPrefix=0,commonSuffix=0;while(commonPrefix<Math.min(left.length,right.length)&&left[commonPrefix]===right[commonPrefix])commonPrefix++;while(commonSuffix<Math.min(left.length,right.length)-commonPrefix&&left[left.length-commonSuffix-1]===right[right.length-commonSuffix-1])commonSuffix++;const columns=[];const add2=(oldOffset,newOffset)=>{const oldByte=oldOffset===null?null:{offset:oldOffset,value:left[oldOffset]};const newByte=newOffset===null?null:{offset:newOffset,value:right[newOffset]};const kind=!oldByte?"insert":!newByte?"delete":oldByte.value===newByte.value?"equal":"replace";columns.push({id:`before:${oldOffset??"none"}|after:${newOffset??"none"}`,kind,before:oldByte,after:newByte})};for(let offset=0;offset<commonPrefix;offset++)add2(offset,offset);const leftMiddle=left.length-commonPrefix-commonSuffix;const rightMiddle=right.length-commonPrefix-commonSuffix;for(let offset=0;offset<Math.max(leftMiddle,rightMiddle);offset++){add2(offset<leftMiddle?commonPrefix+offset:null,offset<rightMiddle?commonPrefix+offset:null)}for(let offset=0;offset<commonSuffix;offset++){add2(left.length-commonSuffix+offset,right.length-commonSuffix+offset)}return{algorithm:"common-prefix/suffix with positional middle",beforeLength:left.length,afterLength:right.length,commonPrefix,commonSuffix,equal:left.length===right.length&&commonPrefix===left.length,columns}}function escapedByte(value){if(!Number.isInteger(value)||value<0||value>255)throw new Error("A byte must be an integer from 0 through 255");if(value===0)return"\\0";if(value===9)return"\\t";if(value===10)return"\\n";if(value===13)return"\\r";if(value===32)return"space";if(value===92)return"\\\\";if(value>=33&&value<=126)return String.fromCharCode(value);return`\\x${value.toString(16).padStart(2,"0").toUpperCase()}`}function byteDifferenceState(options){if(!Number.isFinite(options.scanProgress))throw new Error("Byte scan progress must be finite");const comparison=compareByteSequences(options.before,options.after);const progress=Math.max(0,Math.min(1,options.scanProgress));const scannedColumns=Math.floor(progress*comparison.columns.length);return{comparison,progress,scannedColumns,scanComplete:progress===1,verdict:options.revealVerdict?comparison.equal?"equal":"different":null}}function layoutByteDifference(options){const{x,y,width,height,fontSize=28,maxColumns=10}=options;if(![x,y,width,height,fontSize,x+width,y+height].every(Number.isFinite)||width<=0||height<=0||fontSize<=0){throw new Error("Byte strip bounds and font size must be finite with positive dimensions")}if(fontSize<24)throw new Error("Byte strip font size must be at least 24 px for checked label padding");if(!Number.isSafeInteger(maxColumns)||maxColumns<1)throw new Error("Byte window size must be a positive safe integer");const state=byteDifferenceState(options),all=state.comparison.columns;const start=options.startColumn??Math.max(0,state.comparison.commonPrefix-2);if(!Number.isSafeInteger(start)||start<0||start>all.length||all.length>0&&start===all.length){throw new Error("Byte window start is outside the alignment")}const columns=all.slice(start,start+maxColumns),count=Math.max(1,columns.length);const gutter=fontSize*5.2,cellWidth=(width-gutter)/count;const longest=Math.max(5,...columns.flatMap(column=>[column.before,column.after].map(byte=>byte?String(byte.offset).length+1:5)));if(cellWidth<fontSize*.65*longest+12||height<fontSize*10){throw new Error("Byte strip cannot fit its byte labels and offsets")}const headerHeight=fontSize*1.7,footerHeight=fontSize*1.7,rowHeight=(height-headerHeight-footerHeight)/2;if(cellWidth<=4||rowHeight<=4||gutter-8<=8||headerHeight<=8||footerHeight<=8||rowHeight*.3<=8){throw new Error("Byte strip cannot fit positive cell insets and checked label padding")}const cells=columns.map((column,index)=>({column,alignmentIndex:start+index,beforeBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight,width:cellWidth,height:rowHeight},afterBounds:{x:x+gutter+index*cellWidth,y:y+headerHeight+rowHeight,width:cellWidth,height:rowHeight}}));return{...state,bounds:{x,y,width,height},cells,gutter,headerHeight,footerHeight,rowHeight,omittedLeading:start,omittedTrailing:all.length-start-columns.length}}function createTeachingByteDifference(painter){return options=>{const layout=layoutByteDifference(options);const{x,y,width,height,fontSize=28,fill="#101820",stroke="#516376",textColor="#E9EFFF",mutedColor="#91A3B8",scanColor="#63DEEC",changeColor="#F4D477",beforeLabel="Before",afterLabel="After"}=options;const label=(value,bounds4,size,color=textColor)=>painter.labelScope(bounds4,()=>{painter.text(value,bounds4.x+bounds4.width/2,bounds4.y+bounds4.height/2+size*.34,size,color,"center","mono")},{padding:4});painter.container(layout.bounds,()=>{label("Prefix/suffix alignment; positional middle; not minimum edits",{x,y,width,height:layout.headerHeight},fontSize*.63,mutedColor);for(const[row,name]of[beforeLabel,afterLabel].entries()){label(name,{x,y:y+layout.headerHeight+row*layout.rowHeight,width:layout.gutter-8,height:layout.rowHeight},fontSize*.72)}for(const cell of layout.cells){const visited=cell.alignmentIndex<layout.scannedColumns;const color=visited?cell.column.kind==="equal"?mutedColor:changeColor:stroke;for(const[byte,bounds4]of[[cell.column.before,cell.beforeBounds],[cell.column.after,cell.afterBounds]]){painter.rect(bounds4.x+2,bounds4.y+2,bounds4.width-4,bounds4.height-4,fill,color,0);label(byte?`@${byte.offset}`:"none",{...bounds4,height:bounds4.height*.3},fontSize*.65,mutedColor);label(byte?byte.value.toString(16).padStart(2,"0").toUpperCase():"--",{...bounds4,y:bounds4.y+bounds4.height*.3,height:bounds4.height*.35},fontSize,visited?textColor:mutedColor);label(byte?escapedByte(byte.value):"no byte",{...bounds4,y:bounds4.y+bounds4.height*.65,height:bounds4.height*.35},fontSize*.7,mutedColor)}}if(!layout.cells.length){for(const row of[0,1])label("empty",{x:x+layout.gutter,y:y+layout.headerHeight+row*layout.rowHeight,width:width-layout.gutter,height:layout.rowHeight},fontSize,mutedColor)}const scanPosition=layout.progress*layout.comparison.columns.length-layout.omittedLeading;if(layout.cells.length&&scanPosition>=0&&scanPosition<=layout.cells.length){const cellWidth=layout.cells[0].beforeBounds.width;const cursor=Math.max(1,Math.min(width-layout.gutter-1,scanPosition*cellWidth));painter.rect(x+layout.gutter+cursor-1,y+layout.headerHeight-7,2,5,scanColor,void 0,0)}const verdict=layout.verdict===null?"Verdict held":layout.verdict==="equal"?"Bytes equal":"Bytes differ";label(`${layout.omittedLeading} columns before window; ${layout.omittedTrailing} after \xB7 ${verdict}`,{x,y:y+height-layout.footerHeight,width,height:layout.footerHeight},fontSize*.66,layout.verdict===null?mutedColor:textColor)},{padding:0});return layout}}function tokens(input,name){if(!Array.isArray(input))throw new Error(`Token history ${name} must be an array`);return Object.freeze(input.map(item=>{if(!item||typeof item.id!=="string"||!item.id.trim()||item.id!==item.id.trim()){throw new Error("Token occurrence IDs must be nonempty without surrounding whitespace")}if(!(typeof item.token==="string"&&item.token.trim())&&!(typeof item.token==="number"&&Number.isSafeInteger(item.token)&&item.token>=0)){throw new Error("History tokens require nonempty text or a nonnegative safe integer vocabulary ID")}return Object.freeze({id:item.id,token:item.token})}))}function equal(left,right){return left.id===right.id&&left.token===right.token}function prefix(part,whole,name){if(part.length>whole.length||part.some((token,index)=>!equal(token,whole[index]))){throw new Error(`Token history ${name} must preserve the exact ordered occurrence prefix`)}}function tokenHistoryState(options){const prompt=tokens(options.prompt,"prompt"),accepted=tokens(options.accepted,"accepted");const processed=tokens(options.processed,"processed"),emitted=tokens(options.emitted,"emitted");const history=Object.freeze([...prompt,...accepted]);if(new Set(history.map(token=>token.id)).size!==history.length){throw new Error("Token history requires distinct occurrence IDs, including repeated vocabulary tokens")}prefix(processed,history,"processed");prefix(emitted,accepted,"emitted");if(accepted.length&&processed.length<prompt.length)throw new Error("Accepted output requires the complete processed prompt");if(accepted.length&&processed.length<prompt.length+accepted.length-1){throw new Error("Ordinary decoding permits at most one accepted token awaiting processing")}const phase=options.phase??"resident";if(!["resident","dropped","replay"].includes(phase))throw new Error("Unknown token history phase");if(phase==="replay"&&options.replayProgress===void 0)throw new Error("Replay requires explicit progress");const replayProgress=options.replayProgress??0;if(!Number.isFinite(replayProgress)||replayProgress<0||replayProgress>1){throw new Error("Replay progress must be finite between zero and one")}const position2=replayProgress*processed.length;const completed=phase==="resident"?processed.length:phase==="dropped"?0:Math.floor(position2);const fraction=position2-Math.floor(position2);const moving=phase==="replay"&&fraction>0&&completed<processed.length?Object.freeze({token:processed[completed],position:completed,progress:fraction}):null;return Object.freeze({prompt,accepted,processed,emitted,history,phase,replayProgress,kv:Object.freeze(processed.slice(0,completed)),pendingAccepted:Object.freeze(accepted.filter((_,index)=>prompt.length+index>=processed.length)),moving})}function assertTokenHistoryTransition(before,after){before=tokenHistoryState(before);after=tokenHistoryState(after);prefix(before.prompt,after.prompt,"prompt transition");if(before.prompt.length!==after.prompt.length)throw new Error("A request prompt cannot change during its history");prefix(before.accepted,after.accepted,"accepted transition");prefix(before.emitted,after.emitted,"emitted transition");if(before.phase!=="resident"||after.phase!=="resident"){if(before.accepted.length!==after.accepted.length||before.emitted.length!==after.emitted.length){throw new Error("Drop and replay transitions cannot sample or emit new output")}prefix(before.processed,after.processed,"replay target");if(before.processed.length!==after.processed.length)throw new Error("Replay must rebuild the retained processed prefix")}else if(after.processed.length<before.processed.length){throw new Error("Resident processed history cannot shrink without an explicit drop or replay")}}function createTeachingTokenHistory(painter){return options=>{const state=tokenHistoryState(options);const{x,y,width,height,fontSize=28,gap=8,labelWidth=245,focusPrefix}=options;if(![x,y,x+width,y+height,width,height,fontSize,gap,labelWidth].every(Number.isFinite)||width<=0||height<=0||fontSize<=0||gap<0||labelWidth<=0){throw new Error("Token history drawing bounds and sizes must be finite and positive")}const columns=Math.max(1,state.history.length),top=fontSize*1.9,bottom=fontSize*2;const cellWidth=(width-labelWidth-gap*(columns-1)-4)/columns;const laneHeight=(height-top-bottom)/5,cellHeight=laneHeight-gap;if(cellWidth<fontSize*2.2||cellHeight<fontSize*1.6||labelWidth<fontSize*5){throw new Error("Token history bounds must fit its occurrence columns and five readable lanes")}const color={prompt:"#7FA7FF",accepted:"#92E28C",processed:"#63DEEC",kv:"#63DEEC",emitted:"#92E28C",pending:"#FFD75E",empty:"#586278",text:"#F2EFE6",fill:"#141820",...options.colors};const lanes=[{id:"prompt",label:"Prompt",tokens:state.prompt,offset:0},{id:"accepted",label:"Accepted output",tokens:state.accepted,offset:state.prompt.length},{id:"processed",label:"Processed prefix",tokens:state.processed,offset:0},{id:"kv",label:"Resident KV",tokens:state.kv,offset:0},{id:"emitted",label:"Already delivered",tokens:state.emitted,offset:state.prompt.length}];const pending2=new Set(state.pendingAccepted.map(token=>token.id));const bounds4={x,y,width,height};const target=(id,draw2)=>{if(id&&painter.target)painter.target(id,draw2);else draw2()};const cell=(position2,row)=>({x:x+labelWidth+1+position2*(cellWidth+gap),y:y+top+row*laneHeight,width:cellWidth,height:cellHeight});const paintToken=(token,shape2,stroke,fill=color.fill)=>{painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,fill,stroke,7);painter.labelScope(shape2,()=>painter.text(String(token.token),shape2.x+shape2.width/2,shape2.y+shape2.height/2+fontSize*.34,fontSize,color.text,"center","mono"),{padding:5})};painter.container(bounds4,()=>{for(let position2=0;position2<state.history.length;position2+=1){const shape2=cell(position2,0);painter.labelScope({...shape2,y,height:top},()=>painter.text(`position ${position2}`,shape2.x+shape2.width/2,y+fontSize,fontSize*.7,color.empty,"center"),{padding:3})}lanes.forEach((lane,row)=>target(focusPrefix?`${focusPrefix}-${lane.id}`:void 0,()=>{const labelBounds={x,y:y+top+row*laneHeight,width:labelWidth-gap,height:cellHeight};painter.labelScope(labelBounds,()=>painter.text(lane.label,x+5,labelBounds.y+cellHeight/2+fontSize*.34,fontSize*.82,color[lane.id]),{padding:3});for(let position2=0;position2<columns;position2+=1){const shape2=cell(position2,row),token=lane.tokens[position2-lane.offset];if(token){const isPending=lane.id==="accepted"&&pending2.has(token.id);target(isPending&&focusPrefix?`${focusPrefix}-pending`:void 0,()=>paintToken(token,shape2,isPending?color.pending:color[lane.id],lane.id==="processed"?"transparent":color.fill))}else painter.rect(shape2.x,shape2.y,shape2.width,shape2.height,"transparent",color.empty,7)}}));if(state.moving){const from=cell(state.moving.position,2),to2=cell(state.moving.position,3);const progress=state.moving.progress;const settle=Math.max(0,(progress-.65)/.35);const grow2=Math.max(0,(progress-.8)/.2);const measuredWidth=painter.measureText?.(String(state.moving.token.token),fontSize,"mono");if(measuredWidth!==void 0&&(!Number.isFinite(measuredWidth)||measuredWidth<0)){throw new Error("Token history measured text width must be finite and nonnegative")}const copyWidth=Math.min(from.width,Math.max(fontSize*3,measuredWidth===void 0?from.width:measuredWidth+10));const copyHeight=Math.min(from.height,fontSize*1.8);const movingWidth=copyWidth+(from.width-copyWidth)*grow2;const movingHeight=copyHeight+(from.height-copyHeight)*grow2;const startInset=Math.min(7,from.width-copyWidth);const startCenterX=from.x+startInset+copyWidth/2;const centerX=startCenterX+(from.x+from.width/2-startCenterX)*settle;const centerY=from.y+from.height/2+(to2.y-from.y)*progress;const moving={x:centerX-movingWidth/2,y:centerY-movingHeight/2,width:movingWidth,height:movingHeight};target(focusPrefix?`${focusPrefix}-replay`:void 0,()=>paintToken(state.moving.token,moving,color.kv))}const pendingText=state.pendingAccepted.map(token=>String(token.token)).join(", ");const message=state.phase==="replay"?"Replay rebuilds KV; no sampling or delivery":state.phase==="dropped"?"KV released; accepted and delivered history retained":pendingText?`Accepted but unprocessed: ${pendingText}`:"All accepted positions are processed";painter.labelScope({x,y:y+height-bottom,width,height:bottom},()=>painter.text(message,x+width/2,y+height-fontSize*.6,fontSize*.82,state.phase==="replay"?color.kv:color.pending,"center"),{padding:3})},{padding:0});return state}}var INK="#8D9CB9";var ACCENT="#63DEEC";var PANEL="#18283B";function finite4(value,name){if(!Number.isFinite(value))throw new Error(`${name} must be finite`)}function positive4(value,name){finite4(value,name);if(value<=0)throw new Error(`${name} must be positive`)}function boundsOf(options){finite4(options.x,"Teaching x");finite4(options.y,"Teaching y");positive4(options.width,"Teaching width");positive4(options.height,"Teaching height");return{x:options.x,y:options.y,width:options.width,height:options.height}}function amount(value,name="Teaching progress"){finite4(value,name);return Math.max(0,Math.min(1,value))}function domainOf(domain,name){finite4(domain[0],`${name} start`);finite4(domain[1],`${name} end`);if(domain[1]<=domain[0]||!Number.isFinite(domain[1]-domain[0])){throw new Error(`${name} must have a finite positive span`)}return[domain[0],domain[1]]}function createTeachingCanvas(painter){const components=createCanvasComponents(painter);function axes2(options){let bounds4=boundsOf(options);const xDomain=domainOf(options.xDomain,"Plot x domain");const yDomain=domainOf(options.yDomain,"Plot y domain");if(options.equalUnits){const xSpan=xDomain[1]-xDomain[0];const ySpan=yDomain[1]-yDomain[0];const pixelsPerUnit=Math.min(bounds4.width/xSpan,bounds4.height/ySpan);const width2=xSpan*pixelsPerUnit;const height2=ySpan*pixelsPerUnit;bounds4=boundsOf({x:bounds4.x+(bounds4.width-width2)/2,y:bounds4.y+(bounds4.height-height2)/2,width:width2,height:height2})}const{x,y,width,height}=bounds4;const{color=INK,gridColor,fontSize=28,xTicks=[],yTicks=[],formatX=String,formatY=String}=options;positive4(fontSize,"Axis font size");xTicks.forEach(tick=>finite4(tick,"Axis x tick"));yTicks.forEach(tick=>finite4(tick,"Axis y tick"));const plot={bounds:bounds4,xDomain,yDomain,point(px,py){finite4(px,"Plot point x");finite4(py,"Plot point y");const point={x:x+(px-xDomain[0])/(xDomain[1]-xDomain[0])*width,y:y+height-(py-yDomain[0])/(yDomain[1]-yDomain[0])*height};finite4(point.x,"Mapped point x");finite4(point.y,"Mapped point y");return point}};for(const tick of xTicks){if(tick<xDomain[0]||tick>xDomain[1])continue;const point=plot.point(tick,yDomain[0]);if(gridColor)painter.path([{x:point.x,y},{x:point.x,y:y+height}],{color:gridColor,width:1,clip:bounds4});painter.line(point.x,y+height,point.x,y+height+7,color,2);painter.text(formatX(tick),point.x,y+height+36,fontSize,color,"center")}for(const tick of yTicks){if(tick<yDomain[0]||tick>yDomain[1])continue;const point=plot.point(xDomain[0],tick);if(gridColor)painter.path([{x,y:point.y},{x:x+width,y:point.y}],{color:gridColor,width:1,clip:bounds4});painter.line(x-7,point.y,x,point.y,color,2);painter.text(formatY(tick),x-18,point.y+9,fontSize,color,"right")}painter.line(x,y+height,x+width,y+height,color,2);painter.line(x,y,x,y+height,color,2);if(options.xLabel)painter.text(options.xLabel,x+width/2,y+height+72,30,color,"center");if(options.yLabel)painter.text(options.yLabel,x,y-26,30,color,"left");return plot}function curve2(options){const{plot,points,color,width=4,progress=1}=options;positive4(width,"Curve width");const mapped=points.map(point=>plot.point(point.x,point.y));const visible=tracePolyline(mapped,progress);if(visible.length>1)painter.path(visible,{color,width,clip:plot.bounds});return visible}function scatter2(options){const{plot,points,color=ACCENT,radius=7,opacity=1}=options;positive4(radius,"Scatter radius");const alpha3=amount(opacity,"Scatter opacity");const projected=points.map(point=>{positive4(point.radius??radius,"Scatter point radius");return{...plot.point(point.x,point.y),radius:point.radius??radius,color:point.color??color,inDomain:point.x>=plot.xDomain[0]&&point.x<=plot.xDomain[1]&&point.y>=plot.yDomain[0]&&point.y<=plot.yDomain[1]}});const shapes=[];if(alpha3===0)return shapes;painter.opacity(alpha3,()=>{for(const point of projected){if(!point.inDomain)continue;shapes.push(painter.circle(point.x,point.y,point.radius,point.color))}});return shapes}function bars(options){const bounds4=boundsOf(options);const{x,y,width,height}=bounds4;const{values,labels,colors:colors2,color=ACCENT,progress=1,showValues=false,format=String,fontSize=28,gap=20}=options;positive4(fontSize,"Bar font size");finite4(gap,"Bar gap");if(gap<0)throw new Error("Bar gap must be nonnegative");values.forEach(value=>{finite4(value,"Bar value");if(value<0)throw new Error("Bar values must be nonnegative")});if(labels&&labels.length!==values.length)throw new Error("Bar labels must match values");if(colors2&&colors2.length!==values.length)throw new Error("Bar colors must match values");const maximumValue=values.reduce((maximum2,value)=>Math.max(maximum2,value),0);const maximum=options.max??(maximumValue||1);positive4(maximum,"Bar maximum");if(maximum<maximumValue)throw new Error("Bar maximum must contain every value");const reveal2=amount(progress);if(!values.length)return{bars:[],slots:[],bounds:bounds4};const barWidth=(width-gap*(values.length-1))/values.length;positive4(barWidth,"Bar width after gaps");const shapes=[];const slots=[];values.forEach((value,index)=>{const left=x+index*(barWidth+gap);const barHeight=value/maximum*height*reveal2;slots.push({x:left,y,width:barWidth,height});shapes.push(barHeight>0?painter.rect(left,y+height-barHeight,barWidth,barHeight,colors2?.[index]??color,void 0,Math.min(8,barWidth/2,barHeight/2)):null);if(labels)painter.text(labels[index],left+barWidth/2,y+height+38,fontSize,INK,"center");if(showValues&&reveal2>0)painter.text(format(value),left+barWidth/2,y+height-barHeight-14,fontSize,colors2?.[index]??color,"center")});return{bars:shapes,slots,bounds:bounds4}}function flowGraph(options){const{nodes,edges,stroke=ACCENT,fill=PANEL,textColor="#FFFFFF",padding=12}=options;finite4(padding,"Flow node padding");if(padding<0)throw new Error("Flow node padding must be nonnegative");const descriptors=Object.create(null);for(const node of nodes){if(!node.id||Object.hasOwn(descriptors,node.id))throw new Error("Flow node IDs must be nonempty and unique");const bounds4=boundsOf(node);positive4(node.fontSize??30,"Flow node font size");finite4(node.radius??14,"Flow node radius");if((node.radius??14)<0)throw new Error("Flow node radius must be nonnegative");descriptors[node.id]={...bounds4,radius:node.radius??14}}for(const edge of edges){if(!Object.hasOwn(descriptors,edge.from)||!Object.hasOwn(descriptors,edge.to))throw new Error("Flow edge must reference existing nodes");if(edge.from===edge.to)throw new Error("Flow edges must connect distinct nodes");if(edge.progress!==void 0)amount(edge.progress);if(edge.width!==void 0)positive4(edge.width,"Flow edge width");for(const gap of[edge.gap,edge.fromGap,edge.toGap]){if(gap!==void 0)finite4(gap,"Flow edge gap")}}const target=(id,draw2)=>id&&painter.target?painter.target(id,draw2):draw2();const routes=edges.map(edge=>target(edge.focusTarget,()=>{const{from,to:to2,progress,focusTarget:_focusTarget,...style}=edge;const route=painter.connect(descriptors[from],descriptors[to2],{color:stroke,...style});if(progress!==void 0)components.particle({points:[route.from,route.to],progress,radius:7,fill:style.color??stroke});return route}));for(const node of nodes){const shape2=target(node.focusTarget,()=>components.card({...descriptors[node.id],label:node.label,id:node.id,fill:node.fill??fill,stroke:node.color??stroke,textColor,fontSize:node.fontSize??30,padding}));Object.assign(descriptors[node.id],shape2)}return{nodes:descriptors,routes}}return{axes:axes2,curve:curve2,scatter:scatter2,bars,flowGraph,transfer:createTeachingTransfer(painter),routedTransfer:createTeachingRoutedTransfer(painter),grid:createTeachingGrid(painter),timeline:createTeachingTimeline(painter),allocation:createTeachingAllocation(painter),vectorAccumulation:createTeachingVectorAccumulation(painter),categoricalSampling:createTeachingCategoricalSampling(painter),byteDifference:createTeachingByteDifference(painter),tokenHistory:createTeachingTokenHistory(painter),...createTeachingValueChange(painter),...createTeachingFocus(painter)}}function position(beat,progress){if(!Number.isSafeInteger(beat)||beat<0)throw new Error("Cue beat must be a nonnegative safe integer");if(!Number.isFinite(progress)||progress<0||progress>1)throw new Error("Cue progress must be between zero and one");if(progress===1){if(!Number.isSafeInteger(beat+1))throw new Error("Cue position exceeds the safe integer range");return{beat:beat+1,beatP:0}}return{beat,beatP:progress}}function compare(left,right){return left.beat===right.beat?left.beatP-right.beatP:left.beat-right.beat}function createCueTrack(options){const ids=new Set;const entry=({id,snapshot})=>{if(typeof id!=="string"||!id.trim()||ids.has(id))throw new Error("Cue IDs must be nonempty and unique");ids.add(id);return Object.freeze({id,snapshot})};const initial=entry(options.initial);const cues=options.cues.map(cue=>({position:position(cue.beat,cue.at),value:entry(cue)}));for(let index=1;index<cues.length;index+=1){if(compare(cues[index-1].position,cues[index].position)>=0){throw new Error("Cue positions must be strictly increasing")}}return Object.freeze({sample(current){const at=position(current.beat,current.beatP);let low=0,high=cues.length;while(low<high){const middle=Math.floor((low+high)/2);if(compare(cues[middle].position,at)<=0)low=middle+1;else high=middle}return low===0?initial:cues[low-1].value}})}function clampProgress2(progress){if(!Number.isFinite(progress))throw new Error("Camera progress must be finite");return Math.max(0,Math.min(1,progress))}function assertCamera(camera,context){if(!Number.isFinite(camera.x)||!Number.isFinite(camera.y)){throw new Error(`${context} coordinates must be finite`)}if(!Number.isFinite(camera.zoom)||camera.zoom<=0){throw new Error(`${context} zoom must be finite and greater than zero`)}}function assertViewport(viewport){if(!Number.isFinite(viewport.width)||viewport.width<=0){throw new Error("Camera viewport width must be finite and greater than zero")}if(!Number.isFinite(viewport.height)||viewport.height<=0){throw new Error("Camera viewport height must be finite and greater than zero")}}function assertZoomConstraints(options){const{minZoom,maxZoom}=options;if(minZoom!==void 0&&(!Number.isFinite(minZoom)||minZoom<=0)){throw new Error("Camera minZoom must be finite and greater than zero")}if(maxZoom!==void 0&&(!Number.isFinite(maxZoom)||maxZoom<=0)){throw new Error("Camera maxZoom must be finite and greater than zero")}if(minZoom!==void 0&&maxZoom!==void 0&&minZoom>maxZoom){throw new Error("Camera minZoom cannot exceed maxZoom")}}function assertZoomInRange(camera,options){if(options.minZoom!==void 0&&camera.zoom<options.minZoom||options.maxZoom!==void 0&&camera.zoom>options.maxZoom){throw new Error("Camera zoom is outside the configured range")}}function interpolateLinear(from,to2,progress){return from*(1-progress)+to2*progress}function interpolateCamera(from,to2,progress,options={}){assertCamera(from,"Camera start");assertCamera(to2,"Camera end");assertZoomConstraints(options);assertZoomInRange(from,options);assertZoomInRange(to2,options);const amount2=clampProgress2(progress);if(amount2===0)return{...from};if(amount2===1)return{...to2};const eased=(options.easing??smoothstep)(amount2);if(!Number.isFinite(eased))throw new Error("Camera easing must return a finite number");const t=Math.max(0,Math.min(1,eased));if(t===0)return{...from};if(t===1)return{...to2};const camera={x:interpolateLinear(from.x,to2.x,t),y:interpolateLinear(from.y,to2.y,t),zoom:Math.exp(Math.log(from.zoom)*(1-t)+Math.log(to2.zoom)*t)};assertCamera(camera,"Camera result");assertZoomInRange(camera,options);return camera}function cameraSvgTransform(camera,viewport){assertCamera(camera,"Camera");assertViewport(viewport);return`translate(${viewport.width/2} ${viewport.height/2}) scale(${camera.zoom}) translate(${-camera.x} ${-camera.y})`}function projectWorldPoint(point,camera,viewport){if(!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error("World point coordinates must be finite")}assertCamera(camera,"Camera");assertViewport(viewport);const projected={x:viewport.width/2+(point.x-camera.x)*camera.zoom,y:viewport.height/2+(point.y-camera.y)*camera.zoom};if(!Number.isFinite(projected.x)||!Number.isFinite(projected.y)){throw new Error("Projected world point coordinates must be finite")}return projected}var DEFAULT_MORPH_SAMPLES=64;var MAX_MORPH_SAMPLES=4096;function clampProgress3(progress){if(!Number.isFinite(progress))throw new Error("Polyline morph progress must be finite");return Math.max(0,Math.min(1,progress))}function validatePolyline(points,context){if(!Array.isArray(points)||points.length===0){throw new Error(`${context} polyline must be a non-empty array`)}for(let index=0;index<points.length;index+=1){const point=points[index];if(!point||!Number.isFinite(point.x)||!Number.isFinite(point.y)){throw new Error(`${context} point ${index} coordinates must be finite`)}}}function validateSamples(samples){if(!Number.isInteger(samples)||samples<2){throw new Error("Polyline morph samples must be an integer of at least 2")}if(samples>MAX_MORPH_SAMPLES){throw new Error(`Polyline morph samples cannot exceed ${MAX_MORPH_SAMPLES}`)}}function resamplePolyline(points,samples){const lengths=points.slice(1).map((point,index)=>Math.hypot(point.x-points[index].x,point.y-points[index].y));const total=lengths.reduce((sum,length)=>sum+length,0);if(!Number.isFinite(total))throw new Error("Polyline morph arc length must be finite");if(total===0)return Array.from({length:samples},()=>({...points[0]}));let segment=0;let offset=0;return Array.from({length:samples},(_,index)=>{if(index===samples-1)return{...points[points.length-1]};const distance=total*(index/(samples-1));while(segment<lengths.length-1&&(lengths[segment]===0||distance>offset+lengths[segment])){offset+=lengths[segment++]}const t=(distance-offset)/lengths[segment];const from=points[segment],to2=points[segment+1];return{x:from.x*(1-t)+to2.x*t,y:from.y*(1-t)+to2.y*t}})}function createPolylineMorph(from,to2,options={}){validatePolyline(from,"Start");validatePolyline(to2,"End");const samples=options.samples??DEFAULT_MORPH_SAMPLES;validateSamples(samples);const startSamples=resamplePolyline(from,samples);const endSamples=resamplePolyline(to2,samples);const easing=options.easing??smoothstep;return progress=>{const amount2=clampProgress3(progress);const eased=amount2===0||amount2===1?amount2:easing(amount2);if(!Number.isFinite(eased))throw new Error("Polyline morph easing must return a finite number");const t=Math.max(0,Math.min(1,eased));return startSamples.map((start,index)=>{const end=endSamples[index];return{x:start.x*(1-t)+end.x*t,y:start.y*(1-t)+end.y*t}})}}function morphPolyline(from,to2,progress,options={}){return createPolylineMorph(from,to2,options)(progress)}function graphImportResult(source,graph2,diagnostics){if(graph2.nodes.length===0&&diagnostics.every(({severity})=>severity!=="error")){diagnostics.push({code:"import.empty",severity:"error",message:"The source contains no graph nodes to import.",line:1,column:1,excerpt:""})}const ok=diagnostics.every(({severity})=>severity!=="error");return ok?{source,ok,graph:graph2,diagnostics}:{source,ok,diagnostics}}function addImportDiagnostic(diagnostics,sourceLines,line2,code,severity,message,column=1){diagnostics.push({code,severity,message,line:line2,column,excerpt:(sourceLines[line2-1]??"").trim().slice(0,180)})}var ID_PATTERN=/^[A-Za-z_][A-Za-z0-9_-]*/;var CONNECTORS=["-.->","-->","---"];function skipWhitespace(line2,index){while(index<line2.length&&/\s/.test(line2[index]??""))index++;return index}function readDelimited(line2,start,close){let inDoubleQuote=false;let escaped=false;for(let index=start;index<line2.length;index++){const character=line2[index];if(inDoubleQuote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')inDoubleQuote=false;continue}if(character==='"'){inDoubleQuote=true;continue}if(line2.startsWith(close,index)){return{value:line2.slice(start,index),next:index+close.length}}}return void 0}function decodeLabel(raw){const value=raw.trim();if(!value.startsWith('"'))return value;if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}function labelHasUnsupportedMarkup(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\n|\r/.test(label)}function readEndpoint(line2,from){let index=skipWhitespace(line2,from);const id=line2.slice(index).match(ID_PATTERN)?.[0];if(!id)return void 0;index+=id.length;const afterId=skipWhitespace(line2,index);if(afterId>=line2.length)return{id,label:id,shape:"rectangle",next:afterId};const rest=line2.slice(afterId);const delimiters=[{open:"[(",close:")]",lossy:true},{open:"([",close:"])",lossy:true},{open:"((",close:"))",lossy:true},{open:"{{",close:"}}",lossy:true},{open:"[",close:"]",lossy:false},{open:"(",close:")",lossy:true},{open:"{",close:"}",lossy:true}];const delimiter=delimiters.find(({open})=>rest.startsWith(open));if(!delimiter)return{id,label:id,shape:"rectangle",next:index};const content=readDelimited(line2,afterId+delimiter.open.length,delimiter.close);if(!content)return void 0;const label=decodeLabel(content.value);if(label===void 0)return void 0;return{id,label,shape:delimiter.lossy?"lossy":"rectangle",next:content.next}}function addNode(state,endpoint,groupId,line2,sourceLines,diagnostics,explicitlyDeclared){if(state.groupIds.has(endpoint.id)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid id "${endpoint.id}" is already used by a subgraph and cannot also be a node.`);return false}if(labelHasUnsupportedMarkup(endpoint.label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid label for node "${endpoint.id}" uses HTML or Markdown formatting that GraphDiagram cannot preserve.`);return false}const existingIndex=state.nodeIndexes.get(endpoint.id);if(existingIndex!==void 0){const existing=state.nodes[existingIndex];if(!existing)return false;if(groupId&&existing.group&&existing.group!==groupId){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is assigned to more than one subgraph; GraphDiagram nodes support one group.`);return false}if(groupId&&!existing.group){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`Mermaid node "${endpoint.id}" is referenced both inside and outside a subgraph; its group membership is ambiguous.`);return false}if(explicitlyDeclared)existing.label=endpoint.label}else{state.nodeIndexes.set(endpoint.id,state.nodes.length);state.nodes.push({id:endpoint.id,label:endpoint.label,...groupId?{group:groupId}:{}})}if(endpoint.shape==="lossy"&&!state.warnedShapes.has(endpoint.id)){state.warnedShapes.add(endpoint.id);addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`Mermaid node "${endpoint.id}" uses a non-rectangular shape; it will render as a generic GraphDiagram node.`)}return true}function parseNodeOrEdgeLine(line2,groupId,lineNumber,sourceLines,state,diagnostics){const first=readEndpoint(line2,0);if(!first){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Could not parse this Mermaid node or edge statement.");return}const connectorStart=skipWhitespace(line2,first.next);const hasConnector=CONNECTORS.some(connector2=>line2.startsWith(connector2,connectorStart));if(!addNode(state,first,groupId,lineNumber,sourceLines,diagnostics,!hasConnector))return;let previous=first;let cursor=first.next;while(true){cursor=skipWhitespace(line2,cursor);if(cursor>=line2.length)return;const connector2=CONNECTORS.find(candidate=>line2.startsWith(candidate,cursor));if(!connector2){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Only Mermaid -->, ---, and -.-> connections are supported; chained or styled statements must be split or simplified.",cursor+1);return}cursor+=connector2.length;cursor=skipWhitespace(line2,cursor);let edgeLabel;if(line2[cursor]==="|"){const end=line2.indexOf("|",cursor+1);if(end<0){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid edge label is missing its closing |.",cursor+1);return}edgeLabel=line2.slice(cursor+1,end).trim();cursor=skipWhitespace(line2,end+1);if(labelHasUnsupportedMarkup(edgeLabel)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid edge labels with HTML or Markdown formatting cannot be represented as plain GraphDiagram labels.",cursor+1);return}}const next=readEndpoint(line2,cursor);if(!next){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid connection has no supported target node.",cursor+1);return}if(!addNode(state,next,groupId,lineNumber,sourceLines,diagnostics,false))return;const edge={from:previous.id,to:next.id,...edgeLabel!==void 0?{label:edgeLabel}:{},...connector2==="---"?{arrow:"none"}:connector2==="-.->"?{arrow:"forward",style:"dotted"}:{arrow:"forward"}};state.edges.push(edge);state.edgeReferences.push({id:previous.id,line:lineNumber},{id:next.id,line:lineNumber});previous=next;cursor=next.next}}function importMermaidGraph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const state={nodes:[],nodeIndexes:new Map,groups:[],groupIds:new Set,edges:[],edgeReferences:[],warnedShapes:new Set};let direction2="TB";let currentGroup;let sawHeader=false;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(line2.startsWith("%%{")){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid directives and embedded configuration are not imported.");continue}if(line2.startsWith("%%"))continue;if(!sawHeader){const header=line2.match(/^(?:flowchart|graph)(?:\s+(LR|RL|TB|TD|BT))?$/i);if(!header){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error",'Expected a Mermaid flowchart or graph header such as "flowchart LR".');sawHeader=true;continue}sawHeader=true;const sourceDirection=header[1]?.toUpperCase();direction2=sourceDirection==="TD"?"TB":sourceDirection??"TB";continue}const subgraph=line2.match(/^subgraph\s+([A-Za-z_][A-Za-z0-9_-]*)(?:\s+\[([^\]]*)\])?\s*$/i);if(subgraph){if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Nested Mermaid subgraphs are not imported.");continue}const id=subgraph[1];if(!id)continue;if(state.groupIds.has(id)||state.nodeIndexes.has(id)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph id "${id}" conflicts with an existing group or node.`);continue}const rawLabel=subgraph[2];const label=rawLabel===void 0?id:decodeLabel(rawLabel);if(label===void 0||labelHasUnsupportedMarkup(label)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error",`Mermaid subgraph "${id}" uses a label format that cannot be preserved.`);continue}currentGroup=id;state.groupIds.add(id);state.groups.push({id,label});continue}if(/^subgraph\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_syntax","error","Use a simple Mermaid subgraph declaration with an identifier and optional bracketed label.");continue}if(/^end\s*$/i.test(line2)){if(!currentGroup)addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.parse_error","error","Mermaid end has no matching subgraph.");else currentGroup=void 0;continue}if(/^direction\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,currentGroup?"import.unsupported_semantics":"import.parse_error","error",currentGroup?"Per-subgraph Mermaid direction cannot be represented by GraphDiagram.":"Set Mermaid graph direction in the flowchart or graph header.");continue}if(/^(?:click|class|classDef|style|linkStyle|accTitle|accDescr)\b/i.test(line2)){addImportDiagnostic(diagnostics,sourceLines,lineNumber,"import.unsupported_semantics","error","Mermaid classes, styling, accessibility directives, and click actions are not imported.");continue}parseNodeOrEdgeLine(line2,currentGroup,lineNumber,sourceLines,state,diagnostics)}if(!sawHeader){addImportDiagnostic(diagnostics,sourceLines,1,"import.parse_error","error","Missing Mermaid flowchart or graph header.")}if(currentGroup){addImportDiagnostic(diagnostics,sourceLines,sourceLines.length,"import.parse_error","error",`Mermaid subgraph "${currentGroup}" has no matching end.`)}for(const reference of state.edgeReferences){if(state.groupIds.has(reference.id)){addImportDiagnostic(diagnostics,sourceLines,reference.line,"import.unsupported_semantics","error",`Mermaid edges to or from subgraph "${reference.id}" cannot be represented as GraphDiagram node edges.`)}}const graph2={nodes:state.nodes,edges:state.edges,groups:state.groups,direction:direction2};return graphImportResult("mermaid",graph2,diagnostics)}function decodeD2Label(raw){const value=raw.trim();if(value.startsWith('"')){if(!value.endsWith('"'))return void 0;try{const decoded=JSON.parse(value);return typeof decoded==="string"?decoded:void 0}catch{return void 0}}if(value.startsWith("'")){if(!value.endsWith("'"))return void 0;return value.slice(1,-1).replace(/\\(['\\])/g,"$1")}return value}function hasMarkdownFormatting(label){return/<[^>]*>|`|\*\*|__|~~|(^|\s)\*[^*]|\b_[^_]+_\b|\[[^\]]+\]\(|(^|\n)\s{0,3}(?:#{1,6}\s|[-*+]\s|\d+\.\s)/.test(label)}function hasUnquotedHash(line2){let quote;let escaped=false;for(const character of line2){if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0;continue}if(character==='"'||character==="'")quote=character;else if(character==="#")return true}return false}function addNode2(nodes,id,label,line2,sourceLines,diagnostics,explicitLabel){if(hasMarkdownFormatting(label)){addImportDiagnostic(diagnostics,sourceLines,line2,"import.unsupported_semantics","error",`D2 label for "${id}" uses Markdown or HTML formatting that GraphDiagram cannot preserve.`);return false}const existing=nodes.get(id);if(existing){if(explicitLabel){existing.node.label=label}}else{nodes.set(id,{node:{id,label}})}return true}function reportUnsupported(diagnostics,sourceLines,line2,message,code="import.unsupported_syntax",column=1){addImportDiagnostic(diagnostics,sourceLines,line2,code,"error",message,column)}function importD2Graph(source){const sourceLines=source.split(/\r?\n/);const diagnostics=[];const nodesById=new Map;const edges=[];const shapes=new Map;let direction2="TB";let containerDepth=0;for(let index=0;index<sourceLines.length;index++){const lineNumber=index+1;const rawLine=sourceLines[index]??"";const line2=rawLine.trim();if(!line2)continue;if(containerDepth>0){const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,containerDepth+opens-closes);continue}if(line2.startsWith("#"))continue;if(hasUnquotedHash(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 inline comments and unquoted # text are not supported; use a comment line or quote the label.");continue}if(line2.includes(";")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 semicolon-separated statements are not supported; place one statement on each line.");continue}if(line2.includes("{")||line2.includes("}")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 containers and object-property blocks are not imported. Their contents are skipped to avoid treating nested shapes as top-level nodes.","import.unsupported_semantics");const opens=(rawLine.match(/\{/g)??[]).length;const closes=(rawLine.match(/\}/g)??[]).length;containerDepth=Math.max(0,opens-closes);continue}const directionMatch=line2.match(/^direction\s*:\s*(right|left|down|up)\s*$/i);if(directionMatch){const value=directionMatch[1]?.toLowerCase();direction2=value==="left"?"RL":value==="down"?"TB":value==="up"?"BT":"LR";continue}if(/^direction\b/i.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 direction must be right, left, down, or up.","import.parse_error");continue}const shapeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)\.shape\s*:\s*(.*?)\s*$/);if(shapeMatch){const id=shapeMatch[1];const shape2=decodeD2Label(shapeMatch[2]??"");if(!id||shape2===void 0||shape2===""){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 shape declaration needs a simple identifier and a shape value.","import.parse_error");continue}if(!nodesById.has(id))addNode2(nodesById,id,id,lineNumber,sourceLines,diagnostics,false);shapes.set(id,{value:shape2,line:lineNumber});continue}const edgeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*?)\s*(<->|->|<-|--)\s*([A-Za-z_][A-Za-z0-9_-]*?)(?:\s*:\s*(.*))?\s*$/);if(edgeMatch){const from=edgeMatch[1];const connector2=edgeMatch[2];const to2=edgeMatch[3];const rawLabel=edgeMatch[4];if(!from||!connector2||!to2)continue;let label;if(rawLabel!==void 0){label=decodeD2Label(rawLabel);if(label===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection label has invalid quotes.","import.parse_error");continue}if(hasMarkdownFormatting(label)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 connection labels with Markdown or HTML formatting cannot be represented as plain GraphDiagram labels.","import.unsupported_semantics");continue}}addNode2(nodesById,from,from,lineNumber,sourceLines,diagnostics,false);addNode2(nodesById,to2,to2,lineNumber,sourceLines,diagnostics,false);edges.push({from,to:to2,...label!==void 0?{label}:{},arrow:connector2==="<->"?"both":connector2==="<-"?"backward":connector2==="--"?"none":"forward"});continue}const nodeMatch=line2.match(/^([A-Za-z_][A-Za-z0-9_-]*)(?:\s*:\s*(.*))?$/);if(nodeMatch){const id=nodeMatch[1];const rawLabel=nodeMatch[2];if(!id)continue;let label=id;let explicitLabel=false;if(rawLabel!==void 0){const decoded=decodeD2Label(rawLabel);if(decoded===void 0){reportUnsupported(diagnostics,sourceLines,lineNumber,`D2 label for "${id}" has invalid quotes.`,"import.parse_error");continue}label=decoded;explicitLabel=true}addNode2(nodesById,id,label,lineNumber,sourceLines,diagnostics,explicitLabel);continue}if(line2.includes(".style")||line2.includes(".width")||line2.includes(".height")||line2.includes(".near")){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 styling, sizing, and positioning fields are not imported.","import.unsupported_semantics")}else if(/^[A-Za-z_][A-Za-z0-9_-]*\./.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"D2 dotted paths and shape properties are not supported outside the simple `.shape` declaration.")}else if(/(?:<->|->|<-|--)/.test(line2)){reportUnsupported(diagnostics,sourceLines,lineNumber,"Only one D2 connection between two simple identifiers per line is supported; chaining and connection properties are not imported.")}else{reportUnsupported(diagnostics,sourceLines,lineNumber,"Could not parse this D2 statement in the supported subset.","import.parse_error")}}if(containerDepth>0){reportUnsupported(diagnostics,sourceLines,sourceLines.length,"D2 object-property block has no matching closing brace.","import.parse_error")}for(const[id,{value,line:line2}]of shapes){if(value.toLowerCase()==="rectangle")continue;addImportDiagnostic(diagnostics,sourceLines,line2,"import.lossy_semantics","warning",`D2 shape "${value}" on "${id}" is reduced to a generic GraphDiagram node.`)}return graphImportResult("d2",{nodes:[...nodesById.values()].map(({node})=>node),edges,groups:[],direction:direction2},diagnostics)}import{mkdtemp,rm}from"fs/promises";import{AsyncLocalStorage}from"async_hooks";import{tmpdir}from"os";import{join}from"path";import parseCssColor2 from"parse-css-color";import{Children,isValidElement}from"react";var CHECK_DIAGNOSTIC_CODES=["accessibility.low_contrast","api.unsupported_prop","asset.warning","frame.load_error","frame.unknown_preset","layout.auto_size","layout.connector_congestion","layout.connector_unroutable","layout.overflow","layout.text_overlap","layout.text_overflow","layout.whitespace_imbalance","readability.small_text","render.error","render.svg_context","render.warning","style.unsupported"];var MAX_CONTRAST_NODES=5e3;var MAX_DIAGNOSTICS_PER_RULE=12;var MIN_TEXT_SIZE=8.5;var SVG_ONLY_ELEMENTS=new Set(["circle","clipPath","defs","ellipse","foreignObject","g","image","line","linearGradient","marker","mask","path","pattern","polygon","polyline","radialGradient","rect","stop","symbol","text","textPath","tspan","use"]);function hslToRgb2(hue,saturation,lightness){const h=(hue%360+360)%360;const s=saturation/100;const l=lightness/100;const chroma=(1-Math.abs(2*l-1))*s;const segment=h/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=l-chroma/2;return channels.map(channel=>Math.round((channel+offset)*255))}function colorFromCss(value){if(typeof value!=="string")return void 0;const parsed=parseCssColor2(value);if(!parsed||parsed.values.length<3)return void 0;const[r,g,b]=parsed.type==="hsl"?hslToRgb2(parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0):[parsed.values[0]??0,parsed.values[1]??0,parsed.values[2]??0];return{r,g,b,alpha:parsed.alpha}}function compositeOver(foreground,background){if(foreground.alpha>=1||!background)return foreground;const alpha3=foreground.alpha+background.alpha*(1-foreground.alpha);if(alpha3<=0)return{r:0,g:0,b:0,alpha:0};return{r:(foreground.r*foreground.alpha+background.r*background.alpha*(1-foreground.alpha))/alpha3,g:(foreground.g*foreground.alpha+background.g*background.alpha*(1-foreground.alpha))/alpha3,b:(foreground.b*foreground.alpha+background.b*background.alpha*(1-foreground.alpha))/alpha3,alpha:alpha3}}function isUnresolvedColor(value){if(typeof value!=="string"||value.trim()===""||colorFromCss(value))return false;return!["inherit","initial","revert","unset"].includes(value.trim().toLowerCase())}function channelLuminance(value){const normalized=value/255;return normalized<=.04045?normalized/12.92:((normalized+.055)/1.055)**2.4}function relativeLuminance(color){return .2126*channelLuminance(color.r)+.7152*channelLuminance(color.g)+.0722*channelLuminance(color.b)}function contrastRatio(foreground,background){const lighter=Math.max(relativeLuminance(foreground),relativeLuminance(background));const darker=Math.min(relativeLuminance(foreground),relativeLuminance(background));return(lighter+.05)/(darker+.05)}function numericFontWeight(value){if(typeof value==="number")return value;if(value==="bold")return 700;if(typeof value==="string"&&/^\d+$/.test(value))return Number(value);return void 0}function fontSizePixels(value,inherited){if(typeof value==="number")return value;if(typeof value!=="string")return inherited;const match=value.trim().match(/^(\d+(?:\.\d+)?|\.\d+)(px|pt|rem|em|%)?$/);if(!match?.[1])return inherited;const amount2=Number(match[1]);const unit=match[2]??"px";if(unit==="pt")return amount2*4/3;if(unit==="rem")return amount2*16;if(unit==="em")return amount2*(inherited??16);if(unit==="%")return amount2/100*(inherited??16);return amount2}function requiredContrast(context){const large=(context.fontSize??16)>=24||(context.fontSize??16)>=18.66&&(context.fontWeight??400)>=700;return large?3:4.5}function styleRecord(value){if(!value||typeof value!=="object"||Array.isArray(value))return{};return value}function hasDirectText(children){return Children.toArray(children).some(child=>typeof child==="string"||typeof child==="number")}function elementId(props){const value=props.id??props["data-vizmatic-id"];return typeof value==="string"&&value.trim()!==""?value.trim():void 0}function resolveFunctionComponent(node,trustedComponents){if(!isValidElement(node)||typeof node.type!=="function"||trustedComponents.has(node.type))return void 0;const component=node.type;if(component.__vizmaticPrimitive)return void 0;if(component.prototype?.isReactComponent)return void 0;try{return component(node.props)}catch{return void 0}}function analyzeScene(element,theme,trustedComponents,rootBackground2,svgComponents){const diagnostics=[];const seen=new Set;let visited=0;function visit(node,inherited,path,namespace){if(visited++>=MAX_CONTRAST_NODES||!isValidElement(node))return;const resolved=resolveFunctionComponent(node,trustedComponents);if(resolved!==void 0){visit(resolved,inherited,path,namespace);return}const props=node.props;const svgShape=svgComponents?.shapes.get(node.type)??(svgComponents&&typeof node.type==="string"&&SVG_ONLY_ELEMENTS.has(node.type)?`<${node.type}>`:void 0);if(namespace==="html"&&svgShape){diagnostics.push({code:"render.svg_context",severity:"error",theme,message:`${svgShape} requires an <svg> ancestor at ${path}; its SVG geometry will not render in an HTML layout.`,suggestion:"Place the element inside a native <svg> or an SVG container such as AxisPlot.",elementId:elementId(props),location:{path}})}const childNamespace=typeof node.type==="string"?node.type==="svg"?"svg":node.type==="foreignObject"?"html":namespace:typeof node.type==="function"?svgComponents?.children.get(node.type):namespace;const style=typeof node.type==="string"?styleRecord(props.style):{};const backgroundImage=typeof style.backgroundImage==="string"?style.backgroundImage.trim().toLowerCase():"";const backgroundShorthand=typeof style.background==="string"?style.background.trim():"";const isBackgroundWrapper=typeof node.type==="function"&&(trustedComponents.has(node.type)||Boolean(node.type.__vizmaticPrimitive));const wrapperBackground=isBackgroundWrapper?props.background:void 0;const hasUnresolvedBackground=backgroundImage!==""&&backgroundImage!=="none"||isUnresolvedColor(style.backgroundColor)||backgroundShorthand!==""&&backgroundShorthand.toLowerCase()!=="none"&&!colorFromCss(backgroundShorthand)||isUnresolvedColor(wrapperBackground);const ownBackground=colorFromCss(style.backgroundColor)??colorFromCss(style.background)??colorFromCss(wrapperBackground);const baseBackground=path==="root"&&isBackgroundWrapper&&colorFromCss(wrapperBackground)?void 0:inherited.background;const background=hasUnresolvedBackground?void 0:ownBackground?compositeOver(ownBackground,baseBackground):baseBackground;const color=typeof style.color==="string"&&style.color.trim().toLowerCase()==="currentcolor"?inherited.color:isUnresolvedColor(style.color)?void 0:colorFromCss(style.color)??inherited.color;const fontSize=fontSizePixels(style.fontSize,inherited.fontSize);const fontWeight=numericFontWeight(style.fontWeight)??inherited.fontWeight;const context={background,color,fontSize,fontWeight};if(typeof node.type==="string"&&hasDirectText(props.children)&&color&&background!==void 0&&background.alpha>=1){const renderedColor=compositeOver(color,background);const ratio=contrastRatio(renderedColor,background);const required=requiredContrast(context);if(ratio<required){const rounded=Math.round(ratio*100)/100;const key=`${rounded}:${required}:${path}`;if(!seen.has(key)){seen.add(key);diagnostics.push({code:"accessibility.low_contrast",severity:"warning",theme,message:`Text contrast is ${rounded}:1 at ${path}; ${required}:1 is recommended.`,suggestion:"Use a stronger text or background color token.",elementId:elementId(props),location:{path}})}}}Children.forEach(props.children,(child,index)=>visit(child,context,`${path}.${index}`,childNamespace))}visit(element,{background:colorFromCss(rootBackground2)},"root","html");return diagnostics}function containsLayoutNode(parent,child){const epsilon=.5;return child.left>=parent.left-epsilon&&child.top>=parent.top-epsilon&&child.left+child.width<=parent.left+parent.width+epsilon&&child.top+child.height<=parent.top+parent.height+epsilon}function textUnits(text2){return Array.from(text2.normalize("NFC")).reduce((sum,character)=>sum+((character.codePointAt(0)??0)>255?1.7:1),0)}function renderedTextNodes(nodes){const textNodes=[];const ancestors=[];for(const node of nodes){while(ancestors.length>0&&!containsLayoutNode(ancestors[ancestors.length-1].node,node)){ancestors.pop()}const inherited=ancestors[ancestors.length-1];const style=styleRecord(node.props.style);const fontSize=fontSizePixels(style.fontSize,inherited?.fontSize)??16;const textAlign=typeof style.textAlign==="string"?style.textAlign:inherited?.textAlign??"left";const text2=String(node.textContent??"").trim();if(text2&&typeof style.transform==="string"&&style.transform.includes("rotate"))continue;if(text2&&node.width>0&&node.height>0){const estimatedLines=Math.max(1,Math.round(node.height/Math.max(fontSize*1.5,1)));const paintHeight=Math.min(node.height,fontSize*.9+(estimatedLines-1)*fontSize*1.25);const unwrappedWidth=textUnits(text2)*fontSize*.56;const paintWidth=Math.min(node.width,unwrappedWidth);const horizontalInset=textAlign==="center"?(node.width-paintWidth)/2:textAlign==="right"||textAlign==="end"?node.width-paintWidth:0;textNodes.push({text:text2,elementId:elementId(node.props),left:node.left,top:node.top,width:node.width,height:node.height,paintLeft:node.left+horizontalInset,paintTop:node.top+(node.height-paintHeight)/2,paintWidth,paintHeight,fontSize})}else if(node.width>0&&node.height>0){ancestors.push({node,fontSize,textAlign})}}return textNodes}function textExcerpt(text2){const normalized=text2.replace(/\s+/g," ").trim();return normalized.length>40?`${normalized.slice(0,37)}...`:normalized}function meaningfulOverlap(a,b){const width=Math.min(a.paintLeft+a.paintWidth,b.paintLeft+b.paintWidth)-Math.max(a.paintLeft,b.paintLeft);const height=Math.min(a.paintTop+a.paintHeight,b.paintTop+b.paintHeight)-Math.max(a.paintTop,b.paintTop);if(width<2||height<2)return false;if(a.text===b.text&&a.left===b.left&&a.top===b.top&&a.width===b.width&&a.height===b.height)return false;const overlapArea=width*height;const smallerArea=Math.min(a.paintWidth*a.paintHeight,b.paintWidth*b.paintHeight);return overlapArea/smallerArea>=.08}function overlapCandidates(nodes){const cellSize=96;const buckets=new Map;const pairs=[];for(let index=0;index<nodes.length&&pairs.length<MAX_DIAGNOSTICS_PER_RULE;index+=1){const node=nodes[index];const minX=Math.floor(node.paintLeft/cellSize);const maxX=Math.floor((node.paintLeft+node.paintWidth)/cellSize);const minY=Math.floor(node.paintTop/cellSize);const maxY=Math.floor((node.paintTop+node.paintHeight)/cellSize);const candidates=new Set;for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const bucket=buckets.get(`${x}:${y}`);bucket?.forEach(candidate=>candidates.add(candidate))}}for(const candidate of candidates){if(meaningfulOverlap(nodes[candidate],node))pairs.push([nodes[candidate],node]);if(pairs.length>=MAX_DIAGNOSTICS_PER_RULE)break}for(let x=minX;x<=maxX;x+=1){for(let y=minY;y<=maxY;y+=1){const key=`${x}:${y}`;const bucket=buckets.get(key)??[];bucket.push(index);buckets.set(key,bucket)}}}return pairs}function analyzeRenderedLayout(nodes,theme){const diagnostics=[];const textNodes=renderedTextNodes(nodes);const seenSmallText=new Set;let smallTextCount=0;for(const node of textNodes){if(node.fontSize>=MIN_TEXT_SIZE)continue;const excerpt=textExcerpt(node.text);const key=`${excerpt}:${node.fontSize}`;if(seenSmallText.has(key))continue;seenSmallText.add(key);diagnostics.push({code:"readability.small_text",severity:"warning",theme,message:`Text "${excerpt}" renders at ${node.fontSize}px.`,suggestion:`Use at least ${MIN_TEXT_SIZE}px for details that must remain readable when embedded.`,elementId:node.elementId,location:{x:node.left,y:node.top,width:node.width,height:node.height}});smallTextCount+=1;if(smallTextCount>=MAX_DIAGNOSTICS_PER_RULE)break}for(const[left,right]of overlapCandidates(textNodes)){diagnostics.push({code:"layout.text_overlap",severity:"warning",theme,message:`Text "${textExcerpt(left.text)}" overlaps "${textExcerpt(right.text)}".`,suggestion:"Increase spacing or canvas size, shorten labels, or move one label.",elementId:left.elementId,relatedElementIds:right.elementId?[right.elementId]:void 0,location:{x:left.left,y:left.top,width:left.width,height:left.height}})}const maxDataNumber=attribute=>Math.max(0,...nodes.map(node=>{const value=node.props[attribute];return typeof value==="number"?value:Number(value)||0}));for(const source of nodes.filter(node=>Number(node.props["data-vizmatic-unrouted-connectors"])>0)){const messages=JSON.parse(String(source.props["data-vizmatic-routing-failures"]));for(const message of messages.slice(0,MAX_DIAGNOSTICS_PER_RULE))diagnostics.push({code:"layout.connector_unroutable",severity:"error",theme,message,suggestion:"Increase canvas size or spacing, reduce routingClearance, or choose a different endpoint side or port.",elementId:elementId(source.props),location:{x:source.left,y:source.top,width:source.width,height:source.height}})}const connectorSource=nodes.find(node=>Number(node.props["data-vizmatic-connector-crossings"])>Number(node.props["data-vizmatic-connector-crossing-budget"]??0));const connectorCrossings=connectorSource?Number(connectorSource.props["data-vizmatic-connector-crossings"]):0;if(connectorCrossings>0){const source=connectorSource;diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${connectorCrossings} connector crossing${connectorCrossings===1?"":"s"} detected.`,suggestion:"Use automatic layout, change graph direction, or simplify the edge set.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const labelCollisions=maxDataNumber("data-vizmatic-connector-label-collisions");if(labelCollisions>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-collisions"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${labelCollisions} connector label collision${labelCollisions===1?"":"s"} detected.`,suggestion:"Change graph direction or spacing, shorten edge labels, or remove nonessential labels.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crossedLabels=maxDataNumber("data-vizmatic-connector-label-crossings");if(crossedLabels>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-connector-label-crossings"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"info",theme,message:`${crossedLabels} connector${crossedLabels===1?" passes":"s pass"} behind a label or group title. The label masks it, but the line appears broken.`,suggestion:'Shorten or move the label, change graph direction, or route the connector with routing="orthogonal".',elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const crowdedEndpoints=maxDataNumber("data-vizmatic-crowded-connector-endpoints");if(crowdedEndpoints>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-crowded-connector-endpoints"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${crowdedEndpoints} node${crowdedEndpoints===1?"":"s"} connect more than eight edges.`,suggestion:"Group related branches, add an intermediate hub, or change graph direction.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}const parallelGroups=maxDataNumber("data-vizmatic-parallel-connector-groups");if(parallelGroups>0){const source=nodes.find(node=>Number(node.props["data-vizmatic-parallel-connector-groups"])>0);diagnostics.push({code:"layout.connector_congestion",severity:"warning",theme,message:`${parallelGroups} connector route${parallelGroups===1?"":"s"} contain parallel edges.`,suggestion:"Merge duplicate relationships, label one combined edge, or separate the routes.",elementId:source?elementId(source.props):void 0,location:source?{x:source.left,y:source.top,width:source.width,height:source.height}:void 0})}let overflowCount=0;const graphNodes=nodes.filter(node=>typeof node.props["data-vizmatic-graph-node-id"]==="string");for(const box of graphNodes){for(const text2 of nodes){if(overflowCount>=MAX_DIAGNOSTICS_PER_RULE)break;if(!String(text2.textContent??"").trim()||text2===box)continue;const startsInside=text2.left>=box.left-1&&text2.left<box.left+box.width&&text2.top>=box.top-1&&text2.top<box.top+box.height;if(!startsInside)continue;const spillsRight=text2.left+text2.width>box.left+box.width+1;const spillsDown=text2.top+text2.height>box.top+box.height+1;if(!spillsRight&&!spillsDown)continue;diagnostics.push({code:"layout.text_overflow",severity:"warning",theme,message:`Text "${textExcerpt(String(text2.textContent))}" spills out of node "${String(box.props["data-vizmatic-graph-node-id"])}".`,suggestion:"Omit the fixed node width and height so the node sizes to its content, or shorten the text.",elementId:elementId(box.props),location:{x:text2.left,y:text2.top,width:text2.width,height:text2.height}});overflowCount+=1;break}}let whitespaceCount=0;for(const container of nodes.filter(node=>node.props["data-vizmatic-layout-container"]==="panel")){const contentNodes=nodes.filter(node=>node.props["data-vizmatic-layout-content"]==="panel"&&node.width>0&&node.height>0&&node.left>=container.left&&node.top>=container.top&&node.left+node.width<=container.left+container.width&&node.top+node.height<=container.top+container.height);if(contentNodes.length===0)continue;const contentTop=Math.min(...contentNodes.map(node=>node.top));const contentBottom=Math.max(...contentNodes.map(node=>node.top+node.height));const topGutter=contentTop-container.top;const bottomGutter=container.top+container.height-contentBottom;const difference=Math.abs(bottomGutter-topGutter);if(difference<=48||difference/container.height<=.18)continue;const largerSide=bottomGutter>topGutter?"below":"above";const smallerSide=largerSide==="below"?"above":"below";diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Panel has ${Math.round(difference)}px more whitespace ${largerSide} its content than ${smallerSide} it.`,suggestion:"Reduce the panel height, distribute its contents, or avoid stretching it beside taller content.",elementId:elementId(container.props),location:{x:container.left,y:container.top,width:container.width,height:container.height}});whitespaceCount+=1;if(whitespaceCount>=MAX_DIAGNOSTICS_PER_RULE)break}return diagnostics}function analyzeWhitespaceBalance(bounds4,width,height,theme){const gutters={left:bounds4.x,right:width-bounds4.x-bounds4.width,top:bounds4.y,bottom:height-bounds4.y-bounds4.height};const diagnostics=[];const horizontalDifference=Math.abs(gutters.left-gutters.right);const verticalDifference=Math.abs(gutters.top-gutters.bottom);if(horizontalDifference>48&&horizontalDifference/width>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Horizontal gutters differ by ${Math.round(horizontalDifference)}px (${Math.round(gutters.left)}px left, ${Math.round(gutters.right)}px right).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.height}})}if(verticalDifference>48&&verticalDifference/height>.12){diagnostics.push({code:"layout.whitespace_imbalance",severity:"warning",theme,message:`Vertical gutters differ by ${Math.round(verticalDifference)}px (${Math.round(gutters.top)}px top, ${Math.round(gutters.bottom)}px bottom).`,suggestion:"Recenter the composition, crop the canvas, or use the open space intentionally.",location:{x:bounds4.x,y:bounds4.y,width:bounds4.width,height:bounds4.height}})}return diagnostics}function diagnosticFromMessage(message,severity,theme){if(/unknown preset/i.test(message)){return{code:"frame.unknown_preset",severity,theme,message,suggestion:'Use "default" or "engineering".'}}if(/unsupported prop|unknown prop|does not recognize (?:the )?.* prop/i.test(message)){return{code:"api.unsupported_prop",severity,theme,message,suggestion:"Remove the prop or use one documented for this Vizmatic primitive."}}if(/invalid value for css property|unsupported (?:css|style)|not supported.*css/i.test(message)){return{code:"style.unsupported",severity,theme,message,suggestion:"Use CSS supported by Satori or a Vizmatic primitive."}}if(/font|emoji|image asset|failed to (?:download|fetch)|asset .*not found/i.test(message)){return{code:"asset.warning",severity,theme,message,suggestion:"Use a reachable asset or install it locally before rendering offline."}}return{code:severity==="error"?"render.error":"render.warning",severity,theme,message}}var DEFAULT_WIDTH=960;var DEFAULT_HEIGHT=540;var MAX_WIDTH=1920;var MAX_HEIGHT=1440;var GROWTH=1.25;var MAX_AUTO_SIZE_ATTEMPTS=6;var TRUSTED_COMPONENTS=new Set(Object.values(primitives_exports));var SVG_CONTEXT_COMPONENTS={shapes:new Map([[SvgFrame,"SvgFrame"],[SvgPoint,"SvgPoint"],[VectorArrow,"VectorArrow"],[VectorSegment,"VectorSegment"],[ArrowMarkerDef,"ArrowMarkerDef"]]),children:new Map([...[Board,CanvasItem,Canvas,Scene,Row,Column,Panel,Stack,Card,Tile,WindowFrame,CalloutCard,ChartFrame].map(component=>[component,"html"]),[AxisPlot,"svg"]])};var consoleCaptureContext=new AsyncLocalStorage;var activeConsoleCaptures=0;var originalConsoleMethods;function formatConsoleArgs(args){return args.map(value=>{if(value instanceof Error)return value.message;if(typeof value==="string")return value;try{return JSON.stringify(value)}catch{return String(value)}}).join(" ")}function installConsoleCapture(){if(activeConsoleCaptures===0){originalConsoleMethods={debug:console.debug,error:console.error,info:console.info,log:console.log,warn:console.warn};const original=originalConsoleMethods;const intercept=(method,severity)=>(...args)=>{const messages=consoleCaptureContext.getStore();if(messages){if(severity)messages.push({severity,message:formatConsoleArgs(args)});return}Reflect.apply(original[method],console,args)};console.debug=intercept("debug");console.error=intercept("error","error");console.info=intercept("info");console.log=intercept("log");console.warn=intercept("warn","warning")}activeConsoleCaptures+=1;let restored=false;return()=>{if(restored)return;restored=true;activeConsoleCaptures-=1;if(activeConsoleCaptures===0&&originalConsoleMethods){console.debug=originalConsoleMethods.debug;console.error=originalConsoleMethods.error;console.info=originalConsoleMethods.info;console.log=originalConsoleMethods.log;console.warn=originalConsoleMethods.warn;originalConsoleMethods=void 0}}}async function captureConsole(run2){const messages=[];const uninstall=installConsoleCapture();try{const value=await consoleCaptureContext.run(messages,run2);return{value,messages}}catch(error){return{error,messages}}finally{uninstall()}}function normalizeAutoSize(value,defaults){if(value===true)return{width:true,height:true};if(value===false)return{width:false,height:false};if(value)return{width:value.width??defaults.width,height:value.height??defaults.height};return defaults}function overflowEdges(error){if(!(error instanceof CanvasOverflowError))return void 0;return Object.entries(error.overflow.edges).filter(([,overflows])=>overflows).map(([edge])=>edge)}function nextDimension(value,maximum){return Math.min(maximum,Math.ceil(value*GROWTH/10)*10)}function nextAutoSize(width,height,autoSize,edges){const growWidth=autoSize.width&&(edges.includes("left")||edges.includes("right"));const growHeight=autoSize.height&&(edges.includes("top")||edges.includes("bottom"));const nextWidth=growWidth?nextDimension(width,MAX_WIDTH):width;const nextHeight=growHeight?nextDimension(height,MAX_HEIGHT):height;if(nextWidth===width&&nextHeight===height)return void 0;return{width:nextWidth,height:nextHeight}}async function renderFrame(create,theme,options){let width=options.width;let height=options.height;for(let attempt=0;attempt<MAX_AUTO_SIZE_ATTEMPTS;attempt+=1){try{const layoutNodes=[];const output=await renderToPngWithOutput(create(theme),{width,height,outputPath:options.outputPath,crop:true,scale:1,background:options.background,onNodeDetected:node=>layoutNodes.push(node)},create,theme);return{width,height,outputWidth:output.pixelWidth,outputHeight:output.pixelHeight,logicalOutputWidth:output.width,logicalOutputHeight:output.height,contentBounds:output.contentBounds,layoutNodes}}catch(error){const edges=overflowEdges(error);const next=edges?nextAutoSize(width,height,options.autoSize,edges):void 0;if(!next||attempt===MAX_AUTO_SIZE_ATTEMPTS-1)throw error;width=next.width;height=next.height}}return{width,height,outputWidth:width,outputHeight:height,logicalOutputWidth:width,logicalOutputHeight:height,layoutNodes:[]}}function counts(themes){const diagnostics=themes.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{errors:diagnostics.filter(({severity})=>severity==="error").length,warnings:diagnostics.filter(({severity})=>severity==="warning").length,info:diagnostics.filter(({severity})=>severity==="info").length}}function fails(diagnostics,policy){if(policy==="never")return false;const threshold={error:0,warning:1,info:2}[policy];const levels={error:0,warning:1,info:2};return diagnostics.some(({severity})=>levels[severity]<=threshold)}function messageDiagnostics(messages,theme){return messages.map(({message,severity})=>diagnosticFromMessage(message,severity,theme))}function rootBackground(background,theme){if(background==="theme")return getThemeColors(theme).bg;if(background==="transparent"||background===void 0)return void 0;return background}async function checkFrame(input,options={}){const themes=options.themes??["dark","light"];if(themes.length===0)throw new TypeError("checkFrame requires at least one theme");const width=input.width??DEFAULT_WIDTH;const height=input.height??DEFAULT_HEIGHT;if(!Number.isFinite(width)||width<=0||!Number.isFinite(height)||height<=0){throw new TypeError("checkFrame width and height must be positive finite numbers")}const autoSize=normalizeAutoSize(input.autoSize,{width:input.width==null,height:input.height==null});const create=input.create??(()=>input.scene);const failOn=options.failOn??"error";const tempDir=await mkdtemp(join(tmpdir(),"vizmatic-check-"));const reports=[];try{for(const[themeIndex,theme]of themes.entries()){const inputDimensions={width,height};const diagnostics2=[];const prepared2=await captureConsole(async()=>{const element=create(theme);const background=rootBackground(options.background,theme);return analyzeScene(element,theme,TRUSTED_COMPONENTS,background,SVG_CONTEXT_COMPONENTS)});diagnostics2.push(...messageDiagnostics(prepared2.messages,theme));if(!prepared2.value){diagnostics2.push(diagnosticFromMessage(prepared2.error instanceof Error?prepared2.error.message:String(prepared2.error),"error",theme));reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2});continue}diagnostics2.push(...prepared2.value);const rendered=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize,background:options.background,outputPath:join(tempDir,`${themeIndex}.png`)}));diagnostics2.push(...messageDiagnostics(rendered.messages,theme));if(rendered.value){diagnostics2.push(...analyzeRenderedLayout(rendered.value.layoutNodes,theme));if(rendered.value.contentBounds){diagnostics2.push(...analyzeWhitespaceBalance(rendered.value.contentBounds,rendered.value.logicalOutputWidth,rendered.value.logicalOutputHeight,theme))}if(rendered.value.width!==width||rendered.value.height!==height){diagnostics2.push({code:"layout.auto_size",severity:"info",theme,message:`Canvas auto-sized from ${width}\xD7${height} to ${rendered.value.width}\xD7${rendered.value.height}.`,suggestedDimensions:{width:rendered.value.width,height:rendered.value.height}})}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions,resolved:{width:rendered.value.width,height:rendered.value.height},output:{width:rendered.value.outputWidth,height:rendered.value.outputHeight}},diagnostics:diagnostics2});continue}const edges=overflowEdges(rendered.error);if(edges){const suggestion=await captureConsole(()=>renderFrame(create,theme,{width,height,autoSize:{width:true,height:true},background:options.background,outputPath:join(tempDir,`${themeIndex}-suggestion.png`)}));const suggestedDimensions=suggestion.value?{width:suggestion.value.width,height:suggestion.value.height}:void 0;diagnostics2.push({code:"layout.overflow",severity:"error",theme,edges,message:rendered.error instanceof Error?rendered.error.message:String(rendered.error),suggestion:suggestedDimensions?`Increase the canvas to at least ${suggestedDimensions.width}\xD7${suggestedDimensions.height}, or remove fixed dimensions to enable auto-sizing.`:"Increase the canvas dimensions or remove fixed dimensions to enable auto-sizing.",suggestedDimensions})}else{diagnostics2.push(diagnosticFromMessage(rendered.error instanceof Error?rendered.error.message:String(rendered.error),"error",theme))}reports.push({theme,ok:!fails(diagnostics2,failOn),dimensions:{input:inputDimensions},diagnostics:diagnostics2})}}finally{await rm(tempDir,{recursive:true,force:true})}const summary=counts(reports);const diagnostics=reports.flatMap(({diagnostics:themeDiagnostics})=>themeDiagnostics);return{schemaVersion:1,source:input.source,ok:!fails(diagnostics,failOn),rendered:reports.every(({dimensions})=>dimensions.resolved!==void 0),autoSize,themes:reports,summary}}import parseCssColor3 from"parse-css-color";var themeColorKeys=Object.freeze(Object.keys(getThemeColors("dark")).filter(key=>key!=="preset"&&key!=="fontSans"&&key!=="fontMono"&&key!=="fontSerif"&&key!=="density"));var themeColorKeySet=new Set(themeColorKeys);function validatePlaygroundThemeColors(value){if(value==null||typeof value!=="object"||Array.isArray(value)){throw new Error("themeColors must be a JSON object of CSS colors.")}const colors2={};for(const[key,color]of Object.entries(value)){if(!themeColorKeySet.has(key)){throw new Error(`Unknown themeColors key ${JSON.stringify(key)}.`)}if(typeof color!=="string"||!parseCssColor3(color.trim())){throw new Error(`themeColors.${key} must be a valid CSS color.`)}colors2[key]=color.trim()}return colors2}function parseThemeColorsMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error("themeColors must be a single-line JSON object of CSS colors.");let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error("themeColors must be a single-line JSON object of CSS colors.")}return validatePlaygroundThemeColors(parsed)}function parseBackgroundMetadataLine(line2){const withoutComment=stripTrailingLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=withoutComment.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]\s*(.*?)\s*;?$/);if(!match)return void 0;if(!match[1]?.trim())throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.');let parsed;try{parsed=JSON.parse(match[1])}catch{throw new Error('background must be a single-line JSON string set to "theme", "transparent", or a CSS color.')}return validatePlaygroundBackground(parsed)}function isBackgroundMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?background\s*[:=]/.test(line2)}function validatePlaygroundBackground(value){if(typeof value!=="string"){throw new Error('background must be "theme", "transparent", or a valid CSS color.')}const background=value.trim();if(background==="theme"||background==="transparent"||parseCssColor3(background))return background;throw new Error('background must be "theme", "transparent", or a valid CSS color.')}function isThemeColorsMetadataLine(line2){return/^(?:\s*\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?themeColors\s*[:=]/.test(line2)}function mergePlaygroundThemeColors(mode,preset,overrides){return{...getThemeColors(mode,preset),...overrides}}function stripTrailingLineComment(line2){let quoted=false;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[index];if(quoted){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character==='"')quoted=false;continue}if(character==='"')quoted=true;else if(character==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}function readPresetLine(line2){const candidate=stripLineComment(line2.replace(/^\s*\/\/\s*/,"")).trim();const match=candidate.match(/^(?:export\s+)?(?:(?:const|let|var)\s+)?preset(?:\s*:\s*ThemePreset)?\s*[:=]\s*(.+)$/i);if(!match?.[1])return void 0;const expression=match[1].trim().replace(/;\s*$/,"").trim();const quoted=expression.match(/^(['"])(.*)\1$/);const requested=(quoted?.[2]??expression).trim();const normalized=requested.toLowerCase();const preset=quoted&&(normalized==="default"||normalized==="engineering")?normalized:void 0;return{preset,requested}}function readAnimationLine(line2){const match=line2.match(/^\s*(?:\/\/\s*)?(?:export\s+)?(?:(?:const|let|var)\s+)?(animationDuration|animationFps)\s*[:=]\s*(.*?)\s*;?\s*(?:\/\/.*)?$/);if(!match)return void 0;const expression=match[2].replace(/;\s*$/,"").trim();if(!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(expression)){throw new Error(`${match[1]} must be a numeric literal.`)}return{name:match[1],value:Number(expression)}}function stripLineComment(line2){let quote;let escaped=false;for(let index=0;index<line2.length-1;index+=1){const character=line2[index];if(quote){if(escaped)escaped=false;else if(character==="\\")escaped=true;else if(character===quote)quote=void 0}else if(character==='"'||character==="'")quote=character;else if(character==="/"&&line2[index+1]==="/")return line2.slice(0,index)}return line2}import parseCssColor4 from"parse-css-color";function validatePlaygroundAnimation(animation){if(!Number.isFinite(animation.duration)||animation.duration<=0||animation.duration>10){throw new Error("animationDuration must be greater than 0 and at most 10 seconds.")}if(!Number.isInteger(animation.fps)||animation.fps<1||animation.fps>30){throw new Error("animationFps must be an integer from 1 to 30.")}return{duration:animation.duration,fps:animation.fps}}import{existsSync}from"fs";import{mkdir as mkdir3,stat as stat2,writeFile as writeFile3}from"fs/promises";import{basename,dirname as dirname3,extname,join as join2,relative,resolve as resolve2}from"path";import{mkdir as mkdir2,stat,writeFile as writeFile2}from"fs/promises";import{totalmem}from"os";import{dirname as dirname2,resolve}from"path";import*as gifenc2 from"gifenc";import parseCssColor5 from"parse-css-color";var midnight={name:"midnight",dark:true,background:"#0b0c10",bloom:.2,colors:{bg:"#0b0c10",surface:"#15171d",ink:"#f2efe6",dim:"#a5a7ad",faint:"#5c5f68",grid:"#23303d",gridStrong:"#3d5266",blue:"#5cc4f0",teal:"#4fd8c4",green:"#8fe08a",yellow:"#ffd75e",gold:"#f2b84b",orange:"#ff9d57",red:"#ff6b6b",pink:"#ff8fc0",purple:"#b49cff"}};var paper={name:"paper",dark:false,background:"#f7f3ea",bloom:0,colors:{bg:"#f7f3ea",surface:"#efe9db",ink:"#1d1b16",dim:"#5e5a50",faint:"#a29c8d",grid:"#e2dbca",gridStrong:"#c4bba6",blue:"#1f6fb2",teal:"#0d8577",green:"#3f8a35",yellow:"#b98500",gold:"#a8740a",orange:"#cf5d12",red:"#c62f2f",pink:"#c2387e",purple:"#6a4bc4"}};var blueprint={name:"blueprint",dark:true,background:"#0b2340",bloom:.16,colors:{bg:"#0b2340",surface:"#123054",ink:"#eaf6ff",dim:"#9cc0dc",faint:"#5d86a8",grid:"#1a3f66",gridStrong:"#2c5f8e",blue:"#7fd4ff",teal:"#6fe6d6",green:"#9de8a4",yellow:"#ffe27a",gold:"#f5c566",orange:"#ffb27a",red:"#ff8d8d",pink:"#ffa8cf",purple:"#c5b4ff"}};var chalk={name:"chalk",dark:true,background:"#10201b",bloom:.1,colors:{bg:"#10201b",surface:"#172c25",ink:"#f4f1e4",dim:"#b1b9a9",faint:"#67786d",grid:"#20392f",gridStrong:"#355547",blue:"#8ccbe8",teal:"#7dd9c1",green:"#a9dc8f",yellow:"#f6dd7c",gold:"#e6bf62",orange:"#f2a874",red:"#ee8a80",pink:"#efa2c2",purple:"#bfa9e6"}};var neon={name:"neon",dark:true,background:"#050507",bloom:.4,colors:{bg:"#050507",surface:"#101016",ink:"#ffffff",dim:"#a9a9b8",faint:"#55555f",grid:"#1a1f2e",gridStrong:"#2f3a55",blue:"#3fb2ff",teal:"#21f0d0",green:"#6dff8e",yellow:"#fff04d",gold:"#ffc22e",orange:"#ff8a2e",red:"#ff4560",pink:"#ff5fb0",purple:"#a56bff"}};var LOOKS={midnight,paper,blueprint,chalk,neon};function resolveLook(look){if(look===void 0)return midnight;if(typeof look!=="string")return look;const found=LOOKS[look];if(!found)throw new Error(`Unknown look: ${JSON.stringify(look)}. Use one of: ${Object.keys(LOOKS).join(", ")}.`);return found}var TRANSPARENT=[0,0,0,0];var cache=new Map;var tokens2=midnight.colors;function setColorTokens(next){tokens2=next}function parseColor(input){const token=tokens2[input];const value=token??input;const cached=cache.get(value);if(cached)return cached;const parsed=parseCssColor5(value);if(!parsed)throw new Error(`Unknown color: ${JSON.stringify(input)}. Use a look token such as "blue" or a CSS color.`);let[r,g,b]=parsed.values;if(parsed.type==="hsl")[r,g,b]=hslToRgb3(r,g,b);const result=[r,g,b,parsed.alpha];cache.set(value,result);return result}function hslToRgb3(h,s,l){const a=s/100*Math.min(l/100,1-l/100);const f=n=>{const k=(n+h/30)%12;return 255*(l/100-a*Math.max(-1,Math.min(k-3,9-k,1)))};return[f(0),f(8),f(4)]}function toPaint(input){if(typeof input==="string")return parseColor(input);return input}function isGradient(paint){return!Array.isArray(paint)}function css(color,alpha3=1){const a=color[3]*alpha3;const r=Math.round(color[0]),g=Math.round(color[1]),b=Math.round(color[2]);if(a>=1)return`rgb(${r},${g},${b})`;return`rgba(${r},${g},${b},${Math.round(a*1e3)/1e3})`}function srgbToLinear(v){const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)}function linearToSrgb(v){const x=v<=.0031308?12.92*v:1.055*Math.pow(v,1/2.4)-.055;return Math.max(0,Math.min(255,x*255))}function toOklab(c){const r=srgbToLinear(c[0]),g=srgbToLinear(c[1]),b=srgbToLinear(c[2]);const l=Math.cbrt(.4122214708*r+.5363325363*g+.0514459929*b);const m=Math.cbrt(.2119034982*r+.6806995451*g+.1073969566*b);const s=Math.cbrt(.0883024619*r+.2817188376*g+.6299787005*b);return[.2104542553*l+.793617785*m-.0040720468*s,1.9779984951*l-2.428592205*m+.4505937099*s,.0259040371*l+.7827717662*m-.808675766*s]}function fromOklab(lab,alpha3){const l=lab[0]+.3963377774*lab[1]+.2158037573*lab[2];const m=lab[0]-.1055613458*lab[1]-.0638541728*lab[2];const s=lab[0]-.0894841775*lab[1]-1.291485548*lab[2];const ll=l*l*l,mm=m*m*m,ss=s*s*s;return[linearToSrgb(4.0767416621*ll-3.3077115913*mm+.2309699292*ss),linearToSrgb(-1.2684380046*ll+2.6097574011*mm-.3413193965*ss),linearToSrgb(-.0041960863*ll-.7034186147*mm+1.707614701*ss),alpha3]}function mixColor(a,b,t){if(t<=0)return a;if(t>=1)return b;const x=toOklab(a),y=toOklab(b);return fromOklab([x[0]+(y[0]-x[0])*t,x[1]+(y[1]-x[1])*t,x[2]+(y[2]-x[2])*t],a[3]+(b[3]-a[3])*t)}function mixPaint(a,b,t){if(t<=0)return a;if(t>=1)return b;const ga=isGradient(a),gb=isGradient(b);if(!ga&&!gb)return mixColor(a,b,t);if(ga&&gb&&a.type===b.type&&a.stops.length===b.stops.length){const stops=a.stops.map((stop,i)=>[stop[0]+(b.stops[i][0]-stop[0])*t,mixColor(stop[1],b.stops[i][1],t)]);if(a.type==="linear"&&b.type==="linear"){return{type:"linear",stops,from:[a.from[0]+(b.from[0]-a.from[0])*t,a.from[1]+(b.from[1]-a.from[1])*t],to:[a.to[0]+(b.to[0]-a.to[0])*t,a.to[1]+(b.to[1]-a.to[1])*t]}}if(a.type==="radial"&&b.type==="radial"){return{type:"radial",stops,center:[a.center[0]+(b.center[0]-a.center[0])*t,a.center[1]+(b.center[1]-a.center[1])*t],radius:a.radius+(b.radius-a.radius)*t}}return{type:"along",stops}}const solidA=ga?sampleStops(a.stops,.5):a;const solidB=gb?sampleStops(b.stops,.5):b;return mixColor(solidA,solidB,t)}function sampleStops(stops,at){if(stops.length===0)return TRANSPARENT;if(at<=stops[0][0])return stops[0][1];for(let i=1;i<stops.length;i++){if(at<=stops[i][0]){const[p0,c0]=stops[i-1],[p1,c1]=stops[i];return mixColor(c0,c1,p1>p0?(at-p0)/(p1-p0):0)}}return stops[stops.length-1][1]}function normalizeStops(colors2){const count=colors2.length;return colors2.map((entry,i)=>{if(Array.isArray(entry)&&entry.length===2&&typeof entry[0]==="number"){return[entry[0],solid(entry[1])]}return[count===1?0:i/(count-1),solid(entry)]})}function solid(input){const paint=toPaint(input);return isGradient(paint)?sampleStops(paint.stops,.5):paint}function linearGradient(from,to2,colors2){return{type:"linear",from,to:to2,stops:normalizeStops(colors2)}}function radialGradient(center2,radius,colors2){return{type:"radial",center:center2,radius,stops:normalizeStops(colors2)}}function along(...colors2){return{type:"along",stops:normalizeStops(colors2)}}function ramp(count,...colors2){const stops=normalizeStops(colors2);return Array.from({length:count},(_,i)=>sampleStops(stops,count===1?0:i/(count-1)))}var IDENTITY=[1,0,0,1,0,0];var EMPTY_BOUNDS={x:0,y:0,width:0,height:0};var KAPPA=.5522847498307936;var LUT_STEPS=10;function mul(m,n){return[m[0]*n[0]+m[2]*n[1],m[1]*n[0]+m[3]*n[1],m[0]*n[2]+m[2]*n[3],m[1]*n[2]+m[3]*n[3],m[0]*n[4]+m[2]*n[5]+m[4],m[1]*n[4]+m[3]*n[5]+m[5]]}function invert(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return IDENTITY;const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function apply(m,x,y){return[m[0]*x+m[2]*y+m[4],m[1]*x+m[3]*y+m[5]]}function compose(x,y,rotation,sx,sy,px,py){const cos=rotation===0?1:Math.cos(rotation);const sin=rotation===0?0:Math.sin(rotation);const a=cos*sx;const b=sin*sx;const c=-sin*sy;const d=cos*sy;return[a,b,c,d,x-a*px-c*py,y-b*px-d*py]}function matScale(m){return Math.sqrt(Math.abs(m[0]*m[3]-m[1]*m[2]))}function ring(points,closed=false){return{p:points instanceof Float64Array?points:Float64Array.from(points),closed}}function segmentCount(r){return Math.max(0,(r.p.length-2)/6)}function lineInto(out,x0,y0,x1,y1){out.push(x0+(x1-x0)/3,y0+(y1-y0)/3,x0+(x1-x0)*2/3,y0+(y1-y0)*2/3,x1,y1)}function linePath(a,b){const out=[a[0],a[1]];lineInto(out,a[0],a[1],b[0],b[1]);return[ring(out)]}function polyPath(points,closed=false){if(points.length===0)return[];const first=points[0];const out=[first[0],first[1]];for(let i=1;i<points.length;i++)lineInto(out,points[i-1][0],points[i-1][1],points[i][0],points[i][1]);if(closed){const last=points[points.length-1];if(last[0]!==first[0]||last[1]!==first[1])lineInto(out,last[0],last[1],first[0],first[1])}return[ring(out,closed)]}function smoothPath(points,closed=false,tension=1/6){const n=points.length;if(n===0)return[];if(n<3)return polyPath(points,closed);const at=i=>closed?points[(i+n)%n]:points[Math.max(0,Math.min(n-1,i))];const out=[points[0][0],points[0][1]];const count=closed?n:n-1;for(let i=0;i<count;i++){const p0=at(i-1),p1=at(i),p2=at(i+1),p3=at(i+2);out.push(p1[0]+(p2[0]-p0[0])*tension,p1[1]+(p2[1]-p0[1])*tension,p2[0]-(p3[0]-p1[0])*tension,p2[1]-(p3[1]-p1[1])*tension,p2[0],p2[1])}return[ring(out,closed)]}function arcPath(cx,cy,rx,ry,from,to2){const sweep=to2-from;if(sweep===0)return[];const closed=Math.abs(Math.abs(sweep)-Math.PI*2)<1e-9;const count=Math.max(1,Math.ceil(Math.abs(sweep)/(Math.PI/4)-1e-9));const step=sweep/count;const k=4/3*Math.tan(step/4);const out=[cx+Math.cos(from)*rx,cy+Math.sin(from)*ry];for(let i=0;i<count;i++){const a0=from+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);out.push(cx+(c0-k*s0)*rx,cy+(s0+k*c0)*ry,cx+(c1+k*s1)*rx,cy+(s1-k*c1)*ry,cx+c1*rx,cy+s1*ry)}if(closed){out[out.length-2]=out[0];out[out.length-1]=out[1]}return[ring(out,closed)]}function circlePath(cx,cy,r){return arcPath(cx,cy,r,r,0,Math.PI*2)}function rectPath(x,y,width,height,radius=0){const r=Math.max(0,Math.min(radius,Math.abs(width)/2,Math.abs(height)/2));if(r===0)return polyPath([[x,y],[x+width,y],[x+width,y+height],[x,y+height]],true);const k=r*(1-KAPPA);const right=x+width,bottom=y+height;const out=[x+r,y];lineInto(out,x+r,y,right-r,y);out.push(right-k,y,right,y+k,right,y+r);lineInto(out,right,y+r,right,bottom-r);out.push(right,bottom-k,right-k,bottom,right-r,bottom);lineInto(out,right-r,bottom,x+r,bottom);out.push(x+k,bottom,x,bottom-k,x,bottom-r);lineInto(out,x,bottom-r,x,y+r);out.push(x,y+k,x+k,y,x+r,y);return[ring(out,true)]}function parametricPath(f,from,to2,samples=64){const count=Math.max(2,Math.floor(samples));const points=[];for(let i=0;i<=count;i++)points.push(f(from+(to2-from)*i/count));return curveThrough(points)}function curveThrough(points){const rings=[];let run2=[];const flush=()=>{if(run2.length>=2)rings.push(...smoothPath(run2));run2=[]};for(const point of points){if(Number.isFinite(point[0])&&Number.isFinite(point[1]))run2.push(point);else flush()}flush();return rings}function concat(...paths){return paths.flat()}function transformPath(path,m){if(m===IDENTITY)return path;const out=new Array(path.length);for(let r=0;r<path.length;r++){const src=path[r].p;const dst=new Float64Array(src.length);for(let i=0;i<src.length;i+=2){const x=src[i],y=src[i+1];dst[i]=m[0]*x+m[2]*y+m[4];dst[i+1]=m[1]*x+m[3]*y+m[5]}out[r]={p:dst,closed:path[r].closed}}return out}function warpPath(path,f,subdivisions=4){const dense=subdivisions>1?path.map(r=>subdivideEach(r,subdivisions)):path;return dense.map(r=>{const count=segmentCount(r);const anchors=[];for(let i=0;i<=count;i++){const mapped=f(r.p[i*6],r.p[i*6+1]);anchors.push(mapped)}const out=[anchors[0][0],anchors[0][1]];for(let i=0;i<count;i++){const c1=f(r.p[i*6+2],r.p[i*6+3]);const c2=f(r.p[i*6+4],r.p[i*6+5]);out.push(c1[0],c1[1],c2[0],c2[1],anchors[i+1][0],anchors[i+1][1])}return ring(out,r.closed)})}function splitInto(src,o,t,left,right){const x0=src[o],y0=src[o+1],x1=src[o+2],y1=src[o+3];const x2=src[o+4],y2=src[o+5],x3=src[o+6],y3=src[o+7];const ax=x0+(x1-x0)*t,ay=y0+(y1-y0)*t;const bx=x1+(x2-x1)*t,by=y1+(y2-y1)*t;const cx=x2+(x3-x2)*t,cy=y2+(y3-y2)*t;const dx=ax+(bx-ax)*t,dy=ay+(by-ay)*t;const ex=bx+(cx-bx)*t,ey=by+(cy-by)*t;const fx=dx+(ex-dx)*t,fy=dy+(ey-dy)*t;left.push(ax,ay,dx,dy,fx,fy);right.length=0;right.push(fx,fy,ex,ey,cx,cy,x3,y3)}function subdivideEach(r,n){const count=segmentCount(r);if(n<=1||count===0)return r;const out=[r.p[0],r.p[1]];for(let i=0;i<count;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));for(let k=n;k>1;k--){const rest=[];splitInto(seg,0,1/k,out,rest);seg=rest}out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,r.closed)}var measures=new WeakMap;function measure(r){const cached=measures.get(r);if(cached)return cached;const count=segmentCount(r);const total=new Float64Array(count);const lut=new Float64Array(count*LUT_STEPS);let sum=0;const p=r.p;for(let i=0;i<count;i++){const o=i*6;const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3],x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];let lastX=x0,lastY=y0,acc=0;for(let k=1;k<=LUT_STEPS;k++){const t=k/LUT_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;acc+=Math.hypot(x-lastX,y-lastY);lut[i*LUT_STEPS+k-1]=acc;lastX=x;lastY=y}sum+=acc;total[i]=sum}const result={total,lut,length:sum};measures.set(r,result);return result}function ringLength(r){return measure(r).length}function pathLength(path){let sum=0;for(const r of path)sum+=measure(r).length;return sum}function locate(m,distance){const count=m.total.length;if(count===0)return[0,0];if(distance<=0)return[0,0];if(distance>=m.length)return[count-1,1];let lo=0,hi=count-1;while(lo<hi){const mid=lo+hi>>1;if(m.total[mid]<distance)lo=mid+1;else hi=mid}const before=lo===0?0:m.total[lo-1];const local=distance-before;const base=lo*LUT_STEPS;let k=0;while(k<LUT_STEPS-1&&m.lut[base+k]<local)k++;const start=k===0?0:m.lut[base+k-1];const end=m.lut[base+k];const fraction=end>start?(local-start)/(end-start):0;return[lo,(k+fraction)/LUT_STEPS]}function trimRing(r,from,to2){const count=segmentCount(r);if(count===0)return null;const a=Math.max(0,Math.min(1,from));const b=Math.max(0,Math.min(1,to2));if(b<=a)return null;if(a===0&&b===1)return r;const m=measure(r);if(m.length===0)return null;const[i0,t0]=locate(m,a*m.length);const[i1,t1]=locate(m,b*m.length);const out=[];for(let i=i0;i<=i1;i++){let seg=Array.from(r.p.subarray(i*6,i*6+8));const start=i===i0?t0:0;const end=i===i1?t1:1;if(start>0){const rest=[];splitInto(seg,0,start,[],rest);seg=rest}if(end<1){const left=[];const rest=[];const scaled=start>0?(end-start)/(1-start):end;splitInto(seg,0,scaled,left,rest);seg=[seg[0],seg[1],...left]}if(out.length===0)out.push(seg[0],seg[1]);out.push(seg[2],seg[3],seg[4],seg[5],seg[6],seg[7])}return ring(out,false)}function trimPath(path,from,to2,each=false){if(from<=0&&to2>=1)return path;const out=[];if(each){for(const r of path){const piece=trimRing(r,from,to2);if(piece)out.push(piece)}return out}const total=pathLength(path);if(total===0)return[];let travelled=0;for(const r of path){const length=ringLength(r);const start=(from*total-travelled)/(length||1);const end=(to2*total-travelled)/(length||1);travelled+=length;if(end<=0||start>=1)continue;const piece=trimRing(r,Math.max(0,start),Math.min(1,end));if(piece)out.push(piece)}return out}function pointAt(path,fraction){const total=pathLength(path);if(total===0){const first=path[0]?.p;return first?[first[0],first[1]]:[0,0]}let remaining=Math.max(0,Math.min(1,fraction))*total;for(let i=0;i<path.length;i++){const r=path[i];const length=ringLength(r);if(remaining<=length||i===path.length-1){const[segment,t]=locate(measure(r),remaining);return evaluate(r.p,segment*6,t)}remaining-=length}return[0,0]}function tangentAt(path,fraction){const delta=.002;const a=pointAt(path,Math.max(0,fraction-delta));const b=pointAt(path,Math.min(1,fraction+delta));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return[(b[0]-a[0])/length,(b[1]-a[1])/length]}function evaluate(p,o,t){const u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;return[a*p[o]+b*p[o+2]+c*p[o+4]+d*p[o+6],a*p[o+1]+b*p[o+3]+c*p[o+5]+d*p[o+7]]}function extendCubicAxis(range,p0,p1,p2,p3){range[0]=Math.min(range[0],p0,p3);range[1]=Math.max(range[1],p0,p3);if(p1>=range[0]&&p1<=range[1]&&p2>=range[0]&&p2<=range[1])return;const a=-p0+3*p1-3*p2+p3;const b=2*(p0-2*p1+p2);const c=p1-p0;const roots=[];if(Math.abs(a)<1e-9){if(Math.abs(b)>1e-9)roots.push(-c/b)}else{const disc=b*b-4*a*c;if(disc>=0){const s=Math.sqrt(disc);roots.push((-b+s)/(2*a),(-b-s)/(2*a))}}for(const t of roots){if(t<=0||t>=1)continue;const u=1-t;const value=u*u*u*p0+3*u*u*t*p1+3*u*t*t*p2+t*t*t*p3;range[0]=Math.min(range[0],value);range[1]=Math.max(range[1],value)}}var ringBounds=new WeakMap;function boundsOfRing(r){const cached=ringBounds.get(r);if(cached)return cached;const p=r.p;if(p.length<2)return EMPTY_BOUNDS;const xs=[p[0],p[0]];const ys=[p[1],p[1]];for(let o=0;o+7<p.length;o+=6){extendCubicAxis(xs,p[o],p[o+2],p[o+4],p[o+6]);extendCubicAxis(ys,p[o+1],p[o+3],p[o+5],p[o+7])}const bounds4={x:xs[0],y:ys[0],width:xs[1]-xs[0],height:ys[1]-ys[0]};ringBounds.set(r,bounds4);return bounds4}function pathBounds(path){if(path.length===0)return null;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const r of path){if(r.p.length<2)continue;const b=boundsOfRing(r);minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height)}if(minX===Infinity)return null;return{x:minX,y:minY,width:maxX-minX,height:maxY-minY}}function unionBounds(a,b){if(!a)return b;if(!b)return a;const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function signedArea(r){const p=r.p;let sum=0;for(let o=0;o+7<p.length;o+=6){sum+=p[o]*p[o+7]-p[o+6]*p[o+1]}return sum/2}function ringCenter(r){const b=boundsOfRing(r);return[b.x+b.width/2,b.y+b.height/2]}function reverseRing(r){const p=r.p;const out=new Float64Array(p.length);for(let i=0;i<p.length;i+=2){out[i]=p[p.length-2-i];out[i+1]=p[p.length-1-i]}return{p:out,closed:r.closed}}function parseSvgPath(d){const tokens5=d.match(/[a-zA-Z]|[-+]?(?:\d+\.?\d*|\.\d+)(?:[eE][-+]?\d+)?/g);if(!tokens5)return[];const rings=[];let out=[];let i=0,x=0,y=0,startX=0,startY=0;let lastCmd="",lastCx=0,lastCy=0;const num=()=>Number(tokens5[i++]);const flags=()=>{const token=tokens5[i];if(token.length>1&&(token[0]==="0"||token[0]==="1")&&!token.startsWith("0.")&&!token.startsWith("1.")){tokens5[i]=token.slice(1);return Number(token[0])}i++;return Number(token)};const flush=closed=>{if(out.length>=8)rings.push(ring(out,closed));out=[]};const begin=(px,py)=>{if(out.length===0)out.push(px,py)};let cmd="";while(i<tokens5.length){const token=tokens5[i];if(/^[a-zA-Z]$/.test(token)){cmd=token;i++}else if(cmd==="M"){cmd="L"}else if(cmd==="m"){cmd="l"}else if(cmd===""){throw new Error(`Invalid SVG path data: ${d.slice(0,40)}`)}const rel=cmd>="a";switch(cmd.toUpperCase()){case"M":{flush(false);x=(rel?x:0)+num();y=(rel?y:0)+num();startX=x;startY=y;out.push(x,y);break}case"L":{const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,nx,ny);x=nx;y=ny;break}case"H":{const nx=(rel?x:0)+num();begin(x,y);lineInto(out,x,y,nx,y);x=nx;break}case"V":{const ny=(rel?y:0)+num();begin(x,y);lineInto(out,x,y,x,ny);y=ny;break}case"C":{const ox=rel?x:0,oy=rel?y:0;const c1x=ox+num(),c1y=oy+num(),c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"S":{const ox=rel?x:0,oy=rel?y:0;const smooth3="CScs".includes(lastCmd);const c1x=smooth3?2*x-lastCx:x,c1y=smooth3?2*y-lastCy:y;const c2x=ox+num(),c2y=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(c1x,c1y,c2x,c2y,nx,ny);lastCx=c2x;lastCy=c2y;x=nx;y=ny;break}case"Q":{const ox=rel?x:0,oy=rel?y:0;const qx=ox+num(),qy=oy+num(),nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"T":{const ox=rel?x:0,oy=rel?y:0;const smooth3="QTqt".includes(lastCmd);const qx=smooth3?2*x-lastCx:x,qy=smooth3?2*y-lastCy:y;const nx=ox+num(),ny=oy+num();begin(x,y);out.push(x+(qx-x)*2/3,y+(qy-y)*2/3,nx+(qx-nx)*2/3,ny+(qy-ny)*2/3,nx,ny);lastCx=qx;lastCy=qy;x=nx;y=ny;break}case"A":{const rx=num(),ry=num(),angle=num(),large=flags(),sweep=flags();const nx=(rel?x:0)+num(),ny=(rel?y:0)+num();begin(x,y);arcInto(out,x,y,rx,ry,angle,large===1,sweep===1,nx,ny);x=nx;y=ny;break}case"Z":{if(out.length>0){if(x!==startX||y!==startY)lineInto(out,x,y,startX,startY);flush(true)}x=startX;y=startY;break}default:throw new Error(`Unsupported SVG path command: ${cmd}`)}lastCmd=cmd}flush(false);return rings}function arcInto(out,x0,y0,rxIn,ryIn,degrees,large,sweep,x1,y1){let rx=Math.abs(rxIn),ry=Math.abs(ryIn);if(rx===0||ry===0||x0===x1&&y0===y1){lineInto(out,x0,y0,x1,y1);return}const phi=degrees*Math.PI/180;const cos=Math.cos(phi),sin=Math.sin(phi);const dx=(x0-x1)/2,dy=(y0-y1)/2;const xp=cos*dx+sin*dy,yp=-sin*dx+cos*dy;const lambda=xp*xp/(rx*rx)+yp*yp/(ry*ry);if(lambda>1){const scale=Math.sqrt(lambda);rx*=scale;ry*=scale}const numerator=rx*rx*ry*ry-rx*rx*yp*yp-ry*ry*xp*xp;const denominator=rx*rx*yp*yp+ry*ry*xp*xp;const factor=(large===sweep?-1:1)*Math.sqrt(Math.max(0,numerator/denominator));const cxp=factor*rx*yp/ry,cyp=-factor*ry*xp/rx;const cx=cos*cxp-sin*cyp+(x0+x1)/2;const cy=sin*cxp+cos*cyp+(y0+y1)/2;const start=Math.atan2((yp-cyp)/ry,(xp-cxp)/rx);let delta=Math.atan2((-yp-cyp)/ry,(-xp-cxp)/rx)-start;if(sweep&&delta<0)delta+=Math.PI*2;if(!sweep&&delta>0)delta-=Math.PI*2;const count=Math.max(1,Math.ceil(Math.abs(delta)/(Math.PI/2)-1e-9));const step=delta/count;const k=4/3*Math.tan(step/4);for(let i=0;i<count;i++){const a0=start+i*step,a1=a0+step;const c0=Math.cos(a0),s0=Math.sin(a0),c1=Math.cos(a1),s1=Math.sin(a1);const q1x=(c0-k*s0)*rx,q1y=(s0+k*c0)*ry;const q2x=(c1+k*s1)*rx,q2y=(s1-k*c1)*ry;const ex=c1*rx,ey=s1*ry;out.push(cos*q1x-sin*q1y+cx,sin*q1x+cos*q1y+cy,cos*q2x-sin*q2y+cx,sin*q2x+cos*q2y+cy,i===count-1?x1:cos*ex-sin*ey+cx,i===count-1?y1:sin*ex+cos*ey+cy)}}function fmt(value){const rounded=Math.round(value*100)/100;return rounded===0?"0":String(rounded)}function pathToD(path){const parts=[];for(const r of path){const p=r.p;if(p.length<2)continue;parts.push("M",fmt(p[0])," ",fmt(p[1]));if(r.straight){for(let o=2;o+5<p.length;o+=6)parts.push("L",fmt(p[o+4])," ",fmt(p[o+5]));if(r.closed)parts.push("Z");continue}for(let o=2;o+5<p.length;o+=6){parts.push("C",fmt(p[o])," ",fmt(p[o+1])," ",fmt(p[o+2])," ",fmt(p[o+3])," ",fmt(p[o+4])," ",fmt(p[o+5]))}if(r.closed)parts.push("Z")}return parts.join("")}var clock={now:0,mode:"free",frame:0,capture:null};var Track=class{constructor(initial){this.initial=initial}initial;keys=[];sample(t){const keys=this.keys;let lo=0,hi=keys.length-1,index=-1;while(lo<=hi){const mid=lo+hi>>1;if(keys[mid].t0<=t){index=mid;lo=mid+1}else{hi=mid-1}}if(index<0)return this.initial;const key=keys[index];if(t>=key.t1||!key.at)return key.to;const span=key.t1-key.t0;const raw=span>0?(t-key.t0)/span:1;return key.at(key.ease?key.ease(raw):raw)}add(key){const keys=this.keys;let index=keys.length;while(index>0&&keys[index-1].t0>key.t0)index--;keys.splice(index,0,key)}step(t,value){this.add({t0:t,t1:t,ease:null,to:value,at:null})}get end(){let end=0;for(const key of this.keys)if(key.t1>end)end=key.t1;return end}};import{Unzlib}from"fflate";function growTo(r,target){const count=segmentCount(r);if(count>=target||count===0)return r;const segments=[];for(let i=0;i<count;i++){const o=i*6;const pts=Array.from(r.p.subarray(o,o+8));segments.push({pts,length:chord(pts)})}while(segments.length<target){let longest=0;for(let i=1;i<segments.length;i++)if(segments[i].length>segments[longest].length)longest=i;const[a,b]=bisect(segments[longest].pts);segments.splice(longest,1,{pts:a,length:chord(a)},{pts:b,length:chord(b)})}const out=new Float64Array(2+target*6);out[0]=r.p[0];out[1]=r.p[1];for(let i=0;i<target;i++){const pts=segments[i].pts;for(let k=0;k<6;k++)out[2+i*6+k]=pts[2+k]}return{p:out,closed:r.closed}}function chord(pts){return Math.hypot(pts[2]-pts[0],pts[3]-pts[1])+Math.hypot(pts[4]-pts[2],pts[5]-pts[3])+Math.hypot(pts[6]-pts[4],pts[7]-pts[5])}function bisect(p){const ax=(p[0]+p[2])/2,ay=(p[1]+p[3])/2;const bx=(p[2]+p[4])/2,by=(p[3]+p[5])/2;const cx=(p[4]+p[6])/2,cy=(p[5]+p[7])/2;const dx=(ax+bx)/2,dy=(ay+by)/2;const ex=(bx+cx)/2,ey=(by+cy)/2;const fx=(dx+ex)/2,fy=(dy+ey)/2;return[[p[0],p[1],ax,ay,dx,dy,fx,fy],[fx,fy,ex,ey,cx,cy,p[6],p[7]]]}function bestRotation(a,b){const count=segmentCount(b);if(!a.closed||!b.closed||count<2)return b;const[ax,ay]=ringCenter(a),[bx,by]=ringCenter(b);const stride=Math.max(1,Math.floor(count/48));let best=0,bestCost=Infinity;for(let shift2=0;shift2<count;shift2+=stride){let cost=0;for(let i=0;i<count;i+=stride){const j=(i+shift2)%count;const dx=a.p[i*6]-ax-(b.p[j*6]-bx);const dy=a.p[i*6+1]-ay-(b.p[j*6+1]-by);cost+=dx*dx+dy*dy}if(cost<bestCost){bestCost=cost;best=shift2}}if(best===0)return b;const out=new Float64Array(b.p.length);out[0]=b.p[best*6];out[1]=b.p[best*6+1];for(let i=0;i<count;i++){const j=(i+best)%count;for(let k=0;k<6;k++)out[2+i*6+k]=b.p[2+j*6+k]}return{p:out,closed:b.closed}}function pointRing(x,y,count,closed){const out=new Float64Array(2+count*6);for(let i=0;i<out.length;i+=2){out[i]=x;out[i+1]=y}return{p:out,closed}}function pairRings(from,to2){const rank=path=>[...path].sort((a2,b2)=>Math.abs(signedArea(b2))+ringLength(b2)*.01-(Math.abs(signedArea(a2))+ringLength(a2)*.01));const a=rank(from),b=rank(to2);const pairs=[];const free=b.slice();for(const ringA of a){if(free.length===0){const[x,y]=ringCenter(ringA);pairs.push([ringA,pointRing(x,y,segmentCount(ringA),ringA.closed)]);continue}const[ax,ay]=ringCenter(ringA);let bestIndex=0,bestCost=Infinity;for(let i=0;i<Math.min(free.length,3);i++){const[bx,by]=ringCenter(free[i]);const cost=Math.hypot(ax-bx,ay-by)+i*40;if(cost<bestCost){bestCost=cost;bestIndex=i}}pairs.push([ringA,free[bestIndex]]);free.splice(bestIndex,1)}for(const ringB of free){const[x,y]=ringCenter(ringB);pairs.push([pointRing(x,y,segmentCount(ringB),ringB.closed),ringB])}return pairs}function alignPaths(from,to2,minSegments=12){const pairs=pairRings(from,to2);const a=[],b=[],closed=[];for(const[ra,rb]of pairs){const target=Math.max(segmentCount(ra),segmentCount(rb),ra.closed&&rb.closed?minSegments:1);let x=growTo(ra,target);let y=growTo(rb,target);if(x.closed&&y.closed){if(Math.sign(signedArea(x))!==Math.sign(signedArea(y))&&signedArea(x)!==0&&signedArea(y)!==0)y=reverseRing(y);y=bestRotation(x,y)}else if(!x.closed&&!y.closed){const n=x.p.length;const straight=Math.hypot(x.p[0]-y.p[0],x.p[1]-y.p[1])+Math.hypot(x.p[n-2]-y.p[n-2],x.p[n-1]-y.p[n-1]);const flipped=Math.hypot(x.p[0]-y.p[n-2],x.p[1]-y.p[n-1])+Math.hypot(x.p[n-2]-y.p[0],x.p[n-1]-y.p[1]);if(flipped<straight)y=reverseRing(y)}a.push(x.p);b.push(y.p);closed.push(x.closed&&y.closed)}return{from:a,to:b,closed}}function pathMixer(from,to2){if(from===to2)return()=>to2;if(pathLength(from)===0&&from.length===0)return alpha3=>alpha3>=1?to2:from;const aligned=alignPaths(from,to2);return alpha3=>{if(alpha3<=0)return from;if(alpha3>=1)return to2;const rings=new Array(aligned.from.length);for(let r=0;r<rings.length;r++){const a=aligned.from[r],b=aligned.to[r];const out=new Float64Array(a.length);for(let i=0;i<a.length;i++)out[i]=a[i]+(b[i]-a[i])*alpha3;rings[r]={p:out,closed:aligned.closed[r]}}return rings}}function matchSequence(a,b){const n=a.length,m=b.length;const table=Array.from({length:n+1},()=>new Uint16Array(m+1));for(let i2=n-1;i2>=0;i2--){for(let j2=m-1;j2>=0;j2--){table[i2][j2]=a[i2]===b[j2]?table[i2+1][j2+1]+1:Math.max(table[i2+1][j2],table[i2][j2+1])}}const pairs=[];let i=0,j=0;while(i<n&&j<m){if(a[i]===b[j]){pairs.push([i++,j++])}else if(table[i+1][j]>=table[i][j+1]){i++}else{j++}}return pairs}var DEFAULT_PROPS={x:0,y:0,rotation:0,sx:1,sy:1,px:0,py:0,opacity:1,visible:true,z:0,path:null,fill:null,fillOpacity:1,stroke:null,strokeOpacity:1,strokeWidth:3,cap:"round",join:"round",dash:null,dashOffset:0,trimFrom:0,trimTo:1,trimEach:false,glow:0,glowColor:null,blend:"normal",fixed:false,image:null};var NUMERIC=new Set(["x","y","rotation","sx","sy","px","py","opacity","z","fillOpacity","strokeOpacity","strokeWidth","dashOffset","trimFrom","trimTo","glow"]);function mixer(prop,from,to2){if(NUMERIC.has(prop)){const a=from,b=to2;return(alpha3=>a+(b-a)*alpha3)}if(prop==="fill"||prop==="stroke"){const a=from,b=to2;if(a&&b)return(alpha3=>mixPaint(a,b,alpha3));return null}if(prop==="glowColor"){const a=from,b=to2;if(a&&b)return(alpha3=>mixColor(a,b,alpha3));return null}if(prop==="path"){const a=from,b=to2;if(a&&b)return pathMixer(a,b);return null}return null}var nextId=1;var Node=class _Node{id=nextId++;parent=null;children=[];data={};label="";base=Object.create(DEFAULT_PROPS);tracks=null;overlay=null;overlayFrame=-1;mounted=false;draw=null;rawOps=null;constructor(path){if(path)this.base.path=path}get(prop){const overlay=this.overlay;if(overlay!==null&&overlay.has(prop)&&(this.overlayFrame===clock.frame||clock.capture!==null)){return overlay.get(prop)}const track=this.tracks?.get(prop);if(track)return track.sample(clock.now);return this.base[prop]}set(prop,value){if(clock.capture){this.overlay??=new Map;this.overlay.set(prop,value);clock.capture.add(this);return this}if(!this.mounted){this.base[prop]=value;return this}if(clock.mode==="render"){this.overlay??=new Map;if(this.overlayFrame!==clock.frame){this.overlay.clear();this.overlayFrame=clock.frame}this.overlay.set(prop,value);return this}this.track(prop).step(clock.now,value);return this}track(prop){this.tracks??=new Map;let track=this.tracks.get(prop);if(!track){track=new Track(this.base[prop]);this.tracks.set(prop,track)}return track}tween(prop,to2,t0,t1,ease){const previous=clock.now;clock.now=t0;const from=this.get(prop);clock.now=previous;const at=t1>t0?mixer(prop,from,to2):null;const key={t0,t1,ease,to:to2,at};this.track(prop).add(key)}add(...nodes){for(const child of nodes){if(child.parent===this)continue;child.parent?.drop(child);child.parent=this;this.children.push(child);if(this.mounted)mountTree(child,clock.now)}return this}drop(child){const index=this.children.indexOf(child);if(index>=0)this.children.splice(index,1);child.parent=null;return this}all(){const out=[];const visit=node=>{out.push(node);for(const child of node.children)visit(child)};visit(this);return out}leaves(){return this.all().filter(node=>node.get("path")!==null||node.draw!==null||node.get("image")!==null)}clone(){const copy=Object.create(Object.getPrototypeOf(this));Object.assign(copy,this);copy.id=nextId++;copy.parent=null;copy.mounted=false;copy.tracks=null;copy.overlay=null;copy.overlayFrame=-1;copy.data={...this.data};copy.base=Object.create(DEFAULT_PROPS);for(const key of Object.keys(DEFAULT_PROPS)){;copy.base[key]=this.get(key)}copy.children=this.children.map(child=>{const next=child.clone();next.parent=copy;return next});return copy}localMatrix(){return compose(this.get("x"),this.get("y"),this.get("rotation"),this.get("sx"),this.get("sy"),this.get("px"),this.get("py"))}worldMatrix(){let m=this.localMatrix();for(let node=this.parent;node;node=node.parent)m=mul(node.localMatrix(),m);return m}toWorld(x,y){return apply(this.worldMatrix(),x,y)}bounds(){return this.boundsFrom(this.parent?this.parent.worldMatrix():IDENTITY)??{x:0,y:0,width:0,height:0}}boundsFrom(parent){const m=mul(parent,this.localMatrix());let result=null;const path=this.get("path");if(path)result=pathBounds(transformPath(path,m));const image2=this.get("image");if(image2)result=unionBounds(result,boundsOfRect(m,image2.width,image2.height));if(this.draw){const built=this.draw(clock.now);const list3=built===null?[]:Array.isArray(built)?built:[built];for(const child of list3)result=unionBounds(result,child.boundsFrom(m))}for(const child of this.children){if(child.get("visible"))result=unionBounds(result,child.boundsFrom(m))}return result}get center(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height/2]}get top(){const b=this.bounds();return[b.x+b.width/2,b.y]}get bottom(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height]}get left(){const b=this.bounds();return[b.x,b.y+b.height/2]}get right(){const b=this.bounds();return[b.x+b.width,b.y+b.height/2]}get width(){return this.bounds().width}get height(){return this.bounds().height}at(x,y){const[px,py]=typeof x==="number"?[x,y??0]:x;this.set("x",px);this.set("y",py);return this}shift(dx,dy){const[ox,oy]=typeof dx==="number"?[dx,dy??0]:dx;this.set("x",this.get("x")+ox);this.set("y",this.get("y")+oy);return this}moveTo(target){const destination=target instanceof _Node?target.center:target;const[cx,cy]=this.center;const inverse=this.parent?invert(this.parent.worldMatrix()):IDENTITY;const[lx0,ly0]=apply(inverse,cx,cy);const[lx1,ly1]=apply(inverse,destination[0],destination[1]);return this.shift(lx1-lx0,ly1-ly0)}pivotAt(point){const parent=this.parent?this.parent.worldMatrix():IDENTITY;const before=mul(parent,this.localMatrix());const[lx,ly]=apply(invert(before),point[0],point[1]);const[nx,ny]=apply(invert(parent),point[0],point[1]);this.set("px",lx);this.set("py",ly);this.set("x",nx);this.set("y",ny);return this}scale(factor,about){const[fx,fy]=typeof factor==="number"?[factor,factor]:factor;this.pivotAt(about??this.center);this.set("sx",this.get("sx")*fx);this.set("sy",this.get("sy")*fy);return this}rotate(radians,about){this.pivotAt(about??this.center);this.set("rotation",this.get("rotation")+radians);return this}fitTo(size){const b=this.bounds();const scales=[];if(size.width!==void 0&&b.width>0)scales.push(size.width/b.width);if(size.height!==void 0&&b.height>0)scales.push(size.height/b.height);return scales.length?this.scale(Math.min(...scales)):this}nextTo(target,side="right",gap=28){const[dx,dy]=direction(side);const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const own=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;const anchorX=cx+dx*(b.width/2+gap+own.width/2);const anchorY=cy+dy*(b.height/2+gap+own.height/2);return this.moveTo([anchorX,anchorY])}alignTo(target,edge){const own=this.bounds();const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};if(edge==="left")return this.shift(b.x-own.x,0);if(edge==="right")return this.shift(b.x+b.width-own.x-own.width,0);if(edge==="top")return this.shift(0,b.y-own.y);return this.shift(0,b.y+b.height-own.y-own.height)}arrange(side="right",gap=24){const[dx,dy]=direction(side);const center2=this.center;let previous=null;for(const child of this.children){if(previous){const b=previous.bounds(),own=child.bounds();const px=b.x+b.width/2+dx*(b.width/2+gap+own.width/2);const py=b.y+b.height/2+dy*(b.height/2+gap+own.height/2);child.moveTo([dx===0?b.x+b.width/2:px,dy===0?b.y+b.height/2:py])}previous=child}return this.moveTo(center2)}fill(color,opacity){this.set("fill",color===null?null:toPaint(color));if(opacity!==void 0)this.set("fillOpacity",opacity);return this}stroke(color,width,opacity){this.set("stroke",color===null?null:toPaint(color));if(width!==void 0)this.set("strokeWidth",width);if(opacity!==void 0)this.set("strokeOpacity",opacity);return this}color(color){const paint=toPaint(color);for(const node of this.all()){if(node.get("stroke"))node.set("stroke",paint);if(node.get("fill"))node.set("fill",paint);if(node.get("glowColor")&&!isGradient(paint))node.set("glowColor",paint)}return this}opacity(value){return this.set("opacity",value)}glow(radius,color){this.set("glow",radius);if(color!==void 0){const paint=toPaint(color);this.set("glowColor",isGradient(paint)?null:paint)}return this}dash(pattern,offset=0){this.set("dash",pattern);return this.set("dashOffset",offset)}zIndex(value){return this.set("z",value)}pin(){return this.set("fixed",true)}hide(){return this.set("visible",false)}show(){return this.set("visible",true)}named(label){this.label=label;return this}};function boundsOfRect(m,width,height){const corners=[apply(m,0,0),apply(m,width,0),apply(m,width,height),apply(m,0,height)];const xs=corners.map(c=>c[0]),ys=corners.map(c=>c[1]);const x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y}}function direction(side){if(typeof side!=="string")return side;if(side==="left")return[-1,0];if(side==="right")return[1,0];if(side==="top"||side==="up")return[0,-1];return[0,1]}function mountTree(node,time){const wasVisible=node.base.visible;for(const entry of node.all())entry.mounted=true;if(time>0||!wasVisible){const track=node.track("visible");track.initial=false;if(wasVisible)track.step(time,true)}}function group(...children){return new Node().add(...children)}function dynamic(build){const node=new Node;node.draw=build;return node}var ImageAssetError=class extends Error{constructor(message){super(message);this.name="ImageAssetError"}};var MAX_BYTES=16*1024*1024;var MAX_PIXELS=16*1024*1024;var PREFIX="data:image/png;base64,";var RUNTIME=Symbol.for("vizmatic.stage.image.runtime.v1");var host=globalThis;var runtime=host[RUNTIME]??Object.freeze({prepared:new WeakSet,browserSources:new WeakMap});if(!host[RUNTIME])Object.defineProperty(host,RUNTIME,{value:runtime});var{prepared,browserSources}=runtime;var visibility=new WeakMap;var VISIBILITY=Symbol.for("vizmatic.stage.image.visibility.v1");function freezeAsset(fields,alpha3){if(alpha3!==void 0){const carried=typeof alpha3==="boolean"?alpha3:Object.freeze({width:alpha3.width,height:alpha3.height,bits:base64(alpha3.mask)});Object.defineProperty(fields,VISIBILITY,{value:carried});visibility.set(fields,alpha3)}return Object.freeze(fields)}function fail(message){throw new ImageAssetError(message)}function base64(bytes){const chunks=[];for(let at=0;at<bytes.length;at+=8192)chunks.push(String.fromCharCode(...bytes.subarray(at,at+8192)));return btoa(chunks.join(""))}function dataUri(bytes,mediaType="image/png"){return`data:${mediaType};base64,${base64(bytes)}`}async function sourceBytes(source,options){if(source instanceof Uint8Array){if(source.byteLength>MAX_BYTES)fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);return Uint8Array.from(source)}if(typeof source!=="string"||!source)fail("Image asset needs encoded bytes, a PNG data URI, or a local filename.");if(source.startsWith("data:")){if(!source.startsWith(PREFIX))fail("Image assets currently support only image/png base64 data URIs.");const encoded=source.slice(PREFIX.length);if(!encoded.length||encoded.length>Math.ceil(MAX_BYTES/3)*4||encoded.length%4||!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded))fail("Image asset contains invalid or oversized base64 data.");const bytes=Uint8Array.from(atob(encoded),character=>character.charCodeAt(0));if(bytes.length>MAX_BYTES)fail(`Image asset exceeds ${MAX_BYTES} encoded bytes.`);return bytes}if(/^[a-z][\w+.-]*:/i.test(source)||source.startsWith("//"))fail("Image assets must use local files or embedded bytes; remote URLs are not loaded.");if(typeof process==="undefined"||!process.versions?.node)fail("Resolve browser image assets from embedded bytes or a data URI before compiling.");const fsModule="node:fs/promises",pathModule="node:path";const[fs,path]=await Promise.all([import(fsModule),import(pathModule)]);const filename=path.resolve(options.baseDir??process.cwd(),source);try{if((await fs.stat(filename)).size>MAX_BYTES)fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);const bytes=await fs.readFile(filename);if(bytes.length>MAX_BYTES)fail(`Image asset exceeds ${MAX_BYTES} encoded bytes: ${filename}`);return Uint8Array.from(bytes)}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Could not read image asset ${JSON.stringify(filename)}: ${error.message}`)}}function inspectPng(bytes,strict=true){const signature=[137,80,78,71,13,10,26,10];if(bytes.length<33||signature.some((value,i)=>bytes[i]!==value))fail("Image asset is not a PNG.");const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);const name=at=>String.fromCharCode(...bytes.subarray(at+4,at+8));if(view.getUint32(8)!==13||name(8)!=="IHDR")fail("Image PNG must begin with one IHDR chunk.");const width=view.getUint32(16),height=view.getUint32(20);if(!width||!height||width*height>MAX_PIXELS)fail(`Image PNG must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);const channels={0:1,2:3,3:1,4:2,6:4}[bytes[25]];const depth=bytes[24],interlace=bytes[28];if(strict&&(depth!==8||interlace!==0)){fail("Image assets support noninterlaced 8-bit PNGs, including RGB, RGBA, grayscale and palette images.")}const depths=bytes[25]===0?[1,2,4,8,16]:bytes[25]===3?[1,2,4,8]:[8,16];if(!channels||!depths.includes(depth)||bytes[26]!==0||bytes[27]!==0||interlace>1)fail("Image PNG has unsupported header fields.");const passes=interlace?[[0,0,8,8],[4,0,8,8],[0,4,4,8],[2,0,4,4],[0,2,2,4],[1,0,2,2],[0,1,1,2]]:[[0,0,1,1]];const expected=passes.reduce((sum,[x,y,dx,dy])=>{const w=Math.max(0,Math.ceil((width-x)/dx)),h=Math.max(0,Math.ceil((height-y)/dy));return sum+(w&&h?h*(1+Math.ceil(w*channels*depth/8)):0)},0);let expanded2=0,data=false,dataEnded=false,ended=false;const inflater=new Unzlib(chunk=>{expanded2+=chunk.length;if(expanded2>expected)fail("Image PNG expands beyond its declared dimensions.")});for(let at=8;at+12<=bytes.length;){const length=view.getUint32(at),type=name(at),end=at+length+12;if(end>bytes.length)fail("Image PNG chunk exceeds the encoded bytes.");if(type==="IHDR"&&at!==8)fail("Image PNG has more than one IHDR chunk.");if(strict&&["iCCP","acTL","fcTL","fdAT"].includes(type))fail("Image assets do not support compressed color profiles or animated PNGs.");if(type==="iCCP"){let start=at+8;while(start<end-4&&bytes[start]!==0)start++;if(start+2>=end-4||bytes[start+1]!==0)fail("Image PNG color profile is invalid.");let profileSize=0;const profile=new Unzlib(chunk=>{profileSize+=chunk.length;if(profileSize>MAX_BYTES)fail("Image PNG color profile exceeds the decoded byte limit.")});for(let part=start+2;part<end-4;part+=1024)profile.push(bytes.subarray(part,Math.min(part+1024,end-4)),false);profile.push(new Uint8Array(0),true)}if(type==="IDAT"){if(dataEnded)fail("Image PNG data chunks must be consecutive.");data=true;for(let part=at+8;part<end-4;part+=1024)inflater.push(bytes.subarray(part,Math.min(part+1024,end-4)),false)}else if(data)dataEnded=true;if(type==="IEND"){if(length||end!==bytes.length)fail("Image PNG has an invalid end chunk.");ended=true;break}at=end}if(!data||!ended)fail("Image PNG is missing its data or end chunk.");inflater.push(new Uint8Array(0),true);if(expanded2!==expected)fail("Image PNG scanlines do not match its dimensions.");return{width,height}}async function resolveImageAsset(source,options={}){if(options.mediaType!==void 0&&options.mediaType!=="image/png")fail(`Unsupported image asset media type: ${options.mediaType}. Use image/png.`);if(options.sha256!==void 0&&(typeof options.sha256!=="string"||!/^[a-f\d]{64}$/i.test(options.sha256)))fail("Image asset SHA-256 must contain 64 hexadecimal digits.");if(options.id!==void 0&&(typeof options.id!=="string"||!options.id.trim()))fail("Image asset ID must be a nonempty string.");const bytes=await sourceBytes(source,options);let dimensions;let visible;try{dimensions=inspectPng(bytes);const decoded=decodePng(bytes,{checkCrc:true});visible=pngVisibility(decoded);if(decoded.width!==dimensions.width||decoded.height!==dimensions.height)fail("Decoded image dimensions differ from the PNG header.")}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Could not decode image asset: ${error.message}`)}for(const key of["width","height"]){if(options[key]!==void 0&&options[key]!==dimensions[key])fail(`Image asset ${key} is ${dimensions[key]}, not the declared ${options[key]}.`)}const hash=await globalThis.crypto.subtle.digest("SHA-256",Uint8Array.from(bytes).buffer);const sha256=Array.from(new Uint8Array(hash),byte=>byte.toString(16).padStart(2,"0")).join("");if(options.sha256!==void 0&&sha256!==options.sha256.toLowerCase())fail(`Image asset SHA-256 mismatch: expected ${options.sha256.toLowerCase()}, received ${sha256}.`);const asset=freezeAsset({...options.id?{id:options.id}:{},src:dataUri(bytes),mediaType:"image/png",...dimensions,sha256},visible);await preloadBrowserImage(asset,bytes);prepared.add(asset);return asset}async function preloadBrowserImage(asset,bytes){const swapped=asset.mediaType==="image/jpeg"&&jpegOrientation(bytes)>=5;const width=swapped?asset.height:asset.width,height=swapped?asset.width:asset.height;if(asset.mediaType==="image/gif"&&typeof createImageBitmap!=="undefined"){try{const bitmap=await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer],{type:asset.mediaType}));if(bitmap.width!==width||bitmap.height!==height)fail("Browser image dimensions differ from the validated asset.");browserSources.set(asset,bitmap)}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Browser could not decode image asset: ${error.message}`)}}else if(typeof Image!=="undefined"){const element=new Image;element.src=asset.src;try{await element.decode()}catch(error){fail(`Browser could not decode image asset: ${error.message}`)}if(element.naturalWidth!==width||element.naturalHeight!==height)fail("Browser image dimensions differ from the validated asset.");if(asset.mediaType==="image/gif"){const canvas2=document.createElement("canvas");canvas2.width=asset.width;canvas2.height=asset.height;canvas2.getContext("2d").drawImage(element,0,0);browserSources.set(asset,canvas2)}else browserSources.set(asset,element)}else if(typeof createImageBitmap!=="undefined"){try{const bitmap=await createImageBitmap(new Blob([Uint8Array.from(bytes).buffer],{type:asset.mediaType}));if(bitmap.width!==width||bitmap.height!==height)fail("Browser image dimensions differ from the validated asset.");browserSources.set(asset,bitmap)}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Browser could not decode image asset: ${error.message}`)}}}function jpegOrientation(bytes){const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);for(let at=2;at+4<=bytes.length;){if(bytes[at++]!==255)break;while(bytes[at]===255)at++;const marker=bytes[at++];if(marker===218||marker===217||at+2>bytes.length)break;const length=view.getUint16(at),start=at+2,end=at+length;if(length<2||end>bytes.length)break;if(marker===225&&end-start>=14&&String.fromCharCode(...bytes.subarray(start,start+6))==="Exif\0\0"){const tiff=start+6,order=view.getUint16(tiff),little=order===18761;if(![18761,19789].includes(order)||view.getUint16(tiff+2,little)!==42)return 1;const ifd=tiff+view.getUint32(tiff+4,little);if(ifd<tiff+8||ifd+2>end)return 1;const count=view.getUint16(ifd,little);for(let entry=ifd+2;entry+12<=end&&entry<ifd+2+count*12;entry+=12){if(view.getUint16(entry,little)===274&&view.getUint16(entry+2,little)===3&&view.getUint32(entry+4,little)===1){const orientation=view.getUint16(entry+8,little);return orientation>=1&&orientation<=8?orientation:1}}}at=end}return 1}async function resolveLegacyImage(source,allowNetwork){let bytes,declared;if(source.startsWith("data:")){const match=/^data:(image\/(?:png|jpe?g|gif));base64,([A-Za-z0-9+/]+={0,2})$/.exec(source);if(!match||match[2].length%4||match[2].length>Math.ceil(MAX_BYTES/3)*4)fail("Image contains invalid, unsupported or oversized base64 data.");declared=match[1]==="image/jpg"?"image/jpeg":match[1];bytes=Uint8Array.from(atob(match[2]),character=>character.charCodeAt(0))}else if(/^https?:\/\//i.test(source)||source.startsWith("//")||typeof window!=="undefined"){const offline=typeof process!=="undefined"&&(process.env?.VIZMATIC_DISABLE_NETWORK==="1"||process.env?.VIZMATIC_OFFLINE==="1");if(!allowNetwork||offline)fail("Network image loading is disabled by imageNetwork: deny or the offline environment.");try{const url=typeof document!=="undefined"?new URL(source,document.baseURI).href:source;if(!/^https?:\/\//i.test(url))fail("Network images require an HTTP or HTTPS URL.");const response=await fetch(url,{signal:AbortSignal.timeout(1e4)});if(!response.ok)fail(`Image request failed with HTTP ${response.status}: ${url}`);const length=response.headers.get("content-length");if(length&&Number(length)>MAX_BYTES)fail(`Image exceeds ${MAX_BYTES} encoded bytes.`);declared=response.headers.get("content-type")?.split(";")[0].trim();const reader=response.body?.getReader();if(!reader)fail("Image request returned no body.");const chunks=[];let total=0;for(;;){const{value,done}=await reader.read();if(done)break;total+=value.length;if(total>MAX_BYTES){await reader.cancel();fail(`Image exceeds ${MAX_BYTES} encoded bytes.`)}chunks.push(value)}bytes=new Uint8Array(total);let at=0;for(const chunk of chunks){bytes.set(chunk,at);at+=chunk.length}}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Could not load image ${JSON.stringify(source)}: ${error.message}`)}}else bytes=await sourceBytes(source,{});const{visible,...info}=legacyImageHeader(bytes);if(declared?.startsWith("image/")&&declared!==info.mediaType)fail(`Image MIME type ${declared} does not match ${info.mediaType} bytes.`);const hash=await crypto.subtle.digest("SHA-256",Uint8Array.from(bytes).buffer);const sha256=Array.from(new Uint8Array(hash),byte=>byte.toString(16).padStart(2,"0")).join("");const asset=freezeAsset({src:dataUri(bytes,info.mediaType),sha256,...info},visible);if(typeof process!=="undefined"&&process.versions?.node){const moduleName="@resvg/resvg-js";const{Resvg:Resvg3}=await import(moduleName);try{const raster=new Resvg3(`<svg xmlns="http://www.w3.org/2000/svg" width="${asset.width}" height="${asset.height}"><image width="${asset.width}" height="${asset.height}" href="${asset.src}"/></svg>`,{font:{loadSystemFonts:false}});if(!raster.innerBBox())fail("Image decoder rejected the encoded image.");const rendered=raster.render();if(asset.mediaType==="image/jpeg"&&!rendered.pixels.some((alpha3,i)=>i%4===3&&alpha3>0))fail("Image decoder rejected the JPEG pixel data.")}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Could not decode image: ${error.message}`)}}await preloadBrowserImage(asset,bytes);prepared.add(asset);return asset}function legacyImageHeader(bytes){if(!bytes.length||bytes.length>MAX_BYTES)fail("Image bytes are empty or oversized.");const view=new DataView(bytes.buffer,bytes.byteOffset,bytes.byteLength);let width=0,height=0,mediaType;let visible;if(bytes.length>=33&&[137,80,78,71,13,10,26,10].every((v,i)=>bytes[i]===v)){mediaType="image/png";try{;({width,height}=inspectPng(bytes,false));visible=pngVisibility(decodePng(bytes,{checkCrc:true}))}catch(error){if(error instanceof ImageAssetError)throw error;fail(`Could not decode image PNG: ${error.message}`)}}else if(bytes.length>=14&&/^GIF8[79]a$/.test(String.fromCharCode(...bytes.subarray(0,6)))){width=view.getUint16(6,true);height=view.getUint16(8,true);mediaType="image/gif";let at=13+(bytes[10]&128?3*2**((bytes[10]&7)+1):0),frames=0,ended=false;const blocks=(capture=false)=>{const chunks=[];let total=0;for(;;){if(at>=bytes.length)fail("Image GIF data is truncated.");const length=bytes[at++];if(!length)break;if(capture){chunks.push(bytes.subarray(at,at+length));total+=length}at+=length;if(at>bytes.length)fail("Image GIF block exceeds the encoded bytes.")}const out=new Uint8Array(total);let offset=0;for(const chunk of chunks){out.set(chunk,offset);offset+=chunk.length}return out};while(at<bytes.length){const tag=bytes[at++];if(tag===59){ended=true;break}if(tag===33){at++;blocks()}else if(tag===44){if(at+9>bytes.length)fail("Image GIF descriptor is truncated.");const fw=view.getUint16(at+4,true),fh=view.getUint16(at+6,true),flags=bytes[at+8];if(!fw||!fh||fw*fh>MAX_PIXELS)fail("Image GIF frame dimensions are invalid.");at+=9+(flags&128?3*2**((flags&7)+1):0);if(bytes[at]<2||bytes[at]>8)fail("Image GIF compression code size is invalid.");const codeSize=bytes[at++];validateGifData(blocks(true),codeSize,fw*fh);frames++}else fail("Image GIF contains an invalid block.")}if(!frames||!ended)fail("Image GIF is missing its frame data or trailer.")}else if(bytes[0]===255&&bytes[1]===216){mediaType="image/jpeg";for(let at=2;at+3<bytes.length;){if(bytes[at++]!==255)fail("Image JPEG contains an invalid marker.");while(bytes[at]===255)at++;if(at+3>bytes.length)fail("Image JPEG marker is truncated.");const marker=bytes[at++];if(marker===218||marker===217)break;const length=view.getUint16(at);if(length<2||at+length>bytes.length)fail("Image JPEG segment is truncated.");if(marker>=192&&marker<=207&&![196,200,204].includes(marker)){if(length<8)fail("Image JPEG frame is truncated.");height=view.getUint16(at+3);width=view.getUint16(at+5)}at+=length}if(!bytes.some((value,i)=>i>0&&value===217&&bytes[i-1]===255))fail("Image JPEG is missing its end marker.")}else fail("Image bytes are not a supported PNG, JPEG or GIF.");if(!width||!height||width*height>MAX_PIXELS)fail(`Image must contain at most ${MAX_PIXELS} pixels with positive dimensions.`);return{width,height,mediaType,visible}}function pngVisibility(png){const{width,height,channels,depth,data,palette,transparency}=png;if(channels!==2&&channels!==4&&!palette&&!transparency)return true;const mask=new Uint8Array(Math.ceil(width*height/8));const sample=(x,y,channel=0)=>depth>=8?data[(y*width+x)*channels+channel]:data[y*Math.ceil(width*depth/8)+(x*depth>>3)]>>8-depth-x*depth%8&(1<<depth)-1;let count=0;for(let y=0;y<height;y++)for(let x=0;x<width;x++){let visible;if(channels===2||channels===4)visible=sample(x,y,channels-1)>0;else if(palette){const color=palette[sample(x,y)];if(!color)fail("Image PNG references a missing palette color.");visible=(color[3]??255)>0}else visible=!transparency.every((value,channel)=>sample(x,y,channel)===value);if(visible){const index=y*width+x;mask[index>>3]|=1<<(index&7);count++}}return count===0?false:count===width*height?true:{width,height,mask,crops:new Map}}function imageHasVisiblePixels(asset,crop){let value=asset?visibility.get(asset):void 0;if(value===void 0&&asset){const carried=asset[VISIBILITY];value=typeof carried==="boolean"?carried:carried?{width:carried.width,height:carried.height,mask:Uint8Array.from(atob(carried.bits),c=>c.charCodeAt(0)),crops:new Map}:void 0;if(value!==void 0)visibility.set(asset,value)}if(value===void 0)return true;if(typeof value==="boolean")return value;if(!crop||crop.x===0&&crop.y===0&&crop.width===value.width&&crop.height===value.height)return true;const key=`${crop.x},${crop.y},${crop.width},${crop.height}`,cached=value.crops.get(key);if(cached!==void 0)return cached;for(let y=Math.floor(crop.y);y<Math.ceil(crop.y+crop.height);y++)for(let x=Math.floor(crop.x);x<Math.ceil(crop.x+crop.width);x++){const index=y*value.width+x;if(value.mask[index>>3]&1<<(index&7)){value.crops.set(key,true);return true}}value.crops.set(key,false);return false}function validateGifData(data,minimum,pixels){const clear=1<<minimum,end=clear+1,lengths=new Uint16Array(4096);let bits=minimum+1,next=end+1,previous=0,offset=0,written=0;for(;;){if(offset+bits>data.length*8)fail("Image GIF compressed data is truncated.");let code=0;for(let bit=0;bit<bits;bit++)code|=(data[offset+bit>>3]>>(offset+bit&7)&1)<<bit;offset+=bits;if(code===clear){bits=minimum+1;next=end+1;previous=0;continue}if(code===end){if(written!==pixels)fail("Image GIF decoded length does not match its frame dimensions.");return}const length=code<clear?1:code<next?lengths[code]:code===next&&previous?previous+1:0;if(!length)fail("Image GIF contains an invalid compression reference.");written+=length;if(written>pixels)fail("Image GIF expands beyond its frame dimensions.");if(previous&&next<4096){lengths[next++]=previous+1;if(next===1<<bits&&bits<12)bits++}previous=length}}function isImageAsset(value){return!!value&&typeof value==="object"&&prepared.has(value)}function browserImageSource(asset){return asset?browserSources.get(asset):void 0}function validateStageImage(value,asset){if(![value.width,value.height].every(n=>Number.isFinite(n)&&n>0))fail("Image destination dimensions must be positive finite numbers.");const crop=value.crop;if(crop&&(![crop.x,crop.y,crop.width,crop.height].every(Number.isFinite)||crop.x<0||crop.y<0||crop.width<=0||crop.height<=0||crop.x+crop.width>asset.width||crop.y+crop.height>asset.height)){fail("Image crop must be a nonempty region inside the intrinsic image pixels.")}}function imageFromAsset(asset,options={}){if(!isImageAsset(asset))fail("Call and await resolveImageAsset before creating an image node.");if(options.fit!==void 0&&options.fit!=="contain"&&options.fit!=="cover")fail("Image fit must be contain or cover.");let crop={...options.crop??{x:0,y:0,width:asset.width,height:asset.height}};let width=options.width??(options.height===void 0?crop.width:options.height*crop.width/crop.height);let height=options.height??width*crop.height/crop.width;validateStageImage({src:asset.src,width,height,crop},asset);if(options.fit==="cover"){const ratio=width/height,sourceRatio=crop.width/crop.height;if(sourceRatio>ratio){const next=crop.height*ratio;crop={...crop,x:crop.x+(crop.width-next)/2,width:next}}else{const next=crop.width/ratio;crop={...crop,y:crop.y+(crop.height-next)/2,height:next}}}else{const scale=Math.min(width/crop.width,height/crop.height);width=crop.width*scale;height=crop.height*scale}const node=new Node().set("image",Object.freeze({src:asset.src,width,height,crop:Object.freeze(crop),asset}));node.set("px",width/2).set("py",height/2);node.label=asset.id??"image";return node}var clockNow=()=>clock.now;var ALONG_PIECE_LENGTH=14;var MAX_ALONG_PIECES=96;function worldPaint(paint,m){if(!paint||!isGradient(paint))return paint;if(paint.type==="linear"){return{...paint,from:apply(m,paint.from[0],paint.from[1]),to:apply(m,paint.to[0],paint.to[1])}}if(paint.type==="radial"){return{...paint,center:apply(m,paint.center[0],paint.center[1]),radius:paint.radius*matScale(m)}}return paint}function sameMatrix(a,b){return a[0]===b[0]&&a[1]===b[1]&&a[2]===b[2]&&a[3]===b[3]&&a[4]===b[4]&&a[5]===b[5]}var worldCache=new WeakMap;function toWorld(node,path,m){const cached=worldCache.get(node);if(cached&&cached.path===path&&sameMatrix(cached.matrix,m))return cached.world;const world=transformPath(path,m);worldCache.set(node,{path,matrix:m,world});return world}function emit(node,path,m,alpha3,ops){const fill=node.get("fill");const stroke=node.get("stroke");const fillAlpha=fill?alpha3*node.get("fillOpacity"):0;const strokeAlpha=stroke?alpha3*node.get("strokeOpacity"):0;const glow=node.get("glow");if(fillAlpha<=.002&&strokeAlpha<=.002&&glow<=0)return;const world=toWorld(node,path,m);const scale=matScale(m);const trimFrom=node.get("trimFrom"),trimTo=node.get("trimTo");let strokePath=world;if(trimFrom>0||trimTo<1)strokePath=trimPath(world,trimFrom,trimTo,node.get("trimEach"));if(strokePath.length===0&&fillAlpha<=.002)return;const dash=node.get("dash");const op={kind:"path",path:world,strokePath,fill:fillAlpha>.002?worldPaint(fill,m):null,fillAlpha,stroke:strokeAlpha>.002?worldPaint(stroke,m):null,strokeAlpha,strokeWidth:node.get("strokeWidth")*scale,cap:node.get("cap"),join:node.get("join"),dash:dash?dash.map(value=>value*scale):null,dashOffset:node.get("dashOffset")*scale,glow:glow*scale,glowColor:node.get("glowColor"),blend:node.get("blend"),node};if(op.stroke&&isGradient(op.stroke)&&op.stroke.type==="along")splitAlong(op,op.stroke,ops);else ops.push(op)}function splitAlong(op,paint,ops){ops.push({...op,stroke:null,strokeAlpha:0});const glowless={...op,fill:null,fillAlpha:0,glow:0};const length=pathLength(op.strokePath);const full=pathLength(op.path);if(length===0)return;const fraction=full>0?Math.min(1,length/full):1;const pieces=Math.min(MAX_ALONG_PIECES,Math.max(2,Math.ceil(length/ALONG_PIECE_LENGTH)));const overlap=.6/pieces;for(let i=0;i<pieces;i++){const from=i/pieces,to2=Math.min(1,(i+1)/pieces+overlap);const piece=trimPath(op.strokePath,from,to2);if(piece.length===0)continue;ops.push({...glowless,strokePath:piece,path:piece,stroke:sampleStops(paint.stops,(i+.5)/pieces*fraction),cap:i===0||i===pieces-1?op.cap:"butt"})}}function walk(node,parent,screen,alpha3,ops){if(!node.get("visible"))return;const opacity=node.get("opacity")*alpha3;if(opacity<=.002)return;const base=node.get("fixed")?screen:parent;const m=mul(base,node.localMatrix());const path=node.get("path");if(path&&path.length>0)emit(node,path,m,opacity,ops);const image2=node.get("image");if(image2)ops.push({kind:"image",image:image2,matrix:m,alpha:opacity,node});if(node.rawOps)node.rawOps(m,opacity,ops);if(node.draw){const built=node.draw(clockNow());if(built){const list3=Array.isArray(built)?built:[built];for(const child of list3)walk(child,m,screen,opacity,ops)}}const children=node.children;if(children.length===0)return;let sorted=false;for(let i=0;i<children.length;i++){if(children[i].get("z")!==0){sorted=true;break}}const ordered=sorted?children.map((child,index)=>({child,index,z:child.get("z")})).sort((a,b)=>a.z-b.z||a.index-b.index).map(entry=>entry.child):children;for(const child of ordered)walk(child,m,screen,opacity,ops)}function buildOps(root,camera,width,height){const screen=[1,0,0,1,width/2,height/2];const view=mul(screen,compose(0,0,-camera.rotation,camera.zoom,camera.zoom,camera.x,camera.y));const ops=[];walk(root,view,screen,1,ops);return ops}var GLOW_PASSES=7;function glowPasses(glow,width){const out=[];for(let i=GLOW_PASSES;i>=1;i--){const k=i/GLOW_PASSES;out.push({width:width+glow*2*k,alpha:.16*(1-k)*(1-k)+.018})}return out}function glowOf(op){if(op.glowColor)return op.glowColor;const paint=op.stroke??op.fill;if(!paint)return null;return isGradient(paint)?sampleStops(paint.stops,.5):paint}var dCache=new WeakMap;function pathData(path){let d=dCache.get(path);if(d===void 0){d=pathToD(path);dCache.set(path,d)}return d}function fmt2(value){return String(Math.round(value*1e3)/1e3)}function gradientDef(id,paint){const stops=paint.stops.map(([at,color])=>`<stop offset="${fmt2(at)}" stop-color="${css([color[0],color[1],color[2],1])}"${color[3]<1?` stop-opacity="${fmt2(color[3])}"`:""}/>`).join("");if(paint.type==="linear"){return`<linearGradient id="${id}" gradientUnits="userSpaceOnUse" x1="${fmt2(paint.from[0])}" y1="${fmt2(paint.from[1])}" x2="${fmt2(paint.to[0])}" y2="${fmt2(paint.to[1])}">${stops}</linearGradient>`}if(paint.type==="radial"){return`<radialGradient id="${id}" gradientUnits="userSpaceOnUse" cx="${fmt2(paint.center[0])}" cy="${fmt2(paint.center[1])}" r="${fmt2(paint.radius)}">${stops}</radialGradient>`}return""}function strokeAttrs(op){let attrs=` stroke-linecap="${op.cap}" stroke-linejoin="${op.join}"`;if(op.dash)attrs+=` stroke-dasharray="${op.dash.map(fmt2).join(" ")}" stroke-dashoffset="${fmt2(op.dashOffset)}"`;return attrs}function escapeAttr(value){return value.replace(/&/g,"&amp;").replace(/"/g,"&quot;").replace(/</g,"&lt;")}function frameToSvg(frame,options={}){const scale=options.scale??1;const w=frame.width,h=frame.height;const defs=[];const body=[];let gradientCount=0;const paintAttr=(paint,attr,alpha3)=>{if(isGradient(paint)){const id=`g${gradientCount++}`;defs.push(gradientDef(id,paint));return`${attr}="url(#${id})"${alpha3<1?` ${attr}-opacity="${fmt2(alpha3)}"`:""}`}const rgba=paint;const a=rgba[3]*alpha3;return`${attr}="${css([rgba[0],rgba[1],rgba[2],1])}"${a<1?` ${attr}-opacity="${fmt2(a)}"`:""}`};if(frame.background&&!options.transparent)body.push(`<rect width="${w}" height="${h}" fill="${frame.background}"/>`);for(const op of frame.ops){if(op.kind==="image"){const m=op.matrix;const{image:image2}=op,crop=image2.crop;if(crop&&!image2.asset)throw new ImageAssetError("Cropped image SVG needs a prepared image asset.");const picture=`<image href="${escapeAttr(image2.src)}" width="${crop?image2.asset.width:image2.width}" height="${crop?image2.asset.height:image2.height}" preserveAspectRatio="none"/>`;const content=crop?`<svg width="${fmt2(image2.width)}" height="${fmt2(image2.height)}" viewBox="${[crop.x,crop.y,crop.width,crop.height].map(fmt2).join(" ")}" preserveAspectRatio="none" overflow="hidden">${picture}</svg>`:picture;body.push(`<g transform="matrix(${m.map(fmt2).join(" ")})"${op.alpha<1?` opacity="${fmt2(op.alpha)}"`:""}>${content}</g>`);continue}const style=op.blend!=="normal"?` style="mix-blend-mode:${op.blend}"`:"";if(op.glow>0){const color=glowOf(op);const glowD=pathData(op.strokePath.length?op.strokePath:op.path);if(color&&glowD){const base=Math.max(op.fillAlpha,op.strokeAlpha);const mode=frame.dark?' style="mix-blend-mode:screen"':"";const passes=glowPasses(op.glow,op.stroke?op.strokeWidth:0).map(pass=>`<path d="${glowD}" fill="none" stroke="${css([color[0],color[1],color[2],1])}" stroke-opacity="${fmt2(pass.alpha*base)}" stroke-width="${fmt2(pass.width)}" stroke-linecap="round" stroke-linejoin="round"/>`).join("");body.push(`<g${mode}>${passes}</g>`)}}if(op.fill&&op.stroke&&op.strokePath===op.path){body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)} ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`);continue}if(op.fill)body.push(`<path d="${pathData(op.path)}" ${paintAttr(op.fill,"fill",op.fillAlpha)}${style}/>`);if(op.stroke&&op.strokePath.length){body.push(`<path d="${pathData(op.strokePath)}" fill="none" ${paintAttr(op.stroke,"stroke",op.strokeAlpha)} stroke-width="${fmt2(op.strokeWidth)}"${strokeAttrs(op)}${style}/>`)}}const defsBlock=defs.length?`<defs>${defs.join("")}</defs>`:"";return`<svg xmlns="http://www.w3.org/2000/svg" width="${w*scale}" height="${h*scale}" viewBox="0 0 ${w} ${h}">${defsBlock}${body.join("")}</svg>`}var path2dCache=new WeakMap;function ringsToPath2D(path){let cached=path2dCache.get(path);if(cached)return cached;cached=new Path2D;for(const r of path){const p=r.p;if(p.length<2)continue;cached.moveTo(p[0],p[1]);if(r.straight)for(let o=2;o+5<p.length;o+=6)cached.lineTo(p[o+4],p[o+5]);else for(let o=2;o+5<p.length;o+=6)cached.bezierCurveTo(p[o],p[o+1],p[o+2],p[o+3],p[o+4],p[o+5]);if(r.closed)cached.closePath()}path2dCache.set(path,cached);return cached}function canvasPaint(ctx,paint){if(!isGradient(paint))return css(paint);const gradient=paint.type==="linear"?ctx.createLinearGradient(paint.from[0],paint.from[1],paint.to[0],paint.to[1]):paint.type==="radial"?ctx.createRadialGradient(paint.center[0],paint.center[1],0,paint.center[0],paint.center[1],paint.radius):null;if(!gradient)return css(sampleStops(paint.stops,.5));for(const[at,color]of paint.stops)gradient.addColorStop(at,css(color));return gradient}var BLEND={normal:"source-over",screen:"screen",multiply:"multiply",overlay:"overlay"};function paintFrame(ctx,frame,scale=1,images){ctx.setTransform(1,0,0,1,0,0);ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over";ctx.clearRect(0,0,frame.width*scale,frame.height*scale);ctx.setTransform(scale,0,0,scale,0,0);if(frame.background){ctx.fillStyle=frame.background;ctx.fillRect(0,0,frame.width,frame.height)}for(const op of frame.ops){if(op.kind==="image"){const source=images?.(op.image)??browserImageSource(op.image.asset);if(!source)throw new ImageAssetError("Image pixels are unavailable. Await image preparation and provide an ImageLookup outside the browser.");const m=op.matrix;ctx.save();ctx.transform(m[0],m[1],m[2],m[3],m[4],m[5]);ctx.globalAlpha=op.alpha;ctx.globalCompositeOperation="source-over";const crop=op.image.crop;if(crop)ctx.drawImage(source,crop.x,crop.y,crop.width,crop.height,0,0,op.image.width,op.image.height);else ctx.drawImage(source,0,0,op.image.width,op.image.height);ctx.restore();continue}ctx.globalCompositeOperation=BLEND[op.blend];if(op.glow>0){const color=glowOf(op);if(color){const base=Math.max(op.fillAlpha,op.strokeAlpha);const previous=ctx.globalCompositeOperation;if(frame.dark)ctx.globalCompositeOperation="screen";ctx.strokeStyle=css([color[0],color[1],color[2],1]);ctx.lineCap="round";ctx.lineJoin="round";ctx.setLineDash([]);const glowPath=ringsToPath2D(op.strokePath.length?op.strokePath:op.path);for(const pass of glowPasses(op.glow,op.stroke?op.strokeWidth:0)){ctx.globalAlpha=pass.alpha*base;ctx.lineWidth=pass.width;ctx.stroke(glowPath)}ctx.globalCompositeOperation=previous}}if(op.fill){ctx.globalAlpha=op.fillAlpha;ctx.fillStyle=canvasPaint(ctx,op.fill);ctx.fill(ringsToPath2D(op.path))}if(op.stroke&&op.strokePath.length){ctx.globalAlpha=op.strokeAlpha;ctx.strokeStyle=canvasPaint(ctx,op.stroke);ctx.lineWidth=op.strokeWidth;ctx.lineCap=op.cap;ctx.lineJoin=op.join;ctx.setLineDash(op.dash?[...op.dash]:[]);ctx.lineDashOffset=op.dashOffset;ctx.stroke(ringsToPath2D(op.strokePath))}}ctx.globalAlpha=1;ctx.globalCompositeOperation="source-over"}function frameInkBounds(frame){let result=null;for(const op of frame.ops){if(op.kind==="image"&&!imageHasVisiblePixels(op.image.asset,op.image.crop))continue;const b=op.kind==="image"?imageOpBounds(op):pathBounds(op.path);if(!b)continue;const pad2=op.kind==="path"&&op.stroke?op.strokeWidth/2:0;const next={x:b.x-pad2,y:b.y-pad2,width:b.width+pad2*2,height:b.height+pad2*2};if(!result)result=next;else{const x=Math.min(result.x,next.x),y=Math.min(result.y,next.y);result={x,y,width:Math.max(result.x+result.width,next.x+next.width)-x,height:Math.max(result.y+result.height,next.y+next.height)-y}}}return result}function imageOpBounds(op){const{width,height}=op.image;const corners=[[0,0],[width,0],[0,height],[width,height]].map(([x2,y2])=>apply(op.matrix,x2,y2));const xs=corners.map(p=>p[0]),ys=corners.map(p=>p[1]);const x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y}}import{createRequire}from"module";import{cpus}from"os";import{Worker}from"worker_threads";import{fileURLToPath}from"url";import parseCssColor6 from"parse-css-color";var MEMO_KEY_BYTES=8*1024**2;var MEMO_PIXEL_BYTES=64*1024**2;function rasterMemoBytes(width,height){const pixels=width*height*4;return pixels<=MEMO_PIXEL_BYTES?pixels+MEMO_KEY_BYTES:0}var embeddedJobs=new WeakMap;function embeddedResources(frame){if(typeof frame.width!=="number"||typeof frame.height!=="number")return false;if(frame.background!==null&&(typeof frame.background!=="string"||!parseCssColor6(frame.background)))return false;for(const op of frame.ops){if(op.kind==="image"){const{asset,src,width,height}=op.image;if(!isImageAsset(asset)||src!==asset.src||typeof width!=="number"||typeof height!=="number")return false}else{if(!["normal","screen","multiply","overlay"].includes(op.blend))return false;if(!["round","butt","square"].includes(op.cap)||!["round","miter","bevel"].includes(op.join))return false}}return true}var RASTER_WORKER_SOURCE=String.raw`
3
3
  const { parentPort, workerData } = require('node:worker_threads')
4
4
  const { Resvg } = require(workerData.resvgPath)
5
+ const MAX_KEY_BYTES = ${MEMO_KEY_BYTES}
6
+ const MAX_PIXEL_BYTES = ${MEMO_PIXEL_BYTES}
7
+ let memo = null
8
+
9
+ function sameJob(a, b) {
10
+ return a.width === b.width && a.height === b.height && a.bloom === b.bloom
11
+ && a.background.every((channel, i) => channel === b.background[i])
12
+ && a.svgs.length === b.svgs.length && a.svgs.every((svg, i) => svg === b.svgs[i])
13
+ }
5
14
 
6
15
  function downsample(src, w, h, factor) {
7
16
  const dw = Math.max(1, Math.floor(w / factor)), dh = Math.max(1, Math.floor(h / factor))
@@ -104,6 +113,17 @@ function raster(svg, width, height) {
104
113
 
105
114
  parentPort.on('message', (job) => {
106
115
  try {
116
+ const reusable = job.memoize === true && Number.isInteger(job.width) && job.width > 0
117
+ && Number.isInteger(job.height) && job.height > 0 && job.width * job.height * 4 <= MAX_PIXEL_BYTES
118
+ && Array.isArray(job.background) && job.background.length === 3
119
+ && job.svgs.reduce((bytes, svg) => bytes + svg.length * 2 + 64, 256) <= MAX_KEY_BYTES
120
+ if (reusable && memo && sameJob(memo, job)) {
121
+ // The reply is transferred; the retained bytes must never leave this worker.
122
+ const out = new Uint8Array(memo.pixels)
123
+ parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
124
+ return
125
+ }
126
+ memo = null
107
127
  let out
108
128
  if (job.svgs.length === 1) {
109
129
  out = new Uint8Array(raster(job.svgs[0], job.width, job.height))
@@ -121,16 +141,18 @@ parentPort.on('message', (job) => {
121
141
  for (let i = 0; i < sum.length; i++) out[i] = sum[i] / n + 0.5
122
142
  }
123
143
  if (job.bloom > 0) bloom(out, job.width, job.height, job.bloom, job.background)
144
+ if (reusable) memo = { width: job.width, height: job.height, bloom: job.bloom,
145
+ background: job.background, svgs: job.svgs, pixels: new Uint8Array(out) }
124
146
  parentPort.postMessage({ id: job.id, pixels: out }, [out.buffer])
125
147
  } catch (error) {
126
148
  parentPort.postMessage({ id: job.id, error: String(error && error.message || error) })
127
149
  }
128
150
  })
129
- `;function resolveResvg(){const here=typeof __filename!=="undefined"?__filename:fileURLToPath(import.meta.url);return createRequire(here).resolve("@resvg/resvg-js")}var RasterPool=class{workers=[];idle=[];queue=[];pending=new Map;nextId=1;failure=null;constructor(size=defaultPoolSize()){const resvgPath=resolveResvg();for(let i=0;i<size;i++){const worker=new Worker(RASTER_WORKER_SOURCE,{eval:true,workerData:{resvgPath}});worker.on("message",message=>{const entry=this.pending.get(message.id);this.pending.delete(message.id);this.idle.push(worker);this.pump();if(!entry)return;if(message.error||!message.pixels)entry.reject(new Error(`Frame rasterization failed: ${message.error}`));else entry.resolve(message.pixels)});worker.on("error",error=>this.fail(error instanceof Error?error:new Error(String(error))));this.workers.push(worker);this.idle.push(worker)}}get size(){return this.workers.length}fail(error){this.failure=error;for(const entry of this.pending.values())entry.reject(error);this.pending.clear()}pump(){while(this.idle.length>0&&this.queue.length>0){const worker=this.idle.pop();const{job,id}=this.queue.shift();worker.postMessage({id,...job})}}run(job){if(this.failure)return Promise.reject(this.failure);const id=this.nextId++;return new Promise((resolve4,reject)=>{this.pending.set(id,{resolve:resolve4,reject});this.queue.push({job,id});this.pump()})}async close(){this.failure??=new Error("The raster pool was closed.");for(const entry of this.pending.values())entry.reject(this.failure);this.pending.clear();this.queue.length=0;await Promise.all(this.workers.map(worker=>worker.terminate()))}};function defaultPoolSize(){return Math.max(1,Math.min(12,cpus().length-2))}function framesToJob(frames,width,parseBackground,height){const first=frames[0];const scale=width/first.width;return{svgs:frames.map(frame=>frameToSvg(frame)),width,height:height??Math.round(first.height*scale),bloom:first.dark?first.bloom:0,background:parseBackground(first.background)}}var clamp01=t=>t<=0?0:t>=1?1:t;var linear=t=>t;function sigmoid(x){return 1/(1+Math.exp(-x))}function smoothBy(inflection){const low=sigmoid(-inflection/2);const high=sigmoid(inflection/2);return t=>{if(t<=0)return 0;if(t>=1)return 1;return(sigmoid(inflection*(t-.5))-low)/(high-low)}}var smooth2=smoothBy(10);var smoother=t=>{const x=clamp01(t);return x*x*x*(x*(x*6-15)+10)};var easeInQuad=t=>t*t;var easeOutQuad=t=>1-(1-t)*(1-t);var easeInCubic=t=>t*t*t;var easeOutCubic=t=>1-Math.pow(1-t,3);var easeInOutCubic=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;var easeOutQuint=t=>1-Math.pow(1-t,5);var easeInOutQuint=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;var easeOutExpo=t=>t>=1?1:1-Math.pow(2,-10*t);var easeInExpo=t=>t<=0?0:Math.pow(2,10*t-10);var rushInto=t=>2*smooth2(t/2);var rushFrom=t=>2*smooth2(t/2+.5)-1;var slowInto=t=>Math.sqrt(Math.max(0,1-(1-t)*(1-t)));function overshoot(amount2=1.70158){return t=>{const x=t-1;return x*x*((amount2+1)*x+amount2)+1}}function spring(options={}){const bounce2=options.bounce??.28;const frequency=options.frequency??2.2;const decay=-Math.log(Math.max(1e-4,bounce2))*2.4;return t=>{if(t<=0)return 0;if(t>=1)return 1;return 1-Math.exp(-decay*t)*Math.cos(frequency*Math.PI*2*t)*(1-t)}}var bounce=t=>{const n=7.5625,d=2.75;if(t<1/d)return n*t*t;if(t<2/d)return n*(t-=1.5/d)*t+.75;if(t<2.5/d)return n*(t-=2.25/d)*t+.9375;return n*(t-=2.625/d)*t+.984375};var thereAndBack=t=>smooth2(t<.5?2*t:2*(1-t));function thereAndBackWithPause(pause=1/3){const a=(1-pause)/2;return t=>{if(t<a)return smooth2(t/a);if(t<1-a)return 1;return smooth2((1-t)/a)}}function wiggle(cycles=2){return t=>thereAndBack(t)*Math.sin(cycles*Math.PI*2*t)}function notQuiteThere(amount2=.7,inner=smooth2){return t=>amount2*inner(t)}function lingering(hold2=.25,inner=smooth2){return t=>inner(clamp01(t/(1-hold2)))}function runningStart(pull=-.5){return t=>{const u=1-t;return 15*u**4*t**2*pull+20*u**3*t**3*pull+15*u**2*t**4+6*u*t**5+t**6}}function during(from,to2,inner=smooth2){return t=>inner(clamp01((t-from)/(to2-from)))}function cubicBezier(x1,y1,x2,y2){const cx=3*x1,bx=3*(x2-x1)-cx,ax=1-cx-bx;const cy=3*y1,by=3*(y2-y1)-cy,ay=1-cy-by;const sampleX=t=>((ax*t+bx)*t+cx)*t;const sampleY=t=>((ay*t+by)*t+cy)*t;const slope=t=>(3*ax*t+2*bx)*t+cx;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<8;i++){const dx=sampleX(t)-x;const d=slope(t);if(Math.abs(dx)<1e-5||Math.abs(d)<1e-6)break;t-=dx/d}return sampleY(t)}}function growTo(r,target){const count=segmentCount(r);if(count>=target||count===0)return r;const segments=[];for(let i=0;i<count;i++){const o=i*6;const pts=Array.from(r.p.subarray(o,o+8));segments.push({pts,length:chord(pts)})}while(segments.length<target){let longest=0;for(let i=1;i<segments.length;i++)if(segments[i].length>segments[longest].length)longest=i;const[a,b]=bisect(segments[longest].pts);segments.splice(longest,1,{pts:a,length:chord(a)},{pts:b,length:chord(b)})}const out=new Float64Array(2+target*6);out[0]=r.p[0];out[1]=r.p[1];for(let i=0;i<target;i++){const pts=segments[i].pts;for(let k=0;k<6;k++)out[2+i*6+k]=pts[2+k]}return{p:out,closed:r.closed}}function chord(pts){return Math.hypot(pts[2]-pts[0],pts[3]-pts[1])+Math.hypot(pts[4]-pts[2],pts[5]-pts[3])+Math.hypot(pts[6]-pts[4],pts[7]-pts[5])}function bisect(p){const ax=(p[0]+p[2])/2,ay=(p[1]+p[3])/2;const bx=(p[2]+p[4])/2,by=(p[3]+p[5])/2;const cx=(p[4]+p[6])/2,cy=(p[5]+p[7])/2;const dx=(ax+bx)/2,dy=(ay+by)/2;const ex=(bx+cx)/2,ey=(by+cy)/2;const fx=(dx+ex)/2,fy=(dy+ey)/2;return[[p[0],p[1],ax,ay,dx,dy,fx,fy],[fx,fy,ex,ey,cx,cy,p[6],p[7]]]}function bestRotation(a,b){const count=segmentCount(b);if(!a.closed||!b.closed||count<2)return b;const[ax,ay]=ringCenter(a),[bx,by]=ringCenter(b);const stride=Math.max(1,Math.floor(count/48));let best=0,bestCost=Infinity;for(let shift2=0;shift2<count;shift2+=stride){let cost=0;for(let i=0;i<count;i+=stride){const j=(i+shift2)%count;const dx=a.p[i*6]-ax-(b.p[j*6]-bx);const dy=a.p[i*6+1]-ay-(b.p[j*6+1]-by);cost+=dx*dx+dy*dy}if(cost<bestCost){bestCost=cost;best=shift2}}if(best===0)return b;const out=new Float64Array(b.p.length);out[0]=b.p[best*6];out[1]=b.p[best*6+1];for(let i=0;i<count;i++){const j=(i+best)%count;for(let k=0;k<6;k++)out[2+i*6+k]=b.p[2+j*6+k]}return{p:out,closed:b.closed}}function pointRing(x,y,count,closed){const out=new Float64Array(2+count*6);for(let i=0;i<out.length;i+=2){out[i]=x;out[i+1]=y}return{p:out,closed}}function pairRings(from,to2){const rank=path=>[...path].sort((a2,b2)=>Math.abs(signedArea(b2))+ringLength(b2)*.01-(Math.abs(signedArea(a2))+ringLength(a2)*.01));const a=rank(from),b=rank(to2);const pairs=[];const free=b.slice();for(const ringA of a){if(free.length===0){const[x,y]=ringCenter(ringA);pairs.push([ringA,pointRing(x,y,segmentCount(ringA),ringA.closed)]);continue}const[ax,ay]=ringCenter(ringA);let bestIndex=0,bestCost=Infinity;for(let i=0;i<Math.min(free.length,3);i++){const[bx,by]=ringCenter(free[i]);const cost=Math.hypot(ax-bx,ay-by)+i*40;if(cost<bestCost){bestCost=cost;bestIndex=i}}pairs.push([ringA,free[bestIndex]]);free.splice(bestIndex,1)}for(const ringB of free){const[x,y]=ringCenter(ringB);pairs.push([pointRing(x,y,segmentCount(ringB),ringB.closed),ringB])}return pairs}function alignPaths(from,to2,minSegments=12){const pairs=pairRings(from,to2);const a=[],b=[],closed=[];for(const[ra,rb]of pairs){const target=Math.max(segmentCount(ra),segmentCount(rb),ra.closed&&rb.closed?minSegments:1);let x=growTo(ra,target);let y=growTo(rb,target);if(x.closed&&y.closed){if(Math.sign(signedArea(x))!==Math.sign(signedArea(y))&&signedArea(x)!==0&&signedArea(y)!==0)y=reverseRing(y);y=bestRotation(x,y)}else if(!x.closed&&!y.closed){const n=x.p.length;const straight=Math.hypot(x.p[0]-y.p[0],x.p[1]-y.p[1])+Math.hypot(x.p[n-2]-y.p[n-2],x.p[n-1]-y.p[n-1]);const flipped=Math.hypot(x.p[0]-y.p[n-2],x.p[1]-y.p[n-1])+Math.hypot(x.p[n-2]-y.p[0],x.p[n-1]-y.p[1]);if(flipped<straight)y=reverseRing(y)}a.push(x.p);b.push(y.p);closed.push(x.closed&&y.closed)}return{from:a,to:b,closed}}function pathMixer(from,to2){if(from===to2)return()=>to2;if(pathLength(from)===0&&from.length===0)return alpha3=>alpha3>=1?to2:from;const aligned=alignPaths(from,to2);return alpha3=>{if(alpha3<=0)return from;if(alpha3>=1)return to2;const rings=new Array(aligned.from.length);for(let r=0;r<rings.length;r++){const a=aligned.from[r],b=aligned.to[r];const out=new Float64Array(a.length);for(let i=0;i<a.length;i++)out[i]=a[i]+(b[i]-a[i])*alpha3;rings[r]={p:out,closed:aligned.closed[r]}}return rings}}function matchSequence(a,b){const n=a.length,m=b.length;const table=Array.from({length:n+1},()=>new Uint16Array(m+1));for(let i2=n-1;i2>=0;i2--){for(let j2=m-1;j2>=0;j2--){table[i2][j2]=a[i2]===b[j2]?table[i2+1][j2+1]+1:Math.max(table[i2+1][j2],table[i2][j2+1])}}const pairs=[];let i=0,j=0;while(i<n&&j<m){if(a[i]===b[j]){pairs.push([i++,j++])}else if(table[i+1][j]>=table[i][j+1]){i++}else{j++}}return pairs}var DEFAULT_PROPS={x:0,y:0,rotation:0,sx:1,sy:1,px:0,py:0,opacity:1,visible:true,z:0,path:null,fill:null,fillOpacity:1,stroke:null,strokeOpacity:1,strokeWidth:3,cap:"round",join:"round",dash:null,dashOffset:0,trimFrom:0,trimTo:1,trimEach:false,glow:0,glowColor:null,blend:"normal",fixed:false,image:null};var NUMERIC=new Set(["x","y","rotation","sx","sy","px","py","opacity","z","fillOpacity","strokeOpacity","strokeWidth","dashOffset","trimFrom","trimTo","glow"]);function mixer(prop,from,to2){if(NUMERIC.has(prop)){const a=from,b=to2;return(alpha3=>a+(b-a)*alpha3)}if(prop==="fill"||prop==="stroke"){const a=from,b=to2;if(a&&b)return(alpha3=>mixPaint(a,b,alpha3));return null}if(prop==="glowColor"){const a=from,b=to2;if(a&&b)return(alpha3=>mixColor(a,b,alpha3));return null}if(prop==="path"){const a=from,b=to2;if(a&&b)return pathMixer(a,b);return null}return null}var nextId=1;var Node=class _Node{id=nextId++;parent=null;children=[];data={};label="";base=Object.create(DEFAULT_PROPS);tracks=null;overlay=null;overlayFrame=-1;mounted=false;draw=null;rawOps=null;constructor(path){if(path)this.base.path=path}get(prop){const overlay=this.overlay;if(overlay!==null&&overlay.has(prop)&&(this.overlayFrame===clock.frame||clock.capture!==null)){return overlay.get(prop)}const track=this.tracks?.get(prop);if(track)return track.sample(clock.now);return this.base[prop]}set(prop,value){if(clock.capture){this.overlay??=new Map;this.overlay.set(prop,value);clock.capture.add(this);return this}if(!this.mounted){this.base[prop]=value;return this}if(clock.mode==="render"){this.overlay??=new Map;if(this.overlayFrame!==clock.frame){this.overlay.clear();this.overlayFrame=clock.frame}this.overlay.set(prop,value);return this}this.track(prop).step(clock.now,value);return this}track(prop){this.tracks??=new Map;let track=this.tracks.get(prop);if(!track){track=new Track(this.base[prop]);this.tracks.set(prop,track)}return track}tween(prop,to2,t0,t1,ease){const previous=clock.now;clock.now=t0;const from=this.get(prop);clock.now=previous;const at=t1>t0?mixer(prop,from,to2):null;const key={t0,t1,ease,to:to2,at};this.track(prop).add(key)}add(...nodes){for(const child of nodes){if(child.parent===this)continue;child.parent?.drop(child);child.parent=this;this.children.push(child);if(this.mounted)mountTree(child,clock.now)}return this}drop(child){const index=this.children.indexOf(child);if(index>=0)this.children.splice(index,1);child.parent=null;return this}all(){const out=[];const visit=node=>{out.push(node);for(const child of node.children)visit(child)};visit(this);return out}leaves(){return this.all().filter(node=>node.get("path")!==null||node.draw!==null||node.get("image")!==null)}clone(){const copy=Object.create(Object.getPrototypeOf(this));Object.assign(copy,this);copy.id=nextId++;copy.parent=null;copy.mounted=false;copy.tracks=null;copy.overlay=null;copy.overlayFrame=-1;copy.data={...this.data};copy.base=Object.create(DEFAULT_PROPS);for(const key of Object.keys(DEFAULT_PROPS)){;copy.base[key]=this.get(key)}copy.children=this.children.map(child=>{const next=child.clone();next.parent=copy;return next});return copy}localMatrix(){return compose(this.get("x"),this.get("y"),this.get("rotation"),this.get("sx"),this.get("sy"),this.get("px"),this.get("py"))}worldMatrix(){let m=this.localMatrix();for(let node=this.parent;node;node=node.parent)m=mul(node.localMatrix(),m);return m}toWorld(x,y){return apply(this.worldMatrix(),x,y)}bounds(){return this.boundsFrom(this.parent?this.parent.worldMatrix():IDENTITY)??{x:0,y:0,width:0,height:0}}boundsFrom(parent){const m=mul(parent,this.localMatrix());let result=null;const path=this.get("path");if(path)result=pathBounds(transformPath(path,m));const image2=this.get("image");if(image2)result=unionBounds(result,boundsOfRect(m,image2.width,image2.height));if(this.draw){const built=this.draw(clock.now);const list3=built===null?[]:Array.isArray(built)?built:[built];for(const child of list3)result=unionBounds(result,child.boundsFrom(m))}for(const child of this.children){if(child.get("visible"))result=unionBounds(result,child.boundsFrom(m))}return result}get center(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height/2]}get top(){const b=this.bounds();return[b.x+b.width/2,b.y]}get bottom(){const b=this.bounds();return[b.x+b.width/2,b.y+b.height]}get left(){const b=this.bounds();return[b.x,b.y+b.height/2]}get right(){const b=this.bounds();return[b.x+b.width,b.y+b.height/2]}get width(){return this.bounds().width}get height(){return this.bounds().height}at(x,y){const[px,py]=typeof x==="number"?[x,y??0]:x;this.set("x",px);this.set("y",py);return this}shift(dx,dy){const[ox,oy]=typeof dx==="number"?[dx,dy??0]:dx;this.set("x",this.get("x")+ox);this.set("y",this.get("y")+oy);return this}moveTo(target){const destination=target instanceof _Node?target.center:target;const[cx,cy]=this.center;const inverse=this.parent?invert(this.parent.worldMatrix()):IDENTITY;const[lx0,ly0]=apply(inverse,cx,cy);const[lx1,ly1]=apply(inverse,destination[0],destination[1]);return this.shift(lx1-lx0,ly1-ly0)}pivotAt(point){const parent=this.parent?this.parent.worldMatrix():IDENTITY;const before=mul(parent,this.localMatrix());const[lx,ly]=apply(invert(before),point[0],point[1]);const[nx,ny]=apply(invert(parent),point[0],point[1]);this.set("px",lx);this.set("py",ly);this.set("x",nx);this.set("y",ny);return this}scale(factor,about){const[fx,fy]=typeof factor==="number"?[factor,factor]:factor;this.pivotAt(about??this.center);this.set("sx",this.get("sx")*fx);this.set("sy",this.get("sy")*fy);return this}rotate(radians,about){this.pivotAt(about??this.center);this.set("rotation",this.get("rotation")+radians);return this}fitTo(size){const b=this.bounds();const scales=[];if(size.width!==void 0&&b.width>0)scales.push(size.width/b.width);if(size.height!==void 0&&b.height>0)scales.push(size.height/b.height);return scales.length?this.scale(Math.min(...scales)):this}nextTo(target,side="right",gap=28){const[dx,dy]=direction(side);const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const own=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;const anchorX=cx+dx*(b.width/2+gap+own.width/2);const anchorY=cy+dy*(b.height/2+gap+own.height/2);return this.moveTo([anchorX,anchorY])}alignTo(target,edge){const own=this.bounds();const b=target instanceof _Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};if(edge==="left")return this.shift(b.x-own.x,0);if(edge==="right")return this.shift(b.x+b.width-own.x-own.width,0);if(edge==="top")return this.shift(0,b.y-own.y);return this.shift(0,b.y+b.height-own.y-own.height)}arrange(side="right",gap=24){const[dx,dy]=direction(side);const center2=this.center;let previous=null;for(const child of this.children){if(previous){const b=previous.bounds(),own=child.bounds();const px=b.x+b.width/2+dx*(b.width/2+gap+own.width/2);const py=b.y+b.height/2+dy*(b.height/2+gap+own.height/2);child.moveTo([dx===0?b.x+b.width/2:px,dy===0?b.y+b.height/2:py])}previous=child}return this.moveTo(center2)}fill(color,opacity){this.set("fill",color===null?null:toPaint(color));if(opacity!==void 0)this.set("fillOpacity",opacity);return this}stroke(color,width,opacity){this.set("stroke",color===null?null:toPaint(color));if(width!==void 0)this.set("strokeWidth",width);if(opacity!==void 0)this.set("strokeOpacity",opacity);return this}color(color){const paint=toPaint(color);for(const node of this.all()){if(node.get("stroke"))node.set("stroke",paint);if(node.get("fill"))node.set("fill",paint);if(node.get("glowColor")&&!isGradient(paint))node.set("glowColor",paint)}return this}opacity(value){return this.set("opacity",value)}glow(radius,color){this.set("glow",radius);if(color!==void 0){const paint=toPaint(color);this.set("glowColor",isGradient(paint)?null:paint)}return this}dash(pattern,offset=0){this.set("dash",pattern);return this.set("dashOffset",offset)}zIndex(value){return this.set("z",value)}pin(){return this.set("fixed",true)}hide(){return this.set("visible",false)}show(){return this.set("visible",true)}named(label){this.label=label;return this}};function boundsOfRect(m,width,height){const corners=[apply(m,0,0),apply(m,width,0),apply(m,width,height),apply(m,0,height)];const xs=corners.map(c=>c[0]),ys=corners.map(c=>c[1]);const x=Math.min(...xs),y=Math.min(...ys);return{x,y,width:Math.max(...xs)-x,height:Math.max(...ys)-y}}function direction(side){if(typeof side!=="string")return side;if(side==="left")return[-1,0];if(side==="right")return[1,0];if(side==="top"||side==="up")return[0,-1];return[0,1]}function mountTree(node,time){const wasVisible=node.base.visible;for(const entry of node.all())entry.mounted=true;if(time>0||!wasVisible){const track=node.track("visible");track.initial=false;if(wasVisible)track.step(time,true)}}function group(...children){return new Node().add(...children)}function dynamic(build){const node=new Node;node.draw=build;return node}function list(target){return Array.isArray(target)?[...target]:[target]}function run(anim,t0,t1,parent){clock.now=t0;anim.schedule({t0,t1,ease:anim.ease??parent.ease,stage:parent.stage})}function par(...anims){const duration=Math.max(0,...anims.map(a=>a.duration));return{label:"par",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;for(const anim of anims)run(anim,ctx.t0,ctx.t0+anim.duration*k,ctx)}}}function seq(...anims){const duration=anims.reduce((sum,a)=>sum+a.duration,0);return{label:"seq",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;let t=ctx.t0;for(const anim of anims){const next=t+anim.duration*k;run(anim,t,next,ctx);t=next}}}}function lagged(anims,options={}){const lag=options.lag??.15;const longest=Math.max(0,...anims.map(a=>a.duration));const natural=anims.length===0?0:longest*(1+(anims.length-1)*lag);return{label:"lagged",duration:options.duration??natural,schedule(ctx){const total=ctx.t1-ctx.t0;const each=anims.length===0?0:total/(1+(anims.length-1)*lag);anims.forEach((anim,i)=>{const start=ctx.t0+i*lag*each;run(anim,start,start+each,ctx)})}}}function delay(anim,seconds){return{label:anim.label,duration:anim.duration+seconds,ease:anim.ease,schedule(ctx){const k=anim.duration+seconds>0?(ctx.t1-ctx.t0)/(anim.duration+seconds):1;run(anim,ctx.t0+seconds*k,ctx.t1,ctx)}}}function retime(anim,options){return{...anim,duration:options.duration??anim.duration,ease:options.ease??anim.ease}}function call(fn){return{label:"call",duration:0,schedule:()=>fn()}}function ensureVisible(node,t,stage){if(!node.mounted){let top=node;while(top.parent&&top.parent!==stage.root)top=top.parent;stage.mountAt(top,t)}for(let n=node;n&&n!==stage.root;n=n.parent){const previous=clock.now;clock.now=t;const visible=n.get("visible");clock.now=previous;if(!visible)n.track("visible").step(t,true)}}function hideAt(node,t){node.track("visible").step(t,false)}function holdUntil(node,t0,start){if(start<=t0)return;node.track("visible").step(t0,false);node.track("visible").step(start,true)}var stepAt=(node,prop,value,t)=>{node.track(prop).step(t,value)};function valueAt(node,prop,t){const previous=clock.now;clock.now=t;const value=node.get(prop);clock.now=previous;return value}function solid2(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function drawable(target){return list(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function drawLeaf(leaf,t0,t1,ease,outline){const d=t1-t0;const fill=leaf.get("fill"),stroke=leaf.get("stroke");const fillTarget=leaf.get("fillOpacity");const strokeTarget=leaf.get("strokeOpacity");if(fill&&!stroke){const width=valueAt(leaf,"strokeWidth",t0);stepAt(leaf,"stroke",solid2(fill),t0);stepAt(leaf,"strokeWidth",outline,t0);stepAt(leaf,"strokeOpacity",1,t0);stepAt(leaf,"trimTo",0,t0);stepAt(leaf,"fillOpacity",0,t0);leaf.tween("trimTo",1,t0,t0+d*.72,ease);leaf.tween("fillOpacity",fillTarget,t0+d*.42,t1,ease);leaf.tween("strokeOpacity",0,t0+d*.62,t1,ease);stepAt(leaf,"stroke",null,t1);stepAt(leaf,"strokeWidth",width,t1);stepAt(leaf,"strokeOpacity",strokeTarget,t1);return}stepAt(leaf,"trimTo",0,t0);leaf.tween("trimTo",1,t0,fill?t0+d*.8:t1,ease);if(fill){stepAt(leaf,"fillOpacity",0,t0);leaf.tween("fillOpacity",fillTarget,t0+d*.5,t1,ease)}}function drawAnim(label,target,options,defaults){const nodes=list(target);const count=drawable(nodes).length;const lag=options.lag??defaults.lag;const natural=options.duration??(count<=1?defaults.duration:Math.min(defaults.duration*2.4,defaults.duration+count*.035));return{label,duration:natural,ease:options.ease,schedule(ctx){for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const leaves=drawable(nodes);if(leaves.length===0)return;const total=ctx.t1-ctx.t0;const each=total/(1+(leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;holdUntil(leaf,ctx.t0,start);drawLeaf(leaf,start,start+each,ctx.ease,defaults.outline)});clock.now=ctx.t0}}}function draw(target,options={}){return drawAnim("draw",target,options,{lag:.04,duration:1.3,outline:2})}function write(target,options={}){return drawAnim("write",target,options,{lag:.22,duration:1.1,outline:1.3})}function erase(target,options={}){const nodes=list(target);return{label:"erase",duration:options.duration??.8,ease:options.ease,schedule(ctx){const leaves=drawable(nodes);const lag=options.lag??.02;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;const fill=leaf.get("fill");if(leaf.get("stroke"))leaf.tween("trimFrom",1,start,start+each,ctx.ease);if(fill)leaf.tween("fillOpacity",0,start,start+each*.7,ctx.ease)});for(const node of nodes)hideAt(node,ctx.t1)}}}function fadeIn(target,options={}){const nodes=list(target);return{label:"fadeIn",duration:options.duration??.8,ease:options.ease,schedule(ctx){const items=options.lag!==void 0&&nodes.length===1&&nodes[0].children.length>0?nodes[0].children:nodes;for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,items.length-1)*lag);items.forEach((node,i)=>{const start=ctx.t0+i*lag*each,end=start+each;clock.now=start;holdUntil(node,ctx.t0,start);const opacity=node.get("opacity");stepAt(node,"opacity",0,start);node.tween("opacity",opacity,start,end,ctx.ease);if(options.shift){const x=node.get("x"),y=node.get("y");stepAt(node,"x",x+options.shift[0],start);stepAt(node,"y",y+options.shift[1],start);node.tween("x",x,start,end,ctx.ease);node.tween("y",y,start,end,ctx.ease)}if(options.scale!==void 0)scaleFrom(node,options.scale,start,end,ctx.ease)});clock.now=ctx.t0}}}function scaleFrom(node,factor,t0,t1,ease,about){const previous=clock.now;clock.now=t0;node.pivotAt(about??node.center);const sx=node.get("sx"),sy=node.get("sy");stepAt(node,"sx",sx*factor,t0);stepAt(node,"sy",sy*factor,t0);node.tween("sx",sx,t0,t1,ease);node.tween("sy",sy,t0,t1,ease);clock.now=previous}function fadeOut(target,options={}){const nodes=list(target);return{label:"fadeOut",duration:options.duration??.6,ease:options.ease,schedule(ctx){for(const node of nodes){const opacity=node.get("opacity");node.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);if(options.shift){node.tween("x",node.get("x")+options.shift[0],ctx.t0,ctx.t1,ctx.ease);node.tween("y",node.get("y")+options.shift[1],ctx.t0,ctx.t1,ctx.ease)}if(options.scale!==void 0){node.pivotAt(node.center);node.tween("sx",node.get("sx")*options.scale,ctx.t0,ctx.t1,ctx.ease);node.tween("sy",node.get("sy")*options.scale,ctx.t0,ctx.t1,ctx.ease)}hideAt(node,ctx.t1);stepAt(node,"opacity",opacity,ctx.t1)}}}}function grow(target,options={}){const nodes=list(target);return{label:"grow",duration:options.duration??.9,ease:options.ease,schedule(ctx){for(const node of nodes){ensureVisible(node,ctx.t0,ctx.stage);scaleFrom(node,.001,ctx.t0,ctx.t1,ctx.ease,options.from)}}}}function appear(target){const nodes=list(target);return{label:"appear",duration:0,schedule:ctx=>{for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage)}}}function vanish(target){const nodes=list(target);return{label:"vanish",duration:0,schedule:ctx=>{for(const node of nodes)hideAt(node,ctx.t0)}}}function to(node,change,options={}){return{label:"to",duration:options.duration??1,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const touched=new Set;clock.capture=touched;try{change(node)}finally{clock.capture=null}for(const entry of touched){const target=entry;const values=new Map(target.overlay);target.overlay.clear();applyChanges(target,values,ctx,options.restore===true)}}}}function applyChanges(node,values,ctx,restore){const{t0,t1,ease}=ctx;const props=values;const restoreValues=new Map;const px=props.get("px"),py=props.get("py");if(px!==void 0||py!==void 0){const nextPx=px??node.get("px"),nextPy=py??node.get("py");const m=compose(node.get("x"),node.get("y"),node.get("rotation"),node.get("sx"),node.get("sy"),node.get("px"),node.get("py"));const[startX,startY]=apply(m,nextPx,nextPy);stepAt(node,"px",nextPx,t0);stepAt(node,"py",nextPy,t0);stepAt(node,"x",startX,t0);stepAt(node,"y",startY,t0);props.delete("px");props.delete("py")}clock.now=t0;for(const[prop,value]of props){const from=node.get(prop);if(from===value)continue;if(restore)restoreValues.set(prop,from);node.tween(prop,value,t0,t1,ease)}for(const[prop,value]of restoreValues)stepAt(node,prop,value,t1)}function moveTo(node,target,options={}){return{...to(node,n=>n.moveTo(target),options),label:"moveTo"}}function shift(node,dx,dy,options={}){return{...to(node,n=>n.shift(dx,dy),options),label:"shift"}}function scaleBy(node,factor,options={}){return{...to(node,n=>n.scale(factor,options.about),options),label:"scale"}}function rotate(node,radians,options={}){return{...to(node,n=>n.rotate(radians,options.about),options),label:"rotate"}}function recolor(node,color,options={}){return{...to(node,n=>n.color(color),options),label:"recolor"}}function fade(node,opacity,options={}){return{...to(node,n=>n.opacity(opacity),{duration:.6,...options}),label:"fade"}}function along2(node,track,options={}){return{label:"along",duration:options.duration??2,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const path=track instanceof Node?transformPath(track.get("path")??[],track.worldMatrix()):track;const inverse=node.parent?invertSafe(node.parent.worldMatrix()):null;const position2=alpha3=>{const[x,y]=pointAt(path,alpha3);return inverse?apply(inverse,x,y):[x,y]};const[endX,endY]=position2(1);node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endX,at:a=>position2(a)[0]});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endY,at:a=>position2(a)[1]});if(options.orient){const angle=alpha3=>{const[dx,dy]=tangentAt(path,alpha3);return Math.atan2(dy,dx)};node.track("rotation").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:angle(1),at:angle})}}}}function invertSafe(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return[1,0,0,1,0,0];const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function warp(target,f,options={}){const nodes=list(target);return{label:"warp",duration:options.duration??2,ease:options.ease,schedule(ctx){for(const leaf of drawable(nodes)){ensureVisible(leaf,ctx.t0,ctx.stage);const path=leaf.get("path");const world=leaf.worldMatrix();const inverse=invertSafe(world);const start=path.map(r=>subdivideEach(r,options.subdivisions??6));const end=warpPath(start,(x,y)=>{const[wx,wy]=apply(world,x,y);const[mx,my]=f(wx,wy);return apply(inverse,mx,my)},1);leaf.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:end,at:alpha3=>start.map((r,i)=>{const a=r.p,b=end[i].p;const out=new Float64Array(a.length);for(let k=0;k<a.length;k++)out[k]=a[k]+(b[k]-a[k])*alpha3;return{p:out,closed:r.closed}})})}}}}function applyMatrix(target,matrix2,options={}){const[ox,oy]=options.origin??[0,0];const flip=options.yUp===false?1:-1;const[[a,b],[c,d]]=matrix2;return{...warp(target,(x,y)=>{const ux=x-ox,uy=(y-oy)*flip;const vx=a*ux+b*uy,vy=c*ux+d*uy;return[ox+vx,oy+vy*flip]},{subdivisions:1,...options}),label:"applyMatrix"}}function chainOpacity(node){let value=1;for(let n=node;n;n=n.parent)value*=n.get("opacity");return value}function bake(leaf){const m=leaf.worldMatrix();const opacity=chainOpacity(leaf);let z=0;let fixed=false;for(let n=leaf;n;n=n.parent){z+=n.get("z");fixed||=n.get("fixed")}return{path:transformPath(leaf.get("path")??[],m),fill:leaf.get("fill"),fillOpacity:leaf.get("fill")?leaf.get("fillOpacity")*opacity:0,stroke:leaf.get("stroke"),strokeOpacity:leaf.get("stroke")?leaf.get("strokeOpacity")*opacity:0,strokeWidth:leaf.get("strokeWidth")*matScale(m),glow:leaf.get("glow"),glowColor:leaf.get("glowColor"),cap:leaf.get("cap"),dash:leaf.get("dash"),z,fixed,key:leaf.data["key"]}}function ghost(stage,from,to2,ctx){const node=new Node;node.base.visible=false;node.base.path=from.path;node.base.cap=from.cap;node.base.z=from.z;node.base.fixed=from.fixed;node.base.fill=from.fill??to2.fill;node.base.stroke=from.stroke??to2.stroke;node.base.fillOpacity=from.fillOpacity;node.base.strokeOpacity=from.strokeOpacity;node.base.strokeWidth=from.strokeWidth||to2.strokeWidth;node.base.glow=from.glow;node.base.glowColor=from.glowColor??to2.glowColor;stage.root.add(node);node.track("visible").initial=false;node.track("visible").keys.length=0;stepAt(node,"visible",true,ctx.appear??ctx.t0);node.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:to2.path,at:pathMixer(from.path,to2.path)});if(from.fill&&to2.fill)node.tween("fill",to2.fill,ctx.t0,ctx.t1,ctx.ease);if(from.stroke&&to2.stroke)node.tween("stroke",to2.stroke,ctx.t0,ctx.t1,ctx.ease);node.tween("fillOpacity",to2.fillOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeOpacity",to2.strokeOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeWidth",to2.strokeWidth||from.strokeWidth,ctx.t0,ctx.t1,ctx.ease);if(from.glow!==to2.glow)node.tween("glow",to2.glow,ctx.t0,ctx.t1,ctx.ease);stepAt(node,"visible",false,ctx.hide??ctx.t1);return node}function pairCounts(from,to2){const count=Math.max(from.length,to2.length);const pairs=[];for(let i=0;i<count;i++){pairs.push([from[Math.min(from.length-1,Math.floor(i*from.length/count))],to2[Math.min(to2.length-1,Math.floor(i*to2.length/count))]])}return pairs}function morph(from,to2,options={}){const a=list(from),b=list(to2);return{label:"morph",duration:options.duration??1.2,ease:options.ease,schedule(ctx){prepareTargets(b,ctx);const fromLeaves=drawable(a).map(bake);const toLeaves=drawable(b).map(bake);if(fromLeaves.length===0||toLeaves.length===0){for(const node of a)hideAt(node,ctx.t0);for(const node of b)ensureVisible(node,ctx.t0,ctx.stage);return}const pairs=pairCounts(fromLeaves,toLeaves);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,pairs.length-1)*lag);pairs.forEach(([x,y],i)=>{const start=ctx.t0+i*lag*each;ghost(ctx.stage,x,y,{t0:start,t1:start+each,ease:ctx.ease,appear:ctx.t0,hide:ctx.t1})});finishMorph(a,b,ctx)}}}function prepareTargets(targets,ctx){clock.now=ctx.t0;for(const node of targets){ctx.stage.mountAt(node,ctx.t0);hideAt(node,ctx.t0)}}function finishMorph(a,b,ctx){for(const node of a)hideAt(node,ctx.t0);for(const node of b)node.track("visible").step(ctx.t1,true);clock.now=ctx.t0}function morphMatching(from,to2,options={}){return{label:"morphMatching",duration:options.duration??1.4,ease:options.ease,schedule(ctx){prepareTargets([to2],ctx);const keyOf=options.key??(leaf=>leaf.data["key"]);const fromLeaves=drawable(from),toLeaves=drawable(to2);const fromBaked=fromLeaves.map(bake),toBaked=toLeaves.map(bake);const pairs=matchSequence(fromLeaves.map(keyOf),toLeaves.map(keyOf));const usedFrom=new Set(pairs.map(([i])=>i)),usedTo=new Set(pairs.map(([,j])=>j));for(const[i,j]of pairs)ghost(ctx.stage,fromBaked[i],toBaked[j],ctx);const span=ctx.t1-ctx.t0;const offset=options.fadeShift??[0,0];const shifted=(bakedPath,dx,dy)=>transformPath(bakedPath,[1,0,0,1,dx,dy]);fromBaked.forEach((baked,i)=>{if(usedFrom.has(i))return;ghost(ctx.stage,baked,{...baked,path:shifted(baked.path,offset[0],offset[1]),fillOpacity:0,strokeOpacity:0},{t0:ctx.t0,t1:ctx.t0+span*.55,ease:ctx.ease})});toBaked.forEach((baked,j)=>{if(usedTo.has(j))return;ghost(ctx.stage,{...baked,path:shifted(baked.path,-offset[0],-offset[1]),fillOpacity:0,strokeOpacity:0},baked,{t0:ctx.t0+span*.35,t1:ctx.t1,ease:ctx.ease})});finishMorph([from],[to2],ctx)}}}function indicate(target,options={}){const nodes=list(target);const anims=nodes.map(node=>retime(to(node,n=>{n.scale(options.scale??1.14);n.color(options.color??"yellow")},{restore:true}),{ease:options.ease??thereAndBack}));return{...par(...anims),label:"indicate",duration:options.duration??.9}}function shake(node,options={}){return{label:"shake",duration:options.duration??.8,ease:wiggle(options.cycles??3),schedule(ctx){clock.now=ctx.t0;const[cx,cy]=node.center;node.pivotAt([cx,cy]);const rotation=node.get("rotation");const angle=options.angle??.08;const track=node.track("rotation");track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:rotation,at:alpha3=>rotation+angle*alpha3})}}}function circumscribe(target,options={}){return{label:"circumscribe",duration:options.duration??1.3,ease:options.ease??linear,schedule(ctx){const b=target.bounds();const pad2=options.pad??14;const outline=new Node(rectPath(b.x-pad2,b.y-pad2,b.width+pad2*2,b.height+pad2*2,options.radius??12)).stroke(options.color??"yellow",options.width??3).glow(8);ctx.stage.add(outline);const t0=ctx.t0,t1=ctx.t1,mid=t0+(t1-t0)*.55;stepAt(outline,"trimTo",0,t0);outline.tween("trimTo",1,t0,mid,smooth2);outline.tween("trimFrom",1,mid-(t1-t0)*.08,t1,smooth2);hideAt(outline,t1)}}}function flash(point,options={}){return{label:"flash",duration:options.duration??.7,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const radius=options.radius??54;const rays=options.rays??12;for(let i=0;i<rays;i++){const angle=i/rays*Math.PI*2;const cos=Math.cos(angle),sin=Math.sin(angle);const ray=new Node(linePath([center2[0]+cos*radius*.35,center2[1]+sin*radius*.35],[center2[0]+cos*radius,center2[1]+sin*radius])).stroke(options.color??"yellow",2.5).glow(5);ctx.stage.add(ray);stepAt(ray,"trimTo",0,ctx.t0);ray.tween("trimTo",1,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.6,ctx.ease);ray.tween("trimFrom",1,ctx.t0+(ctx.t1-ctx.t0)*.25,ctx.t1,ctx.ease);hideAt(ray,ctx.t1)}}}}function ripple(point,options={}){return{label:"ripple",duration:options.duration??1,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const ring2=new Node(circlePath(0,0,options.radius??90)).stroke(options.color??"blue",options.width??3).at(center2);ctx.stage.add(ring2);stepAt(ring2,"sx",.05,ctx.t0);stepAt(ring2,"sy",.05,ctx.t0);ring2.tween("sx",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("sy",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("strokeOpacity",0,ctx.t0+(ctx.t1-ctx.t0)*.2,ctx.t1,ctx.ease);hideAt(ring2,ctx.t1)}}}function pulse(line2,options={}){return{label:"pulse",duration:options.duration??1.1,ease:options.ease??smooth2,schedule(ctx){const path=line2.get("path");if(!path)return;const lit=new Node(transformPath(path,line2.worldMatrix())).stroke(options.color??"yellow",options.width??line2.get("strokeWidth")+1.5).glow(options.glow??10);ctx.stage.add(lit);const length=options.length??.18;stepAt(lit,"trimFrom",0,ctx.t0);stepAt(lit,"trimTo",0,ctx.t0);lit.track("trimTo").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.min(1,a*(1+length))});lit.track("trimFrom").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.max(0,a*(1+length)-length)});hideAt(lit,ctx.t1)}}}var Value=class{track;constructor(initial){this.track=new Track(initial)}get value(){return this.track.sample(clock.now)}set(value){this.track.step(clock.now,value);return this}to(value,options={}){const track=this.track;return{label:"value",duration:options.duration??1,ease:options.ease,schedule(ctx){const from=track.sample(ctx.t0);track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:value,at:a=>from+(value-from)*a})}}}};var ASPECTS={"16:9":[1920,1080],"9:16":[1080,1920],"1:1":[1080,1080],"4:3":[1440,1080],"21:9":[2520,1080]};var Stage=class{root=new Node;camera=new Node;width;height;fps;look;chapters=[];clips=[];captions=[];updaters=[];time=0;ending=0;constructor(options){const[w,h]=ASPECTS[options.aspect??"16:9"];this.width=options.width??w;this.height=options.height??h;this.fps=options.fps??60;this.look=resolveLook(options.look);this.root.mounted=true;this.camera.mounted=true}get right(){return this.width/2}get left(){return-this.width/2}get top(){return-this.height/2}get bottom(){return this.height/2}add(first,...rest){clock.now=this.time;for(const node of[first,...rest]){if(!node.mounted){node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,this.time)}else if(!node.get("visible")){node.track("visible").step(this.time,true)}}return first}mountAt(node,time){if(node.mounted)return;node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,time)}remove(...nodes){for(const node of nodes)node.track("visible").step(this.time,false)}play(...items){const anims=items.filter(item=>"schedule"in item);const options=items.find(item=>!("schedule"in item))??{};if(anims.length===0)return this;const natural=Math.max(...anims.map(anim=>anim.duration));const duration=options.duration??natural;const t0=this.time;const t1=t0+duration;for(const anim of anims){clock.now=t0;const end=options.duration!==void 0?t1:t0+anim.duration;anim.schedule({t0,t1:end,ease:options.ease??anim.ease??smooth2,stage:this})}this.clips.push({t0,t1,labels:options.label?[options.label]:anims.map(anim=>anim.label)});this.time=t1;this.ending=Math.max(this.ending,t1);clock.now=t1;return this}wait(seconds=1){this.time+=seconds;this.ending=Math.max(this.ending,this.time);clock.now=this.time;return this}at(time,build){const saved=this.time;this.time=time;clock.now=time;build();this.ending=Math.max(this.ending,this.time);this.time=saved;clock.now=saved;return this}chapter(title){this.chapters.push({title,time:this.time});return this}caption(text2,duration=3){this.captions.push({t0:this.time,t1:this.time+duration,text:text2});this.ending=Math.max(this.ending,this.time+duration);return this}value(initial=0){return new Value(initial)}update(node,fn,window={}){this.updaters.push({node,fn,from:window.from??this.time,to:window.to??Infinity});return node}get duration(){return Math.max(this.ending,this.time)}};function film(a,b){const options=typeof a==="function"?{}:a;const build=typeof a==="function"?a:b;if(!build)throw new Error("film(options, build) needs a build function.");const definition={kind:"vizmatic.film",options,build,compile:overrides=>compileFilm(definition,overrides)};return definition}function isFilm(value){return!!value&&typeof value==="object"&&value.kind==="vizmatic.film"}var Suspend=class{constructor(promise){this.promise=promise}promise;isVizmaticSuspend=true};function isSuspend(error){return typeof error==="object"&&error!==null&&error.isVizmaticSuspend===true}var CompiledFilm=class{width;height;fps;duration;title;description;look;bloom;background;posterTime;bleed;chapters;clips;captions;stage;constructor(stage,options,overrides){this.stage=stage;this.width=stage.width;this.height=stage.height;this.fps=overrides.fps??stage.fps;this.duration=Math.max(stage.duration,1/this.fps);this.title=options.title??"";this.description=options.description??"";this.look=stage.look;this.bloom=overrides.bloom??options.bloom??stage.look.bloom;const background=overrides.background!==void 0?overrides.background:options.background!==void 0?options.background:stage.look.background;this.background=background===null?null:stage.look.colors[background]??background;this.posterTime=options.poster;this.bleed=options.bleed===true;this.chapters=stage.chapters;this.clips=stage.clips;this.captions=stage.captions}get frameCount(){return Math.max(1,Math.round(this.duration*this.fps))}frame(time){const t=Math.max(0,Math.min(this.duration,time));const stage=this.stage;const previous={mode:clock.mode,now:clock.now};setColorTokens(stage.look.colors);clock.mode="render";clock.now=t;clock.frame++;try{for(const updater of stage.updaters){if(t>=updater.from&&t<=updater.to)updater.fn(updater.node,t)}const camera=stage.camera;const ops=buildOps(stage.root,{x:camera.get("x"),y:camera.get("y"),zoom:camera.get("sx"),rotation:camera.get("rotation")},stage.width,stage.height);return{width:stage.width,height:stage.height,background:this.background,bloom:this.bloom,dark:stage.look.dark,ops}}finally{clock.mode=previous.mode;clock.now=previous.now}}svg(time,options={}){return frameToSvg(this.frame(time),options)}};async function compileFilm(definition,overrides={}){const options={...definition.options,...overrides.look?{look:overrides.look}:{},...overrides.fps?{fps:overrides.fps}:{}};for(let attempt=0;attempt<64;attempt++){const stage=new Stage(options);setColorTokens(stage.look.colors);const saved={mode:clock.mode,now:clock.now};clock.mode="compile";clock.now=0;try{await definition.build(stage);clock.mode=saved.mode;clock.now=saved.now;const compiled=new CompiledFilm(stage,options,overrides);await probe(compiled);return compiled}catch(error){clock.mode=saved.mode;clock.now=saved.now;clock.capture=null;if(error instanceof Suspend){await error.promise;continue}throw error}}throw new Error("The film kept requesting new assets while compiling.")}async function probe(film2){const samples=[0,.25,.5,.75,1];for(const fraction of samples){for(let attempt=0;attempt<16;attempt++){try{film2.frame(film2.duration*fraction);break}catch(error){if(!(error instanceof Suspend))throw error;await error.promise}}}}function curveFree(contours){return{contours:contours.filter(contour=>contour.length>=8)}}var assetBase=null;function setAssetBase(url){assetBase=url}var isNode=typeof process!=="undefined"&&!!process.versions?.node&&typeof globalThis.document==="undefined";function moduleUrl(){const url=import.meta.url;if(url)return url;return`file://${typeof __filename!=="undefined"?__filename:""}`}async function nodeRead(relative3){const fsName="node:fs/promises",pathName="node:path",urlName="node:url";const[fs,path,url]=await Promise.all([import(fsName),import(pathName),import(urlName)]);let directory=path.dirname(url.fileURLToPath(moduleUrl()));for(let depth=0;depth<6;depth++){const candidate=path.join(directory,"assets",relative3);try{const bytes=await fs.readFile(candidate);return bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)}catch(error){if(error.code!=="ENOENT")throw error}directory=path.dirname(directory)}throw new Error(`Bundled asset not found: assets/${relative3}`)}async function loadBinaryAsset(relative3){if(isNode)return nodeRead(relative3);const base=assetBase??new URL("./assets/",moduleUrl()).href;const response=await fetch(new URL(relative3,base));const type=response.headers.get("content-type")??"";if(!response.ok||type.includes("text/html")){throw new Error(`Could not load ${relative3} from ${response.url} (HTTP ${response.status}, ${type||"no content type"}). Call setAssetBase() with the folder that holds fonts/.`)}return response.arrayBuffer()}var Reader=class{constructor(bytes,offset=0){this.bytes=bytes;this.offset=offset;this.view=new DataView(bytes)}bytes;offset;view;seek(offset){this.offset=offset;return this}get position(){return this.offset}u8(){return this.view.getUint8(this.offset++)}i8(){return this.view.getInt8(this.offset++)}u16(){const v=this.view.getUint16(this.offset);this.offset+=2;return v}i16(){const v=this.view.getInt16(this.offset);this.offset+=2;return v}u32(){const v=this.view.getUint32(this.offset);this.offset+=4;return v}tag(){let out="";for(let i=0;i<4;i++)out+=String.fromCharCode(this.u8());return out}};function parseFont(bytes){const r=new Reader(bytes);const version=r.u32();if(version!==65536&&version!==1953658213){throw new Error("Stage text needs a TrueType (.ttf) font with glyf outlines.")}const tableCount=r.u16();r.seek(12);const tables=new Map;for(let i=0;i<tableCount;i++){const tag=r.tag();r.u32();tables.set(tag,{offset:r.u32(),length:r.u32()})}const need=tag=>{const table=tables.get(tag);if(!table)throw new Error(`Font is missing its ${tag} table.`);return table};const head=need("head");r.seek(head.offset+18);const unitsPerEm=r.u16();r.seek(head.offset+50);const longLoca=r.i16()===1;const hhea=need("hhea");r.seek(hhea.offset+4);const ascent=r.i16();const descent=r.i16();const lineGap=r.i16();r.seek(hhea.offset+34);const hMetrics=r.u16();r.seek(need("maxp").offset+4);const glyphCount=r.u16();const hmtx=need("hmtx");const loca=need("loca");const glyf=need("glyf");const cmap=parseCmap(r,need("cmap").offset);const kerning=tables.has("GPOS")?parseKerning(r,tables.get("GPOS").offset):()=>0;const advance=glyph=>{const index=Math.min(glyph,hMetrics-1);r.seek(hmtx.offset+index*4);return r.u16()};const outlines=new Map;const contours=(glyph,depth)=>{if(glyph>=glyphCount||depth>6)return[];r.seek(loca.offset+(longLoca?glyph*4:glyph*2));const start=longLoca?r.u32():r.u16()*2;const end=longLoca?r.u32():r.u16()*2;if(start===end)return[];r.seek(glyf.offset+start);const count=r.i16();r.seek(r.position+8);if(count<0)return composite(glyph,depth);const ends=[];for(let i=0;i<count;i++)ends.push(r.u16());const instructionLength=r.u16();r.seek(r.position+instructionLength);const total=(ends[ends.length-1]??-1)+1;const flags=[];while(flags.length<total){const flag=r.u8();flags.push(flag);if(flag&8){let repeat=r.u8();while(repeat-- >0)flags.push(flag)}}const xs=new Array(total);let x=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&2){const dx=r.u8();x+=flag&16?dx:-dx}else if(!(flag&16)){x+=r.i16()}xs[i]=x}const ys=new Array(total);let y=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&4){const dy=r.u8();y+=flag&32?dy:-dy}else if(!(flag&32)){y+=r.i16()}ys[i]=y}const out=[];let first=0;for(const last of ends){out.push(contourToCubics(xs,ys,flags,first,last));first=last+1}return out};function composite(_glyph,depth){const parts=[];let more=true;while(more){const flags=r.u16();const glyph=r.u16();const words=(flags&1)!==0;const xy=(flags&2)!==0;let dx=0,dy=0;if(words){dx=r.i16();dy=r.i16()}else{dx=r.i8();dy=r.i8()}if(!xy){dx=0;dy=0}let a=1,b=0,c=0,d=1;const f2=()=>r.i16()/16384;if(flags&8){a=d=f2()}else if(flags&64){a=f2();d=f2()}else if(flags&128){a=f2();b=f2();c=f2();d=f2()}parts.push({glyph,m:[a,b,c,d,dx,dy]});more=(flags&32)!==0}const out=[];for(const part of parts){for(const contour of contours(part.glyph,depth+1)){const moved=new Array(contour.length);const[a,b,c,d,e,f]=part.m;for(let i=0;i<contour.length;i+=2){moved[i]=a*contour[i]+c*contour[i+1]+e;moved[i+1]=b*contour[i]+d*contour[i+1]+f}out.push(moved)}}return out}return{unitsPerEm,ascent,descent,lineGap,glyphFor(code){return cmap(code)},advance,kern(left,right){return kerning(left,right)},outline(glyph){if(outlines.has(glyph))return outlines.get(glyph);const raw=contours(glyph,0);const result=raw.length?curveFree(raw):null;outlines.set(glyph,result);return result}}}function contourToCubics(xs,ys,flags,first,last){const count=last-first+1;if(count<2)return[];const at=i=>first+(i%count+count)%count;const on=i=>(flags[at(i)]&1)!==0;let startIndex=0;while(startIndex<count&&!on(startIndex))startIndex++;let sx,sy;if(startIndex===count){sx=(xs[at(0)]+xs[at(count-1)])/2;sy=(ys[at(0)]+ys[at(count-1)])/2;startIndex=0}else{sx=xs[at(startIndex)];sy=ys[at(startIndex)];startIndex+=1}const out=[sx,sy];let cx=sx,cy=sy;let controlX=0,controlY=0,hasControl=false;const quad=(qx,qy,ex,ey)=>{out.push(cx+(qx-cx)*2/3,cy+(qy-cy)*2/3,ex+(qx-ex)*2/3,ey+(qy-ey)*2/3,ex,ey);cx=ex;cy=ey};const line2=(ex,ey)=>{out.push(cx+(ex-cx)/3,cy+(ey-cy)/3,cx+(ex-cx)*2/3,cy+(ey-cy)*2/3,ex,ey);cx=ex;cy=ey};for(let k=0;k<count;k++){const i=startIndex+k;const x=xs[at(i)],y=ys[at(i)];if(on(i)){if(hasControl){quad(controlX,controlY,x,y);hasControl=false}else if(x!==cx||y!==cy){line2(x,y)}}else{if(hasControl)quad(controlX,controlY,(controlX+x)/2,(controlY+y)/2);controlX=x;controlY=y;hasControl=true}}if(hasControl)quad(controlX,controlY,sx,sy);else if(cx!==sx||cy!==sy)line2(sx,sy);return out}function parseCmap(r,offset){r.seek(offset+2);const count=r.u16();let best=-1,bestScore=-1;for(let i=0;i<count;i++){const platform=r.u16();const encoding=r.u16();const sub=r.u32();const score=platform===3&&encoding===10?4:platform===0&&encoding>=4?3:platform===3&&encoding===1?2:platform===0?1:0;if(score>bestScore){bestScore=score;best=offset+sub}}if(best<0)return()=>0;r.seek(best);const format=r.u16();if(format===12){r.seek(best+12);const groups=r.u32();const table=[];for(let i=0;i<groups;i++)table.push([r.u32(),r.u32(),r.u32()]);return code=>{let lo=0,hi=table.length-1;while(lo<=hi){const mid=lo+hi>>1;const[start,end,glyph]=table[mid];if(code<start)hi=mid-1;else if(code>end)lo=mid+1;else return glyph+code-start}return 0}}if(format===4){r.seek(best+6);const segX2=r.u16();const segs=segX2/2;const endsAt=best+14;const startsAt=endsAt+segX2+2;const deltasAt=startsAt+segX2;const rangesAt=deltasAt+segX2;const map=new Map;for(let i=0;i<segs;i++){const end=r.seek(endsAt+i*2).u16();const start=r.seek(startsAt+i*2).u16();const delta=r.seek(deltasAt+i*2).i16();const range=r.seek(rangesAt+i*2).u16();for(let c=start;c<=end&&c!==65535;c++){let glyph;if(range===0)glyph=c+delta&65535;else{const raw=r.seek(rangesAt+i*2+range+(c-start)*2).u16();glyph=raw===0?0:raw+delta&65535}if(glyph)map.set(c,glyph)}}return code=>map.get(code)??0}return()=>0}function parseKerning(r,gpos){const lookups=[];try{r.seek(gpos+6);const featureList=gpos+r.u16();const lookupList=gpos+r.u16();r.seek(featureList);const featureCount=r.u16();const indices=new Set;for(let i=0;i<featureCount;i++){r.seek(featureList+2+i*6);const tag=r.tag();const offset=r.u16();if(tag!=="kern")continue;r.seek(featureList+offset+2);const count=r.u16();for(let k=0;k<count;k++)indices.add(r.u16())}for(const index of[...indices].sort((a,b)=>a-b)){r.seek(lookupList+2+index*2);const lookup=lookupList+r.u16();r.seek(lookup);const lookupType=r.u16();r.u16();const subCount=r.u16();const subs=[];for(let i=0;i<subCount;i++)subs.push(lookup+r.u16());const tables=[];for(const first of subs){let sub=first;let type=lookupType;if(type===9){r.seek(sub+2);type=r.u16();sub+=r.u32()}if(type===2)tables.push(readPairs(r,sub))}lookups.push(tables)}}catch{}const cache2=new Map;return(left,right)=>{const key=left*65536+right;const cached=cache2.get(key);if(cached!==void 0)return cached;let total=0;for(const tables of lookups){for(const table of tables){const value=table(left,right);if(value!==void 0){total+=value;break}}}cache2.set(key,total);return total}}function readCoverage(r,offset){r.seek(offset);const format=r.u16();const out=new Set;if(format===1){const count=r.u16();for(let i=0;i<count;i++)out.add(r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)out.add(glyph)}}return out}function readClasses(r,offset){r.seek(offset);const format=r.u16();const classes=new Map;if(format===1){const start=r.u16();const count=r.u16();for(let i=0;i<count;i++)classes.set(start+i,r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16(),value=r.u16();for(let glyph=start;glyph<=end;glyph++)classes.set(glyph,value)}}return glyph=>classes.get(glyph)??0}function valueSize(format){let count=0;for(let bit=0;bit<8;bit++)if(format&1<<bit)count++;return count*2}function readAdvance(r,format){let advance=0;if(format&1)r.i16();if(format&2)r.i16();if(format&4)advance=r.i16();if(format&8)r.i16();for(let bit=4;bit<8;bit++)if(format&1<<bit)r.u16();return advance}function readPairs(r,sub){r.seek(sub);const format=r.u16();const coverageOffset=r.u16();const value1=r.u16();const value2=r.u16();const size1=valueSize(value1);const size2=valueSize(value2);if(format===1){const setCount=r.u16();const offsets=[];for(let i=0;i<setCount;i++)offsets.push(r.u16());r.seek(sub+coverageOffset);const coverageFormat=r.u16();const glyphs=[];if(coverageFormat===1){const count=r.u16();for(let i=0;i<count;i++)glyphs.push(r.u16())}else if(coverageFormat===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)glyphs.push(glyph)}}const sets=new Map;for(let i=0;i<setCount;i++){r.seek(sub+offsets[i]);const count=r.u16();const pairs=new Map;for(let k=0;k<count;k++){const second=r.u16();const advance=readAdvance(r,value1);r.seek(r.position+size2);pairs.set(second,advance)}if(glyphs[i]!==void 0)sets.set(glyphs[i],pairs)}return(left,right)=>sets.get(left)?.get(right)}if(format===2){const class1Offset=r.u16();const class2Offset=r.u16();const class1Count=r.u16();const class2Count=r.u16();const matrix2=r.position;const coverage=readCoverage(r,sub+coverageOffset);const class1=readClasses(r,sub+class1Offset);const class2=readClasses(r,sub+class2Offset);return(left,right)=>{if(!coverage.has(left))return void 0;const c1=class1(left),c2=class2(right);if(c1>=class1Count||c2>=class2Count)return void 0;r.seek(matrix2+c1*class2Count*(size1+size2)+c2*(size1+size2));return readAdvance(r,value1)}}return()=>void 0}var FILES={sans:{"400":"Inter-Regular.ttf","600":"Inter-SemiBold.ttf","700":"Inter-Bold.ttf"},serif:{"400":"InstrumentSerif-Regular.ttf","italic":"InstrumentSerif-Italic.ttf"},"text-serif":{"400":"SourceSerif4-24pt-Regular.ttf","italic":"SourceSerif4-24pt-Italic.ttf"},mono:{"400":"JetBrainsMono-Regular.ttf"},noto:{"400":"NotoSans-Regular.ttf"},math:{"400":"NotoSansMath-Regular.ttf"}};var FALLBACKS={sans:["noto","math"],serif:["text-serif","noto","math"],"text-serif":["noto","math"],mono:["noto","math"],noto:["math"]};var fonts=new Map;var pending=new Map;function fontFor(family,weight=400,italic=false){const files=FILES[family];const file=(italic?files["italic"]:void 0)??files[String(weight)]??files["400"];const loaded=fonts.get(file);if(loaded)return loaded;let waiting=pending.get(file);if(!waiting){waiting=loadBinaryAsset(`fonts/${file}`).then(bytes=>{fonts.set(file,parseFont(bytes));pending.delete(file)});pending.set(file,waiting)}throw new Suspend(waiting)}function fallbackGlyph(family,code,weight=400,italic=false){for(const next of FALLBACKS[family]){const font=fontFor(next,weight,italic);const glyph=font.glyphFor(code);if(glyph!==0)return{font,glyph}}return null}var glyphPaths=new WeakMap;function glyphPath(font,glyph,size){let bySize=glyphPaths.get(font);if(!bySize)glyphPaths.set(font,bySize=new Map);let byGlyph=bySize.get(size);if(!byGlyph)bySize.set(size,byGlyph=new Map);const cached=byGlyph.get(glyph);if(cached)return cached;const outline=font.outline(glyph);const scale=size/font.unitsPerEm;const path=outline?outline.contours.map(contour=>{const out=new Float64Array(contour.length);for(let i=0;i<contour.length;i+=2){out[i]=contour[i]*scale;out[i+1]=-contour[i+1]*scale}return ring(out,true)}):[];byGlyph.set(glyph,path);return path}var TextNode=class extends Node{chars=[];source="";find(fragment){const out=[];const keys=this.chars.map(glyph=>glyph.data["key"]).join("");const needle=fragment.replace(/\s/g,"");for(let at=keys.indexOf(needle);at>=0;at=keys.indexOf(needle,at+1)){out.push(...this.chars.slice(at,at+needle.length))}return out}};function centered(path){const b=pathBounds(path);if(!b)return{path,x:0,y:0};const x=b.x+b.width/2,y=b.y+b.height/2;return{path:transformPath(path,[1,0,0,1,-x,-y]),x,y}}function text(content,options={}){const size=options.size??40;const family=options.font??"sans";const weight=options.weight??400;const italic=options.italic??false;const font=fontFor(family,weight,italic);const scale=size/font.unitsPerEm;const tracking=(options.tracking??0)*size;const leading=(options.leading??1.3)*size;const paint=toPaint(options.color??"ink");const source=options.uppercase?content.toUpperCase():content;const measureWord=word=>{const glyphs=[];let x=0,previous=0,previousFont=null;for(const char of word){const code=char.codePointAt(0);let owner=font,glyph=font.glyphFor(code);if(glyph===0){const found=fallbackGlyph(family,code,weight,italic);if(found){owner=found.font;glyph=found.glyph}}const ownerScale=size/owner.unitsPerEm;if(previous&&previousFont===owner)x+=owner.kern(previous,glyph)*ownerScale;glyphs.push({font:owner,glyph,x,char});x+=owner.advance(glyph)*ownerScale+tracking;previous=glyph;previousFont=owner}return{glyphs,width:x}};const lines=[];const space=font.advance(font.glyphFor(32))*scale+tracking;for(const paragraph of source.split("\n")){let line2=[];let width=0;for(const word of paragraph.split(" ")){const measured=measureWord(word);const gap=line2.length>0?space:0;if(options.maxWidth!==void 0&&line2.length>0&&width+gap+measured.width>options.maxWidth){lines.push({glyphs:line2,width});line2=[];width=0}const offset=width+(line2.length>0?space:0);for(const glyph of measured.glyphs)line2.push({...glyph,x:glyph.x+offset});width=offset+measured.width}lines.push({glyphs:line2,width})}const blockWidth=Math.max(0,...lines.map(line2=>line2.width));const align=options.align??"left";const node=new TextNode;node.source=content;lines.forEach((line2,row)=>{const start=align==="left"?0:align==="center"?(blockWidth-line2.width)/2:blockWidth-line2.width;for(const placed of line2.glyphs){const path=glyphPath(placed.font,placed.glyph,size);if(path.length===0)continue;const shape2=centered(path);const leaf=new Node(shape2.path).at(start+placed.x+shape2.x,row*leading+shape2.y);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=placed.char;if(placed.glyph===0)leaf.data["missingGlyph"]=true;node.chars.push(leaf);node.children.push(leaf);leaf.parent=node}});const ascent=font.ascent*scale;const height=(lines.length-1)*leading;node.base.px=blockWidth/2;node.base.py=height/2-ascent*.36;node.data["size"]=size;return node}function decode(value){return value.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g,(_,code)=>String.fromCodePoint(parseInt(code,16))).replace(/&amp;/g,"&")}function parseXml(source){const root={name:"#root",attrs:{},children:[],text:""};const stack=[root];const token=/<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;for(let match=token.exec(source);match;match=token.exec(source)){const top=stack[stack.length-1];const[,cdata,closing,opening,attributes,selfClosing,content]=match;if(cdata!==void 0){top.text+=cdata}else if(closing){if(stack.length>1)stack.pop()}else if(opening){const element={name:opening.replace(/^.*:/,""),attrs:{},children:[],text:""};for(const attr of(attributes??"").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)){element.attrs[attr[1]]=decode(attr[2]??attr[3]??"")}top.children.push(element);if(!selfClosing)stack.push(element)}else if(content){top.text+=decode(content)}}return root}function parseTransform(value){if(!value)return IDENTITY;let m=IDENTITY;for(const match of value.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)){const a=match[2].trim().split(/[\s,]+/).filter(Boolean).map(Number);const name=match[1];if(name==="matrix"&&a.length===6)m=mul(m,a);else if(name==="translate")m=mul(m,[1,0,0,1,a[0]??0,a[1]??0]);else if(name==="scale")m=mul(m,[a[0]??1,0,0,a[1]??a[0]??1,0,0]);else if(name==="rotate"){const r=(a[0]??0)*Math.PI/180;const c=Math.cos(r),s=Math.sin(r);const cx=a[1]??0,cy=a[2]??0;m=mul(m,[1,0,0,1,cx,cy]);m=mul(m,[c,s,-s,c,0,0]);m=mul(m,[1,0,0,1,-cx,-cy])}else if(name==="skewX")m=mul(m,[1,0,Math.tan((a[0]??0)*Math.PI/180),1,0,0]);else if(name==="skewY")m=mul(m,[1,Math.tan((a[0]??0)*Math.PI/180),0,1,0,0])}return m}var NOT_DRAWN=new Set(["defs","clipPath","mask","pattern","filter","symbol","marker","linearGradient","radialGradient","title","desc","metadata","style","script"]);var SvgNode=class extends Node{byId=new Map;pictureWidth=0;pictureHeight=0;find(id){const found=this.byId.get(id);if(!found)throw new Error(`The SVG has no element with id ${JSON.stringify(id)}.`);return found}};function parseCssRules(root){const rules=new Map;const visit=element=>{if(element.name==="style"){for(const rule of element.text.matchAll(/([^{}]+)\{([^{}]*)\}/g)){const body=parseStyle(rule[2]);for(const selector of rule[1].split(",")){const key=selector.trim();rules.set(key,{...rules.get(key),...body})}}}element.children.forEach(visit)};visit(root);return rules}function parseStyle(value){const out={};if(!value)return out;for(const part of value.split(";")){const index=part.indexOf(":");if(index>0)out[part.slice(0,index).trim()]=part.slice(index+1).trim()}return out}function safeColor(value){if(!value||value==="none"||value==="transparent")return null;try{return parseColor(value)}catch{return null}}function splitIntoGlyphs(path){const items=path.map(r=>{const b=pathBounds([r]);return{ring:r,b,area:b.width*b.height,owner:-1}});const order=items.map((_,i)=>i).sort((a,b)=>items[b].area-items[a].area);for(let k=0;k<order.length;k++){const inner=items[order[k]];for(let j=k-1;j>=0;j--){const outer=items[order[j]];if(outer.owner!==-1)continue;const inside=inner.b.x>=outer.b.x-.01&&inner.b.y>=outer.b.y-.01&&inner.b.x+inner.b.width<=outer.b.x+outer.b.width+.01&&inner.b.y+inner.b.height<=outer.b.y+outer.b.height+.01;if(inside){inner.owner=order[j];break}}}const glyphs=[];const ownerToGlyph=new Map;items.forEach((item,i)=>{if(item.owner!==-1)return;const glyph={x:item.b.x,rings:[item.ring]};ownerToGlyph.set(i,glyph);glyphs.push(glyph)});items.forEach(item=>{if(item.owner!==-1)ownerToGlyph.get(item.owner)?.rings.push(item.ring)});return glyphs.sort((a,b)=>a.x-b.x).map(glyph=>glyph.rings)}function fromSvg(source,options={}){const root=parseXml(source);const svg=root.children.find(child=>child.name==="svg");if(!svg)throw new Error("fromSvg needs markup with an <svg> element.");const rules=parseCssRules(svg);const defs=new Map;const index=element=>{if(element.attrs["id"])defs.set(element.attrs["id"],element);element.children.forEach(index)};index(svg);const box=(svg.attrs["viewBox"]??"").trim().split(/[\s,]+/).map(Number);const declaredW=parseFloat(svg.attrs["width"]??""),declaredH=parseFloat(svg.attrs["height"]??"");const viewW=box.length===4&&box[2]?box[2]:declaredW||300;const viewH=box.length===4&&box[3]?box[3]:declaredH||150;const viewX=box.length===4?box[0]:0,viewY=box.length===4?box[1]:0;const naturalW=Number.isFinite(declaredW)&&declaredW>0?declaredW:viewW;const naturalH=Number.isFinite(declaredH)&&declaredH>0?declaredH:viewH;let scale=1;if(options.width!==void 0||options.height!==void 0){const sx=options.width!==void 0?options.width/viewW:Infinity;const sy=options.height!==void 0?options.height/viewH:Infinity;scale=Math.min(sx,sy)}else{scale=Math.min(naturalW/viewW,naturalH/viewH)}const center2=options.center??true;const offsetX=center2?-(viewX+viewW/2)*scale:-viewX*scale;const offsetY=center2?-(viewY+viewH/2)*scale:-viewY*scale;const base=[scale,0,0,scale,offsetX,offsetY];const out=new SvgNode;out.pictureWidth=viewW*scale;out.pictureHeight=viewH*scale;const splitting=options.splitGlyphs??true;const keepBackground=options.background??false;let firstShape=true;const gradientOf=(id,m,path)=>{const element=defs.get(id);if(!element)return null;if(element.name==="pattern"){const inner=element.children.find(child=>child.name==="linearGradient");if(inner)return linear2(inner,m,path,true);const fill=element.children.find(child=>child.attrs["fill"]?.startsWith("url(#"));const nested=fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];return nested?gradientOf(nested,m,path):null}if(element.name==="linearGradient")return linear2(element,m,path,element.attrs["gradientUnits"]!=="userSpaceOnUse");if(element.name==="radialGradient"){const stops=stopsOf(element);return stops.length?stops[stops.length-1][1]:null}return null};const stopsOf=element=>{const inherited=element.attrs["href"]??element.attrs["xlink:href"];const source2=element.children.some(child=>child.name==="stop")||!inherited?element:defs.get(inherited.replace(/^#/,""))??element;return source2.children.filter(child=>child.name==="stop").map(stop=>{const style2=parseStyle(stop.attrs["style"]);const offsetRaw=stop.attrs["offset"]??"0";const offset=offsetRaw.endsWith("%")?parseFloat(offsetRaw)/100:parseFloat(offsetRaw);const color=safeColor(style2["stop-color"]??stop.attrs["stop-color"]??"#000000")??[0,0,0,1];const alpha3=parseFloat(style2["stop-opacity"]??stop.attrs["stop-opacity"]??"1");return[offset,[color[0],color[1],color[2],color[3]*alpha3]]})};const linear2=(element,m,path,objectBox)=>{const stops=stopsOf(element);if(stops.length===0)return null;const coordinate=(value,fallback)=>{if(value===void 0)return fallback;return value.endsWith("%")?parseFloat(value)/100:parseFloat(value)};const x1=coordinate(element.attrs["x1"],0),y1=coordinate(element.attrs["y1"],0);const x2=coordinate(element.attrs["x2"],1),y2=coordinate(element.attrs["y2"],0);let from,to2;if(objectBox){const b=pathBounds(path)??{x:0,y:0,width:1,height:1};from=[b.x+x1*b.width,b.y+y1*b.height];to2=[b.x+x2*b.width,b.y+y2*b.height]}else{from=apply(m,x1,y1);to2=apply(m,x2,y2)}return{type:"linear",from,to:to2,stops}};const shapePath=element=>{const a=element.attrs;const num=(key,fallback=0)=>{const value=parseFloat(a[key]??"");return Number.isFinite(value)?value:fallback};switch(element.name){case"path":return a["d"]?parseSvgPath(a["d"]):null;case"rect":{const w=num("width"),h=num("height");if(w<=0||h<=0)return null;return rectPath(num("x"),num("y"),w,h,num("rx",num("ry")))}case"circle":return num("r")>0?arcPath(num("cx"),num("cy"),num("r"),num("r"),0,Math.PI*2):null;case"ellipse":return num("rx")>0&&num("ry")>0?arcPath(num("cx"),num("cy"),num("rx"),num("ry"),0,Math.PI*2):null;case"line":return polyPath([[num("x1"),num("y1")],[num("x2"),num("y2")]]);case"polyline":case"polygon":{const values=(a["points"]??"").trim().split(/[\s,]+/).filter(Boolean).map(Number);const points=[];for(let i=0;i+1<values.length;i+=2)points.push([values[i],values[i+1]]);return points.length>=2?polyPath(points,element.name==="polygon"):null}default:return null}};const styleOf=(element,inherited)=>{const a=element.attrs;const cls=(a["class"]??"").split(/\s+/).filter(Boolean);const merged={...rules.get(element.name)};for(const name of cls)Object.assign(merged,rules.get(`.${name}`));if(a["id"])Object.assign(merged,rules.get(`#${a["id"]}`));const pick=key=>parseStyle(a["style"])[key]??a[key]??merged[key];const style2={...inherited};const color=pick("color");if(color)style2.color=color;const fill=pick("fill");if(fill)style2.fill=fill==="currentColor"?style2.color:fill;const stroke=pick("stroke");if(stroke)style2.stroke=stroke==="currentColor"?style2.color:stroke;const width=pick("stroke-width");if(width!==void 0)style2.strokeWidth=parseFloat(width)||0;const fo=pick("fill-opacity");if(fo!==void 0)style2.fillOpacity=parseFloat(fo);const so=pick("stroke-opacity");if(so!==void 0)style2.strokeOpacity=parseFloat(so);const cap=pick("stroke-linecap");if(cap==="round"||cap==="butt"||cap==="square")style2.cap=cap;const join4=pick("stroke-linejoin");if(join4==="round"||join4==="miter"||join4==="bevel")style2.join=join4;const dash=pick("stroke-dasharray");if(dash!==void 0)style2.dash=dash==="none"?null:dash.trim().split(/[\s,]+/).map(Number);const dashOffset=pick("stroke-dashoffset");if(dashOffset!==void 0)style2.dashOffset=parseFloat(dashOffset)||0;const size=pick("font-size");if(size!==void 0)style2.fontSize=parseFloat(size)||style2.fontSize;const anchor=pick("text-anchor");if(anchor)style2.anchor=anchor;return{style:style2,opacity:parseFloat(pick("opacity")??"1")}};const leafFrom=(path,m,element,style2)=>{const world=transformPath(path,m);const scaleOf=matScale(m);const url=value=>value?.match(/^url\(#([^)]+)\)/)?.[1];const fillId=url(style2.fill),strokeId=url(style2.stroke);const fill=fillId?gradientOf(fillId,m,world):safeColor(style2.fill);const stroke=strokeId?gradientOf(strokeId,m,world):safeColor(style2.stroke);const visibleFill=fill&&style2.fillOpacity>0&&!(Array.isArray(fill)&&fill[3]===0);const visibleStroke=stroke&&style2.strokeOpacity>0&&style2.strokeWidth>0&&!(Array.isArray(stroke)&&stroke[3]===0);if(!visibleFill&&!visibleStroke)return[];const clippedStroke=element.attrs["clip-path"]?.5:1;const pieces=splitting&&visibleFill&&!visibleStroke&&world.length>1?splitIntoGlyphs(world):[world];return pieces.map(piece=>{const b=pathBounds(piece)??{x:0,y:0,width:0,height:0};const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(piece,[1,0,0,1,-cx,-cy])).at(cx,cy);if(visibleFill){leaf.base.fill=shiftPaint(fill,-cx,-cy);leaf.base.fillOpacity=style2.fillOpacity}if(visibleStroke){leaf.base.stroke=shiftPaint(stroke,-cx,-cy);leaf.base.strokeWidth=style2.strokeWidth*scaleOf*clippedStroke;leaf.base.strokeOpacity=style2.strokeOpacity;leaf.base.cap=style2.cap;leaf.base.join=style2.join;if(style2.dash)leaf.base.dash=style2.dash.map(value=>value*scaleOf);leaf.base.dashOffset=style2.dashOffset*scaleOf}leaf.base.trimEach=true;return leaf})};const walk2=(element,parent,inherited,parentMatrix)=>{if(NOT_DRAWN.has(element.name))return;if(element.attrs["filter"])return;const{style:style2,opacity}=styleOf(element,inherited);const m=mul(parentMatrix,parseTransform(element.attrs["transform"]));const register=node=>{if(element.attrs["id"])out.byId.set(element.attrs["id"],node)};if(element.name==="g"||element.name==="svg"||element.name==="a"){const group3=new Node;if(opacity<1)group3.base.opacity=opacity;register(group3);parent.add(group3);for(const child of element.children)walk2(child,group3,style2,m);return}if(element.name==="use"){const href=(element.attrs["href"]??element.attrs["xlink:href"]??"").replace(/^#/,"");const referenced=defs.get(href);if(!referenced)return;const placed=mul(m,[1,0,0,1,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0]);const group3=new Node;if(opacity<1)group3.base.opacity=opacity;parent.add(group3);if(referenced.name==="symbol")for(const child of referenced.children)walk2(child,group3,style2,placed);else walk2(referenced,group3,style2,placed);return}if(element.name==="image"){const href=element.attrs["href"]??element.attrs["xlink:href"];if(!href)return;const width=parseFloat(element.attrs["width"]??"0"),height=parseFloat(element.attrs["height"]??"0");const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const unit=matScale(m);const image2={src:href,width,height};const node=new Node().at(x,y);node.base.image=image2;node.base.sx=unit;node.base.sy=unit;if(opacity<1)node.base.opacity=opacity;register(node);parent.add(node);return}if(element.name==="text"){const body=(element.text+element.children.map(child=>child.text).join("")).trim();if(!body)return;const color=safeColor(style2.fill)??[0,0,0,1];const size=style2.fontSize*matScale(m);const label=text(body,{size,color});const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const half=label.get("px");label.at(style2.anchor==="middle"?x:style2.anchor==="end"?x-half:x+half,y-size*.34);if(opacity<1)label.base.opacity=opacity;register(label);parent.add(label);return}const path=shapePath(element);if(!path||path.length===0)return;const isBackground=firstShape&&element.name==="rect"&&!keepBackground&&parseFloat(element.attrs["width"]??"0")>=viewW-.5&&parseFloat(element.attrs["height"]??"0")>=viewH-.5;firstShape=false;if(isBackground)return;const leaves=leafFrom(path,m,element,style2);if(leaves.length===0)return;if(leaves.length===1){if(opacity<1)leaves[0].base.opacity=opacity;register(leaves[0]);parent.add(leaves[0]);return}const group2=new Node;if(opacity<1)group2.base.opacity=opacity;group2.add(...leaves);register(group2);parent.add(group2)};const initial={fill:"#000000",stroke:null,strokeWidth:1,fillOpacity:1,strokeOpacity:1,cap:"butt",join:"miter",dash:null,dashOffset:0,color:"#000000",fontSize:16,anchor:"start"};const{style}=styleOf(svg,initial);for(const child of svg.children)walk2(child,out,style,base);return out}function shiftPaint(paint,dx,dy){if(Array.isArray(paint))return paint;const gradient=paint;if(gradient.type==="linear"){return{...gradient,from:[gradient.from[0]+dx,gradient.from[1]+dy],to:[gradient.to[0]+dx,gradient.to[1]+dy]}}if(gradient.type==="radial")return{...gradient,center:[gradient.center[0]+dx,gradient.center[1]+dy]};return gradient}var QUALITY={draft:{crf:26,vp9Crf:40,preset:"veryfast",motionBlur:1},standard:{crf:18,vp9Crf:31,preset:"medium",motionBlur:1},high:{crf:15,vp9Crf:24,preset:"slow",motionBlur:4},master:{crf:11,vp9Crf:15,preset:"slow",motionBlur:8}};var DEFAULT_GIF_WIDTH=960;var DEFAULT_GIF_FPS=25;var GIF_PALETTE_FRAMES=12;var GIF_PALETTE_PIXELS=1<<19;var MAX_GIF_DELAY=655350;async function resolveFilm(film2,overrides){return isFilm(film2)?film2.compile(overrides):film2}function frameAt(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt(film2,time))}}function backgroundBytes(color){if(!color)return[0,0,0];const rgba=parseColor(color);return[rgba[0],rgba[1],rgba[2]]}function outputSize(film2,requested){const width=requested??film2.width;if(!Number.isInteger(width)||width<2)throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);return{width,height:Math.max(1,Math.round(width*film2.height/film2.width))}}function evenSize(film2,requested){const{width,height}=outputSize(film2,requested);return{width:width+width%2,height:Math.max(2,height+height%2)}}function timeRange(film2,options){const from=Math.max(0,options.from??0);const to2=Math.min(film2.duration,options.to??film2.duration);if(!Number.isFinite(from)||!Number.isFinite(to2)||to2<=from){throw new Error(`The render range ${from}:${to2} is empty. The film is ${film2.duration.toFixed(2)} seconds long.`)}return{from,to:to2}}function planRender(width,height,motionBlur,options={}){const frameBytes=width*height*4;const budget=options.memoryBudget??Math.min(2*1024**3,totalmem()*.25);const requested=Math.max(1,Math.floor(options.workers??defaultPoolSize()));const perWorker=frameBytes*(motionBlur>1?motionBlur+4:3);const workers=Math.max(1,Math.min(requested,Math.floor(budget*.75/perWorker)));const extra=Math.floor(budget*.25/frameBytes);return{workers,readAhead:Math.max(workers+1,Math.min(workers*2,workers+extra))}}function frameStream(film2,pool,timeOf,size,count,readAhead,subframes=1,shutterSpan=0){const inFlight=new Map;const submit=async index=>{const base=timeOf(index);const frames=[];for(let sub=0;sub<subframes;sub++){frames.push(await frameAt(film2,base+sub/subframes*shutterSpan))}return pool.run(framesToJob(frames,size.width,backgroundBytes,size.height))};return async index=>{for(let ahead=index;ahead<Math.min(count,index+readAhead);ahead++){if(inFlight.has(ahead))continue;const job=submit(ahead);job.catch(()=>{});inFlight.set(ahead,job)}const pixels=await inFlight.get(index);inFlight.delete(index);return pixels}}function filmEncoderSettings(quality="standard"){const settings=QUALITY[quality];if(!settings)throw new Error(`Unknown quality: ${quality}. Use draft, standard, high, or master.`);return{crf:settings.crf,preset:settings.preset,tune:"animation"}}async function renderFilmVideo(film2,outputPath,options={}){const compiled=await resolveFilm(film2,options);const quality=QUALITY[options.quality??"standard"];if(!quality)throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);const size=evenSize(compiled,options.width);const motionBlur=Math.max(1,Math.floor(options.motionBlur??quality.motionBlur));const shutter=options.shutter??.5;const fps=compiled.fps;const codec=options.codec??"h264";const{from,to:to2}=timeRange(compiled,options);const plan=planRender(size.width,size.height,motionBlur,options);const pool=new RasterPool(plan.workers);try{const count=Math.max(1,Math.round((to2-from)*fps));const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead,motionBlur,shutter/fps);const output=await renderRgbaVideo(info=>next(info.index),{width:size.width,height:size.height,fps,duration:(to2-from)*1e3,outputPath,codec,crf:codec==="vp9"?quality.vp9Crf:quality.crf,preset:quality.preset,tune:codec==="h264"?filmEncoderSettings(options.quality).tune:void 0,threads:options.threads??6,audioPath:options.audioPath,audioOffset:from>0?from:void 0,ffmpegPath:options.ffmpegPath,title:compiled.title,chapters:options.chapters===false?[]:shiftedChapters(compiled,from),captions:options.embedCaptions===false?[]:compiled.captions.map(cue=>({t0:cue.t0-from,t1:cue.t1-from,text:cue.text})),signal:options.signal,onProgress:options.onProgress});return{...output,title:compiled.title,workers:pool.size,motionBlur,codec}}finally{await pool.close()}}function shiftedChapters(film2,from){const sorted=[...film2.chapters].sort((a,b)=>a.time-b.time);const running=sorted.filter(chapter=>chapter.time<=from).pop();const later=sorted.filter(chapter=>chapter.time>from).map(chapter=>({title:chapter.title,time:chapter.time-from}));return running?[{title:running.title,time:0},...later]:later}var gifApi=typeof gifenc2.GIFEncoder==="function"?gifenc2:gifenc2.default;function changedRegion(previous,current,width,height){let minX=width,minY=height,maxX=-1,maxY=-1;for(let y=0;y<height;y++){const row=y*width*4;for(let x=0;x<width;x++){const o=row+x*4;if(previous[o]!==current[o]||previous[o+1]!==current[o+1]||previous[o+2]!==current[o+2]){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;maxY=y}}}return maxX<0?null:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropRegion(pixels,canvasWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const start=((region.y+y)*canvasWidth+region.x)*4;out.set(pixels.subarray(start,start+region.width*4),y*region.width*4)}return out}async function renderFilmGif(film2,outputPath,options={}){const compiled=await resolveFilm(film2,{...options,fps:void 0});const size=outputSize(compiled,options.width??Math.min(DEFAULT_GIF_WIDTH,compiled.width));const fps=Math.min(options.fps??DEFAULT_GIF_FPS,50);const{from,to:to2}=timeRange(compiled,options);const count=Math.max(1,Math.round((to2-from)*fps));const delay2=1e3/fps;const plan=planRender(size.width,size.height,1,options);const pool=new RasterPool(plan.workers);try{const sampleCount=Math.min(count,GIF_PALETTE_FRAMES);const samples=await Promise.all(Array.from({length:sampleCount},async(_,i)=>{const index=Math.floor((i+.5)*count/sampleCount);return pool.run(framesToJob([await frameAt(compiled,from+index/fps)],size.width,backgroundBytes,size.height))}));const perFrame=Math.max(1,Math.floor(GIF_PALETTE_PIXELS/sampleCount));const combined=new Uint8Array(perFrame*sampleCount*4);samples.forEach((pixels,i)=>{const total=pixels.length/4;for(let k=0;k<perFrame;k++){const at=Math.floor((k+.5)*total/perFrame)*4;combined.set(pixels.subarray(at,at+4),(i*perFrame+k)*4)}});const palette=gifApi.quantize(combined,256,{format:"rgb565"});const gif=gifApi.GIFEncoder();const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead);const repeat=options.loop===false?-1:0;let previous=null;let pending2=null;const flush=first=>{if(!pending2)return;let remaining=pending2.delay;let includePalette=first;do{const span=Math.min(MAX_GIF_DELAY,remaining);const start=gif.bytesView().length;gif.writeFrame(pending2.index,pending2.region.width,pending2.region.height,{...includePalette?{palette}:{},delay:Math.max(20,span),repeat,dispose:1});if(pending2.region.x!==0||pending2.region.y!==0){const bytes=gif.bytesView();const descriptor=start+8;if(bytes[descriptor]!==44)throw new Error("The GIF encoder wrote an unexpected frame layout.");bytes[descriptor+1]=pending2.region.x&255;bytes[descriptor+2]=pending2.region.x>>8&255;bytes[descriptor+3]=pending2.region.y&255;bytes[descriptor+4]=pending2.region.y>>8&255}includePalette=false;remaining-=span}while(remaining>0)};let wroteAny=false;for(let i=0;i<count;i++){options.signal?.throwIfAborted();const pixels=await next(i);const region=previous?changedRegion(previous,pixels,size.width,size.height):{x:0,y:0,width:size.width,height:size.height};if(!region){if(pending2)pending2.delay+=delay2}else{flush(!wroteAny);if(pending2)wroteAny=true;const cropped=region.width===size.width&&region.height===size.height?pixels:cropRegion(pixels,size.width,region);pending2={index:gifApi.applyPalette(cropped,palette,"rgb565"),region,delay:delay2};previous=pixels}await options.onProgress?.({index:i,count,time:i*delay2,duration:count*delay2,progress:i/count,fps})}flush(!wroteAny);gif.finish();const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,gif.bytesView());return{width:size.width,height:size.height,frameCount:count,duration:count*delay2,fps,bytes:(await stat(path)).size,outputPath:path,title:compiled.title}}finally{await pool.close()}}async function renderFilmFrame(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const{width,height}=outputSize(compiled,options.width);const pool=new RasterPool(1);try{const frame=await frameAt(compiled,time);const pixels=await pool.run(framesToJob([frame],width,backgroundBytes,height));const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,encodePng({width,height,data:pixels,depth:8,channels:4}));return{width,height,outputPath:path}}finally{await pool.close()}}async function renderFilmSvg(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});const frame=await frameAt(compiled,time);const scale=(options.width??compiled.width)/compiled.width;await writeFile2(path,frameToSvg(frame,{scale}));return{width:Math.round(compiled.width*scale),height:Math.round(compiled.height*scale),outputPath:path}}async function posterTime(film2){if(film2.posterTime!==void 0)return Math.max(0,Math.min(film2.duration,film2.posterTime));const active=t=>film2.clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;const candidates=new Set;for(const clip of film2.clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))candidates.add(t)}if(candidates.size===0)for(let i=1;i<=10;i++)candidates.add(film2.duration*i/10-nudge);const scored=[];for(const time of[...candidates].sort((a,b)=>a-b)){const frame=await frameAt(film2,time);scored.push({time,ink:frame.ops.length})}const fullest=Math.max(...scored.map(entry=>entry.ink));const rich=scored.filter(entry=>entry.ink>=fullest*.75);return rich[rich.length-1]?.time??film2.duration}function captionsToVtt(film2){const stamp=seconds=>{const m=Math.floor(seconds/60),s=seconds-m*60;return`${String(m).padStart(2,"0")}:${s.toFixed(3).padStart(6,"0")}`};const cues=film2.captions.map(cue=>`${stamp(cue.t0)} --> ${stamp(cue.t1)}
151
+ `;function resolveResvg(){const here=typeof __filename!=="undefined"?__filename:fileURLToPath(import.meta.url);return createRequire(here).resolve("@resvg/resvg-js")}var RasterPool=class{workers=[];idle=[];queue=[];pending=new Map;nextId=1;failure=null;constructor(size=defaultPoolSize()){const resvgPath=resolveResvg();for(let i=0;i<size;i++){const worker=new Worker(RASTER_WORKER_SOURCE,{eval:true,workerData:{resvgPath}});worker.on("message",message=>{const entry=this.pending.get(message.id);this.pending.delete(message.id);this.idle.push(worker);this.pump();if(!entry)return;if(message.error||!message.pixels)entry.reject(new Error(`Frame rasterization failed: ${message.error}`));else entry.resolve(message.pixels)});worker.on("error",error=>this.fail(error instanceof Error?error:new Error(String(error))));this.workers.push(worker);this.idle.push(worker)}}get size(){return this.workers.length}fail(error){this.failure=error;for(const entry of this.pending.values())entry.reject(error);this.pending.clear()}pump(){while(this.idle.length>0&&this.queue.length>0){const worker=this.idle.pop();const{job,id}=this.queue.shift();const original=embeddedJobs.get(job);const memoize=!!original&&original.length===job.svgs.length&&original.every((svg,i)=>svg===job.svgs[i]);worker.postMessage({id,...job,memoize})}}run(job){if(this.failure)return Promise.reject(this.failure);const id=this.nextId++;return new Promise((resolve4,reject)=>{this.pending.set(id,{resolve:resolve4,reject});this.queue.push({job,id});this.pump()})}async close(){this.failure??=new Error("The raster pool was closed.");for(const entry of this.pending.values())entry.reject(this.failure);this.pending.clear();this.queue.length=0;await Promise.all(this.workers.map(worker=>worker.terminate()))}};function defaultPoolSize(){return Math.max(1,Math.min(12,cpus().length-2))}function framesToJob(frames,width,parseBackground,height){const first=frames[0];const scale=width/first.width;const job={svgs:frames.map(frame=>frameToSvg(frame)),width,height:height??Math.round(first.height*scale),bloom:first.dark?first.bloom:0,background:parseBackground(first.background)};if(frames.every(embeddedResources))embeddedJobs.set(job,job.svgs.slice());return job}var clamp01=t=>t<=0?0:t>=1?1:t;var linear=t=>t;function sigmoid(x){return 1/(1+Math.exp(-x))}function smoothBy(inflection){const low=sigmoid(-inflection/2);const high=sigmoid(inflection/2);return t=>{if(t<=0)return 0;if(t>=1)return 1;return(sigmoid(inflection*(t-.5))-low)/(high-low)}}var smooth2=smoothBy(10);var smoother=t=>{const x=clamp01(t);return x*x*x*(x*(x*6-15)+10)};var easeInQuad=t=>t*t;var easeOutQuad=t=>1-(1-t)*(1-t);var easeInCubic=t=>t*t*t;var easeOutCubic=t=>1-Math.pow(1-t,3);var easeInOutCubic=t=>t<.5?4*t*t*t:1-Math.pow(-2*t+2,3)/2;var easeOutQuint=t=>1-Math.pow(1-t,5);var easeInOutQuint=t=>t<.5?16*t*t*t*t*t:1-Math.pow(-2*t+2,5)/2;var easeOutExpo=t=>t>=1?1:1-Math.pow(2,-10*t);var easeInExpo=t=>t<=0?0:Math.pow(2,10*t-10);var rushInto=t=>2*smooth2(t/2);var rushFrom=t=>2*smooth2(t/2+.5)-1;var slowInto=t=>Math.sqrt(Math.max(0,1-(1-t)*(1-t)));function overshoot(amount2=1.70158){return t=>{const x=t-1;return x*x*((amount2+1)*x+amount2)+1}}function spring(options={}){const bounce2=options.bounce??.28;const frequency=options.frequency??2.2;const decay=-Math.log(Math.max(1e-4,bounce2))*2.4;return t=>{if(t<=0)return 0;if(t>=1)return 1;return 1-Math.exp(-decay*t)*Math.cos(frequency*Math.PI*2*t)*(1-t)}}var bounce=t=>{const n=7.5625,d=2.75;if(t<1/d)return n*t*t;if(t<2/d)return n*(t-=1.5/d)*t+.75;if(t<2.5/d)return n*(t-=2.25/d)*t+.9375;return n*(t-=2.625/d)*t+.984375};var thereAndBack=t=>smooth2(t<.5?2*t:2*(1-t));function thereAndBackWithPause(pause=1/3){const a=(1-pause)/2;return t=>{if(t<a)return smooth2(t/a);if(t<1-a)return 1;return smooth2((1-t)/a)}}function wiggle(cycles=2){return t=>thereAndBack(t)*Math.sin(cycles*Math.PI*2*t)}function notQuiteThere(amount2=.7,inner=smooth2){return t=>amount2*inner(t)}function lingering(hold2=.25,inner=smooth2){return t=>inner(clamp01(t/(1-hold2)))}function runningStart(pull=-.5){return t=>{const u=1-t;return 15*u**4*t**2*pull+20*u**3*t**3*pull+15*u**2*t**4+6*u*t**5+t**6}}function during(from,to2,inner=smooth2){return t=>inner(clamp01((t-from)/(to2-from)))}function cubicBezier(x1,y1,x2,y2){const cx=3*x1,bx=3*(x2-x1)-cx,ax=1-cx-bx;const cy=3*y1,by=3*(y2-y1)-cy,ay=1-cy-by;const sampleX=t=>((ax*t+bx)*t+cx)*t;const sampleY=t=>((ay*t+by)*t+cy)*t;const slope=t=>(3*ax*t+2*bx)*t+cx;return x=>{if(x<=0)return 0;if(x>=1)return 1;let t=x;for(let i=0;i<8;i++){const dx=sampleX(t)-x;const d=slope(t);if(Math.abs(dx)<1e-5||Math.abs(d)<1e-6)break;t-=dx/d}return sampleY(t)}}function list(target){return Array.isArray(target)?[...target]:[target]}function run(anim,t0,t1,parent){clock.now=t0;anim.schedule({t0,t1,ease:anim.ease??parent.ease,stage:parent.stage})}function par(...anims){const duration=Math.max(0,...anims.map(a=>a.duration));return{label:"par",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;for(const anim of anims)run(anim,ctx.t0,ctx.t0+anim.duration*k,ctx)}}}function seq(...anims){const duration=anims.reduce((sum,a)=>sum+a.duration,0);return{label:"seq",duration,schedule(ctx){const k=duration>0?(ctx.t1-ctx.t0)/duration:1;let t=ctx.t0;for(const anim of anims){const next=t+anim.duration*k;run(anim,t,next,ctx);t=next}}}}function lagged(anims,options={}){const lag=options.lag??.15;const longest=Math.max(0,...anims.map(a=>a.duration));const natural=anims.length===0?0:longest*(1+(anims.length-1)*lag);return{label:"lagged",duration:options.duration??natural,schedule(ctx){const total=ctx.t1-ctx.t0;const each=anims.length===0?0:total/(1+(anims.length-1)*lag);anims.forEach((anim,i)=>{const start=ctx.t0+i*lag*each;run(anim,start,start+each,ctx)})}}}function delay(anim,seconds){return{label:anim.label,duration:anim.duration+seconds,ease:anim.ease,schedule(ctx){const k=anim.duration+seconds>0?(ctx.t1-ctx.t0)/(anim.duration+seconds):1;run(anim,ctx.t0+seconds*k,ctx.t1,ctx)}}}function retime(anim,options){return{...anim,duration:options.duration??anim.duration,ease:options.ease??anim.ease}}function call(fn){return{label:"call",duration:0,schedule:()=>fn()}}function ensureVisible(node,t,stage){if(!node.mounted){let top=node;while(top.parent&&top.parent!==stage.root)top=top.parent;stage.mountAt(top,t)}for(let n=node;n&&n!==stage.root;n=n.parent){const previous=clock.now;clock.now=t;const visible=n.get("visible");clock.now=previous;if(!visible)n.track("visible").step(t,true)}}function hideAt(node,t){node.track("visible").step(t,false)}function holdUntil(node,t0,start){if(start<=t0)return;node.track("visible").step(t0,false);node.track("visible").step(start,true)}var stepAt=(node,prop,value,t)=>{node.track(prop).step(t,value)};function valueAt(node,prop,t){const previous=clock.now;clock.now=t;const value=node.get(prop);clock.now=previous;return value}function solid2(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function drawable(target){return list(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function drawLeaf(leaf,t0,t1,ease,outline){const d=t1-t0;const fill=leaf.get("fill"),stroke=leaf.get("stroke");const fillTarget=leaf.get("fillOpacity");const strokeTarget=leaf.get("strokeOpacity");if(fill&&!stroke){const width=valueAt(leaf,"strokeWidth",t0);stepAt(leaf,"stroke",solid2(fill),t0);stepAt(leaf,"strokeWidth",outline,t0);stepAt(leaf,"strokeOpacity",1,t0);stepAt(leaf,"trimTo",0,t0);stepAt(leaf,"fillOpacity",0,t0);leaf.tween("trimTo",1,t0,t0+d*.72,ease);leaf.tween("fillOpacity",fillTarget,t0+d*.42,t1,ease);leaf.tween("strokeOpacity",0,t0+d*.62,t1,ease);stepAt(leaf,"stroke",null,t1);stepAt(leaf,"strokeWidth",width,t1);stepAt(leaf,"strokeOpacity",strokeTarget,t1);return}stepAt(leaf,"trimTo",0,t0);leaf.tween("trimTo",1,t0,fill?t0+d*.8:t1,ease);if(fill){stepAt(leaf,"fillOpacity",0,t0);leaf.tween("fillOpacity",fillTarget,t0+d*.5,t1,ease)}}function drawAnim(label,target,options,defaults){const nodes=list(target);const count=drawable(nodes).length;const lag=options.lag??defaults.lag;const natural=options.duration??(count<=1?defaults.duration:Math.min(defaults.duration*2.4,defaults.duration+count*.035));return{label,duration:natural,ease:options.ease,schedule(ctx){for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const leaves=drawable(nodes);if(leaves.length===0)return;const total=ctx.t1-ctx.t0;const each=total/(1+(leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;holdUntil(leaf,ctx.t0,start);drawLeaf(leaf,start,start+each,ctx.ease,defaults.outline)});clock.now=ctx.t0}}}function draw(target,options={}){return drawAnim("draw",target,options,{lag:.04,duration:1.3,outline:2})}function write(target,options={}){return drawAnim("write",target,options,{lag:.22,duration:1.1,outline:1.3})}function erase(target,options={}){const nodes=list(target);return{label:"erase",duration:options.duration??.8,ease:options.ease,schedule(ctx){const leaves=drawable(nodes);const lag=options.lag??.02;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,leaves.length-1)*lag);leaves.forEach((leaf,i)=>{const start=ctx.t0+i*lag*each;clock.now=start;const fill=leaf.get("fill");if(leaf.get("stroke"))leaf.tween("trimFrom",1,start,start+each,ctx.ease);if(fill)leaf.tween("fillOpacity",0,start,start+each*.7,ctx.ease)});for(const node of nodes)hideAt(node,ctx.t1)}}}function fadeIn(target,options={}){const nodes=list(target);return{label:"fadeIn",duration:options.duration??.8,ease:options.ease,schedule(ctx){const items=options.lag!==void 0&&nodes.length===1&&nodes[0].children.length>0?nodes[0].children:nodes;for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,items.length-1)*lag);items.forEach((node,i)=>{const start=ctx.t0+i*lag*each,end=start+each;clock.now=start;holdUntil(node,ctx.t0,start);const opacity=node.get("opacity");stepAt(node,"opacity",0,start);node.tween("opacity",opacity,start,end,ctx.ease);if(options.shift){const x=node.get("x"),y=node.get("y");stepAt(node,"x",x+options.shift[0],start);stepAt(node,"y",y+options.shift[1],start);node.tween("x",x,start,end,ctx.ease);node.tween("y",y,start,end,ctx.ease)}if(options.scale!==void 0)scaleFrom(node,options.scale,start,end,ctx.ease)});clock.now=ctx.t0}}}function scaleFrom(node,factor,t0,t1,ease,about){const previous=clock.now;clock.now=t0;node.pivotAt(about??node.center);const sx=node.get("sx"),sy=node.get("sy");stepAt(node,"sx",sx*factor,t0);stepAt(node,"sy",sy*factor,t0);node.tween("sx",sx,t0,t1,ease);node.tween("sy",sy,t0,t1,ease);clock.now=previous}function fadeOut(target,options={}){const nodes=list(target);return{label:"fadeOut",duration:options.duration??.6,ease:options.ease,schedule(ctx){for(const node of nodes){const opacity=node.get("opacity");node.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);if(options.shift){node.tween("x",node.get("x")+options.shift[0],ctx.t0,ctx.t1,ctx.ease);node.tween("y",node.get("y")+options.shift[1],ctx.t0,ctx.t1,ctx.ease)}if(options.scale!==void 0){node.pivotAt(node.center);node.tween("sx",node.get("sx")*options.scale,ctx.t0,ctx.t1,ctx.ease);node.tween("sy",node.get("sy")*options.scale,ctx.t0,ctx.t1,ctx.ease)}hideAt(node,ctx.t1);stepAt(node,"opacity",opacity,ctx.t1)}}}}function grow(target,options={}){const nodes=list(target);return{label:"grow",duration:options.duration??.9,ease:options.ease,schedule(ctx){for(const node of nodes){ensureVisible(node,ctx.t0,ctx.stage);scaleFrom(node,.001,ctx.t0,ctx.t1,ctx.ease,options.from)}}}}function appear(target){const nodes=list(target);return{label:"appear",duration:0,schedule:ctx=>{for(const node of nodes)ensureVisible(node,ctx.t0,ctx.stage)}}}function vanish(target){const nodes=list(target);return{label:"vanish",duration:0,schedule:ctx=>{for(const node of nodes)hideAt(node,ctx.t0)}}}function to(node,change,options={}){return{label:"to",duration:options.duration??1,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const touched=new Set;clock.capture=touched;try{change(node)}finally{clock.capture=null}for(const entry of touched){const target=entry;const values=new Map(target.overlay);target.overlay.clear();applyChanges(target,values,ctx,options.restore===true)}}}}function applyChanges(node,values,ctx,restore){const{t0,t1,ease}=ctx;const props=values;const restoreValues=new Map;const px=props.get("px"),py=props.get("py");if(px!==void 0||py!==void 0){const nextPx=px??node.get("px"),nextPy=py??node.get("py");const m=compose(node.get("x"),node.get("y"),node.get("rotation"),node.get("sx"),node.get("sy"),node.get("px"),node.get("py"));const[startX,startY]=apply(m,nextPx,nextPy);stepAt(node,"px",nextPx,t0);stepAt(node,"py",nextPy,t0);stepAt(node,"x",startX,t0);stepAt(node,"y",startY,t0);props.delete("px");props.delete("py")}clock.now=t0;for(const[prop,value]of props){const from=node.get(prop);if(from===value)continue;if(restore)restoreValues.set(prop,from);node.tween(prop,value,t0,t1,ease)}for(const[prop,value]of restoreValues)stepAt(node,prop,value,t1)}function moveTo(node,target,options={}){return{...to(node,n=>n.moveTo(target),options),label:"moveTo"}}function shift(node,dx,dy,options={}){return{...to(node,n=>n.shift(dx,dy),options),label:"shift"}}function scaleBy(node,factor,options={}){return{...to(node,n=>n.scale(factor,options.about),options),label:"scale"}}function rotate(node,radians,options={}){return{...to(node,n=>n.rotate(radians,options.about),options),label:"rotate"}}function recolor(node,color,options={}){return{...to(node,n=>n.color(color),options),label:"recolor"}}function fade(node,opacity,options={}){return{...to(node,n=>n.opacity(opacity),{duration:.6,...options}),label:"fade"}}function along2(node,track,options={}){return{label:"along",duration:options.duration??2,ease:options.ease,schedule(ctx){ensureVisible(node,ctx.t0,ctx.stage);const path=track instanceof Node?transformPath(track.get("path")??[],track.worldMatrix()):track;const inverse=node.parent?invertSafe(node.parent.worldMatrix()):null;const position2=alpha3=>{const[x,y]=pointAt(path,alpha3);return inverse?apply(inverse,x,y):[x,y]};const[endX,endY]=position2(1);node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endX,at:a=>position2(a)[0]});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:endY,at:a=>position2(a)[1]});if(options.orient){const angle=alpha3=>{const[dx,dy]=tangentAt(path,alpha3);return Math.atan2(dy,dx)};node.track("rotation").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:angle(1),at:angle})}}}}function invertSafe(m){const det=m[0]*m[3]-m[1]*m[2];if(Math.abs(det)<1e-12)return[1,0,0,1,0,0];const i=1/det;return[m[3]*i,-m[1]*i,-m[2]*i,m[0]*i,(m[2]*m[5]-m[3]*m[4])*i,(m[1]*m[4]-m[0]*m[5])*i]}function warp(target,f,options={}){const nodes=list(target);return{label:"warp",duration:options.duration??2,ease:options.ease,schedule(ctx){for(const leaf of drawable(nodes)){ensureVisible(leaf,ctx.t0,ctx.stage);const path=leaf.get("path");const world=leaf.worldMatrix();const inverse=invertSafe(world);const start=path.map(r=>subdivideEach(r,options.subdivisions??6));const end=warpPath(start,(x,y)=>{const[wx,wy]=apply(world,x,y);const[mx,my]=f(wx,wy);return apply(inverse,mx,my)},1);leaf.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:end,at:alpha3=>start.map((r,i)=>{const a=r.p,b=end[i].p;const out=new Float64Array(a.length);for(let k=0;k<a.length;k++)out[k]=a[k]+(b[k]-a[k])*alpha3;return{p:out,closed:r.closed}})})}}}}function applyMatrix(target,matrix2,options={}){const[ox,oy]=options.origin??[0,0];const flip=options.yUp===false?1:-1;const[[a,b],[c,d]]=matrix2;return{...warp(target,(x,y)=>{const ux=x-ox,uy=(y-oy)*flip;const vx=a*ux+b*uy,vy=c*ux+d*uy;return[ox+vx,oy+vy*flip]},{subdivisions:1,...options}),label:"applyMatrix"}}function chainOpacity(node){let value=1;for(let n=node;n;n=n.parent)value*=n.get("opacity");return value}function bake(leaf){const m=leaf.worldMatrix();const opacity=chainOpacity(leaf);let z=0;let fixed=false;for(let n=leaf;n;n=n.parent){z+=n.get("z");fixed||=n.get("fixed")}return{path:transformPath(leaf.get("path")??[],m),fill:leaf.get("fill"),fillOpacity:leaf.get("fill")?leaf.get("fillOpacity")*opacity:0,stroke:leaf.get("stroke"),strokeOpacity:leaf.get("stroke")?leaf.get("strokeOpacity")*opacity:0,strokeWidth:leaf.get("strokeWidth")*matScale(m),glow:leaf.get("glow"),glowColor:leaf.get("glowColor"),cap:leaf.get("cap"),dash:leaf.get("dash"),z,fixed,key:leaf.data["key"]}}function ghost(stage,from,to2,ctx){const node=new Node;node.base.visible=false;node.base.path=from.path;node.base.cap=from.cap;node.base.z=from.z;node.base.fixed=from.fixed;node.base.fill=from.fill??to2.fill;node.base.stroke=from.stroke??to2.stroke;node.base.fillOpacity=from.fillOpacity;node.base.strokeOpacity=from.strokeOpacity;node.base.strokeWidth=from.strokeWidth||to2.strokeWidth;node.base.glow=from.glow;node.base.glowColor=from.glowColor??to2.glowColor;stage.root.add(node);node.track("visible").initial=false;node.track("visible").keys.length=0;stepAt(node,"visible",true,ctx.appear??ctx.t0);node.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:to2.path,at:pathMixer(from.path,to2.path)});if(from.fill&&to2.fill)node.tween("fill",to2.fill,ctx.t0,ctx.t1,ctx.ease);if(from.stroke&&to2.stroke)node.tween("stroke",to2.stroke,ctx.t0,ctx.t1,ctx.ease);node.tween("fillOpacity",to2.fillOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeOpacity",to2.strokeOpacity,ctx.t0,ctx.t1,ctx.ease);node.tween("strokeWidth",to2.strokeWidth||from.strokeWidth,ctx.t0,ctx.t1,ctx.ease);if(from.glow!==to2.glow)node.tween("glow",to2.glow,ctx.t0,ctx.t1,ctx.ease);stepAt(node,"visible",false,ctx.hide??ctx.t1);return node}function pairCounts(from,to2){const count=Math.max(from.length,to2.length);const pairs=[];for(let i=0;i<count;i++){pairs.push([from[Math.min(from.length-1,Math.floor(i*from.length/count))],to2[Math.min(to2.length-1,Math.floor(i*to2.length/count))]])}return pairs}function morph(from,to2,options={}){const a=list(from),b=list(to2);return{label:"morph",duration:options.duration??1.2,ease:options.ease,schedule(ctx){prepareTargets(b,ctx);const fromLeaves=drawable(a).map(bake);const toLeaves=drawable(b).map(bake);if(fromLeaves.length===0||toLeaves.length===0){for(const node of a)hideAt(node,ctx.t0);for(const node of b)ensureVisible(node,ctx.t0,ctx.stage);return}const pairs=pairCounts(fromLeaves,toLeaves);const lag=options.lag??0;const each=(ctx.t1-ctx.t0)/(1+Math.max(0,pairs.length-1)*lag);pairs.forEach(([x,y],i)=>{const start=ctx.t0+i*lag*each;ghost(ctx.stage,x,y,{t0:start,t1:start+each,ease:ctx.ease,appear:ctx.t0,hide:ctx.t1})});finishMorph(a,b,ctx)}}}function prepareTargets(targets,ctx){clock.now=ctx.t0;for(const node of targets){ctx.stage.mountAt(node,ctx.t0);hideAt(node,ctx.t0)}}function finishMorph(a,b,ctx){for(const node of a)hideAt(node,ctx.t0);for(const node of b)node.track("visible").step(ctx.t1,true);clock.now=ctx.t0}function morphMatching(from,to2,options={}){return{label:"morphMatching",duration:options.duration??1.4,ease:options.ease,schedule(ctx){prepareTargets([to2],ctx);const keyOf=options.key??(leaf=>leaf.data["key"]);const fromLeaves=drawable(from),toLeaves=drawable(to2);const fromBaked=fromLeaves.map(bake),toBaked=toLeaves.map(bake);const pairs=matchSequence(fromLeaves.map(keyOf),toLeaves.map(keyOf));const usedFrom=new Set(pairs.map(([i])=>i)),usedTo=new Set(pairs.map(([,j])=>j));for(const[i,j]of pairs)ghost(ctx.stage,fromBaked[i],toBaked[j],ctx);const span=ctx.t1-ctx.t0;const offset=options.fadeShift??[0,0];const shifted=(bakedPath,dx,dy)=>transformPath(bakedPath,[1,0,0,1,dx,dy]);fromBaked.forEach((baked,i)=>{if(usedFrom.has(i))return;ghost(ctx.stage,baked,{...baked,path:shifted(baked.path,offset[0],offset[1]),fillOpacity:0,strokeOpacity:0},{t0:ctx.t0,t1:ctx.t0+span*.55,ease:ctx.ease})});toBaked.forEach((baked,j)=>{if(usedTo.has(j))return;ghost(ctx.stage,{...baked,path:shifted(baked.path,-offset[0],-offset[1]),fillOpacity:0,strokeOpacity:0},baked,{t0:ctx.t0+span*.35,t1:ctx.t1,ease:ctx.ease})});finishMorph([from],[to2],ctx)}}}function indicate(target,options={}){const nodes=list(target);const anims=nodes.map(node=>retime(to(node,n=>{n.scale(options.scale??1.14);n.color(options.color??"yellow")},{restore:true}),{ease:options.ease??thereAndBack}));return{...par(...anims),label:"indicate",duration:options.duration??.9}}function shake(node,options={}){return{label:"shake",duration:options.duration??.8,ease:wiggle(options.cycles??3),schedule(ctx){clock.now=ctx.t0;const[cx,cy]=node.center;node.pivotAt([cx,cy]);const rotation=node.get("rotation");const angle=options.angle??.08;const track=node.track("rotation");track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:rotation,at:alpha3=>rotation+angle*alpha3})}}}function circumscribe(target,options={}){return{label:"circumscribe",duration:options.duration??1.3,ease:options.ease??linear,schedule(ctx){const b=target.bounds();const pad2=options.pad??14;const outline=new Node(rectPath(b.x-pad2,b.y-pad2,b.width+pad2*2,b.height+pad2*2,options.radius??12)).stroke(options.color??"yellow",options.width??3).glow(8);ctx.stage.add(outline);const t0=ctx.t0,t1=ctx.t1,mid=t0+(t1-t0)*.55;stepAt(outline,"trimTo",0,t0);outline.tween("trimTo",1,t0,mid,smooth2);outline.tween("trimFrom",1,mid-(t1-t0)*.08,t1,smooth2);hideAt(outline,t1)}}}function flash(point,options={}){return{label:"flash",duration:options.duration??.7,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const radius=options.radius??54;const rays=options.rays??12;for(let i=0;i<rays;i++){const angle=i/rays*Math.PI*2;const cos=Math.cos(angle),sin=Math.sin(angle);const ray=new Node(linePath([center2[0]+cos*radius*.35,center2[1]+sin*radius*.35],[center2[0]+cos*radius,center2[1]+sin*radius])).stroke(options.color??"yellow",2.5).glow(5);ctx.stage.add(ray);stepAt(ray,"trimTo",0,ctx.t0);ray.tween("trimTo",1,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.6,ctx.ease);ray.tween("trimFrom",1,ctx.t0+(ctx.t1-ctx.t0)*.25,ctx.t1,ctx.ease);hideAt(ray,ctx.t1)}}}}function ripple(point,options={}){return{label:"ripple",duration:options.duration??1,ease:options.ease??smooth2,schedule(ctx){const center2=point instanceof Node?point.center:point;const ring2=new Node(circlePath(0,0,options.radius??90)).stroke(options.color??"blue",options.width??3).at(center2);ctx.stage.add(ring2);stepAt(ring2,"sx",.05,ctx.t0);stepAt(ring2,"sy",.05,ctx.t0);ring2.tween("sx",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("sy",1,ctx.t0,ctx.t1,ctx.ease);ring2.tween("strokeOpacity",0,ctx.t0+(ctx.t1-ctx.t0)*.2,ctx.t1,ctx.ease);hideAt(ring2,ctx.t1)}}}function pulse(line2,options={}){return{label:"pulse",duration:options.duration??1.1,ease:options.ease??smooth2,schedule(ctx){const path=line2.get("path");if(!path)return;const lit=new Node(transformPath(path,line2.worldMatrix())).stroke(options.color??"yellow",options.width??line2.get("strokeWidth")+1.5).glow(options.glow??10);ctx.stage.add(lit);const length=options.length??.18;stepAt(lit,"trimFrom",0,ctx.t0);stepAt(lit,"trimTo",0,ctx.t0);lit.track("trimTo").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.min(1,a*(1+length))});lit.track("trimFrom").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:1,at:a=>Math.max(0,a*(1+length)-length)});hideAt(lit,ctx.t1)}}}var Value=class{track;constructor(initial){this.track=new Track(initial)}get value(){return this.track.sample(clock.now)}set(value){this.track.step(clock.now,value);return this}to(value,options={}){const track=this.track;return{label:"value",duration:options.duration??1,ease:options.ease,schedule(ctx){const from=track.sample(ctx.t0);track.add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:value,at:a=>from+(value-from)*a})}}}};var ASPECTS={"16:9":[1920,1080],"9:16":[1080,1920],"1:1":[1080,1080],"4:3":[1440,1080],"21:9":[2520,1080]};var Stage=class{root=new Node;camera=new Node;width;height;fps;look;chapters=[];clips=[];captions=[];updaters=[];time=0;ending=0;constructor(options){const[w,h]=ASPECTS[options.aspect??"16:9"];this.width=options.width??w;this.height=options.height??h;this.fps=options.fps??60;this.look=resolveLook(options.look);this.root.mounted=true;this.camera.mounted=true}get right(){return this.width/2}get left(){return-this.width/2}get top(){return-this.height/2}get bottom(){return this.height/2}add(first,...rest){clock.now=this.time;for(const node of[first,...rest]){if(!node.mounted){node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,this.time)}else if(!node.get("visible")){node.track("visible").step(this.time,true)}}return first}mountAt(node,time){if(node.mounted)return;node.parent?.drop(node);node.parent=this.root;this.root.children.push(node);mountTree(node,time)}remove(...nodes){for(const node of nodes)node.track("visible").step(this.time,false)}play(...items){const anims=items.filter(item=>"schedule"in item);const options=items.find(item=>!("schedule"in item))??{};if(anims.length===0)return this;const natural=Math.max(...anims.map(anim=>anim.duration));const duration=options.duration??natural;const t0=this.time;const t1=t0+duration;for(const anim of anims){clock.now=t0;const end=options.duration!==void 0?t1:t0+anim.duration;anim.schedule({t0,t1:end,ease:options.ease??anim.ease??smooth2,stage:this})}this.clips.push({t0,t1,labels:options.label?[options.label]:anims.map(anim=>anim.label)});this.time=t1;this.ending=Math.max(this.ending,t1);clock.now=t1;return this}wait(seconds=1){this.time+=seconds;this.ending=Math.max(this.ending,this.time);clock.now=this.time;return this}at(time,build){const saved=this.time;this.time=time;clock.now=time;build();this.ending=Math.max(this.ending,this.time);this.time=saved;clock.now=saved;return this}chapter(title){this.chapters.push({title,time:this.time});return this}caption(text2,duration=3){this.captions.push({t0:this.time,t1:this.time+duration,text:text2});this.ending=Math.max(this.ending,this.time+duration);return this}value(initial=0){return new Value(initial)}update(node,fn,window2={}){this.updaters.push({node,fn,from:window2.from??this.time,to:window2.to??Infinity});return node}get duration(){return Math.max(this.ending,this.time)}};function film(a,b){const options=typeof a==="function"?{}:a;const build=typeof a==="function"?a:b;if(!build)throw new Error("film(options, build) needs a build function.");const definition={kind:"vizmatic.film",options,build,compile:overrides=>compileFilm(definition,overrides)};return definition}function isFilm(value){return!!value&&typeof value==="object"&&value.kind==="vizmatic.film"}var Suspend=class{constructor(promise){this.promise=promise}promise;isVizmaticSuspend=true};function isSuspend(error){return typeof error==="object"&&error!==null&&error.isVizmaticSuspend===true}var CompiledFilm=class{allowImageNetwork;imageAssets=new Map;imageLoads=new Map;width;height;fps;duration;title;description;look;bloom;background;posterTime;bleed;chapters;clips;captions;stage;constructor(stage,options,overrides){this.allowImageNetwork=(overrides.imageNetwork??options.imageNetwork??"allow")==="allow";this.stage=stage;this.width=stage.width;this.height=stage.height;this.fps=overrides.fps??stage.fps;this.duration=Math.max(stage.duration,1/this.fps);this.title=options.title??"";this.description=options.description??"";this.look=stage.look;this.bloom=overrides.bloom??options.bloom??stage.look.bloom;const background=overrides.background!==void 0?overrides.background:options.background!==void 0?options.background:stage.look.background;this.background=background===null?null:stage.look.colors[background]??background;this.posterTime=options.poster;this.bleed=options.bleed===true;this.chapters=stage.chapters;this.clips=stage.clips;this.captions=stage.captions}get frameCount(){return Math.max(1,Math.round(this.duration*this.fps))}async prepareImage(image2){if(image2.asset){if(!isImageAsset(image2.asset))throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");validateStageImage(image2,image2.asset);return image2.asset}let pending2=this.imageLoads.get(image2.src);if(!pending2){pending2=resolveLegacyImage(image2.src,this.allowImageNetwork).then(asset2=>{this.imageAssets.set(image2.src,asset2);return asset2});this.imageLoads.set(image2.src,pending2)}const asset=await pending2;validateStageImage(image2,asset);return asset}async preloadImages(){for(const node of this.stage.root.all()){const track=node.tracks?.get("image");const images=[node.base.image,track?.initial,...track?.keys.map(key=>key.to)??[]];for(const image2 of images)if(image2)await this.prepareImage(image2)}}frame(time){const t=Math.max(0,Math.min(this.duration,time));const stage=this.stage;const previous={mode:clock.mode,now:clock.now};setColorTokens(stage.look.colors);clock.mode="render";clock.now=t;clock.frame++;try{for(const updater of stage.updaters){if(t>=updater.from&&t<=updater.to)updater.fn(updater.node,t)}const camera=stage.camera;const ops=buildOps(stage.root,{x:camera.get("x"),y:camera.get("y"),zoom:camera.get("sx"),rotation:camera.get("rotation")},stage.width,stage.height);const preparedOps=ops.map(op=>{if(op.kind!=="image")return op;const asset=op.image.asset??this.imageAssets.get(op.image.src);if(!asset)throw new Suspend(this.prepareImage(op.image));if(!isImageAsset(asset))throw new ImageAssetError("Image asset was not prepared by resolveImageAsset.");validateStageImage(op.image,asset);return{...op,image:{...op.image,src:asset.src,asset}}});return{width:stage.width,height:stage.height,background:this.background,bloom:this.bloom,dark:stage.look.dark,ops:preparedOps}}finally{clock.mode=previous.mode;clock.now=previous.now}}svg(time,options={}){return frameToSvg(this.frame(time),options)}};async function compileFilm(definition,overrides={}){const options={...definition.options,...overrides.look?{look:overrides.look}:{},...overrides.fps?{fps:overrides.fps}:{}};for(let attempt=0;attempt<64;attempt++){const stage=new Stage(options);setColorTokens(stage.look.colors);const saved={mode:clock.mode,now:clock.now};clock.mode="compile";clock.now=0;try{await definition.build(stage);clock.mode=saved.mode;clock.now=saved.now;const compiled=new CompiledFilm(stage,options,overrides);await compiled.preloadImages();await probe(compiled);return compiled}catch(error){clock.mode=saved.mode;clock.now=saved.now;clock.capture=null;if(error instanceof Suspend){await error.promise;continue}throw error}}throw new Error("The film kept requesting new assets while compiling.")}async function probe(film2){const samples=[0,.25,.5,.75,1];for(const fraction of samples){for(let attempt=0;attempt<16;attempt++){try{film2.frame(film2.duration*fraction);break}catch(error){if(!(error instanceof Suspend))throw error;await error.promise}}}}function curveFree(contours){return{contours:contours.filter(contour=>contour.length>=8)}}var assetBase=null;function setAssetBase(url){assetBase=url}var isNode=typeof process!=="undefined"&&!!process.versions?.node&&typeof globalThis.document==="undefined";function moduleUrl(){const url=import.meta.url;if(url)return url;return`file://${typeof __filename!=="undefined"?__filename:""}`}async function nodeRead(relative3){const fsName="node:fs/promises",pathName="node:path",urlName="node:url";const[fs,path,url]=await Promise.all([import(fsName),import(pathName),import(urlName)]);let directory=path.dirname(url.fileURLToPath(moduleUrl()));for(let depth=0;depth<6;depth++){const candidate=path.join(directory,"assets",relative3);try{const bytes=await fs.readFile(candidate);return bytes.buffer.slice(bytes.byteOffset,bytes.byteOffset+bytes.byteLength)}catch(error){if(error.code!=="ENOENT")throw error}directory=path.dirname(directory)}throw new Error(`Bundled asset not found: assets/${relative3}`)}async function loadBinaryAsset(relative3){if(isNode)return nodeRead(relative3);const base=assetBase??new URL("./assets/",moduleUrl()).href;const response=await fetch(new URL(relative3,base));const type=response.headers.get("content-type")??"";if(!response.ok||type.includes("text/html")){throw new Error(`Could not load ${relative3} from ${response.url} (HTTP ${response.status}, ${type||"no content type"}). Call setAssetBase() with the folder that holds fonts/.`)}return response.arrayBuffer()}var Reader=class{constructor(bytes,offset=0){this.bytes=bytes;this.offset=offset;this.view=new DataView(bytes)}bytes;offset;view;seek(offset){this.offset=offset;return this}get position(){return this.offset}u8(){return this.view.getUint8(this.offset++)}i8(){return this.view.getInt8(this.offset++)}u16(){const v=this.view.getUint16(this.offset);this.offset+=2;return v}i16(){const v=this.view.getInt16(this.offset);this.offset+=2;return v}u32(){const v=this.view.getUint32(this.offset);this.offset+=4;return v}tag(){let out="";for(let i=0;i<4;i++)out+=String.fromCharCode(this.u8());return out}};function parseFont(bytes){const r=new Reader(bytes);const version=r.u32();if(version!==65536&&version!==1953658213){throw new Error("Stage text needs a TrueType (.ttf) font with glyf outlines.")}const tableCount=r.u16();r.seek(12);const tables=new Map;for(let i=0;i<tableCount;i++){const tag=r.tag();r.u32();tables.set(tag,{offset:r.u32(),length:r.u32()})}const need=tag=>{const table=tables.get(tag);if(!table)throw new Error(`Font is missing its ${tag} table.`);return table};const head=need("head");r.seek(head.offset+18);const unitsPerEm=r.u16();r.seek(head.offset+50);const longLoca=r.i16()===1;const hhea=need("hhea");r.seek(hhea.offset+4);const ascent=r.i16();const descent=r.i16();const lineGap=r.i16();r.seek(hhea.offset+34);const hMetrics=r.u16();r.seek(need("maxp").offset+4);const glyphCount=r.u16();const hmtx=need("hmtx");const loca=need("loca");const glyf=need("glyf");const cmap=parseCmap(r,need("cmap").offset);const kerning=tables.has("GPOS")?parseKerning(r,tables.get("GPOS").offset):()=>0;const advance=glyph=>{const index=Math.min(glyph,hMetrics-1);r.seek(hmtx.offset+index*4);return r.u16()};const outlines=new Map;const contours=(glyph,depth)=>{if(glyph>=glyphCount||depth>6)return[];r.seek(loca.offset+(longLoca?glyph*4:glyph*2));const start=longLoca?r.u32():r.u16()*2;const end=longLoca?r.u32():r.u16()*2;if(start===end)return[];r.seek(glyf.offset+start);const count=r.i16();r.seek(r.position+8);if(count<0)return composite(glyph,depth);const ends=[];for(let i=0;i<count;i++)ends.push(r.u16());const instructionLength=r.u16();r.seek(r.position+instructionLength);const total=(ends[ends.length-1]??-1)+1;const flags=[];while(flags.length<total){const flag=r.u8();flags.push(flag);if(flag&8){let repeat=r.u8();while(repeat-- >0)flags.push(flag)}}const xs=new Array(total);let x=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&2){const dx=r.u8();x+=flag&16?dx:-dx}else if(!(flag&16)){x+=r.i16()}xs[i]=x}const ys=new Array(total);let y=0;for(let i=0;i<total;i++){const flag=flags[i];if(flag&4){const dy=r.u8();y+=flag&32?dy:-dy}else if(!(flag&32)){y+=r.i16()}ys[i]=y}const out=[];let first=0;for(const last of ends){out.push(contourToCubics(xs,ys,flags,first,last));first=last+1}return out};function composite(_glyph,depth){const parts=[];let more=true;while(more){const flags=r.u16();const glyph=r.u16();const words=(flags&1)!==0;const xy=(flags&2)!==0;let dx=0,dy=0;if(words){dx=r.i16();dy=r.i16()}else{dx=r.i8();dy=r.i8()}if(!xy){dx=0;dy=0}let a=1,b=0,c=0,d=1;const f2=()=>r.i16()/16384;if(flags&8){a=d=f2()}else if(flags&64){a=f2();d=f2()}else if(flags&128){a=f2();b=f2();c=f2();d=f2()}parts.push({glyph,m:[a,b,c,d,dx,dy]});more=(flags&32)!==0}const out=[];for(const part of parts){for(const contour of contours(part.glyph,depth+1)){const moved=new Array(contour.length);const[a,b,c,d,e,f]=part.m;for(let i=0;i<contour.length;i+=2){moved[i]=a*contour[i]+c*contour[i+1]+e;moved[i+1]=b*contour[i]+d*contour[i+1]+f}out.push(moved)}}return out}return{unitsPerEm,ascent,descent,lineGap,glyphFor(code){return cmap(code)},advance,kern(left,right){return kerning(left,right)},outline(glyph){if(outlines.has(glyph))return outlines.get(glyph);const raw=contours(glyph,0);const result=raw.length?curveFree(raw):null;outlines.set(glyph,result);return result}}}function contourToCubics(xs,ys,flags,first,last){const count=last-first+1;if(count<2)return[];const at=i=>first+(i%count+count)%count;const on=i=>(flags[at(i)]&1)!==0;let startIndex=0;while(startIndex<count&&!on(startIndex))startIndex++;let sx,sy;if(startIndex===count){sx=(xs[at(0)]+xs[at(count-1)])/2;sy=(ys[at(0)]+ys[at(count-1)])/2;startIndex=0}else{sx=xs[at(startIndex)];sy=ys[at(startIndex)];startIndex+=1}const out=[sx,sy];let cx=sx,cy=sy;let controlX=0,controlY=0,hasControl=false;const quad=(qx,qy,ex,ey)=>{out.push(cx+(qx-cx)*2/3,cy+(qy-cy)*2/3,ex+(qx-ex)*2/3,ey+(qy-ey)*2/3,ex,ey);cx=ex;cy=ey};const line2=(ex,ey)=>{out.push(cx+(ex-cx)/3,cy+(ey-cy)/3,cx+(ex-cx)*2/3,cy+(ey-cy)*2/3,ex,ey);cx=ex;cy=ey};for(let k=0;k<count;k++){const i=startIndex+k;const x=xs[at(i)],y=ys[at(i)];if(on(i)){if(hasControl){quad(controlX,controlY,x,y);hasControl=false}else if(x!==cx||y!==cy){line2(x,y)}}else{if(hasControl)quad(controlX,controlY,(controlX+x)/2,(controlY+y)/2);controlX=x;controlY=y;hasControl=true}}if(hasControl)quad(controlX,controlY,sx,sy);else if(cx!==sx||cy!==sy)line2(sx,sy);return out}function parseCmap(r,offset){r.seek(offset+2);const count=r.u16();let best=-1,bestScore=-1;for(let i=0;i<count;i++){const platform=r.u16();const encoding=r.u16();const sub=r.u32();const score=platform===3&&encoding===10?4:platform===0&&encoding>=4?3:platform===3&&encoding===1?2:platform===0?1:0;if(score>bestScore){bestScore=score;best=offset+sub}}if(best<0)return()=>0;r.seek(best);const format=r.u16();if(format===12){r.seek(best+12);const groups=r.u32();const table=[];for(let i=0;i<groups;i++)table.push([r.u32(),r.u32(),r.u32()]);return code=>{let lo=0,hi=table.length-1;while(lo<=hi){const mid=lo+hi>>1;const[start,end,glyph]=table[mid];if(code<start)hi=mid-1;else if(code>end)lo=mid+1;else return glyph+code-start}return 0}}if(format===4){r.seek(best+6);const segX2=r.u16();const segs=segX2/2;const endsAt=best+14;const startsAt=endsAt+segX2+2;const deltasAt=startsAt+segX2;const rangesAt=deltasAt+segX2;const map=new Map;for(let i=0;i<segs;i++){const end=r.seek(endsAt+i*2).u16();const start=r.seek(startsAt+i*2).u16();const delta=r.seek(deltasAt+i*2).i16();const range=r.seek(rangesAt+i*2).u16();for(let c=start;c<=end&&c!==65535;c++){let glyph;if(range===0)glyph=c+delta&65535;else{const raw=r.seek(rangesAt+i*2+range+(c-start)*2).u16();glyph=raw===0?0:raw+delta&65535}if(glyph)map.set(c,glyph)}}return code=>map.get(code)??0}return()=>0}function parseKerning(r,gpos){const lookups=[];try{r.seek(gpos+6);const featureList=gpos+r.u16();const lookupList=gpos+r.u16();r.seek(featureList);const featureCount=r.u16();const indices=new Set;for(let i=0;i<featureCount;i++){r.seek(featureList+2+i*6);const tag=r.tag();const offset=r.u16();if(tag!=="kern")continue;r.seek(featureList+offset+2);const count=r.u16();for(let k=0;k<count;k++)indices.add(r.u16())}for(const index of[...indices].sort((a,b)=>a-b)){r.seek(lookupList+2+index*2);const lookup=lookupList+r.u16();r.seek(lookup);const lookupType=r.u16();r.u16();const subCount=r.u16();const subs=[];for(let i=0;i<subCount;i++)subs.push(lookup+r.u16());const tables=[];for(const first of subs){let sub=first;let type=lookupType;if(type===9){r.seek(sub+2);type=r.u16();sub+=r.u32()}if(type===2)tables.push(readPairs(r,sub))}lookups.push(tables)}}catch{}const cache2=new Map;return(left,right)=>{const key=left*65536+right;const cached=cache2.get(key);if(cached!==void 0)return cached;let total=0;for(const tables of lookups){for(const table of tables){const value=table(left,right);if(value!==void 0){total+=value;break}}}cache2.set(key,total);return total}}function readCoverage(r,offset){r.seek(offset);const format=r.u16();const out=new Set;if(format===1){const count=r.u16();for(let i=0;i<count;i++)out.add(r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)out.add(glyph)}}return out}function readClasses(r,offset){r.seek(offset);const format=r.u16();const classes=new Map;if(format===1){const start=r.u16();const count=r.u16();for(let i=0;i<count;i++)classes.set(start+i,r.u16())}else if(format===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16(),value=r.u16();for(let glyph=start;glyph<=end;glyph++)classes.set(glyph,value)}}return glyph=>classes.get(glyph)??0}function valueSize(format){let count=0;for(let bit=0;bit<8;bit++)if(format&1<<bit)count++;return count*2}function readAdvance(r,format){let advance=0;if(format&1)r.i16();if(format&2)r.i16();if(format&4)advance=r.i16();if(format&8)r.i16();for(let bit=4;bit<8;bit++)if(format&1<<bit)r.u16();return advance}function readPairs(r,sub){r.seek(sub);const format=r.u16();const coverageOffset=r.u16();const value1=r.u16();const value2=r.u16();const size1=valueSize(value1);const size2=valueSize(value2);if(format===1){const setCount=r.u16();const offsets=[];for(let i=0;i<setCount;i++)offsets.push(r.u16());r.seek(sub+coverageOffset);const coverageFormat=r.u16();const glyphs=[];if(coverageFormat===1){const count=r.u16();for(let i=0;i<count;i++)glyphs.push(r.u16())}else if(coverageFormat===2){const count=r.u16();for(let i=0;i<count;i++){const start=r.u16(),end=r.u16();r.u16();for(let glyph=start;glyph<=end;glyph++)glyphs.push(glyph)}}const sets=new Map;for(let i=0;i<setCount;i++){r.seek(sub+offsets[i]);const count=r.u16();const pairs=new Map;for(let k=0;k<count;k++){const second=r.u16();const advance=readAdvance(r,value1);r.seek(r.position+size2);pairs.set(second,advance)}if(glyphs[i]!==void 0)sets.set(glyphs[i],pairs)}return(left,right)=>sets.get(left)?.get(right)}if(format===2){const class1Offset=r.u16();const class2Offset=r.u16();const class1Count=r.u16();const class2Count=r.u16();const matrix2=r.position;const coverage=readCoverage(r,sub+coverageOffset);const class1=readClasses(r,sub+class1Offset);const class2=readClasses(r,sub+class2Offset);return(left,right)=>{if(!coverage.has(left))return void 0;const c1=class1(left),c2=class2(right);if(c1>=class1Count||c2>=class2Count)return void 0;r.seek(matrix2+c1*class2Count*(size1+size2)+c2*(size1+size2));return readAdvance(r,value1)}}return()=>void 0}var FILES={sans:{"400":"Inter-Regular.ttf","600":"Inter-SemiBold.ttf","700":"Inter-Bold.ttf"},serif:{"400":"InstrumentSerif-Regular.ttf","italic":"InstrumentSerif-Italic.ttf"},"text-serif":{"400":"SourceSerif4-24pt-Regular.ttf","italic":"SourceSerif4-24pt-Italic.ttf"},mono:{"400":"JetBrainsMono-Regular.ttf"},noto:{"400":"NotoSans-Regular.ttf"},math:{"400":"NotoSansMath-Regular.ttf"}};var FALLBACKS={sans:["noto","math"],serif:["text-serif","noto","math"],"text-serif":["noto","math"],mono:["noto","math"],noto:["math"]};var fonts=new Map;var pending=new Map;function fontFor(family,weight=400,italic=false){const files=FILES[family];const file=(italic?files["italic"]:void 0)??files[String(weight)]??files["400"];const loaded=fonts.get(file);if(loaded)return loaded;let waiting=pending.get(file);if(!waiting){waiting=loadBinaryAsset(`fonts/${file}`).then(bytes=>{fonts.set(file,parseFont(bytes));pending.delete(file)});pending.set(file,waiting)}throw new Suspend(waiting)}function fallbackGlyph(family,code,weight=400,italic=false){for(const next of FALLBACKS[family]){const font=fontFor(next,weight,italic);const glyph=font.glyphFor(code);if(glyph!==0)return{font,glyph}}return null}var glyphPaths=new WeakMap;function glyphPath(font,glyph,size){let bySize=glyphPaths.get(font);if(!bySize)glyphPaths.set(font,bySize=new Map);let byGlyph=bySize.get(size);if(!byGlyph)bySize.set(size,byGlyph=new Map);const cached=byGlyph.get(glyph);if(cached)return cached;const outline=font.outline(glyph);const scale=size/font.unitsPerEm;const path=outline?outline.contours.map(contour=>{const out=new Float64Array(contour.length);for(let i=0;i<contour.length;i+=2){out[i]=contour[i]*scale;out[i+1]=-contour[i+1]*scale}return ring(out,true)}):[];byGlyph.set(glyph,path);return path}var TextNode=class extends Node{chars=[];source="";find(fragment){const out=[];const keys=this.chars.map(glyph=>glyph.data["key"]).join("");const needle=fragment.replace(/\s/g,"");for(let at=keys.indexOf(needle);at>=0;at=keys.indexOf(needle,at+1)){out.push(...this.chars.slice(at,at+needle.length))}return out}};function centered(path){const b=pathBounds(path);if(!b)return{path,x:0,y:0};const x=b.x+b.width/2,y=b.y+b.height/2;return{path:transformPath(path,[1,0,0,1,-x,-y]),x,y}}function text(content,options={}){const size=options.size??40;const family=options.font??"sans";const weight=options.weight??400;const italic=options.italic??false;const font=fontFor(family,weight,italic);const scale=size/font.unitsPerEm;const tracking=(options.tracking??0)*size;const leading=(options.leading??1.3)*size;const paint=toPaint(options.color??"ink");const source=options.uppercase?content.toUpperCase():content;const measureWord=word=>{const glyphs=[];let x=0,previous=0,previousFont=null;for(const char of word){const code=char.codePointAt(0);let owner=font,glyph=font.glyphFor(code);if(glyph===0){const found=fallbackGlyph(family,code,weight,italic);if(found){owner=found.font;glyph=found.glyph}}const ownerScale=size/owner.unitsPerEm;if(previous&&previousFont===owner)x+=owner.kern(previous,glyph)*ownerScale;glyphs.push({font:owner,glyph,x,char});x+=owner.advance(glyph)*ownerScale+tracking;previous=glyph;previousFont=owner}return{glyphs,width:x}};const lines=[];const space=font.advance(font.glyphFor(32))*scale+tracking;for(const paragraph of source.split("\n")){let line2=[];let width=0;for(const word of paragraph.split(" ")){const measured=measureWord(word);const gap=line2.length>0?space:0;if(options.maxWidth!==void 0&&line2.length>0&&width+gap+measured.width>options.maxWidth){lines.push({glyphs:line2,width});line2=[];width=0}const offset=width+(line2.length>0?space:0);for(const glyph of measured.glyphs)line2.push({...glyph,x:glyph.x+offset});width=offset+measured.width}lines.push({glyphs:line2,width})}const blockWidth=Math.max(0,...lines.map(line2=>line2.width));const align=options.align??"left";const node=new TextNode;node.source=content;lines.forEach((line2,row)=>{const start=align==="left"?0:align==="center"?(blockWidth-line2.width)/2:blockWidth-line2.width;for(const placed of line2.glyphs){const path=glyphPath(placed.font,placed.glyph,size);if(path.length===0)continue;const shape2=centered(path);const leaf=new Node(shape2.path).at(start+placed.x+shape2.x,row*leading+shape2.y);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=placed.char;if(placed.glyph===0)leaf.data["missingGlyph"]=true;node.chars.push(leaf);node.children.push(leaf);leaf.parent=node}});const ascent=font.ascent*scale;const height=(lines.length-1)*leading;node.base.px=blockWidth/2;node.base.py=height/2-ascent*.36;node.data["size"]=size;return node}function decode(value){return value.replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&apos;/g,"'").replace(/&#(\d+);/g,(_,code)=>String.fromCodePoint(Number(code))).replace(/&#x([\da-fA-F]+);/g,(_,code)=>String.fromCodePoint(parseInt(code,16))).replace(/&amp;/g,"&")}function parseXml(source){const root={name:"#root",attrs:{},children:[],text:""};const stack=[root];const token=/<!--[\s\S]*?-->|<!\[CDATA\[([\s\S]*?)\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE[^>]*>|<\/([\w:.-]+)\s*>|<([\w:.-]+)((?:\s+[\w:.-]+\s*=\s*(?:"[^"]*"|'[^']*'))*)\s*(\/?)>|([^<]+)/g;for(let match=token.exec(source);match;match=token.exec(source)){const top=stack[stack.length-1];const[,cdata,closing,opening,attributes,selfClosing,content]=match;if(cdata!==void 0){top.text+=cdata}else if(closing){if(stack.length>1)stack.pop()}else if(opening){const element={name:opening.replace(/^.*:/,""),attrs:{},children:[],text:""};for(const attr of(attributes??"").matchAll(/([\w:.-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g)){element.attrs[attr[1]]=decode(attr[2]??attr[3]??"")}top.children.push(element);if(!selfClosing)stack.push(element)}else if(content){top.text+=decode(content)}}return root}function parseTransform(value){if(!value)return IDENTITY;let m=IDENTITY;for(const match of value.matchAll(/(matrix|translate|scale|rotate|skewX|skewY)\s*\(([^)]*)\)/g)){const a=match[2].trim().split(/[\s,]+/).filter(Boolean).map(Number);const name=match[1];if(name==="matrix"&&a.length===6)m=mul(m,a);else if(name==="translate")m=mul(m,[1,0,0,1,a[0]??0,a[1]??0]);else if(name==="scale")m=mul(m,[a[0]??1,0,0,a[1]??a[0]??1,0,0]);else if(name==="rotate"){const r=(a[0]??0)*Math.PI/180;const c=Math.cos(r),s=Math.sin(r);const cx=a[1]??0,cy=a[2]??0;m=mul(m,[1,0,0,1,cx,cy]);m=mul(m,[c,s,-s,c,0,0]);m=mul(m,[1,0,0,1,-cx,-cy])}else if(name==="skewX")m=mul(m,[1,0,Math.tan((a[0]??0)*Math.PI/180),1,0,0]);else if(name==="skewY")m=mul(m,[1,Math.tan((a[0]??0)*Math.PI/180),0,1,0,0])}return m}var NOT_DRAWN=new Set(["defs","clipPath","mask","pattern","filter","symbol","marker","linearGradient","radialGradient","title","desc","metadata","style","script"]);var SvgNode=class extends Node{byId=new Map;pictureWidth=0;pictureHeight=0;find(id){const found=this.byId.get(id);if(!found)throw new Error(`The SVG has no element with id ${JSON.stringify(id)}.`);return found}};function parseCssRules(root){const rules=new Map;const visit=element=>{if(element.name==="style"){for(const rule of element.text.matchAll(/([^{}]+)\{([^{}]*)\}/g)){const body=parseStyle(rule[2]);for(const selector of rule[1].split(",")){const key=selector.trim();rules.set(key,{...rules.get(key),...body})}}}element.children.forEach(visit)};visit(root);return rules}function parseStyle(value){const out={};if(!value)return out;for(const part of value.split(";")){const index=part.indexOf(":");if(index>0)out[part.slice(0,index).trim()]=part.slice(index+1).trim()}return out}function safeColor(value){if(!value||value==="none"||value==="transparent")return null;try{return parseColor(value)}catch{return null}}function splitIntoGlyphs(path){const items=path.map(r=>{const b=pathBounds([r]);return{ring:r,b,area:b.width*b.height,owner:-1}});const order=items.map((_,i)=>i).sort((a,b)=>items[b].area-items[a].area);for(let k=0;k<order.length;k++){const inner=items[order[k]];for(let j=k-1;j>=0;j--){const outer=items[order[j]];if(outer.owner!==-1)continue;const inside=inner.b.x>=outer.b.x-.01&&inner.b.y>=outer.b.y-.01&&inner.b.x+inner.b.width<=outer.b.x+outer.b.width+.01&&inner.b.y+inner.b.height<=outer.b.y+outer.b.height+.01;if(inside){inner.owner=order[j];break}}}const glyphs=[];const ownerToGlyph=new Map;items.forEach((item,i)=>{if(item.owner!==-1)return;const glyph={x:item.b.x,rings:[item.ring]};ownerToGlyph.set(i,glyph);glyphs.push(glyph)});items.forEach(item=>{if(item.owner!==-1)ownerToGlyph.get(item.owner)?.rings.push(item.ring)});return glyphs.sort((a,b)=>a.x-b.x).map(glyph=>glyph.rings)}function fromSvg(source,options={}){const root=parseXml(source);const svg=root.children.find(child=>child.name==="svg");if(!svg)throw new Error("fromSvg needs markup with an <svg> element.");const rules=parseCssRules(svg);const defs=new Map;const index=element=>{if(element.attrs["id"])defs.set(element.attrs["id"],element);element.children.forEach(index)};index(svg);const box=(svg.attrs["viewBox"]??"").trim().split(/[\s,]+/).map(Number);const declaredW=parseFloat(svg.attrs["width"]??""),declaredH=parseFloat(svg.attrs["height"]??"");const viewW=box.length===4&&box[2]?box[2]:declaredW||300;const viewH=box.length===4&&box[3]?box[3]:declaredH||150;const viewX=box.length===4?box[0]:0,viewY=box.length===4?box[1]:0;const naturalW=Number.isFinite(declaredW)&&declaredW>0?declaredW:viewW;const naturalH=Number.isFinite(declaredH)&&declaredH>0?declaredH:viewH;let scale=1;if(options.width!==void 0||options.height!==void 0){const sx=options.width!==void 0?options.width/viewW:Infinity;const sy=options.height!==void 0?options.height/viewH:Infinity;scale=Math.min(sx,sy)}else{scale=Math.min(naturalW/viewW,naturalH/viewH)}const center2=options.center??true;const offsetX=center2?-(viewX+viewW/2)*scale:-viewX*scale;const offsetY=center2?-(viewY+viewH/2)*scale:-viewY*scale;const base=[scale,0,0,scale,offsetX,offsetY];const out=new SvgNode;out.pictureWidth=viewW*scale;out.pictureHeight=viewH*scale;const splitting=options.splitGlyphs??true;const keepBackground=options.background??false;let firstShape=true;const gradientOf=(id,m,path)=>{const element=defs.get(id);if(!element)return null;if(element.name==="pattern"){const inner=element.children.find(child=>child.name==="linearGradient");if(inner)return linear2(inner,m,path,true);const fill=element.children.find(child=>child.attrs["fill"]?.startsWith("url(#"));const nested=fill?.attrs["fill"]?.match(/url\(#([^)]+)\)/)?.[1];return nested?gradientOf(nested,m,path):null}if(element.name==="linearGradient")return linear2(element,m,path,element.attrs["gradientUnits"]!=="userSpaceOnUse");if(element.name==="radialGradient"){const stops=stopsOf(element);return stops.length?stops[stops.length-1][1]:null}return null};const stopsOf=element=>{const inherited=element.attrs["href"]??element.attrs["xlink:href"];const source2=element.children.some(child=>child.name==="stop")||!inherited?element:defs.get(inherited.replace(/^#/,""))??element;return source2.children.filter(child=>child.name==="stop").map(stop=>{const style2=parseStyle(stop.attrs["style"]);const offsetRaw=stop.attrs["offset"]??"0";const offset=offsetRaw.endsWith("%")?parseFloat(offsetRaw)/100:parseFloat(offsetRaw);const color=safeColor(style2["stop-color"]??stop.attrs["stop-color"]??"#000000")??[0,0,0,1];const alpha3=parseFloat(style2["stop-opacity"]??stop.attrs["stop-opacity"]??"1");return[offset,[color[0],color[1],color[2],color[3]*alpha3]]})};const linear2=(element,m,path,objectBox)=>{const stops=stopsOf(element);if(stops.length===0)return null;const coordinate=(value,fallback)=>{if(value===void 0)return fallback;return value.endsWith("%")?parseFloat(value)/100:parseFloat(value)};const x1=coordinate(element.attrs["x1"],0),y1=coordinate(element.attrs["y1"],0);const x2=coordinate(element.attrs["x2"],1),y2=coordinate(element.attrs["y2"],0);let from,to2;if(objectBox){const b=pathBounds(path)??{x:0,y:0,width:1,height:1};from=[b.x+x1*b.width,b.y+y1*b.height];to2=[b.x+x2*b.width,b.y+y2*b.height]}else{from=apply(m,x1,y1);to2=apply(m,x2,y2)}return{type:"linear",from,to:to2,stops}};const shapePath=element=>{const a=element.attrs;const num=(key,fallback=0)=>{const value=parseFloat(a[key]??"");return Number.isFinite(value)?value:fallback};switch(element.name){case"path":return a["d"]?parseSvgPath(a["d"]):null;case"rect":{const w=num("width"),h=num("height");if(w<=0||h<=0)return null;return rectPath(num("x"),num("y"),w,h,num("rx",num("ry")))}case"circle":return num("r")>0?arcPath(num("cx"),num("cy"),num("r"),num("r"),0,Math.PI*2):null;case"ellipse":return num("rx")>0&&num("ry")>0?arcPath(num("cx"),num("cy"),num("rx"),num("ry"),0,Math.PI*2):null;case"line":return polyPath([[num("x1"),num("y1")],[num("x2"),num("y2")]]);case"polyline":case"polygon":{const values=(a["points"]??"").trim().split(/[\s,]+/).filter(Boolean).map(Number);const points=[];for(let i=0;i+1<values.length;i+=2)points.push([values[i],values[i+1]]);return points.length>=2?polyPath(points,element.name==="polygon"):null}default:return null}};const styleOf=(element,inherited)=>{const a=element.attrs;const cls=(a["class"]??"").split(/\s+/).filter(Boolean);const merged={...rules.get(element.name)};for(const name of cls)Object.assign(merged,rules.get(`.${name}`));if(a["id"])Object.assign(merged,rules.get(`#${a["id"]}`));const pick=key=>parseStyle(a["style"])[key]??a[key]??merged[key];const style2={...inherited};const color=pick("color");if(color)style2.color=color;const fill=pick("fill");if(fill)style2.fill=fill==="currentColor"?style2.color:fill;const stroke=pick("stroke");if(stroke)style2.stroke=stroke==="currentColor"?style2.color:stroke;const width=pick("stroke-width");if(width!==void 0)style2.strokeWidth=parseFloat(width)||0;const fo=pick("fill-opacity");if(fo!==void 0)style2.fillOpacity=parseFloat(fo);const so=pick("stroke-opacity");if(so!==void 0)style2.strokeOpacity=parseFloat(so);const cap=pick("stroke-linecap");if(cap==="round"||cap==="butt"||cap==="square")style2.cap=cap;const join4=pick("stroke-linejoin");if(join4==="round"||join4==="miter"||join4==="bevel")style2.join=join4;const dash=pick("stroke-dasharray");if(dash!==void 0)style2.dash=dash==="none"?null:dash.trim().split(/[\s,]+/).map(Number);const dashOffset=pick("stroke-dashoffset");if(dashOffset!==void 0)style2.dashOffset=parseFloat(dashOffset)||0;const size=pick("font-size");if(size!==void 0)style2.fontSize=parseFloat(size)||style2.fontSize;const anchor=pick("text-anchor");if(anchor)style2.anchor=anchor;return{style:style2,opacity:parseFloat(pick("opacity")??"1")}};const leafFrom=(path,m,element,style2)=>{const world=transformPath(path,m);const scaleOf=matScale(m);const url=value=>value?.match(/^url\(#([^)]+)\)/)?.[1];const fillId=url(style2.fill),strokeId=url(style2.stroke);const fill=fillId?gradientOf(fillId,m,world):safeColor(style2.fill);const stroke=strokeId?gradientOf(strokeId,m,world):safeColor(style2.stroke);const visibleFill=fill&&style2.fillOpacity>0&&!(Array.isArray(fill)&&fill[3]===0);const visibleStroke=stroke&&style2.strokeOpacity>0&&style2.strokeWidth>0&&!(Array.isArray(stroke)&&stroke[3]===0);if(!visibleFill&&!visibleStroke)return[];const clippedStroke=element.attrs["clip-path"]?.5:1;const pieces=splitting&&visibleFill&&!visibleStroke&&world.length>1?splitIntoGlyphs(world):[world];return pieces.map(piece=>{const b=pathBounds(piece)??{x:0,y:0,width:0,height:0};const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(piece,[1,0,0,1,-cx,-cy])).at(cx,cy);if(visibleFill){leaf.base.fill=shiftPaint(fill,-cx,-cy);leaf.base.fillOpacity=style2.fillOpacity}if(visibleStroke){leaf.base.stroke=shiftPaint(stroke,-cx,-cy);leaf.base.strokeWidth=style2.strokeWidth*scaleOf*clippedStroke;leaf.base.strokeOpacity=style2.strokeOpacity;leaf.base.cap=style2.cap;leaf.base.join=style2.join;if(style2.dash)leaf.base.dash=style2.dash.map(value=>value*scaleOf);leaf.base.dashOffset=style2.dashOffset*scaleOf}leaf.base.trimEach=true;return leaf})};const walk2=(element,parent,inherited,parentMatrix)=>{if(NOT_DRAWN.has(element.name))return;if(element.attrs["filter"])return;const{style:style2,opacity}=styleOf(element,inherited);const m=mul(parentMatrix,parseTransform(element.attrs["transform"]));const register=node=>{if(element.attrs["id"])out.byId.set(element.attrs["id"],node)};if(element.name==="g"||element.name==="svg"||element.name==="a"){const group3=new Node;if(opacity<1)group3.base.opacity=opacity;register(group3);parent.add(group3);for(const child of element.children)walk2(child,group3,style2,m);return}if(element.name==="use"){const href=(element.attrs["href"]??element.attrs["xlink:href"]??"").replace(/^#/,"");const referenced=defs.get(href);if(!referenced)return;const placed=mul(m,[1,0,0,1,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0]);const group3=new Node;if(opacity<1)group3.base.opacity=opacity;parent.add(group3);if(referenced.name==="symbol")for(const child of referenced.children)walk2(child,group3,style2,placed);else walk2(referenced,group3,style2,placed);return}if(element.name==="image"){const href=element.attrs["href"]??element.attrs["xlink:href"];if(!href)return;const width=parseFloat(element.attrs["width"]??"0"),height=parseFloat(element.attrs["height"]??"0");const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const unit=matScale(m);const image2={src:href,width,height};const node=new Node().at(x,y);node.base.image=image2;node.base.sx=unit;node.base.sy=unit;if(opacity<1)node.base.opacity=opacity;register(node);parent.add(node);return}if(element.name==="text"){const body=(element.text+element.children.map(child=>child.text).join("")).trim();if(!body)return;const color=safeColor(style2.fill)??[0,0,0,1];const size=style2.fontSize*matScale(m);const label=text(body,{size,color});const[x,y]=apply(m,parseFloat(element.attrs["x"]??"0")||0,parseFloat(element.attrs["y"]??"0")||0);const half=label.get("px");label.at(style2.anchor==="middle"?x:style2.anchor==="end"?x-half:x+half,y-size*.34);if(opacity<1)label.base.opacity=opacity;register(label);parent.add(label);return}const path=shapePath(element);if(!path||path.length===0)return;const isBackground=firstShape&&element.name==="rect"&&!keepBackground&&parseFloat(element.attrs["width"]??"0")>=viewW-.5&&parseFloat(element.attrs["height"]??"0")>=viewH-.5;firstShape=false;if(isBackground)return;const leaves=leafFrom(path,m,element,style2);if(leaves.length===0)return;if(leaves.length===1){if(opacity<1)leaves[0].base.opacity=opacity;register(leaves[0]);parent.add(leaves[0]);return}const group2=new Node;if(opacity<1)group2.base.opacity=opacity;group2.add(...leaves);register(group2);parent.add(group2)};const initial={fill:"#000000",stroke:null,strokeWidth:1,fillOpacity:1,strokeOpacity:1,cap:"butt",join:"miter",dash:null,dashOffset:0,color:"#000000",fontSize:16,anchor:"start"};const{style}=styleOf(svg,initial);for(const child of svg.children)walk2(child,out,style,base);return out}function shiftPaint(paint,dx,dy){if(Array.isArray(paint))return paint;const gradient=paint;if(gradient.type==="linear"){return{...gradient,from:[gradient.from[0]+dx,gradient.from[1]+dy],to:[gradient.to[0]+dx,gradient.to[1]+dy]}}if(gradient.type==="radial")return{...gradient,center:[gradient.center[0]+dx,gradient.center[1]+dy]};return gradient}var QUALITY={draft:{crf:26,vp9Crf:40,preset:"veryfast",motionBlur:1},standard:{crf:18,vp9Crf:31,preset:"medium",motionBlur:1},high:{crf:15,vp9Crf:24,preset:"slow",motionBlur:4},master:{crf:11,vp9Crf:15,preset:"slow",motionBlur:8}};var DEFAULT_GIF_WIDTH=960;var DEFAULT_GIF_FPS=25;var GIF_PALETTE_FRAMES=12;var GIF_PALETTE_PIXELS=1<<19;var MAX_GIF_DELAY=655350;async function resolveFilm(film2,overrides){return isFilm(film2)?film2.compile(overrides):film2}function frameAt(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt(film2,time))}}function backgroundBytes(color){if(!color)return[0,0,0];const rgba=parseColor(color);return[rgba[0],rgba[1],rgba[2]]}function outputSize(film2,requested){const width=requested??film2.width;if(!Number.isInteger(width)||width<2)throw new Error(`Output width must be an integer of at least 2, but received ${width}.`);return{width,height:Math.max(1,Math.round(width*film2.height/film2.width))}}function evenSize(film2,requested){const{width,height}=outputSize(film2,requested);return{width:width+width%2,height:Math.max(2,height+height%2)}}function timeRange(film2,options){const from=Math.max(0,options.from??0);const to2=Math.min(film2.duration,options.to??film2.duration);if(!Number.isFinite(from)||!Number.isFinite(to2)||to2<=from){throw new Error(`The render range ${from}:${to2} is empty. The film is ${film2.duration.toFixed(2)} seconds long.`)}return{from,to:to2}}function planRender(width,height,motionBlur,options={}){const frameBytes=width*height*4;const budget=options.memoryBudget??Math.min(2*1024**3,totalmem()*.25);const requested=Math.max(1,Math.floor(options.workers??defaultPoolSize()));const perWorker=frameBytes*(motionBlur>1?motionBlur+4:3)+rasterMemoBytes(width,height);const workers=Math.max(1,Math.min(requested,Math.floor(budget*.75/perWorker)));const extra=Math.floor(budget*.25/frameBytes);return{workers,readAhead:Math.max(workers+1,Math.min(workers*2,workers+extra))}}function frameStream(film2,pool,timeOf,size,count,readAhead,subframes=1,shutterSpan=0){const inFlight=new Map;const submit=async index=>{const base=timeOf(index);const frames=[];for(let sub=0;sub<subframes;sub++){frames.push(await frameAt(film2,base+sub/subframes*shutterSpan))}return pool.run(framesToJob(frames,size.width,backgroundBytes,size.height))};return async index=>{for(let ahead=index;ahead<Math.min(count,index+readAhead);ahead++){if(inFlight.has(ahead))continue;const job=submit(ahead);job.catch(()=>{});inFlight.set(ahead,job)}const pixels=await inFlight.get(index);inFlight.delete(index);return pixels}}function filmEncoderSettings(quality="standard"){const settings=QUALITY[quality];if(!settings)throw new Error(`Unknown quality: ${quality}. Use draft, standard, high, or master.`);return{crf:settings.crf,preset:settings.preset,tune:"animation"}}async function renderFilmVideo(film2,outputPath,options={}){const compiled=await resolveFilm(film2,options);const quality=QUALITY[options.quality??"standard"];if(!quality)throw new Error(`Unknown quality: ${options.quality}. Use draft, standard, high, or master.`);const size=evenSize(compiled,options.width);const motionBlur=Math.max(1,Math.floor(options.motionBlur??quality.motionBlur));const shutter=options.shutter??.5;const fps=compiled.fps;const codec=options.codec??"h264";const{from,to:to2}=timeRange(compiled,options);const plan=planRender(size.width,size.height,motionBlur,options);const pool=new RasterPool(plan.workers);try{const count=Math.max(1,Math.round((to2-from)*fps));const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead,motionBlur,shutter/fps);const output=await renderRgbaVideo(info=>next(info.index),{width:size.width,height:size.height,fps,duration:(to2-from)*1e3,outputPath,codec,crf:codec==="vp9"?quality.vp9Crf:quality.crf,preset:quality.preset,tune:codec==="h264"?filmEncoderSettings(options.quality).tune:void 0,threads:options.threads??6,audioPath:options.audioPath,audioOffset:from>0?from:void 0,ffmpegPath:options.ffmpegPath,title:compiled.title,chapters:options.chapters===false?[]:shiftedChapters(compiled,from),captions:options.embedCaptions===false?[]:compiled.captions.map(cue=>({t0:cue.t0-from,t1:cue.t1-from,text:cue.text})),signal:options.signal,onProgress:options.onProgress});return{...output,title:compiled.title,workers:pool.size,motionBlur,codec}}finally{await pool.close()}}function shiftedChapters(film2,from){const sorted=[...film2.chapters].sort((a,b)=>a.time-b.time);const running=sorted.filter(chapter=>chapter.time<=from).pop();const later=sorted.filter(chapter=>chapter.time>from).map(chapter=>({title:chapter.title,time:chapter.time-from}));return running?[{title:running.title,time:0},...later]:later}var gifApi=typeof gifenc2.GIFEncoder==="function"?gifenc2:gifenc2.default;function changedRegion(previous,current,width,height){let minX=width,minY=height,maxX=-1,maxY=-1;for(let y=0;y<height;y++){const row=y*width*4;for(let x=0;x<width;x++){const o=row+x*4;if(previous[o]!==current[o]||previous[o+1]!==current[o+1]||previous[o+2]!==current[o+2]){if(x<minX)minX=x;if(x>maxX)maxX=x;if(y<minY)minY=y;maxY=y}}}return maxX<0?null:{x:minX,y:minY,width:maxX-minX+1,height:maxY-minY+1}}function cropRegion(pixels,canvasWidth,region){const out=new Uint8Array(region.width*region.height*4);for(let y=0;y<region.height;y++){const start=((region.y+y)*canvasWidth+region.x)*4;out.set(pixels.subarray(start,start+region.width*4),y*region.width*4)}return out}async function renderFilmGif(film2,outputPath,options={}){const compiled=await resolveFilm(film2,{...options,fps:void 0});const size=outputSize(compiled,options.width??Math.min(DEFAULT_GIF_WIDTH,compiled.width));const fps=Math.min(options.fps??DEFAULT_GIF_FPS,50);const{from,to:to2}=timeRange(compiled,options);const count=Math.max(1,Math.round((to2-from)*fps));const delay2=1e3/fps;const plan=planRender(size.width,size.height,1,options);const pool=new RasterPool(plan.workers);try{const sampleCount=Math.min(count,GIF_PALETTE_FRAMES);const samples=await Promise.all(Array.from({length:sampleCount},async(_,i)=>{const index=Math.floor((i+.5)*count/sampleCount);return pool.run(framesToJob([await frameAt(compiled,from+index/fps)],size.width,backgroundBytes,size.height))}));const perFrame=Math.max(1,Math.floor(GIF_PALETTE_PIXELS/sampleCount));const combined=new Uint8Array(perFrame*sampleCount*4);samples.forEach((pixels,i)=>{const total=pixels.length/4;for(let k=0;k<perFrame;k++){const at=Math.floor((k+.5)*total/perFrame)*4;combined.set(pixels.subarray(at,at+4),(i*perFrame+k)*4)}});const palette=gifApi.quantize(combined,256,{format:"rgb565"});const gif=gifApi.GIFEncoder();const next=frameStream(compiled,pool,index=>from+index/fps,size,count,plan.readAhead);const repeat=options.loop===false?-1:0;let previous=null;let pending2=null;const flush=first=>{if(!pending2)return;let remaining=pending2.delay;let includePalette=first;do{const span=Math.min(MAX_GIF_DELAY,remaining);const start=gif.bytesView().length;gif.writeFrame(pending2.index,pending2.region.width,pending2.region.height,{...includePalette?{palette}:{},delay:Math.max(20,span),repeat,dispose:1});if(pending2.region.x!==0||pending2.region.y!==0){const bytes=gif.bytesView();const descriptor=start+8;if(bytes[descriptor]!==44)throw new Error("The GIF encoder wrote an unexpected frame layout.");bytes[descriptor+1]=pending2.region.x&255;bytes[descriptor+2]=pending2.region.x>>8&255;bytes[descriptor+3]=pending2.region.y&255;bytes[descriptor+4]=pending2.region.y>>8&255}includePalette=false;remaining-=span}while(remaining>0)};let wroteAny=false;for(let i=0;i<count;i++){options.signal?.throwIfAborted();const pixels=await next(i);const region=previous?changedRegion(previous,pixels,size.width,size.height):{x:0,y:0,width:size.width,height:size.height};if(!region){if(pending2)pending2.delay+=delay2}else{flush(!wroteAny);if(pending2)wroteAny=true;const cropped=region.width===size.width&&region.height===size.height?pixels:cropRegion(pixels,size.width,region);pending2={index:gifApi.applyPalette(cropped,palette,"rgb565"),region,delay:delay2};previous=pixels}await options.onProgress?.({index:i,count,time:i*delay2,duration:count*delay2,progress:i/count,fps})}flush(!wroteAny);gif.finish();const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,gif.bytesView());return{width:size.width,height:size.height,frameCount:count,duration:count*delay2,fps,bytes:(await stat(path)).size,outputPath:path,title:compiled.title}}finally{await pool.close()}}async function renderFilmFrame(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const{width,height}=outputSize(compiled,options.width);const pool=new RasterPool(1);try{const frame=await frameAt(compiled,time);const pixels=await pool.run(framesToJob([frame],width,backgroundBytes,height));const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});await writeFile2(path,encodePng({width,height,data:pixels,depth:8,channels:4}));return{width,height,outputPath:path}}finally{await pool.close()}}async function renderFilmSvg(film2,time,outputPath,options={}){const compiled=await resolveFilm(film2,options);const path=resolve(outputPath);await mkdir2(dirname2(path),{recursive:true});const frame=await frameAt(compiled,time);const scale=(options.width??compiled.width)/compiled.width;await writeFile2(path,frameToSvg(frame,{scale}));return{width:Math.round(compiled.width*scale),height:Math.round(compiled.height*scale),outputPath:path}}async function posterTime(film2){if(film2.posterTime!==void 0)return Math.max(0,Math.min(film2.duration,film2.posterTime));const active=t=>film2.clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;const candidates=new Set;for(const clip of film2.clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))candidates.add(t)}if(candidates.size===0)for(let i=1;i<=10;i++)candidates.add(film2.duration*i/10-nudge);const scored=[];for(const time of[...candidates].sort((a,b)=>a-b)){const frame=await frameAt(film2,time);scored.push({time,ink:frame.ops.length})}const fullest=Math.max(...scored.map(entry=>entry.ink));const rich=scored.filter(entry=>entry.ink>=fullest*.75);return rich[rich.length-1]?.time??film2.duration}function captionsToVtt(film2){const stamp=seconds=>{const m=Math.floor(seconds/60),s=seconds-m*60;return`${String(m).padStart(2,"0")}:${s.toFixed(3).padStart(6,"0")}`};const cues=film2.captions.map(cue=>`${stamp(cue.t0)} --> ${stamp(cue.t1)}
130
152
  ${cue.text}`);return`WEBVTT
131
153
 
132
154
  ${cues.join("\n\n")}
133
- `}var EDGE_TOLERANCE=1;var MIN_ALPHA=.08;var MIN_TEXT_ALPHA=.15;var MIN_OVERLAP=.12;var GLYPH_INSET=.12;var MIN_RESTING_MOMENTS=5;var AUTO_SAMPLES=12;var CUBIC_STEPS=6;var CROSSING_ERROR_WIDTH=2;var BLANK_ALPHA=.25;var BLANK_EDGE_SECONDS=.5;var BLANK_MIN_SECONDS=.2;var CROSSING_ERROR_CONTRAST=2;var MIN_STROKE_CONTRAST=1.6;var OPAQUE=.9;function solid3(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function luminance(color){const channel=value=>{const x=value/255;return x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*channel(color[0])+.7152*channel(color[1])+.0722*channel(color[2])}function contrastOver(color,alpha3,background){const a=color[3]*alpha3;const mixed=[color[0]*a+background[0]*(1-a),color[1]*a+background[1]*(1-a),color[2]*a+background[2]*(1-a),1];const x=luminance(mixed),y=luminance(background);return(Math.max(x,y)+.05)/(Math.min(x,y)+.05)}function pad(bounds4,amount2){return{x:bounds4.x-amount2,y:bounds4.y-amount2,width:bounds4.width+amount2*2,height:bounds4.height+amount2*2}}function inset(bounds4,fraction){const dx=bounds4.width*fraction,dy=bounds4.height*fraction;return{x:bounds4.x+dx,y:bounds4.y+dy,width:bounds4.width-dx*2,height:bounds4.height-dy*2}}function intersects(a,b){return a.x<b.x+b.width&&b.x<a.x+a.width&&a.y<b.y+b.height&&b.y<a.y+a.height}function intersection(a,b){const x=Math.max(a.x,b.x),y=Math.max(a.y,b.y);const right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return right>x&&bottom>y?{x,y,width:right-x,height:bottom-y}:null}function contains(outer,inner){return outer.x<=inner.x&&outer.y<=inner.y&&outer.x+outer.width>=inner.x+inner.width&&outer.y+outer.height>=inner.y+inner.height}function union(a,b){const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function segmentHitsBox(x0,y0,x1,y1,box){let t0=0,t1=1;const dx=x1-x0,dy=y1-y0;const edges=[[-dx,x0-box.x],[dx,box.x+box.width-x0],[-dy,y0-box.y],[dy,box.y+box.height-y0]];for(const[p,q]of edges){if(p===0){if(q<0)return false}else{const r=q/p;if(p<0){if(r>t1)return false;if(r>t0)t0=r}else{if(r<t0)return false;if(r<t1)t1=r}}}return t0<=t1}function strokeHitsBox(path,box){for(const r of path){const p=r.p;for(let o=0;o+7<p.length;o+=6){const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3];const x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];const left=Math.min(x0,x1,x2,x3),right=Math.max(x0,x1,x2,x3);const top=Math.min(y0,y1,y2,y3),bottom=Math.max(y0,y1,y2,y3);if(right<box.x||left>box.x+box.width||bottom<box.y||top>box.y+box.height)continue;let lastX=x0,lastY=y0;for(let k=1;k<=CUBIC_STEPS;k++){const t=k/CUBIC_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;if(segmentHitsBox(lastX,lastY,x,y,box))return true;lastX=x;lastY=y}}}return false}function textBlockOf(node){return node.data["key"]!==void 0?node.parent:null}function isGlyph(op){return!!op.node&&op.node.data["key"]!==void 0}function sourceOf(node){const source=node.source;return typeof source==="string"?source:""}function ownerKey(node){if(!node)return"unknown";let current=node;while(current.parent&&current.parent.parent)current=current.parent;return current.mounted?String(current.id):"dynamic"}function restingMoments(film2,samples){const times=new Set;const clips=film2.clips;const active=t=>clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;for(const clip of clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))times.add(t)}times.add(Math.max(0,film2.duration-nudge));for(let i=0;i<samples;i++)times.add((i+.5)/samples*film2.duration);if(times.size<MIN_RESTING_MOMENTS){for(let i=0;i<AUTO_SAMPLES;i++){const t=(i+.5)/AUTO_SAMPLES*film2.duration;if(!active(t))times.add(t)}}return[...times].sort((a,b)=>a-b)}function frameAt2(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt2(film2,time))}}function zoomAt(film2,time){const camera=film2.stage.camera;const track=camera.tracks?.get("sx");return track?track.sample(time):camera.base.sx}function inspect(frame,time,zoomed,bleed){const findings=[];const{width,height,ops}=frame;const background=frame.background?parseColor(frame.background):frame.dark?[0,0,0,1]:[255,255,255,1];const canvas2={x:0,y:0,width,height};const blocks=new Map;const fills=[];const strokes=[];const off=new Map;let outsideMarks=0;ops.forEach((op,order)=>{if(op.kind!=="path"||op.path.length===0)return;const glyph=isGlyph(op);const alpha3=Math.max(op.fillAlpha,op.strokeAlpha);if(alpha3<MIN_ALPHA)return;const shape2=pathBounds(op.path);if(!shape2)return;const box=op.stroke?pad(shape2,op.strokeWidth/2):shape2;const block=glyph?textBlockOf(op.node):null;const outside=box.x<-EDGE_TOLERANCE||box.y<-EDGE_TOLERANCE||box.x+box.width>width+EDGE_TOLERANCE||box.y+box.height>height+EDGE_TOLERANCE;const spansFrame=box.x<=0&&box.x+box.width>=width||box.y<=0&&box.y+box.height>=height;if(outside&&(glyph||!spansFrame&&!zoomed&&!bleed)){const visible=intersects(box,canvas2);const text2=block?sourceOf(block):void 0;const key=glyph?`text:${text2}`:"marks";const existing=off.get(key);const severity=glyph&&visible&&!zoomed?"error":"warning";if(existing){existing.box=union(existing.box,box);if(!glyph)outsideMarks+=1}else{if(!glyph)outsideMarks=1;off.set(key,{key:`film.off_canvas:${key}`,code:"film.off_canvas",severity,time,box,message:glyph?`Text ${JSON.stringify(text2??"")} runs off the canvas${visible?" and is clipped":""}.`:"",...text2?{text:text2}:{}})}}if(glyph&&op.node.data["missingGlyph"]&&op.fillAlpha>=MIN_TEXT_ALPHA){const char=String(op.node.data["key"]);const code=`U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`;const text2=block?sourceOf(block):"";findings.push({key:`film.missing_glyph:${text2}:${code}`,code:"film.missing_glyph",severity:"error",time,box:shape2,message:`Text ${JSON.stringify(text2)} has a character that no bundled font can draw (${code}). It renders as an empty box.`,text:text2})}if(glyph&&block&&op.fillAlpha>=MIN_TEXT_ALPHA){let entry=blocks.get(block);if(!entry)blocks.set(block,entry={id:block,source:sourceOf(block),bounds:shape2,glyphs:[]});entry.bounds=union(entry.bounds,shape2);entry.glyphs.push({box:shape2,order})}else if(!glyph){if(op.fill&&op.fillAlpha>=OPAQUE&&solid3(op.fill)[3]>=OPAQUE&&op.path.some(r=>r.closed))fills.push({order,bounds:shape2});if(op.stroke&&op.strokeAlpha>=MIN_ALPHA&&op.strokePath.length>0){const contrast=contrastOver(solid3(op.stroke),op.strokeAlpha,background);if(contrast>=MIN_STROKE_CONTRAST)strokes.push({op,order,contrast})}}});const marks=off.get("marks");if(marks)marks.message=`${outsideMarks===1?"A mark extends":`${outsideMarks} marks extend`} past the ${width}x${height} canvas.`;findings.push(...off.values());const occluded=(lower,upper,box)=>fills.some(fill=>fill.order>lower&&fill.order<upper&&contains(fill.bounds,box));const list3=[...blocks.values()];for(let i=0;i<list3.length;i++){const a=list3[i];for(let j=i+1;j<list3.length;j++){const b=list3[j];if(!intersects(a.bounds,b.bounds))continue;let hit=null;for(const ga of a.glyphs){if(!intersects(ga.box,b.bounds))continue;for(const gb of b.glyphs){const shared=intersection(ga.box,gb.box);if(!shared)continue;const smaller=Math.min(ga.box.width*ga.box.height,gb.box.width*gb.box.height);if(smaller<=0||shared.width*shared.height/smaller<MIN_OVERLAP)continue;if(occluded(Math.min(ga.order,gb.order),Math.max(ga.order,gb.order),ga.order<gb.order?ga.box:gb.box))continue;hit=hit?union(hit,shared):shared}}if(hit){findings.push({key:`film.text_overlap:${a.source}|${b.source}`,code:"film.text_overlap",severity:"error",time,box:hit,message:`Text ${JSON.stringify(a.source)} overlaps text ${JSON.stringify(b.source)}.`,text:a.source,other:b.source})}}}for(const block of list3){for(const{op,order,contrast}of strokes){const strokeBox=pathBounds(op.strokePath);if(!strokeBox||!intersects(pad(strokeBox,op.strokeWidth),block.bounds))continue;let hit=null;for(const glyph of block.glyphs){const target=inset(glyph.box,GLYPH_INSET);if(!intersects(strokeBox,target))continue;if(!strokeHitsBox(op.strokePath,target))continue;if(order<glyph.order&&occluded(order,glyph.order,glyph.box))continue;hit=hit?union(hit,glyph.box):glyph.box}if(hit){const strong=op.strokeWidth>=CROSSING_ERROR_WIDTH&&contrast>=CROSSING_ERROR_CONTRAST;findings.push({key:`film.text_crossed:${block.source}:${ownerKey(op.node)}`,code:"film.text_crossed",severity:strong?"error":"warning",time,box:hit,message:`A stroke crosses text ${JSON.stringify(block.source)}.`,text:block.source})}}}return findings}function hasContent(frame,top){return frame.ops.some(op=>{if(op.kind!=="path")return op.alpha>=BLANK_ALPHA;const filled=op.fill!==null&&op.fillAlpha>=BLANK_ALPHA;const stroked=op.stroke!==null&&op.strokeAlpha>=BLANK_ALPHA&&op.strokeWidth>0;if(!filled&&!stroked)return false;const box=pathBounds(filled?op.path:op.strokePath);return box!==null&&box.y+box.height>top&&box.y<frame.height&&box.x+box.width>0&&box.x<frame.width})}async function checkFilm(film2,options={}){const compiled=isFilm(film2)?await film2.compile(options):film2;const times=options.times?[...options.times]:restingMoments(compiled,options.samples??0);const merged=new Map;for(const time of times){const frame=await frameAt2(compiled,time);for(const{key,...finding}of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){const seen=merged.get(key);if(seen){seen.until=time;if(finding.severity==="error")seen.severity="error"}else{merged.set(key,{...finding,until:time,stage:{x:0,y:0}})}}}const frameCount=options.motion?Math.max(1,Math.round(compiled.duration*compiled.fps)):0;const step=1/compiled.fps;if(options.motion){const top=options.contentTop??0;const moving=new Map;const blanks=[];for(let index=0;index<frameCount;index++){const time=index*step;const frame=await frameAt2(compiled,time);for(const finding of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){if(merged.has(finding.key))continue;let runs=moving.get(finding.key);if(!runs)moving.set(finding.key,runs=[]);const last=runs[runs.length-1];if(last&&last.to===index-1)last.to=index;else runs.push({from:index,to:index,first:finding})}const edge=time<BLANK_EDGE_SECONDS||time>compiled.duration-BLANK_EDGE_SECONDS;if(!edge&&!hasContent(frame,top)){const last=blanks[blanks.length-1];if(last&&last.to===index-1)last.to=index;else blanks.push({from:index,to:index})}}const seconds=frames=>Math.round(frames*step*100)/100;for(const[key,runs]of moving){const longest=runs.reduce((best,run2)=>run2.to-run2.from>best.to-best.from?run2:best);const{key:_,...finding}=longest.first;merged.set(key,{...finding,severity:"warning",until:longest.to*step,stage:{x:0,y:0},motion:{spans:runs.length,seconds:seconds(runs.reduce((sum,run2)=>sum+run2.to-run2.from+1,0))}})}for(const run2 of blanks){const length=seconds(run2.to-run2.from+1);if(length<BLANK_MIN_SECONDS)continue;merged.set(`film.blank:${run2.from}`,{code:"film.blank",severity:"warning",message:`Nothing is visible${top>0?` below y=${top}`:""} for ${length} s.`,time:run2.from*step,until:run2.to*step,box:{x:0,y:top,width:compiled.width,height:compiled.height-top},stage:{x:0,y:0},motion:{spans:1,seconds:length}})}}const round=value=>Math.round(value*100)/100;const diagnostics=[...merged.values()].map(entry=>({...entry,time:Math.round(entry.time*1e3)/1e3,until:Math.round(entry.until*1e3)/1e3,box:{x:round(entry.box.x),y:round(entry.box.y),width:round(entry.box.width),height:round(entry.box.height)},stage:{x:round(entry.box.x+entry.box.width/2-compiled.width/2),y:round(entry.box.y+entry.box.height/2-compiled.height/2)}})).sort((a,b)=>a.severity===b.severity?a.time-b.time:a.severity==="error"?-1:1);const errors=diagnostics.filter(entry=>entry.severity==="error").length;return{ok:errors===0,width:compiled.width,height:compiled.height,duration:compiled.duration,sampled:times.map(time=>Math.round(time*1e3)/1e3),...options.motion?{frames:frameCount}:{},diagnostics,summary:{errors,warnings:diagnostics.length-errors}}}var explainer=`import { axes, colorAlong, dot, draw, dynamic, fadeIn, film, line, tex, text, to, write } from 'vizmatic/stage'
155
+ `}var EDGE_TOLERANCE=1;var MIN_ALPHA=.08;var MIN_TEXT_ALPHA=.15;var MIN_OVERLAP=.12;var GLYPH_INSET=.12;var MIN_RESTING_MOMENTS=5;var AUTO_SAMPLES=12;var CUBIC_STEPS=6;var CROSSING_ERROR_WIDTH=2;var BLANK_ALPHA=.25;var BLANK_EDGE_SECONDS=.5;var BLANK_MIN_SECONDS=.2;var CROSSING_ERROR_CONTRAST=2;var MIN_STROKE_CONTRAST=1.6;var OPAQUE=.9;function solid3(paint){return isGradient(paint)?sampleStops(paint.stops,.5):paint}function luminance(color){const channel=value=>{const x=value/255;return x<=.03928?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*channel(color[0])+.7152*channel(color[1])+.0722*channel(color[2])}function contrastOver(color,alpha3,background){const a=color[3]*alpha3;const mixed=[color[0]*a+background[0]*(1-a),color[1]*a+background[1]*(1-a),color[2]*a+background[2]*(1-a),1];const x=luminance(mixed),y=luminance(background);return(Math.max(x,y)+.05)/(Math.min(x,y)+.05)}function pad(bounds4,amount2){return{x:bounds4.x-amount2,y:bounds4.y-amount2,width:bounds4.width+amount2*2,height:bounds4.height+amount2*2}}function inset(bounds4,fraction){const dx=bounds4.width*fraction,dy=bounds4.height*fraction;return{x:bounds4.x+dx,y:bounds4.y+dy,width:bounds4.width-dx*2,height:bounds4.height-dy*2}}function intersects(a,b){return a.x<b.x+b.width&&b.x<a.x+a.width&&a.y<b.y+b.height&&b.y<a.y+a.height}function intersection(a,b){const x=Math.max(a.x,b.x),y=Math.max(a.y,b.y);const right=Math.min(a.x+a.width,b.x+b.width),bottom=Math.min(a.y+a.height,b.y+b.height);return right>x&&bottom>y?{x,y,width:right-x,height:bottom-y}:null}function contains(outer,inner){return outer.x<=inner.x&&outer.y<=inner.y&&outer.x+outer.width>=inner.x+inner.width&&outer.y+outer.height>=inner.y+inner.height}function union(a,b){const x=Math.min(a.x,b.x),y=Math.min(a.y,b.y);return{x,y,width:Math.max(a.x+a.width,b.x+b.width)-x,height:Math.max(a.y+a.height,b.y+b.height)-y}}function segmentHitsBox(x0,y0,x1,y1,box){let t0=0,t1=1;const dx=x1-x0,dy=y1-y0;const edges=[[-dx,x0-box.x],[dx,box.x+box.width-x0],[-dy,y0-box.y],[dy,box.y+box.height-y0]];for(const[p,q]of edges){if(p===0){if(q<0)return false}else{const r=q/p;if(p<0){if(r>t1)return false;if(r>t0)t0=r}else{if(r<t0)return false;if(r<t1)t1=r}}}return t0<=t1}function strokeHitsBox(path,box){for(const r of path){const p=r.p;for(let o=0;o+7<p.length;o+=6){const x0=p[o],y0=p[o+1],x1=p[o+2],y1=p[o+3];const x2=p[o+4],y2=p[o+5],x3=p[o+6],y3=p[o+7];const left=Math.min(x0,x1,x2,x3),right=Math.max(x0,x1,x2,x3);const top=Math.min(y0,y1,y2,y3),bottom=Math.max(y0,y1,y2,y3);if(right<box.x||left>box.x+box.width||bottom<box.y||top>box.y+box.height)continue;let lastX=x0,lastY=y0;for(let k=1;k<=CUBIC_STEPS;k++){const t=k/CUBIC_STEPS,u=1-t;const a=u*u*u,b=3*u*u*t,c=3*u*t*t,d=t*t*t;const x=a*x0+b*x1+c*x2+d*x3;const y=a*y0+b*y1+c*y2+d*y3;if(segmentHitsBox(lastX,lastY,x,y,box))return true;lastX=x;lastY=y}}}return false}function textBlockOf(node){return node.data["key"]!==void 0?node.parent:null}function isGlyph(op){return!!op.node&&op.node.data["key"]!==void 0}function sourceOf(node){const source=node.source;return typeof source==="string"?source:""}function ownerKey(node){if(!node)return"unknown";let current=node;while(current.parent&&current.parent.parent)current=current.parent;return current.mounted?String(current.id):"dynamic"}function restingMoments(film2,samples){const times=new Set;const clips=film2.clips;const active=t=>clips.some(clip=>clip.t0<t&&t<clip.t1);const nudge=.001;for(const clip of clips){const t=clip.t1+nudge;if(t<film2.duration&&!active(t))times.add(t)}times.add(Math.max(0,film2.duration-nudge));for(let i=0;i<samples;i++)times.add((i+.5)/samples*film2.duration);if(times.size<MIN_RESTING_MOMENTS){for(let i=0;i<AUTO_SAMPLES;i++){const t=(i+.5)/AUTO_SAMPLES*film2.duration;if(!active(t))times.add(t)}}return[...times].sort((a,b)=>a-b)}function frameAt2(film2,time){try{return film2.frame(time)}catch(error){if(!isSuspend(error))throw error;return error.promise.then(()=>frameAt2(film2,time))}}function zoomAt(film2,time){const camera=film2.stage.camera;const track=camera.tracks?.get("sx");return track?track.sample(time):camera.base.sx}function inspect(frame,time,zoomed,bleed){const findings=[];const{width,height,ops}=frame;const background=frame.background?parseColor(frame.background):frame.dark?[0,0,0,1]:[255,255,255,1];const canvas2={x:0,y:0,width,height};const blocks=new Map;const fills=[];const strokes=[];const off=new Map;let outsideMarks=0;ops.forEach((op,order)=>{if(op.kind==="image"){if(op.alpha<MIN_ALPHA||!imageHasVisiblePixels(op.image.asset,op.image.crop))return;const box2=imageOpBounds(op);const outside2=box2.x<-EDGE_TOLERANCE||box2.y<-EDGE_TOLERANCE||box2.x+box2.width>width+EDGE_TOLERANCE||box2.y+box2.height>height+EDGE_TOLERANCE;if(outside2&&!zoomed&&!bleed)findings.push({key:`film.off_canvas:image:${ownerKey(op.node)}`,code:"film.off_canvas",severity:"warning",time,box:box2,message:`Image ${JSON.stringify(op.image.asset?.id??op.node?.label??"image")} runs off the canvas.`});return}if(op.kind!=="path"||op.path.length===0)return;const glyph=isGlyph(op);const alpha3=Math.max(op.fillAlpha,op.strokeAlpha);if(alpha3<MIN_ALPHA)return;const shape2=pathBounds(op.path);if(!shape2)return;const box=op.stroke?pad(shape2,op.strokeWidth/2):shape2;const block=glyph?textBlockOf(op.node):null;const outside=box.x<-EDGE_TOLERANCE||box.y<-EDGE_TOLERANCE||box.x+box.width>width+EDGE_TOLERANCE||box.y+box.height>height+EDGE_TOLERANCE;const spansFrame=box.x<=0&&box.x+box.width>=width||box.y<=0&&box.y+box.height>=height;if(outside&&(glyph||!spansFrame&&!zoomed&&!bleed)){const visible=intersects(box,canvas2);const text2=block?sourceOf(block):void 0;const key=glyph?`text:${text2}`:"marks";const existing=off.get(key);const severity=glyph&&visible&&!zoomed?"error":"warning";if(existing){existing.box=union(existing.box,box);if(!glyph)outsideMarks+=1}else{if(!glyph)outsideMarks=1;off.set(key,{key:`film.off_canvas:${key}`,code:"film.off_canvas",severity,time,box,message:glyph?`Text ${JSON.stringify(text2??"")} runs off the canvas${visible?" and is clipped":""}.`:"",...text2?{text:text2}:{}})}}if(glyph&&op.node.data["missingGlyph"]&&op.fillAlpha>=MIN_TEXT_ALPHA){const char=String(op.node.data["key"]);const code=`U+${char.codePointAt(0).toString(16).toUpperCase().padStart(4,"0")}`;const text2=block?sourceOf(block):"";findings.push({key:`film.missing_glyph:${text2}:${code}`,code:"film.missing_glyph",severity:"error",time,box:shape2,message:`Text ${JSON.stringify(text2)} has a character that no bundled font can draw (${code}). It renders as an empty box.`,text:text2})}if(glyph&&block&&op.fillAlpha>=MIN_TEXT_ALPHA){let entry=blocks.get(block);if(!entry)blocks.set(block,entry={id:block,source:sourceOf(block),bounds:shape2,glyphs:[]});entry.bounds=union(entry.bounds,shape2);entry.glyphs.push({box:shape2,order})}else if(!glyph){if(op.fill&&op.fillAlpha>=OPAQUE&&solid3(op.fill)[3]>=OPAQUE&&op.path.some(r=>r.closed))fills.push({order,bounds:shape2});if(op.stroke&&op.strokeAlpha>=MIN_ALPHA&&op.strokePath.length>0){const contrast=contrastOver(solid3(op.stroke),op.strokeAlpha,background);if(contrast>=MIN_STROKE_CONTRAST)strokes.push({op,order,contrast})}}});const marks=off.get("marks");if(marks)marks.message=`${outsideMarks===1?"A mark extends":`${outsideMarks} marks extend`} past the ${width}x${height} canvas.`;findings.push(...off.values());const occluded=(lower,upper,box)=>fills.some(fill=>fill.order>lower&&fill.order<upper&&contains(fill.bounds,box));const list3=[...blocks.values()];for(let i=0;i<list3.length;i++){const a=list3[i];for(let j=i+1;j<list3.length;j++){const b=list3[j];if(!intersects(a.bounds,b.bounds))continue;let hit=null;for(const ga of a.glyphs){if(!intersects(ga.box,b.bounds))continue;for(const gb of b.glyphs){const shared=intersection(ga.box,gb.box);if(!shared)continue;const smaller=Math.min(ga.box.width*ga.box.height,gb.box.width*gb.box.height);if(smaller<=0||shared.width*shared.height/smaller<MIN_OVERLAP)continue;if(occluded(Math.min(ga.order,gb.order),Math.max(ga.order,gb.order),ga.order<gb.order?ga.box:gb.box))continue;hit=hit?union(hit,shared):shared}}if(hit){findings.push({key:`film.text_overlap:${a.source}|${b.source}`,code:"film.text_overlap",severity:"error",time,box:hit,message:`Text ${JSON.stringify(a.source)} overlaps text ${JSON.stringify(b.source)}.`,text:a.source,other:b.source})}}}for(const block of list3){for(const{op,order,contrast}of strokes){const strokeBox=pathBounds(op.strokePath);if(!strokeBox||!intersects(pad(strokeBox,op.strokeWidth),block.bounds))continue;let hit=null;for(const glyph of block.glyphs){const target=inset(glyph.box,GLYPH_INSET);if(!intersects(strokeBox,target))continue;if(!strokeHitsBox(op.strokePath,target))continue;if(order<glyph.order&&occluded(order,glyph.order,glyph.box))continue;hit=hit?union(hit,glyph.box):glyph.box}if(hit){const strong=op.strokeWidth>=CROSSING_ERROR_WIDTH&&contrast>=CROSSING_ERROR_CONTRAST;findings.push({key:`film.text_crossed:${block.source}:${ownerKey(op.node)}`,code:"film.text_crossed",severity:strong?"error":"warning",time,box:hit,message:`A stroke crosses text ${JSON.stringify(block.source)}.`,text:block.source})}}}return findings}function hasContent(frame,top){return frame.ops.some(op=>{if(op.kind==="image"){const box2=imageOpBounds(op);return op.alpha>=BLANK_ALPHA&&imageHasVisiblePixels(op.image.asset,op.image.crop)&&box2.y+box2.height>top&&box2.y<frame.height&&box2.x+box2.width>0&&box2.x<frame.width}const filled=op.fill!==null&&op.fillAlpha>=BLANK_ALPHA;const stroked=op.stroke!==null&&op.strokeAlpha>=BLANK_ALPHA&&op.strokeWidth>0;if(!filled&&!stroked)return false;const box=pathBounds(filled?op.path:op.strokePath);return box!==null&&box.y+box.height>top&&box.y<frame.height&&box.x+box.width>0&&box.x<frame.width})}async function checkFilm(film2,options={}){try{return await inspectFilm(film2,options)}catch(error){if(!(error instanceof ImageAssetError)&&error?.name!=="ImageAssetError")throw error;const dimensions=isFilm(film2)?new Stage(film2.options):film2;return{ok:false,width:dimensions.width,height:dimensions.height,duration:isFilm(film2)?0:film2.duration,sampled:[],diagnostics:[{code:"film.image_asset",severity:"error",message:error.message,time:0,until:0,box:{x:0,y:0,width:0,height:0},stage:{x:0,y:0}}],summary:{errors:1,warnings:0}}}}async function inspectFilm(film2,options){const compiled=isFilm(film2)?await film2.compile(options):film2;const times=options.times?[...options.times]:restingMoments(compiled,options.samples??0);const merged=new Map;for(const time of times){const frame=await frameAt2(compiled,time);for(const{key,...finding}of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){const seen=merged.get(key);if(seen){seen.until=time;if(finding.severity==="error")seen.severity="error"}else{merged.set(key,{...finding,until:time,stage:{x:0,y:0}})}}}const frameCount=options.motion?Math.max(1,Math.round(compiled.duration*compiled.fps)):0;const step=1/compiled.fps;if(options.motion){const top=options.contentTop??0;const moving=new Map;const blanks=[];for(let index=0;index<frameCount;index++){const time=index*step;const frame=await frameAt2(compiled,time);for(const finding of inspect(frame,time,zoomAt(compiled,time)!==1,compiled.bleed)){if(merged.has(finding.key))continue;let runs=moving.get(finding.key);if(!runs)moving.set(finding.key,runs=[]);const last=runs[runs.length-1];if(last&&last.to===index-1)last.to=index;else runs.push({from:index,to:index,first:finding})}const edge=time<BLANK_EDGE_SECONDS||time>compiled.duration-BLANK_EDGE_SECONDS;if(!edge&&!hasContent(frame,top)){const last=blanks[blanks.length-1];if(last&&last.to===index-1)last.to=index;else blanks.push({from:index,to:index})}}const seconds=frames=>Math.round(frames*step*100)/100;for(const[key,runs]of moving){const longest=runs.reduce((best,run2)=>run2.to-run2.from>best.to-best.from?run2:best);const{key:_,...finding}=longest.first;merged.set(key,{...finding,severity:"warning",until:longest.to*step,stage:{x:0,y:0},motion:{spans:runs.length,seconds:seconds(runs.reduce((sum,run2)=>sum+run2.to-run2.from+1,0))}})}for(const run2 of blanks){const length=seconds(run2.to-run2.from+1);if(length<BLANK_MIN_SECONDS)continue;merged.set(`film.blank:${run2.from}`,{code:"film.blank",severity:"warning",message:`Nothing is visible${top>0?` below y=${top}`:""} for ${length} s.`,time:run2.from*step,until:run2.to*step,box:{x:0,y:top,width:compiled.width,height:compiled.height-top},stage:{x:0,y:0},motion:{spans:1,seconds:length}})}}const round=value=>Math.round(value*100)/100;const diagnostics=[...merged.values()].map(entry=>({...entry,time:Math.round(entry.time*1e3)/1e3,until:Math.round(entry.until*1e3)/1e3,box:{x:round(entry.box.x),y:round(entry.box.y),width:round(entry.box.width),height:round(entry.box.height)},stage:{x:round(entry.box.x+entry.box.width/2-compiled.width/2),y:round(entry.box.y+entry.box.height/2-compiled.height/2)}})).sort((a,b)=>a.severity===b.severity?a.time-b.time:a.severity==="error"?-1:1);const errors=diagnostics.filter(entry=>entry.severity==="error").length;return{ok:errors===0,width:compiled.width,height:compiled.height,duration:compiled.duration,sampled:times.map(time=>Math.round(time*1e3)/1e3),...options.motion?{frames:frameCount}:{},diagnostics,summary:{errors,warnings:diagnostics.length-errors}}}var explainer=`import { axes, colorAlong, dot, draw, dynamic, fadeIn, film, line, tex, text, to, write } from 'vizmatic/stage'
134
156
 
135
157
  // One idea, shown as it changes: a secant line becomes a tangent.
136
158
  export default film({ title: 'A limit you can see' }, (s) => {
@@ -329,7 +351,7 @@ export default film({ title: 'Quarterly review' }, (s) => {
329
351
  s.play(fadeOut([heading, ...body], { shift: [0, -24] }))
330
352
  }
331
353
  })
332
- `;var FILM_TEMPLATES=[{name:"explainer",description:"A graph, a moving value, and an equation, in three chapters.",source:explainer},{name:"equation",description:"A step-by-step derivation that morphs glyph by glyph.",source:equation},{name:"architecture",description:"Services with live detail, and packets traveling along the edges.",source:architecture},{name:"chart",description:"Bars that grow in order, with the takeaway as the title.",source:chart},{name:"deck",description:"A stepped presentation with one chapter per slide.",source:deck}];var SHAPES="Shapes";var TEXT="Text and math";var MATH="Math objects";var REVEAL="Reveal and dismiss";var CHANGE="Change";var TIMING="Timing";var EMPHASIS="Emphasis";var CHARTS="Charts";var SYSTEMS="Systems and computer science";var THREE="3D";var BRIDGE="Bring in existing work";var FILM_OBJECTS=[{name:"text",group:TEXT,usage:"text('Hello', { font: 'serif', size: 72, color: 'ink' }): vector glyphs you can write and morph"},{name:"tex",group:TEXT,usage:"tex('e^{i\\\\pi} + 1 = 0', { size: 64 }): typeset math. eq.part('x^2') selects a term"},{name:"decimal",group:TEXT,usage:"decimal(() => v.value, { digits: 2, prefix: 'm = ' }): a live number readout"},{name:"dot",group:SHAPES,usage:"dot(9, 'yellow').at(x, y): a filled point"},{name:"line",group:SHAPES,usage:"line([x0, y0], [x1, y1], { stroke: 'blue', width: 3 })"},{name:"arrow",group:SHAPES,usage:"arrow(from, to, { stroke: 'ink', bend: 40, pad: 8 }): a shaft and a clean tip"},{name:"circle",group:SHAPES,usage:"circle(60, { stroke: 'teal', fill: 'surface' })"},{name:"ellipse",group:SHAPES,usage:"ellipse(rx, ry, style)"},{name:"arc",group:SHAPES,usage:"arc(radius, fromAngle, toAngle, style)"},{name:"rect",group:SHAPES,usage:"rect(240, 96, { radius: 10, stroke: 'blue' })"},{name:"polygon",group:SHAPES,usage:"polygon([[x, y], ...], style)"},{name:"regularPolygon",group:SHAPES,usage:"regularPolygon(6, radius, style)"},{name:"polyline",group:SHAPES,usage:"polyline(points, style): straight segments"},{name:"curve",group:SHAPES,usage:"curve(points, style): a smooth spline through points"},{name:"parametric",group:SHAPES,usage:"parametric((t) => [x, y], t0, t1, style)"},{name:"svgPath",group:SHAPES,usage:"svgPath('M0 0C...', style): any SVG path data"},{name:"brace",group:SHAPES,usage:"brace(from, to, { depth: 24 }): a curly brace beside a span"},{name:"group",group:SHAPES,usage:'group(a, b, c).arrange("right", 24): move and lay out together'},{name:"dynamic",group:SHAPES,usage:"dynamic(() => line(p(v.value), q)): rebuilt every frame from timeline values"},{name:"axes",group:MATH,usage:"axes({ x: [-1, 4], y: [0, 9], grid: true }). plot(f), world(x, y), dotAt(x, y), guides(x, y)"},{name:"plane",group:MATH,usage:"plane({ unit: 120 }): a grid that bends under applyMatrix and warp"},{name:"numberLine",group:MATH,usage:"numberLine({ min: -4, max: 4 }): ticks and labels on one axis"},{name:"complexPlane",group:MATH,usage:"complexPlane({ unit: 120 }): a plane for applyComplex"},{name:"applyComplex",group:MATH,usage:"applyComplex(plane, complex.square): bend a plane through a complex function"},{name:"vectorField",group:MATH,usage:"vectorField((x, y) => [u, v]): arrows that show a field"},{name:"streamLines",group:MATH,usage:"streamLines((x, y) => [u, v]): flowing lines through a field"},{name:"riemann",group:MATH,usage:"riemann(axes, f, { n: 12 }): the rectangles of a Riemann sum"},{name:"areaUnder",group:MATH,usage:"areaUnder(axes, f, { from: 0, to: 2 }): the filled area under a curve"},{name:"tangentLine",group:MATH,usage:"tangentLine(axes, f, () => x.value): a tangent that follows a value"},{name:"secantLine",group:MATH,usage:"secantLine(axes, f, a, b): a secant between two values"},{name:"dashedGuides",group:MATH,usage:"dashedGuides(axes, x, y): dashed lines down to both axes"},{name:"angleMark",group:MATH,usage:"angleMark(vertex, from, to): an arc between two rays"},{name:"rightAngle",group:MATH,usage:"rightAngle(vertex, a, b): a square corner mark"},{name:"matrix",group:MATH,usage:"matrix([[1, 2], [3, 4]]): a bracketed matrix of numbers or TeX"},{name:"braceLabel",group:MATH,usage:"braceLabel(node, 'x^2'): a curly brace beside a node, with a label"},{name:"surroundingBox",group:MATH,usage:"surroundingBox(node): a rounded box around a node"},{name:"labeledDot",group:MATH,usage:"labeledDot('A'): a dot with a label"},{name:"traced",group:MATH,usage:"traced(() => point, t0, t1): the path a moving point leaves"},{name:"fourier",group:MATH,usage:"fourier(points, { terms: 80 }): Fourier terms for a closed curve"},{name:"epicycles",group:MATH,usage:"epicycles(terms, { u }): rotating circles that draw a curve"},{name:"barChart",group:CHARTS,usage:"barChart([{ label: 'A', value: 3 }]): animated bars"},{name:"histogram",group:CHARTS,usage:"histogram(samples, { bins: 20 })"},{name:"scatter",group:CHARTS,usage:"scatter([{ x, y }]): a point cloud on axes"},{name:"lineChart",group:CHARTS,usage:"lineChart([{ name: 'p95', values: [...] }]): series with direct labels"},{name:"pie",group:CHARTS,usage:"pie([{ label: 'A', value: 3 }])"},{name:"donut",group:CHARTS,usage:"donut([{ label: 'A', value: 3 }])"},{name:"heatmap",group:CHARTS,usage:"heatmap(rows): a grid of colored cells"},{name:"sparkline",group:CHARTS,usage:"sparkline(values): a tiny inline trend"},{name:"infoBox",group:SYSTEMS,usage:"infoBox({ title, rows }): a dense box with a title, fields, and live stats"},{name:"connector",group:SYSTEMS,usage:"connector(a, b, { label }): a routed edge between two nodes"},{name:"legend",group:SYSTEMS,usage:"legend([{ label: 'read', color: 'blue' }])"},{name:"callout",group:SYSTEMS,usage:"callout(node, 'Why this matters'): a note with a leader line"},{name:"graph",group:SYSTEMS,usage:"graph(nodes, edges): nodes and edges with automatic layout"},{name:"tree",group:SYSTEMS,usage:"tree(root): a layered tree"},{name:"arrayCells",group:SYSTEMS,usage:"arrayCells([3, 1, 4]): boxes for arrays and buffers"},{name:"codeBlock",group:SYSTEMS,usage:"codeBlock(source, { language }): highlighted code as glyphs"},{name:"morphCode",group:SYSTEMS,usage:"morphCode(before, after): edit code by moving tokens"},{name:"neuralNet",group:SYSTEMS,usage:"neuralNet([3, 4, 2]): layers with edges"},{name:"tokens",group:SYSTEMS,usage:"tokens(['The', 'cat']): a row of token chips"},{name:"attentionMatrix",group:SYSTEMS,usage:"attentionMatrix(rows, columns, weights): a labeled heatmap"},{name:"scene3d",group:THREE,usage:"scene3d({ phi, theta }): a 3D view you can orbit. Add 3D objects to it"},{name:"axes3d",group:THREE,usage:"axes3d({ x, y, z }): three axes"},{name:"surface",group:THREE,usage:"surface((x, y, t) => z, { x, y }): a shaded height field"},{name:"parametricSurface",group:THREE,usage:"parametricSurface((u, v) => [x, y, z], [0, 1], [0, 1])"},{name:"sphere",group:THREE,usage:"sphere(radius): a shaded sphere"},{name:"curve3d",group:THREE,usage:"curve3d((t) => [x, y, z], t0, t1)"},{name:"line3d",group:THREE,usage:"line3d(a, b)"},{name:"vector3d",group:THREE,usage:"vector3d(from, to): an arrow in space"},{name:"points3d",group:THREE,usage:"points3d(points): many points, or a function that returns them"},{name:"point3d",group:THREE,usage:"point3d(() => [x, y, z]): one point that can move"},{name:"trail3d",group:THREE,usage:"trail3d(() => point, t0, t1, { tail }): a trace behind a moving point"},{name:"gridPlane3d",group:THREE,usage:"gridPlane3d(): a floor grid"},{name:"label3d",group:THREE,usage:"label3d('x', [1, 0, 0]): a screen-facing label at a 3D point"},{name:"fromSvg",group:BRIDGE,usage:"fromSvg(svgText): any SVG as animatable shapes"},{name:"image",group:BRIDGE,usage:"image(dataUrl, { width: 400 }): a logo or a photo, centered, that fades and moves like any node"},{name:"narration",group:TIMING,usage:"narration(s, timing).scene('intro').on('a spoken phrase', () => s.play(...)): place changes on measured words"},{name:"fromComponent",group:BRIDGE,usage:"await fromComponent(<Flow ... />, { width, height }): any TSX figure as animatable shapes. Import from 'vizmatic/stage/export'. Node only"},{name:"write",group:REVEAL,usage:"write(node): handwrite text and equations glyph by glyph"},{name:"draw",group:REVEAL,usage:"draw(node): trace strokes in order, then fill"},{name:"erase",group:REVEAL,usage:"erase(node): the reverse of draw"},{name:"fadeIn",group:REVEAL,usage:"fadeIn(node, { shift: [0, 16], scale: 0.9, lag: 0.1 })"},{name:"fadeOut",group:REVEAL,usage:"fadeOut(nodes, { shift: [0, -16] })"},{name:"grow",group:REVEAL,usage:"grow(node, { from: [x, y] }): scale up from a point"},{name:"typewriter",group:REVEAL,usage:"typewriter(text): reveal characters in order"},{name:"wipe",group:REVEAL,usage:"wipe(node): reveal with a moving edge"},{name:"appear",group:REVEAL,usage:"appear(node): show at once"},{name:"vanish",group:REVEAL,usage:"vanish(node): hide at once"},{name:"to",group:CHANGE,usage:"to(node, (n) => n.moveTo([x, y]).color('yellow').scale(2)): animate any change"},{name:"morph",group:CHANGE,usage:"morph(a, b): turn any shape into any other. b stays on stage"},{name:"morphMatching",group:CHANGE,usage:"morphMatching(eqA, eqB): shared glyphs travel, the rest fade"},{name:"moveTo",group:CHANGE,usage:"moveTo(node, [x, y])"},{name:"shift",group:CHANGE,usage:"shift(node, dx, dy)"},{name:"scaleBy",group:CHANGE,usage:"scaleBy(node, 1.5, { about: [x, y] })"},{name:"rotate",group:CHANGE,usage:"rotate(node, Math.PI / 2, { about: [x, y] })"},{name:"recolor",group:CHANGE,usage:"recolor(node, 'teal')"},{name:"fade",group:CHANGE,usage:"fade(node, 0.3): change opacity and stay visible"},{name:"along",group:CHANGE,usage:"along(dot, pathOrNode, { orient: true }): follow a path"},{name:"warp",group:CHANGE,usage:"warp(grid, (x, y) => [u, v]): bend shapes through a function"},{name:"applyMatrix",group:CHANGE,usage:"applyMatrix(grid, [[1, 1], [0, 1]]): a linear map, with y up"},{name:"countUp",group:CHANGE,usage:"countUp(counter, 100): move a counter or value to a number"},{name:"counter",group:TEXT,usage:"counter(0, { digits: 1 }): a number you can animate with countUp"},{name:"spin",group:CHANGE,usage:"spin(node, rate): keep turning for the length of the animation"},{name:"swap",group:CHANGE,usage:"swap(a, b): trade places along arcs"},{name:"par",group:TIMING,usage:"par(a, b): together, inside a sequence"},{name:"seq",group:TIMING,usage:"seq(a, b): one after another"},{name:"lagged",group:TIMING,usage:"lagged([a, b, c], { lag: 0.2 }): overlapping starts"},{name:"delay",group:TIMING,usage:"delay(anim, 0.5)"},{name:"retime",group:TIMING,usage:"retime(anim, { duration: 2, ease: smoother })"},{name:"call",group:TIMING,usage:"call(() => ...): run code at a moment on the timeline"},{name:"indicate",group:EMPHASIS,usage:"indicate(node, { color: 'yellow', scale: 1.14 }): swell and return"},{name:"circumscribe",group:EMPHASIS,usage:"circumscribe(node): trace a line around it"},{name:"flash",group:EMPHASIS,usage:"flash([x, y]): a radial burst"},{name:"ripple",group:EMPHASIS,usage:"ripple([x, y]): an expanding ring"},{name:"pulse",group:EMPHASIS,usage:"pulse(line): a lit segment travels along a line"},{name:"shake",group:EMPHASIS,usage:"shake(node): a small oscillation"},{name:"highlightSweep",group:EMPHASIS,usage:"highlightSweep(node): a marker stroke across text"}];var stage_exports={};__export(stage_exports,{ArrayCells:()=>ArrayCells,Axes:()=>Axes,Axes3D:()=>Axes3D,BarChart:()=>BarChart2,Callout:()=>Callout,CodeBlock:()=>CodeBlock2,CompiledFilm:()=>CompiledFilm,ComplexPlane:()=>ComplexPlane,Connector:()=>Connector2,Counter:()=>Counter,Curve3D:()=>Curve3D,EMPTY_BOUNDS:()=>EMPTY_BOUNDS,Epicycles:()=>Epicycles,Graph:()=>Graph,GraphEdge:()=>GraphEdge,GraphNode:()=>GraphNode,GridPlane3D:()=>GridPlane3D,Heatmap:()=>Heatmap2,Histogram:()=>Histogram,IDENTITY:()=>IDENTITY,InfoBox:()=>InfoBox,LOOKS:()=>LOOKS,Label3D:()=>Label3D,LabeledDot:()=>LabeledDot,Line3D:()=>Line3D,LineChart:()=>LineChart2,MatrixNode:()=>MatrixNode,Narration:()=>Narration,NeuralNet:()=>NeuralNet,Node:()=>Node,NumberLine:()=>NumberLine2,NumberPlane:()=>NumberPlane,Object3D:()=>Object3D,PieChart:()=>PieChart2,Points3D:()=>Points3D,Scatter:()=>Scatter,Scene3D:()=>Scene3D,SceneClock:()=>SceneClock,Stage:()=>Stage,StreamLines:()=>StreamLines,Surface3D:()=>Surface3D,Suspend:()=>Suspend,SvgNode:()=>SvgNode,TexNode:()=>TexNode,TextNode:()=>TextNode,TokenRow:()=>TokenRow,Trail3D:()=>Trail3D,TreeGraph:()=>TreeGraph,Value:()=>Value,Vector3D:()=>Vector3D,VectorField:()=>VectorField,View3D:()=>View3D,along:()=>along2,angleMark:()=>angleMark,appear:()=>appear,apply:()=>apply,applyComplex:()=>applyComplex,applyMatrix:()=>applyMatrix,arc:()=>arc,arcPath:()=>arcPath,areaUnder:()=>areaUnder,arrayCells:()=>arrayCells,arrow:()=>arrow,attentionMatrix:()=>attentionMatrix,axes:()=>axes,axes3d:()=>axes3d,barChart:()=>barChart,blueprint:()=>blueprint,bounce:()=>bounce,brace:()=>brace,braceLabel:()=>braceLabel,buildOps:()=>buildOps,call:()=>call,callout:()=>callout,captionLines:()=>captionLines,chalk:()=>chalk,checkFilm:()=>checkFilm,circle:()=>circle,circlePath:()=>circlePath,circumscribe:()=>circumscribe,codeBlock:()=>codeBlock,colorAlong:()=>along,compileFilm:()=>compileFilm,complex:()=>complex,complexPlane:()=>complexPlane,compose:()=>compose,concat:()=>concat,connector:()=>connector,countUp:()=>countUp,counter:()=>counter,css:()=>css,cubicBezier:()=>cubicBezier,curve:()=>curve,curve3d:()=>curve3d,curveThrough:()=>curveThrough,dashedGuides:()=>dashedGuides,decimal:()=>decimal,delay:()=>delay,donut:()=>donut,dot:()=>dot,draw:()=>draw,during:()=>during,dynamic:()=>dynamic,easeInCubic:()=>easeInCubic,easeInExpo:()=>easeInExpo,easeInOutCubic:()=>easeInOutCubic,easeInOutQuint:()=>easeInOutQuint,easeInQuad:()=>easeInQuad,easeOutCubic:()=>easeOutCubic,easeOutExpo:()=>easeOutExpo,easeOutQuad:()=>easeOutQuad,easeOutQuint:()=>easeOutQuint,ellipse:()=>ellipse,epicycles:()=>epicycles,erase:()=>erase,fade:()=>fade,fadeIn:()=>fadeIn,fadeOut:()=>fadeOut,film:()=>film,flash:()=>flash,fontFor:()=>fontFor,fourier:()=>fourier,fourierPoint:()=>fourierPoint,frameInkBounds:()=>frameInkBounds,frameToSvg:()=>frameToSvg,fromSvg:()=>fromSvg,glyphPath:()=>glyphPath,graph:()=>graph,gridPlane3d:()=>gridPlane3d,group:()=>group,grow:()=>grow,heatmap:()=>heatmap,highlightSweep:()=>highlightSweep,histogram:()=>histogram,image:()=>image,indicate:()=>indicate,infoBox:()=>infoBox,invert:()=>invert,isFilm:()=>isFilm,isSuspend:()=>isSuspend,label3d:()=>label3d,labeledDot:()=>labeledDot,lagged:()=>lagged,legend:()=>legend,line:()=>line,line3d:()=>line3d,lineChart:()=>lineChart,linePath:()=>linePath,linear:()=>linear,linearGradient:()=>linearGradient,lingering:()=>lingering,matScale:()=>matScale,matrix:()=>matrix,midnight:()=>midnight,mixColor:()=>mixColor,morph:()=>morph,morphCode:()=>morphCode,morphMatching:()=>morphMatching,moveTo:()=>moveTo,mul:()=>mul,narration:()=>narration,neon:()=>neon,neuralNet:()=>neuralNet,notQuiteThere:()=>notQuiteThere,numberLine:()=>numberLine,overshoot:()=>overshoot,paintFrame:()=>paintFrame,paper:()=>paper,par:()=>par,parametric:()=>parametric,parametricPath:()=>parametricPath,parametricSurface:()=>parametricSurface,parseColor:()=>parseColor,parseFont:()=>parseFont,parseSvgPath:()=>parseSvgPath,pathBounds:()=>pathBounds,pathLength:()=>pathLength,pathToD:()=>pathToD,pie:()=>pie,plane:()=>plane,point3d:()=>point3d,pointAt:()=>pointAt,points3d:()=>points3d,polyPath:()=>polyPath,polygon:()=>polygon,polyline:()=>polyline,pulse:()=>pulse,radialGradient:()=>radialGradient,ramp:()=>ramp,recolor:()=>recolor,rect:()=>rect,rectPath:()=>rectPath,regularPolygon:()=>regularPolygon,resolveLook:()=>resolveLook,retime:()=>retime,reverseRing:()=>reverseRing,riemann:()=>riemann,rightAngle:()=>rightAngle,ring:()=>ring,ringCenter:()=>ringCenter,ringLength:()=>ringLength,ringThrough:()=>ringThrough,ripple:()=>ripple,rotate:()=>rotate,runningStart:()=>runningStart,rushFrom:()=>rushFrom,rushInto:()=>rushInto,samplePath:()=>samplePath,scaleBy:()=>scaleBy,scatter:()=>scatter,scene3d:()=>scene3d,secantLine:()=>secantLine,segmentCount:()=>segmentCount,seq:()=>seq,setAssetBase:()=>setAssetBase,shake:()=>shake,shape:()=>shape,shift:()=>shift,signedArea:()=>signedArea,slowInto:()=>slowInto,smooth:()=>smooth2,smoothBy:()=>smoothBy,smoothPath:()=>smoothPath,smoother:()=>smoother,sparkline:()=>sparkline,sphere:()=>sphere,spin:()=>spin,spring:()=>spring,streamLines:()=>streamLines,subdivideEach:()=>subdivideEach,surface:()=>surface,surroundingBox:()=>surroundingBox,svgPath:()=>svgPath,swap:()=>swap,tangentAt:()=>tangentAt,tangentLine:()=>tangentLine,tex:()=>tex,text:()=>text,thereAndBack:()=>thereAndBack,thereAndBackWithPause:()=>thereAndBackWithPause,to:()=>to,toPaint:()=>toPaint,tokenize:()=>tokenize,tokens:()=>tokens3,traced:()=>traced,trail3d:()=>trail3d,transformPath:()=>transformPath,tree:()=>tree,trimPath:()=>trimPath,trimRing:()=>trimRing,typewriter:()=>typewriter,unionBounds:()=>unionBounds,vanish:()=>vanish,vector3d:()=>vector3d,vectorField:()=>vectorField,warp:()=>warp,warpPath:()=>warpPath,wiggle:()=>wiggle,wipe:()=>wipe,write:()=>write});var TexNode=class extends Node{glyphs=[];source="";part(fragment){const keys=texKeys(fragment);const own=this.glyphs.map(glyph=>glyph.data["key"]);for(let start=0;start+keys.length<=own.length;start++){if(keys.every((key,i)=>key===own[start+i]))return this.glyphs.slice(start,start+keys.length)}return[]}parts(fragment){const keys=texKeys(fragment);const own=this.glyphs.map(glyph=>glyph.data["key"]);const out=[];for(let start=0;start+keys.length<=own.length;start++){if(keys.every((key,i)=>key===own[start+i])){out.push(this.glyphs.slice(start,start+keys.length));start+=keys.length-1}}return out}};var engine=null;var loading=null;var layouts=new Map;function requireEngine(){if(engine)return engine;loading??=import("./math-QVCETQDQ.js").then(module=>{engine=(tex2,display)=>module.renderMathSvg(tex2,{fontSize:1e3,display,color:"#000000"}).svg});throw new Suspend(loading)}function layoutTex(tex2,display){const cacheKey=`${display?"D":"I"}${tex2}`;const cached=layouts.get(cacheKey);if(cached)return cached;const svg=requireEngine()(tex2,display);const out=[];const stack=[];let current=[1,0,0,1,0,0];const viewBox=/viewBox="([^"]+)"/.exec(svg)?.[1]?.trim().split(/[ ,]+/).map(Number)??[0,0,1e3,1e3];const widthPx=Number(/\swidth="([\d.]+)px"/.exec(svg)?.[1]??1e3);const unit=widthPx/viewBox[2]/1e3;const tag=/<(\/?)([a-zA-Z]+)((?:\s+[-\w:]+="[^"]*")*)\s*(\/?)>/g;let svgDepth=0;let clip=null;const clips=[];for(let match=tag.exec(svg);match;match=tag.exec(svg)){const[,closing,name,attributes="",selfClosing]=match;const attr=key=>new RegExp(`\\s${key}="([^"]*)"`).exec(attributes)?.[1];if(name==="svg"){if(closing){svgDepth--;if(svgDepth>=1){current=stack.pop()??current;clip=clips.pop()??null}continue}svgDepth++;if(svgDepth>1){const box=(attr("viewBox")??"0 0 1 1").trim().split(/[ ,]+/).map(Number);const w=Number(attr("width")??box[2]),h=Number(attr("height")??box[3]);const mapping=mul([w/(box[2]||1),0,0,h/(box[3]||1),Number(attr("x")??0),Number(attr("y")??0)],[1,0,0,1,-box[0],-box[1]]);stack.push(current);clips.push(clip);current=mul(current,mapping);clip=[box[0],box[1],box[0]+box[2],box[1]+box[3]]}continue}if(closing){if(name==="g")current=stack.pop()??current;continue}const transform=attr("transform");const local=transform?parseTransform2(transform):[1,0,0,1,0,0];if(name==="g"){if(!selfClosing){stack.push(current);current=mul(current,local)}continue}if(name==="path"){const d=attr("d");if(!d)continue;const code=attr("data-c");const placed=transformPath(parseSvgPath(d),local);out.push({path:transformPath(clip?clampPath(placed,clip):placed,current),key:code?String.fromCodePoint(parseInt(code,16)):"?"})}else if(name==="rect"){const x=Number(attr("x")??0),y=Number(attr("y")??0);const w=Number(attr("width")??0),h=Number(attr("height")??0);if(w>0&&h>0)out.push({path:transformPath(rectPath(x,y,w,h),mul(current,local)),key:"rule"})}}const scaled=out.map(glyph=>({key:glyph.key,path:transformPath(glyph.path,[unit,0,0,unit,0,0])}));layouts.set(cacheKey,scaled);return scaled}function clampPath(path,box){return path.map(r=>{const out=new Float64Array(r.p.length);for(let i=0;i<out.length;i+=2){out[i]=Math.max(box[0],Math.min(box[2],r.p[i]));out[i+1]=Math.max(box[1],Math.min(box[3],r.p[i+1]))}return{p:out,closed:r.closed}})}function parseTransform2(value){let m=[1,0,0,1,0,0];for(const match of value.matchAll(/(translate|scale|matrix)\(([^)]*)\)/g)){const args=match[2].trim().split(/[ ,]+/).map(Number);if(match[1]==="translate")m=mul(m,[1,0,0,1,args[0]??0,args[1]??0]);else if(match[1]==="scale")m=mul(m,[args[0]??1,0,0,args[1]??args[0]??1,0,0]);else if(args.length===6)m=mul(m,args)}return m}function texKeys(fragment){return layoutTex(fragment,false).map(glyph=>glyph.key)}function tex(source,options={}){const size=options.size??56;const display=options.display??true;const glyphs=layoutTex(source,display);const paint=toPaint(options.color??"ink");const node=new TexNode;node.source=source;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const glyph of glyphs){const path=transformPath(glyph.path,[size,0,0,size,0,0]);const b=pathBounds(path);if(!b)continue;minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height);const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(path,[1,0,0,1,-cx,-cy])).at(cx,cy);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=glyph.key;node.glyphs.push(leaf);node.children.push(leaf);leaf.parent=node}if(minX!==Infinity){node.base.px=(minX+maxX)/2;node.base.py=(minY+maxY)/2}return node}function styled(node,style,defaults){const fill=style.fill!==void 0?style.fill:defaults.fill;const stroke=style.stroke!==void 0?style.stroke:defaults.stroke;if(fill)node.fill(fill);if(stroke)node.stroke(stroke,style.width??defaults.width??3);if(style.opacity!==void 0)node.opacity(style.opacity);if(style.glow)node.glow(style.glow);if(style.dash)node.dash(style.dash);if(style.z!==void 0)node.zIndex(style.z);return node}function shape(path,style={}){return styled(new Node(path),style,{stroke:"ink"})}function svgPath(d,style={}){return shape(parseSvgPath(d),style)}function line(a,b,style={}){return styled(new Node(linePath(a,b)),style,{stroke:"ink"})}function polyline(points,style={}){return styled(new Node(polyPath(points,style.closed)),style,{stroke:"ink"})}function curve(points,style={}){return styled(new Node(style.closed?smoothPath(points,true):curveThrough(points)),style,{stroke:"ink"})}function parametric(f,from,to2,style={}){return styled(new Node(parametricPath(f,from,to2,style.samples??96)),style,{stroke:"ink"})}function circle(radius,style={}){return styled(new Node(circlePath(0,0,radius)),style,{stroke:"ink"})}function ellipse(rx,ry,style={}){return styled(new Node(arcPath(0,0,rx,ry,0,Math.PI*2)),style,{stroke:"ink"})}function arc(radius,from,to2,style={}){return styled(new Node(arcPath(0,0,radius,radius,from,to2)),style,{stroke:"ink"})}function rect(width,height,style={}){return styled(new Node(rectPath(-width/2,-height/2,width,height,style.radius??0)),style,{stroke:"ink"})}function polygon(points,style={}){return styled(new Node(polyPath(points,true)),style,{stroke:"ink"})}function regularPolygon(sides,radius,style={}){const points=[];for(let i=0;i<sides;i++){const angle=-Math.PI/2+i/sides*Math.PI*2;points.push([Math.cos(angle)*radius,Math.sin(angle)*radius])}return polygon(points,style)}function intrinsicSize(src){const match=/^data:image\/(png|gif|jpeg|jpg);base64,/.exec(src);if(!match||typeof atob!=="function")return null;let head;try{head=atob(src.slice(match[0].length,match[0].length+(match[1]==="jpeg"||match[1]==="jpg"?87384:44)))}catch{return null}const byte=i=>head.charCodeAt(i);if(match[1]==="png")return head.length>=24?[byte(16)*16777216+byte(17)*65536+byte(18)*256+byte(19),byte(20)*16777216+byte(21)*65536+byte(22)*256+byte(23)]:null;if(match[1]==="gif")return head.length>=10?[byte(6)+byte(7)*256,byte(8)+byte(9)*256]:null;for(let i=2;i+9<head.length;){if(byte(i)!==255)return null;const marker=byte(i+1);if(marker>=192&&marker<=207&&marker!==196&&marker!==200&&marker!==204)return[byte(i+7)*256+byte(i+8),byte(i+5)*256+byte(i+6)];i+=2+byte(i+2)*256+byte(i+3)}return null}function image(src,options={}){const natural=intrinsicSize(src);let width=options.width,height=options.height;if(width===void 0&&height===void 0){if(!natural)throw new Error("image() needs a width or a height when the picture is not a PNG, GIF, or JPEG data URL.");[width,height]=natural}else if(width===void 0||height===void 0){if(!natural)throw new Error("image() needs both width and height when the picture is not a PNG, GIF, or JPEG data URL.");if(width===void 0)width=height*natural[0]/natural[1];else height=width*natural[1]/natural[0]}if(!(width>0)||!(height>0))throw new Error("image() needs a positive width and height.");const picture=new Node().at(-width/2,-height/2);picture.base.image={src,width,height};const out=new Node;out.add(picture);if(options.opacity!==void 0)out.opacity(options.opacity);return out}function dot(radius=9,color="ink",style={}){return styled(new Node(circlePath(0,0,radius)),style,{fill:color})}function arrow(from,to2,style={}){const color=style.stroke??"ink";const width=style.width??3;const tip=style.tip??Math.max(13,width*4.2);const ratio=style.tipRatio??.72;const pad2=style.pad??0;let dx=to2[0]-from[0],dy=to2[1]-from[1];const length=Math.hypot(dx,dy)||1;dx/=length;dy/=length;const start=[from[0]+dx*pad2,from[1]+dy*pad2];const end=[to2[0]-dx*pad2,to2[1]-dy*pad2];const span=Math.max(0,length-pad2*2);const usableTip=Math.min(tip,span*.45);const group2=new Node;const bend=style.bend??0;const normal=[-dy,dx];const control=[(start[0]+end[0])/2+normal[0]*bend,(start[1]+end[1])/2+normal[1]*bend];let tx=end[0]-control[0],ty=end[1]-control[1];const tl=Math.hypot(tx,ty)||1;tx/=tl;ty/=tl;const baseX=end[0]-tx*usableTip,baseY=end[1]-ty*usableTip;const shaftPath=bend===0?linePath(style.both?[start[0]+dx*usableTip,start[1]+dy*usableTip]:start,[baseX,baseY]):parseSvgPath(`M${start[0]} ${start[1]}Q${control[0]} ${control[1]} ${baseX} ${baseY}`);const shaft=new Node(shaftPath).stroke(color,width);if(style.dash)shaft.dash(style.dash);const half=usableTip*ratio/2;const head=(x,y,ux,uy)=>new Node(polyPath([[x,y],[x-ux*usableTip-uy*half,y-uy*usableTip+ux*half],[x-ux*usableTip+uy*half,y-uy*usableTip-ux*half]],true)).fill(color);group2.add(shaft,head(end[0],end[1],tx,ty));if(style.both)group2.add(head(start[0],start[1],-dx,-dy));if(style.opacity!==void 0)group2.opacity(style.opacity);if(style.glow){shaft.glow(style.glow)}group2.data["shaft"]=shaft;return group2}function brace(from,to2,style={}){const dx=to2[0]-from[0],dy=to2[1]-from[1];const length=Math.hypot(dx,dy)||1;const depth=style.depth??Math.min(26,10+length*.05);const l=length,d=depth,t=1.6;const c=Math.min(d,l/4);const data=`M0 0C0 ${d*.5} ${c*.4} ${d*.5} ${c} ${d*.5}L${l/2-c} ${d*.5}C${l/2-c*.3} ${d*.5} ${l/2} ${d*.72} ${l/2} ${d}C${l/2} ${d*.72} ${l/2+c*.3} ${d*.5} ${l/2+c} ${d*.5}L${l-c} ${d*.5}C${l-c*.4} ${d*.5} ${l} ${d*.5} ${l} 0L${l-t*.2} ${t*.2}C${l-t*.4} ${d*.5-t} ${l-c*.4} ${d*.5-t} ${l-c} ${d*.5-t}L${l/2+c} ${d*.5-t}C${l/2+c*.3} ${d*.5-t} ${l/2+t*.4} ${d*.6} ${l/2} ${d*.82}C${l/2-t*.4} ${d*.6} ${l/2-c*.3} ${d*.5-t} ${l/2-c} ${d*.5-t}L${c} ${d*.5-t}C${c*.4} ${d*.5-t} ${t*.4} ${d*.5-t} ${t*.2} ${t*.2}Z`;const cos=dx/length,sin=dy/length;const path=transformPath(parseSvgPath(data),[cos,sin,-sin,cos,from[0],from[1]]);const node=styled(new Node(path),{...style,width:void 0},{fill:style.stroke??style.fill??"ink"});node.data["tip"]=[(from[0]+to2[0])/2-sin*depth,(from[1]+to2[1])/2+cos*depth];return node}var Axes=class extends Node{xRange;yRange;plotWidth;plotHeight;lines=new Node;grid=new Node;numbers=new Node;constructor(options={}){super();this.xRange=options.x??[-5,5];this.yRange=options.y??[-3,3];this.plotWidth=options.width??1100;this.plotHeight=options.height??640;const color=options.color??"dim";const xStep=options.xStep??niceStep(this.xRange[1]-this.xRange[0]);const yStep=options.yStep??niceStep(this.yRange[1]-this.yRange[0]);const originX=clampInto(0,this.xRange),originY=clampInto(0,this.yRange);const left=this.p(this.xRange[0],originY),right=this.p(this.xRange[1],originY);const bottom=this.p(originX,this.yRange[0]),top=this.p(originX,this.yRange[1]);if(options.grid){for(const x of ticks(this.xRange,xStep)){this.grid.add(line(this.p(x,this.yRange[0]),this.p(x,this.yRange[1]),{stroke:"grid",width:1.25}))}for(const y of ticks(this.yRange,yStep)){this.grid.add(line(this.p(this.xRange[0],y),this.p(this.xRange[1],y),{stroke:"grid",width:1.25}))}}const tips=options.tips??true;const axis=(from,to2)=>tips?arrow(from,to2,{stroke:color,width:2,tip:13}):line(from,to2,{stroke:color,width:2});this.lines.add(axis(left,right),axis(bottom,top));const tickSize=6;for(const x of ticks(this.xRange,xStep)){if(x===originX)continue;const[px,py]=this.p(x,originY);this.lines.add(line([px,py-tickSize],[px,py+tickSize],{stroke:color,width:2}))}for(const y of ticks(this.yRange,yStep)){if(y===originY)continue;const[px,py]=this.p(originX,y);this.lines.add(line([px-tickSize,py],[px+tickSize,py],{stroke:color,width:2}))}if(options.labels??true){const size=options.labelSize??20;for(const x of ticks(this.xRange,xStep)){if(x===originX)continue;const[px,py]=this.p(x,originY);this.numbers.add(tex(formatTick(x),{size,color:"dim",display:false}).moveTo([px,py+26]))}for(const y of ticks(this.yRange,yStep)){if(y===originY)continue;const[px,py]=this.p(originX,y);this.numbers.add(tex(formatTick(y),{size,color:"dim",display:false}).moveTo([px-28,py]))}}this.add(this.grid,this.lines,this.numbers);if(options.xLabel)this.add(tex(options.xLabel,{size:28,color:"ink",display:false}).moveTo([right[0]+4,right[1]-26]));if(options.yLabel){const label=tex(options.yLabel,{size:28,color:"ink",display:false});this.add(label.moveTo([top[0]+16+label.width/2,top[1]+4]))}}p(x,y){const[x0,x1]=this.xRange,[y0,y1]=this.yRange;return[((x-x0)/(x1-x0)-.5)*this.plotWidth,(.5-(y-y0)/(y1-y0))*this.plotHeight]}world(x,y){const[lx,ly]=this.p(x,y);return this.toWorld(lx,ly)}plotPath(f,options={}){const from=options.from??this.xRange[0],to2=options.to??this.xRange[1];const samples=options.samples??160;const[y0,y1]=this.yRange;const margin=(y1-y0)*.02;const points=[];for(let i=0;i<=samples;i++){const x=from+(to2-from)*i/samples;const y=f(x);points.push(Number.isFinite(y)&&y>=y0-margin&&y<=y1+margin?this.p(x,y):[NaN,NaN])}return curveThrough(points)}plot(f,style={}){const curve2=new Node(this.plotPath(f,style)).stroke(style.stroke??"blue",style.width??4);if(style.glow)curve2.glow(style.glow);if(style.dash)curve2.dash(style.dash);this.add(curve2);return curve2}dotAt(x,y,color="yellow",radius=9){const point=dot(radius,color).at(this.p(x,y));this.add(point);return point}guides(x,y,style={}){const originX=clampInto(0,this.xRange),originY=clampInto(0,this.yRange);const made=group(line(this.p(x,originY),this.p(x,y),{stroke:"dim",width:2,dash:[6,7],...style}),line(this.p(originX,y),this.p(x,y),{stroke:"dim",width:2,dash:[6,7],...style}));this.add(made);return made}};function axes(options={}){return new Axes(options)}function clampInto(value,range){return Math.max(range[0],Math.min(range[1],value))}function niceStep(span){const rough=span/8;const power=Math.pow(10,Math.floor(Math.log10(rough)));const unit=rough/power;return(unit<1.5?1:unit<3.5?2:unit<7.5?5:10)*power}function ticks(range,step){const out=[];const first=Math.ceil(range[0]/step-1e-9)*step;for(let value=first;value<=range[1]+1e-9;value+=step)out.push(Math.round(value/step)*step);return out}function formatTick(value){const rounded=Math.round(value*1e3)/1e3;return String(rounded)}var NumberPlane=class extends Node{unit;major=new Node;minor=new Node;axes=new Node;constructor(options={}){super();this.unit=options.unit??120;const[x0,x1]=options.x??[-12,12];const[y0,y1]=options.y??[-8,8];const u=this.unit;const stroke=options.color??"blue";const width=options.width??1.6;const minorPerUnit=options.minor??0;const segment=(a,b,count)=>{const points=[];for(let i=0;i<=count;i++)points.push([a[0]+(b[0]-a[0])*i/count,a[1]+(b[1]-a[1])*i/count]);return points.length>2?curveThrough(points):linePath(a,b)};const density=16;const add2=(parent,a,b,color,w,count)=>{parent.add(new Node(segment(a,b,count)).stroke(color,w))};for(let x=x0;x<=x1;x++){if(minorPerUnit>0&&x<x1){for(let k=1;k<minorPerUnit;k++){const mx=x+k/minorPerUnit;add2(this.minor,[mx*u,y0*u],[mx*u,y1*u],"grid",1,density)}}if(x!==0)add2(this.major,[x*u,y0*u],[x*u,y1*u],stroke,width,density)}for(let y=y0;y<=y1;y++){if(minorPerUnit>0&&y<y1){for(let k=1;k<minorPerUnit;k++){const my=y+k/minorPerUnit;add2(this.minor,[x0*u,my*u],[x1*u,my*u],"grid",1,density)}}if(y!==0)add2(this.major,[x0*u,y*u],[x1*u,y*u],stroke,width,density)}const axisColor=options.axisColor??"ink";add2(this.axes,[x0*u,0],[x1*u,0],axisColor,2.6,density);add2(this.axes,[0,y0*u],[0,y1*u],axisColor,2.6,density);this.add(this.minor,this.major,this.axes)}p(x,y){return[x*this.unit,-y*this.unit]}vector(x,y,style={}){return arrow([0,0],this.p(x,y),{stroke:"yellow",width:5,tip:22,...style})}};function plane(options={}){return new NumberPlane(options)}function decimal(read2,options={}){const node=new Node;node.draw=()=>{const value=read2();const body=(options.prefix??"")+value.toFixed(options.digits??2)+(options.suffix??"");return text(body,{size:options.size??36,color:options.color??"ink",font:options.font??"mono"})};return node}function reveal(node,t,stage){if(!node.mounted){clock.now=t;stage.add(node)}for(let n=node;n&&n!==stage.root;n=n.parent){if(!sampleAt(n,"visible",t))n.track("visible").step(t,true)}}function sampleAt(node,prop,t){const saved=clock.now;clock.now=t;const value=node.get(prop);clock.now=saved;return value}function stepAt2(node,prop,value,t){node.track(prop).step(t,value)}function tweenValue(value,to2,t0,t1,ease){const from=value.track.sample(t0);value.track.add({t0,t1,ease,to:to2,at:a=>from+(to2-from)*a})}function staggered(count,lag,t0,t1){if(count===0)return[];const each=(t1-t0)/(1+(count-1)*lag);return Array.from({length:count},(_,i)=>{const start=t0+i*lag*each;return[start,start+each]})}function labelNode(label,options){if(typeof label!=="string")return label;if(options.math)return tex(label,{size:options.size,color:options.color??"ink",display:false});return text(label,{size:options.size,color:options.color??"ink",font:options.font??"sans",weight:options.weight??400})}function luminance2(color){const f=v=>{const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*f(color[0])+.7152*f(color[1])+.0722*f(color[2])}function solidColor(input){if(typeof input==="string")return parseColor(input);if(Array.isArray(input))return input;const stops=input.stops;return stops[0][1]}function seededRandom2(seed){let state=seed>>>0;return()=>{state=state+1831565813>>>0;let v=Math.imul(state^state>>>15,1|state);v^=v+Math.imul(v^v>>>7,61|v);return((v^v>>>14)>>>0)/4294967296}}function stepsBetween(min,max,step){const out=[];const first=Math.ceil(min/step-1e-9)*step;for(let value=first;value<=max+step*1e-6;value+=step)out.push(Math.round(value/step)*step);return out}function niceTicks(min,max,count=5){const span=max-min||1;const rough=span/Math.max(1,count);const power=Math.pow(10,Math.floor(Math.log10(rough)));const unit=rough/power;const step=(unit<1.5?1:unit<3.5?2:unit<7.5?5:10)*power;return{ticks:stepsBetween(min,max,step),step}}function formatNumber(value,step){if(step!==void 0&&step<1){const digits=Math.min(4,Math.ceil(-Math.log10(step)-1e-9));return value.toFixed(digits)}const rounded=Math.round(value*1e3)/1e3;if(Math.abs(rounded)>=1e3&&Number.isInteger(rounded))return rounded.toLocaleString("en-US");return String(rounded)}function polylineRing(points){const first=points[0];const out=new Array(2+(points.length-1)*6);out[0]=first[0];out[1]=first[1];for(let i=1;i<points.length;i++){const a=points[i-1],b=points[i];const o=2+(i-1)*6;out[o]=a[0]+(b[0]-a[0])/3;out[o+1]=a[1]+(b[1]-a[1])/3;out[o+2]=a[0]+(b[0]-a[0])*2/3;out[o+3]=a[1]+(b[1]-a[1])*2/3;out[o+4]=b[0];out[o+5]=b[1]}return{p:Float64Array.from(out),closed:false,straight:true}}var read=value=>typeof value==="function"?value():value;var NumberLine2=class extends Node{range;length;line;ticks=new Node;numbers=new Node;constructor(options={}){super();this.range=options.range??[-5,5];this.length=options.length??1200;const color=options.color??"dim";const width=options.width??2;const half=this.length/2;const tips=options.tips??true;this.line=tips?arrow([-half-36,0],[half+36,0],{stroke:color,width,tip:14,both:true}):line([-half,0],[half,0],{stroke:color,width});const step=options.step??1;for(const value of stepsBetween(this.range[0],this.range[1],step)){const[x]=this.p(value);this.ticks.add(line([x,-7],[x,7],{stroke:color,width}));if(options.labels??true){const size=options.labelSize??24;const label=tex(String(Math.round(value*1e3)/1e3),{size,color:"dim",display:false});label.set("py",-size*.25);this.numbers.add(label.at(x,34))}}this.add(this.line,this.ticks,this.numbers)}p(value){const[min,max]=this.range;return[((value-min)/(max-min)-.5)*this.length,0]}world(value){const[x,y]=this.p(value);return this.toWorld(x,y)}marker(value,options={}){const color=options.color??"yellow";const size=options.labelSize??28;const build=()=>{const[x]=this.p(read(value));const parts=[dot(options.radius??9,color).at(x,0)];if(options.label)parts.push(tex(options.label,{size,color,display:false}).at(x,-size*1.15));return parts};const node=typeof value==="function"?dynamic(build):new Node().add(...build());this.add(node);return node}interval(from,to2,options={}){const color=options.color??"blue";const offset=options.offset??0;const[a]=this.p(from),[b]=this.p(to2);const band=line([a,offset],[b,offset],{stroke:color,width:options.width??7});const end=(x,open)=>open?dot(9,"bg").stroke(color,4).at(x,offset):dot(9,color).at(x,offset);const node=new Node().add(band,end(a,options.openLeft),end(b,options.openRight));this.add(node);return node}};function numberLine(options={}){return new NumberLine2(options)}var ComplexPlane=class extends NumberPlane{numbers=new Node;constructor(options={}){super(options);const range=options.labelRange??3;const size=options.labelSize??22;for(let k=-range;k<=range;k++){if(k===0)continue;const real=tex(String(k),{size,color:"ink",display:false});real.set("py",-size*.25);this.numbers.add(real.at(k*this.unit,22));const name=k===1?"i":k===-1?"-i":`${k}i`;const imaginary=tex(name,{size,color:"ink",display:false});imaginary.set("py",-size*.25);this.numbers.add(imaginary.at(-size*.9,-k*this.unit))}this.add(this.numbers)}z(re,im){return this.p(re,im)}};function complexPlane(options={}){return new ComplexPlane(options)}function applyComplex(plane2,f,options={}){const inverse=invert(plane2.worldMatrix());const world=plane2.worldMatrix();const unit=plane2.unit;const anim=warp([plane2.minor,plane2.major,plane2.axes],(x,y)=>{const[lx,ly]=apply(inverse,x,y);const[re,im]=f(lx/unit,-ly/unit);return apply(world,re*unit,-im*unit)},{duration:3,...options});return{...anim,label:"applyComplex"}}var complex={mul:(a,b)=>[a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]],div:(a,b)=>{const d=b[0]*b[0]+b[1]*b[1]||1e-12;return[(a[0]*b[0]+a[1]*b[1])/d,(a[1]*b[0]-a[0]*b[1])/d]},exp:a=>{const r=Math.exp(a[0]);return[r*Math.cos(a[1]),r*Math.sin(a[1])]},log:a=>[Math.log(Math.hypot(a[0],a[1])||1e-12),Math.atan2(a[1],a[0])],pow:(a,n)=>{const r=Math.pow(Math.hypot(a[0],a[1]),n),angle=Math.atan2(a[1],a[0])*n;return[r*Math.cos(angle),r*Math.sin(angle)]},sin:a=>[Math.sin(a[0])*Math.cosh(a[1]),Math.cos(a[0])*Math.sinh(a[1])],cos:a=>[Math.cos(a[0])*Math.cosh(a[1]),-Math.sin(a[0])*Math.sinh(a[1])],inv:a=>{const d=a[0]*a[0]+a[1]*a[1]||1e-12;return[a[0]/d,-a[1]/d]}};function arrowRing(x0,y0,dx,dy,thickness){const length=Math.hypot(dx,dy)||1e-6;const ux=dx/length,uy=dy/length;const tip=Math.min(length*.42,thickness*5.2);const half=thickness/2;const head=tip*.42;const bx=x0+dx-ux*tip,by=y0+dy-uy*tip;const nx=-uy,ny=ux;return polyPath([[x0+nx*half,y0+ny*half],[bx+nx*half,by+ny*half],[bx+nx*head,by+ny*head],[x0+dx,y0+dy],[bx-nx*head,by-ny*head],[bx-nx*half,by-ny*half],[x0-nx*half,y0-ny*half]],true)[0]}var VectorField=class extends Node{constructor(f,options={}){super();this.f=f;const unit=this.unit=options.unit??120;const[x0,x1]=options.x??[-8,8];const[y0,y1]=options.y??[-4.5,4.5];const step=options.step??.5;const longest=options.maxLength??step*unit*.92;const width=options.width??2.6;const palette=(options.colors??["blue","teal","green","yellow","orange","red"]).map(c=>toPaint(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const positions=[];for(const y of stepsBetween(y0,y1,step))for(const x of stepsBetween(x0,x1,step))positions.push([x,y]);const magnitude=options.max??(()=>{const samples=positions.map(([x,y])=>{const[u,v]=f(x,y,0);return Math.hypot(u,v)}).filter(Number.isFinite).sort((a,b)=>a-b);return samples[Math.floor(samples.length*.9)]||1})();const shape2=(x,y,t)=>{const[u,v]=f(x,y,t);const m=Math.hypot(u,v);if(!Number.isFinite(m)||m<1e-9)return null;const amount2=Math.min(1,m/magnitude);const length=longest*(.22+.78*(1-Math.exp(-2.2*m/magnitude)));const dx=u/m*length,dy=-(v/m)*length;const px=x*unit,py=-y*unit;return{ring:arrowRing(px-dx/2,py-dy/2,dx,dy,width),at:amount2,cx:px,cy:py}};if(options.animate){const bands=12;this.draw=time=>{const rings=Array.from({length:bands},()=>[]);for(const[x,y]of positions){const made=shape2(x,y,time);if(made)rings[Math.min(bands-1,Math.floor(made.at*bands))].push(made.ring)}return rings.flatMap((list3,band)=>list3.length===0?[]:[new Node(list3).fill(sampleStops(stops,(band+.5)/bands))])};return}for(const[x,y]of positions){const made=shape2(x,y,0);if(!made)continue;const leaf=recenter([made.ring]).fill(sampleStops(stops,made.at));this.arrows.push(leaf);this.add(leaf)}}f;unit;arrows=[]};function recenter(path){const b=pathBounds(path);if(!b)return new Node(path);const cx=b.x+b.width/2,cy=b.y+b.height/2;const shifted=path.map(r=>{const out=new Float64Array(r.p.length);for(let i=0;i<out.length;i+=2){out[i]=r.p[i]-cx;out[i+1]=r.p[i+1]-cy}return{p:out,closed:r.closed}});return new Node(shifted).at(cx,cy)}function vectorField(f,options={}){return new VectorField(f,options)}var StreamLines=class extends Node{lineCount;constructor(f,options={}){super();const unit=options.unit??120;const[x0,x1]=options.x??[-8.5,8.5];const[y0,y1]=options.y??[-5,5];const spacing=options.spacing??.55;const dt=options.dt??.03;const steps=options.steps??130;const width=options.width??2.2;const speed=options.speed??.35;const tail=options.tail??.42;const random=seededRandom2(options.seed??7);const palette=(options.colors??["blue","teal","green","yellow","orange","red"]).map(c=>toPaint(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const lines=[];const speeds=[];const margin=.6;for(let sy=y0;sy<=y1;sy+=spacing){for(let sx=x0;sx<=x1;sx+=spacing){let x=sx+(random()-.5)*spacing,y=sy+(random()-.5)*spacing;const phase=random();const points=[[x*unit,-y*unit]];let total=0;for(let i=0;i<steps;i++){const[k1u,k1v]=f(x,y,0);const[k2u,k2v]=f(x+k1u*dt/2,y+k1v*dt/2,0);const[k3u,k3v]=f(x+k2u*dt/2,y+k2v*dt/2,0);const[k4u,k4v]=f(x+k3u*dt,y+k3v*dt,0);const u=(k1u+2*k2u+2*k3u+k4u)/6,v=(k1v+2*k2v+2*k3v+k4v)/6;if(!Number.isFinite(u)||!Number.isFinite(v))break;const m=Math.hypot(u,v);total+=m;if(m<1e-6)break;x+=u*dt;y+=v*dt;if(x<x0-margin||x>x1+margin||y<y0-margin||y>y1+margin)break;if(i%2===1)points.push([x*unit,-y*unit])}if(points.length<5)continue;const mean=total/(points.length*2);speeds.push(mean);lines.push({points,phase,speedRate:.8+random()*.4,color:mean})}}const sorted=[...speeds].sort((a,b)=>a-b);const top=options.max??(sorted[Math.floor(sorted.length*.92)]||1);const colorBands=8;for(const entry of lines)entry.color=Math.min(colorBands-1,Math.floor(Math.min(1,entry.color/top)*colorBands));this.lineCount=lines.length;const fadeBands=6;const trace=options.trace??0;const tracePath=Array.from({length:colorBands},()=>[]);if(trace>0)for(const entry of lines)tracePath[entry.color].push(polylineRing(entry.points));this.draw=time=>{const buckets=Array.from({length:colorBands*fadeBands},()=>[]);for(const entry of lines){const count=entry.points.length;const window=Math.max(3,Math.floor(count*tail));const travel=count+window;const head=(time*speed*entry.speedRate+entry.phase)%1*travel;for(let band=0;band<fadeBands;band++){const from=Math.floor(head-window*(1-band/fadeBands));const to2=Math.floor(head-window*(1-(band+1)/fadeBands));const a=Math.max(0,from),b=Math.min(count-1,to2);if(b-a<1)continue;buckets[entry.color*fadeBands+band].push(polylineRing(entry.points.slice(a,b+1)))}}const out=[];if(trace>0){tracePath.forEach((rings,c)=>{if(rings.length)out.push(new Node(rings).stroke(sampleStops(stops,(c+.5)/colorBands),width*.6).set("strokeOpacity",trace))})}buckets.forEach((rings,index)=>{if(rings.length===0)return;const c=Math.floor(index/fadeBands),band=index%fadeBands;const node=new Node(rings).stroke(sampleStops(stops,(c+.5)/colorBands),width);node.set("strokeOpacity",Math.pow((band+1)/fadeBands,1.6));if(band<fadeBands-1)node.set("cap","butt");out.push(node)});return out}}};function streamLines(f,options={}){return new StreamLines(f,options)}function riemann(axes2,f,options={}){const from=options.from??axes2.xRange[0],to2=options.to??axes2.xRange[1];const n=options.n??12;const rule=options.rule??"mid";const colors2=ramp(n,...options.colors??["blue","teal","green"]);const made=new Node;const dx=(to2-from)/n;for(let i=0;i<n;i++){const left=from+i*dx;const sample=rule==="left"?left:rule==="right"?left+dx:left+dx/2;const y=f(sample);const[ax,ay]=axes2.p(left,0),[bx,by]=axes2.p(left+dx,y);const leaf=recenter(polyPath([[ax,ay],[bx,ay],[bx,by],[ax,by]],true));leaf.fill(colors2[i],options.opacity??.72);leaf.stroke(options.stroke??"bg",options.strokeWidth??(n>40?.5:1.4));made.add(leaf)}axes2.add(made);return made}function areaPath(axes2,f,from,to2,samples){const points=[];for(let i=0;i<=samples;i++){const x=from+(to2-from)*i/samples;points.push(axes2.p(x,f(x)))}points.push(axes2.p(to2,0),axes2.p(from,0));return polyPath(points,true)}function areaUnder(axes2,f,options={}){const samples=options.samples??96;const color=options.fill??"blue";const opacity=options.opacity??.28;const from=options.from??axes2.xRange[0],to2=options.to??axes2.xRange[1];const node=typeof from==="function"||typeof to2==="function"?dynamic(()=>{const a=read(from),b=read(to2);return Math.abs(b-a)<1e-9?null:new Node(areaPath(axes2,f,a,b,samples)).fill(color,opacity)}):new Node(areaPath(axes2,f,from,to2,samples)).fill(color,opacity);axes2.add(node);return node}function slopeAt(axes2,f,x){const span=axes2.xRange[1]-axes2.xRange[0];const h=span*1e-4;const a=axes2.p(x-h,f(x-h)),b=axes2.p(x+h,f(x+h));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return{point:axes2.p(x,f(x)),ux:(b[0]-a[0])/length,uy:(b[1]-a[1])/length}}function tangentLine(axes2,f,x,style={}){const length=style.length??420;const color=style.stroke??"yellow";const build=()=>{const{point,ux,uy}=slopeAt(axes2,f,read(x));const parts=[line([point[0]-ux*length/2,point[1]-uy*length/2],[point[0]+ux*length/2,point[1]+uy*length/2],{stroke:color,width:style.width??3.5,glow:style.glow,dash:style.dash})];if(style.point??true)parts.push(dot(8,color).at(point));return parts};const node=typeof x==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function secantLine(axes2,f,a,b,style={}){const extend=style.extend??140;const color=style.stroke??"yellow";const build=()=>{const xa=read(a),xb=read(b);const pa=axes2.p(xa,f(xa)),pb=axes2.p(xb,f(xb));const length=Math.hypot(pb[0]-pa[0],pb[1]-pa[1])||1;const ux=(pb[0]-pa[0])/length,uy=(pb[1]-pa[1])/length;const parts=[line([pa[0]-ux*extend,pa[1]-uy*extend],[pb[0]+ux*extend,pb[1]+uy*extend],{stroke:color,width:style.width??3.5,glow:style.glow})];if(style.legs){const corner=[pb[0],pa[1]];const leg=style.legColor??"dim";parts.unshift(line(pa,corner,{stroke:leg,width:2,dash:[6,7]}),line(corner,pb,{stroke:leg,width:2,dash:[6,7]}))}if(style.points??true)parts.push(dot(8,color).at(pa),dot(8,color).at(pb));return parts};const node=typeof a==="function"||typeof b==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function dashedGuides(axes2,x,y,style={}){const build=()=>{const px=read(x),py=read(y);const originX=Math.max(axes2.xRange[0],Math.min(axes2.xRange[1],0));const originY=Math.max(axes2.yRange[0],Math.min(axes2.yRange[1],0));const common={stroke:"dim",width:2,dash:[6,7],...style};return[line(axes2.p(px,originY),axes2.p(px,py),common),line(axes2.p(originX,py),axes2.p(px,py),common)]};const node=typeof x==="function"||typeof y==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function angleMark(vertex,from,to2,options={}){const radius=options.radius??54;const color=options.color??"yellow";const a0=Math.atan2(from[1]-vertex[1],from[0]-vertex[0]);let sweep=Math.atan2(to2[1]-vertex[1],to2[0]-vertex[0])-a0;while(sweep<=-Math.PI)sweep+=Math.PI*2;while(sweep>Math.PI)sweep-=Math.PI*2;if(options.reflex)sweep+=sweep>0?-Math.PI*2:Math.PI*2;const node=new Node;if(options.fillOpacity){const points=[vertex];for(let i=0;i<=24;i++){const a=a0+sweep*i/24;points.push([vertex[0]+Math.cos(a)*radius,vertex[1]+Math.sin(a)*radius])}node.add(new Node(polyPath(points,true)).fill(color,options.fillOpacity))}node.add(new Node(arcPath(vertex[0],vertex[1],radius,radius,a0,a0+sweep)).stroke(color,options.width??3));if(options.label){const size=options.labelSize??30;const mid=a0+sweep/2;const distance=radius+size*.72;node.add(tex(options.label,{size,color,display:false}).at(vertex[0]+Math.cos(mid)*distance,vertex[1]+Math.sin(mid)*distance))}return node}function rightAngle(vertex,a,b,options={}){const size=options.size??26;const unit=p=>{const dx=p[0]-vertex[0],dy=p[1]-vertex[1];const l=Math.hypot(dx,dy)||1;return[dx/l,dy/l]};const[ax,ay]=unit(a),[bx,by]=unit(b);return new Node(polyPath([[vertex[0]+ax*size,vertex[1]+ay*size],[vertex[0]+(ax+bx)*size,vertex[1]+(ay+by)*size],[vertex[0]+bx*size,vertex[1]+by*size]])).stroke(options.color??"ink",options.width??2.5)}var DELIMITERS={"[":["[","]"],"(":["(",")"],"|":["|","|"]};var MatrixNode=class extends Node{cells;entries=new Node;brackets=new Node;rowCount;colCount;positions;options;constructor(rows,options={}){super();this.options=options;const size=options.size??52;const color=options.color??"ink";this.rowCount=rows.length;this.colCount=Math.max(0,...rows.map(row=>row.length));const made=rows.map(row=>row.map(value=>{const cell=tex(String(value),{size,color,display:false});cell.set("py",-size*.25);return cell}));const widths=Array.from({length:this.colCount},(_,j)=>Math.max(0,...made.map(row=>row[j]?.width??0)));const gapX=(options.gapX??.85)*size;const rowStep=(options.gapY??1.32)*size;const totalWidth=widths.reduce((sum,w)=>sum+w,0)+gapX*Math.max(0,this.colCount-1);const totalHeight=rowStep*Math.max(0,this.rowCount-1)+size;const columnX=[];let cursor=-totalWidth/2;for(const width of widths){columnX.push(cursor+width/2);cursor+=width+gapX}this.positions=made.map((row,i)=>row.map((cell,j)=>{const position2=[columnX[j],(i-(this.rowCount-1)/2)*rowStep];cell.at(position2);this.entries.add(cell);return position2}));this.cells=made;const kind=DELIMITERS[options.bracket??"["];const em=(totalHeight+size*.5)/size;const stretch=`\\rule{0pt}{${(em/2+.25).toFixed(3)}em}`;const pad2=size*.42;const left=tex(`\\left${kind[0]}${stretch}\\right.`,{size,color:options.bracketColor??color});const right=tex(`\\left.${stretch}\\right${kind[1]}`,{size,color:options.bracketColor??color});left.moveTo([-totalWidth/2-pad2-left.width/2,0]);right.moveTo([totalWidth/2+pad2+right.width/2,0]);this.brackets.add(left,right);this.add(this.brackets,this.entries)}cell(row,column){const found=this.cells[row]?.[column];if(!found)throw new Error(`Matrix has no cell (${row}, ${column}). It is ${this.rowCount} by ${this.colCount}.`);return found}row(index){return[...this.cells[index]??[]]}col(index){return this.cells.map(row=>row[index]).filter(Boolean)}setCell(row,column,value,options={}){const size=this.options.size??52;const next=tex(String(value),{size,color:this.options.color??"ink",display:false});next.set("py",-size*.25);const position2=this.positions[row][column];next.at(position2);const previous=this.cell(row,column);const self=this;const anim=morphMatching(previous,next,{duration:.8,...options});return{...anim,schedule(ctx){self.entries.add(next);next.track("visible").initial=false;self.cells[row][column]=next;anim.schedule(ctx)}}}};function matrix(rows,options={}){return new MatrixNode(rows,options)}function boundsOf2(target){const list3=Array.isArray(target)?target:[target];let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const node of list3){const b=node.bounds();x0=Math.min(x0,b.x);y0=Math.min(y0,b.y);x1=Math.max(x1,b.x+b.width);y1=Math.max(y1,b.y+b.height)}return{x:x0,y:y0,width:x1-x0,height:y1-y0}}function braceLabel(target,label,options={}){const b=boundsOf2(target);const side=options.side??"bottom";const gap=options.gap??12;const color=options.color??"ink";const size=options.size??34;const left=b.x,right=b.x+b.width,top=b.y,bottom=b.y+b.height;const[from,to2]=side==="bottom"?[[left,bottom+gap],[right,bottom+gap]]:side==="top"?[[right,top-gap],[left,top-gap]]:side==="left"?[[left-gap,top],[left-gap,bottom]]:[[right+gap,bottom],[right+gap,top]];const mark=brace(from,to2,{stroke:color,depth:options.depth});const tip=mark.data["tip"];const caption=labelNode(label,{size,color,math:!options.plain});caption.moveTo(tip);const dir=direction(side);const shifted=10+(dir[0]!==0?caption.width/2:caption.height/2);caption.shift(dir[0]*shifted,dir[1]*shifted);return new Node().add(mark,caption)}function surroundingBox(target,options={}){const b=boundsOf2(target);const pad2=options.pad??12;const box=rect(b.width+pad2*2,b.height+pad2*2,{radius:options.radius??8,stroke:options.color??"yellow",width:options.width??2.5,glow:options.glow});if(options.fill)box.fill(options.fill,options.fillOpacity??.14);return box.at(b.x+b.width/2,b.y+b.height/2)}var LabeledDot=class extends Node{mark;caption;constructor(label,options={}){super();const color=options.color??"yellow";this.mark=dot(options.radius??9,color);this.caption=labelNode(label,{size:options.size??30,color:options.labelColor??color,math:!options.plain});this.add(this.mark,this.caption);this.caption.nextTo(this.mark,options.side??[.72,-.72],options.gap??8)}};function labeledDot(label,options={}){return new LabeledDot(label,options)}function traced(point,from,to2,options={}){const color=options.color??"yellow";const width=options.width??3;const rate=options.rate??60;const fade2=options.fade??(options.tail!==void 0?0:1);const bands=fade2>=1?1:10;const cache2=new Map;const sample=index=>{const cached=cache2.get(index);if(cached)return cached;const saved=clock.now;clock.now=from+index/rate;const value=point();clock.now=saved;if(clock.mode==="render")cache2.set(index,value);return value};return dynamic(time=>{if(time<=from)return null;const end=Math.min(time,to2);const start=options.tail!==void 0?Math.max(from,end-options.tail):from;const i0=Math.ceil((start-from)*rate),i1=Math.floor((end-from)*rate);if(i1-i0<1)return null;const points=[];for(let i=i0;i<=i1;i++)points.push(sample(i));const saved=clock.now;clock.now=end;points.push(point());clock.now=saved;const out=[];for(let band=0;band<bands;band++){const a=Math.floor((points.length-1)*band/bands);const b=Math.min(points.length-1,Math.floor((points.length-1)*(band+1)/bands));if(b-a<1)continue;const node=new Node([polylineRing(points.slice(a,b+1))]).stroke(color,width);const light=bands===1?1:fade2+(1-fade2)*Math.pow((band+1)/bands,1.5);node.set("strokeOpacity",light);if(band<bands-1)node.set("cap","butt");if(options.glow)node.glow(options.glow);out.push(node)}return out})}function fourier(points,options={}){const n=points.length;const out=[];for(let k=0;k<n;k++){const freq=k<=n/2?k:k-n;let re=0,im=0;for(let i=0;i<n;i++){const angle=-2*Math.PI*freq*i/n;const c=Math.cos(angle),s=Math.sin(angle);const[x,y]=points[i];re+=x*c-y*s;im+=x*s+y*c}out.push({freq,amp:Math.hypot(re,im)/n,phase:Math.atan2(im,re)})}out.sort((a,b)=>b.amp-a.amp||a.freq-b.freq);return options.terms?out.slice(0,options.terms):out}function fourierPoint(terms,u){let x=0,y=0;for(const term of terms){const angle=2*Math.PI*term.freq*u+term.phase;x+=term.amp*Math.cos(angle);y+=term.amp*Math.sin(angle)}return[x,y]}function samplePath(path,count){const total=pathLength(path);if(total===0)return[];return Array.from({length:count},(_,i)=>pointAt(path,i/count))}var Epicycles=class extends Node{terms;outlinePoints;constructor(terms,options){super();this.terms=[...terms].sort((a,b)=>(a.freq===0?-1:b.freq===0?1:0)||b.amp-a.amp);const samples=options.samples??1024;this.outlinePoints=Array.from({length:samples+1},(_,i)=>fourierPoint(this.terms,i/samples));const circles=options.circles??64;const circleColor=options.circleColor??"blue";const armColor=options.armColor??"ink";const traceColor=options.traceColor??"yellow";const traceWidth=options.traceWidth??3.5;const tail=options.tail??1;const fadeBands=12;this.draw=()=>{const u=options.u();const cycle=u-Math.floor(u);const out=[];let x=0,y=0;const joints=[];const bands=[[],[],[],[]];this.terms.forEach((term,index)=>{const angle=2*Math.PI*term.freq*cycle+term.phase;const nx=x+term.amp*Math.cos(angle),ny=y+term.amp*Math.sin(angle);if(index<circles&&term.freq!==0&&term.amp>.4){bands[Math.min(3,Math.floor(index/Math.max(1,circles)*4))].push(...circlePath(x,y,term.amp))}x=nx;y=ny;if(index<circles)joints.push([x,y])});bands.forEach((rings,band)=>{if(rings.length)out.push(new Node(rings).stroke(circleColor,1.2).set("strokeOpacity",[.55,.36,.22,.14][band]))});if(joints.length>=2)out.push(new Node([polylineRing(joints)]).stroke(armColor,1.4).set("strokeOpacity",.85));const count=this.outlinePoints.length-1;const reach=u>=1?count:Math.floor(cycle*count);const start=Math.max(0,reach-Math.floor(count*tail));if(reach-start>=2){if(tail>=1){const trace=new Node([polylineRing(this.outlinePoints.slice(start,reach+1))]).stroke(traceColor,traceWidth);if(options.glow)trace.glow(options.glow);out.push(trace)}else{for(let band=0;band<fadeBands;band++){const a=start+Math.floor((reach-start)*band/fadeBands);const b=Math.min(reach,start+Math.floor((reach-start)*(band+1)/fadeBands));if(b-a<1)continue;const node=new Node([polylineRing(this.outlinePoints.slice(a,b+1))]).stroke(traceColor,traceWidth);node.set("strokeOpacity",Math.pow((band+1)/fadeBands,1.5));if(band<fadeBands-1)node.set("cap","butt");out.push(node)}}}if(u<1)out.push(dot(5,traceColor).at(x,y));return out}}outline(){return polyPath(this.outlinePoints.slice(0,-1),true)}point(u){return fourierPoint(this.terms,u)}};function epicycles(terms,options){return new Epicycles(terms,options)}function ringThrough(f,samples=200){const path=parametricPath(f,0,1,samples);return path.map(r=>ring(r.p,true))}var DEFAULT_SERIES=["blue","yellow","teal","orange","purple","green","pink","red"];function small(content,size,color="dim",font="sans"){return text(content,{size,color,font})}var BarChart2=class extends Node{bars=[];labels=[];readouts=[];baseline;values;maxValue;minValue;w;h;horizontal;band;gap;fixedMax;fixedMin;constructor(data,options={}){super();this.w=options.width??900;this.h=options.height??520;this.horizontal=options.horizontal??false;this.gap=options.gap??.28;this.fixedMax=options.max;this.fixedMin=options.min;const labelSize=options.labelSize??20;const count=Math.max(1,data.length);this.band=(this.horizontal?this.h:this.w)/count;const numbers=data.map(d=>d.value);this.maxValue=new Value(options.max??Math.max(0,...numbers));this.minValue=new Value(options.min??Math.min(0,...numbers));this.values=data.map(d=>new Value(d.value));const format=options.format??(v=>formatNumber(Math.round(v*100)/100));const baseColor=options.color??"faint";const[ax,ay]=this.place(0,0,"start"),[bx,by]=this.place(count-1,0,"end");this.baseline=line([ax,ay],[bx,by],{stroke:baseColor,width:1.5});data.forEach((datum,i)=>{const color=datum.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const bar=new Node(this.barPath(i,datum.value)).fill(color,.84);this.bars.push(bar);const label=small(datum.label,labelSize);this.labels.push(label);const[px,py]=this.place(i,0,"mid");if(this.horizontal)label.at(px-12-label.width/2,py);else label.at(px,py+12+labelSize/2);if(options.showValues??true){const readout=dynamic(()=>{const value=this.values[i].value;const[px2,py2]=this.tip(i,value);const node=small(format(value),labelSize,"ink","mono");if(this.horizontal)return node.at(px2+12+node.width/2,py2);return node.at(px2,py2+(value>=0?-1:1)*(10+labelSize*.6))});this.readouts.push(readout)}});this.add(...this.bars,this.baseline,...this.labels,...this.readouts)}lengthOf(value){const span=this.maxValue.value-this.minValue.value||1;return value/span*(this.horizontal?this.w:this.h)}place(i,_unused,at){const center2=(i+.5)*this.band;const half=this.band/2;const along3=at==="mid"?center2:at==="start"?center2-half:center2+half;const span=this.maxValue.value-this.minValue.value||1;if(this.horizontal){const zero2=-this.minValue.value/span*this.w-this.w/2;return[zero2,along3-this.h/2]}const zero=this.h/2- -this.minValue.value/span*this.h;return[along3-this.w/2,zero]}tip(i,value){const[px,py]=this.place(i,0,"mid");const length=this.lengthOf(value);return this.horizontal?[px+length,py]:[px,py-length]}barPath(i,value){const[px,py]=this.place(i,0,"mid");const thick=this.band*(1-this.gap);const length=this.lengthOf(value);if(this.horizontal)return rectPath(px,py-thick/2,length,thick);return rectPath(px-thick/2,py-length,thick,length)}bar(i){return this.bars[i]}enter(options={}){const lag=options.lag??.12;return{label:"barChart.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.baseline,"trimTo",0,ctx.t0);this.baseline.tween("trimTo",1,ctx.t0,ctx.t0+span*.4,ctx.ease);const windows=staggered(this.bars.length,lag,ctx.t0+span*.1,ctx.t1);this.bars.forEach((bar,i)=>{const[start,end]=windows[i];const target=this.values[i].track.sample(ctx.t0);this.values[i].track.step(ctx.t0,0);tweenValue(this.values[i],target,start,end,ctx.ease);bar.track("path").step(ctx.t0,this.barPath(i,0));bar.track("path").add({t0:start,t1:end,ease:ctx.ease,to:this.barPath(i,target),at:a=>this.barPath(i,target*a)});const label=this.labels[i];stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,start,start+(end-start)*.6,ctx.ease);const readout=this.readouts[i];if(readout){stepAt2(readout,"opacity",0,ctx.t0);readout.tween("opacity",1,start,start+(end-start)*.5,ctx.ease)}})}}}update(values,options={}){return{label:"barChart.update",duration:options.duration??1.1,ease:options.ease,schedule:ctx=>{const from=this.values.map(v=>v.track.sample(ctx.t0));const fromMax=this.maxValue.track.sample(ctx.t0),fromMin=this.minValue.track.sample(ctx.t0);const toMax=this.fixedMax??Math.max(0,...values),toMin=this.fixedMin??Math.min(0,...values);tweenValue(this.maxValue,toMax,ctx.t0,ctx.t1,ctx.ease);tweenValue(this.minValue,toMin,ctx.t0,ctx.t1,ctx.ease);values.forEach((value,i)=>{tweenValue(this.values[i],value,ctx.t0,ctx.t1,ctx.ease);const bar=this.bars[i];if(!bar)return;const at=a=>this.barPathAt(i,from[i]+(value-from[i])*a,fromMax+(toMax-fromMax)*a,fromMin+(toMin-fromMin)*a);bar.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:at(1),at})})}}}barPathAt(i,value,max,min){const span=max-min||1;const center2=(i+.5)*this.band;const thick=this.band*(1-this.gap);if(this.horizontal){const zero2=-min/span*this.w-this.w/2;return rectPath(zero2,center2-this.h/2-thick/2,value/span*this.w,thick)}const zero=this.h/2- -min/span*this.h;const length=value/span*this.h;return rectPath(center2-this.w/2-thick/2,zero-length,thick,length)}};function barChart(data,options={}){return new BarChart2(data,options)}var Histogram=class extends Node{shown;bins;range;chartWidth;chartHeight;axis=new Node;total;assigned;peak;constructor(samples,options={}){super();this.chartWidth=options.width??900;this.chartHeight=options.height??480;this.bins=options.bins??24;const low=options.range?.[0]??Math.min(...samples);const high=options.range?.[1]??Math.max(...samples);this.range=[low,high];this.total=samples.length;this.assigned=new Int32Array(samples.length);const counts2=new Int32Array(this.bins);samples.forEach((sample,i)=>{const bin=Math.min(this.bins-1,Math.floor((sample-low)/(high-low||1)*this.bins));this.assigned[i]=sample<low||sample>high?-1:bin;if(this.assigned[i]>=0)counts2[bin]++});this.peak=options.max??Math.max(1,...counts2);this.shown=new Value(samples.length);const labelSize=options.labelSize??20;const w=this.chartWidth,h=this.chartHeight;const baseline=line([-w/2,h/2],[w/2,h/2],{stroke:options.color??"faint",width:1.5});this.axis.add(baseline);const{ticks:ticks2,step}=niceTicks(low,high,options.ticks??6);for(const tick of ticks2){const x=this.xAt(tick);this.axis.add(line([x,h/2],[x,h/2+6],{stroke:"faint",width:1.5}));this.axis.add(small(formatNumber(tick,step),labelSize).at(x,h/2+12+labelSize*.6))}const palette=(options.colors??["blue"]).map(c=>solidColor(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const gap=options.gap??.12;const bars=dynamic(()=>{const n=Math.max(0,Math.min(this.total,Math.round(this.shown.value)));const current=new Int32Array(this.bins);for(let i=0;i<n;i++){const bin=this.assigned[i];if(bin>=0)current[bin]++}const width=w/this.bins;const rings=[];const out=[];for(let b=0;b<this.bins;b++){const height=current[b]/this.peak*h;if(height<=0)continue;const shape2=rectPath(-w/2+b*width+width*gap/2,h/2-height,width*(1-gap),height);if(palette.length===1)rings.push(...shape2);else out.push(new Node(shape2).fill(sampleStops(stops,b/Math.max(1,this.bins-1))))}if(rings.length)out.push(new Node(rings).fill(palette[0]));return out});this.add(bars,this.axis)}xAt(value){const[low,high]=this.range;return((value-low)/(high-low||1)-.5)*this.chartWidth}p(value,count){return[this.xAt(value),this.chartHeight/2-count/this.peak*this.chartHeight]}fillUp(options={}){const shown=this.shown;const target=options.count??this.total;return{label:"histogram.fill",duration:options.duration??3,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);if(shown.track.keys.length===0)shown.track.initial=0;tweenValue(shown,target,ctx.t0,ctx.t1,ctx.ease)}}}curve(f,options={}){const[low,high]=this.range;const samples=options.samples??120;const points=[];for(let i=0;i<=samples;i++){const x=low+(high-low)*i/samples;points.push(this.p(x,f(x)))}const node=new Node(smoothPath(points)).stroke(options.color??"yellow",options.width??4);this.add(node);return node}};function histogram(samples,options={}){return new Histogram(samples,options)}function xyPoint(frame,x,y){const{xRange,yRange,w,h}=frame;return[((x-xRange[0])/(xRange[1]-xRange[0]||1)-.5)*w,(.5-(y-yRange[0])/(yRange[1]-yRange[0]||1))*h]}function xyAxes(frame,options){const axis=new Node;const size=options.labelSize;const color=options.color??"faint";const{w,h}=frame;const x=niceTicks(frame.xRange[0],frame.xRange[1],options.xTicks??6);const y=niceTicks(frame.yRange[0],frame.yRange[1],options.yTicks??5);for(const value of y.ticks){const[,py]=xyPoint(frame,frame.xRange[0],value);if(options.gridY!==false)axis.add(line([-w/2,py],[w/2,py],{stroke:"grid",width:1.25}));const label=small(options.yFormat?options.yFormat(value):formatNumber(value,y.step),size);axis.add(label.at(-w/2-12-label.width/2,py))}axis.add(line([-w/2,h/2],[w/2,h/2],{stroke:color,width:1.5}));for(const value of x.ticks){const[px]=xyPoint(frame,value,frame.yRange[0]);axis.add(line([px,h/2],[px,h/2+6],{stroke:color,width:1.5}));axis.add(small(options.xFormat?options.xFormat(value):formatNumber(value,x.step),size).at(px,h/2+12+size*.6))}if(options.xLabel){const label=small(options.xLabel,size,"ink");axis.add(label.at(w/2-label.width/2,h/2+18+size*1.6))}if(options.yLabel){const label=small(options.yLabel,size,"ink");axis.add(label.at(-w/2+label.width/2,-h/2-12-size/2))}return axis}var Scatter=class extends Node{dots=[];axis;groupLabels=[];frame;constructor(points,options={}){super();const xs=points.map(p=>p.x),ys=points.map(p=>p.y);const pad2=(lo,hi)=>(hi-lo||1)*.06;const xRange=options.x??[Math.min(...xs)-pad2(Math.min(...xs),Math.max(...xs)),Math.max(...xs)+pad2(Math.min(...xs),Math.max(...xs))];const yRange=options.y??[Math.min(...ys)-pad2(Math.min(...ys),Math.max(...ys)),Math.max(...ys)+pad2(Math.min(...ys),Math.max(...ys))];this.frame={xRange,yRange,w:options.width??900,h:options.height??520};const labelSize=options.labelSize??18;this.axis=xyAxes(this.frame,{labelSize,color:options.color,xLabel:options.xLabel,yLabel:options.yLabel});const groups=new Map;const dots=points.map(point=>{let color=point.color;if(point.group!==void 0){let entry=groups.get(point.group);if(!entry){entry={color:color??DEFAULT_SERIES[groups.size%DEFAULT_SERIES.length],sumX:0,top:-Infinity,count:0};groups.set(point.group,entry)}color??=entry.color;entry.sumX+=point.x;entry.top=Math.max(entry.top,point.y);entry.count++}const made=dot(point.radius??options.radius??6,color??"blue").at(xyPoint(this.frame,point.x,point.y));made.set("fillOpacity",.92);return made});this.dots.push(...dots);this.add(this.axis,...dots);if(options.groupLabels??true){for(const[name,entry]of groups){const label=small(name,labelSize+2,entry.color);const[px,py]=xyPoint(this.frame,entry.sumX/entry.count,entry.top);label.at(px,py-labelSize*1.2);this.groupLabels.push(label);this.add(label)}}}p(x,y){return xyPoint(this.frame,x,y)}enter(options={}){const lag=options.lag??Math.min(.2,8/Math.max(1,this.dots.length));return{label:"scatter.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.axis,"opacity",0,ctx.t0);this.axis.tween("opacity",1,ctx.t0,ctx.t0+span*.3,ctx.ease);const order=[...this.dots].sort((a,b)=>a.get("x")-b.get("x"));const windows=staggered(order.length,lag,ctx.t0+span*.15,ctx.t1);order.forEach((point,i)=>{const[start,end]=windows[i];const sx=point.get("sx");stepAt2(point,"sx",.001,ctx.t0);stepAt2(point,"sy",.001,ctx.t0);point.tween("sx",sx,start,end,ctx.ease);point.tween("sy",sx,start,end,ctx.ease)});for(const label of this.groupLabels){stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,ctx.t0+span*.7,ctx.t1,ctx.ease)}}}}fit(f,options={}){const[x0,x1]=this.frame.xRange;const samples=options.samples??60;const points=[];for(let i=0;i<=samples;i++){const x=x0+(x1-x0)*i/samples;points.push(this.p(x,f(x)))}const node=new Node(smoothPath(points)).stroke(options.color??"yellow",options.width??3.5);this.add(node);return node}};function scatter(points,options={}){return new Scatter(points,options)}var LineChart2=class extends Node{lines=[];areas=[];names=[];axis;byName=new Map;frame;constructor(series,options={}){super();const resolved=series.map(entry=>entry.points??(entry.values??[]).map((value,i)=>[i,value]));const xs=resolved.flat().map(p=>p[0]),ys=resolved.flat().map(p=>p[1]);const yLow=Math.min(...ys),yHigh=Math.max(...ys);const yPad=(yHigh-yLow||1)*.08;const xRange=options.x??[Math.min(...xs),Math.max(...xs)];const yRange=options.y??[yLow>=0&&yLow<(yHigh-yLow)*.4?0:yLow-yPad,yHigh+yPad];const w=options.width??900,h=options.height??480;this.frame={xRange,yRange,w,h};const labelSize=options.labelSize??18;this.axis=xyAxes(this.frame,{labelSize,color:options.color,xLabel:options.xLabel,yLabel:options.yLabel,xFormat:options.xFormat,yFormat:options.yFormat,xTicks:options.xTicks,yTicks:options.yTicks});this.add(this.axis);const ends=[];series.forEach((entry,i)=>{const color=entry.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const points=resolved[i].map(([x,y])=>xyPoint(this.frame,x,y));if(entry.area){const base=xyPoint(this.frame,xRange[0],Math.max(yRange[0],0))[1];const shape2=polyPath([...points,[points[points.length-1][0],base],[points[0][0],base]],true);const area=new Node(shape2).fill(color,entry.area);this.areas.push(area);this.add(area)}const path=entry.smooth===false?polyPath(points):smoothPath(points);const stroke=new Node(path).stroke(color,entry.width??3.5);if(entry.dash)stroke.dash(entry.dash);this.lines.push(stroke);this.add(stroke);if(entry.name){this.byName.set(entry.name,stroke);const label=small(entry.name,labelSize+1,color);const last=points[points.length-1];ends.push({label,y:last[1]});label.at(last[0]+12+label.width/2,last[1]);this.names.push(label);this.add(label)}});ends.sort((a,b)=>a.y-b.y);const spacing=labelSize*1.25;for(let pass=0;pass<8;pass++){for(let i=1;i<ends.length;i++){const overlap=spacing-(ends[i].y-ends[i-1].y);if(overlap>0){ends[i-1].y-=overlap/2;ends[i].y+=overlap/2}}}for(const end of ends)end.label.at(end.label.get("x"),end.y)}p(x,y){return xyPoint(this.frame,x,y)}series(name){const found=this.byName.get(name);if(!found)throw new Error(`No series named ${JSON.stringify(name)}.`);return found}enter(options={}){const lag=options.lag??.1;return{label:"lineChart.enter",duration:options.duration??2.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.axis,"opacity",0,ctx.t0);this.axis.tween("opacity",1,ctx.t0,ctx.t0+span*.3,ctx.ease);const windows=staggered(this.lines.length,lag,ctx.t0+span*.15,ctx.t1);this.lines.forEach((stroke,i)=>{const[start,end]=windows[i];stepAt2(stroke,"trimTo",0,ctx.t0);stroke.tween("trimTo",1,start,end,ctx.ease);const name=this.names[i];if(name){stepAt2(name,"opacity",0,ctx.t0);name.tween("opacity",1,end-(end-start)*.2,Math.min(ctx.t1,end+span*.1),ctx.ease)}});for(const area of this.areas){const target=area.get("fillOpacity");stepAt2(area,"fillOpacity",0,ctx.t0);area.tween("fillOpacity",target,ctx.t0+span*.5,ctx.t1,ctx.ease)}}}}};function lineChart(series,options={}){return new LineChart2(series,options)}function wedgePath(a0,a1,inner,outer){if(a1-a0<1e-4)return[];const outerArc=arcPath(0,0,outer,outer,a0,a1)[0].p;const points=Array.from(outerArc);const cx=points[points.length-2],cy=points[points.length-1];const hop=(x,y,tx,ty)=>{points.push(x+(tx-x)/3,y+(ty-y)/3,x+(tx-x)*2/3,y+(ty-y)*2/3,tx,ty)};if(inner>.01){const innerArc=arcPath(0,0,inner,inner,a1,a0)[0].p;hop(cx,cy,innerArc[0],innerArc[1]);for(let i=2;i<innerArc.length;i++)points.push(innerArc[i]);hop(innerArc[innerArc.length-2],innerArc[innerArc.length-1],outerArc[0],outerArc[1])}else{hop(cx,cy,0,0);hop(0,0,outerArc[0],outerArc[1])}return[ring(points,true)]}var PieChart2=class extends Node{wedges=[];labels=[];leaders=[];centerText=null;shares;inner;outer;gap;constructor(data,options={}){super();this.outer=options.radius??240;this.inner=this.outer*(options.hole??0);this.gap=options.gap??(this.inner>0?.018:.008);const total=data.reduce((sum,d)=>sum+Math.max(0,d.value),0)||1;this.shares=data.map(d=>Math.max(0,d.value)/total);const size=options.labelSize??20;const angles=this.angles(this.shares);data.forEach((datum,i)=>{const color=datum.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const[a0,a1]=angles[i];const wedge=new Node(wedgePath(a0,a1,this.inner,this.outer)).fill(color,.86);this.wedges.push(wedge);this.add(wedge)});if(options.labels??true){data.forEach((datum,i)=>{const[a0,a1]=angles[i];const mid=(a0+a1)/2;const cos=Math.cos(mid),sin=Math.sin(mid);const r0=this.outer+6,r1=this.outer+30;const elbowX=cos*r1,elbowY=sin*r1;const endX=elbowX+(cos>=0?18:-18);const leader=new Node(polyPath([[cos*r0,sin*r0],[elbowX,elbowY],[endX,elbowY]])).stroke("faint",1.25);const percent=options.percent??true;const body=percent?`${datum.label} ${Math.round(this.shares[i]*100)}%`:datum.label;const label=small(body,size,"ink");label.at(endX+(cos>=0?8+label.width/2:-8-label.width/2),elbowY);this.leaders.push(leader);this.labels.push(label);this.add(leader,label)})}if(options.centerLabel){const center2=text(options.centerLabel,{size:options.centerSize??Math.max(24,this.inner*.34),font:"serif",color:"ink"}).at(0,0);this.centerText=center2;this.add(center2)}}angles(shares,sweep=1){let cursor=-Math.PI/2;return shares.map(share=>{const span=share*Math.PI*2*sweep;const gap=Math.min(this.gap*sweep,span*.45);const out=[cursor+gap/2,cursor+span-gap/2];cursor+=span;return out})}enter(options={}){return{label:"pie.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const sweepEnd=ctx.t0+span*.78;this.wedges.forEach((wedge,i)=>{const at=a=>{const[x,y]=this.angles(this.shares,a)[i];return wedgePath(x,y,this.inner,this.outer)};wedge.track("path").step(ctx.t0,[]);wedge.track("path").add({t0:ctx.t0,t1:sweepEnd,ease:ctx.ease,to:at(1),at})});for(const node of[...this.labels,...this.leaders,...this.centerText?[this.centerText]:[]]){stepAt2(node,"opacity",0,ctx.t0);node.tween("opacity",1,ctx.t0+span*.62,ctx.t1,ctx.ease)}}}}update(values,options={}){return{label:"pie.update",duration:options.duration??1.1,ease:options.ease,schedule:ctx=>{const total=values.reduce((sum,v)=>sum+Math.max(0,v),0)||1;const next=values.map(v=>Math.max(0,v)/total);const previous=[...this.shares];this.wedges.forEach((wedge,i)=>{const at=a=>{const shares=previous.map((share,k)=>share+((next[k]??0)-share)*a);const[x,y]=this.angles(shares)[i];return wedgePath(x,y,this.inner,this.outer)};wedge.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:at(1),at})});for(const node of[...this.labels,...this.leaders]){node.tween("opacity",0,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.3,ctx.ease)}next.forEach((share,i)=>{this.shares[i]=share})}}}};function pie(data,options={}){return new PieChart2(data,options)}function donut(data,options={}){return new PieChart2(data,{hole:.62,...options})}var Heatmap2=class extends Node{cells=[];rowLabels=[];columnLabels=[];numbers=[];rowCount;colCount;stops;domain;constructor(values,options={}){super();this.rowCount=values.length;this.colCount=Math.max(0,...values.map(row=>row.length));const w=options.cellWidth??options.cell??44;const h=options.cellHeight??options.cell??44;const gap=options.gap??2;const flat=values.flat();this.domain=options.domain??[Math.min(...flat),Math.max(...flat)];const palette=(options.colors??["surface","blue","yellow"]).map(c=>solidColor(c));this.stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const totalW=this.colCount*w+(this.colCount-1)*gap;const totalH=this.rowCount*h+(this.rowCount-1)*gap;const labelSize=options.labelSize??16;const valueSize2=options.valueSize??Math.min(h*.38,w*.36);const format=options.format??(v=>(Math.round(v*100)/100).toString());values.forEach((row,i)=>{const cells=[];const numbers=[];row.forEach((value,j)=>{const cx=-totalW/2+j*(w+gap)+w/2;const cy=-totalH/2+i*(h+gap)+h/2;const color=this.colorFor(value);const cell=new Node(rectPath(-w/2,-h/2,w,h,options.radius??0)).fill(color).at(cx,cy);cells.push(cell);this.add(cell);if(options.values){const label=text(format(value),{size:valueSize2,font:"mono",color:luminance2(color)>.32?"#101114":"#f2efe6"}).at(cx,cy);numbers.push(label);this.add(label)}});this.cells.push(cells);this.numbers.push(numbers)});options.rowLabels?.forEach((name,i)=>{const label=small(name,labelSize);const y=-totalH/2+i*(h+gap)+h/2;label.at(-totalW/2-10-label.width/2,y);this.rowLabels.push(label);this.add(label)});options.columnLabels?.forEach((name,j)=>{const label=small(name,labelSize);const x=-totalW/2+j*(w+gap)+w/2;const angle=options.columnLabelAngle??0;if(angle!==0){const length=label.width;label.at(x+Math.cos(angle)*length/2,-totalH/2-12+Math.sin(angle)*length/2);label.set("rotation",angle)}else{label.at(x,-totalH/2-10-labelSize/2)}this.columnLabels.push(label);this.add(label)})}colorFor(value){const[low,high]=this.domain;return sampleStops(this.stops,Math.max(0,Math.min(1,(value-low)/(high-low||1))))}cell(row,column){const found=this.cells[row]?.[column];if(!found)throw new Error(`Heatmap has no cell (${row}, ${column}). It is ${this.rowCount} by ${this.colCount}.`);return found}row(index){return[...this.cells[index]??[]]}col(index){return this.cells.map(row=>row[index]).filter(Boolean)}enter(options={}){return{label:"heatmap.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const diagonals=this.rowCount+this.colCount-1;const each=span*.5;const stagger=diagonals>1?(span-each)/(diagonals-1):0;this.cells.forEach((row,i)=>row.forEach((cell,j)=>{const start=ctx.t0+(i+j)*stagger;stepAt2(cell,"opacity",0,ctx.t0);cell.tween("opacity",1,start,start+each,ctx.ease);const number=this.numbers[i]?.[j];if(number){stepAt2(number,"opacity",0,ctx.t0);number.tween("opacity",1,start,start+each,ctx.ease)}}));for(const label of[...this.rowLabels,...this.columnLabels]){stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,ctx.t0,ctx.t0+span*.4,ctx.ease)}}}}update(values,options={}){return{label:"heatmap.update",duration:options.duration??1,ease:options.ease,schedule:ctx=>{values.forEach((row,i)=>row.forEach((value,j)=>{const cell=this.cells[i]?.[j];if(cell)cell.tween("fill",this.colorFor(value),ctx.t0,ctx.t1,ctx.ease)}))}}}};function heatmap(values,options={}){return new Heatmap2(values,options)}var dagreModule=null;var dagreLoading=null;function requireDagre(){if(dagreModule)return dagreModule;dagreLoading??=import("@dagrejs/dagre").then(module=>{dagreModule=module.default??module});throw new Suspend(dagreLoading)}var GraphNode=class extends Node{shape;caption=null;halfWidth=0;halfHeight=0;round=true;edgePoint(fx,fy,tx,ty,pad2=0){const dx=tx-fx,dy=ty-fy;const length=Math.hypot(dx,dy)||1;if(this.round)return[fx+dx/length*(this.halfWidth+pad2),fy+dy/length*(this.halfWidth+pad2)];const sx=dx===0?Infinity:this.halfWidth/Math.abs(dx);const sy=dy===0?Infinity:this.halfHeight/Math.abs(dy);const s=Math.min(sx,sy);return[fx+dx*s+dx/length*pad2,fy+dy*s+dy/length*pad2]}};var GraphEdge=class extends Node{shaft;tip=null;caption=null;from="";to="";tipSize=14};function tipPath(path,size){const length=pathLength(path);if(length<=size*1.1)return{head:[],trimmed:path};const fraction=1-size/length;const trimmed=trimPath(path,0,fraction);const[x,y]=pointAt(path,1);const[ux,uy]=tangentAt(path,.997);const half=size*.38;const bx=x-ux*size,by=y-uy*size;return{head:polyPath([[x,y],[bx-uy*half,by+ux*half],[bx+uy*half,by-ux*half]],true),trimmed}}var Graph=class extends Node{nodes=new Map;edges=[];edgeLayer=new Node;nodeLayer=new Node;specs;constructor(nodes,edges,options={}){super();this.specs=nodes;const defaultRadius=options.radius??30;const labelSize=options.labelSize??26;const sizeOf=spec=>spec.width?[spec.width,spec.height??labelSize*2]:[(spec.radius??defaultRadius)*2,(spec.radius??defaultRadius)*2];const layout=options.layout??"dagre";let positions=new Map;const routes=new Map;if(layout==="dagre"){const dagre=requireDagre();const g=new dagre.graphlib.Graph({multigraph:true});g.setGraph({rankdir:options.direction??"LR",nodesep:options.nodeGap??60,ranksep:options.rankGap??110,edgesep:24,ranker:"network-simplex"});g.setDefaultEdgeLabel(()=>({}));for(const spec of nodes){const[width,height]=sizeOf(spec);g.setNode(spec.id,{width,height})}edges.forEach((edge,i)=>g.setEdge(edge.from,edge.to,{},String(i)));dagre.layout(g);const info=g.graph();const cx=(info.width??0)/2,cy=(info.height??0)/2;for(const spec of nodes){const placed=g.node(spec.id);positions.set(spec.id,[placed.x-cx,placed.y-cy])}edges.forEach((edge,i)=>{const data=g.edge({v:edge.from,w:edge.to,name:String(i)});if(data?.points)routes.set(edge,data.points.map(point=>[point.x-cx,point.y-cy]))})}else if(layout==="circle"){const radius=Math.min(options.width??700,options.height??700)/2;nodes.forEach((spec,i)=>{const angle=-Math.PI/2+i/nodes.length*Math.PI*2;positions.set(spec.id,[Math.cos(angle)*radius,Math.sin(angle)*radius])})}else if(layout==="force"){positions=forceLayout(nodes,edges,options.width??900,options.height??620,options.seed??3)}else{for(const spec of nodes)positions.set(spec.id,spec.at??[0,0])}const nodeColor=options.nodeColor??"blue";for(const spec of nodes){const view=new GraphNode;const color=spec.color??nodeColor;const[width,height]=sizeOf(spec);view.halfWidth=width/2;view.halfHeight=height/2;view.round=!spec.width;view.shape=new Node(spec.width?rectPath(-width/2,-height/2,width,height,8):circlePath(0,0,width/2)).fill(color,options.fillOpacity??.16).stroke(color,2.5);view.add(view.shape);if(spec.label){view.caption=spec.math?tex(spec.label,{size:labelSize,color:"ink",display:false}):text(spec.label,{size:labelSize,color:"ink"});view.add(view.caption.at(0,0))}view.named(spec.id);view.at(positions.get(spec.id)??[0,0]);this.nodes.set(spec.id,view);this.nodeLayer.add(view)}const directed=options.directed??true;const edgeColor=options.edgeColor??"dim";const edgeLabelSize=options.edgeLabelSize??20;for(const spec of edges){const from=this.nodes.get(spec.from),to2=this.nodes.get(spec.to);if(!from||!to2)throw new Error(`Graph edge ${spec.from} -> ${spec.to} refers to a node that does not exist.`);const view=new GraphEdge;view.from=spec.from;view.to=spec.to;const a=positions.get(spec.from),b=positions.get(spec.to);const route=routes.get(spec);const horizontal=(options.direction??"LR")==="LR"||options.direction==="RL";const path=routeEdge(from,to2,a,b,route,horizontal);const isDirected=spec.directed??directed;const color=spec.color??edgeColor;const{head,trimmed}=isDirected?tipPath(path,view.tipSize):{head:[],trimmed:path};view.shaft=new Node(trimmed).stroke(color,spec.width??2.2);if(spec.dash)view.shaft.dash(spec.dash);view.add(view.shaft);if(head.length){view.tip=new Node(head).fill(color);view.add(view.tip)}if(spec.label){const[mx,my]=pointAt(path,.5);const caption=text(spec.label,{size:edgeLabelSize,color:"ink",font:"mono"}).at(mx,my);const pad2=edgeLabelSize*.34;const plate=new Node(rectPath(mx-caption.width/2-pad2,my-edgeLabelSize*.68,caption.width+pad2*2,edgeLabelSize*1.36,4)).fill("bg");view.caption=new Node().add(plate,caption);view.add(view.caption)}this.edges.push(view);this.edgeLayer.add(view)}this.add(this.edgeLayer,this.nodeLayer)}node(id){const found=this.nodes.get(id);if(!found)throw new Error(`Graph has no node ${JSON.stringify(id)}.`);return found}edge(from,to2){const found=this.edges.find(edge=>edge.from===from&&edge.to===to2)??this.edges.find(edge=>edge.from===to2&&edge.to===from);if(!found)throw new Error(`Graph has no edge ${from} -> ${to2}.`);return found}enter(options={}){const lag=options.lag??.14;return{label:"graph.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const ordered=this.specs.map(spec=>this.nodes.get(spec.id));const windows=staggered(ordered.length,lag,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.78);const startOf=new Map;ordered.forEach((view,i)=>{const[start,end]=windows[i];startOf.set(view,end);popIn(view,ctx.t0,start,end,ctx.ease)});for(const edge of this.edges){const start=startOf.get(this.nodes.get(edge.from))??ctx.t0;const end=Math.min(ctx.t1,start+(ctx.t1-ctx.t0)*.22);stepAt2(edge.shaft,"trimTo",0,ctx.t0);edge.shaft.tween("trimTo",1,start,end,ctx.ease);for(const part of[edge.tip,edge.caption]){if(!part)continue;stepAt2(part,"opacity",0,ctx.t0);part.tween("opacity",1,end-(end-start)*.3,end,ctx.ease)}}}}}pulseEdge(from,to2,options={}){const edge=this.edge(from,to2);return{...pulse(edge.shaft,{color:options.color??"yellow",length:options.length??.3,...options}),label:"graph.pulse"}}visit(id,options={}){const view=this.node(id);const color=options.color??"yellow";return{label:"graph.visit",duration:options.duration??.6,ease:options.ease,schedule:ctx=>{const paint=toPaint(color);view.shape.tween("stroke",paint,ctx.t0,ctx.t1,ctx.ease);view.shape.tween("fill",paint,ctx.t0,ctx.t1,ctx.ease);const span=ctx.t1-ctx.t0;const sx=view.get("sx");view.tween("sx",sx*1.16,ctx.t0,ctx.t0+span*.45,ctx.ease);view.tween("sy",sx*1.16,ctx.t0,ctx.t0+span*.45,ctx.ease);view.tween("sx",sx,ctx.t0+span*.45,ctx.t1,ctx.ease);view.tween("sy",sx,ctx.t0+span*.45,ctx.t1,ctx.ease)}}}moveNode(id,to2,options={}){const view=this.node(id);return{label:"graph.move",duration:options.duration??1,ease:options.ease,schedule:ctx=>{const fromX=view.get("x"),fromY=view.get("y");view.tween("x",to2[0],ctx.t0,ctx.t1,ctx.ease);view.tween("y",to2[1],ctx.t0,ctx.t1,ctx.ease);for(const edge of this.edges){if(edge.from!==id&&edge.to!==id)continue;const other=this.node(edge.from===id?edge.to:edge.from);const ox=sampleAt(other,"x",ctx.t0),oy=sampleAt(other,"y",ctx.t0);const geometry=a=>{const x=fromX+(to2[0]-fromX)*a,y=fromY+(to2[1]-fromY)*a;const start=edge.from===id?view.edgePoint(x,y,ox,oy,2):other.edgePoint(ox,oy,x,y,2);const end=edge.from===id?other.edgePoint(ox,oy,x,y,4):view.edgePoint(x,y,ox,oy,4);return polyPath([start,end])};const shaftAt=a=>edge.tip?tipPath(geometry(a),edge.tipSize).trimmed:geometry(a);edge.shaft.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:shaftAt(1),at:shaftAt});if(edge.tip){const tipAt=a=>tipPath(geometry(a),edge.tipSize).head;edge.tip.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:tipAt(1),at:tipAt})}}}}}};function routeEdge(from,to2,a,b,route,horizontal){const interior=route?route.slice(1,-1):[];const firstTarget=interior[0]??b,lastSource=interior[interior.length-1]??a;const start=from.edgePoint(a[0],a[1],firstTarget[0],firstTarget[1],2);const end=to2.edgePoint(b[0],b[1],lastSource[0],lastSource[1],4);if(!route)return polyPath([start,end]);if(interior.length<=1){const dx=end[0]-start[0],dy=end[1]-start[1];if(Math.abs(horizontal?dy:dx)<2)return polyPath([start,end]);const reach=(horizontal?dx:dy)*.5;const c1=horizontal?`${start[0]+reach} ${start[1]}`:`${start[0]} ${start[1]+reach}`;const c2=horizontal?`${end[0]-reach} ${end[1]}`:`${end[0]} ${end[1]-reach}`;return parseSvgPath(`M${start[0]} ${start[1]}C${c1} ${c2} ${end[0]} ${end[1]}`)}return smoothPath([start,...interior.slice(1,-1),end])}function popIn(node,hideFrom,start,end,ease){const sx=sampleAt(node,"sx",start),sy=sampleAt(node,"sy",start);stepAt2(node,"sx",sx*.001,hideFrom);stepAt2(node,"sy",sy*.001,hideFrom);node.tween("sx",sx,start,end,ease);node.tween("sy",sy,start,end,ease)}function forceLayout(nodes,edges,width,height,seed){const random=seededRandom2(seed);const ids=nodes.map(spec=>spec.id);const x=new Float64Array(ids.length),y=new Float64Array(ids.length);for(let i=0;i<ids.length;i++){x[i]=(random()-.5)*width;y[i]=(random()-.5)*height}const index=new Map(ids.map((id,i)=>[id,i]));const k=Math.sqrt(width*height/Math.max(1,ids.length))*.72;let temperature=Math.max(width,height)*.12;for(let round=0;round<420;round++){const dx=new Float64Array(ids.length),dy=new Float64Array(ids.length);for(let i=0;i<ids.length;i++){for(let j=i+1;j<ids.length;j++){const ox=x[i]-x[j],oy=y[i]-y[j];const d=Math.max(1,Math.hypot(ox,oy));const force=k*k/d;dx[i]+=ox/d*force;dy[i]+=oy/d*force;dx[j]-=ox/d*force;dy[j]-=oy/d*force}}for(const edge of edges){const a=index.get(edge.from),b=index.get(edge.to);if(a===void 0||b===void 0)continue;const ox=x[a]-x[b],oy=y[a]-y[b];const d=Math.max(1,Math.hypot(ox,oy));const force=d*d/k;dx[a]-=ox/d*force;dy[a]-=oy/d*force;dx[b]+=ox/d*force;dy[b]+=oy/d*force}for(let i=0;i<ids.length;i++){const length=Math.max(1e-6,Math.hypot(dx[i],dy[i]));x[i]+=dx[i]/length*Math.min(length,temperature);y[i]+=dy[i]/length*Math.min(length,temperature);x[i]=Math.max(-width/2,Math.min(width/2,x[i]));y[i]=Math.max(-height/2,Math.min(height/2,y[i]))}temperature*=.985}return new Map(ids.map((id,i)=>[id,[x[i],y[i]]]))}function graph(nodes,edges,options={}){return new Graph(nodes,edges,options)}var TreeGraph=class extends Graph{depths=new Map;constructor(root,options={}){const specs=[];const links=[];const depthOf=new Map;const levelGap=options.levelGap??130;const siblingGap=options.siblingGap??96;let counter2=0;let leafCursor=0;const place2=(node,depth)=>{const id=node.id??`n${counter2++}`;depthOf.set(id,depth);const children=node.children??[];let position2;const entry={id,label:node.label,color:node.color,math:node.math};specs.push(entry);if(children.length===0){position2=leafCursor++}else{const placed=children.map(child=>place2(child,depth+1));position2=(placed[0].position+placed[placed.length-1].position)/2;for(const child of placed)links.push({from:id,to:child.id,directed:false})};entry.at=options.direction==="right"?[depth*levelGap,position2*siblingGap]:[position2*siblingGap,depth*levelGap];return{id,position:position2}};place2(root,0);const xs=specs.map(spec=>spec.at[0]),ys=specs.map(spec=>spec.at[1]);const cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;for(const spec of specs)spec.at=[spec.at[0]-cx,spec.at[1]-cy];super(specs,links,{layout:"manual",radius:options.radius??28,labelSize:options.labelSize??24,nodeColor:options.nodeColor,edgeColor:options.edgeColor,fillOpacity:options.fillOpacity,directed:false});for(const[id,depth]of depthOf)this.depths.set(id,depth)}enter(options={}){return{label:"tree.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const levels=Math.max(...this.depths.values())+1;const span=(ctx.t1-ctx.t0)/levels;for(const[id,view]of this.nodes){const depth=this.depths.get(id)??0;const start=ctx.t0+depth*span;popIn(view,ctx.t0,start,start+span,ctx.ease)}for(const edge of this.edges){const depth=this.depths.get(edge.to)??1;const start=ctx.t0+(depth-1)*span+span*.3;stepAt2(edge.shaft,"trimTo",0,ctx.t0);edge.shaft.tween("trimTo",1,start,start+span*.8,ctx.ease)}}}}};function tree(root,options={}){return new TreeGraph(root,options)}var ArrayCells=class extends Node{slots=[];indexLabels=[];items=[];cellSize;step;constructor(values,options={}){super();const cell=this.cellSize=options.cell??72;const gap=options.gap??6;this.step=cell+gap;const size=options.size??cell*.38;const color=options.color??"blue";const left=-((values.length-1)*this.step)/2;values.forEach((_,i)=>{const x=left+i*this.step;const slot=new Node(rectPath(-cell/2,-cell/2,cell,cell,6)).stroke("faint",1.5).at(x,0);this.slots.push(slot);this.add(slot);if(options.indices??true){const label=text(String(i),{size:options.indexSize??Math.max(13,cell*.2),color:"faint",font:"mono"}).at(x,cell/2+(options.indexSize??cell*.2)+2);this.indexLabels.push(label);this.add(label)}});values.forEach((value,i)=>{const x=left+i*this.step;const item=new Node().at(x,0);const box=new Node(rectPath(-cell/2+2,-cell/2+2,cell-4,cell-4,5)).fill(color,.16).stroke(color,2);const glyphs=text(String(value),{size,font:options.font??"mono",color:"ink"}).at(0,0);item.add(box,glyphs);item.data["box"]=box;item.data["value"]=value;this.items.push(item);this.add(item)})}cell(index){const found=this.items[index];if(!found)throw new Error(`Array has no index ${index}.`);return found}slotAt(index){return[this.slots[index].get("x"),this.slots[index].get("y")]}swap(i,j,options={}){return{label:"array.swap",duration:options.duration??.8,ease:options.ease,schedule:ctx=>{const a=this.items[i],b=this.items[j];const[ax,ay]=this.slotAt(i),[bx,by]=this.slotAt(j);const lift=options.lift??this.cellSize*.9+Math.abs(i-j)*6;const arc2=(node,fx,fy,tx,ty,sign)=>{node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:tx,at:t=>fx+(tx-fx)*t});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:ty,at:t=>fy+(ty-fy)*t-sign*lift*4*t*(1-t)})};arc2(a,ax,ay,bx,by,1);arc2(b,bx,by,ax,ay,-1);this.items[i]=b;this.items[j]=a}}}mark(index,color,options={}){const item=this.cell(index);return{...recolor(item.data["box"],color,{duration:.35,...options}),label:"array.mark"}}enter(options={}){const lag=options.lag??.2;return{label:"array.enter",duration:options.duration??1.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const windows=staggered(this.items.length,lag,ctx.t0,ctx.t1);this.items.forEach((item,i)=>{const[start,end]=windows[i];popIn(item,ctx.t0,start,end,ctx.ease);stepAt2(this.slots[i],"opacity",0,ctx.t0);this.slots[i].tween("opacity",1,start,end,ctx.ease);const index=this.indexLabels[i];if(index){stepAt2(index,"opacity",0,ctx.t0);index.tween("opacity",1,start,end,ctx.ease)}})}}}};function arrayCells(values,options={}){return new ArrayCells(values,options)}var KEYWORDS={ts:new Set("const let var function return if else for while do switch case break continue new class extends implements interface type enum import export from default async await yield try catch finally throw typeof instanceof in of this super null undefined true false void as readonly public private protected static get set".split(" ")),python:new Set("def return if elif else for while in not and or is class import from as with try except finally raise lambda yield pass break continue global nonlocal None True False self async await assert del print".split(" ")),rust:new Set("fn let mut pub struct enum impl trait use mod match if else for while loop return self Self as in where const static crate super true false ref move async await dyn type".split(" ")),go:new Set("func var const type struct interface package import return if else for range switch case default break continue go defer select chan map nil true false".split(" ")),sql:new Set("select from where join left right inner outer on group by order having limit as and or not in is null insert into values update set delete create table with distinct count sum avg min max".split(" ")),bash:new Set("if then else elif fi for do done while case esac in function return export local echo cd exit set".split(" ")),plain:new Set};function tokenize(source,language="ts"){const lang=language==="js"||language==="tsx"||language==="jsx"||language==="typescript"||language==="javascript"?"ts":language==="py"?"python":language;const keywords=KEYWORDS[lang]??KEYWORDS["ts"];const insensitive=lang==="sql";const hashComment=lang==="python"||lang==="bash";const dashComment=lang==="sql";const out=[];source.split("\n").forEach((row,line2)=>{let i=0;while(i<row.length){const rest=row.slice(i);const push=(value,kind)=>{out.push({text:value,kind,line:line2});i+=value.length};const space=/^\s+/.exec(rest);if(space){push(space[0],"space");continue}if(!hashComment&&!dashComment&&rest.startsWith("//")||hashComment&&rest[0]==="#"||dashComment&&rest.startsWith("--")){push(rest,"comment");continue}const string=/^("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?)/.exec(rest);if(string){push(string[0],"string");continue}const number=/^(0x[\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:e[-+]?\d+)?)/.exec(rest);if(number){push(number[0],"number");continue}const word=/^[A-Za-z_$][\w$]*/.exec(rest);if(word){const value=word[0];const after=rest.slice(value.length);const isKeyword=keywords.has(insensitive?value.toLowerCase():value);const kind=isKeyword?"keyword":/^\s*\(/.test(after)?"function":/^[A-Z]/.test(value)?"type":"plain";push(value,kind);continue}push(rest[0],"punctuation")}});return out}var CODE_COLORS={keyword:"purple",string:"green",number:"orange",comment:"faint",function:"blue",type:"teal",punctuation:"dim",plain:"ink"};var CodeBlock2=class extends Node{lines=[];tokens=[];chars=[];panelNode=null;body=new Node;source;bar;rowHeight;originY;contentWidth;constructor(source,options={}){super();this.source=source;const size=options.size??26;const rowHeight=this.rowHeight=size*(options.leading??1.5);const font=fontFor("mono",400);const scale=size/font.unitsPerEm;const advance=font.advance(font.glyphFor(48))*scale;const tokens5=tokenize(source,options.language??"ts");const rows=source.split("\n");const gutter=options.lineNumbers?(String(rows.length).length+2)*advance:0;const pad2=options.padding??size*.9;const width=Math.max(options.minWidth??0,Math.max(...rows.map(row=>row.length))*advance+gutter+pad2*2);const height=rows.length*rowHeight+pad2*2-(rowHeight-size);this.contentWidth=width;const left=-width/2+pad2+gutter,top=-height/2+pad2+size*.82;this.originY=top;if(options.panel??true){const panel=new Node(rectPath(-width/2,-height/2,width,height,8)).fill("surface").stroke("gridStrong",1);this.panelNode=panel;this.add(panel)}this.bar=new Node().fill("yellow",.1);this.bar.base.visible=false;this.add(this.bar);for(let i=0;i<rows.length;i++){const line2=new Node;this.lines.push(line2);this.body.add(line2);if(options.lineNumbers){const label=String(i+1).padStart(String(rows.length).length," ");let cx=left-gutter;for(const char of label){if(char!==" ")line2.add(makeGlyph(font,char,size,"faint",cx,top+i*rowHeight));cx+=advance}}}const colors2={...CODE_COLORS,...options.colors};const column=new Map;for(const token of tokens5){const start=column.get(token.line)??0;column.set(token.line,start+token.text.length);const entry={...token,glyphs:[]};this.tokens.push(entry);if(token.kind==="space")continue;const color=colors2[token.kind];[...token.text].forEach((char,offset)=>{const leaf=makeGlyph(font,char,size,color,left+(start+offset)*advance,top+token.line*rowHeight);entry.glyphs.push(leaf);this.chars.push(leaf);this.lines[token.line].add(leaf)})}this.add(this.body)}line(index){const found=this.lines[index];if(!found)throw new Error(`Code has no line ${index}.`);return found}find(fragment){return this.tokens.filter(token=>token.text===fragment).flatMap(token=>token.glyphs)}focus(lines,options={}){const wanted=new Set(typeof lines==="number"?[lines]:lines);return{label:"code.focus",duration:options.duration??.6,ease:options.ease,schedule:ctx=>{this.lines.forEach((line2,i)=>{line2.tween("opacity",wanted.has(i)?1:options.dim??.28,ctx.t0,ctx.t1,ctx.ease)});const sorted=[...wanted].sort((a,b)=>a-b);const first=sorted[0]??0,last=sorted[sorted.length-1]??first;const y=this.originY-this.rowHeight*.32+(first+last)/2*this.rowHeight;const spanRows=last-first+1;const barPath=rectPath(-this.contentWidth/2+2,-this.rowHeight*spanRows/2,this.contentWidth-4,this.rowHeight*spanRows,3);const wasVisible=sampleAt(this.bar,"visible",ctx.t0);if(!wasVisible){stepAt2(this.bar,"x",0,ctx.t0);stepAt2(this.bar,"y",y,ctx.t0);this.bar.track("path").step(ctx.t0,barPath);stepAt2(this.bar,"visible",true,ctx.t0);stepAt2(this.bar,"opacity",0,ctx.t0);this.bar.tween("opacity",1,ctx.t0,ctx.t1,ctx.ease)}else{this.bar.tween("y",y,ctx.t0,ctx.t1,ctx.ease);this.bar.tween("path",barPath,ctx.t0,ctx.t1,ctx.ease)}if(options.color)this.bar.tween("fill",toPaint(options.color),ctx.t0,ctx.t1,ctx.ease)}}}unfocus(options={}){return{label:"code.unfocus",duration:options.duration??.5,ease:options.ease,schedule:ctx=>{for(const line2 of this.lines)line2.tween("opacity",1,ctx.t0,ctx.t1,ctx.ease);this.bar.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);stepAt2(this.bar,"visible",false,ctx.t1)}}}};function makeGlyph(font,char,size,color,x,baseline){const leaf=new Node(glyphPath(font,font.glyphFor(char.codePointAt(0)),size));leaf.base.fill=toPaint(color);leaf.base.trimEach=true;leaf.data["key"]=char;return leaf.at(x,baseline)}function codeBlock(source,options={}){return new CodeBlock2(source,options)}function morphCode(from,to2,options={}){const visible=block=>block.tokens.filter(token=>token.kind!=="space"&&token.glyphs.length>0);const a=visible(from),b=visible(to2);const pairs=matchSequence(a.map(token=>token.text),b.map(token=>token.text));const keys=new Map;pairs.forEach(([i,j],pair)=>{a[i].glyphs.forEach((glyph,k)=>keys.set(glyph,`m${pair}:${k}`));b[j].glyphs.forEach((glyph,k)=>keys.set(glyph,`m${pair}:${k}`))});if(from.panelNode&&to2.panelNode){keys.set(from.panelNode,"panel");keys.set(to2.panelNode,"panel")}let unique=0;const anim=morphMatching(from,to2,{duration:1.5,...options,key:leaf=>{let key=keys.get(leaf);if(key===void 0){key=`only:${unique++}`;keys.set(leaf,key)}return key}});return{...anim,label:"morphCode"}}var NeuralNet=class extends Node{neurons=[];links=[];edgeLayer=new Node;neuronLayer=new Node;captions=[];seed;layerColors;constructor(layers,options={}){super();const width=options.width??1e3;const height=options.height??560;const radius=options.radius??15;const collapse=options.collapse??8;const columnGap=layers.length>1?width/(layers.length-1):0;this.seed=options.seed??11;this.layerColors=options.colors??["blue","teal","teal","yellow"];const edgeColor=options.edgeColor??"dim";const edgeOpacity=options.edgeOpacity??.32;const positions=[];layers.forEach((count,l)=>{const shown=count>collapse?collapse:count;const step=Math.min(radius*3.6,height/Math.max(1,shown+(count>collapse?1:0)));const x=-width/2+l*columnGap;const column=[];const views=[];const color=this.layerColors[Math.min(l,this.layerColors.length-1)];const keepTop=Math.ceil(shown/2);for(let i=0;i<shown+(count>collapse?1:0);i++){const y=(i-(shown+(count>collapse?1:0)-1)/2)*step;if(count>collapse&&i===keepTop){this.neuronLayer.add(tex("\\vdots",{size:radius*1.9,color:"dim",display:false}).at(x,y));continue}column.push([x,y]);const neuron=new Node(circlePath(0,0,radius)).stroke(color,2.2).fill(color,.08).at(x,y);views.push(neuron);this.neuronLayer.add(neuron)}positions.push(column);this.neurons.push(views);const name=options.layerLabels?.[l];if(name){const size=options.labelSize??22;const caption=text(name,{size,color:"dim"}).at(x,height/2+size*1.5);this.captions.push(caption);this.add(caption)}});for(let l=0;l+1<positions.length;l++){const rows=[];for(const a of positions[l]){const row=[];for(const b of positions[l+1]){const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;const ux=(b[0]-a[0])/length,uy=(b[1]-a[1])/length;const link=line([a[0]+ux*radius,a[1]+uy*radius],[b[0]-ux*radius,b[1]-uy*radius],{stroke:edgeColor,width:1.1});link.set("strokeOpacity",edgeOpacity);row.push(link);this.edgeLayer.add(link)}rows.push(row)}this.links.push(rows)}this.add(this.edgeLayer,this.neuronLayer)}layer(index){return this.neurons[index]??[]}enter(options={}){return{label:"net.enter",duration:options.duration??2.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const layers=this.neurons.length;const each=span*.45;const gap=layers>1?span*.55/(layers-1):0;this.neurons.forEach((views,l)=>{const windows=staggered(views.length,.12,ctx.t0+l*gap,ctx.t0+l*gap+each);views.forEach((neuron,i)=>popIn(neuron,ctx.t0,windows[i][0],windows[i][1],ctx.ease))});this.links.forEach((rows,l)=>{const start=ctx.t0+l*gap+each*.45;for(const row of rows)for(const link of row){stepAt2(link,"trimTo",0,ctx.t0);link.tween("trimTo",1,start,start+each,ctx.ease)}});for(const child of this.neuronLayer.children){if(child.get("path"))continue;stepAt2(child,"opacity",0,ctx.t0);child.tween("opacity",1,ctx.t0+span*.3,ctx.t1,ctx.ease)}for(const caption of this.captions){stepAt2(caption,"opacity",0,ctx.t0);caption.tween("opacity",1,ctx.t0+span*.3,ctx.t1,ctx.ease)}}}}activate(layer,values,options={}){return{label:"net.activate",duration:options.duration??.45,ease:options.ease,schedule:ctx=>{this.neurons[layer].forEach((neuron,i)=>{const amount2=Math.max(.04,Math.min(1,values[i]??0));neuron.tween("fillOpacity",amount2,ctx.t0,ctx.t1,ctx.ease);if(options.color)neuron.tween("fill",toPaint(options.color),ctx.t0,ctx.t1,ctx.ease)})}}}forward(options={}){const random=seededRandom2(this.seed);const activations=this.neurons.map((views,l)=>options.activations?.[l]??views.map(()=>random()*random()));const color=options.color??"yellow";const steps=[];activations.forEach((values,l)=>{steps.push(this.activate(l,values,{duration:.35}));if(l+1>=this.neurons.length)return;const candidates=[];this.links[l].forEach((row,i)=>row.forEach((link,j)=>{candidates.push({link,score:(values[i]??0)*(activations[l+1]?.[j]??0)})}));candidates.sort((a,b)=>b.score-a.score);const picked=candidates.slice(0,options.pulses??10);steps.push(par(...picked.map(({link,score})=>pulse(link,{color,length:.42,width:1.5+score*3,glow:4,duration:.7}))))});const whole=seq(...steps);return{...whole,label:"net.forward",duration:options.duration??whole.duration,ease:options.ease}}};function neuralNet(layers,options={}){return new NeuralNet(layers,options)}var TokenRow=class extends Node{chips=[];constructor(items,options={}){super();const size=options.size??22;const gap=options.gap??size*.28;const subSize=options.subSize??size*.62;const padX=size*.42,padY=size*.3;const specs=items.map(item=>typeof item==="string"?{text:item}:item);const palette=options.colors?ramp(specs.length,...options.colors):null;let x=0,y=0;const placed=[];const rowHeight=size+padY*2+(specs.some(s=>s.sub)?subSize*1.4:0);for(let i=0;i<specs.length;i++){const spec=specs[i];const color=spec.color??(palette?palette[i]:options.color??"blue");const label=text(spec.text.replace(/ /g,"\xB7"),{size,font:options.font??"mono",color:"ink"});const w=Math.max(label.width,size*.5)+padX*2;const h=size+padY*2;if(options.maxWidth!==void 0&&x>0&&x+w>options.maxWidth){x=0;y+=rowHeight+gap}const chip=new Node;const box=new Node(rectPath(-w/2,-h/2,w,h,options.radius??4)).fill(color,.18).stroke(color,1.5);chip.add(box,label.at(0,0));if(spec.sub)chip.add(text(spec.sub,{size:subSize,font:"mono",color:"dim"}).at(0,h/2+subSize*.82));chip.data["box"]=box;placed.push({node:chip,x:x+w/2,y,w});x+=w+gap}const maxX=Math.max(...placed.map(p=>p.x+p.w/2),0);const maxY=Math.max(...placed.map(p=>p.y),0);for(const entry of placed){entry.node.at(entry.x-maxX/2,entry.y-maxY/2);this.chips.push(entry.node);this.add(entry.node)}}token(index){const found=this.chips[index];if(!found)throw new Error(`Token row has no token ${index}.`);return found}enter(options={}){const lag=options.lag??.16;return{label:"tokens.enter",duration:options.duration??1.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const windows=staggered(this.chips.length,lag,ctx.t0,ctx.t1);this.chips.forEach((chip,i)=>{const[start,end]=windows[i];const y=chip.get("y");stepAt2(chip,"opacity",0,ctx.t0);stepAt2(chip,"y",y+16,ctx.t0);chip.tween("opacity",1,start,end,ctx.ease);chip.tween("y",y,start,end,ctx.ease)})}}}arcs(from,weights,options={}){const source=this.token(from).bounds();const made=new Node;const startX=source.x+source.width/2,startY=source.y-3;weights.forEach((weight,j)=>{if(j===from||weight<=.01)return;const target=this.token(j).bounds();const endX=target.x+target.width/2,endY=target.y-3;const lift=options.lift??40+Math.abs(endX-startX)*.22;const path=parseSvgPath(`M${startX} ${startY}C${startX} ${startY-lift} ${endX} ${endY-lift} ${endX} ${endY}`);const node=new Node(path).stroke(options.color??"yellow",.8+weight*(options.maxWidth??6));node.set("strokeOpacity",.2+weight*.8);made.add(node)});return made}};function tokens3(items,options={}){return new TokenRow(items,options)}function attentionMatrix(rows,columns,weights,options={}){return new Heatmap2(weights,{cell:options.cell??42,gap:options.gap??2,colors:options.colors??["surface","teal","yellow"],domain:[0,Math.max(...weights.flat())],values:options.values,rowLabels:rows,columnLabels:columns,labelSize:options.labelSize??18,columnLabelAngle:-Math.PI/4})}function place(node,x,y,align="left"){const half=node.get("px");return node.at(align==="left"?x+half:align==="right"?x-half:x,y)}function advanceWidth(node){return node.get("px")*2}var InfoBox=class extends Node{frame;accentBar=null;titleNode;subtitleNode=null;badgeNode=null;rowLabels=[];rowValues=[];meters=[];tagNodes=[];boxWidth;boxHeight;valueSize;constructor(options){super();const size=options.size??14;this.valueSize=size;const pad2=size*.8;const rows=options.rows??[];const rowHeight=size*1.56;const title=text(options.title,{size:size*1.14,weight:600,color:"ink"});const subtitle=options.subtitle?text(options.subtitle,{size:size*.86,font:"mono",color:"dim"}):null;const badgeTone=options.badgeTone??options.accent??"dim";const badge=options.badge?text(options.badge,{size:size*.78,font:"mono",color:badgeTone}):null;const labels=rows.map(row=>text(row.label,{size,color:"dim"}));const values=rows.map(row=>row.value!==void 0?text(row.value,{size,font:"mono",color:row.tone??"ink"}):null);const sparkWidth=size*3.6;const contentWidth=Math.max(advanceWidth(title)+(badge?advanceWidth(badge)+size*1.6:0),subtitle?advanceWidth(subtitle):0,...rows.map((row,i)=>advanceWidth(labels[i])+(values[i]?advanceWidth(values[i])+size*1.1:0)+(row.spark?sparkWidth+size*.6:0)),0);const width=this.boxWidth=Math.max(options.width??0,contentWidth+pad2*2);const headerHeight=size*1.4+(subtitle?size*1.2:0);const rowsHeight=rows.reduce((sum,row)=>sum+rowHeight+(row.meter!==void 0?size*.32:0),0);const tagsHeight=options.tags?.length?size*1.72:0;const height=this.boxHeight=pad2*1.5+headerHeight+(rows.length?size*.55:0)+rowsHeight+tagsHeight;const left=-width/2+pad2,right=width/2-pad2;this.frame=new Node(rectPath(-width/2,-height/2,width,height,options.radius??4)).fill(options.fill??"surface").stroke(options.border??"gridStrong",1);this.add(this.frame);if(options.accent){const bar=new Node(rectPath(-width/2,-height/2+1,2.5,height-2)).fill(options.accent);this.accentBar=bar;this.add(bar)}let y=-height/2+pad2*.75+size*.62;this.titleNode=place(title,left,y);this.add(title);if(badge){;this.badgeNode=place(badge,right,y,"right");this.add(badge)}y+=size*1.3;if(subtitle){;this.subtitleNode=place(subtitle,left,y-size*.1);this.add(subtitle);y+=size*1.2}if(rows.length){const ruleY=y-size*.38;this.add(line([-width/2+pad2,ruleY],[width/2-pad2,ruleY],{stroke:"grid",width:1}));y+=size*.5}rows.forEach((row,i)=>{place(labels[i],left,y);this.rowLabels.push(labels[i]);this.add(labels[i]);let end=right;const value=values[i];if(value){place(value,end,y,"right");this.add(value);end-=advanceWidth(value)+size*.7}this.rowValues.push(value??null);if(row.spark){const spark=sparkline(row.spark,{width:sparkWidth,height:size*.82,color:row.tone??"blue",dotted:true,weight:1.2});this.add(spark.at(end-sparkWidth/2,y-size*.1))}y+=rowHeight;if(row.meter!==void 0){const meterY=y-size*.62;this.add(line([left,meterY],[right,meterY],{stroke:"grid",width:2}));const meter=line([left,meterY],[left+(right-left)*Math.max(0,Math.min(1,row.meter)),meterY],{stroke:row.tone??"blue",width:2});meter.set("cap","butt");this.meters.push(meter);this.add(meter);y+=size*.32}});if(options.tags?.length){let x=left;const tagY=height/2-pad2*.7-size*.4;for(const tag of options.tags){const label=text(tag,{size:size*.78,font:"mono",color:"dim"});const w=advanceWidth(label)+size*.7;const chip=new Node(rectPath(x,tagY-size*.62,w,size*1.24,2)).stroke("gridStrong",1);place(label,x+size*.35,tagY);this.tagNodes.push(label);this.add(chip,label);x+=w+size*.34}}}port(side,at=0){const b=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;if(side==="left")return[b.x,cy+at*b.height/2];if(side==="right")return[b.x+b.width,cy+at*b.height/2];if(side==="top")return[cx+at*b.width/2,b.y];return[cx+at*b.width/2,b.y+b.height]}enter(options={}){return{label:"infoBox.enter",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const fillTarget=this.frame.get("fillOpacity");stepAt2(this.frame,"trimTo",0,ctx.t0);stepAt2(this.frame,"fillOpacity",0,ctx.t0);this.frame.tween("trimTo",1,ctx.t0,ctx.t0+span*.65,ctx.ease);this.frame.tween("fillOpacity",fillTarget,ctx.t0+span*.2,ctx.t0+span*.8,ctx.ease);const items=this.children.filter(child=>child!==this.frame);const windows=staggered(items.length,.06,ctx.t0+span*.25,ctx.t1);items.forEach((item,i)=>{const[start,end]=windows[i];const target=item.get("opacity");stepAt2(item,"opacity",0,ctx.t0);item.tween("opacity",target,start,end,ctx.ease)})}}}setValue(row,value,options={}){const previous=this.rowValues[row];if(!previous)throw new Error(`Info box row ${row} has no value to change.`);const next=text(value,{size:this.valueSize,font:"mono",color:options.tone??"ink"});const right=previous.get("x")+previous.get("px");place(next,right,previous.get("y"),"right");const anim=morphMatching(previous,next,{duration:.5,...options});return{...anim,label:"infoBox.setValue",schedule:ctx=>{this.add(next);this.rowValues[row]=next;anim.schedule(ctx)}}}};function infoBox(options){return new InfoBox(options)}function sparkline(values,options={}){const width=options.width??80,height=options.height??20;const low=Math.min(...values),high=Math.max(...values);const span=high-low||1;const points=values.map((value,i)=>[(i/Math.max(1,values.length-1)-.5)*width,(.5-(value-low)/span)*height]);const color=options.color??"blue";const made=new Node;if(options.area){made.add(new Node(polyPath([...points,[width/2,height/2],[-width/2,height/2]],true)).fill(color,options.area))}made.add(new Node(values.length>2?smoothPath(points):polyPath(points)).stroke(color,options.weight??1.5));if(options.dotted)made.add(dot((options.weight??1.5)*1.5,color).at(points[points.length-1]));return made}var NORMALS={left:[-1,0],right:[1,0],top:[0,-1],bottom:[0,1]};function sidePoint(b,side,offset){const cx=b.x+b.width/2,cy=b.y+b.height/2;if(side==="left")return[b.x,cy+offset*b.height/2];if(side==="right")return[b.x+b.width,cy+offset*b.height/2];if(side==="top")return[cx+offset*b.width/2,b.y];return[cx+offset*b.width/2,b.y+b.height]}function chooseSides(a,b){const gapX=Math.max(b.x-(a.x+a.width),a.x-(b.x+b.width));const gapY=Math.max(b.y-(a.y+a.height),a.y-(b.y+b.height));const ax=a.x+a.width/2,ay=a.y+a.height/2,bx=b.x+b.width/2,by=b.y+b.height/2;if(gapX>=gapY)return bx>=ax?["right","left"]:["left","right"];return by>=ay?["bottom","top"]:["top","bottom"]}function fillet(points,radius){let d=`M${points[0][0]} ${points[0][1]}`;for(let i=1;i<points.length-1;i++){const prev=points[i-1],at=points[i],next=points[i+1];const l0=Math.hypot(at[0]-prev[0],at[1]-prev[1]),l1=Math.hypot(next[0]-at[0],next[1]-at[1]);const r=Math.min(radius,l0/2,l1/2);if(r<.5){d+=`L${at[0]} ${at[1]}`;continue}const p0x=at[0]-(at[0]-prev[0])/(l0||1)*r,p0y=at[1]-(at[1]-prev[1])/(l0||1)*r;const p1x=at[0]+(next[0]-at[0])/(l1||1)*r,p1y=at[1]+(next[1]-at[1])/(l1||1)*r;d+=`L${p0x} ${p0y}Q${at[0]} ${at[1]} ${p1x} ${p1y}`}const last=points[points.length-1];return parseSvgPath(`${d}L${last[0]} ${last[1]}`)}var Connector2=class extends Node{fromEnd;toEnd;options;pulses=[];plate=null;caption=null;constructor(from,to2,options={}){super([]);this.fromEnd=from;this.toEnd=to2;this.options=options;this.base.stroke=toPaint(options.color??"dim");this.base.strokeWidth=options.width??1.6;this.draw=time=>this.build(time)}anchors(){const{fromEnd,toEnd,options}=this;const gap=options.gap??3;const boxOf=end=>end instanceof Node?end.bounds():{x:end[0],y:end[1],width:0,height:0};const a=boxOf(fromEnd),b=boxOf(toEnd);const[autoFrom,autoTo]=chooseSides(a,b);const sideFrom=options.from??autoFrom,sideTo=options.to??autoTo;const anchor=(end,box,side,offset)=>{const normal=NORMALS[side];if(!(end instanceof Node))return{point:end,normal};const[x,y]=sidePoint(box,side,offset);return{point:[x+normal[0]*gap,y+normal[1]*gap],normal}};return[anchor(fromEnd,a,sideFrom,options.fromOffset??0),anchor(toEnd,b,sideTo,options.toOffset??0)]}routeNow(){const[a,b]=this.anchors();const route=this.options.route??"curve";if(route==="straight")return polyPath([a.point,b.point]);if(route==="ortho"){const r=this.options.radius??8;const horizontalA=a.normal[0]!==0,horizontalB=b.normal[0]!==0;if(horizontalA&&horizontalB){const mid=(a.point[0]+b.point[0])/2;return fillet([a.point,[mid,a.point[1]],[mid,b.point[1]],b.point],r)}if(!horizontalA&&!horizontalB){const mid=(a.point[1]+b.point[1])/2;return fillet([a.point,[a.point[0],mid],[b.point[0],mid],b.point],r)}const corner=horizontalA?[b.point[0],a.point[1]]:[a.point[0],b.point[1]];return fillet([a.point,corner,b.point],r)}const distance=Math.hypot(b.point[0]-a.point[0],b.point[1]-a.point[1]);const reach=Math.max(18,distance*(this.options.curvature??.42));const c1=[a.point[0]+a.normal[0]*reach,a.point[1]+a.normal[1]*reach];const c2=[b.point[0]+b.normal[0]*reach,b.point[1]+b.normal[1]*reach];return parseSvgPath(`M${a.point[0]} ${a.point[1]}C${c1[0]} ${c1[1]} ${c2[0]} ${c2[1]} ${b.point[0]} ${b.point[1]}`)}build(time){const inverse=this.parent&&this.parent!==null?invert(this.worldMatrix()):IDENTITY;const whole=transformPath(this.routeNow(),inverse);const length=pathLength(whole);if(length<1)return[];const progress=this.get("trimTo");const options=this.options;const stroke=this.get("stroke");const width=this.get("strokeWidth");const out=[];const tip=options.tip??true;const tipSize=tip?options.tipSize??Math.max(7,width*4.4):0;const shaftEnd=progress*(1-tipSize/length);const shaft=trimPath(whole,this.get("trimFrom"),shaftEnd);const color=stroke??toPaint("dim");if(shaft.length){const node=new Node(shaft).stroke(color,width);if(options.dash||options.flow){node.dash(options.dash??[6,6],options.flow?-time*options.flow:0)}node.set("strokeOpacity",this.get("strokeOpacity"));out.push(node)}if(tip&&progress>.02){const[x,y]=pointAt(whole,progress);const[ux,uy]=tangentAt(whole,Math.min(.997,progress));const half=tipSize*.38;const bx=x-ux*tipSize,by=y-uy*tipSize;out.push(new Node(polyPath([[x,y],[bx-uy*half,by+ux*half],[bx+uy*half,by-ux*half]],true)).fill(color))}for(const entry of this.pulses){if(time<entry.t0||time>=entry.t1)continue;const a=entry.ease((time-entry.t0)/(entry.t1-entry.t0));const from=Math.max(0,a*(1+entry.length)-entry.length),to2=Math.min(1,a*(1+entry.length));const lit=trimPath(whole,from,to2);if(lit.length)out.push(new Node(lit).stroke(entry.color,entry.width).glow(entry.glow))}if(options.label&&progress>.5){const size=options.labelSize??12;this.caption??=text(options.label,{size,font:"mono",color:options.labelColor??"dim"});const textWidth=advanceWidth(this.caption);const pad2=size*.35;this.plate??=new Node(rectPath(-textWidth/2-pad2,-size*.72,textWidth+pad2*2,size*1.44,2)).fill(options.labelBackground??"bg");const[mx,my]=pointAt(whole,options.labelAt??.5);const fade2=Math.min(1,(progress-.5)*4);out.push(this.plate.at(mx,my).opacity(fade2),this.caption.at(mx,my).opacity(fade2))}return out}pulse(options={}){return{label:"connector.pulse",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);this.pulses.push({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,color:options.color??"yellow",length:options.length??.22,width:options.width??this.get("strokeWidth")+1.2,glow:options.glow??6})}}}pointNow(fraction=.5){return pointAt(this.routeNow(),fraction)}};function connector(from,to2,options={}){return new Connector2(from,to2,options)}function legend(items,options={}){const size=options.size??13;const row=(options.direction??"row")==="row";const gap=options.gap??(row?size*1.5:size*.6);const keyWidth=size*1.5;const made=new Node;let cursor=0;const entries=[];for(const item of items){const color=item.color??"dim";const kind=item.kind??"swatch";const key=kind==="line"?line([-keyWidth/2,0],[keyWidth/2,0],{stroke:color,width:2.2}):kind==="dash"?line([-keyWidth/2,0],[keyWidth/2,0],{stroke:color,width:2,dash:[4,3.5]}):kind==="dot"?dot(size*.32,color):kind==="ring"?circle(size*.32,{stroke:color,width:1.6}):new Node(rectPath(-size*.42,-size*.42,size*.84,size*.84,1.5)).fill(color);const caption=text(item.label,{size,color:"dim"});const width=keyWidth+size*.5+advanceWidth(caption);const entry=new Node;entry.add(key.at(keyWidth/2,0));place(caption,keyWidth+size*.5,0);entry.add(caption);entries.push({node:entry,width})}const total=entries.reduce((sum,entry)=>sum+entry.width,0)+gap*Math.max(0,entries.length-1);const widest=Math.max(0,...entries.map(entry=>entry.width));const step=size*1.2+gap;entries.forEach((entry,i)=>{if(row){entry.node.at(-total/2+cursor,0);cursor+=entry.width+gap}else{entry.node.at(-widest/2,(i-(entries.length-1)/2)*step)}made.add(entry.node)});return made}var Callout=class extends Node{leader;marker;body;titleNode=null;constructor(target,body,options={}){super();const size=options.size??15;const color=options.color??"yellow";const side=options.side??"right";const distance=options.distance??72;const wrap=options.width??280;const normal=NORMALS[side];const box=target instanceof Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const anchor=target instanceof Node?sidePoint(box,side,0):target;const title=options.title?text(options.title,{size,weight:600,color}):null;const copy=text(body,{size:size*.94,color:options.bodyColor??"dim",maxWidth:wrap,leading:1.36});const titleHeight=title?size*1.42:0;const blockWidth=Math.max(copy.width,title?advanceWidth(title):0);const copyHeight=copy.height;const blockHeight=titleHeight+copyHeight;const offset=options.offset??0;const blockLeft=side==="right"?anchor[0]+distance:side==="left"?anchor[0]-distance-blockWidth:anchor[0]-blockWidth/2+offset;const blockTop=side==="bottom"?anchor[1]+distance:side==="top"?anchor[1]-distance-blockHeight:anchor[1]-blockHeight/2+offset;if(options.plate){const pad2=size*.5;this.add(new Node(rectPath(blockLeft-pad2,blockTop-pad2,blockWidth+pad2*2,blockHeight+pad2*2,3)).fill("bg",.86))}if(title){;this.titleNode=place(title,blockLeft,blockTop+size*.62);this.add(title)}copy.moveTo([blockLeft+copy.width/2,blockTop+titleHeight+copyHeight/2]);this.body=copy;this.add(copy);const reach=side==="right"?[blockLeft-8,blockTop+blockHeight/2]:side==="left"?[blockLeft+blockWidth+8,blockTop+blockHeight/2]:side==="bottom"?[blockLeft+blockWidth/2,blockTop-8]:[blockLeft+blockWidth/2,blockTop+blockHeight+8];const elbow=normal[0]!==0?[anchor[0]+normal[0]*distance*.45,reach[1]]:[reach[0],anchor[1]+normal[1]*distance*.45];this.leader=new Node(polyPath([anchor,elbow,reach])).stroke(color,1.25);this.marker=dot(3,color).at(anchor);this.add(this.leader,this.marker)}enter(options={}){return{label:"callout.enter",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.marker,"opacity",0,ctx.t0);this.marker.tween("opacity",1,ctx.t0,ctx.t0+span*.2,ctx.ease);stepAt2(this.leader,"trimTo",0,ctx.t0);this.leader.tween("trimTo",1,ctx.t0,ctx.t0+span*.55,ctx.ease);for(const child of this.children){if(child===this.marker||child===this.leader)continue;const target=child.get("opacity");stepAt2(child,"opacity",0,ctx.t0);child.tween("opacity",target,ctx.t0+span*.42,ctx.t1,ctx.ease)}}}}};function callout(target,body,options={}){return new Callout(target,body,options)}function list2(target){return Array.isArray(target)?[...target]:[target]}function glyphsOf(target){return list2(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function typewriter(target,options={}){const glyphs=glyphsOf(target);return{label:"typewriter",duration:options.duration??Math.max(.5,glyphs.length*.035),ease:options.ease??linear,schedule(ctx){for(const node of list2(target))reveal(node,ctx.t0,ctx.stage);const leaves=glyphsOf(target);if(leaves.length===0)return;const span=ctx.t1-ctx.t0;let cursor=null;if(options.cursor){const first=leaves[0].bounds();const height=first.height*1.35||24;cursor=new Node(rectPath(0,-height/2,Math.max(3,height*.1),height)).fill(options.cursorColor??"ink");ctx.stage.add(cursor)}leaves.forEach((leaf,i)=>{const at=ctx.t0+span*ctx.ease(i/leaves.length);const opacity=leaf.get("opacity");stepAt2(leaf,"opacity",0,ctx.t0);stepAt2(leaf,"opacity",opacity,at);if(cursor){clock.now=at;const b=leaf.bounds();stepAt2(cursor,"x",b.x+b.width+3,at);stepAt2(cursor,"y",b.y+b.height/2,at);clock.now=ctx.t0}});if(cursor)stepAt2(cursor,"visible",false,ctx.t1)}}}function wipe(target,options={}){return{label:"wipe",duration:options.duration??1.2,ease:options.ease??smooth2,schedule(ctx){const from=options.from??"left";for(const node of list2(target))reveal(node,ctx.t0,ctx.stage);const leaves=list2(target).flatMap(node=>node.leaves());const position2=leaf=>{const b=leaf.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;return from==="left"?cx:from==="right"?-cx:from==="top"?cy:-cy};const values=leaves.map(position2);const low=Math.min(...values),high=Math.max(...values);const soft=options.soft??.25;const travel=options.travel??0;const span=ctx.t1-ctx.t0;const dx=from==="left"?-travel:from==="right"?travel:0;const dy=from==="top"?-travel:from==="bottom"?travel:0;leaves.forEach((leaf,i)=>{const fraction=high>low?(values[i]-low)/(high-low):0;const start=ctx.t0+span*(1-soft)*ctx.ease(fraction);const end=start+span*soft;const opacity=leaf.get("opacity");stepAt2(leaf,"opacity",0,ctx.t0);leaf.tween("opacity",opacity,start,end,smooth2);if(travel){const x=leaf.get("x"),y=leaf.get("y");stepAt2(leaf,"x",x+dx,ctx.t0);stepAt2(leaf,"y",y+dy,ctx.t0);leaf.tween("x",x,start,end,smooth2);leaf.tween("y",y,start,end,smooth2)}})}}}var Counter=class extends Node{value;constructor(initial=0,options={}){super();this.value=new Value(initial);const digits=options.digits??0;const format=new Intl.NumberFormat("en-US",{minimumFractionDigits:digits,maximumFractionDigits:digits,useGrouping:options.grouped??true});const inner=dynamic(()=>{const body=`${options.prefix??""}${format.format(this.value.value)}${options.suffix??""}`;return text(body,{size:options.size??48,color:options.color??"ink",font:options.font??"mono",weight:options.weight??400})});this.add(inner)}};function counter(initial=0,options={}){return new Counter(initial,options)}function countUp(target,to2,options={}){const value=target instanceof Counter?target.value:target;return{label:"countUp",duration:options.duration??1.2,ease:options.ease,schedule(ctx){if(target instanceof Counter)reveal(target,ctx.t0,ctx.stage);tweenValue(value,to2,ctx.t0,ctx.t1,ctx.ease)}}}function spin(node,rate,options={}){return{label:"spin",duration:options.duration??2,ease:options.ease??linear,schedule(ctx){reveal(node,ctx.t0,ctx.stage);clock.now=ctx.t0;node.pivotAt(options.about??node.center);const start=node.get("rotation");const seconds=ctx.t1-ctx.t0;node.tween("rotation",start+rate*seconds,ctx.t0,ctx.t1,ctx.ease)}}}function swap(a,b,options={}){return{label:"swap",duration:options.duration??.9,ease:options.ease,schedule(ctx){reveal(a,ctx.t0,ctx.stage);reveal(b,ctx.t0,ctx.stage);clock.now=ctx.t0;const ca=a.center,cb=b.center;const lift=options.lift??Math.max(60,Math.hypot(cb[0]-ca[0],cb[1]-ca[1])*.3);const travel=(node,from,to2,sign)=>{const inverse=node.parent?invert(node.parent.worldMatrix()):[1,0,0,1,0,0];const x0=node.get("x"),y0=node.get("y");const[lfx,lfy]=apply(inverse,from[0],from[1]),[ltx,lty]=apply(inverse,to2[0],to2[1]);const x1=x0+ltx-lfx,y1=y0+lty-lfy;node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:x1,at:t=>x0+(x1-x0)*t});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:y1,at:t=>y0+(y1-y0)*t-sign*lift*4*t*(1-t)})};travel(a,ca,cb,1);travel(b,cb,ca,-1)}}}function highlightSweep(target,options={}){const mark=new Node([]);const nodes=list2(target);return{mark,label:"highlightSweep",duration:options.duration??.7,ease:options.ease,schedule(ctx){let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const node of nodes){const b=node.bounds();x0=Math.min(x0,b.x);y0=Math.min(y0,b.y);x1=Math.max(x1,b.x+b.width);y1=Math.max(y1,b.y+b.height)}const pad2=options.pad??6;const left=x0-pad2,top=y0-pad2,width=x1-x0+pad2*2,height=y1-y0+pad2*2;const radius=options.radius??3;const color=options.color??"yellow";mark.base.fill=toPaint(color);mark.base.fillOpacity=options.opacity??.26;const parent=ctx.stage.root;parent.add(mark);const first=nodes[0];let anchor=first;while(anchor.parent&&anchor.parent!==parent)anchor=anchor.parent;const index=parent.children.indexOf(anchor);parent.children.splice(parent.children.indexOf(mark),1);parent.children.splice(index>=0?index:parent.children.length,0,mark);const fromRight=options.from==="right";const shape2=a=>{const w=Math.max(.01,width*a);return rectPath(fromRight?left+width-w:left,top,w,height,radius)};mark.track("path").step(ctx.t0,shape2(0));mark.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:shape2(1),at:shape2})}}}var tokens4=text2=>text2.toLowerCase().replace(/[^a-z0-9.]+/g," ").split(" ").map(token=>token.replace(/^\.+|\.+$/g,"")).filter(Boolean);function captionLines(text2,length=74){const lines=[];for(const sentence of text2.match(/[^.?!]+(?:[.?!]+(?=\s|$)|\.\d[^.?!]*[.?!]?|$)/g)??[]){let line2="";for(const word of sentence.split(/\s+/).filter(Boolean)){if(line2&&line2.length+word.length+1>length){lines.push(line2);line2=word}else{line2=line2?`${line2} ${word}`:word}}if(line2)lines.push(line2)}return lines}var SceneClock=class{constructor(stage,id,start,end,beats){this.stage=stage;this.id=id;this.start=start;this.end=end;this.beats=beats}stage;id;start;end;beats;cue(phrase,beat){const want=tokens4(phrase);if(want.length===0)throw new Error(`narration: scene "${this.id}": a cue needs at least one word`);if(beat!==void 0&&!this.beats[beat])throw new Error(`narration: scene "${this.id}" has no beat ${beat}`);const list3=beat===void 0?this.beats:[this.beats[beat]];for(const placed of list3){const spoken=placed.words.flatMap(word=>tokens4(word.text).map(token=>({token,start:word.start,end:word.end})));for(let i=0;i+want.length<=spoken.length;i++){if(want.every((token,j)=>spoken[i+j].token===token)){return{start:placed.start+spoken[i].start,end:placed.start+spoken[i+want.length-1].end}}}}const where=beat===void 0?"":` in beat ${beat}`;throw new Error(`narration: scene "${this.id}": the voice never says "${phrase}"${where}`)}on(phrase,build,offset=0,beat){this.stage.at(Math.max(0,this.cue(phrase,beat).start+offset),build);return this}after(phrase,build,offset=0,beat){this.stage.at(Math.max(0,this.cue(phrase,beat).end+offset),build);return this}onBeat(index,build,offset=0){const beat=this.beats[index];if(!beat)throw new Error(`narration: scene "${this.id}" has no beat ${index}`);this.stage.at(Math.max(0,beat.start+offset),build);return this}at(seconds,build){this.stage.at(Math.max(0,this.start+seconds),build);return this}clear(nodes,lead=.24,duration=.26){this.stage.at(this.end-lead,()=>this.stage.play(...nodes.map(node=>fade(node,0,{duration}))));return this}};var Narration=class{scenes;duration;lead;gap;constructor(stage,timing,options={}){this.lead=options.lead??timing.lead??.6;this.gap=options.gap??timing.gap??.4;if(!(this.lead>=0)||!(this.gap>=0))throw new Error("narration: lead and gap must be zero or more seconds");const seen=new Set;const scenes=[];let now=this.lead;let last=now;for(const scene of timing.scenes){if(seen.has(scene.id))throw new Error(`narration: two scenes are named "${scene.id}"`);seen.add(scene.id);const start=now;const beats=[];for(const beat of scene.beats){if(!(beat.duration>0))throw new Error(`narration: scene "${scene.id}" has a beat without a measured duration: "${beat.say}"`);const hold2=beat.hold??0;beats.push({start:now,end:now+beat.duration,until:now+beat.duration+hold2,text:beat.say,words:beat.words??[]});now+=beat.duration+hold2}scenes.push(new SceneClock(stage,scene.id,start,now,beats));if(options.chapters!==false&&scene.title)stage.chapters.push({title:scene.title,time:scenes.length===1?0:start});if(options.captions!==false){for(const beat of beats){const lines=captionLines(beat.text,options.captionLength);const total=lines.reduce((sum,line2)=>sum+line2.length,0);let t0=beat.start;for(const line2 of lines){const t1=t0+(beat.end-beat.start)*line2.length/total;stage.captions.push({t0,t1,text:line2});t0=t1}}}last=now;now+=this.gap}this.scenes=scenes;this.duration=last;stage.at(last,()=>{})}scene(id){const found=this.scenes.find(scene=>scene.id===id);if(!found)throw new Error(`narration: no scene "${id}". The scenes are: ${this.scenes.map(scene=>scene.id).join(", ")}`);return found}placements(){return this.scenes.flatMap(scene=>scene.beats.map((beat,index)=>({scene:scene.id,beat:index,start:beat.start,end:beat.end})))}};function narration(stage,timing,options={}){return new Narration(stage,timing,options)}var read3=value=>typeof value==="function"?value():value;var normalize=v=>{const length=Math.hypot(v[0],v[1],v[2])||1;return[v[0]/length,v[1]/length,v[2]/length]};var View3D=class{ops=[];depths=[];rx=0;ry=0;ux=0;uy=0;uz=0;dx=0;dy=0;dz=0;fx=0;fy=0;fz=0;distance=12;unit=100;perspective=true;matrix=[1,0,0,1,0,0];alpha=1;scale=1;light=[0,0,1];half=[0,0,1];ambient=.4;shine=.2;fog=0;fogColor=[0,0,0,1];depthRange=1;brightness=1;px=0;py=0;pz=0;ps=1;project(x,y,z){const vx=x-this.fx,vy=y-this.fy,vz=z-this.fz;const cx=vx*this.rx+vy*this.ry;const cy=vx*this.ux+vy*this.uy+vz*this.uz;const cz=vx*this.dx+vy*this.dy+vz*this.dz;let s=1;if(this.perspective){const gap=this.distance-cz;if(gap<=.05)return false;s=this.distance/gap}const sx=cx*this.unit*s,sy=-cy*this.unit*s;const m=this.matrix;this.px=m[0]*sx+m[2]*sy+m[4];this.py=m[1]*sx+m[3]*sy+m[5];this.pz=cz;this.ps=s;return true}screen(x,y,z){const vx=x-this.fx,vy=y-this.fy,vz=z-this.fz;const cx=vx*this.rx+vy*this.ry;const cy=vx*this.ux+vy*this.uy+vz*this.uz;const cz=vx*this.dx+vy*this.dy+vz*this.dz;let s=1;if(this.perspective){const gap=this.distance-cz;if(gap<=.05)return null;s=this.distance/gap}return[cx*this.unit*s,-cy*this.unit*s]}fogged(r,g,b,depth){if(this.fog<=0)return[r,g,b,1];const t=Math.max(0,Math.min(1,-depth/this.depthRange*this.fog));return[r+(this.fogColor[0]-r)*t,g+(this.fogColor[1]-g)*t,b+(this.fogColor[2]-b)*t,1]}push(op,depth){this.ops.push(op);this.depths.push(depth)}};function strokeOp(path,color,alpha3,width,glow=0,cap="round"){return{kind:"path",path,strokePath:path,fill:null,fillAlpha:0,stroke:color,strokeAlpha:alpha3,strokeWidth:width,cap,join:"round",dash:null,dashOffset:0,glow,glowColor:null,blend:"normal"}}function fillOp(path,color,alpha3,stroke,strokeAlpha,strokeWidth){return{kind:"path",path,strokePath:path,fill:color,fillAlpha:alpha3,stroke,strokeAlpha,strokeWidth,cap:"round",join:"round",dash:null,dashOffset:0,glow:0,glowColor:null,blend:"normal"}}function lineRing(x0,y0,x1,y1){const dx=x1-x0,dy=y1-y0;const p=new Float64Array(8);p[0]=x0;p[1]=y0;p[2]=x0+dx/3;p[3]=y0+dy/3;p[4]=x0+dx*2/3;p[5]=y0+dy*2/3;p[6]=x1;p[7]=y1;return{p,closed:false,straight:true}}function polygonRing(points){const count=points.length/2;const p=new Float64Array(2+count*6);p[0]=points[0];p[1]=points[1];let o=2;for(let i=0;i<count;i++){const ax=points[i*2],ay=points[i*2+1];const bx=points[(i+1)%count*2],by=points[(i+1)%count*2+1];p[o++]=ax+(bx-ax)/3;p[o++]=ay+(by-ay)/3;p[o++]=ax+(bx-ax)*2/3;p[o++]=ay+(by-ay)*2/3;p[o++]=bx;p[o++]=by}return{p,closed:true,straight:true}}var KAPPA2=.5522847498307936;function circleRing(cx,cy,r){const k=r*KAPPA2;return{closed:true,p:Float64Array.of(cx+r,cy,cx+r,cy+k,cx+k,cy+r,cx,cy+r,cx-k,cy+r,cx-r,cy+k,cx-r,cy,cx-r,cy-k,cx-k,cy-r,cx,cy-r,cx+k,cy-r,cx+r,cy-k,cx+r,cy)}}var Object3D=class extends Node{constructor(){super([])}labelsNow(_view){return[]}objectAlpha(view){return view.alpha*this.get("opacity")}};var Scene3D=class extends Node{phi;theta;distance;unit;focusX;focusY;focusZ;orthographic;settings;spins=[];openSpin=null;constructor(options={}){super();this.settings=options;this.phi=new Value(options.phi??1.15);this.theta=new Value(options.theta??-1);this.distance=new Value(options.distance??14);this.unit=new Value(options.unit??120);this.focusX=new Value(options.focus?.[0]??0);this.focusY=new Value(options.focus?.[1]??0);this.focusZ=new Value(options.focus?.[2]??0);this.orthographic=options.perspective===false;this.rawOps=(matrix2,alpha3,ops)=>this.render(matrix2,alpha3,ops);this.draw=time=>{const view=this.view(this.worldless,1,time);return this.children.flatMap(child=>child instanceof Object3D&&child.get("visible")?child.labelsNow(view):[])}}worldless=[1,0,0,1,0,0];view(matrix2,alpha3,time){const view=new View3D;const phi=this.phi.value;let theta=this.theta.value;for(const spin2 of this.spins){if(time>spin2.from)theta+=(Math.min(time,spin2.to)-spin2.from)*spin2.rate}const sinP=Math.sin(phi),cosP=Math.cos(phi),sinT=Math.sin(theta),cosT=Math.cos(theta);view.rx=-sinT;view.ry=cosT;view.ux=-cosP*cosT;view.uy=-cosP*sinT;view.uz=sinP;view.dx=sinP*cosT;view.dy=sinP*sinT;view.dz=cosP;view.fx=this.focusX.value;view.fy=this.focusY.value;view.fz=this.focusZ.value;view.distance=this.distance.value;view.unit=this.unit.value;view.perspective=!this.orthographic;view.matrix=matrix2;view.alpha=alpha3;view.scale=Math.sqrt(Math.abs(matrix2[0]*matrix2[3]-matrix2[1]*matrix2[2]));const light=normalize(this.settings.light??[-.45,-.55,.85]);view.light=light;view.half=normalize([light[0]+view.dx,light[1]+view.dy,light[2]+view.dz]);view.ambient=this.settings.ambient??.26;view.shine=this.settings.shine??.2;view.fog=this.settings.fog??.6;const background=parseColor("bg");view.fogColor=this.settings.fogColor?solidColor(this.settings.fogColor):background;view.depthRange=Math.max(3,view.distance*.5);view.brightness=this.settings.brightness??(background[0]+background[1]+background[2]<200?.8:1);return view}render(matrix2,alpha3,ops){const time=clock.now;const view=this.view(matrix2,alpha3,time);for(const child of this.children){if(child instanceof Object3D&&child.get("visible"))child.emit(view,time)}const count=view.ops.length;const order=new Uint32Array(count);for(let i=0;i<count;i++)order[i]=i;const depths=view.depths;order.sort((a,b)=>depths[a]-depths[b]);for(let i=0;i<count;i++)ops.push(view.ops[order[i]])}orbit(target,options={}){return{label:"camera3d",duration:options.duration??2,ease:options.ease,schedule:ctx=>{if(target.phi!==void 0)tweenValue(this.phi,target.phi,ctx.t0,ctx.t1,ctx.ease);if(target.theta!==void 0)tweenValue(this.theta,target.theta,ctx.t0,ctx.t1,ctx.ease);if(target.distance!==void 0)tweenValue(this.distance,target.distance,ctx.t0,ctx.t1,ctx.ease);if(target.unit!==void 0)tweenValue(this.unit,target.unit,ctx.t0,ctx.t1,ctx.ease);if(target.focus){tweenValue(this.focusX,target.focus[0],ctx.t0,ctx.t1,ctx.ease);tweenValue(this.focusY,target.focus[1],ctx.t0,ctx.t1,ctx.ease);tweenValue(this.focusZ,target.focus[2],ctx.t0,ctx.t1,ctx.ease)}}}}spin(rate=.12){this.stopSpin();this.openSpin={from:clock.now,to:Infinity,rate};this.spins.push(this.openSpin);return this}stopSpin(){if(this.openSpin)this.openSpin.to=clock.now;this.openSpin=null;return this}stagePoint(point){const view=this.view(this.worldMatrix(),1,clock.now);return view.project(point[0],point[1],point[2])?[view.px,view.py]:[0,0]}};function scene3d(options={}){return new Scene3D(options)}var Surface3D=class extends Object3D{constructor(fn,uRange,vRange,options={}){super();this.fn=fn;this.uRange=uRange;this.vRange=vRange;this.options=options;const res=options.resolution??40;this.nu=typeof res==="number"?res:res[0];this.nv=typeof res==="number"?res:res[1];const vertices=(this.nu+1)*(this.nv+1);this.positions=new Float64Array(vertices*3);this.normals=new Float64Array(this.nu*this.nv*3);this.vertexNormals=new Float64Array(vertices*3);this.shadingNormals=new Float64Array(this.nu*this.nv*3);this.faceColors=new Float32Array(this.nu*this.nv*3);this.screenX=new Float64Array(vertices);this.screenY=new Float64Array(vertices);this.screenZ=new Float64Array(vertices);this.valid=new Uint8Array(vertices);this.meshColor=options.mesh?solidColor(options.mesh):null;if(options.colors){const palette=options.colors.map(c=>solidColor(c));this.ramp=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c])}if(options.checker)this.checkerColors=[solidColor(options.checker[0]),solidColor(options.checker[1])];if(options.color||!options.colors&&!options.checker&&!options.colorAt){this.base.fill=toPaint(options.color??"blue")}}fn;uRange;vRange;options;nu;nv;positions;normals;vertexNormals;shadingNormals;faceColors;computedFor=-Infinity;screenX;screenY;screenZ;valid;meshColor;ramp=null;checkerColors=null;compute(time){const{nu,nv,positions,normals,faceColors,fn,uRange,vRange,options}=this;let o=0;let zMin=Infinity,zMax=-Infinity;for(let i=0;i<=nu;i++){const u=uRange[0]+(uRange[1]-uRange[0])*i/nu;for(let j=0;j<=nv;j++){const v=vRange[0]+(vRange[1]-vRange[0])*j/nv;const p=fn(u,v,time);positions[o++]=p[0];positions[o++]=p[1];positions[o++]=p[2];if(p[2]<zMin)zMin=p[2];if(p[2]>zMax)zMax=p[2]}}const stride=nv+1;const vertexNormals=this.vertexNormals;vertexNormals.fill(0);for(let i=0;i<nu;i++){for(let j=0;j<nv;j++){const a=(i*stride+j)*3,b=((i+1)*stride+j)*3;const c=((i+1)*stride+j+1)*3,d=(i*stride+j+1)*3;const ex=positions[c]-positions[a],ey=positions[c+1]-positions[a+1],ez=positions[c+2]-positions[a+2];const fx=positions[d]-positions[b],fy=positions[d+1]-positions[b+1],fz=positions[d+2]-positions[b+2];let nx=ey*fz-ez*fy,ny=ez*fx-ex*fz,nz=ex*fy-ey*fx;const length=Math.hypot(nx,ny,nz)||1;nx/=length;ny/=length;nz/=length;if(options.outwardFrom){const[ox,oy,oz]=options.outwardFrom;const mx=(positions[a]+positions[c])/2-ox,my=(positions[a+1]+positions[c+1])/2-oy,mz=(positions[a+2]+positions[c+2])/2-oz;if(nx*mx+ny*my+nz*mz<0){nx=-nx;ny=-ny;nz=-nz}}const f=(i*nv+j)*3;normals[f]=nx;normals[f+1]=ny;normals[f+2]=nz;for(const vertex of[a/3,b/3,c/3,d/3]){vertexNormals[vertex*3]+=nx;vertexNormals[vertex*3+1]+=ny;vertexNormals[vertex*3+2]+=nz}if(this.ramp||this.checkerColors||options.colorAt){let color;if(options.colorAt){const mx=(positions[a]+positions[c])/2,my=(positions[a+1]+positions[c+1])/2,mz=(positions[a+2]+positions[c+2])/2;color=options.colorAt(mx,my,mz,(i+.5)/nu,(j+.5)/nv)}else if(this.checkerColors){color=this.checkerColors[(i+j)%2]}else{const mz=(positions[a+2]+positions[c+2]+positions[b+2]+positions[d+2])/4;color=sampleStops(this.ramp,zMax>zMin?(mz-zMin)/(zMax-zMin):0)}faceColors[f]=color[0];faceColors[f+1]=color[1];faceColors[f+2]=color[2]}}}const shading=this.shadingNormals;for(let i=0;i<nu;i++){for(let j=0;j<nv;j++){const a=(i*stride+j)*3,b=((i+1)*stride+j)*3;const c=((i+1)*stride+j+1)*3,d=(i*stride+j+1)*3;let sx=0,sy=0,sz=0;for(const v of[a,b,c,d]){sx+=vertexNormals[v];sy+=vertexNormals[v+1];sz+=vertexNormals[v+2]}const length=Math.hypot(sx,sy,sz)||1;const f=(i*nv+j)*3;shading[f]=sx/length;shading[f+1]=sy/length;shading[f+2]=sz/length}}}emit(view,time){const{options,nu,nv,normals,shadingNormals,faceColors,screenX,screenY,screenZ,valid}=this;const alpha3=this.objectAlpha(view)*(options.opacity??1)*this.get("fillOpacity");if(alpha3<=.002)return;if(options.animate?this.computedFor!==time:this.computedFor===-Infinity){this.compute(options.animate?time:0);this.computedFor=time}const positions=this.positions;const stride=nv+1;const count=(nu+1)*(nv+1);for(let i=0;i<count;i++){const k=i*3;if(view.project(positions[k],positions[k+1],positions[k+2])){screenX[i]=view.px;screenY[i]=view.py;screenZ[i]=view.pz;valid[i]=1}else{valid[i]=0}}const solid4=this.ramp||this.checkerColors||options.colorAt?null:solidOf(this.get("fill"));const shaded=options.shaded??true;const opaque=alpha3>=.995;const reveal2=this.get("trimTo");const rows=Math.ceil(reveal2*nu);const{light,half,ambient,shine,brightness,dx,dy,dz}=view;const cull=options.cull??false;const meshColor=this.meshColor;const meshAlpha=(options.meshOpacity??.35)*alpha3;const meshWidth=(options.meshWidth??1)*view.scale;const seam=.55*view.scale;for(let i=0;i<rows;i++){for(let j=0;j<nv;j++){const a=i*stride+j,b=(i+1)*stride+j,c=(i+1)*stride+j+1,d=i*stride+j+1;if(!valid[a]||!valid[b]||!valid[c]||!valid[d])continue;const f=(i*nv+j)*3;const facing=normals[f]*dx+normals[f+1]*dy+normals[f+2]*dz;if(facing<0&&cull)continue;const flip=facing<0?-1:1;const nx=shadingNormals[f]*flip,ny=shadingNormals[f+1]*flip,nz=shadingNormals[f+2]*flip;let r,g,bl;if(solid4){r=solid4[0];g=solid4[1];bl=solid4[2]}else{r=faceColors[f];g=faceColors[f+1];bl=faceColors[f+2]}if(shaded){const wrap=.5+.5*(nx*light[0]+ny*light[1]+nz*light[2]);const diffuse=(ambient+(1-ambient)*wrap*wrap)*brightness;const spec=shine>0?shine*Math.pow(Math.max(0,nx*half[0]+ny*half[1]+nz*half[2]),42)*255:0;r=Math.min(255,r*diffuse+spec);g=Math.min(255,g*diffuse+spec);bl=Math.min(255,bl*diffuse+spec)}const depth=(screenZ[a]+screenZ[b]+screenZ[c]+screenZ[d])/4;const color=view.fogged(r,g,bl,depth);let ax=screenX[a],ay=screenY[a],bx=screenX[b],by=screenY[b];let cx=screenX[c],cy=screenY[c],ex=screenX[d],ey=screenY[d];if(opaque&&!meshColor){const mx=(ax+bx+cx+ex)/4,my=(ay+by+cy+ey)/4;const grow2=(x,y)=>seam/(Math.hypot(x-mx,y-my)||1);const ka=grow2(ax,ay),kb=grow2(bx,by),kc=grow2(cx,cy),ke=grow2(ex,ey);ax+=(ax-mx)*ka;ay+=(ay-my)*ka;bx+=(bx-mx)*kb;by+=(by-my)*kb;cx+=(cx-mx)*kc;cy+=(cy-my)*kc;ex+=(ex-mx)*ke;ey+=(ey-my)*ke}const ring2=polygonRing([ax,ay,bx,by,cx,cy,ex,ey]);view.push(meshColor?fillOp([ring2],color,alpha3,meshColor,meshAlpha,meshWidth):fillOp([ring2],color,alpha3,null,0,0),depth)}}}};function solidOf(paint){if(!paint)return[90,180,240,1];return Array.isArray(paint)?paint:solidColor(paint)}function parametricSurface(fn,u,v,options={}){return new Surface3D(fn,u,v,options)}function surface(f,options={}){const x=options.x??[-4,4],y=options.y??[-4,4];return new Surface3D((u,v,t)=>[u,v,f(u,v,t)],x,y,{colors:options.color||options.checker||options.colorAt?void 0:["blue","teal","yellow"],...options})}function sphere(radius=1,options={}){const[cx,cy,cz]=options.center??[0,0,0];return new Surface3D((u,v)=>[cx+radius*Math.sin(v)*Math.cos(u),cy+radius*Math.sin(v)*Math.sin(u),cz+radius*Math.cos(v)],[0,Math.PI*2],[0,Math.PI],{cull:true,resolution:[64,40],outwardFrom:[cx,cy,cz],...options})}var ON_TOP=1e6;var Curve3D=class extends Object3D{constructor(f,from,to2,style={}){super();this.style=style;const samples=style.samples??240;this.points=new Float64Array((samples+1)*3);for(let i=0;i<=samples;i++){const[x,y,z]=f(from+(to2-from)*i/samples);this.points[i*3]=x;this.points[i*3+1]=y;this.points[i*3+2]=z}this.base.stroke=toPaint(style.color??"yellow");this.base.strokeWidth=style.width??3;if(style.colors){const palette=style.colors.map(c=>solidColor(c));this.stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c])}else{this.stops=null}}style;points;stops;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const trim=this.get("trimTo");const count=this.points.length/3-1;const last=Math.floor(trim*count);if(last<1)return;const piece=Math.max(2,Math.ceil(count/72));const base=this.get("stroke")??toPaint("yellow");const width=this.get("strokeWidth")*view.scale;const bias=this.style.onTop?ON_TOP:this.style.bias??.12;const glow=(this.style.glow??0)*view.scale;for(let start=0;start<last;start+=piece){const end=Math.min(last,start+piece);const coords=[];let depth=0;let scale=0;let drawn=0;for(let i=start;i<=end;i++){if(!view.project(this.points[i*3],this.points[i*3+1],this.points[i*3+2]))continue;coords.push([view.px,view.py]);depth+=view.pz;scale+=view.ps;drawn++}if(drawn<2)continue;depth/=drawn;scale/=drawn;const rgb=this.stops?sampleStops(this.stops,(start+end)/2/count):solidOf(base);const color=view.fogged(rgb[0],rgb[1],rgb[2],depth);view.push(strokeOp([chain(coords)],color,alpha3,width*scale,glow,"round"),depth+bias)}}};function chain(points){const p=new Float64Array(2+(points.length-1)*6);p[0]=points[0][0];p[1]=points[0][1];let o=2;for(let i=1;i<points.length;i++){const a=points[i-1],b=points[i];p[o++]=a[0]+(b[0]-a[0])/3;p[o++]=a[1]+(b[1]-a[1])/3;p[o++]=a[0]+(b[0]-a[0])*2/3;p[o++]=a[1]+(b[1]-a[1])*2/3;p[o++]=b[0];p[o++]=b[1]}return{p,closed:false,straight:true}}function curve3d(f,from,to2,style={}){return new Curve3D(f,from,to2,style)}var Line3D=class extends Object3D{constructor(a,b,style={}){super();this.a=a;this.b=b;this.style=style;this.base.stroke=toPaint(style.color??"ink");this.base.strokeWidth=style.width??2.5}a;b;style;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const a=read3(this.a),b=read3(this.b);const pieces=this.style.pieces??14;const trim=this.get("trimTo");const base=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const bias=this.style.onTop?ON_TOP:this.style.bias??0;for(let i=0;i<pieces;i++){const t0=i/pieces*trim,t1=(i+1)/pieces*trim;if(!view.project(a[0]+(b[0]-a[0])*t0,a[1]+(b[1]-a[1])*t0,a[2]+(b[2]-a[2])*t0))continue;const x0=view.px,y0=view.py,z0=view.pz,s0=view.ps;if(!view.project(a[0]+(b[0]-a[0])*t1,a[1]+(b[1]-a[1])*t1,a[2]+(b[2]-a[2])*t1))continue;const depth=(z0+view.pz)/2;const color=view.fogged(base[0],base[1],base[2],depth);view.push(strokeOp([lineRing(x0,y0,view.px,view.py)],color,alpha3,width*(s0+view.ps)/2,0,"butt"),depth+bias)}}};function line3d(a,b,style={}){return new Line3D(a,b,style)}var Vector3D=class extends Line3D{from3;to3;tipSize;tipBias;constructor(from,to2,style={}){super(from,()=>{const a=read3(from),b=read3(to2);const length=Math.hypot(b[0]-a[0],b[1]-a[1],b[2]-a[2])||1;const pull=Math.min(.9,.22/length);return[b[0]-(b[0]-a[0])*pull,b[1]-(b[1]-a[1])*pull,b[2]-(b[2]-a[2])*pull]},{color:"yellow",width:4,...style});this.from3=from;this.to3=to2;this.tipSize=style.tip??24;this.tipBias=style.onTop?ON_TOP:style.bias??0}emit(view){super.emit(view);const trim=this.get("trimTo");if(trim<.98)return;const a=read3(this.from3),b=read3(this.to3);const alpha3=this.objectAlpha(view);if(!view.project(a[0],a[1],a[2]))return;const ax=view.px,ay=view.py;if(!view.project(b[0],b[1],b[2]))return;const bx=view.px,by=view.py,depth=view.pz,s=view.ps;const length=Math.hypot(bx-ax,by-ay)||1;const ux=(bx-ax)/length,uy=(by-ay)/length;const size=this.tipSize*view.scale*s;const half=size*.42;const rgb=solidOf(this.get("stroke"));const color=view.fogged(rgb[0],rgb[1],rgb[2],depth);const ring2=polygonRing([bx,by,bx-ux*size-uy*half,by-uy*size+ux*half,bx-ux*size+uy*half,by-uy*size-ux*half]);view.push(fillOp([ring2],color,alpha3,null,0,0),depth+.01+this.tipBias)}};function vector3d(from,to2,style={}){return new Vector3D(from,to2,style)}var Points3D=class extends Object3D{constructor(source,style={}){super();this.source=source;this.style=style;this.base.fill=toPaint(style.color??"yellow")}source;style;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("fillOpacity");if(alpha3<=.002)return;const points=typeof this.source==="function"?this.source():this.source;const radius=(this.style.radius??8)*view.scale;const trim=this.get("trimTo");const shown=Math.ceil(points.length*trim);const base=solidOf(this.get("fill"));const bias=this.style.onTop?ON_TOP:this.style.bias??0;for(let i=0;i<shown;i++){const point=points[i];if(!view.project(point[0],point[1],point[2]))continue;const rgb=this.style.colorAt?solidColor(this.style.colorAt(i,point)):base;const color=view.fogged(rgb[0],rgb[1],rgb[2],view.pz);const r=radius*view.ps;if(this.style.halo){view.push(fillOp([circleRing(view.px,view.py,r*(1+this.style.halo))],color,alpha3*.18,null,0,0),view.pz+bias-.001)}view.push(fillOp([circleRing(view.px,view.py,r)],color,alpha3,null,0,0),view.pz+bias)}}};function points3d(points,style={}){return new Points3D(points,style)}function point3d(point,style={}){return new Points3D(()=>[read3(point)],style)}var Trail3D=class extends Object3D{constructor(point,from,to2,style={}){super();this.point=point;this.from=from;this.to=to2;this.style=style;this.base.stroke=toPaint(style.color??"yellow");this.base.strokeWidth=style.width??3}point;from;to;style;cache=new Map;sample(index,rate){const cached=this.cache.get(index);if(cached)return cached;const saved=clock.now;clock.now=this.from+index/rate;const value=this.point();clock.now=saved;if(clock.mode==="render")this.cache.set(index,value);return value}emit(view,time){if(time<=this.from)return;const alpha3=this.objectAlpha(view)*(this.style.opacity??1);const rate=this.style.rate??30;const end=Math.min(time,this.to);const tail=this.style.tail;const start=tail!==void 0?Math.max(this.from,end-tail):this.from;const i0=Math.ceil((start-this.from)*rate),i1=Math.floor((end-this.from)*rate);if(i1-i0<1)return;const width=this.get("strokeWidth")*view.scale;const base=solidOf(this.get("stroke"));const fade2=this.style.fade??(tail!==void 0?0:1);const bias=this.style.onTop?ON_TOP:this.style.bias??0;const glow=(this.style.glow??0)*view.scale;const moved=[];let last=null;for(let k=i0;k<=i1;k++){const p=this.sample(k,rate);if(last&&Math.abs(p[0]-last[0])+Math.abs(p[1]-last[1])+Math.abs(p[2]-last[2])<1e-9)continue;moved.push(p);last=p}const span=moved.length-1;if(span<1)return;const piece=Math.max(1,Math.ceil(span/48));for(let i=0;i<span;i+=piece){const coords=[];let depth=0;let scale=0;for(let k=i;k<=Math.min(span,i+piece);k++){const p=moved[k];if(!view.project(p[0],p[1],p[2]))continue;coords.push([view.px,view.py]);depth+=view.pz;scale+=view.ps}if(coords.length<2)continue;depth/=coords.length;scale/=coords.length;const fraction=Math.min(1,(i+piece/2)/span);const light=fade2+(1-fade2)*Math.pow(fraction,1.6);const color=view.fogged(base[0],base[1],base[2],depth);view.push(strokeOp([chain(coords)],color,alpha3*light,width*scale,glow,"butt"),depth+bias)}}};function trail3d(point,from,to2,style={}){return new Trail3D(point,from,to2,style)}var Axes3D=class extends Object3D{constructor(options={}){super();this.options=options;this.ranges=[options.x??[-4,4],options.y??[-4,4],options.z??[-2.5,2.5]];this.step=options.step??1;this.base.stroke=toPaint(options.color??"dim");this.base.strokeWidth=options.width??2;const size=options.labelSize??34;const names=options.labels===false?null:Array.isArray(options.labels)?options.labels:["x","y","z"];this.tags=names?names.map(name=>tex(name,{size,display:false,color:"ink"})):[];if(options.numbers){const axes2=[[1,0,0],[0,1,0],[0,0,1]];this.ranges.forEach((range,axis)=>{for(const value of stepsBetween(range[0],range[1],this.step)){if(value===0)continue;const at=[axes2[axis][0]*value,axes2[axis][1]*value,axes2[axis][2]*value];this.numberNodes.push({node:text(String(value),{size:18,color:"dim"}),at})}})}}options;ranges;step;tags;numberNodes=[];emit(view){const alpha3=this.objectAlpha(view)*this.get("strokeOpacity");if(alpha3<=.002)return;const trim=this.get("trimTo");const rgb=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const unitVectors=[[1,0,0],[0,1,0],[0,0,1]];const bias=this.options.onTop?ON_TOP:this.options.bias??.4;this.ranges.forEach((range,axis)=>{const u=unitVectors[axis];const pieces=16;const low=range[0],high=low+(range[1]-low)*trim;for(let i=0;i<pieces;i++){const a=low+(high-low)*i/pieces,b=low+(high-low)*(i+1)/pieces;if(!view.project(u[0]*a,u[1]*a,u[2]*a))continue;const x0=view.px,y0=view.py,z0=view.pz;if(!view.project(u[0]*b,u[1]*b,u[2]*b))continue;const depth=(z0+view.pz)/2;view.push(strokeOp([lineRing(x0,y0,view.px,view.py)],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width,0,"butt"),depth+bias)}if(this.options.ticks??true){for(const value of stepsBetween(range[0],high,this.step)){if(value===0)continue;if(!view.project(u[0]*value,u[1]*value,u[2]*value))continue;const cx=view.px,cy=view.py,depth=view.pz;const size=5*view.ps*view.scale;const ring2=lineRing(cx-(axis===2?size:0),cy-(axis===2?0:size),cx+(axis===2?size:0),cy+(axis===2?0:size));view.push(strokeOp([ring2],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width*.8,0,"butt"),depth+bias)}}if(trim>.98&&view.project(u[0]*range[1],u[1]*range[1],u[2]*range[1])){const tipX=view.px,tipY=view.py,depth=view.pz;const back=range[1]-.2;if(view.project(u[0]*back,u[1]*back,u[2]*back)){const length=Math.hypot(tipX-view.px,tipY-view.py)||1;const ux=(tipX-view.px)/length,uy=(tipY-view.py)/length;const size=14*view.scale,half=size*.42;const ring2=polygonRing([tipX,tipY,tipX-ux*size-uy*half,tipY-uy*size+ux*half,tipX-ux*size+uy*half,tipY-uy*size-ux*half]);view.push(fillOp([ring2],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,null,0,0),depth+bias)}}})}labelsNow(view){const alpha3=this.get("opacity")*this.get("strokeOpacity");if(alpha3<=.002||this.get("trimTo")<.9)return[];const out=[];const unitVectors=[[1,0,0],[0,1,0],[0,0,1]];this.tags.forEach((tag,axis)=>{const u=unitVectors[axis];const reach=this.ranges[axis][1]+.35;const at=view.screen(u[0]*reach,u[1]*reach,u[2]*reach);if(at){tag.at(at);tag.set("opacity",alpha3);out.push(tag)}});for(const{node,at}of this.numberNodes){const screen=view.screen(at[0],at[1],at[2]);if(screen){node.at(screen[0]+12,screen[1]+14);node.set("opacity",alpha3);out.push(node)}}return out}};function axes3d(options={}){return new Axes3D(options)}var GridPlane3D=class extends Object3D{constructor(options={}){super();this.options=options;this.base.stroke=toPaint(options.color??"grid");this.base.strokeWidth=options.width??1.2}options;emit(view){const alpha3=this.objectAlpha(view)*(this.options.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const[x0,x1]=this.options.x??[-5,5];const[y0,y1]=this.options.y??[-5,5];const z=this.options.z??0;const step=this.options.step??1;const rgb=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const trim=this.get("trimTo");const run2=(ax,ay,bx,by)=>{const pieces=10;for(let i=0;i<pieces;i++){const t0=i/pieces*trim,t1=(i+1)/pieces*trim;if(!view.project(ax+(bx-ax)*t0,ay+(by-ay)*t0,z))continue;const px=view.px,py=view.py,pz=view.pz;if(!view.project(ax+(bx-ax)*t1,ay+(by-ay)*t1,z))continue;const depth=(pz+view.pz)/2;view.push(strokeOp([lineRing(px,py,view.px,view.py)],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width,0,"butt"),depth-.05)}};for(const x of stepsBetween(x0,x1,step))run2(x,y0,x,y1);for(const y of stepsBetween(y0,y1,step))run2(x0,y,x1,y)}};function gridPlane3d(options={}){return new GridPlane3D(options)}var Label3D=class extends Object3D{constructor(content,position2,options={}){super();this.position=position2;this.content=typeof content==="string"?options.math===false?text(content,{size:options.size??28,color:options.color??"ink"}):tex(content,{size:options.size??32,color:options.color??"ink",display:false}):content;this.offset=options.offset??[0,0]}position;content;offset;emit(){}labelsNow(view){const alpha3=this.get("opacity");if(alpha3<=.002)return[];const p=read3(this.position);const at=view.screen(p[0],p[1],p[2]);if(!at)return[];this.content.at(at[0]+this.offset[0],at[1]+this.offset[1]);this.content.set("opacity",alpha3*this.get("trimTo"));return[this.content]}};function label3d(content,position2,options={}){return new Label3D(content,position2,options)}var FORMATS=["mp4","webm","gif","png","svg"];var QUALITIES=["draft","standard","high","master"];function isLookName(value){return Object.hasOwn(LOOKS,value)}function requireValue(args,index,name){const value=args[index+1];if(value===void 0||value.startsWith("--"))throw new Error(`${name} requires a value`);return value}function positiveNumber(value,name){const parsed=Number(value);if(!Number.isFinite(parsed)||parsed<=0)throw new Error(`${name} must be a positive number, but received ${value}`);return parsed}function positiveInteger(value,name){const parsed=positiveNumber(value,name);if(!Number.isInteger(parsed))throw new Error(`${name} must be a whole number, but received ${value}`);return parsed}function parseLooks(value){const looks=value.split(",").map(item=>item.trim()).filter(Boolean);for(const look of looks){if(!isLookName(look))throw new Error(`Unknown look ${JSON.stringify(look)}. Run "vizmatic looks" to see all looks: ${Object.keys(LOOKS).join(", ")}.`)}if(looks.length===0)throw new Error("--look requires at least one look");return looks}function parseRange(value){const match=/^([\d.]*):([\d.]*)$/.exec(value);if(!match||!match[1]&&!match[2])throw new Error(`--range needs start:end in seconds, such as 3:8 or 3: or :8, but received ${value}`);const from=match[1]?Number(match[1]):void 0;const to2=match[2]?Number(match[2]):void 0;if(from!==void 0&&!Number.isFinite(from)||to2!==void 0&&!Number.isFinite(to2))throw new Error(`--range has an invalid number: ${value}`);if(from!==void 0&&to2!==void 0&&to2<=from)throw new Error(`--range must end after it starts, but received ${value}`);return{from,to:to2}}function parseFilmArgs(argv){const args={inputs:[],outDir:"dist/films",looks:[],quality:"standard",frames:[],poster:false,formats:[],json:false};for(let i=0;i<argv.length;i++){const arg=argv[i];switch(arg){case"--out":args.outDir=requireValue(argv,i++,arg);break;case"--look":args.looks=parseLooks(requireValue(argv,i++,arg));break;case"--fps":args.fps=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--width":args.width=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--motion-blur":args.motionBlur=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--shutter":args.shutter=positiveNumber(requireValue(argv,i++,arg),arg);break;case"--workers":args.workers=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--audio":args.audioPath=requireValue(argv,i++,arg);break;case"--ffmpeg":args.ffmpegPath=requireValue(argv,i++,arg);break;case"--background":{const value=requireValue(argv,i++,arg);args.background=value==="none"||value==="transparent"?null:value;break}case"--poster":args.poster=true;break;case"--json":args.json=true;break;case"--quality":{const value=requireValue(argv,i++,arg);if(!QUALITIES.includes(value))throw new Error(`--quality must be one of ${QUALITIES.join(", ")}, but received ${value}`);args.quality=value;break}case"--range":Object.assign(args,parseRange(requireValue(argv,i++,arg)));break;case"--frame":{for(const part of requireValue(argv,i++,arg).split(",")){const time=Number(part);if(!Number.isFinite(time)||time<0)throw new Error(`--frame needs times in seconds, but received ${part}`);args.frames.push(time)}break}case"--format":{for(const part of requireValue(argv,i++,arg).split(",")){const format=part.trim();if(!FORMATS.includes(format))throw new Error(`--format must list ${FORMATS.join(", ")}, but received ${part}`);if(!args.formats.includes(format))args.formats.push(format)}break}default:if(arg.startsWith("--"))throw new Error(`Unknown option for vizmatic film: ${arg}`);args.inputs.push(arg)}}if(args.inputs.length===0)throw new Error("vizmatic film needs a film file, such as: vizmatic film ./intro.ts --out dist/films");return args}function filmFromModule(mod){const top=mod;for(const candidate of[top?.default,top?.default?.default,top?.film]){if(isFilm(candidate))return candidate}return void 0}async function loadFilmDefinition(file,load){const candidate=filmFromModule(await load(file));if(candidate)return candidate;const shown=relative(process.cwd(),file);throw new Error(`${shown} must export a film as its default export: export default film({ title: 'Intro' }, (s) => { ... })`)}function formatClock(seconds){const whole=Math.max(0,Math.round(seconds));return`${Math.floor(whole/60)}:${String(whole%60).padStart(2,"0")}`}function formatBytes(bytes){if(bytes<1024)return`${bytes} B`;if(bytes<1024**2)return`${(bytes/1024).toFixed(0)} KB`;return`${(bytes/1024**2).toFixed(1)} MB`}function progressReporter(label,quiet){const started=performance.now();const live=process.stderr.isTTY===true;let lastPrint=0;let lastDecile=-1;return{update(frame){if(quiet)return;const now=performance.now();const completed=frame.index+1;const finished=completed===frame.count;if(live&&!finished&&now-lastPrint<80)return;lastPrint=now;const elapsed=(now-started)/1e3;const fps=completed/Math.max(elapsed,.001);const remaining=(frame.count-completed)/Math.max(fps,.001);const percent=Math.floor(completed/frame.count*100);const line2=`${label} frame ${completed}/${frame.count} ${percent}% ${fps.toFixed(1)} fps ETA ${formatClock(remaining)}`;if(live){process.stderr.write(`\r\x1B[2K${line2}`)}else{const decile=Math.floor(percent/10);if(decile!==lastDecile){lastDecile=decile;process.stderr.write(`${line2}
354
+ `;var FILM_TEMPLATES=[{name:"explainer",description:"A graph, a moving value, and an equation, in three chapters.",source:explainer},{name:"equation",description:"A step-by-step derivation that morphs glyph by glyph.",source:equation},{name:"architecture",description:"Services with live detail, and packets traveling along the edges.",source:architecture},{name:"chart",description:"Bars that grow in order, with the takeaway as the title.",source:chart},{name:"deck",description:"A stepped presentation with one chapter per slide.",source:deck}];var SHAPES="Shapes";var TEXT="Text and math";var MATH="Math objects";var REVEAL="Reveal and dismiss";var CHANGE="Change";var TIMING="Timing";var EMPHASIS="Emphasis";var CHARTS="Charts";var SYSTEMS="Systems and computer science";var THREE="3D";var BRIDGE="Bring in existing work";var FILM_OBJECTS=[{name:"text",group:TEXT,usage:"text('Hello', { font: 'serif', size: 72, color: 'ink' }): vector glyphs you can write and morph"},{name:"tex",group:TEXT,usage:"tex('e^{i\\\\pi} + 1 = 0', { size: 64 }): typeset math. eq.part('x^2') selects a term"},{name:"decimal",group:TEXT,usage:"decimal(() => v.value, { digits: 2, prefix: 'm = ' }): a live number readout"},{name:"dot",group:SHAPES,usage:"dot(9, 'yellow').at(x, y): a filled point"},{name:"line",group:SHAPES,usage:"line([x0, y0], [x1, y1], { stroke: 'blue', width: 3 })"},{name:"arrow",group:SHAPES,usage:"arrow(from, to, { stroke: 'ink', bend: 40, pad: 8 }): a shaft and a clean tip"},{name:"circle",group:SHAPES,usage:"circle(60, { stroke: 'teal', fill: 'surface' })"},{name:"ellipse",group:SHAPES,usage:"ellipse(rx, ry, style)"},{name:"arc",group:SHAPES,usage:"arc(radius, fromAngle, toAngle, style)"},{name:"rect",group:SHAPES,usage:"rect(240, 96, { radius: 10, stroke: 'blue' })"},{name:"polygon",group:SHAPES,usage:"polygon([[x, y], ...], style)"},{name:"regularPolygon",group:SHAPES,usage:"regularPolygon(6, radius, style)"},{name:"polyline",group:SHAPES,usage:"polyline(points, style): straight segments"},{name:"curve",group:SHAPES,usage:"curve(points, style): a smooth spline through points"},{name:"parametric",group:SHAPES,usage:"parametric((t) => [x, y], t0, t1, style)"},{name:"svgPath",group:SHAPES,usage:"svgPath('M0 0C...', style): any SVG path data"},{name:"brace",group:SHAPES,usage:"brace(from, to, { depth: 24 }): a curly brace beside a span"},{name:"group",group:SHAPES,usage:'group(a, b, c).arrange("right", 24): move and lay out together'},{name:"dynamic",group:SHAPES,usage:"dynamic(() => line(p(v.value), q)): rebuilt every frame from timeline values"},{name:"axes",group:MATH,usage:"axes({ x: [-1, 4], y: [0, 9], grid: true }). plot(f), world(x, y), dotAt(x, y), guides(x, y)"},{name:"plane",group:MATH,usage:"plane({ unit: 120 }): a grid that bends under applyMatrix and warp"},{name:"numberLine",group:MATH,usage:"numberLine({ min: -4, max: 4 }): ticks and labels on one axis"},{name:"complexPlane",group:MATH,usage:"complexPlane({ unit: 120 }): a plane for applyComplex"},{name:"applyComplex",group:MATH,usage:"applyComplex(plane, complex.square): bend a plane through a complex function"},{name:"vectorField",group:MATH,usage:"vectorField((x, y) => [u, v]): arrows that show a field"},{name:"streamLines",group:MATH,usage:"streamLines((x, y) => [u, v]): flowing lines through a field"},{name:"riemann",group:MATH,usage:"riemann(axes, f, { n: 12 }): the rectangles of a Riemann sum"},{name:"areaUnder",group:MATH,usage:"areaUnder(axes, f, { from: 0, to: 2 }): the filled area under a curve"},{name:"tangentLine",group:MATH,usage:"tangentLine(axes, f, () => x.value): a tangent that follows a value"},{name:"secantLine",group:MATH,usage:"secantLine(axes, f, a, b): a secant between two values"},{name:"dashedGuides",group:MATH,usage:"dashedGuides(axes, x, y): dashed lines down to both axes"},{name:"angleMark",group:MATH,usage:"angleMark(vertex, from, to): an arc between two rays"},{name:"rightAngle",group:MATH,usage:"rightAngle(vertex, a, b): a square corner mark"},{name:"matrix",group:MATH,usage:"matrix([[1, 2], [3, 4]]): a bracketed matrix of numbers or TeX"},{name:"braceLabel",group:MATH,usage:"braceLabel(node, 'x^2'): a curly brace beside a node, with a label"},{name:"surroundingBox",group:MATH,usage:"surroundingBox(node): a rounded box around a node"},{name:"labeledDot",group:MATH,usage:"labeledDot('A'): a dot with a label"},{name:"traced",group:MATH,usage:"traced(() => point, t0, t1): the path a moving point leaves"},{name:"fourier",group:MATH,usage:"fourier(points, { terms: 80 }): Fourier terms for a closed curve"},{name:"epicycles",group:MATH,usage:"epicycles(terms, { u }): rotating circles that draw a curve"},{name:"barChart",group:CHARTS,usage:"barChart([{ label: 'A', value: 3 }]): animated bars"},{name:"histogram",group:CHARTS,usage:"histogram(samples, { bins: 20 })"},{name:"scatter",group:CHARTS,usage:"scatter([{ x, y }]): a point cloud on axes"},{name:"lineChart",group:CHARTS,usage:"lineChart([{ name: 'p95', values: [...] }]): series with direct labels"},{name:"pie",group:CHARTS,usage:"pie([{ label: 'A', value: 3 }])"},{name:"donut",group:CHARTS,usage:"donut([{ label: 'A', value: 3 }])"},{name:"heatmap",group:CHARTS,usage:"heatmap(rows): a grid of colored cells"},{name:"sparkline",group:CHARTS,usage:"sparkline(values): a tiny inline trend"},{name:"infoBox",group:SYSTEMS,usage:"infoBox({ title, rows }): a dense box with a title, fields, and live stats"},{name:"connector",group:SYSTEMS,usage:"connector(a, b, { label }): a routed edge between two nodes"},{name:"legend",group:SYSTEMS,usage:"legend([{ label: 'read', color: 'blue' }])"},{name:"callout",group:SYSTEMS,usage:"callout(node, 'Why this matters'): a note with a leader line"},{name:"graph",group:SYSTEMS,usage:"graph(nodes, edges): nodes and edges with automatic layout"},{name:"tree",group:SYSTEMS,usage:"tree(root): a layered tree"},{name:"arrayCells",group:SYSTEMS,usage:"arrayCells([3, 1, 4]): boxes for arrays and buffers"},{name:"codeBlock",group:SYSTEMS,usage:"codeBlock(source, { language }): highlighted code as glyphs"},{name:"morphCode",group:SYSTEMS,usage:"morphCode(before, after): edit code by moving tokens"},{name:"neuralNet",group:SYSTEMS,usage:"neuralNet([3, 4, 2]): layers with edges"},{name:"tokens",group:SYSTEMS,usage:"tokens(['The', 'cat']): a row of token chips"},{name:"attentionMatrix",group:SYSTEMS,usage:"attentionMatrix(rows, columns, weights): a labeled heatmap"},{name:"scene3d",group:THREE,usage:"scene3d({ phi, theta }): a 3D view you can orbit. Add 3D objects to it"},{name:"axes3d",group:THREE,usage:"axes3d({ x, y, z }): three axes"},{name:"surface",group:THREE,usage:"surface((x, y, t) => z, { x, y }): a shaded height field"},{name:"parametricSurface",group:THREE,usage:"parametricSurface((u, v) => [x, y, z], [0, 1], [0, 1])"},{name:"sphere",group:THREE,usage:"sphere(radius): a shaded sphere"},{name:"curve3d",group:THREE,usage:"curve3d((t) => [x, y, z], t0, t1)"},{name:"line3d",group:THREE,usage:"line3d(a, b)"},{name:"vector3d",group:THREE,usage:"vector3d(from, to): an arrow in space"},{name:"points3d",group:THREE,usage:"points3d(points): many points, or a function that returns them"},{name:"point3d",group:THREE,usage:"point3d(() => [x, y, z]): one point that can move"},{name:"trail3d",group:THREE,usage:"trail3d(() => point, t0, t1, { tail }): a trace behind a moving point"},{name:"gridPlane3d",group:THREE,usage:"gridPlane3d(): a floor grid"},{name:"label3d",group:THREE,usage:"label3d('x', [1, 0, 0]): a screen-facing label at a 3D point"},{name:"fromSvg",group:BRIDGE,usage:"fromSvg(svgText): any SVG as animatable shapes"},{name:"image",group:BRIDGE,usage:"image(dataUrl, { width: 400 }): a logo or a photo, centered, that fades and moves like any node"},{name:"narration",group:TIMING,usage:"narration(s, timing).scene('intro').on('a spoken phrase', () => s.play(...)): place changes on measured words"},{name:"fromComponent",group:BRIDGE,usage:"await fromComponent(<Flow ... />, { width, height }): any TSX figure as animatable shapes. Import from 'vizmatic/stage/export'. Node only"},{name:"write",group:REVEAL,usage:"write(node): handwrite text and equations glyph by glyph"},{name:"draw",group:REVEAL,usage:"draw(node): trace strokes in order, then fill"},{name:"erase",group:REVEAL,usage:"erase(node): the reverse of draw"},{name:"fadeIn",group:REVEAL,usage:"fadeIn(node, { shift: [0, 16], scale: 0.9, lag: 0.1 })"},{name:"fadeOut",group:REVEAL,usage:"fadeOut(nodes, { shift: [0, -16] })"},{name:"grow",group:REVEAL,usage:"grow(node, { from: [x, y] }): scale up from a point"},{name:"typewriter",group:REVEAL,usage:"typewriter(text): reveal characters in order"},{name:"wipe",group:REVEAL,usage:"wipe(node): reveal with a moving edge"},{name:"appear",group:REVEAL,usage:"appear(node): show at once"},{name:"vanish",group:REVEAL,usage:"vanish(node): hide at once"},{name:"to",group:CHANGE,usage:"to(node, (n) => n.moveTo([x, y]).color('yellow').scale(2)): animate any change"},{name:"morph",group:CHANGE,usage:"morph(a, b): turn any shape into any other. b stays on stage"},{name:"morphMatching",group:CHANGE,usage:"morphMatching(eqA, eqB): shared glyphs travel, the rest fade"},{name:"moveTo",group:CHANGE,usage:"moveTo(node, [x, y])"},{name:"shift",group:CHANGE,usage:"shift(node, dx, dy)"},{name:"scaleBy",group:CHANGE,usage:"scaleBy(node, 1.5, { about: [x, y] })"},{name:"rotate",group:CHANGE,usage:"rotate(node, Math.PI / 2, { about: [x, y] })"},{name:"recolor",group:CHANGE,usage:"recolor(node, 'teal')"},{name:"fade",group:CHANGE,usage:"fade(node, 0.3): change opacity and stay visible"},{name:"along",group:CHANGE,usage:"along(dot, pathOrNode, { orient: true }): follow a path"},{name:"warp",group:CHANGE,usage:"warp(grid, (x, y) => [u, v]): bend shapes through a function"},{name:"applyMatrix",group:CHANGE,usage:"applyMatrix(grid, [[1, 1], [0, 1]]): a linear map, with y up"},{name:"countUp",group:CHANGE,usage:"countUp(counter, 100): move a counter or value to a number"},{name:"counter",group:TEXT,usage:"counter(0, { digits: 1 }): a number you can animate with countUp"},{name:"spin",group:CHANGE,usage:"spin(node, rate): keep turning for the length of the animation"},{name:"swap",group:CHANGE,usage:"swap(a, b): trade places along arcs"},{name:"par",group:TIMING,usage:"par(a, b): together, inside a sequence"},{name:"seq",group:TIMING,usage:"seq(a, b): one after another"},{name:"lagged",group:TIMING,usage:"lagged([a, b, c], { lag: 0.2 }): overlapping starts"},{name:"delay",group:TIMING,usage:"delay(anim, 0.5)"},{name:"retime",group:TIMING,usage:"retime(anim, { duration: 2, ease: smoother })"},{name:"call",group:TIMING,usage:"call(() => ...): run code at a moment on the timeline"},{name:"indicate",group:EMPHASIS,usage:"indicate(node, { color: 'yellow', scale: 1.14 }): swell and return"},{name:"circumscribe",group:EMPHASIS,usage:"circumscribe(node): trace a line around it"},{name:"flash",group:EMPHASIS,usage:"flash([x, y]): a radial burst"},{name:"ripple",group:EMPHASIS,usage:"ripple([x, y]): an expanding ring"},{name:"pulse",group:EMPHASIS,usage:"pulse(line): a lit segment travels along a line"},{name:"shake",group:EMPHASIS,usage:"shake(node): a small oscillation"},{name:"highlightSweep",group:EMPHASIS,usage:"highlightSweep(node): a marker stroke across text"}];var stage_exports={};__export(stage_exports,{ArrayCells:()=>ArrayCells,Axes:()=>Axes,Axes3D:()=>Axes3D,BarChart:()=>BarChart2,Callout:()=>Callout,CodeBlock:()=>CodeBlock2,CompiledFilm:()=>CompiledFilm,ComplexPlane:()=>ComplexPlane,Connector:()=>Connector2,Counter:()=>Counter,Curve3D:()=>Curve3D,EMPTY_BOUNDS:()=>EMPTY_BOUNDS,Epicycles:()=>Epicycles,Graph:()=>Graph,GraphEdge:()=>GraphEdge,GraphNode:()=>GraphNode,GridPlane3D:()=>GridPlane3D,Heatmap:()=>Heatmap2,Histogram:()=>Histogram,IDENTITY:()=>IDENTITY,ImageAssetError:()=>ImageAssetError,InfoBox:()=>InfoBox,LOOKS:()=>LOOKS,Label3D:()=>Label3D,LabeledDot:()=>LabeledDot,Line3D:()=>Line3D,LineChart:()=>LineChart2,MatrixNode:()=>MatrixNode,Narration:()=>Narration,NeuralNet:()=>NeuralNet,Node:()=>Node,NumberLine:()=>NumberLine2,NumberPlane:()=>NumberPlane,Object3D:()=>Object3D,PieChart:()=>PieChart2,Points3D:()=>Points3D,Scatter:()=>Scatter,Scene3D:()=>Scene3D,SceneClock:()=>SceneClock,Stage:()=>Stage,StreamLines:()=>StreamLines,Surface3D:()=>Surface3D,Suspend:()=>Suspend,SvgNode:()=>SvgNode,TexNode:()=>TexNode,TextNode:()=>TextNode,TokenRow:()=>TokenRow,Trail3D:()=>Trail3D,TreeGraph:()=>TreeGraph,Value:()=>Value,Vector3D:()=>Vector3D,VectorField:()=>VectorField,View3D:()=>View3D,along:()=>along2,angleMark:()=>angleMark,appear:()=>appear,apply:()=>apply,applyComplex:()=>applyComplex,applyMatrix:()=>applyMatrix,arc:()=>arc,arcPath:()=>arcPath,areaUnder:()=>areaUnder,arrayCells:()=>arrayCells,arrow:()=>arrow,attentionMatrix:()=>attentionMatrix,axes:()=>axes,axes3d:()=>axes3d,barChart:()=>barChart,blueprint:()=>blueprint,bounce:()=>bounce,brace:()=>brace,braceLabel:()=>braceLabel,buildOps:()=>buildOps,call:()=>call,callout:()=>callout,captionLines:()=>captionLines,chalk:()=>chalk,checkFilm:()=>checkFilm,circle:()=>circle,circlePath:()=>circlePath,circumscribe:()=>circumscribe,codeBlock:()=>codeBlock,colorAlong:()=>along,compileFilm:()=>compileFilm,complex:()=>complex,complexPlane:()=>complexPlane,compose:()=>compose,concat:()=>concat,connector:()=>connector,countUp:()=>countUp,counter:()=>counter,css:()=>css,cubicBezier:()=>cubicBezier,curve:()=>curve,curve3d:()=>curve3d,curveThrough:()=>curveThrough,dashedGuides:()=>dashedGuides,decimal:()=>decimal,delay:()=>delay,donut:()=>donut,dot:()=>dot,draw:()=>draw,during:()=>during,dynamic:()=>dynamic,easeInCubic:()=>easeInCubic,easeInExpo:()=>easeInExpo,easeInOutCubic:()=>easeInOutCubic,easeInOutQuint:()=>easeInOutQuint,easeInQuad:()=>easeInQuad,easeOutCubic:()=>easeOutCubic,easeOutExpo:()=>easeOutExpo,easeOutQuad:()=>easeOutQuad,easeOutQuint:()=>easeOutQuint,ellipse:()=>ellipse,epicycles:()=>epicycles,erase:()=>erase,fade:()=>fade,fadeIn:()=>fadeIn,fadeOut:()=>fadeOut,film:()=>film,flash:()=>flash,fontFor:()=>fontFor,fourier:()=>fourier,fourierPoint:()=>fourierPoint,frameInkBounds:()=>frameInkBounds,frameToSvg:()=>frameToSvg,fromSvg:()=>fromSvg,glyphPath:()=>glyphPath,graph:()=>graph,gridPlane3d:()=>gridPlane3d,group:()=>group,grow:()=>grow,heatmap:()=>heatmap,highlightSweep:()=>highlightSweep,histogram:()=>histogram,image:()=>image,indicate:()=>indicate,infoBox:()=>infoBox,invert:()=>invert,isFilm:()=>isFilm,isSuspend:()=>isSuspend,label3d:()=>label3d,labeledDot:()=>labeledDot,lagged:()=>lagged,legend:()=>legend,line:()=>line,line3d:()=>line3d,lineChart:()=>lineChart,linePath:()=>linePath,linear:()=>linear,linearGradient:()=>linearGradient,lingering:()=>lingering,matScale:()=>matScale,matrix:()=>matrix,midnight:()=>midnight,mixColor:()=>mixColor,morph:()=>morph,morphCode:()=>morphCode,morphMatching:()=>morphMatching,moveTo:()=>moveTo,mul:()=>mul,narration:()=>narration,neon:()=>neon,neuralNet:()=>neuralNet,notQuiteThere:()=>notQuiteThere,numberLine:()=>numberLine,overshoot:()=>overshoot,paintFrame:()=>paintFrame,paper:()=>paper,par:()=>par,parametric:()=>parametric,parametricPath:()=>parametricPath,parametricSurface:()=>parametricSurface,parseColor:()=>parseColor,parseFont:()=>parseFont,parseSvgPath:()=>parseSvgPath,pathBounds:()=>pathBounds,pathLength:()=>pathLength,pathToD:()=>pathToD,pie:()=>pie,plane:()=>plane,point3d:()=>point3d,pointAt:()=>pointAt,points3d:()=>points3d,polyPath:()=>polyPath,polygon:()=>polygon,polyline:()=>polyline,pulse:()=>pulse,radialGradient:()=>radialGradient,ramp:()=>ramp,recolor:()=>recolor,rect:()=>rect,rectPath:()=>rectPath,regularPolygon:()=>regularPolygon,resolveImageAsset:()=>resolveImageAsset,resolveLook:()=>resolveLook,retime:()=>retime,reverseRing:()=>reverseRing,riemann:()=>riemann,rightAngle:()=>rightAngle,ring:()=>ring,ringCenter:()=>ringCenter,ringLength:()=>ringLength,ringThrough:()=>ringThrough,ripple:()=>ripple,rotate:()=>rotate,runningStart:()=>runningStart,rushFrom:()=>rushFrom,rushInto:()=>rushInto,samplePath:()=>samplePath,scaleBy:()=>scaleBy,scatter:()=>scatter,scene3d:()=>scene3d,secantLine:()=>secantLine,segmentCount:()=>segmentCount,seq:()=>seq,setAssetBase:()=>setAssetBase,shake:()=>shake,shape:()=>shape,shift:()=>shift,signedArea:()=>signedArea,slowInto:()=>slowInto,smooth:()=>smooth2,smoothBy:()=>smoothBy,smoothPath:()=>smoothPath,smoother:()=>smoother,sparkline:()=>sparkline,sphere:()=>sphere,spin:()=>spin,spring:()=>spring,streamLines:()=>streamLines,subdivideEach:()=>subdivideEach,surface:()=>surface,surroundingBox:()=>surroundingBox,svgPath:()=>svgPath,swap:()=>swap,tangentAt:()=>tangentAt,tangentLine:()=>tangentLine,tex:()=>tex,text:()=>text,thereAndBack:()=>thereAndBack,thereAndBackWithPause:()=>thereAndBackWithPause,to:()=>to,toPaint:()=>toPaint,tokenize:()=>tokenize,tokens:()=>tokens3,traced:()=>traced,trail3d:()=>trail3d,transformPath:()=>transformPath,tree:()=>tree,trimPath:()=>trimPath,trimRing:()=>trimRing,typewriter:()=>typewriter,unionBounds:()=>unionBounds,vanish:()=>vanish,vector3d:()=>vector3d,vectorField:()=>vectorField,warp:()=>warp,warpPath:()=>warpPath,wiggle:()=>wiggle,wipe:()=>wipe,write:()=>write});var TexNode=class extends Node{glyphs=[];source="";part(fragment){const keys=texKeys(fragment);const own=this.glyphs.map(glyph=>glyph.data["key"]);for(let start=0;start+keys.length<=own.length;start++){if(keys.every((key,i)=>key===own[start+i]))return this.glyphs.slice(start,start+keys.length)}return[]}parts(fragment){const keys=texKeys(fragment);const own=this.glyphs.map(glyph=>glyph.data["key"]);const out=[];for(let start=0;start+keys.length<=own.length;start++){if(keys.every((key,i)=>key===own[start+i])){out.push(this.glyphs.slice(start,start+keys.length));start+=keys.length-1}}return out}};var engine=null;var loading=null;var layouts=new Map;function requireEngine(){if(engine)return engine;loading??=import("./math-QVCETQDQ.js").then(module=>{engine=(tex2,display)=>module.renderMathSvg(tex2,{fontSize:1e3,display,color:"#000000"}).svg});throw new Suspend(loading)}function layoutTex(tex2,display){const cacheKey=`${display?"D":"I"}${tex2}`;const cached=layouts.get(cacheKey);if(cached)return cached;const svg=requireEngine()(tex2,display);const out=[];const stack=[];let current=[1,0,0,1,0,0];const viewBox=/viewBox="([^"]+)"/.exec(svg)?.[1]?.trim().split(/[ ,]+/).map(Number)??[0,0,1e3,1e3];const widthPx=Number(/\swidth="([\d.]+)px"/.exec(svg)?.[1]??1e3);const unit=widthPx/viewBox[2]/1e3;const tag=/<(\/?)([a-zA-Z]+)((?:\s+[-\w:]+="[^"]*")*)\s*(\/?)>/g;let svgDepth=0;let clip=null;const clips=[];for(let match=tag.exec(svg);match;match=tag.exec(svg)){const[,closing,name,attributes="",selfClosing]=match;const attr=key=>new RegExp(`\\s${key}="([^"]*)"`).exec(attributes)?.[1];if(name==="svg"){if(closing){svgDepth--;if(svgDepth>=1){current=stack.pop()??current;clip=clips.pop()??null}continue}svgDepth++;if(svgDepth>1){const box=(attr("viewBox")??"0 0 1 1").trim().split(/[ ,]+/).map(Number);const w=Number(attr("width")??box[2]),h=Number(attr("height")??box[3]);const mapping=mul([w/(box[2]||1),0,0,h/(box[3]||1),Number(attr("x")??0),Number(attr("y")??0)],[1,0,0,1,-box[0],-box[1]]);stack.push(current);clips.push(clip);current=mul(current,mapping);clip=[box[0],box[1],box[0]+box[2],box[1]+box[3]]}continue}if(closing){if(name==="g")current=stack.pop()??current;continue}const transform=attr("transform");const local=transform?parseTransform2(transform):[1,0,0,1,0,0];if(name==="g"){if(!selfClosing){stack.push(current);current=mul(current,local)}continue}if(name==="path"){const d=attr("d");if(!d)continue;const code=attr("data-c");const placed=transformPath(parseSvgPath(d),local);out.push({path:transformPath(clip?clampPath(placed,clip):placed,current),key:code?String.fromCodePoint(parseInt(code,16)):"?"})}else if(name==="rect"){const x=Number(attr("x")??0),y=Number(attr("y")??0);const w=Number(attr("width")??0),h=Number(attr("height")??0);if(w>0&&h>0)out.push({path:transformPath(rectPath(x,y,w,h),mul(current,local)),key:"rule"})}}const scaled=out.map(glyph=>({key:glyph.key,path:transformPath(glyph.path,[unit,0,0,unit,0,0])}));layouts.set(cacheKey,scaled);return scaled}function clampPath(path,box){return path.map(r=>{const out=new Float64Array(r.p.length);for(let i=0;i<out.length;i+=2){out[i]=Math.max(box[0],Math.min(box[2],r.p[i]));out[i+1]=Math.max(box[1],Math.min(box[3],r.p[i+1]))}return{p:out,closed:r.closed}})}function parseTransform2(value){let m=[1,0,0,1,0,0];for(const match of value.matchAll(/(translate|scale|matrix)\(([^)]*)\)/g)){const args=match[2].trim().split(/[ ,]+/).map(Number);if(match[1]==="translate")m=mul(m,[1,0,0,1,args[0]??0,args[1]??0]);else if(match[1]==="scale")m=mul(m,[args[0]??1,0,0,args[1]??args[0]??1,0,0]);else if(args.length===6)m=mul(m,args)}return m}function texKeys(fragment){return layoutTex(fragment,false).map(glyph=>glyph.key)}function tex(source,options={}){const size=options.size??56;const display=options.display??true;const glyphs=layoutTex(source,display);const paint=toPaint(options.color??"ink");const node=new TexNode;node.source=source;let minX=Infinity,minY=Infinity,maxX=-Infinity,maxY=-Infinity;for(const glyph of glyphs){const path=transformPath(glyph.path,[size,0,0,size,0,0]);const b=pathBounds(path);if(!b)continue;minX=Math.min(minX,b.x);minY=Math.min(minY,b.y);maxX=Math.max(maxX,b.x+b.width);maxY=Math.max(maxY,b.y+b.height);const cx=b.x+b.width/2,cy=b.y+b.height/2;const leaf=new Node(transformPath(path,[1,0,0,1,-cx,-cy])).at(cx,cy);leaf.base.fill=paint;leaf.base.trimEach=true;leaf.data["key"]=glyph.key;node.glyphs.push(leaf);node.children.push(leaf);leaf.parent=node}if(minX!==Infinity){node.base.px=(minX+maxX)/2;node.base.py=(minY+maxY)/2}return node}function styled(node,style,defaults){const fill=style.fill!==void 0?style.fill:defaults.fill;const stroke=style.stroke!==void 0?style.stroke:defaults.stroke;if(fill)node.fill(fill);if(stroke)node.stroke(stroke,style.width??defaults.width??3);if(style.opacity!==void 0)node.opacity(style.opacity);if(style.glow)node.glow(style.glow);if(style.dash)node.dash(style.dash);if(style.z!==void 0)node.zIndex(style.z);return node}function shape(path,style={}){return styled(new Node(path),style,{stroke:"ink"})}function svgPath(d,style={}){return shape(parseSvgPath(d),style)}function line(a,b,style={}){return styled(new Node(linePath(a,b)),style,{stroke:"ink"})}function polyline(points,style={}){return styled(new Node(polyPath(points,style.closed)),style,{stroke:"ink"})}function curve(points,style={}){return styled(new Node(style.closed?smoothPath(points,true):curveThrough(points)),style,{stroke:"ink"})}function parametric(f,from,to2,style={}){return styled(new Node(parametricPath(f,from,to2,style.samples??96)),style,{stroke:"ink"})}function circle(radius,style={}){return styled(new Node(circlePath(0,0,radius)),style,{stroke:"ink"})}function ellipse(rx,ry,style={}){return styled(new Node(arcPath(0,0,rx,ry,0,Math.PI*2)),style,{stroke:"ink"})}function arc(radius,from,to2,style={}){return styled(new Node(arcPath(0,0,radius,radius,from,to2)),style,{stroke:"ink"})}function rect(width,height,style={}){return styled(new Node(rectPath(-width/2,-height/2,width,height,style.radius??0)),style,{stroke:"ink"})}function polygon(points,style={}){return styled(new Node(polyPath(points,true)),style,{stroke:"ink"})}function regularPolygon(sides,radius,style={}){const points=[];for(let i=0;i<sides;i++){const angle=-Math.PI/2+i/sides*Math.PI*2;points.push([Math.cos(angle)*radius,Math.sin(angle)*radius])}return polygon(points,style)}function intrinsicSize(src){const match=/^data:image\/(png|gif|jpeg|jpg);base64,/.exec(src);if(!match||typeof atob!=="function")return null;let head;try{head=atob(src.slice(match[0].length,match[0].length+(match[1]==="jpeg"||match[1]==="jpg"?87384:44)))}catch{return null}const byte=i=>head.charCodeAt(i);if(match[1]==="png")return head.length>=24?[byte(16)*16777216+byte(17)*65536+byte(18)*256+byte(19),byte(20)*16777216+byte(21)*65536+byte(22)*256+byte(23)]:null;if(match[1]==="gif")return head.length>=10?[byte(6)+byte(7)*256,byte(8)+byte(9)*256]:null;for(let i=2;i+9<head.length;){if(byte(i)!==255)return null;const marker=byte(i+1);if(marker>=192&&marker<=207&&marker!==196&&marker!==200&&marker!==204)return[byte(i+7)*256+byte(i+8),byte(i+5)*256+byte(i+6)];i+=2+byte(i+2)*256+byte(i+3)}return null}function image(src,options={}){if(typeof src!=="string"){const node=imageFromAsset(src,options);if(options.opacity!==void 0)node.opacity(options.opacity);return node}if(options.crop!==void 0||options.fit!==void 0)throw new Error("Await resolveImageAsset before using image fit or crop options.");const natural=intrinsicSize(src);let width=options.width,height=options.height;if(width===void 0&&height===void 0){if(!natural)throw new Error("image() needs a width or a height when the picture is not a PNG, GIF, or JPEG data URL.");[width,height]=natural}else if(width===void 0||height===void 0){if(!natural)throw new Error("image() needs both width and height when the picture is not a PNG, GIF, or JPEG data URL.");if(width===void 0)width=height*natural[0]/natural[1];else height=width*natural[1]/natural[0]}if(!(width>0)||!(height>0))throw new Error("image() needs a positive width and height.");const picture=new Node().at(-width/2,-height/2);picture.base.image={src,width,height};const out=new Node;out.add(picture);if(options.opacity!==void 0)out.opacity(options.opacity);return out}function dot(radius=9,color="ink",style={}){return styled(new Node(circlePath(0,0,radius)),style,{fill:color})}function arrow(from,to2,style={}){const color=style.stroke??"ink";const width=style.width??3;const tip=style.tip??Math.max(13,width*4.2);const ratio=style.tipRatio??.72;const pad2=style.pad??0;let dx=to2[0]-from[0],dy=to2[1]-from[1];const length=Math.hypot(dx,dy)||1;dx/=length;dy/=length;const start=[from[0]+dx*pad2,from[1]+dy*pad2];const end=[to2[0]-dx*pad2,to2[1]-dy*pad2];const span=Math.max(0,length-pad2*2);const usableTip=Math.min(tip,span*.45);const group2=new Node;const bend=style.bend??0;const normal=[-dy,dx];const control=[(start[0]+end[0])/2+normal[0]*bend,(start[1]+end[1])/2+normal[1]*bend];let tx=end[0]-control[0],ty=end[1]-control[1];const tl=Math.hypot(tx,ty)||1;tx/=tl;ty/=tl;const baseX=end[0]-tx*usableTip,baseY=end[1]-ty*usableTip;const shaftPath=bend===0?linePath(style.both?[start[0]+dx*usableTip,start[1]+dy*usableTip]:start,[baseX,baseY]):parseSvgPath(`M${start[0]} ${start[1]}Q${control[0]} ${control[1]} ${baseX} ${baseY}`);const shaft=new Node(shaftPath).stroke(color,width);if(style.dash)shaft.dash(style.dash);const half=usableTip*ratio/2;const head=(x,y,ux,uy)=>new Node(polyPath([[x,y],[x-ux*usableTip-uy*half,y-uy*usableTip+ux*half],[x-ux*usableTip+uy*half,y-uy*usableTip-ux*half]],true)).fill(color);group2.add(shaft,head(end[0],end[1],tx,ty));if(style.both)group2.add(head(start[0],start[1],-dx,-dy));if(style.opacity!==void 0)group2.opacity(style.opacity);if(style.glow){shaft.glow(style.glow)}group2.data["shaft"]=shaft;return group2}function brace(from,to2,style={}){const dx=to2[0]-from[0],dy=to2[1]-from[1];const length=Math.hypot(dx,dy)||1;const depth=style.depth??Math.min(26,10+length*.05);const l=length,d=depth,t=1.6;const c=Math.min(d,l/4);const data=`M0 0C0 ${d*.5} ${c*.4} ${d*.5} ${c} ${d*.5}L${l/2-c} ${d*.5}C${l/2-c*.3} ${d*.5} ${l/2} ${d*.72} ${l/2} ${d}C${l/2} ${d*.72} ${l/2+c*.3} ${d*.5} ${l/2+c} ${d*.5}L${l-c} ${d*.5}C${l-c*.4} ${d*.5} ${l} ${d*.5} ${l} 0L${l-t*.2} ${t*.2}C${l-t*.4} ${d*.5-t} ${l-c*.4} ${d*.5-t} ${l-c} ${d*.5-t}L${l/2+c} ${d*.5-t}C${l/2+c*.3} ${d*.5-t} ${l/2+t*.4} ${d*.6} ${l/2} ${d*.82}C${l/2-t*.4} ${d*.6} ${l/2-c*.3} ${d*.5-t} ${l/2-c} ${d*.5-t}L${c} ${d*.5-t}C${c*.4} ${d*.5-t} ${t*.4} ${d*.5-t} ${t*.2} ${t*.2}Z`;const cos=dx/length,sin=dy/length;const path=transformPath(parseSvgPath(data),[cos,sin,-sin,cos,from[0],from[1]]);const node=styled(new Node(path),{...style,width:void 0},{fill:style.stroke??style.fill??"ink"});node.data["tip"]=[(from[0]+to2[0])/2-sin*depth,(from[1]+to2[1])/2+cos*depth];return node}var Axes=class extends Node{xRange;yRange;plotWidth;plotHeight;lines=new Node;grid=new Node;numbers=new Node;constructor(options={}){super();this.xRange=options.x??[-5,5];this.yRange=options.y??[-3,3];this.plotWidth=options.width??1100;this.plotHeight=options.height??640;const color=options.color??"dim";const xStep=options.xStep??niceStep(this.xRange[1]-this.xRange[0]);const yStep=options.yStep??niceStep(this.yRange[1]-this.yRange[0]);const originX=clampInto(0,this.xRange),originY=clampInto(0,this.yRange);const left=this.p(this.xRange[0],originY),right=this.p(this.xRange[1],originY);const bottom=this.p(originX,this.yRange[0]),top=this.p(originX,this.yRange[1]);if(options.grid){for(const x of ticks(this.xRange,xStep)){this.grid.add(line(this.p(x,this.yRange[0]),this.p(x,this.yRange[1]),{stroke:"grid",width:1.25}))}for(const y of ticks(this.yRange,yStep)){this.grid.add(line(this.p(this.xRange[0],y),this.p(this.xRange[1],y),{stroke:"grid",width:1.25}))}}const tips=options.tips??true;const axis=(from,to2)=>tips?arrow(from,to2,{stroke:color,width:2,tip:13}):line(from,to2,{stroke:color,width:2});this.lines.add(axis(left,right),axis(bottom,top));const tickSize=6;for(const x of ticks(this.xRange,xStep)){if(x===originX)continue;const[px,py]=this.p(x,originY);this.lines.add(line([px,py-tickSize],[px,py+tickSize],{stroke:color,width:2}))}for(const y of ticks(this.yRange,yStep)){if(y===originY)continue;const[px,py]=this.p(originX,y);this.lines.add(line([px-tickSize,py],[px+tickSize,py],{stroke:color,width:2}))}if(options.labels??true){const size=options.labelSize??20;for(const x of ticks(this.xRange,xStep)){if(x===originX)continue;const[px,py]=this.p(x,originY);this.numbers.add(tex(formatTick(x),{size,color:"dim",display:false}).moveTo([px,py+26]))}for(const y of ticks(this.yRange,yStep)){if(y===originY)continue;const[px,py]=this.p(originX,y);this.numbers.add(tex(formatTick(y),{size,color:"dim",display:false}).moveTo([px-28,py]))}}this.add(this.grid,this.lines,this.numbers);if(options.xLabel)this.add(tex(options.xLabel,{size:28,color:"ink",display:false}).moveTo([right[0]+4,right[1]-26]));if(options.yLabel){const label=tex(options.yLabel,{size:28,color:"ink",display:false});this.add(label.moveTo([top[0]+16+label.width/2,top[1]+4]))}}p(x,y){const[x0,x1]=this.xRange,[y0,y1]=this.yRange;return[((x-x0)/(x1-x0)-.5)*this.plotWidth,(.5-(y-y0)/(y1-y0))*this.plotHeight]}world(x,y){const[lx,ly]=this.p(x,y);return this.toWorld(lx,ly)}plotPath(f,options={}){const from=options.from??this.xRange[0],to2=options.to??this.xRange[1];const samples=options.samples??160;const[y0,y1]=this.yRange;const margin=(y1-y0)*.02;const points=[];for(let i=0;i<=samples;i++){const x=from+(to2-from)*i/samples;const y=f(x);points.push(Number.isFinite(y)&&y>=y0-margin&&y<=y1+margin?this.p(x,y):[NaN,NaN])}return curveThrough(points)}plot(f,style={}){const curve2=new Node(this.plotPath(f,style)).stroke(style.stroke??"blue",style.width??4);if(style.glow)curve2.glow(style.glow);if(style.dash)curve2.dash(style.dash);this.add(curve2);return curve2}dotAt(x,y,color="yellow",radius=9){const point=dot(radius,color).at(this.p(x,y));this.add(point);return point}guides(x,y,style={}){const originX=clampInto(0,this.xRange),originY=clampInto(0,this.yRange);const made=group(line(this.p(x,originY),this.p(x,y),{stroke:"dim",width:2,dash:[6,7],...style}),line(this.p(originX,y),this.p(x,y),{stroke:"dim",width:2,dash:[6,7],...style}));this.add(made);return made}};function axes(options={}){return new Axes(options)}function clampInto(value,range){return Math.max(range[0],Math.min(range[1],value))}function niceStep(span){const rough=span/8;const power=Math.pow(10,Math.floor(Math.log10(rough)));const unit=rough/power;return(unit<1.5?1:unit<3.5?2:unit<7.5?5:10)*power}function ticks(range,step){const out=[];const first=Math.ceil(range[0]/step-1e-9)*step;for(let value=first;value<=range[1]+1e-9;value+=step)out.push(Math.round(value/step)*step);return out}function formatTick(value){const rounded=Math.round(value*1e3)/1e3;return String(rounded)}var NumberPlane=class extends Node{unit;major=new Node;minor=new Node;axes=new Node;constructor(options={}){super();this.unit=options.unit??120;const[x0,x1]=options.x??[-12,12];const[y0,y1]=options.y??[-8,8];const u=this.unit;const stroke=options.color??"blue";const width=options.width??1.6;const minorPerUnit=options.minor??0;const segment=(a,b,count)=>{const points=[];for(let i=0;i<=count;i++)points.push([a[0]+(b[0]-a[0])*i/count,a[1]+(b[1]-a[1])*i/count]);return points.length>2?curveThrough(points):linePath(a,b)};const density=16;const add2=(parent,a,b,color,w,count)=>{parent.add(new Node(segment(a,b,count)).stroke(color,w))};for(let x=x0;x<=x1;x++){if(minorPerUnit>0&&x<x1){for(let k=1;k<minorPerUnit;k++){const mx=x+k/minorPerUnit;add2(this.minor,[mx*u,y0*u],[mx*u,y1*u],"grid",1,density)}}if(x!==0)add2(this.major,[x*u,y0*u],[x*u,y1*u],stroke,width,density)}for(let y=y0;y<=y1;y++){if(minorPerUnit>0&&y<y1){for(let k=1;k<minorPerUnit;k++){const my=y+k/minorPerUnit;add2(this.minor,[x0*u,my*u],[x1*u,my*u],"grid",1,density)}}if(y!==0)add2(this.major,[x0*u,y*u],[x1*u,y*u],stroke,width,density)}const axisColor=options.axisColor??"ink";add2(this.axes,[x0*u,0],[x1*u,0],axisColor,2.6,density);add2(this.axes,[0,y0*u],[0,y1*u],axisColor,2.6,density);this.add(this.minor,this.major,this.axes)}p(x,y){return[x*this.unit,-y*this.unit]}vector(x,y,style={}){return arrow([0,0],this.p(x,y),{stroke:"yellow",width:5,tip:22,...style})}};function plane(options={}){return new NumberPlane(options)}function decimal(read2,options={}){const node=new Node;node.draw=()=>{const value=read2();const body=(options.prefix??"")+value.toFixed(options.digits??2)+(options.suffix??"");return text(body,{size:options.size??36,color:options.color??"ink",font:options.font??"mono"})};return node}function reveal(node,t,stage){if(!node.mounted){clock.now=t;stage.add(node)}for(let n=node;n&&n!==stage.root;n=n.parent){if(!sampleAt(n,"visible",t))n.track("visible").step(t,true)}}function sampleAt(node,prop,t){const saved=clock.now;clock.now=t;const value=node.get(prop);clock.now=saved;return value}function stepAt2(node,prop,value,t){node.track(prop).step(t,value)}function tweenValue(value,to2,t0,t1,ease){const from=value.track.sample(t0);value.track.add({t0,t1,ease,to:to2,at:a=>from+(to2-from)*a})}function staggered(count,lag,t0,t1){if(count===0)return[];const each=(t1-t0)/(1+(count-1)*lag);return Array.from({length:count},(_,i)=>{const start=t0+i*lag*each;return[start,start+each]})}function labelNode(label,options){if(typeof label!=="string")return label;if(options.math)return tex(label,{size:options.size,color:options.color??"ink",display:false});return text(label,{size:options.size,color:options.color??"ink",font:options.font??"sans",weight:options.weight??400})}function luminance2(color){const f=v=>{const x=v/255;return x<=.04045?x/12.92:Math.pow((x+.055)/1.055,2.4)};return .2126*f(color[0])+.7152*f(color[1])+.0722*f(color[2])}function solidColor(input){if(typeof input==="string")return parseColor(input);if(Array.isArray(input))return input;const stops=input.stops;return stops[0][1]}function seededRandom2(seed){let state=seed>>>0;return()=>{state=state+1831565813>>>0;let v=Math.imul(state^state>>>15,1|state);v^=v+Math.imul(v^v>>>7,61|v);return((v^v>>>14)>>>0)/4294967296}}function stepsBetween(min,max,step){const out=[];const first=Math.ceil(min/step-1e-9)*step;for(let value=first;value<=max+step*1e-6;value+=step)out.push(Math.round(value/step)*step);return out}function niceTicks(min,max,count=5){const span=max-min||1;const rough=span/Math.max(1,count);const power=Math.pow(10,Math.floor(Math.log10(rough)));const unit=rough/power;const step=(unit<1.5?1:unit<3.5?2:unit<7.5?5:10)*power;return{ticks:stepsBetween(min,max,step),step}}function formatNumber(value,step){if(step!==void 0&&step<1){const digits=Math.min(4,Math.ceil(-Math.log10(step)-1e-9));return value.toFixed(digits)}const rounded=Math.round(value*1e3)/1e3;if(Math.abs(rounded)>=1e3&&Number.isInteger(rounded))return rounded.toLocaleString("en-US");return String(rounded)}function polylineRing(points){const first=points[0];const out=new Array(2+(points.length-1)*6);out[0]=first[0];out[1]=first[1];for(let i=1;i<points.length;i++){const a=points[i-1],b=points[i];const o=2+(i-1)*6;out[o]=a[0]+(b[0]-a[0])/3;out[o+1]=a[1]+(b[1]-a[1])/3;out[o+2]=a[0]+(b[0]-a[0])*2/3;out[o+3]=a[1]+(b[1]-a[1])*2/3;out[o+4]=b[0];out[o+5]=b[1]}return{p:Float64Array.from(out),closed:false,straight:true}}var read=value=>typeof value==="function"?value():value;var NumberLine2=class extends Node{range;length;line;ticks=new Node;numbers=new Node;constructor(options={}){super();this.range=options.range??[-5,5];this.length=options.length??1200;const color=options.color??"dim";const width=options.width??2;const half=this.length/2;const tips=options.tips??true;this.line=tips?arrow([-half-36,0],[half+36,0],{stroke:color,width,tip:14,both:true}):line([-half,0],[half,0],{stroke:color,width});const step=options.step??1;for(const value of stepsBetween(this.range[0],this.range[1],step)){const[x]=this.p(value);this.ticks.add(line([x,-7],[x,7],{stroke:color,width}));if(options.labels??true){const size=options.labelSize??24;const label=tex(String(Math.round(value*1e3)/1e3),{size,color:"dim",display:false});label.set("py",-size*.25);this.numbers.add(label.at(x,34))}}this.add(this.line,this.ticks,this.numbers)}p(value){const[min,max]=this.range;return[((value-min)/(max-min)-.5)*this.length,0]}world(value){const[x,y]=this.p(value);return this.toWorld(x,y)}marker(value,options={}){const color=options.color??"yellow";const size=options.labelSize??28;const build=()=>{const[x]=this.p(read(value));const parts=[dot(options.radius??9,color).at(x,0)];if(options.label)parts.push(tex(options.label,{size,color,display:false}).at(x,-size*1.15));return parts};const node=typeof value==="function"?dynamic(build):new Node().add(...build());this.add(node);return node}interval(from,to2,options={}){const color=options.color??"blue";const offset=options.offset??0;const[a]=this.p(from),[b]=this.p(to2);const band=line([a,offset],[b,offset],{stroke:color,width:options.width??7});const end=(x,open)=>open?dot(9,"bg").stroke(color,4).at(x,offset):dot(9,color).at(x,offset);const node=new Node().add(band,end(a,options.openLeft),end(b,options.openRight));this.add(node);return node}};function numberLine(options={}){return new NumberLine2(options)}var ComplexPlane=class extends NumberPlane{numbers=new Node;constructor(options={}){super(options);const range=options.labelRange??3;const size=options.labelSize??22;for(let k=-range;k<=range;k++){if(k===0)continue;const real=tex(String(k),{size,color:"ink",display:false});real.set("py",-size*.25);this.numbers.add(real.at(k*this.unit,22));const name=k===1?"i":k===-1?"-i":`${k}i`;const imaginary=tex(name,{size,color:"ink",display:false});imaginary.set("py",-size*.25);this.numbers.add(imaginary.at(-size*.9,-k*this.unit))}this.add(this.numbers)}z(re,im){return this.p(re,im)}};function complexPlane(options={}){return new ComplexPlane(options)}function applyComplex(plane2,f,options={}){const inverse=invert(plane2.worldMatrix());const world=plane2.worldMatrix();const unit=plane2.unit;const anim=warp([plane2.minor,plane2.major,plane2.axes],(x,y)=>{const[lx,ly]=apply(inverse,x,y);const[re,im]=f(lx/unit,-ly/unit);return apply(world,re*unit,-im*unit)},{duration:3,...options});return{...anim,label:"applyComplex"}}var complex={mul:(a,b)=>[a[0]*b[0]-a[1]*b[1],a[0]*b[1]+a[1]*b[0]],div:(a,b)=>{const d=b[0]*b[0]+b[1]*b[1]||1e-12;return[(a[0]*b[0]+a[1]*b[1])/d,(a[1]*b[0]-a[0]*b[1])/d]},exp:a=>{const r=Math.exp(a[0]);return[r*Math.cos(a[1]),r*Math.sin(a[1])]},log:a=>[Math.log(Math.hypot(a[0],a[1])||1e-12),Math.atan2(a[1],a[0])],pow:(a,n)=>{const r=Math.pow(Math.hypot(a[0],a[1]),n),angle=Math.atan2(a[1],a[0])*n;return[r*Math.cos(angle),r*Math.sin(angle)]},sin:a=>[Math.sin(a[0])*Math.cosh(a[1]),Math.cos(a[0])*Math.sinh(a[1])],cos:a=>[Math.cos(a[0])*Math.cosh(a[1]),-Math.sin(a[0])*Math.sinh(a[1])],inv:a=>{const d=a[0]*a[0]+a[1]*a[1]||1e-12;return[a[0]/d,-a[1]/d]}};function arrowRing(x0,y0,dx,dy,thickness){const length=Math.hypot(dx,dy)||1e-6;const ux=dx/length,uy=dy/length;const tip=Math.min(length*.42,thickness*5.2);const half=thickness/2;const head=tip*.42;const bx=x0+dx-ux*tip,by=y0+dy-uy*tip;const nx=-uy,ny=ux;return polyPath([[x0+nx*half,y0+ny*half],[bx+nx*half,by+ny*half],[bx+nx*head,by+ny*head],[x0+dx,y0+dy],[bx-nx*head,by-ny*head],[bx-nx*half,by-ny*half],[x0-nx*half,y0-ny*half]],true)[0]}var VectorField=class extends Node{constructor(f,options={}){super();this.f=f;const unit=this.unit=options.unit??120;const[x0,x1]=options.x??[-8,8];const[y0,y1]=options.y??[-4.5,4.5];const step=options.step??.5;const longest=options.maxLength??step*unit*.92;const width=options.width??2.6;const palette=(options.colors??["blue","teal","green","yellow","orange","red"]).map(c=>toPaint(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const positions=[];for(const y of stepsBetween(y0,y1,step))for(const x of stepsBetween(x0,x1,step))positions.push([x,y]);const magnitude=options.max??(()=>{const samples=positions.map(([x,y])=>{const[u,v]=f(x,y,0);return Math.hypot(u,v)}).filter(Number.isFinite).sort((a,b)=>a-b);return samples[Math.floor(samples.length*.9)]||1})();const shape2=(x,y,t)=>{const[u,v]=f(x,y,t);const m=Math.hypot(u,v);if(!Number.isFinite(m)||m<1e-9)return null;const amount2=Math.min(1,m/magnitude);const length=longest*(.22+.78*(1-Math.exp(-2.2*m/magnitude)));const dx=u/m*length,dy=-(v/m)*length;const px=x*unit,py=-y*unit;return{ring:arrowRing(px-dx/2,py-dy/2,dx,dy,width),at:amount2,cx:px,cy:py}};if(options.animate){const bands=12;this.draw=time=>{const rings=Array.from({length:bands},()=>[]);for(const[x,y]of positions){const made=shape2(x,y,time);if(made)rings[Math.min(bands-1,Math.floor(made.at*bands))].push(made.ring)}return rings.flatMap((list3,band)=>list3.length===0?[]:[new Node(list3).fill(sampleStops(stops,(band+.5)/bands))])};return}for(const[x,y]of positions){const made=shape2(x,y,0);if(!made)continue;const leaf=recenter([made.ring]).fill(sampleStops(stops,made.at));this.arrows.push(leaf);this.add(leaf)}}f;unit;arrows=[]};function recenter(path){const b=pathBounds(path);if(!b)return new Node(path);const cx=b.x+b.width/2,cy=b.y+b.height/2;const shifted=path.map(r=>{const out=new Float64Array(r.p.length);for(let i=0;i<out.length;i+=2){out[i]=r.p[i]-cx;out[i+1]=r.p[i+1]-cy}return{p:out,closed:r.closed}});return new Node(shifted).at(cx,cy)}function vectorField(f,options={}){return new VectorField(f,options)}var StreamLines=class extends Node{lineCount;constructor(f,options={}){super();const unit=options.unit??120;const[x0,x1]=options.x??[-8.5,8.5];const[y0,y1]=options.y??[-5,5];const spacing=options.spacing??.55;const dt=options.dt??.03;const steps=options.steps??130;const width=options.width??2.2;const speed=options.speed??.35;const tail=options.tail??.42;const random=seededRandom2(options.seed??7);const palette=(options.colors??["blue","teal","green","yellow","orange","red"]).map(c=>toPaint(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const lines=[];const speeds=[];const margin=.6;for(let sy=y0;sy<=y1;sy+=spacing){for(let sx=x0;sx<=x1;sx+=spacing){let x=sx+(random()-.5)*spacing,y=sy+(random()-.5)*spacing;const phase=random();const points=[[x*unit,-y*unit]];let total=0;for(let i=0;i<steps;i++){const[k1u,k1v]=f(x,y,0);const[k2u,k2v]=f(x+k1u*dt/2,y+k1v*dt/2,0);const[k3u,k3v]=f(x+k2u*dt/2,y+k2v*dt/2,0);const[k4u,k4v]=f(x+k3u*dt,y+k3v*dt,0);const u=(k1u+2*k2u+2*k3u+k4u)/6,v=(k1v+2*k2v+2*k3v+k4v)/6;if(!Number.isFinite(u)||!Number.isFinite(v))break;const m=Math.hypot(u,v);total+=m;if(m<1e-6)break;x+=u*dt;y+=v*dt;if(x<x0-margin||x>x1+margin||y<y0-margin||y>y1+margin)break;if(i%2===1)points.push([x*unit,-y*unit])}if(points.length<5)continue;const mean=total/(points.length*2);speeds.push(mean);lines.push({points,phase,speedRate:.8+random()*.4,color:mean})}}const sorted=[...speeds].sort((a,b)=>a-b);const top=options.max??(sorted[Math.floor(sorted.length*.92)]||1);const colorBands=8;for(const entry of lines)entry.color=Math.min(colorBands-1,Math.floor(Math.min(1,entry.color/top)*colorBands));this.lineCount=lines.length;const fadeBands=6;const trace=options.trace??0;const tracePath=Array.from({length:colorBands},()=>[]);if(trace>0)for(const entry of lines)tracePath[entry.color].push(polylineRing(entry.points));this.draw=time=>{const buckets=Array.from({length:colorBands*fadeBands},()=>[]);for(const entry of lines){const count=entry.points.length;const window2=Math.max(3,Math.floor(count*tail));const travel=count+window2;const head=(time*speed*entry.speedRate+entry.phase)%1*travel;for(let band=0;band<fadeBands;band++){const from=Math.floor(head-window2*(1-band/fadeBands));const to2=Math.floor(head-window2*(1-(band+1)/fadeBands));const a=Math.max(0,from),b=Math.min(count-1,to2);if(b-a<1)continue;buckets[entry.color*fadeBands+band].push(polylineRing(entry.points.slice(a,b+1)))}}const out=[];if(trace>0){tracePath.forEach((rings,c)=>{if(rings.length)out.push(new Node(rings).stroke(sampleStops(stops,(c+.5)/colorBands),width*.6).set("strokeOpacity",trace))})}buckets.forEach((rings,index)=>{if(rings.length===0)return;const c=Math.floor(index/fadeBands),band=index%fadeBands;const node=new Node(rings).stroke(sampleStops(stops,(c+.5)/colorBands),width);node.set("strokeOpacity",Math.pow((band+1)/fadeBands,1.6));if(band<fadeBands-1)node.set("cap","butt");out.push(node)});return out}}};function streamLines(f,options={}){return new StreamLines(f,options)}function riemann(axes2,f,options={}){const from=options.from??axes2.xRange[0],to2=options.to??axes2.xRange[1];const n=options.n??12;const rule=options.rule??"mid";const colors2=ramp(n,...options.colors??["blue","teal","green"]);const made=new Node;const dx=(to2-from)/n;for(let i=0;i<n;i++){const left=from+i*dx;const sample=rule==="left"?left:rule==="right"?left+dx:left+dx/2;const y=f(sample);const[ax,ay]=axes2.p(left,0),[bx,by]=axes2.p(left+dx,y);const leaf=recenter(polyPath([[ax,ay],[bx,ay],[bx,by],[ax,by]],true));leaf.fill(colors2[i],options.opacity??.72);leaf.stroke(options.stroke??"bg",options.strokeWidth??(n>40?.5:1.4));made.add(leaf)}axes2.add(made);return made}function areaPath(axes2,f,from,to2,samples){const points=[];for(let i=0;i<=samples;i++){const x=from+(to2-from)*i/samples;points.push(axes2.p(x,f(x)))}points.push(axes2.p(to2,0),axes2.p(from,0));return polyPath(points,true)}function areaUnder(axes2,f,options={}){const samples=options.samples??96;const color=options.fill??"blue";const opacity=options.opacity??.28;const from=options.from??axes2.xRange[0],to2=options.to??axes2.xRange[1];const node=typeof from==="function"||typeof to2==="function"?dynamic(()=>{const a=read(from),b=read(to2);return Math.abs(b-a)<1e-9?null:new Node(areaPath(axes2,f,a,b,samples)).fill(color,opacity)}):new Node(areaPath(axes2,f,from,to2,samples)).fill(color,opacity);axes2.add(node);return node}function slopeAt(axes2,f,x){const span=axes2.xRange[1]-axes2.xRange[0];const h=span*1e-4;const a=axes2.p(x-h,f(x-h)),b=axes2.p(x+h,f(x+h));const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;return{point:axes2.p(x,f(x)),ux:(b[0]-a[0])/length,uy:(b[1]-a[1])/length}}function tangentLine(axes2,f,x,style={}){const length=style.length??420;const color=style.stroke??"yellow";const build=()=>{const{point,ux,uy}=slopeAt(axes2,f,read(x));const parts=[line([point[0]-ux*length/2,point[1]-uy*length/2],[point[0]+ux*length/2,point[1]+uy*length/2],{stroke:color,width:style.width??3.5,glow:style.glow,dash:style.dash})];if(style.point??true)parts.push(dot(8,color).at(point));return parts};const node=typeof x==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function secantLine(axes2,f,a,b,style={}){const extend=style.extend??140;const color=style.stroke??"yellow";const build=()=>{const xa=read(a),xb=read(b);const pa=axes2.p(xa,f(xa)),pb=axes2.p(xb,f(xb));const length=Math.hypot(pb[0]-pa[0],pb[1]-pa[1])||1;const ux=(pb[0]-pa[0])/length,uy=(pb[1]-pa[1])/length;const parts=[line([pa[0]-ux*extend,pa[1]-uy*extend],[pb[0]+ux*extend,pb[1]+uy*extend],{stroke:color,width:style.width??3.5,glow:style.glow})];if(style.legs){const corner=[pb[0],pa[1]];const leg=style.legColor??"dim";parts.unshift(line(pa,corner,{stroke:leg,width:2,dash:[6,7]}),line(corner,pb,{stroke:leg,width:2,dash:[6,7]}))}if(style.points??true)parts.push(dot(8,color).at(pa),dot(8,color).at(pb));return parts};const node=typeof a==="function"||typeof b==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function dashedGuides(axes2,x,y,style={}){const build=()=>{const px=read(x),py=read(y);const originX=Math.max(axes2.xRange[0],Math.min(axes2.xRange[1],0));const originY=Math.max(axes2.yRange[0],Math.min(axes2.yRange[1],0));const common={stroke:"dim",width:2,dash:[6,7],...style};return[line(axes2.p(px,originY),axes2.p(px,py),common),line(axes2.p(originX,py),axes2.p(px,py),common)]};const node=typeof x==="function"||typeof y==="function"?dynamic(build):new Node().add(...build());axes2.add(node);return node}function angleMark(vertex,from,to2,options={}){const radius=options.radius??54;const color=options.color??"yellow";const a0=Math.atan2(from[1]-vertex[1],from[0]-vertex[0]);let sweep=Math.atan2(to2[1]-vertex[1],to2[0]-vertex[0])-a0;while(sweep<=-Math.PI)sweep+=Math.PI*2;while(sweep>Math.PI)sweep-=Math.PI*2;if(options.reflex)sweep+=sweep>0?-Math.PI*2:Math.PI*2;const node=new Node;if(options.fillOpacity){const points=[vertex];for(let i=0;i<=24;i++){const a=a0+sweep*i/24;points.push([vertex[0]+Math.cos(a)*radius,vertex[1]+Math.sin(a)*radius])}node.add(new Node(polyPath(points,true)).fill(color,options.fillOpacity))}node.add(new Node(arcPath(vertex[0],vertex[1],radius,radius,a0,a0+sweep)).stroke(color,options.width??3));if(options.label){const size=options.labelSize??30;const mid=a0+sweep/2;const distance=radius+size*.72;node.add(tex(options.label,{size,color,display:false}).at(vertex[0]+Math.cos(mid)*distance,vertex[1]+Math.sin(mid)*distance))}return node}function rightAngle(vertex,a,b,options={}){const size=options.size??26;const unit=p=>{const dx=p[0]-vertex[0],dy=p[1]-vertex[1];const l=Math.hypot(dx,dy)||1;return[dx/l,dy/l]};const[ax,ay]=unit(a),[bx,by]=unit(b);return new Node(polyPath([[vertex[0]+ax*size,vertex[1]+ay*size],[vertex[0]+(ax+bx)*size,vertex[1]+(ay+by)*size],[vertex[0]+bx*size,vertex[1]+by*size]])).stroke(options.color??"ink",options.width??2.5)}var DELIMITERS={"[":["[","]"],"(":["(",")"],"|":["|","|"]};var MatrixNode=class extends Node{cells;entries=new Node;brackets=new Node;rowCount;colCount;positions;options;constructor(rows,options={}){super();this.options=options;const size=options.size??52;const color=options.color??"ink";this.rowCount=rows.length;this.colCount=Math.max(0,...rows.map(row=>row.length));const made=rows.map(row=>row.map(value=>{const cell=tex(String(value),{size,color,display:false});cell.set("py",-size*.25);return cell}));const widths=Array.from({length:this.colCount},(_,j)=>Math.max(0,...made.map(row=>row[j]?.width??0)));const gapX=(options.gapX??.85)*size;const rowStep=(options.gapY??1.32)*size;const totalWidth=widths.reduce((sum,w)=>sum+w,0)+gapX*Math.max(0,this.colCount-1);const totalHeight=rowStep*Math.max(0,this.rowCount-1)+size;const columnX=[];let cursor=-totalWidth/2;for(const width of widths){columnX.push(cursor+width/2);cursor+=width+gapX}this.positions=made.map((row,i)=>row.map((cell,j)=>{const position2=[columnX[j],(i-(this.rowCount-1)/2)*rowStep];cell.at(position2);this.entries.add(cell);return position2}));this.cells=made;const kind=DELIMITERS[options.bracket??"["];const em=(totalHeight+size*.5)/size;const stretch=`\\rule{0pt}{${(em/2+.25).toFixed(3)}em}`;const pad2=size*.42;const left=tex(`\\left${kind[0]}${stretch}\\right.`,{size,color:options.bracketColor??color});const right=tex(`\\left.${stretch}\\right${kind[1]}`,{size,color:options.bracketColor??color});left.moveTo([-totalWidth/2-pad2-left.width/2,0]);right.moveTo([totalWidth/2+pad2+right.width/2,0]);this.brackets.add(left,right);this.add(this.brackets,this.entries)}cell(row,column){const found=this.cells[row]?.[column];if(!found)throw new Error(`Matrix has no cell (${row}, ${column}). It is ${this.rowCount} by ${this.colCount}.`);return found}row(index){return[...this.cells[index]??[]]}col(index){return this.cells.map(row=>row[index]).filter(Boolean)}setCell(row,column,value,options={}){const size=this.options.size??52;const next=tex(String(value),{size,color:this.options.color??"ink",display:false});next.set("py",-size*.25);const position2=this.positions[row][column];next.at(position2);const previous=this.cell(row,column);const self=this;const anim=morphMatching(previous,next,{duration:.8,...options});return{...anim,schedule(ctx){self.entries.add(next);next.track("visible").initial=false;self.cells[row][column]=next;anim.schedule(ctx)}}}};function matrix(rows,options={}){return new MatrixNode(rows,options)}function boundsOf2(target){const list3=Array.isArray(target)?target:[target];let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const node of list3){const b=node.bounds();x0=Math.min(x0,b.x);y0=Math.min(y0,b.y);x1=Math.max(x1,b.x+b.width);y1=Math.max(y1,b.y+b.height)}return{x:x0,y:y0,width:x1-x0,height:y1-y0}}function braceLabel(target,label,options={}){const b=boundsOf2(target);const side=options.side??"bottom";const gap=options.gap??12;const color=options.color??"ink";const size=options.size??34;const left=b.x,right=b.x+b.width,top=b.y,bottom=b.y+b.height;const[from,to2]=side==="bottom"?[[left,bottom+gap],[right,bottom+gap]]:side==="top"?[[right,top-gap],[left,top-gap]]:side==="left"?[[left-gap,top],[left-gap,bottom]]:[[right+gap,bottom],[right+gap,top]];const mark=brace(from,to2,{stroke:color,depth:options.depth});const tip=mark.data["tip"];const caption=labelNode(label,{size,color,math:!options.plain});caption.moveTo(tip);const dir=direction(side);const shifted=10+(dir[0]!==0?caption.width/2:caption.height/2);caption.shift(dir[0]*shifted,dir[1]*shifted);return new Node().add(mark,caption)}function surroundingBox(target,options={}){const b=boundsOf2(target);const pad2=options.pad??12;const box=rect(b.width+pad2*2,b.height+pad2*2,{radius:options.radius??8,stroke:options.color??"yellow",width:options.width??2.5,glow:options.glow});if(options.fill)box.fill(options.fill,options.fillOpacity??.14);return box.at(b.x+b.width/2,b.y+b.height/2)}var LabeledDot=class extends Node{mark;caption;constructor(label,options={}){super();const color=options.color??"yellow";this.mark=dot(options.radius??9,color);this.caption=labelNode(label,{size:options.size??30,color:options.labelColor??color,math:!options.plain});this.add(this.mark,this.caption);this.caption.nextTo(this.mark,options.side??[.72,-.72],options.gap??8)}};function labeledDot(label,options={}){return new LabeledDot(label,options)}function traced(point,from,to2,options={}){const color=options.color??"yellow";const width=options.width??3;const rate=options.rate??60;const fade2=options.fade??(options.tail!==void 0?0:1);const bands=fade2>=1?1:10;const cache2=new Map;const sample=index=>{const cached=cache2.get(index);if(cached)return cached;const saved=clock.now;clock.now=from+index/rate;const value=point();clock.now=saved;if(clock.mode==="render")cache2.set(index,value);return value};return dynamic(time=>{if(time<=from)return null;const end=Math.min(time,to2);const start=options.tail!==void 0?Math.max(from,end-options.tail):from;const i0=Math.ceil((start-from)*rate),i1=Math.floor((end-from)*rate);if(i1-i0<1)return null;const points=[];for(let i=i0;i<=i1;i++)points.push(sample(i));const saved=clock.now;clock.now=end;points.push(point());clock.now=saved;const out=[];for(let band=0;band<bands;band++){const a=Math.floor((points.length-1)*band/bands);const b=Math.min(points.length-1,Math.floor((points.length-1)*(band+1)/bands));if(b-a<1)continue;const node=new Node([polylineRing(points.slice(a,b+1))]).stroke(color,width);const light=bands===1?1:fade2+(1-fade2)*Math.pow((band+1)/bands,1.5);node.set("strokeOpacity",light);if(band<bands-1)node.set("cap","butt");if(options.glow)node.glow(options.glow);out.push(node)}return out})}function fourier(points,options={}){const n=points.length;const out=[];for(let k=0;k<n;k++){const freq=k<=n/2?k:k-n;let re=0,im=0;for(let i=0;i<n;i++){const angle=-2*Math.PI*freq*i/n;const c=Math.cos(angle),s=Math.sin(angle);const[x,y]=points[i];re+=x*c-y*s;im+=x*s+y*c}out.push({freq,amp:Math.hypot(re,im)/n,phase:Math.atan2(im,re)})}out.sort((a,b)=>b.amp-a.amp||a.freq-b.freq);return options.terms?out.slice(0,options.terms):out}function fourierPoint(terms,u){let x=0,y=0;for(const term of terms){const angle=2*Math.PI*term.freq*u+term.phase;x+=term.amp*Math.cos(angle);y+=term.amp*Math.sin(angle)}return[x,y]}function samplePath(path,count){const total=pathLength(path);if(total===0)return[];return Array.from({length:count},(_,i)=>pointAt(path,i/count))}var Epicycles=class extends Node{terms;outlinePoints;constructor(terms,options){super();this.terms=[...terms].sort((a,b)=>(a.freq===0?-1:b.freq===0?1:0)||b.amp-a.amp);const samples=options.samples??1024;this.outlinePoints=Array.from({length:samples+1},(_,i)=>fourierPoint(this.terms,i/samples));const circles=options.circles??64;const circleColor=options.circleColor??"blue";const armColor=options.armColor??"ink";const traceColor=options.traceColor??"yellow";const traceWidth=options.traceWidth??3.5;const tail=options.tail??1;const fadeBands=12;this.draw=()=>{const u=options.u();const cycle=u-Math.floor(u);const out=[];let x=0,y=0;const joints=[];const bands=[[],[],[],[]];this.terms.forEach((term,index)=>{const angle=2*Math.PI*term.freq*cycle+term.phase;const nx=x+term.amp*Math.cos(angle),ny=y+term.amp*Math.sin(angle);if(index<circles&&term.freq!==0&&term.amp>.4){bands[Math.min(3,Math.floor(index/Math.max(1,circles)*4))].push(...circlePath(x,y,term.amp))}x=nx;y=ny;if(index<circles)joints.push([x,y])});bands.forEach((rings,band)=>{if(rings.length)out.push(new Node(rings).stroke(circleColor,1.2).set("strokeOpacity",[.55,.36,.22,.14][band]))});if(joints.length>=2)out.push(new Node([polylineRing(joints)]).stroke(armColor,1.4).set("strokeOpacity",.85));const count=this.outlinePoints.length-1;const reach=u>=1?count:Math.floor(cycle*count);const start=Math.max(0,reach-Math.floor(count*tail));if(reach-start>=2){if(tail>=1){const trace=new Node([polylineRing(this.outlinePoints.slice(start,reach+1))]).stroke(traceColor,traceWidth);if(options.glow)trace.glow(options.glow);out.push(trace)}else{for(let band=0;band<fadeBands;band++){const a=start+Math.floor((reach-start)*band/fadeBands);const b=Math.min(reach,start+Math.floor((reach-start)*(band+1)/fadeBands));if(b-a<1)continue;const node=new Node([polylineRing(this.outlinePoints.slice(a,b+1))]).stroke(traceColor,traceWidth);node.set("strokeOpacity",Math.pow((band+1)/fadeBands,1.5));if(band<fadeBands-1)node.set("cap","butt");out.push(node)}}}if(u<1)out.push(dot(5,traceColor).at(x,y));return out}}outline(){return polyPath(this.outlinePoints.slice(0,-1),true)}point(u){return fourierPoint(this.terms,u)}};function epicycles(terms,options){return new Epicycles(terms,options)}function ringThrough(f,samples=200){const path=parametricPath(f,0,1,samples);return path.map(r=>ring(r.p,true))}var DEFAULT_SERIES=["blue","yellow","teal","orange","purple","green","pink","red"];function small(content,size,color="dim",font="sans"){return text(content,{size,color,font})}var BarChart2=class extends Node{bars=[];labels=[];readouts=[];baseline;values;maxValue;minValue;w;h;horizontal;band;gap;fixedMax;fixedMin;constructor(data,options={}){super();this.w=options.width??900;this.h=options.height??520;this.horizontal=options.horizontal??false;this.gap=options.gap??.28;this.fixedMax=options.max;this.fixedMin=options.min;const labelSize=options.labelSize??20;const count=Math.max(1,data.length);this.band=(this.horizontal?this.h:this.w)/count;const numbers=data.map(d=>d.value);this.maxValue=new Value(options.max??Math.max(0,...numbers));this.minValue=new Value(options.min??Math.min(0,...numbers));this.values=data.map(d=>new Value(d.value));const format=options.format??(v=>formatNumber(Math.round(v*100)/100));const baseColor=options.color??"faint";const[ax,ay]=this.place(0,0,"start"),[bx,by]=this.place(count-1,0,"end");this.baseline=line([ax,ay],[bx,by],{stroke:baseColor,width:1.5});data.forEach((datum,i)=>{const color=datum.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const bar=new Node(this.barPath(i,datum.value)).fill(color,.84);this.bars.push(bar);const label=small(datum.label,labelSize);this.labels.push(label);const[px,py]=this.place(i,0,"mid");if(this.horizontal)label.at(px-12-label.width/2,py);else label.at(px,py+12+labelSize/2);if(options.showValues??true){const readout=dynamic(()=>{const value=this.values[i].value;const[px2,py2]=this.tip(i,value);const node=small(format(value),labelSize,"ink","mono");if(this.horizontal)return node.at(px2+12+node.width/2,py2);return node.at(px2,py2+(value>=0?-1:1)*(10+labelSize*.6))});this.readouts.push(readout)}});this.add(...this.bars,this.baseline,...this.labels,...this.readouts)}lengthOf(value){const span=this.maxValue.value-this.minValue.value||1;return value/span*(this.horizontal?this.w:this.h)}place(i,_unused,at){const center2=(i+.5)*this.band;const half=this.band/2;const along3=at==="mid"?center2:at==="start"?center2-half:center2+half;const span=this.maxValue.value-this.minValue.value||1;if(this.horizontal){const zero2=-this.minValue.value/span*this.w-this.w/2;return[zero2,along3-this.h/2]}const zero=this.h/2- -this.minValue.value/span*this.h;return[along3-this.w/2,zero]}tip(i,value){const[px,py]=this.place(i,0,"mid");const length=this.lengthOf(value);return this.horizontal?[px+length,py]:[px,py-length]}barPath(i,value){const[px,py]=this.place(i,0,"mid");const thick=this.band*(1-this.gap);const length=this.lengthOf(value);if(this.horizontal)return rectPath(px,py-thick/2,length,thick);return rectPath(px-thick/2,py-length,thick,length)}bar(i){return this.bars[i]}enter(options={}){const lag=options.lag??.12;return{label:"barChart.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.baseline,"trimTo",0,ctx.t0);this.baseline.tween("trimTo",1,ctx.t0,ctx.t0+span*.4,ctx.ease);const windows=staggered(this.bars.length,lag,ctx.t0+span*.1,ctx.t1);this.bars.forEach((bar,i)=>{const[start,end]=windows[i];const target=this.values[i].track.sample(ctx.t0);this.values[i].track.step(ctx.t0,0);tweenValue(this.values[i],target,start,end,ctx.ease);bar.track("path").step(ctx.t0,this.barPath(i,0));bar.track("path").add({t0:start,t1:end,ease:ctx.ease,to:this.barPath(i,target),at:a=>this.barPath(i,target*a)});const label=this.labels[i];stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,start,start+(end-start)*.6,ctx.ease);const readout=this.readouts[i];if(readout){stepAt2(readout,"opacity",0,ctx.t0);readout.tween("opacity",1,start,start+(end-start)*.5,ctx.ease)}})}}}update(values,options={}){return{label:"barChart.update",duration:options.duration??1.1,ease:options.ease,schedule:ctx=>{const from=this.values.map(v=>v.track.sample(ctx.t0));const fromMax=this.maxValue.track.sample(ctx.t0),fromMin=this.minValue.track.sample(ctx.t0);const toMax=this.fixedMax??Math.max(0,...values),toMin=this.fixedMin??Math.min(0,...values);tweenValue(this.maxValue,toMax,ctx.t0,ctx.t1,ctx.ease);tweenValue(this.minValue,toMin,ctx.t0,ctx.t1,ctx.ease);values.forEach((value,i)=>{tweenValue(this.values[i],value,ctx.t0,ctx.t1,ctx.ease);const bar=this.bars[i];if(!bar)return;const at=a=>this.barPathAt(i,from[i]+(value-from[i])*a,fromMax+(toMax-fromMax)*a,fromMin+(toMin-fromMin)*a);bar.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:at(1),at})})}}}barPathAt(i,value,max,min){const span=max-min||1;const center2=(i+.5)*this.band;const thick=this.band*(1-this.gap);if(this.horizontal){const zero2=-min/span*this.w-this.w/2;return rectPath(zero2,center2-this.h/2-thick/2,value/span*this.w,thick)}const zero=this.h/2- -min/span*this.h;const length=value/span*this.h;return rectPath(center2-this.w/2-thick/2,zero-length,thick,length)}};function barChart(data,options={}){return new BarChart2(data,options)}var Histogram=class extends Node{shown;bins;range;chartWidth;chartHeight;axis=new Node;total;assigned;peak;constructor(samples,options={}){super();this.chartWidth=options.width??900;this.chartHeight=options.height??480;this.bins=options.bins??24;const low=options.range?.[0]??Math.min(...samples);const high=options.range?.[1]??Math.max(...samples);this.range=[low,high];this.total=samples.length;this.assigned=new Int32Array(samples.length);const counts2=new Int32Array(this.bins);samples.forEach((sample,i)=>{const bin=Math.min(this.bins-1,Math.floor((sample-low)/(high-low||1)*this.bins));this.assigned[i]=sample<low||sample>high?-1:bin;if(this.assigned[i]>=0)counts2[bin]++});this.peak=options.max??Math.max(1,...counts2);this.shown=new Value(samples.length);const labelSize=options.labelSize??20;const w=this.chartWidth,h=this.chartHeight;const baseline=line([-w/2,h/2],[w/2,h/2],{stroke:options.color??"faint",width:1.5});this.axis.add(baseline);const{ticks:ticks2,step}=niceTicks(low,high,options.ticks??6);for(const tick of ticks2){const x=this.xAt(tick);this.axis.add(line([x,h/2],[x,h/2+6],{stroke:"faint",width:1.5}));this.axis.add(small(formatNumber(tick,step),labelSize).at(x,h/2+12+labelSize*.6))}const palette=(options.colors??["blue"]).map(c=>solidColor(c));const stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const gap=options.gap??.12;const bars=dynamic(()=>{const n=Math.max(0,Math.min(this.total,Math.round(this.shown.value)));const current=new Int32Array(this.bins);for(let i=0;i<n;i++){const bin=this.assigned[i];if(bin>=0)current[bin]++}const width=w/this.bins;const rings=[];const out=[];for(let b=0;b<this.bins;b++){const height=current[b]/this.peak*h;if(height<=0)continue;const shape2=rectPath(-w/2+b*width+width*gap/2,h/2-height,width*(1-gap),height);if(palette.length===1)rings.push(...shape2);else out.push(new Node(shape2).fill(sampleStops(stops,b/Math.max(1,this.bins-1))))}if(rings.length)out.push(new Node(rings).fill(palette[0]));return out});this.add(bars,this.axis)}xAt(value){const[low,high]=this.range;return((value-low)/(high-low||1)-.5)*this.chartWidth}p(value,count){return[this.xAt(value),this.chartHeight/2-count/this.peak*this.chartHeight]}fillUp(options={}){const shown=this.shown;const target=options.count??this.total;return{label:"histogram.fill",duration:options.duration??3,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);if(shown.track.keys.length===0)shown.track.initial=0;tweenValue(shown,target,ctx.t0,ctx.t1,ctx.ease)}}}curve(f,options={}){const[low,high]=this.range;const samples=options.samples??120;const points=[];for(let i=0;i<=samples;i++){const x=low+(high-low)*i/samples;points.push(this.p(x,f(x)))}const node=new Node(smoothPath(points)).stroke(options.color??"yellow",options.width??4);this.add(node);return node}};function histogram(samples,options={}){return new Histogram(samples,options)}function xyPoint(frame,x,y){const{xRange,yRange,w,h}=frame;return[((x-xRange[0])/(xRange[1]-xRange[0]||1)-.5)*w,(.5-(y-yRange[0])/(yRange[1]-yRange[0]||1))*h]}function xyAxes(frame,options){const axis=new Node;const size=options.labelSize;const color=options.color??"faint";const{w,h}=frame;const x=niceTicks(frame.xRange[0],frame.xRange[1],options.xTicks??6);const y=niceTicks(frame.yRange[0],frame.yRange[1],options.yTicks??5);for(const value of y.ticks){const[,py]=xyPoint(frame,frame.xRange[0],value);if(options.gridY!==false)axis.add(line([-w/2,py],[w/2,py],{stroke:"grid",width:1.25}));const label=small(options.yFormat?options.yFormat(value):formatNumber(value,y.step),size);axis.add(label.at(-w/2-12-label.width/2,py))}axis.add(line([-w/2,h/2],[w/2,h/2],{stroke:color,width:1.5}));for(const value of x.ticks){const[px]=xyPoint(frame,value,frame.yRange[0]);axis.add(line([px,h/2],[px,h/2+6],{stroke:color,width:1.5}));axis.add(small(options.xFormat?options.xFormat(value):formatNumber(value,x.step),size).at(px,h/2+12+size*.6))}if(options.xLabel){const label=small(options.xLabel,size,"ink");axis.add(label.at(w/2-label.width/2,h/2+18+size*1.6))}if(options.yLabel){const label=small(options.yLabel,size,"ink");axis.add(label.at(-w/2+label.width/2,-h/2-12-size/2))}return axis}var Scatter=class extends Node{dots=[];axis;groupLabels=[];frame;constructor(points,options={}){super();const xs=points.map(p=>p.x),ys=points.map(p=>p.y);const pad2=(lo,hi)=>(hi-lo||1)*.06;const xRange=options.x??[Math.min(...xs)-pad2(Math.min(...xs),Math.max(...xs)),Math.max(...xs)+pad2(Math.min(...xs),Math.max(...xs))];const yRange=options.y??[Math.min(...ys)-pad2(Math.min(...ys),Math.max(...ys)),Math.max(...ys)+pad2(Math.min(...ys),Math.max(...ys))];this.frame={xRange,yRange,w:options.width??900,h:options.height??520};const labelSize=options.labelSize??18;this.axis=xyAxes(this.frame,{labelSize,color:options.color,xLabel:options.xLabel,yLabel:options.yLabel});const groups=new Map;const dots=points.map(point=>{let color=point.color;if(point.group!==void 0){let entry=groups.get(point.group);if(!entry){entry={color:color??DEFAULT_SERIES[groups.size%DEFAULT_SERIES.length],sumX:0,top:-Infinity,count:0};groups.set(point.group,entry)}color??=entry.color;entry.sumX+=point.x;entry.top=Math.max(entry.top,point.y);entry.count++}const made=dot(point.radius??options.radius??6,color??"blue").at(xyPoint(this.frame,point.x,point.y));made.set("fillOpacity",.92);return made});this.dots.push(...dots);this.add(this.axis,...dots);if(options.groupLabels??true){for(const[name,entry]of groups){const label=small(name,labelSize+2,entry.color);const[px,py]=xyPoint(this.frame,entry.sumX/entry.count,entry.top);label.at(px,py-labelSize*1.2);this.groupLabels.push(label);this.add(label)}}}p(x,y){return xyPoint(this.frame,x,y)}enter(options={}){const lag=options.lag??Math.min(.2,8/Math.max(1,this.dots.length));return{label:"scatter.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.axis,"opacity",0,ctx.t0);this.axis.tween("opacity",1,ctx.t0,ctx.t0+span*.3,ctx.ease);const order=[...this.dots].sort((a,b)=>a.get("x")-b.get("x"));const windows=staggered(order.length,lag,ctx.t0+span*.15,ctx.t1);order.forEach((point,i)=>{const[start,end]=windows[i];const sx=point.get("sx");stepAt2(point,"sx",.001,ctx.t0);stepAt2(point,"sy",.001,ctx.t0);point.tween("sx",sx,start,end,ctx.ease);point.tween("sy",sx,start,end,ctx.ease)});for(const label of this.groupLabels){stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,ctx.t0+span*.7,ctx.t1,ctx.ease)}}}}fit(f,options={}){const[x0,x1]=this.frame.xRange;const samples=options.samples??60;const points=[];for(let i=0;i<=samples;i++){const x=x0+(x1-x0)*i/samples;points.push(this.p(x,f(x)))}const node=new Node(smoothPath(points)).stroke(options.color??"yellow",options.width??3.5);this.add(node);return node}};function scatter(points,options={}){return new Scatter(points,options)}var LineChart2=class extends Node{lines=[];areas=[];names=[];axis;byName=new Map;frame;constructor(series,options={}){super();const resolved=series.map(entry=>entry.points??(entry.values??[]).map((value,i)=>[i,value]));const xs=resolved.flat().map(p=>p[0]),ys=resolved.flat().map(p=>p[1]);const yLow=Math.min(...ys),yHigh=Math.max(...ys);const yPad=(yHigh-yLow||1)*.08;const xRange=options.x??[Math.min(...xs),Math.max(...xs)];const yRange=options.y??[yLow>=0&&yLow<(yHigh-yLow)*.4?0:yLow-yPad,yHigh+yPad];const w=options.width??900,h=options.height??480;this.frame={xRange,yRange,w,h};const labelSize=options.labelSize??18;this.axis=xyAxes(this.frame,{labelSize,color:options.color,xLabel:options.xLabel,yLabel:options.yLabel,xFormat:options.xFormat,yFormat:options.yFormat,xTicks:options.xTicks,yTicks:options.yTicks});this.add(this.axis);const ends=[];series.forEach((entry,i)=>{const color=entry.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const points=resolved[i].map(([x,y])=>xyPoint(this.frame,x,y));if(entry.area){const base=xyPoint(this.frame,xRange[0],Math.max(yRange[0],0))[1];const shape2=polyPath([...points,[points[points.length-1][0],base],[points[0][0],base]],true);const area=new Node(shape2).fill(color,entry.area);this.areas.push(area);this.add(area)}const path=entry.smooth===false?polyPath(points):smoothPath(points);const stroke=new Node(path).stroke(color,entry.width??3.5);if(entry.dash)stroke.dash(entry.dash);this.lines.push(stroke);this.add(stroke);if(entry.name){this.byName.set(entry.name,stroke);const label=small(entry.name,labelSize+1,color);const last=points[points.length-1];ends.push({label,y:last[1]});label.at(last[0]+12+label.width/2,last[1]);this.names.push(label);this.add(label)}});ends.sort((a,b)=>a.y-b.y);const spacing=labelSize*1.25;for(let pass=0;pass<8;pass++){for(let i=1;i<ends.length;i++){const overlap=spacing-(ends[i].y-ends[i-1].y);if(overlap>0){ends[i-1].y-=overlap/2;ends[i].y+=overlap/2}}}for(const end of ends)end.label.at(end.label.get("x"),end.y)}p(x,y){return xyPoint(this.frame,x,y)}series(name){const found=this.byName.get(name);if(!found)throw new Error(`No series named ${JSON.stringify(name)}.`);return found}enter(options={}){const lag=options.lag??.1;return{label:"lineChart.enter",duration:options.duration??2.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.axis,"opacity",0,ctx.t0);this.axis.tween("opacity",1,ctx.t0,ctx.t0+span*.3,ctx.ease);const windows=staggered(this.lines.length,lag,ctx.t0+span*.15,ctx.t1);this.lines.forEach((stroke,i)=>{const[start,end]=windows[i];stepAt2(stroke,"trimTo",0,ctx.t0);stroke.tween("trimTo",1,start,end,ctx.ease);const name=this.names[i];if(name){stepAt2(name,"opacity",0,ctx.t0);name.tween("opacity",1,end-(end-start)*.2,Math.min(ctx.t1,end+span*.1),ctx.ease)}});for(const area of this.areas){const target=area.get("fillOpacity");stepAt2(area,"fillOpacity",0,ctx.t0);area.tween("fillOpacity",target,ctx.t0+span*.5,ctx.t1,ctx.ease)}}}}};function lineChart(series,options={}){return new LineChart2(series,options)}function wedgePath(a0,a1,inner,outer){if(a1-a0<1e-4)return[];const outerArc=arcPath(0,0,outer,outer,a0,a1)[0].p;const points=Array.from(outerArc);const cx=points[points.length-2],cy=points[points.length-1];const hop=(x,y,tx,ty)=>{points.push(x+(tx-x)/3,y+(ty-y)/3,x+(tx-x)*2/3,y+(ty-y)*2/3,tx,ty)};if(inner>.01){const innerArc=arcPath(0,0,inner,inner,a1,a0)[0].p;hop(cx,cy,innerArc[0],innerArc[1]);for(let i=2;i<innerArc.length;i++)points.push(innerArc[i]);hop(innerArc[innerArc.length-2],innerArc[innerArc.length-1],outerArc[0],outerArc[1])}else{hop(cx,cy,0,0);hop(0,0,outerArc[0],outerArc[1])}return[ring(points,true)]}var PieChart2=class extends Node{wedges=[];labels=[];leaders=[];centerText=null;shares;inner;outer;gap;constructor(data,options={}){super();this.outer=options.radius??240;this.inner=this.outer*(options.hole??0);this.gap=options.gap??(this.inner>0?.018:.008);const total=data.reduce((sum,d)=>sum+Math.max(0,d.value),0)||1;this.shares=data.map(d=>Math.max(0,d.value)/total);const size=options.labelSize??20;const angles=this.angles(this.shares);data.forEach((datum,i)=>{const color=datum.color??DEFAULT_SERIES[i%DEFAULT_SERIES.length];const[a0,a1]=angles[i];const wedge=new Node(wedgePath(a0,a1,this.inner,this.outer)).fill(color,.86);this.wedges.push(wedge);this.add(wedge)});if(options.labels??true){data.forEach((datum,i)=>{const[a0,a1]=angles[i];const mid=(a0+a1)/2;const cos=Math.cos(mid),sin=Math.sin(mid);const r0=this.outer+6,r1=this.outer+30;const elbowX=cos*r1,elbowY=sin*r1;const endX=elbowX+(cos>=0?18:-18);const leader=new Node(polyPath([[cos*r0,sin*r0],[elbowX,elbowY],[endX,elbowY]])).stroke("faint",1.25);const percent=options.percent??true;const body=percent?`${datum.label} ${Math.round(this.shares[i]*100)}%`:datum.label;const label=small(body,size,"ink");label.at(endX+(cos>=0?8+label.width/2:-8-label.width/2),elbowY);this.leaders.push(leader);this.labels.push(label);this.add(leader,label)})}if(options.centerLabel){const center2=text(options.centerLabel,{size:options.centerSize??Math.max(24,this.inner*.34),font:"serif",color:"ink"}).at(0,0);this.centerText=center2;this.add(center2)}}angles(shares,sweep=1){let cursor=-Math.PI/2;return shares.map(share=>{const span=share*Math.PI*2*sweep;const gap=Math.min(this.gap*sweep,span*.45);const out=[cursor+gap/2,cursor+span-gap/2];cursor+=span;return out})}enter(options={}){return{label:"pie.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const sweepEnd=ctx.t0+span*.78;this.wedges.forEach((wedge,i)=>{const at=a=>{const[x,y]=this.angles(this.shares,a)[i];return wedgePath(x,y,this.inner,this.outer)};wedge.track("path").step(ctx.t0,[]);wedge.track("path").add({t0:ctx.t0,t1:sweepEnd,ease:ctx.ease,to:at(1),at})});for(const node of[...this.labels,...this.leaders,...this.centerText?[this.centerText]:[]]){stepAt2(node,"opacity",0,ctx.t0);node.tween("opacity",1,ctx.t0+span*.62,ctx.t1,ctx.ease)}}}}update(values,options={}){return{label:"pie.update",duration:options.duration??1.1,ease:options.ease,schedule:ctx=>{const total=values.reduce((sum,v)=>sum+Math.max(0,v),0)||1;const next=values.map(v=>Math.max(0,v)/total);const previous=[...this.shares];this.wedges.forEach((wedge,i)=>{const at=a=>{const shares=previous.map((share,k)=>share+((next[k]??0)-share)*a);const[x,y]=this.angles(shares)[i];return wedgePath(x,y,this.inner,this.outer)};wedge.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:at(1),at})});for(const node of[...this.labels,...this.leaders]){node.tween("opacity",0,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.3,ctx.ease)}next.forEach((share,i)=>{this.shares[i]=share})}}}};function pie(data,options={}){return new PieChart2(data,options)}function donut(data,options={}){return new PieChart2(data,{hole:.62,...options})}var Heatmap2=class extends Node{cells=[];rowLabels=[];columnLabels=[];numbers=[];rowCount;colCount;stops;domain;constructor(values,options={}){super();this.rowCount=values.length;this.colCount=Math.max(0,...values.map(row=>row.length));const w=options.cellWidth??options.cell??44;const h=options.cellHeight??options.cell??44;const gap=options.gap??2;const flat=values.flat();this.domain=options.domain??[Math.min(...flat),Math.max(...flat)];const palette=(options.colors??["surface","blue","yellow"]).map(c=>solidColor(c));this.stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c]);const totalW=this.colCount*w+(this.colCount-1)*gap;const totalH=this.rowCount*h+(this.rowCount-1)*gap;const labelSize=options.labelSize??16;const valueSize2=options.valueSize??Math.min(h*.38,w*.36);const format=options.format??(v=>(Math.round(v*100)/100).toString());values.forEach((row,i)=>{const cells=[];const numbers=[];row.forEach((value,j)=>{const cx=-totalW/2+j*(w+gap)+w/2;const cy=-totalH/2+i*(h+gap)+h/2;const color=this.colorFor(value);const cell=new Node(rectPath(-w/2,-h/2,w,h,options.radius??0)).fill(color).at(cx,cy);cells.push(cell);this.add(cell);if(options.values){const label=text(format(value),{size:valueSize2,font:"mono",color:luminance2(color)>.32?"#101114":"#f2efe6"}).at(cx,cy);numbers.push(label);this.add(label)}});this.cells.push(cells);this.numbers.push(numbers)});options.rowLabels?.forEach((name,i)=>{const label=small(name,labelSize);const y=-totalH/2+i*(h+gap)+h/2;label.at(-totalW/2-10-label.width/2,y);this.rowLabels.push(label);this.add(label)});options.columnLabels?.forEach((name,j)=>{const label=small(name,labelSize);const x=-totalW/2+j*(w+gap)+w/2;const angle=options.columnLabelAngle??0;if(angle!==0){const length=label.width;label.at(x+Math.cos(angle)*length/2,-totalH/2-12+Math.sin(angle)*length/2);label.set("rotation",angle)}else{label.at(x,-totalH/2-10-labelSize/2)}this.columnLabels.push(label);this.add(label)})}colorFor(value){const[low,high]=this.domain;return sampleStops(this.stops,Math.max(0,Math.min(1,(value-low)/(high-low||1))))}cell(row,column){const found=this.cells[row]?.[column];if(!found)throw new Error(`Heatmap has no cell (${row}, ${column}). It is ${this.rowCount} by ${this.colCount}.`);return found}row(index){return[...this.cells[index]??[]]}col(index){return this.cells.map(row=>row[index]).filter(Boolean)}enter(options={}){return{label:"heatmap.enter",duration:options.duration??1.6,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const diagonals=this.rowCount+this.colCount-1;const each=span*.5;const stagger=diagonals>1?(span-each)/(diagonals-1):0;this.cells.forEach((row,i)=>row.forEach((cell,j)=>{const start=ctx.t0+(i+j)*stagger;stepAt2(cell,"opacity",0,ctx.t0);cell.tween("opacity",1,start,start+each,ctx.ease);const number=this.numbers[i]?.[j];if(number){stepAt2(number,"opacity",0,ctx.t0);number.tween("opacity",1,start,start+each,ctx.ease)}}));for(const label of[...this.rowLabels,...this.columnLabels]){stepAt2(label,"opacity",0,ctx.t0);label.tween("opacity",1,ctx.t0,ctx.t0+span*.4,ctx.ease)}}}}update(values,options={}){return{label:"heatmap.update",duration:options.duration??1,ease:options.ease,schedule:ctx=>{values.forEach((row,i)=>row.forEach((value,j)=>{const cell=this.cells[i]?.[j];if(cell)cell.tween("fill",this.colorFor(value),ctx.t0,ctx.t1,ctx.ease)}))}}}};function heatmap(values,options={}){return new Heatmap2(values,options)}var dagreModule=null;var dagreLoading=null;function requireDagre(){if(dagreModule)return dagreModule;dagreLoading??=import("@dagrejs/dagre").then(module=>{dagreModule=module.default??module});throw new Suspend(dagreLoading)}var GraphNode=class extends Node{shape;caption=null;halfWidth=0;halfHeight=0;round=true;edgePoint(fx,fy,tx,ty,pad2=0){const dx=tx-fx,dy=ty-fy;const length=Math.hypot(dx,dy)||1;if(this.round)return[fx+dx/length*(this.halfWidth+pad2),fy+dy/length*(this.halfWidth+pad2)];const sx=dx===0?Infinity:this.halfWidth/Math.abs(dx);const sy=dy===0?Infinity:this.halfHeight/Math.abs(dy);const s=Math.min(sx,sy);return[fx+dx*s+dx/length*pad2,fy+dy*s+dy/length*pad2]}};var GraphEdge=class extends Node{shaft;tip=null;caption=null;from="";to="";tipSize=14};function tipPath(path,size){const length=pathLength(path);if(length<=size*1.1)return{head:[],trimmed:path};const fraction=1-size/length;const trimmed=trimPath(path,0,fraction);const[x,y]=pointAt(path,1);const[ux,uy]=tangentAt(path,.997);const half=size*.38;const bx=x-ux*size,by=y-uy*size;return{head:polyPath([[x,y],[bx-uy*half,by+ux*half],[bx+uy*half,by-ux*half]],true),trimmed}}var Graph=class extends Node{nodes=new Map;edges=[];edgeLayer=new Node;nodeLayer=new Node;specs;constructor(nodes,edges,options={}){super();this.specs=nodes;const defaultRadius=options.radius??30;const labelSize=options.labelSize??26;const sizeOf=spec=>spec.width?[spec.width,spec.height??labelSize*2]:[(spec.radius??defaultRadius)*2,(spec.radius??defaultRadius)*2];const layout=options.layout??"dagre";let positions=new Map;const routes=new Map;if(layout==="dagre"){const dagre=requireDagre();const g=new dagre.graphlib.Graph({multigraph:true});g.setGraph({rankdir:options.direction??"LR",nodesep:options.nodeGap??60,ranksep:options.rankGap??110,edgesep:24,ranker:"network-simplex"});g.setDefaultEdgeLabel(()=>({}));for(const spec of nodes){const[width,height]=sizeOf(spec);g.setNode(spec.id,{width,height})}edges.forEach((edge,i)=>g.setEdge(edge.from,edge.to,{},String(i)));dagre.layout(g);const info=g.graph();const cx=(info.width??0)/2,cy=(info.height??0)/2;for(const spec of nodes){const placed=g.node(spec.id);positions.set(spec.id,[placed.x-cx,placed.y-cy])}edges.forEach((edge,i)=>{const data=g.edge({v:edge.from,w:edge.to,name:String(i)});if(data?.points)routes.set(edge,data.points.map(point=>[point.x-cx,point.y-cy]))})}else if(layout==="circle"){const radius=Math.min(options.width??700,options.height??700)/2;nodes.forEach((spec,i)=>{const angle=-Math.PI/2+i/nodes.length*Math.PI*2;positions.set(spec.id,[Math.cos(angle)*radius,Math.sin(angle)*radius])})}else if(layout==="force"){positions=forceLayout(nodes,edges,options.width??900,options.height??620,options.seed??3)}else{for(const spec of nodes)positions.set(spec.id,spec.at??[0,0])}const nodeColor=options.nodeColor??"blue";for(const spec of nodes){const view=new GraphNode;const color=spec.color??nodeColor;const[width,height]=sizeOf(spec);view.halfWidth=width/2;view.halfHeight=height/2;view.round=!spec.width;view.shape=new Node(spec.width?rectPath(-width/2,-height/2,width,height,8):circlePath(0,0,width/2)).fill(color,options.fillOpacity??.16).stroke(color,2.5);view.add(view.shape);if(spec.label){view.caption=spec.math?tex(spec.label,{size:labelSize,color:"ink",display:false}):text(spec.label,{size:labelSize,color:"ink"});view.add(view.caption.at(0,0))}view.named(spec.id);view.at(positions.get(spec.id)??[0,0]);this.nodes.set(spec.id,view);this.nodeLayer.add(view)}const directed=options.directed??true;const edgeColor=options.edgeColor??"dim";const edgeLabelSize=options.edgeLabelSize??20;for(const spec of edges){const from=this.nodes.get(spec.from),to2=this.nodes.get(spec.to);if(!from||!to2)throw new Error(`Graph edge ${spec.from} -> ${spec.to} refers to a node that does not exist.`);const view=new GraphEdge;view.from=spec.from;view.to=spec.to;const a=positions.get(spec.from),b=positions.get(spec.to);const route=routes.get(spec);const horizontal=(options.direction??"LR")==="LR"||options.direction==="RL";const path=routeEdge(from,to2,a,b,route,horizontal);const isDirected=spec.directed??directed;const color=spec.color??edgeColor;const{head,trimmed}=isDirected?tipPath(path,view.tipSize):{head:[],trimmed:path};view.shaft=new Node(trimmed).stroke(color,spec.width??2.2);if(spec.dash)view.shaft.dash(spec.dash);view.add(view.shaft);if(head.length){view.tip=new Node(head).fill(color);view.add(view.tip)}if(spec.label){const[mx,my]=pointAt(path,.5);const caption=text(spec.label,{size:edgeLabelSize,color:"ink",font:"mono"}).at(mx,my);const pad2=edgeLabelSize*.34;const plate=new Node(rectPath(mx-caption.width/2-pad2,my-edgeLabelSize*.68,caption.width+pad2*2,edgeLabelSize*1.36,4)).fill("bg");view.caption=new Node().add(plate,caption);view.add(view.caption)}this.edges.push(view);this.edgeLayer.add(view)}this.add(this.edgeLayer,this.nodeLayer)}node(id){const found=this.nodes.get(id);if(!found)throw new Error(`Graph has no node ${JSON.stringify(id)}.`);return found}edge(from,to2){const found=this.edges.find(edge=>edge.from===from&&edge.to===to2)??this.edges.find(edge=>edge.from===to2&&edge.to===from);if(!found)throw new Error(`Graph has no edge ${from} -> ${to2}.`);return found}enter(options={}){const lag=options.lag??.14;return{label:"graph.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const ordered=this.specs.map(spec=>this.nodes.get(spec.id));const windows=staggered(ordered.length,lag,ctx.t0,ctx.t0+(ctx.t1-ctx.t0)*.78);const startOf=new Map;ordered.forEach((view,i)=>{const[start,end]=windows[i];startOf.set(view,end);popIn(view,ctx.t0,start,end,ctx.ease)});for(const edge of this.edges){const start=startOf.get(this.nodes.get(edge.from))??ctx.t0;const end=Math.min(ctx.t1,start+(ctx.t1-ctx.t0)*.22);stepAt2(edge.shaft,"trimTo",0,ctx.t0);edge.shaft.tween("trimTo",1,start,end,ctx.ease);for(const part of[edge.tip,edge.caption]){if(!part)continue;stepAt2(part,"opacity",0,ctx.t0);part.tween("opacity",1,end-(end-start)*.3,end,ctx.ease)}}}}}pulseEdge(from,to2,options={}){const edge=this.edge(from,to2);return{...pulse(edge.shaft,{color:options.color??"yellow",length:options.length??.3,...options}),label:"graph.pulse"}}visit(id,options={}){const view=this.node(id);const color=options.color??"yellow";return{label:"graph.visit",duration:options.duration??.6,ease:options.ease,schedule:ctx=>{const paint=toPaint(color);view.shape.tween("stroke",paint,ctx.t0,ctx.t1,ctx.ease);view.shape.tween("fill",paint,ctx.t0,ctx.t1,ctx.ease);const span=ctx.t1-ctx.t0;const sx=view.get("sx");view.tween("sx",sx*1.16,ctx.t0,ctx.t0+span*.45,ctx.ease);view.tween("sy",sx*1.16,ctx.t0,ctx.t0+span*.45,ctx.ease);view.tween("sx",sx,ctx.t0+span*.45,ctx.t1,ctx.ease);view.tween("sy",sx,ctx.t0+span*.45,ctx.t1,ctx.ease)}}}moveNode(id,to2,options={}){const view=this.node(id);return{label:"graph.move",duration:options.duration??1,ease:options.ease,schedule:ctx=>{const fromX=view.get("x"),fromY=view.get("y");view.tween("x",to2[0],ctx.t0,ctx.t1,ctx.ease);view.tween("y",to2[1],ctx.t0,ctx.t1,ctx.ease);for(const edge of this.edges){if(edge.from!==id&&edge.to!==id)continue;const other=this.node(edge.from===id?edge.to:edge.from);const ox=sampleAt(other,"x",ctx.t0),oy=sampleAt(other,"y",ctx.t0);const geometry=a=>{const x=fromX+(to2[0]-fromX)*a,y=fromY+(to2[1]-fromY)*a;const start=edge.from===id?view.edgePoint(x,y,ox,oy,2):other.edgePoint(ox,oy,x,y,2);const end=edge.from===id?other.edgePoint(ox,oy,x,y,4):view.edgePoint(x,y,ox,oy,4);return polyPath([start,end])};const shaftAt=a=>edge.tip?tipPath(geometry(a),edge.tipSize).trimmed:geometry(a);edge.shaft.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:shaftAt(1),at:shaftAt});if(edge.tip){const tipAt=a=>tipPath(geometry(a),edge.tipSize).head;edge.tip.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:tipAt(1),at:tipAt})}}}}}};function routeEdge(from,to2,a,b,route,horizontal){const interior=route?route.slice(1,-1):[];const firstTarget=interior[0]??b,lastSource=interior[interior.length-1]??a;const start=from.edgePoint(a[0],a[1],firstTarget[0],firstTarget[1],2);const end=to2.edgePoint(b[0],b[1],lastSource[0],lastSource[1],4);if(!route)return polyPath([start,end]);if(interior.length<=1){const dx=end[0]-start[0],dy=end[1]-start[1];if(Math.abs(horizontal?dy:dx)<2)return polyPath([start,end]);const reach=(horizontal?dx:dy)*.5;const c1=horizontal?`${start[0]+reach} ${start[1]}`:`${start[0]} ${start[1]+reach}`;const c2=horizontal?`${end[0]-reach} ${end[1]}`:`${end[0]} ${end[1]-reach}`;return parseSvgPath(`M${start[0]} ${start[1]}C${c1} ${c2} ${end[0]} ${end[1]}`)}return smoothPath([start,...interior.slice(1,-1),end])}function popIn(node,hideFrom,start,end,ease){const sx=sampleAt(node,"sx",start),sy=sampleAt(node,"sy",start);stepAt2(node,"sx",sx*.001,hideFrom);stepAt2(node,"sy",sy*.001,hideFrom);node.tween("sx",sx,start,end,ease);node.tween("sy",sy,start,end,ease)}function forceLayout(nodes,edges,width,height,seed){const random=seededRandom2(seed);const ids=nodes.map(spec=>spec.id);const x=new Float64Array(ids.length),y=new Float64Array(ids.length);for(let i=0;i<ids.length;i++){x[i]=(random()-.5)*width;y[i]=(random()-.5)*height}const index=new Map(ids.map((id,i)=>[id,i]));const k=Math.sqrt(width*height/Math.max(1,ids.length))*.72;let temperature=Math.max(width,height)*.12;for(let round=0;round<420;round++){const dx=new Float64Array(ids.length),dy=new Float64Array(ids.length);for(let i=0;i<ids.length;i++){for(let j=i+1;j<ids.length;j++){const ox=x[i]-x[j],oy=y[i]-y[j];const d=Math.max(1,Math.hypot(ox,oy));const force=k*k/d;dx[i]+=ox/d*force;dy[i]+=oy/d*force;dx[j]-=ox/d*force;dy[j]-=oy/d*force}}for(const edge of edges){const a=index.get(edge.from),b=index.get(edge.to);if(a===void 0||b===void 0)continue;const ox=x[a]-x[b],oy=y[a]-y[b];const d=Math.max(1,Math.hypot(ox,oy));const force=d*d/k;dx[a]-=ox/d*force;dy[a]-=oy/d*force;dx[b]+=ox/d*force;dy[b]+=oy/d*force}for(let i=0;i<ids.length;i++){const length=Math.max(1e-6,Math.hypot(dx[i],dy[i]));x[i]+=dx[i]/length*Math.min(length,temperature);y[i]+=dy[i]/length*Math.min(length,temperature);x[i]=Math.max(-width/2,Math.min(width/2,x[i]));y[i]=Math.max(-height/2,Math.min(height/2,y[i]))}temperature*=.985}return new Map(ids.map((id,i)=>[id,[x[i],y[i]]]))}function graph(nodes,edges,options={}){return new Graph(nodes,edges,options)}var TreeGraph=class extends Graph{depths=new Map;constructor(root,options={}){const specs=[];const links=[];const depthOf=new Map;const levelGap=options.levelGap??130;const siblingGap=options.siblingGap??96;let counter2=0;let leafCursor=0;const place2=(node,depth)=>{const id=node.id??`n${counter2++}`;depthOf.set(id,depth);const children=node.children??[];let position2;const entry={id,label:node.label,color:node.color,math:node.math};specs.push(entry);if(children.length===0){position2=leafCursor++}else{const placed=children.map(child=>place2(child,depth+1));position2=(placed[0].position+placed[placed.length-1].position)/2;for(const child of placed)links.push({from:id,to:child.id,directed:false})};entry.at=options.direction==="right"?[depth*levelGap,position2*siblingGap]:[position2*siblingGap,depth*levelGap];return{id,position:position2}};place2(root,0);const xs=specs.map(spec=>spec.at[0]),ys=specs.map(spec=>spec.at[1]);const cx=(Math.min(...xs)+Math.max(...xs))/2,cy=(Math.min(...ys)+Math.max(...ys))/2;for(const spec of specs)spec.at=[spec.at[0]-cx,spec.at[1]-cy];super(specs,links,{layout:"manual",radius:options.radius??28,labelSize:options.labelSize??24,nodeColor:options.nodeColor,edgeColor:options.edgeColor,fillOpacity:options.fillOpacity,directed:false});for(const[id,depth]of depthOf)this.depths.set(id,depth)}enter(options={}){return{label:"tree.enter",duration:options.duration??2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const levels=Math.max(...this.depths.values())+1;const span=(ctx.t1-ctx.t0)/levels;for(const[id,view]of this.nodes){const depth=this.depths.get(id)??0;const start=ctx.t0+depth*span;popIn(view,ctx.t0,start,start+span,ctx.ease)}for(const edge of this.edges){const depth=this.depths.get(edge.to)??1;const start=ctx.t0+(depth-1)*span+span*.3;stepAt2(edge.shaft,"trimTo",0,ctx.t0);edge.shaft.tween("trimTo",1,start,start+span*.8,ctx.ease)}}}}};function tree(root,options={}){return new TreeGraph(root,options)}var ArrayCells=class extends Node{slots=[];indexLabels=[];items=[];cellSize;step;constructor(values,options={}){super();const cell=this.cellSize=options.cell??72;const gap=options.gap??6;this.step=cell+gap;const size=options.size??cell*.38;const color=options.color??"blue";const left=-((values.length-1)*this.step)/2;values.forEach((_,i)=>{const x=left+i*this.step;const slot=new Node(rectPath(-cell/2,-cell/2,cell,cell,6)).stroke("faint",1.5).at(x,0);this.slots.push(slot);this.add(slot);if(options.indices??true){const label=text(String(i),{size:options.indexSize??Math.max(13,cell*.2),color:"faint",font:"mono"}).at(x,cell/2+(options.indexSize??cell*.2)+2);this.indexLabels.push(label);this.add(label)}});values.forEach((value,i)=>{const x=left+i*this.step;const item=new Node().at(x,0);const box=new Node(rectPath(-cell/2+2,-cell/2+2,cell-4,cell-4,5)).fill(color,.16).stroke(color,2);const glyphs=text(String(value),{size,font:options.font??"mono",color:"ink"}).at(0,0);item.add(box,glyphs);item.data["box"]=box;item.data["value"]=value;this.items.push(item);this.add(item)})}cell(index){const found=this.items[index];if(!found)throw new Error(`Array has no index ${index}.`);return found}slotAt(index){return[this.slots[index].get("x"),this.slots[index].get("y")]}swap(i,j,options={}){return{label:"array.swap",duration:options.duration??.8,ease:options.ease,schedule:ctx=>{const a=this.items[i],b=this.items[j];const[ax,ay]=this.slotAt(i),[bx,by]=this.slotAt(j);const lift=options.lift??this.cellSize*.9+Math.abs(i-j)*6;const arc2=(node,fx,fy,tx,ty,sign)=>{node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:tx,at:t=>fx+(tx-fx)*t});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:ty,at:t=>fy+(ty-fy)*t-sign*lift*4*t*(1-t)})};arc2(a,ax,ay,bx,by,1);arc2(b,bx,by,ax,ay,-1);this.items[i]=b;this.items[j]=a}}}mark(index,color,options={}){const item=this.cell(index);return{...recolor(item.data["box"],color,{duration:.35,...options}),label:"array.mark"}}enter(options={}){const lag=options.lag??.2;return{label:"array.enter",duration:options.duration??1.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const windows=staggered(this.items.length,lag,ctx.t0,ctx.t1);this.items.forEach((item,i)=>{const[start,end]=windows[i];popIn(item,ctx.t0,start,end,ctx.ease);stepAt2(this.slots[i],"opacity",0,ctx.t0);this.slots[i].tween("opacity",1,start,end,ctx.ease);const index=this.indexLabels[i];if(index){stepAt2(index,"opacity",0,ctx.t0);index.tween("opacity",1,start,end,ctx.ease)}})}}}};function arrayCells(values,options={}){return new ArrayCells(values,options)}var KEYWORDS={ts:new Set("const let var function return if else for while do switch case break continue new class extends implements interface type enum import export from default async await yield try catch finally throw typeof instanceof in of this super null undefined true false void as readonly public private protected static get set".split(" ")),python:new Set("def return if elif else for while in not and or is class import from as with try except finally raise lambda yield pass break continue global nonlocal None True False self async await assert del print".split(" ")),rust:new Set("fn let mut pub struct enum impl trait use mod match if else for while loop return self Self as in where const static crate super true false ref move async await dyn type".split(" ")),go:new Set("func var const type struct interface package import return if else for range switch case default break continue go defer select chan map nil true false".split(" ")),sql:new Set("select from where join left right inner outer on group by order having limit as and or not in is null insert into values update set delete create table with distinct count sum avg min max".split(" ")),bash:new Set("if then else elif fi for do done while case esac in function return export local echo cd exit set".split(" ")),plain:new Set};function tokenize(source,language="ts"){const lang=language==="js"||language==="tsx"||language==="jsx"||language==="typescript"||language==="javascript"?"ts":language==="py"?"python":language;const keywords=KEYWORDS[lang]??KEYWORDS["ts"];const insensitive=lang==="sql";const hashComment=lang==="python"||lang==="bash";const dashComment=lang==="sql";const out=[];source.split("\n").forEach((row,line2)=>{let i=0;while(i<row.length){const rest=row.slice(i);const push=(value,kind)=>{out.push({text:value,kind,line:line2});i+=value.length};const space=/^\s+/.exec(rest);if(space){push(space[0],"space");continue}if(!hashComment&&!dashComment&&rest.startsWith("//")||hashComment&&rest[0]==="#"||dashComment&&rest.startsWith("--")){push(rest,"comment");continue}const string=/^("(?:[^"\\]|\\.)*"?|'(?:[^'\\]|\\.)*'?|`(?:[^`\\]|\\.)*`?)/.exec(rest);if(string){push(string[0],"string");continue}const number=/^(0x[\da-fA-F_]+|\d[\d_]*(?:\.\d+)?(?:e[-+]?\d+)?)/.exec(rest);if(number){push(number[0],"number");continue}const word=/^[A-Za-z_$][\w$]*/.exec(rest);if(word){const value=word[0];const after=rest.slice(value.length);const isKeyword=keywords.has(insensitive?value.toLowerCase():value);const kind=isKeyword?"keyword":/^\s*\(/.test(after)?"function":/^[A-Z]/.test(value)?"type":"plain";push(value,kind);continue}push(rest[0],"punctuation")}});return out}var CODE_COLORS={keyword:"purple",string:"green",number:"orange",comment:"faint",function:"blue",type:"teal",punctuation:"dim",plain:"ink"};var CodeBlock2=class extends Node{lines=[];tokens=[];chars=[];panelNode=null;body=new Node;source;bar;rowHeight;originY;contentWidth;constructor(source,options={}){super();this.source=source;const size=options.size??26;const rowHeight=this.rowHeight=size*(options.leading??1.5);const font=fontFor("mono",400);const scale=size/font.unitsPerEm;const advance=font.advance(font.glyphFor(48))*scale;const tokens5=tokenize(source,options.language??"ts");const rows=source.split("\n");const gutter=options.lineNumbers?(String(rows.length).length+2)*advance:0;const pad2=options.padding??size*.9;const width=Math.max(options.minWidth??0,Math.max(...rows.map(row=>row.length))*advance+gutter+pad2*2);const height=rows.length*rowHeight+pad2*2-(rowHeight-size);this.contentWidth=width;const left=-width/2+pad2+gutter,top=-height/2+pad2+size*.82;this.originY=top;if(options.panel??true){const panel=new Node(rectPath(-width/2,-height/2,width,height,8)).fill("surface").stroke("gridStrong",1);this.panelNode=panel;this.add(panel)}this.bar=new Node().fill("yellow",.1);this.bar.base.visible=false;this.add(this.bar);for(let i=0;i<rows.length;i++){const line2=new Node;this.lines.push(line2);this.body.add(line2);if(options.lineNumbers){const label=String(i+1).padStart(String(rows.length).length," ");let cx=left-gutter;for(const char of label){if(char!==" ")line2.add(makeGlyph(font,char,size,"faint",cx,top+i*rowHeight));cx+=advance}}}const colors2={...CODE_COLORS,...options.colors};const column=new Map;for(const token of tokens5){const start=column.get(token.line)??0;column.set(token.line,start+token.text.length);const entry={...token,glyphs:[]};this.tokens.push(entry);if(token.kind==="space")continue;const color=colors2[token.kind];[...token.text].forEach((char,offset)=>{const leaf=makeGlyph(font,char,size,color,left+(start+offset)*advance,top+token.line*rowHeight);entry.glyphs.push(leaf);this.chars.push(leaf);this.lines[token.line].add(leaf)})}this.add(this.body)}line(index){const found=this.lines[index];if(!found)throw new Error(`Code has no line ${index}.`);return found}find(fragment){return this.tokens.filter(token=>token.text===fragment).flatMap(token=>token.glyphs)}focus(lines,options={}){const wanted=new Set(typeof lines==="number"?[lines]:lines);return{label:"code.focus",duration:options.duration??.6,ease:options.ease,schedule:ctx=>{this.lines.forEach((line2,i)=>{line2.tween("opacity",wanted.has(i)?1:options.dim??.28,ctx.t0,ctx.t1,ctx.ease)});const sorted=[...wanted].sort((a,b)=>a-b);const first=sorted[0]??0,last=sorted[sorted.length-1]??first;const y=this.originY-this.rowHeight*.32+(first+last)/2*this.rowHeight;const spanRows=last-first+1;const barPath=rectPath(-this.contentWidth/2+2,-this.rowHeight*spanRows/2,this.contentWidth-4,this.rowHeight*spanRows,3);const wasVisible=sampleAt(this.bar,"visible",ctx.t0);if(!wasVisible){stepAt2(this.bar,"x",0,ctx.t0);stepAt2(this.bar,"y",y,ctx.t0);this.bar.track("path").step(ctx.t0,barPath);stepAt2(this.bar,"visible",true,ctx.t0);stepAt2(this.bar,"opacity",0,ctx.t0);this.bar.tween("opacity",1,ctx.t0,ctx.t1,ctx.ease)}else{this.bar.tween("y",y,ctx.t0,ctx.t1,ctx.ease);this.bar.tween("path",barPath,ctx.t0,ctx.t1,ctx.ease)}if(options.color)this.bar.tween("fill",toPaint(options.color),ctx.t0,ctx.t1,ctx.ease)}}}unfocus(options={}){return{label:"code.unfocus",duration:options.duration??.5,ease:options.ease,schedule:ctx=>{for(const line2 of this.lines)line2.tween("opacity",1,ctx.t0,ctx.t1,ctx.ease);this.bar.tween("opacity",0,ctx.t0,ctx.t1,ctx.ease);stepAt2(this.bar,"visible",false,ctx.t1)}}}};function makeGlyph(font,char,size,color,x,baseline){const leaf=new Node(glyphPath(font,font.glyphFor(char.codePointAt(0)),size));leaf.base.fill=toPaint(color);leaf.base.trimEach=true;leaf.data["key"]=char;return leaf.at(x,baseline)}function codeBlock(source,options={}){return new CodeBlock2(source,options)}function morphCode(from,to2,options={}){const visible=block=>block.tokens.filter(token=>token.kind!=="space"&&token.glyphs.length>0);const a=visible(from),b=visible(to2);const pairs=matchSequence(a.map(token=>token.text),b.map(token=>token.text));const keys=new Map;pairs.forEach(([i,j],pair)=>{a[i].glyphs.forEach((glyph,k)=>keys.set(glyph,`m${pair}:${k}`));b[j].glyphs.forEach((glyph,k)=>keys.set(glyph,`m${pair}:${k}`))});if(from.panelNode&&to2.panelNode){keys.set(from.panelNode,"panel");keys.set(to2.panelNode,"panel")}let unique=0;const anim=morphMatching(from,to2,{duration:1.5,...options,key:leaf=>{let key=keys.get(leaf);if(key===void 0){key=`only:${unique++}`;keys.set(leaf,key)}return key}});return{...anim,label:"morphCode"}}var NeuralNet=class extends Node{neurons=[];links=[];edgeLayer=new Node;neuronLayer=new Node;captions=[];seed;layerColors;constructor(layers,options={}){super();const width=options.width??1e3;const height=options.height??560;const radius=options.radius??15;const collapse=options.collapse??8;const columnGap=layers.length>1?width/(layers.length-1):0;this.seed=options.seed??11;this.layerColors=options.colors??["blue","teal","teal","yellow"];const edgeColor=options.edgeColor??"dim";const edgeOpacity=options.edgeOpacity??.32;const positions=[];layers.forEach((count,l)=>{const shown=count>collapse?collapse:count;const step=Math.min(radius*3.6,height/Math.max(1,shown+(count>collapse?1:0)));const x=-width/2+l*columnGap;const column=[];const views=[];const color=this.layerColors[Math.min(l,this.layerColors.length-1)];const keepTop=Math.ceil(shown/2);for(let i=0;i<shown+(count>collapse?1:0);i++){const y=(i-(shown+(count>collapse?1:0)-1)/2)*step;if(count>collapse&&i===keepTop){this.neuronLayer.add(tex("\\vdots",{size:radius*1.9,color:"dim",display:false}).at(x,y));continue}column.push([x,y]);const neuron=new Node(circlePath(0,0,radius)).stroke(color,2.2).fill(color,.08).at(x,y);views.push(neuron);this.neuronLayer.add(neuron)}positions.push(column);this.neurons.push(views);const name=options.layerLabels?.[l];if(name){const size=options.labelSize??22;const caption=text(name,{size,color:"dim"}).at(x,height/2+size*1.5);this.captions.push(caption);this.add(caption)}});for(let l=0;l+1<positions.length;l++){const rows=[];for(const a of positions[l]){const row=[];for(const b of positions[l+1]){const length=Math.hypot(b[0]-a[0],b[1]-a[1])||1;const ux=(b[0]-a[0])/length,uy=(b[1]-a[1])/length;const link=line([a[0]+ux*radius,a[1]+uy*radius],[b[0]-ux*radius,b[1]-uy*radius],{stroke:edgeColor,width:1.1});link.set("strokeOpacity",edgeOpacity);row.push(link);this.edgeLayer.add(link)}rows.push(row)}this.links.push(rows)}this.add(this.edgeLayer,this.neuronLayer)}layer(index){return this.neurons[index]??[]}enter(options={}){return{label:"net.enter",duration:options.duration??2.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const layers=this.neurons.length;const each=span*.45;const gap=layers>1?span*.55/(layers-1):0;this.neurons.forEach((views,l)=>{const windows=staggered(views.length,.12,ctx.t0+l*gap,ctx.t0+l*gap+each);views.forEach((neuron,i)=>popIn(neuron,ctx.t0,windows[i][0],windows[i][1],ctx.ease))});this.links.forEach((rows,l)=>{const start=ctx.t0+l*gap+each*.45;for(const row of rows)for(const link of row){stepAt2(link,"trimTo",0,ctx.t0);link.tween("trimTo",1,start,start+each,ctx.ease)}});for(const child of this.neuronLayer.children){if(child.get("path"))continue;stepAt2(child,"opacity",0,ctx.t0);child.tween("opacity",1,ctx.t0+span*.3,ctx.t1,ctx.ease)}for(const caption of this.captions){stepAt2(caption,"opacity",0,ctx.t0);caption.tween("opacity",1,ctx.t0+span*.3,ctx.t1,ctx.ease)}}}}activate(layer,values,options={}){return{label:"net.activate",duration:options.duration??.45,ease:options.ease,schedule:ctx=>{this.neurons[layer].forEach((neuron,i)=>{const amount2=Math.max(.04,Math.min(1,values[i]??0));neuron.tween("fillOpacity",amount2,ctx.t0,ctx.t1,ctx.ease);if(options.color)neuron.tween("fill",toPaint(options.color),ctx.t0,ctx.t1,ctx.ease)})}}}forward(options={}){const random=seededRandom2(this.seed);const activations=this.neurons.map((views,l)=>options.activations?.[l]??views.map(()=>random()*random()));const color=options.color??"yellow";const steps=[];activations.forEach((values,l)=>{steps.push(this.activate(l,values,{duration:.35}));if(l+1>=this.neurons.length)return;const candidates=[];this.links[l].forEach((row,i)=>row.forEach((link,j)=>{candidates.push({link,score:(values[i]??0)*(activations[l+1]?.[j]??0)})}));candidates.sort((a,b)=>b.score-a.score);const picked=candidates.slice(0,options.pulses??10);steps.push(par(...picked.map(({link,score})=>pulse(link,{color,length:.42,width:1.5+score*3,glow:4,duration:.7}))))});const whole=seq(...steps);return{...whole,label:"net.forward",duration:options.duration??whole.duration,ease:options.ease}}};function neuralNet(layers,options={}){return new NeuralNet(layers,options)}var TokenRow=class extends Node{chips=[];constructor(items,options={}){super();const size=options.size??22;const gap=options.gap??size*.28;const subSize=options.subSize??size*.62;const padX=size*.42,padY=size*.3;const specs=items.map(item=>typeof item==="string"?{text:item}:item);const palette=options.colors?ramp(specs.length,...options.colors):null;let x=0,y=0;const placed=[];const rowHeight=size+padY*2+(specs.some(s=>s.sub)?subSize*1.4:0);for(let i=0;i<specs.length;i++){const spec=specs[i];const color=spec.color??(palette?palette[i]:options.color??"blue");const label=text(spec.text.replace(/ /g,"\xB7"),{size,font:options.font??"mono",color:"ink"});const w=Math.max(label.width,size*.5)+padX*2;const h=size+padY*2;if(options.maxWidth!==void 0&&x>0&&x+w>options.maxWidth){x=0;y+=rowHeight+gap}const chip=new Node;const box=new Node(rectPath(-w/2,-h/2,w,h,options.radius??4)).fill(color,.18).stroke(color,1.5);chip.add(box,label.at(0,0));if(spec.sub)chip.add(text(spec.sub,{size:subSize,font:"mono",color:"dim"}).at(0,h/2+subSize*.82));chip.data["box"]=box;placed.push({node:chip,x:x+w/2,y,w});x+=w+gap}const maxX=Math.max(...placed.map(p=>p.x+p.w/2),0);const maxY=Math.max(...placed.map(p=>p.y),0);for(const entry of placed){entry.node.at(entry.x-maxX/2,entry.y-maxY/2);this.chips.push(entry.node);this.add(entry.node)}}token(index){const found=this.chips[index];if(!found)throw new Error(`Token row has no token ${index}.`);return found}enter(options={}){const lag=options.lag??.16;return{label:"tokens.enter",duration:options.duration??1.2,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const windows=staggered(this.chips.length,lag,ctx.t0,ctx.t1);this.chips.forEach((chip,i)=>{const[start,end]=windows[i];const y=chip.get("y");stepAt2(chip,"opacity",0,ctx.t0);stepAt2(chip,"y",y+16,ctx.t0);chip.tween("opacity",1,start,end,ctx.ease);chip.tween("y",y,start,end,ctx.ease)})}}}arcs(from,weights,options={}){const source=this.token(from).bounds();const made=new Node;const startX=source.x+source.width/2,startY=source.y-3;weights.forEach((weight,j)=>{if(j===from||weight<=.01)return;const target=this.token(j).bounds();const endX=target.x+target.width/2,endY=target.y-3;const lift=options.lift??40+Math.abs(endX-startX)*.22;const path=parseSvgPath(`M${startX} ${startY}C${startX} ${startY-lift} ${endX} ${endY-lift} ${endX} ${endY}`);const node=new Node(path).stroke(options.color??"yellow",.8+weight*(options.maxWidth??6));node.set("strokeOpacity",.2+weight*.8);made.add(node)});return made}};function tokens3(items,options={}){return new TokenRow(items,options)}function attentionMatrix(rows,columns,weights,options={}){return new Heatmap2(weights,{cell:options.cell??42,gap:options.gap??2,colors:options.colors??["surface","teal","yellow"],domain:[0,Math.max(...weights.flat())],values:options.values,rowLabels:rows,columnLabels:columns,labelSize:options.labelSize??18,columnLabelAngle:-Math.PI/4})}function place(node,x,y,align="left"){const half=node.get("px");return node.at(align==="left"?x+half:align==="right"?x-half:x,y)}function advanceWidth(node){return node.get("px")*2}var InfoBox=class extends Node{frame;accentBar=null;titleNode;subtitleNode=null;badgeNode=null;rowLabels=[];rowValues=[];meters=[];tagNodes=[];boxWidth;boxHeight;valueSize;constructor(options){super();const size=options.size??14;this.valueSize=size;const pad2=size*.8;const rows=options.rows??[];const rowHeight=size*1.56;const title=text(options.title,{size:size*1.14,weight:600,color:"ink"});const subtitle=options.subtitle?text(options.subtitle,{size:size*.86,font:"mono",color:"dim"}):null;const badgeTone=options.badgeTone??options.accent??"dim";const badge=options.badge?text(options.badge,{size:size*.78,font:"mono",color:badgeTone}):null;const labels=rows.map(row=>text(row.label,{size,color:"dim"}));const values=rows.map(row=>row.value!==void 0?text(row.value,{size,font:"mono",color:row.tone??"ink"}):null);const sparkWidth=size*3.6;const contentWidth=Math.max(advanceWidth(title)+(badge?advanceWidth(badge)+size*1.6:0),subtitle?advanceWidth(subtitle):0,...rows.map((row,i)=>advanceWidth(labels[i])+(values[i]?advanceWidth(values[i])+size*1.1:0)+(row.spark?sparkWidth+size*.6:0)),0);const width=this.boxWidth=Math.max(options.width??0,contentWidth+pad2*2);const headerHeight=size*1.4+(subtitle?size*1.2:0);const rowsHeight=rows.reduce((sum,row)=>sum+rowHeight+(row.meter!==void 0?size*.32:0),0);const tagsHeight=options.tags?.length?size*1.72:0;const height=this.boxHeight=pad2*1.5+headerHeight+(rows.length?size*.55:0)+rowsHeight+tagsHeight;const left=-width/2+pad2,right=width/2-pad2;this.frame=new Node(rectPath(-width/2,-height/2,width,height,options.radius??4)).fill(options.fill??"surface").stroke(options.border??"gridStrong",1);this.add(this.frame);if(options.accent){const bar=new Node(rectPath(-width/2,-height/2+1,2.5,height-2)).fill(options.accent);this.accentBar=bar;this.add(bar)}let y=-height/2+pad2*.75+size*.62;this.titleNode=place(title,left,y);this.add(title);if(badge){;this.badgeNode=place(badge,right,y,"right");this.add(badge)}y+=size*1.3;if(subtitle){;this.subtitleNode=place(subtitle,left,y-size*.1);this.add(subtitle);y+=size*1.2}if(rows.length){const ruleY=y-size*.38;this.add(line([-width/2+pad2,ruleY],[width/2-pad2,ruleY],{stroke:"grid",width:1}));y+=size*.5}rows.forEach((row,i)=>{place(labels[i],left,y);this.rowLabels.push(labels[i]);this.add(labels[i]);let end=right;const value=values[i];if(value){place(value,end,y,"right");this.add(value);end-=advanceWidth(value)+size*.7}this.rowValues.push(value??null);if(row.spark){const spark=sparkline(row.spark,{width:sparkWidth,height:size*.82,color:row.tone??"blue",dotted:true,weight:1.2});this.add(spark.at(end-sparkWidth/2,y-size*.1))}y+=rowHeight;if(row.meter!==void 0){const meterY=y-size*.62;this.add(line([left,meterY],[right,meterY],{stroke:"grid",width:2}));const meter=line([left,meterY],[left+(right-left)*Math.max(0,Math.min(1,row.meter)),meterY],{stroke:row.tone??"blue",width:2});meter.set("cap","butt");this.meters.push(meter);this.add(meter);y+=size*.32}});if(options.tags?.length){let x=left;const tagY=height/2-pad2*.7-size*.4;for(const tag of options.tags){const label=text(tag,{size:size*.78,font:"mono",color:"dim"});const w=advanceWidth(label)+size*.7;const chip=new Node(rectPath(x,tagY-size*.62,w,size*1.24,2)).stroke("gridStrong",1);place(label,x+size*.35,tagY);this.tagNodes.push(label);this.add(chip,label);x+=w+size*.34}}}port(side,at=0){const b=this.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;if(side==="left")return[b.x,cy+at*b.height/2];if(side==="right")return[b.x+b.width,cy+at*b.height/2];if(side==="top")return[cx+at*b.width/2,b.y];return[cx+at*b.width/2,b.y+b.height]}enter(options={}){return{label:"infoBox.enter",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;const fillTarget=this.frame.get("fillOpacity");stepAt2(this.frame,"trimTo",0,ctx.t0);stepAt2(this.frame,"fillOpacity",0,ctx.t0);this.frame.tween("trimTo",1,ctx.t0,ctx.t0+span*.65,ctx.ease);this.frame.tween("fillOpacity",fillTarget,ctx.t0+span*.2,ctx.t0+span*.8,ctx.ease);const items=this.children.filter(child=>child!==this.frame);const windows=staggered(items.length,.06,ctx.t0+span*.25,ctx.t1);items.forEach((item,i)=>{const[start,end]=windows[i];const target=item.get("opacity");stepAt2(item,"opacity",0,ctx.t0);item.tween("opacity",target,start,end,ctx.ease)})}}}setValue(row,value,options={}){const previous=this.rowValues[row];if(!previous)throw new Error(`Info box row ${row} has no value to change.`);const next=text(value,{size:this.valueSize,font:"mono",color:options.tone??"ink"});const right=previous.get("x")+previous.get("px");place(next,right,previous.get("y"),"right");const anim=morphMatching(previous,next,{duration:.5,...options});return{...anim,label:"infoBox.setValue",schedule:ctx=>{this.add(next);this.rowValues[row]=next;anim.schedule(ctx)}}}};function infoBox(options){return new InfoBox(options)}function sparkline(values,options={}){const width=options.width??80,height=options.height??20;const low=Math.min(...values),high=Math.max(...values);const span=high-low||1;const points=values.map((value,i)=>[(i/Math.max(1,values.length-1)-.5)*width,(.5-(value-low)/span)*height]);const color=options.color??"blue";const made=new Node;if(options.area){made.add(new Node(polyPath([...points,[width/2,height/2],[-width/2,height/2]],true)).fill(color,options.area))}made.add(new Node(values.length>2?smoothPath(points):polyPath(points)).stroke(color,options.weight??1.5));if(options.dotted)made.add(dot((options.weight??1.5)*1.5,color).at(points[points.length-1]));return made}var NORMALS={left:[-1,0],right:[1,0],top:[0,-1],bottom:[0,1]};function sidePoint(b,side,offset){const cx=b.x+b.width/2,cy=b.y+b.height/2;if(side==="left")return[b.x,cy+offset*b.height/2];if(side==="right")return[b.x+b.width,cy+offset*b.height/2];if(side==="top")return[cx+offset*b.width/2,b.y];return[cx+offset*b.width/2,b.y+b.height]}function chooseSides(a,b){const gapX=Math.max(b.x-(a.x+a.width),a.x-(b.x+b.width));const gapY=Math.max(b.y-(a.y+a.height),a.y-(b.y+b.height));const ax=a.x+a.width/2,ay=a.y+a.height/2,bx=b.x+b.width/2,by=b.y+b.height/2;if(gapX>=gapY)return bx>=ax?["right","left"]:["left","right"];return by>=ay?["bottom","top"]:["top","bottom"]}function fillet(points,radius){let d=`M${points[0][0]} ${points[0][1]}`;for(let i=1;i<points.length-1;i++){const prev=points[i-1],at=points[i],next=points[i+1];const l0=Math.hypot(at[0]-prev[0],at[1]-prev[1]),l1=Math.hypot(next[0]-at[0],next[1]-at[1]);const r=Math.min(radius,l0/2,l1/2);if(r<.5){d+=`L${at[0]} ${at[1]}`;continue}const p0x=at[0]-(at[0]-prev[0])/(l0||1)*r,p0y=at[1]-(at[1]-prev[1])/(l0||1)*r;const p1x=at[0]+(next[0]-at[0])/(l1||1)*r,p1y=at[1]+(next[1]-at[1])/(l1||1)*r;d+=`L${p0x} ${p0y}Q${at[0]} ${at[1]} ${p1x} ${p1y}`}const last=points[points.length-1];return parseSvgPath(`${d}L${last[0]} ${last[1]}`)}var Connector2=class extends Node{fromEnd;toEnd;options;pulses=[];plate=null;caption=null;constructor(from,to2,options={}){super([]);this.fromEnd=from;this.toEnd=to2;this.options=options;this.base.stroke=toPaint(options.color??"dim");this.base.strokeWidth=options.width??1.6;this.draw=time=>this.build(time)}anchors(){const{fromEnd,toEnd,options}=this;const gap=options.gap??3;const boxOf=end=>end instanceof Node?end.bounds():{x:end[0],y:end[1],width:0,height:0};const a=boxOf(fromEnd),b=boxOf(toEnd);const[autoFrom,autoTo]=chooseSides(a,b);const sideFrom=options.from??autoFrom,sideTo=options.to??autoTo;const anchor=(end,box,side,offset)=>{const normal=NORMALS[side];if(!(end instanceof Node))return{point:end,normal};const[x,y]=sidePoint(box,side,offset);return{point:[x+normal[0]*gap,y+normal[1]*gap],normal}};return[anchor(fromEnd,a,sideFrom,options.fromOffset??0),anchor(toEnd,b,sideTo,options.toOffset??0)]}routeNow(){const[a,b]=this.anchors();const route=this.options.route??"curve";if(route==="straight")return polyPath([a.point,b.point]);if(route==="ortho"){const r=this.options.radius??8;const horizontalA=a.normal[0]!==0,horizontalB=b.normal[0]!==0;if(horizontalA&&horizontalB){const mid=(a.point[0]+b.point[0])/2;return fillet([a.point,[mid,a.point[1]],[mid,b.point[1]],b.point],r)}if(!horizontalA&&!horizontalB){const mid=(a.point[1]+b.point[1])/2;return fillet([a.point,[a.point[0],mid],[b.point[0],mid],b.point],r)}const corner=horizontalA?[b.point[0],a.point[1]]:[a.point[0],b.point[1]];return fillet([a.point,corner,b.point],r)}const distance=Math.hypot(b.point[0]-a.point[0],b.point[1]-a.point[1]);const reach=Math.max(18,distance*(this.options.curvature??.42));const c1=[a.point[0]+a.normal[0]*reach,a.point[1]+a.normal[1]*reach];const c2=[b.point[0]+b.normal[0]*reach,b.point[1]+b.normal[1]*reach];return parseSvgPath(`M${a.point[0]} ${a.point[1]}C${c1[0]} ${c1[1]} ${c2[0]} ${c2[1]} ${b.point[0]} ${b.point[1]}`)}build(time){const inverse=this.parent&&this.parent!==null?invert(this.worldMatrix()):IDENTITY;const whole=transformPath(this.routeNow(),inverse);const length=pathLength(whole);if(length<1)return[];const progress=this.get("trimTo");const options=this.options;const stroke=this.get("stroke");const width=this.get("strokeWidth");const out=[];const tip=options.tip??true;const tipSize=tip?options.tipSize??Math.max(7,width*4.4):0;const shaftEnd=progress*(1-tipSize/length);const shaft=trimPath(whole,this.get("trimFrom"),shaftEnd);const color=stroke??toPaint("dim");if(shaft.length){const node=new Node(shaft).stroke(color,width);if(options.dash||options.flow){node.dash(options.dash??[6,6],options.flow?-time*options.flow:0)}node.set("strokeOpacity",this.get("strokeOpacity"));out.push(node)}if(tip&&progress>.02){const[x,y]=pointAt(whole,progress);const[ux,uy]=tangentAt(whole,Math.min(.997,progress));const half=tipSize*.38;const bx=x-ux*tipSize,by=y-uy*tipSize;out.push(new Node(polyPath([[x,y],[bx-uy*half,by+ux*half],[bx+uy*half,by-ux*half]],true)).fill(color))}for(const entry of this.pulses){if(time<entry.t0||time>=entry.t1)continue;const a=entry.ease((time-entry.t0)/(entry.t1-entry.t0));const from=Math.max(0,a*(1+entry.length)-entry.length),to2=Math.min(1,a*(1+entry.length));const lit=trimPath(whole,from,to2);if(lit.length)out.push(new Node(lit).stroke(entry.color,entry.width).glow(entry.glow))}if(options.label&&progress>.5){const size=options.labelSize??12;this.caption??=text(options.label,{size,font:"mono",color:options.labelColor??"dim"});const textWidth=advanceWidth(this.caption);const pad2=size*.35;this.plate??=new Node(rectPath(-textWidth/2-pad2,-size*.72,textWidth+pad2*2,size*1.44,2)).fill(options.labelBackground??"bg");const[mx,my]=pointAt(whole,options.labelAt??.5);const fade2=Math.min(1,(progress-.5)*4);out.push(this.plate.at(mx,my).opacity(fade2),this.caption.at(mx,my).opacity(fade2))}return out}pulse(options={}){return{label:"connector.pulse",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);this.pulses.push({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,color:options.color??"yellow",length:options.length??.22,width:options.width??this.get("strokeWidth")+1.2,glow:options.glow??6})}}}pointNow(fraction=.5){return pointAt(this.routeNow(),fraction)}};function connector(from,to2,options={}){return new Connector2(from,to2,options)}function legend(items,options={}){const size=options.size??13;const row=(options.direction??"row")==="row";const gap=options.gap??(row?size*1.5:size*.6);const keyWidth=size*1.5;const made=new Node;let cursor=0;const entries=[];for(const item of items){const color=item.color??"dim";const kind=item.kind??"swatch";const key=kind==="line"?line([-keyWidth/2,0],[keyWidth/2,0],{stroke:color,width:2.2}):kind==="dash"?line([-keyWidth/2,0],[keyWidth/2,0],{stroke:color,width:2,dash:[4,3.5]}):kind==="dot"?dot(size*.32,color):kind==="ring"?circle(size*.32,{stroke:color,width:1.6}):new Node(rectPath(-size*.42,-size*.42,size*.84,size*.84,1.5)).fill(color);const caption=text(item.label,{size,color:"dim"});const width=keyWidth+size*.5+advanceWidth(caption);const entry=new Node;entry.add(key.at(keyWidth/2,0));place(caption,keyWidth+size*.5,0);entry.add(caption);entries.push({node:entry,width})}const total=entries.reduce((sum,entry)=>sum+entry.width,0)+gap*Math.max(0,entries.length-1);const widest=Math.max(0,...entries.map(entry=>entry.width));const step=size*1.2+gap;entries.forEach((entry,i)=>{if(row){entry.node.at(-total/2+cursor,0);cursor+=entry.width+gap}else{entry.node.at(-widest/2,(i-(entries.length-1)/2)*step)}made.add(entry.node)});return made}var Callout=class extends Node{leader;marker;body;titleNode=null;constructor(target,body,options={}){super();const size=options.size??15;const color=options.color??"yellow";const side=options.side??"right";const distance=options.distance??72;const wrap=options.width??280;const normal=NORMALS[side];const box=target instanceof Node?target.bounds():{x:target[0],y:target[1],width:0,height:0};const anchor=target instanceof Node?sidePoint(box,side,0):target;const title=options.title?text(options.title,{size,weight:600,color}):null;const copy=text(body,{size:size*.94,color:options.bodyColor??"dim",maxWidth:wrap,leading:1.36});const titleHeight=title?size*1.42:0;const blockWidth=Math.max(copy.width,title?advanceWidth(title):0);const copyHeight=copy.height;const blockHeight=titleHeight+copyHeight;const offset=options.offset??0;const blockLeft=side==="right"?anchor[0]+distance:side==="left"?anchor[0]-distance-blockWidth:anchor[0]-blockWidth/2+offset;const blockTop=side==="bottom"?anchor[1]+distance:side==="top"?anchor[1]-distance-blockHeight:anchor[1]-blockHeight/2+offset;if(options.plate){const pad2=size*.5;this.add(new Node(rectPath(blockLeft-pad2,blockTop-pad2,blockWidth+pad2*2,blockHeight+pad2*2,3)).fill("bg",.86))}if(title){;this.titleNode=place(title,blockLeft,blockTop+size*.62);this.add(title)}copy.moveTo([blockLeft+copy.width/2,blockTop+titleHeight+copyHeight/2]);this.body=copy;this.add(copy);const reach=side==="right"?[blockLeft-8,blockTop+blockHeight/2]:side==="left"?[blockLeft+blockWidth+8,blockTop+blockHeight/2]:side==="bottom"?[blockLeft+blockWidth/2,blockTop-8]:[blockLeft+blockWidth/2,blockTop+blockHeight+8];const elbow=normal[0]!==0?[anchor[0]+normal[0]*distance*.45,reach[1]]:[reach[0],anchor[1]+normal[1]*distance*.45];this.leader=new Node(polyPath([anchor,elbow,reach])).stroke(color,1.25);this.marker=dot(3,color).at(anchor);this.add(this.leader,this.marker)}enter(options={}){return{label:"callout.enter",duration:options.duration??.9,ease:options.ease,schedule:ctx=>{reveal(this,ctx.t0,ctx.stage);const span=ctx.t1-ctx.t0;stepAt2(this.marker,"opacity",0,ctx.t0);this.marker.tween("opacity",1,ctx.t0,ctx.t0+span*.2,ctx.ease);stepAt2(this.leader,"trimTo",0,ctx.t0);this.leader.tween("trimTo",1,ctx.t0,ctx.t0+span*.55,ctx.ease);for(const child of this.children){if(child===this.marker||child===this.leader)continue;const target=child.get("opacity");stepAt2(child,"opacity",0,ctx.t0);child.tween("opacity",target,ctx.t0+span*.42,ctx.t1,ctx.ease)}}}}};function callout(target,body,options={}){return new Callout(target,body,options)}function list2(target){return Array.isArray(target)?[...target]:[target]}function glyphsOf(target){return list2(target).flatMap(node=>node.leaves().filter(leaf=>leaf.get("path")))}function typewriter(target,options={}){const glyphs=glyphsOf(target);return{label:"typewriter",duration:options.duration??Math.max(.5,glyphs.length*.035),ease:options.ease??linear,schedule(ctx){for(const node of list2(target))reveal(node,ctx.t0,ctx.stage);const leaves=glyphsOf(target);if(leaves.length===0)return;const span=ctx.t1-ctx.t0;let cursor=null;if(options.cursor){const first=leaves[0].bounds();const height=first.height*1.35||24;cursor=new Node(rectPath(0,-height/2,Math.max(3,height*.1),height)).fill(options.cursorColor??"ink");ctx.stage.add(cursor)}leaves.forEach((leaf,i)=>{const at=ctx.t0+span*ctx.ease(i/leaves.length);const opacity=leaf.get("opacity");stepAt2(leaf,"opacity",0,ctx.t0);stepAt2(leaf,"opacity",opacity,at);if(cursor){clock.now=at;const b=leaf.bounds();stepAt2(cursor,"x",b.x+b.width+3,at);stepAt2(cursor,"y",b.y+b.height/2,at);clock.now=ctx.t0}});if(cursor)stepAt2(cursor,"visible",false,ctx.t1)}}}function wipe(target,options={}){return{label:"wipe",duration:options.duration??1.2,ease:options.ease??smooth2,schedule(ctx){const from=options.from??"left";for(const node of list2(target))reveal(node,ctx.t0,ctx.stage);const leaves=list2(target).flatMap(node=>node.leaves());const position2=leaf=>{const b=leaf.bounds();const cx=b.x+b.width/2,cy=b.y+b.height/2;return from==="left"?cx:from==="right"?-cx:from==="top"?cy:-cy};const values=leaves.map(position2);const low=Math.min(...values),high=Math.max(...values);const soft=options.soft??.25;const travel=options.travel??0;const span=ctx.t1-ctx.t0;const dx=from==="left"?-travel:from==="right"?travel:0;const dy=from==="top"?-travel:from==="bottom"?travel:0;leaves.forEach((leaf,i)=>{const fraction=high>low?(values[i]-low)/(high-low):0;const start=ctx.t0+span*(1-soft)*ctx.ease(fraction);const end=start+span*soft;const opacity=leaf.get("opacity");stepAt2(leaf,"opacity",0,ctx.t0);leaf.tween("opacity",opacity,start,end,smooth2);if(travel){const x=leaf.get("x"),y=leaf.get("y");stepAt2(leaf,"x",x+dx,ctx.t0);stepAt2(leaf,"y",y+dy,ctx.t0);leaf.tween("x",x,start,end,smooth2);leaf.tween("y",y,start,end,smooth2)}})}}}var Counter=class extends Node{value;constructor(initial=0,options={}){super();this.value=new Value(initial);const digits=options.digits??0;const format=new Intl.NumberFormat("en-US",{minimumFractionDigits:digits,maximumFractionDigits:digits,useGrouping:options.grouped??true});const inner=dynamic(()=>{const body=`${options.prefix??""}${format.format(this.value.value)}${options.suffix??""}`;return text(body,{size:options.size??48,color:options.color??"ink",font:options.font??"mono",weight:options.weight??400})});this.add(inner)}};function counter(initial=0,options={}){return new Counter(initial,options)}function countUp(target,to2,options={}){const value=target instanceof Counter?target.value:target;return{label:"countUp",duration:options.duration??1.2,ease:options.ease,schedule(ctx){if(target instanceof Counter)reveal(target,ctx.t0,ctx.stage);tweenValue(value,to2,ctx.t0,ctx.t1,ctx.ease)}}}function spin(node,rate,options={}){return{label:"spin",duration:options.duration??2,ease:options.ease??linear,schedule(ctx){reveal(node,ctx.t0,ctx.stage);clock.now=ctx.t0;node.pivotAt(options.about??node.center);const start=node.get("rotation");const seconds=ctx.t1-ctx.t0;node.tween("rotation",start+rate*seconds,ctx.t0,ctx.t1,ctx.ease)}}}function swap(a,b,options={}){return{label:"swap",duration:options.duration??.9,ease:options.ease,schedule(ctx){reveal(a,ctx.t0,ctx.stage);reveal(b,ctx.t0,ctx.stage);clock.now=ctx.t0;const ca=a.center,cb=b.center;const lift=options.lift??Math.max(60,Math.hypot(cb[0]-ca[0],cb[1]-ca[1])*.3);const travel=(node,from,to2,sign)=>{const inverse=node.parent?invert(node.parent.worldMatrix()):[1,0,0,1,0,0];const x0=node.get("x"),y0=node.get("y");const[lfx,lfy]=apply(inverse,from[0],from[1]),[ltx,lty]=apply(inverse,to2[0],to2[1]);const x1=x0+ltx-lfx,y1=y0+lty-lfy;node.track("x").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:x1,at:t=>x0+(x1-x0)*t});node.track("y").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:y1,at:t=>y0+(y1-y0)*t-sign*lift*4*t*(1-t)})};travel(a,ca,cb,1);travel(b,cb,ca,-1)}}}function highlightSweep(target,options={}){const mark=new Node([]);const nodes=list2(target);return{mark,label:"highlightSweep",duration:options.duration??.7,ease:options.ease,schedule(ctx){let x0=Infinity,y0=Infinity,x1=-Infinity,y1=-Infinity;for(const node of nodes){const b=node.bounds();x0=Math.min(x0,b.x);y0=Math.min(y0,b.y);x1=Math.max(x1,b.x+b.width);y1=Math.max(y1,b.y+b.height)}const pad2=options.pad??6;const left=x0-pad2,top=y0-pad2,width=x1-x0+pad2*2,height=y1-y0+pad2*2;const radius=options.radius??3;const color=options.color??"yellow";mark.base.fill=toPaint(color);mark.base.fillOpacity=options.opacity??.26;const parent=ctx.stage.root;parent.add(mark);const first=nodes[0];let anchor=first;while(anchor.parent&&anchor.parent!==parent)anchor=anchor.parent;const index=parent.children.indexOf(anchor);parent.children.splice(parent.children.indexOf(mark),1);parent.children.splice(index>=0?index:parent.children.length,0,mark);const fromRight=options.from==="right";const shape2=a=>{const w=Math.max(.01,width*a);return rectPath(fromRight?left+width-w:left,top,w,height,radius)};mark.track("path").step(ctx.t0,shape2(0));mark.track("path").add({t0:ctx.t0,t1:ctx.t1,ease:ctx.ease,to:shape2(1),at:shape2})}}}var tokens4=text2=>text2.toLowerCase().replace(/[^a-z0-9.]+/g," ").split(" ").map(token=>token.replace(/^\.+|\.+$/g,"")).filter(Boolean);function captionLines(text2,length=74){const lines=[];for(const sentence of text2.match(/[^.?!]+(?:[.?!]+(?=\s|$)|\.\d[^.?!]*[.?!]?|$)/g)??[]){let line2="";for(const word of sentence.split(/\s+/).filter(Boolean)){if(line2&&line2.length+word.length+1>length){lines.push(line2);line2=word}else{line2=line2?`${line2} ${word}`:word}}if(line2)lines.push(line2)}return lines}var SceneClock=class{constructor(stage,id,start,end,beats){this.stage=stage;this.id=id;this.start=start;this.end=end;this.beats=beats}stage;id;start;end;beats;cue(phrase,beat){const want=tokens4(phrase);if(want.length===0)throw new Error(`narration: scene "${this.id}": a cue needs at least one word`);if(beat!==void 0&&!this.beats[beat])throw new Error(`narration: scene "${this.id}" has no beat ${beat}`);const list3=beat===void 0?this.beats:[this.beats[beat]];for(const placed of list3){const spoken=placed.words.flatMap(word=>tokens4(word.text).map(token=>({token,start:word.start,end:word.end})));for(let i=0;i+want.length<=spoken.length;i++){if(want.every((token,j)=>spoken[i+j].token===token)){return{start:placed.start+spoken[i].start,end:placed.start+spoken[i+want.length-1].end}}}}const where=beat===void 0?"":` in beat ${beat}`;throw new Error(`narration: scene "${this.id}": the voice never says "${phrase}"${where}`)}on(phrase,build,offset=0,beat){this.stage.at(Math.max(0,this.cue(phrase,beat).start+offset),build);return this}after(phrase,build,offset=0,beat){this.stage.at(Math.max(0,this.cue(phrase,beat).end+offset),build);return this}onBeat(index,build,offset=0){const beat=this.beats[index];if(!beat)throw new Error(`narration: scene "${this.id}" has no beat ${index}`);this.stage.at(Math.max(0,beat.start+offset),build);return this}at(seconds,build){this.stage.at(Math.max(0,this.start+seconds),build);return this}clear(nodes,lead=.24,duration=.26){this.stage.at(this.end-lead,()=>this.stage.play(...nodes.map(node=>fade(node,0,{duration}))));return this}};var Narration=class{scenes;duration;lead;gap;constructor(stage,timing,options={}){this.lead=options.lead??timing.lead??.6;this.gap=options.gap??timing.gap??.4;if(!(this.lead>=0)||!(this.gap>=0))throw new Error("narration: lead and gap must be zero or more seconds");const seen=new Set;const scenes=[];let now=this.lead;let last=now;for(const scene of timing.scenes){if(seen.has(scene.id))throw new Error(`narration: two scenes are named "${scene.id}"`);seen.add(scene.id);const start=now;const beats=[];for(const beat of scene.beats){if(!(beat.duration>0))throw new Error(`narration: scene "${scene.id}" has a beat without a measured duration: "${beat.say}"`);const hold2=beat.hold??0;beats.push({start:now,end:now+beat.duration,until:now+beat.duration+hold2,text:beat.say,words:beat.words??[]});now+=beat.duration+hold2}scenes.push(new SceneClock(stage,scene.id,start,now,beats));if(options.chapters!==false&&scene.title)stage.chapters.push({title:scene.title,time:scenes.length===1?0:start});if(options.captions!==false){for(const beat of beats){const lines=captionLines(beat.text,options.captionLength);const total=lines.reduce((sum,line2)=>sum+line2.length,0);let t0=beat.start;for(const line2 of lines){const t1=t0+(beat.end-beat.start)*line2.length/total;stage.captions.push({t0,t1,text:line2});t0=t1}}}last=now;now+=this.gap}this.scenes=scenes;this.duration=last;stage.at(last,()=>{})}scene(id){const found=this.scenes.find(scene=>scene.id===id);if(!found)throw new Error(`narration: no scene "${id}". The scenes are: ${this.scenes.map(scene=>scene.id).join(", ")}`);return found}placements(){return this.scenes.flatMap(scene=>scene.beats.map((beat,index)=>({scene:scene.id,beat:index,start:beat.start,end:beat.end})))}};function narration(stage,timing,options={}){return new Narration(stage,timing,options)}var read3=value=>typeof value==="function"?value():value;var normalize=v=>{const length=Math.hypot(v[0],v[1],v[2])||1;return[v[0]/length,v[1]/length,v[2]/length]};var View3D=class{ops=[];depths=[];rx=0;ry=0;ux=0;uy=0;uz=0;dx=0;dy=0;dz=0;fx=0;fy=0;fz=0;distance=12;unit=100;perspective=true;matrix=[1,0,0,1,0,0];alpha=1;scale=1;light=[0,0,1];half=[0,0,1];ambient=.4;shine=.2;fog=0;fogColor=[0,0,0,1];depthRange=1;brightness=1;px=0;py=0;pz=0;ps=1;project(x,y,z){const vx=x-this.fx,vy=y-this.fy,vz=z-this.fz;const cx=vx*this.rx+vy*this.ry;const cy=vx*this.ux+vy*this.uy+vz*this.uz;const cz=vx*this.dx+vy*this.dy+vz*this.dz;let s=1;if(this.perspective){const gap=this.distance-cz;if(gap<=.05)return false;s=this.distance/gap}const sx=cx*this.unit*s,sy=-cy*this.unit*s;const m=this.matrix;this.px=m[0]*sx+m[2]*sy+m[4];this.py=m[1]*sx+m[3]*sy+m[5];this.pz=cz;this.ps=s;return true}screen(x,y,z){const vx=x-this.fx,vy=y-this.fy,vz=z-this.fz;const cx=vx*this.rx+vy*this.ry;const cy=vx*this.ux+vy*this.uy+vz*this.uz;const cz=vx*this.dx+vy*this.dy+vz*this.dz;let s=1;if(this.perspective){const gap=this.distance-cz;if(gap<=.05)return null;s=this.distance/gap}return[cx*this.unit*s,-cy*this.unit*s]}fogged(r,g,b,depth){if(this.fog<=0)return[r,g,b,1];const t=Math.max(0,Math.min(1,-depth/this.depthRange*this.fog));return[r+(this.fogColor[0]-r)*t,g+(this.fogColor[1]-g)*t,b+(this.fogColor[2]-b)*t,1]}push(op,depth){this.ops.push(op);this.depths.push(depth)}};function strokeOp(path,color,alpha3,width,glow=0,cap="round"){return{kind:"path",path,strokePath:path,fill:null,fillAlpha:0,stroke:color,strokeAlpha:alpha3,strokeWidth:width,cap,join:"round",dash:null,dashOffset:0,glow,glowColor:null,blend:"normal"}}function fillOp(path,color,alpha3,stroke,strokeAlpha,strokeWidth){return{kind:"path",path,strokePath:path,fill:color,fillAlpha:alpha3,stroke,strokeAlpha,strokeWidth,cap:"round",join:"round",dash:null,dashOffset:0,glow:0,glowColor:null,blend:"normal"}}function lineRing(x0,y0,x1,y1){const dx=x1-x0,dy=y1-y0;const p=new Float64Array(8);p[0]=x0;p[1]=y0;p[2]=x0+dx/3;p[3]=y0+dy/3;p[4]=x0+dx*2/3;p[5]=y0+dy*2/3;p[6]=x1;p[7]=y1;return{p,closed:false,straight:true}}function polygonRing(points){const count=points.length/2;const p=new Float64Array(2+count*6);p[0]=points[0];p[1]=points[1];let o=2;for(let i=0;i<count;i++){const ax=points[i*2],ay=points[i*2+1];const bx=points[(i+1)%count*2],by=points[(i+1)%count*2+1];p[o++]=ax+(bx-ax)/3;p[o++]=ay+(by-ay)/3;p[o++]=ax+(bx-ax)*2/3;p[o++]=ay+(by-ay)*2/3;p[o++]=bx;p[o++]=by}return{p,closed:true,straight:true}}var KAPPA2=.5522847498307936;function circleRing(cx,cy,r){const k=r*KAPPA2;return{closed:true,p:Float64Array.of(cx+r,cy,cx+r,cy+k,cx+k,cy+r,cx,cy+r,cx-k,cy+r,cx-r,cy+k,cx-r,cy,cx-r,cy-k,cx-k,cy-r,cx,cy-r,cx+k,cy-r,cx+r,cy-k,cx+r,cy)}}var Object3D=class extends Node{constructor(){super([])}labelsNow(_view){return[]}objectAlpha(view){return view.alpha*this.get("opacity")}};var Scene3D=class extends Node{phi;theta;distance;unit;focusX;focusY;focusZ;orthographic;settings;spins=[];openSpin=null;constructor(options={}){super();this.settings=options;this.phi=new Value(options.phi??1.15);this.theta=new Value(options.theta??-1);this.distance=new Value(options.distance??14);this.unit=new Value(options.unit??120);this.focusX=new Value(options.focus?.[0]??0);this.focusY=new Value(options.focus?.[1]??0);this.focusZ=new Value(options.focus?.[2]??0);this.orthographic=options.perspective===false;this.rawOps=(matrix2,alpha3,ops)=>this.render(matrix2,alpha3,ops);this.draw=time=>{const view=this.view(this.worldless,1,time);return this.children.flatMap(child=>child instanceof Object3D&&child.get("visible")?child.labelsNow(view):[])}}worldless=[1,0,0,1,0,0];view(matrix2,alpha3,time){const view=new View3D;const phi=this.phi.value;let theta=this.theta.value;for(const spin2 of this.spins){if(time>spin2.from)theta+=(Math.min(time,spin2.to)-spin2.from)*spin2.rate}const sinP=Math.sin(phi),cosP=Math.cos(phi),sinT=Math.sin(theta),cosT=Math.cos(theta);view.rx=-sinT;view.ry=cosT;view.ux=-cosP*cosT;view.uy=-cosP*sinT;view.uz=sinP;view.dx=sinP*cosT;view.dy=sinP*sinT;view.dz=cosP;view.fx=this.focusX.value;view.fy=this.focusY.value;view.fz=this.focusZ.value;view.distance=this.distance.value;view.unit=this.unit.value;view.perspective=!this.orthographic;view.matrix=matrix2;view.alpha=alpha3;view.scale=Math.sqrt(Math.abs(matrix2[0]*matrix2[3]-matrix2[1]*matrix2[2]));const light=normalize(this.settings.light??[-.45,-.55,.85]);view.light=light;view.half=normalize([light[0]+view.dx,light[1]+view.dy,light[2]+view.dz]);view.ambient=this.settings.ambient??.26;view.shine=this.settings.shine??.2;view.fog=this.settings.fog??.6;const background=parseColor("bg");view.fogColor=this.settings.fogColor?solidColor(this.settings.fogColor):background;view.depthRange=Math.max(3,view.distance*.5);view.brightness=this.settings.brightness??(background[0]+background[1]+background[2]<200?.8:1);return view}render(matrix2,alpha3,ops){const time=clock.now;const view=this.view(matrix2,alpha3,time);for(const child of this.children){if(child instanceof Object3D&&child.get("visible"))child.emit(view,time)}const count=view.ops.length;const order=new Uint32Array(count);for(let i=0;i<count;i++)order[i]=i;const depths=view.depths;order.sort((a,b)=>depths[a]-depths[b]);for(let i=0;i<count;i++)ops.push(view.ops[order[i]])}orbit(target,options={}){return{label:"camera3d",duration:options.duration??2,ease:options.ease,schedule:ctx=>{if(target.phi!==void 0)tweenValue(this.phi,target.phi,ctx.t0,ctx.t1,ctx.ease);if(target.theta!==void 0)tweenValue(this.theta,target.theta,ctx.t0,ctx.t1,ctx.ease);if(target.distance!==void 0)tweenValue(this.distance,target.distance,ctx.t0,ctx.t1,ctx.ease);if(target.unit!==void 0)tweenValue(this.unit,target.unit,ctx.t0,ctx.t1,ctx.ease);if(target.focus){tweenValue(this.focusX,target.focus[0],ctx.t0,ctx.t1,ctx.ease);tweenValue(this.focusY,target.focus[1],ctx.t0,ctx.t1,ctx.ease);tweenValue(this.focusZ,target.focus[2],ctx.t0,ctx.t1,ctx.ease)}}}}spin(rate=.12){this.stopSpin();this.openSpin={from:clock.now,to:Infinity,rate};this.spins.push(this.openSpin);return this}stopSpin(){if(this.openSpin)this.openSpin.to=clock.now;this.openSpin=null;return this}stagePoint(point){const view=this.view(this.worldMatrix(),1,clock.now);return view.project(point[0],point[1],point[2])?[view.px,view.py]:[0,0]}};function scene3d(options={}){return new Scene3D(options)}var Surface3D=class extends Object3D{constructor(fn,uRange,vRange,options={}){super();this.fn=fn;this.uRange=uRange;this.vRange=vRange;this.options=options;const res=options.resolution??40;this.nu=typeof res==="number"?res:res[0];this.nv=typeof res==="number"?res:res[1];const vertices=(this.nu+1)*(this.nv+1);this.positions=new Float64Array(vertices*3);this.normals=new Float64Array(this.nu*this.nv*3);this.vertexNormals=new Float64Array(vertices*3);this.shadingNormals=new Float64Array(this.nu*this.nv*3);this.faceColors=new Float32Array(this.nu*this.nv*3);this.screenX=new Float64Array(vertices);this.screenY=new Float64Array(vertices);this.screenZ=new Float64Array(vertices);this.valid=new Uint8Array(vertices);this.meshColor=options.mesh?solidColor(options.mesh):null;if(options.colors){const palette=options.colors.map(c=>solidColor(c));this.ramp=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c])}if(options.checker)this.checkerColors=[solidColor(options.checker[0]),solidColor(options.checker[1])];if(options.color||!options.colors&&!options.checker&&!options.colorAt){this.base.fill=toPaint(options.color??"blue")}}fn;uRange;vRange;options;nu;nv;positions;normals;vertexNormals;shadingNormals;faceColors;computedFor=-Infinity;screenX;screenY;screenZ;valid;meshColor;ramp=null;checkerColors=null;compute(time){const{nu,nv,positions,normals,faceColors,fn,uRange,vRange,options}=this;let o=0;let zMin=Infinity,zMax=-Infinity;for(let i=0;i<=nu;i++){const u=uRange[0]+(uRange[1]-uRange[0])*i/nu;for(let j=0;j<=nv;j++){const v=vRange[0]+(vRange[1]-vRange[0])*j/nv;const p=fn(u,v,time);positions[o++]=p[0];positions[o++]=p[1];positions[o++]=p[2];if(p[2]<zMin)zMin=p[2];if(p[2]>zMax)zMax=p[2]}}const stride=nv+1;const vertexNormals=this.vertexNormals;vertexNormals.fill(0);for(let i=0;i<nu;i++){for(let j=0;j<nv;j++){const a=(i*stride+j)*3,b=((i+1)*stride+j)*3;const c=((i+1)*stride+j+1)*3,d=(i*stride+j+1)*3;const ex=positions[c]-positions[a],ey=positions[c+1]-positions[a+1],ez=positions[c+2]-positions[a+2];const fx=positions[d]-positions[b],fy=positions[d+1]-positions[b+1],fz=positions[d+2]-positions[b+2];let nx=ey*fz-ez*fy,ny=ez*fx-ex*fz,nz=ex*fy-ey*fx;const length=Math.hypot(nx,ny,nz)||1;nx/=length;ny/=length;nz/=length;if(options.outwardFrom){const[ox,oy,oz]=options.outwardFrom;const mx=(positions[a]+positions[c])/2-ox,my=(positions[a+1]+positions[c+1])/2-oy,mz=(positions[a+2]+positions[c+2])/2-oz;if(nx*mx+ny*my+nz*mz<0){nx=-nx;ny=-ny;nz=-nz}}const f=(i*nv+j)*3;normals[f]=nx;normals[f+1]=ny;normals[f+2]=nz;for(const vertex of[a/3,b/3,c/3,d/3]){vertexNormals[vertex*3]+=nx;vertexNormals[vertex*3+1]+=ny;vertexNormals[vertex*3+2]+=nz}if(this.ramp||this.checkerColors||options.colorAt){let color;if(options.colorAt){const mx=(positions[a]+positions[c])/2,my=(positions[a+1]+positions[c+1])/2,mz=(positions[a+2]+positions[c+2])/2;color=options.colorAt(mx,my,mz,(i+.5)/nu,(j+.5)/nv)}else if(this.checkerColors){color=this.checkerColors[(i+j)%2]}else{const mz=(positions[a+2]+positions[c+2]+positions[b+2]+positions[d+2])/4;color=sampleStops(this.ramp,zMax>zMin?(mz-zMin)/(zMax-zMin):0)}faceColors[f]=color[0];faceColors[f+1]=color[1];faceColors[f+2]=color[2]}}}const shading=this.shadingNormals;for(let i=0;i<nu;i++){for(let j=0;j<nv;j++){const a=(i*stride+j)*3,b=((i+1)*stride+j)*3;const c=((i+1)*stride+j+1)*3,d=(i*stride+j+1)*3;let sx=0,sy=0,sz=0;for(const v of[a,b,c,d]){sx+=vertexNormals[v];sy+=vertexNormals[v+1];sz+=vertexNormals[v+2]}const length=Math.hypot(sx,sy,sz)||1;const f=(i*nv+j)*3;shading[f]=sx/length;shading[f+1]=sy/length;shading[f+2]=sz/length}}}emit(view,time){const{options,nu,nv,normals,shadingNormals,faceColors,screenX,screenY,screenZ,valid}=this;const alpha3=this.objectAlpha(view)*(options.opacity??1)*this.get("fillOpacity");if(alpha3<=.002)return;if(options.animate?this.computedFor!==time:this.computedFor===-Infinity){this.compute(options.animate?time:0);this.computedFor=time}const positions=this.positions;const stride=nv+1;const count=(nu+1)*(nv+1);for(let i=0;i<count;i++){const k=i*3;if(view.project(positions[k],positions[k+1],positions[k+2])){screenX[i]=view.px;screenY[i]=view.py;screenZ[i]=view.pz;valid[i]=1}else{valid[i]=0}}const solid4=this.ramp||this.checkerColors||options.colorAt?null:solidOf(this.get("fill"));const shaded=options.shaded??true;const opaque=alpha3>=.995;const reveal2=this.get("trimTo");const rows=Math.ceil(reveal2*nu);const{light,half,ambient,shine,brightness,dx,dy,dz}=view;const cull=options.cull??false;const meshColor=this.meshColor;const meshAlpha=(options.meshOpacity??.35)*alpha3;const meshWidth=(options.meshWidth??1)*view.scale;const seam=.55*view.scale;for(let i=0;i<rows;i++){for(let j=0;j<nv;j++){const a=i*stride+j,b=(i+1)*stride+j,c=(i+1)*stride+j+1,d=i*stride+j+1;if(!valid[a]||!valid[b]||!valid[c]||!valid[d])continue;const f=(i*nv+j)*3;const facing=normals[f]*dx+normals[f+1]*dy+normals[f+2]*dz;if(facing<0&&cull)continue;const flip=facing<0?-1:1;const nx=shadingNormals[f]*flip,ny=shadingNormals[f+1]*flip,nz=shadingNormals[f+2]*flip;let r,g,bl;if(solid4){r=solid4[0];g=solid4[1];bl=solid4[2]}else{r=faceColors[f];g=faceColors[f+1];bl=faceColors[f+2]}if(shaded){const wrap=.5+.5*(nx*light[0]+ny*light[1]+nz*light[2]);const diffuse=(ambient+(1-ambient)*wrap*wrap)*brightness;const spec=shine>0?shine*Math.pow(Math.max(0,nx*half[0]+ny*half[1]+nz*half[2]),42)*255:0;r=Math.min(255,r*diffuse+spec);g=Math.min(255,g*diffuse+spec);bl=Math.min(255,bl*diffuse+spec)}const depth=(screenZ[a]+screenZ[b]+screenZ[c]+screenZ[d])/4;const color=view.fogged(r,g,bl,depth);let ax=screenX[a],ay=screenY[a],bx=screenX[b],by=screenY[b];let cx=screenX[c],cy=screenY[c],ex=screenX[d],ey=screenY[d];if(opaque&&!meshColor){const mx=(ax+bx+cx+ex)/4,my=(ay+by+cy+ey)/4;const grow2=(x,y)=>seam/(Math.hypot(x-mx,y-my)||1);const ka=grow2(ax,ay),kb=grow2(bx,by),kc=grow2(cx,cy),ke=grow2(ex,ey);ax+=(ax-mx)*ka;ay+=(ay-my)*ka;bx+=(bx-mx)*kb;by+=(by-my)*kb;cx+=(cx-mx)*kc;cy+=(cy-my)*kc;ex+=(ex-mx)*ke;ey+=(ey-my)*ke}const ring2=polygonRing([ax,ay,bx,by,cx,cy,ex,ey]);view.push(meshColor?fillOp([ring2],color,alpha3,meshColor,meshAlpha,meshWidth):fillOp([ring2],color,alpha3,null,0,0),depth)}}}};function solidOf(paint){if(!paint)return[90,180,240,1];return Array.isArray(paint)?paint:solidColor(paint)}function parametricSurface(fn,u,v,options={}){return new Surface3D(fn,u,v,options)}function surface(f,options={}){const x=options.x??[-4,4],y=options.y??[-4,4];return new Surface3D((u,v,t)=>[u,v,f(u,v,t)],x,y,{colors:options.color||options.checker||options.colorAt?void 0:["blue","teal","yellow"],...options})}function sphere(radius=1,options={}){const[cx,cy,cz]=options.center??[0,0,0];return new Surface3D((u,v)=>[cx+radius*Math.sin(v)*Math.cos(u),cy+radius*Math.sin(v)*Math.sin(u),cz+radius*Math.cos(v)],[0,Math.PI*2],[0,Math.PI],{cull:true,resolution:[64,40],outwardFrom:[cx,cy,cz],...options})}var ON_TOP=1e6;var Curve3D=class extends Object3D{constructor(f,from,to2,style={}){super();this.style=style;const samples=style.samples??240;this.points=new Float64Array((samples+1)*3);for(let i=0;i<=samples;i++){const[x,y,z]=f(from+(to2-from)*i/samples);this.points[i*3]=x;this.points[i*3+1]=y;this.points[i*3+2]=z}this.base.stroke=toPaint(style.color??"yellow");this.base.strokeWidth=style.width??3;if(style.colors){const palette=style.colors.map(c=>solidColor(c));this.stops=palette.map((c,i)=>[palette.length===1?0:i/(palette.length-1),c])}else{this.stops=null}}style;points;stops;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const trim=this.get("trimTo");const count=this.points.length/3-1;const last=Math.floor(trim*count);if(last<1)return;const piece=Math.max(2,Math.ceil(count/72));const base=this.get("stroke")??toPaint("yellow");const width=this.get("strokeWidth")*view.scale;const bias=this.style.onTop?ON_TOP:this.style.bias??.12;const glow=(this.style.glow??0)*view.scale;for(let start=0;start<last;start+=piece){const end=Math.min(last,start+piece);const coords=[];let depth=0;let scale=0;let drawn=0;for(let i=start;i<=end;i++){if(!view.project(this.points[i*3],this.points[i*3+1],this.points[i*3+2]))continue;coords.push([view.px,view.py]);depth+=view.pz;scale+=view.ps;drawn++}if(drawn<2)continue;depth/=drawn;scale/=drawn;const rgb=this.stops?sampleStops(this.stops,(start+end)/2/count):solidOf(base);const color=view.fogged(rgb[0],rgb[1],rgb[2],depth);view.push(strokeOp([chain(coords)],color,alpha3,width*scale,glow,"round"),depth+bias)}}};function chain(points){const p=new Float64Array(2+(points.length-1)*6);p[0]=points[0][0];p[1]=points[0][1];let o=2;for(let i=1;i<points.length;i++){const a=points[i-1],b=points[i];p[o++]=a[0]+(b[0]-a[0])/3;p[o++]=a[1]+(b[1]-a[1])/3;p[o++]=a[0]+(b[0]-a[0])*2/3;p[o++]=a[1]+(b[1]-a[1])*2/3;p[o++]=b[0];p[o++]=b[1]}return{p,closed:false,straight:true}}function curve3d(f,from,to2,style={}){return new Curve3D(f,from,to2,style)}var Line3D=class extends Object3D{constructor(a,b,style={}){super();this.a=a;this.b=b;this.style=style;this.base.stroke=toPaint(style.color??"ink");this.base.strokeWidth=style.width??2.5}a;b;style;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const a=read3(this.a),b=read3(this.b);const pieces=this.style.pieces??14;const trim=this.get("trimTo");const base=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const bias=this.style.onTop?ON_TOP:this.style.bias??0;for(let i=0;i<pieces;i++){const t0=i/pieces*trim,t1=(i+1)/pieces*trim;if(!view.project(a[0]+(b[0]-a[0])*t0,a[1]+(b[1]-a[1])*t0,a[2]+(b[2]-a[2])*t0))continue;const x0=view.px,y0=view.py,z0=view.pz,s0=view.ps;if(!view.project(a[0]+(b[0]-a[0])*t1,a[1]+(b[1]-a[1])*t1,a[2]+(b[2]-a[2])*t1))continue;const depth=(z0+view.pz)/2;const color=view.fogged(base[0],base[1],base[2],depth);view.push(strokeOp([lineRing(x0,y0,view.px,view.py)],color,alpha3,width*(s0+view.ps)/2,0,"butt"),depth+bias)}}};function line3d(a,b,style={}){return new Line3D(a,b,style)}var Vector3D=class extends Line3D{from3;to3;tipSize;tipBias;constructor(from,to2,style={}){super(from,()=>{const a=read3(from),b=read3(to2);const length=Math.hypot(b[0]-a[0],b[1]-a[1],b[2]-a[2])||1;const pull=Math.min(.9,.22/length);return[b[0]-(b[0]-a[0])*pull,b[1]-(b[1]-a[1])*pull,b[2]-(b[2]-a[2])*pull]},{color:"yellow",width:4,...style});this.from3=from;this.to3=to2;this.tipSize=style.tip??24;this.tipBias=style.onTop?ON_TOP:style.bias??0}emit(view){super.emit(view);const trim=this.get("trimTo");if(trim<.98)return;const a=read3(this.from3),b=read3(this.to3);const alpha3=this.objectAlpha(view);if(!view.project(a[0],a[1],a[2]))return;const ax=view.px,ay=view.py;if(!view.project(b[0],b[1],b[2]))return;const bx=view.px,by=view.py,depth=view.pz,s=view.ps;const length=Math.hypot(bx-ax,by-ay)||1;const ux=(bx-ax)/length,uy=(by-ay)/length;const size=this.tipSize*view.scale*s;const half=size*.42;const rgb=solidOf(this.get("stroke"));const color=view.fogged(rgb[0],rgb[1],rgb[2],depth);const ring2=polygonRing([bx,by,bx-ux*size-uy*half,by-uy*size+ux*half,bx-ux*size+uy*half,by-uy*size-ux*half]);view.push(fillOp([ring2],color,alpha3,null,0,0),depth+.01+this.tipBias)}};function vector3d(from,to2,style={}){return new Vector3D(from,to2,style)}var Points3D=class extends Object3D{constructor(source,style={}){super();this.source=source;this.style=style;this.base.fill=toPaint(style.color??"yellow")}source;style;emit(view){const alpha3=this.objectAlpha(view)*(this.style.opacity??1)*this.get("fillOpacity");if(alpha3<=.002)return;const points=typeof this.source==="function"?this.source():this.source;const radius=(this.style.radius??8)*view.scale;const trim=this.get("trimTo");const shown=Math.ceil(points.length*trim);const base=solidOf(this.get("fill"));const bias=this.style.onTop?ON_TOP:this.style.bias??0;for(let i=0;i<shown;i++){const point=points[i];if(!view.project(point[0],point[1],point[2]))continue;const rgb=this.style.colorAt?solidColor(this.style.colorAt(i,point)):base;const color=view.fogged(rgb[0],rgb[1],rgb[2],view.pz);const r=radius*view.ps;if(this.style.halo){view.push(fillOp([circleRing(view.px,view.py,r*(1+this.style.halo))],color,alpha3*.18,null,0,0),view.pz+bias-.001)}view.push(fillOp([circleRing(view.px,view.py,r)],color,alpha3,null,0,0),view.pz+bias)}}};function points3d(points,style={}){return new Points3D(points,style)}function point3d(point,style={}){return new Points3D(()=>[read3(point)],style)}var Trail3D=class extends Object3D{constructor(point,from,to2,style={}){super();this.point=point;this.from=from;this.to=to2;this.style=style;this.base.stroke=toPaint(style.color??"yellow");this.base.strokeWidth=style.width??3}point;from;to;style;cache=new Map;sample(index,rate){const cached=this.cache.get(index);if(cached)return cached;const saved=clock.now;clock.now=this.from+index/rate;const value=this.point();clock.now=saved;if(clock.mode==="render")this.cache.set(index,value);return value}emit(view,time){if(time<=this.from)return;const alpha3=this.objectAlpha(view)*(this.style.opacity??1);const rate=this.style.rate??30;const end=Math.min(time,this.to);const tail=this.style.tail;const start=tail!==void 0?Math.max(this.from,end-tail):this.from;const i0=Math.ceil((start-this.from)*rate),i1=Math.floor((end-this.from)*rate);if(i1-i0<1)return;const width=this.get("strokeWidth")*view.scale;const base=solidOf(this.get("stroke"));const fade2=this.style.fade??(tail!==void 0?0:1);const bias=this.style.onTop?ON_TOP:this.style.bias??0;const glow=(this.style.glow??0)*view.scale;const moved=[];let last=null;for(let k=i0;k<=i1;k++){const p=this.sample(k,rate);if(last&&Math.abs(p[0]-last[0])+Math.abs(p[1]-last[1])+Math.abs(p[2]-last[2])<1e-9)continue;moved.push(p);last=p}const span=moved.length-1;if(span<1)return;const piece=Math.max(1,Math.ceil(span/48));for(let i=0;i<span;i+=piece){const coords=[];let depth=0;let scale=0;for(let k=i;k<=Math.min(span,i+piece);k++){const p=moved[k];if(!view.project(p[0],p[1],p[2]))continue;coords.push([view.px,view.py]);depth+=view.pz;scale+=view.ps}if(coords.length<2)continue;depth/=coords.length;scale/=coords.length;const fraction=Math.min(1,(i+piece/2)/span);const light=fade2+(1-fade2)*Math.pow(fraction,1.6);const color=view.fogged(base[0],base[1],base[2],depth);view.push(strokeOp([chain(coords)],color,alpha3*light,width*scale,glow,"butt"),depth+bias)}}};function trail3d(point,from,to2,style={}){return new Trail3D(point,from,to2,style)}var Axes3D=class extends Object3D{constructor(options={}){super();this.options=options;this.ranges=[options.x??[-4,4],options.y??[-4,4],options.z??[-2.5,2.5]];this.step=options.step??1;this.base.stroke=toPaint(options.color??"dim");this.base.strokeWidth=options.width??2;const size=options.labelSize??34;const names=options.labels===false?null:Array.isArray(options.labels)?options.labels:["x","y","z"];this.tags=names?names.map(name=>tex(name,{size,display:false,color:"ink"})):[];if(options.numbers){const axes2=[[1,0,0],[0,1,0],[0,0,1]];this.ranges.forEach((range,axis)=>{for(const value of stepsBetween(range[0],range[1],this.step)){if(value===0)continue;const at=[axes2[axis][0]*value,axes2[axis][1]*value,axes2[axis][2]*value];this.numberNodes.push({node:text(String(value),{size:18,color:"dim"}),at})}})}}options;ranges;step;tags;numberNodes=[];emit(view){const alpha3=this.objectAlpha(view)*this.get("strokeOpacity");if(alpha3<=.002)return;const trim=this.get("trimTo");const rgb=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const unitVectors=[[1,0,0],[0,1,0],[0,0,1]];const bias=this.options.onTop?ON_TOP:this.options.bias??.4;this.ranges.forEach((range,axis)=>{const u=unitVectors[axis];const pieces=16;const low=range[0],high=low+(range[1]-low)*trim;for(let i=0;i<pieces;i++){const a=low+(high-low)*i/pieces,b=low+(high-low)*(i+1)/pieces;if(!view.project(u[0]*a,u[1]*a,u[2]*a))continue;const x0=view.px,y0=view.py,z0=view.pz;if(!view.project(u[0]*b,u[1]*b,u[2]*b))continue;const depth=(z0+view.pz)/2;view.push(strokeOp([lineRing(x0,y0,view.px,view.py)],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width,0,"butt"),depth+bias)}if(this.options.ticks??true){for(const value of stepsBetween(range[0],high,this.step)){if(value===0)continue;if(!view.project(u[0]*value,u[1]*value,u[2]*value))continue;const cx=view.px,cy=view.py,depth=view.pz;const size=5*view.ps*view.scale;const ring2=lineRing(cx-(axis===2?size:0),cy-(axis===2?0:size),cx+(axis===2?size:0),cy+(axis===2?0:size));view.push(strokeOp([ring2],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width*.8,0,"butt"),depth+bias)}}if(trim>.98&&view.project(u[0]*range[1],u[1]*range[1],u[2]*range[1])){const tipX=view.px,tipY=view.py,depth=view.pz;const back=range[1]-.2;if(view.project(u[0]*back,u[1]*back,u[2]*back)){const length=Math.hypot(tipX-view.px,tipY-view.py)||1;const ux=(tipX-view.px)/length,uy=(tipY-view.py)/length;const size=14*view.scale,half=size*.42;const ring2=polygonRing([tipX,tipY,tipX-ux*size-uy*half,tipY-uy*size+ux*half,tipX-ux*size+uy*half,tipY-uy*size-ux*half]);view.push(fillOp([ring2],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,null,0,0),depth+bias)}}})}labelsNow(view){const alpha3=this.get("opacity")*this.get("strokeOpacity");if(alpha3<=.002||this.get("trimTo")<.9)return[];const out=[];const unitVectors=[[1,0,0],[0,1,0],[0,0,1]];this.tags.forEach((tag,axis)=>{const u=unitVectors[axis];const reach=this.ranges[axis][1]+.35;const at=view.screen(u[0]*reach,u[1]*reach,u[2]*reach);if(at){tag.at(at);tag.set("opacity",alpha3);out.push(tag)}});for(const{node,at}of this.numberNodes){const screen=view.screen(at[0],at[1],at[2]);if(screen){node.at(screen[0]+12,screen[1]+14);node.set("opacity",alpha3);out.push(node)}}return out}};function axes3d(options={}){return new Axes3D(options)}var GridPlane3D=class extends Object3D{constructor(options={}){super();this.options=options;this.base.stroke=toPaint(options.color??"grid");this.base.strokeWidth=options.width??1.2}options;emit(view){const alpha3=this.objectAlpha(view)*(this.options.opacity??1)*this.get("strokeOpacity");if(alpha3<=.002)return;const[x0,x1]=this.options.x??[-5,5];const[y0,y1]=this.options.y??[-5,5];const z=this.options.z??0;const step=this.options.step??1;const rgb=solidOf(this.get("stroke"));const width=this.get("strokeWidth")*view.scale;const trim=this.get("trimTo");const run2=(ax,ay,bx,by)=>{const pieces=10;for(let i=0;i<pieces;i++){const t0=i/pieces*trim,t1=(i+1)/pieces*trim;if(!view.project(ax+(bx-ax)*t0,ay+(by-ay)*t0,z))continue;const px=view.px,py=view.py,pz=view.pz;if(!view.project(ax+(bx-ax)*t1,ay+(by-ay)*t1,z))continue;const depth=(pz+view.pz)/2;view.push(strokeOp([lineRing(px,py,view.px,view.py)],view.fogged(rgb[0],rgb[1],rgb[2],depth),alpha3,width,0,"butt"),depth-.05)}};for(const x of stepsBetween(x0,x1,step))run2(x,y0,x,y1);for(const y of stepsBetween(y0,y1,step))run2(x0,y,x1,y)}};function gridPlane3d(options={}){return new GridPlane3D(options)}var Label3D=class extends Object3D{constructor(content,position2,options={}){super();this.position=position2;this.content=typeof content==="string"?options.math===false?text(content,{size:options.size??28,color:options.color??"ink"}):tex(content,{size:options.size??32,color:options.color??"ink",display:false}):content;this.offset=options.offset??[0,0]}position;content;offset;emit(){}labelsNow(view){const alpha3=this.get("opacity");if(alpha3<=.002)return[];const p=read3(this.position);const at=view.screen(p[0],p[1],p[2]);if(!at)return[];this.content.at(at[0]+this.offset[0],at[1]+this.offset[1]);this.content.set("opacity",alpha3*this.get("trimTo"));return[this.content]}};function label3d(content,position2,options={}){return new Label3D(content,position2,options)}var FORMATS=["mp4","webm","gif","png","svg"];var QUALITIES=["draft","standard","high","master"];function isLookName(value){return Object.hasOwn(LOOKS,value)}function requireValue(args,index,name){const value=args[index+1];if(value===void 0||value.startsWith("--"))throw new Error(`${name} requires a value`);return value}function positiveNumber(value,name){const parsed=Number(value);if(!Number.isFinite(parsed)||parsed<=0)throw new Error(`${name} must be a positive number, but received ${value}`);return parsed}function positiveInteger(value,name){const parsed=positiveNumber(value,name);if(!Number.isInteger(parsed))throw new Error(`${name} must be a whole number, but received ${value}`);return parsed}function parseLooks(value){const looks=value.split(",").map(item=>item.trim()).filter(Boolean);for(const look of looks){if(!isLookName(look))throw new Error(`Unknown look ${JSON.stringify(look)}. Run "vizmatic looks" to see all looks: ${Object.keys(LOOKS).join(", ")}.`)}if(looks.length===0)throw new Error("--look requires at least one look");return looks}function parseRange(value){const match=/^([\d.]*):([\d.]*)$/.exec(value);if(!match||!match[1]&&!match[2])throw new Error(`--range needs start:end in seconds, such as 3:8 or 3: or :8, but received ${value}`);const from=match[1]?Number(match[1]):void 0;const to2=match[2]?Number(match[2]):void 0;if(from!==void 0&&!Number.isFinite(from)||to2!==void 0&&!Number.isFinite(to2))throw new Error(`--range has an invalid number: ${value}`);if(from!==void 0&&to2!==void 0&&to2<=from)throw new Error(`--range must end after it starts, but received ${value}`);return{from,to:to2}}function parseFilmArgs(argv){const args={inputs:[],outDir:"dist/films",looks:[],quality:"standard",frames:[],poster:false,formats:[],json:false};for(let i=0;i<argv.length;i++){const arg=argv[i];switch(arg){case"--out":args.outDir=requireValue(argv,i++,arg);break;case"--look":args.looks=parseLooks(requireValue(argv,i++,arg));break;case"--fps":args.fps=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--width":args.width=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--motion-blur":args.motionBlur=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--shutter":args.shutter=positiveNumber(requireValue(argv,i++,arg),arg);break;case"--workers":args.workers=positiveInteger(requireValue(argv,i++,arg),arg);break;case"--audio":args.audioPath=requireValue(argv,i++,arg);break;case"--ffmpeg":args.ffmpegPath=requireValue(argv,i++,arg);break;case"--background":{const value=requireValue(argv,i++,arg);args.background=value==="none"||value==="transparent"?null:value;break}case"--poster":args.poster=true;break;case"--json":args.json=true;break;case"--quality":{const value=requireValue(argv,i++,arg);if(!QUALITIES.includes(value))throw new Error(`--quality must be one of ${QUALITIES.join(", ")}, but received ${value}`);args.quality=value;break}case"--range":Object.assign(args,parseRange(requireValue(argv,i++,arg)));break;case"--frame":{for(const part of requireValue(argv,i++,arg).split(",")){const time=Number(part);if(!Number.isFinite(time)||time<0)throw new Error(`--frame needs times in seconds, but received ${part}`);args.frames.push(time)}break}case"--format":{for(const part of requireValue(argv,i++,arg).split(",")){const format=part.trim();if(!FORMATS.includes(format))throw new Error(`--format must list ${FORMATS.join(", ")}, but received ${part}`);if(!args.formats.includes(format))args.formats.push(format)}break}default:if(arg.startsWith("--"))throw new Error(`Unknown option for vizmatic film: ${arg}`);args.inputs.push(arg)}}if(args.inputs.length===0)throw new Error("vizmatic film needs a film file, such as: vizmatic film ./intro.ts --out dist/films");return args}function filmFromModule(mod){const top=mod;for(const candidate of[top?.default,top?.default?.default,top?.film]){if(isFilm(candidate))return candidate}return void 0}async function loadFilmDefinition(file,load){const candidate=filmFromModule(await load(file));if(candidate)return candidate;const shown=relative(process.cwd(),file);throw new Error(`${shown} must export a film as its default export: export default film({ title: 'Intro' }, (s) => { ... })`)}function formatClock(seconds){const whole=Math.max(0,Math.round(seconds));return`${Math.floor(whole/60)}:${String(whole%60).padStart(2,"0")}`}function formatBytes(bytes){if(bytes<1024)return`${bytes} B`;if(bytes<1024**2)return`${(bytes/1024).toFixed(0)} KB`;return`${(bytes/1024**2).toFixed(1)} MB`}function progressReporter(label,quiet){const started=performance.now();const live=process.stderr.isTTY===true;let lastPrint=0;let lastDecile=-1;return{update(frame){if(quiet)return;const now=performance.now();const completed=frame.index+1;const finished=completed===frame.count;if(live&&!finished&&now-lastPrint<80)return;lastPrint=now;const elapsed=(now-started)/1e3;const fps=completed/Math.max(elapsed,.001);const remaining=(frame.count-completed)/Math.max(fps,.001);const percent=Math.floor(completed/frame.count*100);const line2=`${label} frame ${completed}/${frame.count} ${percent}% ${fps.toFixed(1)} fps ETA ${formatClock(remaining)}`;if(live){process.stderr.write(`\r\x1B[2K${line2}`)}else{const decile=Math.floor(percent/10);if(decile!==lastDecile){lastDecile=decile;process.stderr.write(`${line2}
333
355
  `)}}},done(){if(!quiet&&live)process.stderr.write("\r\x1B[2K");return(performance.now()-started)/1e3}}}function frameStamp(time){return`t${time.toFixed(3).padStart(7,"0")}`}async function renderOneLook(compiled,name,lookLabel,args,signal,say){const outputs=[];const stem=lookLabel?`${name}_${lookLabel}`:name;const shown=path=>relative(process.cwd(),path);const common={quality:args.quality,motionBlur:args.motionBlur,shutter:args.shutter,workers:args.workers,from:args.from,to:args.to,audioPath:args.audioPath,ffmpegPath:args.ffmpegPath,signal,width:args.width};const look=compiled.look.name;const stillFormats=args.formats.filter(format=>format==="png"||format==="svg");const movieFormats=args.formats.filter(format=>format==="mp4"||format==="webm"||format==="gif");const stills=[];for(const time of args.frames)stills.push({time,suffix:`_${frameStamp(time)}`,formats:stillFormats.length?stillFormats:["png"]});if(args.frames.length===0&&(args.poster||stillFormats.length>0)){stills.push({time:await posterTime(compiled),suffix:"",formats:stillFormats.length?stillFormats:["png"]})}else if(args.poster){stills.push({time:await posterTime(compiled),suffix:"",formats:["png"]})}for(const still of stills){for(const format of still.formats){const path=join2(args.outDir,`${stem}${still.suffix}.${format}`);const written=format==="png"?await renderFilmFrame(compiled,still.time,path,{width:args.width}):await renderFilmSvg(compiled,still.time,path,{width:args.width});const bytes=(await stat2(written.outputPath)).size;outputs.push({format,path:shown(written.outputPath),look,width:written.width,height:written.height,bytes,time:Math.round(still.time*1e3)/1e3});say(`rendered ${shown(written.outputPath)} at ${still.time.toFixed(2)}s (${written.width}x${written.height}, ${formatBytes(bytes)})`)}}for(const format of movieFormats){const path=join2(args.outDir,`${stem}.${format}`);const progress=progressReporter(`${basename(path)}`,args.json);const onProgress=frame=>progress.update(frame);if(format==="gif"){const gif=await renderFilmGif(compiled,path,{...common,fps:args.fps,onProgress});const seconds2=progress.done();outputs.push({format,path:shown(gif.outputPath),look,width:gif.width,height:gif.height,bytes:gif.bytes,frameCount:gif.frameCount,fps:gif.fps,duration:gif.duration/1e3,renderSeconds:Math.round(seconds2*100)/100,renderFps:Math.round(gif.frameCount/seconds2*10)/10});say(`rendered ${shown(gif.outputPath)} (${gif.frameCount} frames at ${gif.width}x${gif.height}, ${formatBytes(gif.bytes)}, ${seconds2.toFixed(1)}s)`);continue}const video=await renderFilmVideo(compiled,path,{...common,codec:format==="webm"?"vp9":"h264",onProgress});const seconds=progress.done();outputs.push({format,path:shown(video.outputPath),look,width:video.width,height:video.height,bytes:video.bytes,frameCount:video.frameCount,fps:video.fps,duration:video.duration/1e3,codec:video.codec,quality:args.quality,motionBlur:video.motionBlur,workers:video.workers,renderSeconds:Math.round(seconds*100)/100,renderFps:Math.round(video.frameCount/seconds*10)/10});say(`rendered ${shown(video.outputPath)} (${video.frameCount} frames at ${video.width}x${video.height}, ${formatBytes(video.bytes)}, ${(video.frameCount/seconds).toFixed(1)} render fps)`)}return outputs}async function runFilmCommand(args,files,stems,load){if(files.length===0)throw new Error("No film files were found.");if(args.formats.length===0&&args.frames.length===0)args.formats=["mp4"];const say=line2=>{if(!args.json)console.log(line2)};const controller=new AbortController;const abort=()=>controller.abort();process.once("SIGINT",abort);process.once("SIGTERM",abort);const manifest=[];const started=performance.now();try{await mkdir3(args.outDir,{recursive:true});for(const file of files){const definition=await loadFilmDefinition(file,load);const name=stems.get(file)??basename(file,extname(file));const looks=args.looks.length>0?args.looks:[void 0];const outputs=[];let first;let captionsPath;for(const look of looks){const compiled=await definition.compile({...look?{look}:{},...args.fps?{fps:args.fps}:{},...args.background!==void 0?{background:args.background}:{}});first??=compiled;outputs.push(...await renderOneLook(compiled,name,args.looks.length>1?look:"",args,controller.signal,say));if(compiled.captions.length>0&&!captionsPath&&args.formats.some(format=>format==="mp4"||format==="webm")){captionsPath=join2(args.outDir,`${name}.vtt`);await writeFile3(captionsPath,captionsToVtt(compiled));say(`wrote captions ${relative(process.cwd(),captionsPath)}`)}}manifest.push({name,source:relative(process.cwd(),file),title:first.title,duration:first.duration,fps:first.fps,width:first.width,height:first.height,chapters:first.chapters,...captionsPath?{captions:relative(process.cwd(),captionsPath)}:{},outputs})}const report={schemaVersion:1,command:"film",ok:true,elapsedSeconds:Math.round((performance.now()-started)/10)/100,films:manifest};const text2=`${JSON.stringify(report,null,2)}
334
356
  `;await writeFile3(join2(args.outDir,"film-manifest.json"),text2);if(args.json)process.stdout.write(text2)}finally{process.removeListener("SIGINT",abort);process.removeListener("SIGTERM",abort)}}async function checkFilmFile(file,load,looks,options={}){const definition=await loadFilmDefinition(file,load);const source=relative(process.cwd(),file);const reports=[];for(const look of looks.length>0?looks:[void 0]){const compiled=await definition.compile(look?{look}:{});reports.push({source,title:compiled.title,...await checkFilm(compiled,options)})}return reports}function printFilmCheck(report){const status=report.ok?"ok":"failed";const frames=report.frames===void 0?"":` and ${report.frames} frames`;console.log(`${report.source}: ${status}, ${report.diagnostics.length} finding(s) in ${report.sampled.length} sampled moments${frames} over ${report.duration.toFixed(1)}s`);for(const entry of report.diagnostics){const span=entry.time===entry.until?`${entry.time.toFixed(2)}s`:`${entry.time.toFixed(2)}s to ${entry.until.toFixed(2)}s`;const repeats=entry.motion&&entry.motion.spans>1?`, ${entry.motion.spans} times, ${entry.motion.seconds}s in total`:"";const when=entry.motion?`${span} (in motion${repeats})`:span;const{x,y,width,height}=entry.box;console.log(` ${entry.severity} ${entry.code} at ${when}: ${entry.message} Box x=${x} y=${y} w=${width} h=${height}. Stage (${entry.stage.x}, ${entry.stage.y}).`)}}async function runNewCommand(argv){let templateName="explainer";let force=false;let target;for(let i=0;i<argv.length;i++){const arg=argv[i];if(arg==="--template")templateName=requireValue(argv,i++,arg);else if(arg==="--force")force=true;else if(arg==="--list"){for(const template2 of FILM_TEMPLATES)console.log(`${template2.name.padEnd(14)}${template2.description}`);return}else if(arg.startsWith("--"))throw new Error(`Unknown option for vizmatic new: ${arg}`);else target=arg}const template=FILM_TEMPLATES.find(entry=>entry.name===templateName);if(!template)throw new Error(`Unknown template ${JSON.stringify(templateName)}. Use one of: ${FILM_TEMPLATES.map(entry=>entry.name).join(", ")}.`);if(!target)throw new Error(`vizmatic new needs a name, such as: vizmatic new intro --template ${template.name}`);const path=resolve2(extname(target)?target:`${target}.ts`);if(existsSync(path)&&!force)throw new Error(`${relative(process.cwd(),path)} already exists. Pass --force to replace it.`);await mkdir3(dirname3(path),{recursive:true});await writeFile3(path,template.source);const shown=relative(process.cwd(),path);console.log(`created ${shown} from the ${template.name} template
335
357