Skip to content

Plugins & Authoring ​

All core capabilities of @neosjs/release are implemented through its plugin architecture. You can use the built-in plugins, hook up third-party plugins, or quickly write your own plugin on top of the built-in base classes.

Built-in Plugins ​

The following plugins are built into @neosjs/release and registered in a fixed internal order. No extra installation is required:

OrderPluginPurposeEnabled When
1changelogGenerate the changelog from Conventional Commits (with a contributors section) and recommend a version bump by releasable commit typeAlways
2npmRead / bump the package.json version, run safety preflight checks, and publish to npmpackage.json exists in the current directory and npm !== false
3gitPreflight checks, stage, commit, tag, push, and rollbackThe current directory is a Git repository and git !== false
4prCreate or update a GitHub PR / GitLab MR after pushing the release branchpr: true or pr.enabled: true
5githubCreate / update GitHub Releases (supports environment-variable tokens and gh CLI credentials), upload assets, and post comments automaticallygithub.release: true
6gitlabCreate GitLab Releases, validate milestones, and upload assetsgitlab.release: true
7versionCalculate the next semantic version and prompt for it in interactive modeAlways

Using External Plugins ​

Declare the plugin package name or a local file path in the plugins field of your config file:

json
{
  "plugins": {
    "some-release-plugin": {
      "optionA": true
    },
    "./scripts/my-local-plugin.mjs": {
      "file": "VERSION"
    }
  }
}
  • Keys: an npm package name, or a relative path starting with . (relative to the current working directory, process.cwd()).
  • Default values: this.options of an external plugin contains only the configuration object you passed in plugins; the plugin itself is responsible for handling defaults.
  • Custom namespace: the package name is used as the namespace by default (for a local path, the file name without its extension). To set the namespace explicitly (for example, to write shorter hook names), use the tuple form [namespace, options]:
json
{
  "plugins": {
    "@scope/my-long-plugin-name": ["my-plugin", { "optionA": true }]
  },
  "hooks": {
    "before:my-plugin:bump": "echo 'preparing bump'",
    "after:my-plugin:release": "echo 'plugin released'"
  }
}

Plugin Execution Order ​

The relative execution order of external and built-in plugins is adjusted automatically for each phase:

  • init, the info getters (getName, getLatestVersion, getIncrement, getIncrementedVersion*, getChangelog), beforeBump, bump, and beforeRelease: external plugins → built-in plugins. This lets external plugins take over the version source and changelog generation, and modify tracked files in the repository during bump; the built-in git plugin then stages and commits them all together (new untracked files require git.addUntrackedFiles to be enabled, or the plugin has to run git add itself).
  • release and afterRelease: built-in plugins → external plugins. This ensures that the publishing and wrap-up actions of external plugins run after the npm publish, the Git commit / tag / push, and the GitHub / GitLab Release.

Writing a Custom Plugin ​

A plugin is a class with a default export (export default) that extends the Plugin base class exported by @neosjs/release (before the release, the loader verifies that the class has a static isEnabled method and that its prototype contains all 12 lifecycle methods).

Minimal Example: Read and Write a Custom VERSION File ​

js
import fs from 'node:fs'
import { Plugin } from '@neosjs/release'

export default class VersionFilePlugin extends Plugin {
  getLatestVersion() {
    return fs.readFileSync('VERSION', 'utf8').trim()
  }

  bump(version) {
    if (this.config.isDryRun) return
    fs.writeFileSync('VERSION', `${version}\n`)
  }
}

Replacing Built-in Plugins ​

If a custom plugin should fully replace some built-in plugins, implement the static method disablePlugin(options) and return the names of the built-in plugins to disable (a string or an array):

js
import { Plugin } from '@neosjs/release'

export default class CustomVersionPlugin extends Plugin {
  static disablePlugin() {
    return ['npm', 'version']
  }
}

Supporting Other Git Hosting Platforms ​

To write a Release plugin for hosting platforms such as Gitea, Bitbucket, or Gitee, you can extend the GitBase or GitRelease base classes exported by @neosjs/release (the built-in github and gitlab plugins both extend GitRelease):

  • GitBase: automatically reads the remote URL and resolves repo, the current branch, the latest tag (latestTag), and the tag template (tagTemplate).
  • GitRelease: extends GitBase and provides token reading (it reads the environment variable options.tokenRef and then ghToken from the context, in that order), release notes resolution in beforeRelease (supports changelog / a shell command / a function), progress display via runTask, and, in afterRelease, output of releaseUrl and connection cleanup.

Lifecycle Method Reference ​

Leave the methods you do not need unimplemented; all instance methods can be synchronous or asynchronous (returning a Promise):

MethodDescription
static isEnabled(options)Returns whether the plugin is enabled (default options ?? true); supports async
static disablePlugin(options)Returns the names of the built-in plugins to disable (string | string[] | null)
init()Initialize the plugin and run preflight checks
getName()Returns the project name
getLatestVersion()Returns the current latest version
getIncrement(options)Returns the recommended or specified increment type (for example 'minor')
getIncrementedVersionCI(options)Calculates and returns the next version in CI mode
getIncrementedVersion(options)Called when the previous step did not produce a version; may prompt the user in interactive mode
getChangelog(latestVersion)Returns the changelog text for this release
beforeBump()Runs before the version bump (version is already determined and written to the context at this point)
bump(version)Writes the version or updates files
beforeRelease()Prepares the release (stage files, generate files, check external dependencies, etc.)
release()Performs the core publishing action
afterRelease()Post-release wrap-up: print links and clean up resources

