Skip to content

oneRepo API

NamespaceDescription
buildersCommon and reusable command-line option builders.
fileFile manipulation functions.
gitSpecial handlers for managing complex queries and manipulation of the git repository’s state.
const defaultConfig: Required<RootConfig>;

Source: modules/onerepo/src/setup/setup.ts

type Argv<CommandArgv>: Arguments<CommandArgv & DefaultArgv>;

Helper for combining local parsed arguments along with the default arguments provided by the oneRepo command module.

Type parameters:

Type parameterValueDescription
CommandArgvobjectArguments that will be parsed for this command, always a union with DefaultArgv and PositionalArgv.

Source: modules/yargs/src/yargs.ts


type Builder<CommandArgv>: (yargs) => Yargv<CommandArgv>;

Option argument parser for the given command. See Yargs .command(module) for more, but note that only the object variant is not accepted – only function variants will be accepted in oneRepo commands.

For common arguments that work in conjunction with HandlerExtra methods like getAffected(), you can use helpers from the builders namespace, like builders.withAffected().

type Argv = {
'with-tacos'?: boolean;
};
export const builder: Builder<Argv> = (yargs) =>
yargs.usage(`$0 ${command}`).option('with-tacos', {
description: 'Include tacos',
type: 'boolean',
});

See also:

Type parameters:

Type parameterValueDescription
CommandArgvobjectArguments that will be parsed for this command

Parameters:

ParameterTypeDescription
yargsYargsThe Yargs instance. See Yargs .command(module)

Returns: Yargv<CommandArgv>
Source: modules/yargs/src/yargs.ts


type DefaultArgv: {
dry-run: boolean;
quiet: boolean;
skip-engine-check: boolean;
verbosity: number;
};

Default arguments provided globally for all commands. These arguments are included by when using Builder and Handler.

dry-run: boolean;

Whether the command should run non-destructive dry-mode. This prevents all subprocesses, files, and git operations from running unless explicitly specified as safe to run.

Also internally sets process.env.ONEREPO_DRY_RUN = 'true'.

Default: false

quiet: boolean;

Silence all logger output. Prevents all stdout and stderr output from the logger entirely.

Default: false

skip-engine-check: boolean;

Skip the engines check. When false, oneRepo will the current process’s node version with the range for engines.node as defined in package.json. If not defined in the root package.json, this will be skipped.

Default: false

verbosity: number;

Verbosity level for the Logger. See Logger.verbosity for more information.

Default: 3
Source: modules/yargs/src/yargs.ts


type Handler<CommandArgv>: (argv, extra) => Promise<void>;

Command handler that includes oneRepo tools like graph, logger, and more. This function is type-safe if Argv is correctly passed through to the type definition.

type Argv = {
'with-tacos'?: boolean;
};
export const handler: Handler<Argv> = (argv, { logger }) => {
const { 'with-tacos': withTacos, '--': passthrough } = argv;
logger.log(withTacos ? 'Include tacos' : 'No tacos, thanks');
logger.debug(passthrough);
};

See also:

Type parameters:

Type parameterValueDescription
CommandArgvobjectArguments that will be parsed for this command. DefaultArguments will be automatically merged into this object for use within the handler.

Parameters:

ParameterType
argvArgv<CommandArgv>
extraHandlerExtra

Returns: Promise<void>
Source: modules/yargs/src/yargs.ts


type HandlerExtra: {
config: Required<RootConfig>;
getAffected: (opts?) => Promise<Workspace[]>;
getFilepaths: (opts?) => Promise<string[]>;
getWorkspaces: (opts?) => Promise<Workspace[]>;
graph: Graph;
logger: Logger;
};

Commands in oneRepo extend beyond what Yargs is able to provide by adding a second argument to the handler.

All extras are available as the second argument on your Handler

export const handler: Handler = (argv, { getAffected, getFilepaths, getWorkspace, logger }) => {
logger.warn('Nothing to do!');
};

Overriding the affected threshold in getFilepaths

export const handler: Handler = (argv, { getFilepaths }) => {
const filepaths = await getFilepaths({ affectedThreshold: 0 });
};
config: Required<RootConfig>;

This repository’s oneRepo config, resolved with all defaults.

getAffected: (opts?) => Promise<Workspace[]>;

Get the affected Workspaces based on the current state of the repository.

This is a wrapped implementation of builders.getAffected that does not require passing the graph argument.

Parameters:

ParameterType
opts?GetterOptions

Returns: Promise<Workspace[]>

getFilepaths: (opts?) => Promise<string[]>;

Get the affected filepaths based on the current inputs and state of the repository. Respects manual inputs provided by builders.withFiles if provided.

This is a wrapped implementation of builders.getFilepaths that does not require the graph and argv arguments.

Note: that when used with --affected, there is a default limit of 100 files before this will switch to returning affected Workspace paths. Use affectedThreshold: 0 to disable the limit.
Parameters:

ParameterType
opts?FileGetterOptions

Returns: Promise<string[]>

getWorkspaces: (opts?) => Promise<Workspace[]>;

Get the affected Workspaces based on the current inputs and the state of the repository. This function differs from getAffected in that it respects all input arguments provided by builders.withWorkspaces, builders.withFiles and builders.withAffected.

This is a wrapped implementation of builders.getWorkspaces that does not require the graph and argv arguments.

Parameters:

ParameterType
opts?GetterOptions

Returns: Promise<Workspace[]>

graph: Graph;

The full monorepo Graph.

logger: Logger;

Standard Logger. This should always be used in place of console.log methods unless you have a specific need to write to standard out differently.

Source: modules/yargs/src/yargs.ts


type PositionalArgv: {
$0: string;
--: string[];
_: (string | number)[];
};

Always present in Builder and Handler arguments as parsed by Yargs.

$0: string;

The script name or node command. Similar to process.argv[1]

—
--: string[];

Any content that comes after ” — ” gets populated here. These are useful for spreading through to spawned run functions that may take extra options that you don’t want to enumerate and validate.

_: (string | number)[];

Positionals / non-option arguments. These will only be filled if you include .positional() or .strictCommands(false) in your Builder.

Source: modules/yargs/src/yargs.ts

type Config<CustomLifecycles>: RootConfig<CustomLifecycles> | WorkspaceConfig<CustomLifecycles>;

Picks the correct config type between RootConfig and WorkspaceConfig based on whether the root property is set. Use this to help ensure your configs do not have any incorrect keys or values.

Satisfy a RootConfig:

import type { Config } from 'onerepo';
export default {
root: true,
} satisfies Config;

Satisfy a WorkspaceConfig with custom lifecycles on tasks:

import type { Config } from 'onerepo';
export default {
tasks: {
stage: {
serial: ['$0 build'],
},
},
} satisfies Config<'stage'>;

Type parameters:

Type parameterValue
CustomLifecycles extends string | voidvoid

Source: modules/onerepo/src/types/index.ts


type Lifecycle:
| "pre-commit"
| "post-commit"
| "post-checkout"
| "pre-merge"
| "post-merge"
| "build"
| "pre-deploy"
| "pre-publish"
| "post-publish";

oneRepo comes with a pre-configured list of common lifecycles for grouping tasks.

Source: modules/onerepo/src/types/tasks.ts


