Skip to Content
flowpact

API

Run flowpact from JavaScript, one function per CLI command, and build your own GitHub Action on it.

The flowpact npm package is also a library. It has one function per CLI command, and the CLI is built on these functions, so both give the same results. Use it to run flowpact inside your own program, such as your organization's own JavaScript action.

npm install --save-exact flowpact@0.29
import { lint } from 'flowpact';

const analysis = await lint({ root: 'path/to/repository' });
console.log(`${analysis.report.summary.errors} error(s)`);
process.exitCode = analysis.exitCode();
  • The package is an ES module (import, not require()) for Node.js 22 or later. Its types are included, and it has no dependencies.
  • Options are the command's flags in camelCase. Relative paths in options are read from the working directory, like the flags; paths are relative to root.
  • The functions print nothing and never exit. They return their results, and throw a FlowpactError for a problem with the options, the config or a plugin.
  • Nothing is logged unless you pass log.

Functions

FunctionCommandReturns
lint(options?)flowpact lintAnalysis
check(options?)flowpact checkAnalysis, with contracts
impact(options?)flowpact impactAnalysis, with impact
generate(options?)flowpact generateContractGeneration
graph(options?)flowpact graph --format jsonCallGraph
trace(options)flowpact trace --format jsonTraceResult
rules(options?)flowpact rules --format jsonRuleInfo[]
explain(codeOrName, options?)flowpact explainRuleDocs
remotesUpdate(options?)flowpact remotes updateRemotesUpdateResult
remotesDownload(options?)flowpact remotes downloadRemotesDownloadResult
remotesClean(options?)flowpact remotes cleanRemotesCleanResult

Each returns a promise. flowpact lsp has no function: editors start the language server through the CLI. What the commands print in the terminal comes from these results: pretty() and the other methods of an Analysis, and the format functions for the rest.

Every function takes these options:

OptionFlagDescription
root--rootRepository root. Default: the working directory.
config--configConfig file. Default: .github/flowpact/flowpact.config.yml under the root, when it exists.
baseConfig--base-configOrganization defaults under the repository's config.
plugins--pluginPlugins to load besides those the config lists, such as your organization rules. repositoryPlugins does not affect them.
repositoryPlugins--no-pluginsfalse skips the plugins the config lists, which run the repository's code. Default: true.
log--debug, -v, -q{ level, write(record) }: receives each log record at level (default info) or above, with its level, scope, message, data and time. Like an error's, a record's message is written for people and can name the CLI's flags.

graph, remotesUpdate and remotesDownload take only root, config, baseConfig and log of these: they run no rules, so they load no plugins. remotesClean takes none of them: it works on the cache alone.

lint, check and impact

import { check } from 'flowpact';

const analysis = await check({ paths: ['.github/workflows/deploy.yml'], only: ['FP401'] });
OptionFlagDescription
paths[paths…]Workflow and action files or directories to report on, relative to the root. Default: all. In impact mode, only the published ones within them are graded (Only some units).
only--onlyRule codes or names to run.
schema--no-schemafalse skips the validation against GitHub's workflow schema. Not for impact.
impact--impactlint and check: also check the release impact of the changes.
base, expect, title, labels--base, --expect, --title, --labelsImpact mode's baseline and declared impact; labels is an array. In GitHub Actions, impact mode reads them from the pull request, as the CLI does.
nowFLOWPACT_NOWThe current time, a Date, for the expiry of overrides.
fetchRemotes--fetch-remoteslint and check: fetch the interfaces of the remote workflows and actions the remote interfaces lockfile lacks, for this run only, and grade the version changes. A reference that cannot be fetched is a warning in the log.
token, apiUrlGH_TOKEN, GITHUB_API_URLWith fetchRemotes: the token to read the remote repositories with, sent only to apiUrl. Default: GH_TOKEN, else GITHUB_TOKEN, else the GitHub CLI's; the API is GITHUB_API_URL, else github.com's.
githubCom--github-comWith fetchRemotes on GitHub Enterprise Server or GHE.com: also look on github.com for the references the enterprise server lacks, with GITHUB_COM_TOKEN or none, never token.

