Workflow API

Defining, validating, importing, exporting and running workflows from code.

Two formats, one runner

This page is the format reference: what a workflow file contains and how to run one from code. If you only want to chain tools, use the Workflow board and skip the JSON.

A workflow is a JSON object. The current format is version 2: a graph of input, task, if, and, or, not and output blocks connected by edges. The older version 1 format is a straight line of text operations. Version 1 is converted into a version 2 graph when it is imported, so one runner executes both. The Workflow board saves and loads version 2.

Running a workflow from a page

window.eeshgarg.runWorkflow(definition, files, { signal, onNode }) takes a version 2 object, a version 1 object, or the JSON text of either. The files are File or Blob objects with a name, or { name, bytes } objects. It resolves to { status, files, outputs, nodes }:

const workflow = {
  version: 2, name: "Rotate PDFs only",
  nodes: [
    { id: "in", type: "input", x: 0, y: 0, config: { type: "any" } },
    { id: "pdf", type: "if", x: 200, y: 0, config: { field: "type", operator: "==", value: "pdf" } },
    { id: "rot", type: "task", x: 400, y: 0, config: { tool: "rotate", options: { angle: 90 } } },
    { id: "out", type: "output", x: 600, y: 0, config: {} },
  ],
  edges: [
    { from: "in", fromPort: "out", to: "pdf", toPort: "in" },
    { from: "pdf", fromPort: "true", to: "rot", toPort: "in" },
    { from: "rot", fromPort: "out", to: "out", toPort: "in" },
  ],
};
const res = await window.eeshgarg.runWorkflow(workflow, selectedFiles, {
  onNode: (n) => console.log(n.id, n.status, n.message),
});
// res.status: "done" | "failed" | "cancelled"; res.files: every file that reached an output block

An invalid workflow throws a WorkflowValidationError whose errors list says where each problem is, such as nodes[2].config.tool: unknown tool "nope". What a run does with the files, in order, is in Workflow semantics.

The result, progress and cancellation

runWorkflow resolves once every block has been decided; a failed block does not make it reject. Check res.status and read res.nodes to see what happened:

Fields of the object runWorkflow resolves to
FieldTypeMeaning
statusstring"done", "failed" (at least one block failed) or "cancelled" (the signal was aborted; cancelled takes priority over failed).
filesFile[]Every file collected by an output block, in the order the output blocks ran. Present even when status is failed or cancelled.
outputs{ id, files }[]One entry per output block that received files, with that block's id. A skipped output block has no entry.
nodes{ id, type, status, message }[]Every block, in the order of your nodes array, with its final status and message.

A block status is waiting, running, done, skipped or failed. The message is plain text for people: a file count on success, Skipped: no files reached this step. or Skipped: an earlier step failed. on a skip, and the tool's own error text on a failure. Show it; do not parse it.

Progress with onNode

onNode is called with { id, type, status, message } every time a block changes status, so you can draw progress without waiting for the run to end. Only task blocks report running; the other types go straight to done, skipped or failed. Blocks run one at a time in dependency order.

const res = await window.eeshgarg.runWorkflow(workflow, files, {
  onNode: ({ id, type, status, message }) => {
    console.log(`${type} ${id}: ${status} ${message}`);
  },
});
for (const n of res.nodes) {
  if (n.status === "failed") console.warn(`${n.id} failed: ${n.message}`);
}

Cancelling a run

Pass an AbortSignal. Aborting does not reject: the promise resolves with status: "cancelled", the block that was running is reported as waiting with the message Cancelled., blocks that never started stay waiting, and files already collected by output blocks are still returned. Treat a cancelled result as partial.

const controller = new AbortController();
cancelButton.onclick = () => controller.abort();
const res = await window.eeshgarg.runWorkflow(workflow, files, { signal: controller.signal });
if (res.status === "cancelled") console.log("Stopped early; partial files:", res.files.length);

Error shapes