type RootConfig<CustomLifecycles>: {
changes: {
filenames: "hash" | "human";
formatting: {
commit: string;
footer: string;
};
prompts: "guided" | "semver";
};
codeowners: Record<string, string[]>;
commands: {
directory: string | false;
ignore: RegExp;
};
dependencies: {
dedupe: boolean;
mode: "strict" | "loose" | "off";
};
head: string;
ignore: string[];
meta: Record<string, unknown>;
plugins: Plugin[];
root: true;
taskConfig: {
lifecycles: CustomLifecycles[];
stashUnstaged: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[];
};
tasks: TaskConfig<CustomLifecycles>;
templateDir: string;
validation: {
schema: string | null;
};
vcs: {
autoSyncHooks: boolean;
hooksPath: string;
provider: "github" | "gitlab" | "bitbucket" | "gitea";
};
visualizationUrl: string;
};

Setup configuration for the root of the repository.

Type parameters:

Type parameterValue
CustomLifecycles extends string | voidvoid
optional changes: {
filenames: "hash" | "human";
formatting: {
commit: string;
footer: string;
};
prompts: "guided" | "semver";
};
optional filenames: "hash" | "human";

Default: 'hash'

To generate human-readable unique filenames for change files, ensure human-id is installed.

optional formatting: {
commit: string;
footer: string;
};

Default: {}

Override some formatting strings in generated changelog files.

onerepo.config.ts
export default {
root: true,
changes: {
formatting: {
commit: '([${ref.short}](https://github.com/paularmstrong/onerepo/commit/${ref}))',
footer:
'> Full changelog [${fromRef.short}...${throughRef.short}](https://github.com/my-repo/commits/${fromRef}...${throughRef})',
},
},
};
optional commit: string;

Default: '(${ref.short})'

Format how the commit ref will appear at the end of the first line of each change entry.

Available replacement strings:

ReplacementDescription
${ref.short}8-character version of the commit ref
${ref}Full commit ref
optional footer: string;

Default: '_View git logs for full change list._'

Format the footer at the end of each version in the generated changelog files.

Available replacement strings:

ReplacementDescription
${fromRef.short}8-character version of the first commit ref in the version
${fromRef}Full commit ref of the first commit in the version
${through.short}8-character version of the last commit ref in the version
${through}Full commit ref of the last commit in the version
${version}New version string
optional prompts: "guided" | "semver";

Default: 'guided'

Change the prompt question & answer style when adding change entries.

  • 'guided': Gives more detailed explanations when release types.
  • 'semver': A simple choice list of semver release types.
optional codeowners: Record<string, string[]>;

Default: {}

Map of paths to array of owners.

When used with the codeowners commands, this configuration enables syncing configurations from Workspaces to the appropriate root level CODEOWNERS file given your vcsProvider as well as verifying that the root file is up to date.

onerepo.config.ts
export default {
root: true,
codeowners: {
'*': ['@my-team', '@person'],
scripts: ['@infra-team'],
},
};
optional commands: {
directory: string | false;
ignore: RegExp;
};

Configuration for custom commands.

optional directory: string | false;

Default: 'commands'

A string to use as filepaths to subcommands. We’ll look for commands in all Workspaces using this string. If any are found, they’ll be available from the CLI.

onerepo.config.ts
export default {
root: true,
commands: {
directory: 'commands',
},
};

