Skip to content

Plugin development ​

A plugin teaches Aburi something it does not already know: a language to parse, a framework whose decorators mean something, or a library whose calls have effects. There are three kinds, and they plug into different stages of the pipeline.

KindYou implementIt produces
LanguageparseFile, extractSymbols, walkBody, normalizeAstSymbols, plus the rules and calls in their bodies
FrameworkclassifySymbolA framework kind and boundary flags for a symbol
EffectsclassifyAn effect for a call: db.write, network.rpc, and so on

Type signatures live in @aburi/types; the full contracts are in the design docs.

Before writing one

A decorator-based framework often needs no code at all. frameworkHints covers it from config.

Manifest ​

Every plugin exports a PluginManifest and Aburi validates it against schema/aburi.plugin.v1.json. The manifest is the only place a plugin declares what vocabulary it owns. The runtime VocabRegistry reads that declaration to enforce namespace ownership and reject cross-plugin collisions at load time.

ts
import { type FrameworkManifest, PLUGIN_SCHEMA_URL } from "@aburi/types"

export const myFrameworkManifest: FrameworkManifest = {
  $schema: PLUGIN_SCHEMA_URL, // "https://aburi.dev/schema/aburi.plugin.v1.json"
  name: "framework-mytool",
  version: "0.1.0",
  type: "framework",
  engines: { aburi: "*" },
  provides: {
    effects: [],
    effectPrefixes: [],
    extKinds: [
      {
        id: "framework:mytool:widget",
        baseKind: "class",
        description: "MyTool widget class declared with @Widget().",
      },
    ],
    extKindPrefixes: ["framework:mytool"],
    derivedByPrefixes: ["framework:mytool"],
    frameworks: ["mytool"],
  },
}

Key rules:

  • extKinds[].id must be namespaced under one of extKindPrefixes.
  • derivedByPrefixes claims the tag prefixes your plugin will emit in derivedBy. Every derivedBy entry the plugin returns at runtime must fall under one of these prefixes.
  • frameworks claims the framework ids your plugin provides (mytool), the values a component's frameworks in aburi.json holds. Two plugins claiming one id are refused at load time. aburi init does not read it: it detects the first-party frameworks alone.

Two plugins declaring the same extKind id make the registry throw at register time. We chose a loud failure over a silent takeover. aburi scan then exits 3 and names the entry in aburi.json that loaded the refused plugin.

To see what the registry made of your manifest, list your plugin in aburi.json and run aburi vocab list, or aburi vocab who-owns framework:mytool:widget for one value: it names the plugin that owns it and whether by id or by prefix, as a scan would resolve it, without scanning.

Language plugin ​

Parses a file, extracts Symbols, walks bodies to collect Rules + Calls, and computes a normalised AST string for fingerprinting.

ts
import { makeLanguageId } from "@aburi/core"
import {
  type BodyExtraction,
  type LangManifest,
  type LanguagePlugin,
  type ParseResult,
  PLUGIN_SCHEMA_URL,
} from "@aburi/types"

export const myLangManifest: LangManifest = {
  $schema: PLUGIN_SCHEMA_URL,
  name: "lang-mylang",
  version: "0.1.0",
  type: "lang",
  // The LanguageId you stamp on every Symbol id, and what lands in
  // IR.workspace.languages. It must match `^[a-z][a-z0-9]*$`, no other loaded
  // plugin may declare it, and an id opening with any other token ends the
  // run. The manifest name ("lang-mylang") is a plugin ref and cannot be used
  // here. `makeLanguageId` checks the grammar and brands the string.
  languageId: makeLanguageId("my"),
  engines: { aburi: "*" },
  provides: {
    effects: [],
    effectPrefixes: [],
    extKinds: [],
    extKindPrefixes: [],
    derivedByPrefixes: [],
    frameworks: [],
  },
}

class MyLangPlugin implements LanguagePlugin {
  readonly manifest = myLangManifest
  readonly fileExtensions = [".my"] as const
  readonly capabilities = { /* boolean matrix */ }

  async init() {}

  async parseFile(file): Promise<ParseResult> {
    // Return { tree, errors, imports }. `tree` is opaque to the pipeline.
  }

  extractSymbols(tree, ctx) {
    // Return SymbolCandidate<Node>[]. Every id must start with `<language>:`.
  }

  walkBody(symbol, ctx): BodyExtraction {
    return { rules: [], calls: [] }
  }

  normalizeAst(symbol) {
    // Canonical AST string. Whitespace / comment insensitive. Identifiers, literals,
    // operators, keywords and modifiers preserved (fingerprint.md §5.1).
    return ""
  }