What can go wrong and how it shows up
ProblemHow it surfaces
The workflow is invalid (bad JSON, wrong version, unknown tool or option, missing port, cycle)runWorkflow throws WorkflowValidationError before anything runs. error.errors is an array of up to 20 strings, each starting with the path, such as nodes[2].config.tool: unknown tool "nope"; error.message joins them with semicolons.
files is not an array, or an item is not a File, a Blob with a name, or { name, bytes }runWorkflow throws a TypeError such as files[1] must be a File, a Blob with a name, or { name, bytes }. Nothing runs.
A task fails (the tool throws, rejects the files, or produces none)No throw. That node ends failed with the message; the blocks after it are skipped with Skipped: an earlier step failed.; status is "failed"; other branches still run.
An if test cannot be evaluatedThe if node ends failed and both of its ports carry nothing, so everything after it is skipped.
No file reaches a blockThat block is skipped, not failed. An input block keeps only the files of its kind and says, for example, 1 of 3 file(s) are pdf.
The signal is abortedNo throw. status is "cancelled"; see above.
try {
  const res = await window.eeshgarg.runWorkflow(workflowJsonText, files);
  if (res.status !== "done") showProblems(res.nodes.filter((n) => n.status === "failed"));
} catch (e) {
  if (e.name === "WorkflowValidationError") e.errors.forEach((line) => console.error(line));
  else throw e; // a TypeError about the files argument
}

A worked example for each node type

Each example is a complete version 2 workflow you can pass to runWorkflow. Every edge names both ports. The x and y numbers only place a block on the board.

Input: keep only one kind of file

With type: "image" the block passes on images and drops everything else. Its message reports how many matched, for example 2 of 3 file(s) are image. With type: "any" all files pass.

{ version: 2, name: "Images to WebP",
  nodes: [
    { id: "in",  type: "input",  x: 0,   y: 0, config: { type: "image" } },
    { id: "cv",  type: "task",   x: 200, y: 0, config: { tool: "feature:convert", options: { to: "webp", quality: 0.8 } } },
    { id: "out", type: "output", x: 400, y: 0, config: {} },
  ],
  edges: [
    { from: "in", fromPort: "out", to: "cv",  toPort: "in" },
    { from: "cv", fromPort: "out", to: "out", toPort: "in" },
  ] }

Task: a text operation on every file

A task runs one thing on every file that arrives. tool is a site tool id, a feature:<name> step, or text:<op>. Options you leave out take their defaults; an unknown option name or a value of the wrong kind is a validation error. This one upper-cases text files and keeps their names:

{ version: 2, name: "Shout",
  nodes: [
    { id: "in",  type: "input",  x: 0,   y: 0, config: { type: "text" } },
    { id: "up",  type: "task",   x: 200, y: 0, config: { tool: "text:text.case", options: { mode: "upper" } } },
    { id: "out", type: "output", x: 400, y: 0, config: {} },
  ],
  edges: [
    { from: "in", fromPort: "out", to: "up",  toPort: "in" },
    { from: "up", fromPort: "out", to: "out", toPort: "in" },
  ] }

If: route by a test

The test looks at all files on the input port together, then sends all of them to true or all of them to false. count is the number of files and size is their total bytes. This example bundles a set of five or more files and hashes a smaller one:

{ version: 2, name: "Big set or small set",
  nodes: [
    { id: "in",   type: "input",  x: 0,   y: 0,   config: { type: "any" } },
    { id: "many", type: "if",     x: 200, y: 0,   config: { field: "count", operator: ">=", value: 5 } },
    { id: "zip",  type: "task",   x: 400, y: -60, config: { tool: "feature:zip-create", options: { level: 6 } } },
    { id: "hash", type: "task",   x: 400, y: 60,  config: { tool: "feature:hash", options: { algorithm: "sha256" } } },
    { id: "out",  type: "output", x: 600, y: 0,   config: {} },
  ],
  edges: [
    { from: "in",   fromPort: "out",   to: "many", toPort: "in" },
    { from: "many", fromPort: "true",  to: "zip",  toPort: "in" },
    { from: "many", fromPort: "false", to: "hash", toPort: "in" },
    { from: "zip",  fromPort: "out",   to: "out",  toPort: "in" },
    { from: "hash", fromPort: "out",   to: "out",  toPort: "in" },
  ] }

