Library API
All exports are available from the effect-analyzer package. The library is designed for integration into custom tools, CI pipelines, and editors.
import { analyze, renderMermaid, calculateComplexity } from "effect-analyzer"Analysis
Section titled “Analysis”analyze(path)
Section titled “analyze(path)”The primary entry point. Returns a fluent API for extracting programs from a file.
import { analyze } from "effect-analyzer"import { Effect } from "effect"
// Get a single program (throws if file has zero or multiple)const ir = await Effect.runPromise(analyze("./src/program.ts").single())
// Get all programs in a fileconst irs = await Effect.runPromise(analyze("./src/program.ts").all())
// Get a program by nameconst named = await Effect.runPromise(analyze("./src/program.ts").named("transfer"))analyzeEffectFile(filePath, options?)
Section titled “analyzeEffectFile(filePath, options?)”Lower-level file analysis. Returns StaticEffectIR[] - one IR per detected program.
analyzeEffectSource(source, filePath?, options?)
Section titled “analyzeEffectSource(source, filePath?, options?)”Analyze a TypeScript source string directly, without reading from disk:
import { analyzeEffectSource } from "effect-analyzer"
const irs = analyzeEffectSource(` import { Effect } from 'effect'; export const hello = Effect.succeed('world');`)analyze.source(code)
Section titled “analyze.source(code)”Analyze a TypeScript source string using the fluent API:
import { analyze } from "effect-analyzer"import { Effect } from "effect"
const ir = await Effect.runPromise(analyze.source(` import { Effect } from 'effect'; export const hello = Effect.succeed('world');`).single())The fluent API methods available on analyze(path) and analyze.source(code):
| Method | Description |
|---|---|
.single() | Returns exactly one program (fails if zero or multiple) |
.singleOption() | Returns Option<IR> - None if zero programs, fails if multiple |
.all() | Returns all programs as an array |
.named(name) | Returns the program matching the given name |
.first() | Returns the first program (fails if zero programs) |
.firstOption() | Returns Option<IR> - the first program or None |
analyzeProject(dirPath, options?)
Section titled “analyzeProject(dirPath, options?)”Analyze all TypeScript files in a directory. Returns a ProjectAnalysisResult with per-file outcomes.
runCoverageAudit(dirPath, options?)
Section titled “runCoverageAudit(dirPath, options?)”Run a coverage audit across a directory. Returns a CoverageAuditResult.
Rendering
Section titled “Rendering”Mermaid Diagrams
Section titled “Mermaid Diagrams”| Function | Description |
|---|---|
renderMermaid(ir, options?) | Standard flowchart |
renderStaticMermaid(ir, options?) | Static flowchart (no animation) |
renderRailwayMermaid(ir, options?) | Railway diagram with error branches |
renderPathsMermaid(ir, options?) | All execution paths as separate flows |
renderEnhancedMermaid(ir, options?) | Rich annotations per node |
renderServiceGraphMermaid(ir) | Service dependency graph |
renderSequenceMermaid(ir) | Sequence diagram |
renderRetryGanttMermaid(ir) | Retry timeline as Gantt chart |
renderGraphMermaid(graph) | Cross-program composition graph |
renderCompositionMermaid(graph) | Composition with call edges |
renderCompositionWithServicesMermaid(graph) | Composition including service nodes |
All Mermaid renderers accept a MermaidOptions object:
import { renderMermaid } from "effect-analyzer"import { Effect } from "effect"
const diagram = await Effect.runPromise(renderMermaid(ir, { direction: "LR", // TB | LR | BT | RL styleGuide: true, // Apply readability heuristics}))Structured Output
Section titled “Structured Output”| Function | Description |
|---|---|
renderJSON(ir, options?) | Full IR as JSON |
renderMultipleJSON(irs) | Multiple IRs as JSON array |
renderExplanation(ir) | Plain-English narrative |
renderMultipleExplanations(irs) | Explanations for multiple programs |
renderSummary(ir) | One-line summary |
renderMultipleSummaries(irs) | Summaries for multiple programs |
renderDependencyMatrix(irs) | Program-by-service dependency table |
renderDocumentation(ir, options?) | Markdown documentation |
renderMultiProgramDocs(irs, options?) | Documentation for multiple programs |
generateShowcase(ir, options?) | Detailed step-by-step showcase |
Interactive HTML
Section titled “Interactive HTML”import { renderInteractiveHTML } from "effect-analyzer"
const html = renderInteractiveHTML(ir, { title: "Transfer Analysis", theme: "midnight", // midnight | ocean | ember | forest | daylight | paper})See Interactive HTML for full details.
API Documentation
Section titled “API Documentation”| Function | Description |
|---|---|
renderApiDocsMarkdown(structure) | HttpApi structure to markdown |
renderApiDocsMermaid(structure) | HttpApi structure to Mermaid |
renderOpenApiPaths(structure) | Minimal OpenAPI paths |
extractHttpApiStructure(ir) | Extract HttpApi info from IR |
Complexity
Section titled “Complexity”calculateComplexity(ir)
Section titled “calculateComplexity(ir)”Returns ComplexityMetrics with 6 metrics:
import { calculateComplexity } from "effect-analyzer"
const metrics = calculateComplexity(ir)// { cyclomaticComplexity, cognitiveComplexity, pathCount, maxDepth, maxParallelBreadth, decisionPoints }assessComplexity(metrics, thresholds?)
Section titled “assessComplexity(metrics, thresholds?)”Evaluate metrics against thresholds. Returns a ComplexityAssessment with severity and warnings.
formatComplexitySummary(metrics)
Section titled “formatComplexitySummary(metrics)”Format metrics as a human-readable one-liner.
DEFAULT_THRESHOLDS
Section titled “DEFAULT_THRESHOLDS”The default complexity thresholds object.
Path Generation
Section titled “Path Generation”generatePaths(ir, options?)
Section titled “generatePaths(ir, options?)”Enumerate execution paths. Returns EffectPath[].
import { generatePaths } from "effect-analyzer"
const paths = generatePaths(ir, { maxPaths: 100, expandLoops: true })generatePathsWithMetadata(ir, options?)
Section titled “generatePathsWithMetadata(ir, options?)”Same as generatePaths but returns a PathGenerationResult with a limitHit flag.
calculatePathStatistics(paths)
Section titled “calculatePathStatistics(paths)”Aggregate statistics across paths.
filterPaths(paths, criteria)
Section titled “filterPaths(paths, criteria)”Filter paths by step names, error conditions, or loop presence.
Test Matrix
Section titled “Test Matrix”generateTestMatrix(paths, options?)
Section titled “generateTestMatrix(paths, options?)”Generate test cases from paths. Returns a TestMatrix.
import { generateTestMatrix } from "effect-analyzer"
const matrix = generateTestMatrix(paths, { testNamePrefix: "should" })formatTestMatrixMarkdown(matrix)
Section titled “formatTestMatrixMarkdown(matrix)”Render the test matrix as a markdown table.
formatTestMatrixAsCode(matrix, options?)
Section titled “formatTestMatrixAsCode(matrix, options?)”Generate test code skeletons for vitest, jest, or mocha.
formatTestChecklist(matrix)
Section titled “formatTestChecklist(matrix)”Render the test matrix as a markdown checklist.
Data Flow
Section titled “Data Flow”buildDataFlowGraph(ir)
Section titled “buildDataFlowGraph(ir)”Build a data flow graph tracking value producers and consumers.
import { buildDataFlowGraph, getProducers, getConsumers } from "effect-analyzer"
const graph = buildDataFlowGraph(ir)const producers = getProducers(graph, "AccountService")const consumers = getConsumers(graph, "balance")getDataFlowOrder(graph)
Section titled “getDataFlowOrder(graph)”Topological order of data flow nodes.
getTransitiveDependencies(graph, nodeId)
Section titled “getTransitiveDependencies(graph, nodeId)”All transitive dependencies of a node.
findCycles(graph)
Section titled “findCycles(graph)”Detect circular dependencies in the data flow.
validateDataFlow(graph)
Section titled “validateDataFlow(graph)”Check for undefined reads and duplicate writes.
renderDataFlowMermaid(graph)
Section titled “renderDataFlowMermaid(graph)”Render the data flow graph as a Mermaid diagram.
Error Flow
Section titled “Error Flow”analyzeErrorFlow(ir)
Section titled “analyzeErrorFlow(ir)”Extract all error types and map them to steps.
analyzeErrorPropagation(ir)
Section titled “analyzeErrorPropagation(ir)”Track how errors propagate through the program and how handlers narrow them.
getErrorsAtPoint(propagation, nodeId)
Section titled “getErrorsAtPoint(propagation, nodeId)”Look up the error state at a specific node.
getErrorProducers(flow, errorType)
Section titled “getErrorProducers(flow, errorType)”Find all steps that can produce a given error type.
validateWorkflowErrors(ir)
Section titled “validateWorkflowErrors(ir)”Check for undeclared and unused error types.
renderErrorFlowMermaid(flow)
Section titled “renderErrorFlowMermaid(flow)”Render the error flow as a Mermaid diagram.
formatErrorSummary(flow)
Section titled “formatErrorSummary(flow)”Human-readable error summary.
Layer Analysis
Section titled “Layer Analysis”buildLayerDependencyGraph(irs)
Section titled “buildLayerDependencyGraph(irs)”Build a dependency graph of all layers in a set of IRs.
renderLayerGraphMermaid(graph)
Section titled “renderLayerGraphMermaid(graph)”Render the layer graph as Mermaid.
detectLayerCycles(graph)
Section titled “detectLayerCycles(graph)”Find circular layer dependencies.
detectDiamondDependencies(graph)
Section titled “detectDiamondDependencies(graph)”Find diamond dependencies in the layer graph.
findUnsatisfiedServices(graph)
Section titled “findUnsatisfiedServices(graph)”Find services that are required but have no layer provider.
Service Flow
Section titled “Service Flow”analyzeServiceFlow(ir)
Section titled “analyzeServiceFlow(ir)”Track service provisions, unsatisfied services, and lifecycle.
buildProjectServiceMap(irs)
Section titled “buildProjectServiceMap(irs)”Build a project-wide map of all services, their providers, and consumers.
diffPrograms(before, after, options?)
Section titled “diffPrograms(before, after, options?)”Compare two program IRs. Returns a structured diff.
renderDiffMarkdown(diff)
Section titled “renderDiffMarkdown(diff)”Render the diff as markdown.
renderDiffJSON(diff)
Section titled “renderDiffJSON(diff)”Render the diff as JSON.
renderDiffMermaid(diff)
Section titled “renderDiffMermaid(diff)”Render the diff as a Mermaid diagram with change highlights.
parseSourceArg(arg)
Section titled “parseSourceArg(arg)”Parse a ref:path string into its components.
resolveGitSource(arg)
Section titled “resolveGitSource(arg)”Resolve a git ref to source code.
Composition
Section titled “Composition”analyzeProgramGraph(irs, options?)
Section titled “analyzeProgramGraph(irs, options?)”Build a call graph across multiple programs.
analyzeProjectComposition(dirPath, options?)
Section titled “analyzeProjectComposition(dirPath, options?)”Analyze composition across an entire project.
getTopologicalOrder(graph)
Section titled “getTopologicalOrder(graph)”Topological sort of the program call graph.
getDependencies(graph, programName)
Section titled “getDependencies(graph, programName)”Get direct dependencies of a program.
getDependents(graph, programName)
Section titled “getDependents(graph, programName)”Get direct dependents of a program.
calculateGraphComplexity(graph)
Section titled “calculateGraphComplexity(graph)”Complexity metrics for the composition graph.
Diagnostics
Section titled “Diagnostics”validateStrict(ir, options?)
Section titled “validateStrict(ir, options?)”Validate an IR against strict diagnostic rules.
import { validateStrict } from "effect-analyzer"
const result = validateStrict(ir, { warningsAsErrors: true })formatDiagnostics(result)
Section titled “formatDiagnostics(result)”Human-readable diagnostic output.
formatDiagnosticsJSON(result)
Section titled “formatDiagnosticsJSON(result)”JSON diagnostic output.
getSummary(result)
Section titled “getSummary(result)”Error and warning counts.
Const Inliner
Section titled “Const Inliner”createConstCache(sourceFile)
Section titled “createConstCache(sourceFile)”Build a cache of const declarations from a ts-morph source file.
resolveConst(name, cache)
Section titled “resolveConst(name, cache)”Look up a const value by name.
constValueToJS(value)
Section titled “constValueToJS(value)”Convert a ConstValue to a plain JavaScript value.
extractStringArray(node, cache)
Section titled “extractStringArray(node, cache)”Extract a string array from a const or literal.
extractString(node, cache)
Section titled “extractString(node, cache)”Extract a single string value.
Auto-Detection
Section titled “Auto-Detection”inferBestDiagramType(ir)
Section titled “inferBestDiagramType(ir)”Choose between 'mermaid' and 'railway' based on IR structure.
selectFormats(ir)
Section titled “selectFormats(ir)”Select the full set of auto-mode formats for a program.
Linting
Section titled “Linting”lintEffectProgram(ir, rules?)
Section titled “lintEffectProgram(ir, rules?)”Run lint rules against an Effect program IR.
import { lintEffectProgram, DEFAULT_LINT_RULES } from "effect-analyzer"
const result = lintEffectProgram(ir, DEFAULT_LINT_RULES)formatLintReport(result)
Section titled “formatLintReport(result)”Format lint issues as a human-readable report.
Built-in Rules
Section titled “Built-in Rules”| Rule | Description |
|---|---|
errorTypeTooWideRule | Error type is unknown or Error instead of a tagged union |
unboundedParallelismRule | Effect.all without concurrency option |
redundantPipeRule | Single-step pipe that could be simplified |
orDieWarningRule | Use of Effect.orDie which discards error info |
untaggedYieldRule | Yield without a descriptive variable name |
missingErrorHandlerRule | Errors produced but no handler present |
deadCodeRule | Unreachable code after terminal effects |
complexLayerRule | Layer with too many dependencies |
catchAllVsCatchTagRule | catchAll used where catchTag would be more precise |
Type Extraction
Section titled “Type Extraction”extractEffectTypeSignature(node)
Section titled “extractEffectTypeSignature(node)”Extract Effect<A, E, R> type parameters from a ts-morph node.
extractStreamTypeSignature(node)
Section titled “extractStreamTypeSignature(node)”Extract Stream<A, E, R> type parameters.
extractLayerTypeSignature(node)
Section titled “extractLayerTypeSignature(node)”Extract Layer<A, E, R> type parameters.
extractServiceRequirements(ir)
Section titled “extractServiceRequirements(ir)”Get all service requirements for a program.
formatTypeSignature(sig)
Section titled “formatTypeSignature(sig)”Format a type signature as a readable string.
Diagram Quality
Section titled “Diagram Quality”computeProgramDiagramQuality(ir)
Section titled “computeProgramDiagramQuality(ir)”Compute readability metrics for a program’s diagram.
computeFileDiagramQuality(irs)
Section titled “computeFileDiagramQuality(irs)”Compute quality metrics for all programs in a file.
buildTopOffendersReport(qualities)
Section titled “buildTopOffendersReport(qualities)”Build a report of the worst-quality diagrams.
Additional Analyzers
Section titled “Additional Analyzers”| Function | Description |
|---|---|
analyzeStateFlow(ir) | Track Ref mutations and race conditions |
analyzeScopeResource(ir) | Analyze acquireRelease and scope boundaries |
analyzeObservability(ir) | Find spans, log points, and metrics |
analyzeFiberLeaks(ir) | Detect potentially leaked fibers |
analyzeGenYields(ir) | Detailed analysis of yield* bindings in generators |
analyzeMatch(ir) | Analyze Match pattern sites and arms |
analyzePlatformUsage(ir) | Detect @effect/platform usage |
analyzeSqlPatterns(ir) | Detect @effect/sql patterns |
analyzeRpcPatterns(ir) | Detect @effect/rpc patterns |
analyzeRequestBatching(ir) | Detect request batching patterns |
analyzeStm(ir) | Detect STM (software transactional memory) usage |
analyzeConfig(ir) | Analyze Config usage |
analyzeTestingPatterns(ir) | Detect testing patterns (TestContext, TestClock) |
checkDICompleteness(irs) | Check if all services have layer providers |
formatDICompletenessReport(result) | Format DI completeness check as a report |
findMigrationOpportunities(path) | Find patterns migratable to Effect |
exportForPlayground(ir) | Export IR for the Effect playground |