impact() runs only the impact rules, without the schema validation, as flowpact impact does. For lint's findings and the release impact in one run, call lint({ impact: true }) (or check).

Impact mode compares with the baseline commit, which must be in the clone: check out with fetch-depth: 0. On merge_group it is skipped (notes says so), and so it is when there is nothing to grade or to report on; impact() then reports nothing.

Analysis

MemberDescription
reportThe JSON report: what --format json prints, as an object.
exitCode(failOn?)The CLI's exit code for --fail-on ('error' by default, 'warning' or 'never'): 1 when there are findings at that level, or unless it is 'never', when a version change breaks a call; else 0.
annotations({ pathPrefix }?)One annotation per finding, for @actions/core's error(), warning() and notice(): level, message, title, file, startLine, endLine, and for a finding on one line startColumn and endColumn.
github({ pathPrefix }?)The annotations as GitHub workflow commands (--format github), one line each: printed in a GitHub Actions step, they annotate the run and the pull request, without @actions/core.
sarif({ pathPrefix }?)SARIF 2.1.0 for code scanning, as text.
markdown(options?)The Markdown report, for job summaries and pull request comments. Options: title, maxFindings (default 50), repoUrl and sha (to link locations to the files at that commit), includeGraph. When a version change was graded or could not be fetched, it ends with the Version changes section of the action's job summary.
json({ includeGraph }?)The JSON report as --format json prints it.
pretty(options?)The terminal report, followed by the version changes when one was graded or could not be fetched. Options: color, width (default 100), ascii, hideInfo, hyperlinks.
contractscheck only: drift, breaking, and patch(), the regenerated contracts as a patch for git apply when they drifted (--patch).
impactImpact mode's verdict, as in the report: required, declared, ok, changes and baseline, with paths, scope, and when ignore left out published units, ignored.
versionChangeslint and check with fetchRemotes: the remote references the change moves to another version, graded (Version changes).
notesWhat the CLI prints as impact: … lines: impact mode skipped, notes about its baseline and how it graded, and the paths it does not refuse though they name no workflow or action. With fetchRemotes, also version changes: … lines: why they were not graded.

pathPrefix is the root relative to the repository, when the root is a subdirectory of it. GitHub resolves annotation and SARIF paths against the repository; flowpact reports them relative to the root. pretty() and markdown() are safe to print in a GitHub Actions log, like the text of the other commands.

Version changes

With fetchRemotes, lint and check also grade the remote references the change moves to another version (octo/setup@v2 → @v3) against the repository's calls, as --fetch-remotes and the action's remotes: fetch do (On a pull request). The base is base, else in GitHub Actions the pull request's base commit. The API fetches no commits, so the base must be in the clone (check out with fetch-depth: 0); when it is not, notes says so. Without a base, and on pull_request_target and workflow_run, whose checkout may be untrusted, nothing is graded.

versionChanges has the base commit, the changes (each { ref, from }), their grades (the grades of remotesUpdate()), and failed, the references that could not be fetched. As the CLI and the action fail on a version change that breaks a call, exitCode() returns 1 for one, unless failOn is 'never'. pretty() and markdown() list the grades; the other reports are about the findings only.

generate

import { writeFile } from 'node:fs/promises';
import { generate } from 'flowpact';

const result = await generate({ dryRun: true });
if (result.drift) await writeFile('contracts.patch', result.patch());

The options are paths, dryRun (--dry-run) and out (--out); for --patch, run with dryRun and write patch() yourself. The result has:

  • drift and breaking: whether any contract changes, and how many of the changes are breaking;
  • counts and entries: each contract file with its status (create, update, delete, unchanged) and changes;
  • dryRun: whether nothing was written (the option);
  • written: the files written, relative to the root (or to out); none with dryRun;
  • skipped: workflows and actions with YAML syntax errors, whose contracts were kept;
  • patch(): the changes as a patch for git apply, or undefined when nothing changes.