Given the preceding configuration, commands will be searched for within the commands/ directory at the root of the repository as well as a directory of the same name at the root of each Workspace:

  • <root>/commands/*
  • <root>/<workspaces>/commands/*
optional ignore: RegExp;

Default: /(/__\w+__/|\.test\.|\.spec\.|\.config\.)/

Prevent reading matched files in the commands.directory as commands.

When writing custom commands and Workspace-level subcommands, we may need to ignore certain files like tests, fixtures, and other helpers. Use a regular expression here to configure which files will be ignored when oneRepo parses and executes commands.

onerepo.config.ts
export default {
root: true,
commands: {
ignore: /(/__\w+__/|\.test\.|\.spec\.|\.config\.)/,
},
};
optional dependencies: {
dedupe: boolean;
mode: "strict" | "loose" | "off";
};
optional dedupe: boolean;

Default: true

When modifying dependencies using the one dependencies command, a dedupe will automatically be run to reduce duplicate package versions that overlap the requested ranges. Set this to false to disable this behavior.

optional mode: "strict" | "loose" | "off";

Default: 'loose'

The dependency mode will be used for node module dependency management and verification.

  • off: No validation will occur. Everything goes.
  • loose: Reused third-party dependencies will be required to have semantic version overlap across unique branches of the Graph.
  • strict: Versions of all dependencies across each discrete Workspace dependency tree must be strictly equal.
optional head: string;

Default: 'main'

The default branch of your repo? Probably main, but it might be something else, so it’s helpful to put that here so that we can determine changed files accurately.

onerepo.config.ts
export default {
root: true,
head: 'develop',
};
optional ignore: string[];

Default: []

Array of fileglobs to ignore when calculating the changed Workspaces.

Periodically we may find that there are certain files or types of files that we know for a fact do not affect the validity of the repository or any code. When this happens and the files are modified, unnecessary tasks and processes will be spun up that don’t have any bearing on the outcome of the change.

To avoid extra processing, we can add file globs to ignore when calculated the afected Workspace graph.

onerepo.config.ts
export default {
root: true,
ignore: ['.github/*'],
};
optional meta: Record<string, unknown>;

Default: {}

A place to put any custom information or configuration. A helpful space for you to extend Workspace configurations for your own custom commands.

onerepo.config.ts
export default {
root: true,
meta: {
tacos: 'are delicious',
},
};
optional plugins: Plugin[];

Default: []

Add shared commands and extra handlers. See the official plugin list for more information.

onerepo.config.ts
import { eslint } from '@onerepo/plugins-eslint';
export default {
plugins: [eslint()],
};
root: true;

Must be set to true in order to denote that this is the root of the repository.

optional taskConfig: {
lifecycles: CustomLifecycles[];
stashUnstaged: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[];
};

Optional extra configuration for tasks.

optional lifecycles: CustomLifecycles[];

Default: []

Additional task lifecycles to make available.

See Lifecycle for a list of pre-configured lifecycles.

onerepo.config.ts
export default {
root: true,
tasks: {
lifecycles: ['deploy-staging'],
},
};
optional stashUnstaged: CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle[];

Default: ['pre-commit'] Stash unstaged changes before running these tasks and re-apply them after the task has completed.

onerepo.config.ts
export default {
root: true,
tasks: {
stashUnstaged: ['pre-commit', 'post-checkout'],
},
};
optional tasks: TaskConfig<CustomLifecycles>;

Default: {}

Globally defined tasks per lifecycle. Tasks defined here will be assumed to run for all changes, regardless of affected Workspaces. Refer to the tasks command specifications for details and examples.

optional templateDir: string;

Default: './config/templates'

Folder path for generate command’s templates.

optional validation: {
schema: string | null;
};
optional schema: string | null;

Default: undefined

File path for custom Graph and configuration file validation schema.

optional vcs: {
autoSyncHooks: boolean;
hooksPath: string;
provider: "github" | "gitlab" | "bitbucket" | "gitea";
};

Version control system settings.

optional autoSyncHooks: boolean;

Default: false

Automatically set and sync oneRepo-managed git hooks. Change the directory for your git hooks with the vcs.hooksPath setting. Refer to the Git hooks documentation to learn more.

onerepo.config.ts
export default {
root: true,
vcs: {
autoSyncHooks: false,
},
};
optional hooksPath: string;

Default: '.hooks'

Modify the default git hooks path for the repository. This will automatically be synchronized via one hooks sync unless explicitly disabled by setting vcs.autoSyncHooks to false.

onerepo.config.ts
export default {
root: true,
vcs: {
hooksPath: '.githooks',
},
};
optional provider: "github" | "gitlab" | "bitbucket" | "gitea";

Default: 'github'

The provider will be factored in to various commands, like CODEOWNERS generation.

onerepo.config.ts
export default {
root: true,
vcs: {
provider: 'github',
},
};
optional visualizationUrl: string;

Default: 'https://onerepo.tools/visualize/'

Override the URL used to visualize the Graph. The Graph data will be attached the the g query parameter as a JSON string of the DAG, compressed using zLib deflate.

Source: modules/onerepo/src/types/config-root.ts


type Task: string | TaskDef | string[];

A Task can either be a string or TaskDef object with extra options, or an array of strings. If provided as an array of strings, each command will be run sequentially, waiting for the previous to succeed. If one command fails, the rest in the sequence will not be run.

To run sequences of commands with match and meta information, you can pass an array of strings to the cmd property of a TaskDef.

Source: modules/onerepo/src/types/tasks.ts


type TaskConfig<CustomLifecycles>: Partial<Record<CustomLifecycles extends string ? Lifecycle | CustomLifecycles : Lifecycle, Tasks>>;

Type parameters:

Type parameterValue
CustomLifecycles extends string | voidvoid

Source: modules/onerepo/src/types/tasks.ts


type TaskDef: {
cmd: string | string[];
match: string | string[];
meta: Record<string, unknown>;
};

Tasks can optionally include meta information or only be run if the configured match glob string matches the modified files. If no files match, the individual task will not be run.

export default {
tasks: {
'pre-commit': {
parallel: [
// Only run `astro check` if astro files have been modified
{ match: '*.astro', cmd: '$0 astro check' },
// Use a glob match with sequential tasks
{ match: '*.{ts,js}', cmd: ['$0 lint', '$0 format'] },
],
},
},
} satisfies Config;
cmd: string | string[];

String command(s) to run. If provided as an array of strings, each command will be run sequentially, waiting for the previous to succeed. If one command fails, the rest in the sequence will not be run.

The commands can use replaced tokens:

  • $0: the oneRepo CLI for your repository
  • ${workspaces}: replaced with a space-separated list of Workspace names necessary for the given lifecycle
optional match: string | string[];

Glob file match. This will force the cmd to run if any of the paths in the modified files list match the glob. Conversely, if no files are matched, the cmd will not run.

optional meta: Record<string, unknown>;

Extra information that will be provided only when listing tasks with the --list option from the tasks command. This object is helpful when creating a matrix of runners with GitHub actions or similar CI pipelines.

Source: modules/onerepo/src/types/tasks.ts


type Tasks: {
parallel: Task[];
serial: Task[];
};

Individual Tasks in any Lifecycle may be grouped to run either serial (one after the other) or in parallel (multiple at the same time).

optional parallel: Task[];
optional serial: Task[];

Source: modules/onerepo/src/types/tasks.ts


WorkspaceConfig<CustomLifecycles>

Section titled WorkspaceConfig<CustomLifecycles>
type WorkspaceConfig<CustomLifecycles>: {
codeowners: Record<string, string[]>;
commands: {
passthrough: Record<string, {
command: string;
description: string;
}>;
};
meta: Record<string, unknown>;
tasks: TaskConfig<CustomLifecycles>;
};

Type parameters:

Type parameterValue
CustomLifecycles extends string | voidvoid
optional codeowners: Record<string, string[]>;

Default: {}. Map of paths to array of owners.

When used with the codeowners commands, this configuration enables syncing configurations from Workspaces to the appropriate root level CODEOWNERS file given your RootConfig.vcs.provider as well as verifying that the root file is up to date.

onerepo.config.ts
export default {
codeowners: {
'*': ['@my-team', '@person'],
scripts: ['@infra-team'],
},
};
optional commands: {
passthrough: Record<string, {
command: string;
description: string;
}>;
};

Configuration for custom commands. To configure the commands directory, see RootConfig commands.directory.

passthrough: Record<
string,
{
command: string;
description: string;
}
>;

Default: {}

Enable commands from installed dependencies. Similar to running npx <command>, but pulled into the oneRepo CLI and able to be limited by Workspace. Passthrough commands must have helpful descriptions.

onerepo.config.ts
export default {
commands: {
passthrough: {
astro: { description: 'Run Astro commands directly.' },
start: { description: 'Run the Astro dev server.', command: 'astro dev --port=8000' },
},
},
};
optional meta: Record<string, unknown>;

Default: {} A place to put any custom information or configuration. A helpful space for you to extend Workspace configurations for your own custom commands.

onerepo.config.ts
export default {
meta: {
tacos: 'are delicious',
},
};
optional tasks: TaskConfig<CustomLifecycles>;

Default: {} Tasks for this Workspace. These will be merged with global tasks and any other affected Workspace tasks. Refer to the tasks command specifications for details and examples.

Source: modules/onerepo/src/types/config-workspace.ts

getGraph(workingDir?): Graph

Get the Graph given a particular root working directory. If the working directory is not a monorepo’s root, an empty Graph will be given in its place.

const graph = getGraph(process.cwd());
assert.ok(graph.isRoot);

Parameters:

ParameterType
workingDir?string

Returns: Graph
Source: modules/graph/src/index.ts


The oneRepo Graph is a representation of the entire repository’s Workspaces and how they depend upon each other. Most commonly, you will want to use the Graph to get lists of Workspaces that either depend on some input or are dependencies thereof:

const workspacesToCheck = graph.affected('tacos');
for (const ws of workspacesToCheck) {
// verify no issues based on changes
}

The Graph also includes various helpers for determining workspaces based on filepaths, name, and other factors.

get packageManager(): PackageManager

Get the PackageManager that this Graph depends on. This object allows you to run many common package management commands safely, agnostic of any particular flavor of package management. Works with npm, Yarn, and pnpm.

await graph.packageManager.install();

Returns: PackageManager
Source: modules/graph/src/Graph.ts

get root(): Workspace

This returns the Workspace that is at the root of the repository.

Regardless of how the workspaces are configured with the package manager, the root package.json is always registered as a Workspace.

const root = graph.root;
root.isRoot === true;

Returns: Workspace
Source: modules/graph/src/Graph.ts

get workspaces(): Workspace[]

Get a list of all Workspaces that are part of the repository {@Link Graph | Graph}.

for (const workspace of graph.workspaces) {
logger.info(workspace.name);
}

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

affected<T>(source, type?): Workspace[]

Get a list of Workspaces that will be affected by the given source(s). This is equivalent to graph.dependents(sources, true). See also dependents.

const dependents = graph.dependents(sources, true);
const affected = graph.affected(sources);
assert.isEqual(dependents, affecteed);

Type parameters:

Type parameter
T extends string | Workspace

Parameters:

ParameterTypeDescription
sourceT | T[]-
type?DepTypeFilter the dependents to a dependency type.

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

dependencies<T>(
sources?,
includeSelf?,
type?): Workspace[]

Get all dependency Workspaces of one or more input Workspaces or qualified names of Workspaces. This not only returns the direct dependencies, but all dependencies throughout the entire Graph. This returns the opposite result of dependents.

for (const workspace of graph.dependencies('tacos')) {
logger.info(`"${workspace.name}" is a dependency of "tacos"`);
}

Type parameters:

Type parameter
T extends string | Workspace

Parameters:

ParameterTypeDescription
sources?T | T[]A list of Workspaces by names or any available aliases.
includeSelf?booleanWhether to include the Workspaces for the input sources in the return array.
type?DepTypeFilter the dependencies to a dependency type.

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

dependents<T>(
sources?,
includeSelf?,
type?): Workspace[]

Get all dependent Workspaces of one or more input Workspaces or qualified names of Workspaces. This not only returns the direct dependents, but all dependents throughout the entire Graph. This returns the opposite result of dependencies.

for (const workspace of graph.dependents('tacos')) {
logger.info(`"${workspace.name}" depends on "tacos"`);
}

Type parameters:

Type parameter
T extends string | Workspace

Parameters:

ParameterTypeDescription
sources?T | T[]One or more Workspaces by name or Workspace instance
includeSelf?booleanWhether to include the Workspaces for the input sources in the return array.
type?DepTypeFilter the dependents to a dependency type.

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

getAllByLocation(locations): Workspace[]

Get all Workspaces given an array of filepaths.

const workspaces = graph.getAllByLocation([__dirname, 'file:///foo/bar']);

Parameters:

ParameterTypeDescription
locationsstring[]A list of filepath strings. May be file URLs or string paths.

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

getAllByName(names): Workspace[]

Get a list of Workspaces by string names.

const workspaces = graph.getAllByName(['tacos', 'burritos']);

Parameters:

ParameterTypeDescription
namesstring[]A list of Workspace names or any available aliases.

Returns: Workspace[]
Source: modules/graph/src/Graph.ts

getByLocation(location): Workspace

Get the equivalent Workspace for a filepath. This can be any location within a Workspace, not just its root.

CommonJS compatible
// in Node.js
graph.getByLocation(__dirname);
ESM compatible
graph.getByLocation(import.meta.url);

Parameters:

ParameterTypeDescription
locationstringA string or URL-based filepath.

Returns: Workspace

Error if no Workspace can be found.

Source: modules/graph/src/Graph.ts

getByName(name): Workspace

Get a Workspace by string name.

const workspace = graph.getByName('my-cool-package');

Parameters:

ParameterTypeDescription
namestringA Workspace’s name or any available aliases.

Returns: Workspace

Error if no Workspace exists with the given input name.

Source: modules/graph/src/Graph.ts


get aliases(): string[]

Allow custom array of aliases. If the fully qualified package name is scoped, this will include the un-scoped name

Returns: string[]
Source: modules/graph/src/Workspace.ts

get codeowners(): Required<Record<string, string[]>>

Returns: Required<Record<string, string[]>>
Source: modules/graph/src/Workspace.ts

get config(): Required<RootConfig | WorkspaceConfig>

Get the Workspace’s configuration

Returns: Required<RootConfig | WorkspaceConfig>
Source: modules/graph/src/Workspace.ts

get dependencies(): Record<string, string>

Get the package.json defined production dependencies for the Workspace.

Returns: Record<string, string>

Map of modules to their version.

Source: modules/graph/src/Workspace.ts

get description(): undefined | string

Canonical to the package.json "description" field.

Returns: undefined | string
Source: modules/graph/src/Workspace.ts

get devDependencies(): Record<string, string>

Get the package.json defined development dependencies for the Workspace.

Returns: Record<string, string>

Map of modules to their version.

Source: modules/graph/src/Workspace.ts

get isRoot(): boolean

Whether or not this Workspace is the root of the repository / Graph.

Returns: boolean
Source: modules/graph/src/Workspace.ts

get location(): string

Absolute path on the current filesystem to the Workspace.

Returns: string
Source: modules/graph/src/Workspace.ts

get main(): string

Returns: string
Source: modules/graph/src/Workspace.ts

get name(): string

The full name of the Workspace, as defined in its package.json

Returns: string
Source: modules/graph/src/Workspace.ts

get packageJson(): PackageJson

A full deep copy of the package.json file for the Workspace. Modifications to this object will not be preserved on the Workspace.

Returns: PackageJson
Source: modules/graph/src/Workspace.ts

get peerDependencies(): Record<string, string>

Get the package.json defined peer dependencies for the Workspace.

Returns: Record<string, string>

Map of modules to their version.

Source: modules/graph/src/Workspace.ts

get private(): boolean

If a Workspace package.json is set to private: true, it will not be available to publish through NPM or other package management registries.

Returns: boolean
Source: modules/graph/src/Workspace.ts

get publishablePackageJson(): null | PublicPackageJson

Get a version of the Workspace’s package.json that is meant for publishing.

This strips off devDependencies and applies appropriate publishConfig values to the root of the package.json. This feature enables your monorepo to use source-dependencies and avoid manually building shared Workspaces for every change in order to see them take affect in dependent Workspaces.

To take advantage of this, configure your package.json root level to point to source files and the publishConfig entries to point to the build location of those entrypoints.

{
3 collapsed lines
"name": "my-module",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"publishConfig": {
"access": "public",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts"
}
}

Returns: null | PublicPackageJson
Source: modules/graph/src/Workspace.ts

get scope(): string

Get module name scope if there is one, eg @onerepo

Returns: string
Source: modules/graph/src/Workspace.ts

get tasks(): Partial<Record<Lifecycle, Tasks>>

Get the task configuration as defined in the onerepo.config.js file at the root of the Workspace.

Returns: Partial<Record<Lifecycle, Tasks>>

If a config does not exist, an empty object will be given.

Source: modules/graph/src/Workspace.ts

get version(): undefined | string

Returns: undefined | string
Source: modules/graph/src/Workspace.ts

getCodeowners(filepath): string[]

Parameters:

ParameterType
filepathstring

Returns: string[]
Source: modules/graph/src/Workspace.ts

getTasks(lifecycle): Required<Tasks>

Get a list of Workspace tasks for the given lifecycle

Parameters:

ParameterType
lifecyclestring

Returns: Required<Tasks>
Source: modules/graph/src/Workspace.ts

relative(to): string

Get the relative path of an absolute path to the Workspace’s location root

const relativePath = workspace.relative('/some/absolute/path');

Parameters:

ParameterTypeDescription
tostringAbsolute filepath

Returns: string

Relative path to the workspace’s root location.

Source: modules/graph/src/Workspace.ts

resolve(...pathSegments): string

Resolve a full filepath within the Workspace given the path segments. Similar to Node.js’s path.resolve().

const main = workspace.resolve(workspace.main);

Parameters:

ParameterTypeDescription
…pathSegmentsstring[]A sequence of paths or path segments

Returns: string

Absolute path based on the input path segments

Source: modules/graph/src/Workspace.ts


const DependencyType: {
DEV: 2;
PEER: 1;
PROD: 3;
};
readonly DEV: 2;

Development-only dependency (defined in devDependencies keys of package.json)

readonly PEER: 1;

Peer dependency (defined in peerDependencies key of package.json)

readonly PROD: 3;

Production dependency (defined in dependencies of package.json)

Source: modules/graph/src/Graph.ts


type DepType: 1 | 2 | 3;

Dependency type value.

See also: DependencyType

Source: modules/graph/src/Graph.ts


type GraphSchemaValidators: Record<string, Record<string, Schema & {
$required: boolean;
} | (workspace, graph) => Schema & {
$required: boolean;
}>>;

Definition for graph verify JSON schema validators.

See “Validating configurations” for more examples and use cases.

import type { GraphSchemaValidators } from 'onerepo';
export default {
'**': {
'package.json': {
type: 'object',
$required: true,
properties: {
name: { type: 'string' },
},
required: ['name'],
},
},
} satisfies GraphSchemaValidators;

Source: modules/onerepo/src/core/graph/schema.ts

Alpha

bufferSubLogger(step): {
end: () => Promise<void>;
logger: Logger;
}

Create a new Logger instance that has its output buffered up to a LogStep.

const step = logger.createStep(name, { writePrefixes: false });
const subLogger = bufferSubLogger(step);
const substep = subLogger.logger.createStep('Sub-step');
substep.warning('This gets buffered');
await substep.end();
await subLogger.end();
await step.en();

Parameters:

ParameterType
stepLogStep

Returns: ```ts { end: () => Promise; logger: Logger; }

##### end
```ts
end: () => Promise<void>;

Returns: Promise<void>

logger: Logger;

Source: modules/logger/src/index.ts


getLogger(opts?): Logger

This gets the logger singleton for use across all of oneRepo and its commands.

Available directly as HandlerExtra on Handler functions:

export const handler: Handler = (argv, { logger }) => {
logger.log('Hello!');
};

Parameters:

ParameterType
opts?Partial<LoggerOptions>

Returns: Logger
Source: modules/logger/src/index.ts


stepWrapper<T>(options, fn): Promise<T>

For cases where multiple processes need to be completed, but should be joined under a single LogStep to avoid too much noisy output, this safely wraps an asynchronous function and handles step creation and completion, unless a step override is given.

export async function exists(filename: string, { step }: Options = {}) {
return stepWrapper({ step, name: 'Step fallback name' }, (step) => {
return; // do some work
});
}

Type parameters:

Type parameter
T

Parameters:

ParameterType
optionsObject
options.namestring
options.step?LogStep
fn(step) => Promise<T>

Returns: Promise<T>
Source: modules/logger/src/index.ts


Log steps should only be created via the logger.createStep() method.

const step = logger.createStep('Do some work');
// ... long task with a bunch of potential output
await step.end();
PropertyTypeDescription
hasErrorbooleanWhether or not an error has been sent to the step. This is not necessarily indicative of uncaught thrown errors, but solely on whether .error() has been called in this step.
hasInfobooleanWhether or not an info message has been sent to this step.
hasLogbooleanWhether or not a log message has been sent to this step.
hasWarningbooleanWhether or not a warning has been sent to this step.
end(): Promise<void>

Finish this step and flush all buffered logs. Once a step is ended, it will no longer accept any logging output and will be effectively removed from the base logger. Consider this method similar to a destructor or teardown.

await step.end();

Returns: Promise<void>
Source: modules/logger/src/LogStep.ts

debug(contents): void

Extra debug logging when verbosity greater than or equal to 4.

step.debug('Log this content when verbosity is >= 4');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged debug information:

step.debug(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
Source: modules/logger/src/LogStep.ts

error(contents): void

Log an error. This will cause the root logger to include an error and fail a command.

step.error('Log this content when verbosity is >= 1');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged error:

step.error(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
Source: modules/logger/src/LogStep.ts

info(contents): void

Log an informative message. Should be used when trying to convey information with a user that is important enough to always be returned.

step.info('Log this content when verbosity is >= 1');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:

step.info(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
Source: modules/logger/src/LogStep.ts

log(contents): void

General logging information. Useful for light informative debugging. Recommended to use sparingly.

step.log('Log this content when verbosity is >= 3');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:

step.log(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
Source: modules/logger/src/LogStep.ts

timing(start, end): void

Log timing information between two Node.js performance mark names.

Parameters:

ParameterTypeDescription
startstringA PerformanceMark entry name
endstringA PerformanceMark entry name

Returns: void
Source: modules/logger/src/LogStep.ts

warn(contents): void

Log a warning. Does not have any effect on the command run, but will be called out.

step.warn('Log this content when verbosity is >= 2');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged warning:

step.warn(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
Source: modules/logger/src/LogStep.ts


The oneRepo logger helps build commands and capture output from spawned subprocess in a way that’s both delightful to the end user and includes easy to scan and follow output.

All output will be redirected from stdout to stderr to ensure order of output and prevent confusion of what output can be piped and written to files.

If the current terminal is a TTY, output will be buffered and asynchronous steps will animated with a progress logger.

See HandlerExtra for access the the global Logger instance.

get hasError(): boolean

Whether or not an error has been sent to the logger or any of its steps. This is not necessarily indicative of uncaught thrown errors, but solely on whether .error() has been called in the Logger or any Step instance.

Returns: boolean
Source: modules/logger/src/Logger.ts

get hasInfo(): boolean

Whether or not an info message has been sent to the logger or any of its steps.

Returns: boolean
Source: modules/logger/src/Logger.ts

get hasLog(): boolean

Whether or not a log message has been sent to the logger or any of its steps.

Returns: boolean
Source: modules/logger/src/Logger.ts

get hasWarning(): boolean

Whether or not a warning has been sent to the logger or any of its steps.

Returns: boolean
Source: modules/logger/src/Logger.ts

get verbosity(): Verbosity

Get the logger’s verbosity level

set verbosity(value): void

Recursively applies the new verbosity to the logger and all of its active steps.

Parameters:

ParameterType
valueVerbosity

Returns: Verbosity
Source: modules/logger/src/Logger.ts

get writable(): boolean

Returns: boolean
Source: modules/logger/src/Logger.ts

createStep(name, __namedParameters?): LogStep

Create a sub-step, LogStep, for the logger. This and any other step will be tracked and required to finish before exit.

const step = logger.createStep('Do fun stuff');
// do some work
await step.end();

Parameters:

ParameterTypeDescription
namestringThe name to be written and wrapped around any output logged to this new step.
__namedParameters?Object-
__namedParameters.writePrefixes?boolean-

Returns: LogStep
Source: modules/logger/src/Logger.ts

pause(write?): void

When the terminal is a TTY, steps are automatically animated with a progress indicator. There are times when it’s necessary to stop this animation, like when needing to capture user input from stdin. Call the pause() method before requesting input and logger.unpause() when complete.

This process is also automated by the run() function when stdio is set to pipe.

logger.pause();
// capture input
logger.unpause();

Parameters:

ParameterType
write?boolean

Returns: void
Source: modules/logger/src/Logger.ts

unpause(): void

Unpause the logger and resume writing buffered logs to stderr. See logger.pause() for more information.

Returns: void
Source: modules/logger/src/Logger.ts

debug(contents): void

Extra debug logging when verbosity greater than or equal to 4.

logger.debug('Log this content when verbosity is >= 4');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged debug information:

logger.debug(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
See also: debug() This is a pass-through for the main step’s debug() method.

Source: modules/logger/src/Logger.ts

error(contents): void

Log an error. This will cause the root logger to include an error and fail a command.

logger.error('Log this content when verbosity is >= 1');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged error:

logger.error(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
See also: error() This is a pass-through for the main step’s error() method.

Source: modules/logger/src/Logger.ts

info(contents): void

Should be used to convey information or instructions through the log, will log when verbositu >= 1

logger.info('Log this content when verbosity is >= 1');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:

logger.info(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
See also: info() This is a pass-through for the main step’s info() method.

Source: modules/logger/src/Logger.ts

log(contents): void

General logging information. Useful for light informative debugging. Recommended to use sparingly.

logger.log('Log this content when verbosity is >= 3');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged information:

logger.log(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
See also: log() This is a pass-through for the main step’s log() method.

Source: modules/logger/src/Logger.ts

timing(start, end): void

Log timing information between two Node.js performance mark names.

Parameters:

ParameterTypeDescription
startstringA PerformanceMark entry name
endstringA PerformanceMark entry name

Returns: void
See also: timing() This is a pass-through for the main step’s timing() method.

Source: modules/logger/src/Logger.ts

warn(contents): void

Log a warning. Does not have any effect on the command run, but will be called out.

logger.warn('Log this content when verbosity is >= 2');

If a function with zero arguments is passed, the function will be executed before writing. This is helpful for avoiding extra work in the event that the verbosity is not actually high enough to render the logged warning:

logger.warn(() => bigArray.map((item) => item.name));

Parameters:

ParameterTypeDescription
contentsunknownAny value that can be converted to a string for writing to stderr.

Returns: void
See also: warn() This is a pass-through for the main step’s warn() method.

Source: modules/logger/src/Logger.ts


type LoggerOptions: {
stream: Writable;
verbosity: Verbosity;
};
optional stream: Writable;

Advanced – override the writable stream in order to pipe logs elsewhere. Mostly used for dependency injection for @onerepo/test-cli.

verbosity: Verbosity;

Control how much and what kind of output the Logger will provide.

Source: modules/logger/src/Logger.ts


type Verbosity:
| 0
| 1
| 2
| 3
| 4
| 5;

Control the verbosity of the log output

ValueWhatDescription
<= 0SilentNo output will be read or written.
>= 1Error, Info
>= 2Warnings
>= 3Log
>= 4Debuglogger.debug() will be included
>= 5TimingExtra performance timing metrics will be written

Source: modules/logger/src/Logger.ts

getLockfile(cwd): string | null

Get the absolute path for the package manager’s lock file for this repository.

Parameters:

ParameterType
cwdstring

Returns: string | null
Source: modules/package-manager/src/get-package-manager.ts


getPackageManager(type): PackageManager

Get the PackageManager for the given package manager type (NPM, PNPm, or Yarn)

Parameters:

ParameterType
type"yarn" | "pnpm" | "npm"

Returns: PackageManager
Source: modules/package-manager/src/index.ts


getPackageManagerName(cwd, fromPkgJson?): "npm" | "pnpm" | "yarn"

Get the package manager for the current working directory with some confidence

Parameters:

ParameterTypeDescription
cwdstringCurrent working directory. Should be the root of the module/repository.
fromPkgJson?stringValue as defined in a package.json file, typically the packageManager value

Returns: "npm" | "pnpm" | "yarn"
Source: modules/package-manager/src/get-package-manager.ts


Implementation details for all package managers. This interface defines a subset of common methods typically needed when interacting with a monorepo and its dependency Graph & Workspaces.

add(packages, opts?): Promise<void>

Add one or more packages from external registries

Parameters:

ParameterTypeDescription
packagesstring | string[]One or more packages, by name and/or 'name@version'.
opts?ObjectVarious options to pass while installing the packages
opts.dev?booleanSet to true to install as a devDependency.

Default
false

Returns: Promise<void>
Source: modules/package-manager/src/methods.ts

batch(processes): Promise<(Error | [string, string])[]>

Batch commands from npm packages as a batch of subprocesses using the package manager. Alternative to batching with npm exec and compatible APIs.

Parameters:

ParameterType
processesRunSpec[]

Returns: Promise<(Error | [string, string])[]>
See also: batch for general subprocess batching.

Source: modules/package-manager/src/methods.ts

dedupe(): Promise<void>

Reduce duplication in the package tree by checking overlapping ranges.

Returns: Promise<void>
Source: modules/package-manager/src/methods.ts

info(name, opts?): Promise<null | NpmInfo>

Get standard information about a package

Parameters:

ParameterType
namestring
opts?Partial<RunSpec>

Returns: Promise<null | NpmInfo>
Source: modules/package-manager/src/methods.ts

install(cwd?): Promise<string>

Install current dependencies as listed in the package manager’s lock file

Parameters:

ParameterType
cwd?string

Returns: Promise<string>
Source: modules/package-manager/src/methods.ts

loggedIn(opts?): Promise<boolean>

Check if the current user is logged in to the external registry

Parameters:

ParameterTypeDescription
opts?Object-
opts.registry?stringThe base URL of your NPM registry. PNPM and NPM ignore scope and look up per-registry.
opts.scope?stringWhen using Yarn, lookups are done by registry configured by scope. This value must be included if you have separate registries for separate scopes.

Returns: Promise<boolean>
Source: modules/package-manager/src/methods.ts

publish<T>(opts): Promise<void>

Publish Workspaces to the external registry

Type parameters:

Type parameter
T extends MinimalWorkspace

Parameters:

ParameterTypeDescription
optsObject-
opts.access?"restricted" | "public"Set the registry access level for the package

Default
inferred from Workspaces publishConfig.access or 'public'
opts.cwd?stringCommand working directory. Defaults to the repository root.
opts.otp?stringThis is a one-time password from a two-factor authenticator.
opts.tag?stringIf you ask npm to install a package and don’t tell it a specific version, then it will install the specified tag.

Default
'latest'
opts.workspacesT[]Workspaces to publish. If not provided or empty array, only the given Workspace at cwd will be published. This type is generally compatible with Workspace.

Returns: Promise<void>
Source: modules/package-manager/src/methods.ts

publishable<T>(workspaces): Promise<T[]>

Filter Workspaces to the set of those that are actually publishable. This will check both whether the package is not marked as “private” and if the current version is not in the external registry.

Type parameters:

Type parameter
T extends MinimalWorkspace

Parameters:

ParameterTypeDescription
workspacesT[]List of compatible Workspace objects.

Returns: Promise<T[]>
Source: modules/package-manager/src/methods.ts

remove(packages): Promise<void>

Remove one or more packages.

Parameters:

ParameterTypeDescription
packagesstring | string[]One or more packages, by name

Returns: Promise<void>
Source: modules/package-manager/src/methods.ts

run(opts): Promise<[string, string]>

Run a command from an npm package as a subprocess using the package manager. Alternative to npm exec and compatible APIs.

Parameters:

ParameterType
optsRunSpec

Returns: Promise<[string, string]>
See also: batch for general subprocess running.

Source: modules/package-manager/src/methods.ts


type MinimalWorkspace: {
location: string;
name: string;
private: boolean;
version: string;
};
optional location: string;
name: string;
optional private: boolean;
optional version: string;

Source: modules/package-manager/src/methods.ts


type NpmInfo: {
dependencies: Record<string, string>;
dist-tags: {
[key: string]: string; latest: string;
};
homepage: string;
license: string;
name: string;
version: string;
versions: string[];
};
dependencies: Record<string, string>;
dist-tags: {
[key: string]: string; latest: string;
};

[key: string]: string

latest: string;
homepage: string;
license: string;
name: string;
version: string;
versions: string[];

Source: modules/package-manager/src/methods.ts

type Plugin: PluginObject | (config, graph) => PluginObject;

Source: modules/onerepo/src/types/plugin.ts


type PluginObject: {
shutdown: (argv) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void;
startup: (argv) => Promise<void> | void;
yargs: (yargs, visitor) => Yargs;
};
optional shutdown: (argv) => Promise<Record<string, unknown> | void> | Record<string, unknown> | void;

Runs just before the application process is exited. Allows returning data that will be merged with all other shutdown handlers.

Parameters:

ParameterType
argvArgv<DefaultArgv>

Returns: Promise<Record<string, unknown> | void> | Record<string, unknown> | void

optional startup: (argv) => Promise<void> | void;

Runs before any and all commands after argument parsing. This is similar to global Yargs middleware, but guaranteed to have the fully resolved and parsed arguments.

Use this function for setting up global even listeners like PerformanceObserver, process events, etc.

Parameters:

ParameterType
argvArgv<DefaultArgv>

Returns: Promise<void> | void

optional yargs: (yargs, visitor) => Yargs;

A function that is called with the CLI’s yargs object and a visitor. It is important to ensure every command passed through the visitor to enable all of the features of oneRepo. Without this step, you will not have access to the Workspace Graph, affected list, and much more.

Parameters:

ParameterType
yargsYargs
visitorNonNullable<RequireDirectoryOptions["visit"]>

Returns: Yargs
Source: modules/onerepo/src/types/plugin.ts

batch(processes, options?): Promise<([string, string] | Error)[]>

Batch multiple subprocesses, similar to Promise.all, but only run as many processes at a time fulfilling N-1 cores. If there are more processes than cores, as each process finishes, a new process will be picked to run, ensuring maximum CPU usage at all times.

If any process throws a SubprocessError, this function will reject with a BatchError, but only after all processes have completed running.

Most oneRepo commands will consist of at least one run() or batch() processes.

const processes: Array<RunSpec> = [
{ name: 'Say hello', cmd: 'echo', args: ['"hello"'] },
{ name: 'Say world', cmd: 'echo', args: ['"world"'] },
];
const results = await batch(processes);
expect(results).toEqual([
['hello', ''],
['world', ''],
]);

Parameters:

ParameterType
processes(RunSpec | PromiseFn)[]
options?BatchOptions

Returns: Promise<([string, string] | Error)[]>

BatchError An object that includes a list of all of the SubprocessErrors thrown.

See also: PackageManager.batch to safely batch executables exposed from third party modules.

Source: modules/subprocess/src/index.ts


run(options): Promise<[string, string]>

Spawn a process and capture its stdout and stderr through a Logger Step. Most oneRepo commands will consist of at least one run() or batch() processes.

The run() command is an async wrapper around Node.js’s child_process.spawn and has a very similar API, with some additions. This command will buffer and catch all stdout and stderr responses.

await run({
name: 'Do some work',
cmd: 'echo',
args: ['"hello!"'],
});

Skipping failures:

If a subprocess fails when called through run(), a SubprocessError will be thrown. Some third-party tooling will exit with error codes as an informational tool. While this is discouraged, there’s nothing we can do about how they’ve been chosen to work. To prevent throwing errors, but still act on the stderr response, include the skipFailures option:

const [stdout, stderr] = await run({
name: 'Run dry',
cmd: 'echo',
args: ['"hello"'],
skipFailures: true,
});
logger.error(stderr);

Dry-run:

By default, run() will respect oneRepo’s --dry-run option (see DefaultArgv, process.env.ONEREPO_DRY_RUN). When set, the process will not be spawned, but merely log information about what would run instead. To continue running a command, despite the --dry-run option being set, use runDry: true:

await run({
name: 'Run dry',
cmd: 'echo',
args: ['"hello"'],
runDry: true,
});

Parameters:

ParameterType
optionsRunSpec

Returns: Promise<[string, string]>

A promise with an array of [stdout, stderr], as captured from the command run.

SubprocessError if not skipFailures and the spawned process does not exit cleanly (with code 0)

See also: PackageManager.run to safely run executables exposed from third party modules.

Source: modules/subprocess/src/index.ts


Alpha

runTasks(
lifecycle,
args,
graph,
logger?): Promise<void>

Run Lifecycle tasks in commands other than the one tasks command. Use this function when you have a command triggering a Lifecycle in non-standard ways.

await runTasks('pre-publish', ['-w', 'my-workspace'], graph);

Parameters:

ParameterTypeDescription
lifecycleLifecycleThe individual Lifecycle to trigger.
argsstring[]Array of string arguments as if passed in from the command-line.
graphGraphThe current repository Graph.
logger?LoggerOptional Logger instance. Defaults to the current Logger (usually there is only one).

Returns: Promise<void>
Source: modules/onerepo/src/core/tasks/run-tasks.ts


start(options): ChildProcess

Start a subprocess. For use when control over watching the stdout and stderr or long-running processes that are not expected to complete without SIGINT/SIGKILL.

Parameters:

ParameterType
optionsOmit<RunSpec, "name" | "runDry">

Returns: ChildProcess
Source: modules/subprocess/src/index.ts


sudo(options): Promise<[string, string]>

This function is similar to run, but can request and run with elevated sudo permissions. This function should not be used unless you absolutely know that you will need to spawn an executable with elevated permissions.

This function will first check if sudo permissions are valid. If not, the logger will warn the user that sudo permissions are being requested and properly pause the animated logger while the user enters their password directly through stdin. If permissions are valid, no warning will be given.

await sudo({
name: 'Change permissions',
cmd: 'chmod',
args: ['a+x', '/usr/bin/thing'],
reason: 'When prompted, please type your password and hit [RETURN] to allow `thing` to be run later',
});

Parameters:

ParameterType
optionsOmit<RunSpec, "opts"> & { reason: string; }

Returns: Promise<[string, string]>
Source: modules/subprocess/src/index.ts


  • Error
new BatchError(errors, options)
Section titled new BatchError(errors, options)
new BatchError(errors, options?): BatchError

Parameters:

ParameterType
errors(string | SubprocessError)[]
options?ErrorOptions

Returns: BatchError

Error.constructor

Source: modules/subprocess/src/index.ts

PropertyModifierTypeDescriptionInherited from
cause?publicunknown-Error.cause
errorspublic(string | SubprocessError)[]--
messagepublicstring-Error.message
namepublicstring-Error.name
prepareStackTrace?static(err: Error, stackTraces: CallSite[]) => anyOptional override for formatting stack traces

See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Error.prepareStackTrace
stack?publicstring-Error.stack
stackTraceLimitstaticnumber-Error.stackTraceLimit
static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters:

ParameterType
targetObjectobject
constructorOpt?Function

Returns: void

Error.captureStackTrace

Source: node_modules/@types/node/globals.d.ts:21


  • Error
new SubprocessError(message, options)
Section titled new SubprocessError(message, options)
new SubprocessError(message, options?): SubprocessError

Parameters:

ParameterType
messagestring
options?ErrorOptions

Returns: SubprocessError

Error.constructor

Source: modules/subprocess/src/index.ts

PropertyModifierTypeDescriptionInherited from
cause?publicunknown-Error.cause
messagepublicstring-Error.message
namepublicstring-Error.name
prepareStackTrace?static(err: Error, stackTraces: CallSite[]) => anyOptional override for formatting stack traces

See
https://v8.dev/docs/stack-trace-api#customizing-stack-traces
Error.prepareStackTrace
stack?publicstring-Error.stack
stackTraceLimitstaticnumber-Error.stackTraceLimit
static captureStackTrace(targetObject, constructorOpt?): void

Create .stack property on a target object

Parameters:

ParameterType
targetObjectobject
constructorOpt?Function

Returns: void

Error.captureStackTrace

Source: node_modules/@types/node/globals.d.ts:21


type BatchOptions: {
maxParallel: number;
};

Options for running batch() subprocesses.

optional maxParallel: number;

The absolute maximum number of subprocesses to batch. This amount will always be limited by the number of CPUs/cores available on the current machine.

Default: deterministic Number of CPUs - 1
Source: modules/subprocess/src/index.ts


type PromiseFn: () => Promise<[string, string]>;

Returns: Promise<[string, string]>
Source: modules/subprocess/src/index.ts


type RunSpec: {
args: string[];
cmd: string;
name: string;
opts: SpawnOptions;
runDry: boolean;
skipFailures: boolean;
step: LogStep;
};

The core configuration for run, start, sudo, and batch subprocessing.

optional args: string[];

Arguments to pass to the executable. All arguments must be separate string entries.

Beware that some commands have different ways of parsing arguments.

Typically, it is safest to have separate entries in the args array for the flag and its value:

args: ['--some-flag', 'some-flags-value']

However, if an argument parser is implemented in a non-standard way, the flag and its value may need to be a single entry:

args: ['--some-flag=some-flags-value']
cmd: string;

The command to run. This should be an available executable or path to an executable.

name: string;

A friendly name for the Step in log output.

optional opts: SpawnOptions;

See the Node.js child_process.spawn() documentation for available options.

optional runDry: boolean;

Skip the --dry-run check and run this command anyway.

optional skipFailures: boolean;

Prevents throwing a SubprocessError in the event of the process failing and exiting with an unclean state.

optional step: LogStep;

Pass a custom LogStep to bundle this process input & output into another step instead of creating a new one.

Source: modules/subprocess/src/index.ts

getPublishablePackageJson(input): PublicPackageJson

Return a deep copy of a package.json suitabkle for publishing. Moves all non-standard publishConfig keys to the root of the package.json and deletes devDependencies.

Parameters:

ParameterType
inputPublicPackageJson

Returns: PublicPackageJson
Source: modules/package-manager/src/package-json.ts


type BasePackageJson: {
alias: string[];
author: string | Person;
bin: string | Record<string, string>;
bugs: {
email: string;
url: string;
};
bundleDependencies: string[];
contributors: (Person | string)[];
dependencies: Record<string, string>;
description: string;
devDependencies: Record<string, string>;
engines: Record<string, string>;
exports: Record<string, string | {
default: string;
import: string;
require: string;
types: string;
}>;
files: string[];
homepage: string;
keywords: string[];
license: string;
main: string;
name: string;
optionalDependencies: string[];
os: string[];
overrides: Record<string, string>;
packageManager: string;
peerDependencies: Record<string, string>;
peerDependenciesMeta: Record<string, {
optional: boolean;
}>;
scripts: Record<string, string>;
version: string;
};
optional alias: string[];

Enable’s the Graph to look up Workspaces by shorter names or common aliases used by teams. This enables much short command-line execution. See Graph.getByName and Graph.getAllByName.

optional author: string | Person;
optional bin: string | Record<string, string>;
optional bugs: {
email: string;
url: string;
};
optional email: string;
optional url: string;
optional bundleDependencies: string[];
optional contributors: (Person | string)[];
optional dependencies: Record<string, string>;
optional description: string;
optional devDependencies: Record<string, string>;
optional engines: Record<string, string>;
optional exports: Record<string, string | {
default: string;
import: string;
require: string;
types: string;
}>;
optional files: string[];
optional homepage: string;
optional keywords: string[];
optional license: string;
optional main: string;
name: string;

The full name for the Workspace. This will be used within the package manager and publishable registry.

optional optionalDependencies: string[];
optional os: string[];
optional overrides: Record<string, string>;
optional packageManager: string;
optional peerDependencies: Record<string, string>;
optional peerDependenciesMeta: Record<string, {
optional: boolean;
}>;
optional scripts: Record<string, string>;
optional version: string;

Source: modules/package-manager/src/package-json.ts


type PackageJson: PrivatePackageJson | PublicPackageJson;

Source: modules/package-manager/src/package-json.ts


type Person: {
email: string;
name: string;
url: string;
};
optional email: string;
optional name: string;
optional url: string;

Source: modules/package-manager/src/package-json.ts


type PrivatePackageJson: {
license: "UNLICENSED";
private: true;
workspaces: string[];
} & BasePackageJson;
optional license: "UNLICENSED";
private: true;
optional workspaces: string[];

Source: modules/package-manager/src/package-json.ts


type PublicPackageJson: {
private: false;
publishConfig: PublishConfig;
workspaces: never;
} & BasePackageJson;
optional private: false;
optional publishConfig: PublishConfig;
optional workspaces: never;

Source: modules/package-manager/src/package-json.ts


type PublishConfig: {
[key: typeof publishConfigKeep[number]]: unknown; bin: string | Record<string, string>;
exports: Record<string, string | {
default: string;
import: string;
require: string;
types: string;
}>;
main: string;
module: string;
typings: string;
};

The publishConfig should follow NPM’s guidelines, apart from the possible defined extra keys here. Anything defined here will be merged back to the root of the package.json at publish time.

Use these keys to help differentiate between your repository’s source-dependency entrypoints vs published module entrypoints.

{
3 collapsed lines
"name": "my-module",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"publishConfig": {
"access": "public",
"main": "./dist/index.js",
"typings": "./dist/index.d.ts"
}
}

[key: typeof publishConfigKeep[number]]: unknown

optional bin: string | Record<string, string>;
optional exports: Record<string, string | {
default: string;
import: string;
require: string;
types: string;
}>;
optional main: string;
optional module: string;
optional typings: string;

Source: modules/package-manager/src/package-json.ts