  symbolDropHint(symbol, ctx) {
    // Optional: language-specific drop candidates the shape-only core rules
    // cannot judge (e.g. `{}` empty body detection).
    return null
  }
}

Contracts to know:

  • Every SymbolCandidate.id must begin with <language>: (the language prefix claimed by your manifest). The pipeline throws otherwise.
  • walkBody's Rule output is line-sorted by the pipeline before entering the IR, so you do not sort it yourself. Same for calls.
  • Take comments out of rule strings yourself, and use the shared helper for the rest. A rule's condition, what and expr hold no comments, one space for each run of whitespace, and at most 120 code points plus .... Only your plugin has the grammar that tells a comment from the code around it, so replace each one with a space before anything else sees the string. Nothing downstream can notice a comment left in: the Document still validates, and the only symptom is a logic fingerprint that moves when someone edits the comment. Do not re-implement the collapse and the cut: normalizeRuleText from @aburi/core does both to one string, counting code points as the schema's maxLength does, and normalizeRuleStrings does all three strings of a Rule. The scan applies them again at the plugin boundary, so a string they already produced passes unchanged. The rule-string contract has the reasoning.
  • Say what a module exports through its imports. An edge's symbols are the names it takes from its source. On a re-export, and on an import the module republishes in an export clause, also set reexports to each { imported, exported } pair. The scan follows a decorator's name through a barrel by those entries alone, so an edge without them is never read as a re-export. Leave origins out: the scan sets it and drops one you return. To map bare specifiers such as path aliases to workspace files, implement createImportResolver.
  • symbolDropHint returns { reason, category: "B" | "C" } or null. Category B drops keep the Symbol out of the IR, so use it for genuine boilerplate. Category C keeps the Symbol and prunes its calls.
  • A syntax error is not a reason to give up: return the tree you built and add a recoverable: true error. The file is extracted as usual.
  • Refuse a file by adding an error with recoverable: false, or by returning tree: null. The file is withdrawn and recorded as skipped, and the run still exits 0. An unusable source file tells you about your repository, not about a failure.
  • Throw only when your plugin has a bug or cannot run with the options it was given (Options). A throw withdraws the file and exits the scan 3.
The exact contract for refusing and throwing

recoverable: false must be the literal false; omitting the key means recoverable. A refused file gets no Symbols, is left out of stats.parsedFiles, and appears in ScanResult.skipped under reason: "parse-failed" with your message. Set both the flag and tree: null when you have no tree; set only the flag when you have one but refuse it, such as a wrong-dialect source or a generated blob.

Refusals leave the exit code at 0 until they take the whole workspace: a scan that parsed no file at all exits 3, so a dialect check with its comparison backwards is caught rather than shipped as an empty IR.

A throw is recorded as reason: "extraction-failed" along with what you threw. The exception is an error whose code names a fault in the plugin set rather than in the file, such as scan-plugin-misconfigured, invalid-language-id, or vocab-undeclared. Those are re-thrown and end the run immediately with exit 3, because they would otherwise repeat for every file and report the workspace as broken instead of the plugin. The code decides, not the class: a refusal from ctx.registry.assertEffectDeclared is the registry's error, and it ends the run the same way.

Framework plugin ​

Classifies a SymbolCandidate into a framework-owned extKind and optionally overrides decorator boundaries.

ts
import { DEFAULT_EXPORT_NAME, splitAliasedImportName } from "@aburi/core"
import { assertImportBinding, assertImportEdgeSource } from "@aburi/plugin-registry/plugin-input"
import type { Confidence, FrameworkClassifyContext, ImportEdge, SymbolClassification } from "@aburi/types"

/** Written identifier → the exported name it resolves to, and whether you own the module. */
function importedNames(imports: readonly ImportEdge[], filePath: string) {
  const origin = { plugin: "framework-mytool", filePath }
  const names = new Map<string, { imported: string; mine: boolean }>()
  for (const edge of imports) {
    // Validate every edge before answering, or the throw depends on import order.
    assertImportEdgeSource(edge, origin)
    if (edge.symbols === "*") continue
    for (const raw of edge.symbols) {
      const binding = splitAliasedImportName(raw)
      assertImportBinding(binding, raw, edge, origin)
      // A workspace barrel's re-export is traced to the module that declares the name.
      const declaredIn = edge.origins?.get(binding.imported) ?? edge.source
      names.set(binding.local, { imported: binding.imported, mine: declaredIn.startsWith("@mytool/") })
    }
  }
  return names
}