Like the CLI, generate refuses to write through a symlink or out of the repository.

graph, trace, rules and explain

They return what the command prints as JSON:

import { explain, graph, rules, trace } from 'flowpact';

const { nodes, edges } = await graph();
const { traces } = await trace({ symbol: 'pipeline.yml#inputs.config', up: true, depth: 5 });
const enabled = (await rules()).filter((rule) => rule.severity !== 'off');
const { summary, why, fix, docsUrl } = await explain('FP401');
  • graph({ paths }): nodes (workflows, actions, remote workflows, missing targets) and edges, who calls whom via which job or step; with paths, only those workflows and actions (roots) and what they call and use.
  • trace({ symbol, up, depth }): one tree per matching symbol, as in flowpact trace; for a workflow or action without inputs, secrets or outputs, traces is empty and unit names it.
  • rules(): each rule's code, name, category, defaultSeverity, severity after the config, summary and docsUrl.
  • explain(codeOrName): the same for one rule, with why, fix, examples and generatedFiles, and scope when the rule has one.

remotesUpdate, remotesDownload and remotesClean

The remote interfaces commands, for a program that keeps a repository's lockfile current, such as your own bot or a step after Renovate's update:

import { formatRemotesUpdate, remotesUpdate } from 'flowpact';

const result = await remotesUpdate({ root: 'path/to/repository', cacheDir: false });
console.log(formatRemotesUpdate(result));
if (result.failed.length) process.exitCode = 1;
if (result.changes) {
  // Commit result.file (.github/flowpact/remotes.lock.yaml).
}
  • remotesUpdate(options): paths, dryRun, token, apiUrl, githubCom, cacheDir and onProgress. The token is GH_TOKEN, else GITHUB_TOKEN, else the GitHub CLI's, unless you pass one, and is sent only to apiUrl (GITHUB_API_URL, else github.com's API). cacheDir is flowpact's cache directory (as --cache-dir), or false to keep none (--no-cache); by default it is FLOWPACT_CACHE_DIR, else none in CI, else the per-user cache. onProgress(progress) is called as each reference is done, with done, total, ref, outcome and detail. The result has file (the lockfile), changes, added, changed and removed, failed and unreadable (each { ref, error, kind }, kind being unreachable, timeout, token, access, rate-limit, server, not-found, too-large (a file over 1 MB), digest or other), apiUrl (the API it read), tokenSource (where the token came from, never the token), hints (what to check, when references could not be read) with guide (where to point flowpact, when the API or the token may be the wrong one), and sources (the cache's dir, and files written, older commits removed, files notKept with why) or sourcesNotKept. grades has each changed entry graded against the repository's calls: its ref, commits, verdict (breaks, unchecked or fits), the interface changes, and its calls, each with call (where it is), verdict, the findings it added and removed, why it is unchecked, and notes (see When a version changes). actionsLock, when the repository has GitHub's actions.lock, has its file, how many references were read at the commits it pinned, or the error that kept it from being used.
  • remotesDownload(options): the same options but dryRun, with cacheDir a directory. The result has downloaded, cached, notLocked, skipped ({ ref, reason }), failed ({ ref, error }, with kind when downloading failed and cache: true when writing the cache did), the cache's dir, the older commits removed, and apiUrl, tokenSource, hints and guide as remotesUpdate's. Without a lockfile, or with one it cannot use, it throws a usage error.
  • remotesClean({ cacheDir, keep }): removes the cached commits, or keeps the keep most recently used of each repository. The result has dir, keep, removed, and failed when a commit could not be removed.

As with the CLI, a reference that cannot be fetched is in the result, not thrown: check failed. The functions make requests to the GitHub API and, but for dryRun, write the lockfile and the cache; nothing else.

Text

What the commands print, from what the functions return: the same text as the CLI's for the same options.

