Modern package manager CLI for Node.js and other languages with plugin support, workspaces, and advanced dependency management features
npx @tessl/cli install tessl/npm-yarnpkg--cli@4.9.00
# Yarn CLI
1
2
Yarn CLI provides a programmatic interface for the Yarn package manager, enabling developers to integrate Yarn's functionality into their applications. It offers APIs for creating CLI instances, executing commands, and extending functionality through plugins.
3
4
## Package Information
5
6
- **Package Name**: @yarnpkg/cli
7
- **Package Type**: npm
8
- **Language**: TypeScript
9
- **Installation**: `npm install @yarnpkg/cli`
10
11
## Core Imports
12
13
```typescript
14
import { getCli, runExit, BaseCommand, type YarnCli, type CommandContext } from "@yarnpkg/cli";
15
```
16
17
For CommonJS:
18
19
```javascript
20
const { getCli, runExit, BaseCommand } = require("@yarnpkg/cli");
21
```
22
23
## Basic Usage
24
25
```typescript
26
import { getCli, runExit, getPluginConfiguration } from "@yarnpkg/cli";
27
import { ppath } from "@yarnpkg/fslib";
28
29
// Create a Yarn CLI instance with default plugins
30
const cli = await getCli({
31
cwd: ppath.cwd(),
32
pluginConfiguration: getPluginConfiguration()
33
});
34
35
// Process and execute a command
36
const command = cli.process(["install"], cli.defaultContext);
37
const exitCode = await cli.run(command, cli.defaultContext);
38
39
// Or run and exit (for standalone applications)
40
await runExit(["install"], {
41
cwd: ppath.cwd(),
42
selfPath: null,
43
pluginConfiguration: getPluginConfiguration()
44
});
45
```
46
47
## Architecture
48
49
Yarn CLI is built around several key components:
50
51
- **CLI Factory**: `getCli()` function creates configured CLI instances with plugin support
52
- **Command Runner**: `runExit()` executes commands and handles process lifecycle
53
- **Base Command Class**: `BaseCommand` provides foundation for creating custom Yarn commands
54
- **Plugin System**: Dynamic plugin loading and configuration through `getPluginConfiguration()`
55
- **Workspace Tools**: Utilities for working with Yarn workspaces and projects
56
- **Error Handling**: Specialized error classes for workspace and command validation
57
58
## Capabilities
59
60
### CLI Instance Creation
61
62
Create and configure Yarn CLI instances with plugin support and workspace awareness.
63
64
```typescript { .api }
65
/**
66
* Creates a Yarn CLI instance with initialized commands
67
* @param options - Configuration options
68
* @returns Promise that resolves to a configured YarnCli instance
69
*/
70
function getCli(options?: {
71
cwd?: PortablePath;
72
pluginConfiguration?: PluginConfiguration;
73
}): Promise<YarnCli>;
74
75
/**
76
* Yarn CLI instance with command registration and execution capabilities
77
*/
78
interface YarnCli extends Cli<CommandContext> {
79
/** Default context object used for command execution */
80
readonly defaultContext: CommandContext & {
81
cwd: PortablePath;
82
plugins: PluginConfiguration;
83
quiet: boolean;
84
stdin: NodeJS.ReadableStream;
85
stdout: NodeJS.WritableStream;
86
stderr: NodeJS.WritableStream;
87
};
88
89
/** Binary label displayed in help output */
90
readonly binaryLabel: string;
91
92
/** Binary name used in command line */
93
readonly binaryName: string;
94
95
/** Binary version string */
96
readonly binaryVersion: string | null;
97
98
/** Register a command class with the CLI */
99
register(command: new () => Command<CommandContext>): void;
100
101
/** Process command line arguments and return command instance */
102
process(argv: Array<string>, context: CommandContext): Command<CommandContext>;
103
104
/** Execute a command instance */
105
run(command: Command<CommandContext>, context: CommandContext): Promise<number>;
106
107
/** Format an error for display */
108
error(error: Error): string;
109
}
110
```
111
112
### Command Execution
113
114
Execute Yarn commands programmatically with full process lifecycle management.
115
116
```typescript { .api }
117
/**
118
* Runs Yarn CLI with the given arguments and exits the process
119
* @param argv - Command line arguments array
120
* @param options - Execution options
121
*/
122
function runExit(
123
argv: Array<string>,
124
options: {
125
cwd: PortablePath;
126
selfPath: PortablePath | null;
127
pluginConfiguration: PluginConfiguration;
128
}
129
): Promise<void>;
130
```
131
132
### Command Development
133
134
Base class for creating custom Yarn commands with proper context handling.
135
136
```typescript { .api }
137
/**
138
* Base class for creating Yarn commands
139
*/
140
abstract class BaseCommand extends Command<CommandContext> {
141
/** Hidden cwd option for command-line usage */
142
cwd: string | undefined;
143
144
/** Must be implemented by subclasses */
145
abstract execute(): Promise<number | void>;
146
147
/** Validates cwd option and executes command */
148
validateAndExecute(): Promise<number>;
149
}
150
```
151
152
### Workspace Management
153
154
Utilities for working with Yarn workspaces and handling workspace-specific operations.
155
156
```typescript { .api }
157
/**
158
* Opens a workspace at the given directory
159
* @param configuration - Configuration object
160
* @param cwd - Working directory path
161
* @returns Promise that resolves to Workspace object
162
* @throws WorkspaceRequiredError if not in a workspace
163
*/
164
function openWorkspace(
165
configuration: Configuration,
166
cwd: PortablePath
167
): Promise<Workspace>;
168
169
/**
170
* Error thrown when a command requires a workspace context
171
*/
172
class WorkspaceRequiredError extends UsageError {
173
constructor(projectCwd: PortablePath, cwd: PortablePath);
174
}
175
```
176
177
### Plugin Configuration
178
179
Manage Yarn's plugin system and dynamic library loading.
180
181
```typescript { .api }
182
/**
183
* Gets the standard plugin configuration for Yarn CLI
184
* @returns Configuration object with plugins and modules
185
*/
186
function getPluginConfiguration(): PluginConfiguration;
187
188
/**
189
* Returns a map of dynamic libraries available to plugins
190
* @returns Map containing Yarn modules and dependencies
191
*/
192
function getDynamicLibs(): Map<string, any>;
193
194
/**
195
* Map of plugin names to their command arrays (auto-generated)
196
*/
197
const pluginCommands: Map<string, Array<string>>;
198
```
199
200
## Types
201
202
```typescript { .api }
203
/**
204
* Context object passed to Yarn commands with execution environment
205
*/
206
interface CommandContext {
207
/** Current working directory */
208
cwd: PortablePath;
209
/** Plugin configuration */
210
plugins: PluginConfiguration;
211
/** Whether to suppress output */
212
quiet: boolean;
213
/** Standard input stream */
214
stdin: NodeJS.ReadableStream;
215
/** Standard output stream */
216
stdout: NodeJS.WritableStream;
217
/** Standard error stream */
218
stderr: NodeJS.WritableStream;
219
/** Additional properties from @yarnpkg/core CommandContext */
220
[key: string]: any;
221
}
222
223
/**
224
* Plugin configuration interface for managing Yarn plugins
225
*/
226
interface PluginConfiguration {
227
/** Set of plugin names to load */
228
plugins: Set<string>;
229
/** Map of module names to their implementations */
230
modules: Map<string, any>;
231
}
232
233
/**
234
* Portable path type from @yarnpkg/fslib
235
*/
236
type PortablePath = import("@yarnpkg/fslib").PortablePath;
237
238
/**
239
* Configuration object from @yarnpkg/core
240
*/
241
type Configuration = import("@yarnpkg/core").Configuration;
242
243
/**
244
* Workspace object from @yarnpkg/core
245
*/
246
type Workspace = import("@yarnpkg/core").Workspace;
247
```
248
249
## Error Handling
250
251
The CLI properly handles various error conditions:
252
253
- **Node Version Validation**: Ensures compatible Node.js version (>=18.12.0)
254
- **Workspace Errors**: `WorkspaceRequiredError` when workspace context is required
255
- **Configuration Errors**: Proper error reporting for invalid configurations
256
- **Plugin Errors**: Graceful handling of plugin loading failures
257
258
## Advanced Usage
259
260
### Creating Custom Commands
261
262
```typescript
263
import { BaseCommand } from "@yarnpkg/cli";
264
import { Option } from "clipanion";
265
266
class MyCustomCommand extends BaseCommand {
267
static paths = [["my", "command"]];
268
269
myOption = Option.String("--option", "default-value");
270
271
async execute() {
272
this.context.stdout.write(`Option value: ${this.myOption}\n`);
273
return 0;
274
}
275
}
276
277
// Register with CLI instance
278
const cli = await getCli();
279
cli.register(MyCustomCommand);
280
```
281
282
### Working with Workspaces
283
284
```typescript
285
import { openWorkspace, getPluginConfiguration } from "@yarnpkg/cli";
286
import { Configuration } from "@yarnpkg/core";
287
import { ppath } from "@yarnpkg/fslib";
288
289
try {
290
const configuration = await Configuration.find(
291
ppath.cwd(),
292
getPluginConfiguration()
293
);
294
295
const workspace = await openWorkspace(configuration, ppath.cwd());
296
console.log(`Workspace: ${workspace.locator.name}`);
297
} catch (error) {
298
if (error instanceof WorkspaceRequiredError) {
299
console.error("Not in a workspace directory");
300
}
301
}
302
```