class MyFrameworkPlugin implements FrameworkPlugin {
  readonly manifest = myFrameworkManifest

  async init() {}

  classifySymbol(candidate, ctx: FrameworkClassifyContext): SymbolClassification | null {
    const names = importedNames(ctx.imports, ctx.file.path)
    let confidence: Confidence = "high"
    const hit = candidate.decorators.find((d) => {
      const origin = names.get(d.name)
      // No edge mentions it: nothing to resolve, so the written name stands.
      if (origin === undefined) return d.name === "Widget"
      // A default import arrives as `"default as Widget"`: `default` is in no vocabulary, so
      // the written name is the only evidence of which decorator it is.
      const exported = origin.imported === DEFAULT_EXPORT_NAME ? d.name : origin.imported
      if (exported !== "Widget") return false
      // Same name, someone else's module. Classify, but say you are less sure.
      confidence = origin.mine ? "high" : "medium"
      return true
    })
    // Return null to abstain; the next framework plugin gets a turn.
    if (hit === undefined) return null
    return {
      extKind: "framework:mytool:widget",
      derivedBy: "framework:mytool:widget",
      // Keyed on the name the source wrote, which is what the pipeline matches against
      // `Decorator.name`. Optional: flip boundary flag for specific decorators.
      decoratorBoundaries: { [hit.name]: true },
      // Omit the key for `high`: the pipeline reads an absent `confidence` as exactly that.
      ...(confidence === "high" ? {} : { confidence }),
    }
  }
}

framework-nestjs is the same shape with the duplicate-binding rule and the per-file memo filled in; read packages/framework-nestjs/src/imports.ts before shipping a plugin that matches names against a package's vocabulary.

Contracts:

  • First non-null classification wins. Order matters, because the CLI walks frameworks in the order they appear in aburi.json.
  • derivedBy may contain ;-separated multi-signal reasons; the pipeline splits them into individual derivedBy[] entries.
  • Build an entry that names something in the source from the names in the syntax tree, never from an expression node's .text: that text carries the line breaks, indentation and comments the code was written with, and a ; in a comment splits the entry. calleeName(call) from @aburi/core returns { name, leaf }, or null for a callee that is neither a name nor a member access; name is <receiver>.<method>, the receiver being the name the chain starts from, read through parentheses, as, satisfies, ! and every call on the way — app.get for app.get(…), (app as Express).get(…) and app.route("/x").get(…) alike. To read more of a chain than its name, take the nodes from the same walk: walkReceiverChain(node) returns { steps, root }, every call, member access and index on the way down, outermost first, and the node the chain starts from; chainCalls(call) returns the calls the chain passes, the call itself first.
  • A plugin for a framework that registers handlers by call can return middleware: what the registration runs before its handler, in order, named from the syntax tree by the same rule as derivedBy. The pipeline writes it to Symbol.middleware, which the logic fingerprint reads, so a removed authorization step is a logic change the report names. Leave inline functions out: their bodies are already the Symbol's.
  • Any extKind or derivedBy you emit must be declared in your manifest's extKindPrefixes / derivedByPrefixes.
  • Match a decorator on the name it was imported under, not the one the source wrote, and read ImportEdge.origins for provenance before ImportEdge.source. Matching the written name alone loses import { Widget as W } and claims a @Widget that came from some other library. A default import's imported name is default, so match its written name instead. When a decorator's import reaches a workspace barrel, relative or through a path alias, the scan follows the barrel's re-exports and records on origins the module outside the workspace that the name comes from. When neither field names a module you own, classify at confidence: "medium" rather than refusing, because a barrel the scan could not follow, such as one that re-exports through export *, looks like a foreign package. See the language plugin spec.
  • ctx.imports is the live array the pipeline reports as the file's imports, not a copy. Read it, memoize on its identity if you like, and never mutate it.
  • A const Symbol's fullNode is its whole declaration statement, which can declare several names (export const PAGE_SIZE = 20, Row = memo(RowImpl)), so read one name's initializer from its own declarator. Given the statement (asSyntaxNode(symbol.fullNode)) and the name's last segment (lastQnameSegment(symbol.name)), declaratorValue returns that initializer read through as, satisfies, ! and parentheses. It returns null for a name with no initializer of its own (declare const Ctx: Context<string>, let x) and for one a destructuring pattern binds. A default export written as a call handed a function (export default memo(function Row() { … })) is a const named <default> whose fullNode is the export_statement; for it the same call returns the statement's value, read through the same wrappers. All three come from @aburi/core. Searching the whole statement for its first call finds one that may belong to another name.
  • An optional symbolDropHint(symbol, ctx) drops a Symbol the way a language plugin's does. Every framework plugin is asked, not only the one that classified the Symbol, and the Symbol already carries the winning classification. Leave a Symbol with a boundary decorator alone.