And: continue only when both sides have files

and needs files on both a and b; if either side is empty the block is skipped. Its output is the files of a followed by the files of b. Here images and PDFs are bundled only when the run has both:

{ version: 2, name: "Bundle when both kinds are present",
  nodes: [
    { id: "imgs", type: "input",  x: 0,   y: 0,   config: { type: "image" } },
    { id: "pdfs", type: "input",  x: 0,   y: 100, config: { type: "pdf" } },
    { id: "both", type: "and",    x: 200, y: 50,  config: {} },
    { id: "zip",  type: "task",   x: 400, y: 50,  config: { tool: "feature:zip-create", options: {} } },
    { id: "out",  type: "output", x: 600, y: 50,  config: {} },
  ],
  edges: [
    { from: "imgs", fromPort: "out", to: "both", toPort: "a" },
    { from: "pdfs", fromPort: "out", to: "both", toPort: "b" },
    { from: "both", fromPort: "out", to: "zip",  toPort: "in" },
    { from: "zip",  fromPort: "out", to: "out",  toPort: "in" },
  ] }

Or: take whichever side has files

or passes on the files from a and b, and is skipped only when neither has any. It is how two branches rejoin before one shared step. This sends large files and PDFs through the same hash step:

{ version: 2, name: "Hash either way",
  nodes: [
    { id: "in",   type: "input",  x: 0,   y: 0,   config: { type: "any" } },
    { id: "big",  type: "if",     x: 200, y: 0,   config: { field: "size", operator: ">", value: 1000000 } },
    { id: "pdf",  type: "if",     x: 200, y: 120, config: { field: "type", operator: "==", value: "pdf" } },
    { id: "join", type: "or",     x: 400, y: 60,  config: {} },
    { id: "h",    type: "task",   x: 600, y: 60,  config: { tool: "feature:hash", options: {} } },
    { id: "out",  type: "output", x: 800, y: 60,  config: {} },
  ],
  edges: [
    { from: "in",   fromPort: "out",  to: "big",  toPort: "in" },
    { from: "in",   fromPort: "out",  to: "pdf",  toPort: "in" },
    { from: "big",  fromPort: "true", to: "join", toPort: "a" },
    { from: "pdf",  fromPort: "true", to: "join", toPort: "b" },
    { from: "join", fromPort: "out",  to: "h",    toPort: "in" },
    { from: "h",    fromPort: "out",  to: "out",  toPort: "in" },
  ] }

Not: a fallback when nothing else matched

not passes the files on in only when nothing arrives on unless. A branch that failed counts as uncertain, not absent, so a failure upstream of unless blocks the files rather than letting them through. This converts files to PDF only when none of them is already a PDF:

{ version: 2, name: "Convert only when there is no PDF",
  nodes: [
    { id: "in",  type: "input",  x: 0,   y: 0,   config: { type: "any" } },
    { id: "pdf", type: "input",  x: 0,   y: 100, config: { type: "pdf" } },
    { id: "no",  type: "not",    x: 200, y: 0,   config: {} },
    { id: "doc", type: "task",   x: 400, y: 0,   config: { tool: "feature:document", options: { to: "pdf" } } },
    { id: "out", type: "output", x: 600, y: 0,   config: {} },
  ],
  edges: [
    { from: "in",  fromPort: "out", to: "no",  toPort: "in" },
    { from: "pdf", fromPort: "out", to: "no",  toPort: "unless" },
    { from: "no",  fromPort: "out", to: "doc", toPort: "in" },
    { from: "doc", fromPort: "out", to: "out", toPort: "in" },
  ] }

Output: collect results, one or several

