CLIアプリケーション構築のためのコアユーティリティ。
すべての機能は @d-zero/cli-core からインポートできます:
createCLI- CLIアプリケーションを作成し、コマンドライン引数をパースparseCommonOptions- 共通のCLIオプションをパースparseList- カンマ区切りの文字列を配列に変換- 型定義:
BaseCLIOptions,CLIAlias,CLIConfig,ParsedCLI
CLIアプリケーションを作成し、コマンドライン引数をパースします。検証に失敗した場合は使用方法を表示して終了します。
パラメータ:
config: CLIConfig<T>- CLI設定オブジェクトname?: string- パッケージ名(バージョン表示時に使用)version?: string- パッケージバージョン(-v/--versionオプションで表示)aliases?: CLIAlias- コマンドラインオプションのエイリアス定義(例:{ o: 'output' })usage: string[]- ヘルプメッセージとして表示される使用方法の文字列配列parseArgs: (cli: ParsedArgs) => T- 引数をパースしてオプションオブジェクトに変換する関数validateArgs: (options: T, cli: ParsedArgs) => boolean- 引数の妥当性を検証する関数(falseを返すと終了)
バージョン表示:
nameとversionを設定すると、-vまたは--versionオプションでバージョン情報を表示できます。ただし、aliasesでvが既に別のオプションに割り当てられている場合は、--versionのみが使用可能です。
戻り値:
ParsedCLI<T> オブジェクト:
options: T- パースされたオプションargs: string[]- 位置引数の配列hasConfigFile: boolean- 設定ファイル(listfileオプション)が指定されているかどうか
使用例:
import { createRequire } from 'node:module';
import { createCLI, type BaseCLIOptions } from '@d-zero/cli-core';
const require = createRequire(import.meta.url);
const pkg = require('../package.json') as { name: string; version: string };
interface MyOptions extends BaseCLIOptions {
output?: string;
}
const cli = createCLI<MyOptions>({
name: pkg.name,
version: pkg.version,
aliases: {
o: 'output',
l: 'limit',
d: 'debug',
},
usage: [
'Usage: my-cli [options] <input>',
'',
'Options:',
' -o, --output <file> 出力ファイルパス',
' -l, --limit <num> 処理する最大件数',
' -d, --debug デバッグモードを有効化',
],
parseArgs: (cli) => ({
output: cli.output,
limit: cli.limit ? Number.parseInt(cli.limit) : undefined,
debug: !!cli.debug,
}),
validateArgs: (options, cli) => {
return cli._.length > 0; // 少なくとも1つの引数が必要
},
});
console.log(cli.options); // パースされたオプション
console.log(cli.args); // 位置引数parseCommonOptions(cli: ParsedArgs): Pick<BaseCLIOptions, 'limit' | 'debug' | 'verbose' | 'interval'>
共通のCLIオプション(limit, debug, verbose, interval)をパースします。createCLIのparseArgs関数内で使用することを想定しています。
パラメータ:
cli: ParsedArgs-minimistでパースされた引数オブジェクト
戻り値:
以下のプロパティを持つオブジェクト:
limit?: number- 処理する最大件数debug?: boolean- デバッグモードフラグverbose?: boolean- 詳細出力モードフラグinterval?: number | DelayOptions- 処理間隔(ミリ秒または遅延オプション)
使用例:
import { createCLI, parseCommonOptions } from '@d-zero/cli-core';
const cli = createCLI({
parseArgs: (parsedArgs) => {
const common = parseCommonOptions(parsedArgs);
return {
...common,
// カスタムオプションを追加
output: parsedArgs.output,
};
},
// ...
});カンマ区切りの文字列をパースして、トリミングされた文字列の配列に変換します。
パラメータ:
listParam: string- カンマ区切りの文字列
戻り値:
string[] - トリミングされた文字列の配列
使用例:
import { parseList } from '@d-zero/cli-core';
const result = parseList('apple, banana, cherry');
console.log(result); // ['apple', 'banana', 'cherry']
const result2 = parseList('item1,item2, item3 ');
console.log(result2); // ['item1', 'item2', 'item3']