Decorator-free classification (name / shape / body signals) is also supported: see packages/framework-react for a reference plugin that keys off PascalCase naming, use[A-Z] naming, JSX return detection, and createContext(...) / forwardRef(...) / memo(...) call-shape recognition, with no decorators involved.

Effects plugin ​

Classifies a CallCandidate into a core effect vocabulary (db.read / db.write / db.transaction / event.publish / network.http / fs.read / fs.write / …).

ts
import type { EffectClassification, EffectDecline, EffectPlugin } from "@aburi/types"

class MyEffectsPlugin implements EffectPlugin {
  readonly manifest = myEffectsManifest

  async init() {}

  classify(call, ctx): EffectClassification | EffectDecline | null {
    // Keep it pure: no I/O, no state, no async. The per-call budget is 50ms
    // by default and stateful classifiers are the reason it exists.
    if (!looksLikeMyEffect(call, ctx)) return null
    // Recognised, but which effect is not in the call site: say so instead of guessing.
    if (call.target.endsWith(".raw")) return { declined: "effects-plugin:mytool:raw" }
    return {
      effectId: "network.http",
      confidence: "high",
      derivedBy: `effects-plugin:mytool:${call.target}`,
    }
  }

  // Optional: drop callees you know are pure-boilerplate (Category C).
  readonly dropCallees = ["mytool.helper.formatUrl"]
}