Every output block that receives files adds an entry to res.outputs, and its files are also in res.files. Give output blocks distinct ids to tell their results apart:

const res = await window.eeshgarg.runWorkflow(workflow, files);
const pdfs = res.outputs.find((o) => o.id === "pdfsOut")?.files ?? [];
const rest = res.outputs.find((o) => o.id === "restOut")?.files ?? [];
for (const f of res.files) download(f); // each is a File: f.name, f.size, f.type

The version 2 graph format

Top-level fields of a version 2 workflow
FieldRule
versionMust be 2.
nameText of 1 to 120 characters after trimming.
nodes1 to 100 nodes. Each node has id, type, x, y and config.
edges0 to 200 edges. Each edge has from, fromPort, to and toPort. No other fields are allowed.

A node id is 1 to 40 letters, digits, - or _. The x and y numbers only position the block on the board; they do not affect what runs. Unknown fields are rejected, and so are the keys __proto__, constructor and prototype anywhere in the object.

Node types and ports

Node types, ports and what each one passes on
TypeInput portsOutput portsPasses on
inputnoneoutThe files whose kind matches its type setting.
taskinoutThe result of one tool or text operation.
ifintrue, falseAll files to one port, depending on a test.
anda, boutFiles from both a and b, when both carry files.
ora, boutFiles from a and b, whichever carry files.
notin, unlessoutFiles on in, only when nothing arrives on unless.
outputinnoneCollected as a result of the run.

An edge connects an output port to an input port. Several edges may enter one input port, and their files are joined in edge order. There is no NOR block: a NOR is built from a not and an or, as described in the semantics page.

Node settings

  • input: type is any or one file kind: pdf, image, docx, xlsx, pptx, html or text. Other files are dropped at this block.
  • task: tool is a tool or feature id from the catalog, or text:<op> for a text operation. options is an object checked against the tool's options.
  • if: field is type, count, size or name; operator and value depend on the field. Type uses == or != and a file kind as the value; count and size use the six comparisons and a whole number; name uses contains or matches and text of 1 to 200 characters, which for matches must be a valid regular expression.
  • and, or, not, output: no settings; config must be empty.

Validation and errors

A graph is rejected, with every problem listed (up to 20), when it:

  • has no input block or no output block, or a node that no input block can reach;
  • has a cycle, so a branch leads back to itself;
  • leaves an input port of an and, or or not block without an edge;
  • uses a tool id, text operation, option or test value the site does not know or cannot accept;
  • connects a port that does not exist on that block type, or repeats the same edge.

Validation runs before anything runs. An invalid workflow never starts.

Version 1 text pipelines

A version 1 pipeline is { version: 1, name, steps: [{ op, params }] } with 1 to 50 steps. Each step's output type must match the next step's input type (text, bytes or JSON); a mismatch is reported at validation, with the fix, for example adding text.utf8Encode before a hash. The engine that runs pipelines in memory is a library in src/workflow/ (runPipeline and runBatch, with a batch limit of 1000 items). It is not a separate page or endpoint; the site runs a version 1 workflow as a version 2 graph.

Text operations for task blocks

A task with tool: "text:<op>" runs a text operation on each file in turn, reads the file as the operation's input type and keeps the file name. The operations are:

Text operations usable as text:<op> task blocks
OperationWhat it does
text.caseUpper, lower, title, sentence or swap case.
text.whitespaceTrim and collapse whitespace; line endings keep, LF or CRLF.
text.normalizeUnicode normalization.
text.replaceFind and replace.
text.dedupeLines, text.sortLinesRemove repeated lines; sort lines.
text.urlEncode, text.urlDecode, text.htmlEncode, text.htmlDecodeURL and HTML escaping.
text.base64Encode, text.base64DecodeBase64.
text.utf8Encode, bytes.utf8DecodeText to bytes and back (UTF-8; decoding fails on invalid UTF-8).
hex.encode, hex.decodeHexadecimal of the UTF-8 bytes, and back.
json.parse, json.stringifyParse JSON text, or write a JSON value as text (indent 0 to 8).
data.convertConvert CSV, JSON, NDJSON, YAML or XML to another of those formats.
hash.sha256, hash.sha512, hash.sha384, hash.sha1, hash.sha3-256, hash.sha3-512, hash.blake3, hash.md5, hash.crc32, hash.xxh64Hex digests of the file bytes. MD5, SHA-1, CRC-32 and xxHash64 are not collision-resistant; use them for compatibility or error detection only.