import { formatGraph, formatTrace, graph, terminalOptions, trace } from 'flowpact';

const calls = await graph();
console.log(formatGraph(calls, terminalOptions())); // the tree `flowpact graph` prints in this terminal
const diagram = formatGraph(calls, { format: 'mermaid' }); // for a job summary, in a mermaid code block
console.log(formatTrace(await trace({ symbol: 'pipeline.yml#inputs.config' })));
FunctionPrints what
formatGraph(graph, options?)flowpact graph. format: tree (default), mermaid (without code fences) or dot.
formatTrace(result, options?)flowpact trace
formatRules(rules, options?)flowpact rules
formatExplain(rule, options?)flowpact explain
formatGeneration(generation, options?)flowpact generate: what was written, or after a dryRun, what would be. diff: true adds the diff, as --dry-run prints it.
formatRemotesUpdate(result, options?)flowpact remotes update
formatRemotesDownload(result, options?)flowpact remotes download
formatRemotesClean(result, options?)flowpact remotes clean

For the reports of lint, check and impact, use the Analysis methods: pretty() is --format pretty.

  • The options are those of pretty() except hideInfo: color, width (default 100), ascii and hyperlinks. The functions never look at the terminal: without options, the text has no colors, and what wraps (rules, explanations and pretty()) wraps at 100 columns. That is the text for files and job summaries.
  • terminalOptions() is for text printed to the standard output: it returns what the CLI would use there. Colors are off with NO_COLOR or FORCE_COLOR=0 and on with FORCE_COLOR; otherwise they are on in a terminal and in CI (on GitHub Actions runners too). The width is the terminal's, else COLUMNS, from 40 to 140 columns.
  • graph, trace and rules results are plain data, so JSON that the CLI printed with --format json renders as well.
  • Like the CLI's output, the text is safe to print in a GitHub Actions log: no line of it is read as a workflow command, whatever names the workflows use. github() is the exception by design: its lines are workflow commands, with every value escaped.
  • The text is written for people: its wording can change in any minor release. A program reads the results instead.

Errors

import { FlowpactError, lint } from 'flowpact';

try {
  await lint();
} catch (err) {
  if (!(err instanceof FlowpactError)) throw err;
  console.error(`${err.kind}: ${err.message}`, err.issues);
}

A FlowpactError is what the CLI reports with exit code 2. Act on its kind; the message is written for people and can name the CLI's flags. issues lists the individual problems (one per invalid config entry), and file names the config file when there is one.

kindWhat went wrong
usageAn option or path that cannot work: a path that does not exist, a root without workflows, a rule explain does not know, a symbol trace cannot find.
configThe config or base config is invalid, or names a rule that does not exist. So does an unknown rule in only.
pluginA plugin is missing, fails to load, exports no rules or registers an invalid rule.
unsafe-pathgenerate refused to write through a symlink or out of the repository.
impact-setupImpact mode has no baseline, or cannot read it.

Any other error is a bug (report it) or a plugin rule that threw.

TypeScript

The package's types describe the options and results above, the report (Report, Finding, Loc, Severity) and Annotation. They also type plugin rules: a type-only import keeps the compiled plugin free of imports, so it loads wherever flowpact runs.

rules/acme.ts
import type { RuleDefinition } from 'flowpact';

const prodNeedsApproval: RuleDefinition = {
  code: 'ACME601',
  name: 'prod-deploy-needs-approval',
  category: 'structure',
  defaultSeverity: 'error',
  docsUrl: 'https://wiki.acme.dev/ci/ACME601',
  docs: { summary: '…', why: '…', fix: '…' },
  check(ctx) {
    for (const wf of ctx.index.project.workflows.values()) {
      // …
    }
  },
};

export default [prodNeedsApproval];

defineRule(rule) does the same as a function that returns the rule, for a plugin that has flowpact installed where it runs. Compile the plugin to JavaScript before listing it: flowpact loads plugins with Node's import().