Contracts:

  • First classification wins across the effects plugin list. null and a decline both pass the call to the next plugin.

  • Decline what you recognise but cannot classify. Return { declined: "effects-plugin:<plugin>:<reason>" } instead of null when the call is your library's but the effect is not in the call site: raw SQL that may read or write, or a verb your library spells two ways. If no later plugin classifies the call, it stays in calls[] and the scan records your reason in stats.declinedCalls, which aburi explain shows for the Symbol. A null is indistinguishable from a call you never recognised. An empty or non-string reason fails the run, and so does an answer that carries both effectId and declined. effect-plugin.md §4.5 has the contract.

  • The classifier is timed against a per-call budget (classifyTimeoutMs). A call over it keeps its answer and is listed in stats.effectClassifyTimeouts. Keep the classifier pure and synchronous so a slow classification is a bug, not a design decision.

  • Two-signal layered gate is strongly recommended: check for both an import-time signal (does the file import the target library at all?) AND a call-site signal (does the target's segment shape match?). See packages/effects-prisma for the reference pattern. A random foo.findMany() in a file that never imports @prisma/client should return null, and so should prisma.foo.bar() in a file that never uses Prisma's method vocabulary.

  • If your verbs are shared vocabulary, weigh the receiver too. The import gate says the file uses your library, not that this call does — a file is free to hold an Express router beside its queries, and delete / create / select belong to Map, the DOM and every HTTP router as much as to an ORM. Reject the argument shapes your library's own signatures cannot produce at all, and let the receiver's name and the argument count set the tier: high when the receiver names a client binding and the call fits the signature, medium when it does not, rather than high for everything the shape matched. Keep the tier and the gate apart — argumentCount is a syntactic count, so an unexpected arity should cost confidence rather than erase the effect. effect-plugin.md §5.4 has the rule and the reasoning.

  • Use the shared input guards, do not re-implement them.@aburi/plugin-registry/plugin-input exports assertNonEmptySegments (splits a CallCandidate.target and rejects an empty target or empty segment) and hasMatchingImport (matches a module specifier after checking every ImportEdge.source). Both enforce the language plugin's normalized-output contract from the language plugin spec, and both take a { plugin, filePath } record so the PluginInputError they throw names your plugin and the offending file. Its code says what was malformed (unnormalized-callee, unnormalized-import-source, …), and the scan keeps it on the withdrawn file's extractionFailures entry. The same module carries the readers for the receiver check — identifierWords / identifierMentions (a word split, so feedback does not read as db) and hasLiteralFirstArgument:

    ts
    import {
      assertNonEmptySegments,
      hasLiteralFirstArgument,
      hasMatchingImport,
      identifierMentions,
    } from "@aburi/plugin-registry/plugin-input"
    
    // Words that actually separate your client from everything else sharing the verbs.
    // `client` is not one: it matches `apiClient`, `httpClient`, `redisClient`, ...
    const MY_CLIENT_WORDS = new Set(["mytool", "gateway"])
    const MAX_ARGUMENTS = new Map([["send", 2]])
    
    classify(call, ctx) {
      const origin = { plugin: "effects-mytool", filePath: ctx.file.path }
    
      // Run the fail-fast BEFORE the import gate. The other order lets an upstream
      // normalization bug surface only in files that import your library and stay
      // silent everywhere else.
      const { segments, last } = assertNonEmptySegments(call.target, origin)
      if (!hasMatchingImport(ctx.file.imports, origin, (source) => source === "mytool")) return null
    
      if (segments.length < 2 || !MY_VERBS.has(last)) return null
      // A first argument your library's signatures could never take is not your call.
      if (hasLiteralFirstArgument(call)) return null
    
      // The receiver and the arity set the tier; neither gates the classification.
      const receiver = segments.at(-2)
      const named = receiver !== undefined && identifierMentions(receiver, MY_CLIENT_WORDS)
      const fits = call.argumentCount <= (MAX_ARGUMENTS.get(last) ?? 1)
      const confidence = named && fits && call.dynamicReceiver !== true ? "high" : "medium"
    
      return { effectId: "network.http", confidence, derivedBy: `effects-plugin:mytool:${last}` }
    }

    Import the dedicated /plugin-input subpath rather than the package root, which would pull the manifest validator and its schema compilation into your classifier's startup path.

Registering with the CLI ​

Once your manifest and plugin object are ready, the CLI's plugin-loader discovers them by package name from aburi.json:

jsonc
{
  "$schema": "https://aburi.dev/schema/aburi.config.v1.json",
  "languages": ["lang-typescript"],
  "frameworks": ["framework-mytool"],
  "effects": ["effects-mytool"]
}

Each entry resolves to one specifier. There is no fallback chain:

WrittenResolves to
framework-mytool@aburi/framework-mytool
@myorg/mypkg@myorg/mypkg, verbatim
./plugins/mytool.mjsThat path, relative to the workspace root
/opt/plugins/mytool.mjs on POSIXThat file
C:/plugins/mytool.mjs on WindowsThat file
A Windows path without a drive (/opt/…), or a drive letter on POSIXA config error (exit 2), before any plugin is loaded
A bare name of lowercase letters and digits only (mytool, ts)A config error (exit 2), before any plugin is loaded

No bucket prefix is inferred, and a bare name shaped like a language or framework id is refused rather than resolved: frameworks: ["mytool"] stops the run instead of looking for @aburi/mytool or @aburi/framework-mytool. Publish under a scope and write the full package name.

The list a plugin appears in must match its manifest type, or the loader fails the run.

Your module must export the plugin as a default export, a plugin export, or any top-level export whose value has a manifest field. The first hit wins.

Options ​

Users configure your plugin under pluginOptions, keyed by your manifest name:

jsonc
{
  "effects": ["@myorg/aburi-effects"],
  "pluginOptions": {
    "effects-myorg": { "queues": ["billing", "mail"] }
  }
}

Aburi does not look inside the value: the config schema accepts any JSON value there. The whole config is on the ctx of each per-file hook (extractSymbols, walkBody and symbolDropHint of a language plugin, classifySymbol and symbolDropHint of a framework plugin, classify of an effects plugin), so read your key as ctx.config.pluginOptions?.["effects-myorg"], check its shape before you rely on it, and document the options in your README. A value you cannot use is a fault in the plugin set rather than in a file: throw an error whose code is scan-plugin-misconfigured, and the run ends with exit 3 instead of recording the same failure against every file.

Testing ​

  • Unit-test your plugin in isolation. See packages/framework-nestjs/test and packages/framework-react/test for the pattern (fake ExtractionContext, hand-authored SymbolCandidates; the React tests also drive the real @aburi/lang-typescript parser for JSX-body walkers).
  • Snapshot-verify the manifest against schema/aburi.plugin.v1.json, reusing the schema validation helpers in @aburi/plugin-registry.
  • Add an integration pass in the plugin's own test/: write a small source tree with useScratchWorkspace from @aburi/test-support and scan it for real with scanWith from @aburi/test-harness, the TypeScript plugin in the lineup beside yours.

Publishing ​

  • Namespace under @aburi/* if first-party. Third-party plugins can use any scope, or none at all. The loader accepts both.
  • Follow the workspace tsdown / tsconfig config so the plugin ships ESM (.mjs + .d.mts).
  • Include manifest in the top-level exports so the loader's fallback hunt finds it.

Released under the Apache License 2.0.