Step reference: ids, parameters and defaults

Every text operation, with the type it reads and writes and each parameter with its default. A parameter you leave out takes its default; a parameter name not listed here is rejected. In a version 1 pipeline these are the step ids; in a version 2 graph write them as text:<id>.

Text operation steps, parameters and defaults
Step idInput to outputParameters and defaults
text.casetext to textmode = "upper" (upper | lower | title | sentence | swap); locale = ""
text.whitespacetext to texttrim = true; trimLines = false; collapse = false; removeBlank = false; eol = "keep" (keep | lf | crlf)
text.normalizetext to textform = "NFC" (NFC | NFD | NFKC | NFKD)
text.replacetext to textfind = ""; replace = ""; regex = false; caseSensitive = true; wholeWord = false
text.dedupeLinestext to textignoreCase = false; trimCompare = false; keep = "first" (first | last)
text.sortLinestext to textmode = "natural" (natural | numeric | length); reverse = false; unique = false; ignoreCase = true
text.urlEncodetext to textfull = false
text.urlDecodetext to textplus = true
text.base64Encodetext to texturlSafe = false; pad = true
text.base64Decodetext to textnone
text.htmlEncodetext to textnonAscii = false
text.htmlDecodetext to textnone
hex.encodetext to textnone
hex.decodetext to textnone
text.utf8Encodetext to bytesnone
bytes.utf8Decodebytes to textnone
hash.sha256bytes to textnone
hash.sha512bytes to textnone
hash.blake3bytes to textnone
hash.sha1bytes to textnone
hash.sha384bytes to textnone
hash.sha3-256bytes to textnone
hash.sha3-512bytes to textnone
hash.md5bytes to textnone
hash.crc32bytes to textnone
hash.xxh64bytes to textnone
json.parsetext to jsonnone
json.stringifyjson to textindent = 2 (0 to 8)
data.converttext to textfrom = "csv" (csv | json | ndjson | yaml | xml); to = "json" (csv | json | ndjson | yaml | xml); profile = "default" (default | semicolon | tsv | strings | headerless); neutralizeFormulas = true

json.stringify takes indent as a whole number from 0 to 8. The hash steps take bytes, so put text.utf8Encode before them, as in the version 1 example above.

Feature steps and their defaults

A task block can also name a feature step. These read and write whole files, take every file on the block's input port, and appear in the capability catalog with the allowed values of each choice option. The defaults below are what a block uses when you set no option.