ctx.index, the data-flow graph, follows flowpact's internals: its types can change in any minor release, without the notice the rest of the API gets. Use the members listed in Custom rules.

Write your own action

A JavaScript action of your own runs flowpact with your defaults, rules, inputs and reports, where your policy allows only your organization's actions. It uses no other actions and installs nothing when it runs: the bundle holds flowpact and @actions/core.

acme/flowpact-action
├── action.yml
├── src/main.js
├── build.mjs
├── dist/index.mjs        # the bundle, committed
├── acme.base.yml         # organization defaults
└── rules/acme.mjs        # organization rules
npm install --save-exact flowpact@0.29 @actions/core
npm install --save-dev esbuild
node build.mjs            # after every update; commit dist/index.mjs

acme.base.yml and rules/acme.mjs are the base config and the plugin of Roll it out across an organization.

action.yml
name: Acme flowpact
description: flowpact with Acme's defaults, rules and reports
inputs:
  command:
    description: lint, or check when the repository commits contracts
    default: lint
  impact:
    description: Also check the release impact of changes to published workflows and actions
    default: 'false'
  fail-on:
    description: Fail the step on findings at this level (error, warning or never)
    default: error
  token:
    description: Reads the remote workflows and actions the remote interfaces lockfile lacks
    default: ${{ github.token }}
  sarif:
    description: Write SARIF for code scanning (its path is the sarif output)
    default: 'true'
outputs:
  report-json:
    description: The JSON report, for actions/upload-artifact
  sarif:
    description: The SARIF file, for github/codeql-action/upload-sarif
  errors:
    description: Number of errors
  warnings:
    description: Number of warnings
  patch:
    description: The regenerated contracts as a patch, when they drifted (check)
runs:
  using: node24
  main: dist/index.mjs
src/main.js
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import * as core from '@actions/core';
import { check, FlowpactError, lint } from 'flowpact';

// This file runs as dist/index.mjs; the defaults and rules ship next to it, in the action's directory.
const action = join(import.meta.dirname, '..');
// Events that run a fork's code with secrets: the repository's own plugins would run its code, and fetching would let
// it choose which repositories the token reads.
const UNTRUSTED = ['pull_request_target', 'workflow_run'];