Things to Keep in Mind ​

  • First value wins: getName, getLatestVersion, getIncrement, getIncrementedVersionCI, getIncrementedVersion, and getChangelog all "take the first valid result in execution order". External plugins run before the built-in plugins, so implementing the corresponding method is enough to take over.
  • Shape of the options argument: the argument object received by getIncrement, getIncrementedVersionCI, and getIncrementedVersion is { latestVersion, increment, isPreRelease, preReleaseId, preReleaseBase }.
  • Return false to skip hooks: when any lifecycle method returns false, the corresponding after:<namespace>:<hook> hook is skipped.
  • Respect dry-run mode: write commands executed through this.exec are skipped automatically under --dry-run; before writing to the file system or sending a network request directly, you must check if (this.config.isDryRun) return yourself.
  • Errors and early exit: when a preflight check fails, throw formatErrorMessage('Error description') (exit code 1); passing false as the third argument (formatErrorMessage('Nothing to release', '', false)) means ending early without an error (exit code 0).
  • Released marker: if the plugin performs an irreversible external publish, it is recommended to call this.config.setContext({ isReleased: true }); the built-in git plugin uses it to keep the local commit instead of rolling back when the push fails.
  • Cancelling custom prompts: if the plugin starts a terminal interaction on its own, bypassing this.step, and the user interrupts it, call markCancelled() so that the release is handled as a "user cancellation" rather than a "failed release".

Built-in Utilities on Plugin Instances ​

After extending Plugin, the following properties and methods are available directly:

Property / MethodDescription
this.namespaceThe plugin's namespace string
this.optionsThis plugin's configuration object (already Object.freezed)
this.configThe global Config instance: getContext(path?), setContext(obj), isDryRun, isCI, isIncrement, isCanary, isPR, etc.
this.getContext(path?) / this.setContext(obj)Read / write the current plugin's private context (this.options is merged in on read)
this.log / this.debugUnified logger (log, info, success, warn, error, verbose, exec, preview); debug logs are enabled with NODE_DEBUG=@neosjs/release:*
this.exec(command, { options?, context? })Executes a command; skipped by default under --dry-run, so pass { options: { write: false } } for read-only commands. An argument array (this.exec(['git', 'status'])) does not go through a shell: each element is passed as-is as one argument, so always use this form when running commands. A string is a shell command template: it is first rendered with the context (${...} is an evaluated expression) and then handed to the system shell, so use it only for user-configured commands (hook scripts, git.logCommand, etc.): execution is refused when a template value contains shell syntax (whitespace, quotes, $, ;, etc.), so pass multi-line content through RELEASE_ environment variables instead (see Lifecycle Hooks), and never interpolate repository-derived content such as branch or tag names in any other way
this.execSync(command)Executes an argument-array command synchronously (used for the process exit rollback; only prints under --dry-run)
this.rollbackWith(commands, scope)Synchronously runs a set of rollback commands and prints a unified notice
this.registerPrompts(prompts)Registers the plugin's own inquirer prompts
this.step({ enabled?, task, label, prompt? })Unified task step: in interactive mode it asks for confirmation through prompt first (and prints a skip notice with label when declined); in CI mode it runs automatically through spinner
this.showPrompt(options)Triggers a registered interactive prompt directly
this.spinner / this.promptThe underlying Spinner and Prompt instances (calling this.log while the spinner is spinning pauses and resumes it automatically, so lines are never broken)

Exports Reference ​

@neosjs/release exports the base classes, utility functions, and constants that its internal plugins reuse as well:

ExportDescription
Plugin, GitBase, GitReleaseThe plugin base class and the Git / Release abstract base classes
Config, defineConfig, ReleaseManager, releaseThe config class, the config helper, the release manager, and the programmatic entry point
format(template, context)Renders a ${...} template string with Eta (an error thrown on a rendering failure carries only the template and the reason, not the context)
parseVersion(version)Parses a version and returns { version, isPreRelease, preReleaseId }
parseGitUrl(url)Parses a Git remote URL and returns { host, owner, project, protocol, remote, repository }
formatErrorMessage(message, docs?, fail?)Builds a standard error object with an exit code (1 or 0)
castArray(value), fixArgs(args)Normalizes a value into an array; converts command arguments given as a string or an array into an array of strings
readJSON(file), hasAccess(path)Reads a JSON file; checks whether a file / directory is accessible
once(fn), rejectAfter(ms, error)Returns a single-execution wrapper function; builds a Promise that rejects after a timeout
isCancelled(), markCancelled(), isCancelPromptError(error)Query and mark the cancellation state
colors, symbols, COLORSColor and icon utilities matching the built-in output style
RETRY_CODES, DEFAULT_RETRY_MIN_TIMEOUTThe default retryable HTTP status codes and the minimum retry wait time in milliseconds

Publishing a Third-Party Plugin to npm ​

Declare @neosjs/release in peerDependencies, and make sure the package entry point default-exports the plugin class:

json
{
  "name": "my-neosjs-release-plugin",
  "type": "module",
  "exports": {
    ".": {
      "import": "./dist/index.js",
      "require": "./dist/index.js"
    }
  },
  "peerDependencies": {
    "@neosjs/release": "^1.3.0"
  },
  "devDependencies": {
    "@neosjs/release": "^1.3.0"
  },
  "keywords": ["neosjs-release-plugin"]
}

A note on the exports field: when loading an external plugin by package name, @neosjs/release tries, in order, a direct import(), an import() from the current directory, and running require.resolve() in the project working directory to resolve the path. Therefore, always provide a require or default condition in exports (providing only an import condition fails to load in some resolution scenarios). It is also recommended to add the neosjs-release-plugin keyword so the plugin can be found by search.