Feature steps, accepted files and option defaults
Step idAcceptsOption defaults
feature:convertany, 1 or more filesto = "png"; quality = 0.9
feature:compressany, 1 or more filesformat = "gzip"; level = 9; mode = "archive"; preset = "balanced"; targetSize = ""; imageFormat = "auto"; quality = 0; maxWidth = 0; maxHeight = 0; colours = 0; imageMetadata = "default"; pdfPpi = 0; pdfQuality = 0; pdfGray = "default"; audioCodec = "auto"; mediaQuality = "auto"; channels = "keep"; sampleRate = 0; videoContainer = "auto"; videoKbps = 0; keyframe = 0; muteAudio = false
feature:decompressany, 1 or more filesnone
feature:zip-createany, 1 or more fileslevel = 6
feature:zip-extractany, 1 or more filesnone
feature:tar-createany, 1 or more filesgzip = false; level = 6
feature:tar-extractany, 1 or more filesnone
feature:hashany, 1 or more filesalgorithm = "sha256"
feature:svg-optimizeany, 1 or more filesprecision = 3; multipass = true
feature:barcodeany, 1 or more filessymbology = "qrcode"; format = "svg"; scale = 4; widthMm = 0; dpi = 300
feature:text-transformany, 1 or more filesop = "upper"; find = ""; replace = ""; regex = false; caseSensitive = true
feature:text-diffany, 2 filesnone
feature:text-mergeany, 3 filesnone
feature:redact-textany, 1 or more filespresets = "email,phone,ssn,card,iban,ipv4,apiKey"; pattern = ""; caseSensitive = true; marker = "[REDACTED]"
feature:data-queryany, 1 or more filesexpression = "@"; to = "json"
feature:data-tableany, 1 or more filesop = "sort"; columns = ""; value = ""; aggregate = "count"; descending = false; keep = "first"
feature:image-metadataany, 1 or more filesmode = "inspect"; policy = "strip-all"
feature:paletteimage, 1 or more filescolors = 6; format = "json"
feature:documentany, 1 or more filesto = "pdf"
feature:spreadsheetany, 1 or more filesto = "xlsx"
feature:presentationany, 1 or more filesto = "pdf"
feature:pdf-security-reportpdf, 1 or more filesformat = "json"
feature:pdf-font-reportpdf, 1 or more filesnone
feature:pdf-replace-textpdf, 1 or more filesfind = ""; replace = ""; page = 1; occurrence = "only"; preserveWidth = false; allowReflow = false
feature:pdf-attachmentsany, 1 or more filesmode = "attach"; name = ""
feature:pdf-compress-advancedpdf, 1 or more filesimages = "none"; thumbnails = false; attachments = false; removeUnused = false; metadata = "leave"; objectStreams = "preserve"; writer = "qpdf"
feature:image-iccimage, 1 or more filesmode = "extract"
feature:image-alpha-cleanupimage, 1 or more filessnapLow = 0.02; snapHigh = 0.98; minArea = 4; defringe = false
feature:image-seam-carveimage, 1 or more filespixels = 50
feature:audio-echoaudio, 1 or more filesdelaySeconds = 0.3; feedback = 0.5; mix = 0.5
feature:audio-reverbaudio, 1 or more filesrt60Seconds = 1.5; mix = 0.3
feature:audio-limiteraudio, 1 or more filesceilingDb = -1
feature:audio-mixaudio, 2 or more filesgainDb = 0; safeScale = true
feature:audio-denoiseaudio, 1 or more filesmode = "wiener"; floorDb = -20
feature:image-orientation-checkimage, 1 or more filesnone
feature:video-lutany, 2 or more filesnone
feature:video-stabilizeany, 1 or more filessearch = 16; edge = "mirror"
feature:video-frame-rateany, 1 or more filesmode = "check"; fps = 30

Saving, loading and exporting

The Workflow board exports the graph as JSON, normalized with every default written out, and imports either version. The same JSON text can be passed to runWorkflow. The site keeps a copy of a workflow in this browser only when you turn on Remembrance in Settings; otherwise the file you export is the copy. Open the Workflow hub to build one; its tabs are Build, Recipes (ready-made workflows), Droplets (drop files on a tile to run a saved workflow) and Autopilot (runs a workflow on the files in a folder). A recipe or droplet can be inserted into the canvas, and the canvas saved as a droplet.

The .html export writes the workflow as one self-contained page. Its import link has the form /more/workflow#import=<base64url of the JSON>; the part after the # is never sent to a server. The hub validates it exactly like an imported .json file. A tool's + Workflow control queues a task block whose config.tool is the tool id and whose options are the tool's current settings, and the hub appends it. See Workflows.

Limits

The JSON text of a workflow is limited to 256 KB (UTF-8 bytes). The graph limits are in Workflow semantics, with the numbers from the code. Limits on the files themselves depend on the tool that reads them, and are described on that tool's page.