try {
  const workspace = process.env.GITHUB_WORKSPACE ?? process.cwd();
  const trusted = !UNTRUSTED.includes(process.env.GITHUB_EVENT_NAME ?? '');
  // lint (or check) with impact: lint's rules and the release impact in one run. impact() runs only the impact rules.
  const run = core.getInput('command') === 'check' ? check : lint;
  const analysis = await run({
    root: workspace,
    baseConfig: join(action, 'acme.base.yml'),
    plugins: [join(action, 'rules/acme.mjs')],
    repositoryPlugins: trusted,
    impact: core.getBooleanInput('impact'),
    // The interfaces the remote interfaces lockfile lacks, read with the token for this run; on a pull request, the
    // references it moves to another version are graded too (analysis.versionChanges).
    fetchRemotes: trusted,
    token: core.getInput('token'),
    log: { level: 'warn', write: (record) => core.info(`${record.level}: ${record.message}`) },
  });

  // Why impact mode was skipped, its baseline, and why version changes were not graded.
  for (const note of analysis.notes) core.info(note);

  // An annotation on the file and line of each finding.
  for (const { level, message, ...properties } of analysis.annotations()) {
    if (level === 'error') core.error(message, properties);
    else if (level === 'warning') core.warning(message, properties);
    else core.notice(message, properties);
  }

  // The Markdown report as the job summary, with the version changes, linking to the files at this commit.
  const { GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_SHA } = process.env;
  const repoUrl = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}`;
  await core.summary.addRaw(analysis.markdown({ title: 'Acme flowpact', repoUrl, sha: GITHUB_SHA })).write();

  // The JSON report, SARIF for code scanning, and the regenerated contracts as a patch when they drifted (check). They
  // go to RUNNER_TEMP, not the checkout, where a pull request could have committed a symlink in their place.
  const json = join(process.env.RUNNER_TEMP, 'flowpact.json');
  writeFileSync(json, analysis.json());
  core.setOutput('report-json', json);
  if (core.getBooleanInput('sarif')) {
    const file = join(process.env.RUNNER_TEMP, 'flowpact.sarif');
    writeFileSync(file, analysis.sarif());
    core.setOutput('sarif', file);
  }
  const patch = analysis.contracts?.patch();
  if (patch) {
    const file = join(process.env.RUNNER_TEMP, 'flowpact-contracts.patch');
    writeFileSync(file, patch);
    core.setOutput('patch', file);
  }

  const { errors, warnings } = analysis.report.summary;
  core.setOutput('errors', errors);
  core.setOutput('warnings', warnings);
  // Findings at fail-on fail the step, and so does a version change that breaks a call, unless fail-on is never.
  const breaks = analysis.versionChanges?.grades.some((g) => g.verdict === 'breaks');
  if (analysis.exitCode(core.getInput('fail-on')) === 1)
    core.setFailed(`flowpact found ${errors} error(s) and ${warnings} warning(s)${breaks ? '; a version change breaks a call' : ''}`);
} catch (err) {
  // A config, plugin or path problem: its message and each issue. Anything else is a bug, with its stack.
  if (!(err instanceof FlowpactError)) throw err;
  core.setFailed([err.message, ...err.issues.map((issue) => `  - ${issue}`)].join('\n'));
}
build.mjs
import { build } from 'esbuild';

await build({
  entryPoints: ['src/main.js'],
  bundle: true,
  platform: 'node',
  format: 'esm',
  target: 'node24',
  // .mjs: an ES module whatever package.json the action's repository has.
  outfile: 'dist/index.mjs',
  // Some of @actions/core's dependencies are CommonJS and call require().
  banner: { js: "import { createRequire } from 'node:module';\nconst require = createRequire(import.meta.url);" },
});

From one run, this gives the annotations, the job summary with the version changes, the JSON report for actions/upload-artifact (the report-json output), the SARIF file for github/codeql-action/upload-sarif (the sarif output), a failed step at fail-on or on a version change that breaks a call, the patch when contracts drifted, and the counts as outputs. Repositories use it after actions/checkout:

.github/workflows/flowpact.yml
on: pull_request
permissions:
  contents: read
jobs:
  flowpact:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7                       # pin to a commit SHA
        with:
          fetch-depth: 0                                # the base, for impact mode and version changes
          persist-credentials: false
      - uses: acme/flowpact-action@<commit-sha>
        id: flowpact
        with:
          impact: true
      - uses: actions/upload-artifact@v7                # pin to a commit SHA
        if: ${{ !cancelled() && steps.flowpact.outputs.report-json != '' }}
        with:
          name: flowpact-report
          path: ${{ steps.flowpact.outputs.report-json }}

The token reads public repositories; private and internal ones need a token that can read them, such as a GitHub App installation token passed as token (Which token).

  • @vercel/ncc works as well when the action's package.json has "type": "module" (npm init writes "commonjs", and ncc then fails with 'import' and 'export' may appear only with 'sourceType: module'). ncc build src/main.js -o dist writes dist/index.js and a dist/package.json that marks it as an ES module; commit both, and point main at dist/index.js.
  • A bundler's license report lists flowpact as one package. flowpact's own notices and SBOM list what it bundles: copy node_modules/flowpact/dist/THIRD_PARTY_LICENSES.txt and sbom.cdx.json next to yours.
  • When flowpact is updated (Renovate or Dependabot, as in Keeping it current), rebuild and commit the bundle. A CI job that rebuilds it and fails on a difference keeps the committed bundle in step with the source.

Stability

The API follows the same policy as the CLI: only a major release changes it in an incompatible way, and says so under Breaking changes in its release notes; minor and patch releases never do. RuleContext.index and the types it leads to are the exception above. See Stability for every interface it covers.

On this page