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/{chunk-5ZAFH2JC.js → chunk-6H2KTNJ7.js} +1405 -862
- package/dist/{chunk-QVYHYC7T.js → chunk-6N6P2GJG.js} +1 -1
- package/dist/chunk-YOP55T6W.js +1788 -0
- package/dist/{chunk-F6QI6QJY.js → chunk-ZB3HK7RM.js} +0 -1786
- package/dist/cli.js +26 -4
- package/dist/index.js +6 -4
- package/dist/scene-cli.js +1 -1
- package/dist/stage-browser/browser.d.ts +56 -7
- package/dist/stage-browser/stage.js +5 -5
- package/dist/stage-export.cjs +583 -510
- package/dist/stage-export.js +57 -6
- package/dist/stage.cjs +2083 -20
- package/dist/stage.d.cts +6 -6
- package/dist/stage.d.ts +6 -6
- package/dist/stage.js +58 -2
- package/dist/{svg-import-5_oTbEJR.d.ts → svg-import-C-RG1t7s.d.cts} +53 -3
- package/dist/{svg-import-5_oTbEJR.d.cts → svg-import-C-RG1t7s.d.ts} +53 -3
- package/package.json +1 -1
|
@@ -85,4 +85,4 @@ if (typeof error === 'string') throw error.slice(0, 1024);
|
|
|
85
85
|
const message = error && typeof error === 'object' ? __ownDescriptor(error, 'message')?.value : undefined;
|
|
86
86
|
throw typeof message === 'string' ? message.slice(0, 1024) : 'Scene evaluation failed.';
|
|
87
87
|
}
|
|
88
|
-
})()`,"scene.tsx");if(result.error){const error=result.error;try{const message=vm.typeof(error)==="string"?vm.getString(error):"Scene evaluation failed or exceeded its CPU, stack or memory limit.";throw new Error(message.slice(0,1024))}finally{error.dispose()}}const handle=result.value;try{if(vm.typeof(handle)!=="string")throw new Error("Scene source must return synchronous JSX.");const length=vm.getProp(handle,"length");try{if(vm.getNumber(length)>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.")}finally{length.dispose()}const json=vm.getString(handle);if(new TextEncoder().encode(json).byteLength>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.");const graph=validateSceneGraph(JSON.parse(json));return{graph,request:normalized,time,runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256,inputSha256:await sceneSha256(JSON.stringify({sceneInputSha256:inputSha256,time}))}}finally{handle.dispose()}}finally{vm.dispose();runtime.dispose()}};return{request:normalized,sourceSha256,inputSha256,evaluate}}async function evaluateSceneSource(request){return(await prepareScene(request)).evaluate(request.time)}function outputSettings(prepared,outputScale=1,previewFps){if(!Number.isFinite(outputScale)||outputScale<.25||outputScale>1){throw new Error("Scene outputScale must be from 0.25 to 1.")}const{width:logicalWidth,height:logicalHeight,fps:logicalFps,duration}=prepared.request;const width=logicalWidth*outputScale,height=logicalHeight*outputScale;if(![width,height].every(value=>Number.isInteger(value)&&value>=2&&value%2===0)){throw new Error("Scaled scene width and height must be positive even integers.")}const fps=previewFps===void 0?logicalFps:previewFps;if(!Number.isInteger(fps)||fps<1||fps>logicalFps){throw new Error("Scene previewFps must be an integer from 1 to the logical scene fps.")}const frameCount=Math.round(duration*fps);if(frameCount<1)throw new Error("Scene preview duration must round to at least one output frame.");return{width,height,fps,frameCount,outputScale,preview:outputScale!==1||fps!==logicalFps}}var assetPins={"fonts/Inter-Regular.ttf":"1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba","fonts/Inter-SemiBold.ttf":"e7a1aaf7eda9f2fad4131725fa556265ec75ca7b2d756260173a040363e8d4f7","fonts/Inter-Bold.ttf":"b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c","fonts/JetBrainsMono-Regular.ttf":"44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3","fonts/NotoSans-Regular.ttf":"5be701a9511117e73603bdab95947feef4f18bd1851dbddc30659370b26c69f1","fonts/NotoSansMath-Regular.ttf":"3cbaf44af13f592bc7f7172a50edab4c73ac2f3d19af2d697a01ebd3288e322d","fonts/InstrumentSerif-Regular.ttf":"498efd461f6ddfcb7a111bf9a565709d2085d48201d501ead960d93e84ffbb88","fonts/InstrumentSerif-Italic.ttf":"08939b8bdf534afec24ae0ef5e03f948940cd9a8fe08e7fecbad040e62327385","emoji.json.br":"4911e822be2ed684fe811cadf036139e3efe353ffe2990311e1763f38ae7daab"};var assetsPromise;async function sceneAssets(){assetsPromise??=loadSceneAssets().catch(error=>{assetsPromise=void 0;throw error});return assetsPromise}async function loadSceneAssets(){const moduleDir=typeof __dirname!=="undefined"?__dirname:dirname3(fileURLToPath2(import.meta.url));const assetDir=join3(moduleDir,"..","assets");const files=new Map;for(const[name,expected]of Object.entries(assetPins)){const bytes=await readFile2(join3(assetDir,name));if(await sceneSha256(bytes)!==expected)throw new Error(`Pinned scene asset does not match: ${name}`);files.set(name,bytes)}const fontDefinitions=[["Inter","Inter-Regular.ttf",400],["Inter","Inter-SemiBold.ttf",600],["Inter","Inter-Bold.ttf",700],["JetBrains Mono","JetBrainsMono-Regular.ttf",400],["Noto Sans","NotoSans-Regular.ttf",400],["Noto Sans Math","NotoSansMath-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Italic.ttf",400,"italic"]];return{fonts:fontDefinitions.map(([name,filename,weight,style])=>({name,weight,style:style??"normal",data:Uint8Array.from(files.get(`fonts/${filename}`)).buffer})),fontFiles:fontDefinitions.map(([,filename])=>join3(assetDir,"fonts",filename)),emoji:JSON.parse(brotliDecompressSync2(files.get("emoji.json.br")).toString("utf8")),sha256:await sceneSha256(JSON.stringify(assetPins))}}var trustedComponents=Object.fromEntries(SCENE_COMPONENT_NAMES.map(name=>[name,primitives_exports[name]]));var svgTags=new Set(SCENE_DOM_TAGS.filter(name=>!["div","span","p","strong","em","b","i","br"].includes(name)));function isElement(value){return Boolean(value&&!Array.isArray(value)&&typeof value==="object"&&value.kind==="vizmatic.element")}var xml=value=>String(value).replace(/[&<>"']/g,character=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[character]);function svgAttribute(name){if(name==="className")return"class";if(name==="xlinkHref")return"href";if(/^(?:viewBox|preserveAspectRatio|gradientUnits|gradientTransform|patternUnits|patternContentUnits|patternTransform|markerWidth|markerHeight|markerUnits|refX|refY|textLength|lengthAdjust|clipPathUnits)$/.test(name))return name;return name.replace(/[A-Z]/g,character=>`-${character.toLowerCase()}`)}function serializeSvg(node,budget,depth=0){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(depth>SCENE_LIMITS.depth*2)throw new Error("Resolved SVG exceeds its depth limit.");const emit=chunk=>{budget.svgBytes+=Buffer.byteLength(chunk);if(budget.svgBytes>SCENE_LIMITS.graphBytes*4)throw new Error("Resolved SVG exceeds its serialized byte budget.");return chunk};if(node===null||node===void 0||typeof node==="boolean")return"";if(typeof node==="string"||typeof node==="number")return emit(xml(node));if(Array.isArray(node))return node.map(child=>serializeSvg(child,budget,depth+1)).join("");if(!React21.isValidElement(node))throw new Error("Invalid resolved SVG child.");if(node.type===React21.Fragment)return serializeSvg(node.props.children,budget,depth+1);if(node.type===SvgMathText){const{text,x,y,fill,fontSize=13,fontFamily="JetBrains Mono",fontWeight=700,textAnchor="middle",dominantBaseline="middle",opacity=1}=node.props;return serializeSvg(React21.createElement("text",{x,y,fill,fontSize,fontFamily,fontWeight,textAnchor,dominantBaseline,opacity},String(text)),budget,depth+1)}if(typeof node.type==="function"){return serializeSvg(node.type(node.props),budget,depth+1)}if(typeof node.type!=="string"||!svgTags.has(node.type))throw new Error("Only SVG components may be placed inside an SVG scene.");validateResolvedSceneResources(node.props);const attributes=Object.entries(node.props).filter(([key,value])=>key!=="children"&&key!=="key"&&value!==void 0&&value!==null).map(([key,value])=>{if(key==="style"&&typeof value==="object"){const style=Object.entries(value).map(([property,item])=>`${svgAttribute(property)}:${String(item)}`).join(";");return` style="${xml(style)}"`}if(!/^[A-Za-z_][\w:.-]*$/.test(key)||typeof value==="object"||typeof value==="function")throw new Error("Unsupported SVG attribute.");return` ${svgAttribute(key)}="${xml(String(value))}"`}).join("");return emit(`<${node.type}${attributes}>`)+serializeSvg(node.props.children,budget,depth+1)+emit(`</${node.type}>`)}function graphToReact(value,theme){if(Array.isArray(value))return value.map(child=>graphToReact(child,theme));if(!isElement(value))return value;const convertProp=prop=>{if(isElement(prop))return graphToReact(prop,theme);if(Array.isArray(prop))return prop.map(convertProp);if(prop&&typeof prop==="object")return Object.fromEntries(Object.entries(prop).map(([key,item])=>[key,convertProp(item)]));return prop};const props=Object.fromEntries(Object.entries(value.props).map(([name,prop])=>[name,convertProp(prop)]));const component=trustedComponents[value.type];if(component)props.c??=theme;return React21.createElement(component??value.type,props,...value.children.map(child=>graphToReact(child,theme)))}function renderSvgImage(element,assets,width,height,budget,outputScale=1,includePng=true){const root=React21.cloneElement(element,{xmlns:"http://www.w3.org/2000/svg",width,height});const svg=serializeSvg(root,budget);const image=new Resvg3(svg,{font:{loadSystemFonts:false,fontFiles:assets.fontFiles,defaultFontFamily:"Inter"},background:"rgba(0,0,0,0)",...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("SVG frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}}function rasterizeNestedSvg(node,assets,defaultWidth,defaultHeight,budget){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(Array.isArray(node))return node.map(child=>rasterizeNestedSvg(child,assets,defaultWidth,defaultHeight,budget));if(!React21.isValidElement(node))return node;if(node.type==="svg"){const width=typeof node.props.width==="number"?node.props.width:defaultWidth;const height=typeof node.props.height==="number"?node.props.height:defaultHeight;if(!Number.isInteger(width)||!Number.isInteger(height)||width<1||height<1||width>SCENE_LIMITS.canvasEdge||height>SCENE_LIMITS.canvasEdge||width*height>SCENE_LIMITS.canvasPixels){throw new Error("Nested SVG dimensions exceed the scene canvas limits.")}budget.pixels+=width*height;budget.count+=1;if(budget.pixels>defaultWidth*defaultHeight*4||budget.count>16){throw new Error("Nested SVG rasterization exceeds the per-frame pixel or image budget.")}const{png}=renderSvgImage(node,assets,width,height,budget);return React21.createElement("img",{width,height,src:`data:image/png;base64,${Buffer.from(png).toString("base64")}`,style:{display:"flex",flexShrink:0,...node.props.style}})}if(typeof node.type==="function")return rasterizeNestedSvg(node.type(node.props),assets,defaultWidth,defaultHeight,budget);validateResolvedSceneResources(node.props);return React21.cloneElement(node,{},rasterizeNestedSvg(node.props.children,assets,defaultWidth,defaultHeight,budget))}async function renderPreparedFrame(prepared,assets,time,outputScale,includePng){const evaluated=await prepared.evaluate(time);const{width,height,theme}=prepared.request;const c=getThemeColors(theme);let element=graphToReact(evaluated.graph,c);if(React21.isValidElement(element)&&element.type==="svg"){const image=renderSvgImage(React21.cloneElement(element,{children:[React21.createElement("rect",{key:"__scene_background",width,height,fill:c.bg}),element.props.children]}),assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0},outputScale,includePng);return image}element=React21.createElement("div",{style:{display:"flex",position:"relative",width,height,backgroundColor:c.bg,fontFamily:"Inter",color:c.textPrimary}},element);return withRenderContext({background:"theme"},async()=>{element=rasterizeNestedSvg(element,assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0});const accessible=prepareAccessibleSvg(element);const layoutNodes=[];const rendered=await satori(accessible.element,{width,height,fonts:assets.fonts,loadAdditionalAsset:async(code,segment)=>{if(code!=="emoji")return[];const points=[...segment].map(character=>character.codePointAt(0).toString(16));const candidates=[points.join("-"),points.filter(point=>point!=="fe0f").join("-")];const svg2=candidates.map(name=>assets.emoji[`${name}.svg`]).find(Boolean);if(!svg2)throw new Error("A scene glyph is not available in the pinned offline font and emoji assets.");return`data:image/svg+xml;base64,${Buffer.from(svg2).toString("base64")}`},onNodeDetected:node=>layoutNodes.push(node)});const svg=addSvgAccessibility(rendered,accessible.graphs,layoutNodes);const image=new Resvg3(svg,{background:c.bg,font:{loadSystemFonts:false,fontFiles:assets.fontFiles},...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("Layout frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}})}async function outputMetadata(prepared,assets,settings,outputPath,bytes,kind,time){const{width,height,duration,fps,frameCount}=prepared.request;const digest=createHash("sha256");for await(const chunk of createReadStream(outputPath))digest.update(chunk);return{runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256:prepared.sourceSha256,inputSha256:await sceneSha256(JSON.stringify({requestSha256:prepared.inputSha256,fontAssetsSha256:assets.sha256,kind,...time!==void 0?{time}:{},...settings.preview?{outputScale:settings.outputScale,width:settings.width,height:settings.height,fps:settings.fps,frameCount:settings.frameCount}:{}})),assetSha256:digest.digest("hex"),fontAssetsSha256:assets.sha256,width:settings.width,height:settings.height,duration,fps:settings.fps,frameCount:settings.frameCount,bytes,outputPath:resolve2(outputPath),...settings.preview?{outputScale:settings.outputScale,...kind==="mp4"?{previewFps:settings.fps}:{},logicalWidth:width,logicalHeight:height,logicalFps:fps,logicalFrameCount:frameCount}:{}}}async function atomicWrite(outputPath,bytes){const target=resolve2(outputPath);await mkdir3(dirname3(target),{recursive:true});const temporary=join3(dirname3(target),`.vizmatic-scene-${randomUUID2()}.tmp`);const file=await open2(temporary,"wx",384);try{await file.writeFile(bytes);await file.close();await rename2(temporary,target)}catch(error){await file.close().catch(()=>{});await rm2(temporary,{force:true});throw error}}async function renderSceneFrame(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale);const time=normalizeSceneTime(options.time,prepared.request.duration);const assets=await sceneAssets();const image=await renderPreparedFrame(prepared,assets,time,settings.outputScale,true);await atomicWrite(options.outputPath,image.png);return{...await outputMetadata(prepared,assets,settings,options.outputPath,image.png.byteLength,"png",time),time}}async function renderSceneVideo(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale,options.previewFps);const assets=await sceneAssets();const{duration}=prepared.request;const output=await renderRgbaVideo(async frame=>(await renderPreparedFrame(prepared,assets,frame.time/1e3,settings.outputScale,false)).pixels,{width:settings.width,height:settings.height,duration:duration*1e3,fps:settings.fps,outputPath:options.outputPath,signal:options.signal});return{...await outputMetadata(prepared,assets,settings,options.outputPath,output.bytes,"mp4"),encodedDuration:output.duration/1e3}}export{DENSITY_NAMES,DEFAULT_DENSITY,assertDensity,parseDensity,densityTokens,setDefaultDensity,setDensityResolver,densityOf,withDensity,getThemeColors,colors,gradients,toneGradients,getToneGradient,getToneColor,getReadableToneColor,getToneFill,typography,hasShadow,typeOf,canvas,getStyles,styles,getColor,getReadableColor,withColorAlpha,compositeColor,getReadableTextColor,getGradient,heatColor,withRenderContext,defineIllustration,Canvas,TitleBar,scopeDensity,Scene,Row,Column,ToneStrip,Icon,Panel,formatMathText,MathText,TextLabel,SvgMathText,Box,Arrow,FlowArrow,Connector,VectorArrow,VectorSegment,SvgFrame,SvgPoint,ArrowMarkerDef,Stack,Card,ValuePill,EquationCard,BadgePill,GradientChip,StepCard,MetricCard,estimateTextWidth,statusColor,StatusDot,Sparkline,InlineBar,FactRows,MetricStrip,TagList,DiagramLegend,SmallMultiples,ProgressRow,ProgressList,MiniBarChart,DetailList,Tile,TileGrid,CodeBlock,Comparison,KeyValueList,WindowFrame,StatusRow,StatusList,Timeline,Flow,routingSegmentBlocked,routeOrthogonalGraph,pointAlongSamples,LayeredNetwork,defineDiagramIcon,defineIconRegistry,GraphDiagram,TreeDiagram,CalloutCard,Pipeline,SequenceDiagram,DataflowDiagram,DeploymentDiagram,EntityRelationshipDiagram,formatTensorShape,TransformerTopology,Matrix,Heatmap,TiledMatrix,DataTable,Grid,AxisPlot,createPlotArea,ChartFrame,PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart,ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot,Badge,DotPoint,DashedLine,Legend,CANVAS_ITEM_COMPONENT,Board,CanvasItem,mapNumberLine,NumberLine,geometryBounds,GeometryDiagram,sumForces,FreeBodyDiagram,waveValue,sampleWave,WaveDiagram,ELEMENT_SYMBOLS,MoleculeDiagram,reactionBalance,ReactionEquation,ReactionEnergyDiagram,seededRandom,lerpArray,dotProduct,multiplyMatrices,stableSoftmax,entropy,normalizeVector,sampleFunction,gaussian,sampleGaussian,scaledDotProductAttention,AttentionMatrix,transposeMatrix,rgbChannel,cropRgbImage,flattenRgbImage,PixelGrid,crossCorrelate2d,gaussianKernel,encodePng,decodeRgbPng,encodeRgbPng,cropRgbRaster,gaussianBlurRgb,primitives_exports,normalizeWatermark,Watermark,wrapWithWatermark,wrapWithBrand,detectBackgroundColor,detectContentBounds,cropPixels,detectOverflow,detectLayoutOverflow,satori,loadAdditionalAsset,getFonts,CanvasOverflowError,renderToPng,renderToPngWithOutput,renderToBuffer,renderToSvg,hold,keyframe,tween,parallel,defineAnimation,sampleAnimation,sampleAnimationFrame,analyzeAnimationCadence,sampleAnimationFrames,chapterMetadata,captionsToSrt,videoFrameSchedule,renderAnimationVideo,renderRgbaVideo,extractRootJsx,findBareRootJsxStart,SCENE_RUNTIME_VERSION,SCENE_LIMITS,prepareScene,evaluateSceneSource,renderSceneFrame,renderSceneVideo};
|
|
88
|
+
})()`,"scene.tsx");if(result.error){const error=result.error;try{const message=vm.typeof(error)==="string"?vm.getString(error):"Scene evaluation failed or exceeded its CPU, stack or memory limit.";throw new Error(message.slice(0,1024))}finally{error.dispose()}}const handle=result.value;try{if(vm.typeof(handle)!=="string")throw new Error("Scene source must return synchronous JSX.");const length=vm.getProp(handle,"length");try{if(vm.getNumber(length)>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.")}finally{length.dispose()}const json=vm.getString(handle);if(new TextEncoder().encode(json).byteLength>SCENE_LIMITS.graphBytes)throw new Error("Scene graph exceeds its serialized size limit.");const graph=validateSceneGraph(JSON.parse(json));return{graph,request:normalized,time,runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256,inputSha256:await sceneSha256(JSON.stringify({sceneInputSha256:inputSha256,time}))}}finally{handle.dispose()}}finally{vm.dispose();runtime.dispose()}};return{request:normalized,sourceSha256,inputSha256,evaluate}}async function evaluateSceneSource(request){return(await prepareScene(request)).evaluate(request.time)}function outputSettings(prepared,outputScale=1,previewFps){if(!Number.isFinite(outputScale)||outputScale<.25||outputScale>1){throw new Error("Scene outputScale must be from 0.25 to 1.")}const{width:logicalWidth,height:logicalHeight,fps:logicalFps,duration}=prepared.request;const width=logicalWidth*outputScale,height=logicalHeight*outputScale;if(![width,height].every(value=>Number.isInteger(value)&&value>=2&&value%2===0)){throw new Error("Scaled scene width and height must be positive even integers.")}const fps=previewFps===void 0?logicalFps:previewFps;if(!Number.isInteger(fps)||fps<1||fps>logicalFps){throw new Error("Scene previewFps must be an integer from 1 to the logical scene fps.")}const frameCount=Math.round(duration*fps);if(frameCount<1)throw new Error("Scene preview duration must round to at least one output frame.");return{width,height,fps,frameCount,outputScale,preview:outputScale!==1||fps!==logicalFps}}var assetPins={"fonts/Inter-Regular.ttf":"1b08e7fc267a5c7e1d614100f604b83e7e8a0be241f0f288faa2b3ac93a683ba","fonts/Inter-SemiBold.ttf":"e7a1aaf7eda9f2fad4131725fa556265ec75ca7b2d756260173a040363e8d4f7","fonts/Inter-Bold.ttf":"b37284b5701b6b168dfc770aa1a4ac492106422fd3ba76bc7641e37434e8019c","fonts/JetBrainsMono-Regular.ttf":"44ce4a84f20d60f24539bd0cef11f79c29e38609e0f8adf18551c9794a5d9dc3","fonts/NotoSans-Regular.ttf":"5be701a9511117e73603bdab95947feef4f18bd1851dbddc30659370b26c69f1","fonts/NotoSansMath-Regular.ttf":"3cbaf44af13f592bc7f7172a50edab4c73ac2f3d19af2d697a01ebd3288e322d","fonts/InstrumentSerif-Regular.ttf":"498efd461f6ddfcb7a111bf9a565709d2085d48201d501ead960d93e84ffbb88","fonts/InstrumentSerif-Italic.ttf":"08939b8bdf534afec24ae0ef5e03f948940cd9a8fe08e7fecbad040e62327385","emoji.json.br":"4911e822be2ed684fe811cadf036139e3efe353ffe2990311e1763f38ae7daab"};var assetsPromise;async function sceneAssets(){assetsPromise??=loadSceneAssets().catch(error=>{assetsPromise=void 0;throw error});return assetsPromise}async function loadSceneAssets(){const moduleDir=typeof __dirname!=="undefined"?__dirname:dirname3(fileURLToPath2(import.meta.url));const assetDir=join3(moduleDir,"..","assets");const files=new Map;for(const[name,expected]of Object.entries(assetPins)){const bytes=await readFile2(join3(assetDir,name));if(await sceneSha256(bytes)!==expected)throw new Error(`Pinned scene asset does not match: ${name}`);files.set(name,bytes)}const fontDefinitions=[["Inter","Inter-Regular.ttf",400],["Inter","Inter-SemiBold.ttf",600],["Inter","Inter-Bold.ttf",700],["JetBrains Mono","JetBrainsMono-Regular.ttf",400],["Noto Sans","NotoSans-Regular.ttf",400],["Noto Sans Math","NotoSansMath-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Regular.ttf",400],["Instrument Serif","InstrumentSerif-Italic.ttf",400,"italic"]];return{fonts:fontDefinitions.map(([name,filename,weight,style])=>({name,weight,style:style??"normal",data:Uint8Array.from(files.get(`fonts/${filename}`)).buffer})),fontFiles:fontDefinitions.map(([,filename])=>join3(assetDir,"fonts",filename)),emoji:JSON.parse(brotliDecompressSync2(files.get("emoji.json.br")).toString("utf8")),sha256:await sceneSha256(JSON.stringify(assetPins))}}var trustedComponents=Object.fromEntries(SCENE_COMPONENT_NAMES.map(name=>[name,primitives_exports[name]]));var svgTags=new Set(SCENE_DOM_TAGS.filter(name=>!["div","span","p","strong","em","b","i","br"].includes(name)));function isElement(value){return Boolean(value&&!Array.isArray(value)&&typeof value==="object"&&value.kind==="vizmatic.element")}var xml=value=>String(value).replace(/[&<>"']/g,character=>({"&":"&","<":"<",">":">",'"':""","'":"'"})[character]);function svgAttribute(name){if(name==="className")return"class";if(name==="xlinkHref")return"href";if(/^(?:viewBox|preserveAspectRatio|gradientUnits|gradientTransform|patternUnits|patternContentUnits|patternTransform|markerWidth|markerHeight|markerUnits|refX|refY|textLength|lengthAdjust|clipPathUnits)$/.test(name))return name;return name.replace(/[A-Z]/g,character=>`-${character.toLowerCase()}`)}function serializeSvg(node,budget,depth=0){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(depth>SCENE_LIMITS.depth*2)throw new Error("Resolved SVG exceeds its depth limit.");const emit=chunk=>{budget.svgBytes+=Buffer.byteLength(chunk);if(budget.svgBytes>SCENE_LIMITS.graphBytes*4)throw new Error("Resolved SVG exceeds its serialized byte budget.");return chunk};if(node===null||node===void 0||typeof node==="boolean")return"";if(typeof node==="string"||typeof node==="number")return emit(xml(node));if(Array.isArray(node))return node.map(child=>serializeSvg(child,budget,depth+1)).join("");if(!React21.isValidElement(node))throw new Error("Invalid resolved SVG child.");if(node.type===React21.Fragment)return serializeSvg(node.props.children,budget,depth+1);if(node.type===SvgMathText){const{text,x,y,fill,fontSize=13,fontFamily="JetBrains Mono",fontWeight=700,textAnchor="middle",dominantBaseline="middle",opacity=1}=node.props;return serializeSvg(React21.createElement("text",{x,y,fill,fontSize,fontFamily,fontWeight,textAnchor,dominantBaseline,opacity},String(text)),budget,depth+1)}if(typeof node.type==="function"){return serializeSvg(node.type(node.props),budget,depth+1)}if(typeof node.type!=="string"||!svgTags.has(node.type))throw new Error("Only SVG components may be placed inside an SVG scene.");validateResolvedSceneResources(node.props);const attributes=Object.entries(node.props).filter(([key,value])=>key!=="children"&&key!=="key"&&value!==void 0&&value!==null).map(([key,value])=>{if(key==="style"&&typeof value==="object"){const style=Object.entries(value).map(([property,item])=>`${svgAttribute(property)}:${String(item)}`).join(";");return` style="${xml(style)}"`}if(!/^[A-Za-z_][\w:.-]*$/.test(key)||typeof value==="object"||typeof value==="function")throw new Error("Unsupported SVG attribute.");return` ${svgAttribute(key)}="${xml(String(value))}"`}).join("");return emit(`<${node.type}${attributes}>`)+serializeSvg(node.props.children,budget,depth+1)+emit(`</${node.type}>`)}function graphToReact(value,theme){if(Array.isArray(value))return value.map(child=>graphToReact(child,theme));if(!isElement(value))return value;const convertProp=prop=>{if(isElement(prop))return graphToReact(prop,theme);if(Array.isArray(prop))return prop.map(convertProp);if(prop&&typeof prop==="object")return Object.fromEntries(Object.entries(prop).map(([key,item])=>[key,convertProp(item)]));return prop};const props=Object.fromEntries(Object.entries(value.props).map(([name,prop])=>[name,convertProp(prop)]));const component=trustedComponents[value.type];if(component)props.c??=theme;return React21.createElement(component??value.type,props,...value.children.map(child=>graphToReact(child,theme)))}function renderSvgImage(element,assets,width,height,budget,outputScale=1,includePng=true){const root=React21.cloneElement(element,{xmlns:"http://www.w3.org/2000/svg",width,height});const svg=serializeSvg(root,budget);const image=new Resvg3(svg,{font:{loadSystemFonts:false,fontFiles:assets.fontFiles,defaultFontFamily:"Inter"},background:"rgba(0,0,0,0)",...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("SVG frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}}function rasterizeNestedSvg(node,assets,defaultWidth,defaultHeight,budget){if(++budget.nodes>SCENE_LIMITS.nodes*16)throw new Error("Resolved scene exceeds its host element budget.");if(Array.isArray(node))return node.map(child=>rasterizeNestedSvg(child,assets,defaultWidth,defaultHeight,budget));if(!React21.isValidElement(node))return node;if(node.type==="svg"){const width=typeof node.props.width==="number"?node.props.width:defaultWidth;const height=typeof node.props.height==="number"?node.props.height:defaultHeight;if(!Number.isInteger(width)||!Number.isInteger(height)||width<1||height<1||width>SCENE_LIMITS.canvasEdge||height>SCENE_LIMITS.canvasEdge||width*height>SCENE_LIMITS.canvasPixels){throw new Error("Nested SVG dimensions exceed the scene canvas limits.")}budget.pixels+=width*height;budget.count+=1;if(budget.pixels>defaultWidth*defaultHeight*4||budget.count>16){throw new Error("Nested SVG rasterization exceeds the per-frame pixel or image budget.")}const{png}=renderSvgImage(node,assets,width,height,budget);return React21.createElement("img",{width,height,src:`data:image/png;base64,${Buffer.from(png).toString("base64")}`,style:{display:"flex",flexShrink:0,...node.props.style}})}if(typeof node.type==="function")return rasterizeNestedSvg(node.type(node.props),assets,defaultWidth,defaultHeight,budget);validateResolvedSceneResources(node.props);return React21.cloneElement(node,{},rasterizeNestedSvg(node.props.children,assets,defaultWidth,defaultHeight,budget))}async function renderPreparedFrame(prepared,assets,time,outputScale,includePng){const evaluated=await prepared.evaluate(time);const{width,height,theme}=prepared.request;const c=getThemeColors(theme);let element=graphToReact(evaluated.graph,c);if(React21.isValidElement(element)&&element.type==="svg"){const image=renderSvgImage(React21.cloneElement(element,{children:[React21.createElement("rect",{key:"__scene_background",width,height,fill:c.bg}),element.props.children]}),assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0},outputScale,includePng);return image}element=React21.createElement("div",{style:{display:"flex",position:"relative",width,height,backgroundColor:c.bg,fontFamily:"Inter",color:c.textPrimary}},element);return withRenderContext({background:"theme"},async()=>{element=rasterizeNestedSvg(element,assets,width,height,{pixels:0,count:0,nodes:0,svgBytes:0});const accessible=prepareAccessibleSvg(element);const layoutNodes=[];const rendered=await satori(accessible.element,{width,height,fonts:assets.fonts,loadAdditionalAsset:async(code,segment)=>{if(code!=="emoji")return[];const points=[...segment].map(character=>character.codePointAt(0).toString(16));const candidates=[points.join("-"),points.filter(point=>point!=="fe0f").join("-")];const svg2=candidates.map(name=>assets.emoji[`${name}.svg`]).find(Boolean);if(!svg2)throw new Error("A scene glyph is not available in the pinned offline font and emoji assets.");return`data:image/svg+xml;base64,${Buffer.from(svg2).toString("base64")}`},onNodeDetected:node=>layoutNodes.push(node)});const svg=addSvgAccessibility(rendered,accessible.graphs,layoutNodes);const image=new Resvg3(svg,{background:c.bg,font:{loadSystemFonts:false,fontFiles:assets.fontFiles},...outputScale!==1?{fitTo:{mode:"width",value:width*outputScale}}:{}}).render();if(image.width!==width*outputScale||image.height!==height*outputScale)throw new Error("Layout frame does not match scaled scene dimensions.");return{pixels:image.pixels,...includePng?{png:image.asPng()}:{}}})}async function outputMetadata(prepared,assets,settings,outputPath,bytes,kind,time){const{width,height,duration,fps,frameCount}=prepared.request;const digest=createHash("sha256");for await(const chunk of createReadStream(outputPath))digest.update(chunk);return{runtimeVersion:SCENE_RUNTIME_VERSION,sourceSha256:prepared.sourceSha256,inputSha256:await sceneSha256(JSON.stringify({requestSha256:prepared.inputSha256,fontAssetsSha256:assets.sha256,kind,...time!==void 0?{time}:{},...settings.preview?{outputScale:settings.outputScale,width:settings.width,height:settings.height,fps:settings.fps,frameCount:settings.frameCount}:{}})),assetSha256:digest.digest("hex"),fontAssetsSha256:assets.sha256,width:settings.width,height:settings.height,duration,fps:settings.fps,frameCount:settings.frameCount,bytes,outputPath:resolve2(outputPath),...settings.preview?{outputScale:settings.outputScale,...kind==="mp4"?{previewFps:settings.fps}:{},logicalWidth:width,logicalHeight:height,logicalFps:fps,logicalFrameCount:frameCount}:{}}}async function atomicWrite(outputPath,bytes){const target=resolve2(outputPath);await mkdir3(dirname3(target),{recursive:true});const temporary=join3(dirname3(target),`.vizmatic-scene-${randomUUID2()}.tmp`);const file=await open2(temporary,"wx",384);try{await file.writeFile(bytes);await file.close();await rename2(temporary,target)}catch(error){await file.close().catch(()=>{});await rm2(temporary,{force:true});throw error}}async function renderSceneFrame(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale);const time=normalizeSceneTime(options.time,prepared.request.duration);const assets=await sceneAssets();const image=await renderPreparedFrame(prepared,assets,time,settings.outputScale,true);await atomicWrite(options.outputPath,image.png);return{...await outputMetadata(prepared,assets,settings,options.outputPath,image.png.byteLength,"png",time),time}}async function renderSceneVideo(options){if(typeof options.outputPath!=="string"||!options.outputPath)throw new Error("Scene outputPath is required.");const prepared=await prepareScene(options);const settings=outputSettings(prepared,options.outputScale,options.previewFps);const assets=await sceneAssets();const{duration}=prepared.request;const output=await renderRgbaVideo(async frame=>(await renderPreparedFrame(prepared,assets,frame.time/1e3,settings.outputScale,false)).pixels,{width:settings.width,height:settings.height,duration:duration*1e3,fps:settings.fps,outputPath:options.outputPath,signal:options.signal});return{...await outputMetadata(prepared,assets,settings,options.outputPath,output.bytes,"mp4"),encodedDuration:output.duration/1e3}}export{DENSITY_NAMES,DEFAULT_DENSITY,assertDensity,parseDensity,densityTokens,setDefaultDensity,setDensityResolver,densityOf,withDensity,getThemeColors,colors,gradients,toneGradients,getToneGradient,getToneColor,getReadableToneColor,getToneFill,typography,hasShadow,typeOf,canvas,getStyles,styles,getColor,getReadableColor,withColorAlpha,compositeColor,getReadableTextColor,getGradient,heatColor,withRenderContext,defineIllustration,Canvas,TitleBar,scopeDensity,Scene,Row,Column,ToneStrip,Icon,Panel,formatMathText,MathText,TextLabel,SvgMathText,Box,Arrow,FlowArrow,Connector,VectorArrow,VectorSegment,SvgFrame,SvgPoint,ArrowMarkerDef,Stack,Card,ValuePill,EquationCard,BadgePill,GradientChip,StepCard,MetricCard,estimateTextWidth,statusColor,StatusDot,Sparkline,InlineBar,FactRows,MetricStrip,TagList,DiagramLegend,SmallMultiples,ProgressRow,ProgressList,MiniBarChart,DetailList,Tile,TileGrid,CodeBlock,Comparison,KeyValueList,WindowFrame,StatusRow,StatusList,Timeline,Flow,routingSegmentBlocked,routeOrthogonalGraph,pointAlongSamples,LayeredNetwork,defineDiagramIcon,defineIconRegistry,GraphDiagram,TreeDiagram,CalloutCard,Pipeline,SequenceDiagram,DataflowDiagram,DeploymentDiagram,EntityRelationshipDiagram,formatTensorShape,TransformerTopology,Matrix,Heatmap,TiledMatrix,DataTable,Grid,AxisPlot,createPlotArea,ChartFrame,PieChart,DonutChart,StackedBar,BarChart,ParetoBarChart,LineChart,ScatterPlot,ParetoChart,QuadrantChart,IntervalPlot,Badge,DotPoint,DashedLine,Legend,CANVAS_ITEM_COMPONENT,Board,CanvasItem,mapNumberLine,NumberLine,geometryBounds,GeometryDiagram,sumForces,FreeBodyDiagram,waveValue,sampleWave,WaveDiagram,ELEMENT_SYMBOLS,MoleculeDiagram,reactionBalance,ReactionEquation,ReactionEnergyDiagram,seededRandom,lerpArray,dotProduct,multiplyMatrices,stableSoftmax,entropy,normalizeVector,sampleFunction,gaussian,sampleGaussian,scaledDotProductAttention,AttentionMatrix,transposeMatrix,rgbChannel,cropRgbImage,flattenRgbImage,PixelGrid,crossCorrelate2d,gaussianKernel,decodePng,encodePng,decodeRgbPng,encodeRgbPng,cropRgbRaster,gaussianBlurRgb,primitives_exports,normalizeWatermark,Watermark,wrapWithWatermark,wrapWithBrand,detectBackgroundColor,detectContentBounds,cropPixels,detectOverflow,detectLayoutOverflow,satori,loadAdditionalAsset,getFonts,CanvasOverflowError,renderToPng,renderToPngWithOutput,renderToBuffer,renderToSvg,hold,keyframe,tween,parallel,defineAnimation,sampleAnimation,sampleAnimationFrame,analyzeAnimationCadence,sampleAnimationFrames,chapterMetadata,captionsToSrt,videoFrameSchedule,renderAnimationVideo,renderRgbaVideo,extractRootJsx,findBareRootJsxStart,SCENE_RUNTIME_VERSION,SCENE_LIMITS,prepareScene,evaluateSceneSource,renderSceneFrame,renderSceneVideo};
|