=============== LIBRARY RULES =============== From library maintainers: - AGENTS.md lists every entry point, its runtime and the common mistakes; check it before importing from a subpath. - Functions take a single flat object parameter: options sit beside aslDefinition, e.g. generateSvg({ aslDefinition, layout: 'LR', theme: 'dark' }), never under an options key. - Runtimes: 'sfn-diagram', 'sfn-diagram/cfn' and 'sfn-diagram/terraform' run in Node, browsers and edge. 'sfn-diagram/png' (exportPng), 'sfn-diagram/aws', 'sfn-diagram/ci' and the CLI are Node-only. 'sfn-diagram/element' is browser-only. - generateFromAwsResponse is exported from the root 'sfn-diagram' entry, not from 'sfn-diagram/aws'. - The extractors return an object: const { aslDefinition } = extractAslFromTemplate({ template }) from 'sfn-diagram/cfn', or extractAslFromTerraform({ config }) from 'sfn-diagram/terraform'. - When a template or Terraform config defines more than one state machine, also pass resourceId: the CloudFormation logical ID, or the Terraform resource name (e.g. aws_sfn_state_machine.orders). ### Run the playground locally with pnpm Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/playground.md Install dependencies, build the library, and start the site dev server. The editor is then served at /playground. ```bash pnpm install pnpm run build # build the library the playground imports pnpm --filter sfn-diagram-site dev ``` -------------------------------- ### Install sfn-diagram with bun Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs the core sfn-diagram package using bun. ```bash bun add sfn-diagram ``` -------------------------------- ### Install sfn-diagram-react with bun Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/react.mdx Install the sfn-diagram-react package along with sfn-diagram and react using bun. ```bash bun add sfn-diagram-react sfn-diagram react ``` -------------------------------- ### Install sfn-diagram-react with npm Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/react.mdx Install the sfn-diagram-react package along with sfn-diagram and react using npm. ```bash npm install sfn-diagram-react sfn-diagram react ``` -------------------------------- ### Install sfn-diagram-react with pnpm Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/react.mdx Install the sfn-diagram-react package along with sfn-diagram and react using pnpm. ```bash pnpm add sfn-diagram-react sfn-diagram react ``` -------------------------------- ### Install sfn-diagram and @resvg/resvg-js with bun Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs sfn-diagram along with the optional peer dependency @resvg/resvg-js for PNG export. ```bash bun add sfn-diagram @resvg/resvg-js ``` -------------------------------- ### Install sfn-diagram-react with yarn Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/react.mdx Install the sfn-diagram-react package along with sfn-diagram and react using yarn. ```bash yarn add sfn-diagram-react sfn-diagram react ``` -------------------------------- ### Install standalone binary with Homebrew Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Install the sfn-diagram standalone binary using Homebrew, or download the binary from a core release and make it executable with chmod +x. ```bash brew install yusufaf/tap/sfn-diagram # or download sfn-diagram-- from a core release and chmod +x it ``` -------------------------------- ### Install sfn-diagram and @resvg/resvg-js with pnpm Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs sfn-diagram along with the optional peer dependency @resvg/resvg-js for PNG export. ```bash pnpm add sfn-diagram @resvg/resvg-js ``` -------------------------------- ### Install sfn-diagram with yarn Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs the core sfn-diagram package using yarn. ```bash yarn add sfn-diagram ``` -------------------------------- ### Example sfn-diagram.config.json Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx A sample configuration file showing layout, icons, padding, and theme settings. ```json { "layout": "LR", "showIcons": true, "padding": 40, "theme": { "base": "dark", "background": "#101014" } } ``` -------------------------------- ### Install sfn-diagram with pnpm Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs the core sfn-diagram package using pnpm. ```bash pnpm add sfn-diagram ``` -------------------------------- ### Following output example Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Example output while following an execution, showing polling every 2 seconds and the final success message. ```text following arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 every 2s (Ctrl-C to stop) ... arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 succeeded after 14 update(s) ``` -------------------------------- ### Output of sfn-diagram --watch Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Example output from the --watch command, showing the initial message and change notifications. The output indicates that watching has started and lists changed files. ```text watching 2 path(s); Ctrl-C to stop machines/order.asl.json changed machines/payments.asl.json changed stopped watching ``` -------------------------------- ### Install sfn-diagram via Homebrew Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Installs the standalone binary on macOS and Linux via Homebrew. No Node.js required. ```bash brew install yusufaf/tap/sfn-diagram ``` -------------------------------- ### Install sfn-diagram from JSR with Deno Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs the sfn-diagram package from JSR using Deno. ```bash deno add jsr:@yusufaf/sfn-diagram ``` -------------------------------- ### Build and install local .vsix Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/vscode-sfn-diagram/README.md Run these commands from the packages/vscode-sfn-diagram directory to produce a .vsix file and install it into VS Code. Requires pnpm and the VS Code CLI. ```bash cd packages/vscode-sfn-diagram pnpm install pnpm package # produces vscode-sfn-diagram-.vsix code --install-extension vscode-sfn-diagram-*.vsix ``` -------------------------------- ### Install sfn-diagram and @resvg/resvg-js with yarn Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/installation.mdx Installs sfn-diagram along with the optional peer dependency @resvg/resvg-js for PNG export. ```bash yarn add sfn-diagram @resvg/resvg-js ``` -------------------------------- ### Install extension via Codium CLI (Open VSX) Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/vscode-sfn-diagram/README.md Install the extension from the Open VSX registry using the Codium CLI, which is the default for Cursor, Windsurf, VSCodium, Gitpod, and Eclipse Theia. ```bash codium --install-extension yusufaf.vscode-sfn-diagram ``` -------------------------------- ### Install sfn-diagram-react and sfn-diagram Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Install the package and its peer dependency. Use either npm or pnpm. Requires sfn-diagram >= 1.7.0. ```bash npm install sfn-diagram-react sfn-diagram # or pnpm add sfn-diagram-react sfn-diagram ``` -------------------------------- ### Install optional peer and render live state machine with --from-aws Source: https://github.com/yusufaf/sfn-diagram/blob/main/README.md Install the optional peer dependency @aws-sdk/client-sfn needed for --from-aws, then render a live state machine from its ARN to an SVG file. The region is derived from the ARN and credentials come from the AWS SDK's default chain, so AWS_PROFILE, SSO, and instance roles work as with the AWS CLI. The flag accepts a state machine, version, or alias ARN (not a bare name), is repeatable with --out-dir, and combines with --diff, --execution, and --check. ```bash pnpm add @aws-sdk/client-sfn # optional peer, only needed for --from-aws sfn-diagram --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders -o live.svg ``` -------------------------------- ### Follow execution with --follow Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Add --follow to keep updating the output file until the execution finishes. The example writes to an HTML file. ```bash sfn-diagram order.asl.json \ --execution arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 \ --follow -o run.html ``` -------------------------------- ### Install sfn-diagram via npm Source: https://github.com/yusufaf/sfn-diagram/blob/main/README.md Installs the core package, which includes no browser engine or native rasterizer. SVG and Mermaid generation remain lightweight. ```bash npm install sfn-diagram ``` -------------------------------- ### Install Step Functions Diagram extension via CLI Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/vscode.md Install the extension from the command line using the VS Code CLI. This is an alternative to searching for 'Step Functions Diagram' in the Extensions panel. ```bash code --install-extension yusufaf.vscode-sfn-diagram ``` -------------------------------- ### Config file error example Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows the error output and exit code when a config file contains an invalid theme. ```bash $ sfn-diagram state.asl.json --config ci/sfn.json Error: Invalid theme in /repo/ci/sfn.json: expected 'light', 'dark', or a custom theme object $ echo $? 1 ``` -------------------------------- ### Install sfn-diagram with PNG support Source: https://github.com/yusufaf/sfn-diagram/blob/main/README.md Adds the optional peer dependency @resvg/resvg-js for PNG export. Only needed if you use sfn-diagram/png. ```bash npm install sfn-diagram @resvg/resvg-js ``` -------------------------------- ### Lint a Definition with lintAsl Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/examples.md Runs lintAsl on an ASL definition to get diagnostics. lintAsl never throws; it returns an array of diagnostics with codes like 'unreachable-state' and severity levels. The example exits with code 1 if any error-severity diagnostic is found. ```typescript import { lintAsl } from 'sfn-diagram'; const diagnostics = lintAsl({ definition: asl }); // [ // { code: 'unreachable-state', severity: 'warning', path: '/States/Audit', // message: 'State "Audit" is unreachable from StartAt "Validate"' }, // ] if (diagnostics.some((diagnostic) => diagnostic.severity === 'error')) { process.exit(1); } ``` -------------------------------- ### Example lint output Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Example output from the --check command. Each line shows severity, a JSON Pointer to the offending value, the message, and the rule code. The final line reports the total counts of errors and warnings. ```text error /States/Ship/Next State "Ship" sets both "End: true" and "Next" [end-with-next] warning /States/Audit State "Audit" is unreachable from StartAt "Validate" [unreachable-state] 1 error, 1 warning ``` -------------------------------- ### Run sfn-diagram via Docker for SVG and PNG output Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Runs the prebuilt Docker image from GitHub Container Registry, mounting the current directory to /work. The first command generates an SVG diagram, the second generates a PNG diagram. The image includes the PNG rasterizer, so `--format png` works without extra setup. ```bash docker run --rm -v "$PWD":/work ghcr.io/yusufaf/sfn-diagram:latest \ /work/state.asl.json --format svg -o /work/diagram.svg ``` ```bash docker run --rm -v "$PWD":/work ghcr.io/yusufaf/sfn-diagram:latest \ /work/state.asl.json --format png -o /work/diagram.png ``` -------------------------------- ### Full CustomTheme example Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Shows a complete CustomTheme object specifying background, edge colors, font family, font size, node colors for all state types, and text color. The example includes a comment noting that the 'retry' edge color is optional and falls back to 'error' when omitted. It is passed to generateSvg. ```typescript const customTheme: CustomTheme = { background: '#ffffff', edgeColors: { choice: '#7b1fa2', default: '#607d8b', error: '#f44336', normal: '#232f3e', retry: '#f9a825', // optional; falls back to `error` when omitted }, fontFamily: 'Arial, sans-serif', fontSize: 14, nodeColors: { Pass: { fill: '#e8f5e9', stroke: '#4caf50' }, Task: { fill: '#e3f2fd', stroke: '#2196f3' }, Choice: { fill: '#fff3e0', stroke: '#ff9800' }, Wait: { fill: '#f3e5f5', stroke: '#9c27b0' }, Succeed: { fill: '#e8f5e9', stroke: '#4caf50' }, Fail: { fill: '#ffebee', stroke: '#f44336' }, Parallel: { fill: '#e0f7fa', stroke: '#00bcd4' }, Map: { fill: '#e8eaf6', stroke: '#3f51b5' }, }, textColor: '#232f3e', }; generateSvg({ aslDefinition: asl, theme: customTheme }); ``` -------------------------------- ### Run sfn-diagram with --watch on a single file and a glob Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows two example invocations of the --watch flag: one watching a single file and one watching a glob pattern. The command renders once and then re-renders on changes. ```bash sfn-diagram order.asl.json --watch -o diagram.svg sfn-diagram 'machines/**/*.asl.json' --watch --out-dir diagrams ``` -------------------------------- ### CustomTheme partial override example Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Shows how to create a custom theme by overriding only specific fields. The 'bigDark' theme sets base to 'dark' and fontSize to 18, while 'greenTasks' overrides only the Task fill color, leaving other colors from the base theme. The example also demonstrates passing the theme to generateSvg. ```typescript import type { CustomTheme } from 'sfn-diagram'; // Dark theme, bigger labels const bigDark: CustomTheme = { base: 'dark', fontSize: 18 }; // Light theme with a different Task fill — the Task stroke and every other colour stay const greenTasks: CustomTheme = { nodeColors: { Task: { fill: '#e8f5e9' } } }; generateSvg({ aslDefinition: asl, theme: bigDark }); ``` -------------------------------- ### Build the action bundle Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/github-action-sfn-diagram/README.md Rebuild the bundled dist/index.js after changing src/ or bumping the core. The bundle is committed because GitHub runs the action without installing dependencies. ```bash pnpm --filter github-action-sfn-diagram build ``` -------------------------------- ### Custom theme JSON file (brand.theme.json) Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Example of a custom theme file. Every field is optional; 'base' selects the built-in theme that supplies omitted fields. A missing file, malformed JSON, or a non-object top-level value causes a runtime failure with 'Error: Cannot read theme file : ' and exit code 1. ```json { "base": "light", "background": "#fbfbfd", "fontFamily": "Inter, system-ui, sans-serif", "nodeColors": { "Task": { "fill": "#eef2ff", "stroke": "#4338ca" }, "Choice": { "fill": "#fefce8", "stroke": "#a16207" } } } ``` -------------------------------- ### ASL definition example: order-processing workflow Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/introduction.md An example ASL definition for an order-processing workflow, used to demonstrate sfn-diagram's rendering. It includes Pass, Choice, Task, Fail, and Succeed states. ```jsonc { "StartAt": "ValidateOrder", "States": { "ValidateOrder": { "Type": "Pass", "Next": "CheckStock" }, "CheckStock": { "Type": "Choice", "Choices": [{ "Variable": "$.inStock", "BooleanEquals": true, "Next": "ChargePayment" }], "Default": "CancelOrder" }, "ChargePayment": { "Type": "Task", "Resource": "arn:aws:lambda:...:charge-payment", "Next": "ShipOrder" }, "ShipOrder": { "Type": "Task", "Resource": "arn:aws:lambda:...:ship-order", "Next": "OrderComplete" }, "CancelOrder": { "Type": "Fail", "Error": "OutOfStock" }, "OrderComplete": { "Type": "Succeed" } } } ``` -------------------------------- ### GitHub Action workflow usage Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/github-action-sfn-diagram/README.md Example workflow that triggers on pull requests with ASL file changes, sets required permissions, and uses the action. No checkout step is needed because the action reads files via the GitHub API. ```yaml # .github/workflows/sfn-preview.yml name: Step Functions Preview on: pull_request: paths: ['**/*.asl.json', '**/*.asl'] permissions: contents: read pull-requests: write jobs: preview: runs-on: ubuntu-latest steps: - uses: yusufaf/sfn-diagram-action@v1 ``` -------------------------------- ### Read action outputs in a workflow step Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/github-action-sfn-diagram/README.md Use the action with an id to access its outputs in subsequent steps. The example checks if the changed-count output is not '0' to conditionally run a notification step. ```yaml - name: Preview Step Functions diagrams id: preview uses: yusufaf/sfn-diagram-action@v1 - name: Notify on diagram changes if: steps.preview.outputs.changed-count != '0' run: echo "${{ steps.preview.outputs.changed-count }} ASL file(s) changed" ``` -------------------------------- ### useSfnDiagram hook for raw output Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Use the hook to get the raw SVG/HTML string, Mermaid code, dimensions, and metadata without mounting anything. Accepts the same option-bearing props as `` but not presentational ones. Errors are returned as `{ type: 'error', error }` rather than thrown. ```tsx import { useSfnDiagram } from 'sfn-diagram-react' function DownloadSvgButton({ definition }: { definition: object }) { const result = useSfnDiagram({ definition }) if (result.type !== 'svg') return null const href = `data:image/svg+xml;base64,${btoa(result.svg)}` return ( Download SVG ) } ``` -------------------------------- ### Generate SVG from ASL definition Source: https://github.com/yusufaf/sfn-diagram/blob/main/README.md Imports generateSvg and generates an SVG diagram from an ASL definition. The example uses a simple two-state machine with layout 'TB' and theme 'light'. ```ts import { generateSvg } from 'sfn-diagram'; const { svg } = generateSvg({ aslDefinition: { StartAt: 'Hello', States: { Hello: { Type: 'Pass', Next: 'World' }, World: { Type: 'Succeed' }, }, }, layout: 'TB', theme: 'light', }); ``` -------------------------------- ### Redact hook example for generateHtml Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Example of using the redact option in generateHtml to redact payloads and Parameters fields. The hook is called per state and per field; returning undefined redacts the value, inlining '[redacted]' (exported as REDACTED). ```typescript const { html } = generateHtml({ aslDefinition: asl, redact: ({ kind, path, value }) => kind === 'payload' || path.endsWith('.Parameters') ? undefined : value, }); ``` -------------------------------- ### Exit code 0 with --check and --watch Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Example of running --check with --watch, showing that interrupting the watch exits with code 0 even if there are errors. The output includes an error message and the final 'stopped watching' line. ```bash $ sfn-diagram order.asl.json --check --watch watching 1 path(s); Ctrl-C to stop order.asl.json changed error /States/Next Unreachable state [unreachable-state] ^C stopped watching # exit 0 ``` -------------------------------- ### Exit codes for bad paths Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Commands with unreadable paths exit with code 1 (runtime failure), not 2. The example shows three invocations with missing files, each returning 1. ```bash sfn-diagram missing.asl.json # 1 sfn-diagram state.asl.json --diff gone.json # 1 sfn-diagram state.asl.json --theme gone.json # 1 ``` -------------------------------- ### Class-based API: SfnDiagramGenerator Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/quick-start.md Use the class-based API to create a generator instance with configuration options, then generate both SVG and Mermaid diagrams from an ASL definition. The example shows the constructor and the generateSvg and generateMermaid methods. ```typescript import { SfnDiagramGenerator } from 'sfn-diagram'; const generator = new SfnDiagramGenerator({ theme: 'dark', layout: 'TB', nodeWidth: 150, nodeHeight: 80, }); const { svg } = generator.generateSvg({ aslDefinition: asl }); const { code } = generator.generateMermaid({ aslDefinition: asl }); ``` -------------------------------- ### Function-based API: generateSvg Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/quick-start.md Use the function-based API to generate an SVG diagram from an ASL definition. The example imports generateSvg and writeFileSync, defines a simple state machine, and writes the SVG to a file. The output includes the SVG string and its dimensions. ```typescript import { generateSvg } from 'sfn-diagram'; import { writeFileSync } from 'fs'; const asl = { StartAt: 'HelloWorld', States: { HelloWorld: { Type: 'Pass', Result: 'Hello, World!', End: true } } }; const { svg, width, height } = generateSvg({ aslDefinition: asl, theme: 'dark', layout: 'LR' }); writeFileSync('diagram.svg', svg); console.log(`Generated ${width}x${height} diagram`); ``` -------------------------------- ### Deep link URL examples for state and edge selection Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Shows the URL fragment format used to deep-link to a specific state or edge in the standalone HTML viewer. The edge id is percent-encoded because it contains '->'. Opening such a link opens the panel on that state or edge; closing the panel clears the fragment. ```text diagram.html#sfn=state:ProcessOrder diagram.html#sfn=edge:ProcessOrder-%3EShip ``` -------------------------------- ### Check exit codes with --check Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use `--check` to lint a state machine definition. The command exits with 0 for clean or warnings only, 1 for lint errors, and 2 for usage errors. The example shows a `case` statement on `$?` to handle each code. ```bash sfn-diagram state.asl.json --check case $? in 0) echo "clean (or warnings only)" ;; 1) echo "lint errors found" ;; 2) echo "bad invocation" ;; esac ``` -------------------------------- ### Svelte 5 usage: bind element with bind:this Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/web-component.mdx In Svelte 5, use `bind:this={el}` to get a reference to the element and set the `definition` property. The `interactive` attribute is also included. ```svelte ``` -------------------------------- ### Capture exit status in CI Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx In CI, capture the exit status into a variable before branching. Inside `if ! command; then`, `$?` is the status of the negated test (always 0), so a `case` on it would never match. The example uses `set +e` to avoid exiting on failure, then branches on the captured status. ```yaml - name: Render the diagram run: | set +e sfn-diagram state.asl.json -o diagram.svg status=$? set -e case "$status" in 0) ;; 2) echo "::error::sfn-diagram was invoked incorrectly - check the flags"; exit 1 ;; *) echo "::error::sfn-diagram failed to render - check the definition"; exit 1 ;; esac ``` -------------------------------- ### onStateClick event handler Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Fires when a state node is clicked, SVG format only. Not invoked for `format="mermaid"` or `format="html"`. `stateId` is the graph node id, which equals the state name for unique names; nested states with repeated names get a scope-qualified id. No click listener is attached when `onStateClick` is omitted. ```tsx console.log('clicked', stateId)} /> ``` -------------------------------- ### Download and run standalone binary directly Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Downloads the Linux x64 standalone binary, makes it executable, and verifies the version. Substitute your platform; Windows uses sfn-diagram-windows-x64.exe. The standalone build lacks AWS flags and PNG format. ```bash curl -fsSL -o sfn-diagram \ https://github.com/yusufaf/sfn-diagram/releases/download/sfn-diagram-v1.8.0/sfn-diagram-linux-x64 # x-release-please-version chmod +x sfn-diagram ./sfn-diagram --version ``` -------------------------------- ### Using the config file with CLI flags Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows how to use the config file by default, override it with a flag, and specify a custom config path. ```bash sfn-diagram state.asl.json -o diagram.svg # uses the file sfn-diagram state.asl.json -o diagram.svg --layout TB # the flag wins sfn-diagram state.asl.json -o diagram.svg --config ci/sfn.yaml ``` -------------------------------- ### Follow with --from-aws Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use --from-aws to fetch the state machine definition and --execution with --follow to render a running execution. Note that --from-aws returns the current definition, which may not match the one used for the run. ```bash sfn-diagram --from-aws arn:...:stateMachine:Orders \ --execution arn:...:execution:Orders:run-1 --follow -o run.html ``` -------------------------------- ### Fetch and render a state machine from AWS with --from-aws Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Fetches a state machine definition from AWS using DescribeStateMachine and renders it to a file. Requires the optional peer dependency @aws-sdk/client-sfn. ```bash sfn-diagram --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders -o live.svg ``` ```bash pnpm add @aws-sdk/client-sfn ``` -------------------------------- ### Use --from-aws with npx and the AWS SDK Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows how to run --from-aws via npx when the standalone binary is not available, explicitly including the @aws-sdk/client-sfn package. ```bash npx --package sfn-diagram --package @aws-sdk/client-sfn sfn-diagram --from-aws arn:... ``` -------------------------------- ### Run sfn-diagram with a custom theme file Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use --theme with a path to a JSON file to apply a custom theme. Any value that isn't 'light' or 'dark' is read as a path. ```bash sfn-diagram state.asl.json --theme ./brand.theme.json -o diagram.svg ``` -------------------------------- ### Import core and Node-only entry points Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/runtimes.md Shows how to import the core `generateSvg` function (works in Node, browser, and edge) and the Node-only `exportPng` and `runGitlabComment` functions from their respective entry points. ```typescript // Works in Node, browser, and edge: import { generateSvg } from 'sfn-diagram'; // Node-only: import { exportPng } from 'sfn-diagram/png'; import { runGitlabComment } from 'sfn-diagram/ci'; ``` -------------------------------- ### Generate interactive HTML diagram with --format html Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Use the CLI to generate a self-contained interactive HTML viewer. No external dependencies, opens offline from file://. ```bash npx sfn-diagram state.asl.json --format html -o diagram.html ``` -------------------------------- ### Sync action to mirror repository Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/github-action-sfn-diagram/README.md Run the sync script from the repo root to rebuild the bundle and push the generated payload to the mirror's main branch. Requires gh with push access to the mirror. ```bash pnpm sync:action ``` -------------------------------- ### Compare live definitions with --diff Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows two ways to use --diff with --from-aws: comparing a live definition against a local baseline, and comparing two live definitions (staging vs production). ```bash # deployed vs. the repo sfn-diagram --from-aws arn:...:stateMachine:Orders --diff machines/order.asl.json --format mermaid # staging vs. production sfn-diagram --from-aws arn:aws:states:us-east-1:1:stateMachine:Orders \ --diff arn:aws:states:eu-west-1:2:stateMachine:Orders --format mermaid ``` -------------------------------- ### Transparent theme JSON file (transparent.theme.json) Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Minimal theme file that sets the background to transparent, allowing --background-color to show through. ```json { "base": "light", "background": "transparent" } ``` -------------------------------- ### Run sfn-diagram via npx in a CDK project Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Use this command in any CDK project (Python, Java, C#, Go) to generate a diagram from a synthesized CloudFormation template. Requires Node.js at synth time, which is already present in CDK projects. ```bash npx sfn-diagram cdk.out/MyStack.template.json --resource MyStateMachine -o diagram.svg ``` -------------------------------- ### Generate diagram via CLI Source: https://github.com/yusufaf/sfn-diagram/blob/main/README.md Uses npx to run the sfn-diagram CLI, converting an ASL file to SVG output. ```bash npx sfn-diagram my-workflow.asl.json --format svg -o diagram.svg ``` -------------------------------- ### Run sfn-diagram via Docker with stdin Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Runs the sfn-diagram Docker image, reading a state machine definition from stdin and writing an SVG diagram to stdout. The `--format svg` flag is used; the image is the only option that supports PNG. ```bash docker run --rm -i ghcr.io/yusufaf/sfn-diagram:latest - --format svg \ < state.asl.json > diagram.svg ``` -------------------------------- ### Astro: render static SVG with set:html Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/frameworks.md Astro runs the frontmatter at build time, so the diagram ships as static markup with zero client-side JavaScript. Uses ?raw import to read the ASL file as a string and sets theme to 'light'. ```astro --- import { generateSvg } from 'sfn-diagram'; // `?raw` gives the file as a string, which `aslDefinition` accepts directly import definition from '../workflows/order-processing.asl.json?raw'; const { svg } = generateSvg({ aslDefinition: definition, theme: 'light' }); --- ``` -------------------------------- ### Show help for `sfn-diagram comment gitlab` Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Displays the help text for the `comment gitlab` command, which posts or updates a diagram/diff on a GitLab merge request from CI. See the GitLab CI documentation for the full workflow and options. ```bash sfn-diagram comment gitlab --help ``` -------------------------------- ### Config file search names Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Lists the filenames tried in order when searching for a configuration file. ```text sfn-diagram.config.json sfn-diagram.config.yaml sfn-diagram.config.yml .sfn-diagramrc .sfn-diagramrc.json .sfn-diagramrc.yaml .sfn-diagramrc.yml ``` -------------------------------- ### Call sfn-diagram from Python Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Uses subprocess to run the sfn-diagram CLI with stdin and stdout, returning the SVG string. The `layout` parameter defaults to "TB". Swap the command for `["npx", "sfn-diagram"]` in a CDK project or for the Docker command if preferred. ```python import json import subprocess def render_svg(definition: dict, layout: str = "TB") -> str: result = subprocess.run( ["sfn-diagram", "-", "--format", "svg", "--layout", layout], input=json.dumps(definition), capture_output=True, check=True, text=True, ) return result.stdout ``` -------------------------------- ### Render multiple state machines with --from-aws and --out-dir Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Repeats --from-aws for multiple ARNs and uses --out-dir to write each output named after the state machine. The comment shows the resulting filenames. ```bash sfn-diagram \ --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Orders \ --from-aws arn:aws:states:us-east-1:111122223333:stateMachine:Refunds \ --out-dir diagrams # diagrams/Orders.svg, diagrams/Refunds.svg ``` -------------------------------- ### Development commands Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/vscode-sfn-diagram/README.md Use these commands during development. pnpm build bundles with esbuild to out/extension.js, pnpm dev rebuilds on change, and pnpm typecheck runs tsc --noEmit. Press F5 in VS Code to launch an Extension Development Host. ```bash pnpm build # bundle with esbuild -> out/extension.js pnpm dev # rebuild on change pnpm typecheck # tsc --noEmit ``` -------------------------------- ### Interactive viewer with format="html" Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Render the full interactive pan/zoom/search viewer inside a sandboxed iframe. Page CSS does not reach the iframe; size it yourself. onStateClick does not fire from inside it. Cannot be combined with history. ```tsx ``` -------------------------------- ### Generate diagram from Terraform file with sfn-diagram CLI Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use this command to generate a diagram from a Terraform file. The --resource flag selects a specific state machine when the file declares several. Terraform files are detected by extension or by an aws_sfn_state_machine resource for stdin/extensionless files. ```bash sfn-diagram main.tf --resource orders -o orders.svg ``` -------------------------------- ### Generate HTML diff with CLI Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Use the CLI to generate an HTML diff overlay. The --format html option enables the viewer for easier inspection of large diffs. ```bash npx sfn-diagram head.asl.json --diff base.asl.json --format html -o diff.html ``` -------------------------------- ### Generate diagram from execution ARN Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use --execution with an ARN to fetch the execution history live and generate a diagram. The output is written to the specified file. ```bash sfn-diagram order.asl.json \ --execution arn:aws:states:us-east-1:111122223333:execution:Orders:run-1 -o run.svg ``` -------------------------------- ### Import types from sfn-diagram and sfn-diagram/png Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/typescript.md Shows how to import type definitions from the main package and the Node-only subpath for PNG-related types. ```typescript import type { AslDefinition, DiagramOptions, SvgOutput, MermaidOutput, CustomTheme, StateType } from 'sfn-diagram'; // PNG types live on the Node-only subpath import type { PngOutput, ExportPngParams } from 'sfn-diagram/png'; ``` -------------------------------- ### Render diagram with npx and pipe input Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Renders an SVG diagram from a state machine JSON file piped to the CLI. The `-` argument tells the CLI to read from stdin. Works with any runner that supports piping, such as pnpm dlx, yarn dlx, or bunx. ```bash cat state.asl.json | npx sfn-diagram - --format svg ``` -------------------------------- ### Workflow to comment Step Functions diagram on pull request Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/github-action.md Add this workflow to run the action on pull requests that touch ASL files. It requires pull-requests: write permission and uses the action yusufaf/sfn-diagram-action@v1. No checkout step is needed because the action reads files via the GitHub API. ```yaml # .github/workflows/sfn-preview.yml name: Step Functions Preview on: pull_request: paths: ['**/*.asl.json', '**/*.asl'] permissions: contents: read pull-requests: write # required to post the comment jobs: preview: runs-on: ubuntu-latest steps: - uses: yusufaf/sfn-diagram-action@v1 ``` -------------------------------- ### Run sfn-diagram with transparent theme and background color Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use --background-color with a transparent theme to set the PNG background. The built-in light and dark themes paint their own background, so the flag has no visible effect unless the theme's background is transparent. ```bash sfn-diagram state.asl.json --format png --theme ./transparent.theme.json \ --background-color '#ffffff' -o diagram.png ``` -------------------------------- ### Imperative handle (ref) Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md SfnDiagram forwards a ref exposing `getSvg()` which returns the rendered SVG markup for format="svg", or null for other formats. ```APIDOC ## Imperative handle (ref) ### Description SfnDiagram forwards a `ref` exposing `{ getSvg(): string | null }` — the rendered SVG markup for `format="svg"`, or `null` for every other format (including an errored render). ### Methods - `getSvg()` (() => string | null) - Returns the SVG markup for `format="svg"`, or `null` otherwise. ### Usage Example ```tsx const ref = useRef(null) // later: ref.current?.getSvg() ``` ### Notes - There is no programmatic zoom/pan control — core doesn't expose the interactive viewer's controller from a public subpath yet, so a meaningful pan/zoom handle needs a core change first. ``` -------------------------------- ### Call sfn-diagram from Java Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/other-languages.md Uses ProcessBuilder to run the sfn-diagram CLI, writing the definition JSON to stdin and reading the SVG from stdout. Throws an exception if the process exits with a non-zero code. ```java Process process = new ProcessBuilder("sfn-diagram", "-", "--format", "svg") .redirectError(ProcessBuilder.Redirect.INHERIT) .start(); try (var stdin = process.getOutputStream()) { stdin.write(definitionJson.getBytes(StandardCharsets.UTF_8)); } String svg = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8); if (process.waitFor() != 0) { throw new IllegalStateException("sfn-diagram failed"); } ``` -------------------------------- ### Register with auto-import and set definition Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/web-component.mdx Imports the zero-config auto-registering module and uses the element with interactive and theme attributes. The script sets the definition property to a custom ASL definition object. ```html ``` -------------------------------- ### Basic usage of SfnDiagram component Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Import SfnDiagram and render it with an ASL definition object. The definition can also be a JSON string. Options like layout, theme, and onError are forwarded. ```tsx import { SfnDiagram } from 'sfn-diagram-react' const definition = { StartAt: 'Hello', States: { Hello: { Type: 'Pass', Next: 'World' }, World: { Type: 'Succeed' }, }, } export function Diagram() { return ( console.error(error)} /> ) } ``` -------------------------------- ### Server-rendered with pre-rendered SVG Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/ecosystem/web-component.mdx Omit the `definition` attribute and provide a pre-rendered `` child from `generateSvg()` to keep the element untouched. The `set:html` directive injects the SVG. Adding `interactive` still upgrades it with pan/zoom and search, but the detail panel requires the original ASL client-side. ```astro --- import { generateSvg } from 'sfn-diagram'; const { svg } = generateSvg({ aslDefinition: definition }); --- ``` -------------------------------- ### Render multiple files with --out-dir Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Pass multiple input files or a glob pattern to sfn-diagram with --out-dir to render all definitions into a directory. Quote the glob to ensure consistent expansion across shells, including Windows cmd and PowerShell. ```bash sfn-diagram machines/order.asl.json machines/refund.asl.json --out-dir diagrams sfn-diagram 'machines/**/*.asl.json' --out-dir diagrams ``` -------------------------------- ### Use --resolve-cfn with a live baseline Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Shows how --resolve-cfn works on the head of a diff when the baseline is an ARN, unwrapping the template while leaving the live baseline untouched. ```bash sfn-diagram template.yaml --resolve-cfn --diff arn:...:stateMachine:Orders --format mermaid ``` -------------------------------- ### Generate diff and execution overlays with sfn-diagram CLI Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Use these commands to highlight changes between revisions, color a diagram by execution history, or combine both. The diff and execution flags support SVG, Mermaid, and HTML formats; combining them requires HTML. Other formats exit with code 2. The change/status summaries are written to stderr. ```bash # Highlight what changed between two revisions of a definition npx sfn-diagram head.asl.json --diff base.asl.json -o diff.svg npx sfn-diagram head.asl.json --diff base.asl.json --format mermaid > diff.mmd # Colour a diagram by what actually happened in a run aws stepfunctions get-execution-history --execution-arn "$ARN" > history.json npx sfn-diagram state.asl.json --execution history.json -o run.svg # Both at once: a run painted onto what changed (HTML only) npx sfn-diagram head.asl.json --diff base.asl.json --execution history.json --format html -o run.html ``` -------------------------------- ### Build execution timeline Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Use buildExecutionTimeline to replay a run as an ordered list of state runs. Each Retry attempt, Map iteration, and Parallel branch is an entry with stateName, attempt, and status. ```typescript import { buildExecutionTimeline } from 'sfn-diagram'; const { entries } = buildExecutionTimeline({ definition: asl, events }); for (const entry of entries) { // ProcessOrder attempt 2 failed console.log(entry.stateName, entry.attempt, entry.status); } ``` -------------------------------- ### generateSvg with edgeOverrides using bare and qualified keys Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Shows how to use edgeOverrides with both a bare 'Route->Work' key and a qualified 'Route->Work#choice#1' key. The qualified key is merged on top of the bare one, allowing a pair-wide width and a single-branch color to compose. ```typescript generateSvg({ aslDefinition: asl, edgeOverrides: { // Both branches out of Route get the thicker stroke... 'Route->Work': { strokeWidth: 2 }, // ...and only the second Choice rule is recoloured. 'Route->Work#choice#1': { stroke: '#d13212' }, }, }); ``` -------------------------------- ### CLI: collapse containers (--collapse) Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/configuration.md Collapse Parallel/Map containers into placeholder nodes for a smaller diagram. Can specify state names to collapse only those containers. Applies to SVG, Mermaid, HTML, and --diff (except --diff --format mermaid), but not to --execution overlays. ```bash npx sfn-diagram state.asl.json --collapse --format svg -o diagram.svg ``` -------------------------------- ### useSfnDiagram hook Source: https://github.com/yusufaf/sfn-diagram/blob/main/packages/sfn-diagram-react/README.md Returns the raw output (SVG/HTML string, Mermaid code, dimensions, metadata) without mounting anything. Accepts the same option-bearing props as SfnDiagram, but not presentational ones. ```APIDOC ## useSfnDiagram ### Description Returns the raw output (SVG/HTML string, Mermaid code, dimensions, metadata) without mounting anything. Accepts the same option-bearing props as SfnDiagram, but not presentational ones. ### Parameters - `options` (object) - Required - The same option-bearing props as ``: `before`, `definition`, `format`, `history`, plus every diagram option. Not presentational ones (`className`, `onError`, `onStateClick`, `style`, `title`). ### Return Value - `result` (object) - The result object. If `format="svg"`, it has `type: 'svg'` and `svg` property. If an error occurs, it returns `{ type: 'error', error }`. ### Usage Example ```tsx import { useSfnDiagram } from 'sfn-diagram-react' function DownloadSvgButton({ definition }: { definition: object }) { const result = useSfnDiagram({ definition }) if (result.type !== 'svg') return null const href = `data:image/svg+xml;base64,${btoa(result.svg)}` return ( Download SVG ) } ``` ### Notes - Errors are returned as `{ type: 'error', error }` rather than thrown. ``` -------------------------------- ### Run lintAsl with --check Source: https://github.com/yusufaf/sfn-diagram/blob/main/site/src/content/docs/guides/cli.mdx Runs lintAsl on the input file and prints findings to stderr instead of a diagram. Exit code is 1 when any finding is an error, 0 otherwise, so it can be used in pre-commit hooks or CI. Cannot be combined with --diff, --execution, or --output. ```bash npx sfn-diagram state.asl.json --check ```