{"id":15286987,"url":"https://github.com/author/arg","last_synced_at":"2025-04-13T04:12:12.859Z","repository":{"id":48259111,"uuid":"226461132","full_name":"author/arg","owner":"author","description":"An argument parser for CLI applications.","archived":false,"fork":false,"pushed_at":"2022-11-12T03:52:06.000Z","size":147,"stargazers_count":11,"open_issues_count":1,"forks_count":2,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-01T17:08:56.604Z","etag":null,"topics":["argument-parser","browser","cli","deno","javascript","nodejs","shell","web"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/author.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["coreybutler"],"patreon":null,"open_collective":null,"ko_fi":null,"tidelift":null,"community_bridge":null,"liberapay":null,"issuehunt":null,"otechie":null,"custom":null}},"created_at":"2019-12-07T05:31:12.000Z","updated_at":"2023-08-23T03:41:17.000Z","dependencies_parsed_at":"2023-01-22T00:19:32.747Z","dependency_job_id":null,"html_url":"https://github.com/author/arg","commit_stats":null,"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/author%2Farg","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/author%2Farg/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/author%2Farg/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/author%2Farg/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/author","download_url":"https://codeload.github.com/author/arg/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248566413,"owners_count":21125663,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["argument-parser","browser","cli","deno","javascript","nodejs","shell","web"],"created_at":"2024-09-30T15:20:12.449Z","updated_at":"2025-04-13T04:12:12.831Z","avatar_url":"https://github.com/author.png","language":"JavaScript","readme":"# Argument Parser ![Version](https://img.shields.io/github/v/tag/author/arg?label=Latest\u0026style=for-the-badge)\n\nThere are many CLI argument parsers for Node.js. This differs in the following ways:\n\n1. Uses modern [ES Modules](https://nodejs.org/api/esm.html#esm_ecmascript_modules) with private properties (easy to read).\n1. No dependencies.\n1. Separation of Concerns.*\n1. Also works in browsers.\n\nAfter writing countless CLI utilities, it became clear that the majority of most existing libraries contain a ton of code that really isn't necessary 99% of the time. This library is still very powerful, but works very transparently, with a minimal API.\n\n\u003e **This tool is just a parser.** It parses arguments and optionally enforces developer-defined rules. It exposes all relevant aspects of the arguments so developers can use the parsed content in any manner. It does not attempt to autogenerate help screens or apply any other \"blackbox\" functionality. WYSIWYG.\u003cbr/\u003e\u003cbr/\u003e\n**If your tool needs more management/organization features, see the [@author.io/shell](https://github.com/author/shell) micro-framework** _(which is built atop this library)_**.**\n\n\u003e This library is part of the [CLI-First development initiative](https://github.com/coreybutler/clifirst).\n\n## Verbose Example\n\n**Install:** `npm install @author.io/arg`\n\nThe following example automatically parses the `process.argv` variable (i.e. flags passed to a Node script) and strips the first two arguments (the executable name (node) and the script name). It then enforces several rules.\n\n```javascript\n#!/usr/bin/env node --experimental-modules\nimport Args from '@author.io/arg'\n\n// Require specific flags\nArgs.require('a', 'b', 'input')\n\n// Optionally specify flag types\nArgs.types({\n  a: Boolean, // accepts primitives or strings, such as 'boolean'\n\n})\n\n// Optionally specify default values for specific flags\nArgs.defaults({\n  c: 'test'\n})\n\n// Optionally alias flags\nArgs.alias({\n  input: 'in'\n})\n\n// Optionally specify a list of possible flag values (autocreates the flag if it does not already exist, updates options if it does)\nArgs.setOptions('name', 'john', 'jane')\n\n// Allow a flag to accept multiple values (applies when the same flag is defined multiple times).\nArgs.allowMultipleValues('c')\n\n// Do not allow unrecognized flags\nArgs.disallowUnrecognized() \n\n// Enforce all of the rules specified above, by exiting with an error when an invalid configuration is identified.\nArgs.enforceRules()\n\nconsole.log(Args.data)\n```\n\nUsing the script above in a `mycli.js` file could be executed as follows:\n\n```sh\n./mycli.js -a false -b \"some value\" -in testfile.txt -c \"ignored\" -c \"accepted\" -name jane\n```\n\n_Output:_\n```json\n{\n  \"a\": false, \n  \"b\": \"some value\", \n  \"c\": \"accepted\",\n  \"input\": \"testfile.txt\",\n  \"name\": \"jane\"\n}\n```\n\n## Simpler Syntax\n\nFor brevity, there is also a `configure` method which will automatically do all of the things the first script does, but with minimal code.\n\n```javascript\n#!/usr/bin/env node --experimental-modules\nimport Args from '@author.io/arg'\n\nArgs.configure({\n  a: {\n    required: true,\n    type: 'boolean'\n  },\n  b: {\n    required: true\n  },\n  c: {\n    default: 'test',\n    allowMultipleValues: true\n  },\n  input: {\n    alias: 'in'\n  },\n  name: {\n    options: ['john', 'jane']\n  }\n})\n\n// Do not allow unrecognized flags\nArgs.disallowUnrecognized()\n\n// Enforce all of the rules specified above, by exiting with an error when an invalid configuration is identified.\nArgs.enforceRules()\n\nconsole.log(Args.data)\n```\n\nIt is also possible to parse something other than than the `process.argv` variable. An alternative is to provide an array of arguments.\n\n_Notice the change in the `import` and the optional configuration._\n\n```javascript\n#!/usr/bin/env node --experimental-modules\nimport { Parser } from '@author.io/arg'\n\nlet Args = new Parser(myArgs [,cfg])\n\nconsole.log(Args.data)\n```\n\n## API/Usage\n\nThe source code is pretty easy to figure out, but here's an overview:\n\n## Configuring Parser Logic\n\nThere are two ways to configure the parser. A single `configure()` method can describe everything, or individual methods can be used to dynamically define the parsing logic.\n\n### Using `configure()`\n\nThe `configure()` method accepts a shorthand (yet-easily-understood) configuration object.\n\n```javascript\nArgs.configure({\n  flagname: {\n    required: true/false,\n    default: value,\n    type: string_or_primitive, // example: 'boolean' or Boolean\n    alias: string,\n    allowMultipleValues: true/false,\n    options: [...],\n    validate: function(){}/RegExp\n  }, {\n    ...\n  }\n})\n```\n\n_Purpose:_\n\n- `required` - Indicates the flag must be present in the command.\n- `default` - A value to use when the flag is not specified.\n- `type` - The data type. Supports primitives like `Boolean` or their text (typeof) equivalent (i.e. \"`boolean`\").\n- `alias` - A string representing an alternative name for the flag.\n- `aliases` - Support for multiple aliases.\n- `allowMultipleValues` - If a flag is specified more than once, capture all values (instead of only the last one specified).\n- `options` - An array of valid values for the flag.\n- `validate` - This is a function or regular expression that determines whether the value of the flag is valid or not. A function receives the value as the only argument and is expected to return `true` or `false` (where `true` means the value is valid). If a RegExp is provided, the [RegExp.test()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/test) method is executed against the flag value. The validate feature is used **in addition** to other validation mechanisms (options, typing, etc).\n\n### Using Individual Methods\n\nThe following methods can be used to dynamically construct the parsing logic, or modify existing logic.\n\n#### require('flag1', 'flag2', ...)\n\nRequire the presence of specific flags amongst the arguments. Automatically executes `recognize` for all required flags.\n\n#### recognize('flag1', 'flag2', ...)\n\nRegister \"known\" flags. This is useful when you want to prevent unrecognized flags from being passed to the application.\n\n#### types({...})\n\nIdentify the data type of a flag or series of flags. Automatically executes `recognize` for any flags specified amongst the data types.\n\n#### defaults({...})\n\nIdentify default values for flags. \n\nAutomatically executes `recognize` for any flags specified amongst the defaults.\n\n#### alias({...})\n\nIdentify aliases for recognized flags. \n\nAutomatically executes `recognize` for any flags specified amongst the defaults.\n\n#### allowMultipleValues('flag1', 'flag2', ...)\n\nBy default, if the same flag is defined multiple times, only the last value is recognized. Setting `allowMultiple` on a flag will capture all values (as an array).\n\nAutomatically executes `recognize` for any flags specified amongst the defaults.\n\n#### setOptions('flag', 'optionA', 'optionB')\n\nA list/enumeration of values will be enforced _if_ the flag is set. If a flag contains a value not present in the list, a violation will be recognized.\n\nAutomatically executes `recognize` for any flags specified amongst the defaults.\n\n---\n\n## Enforcement Methods\n\nEnforcement methods are designed to help toggle rules on/off as needed.\n\nThere is no special method to enforce a flag value to be within a list of valid options (enumerability), _because this is enforced automatically_.\n\n#### disallowUnrecognized()\n\nSets a rule to prevent the presence of any unrecognized flags.\n\n#### allowUnrecognized()\n\nSets a rule to allow the presence of unrecognized flags (this is the default behavior).\n\n#### ignoreDataTypes()\n\nThis will ignore data type checks, even if the `types` method has been used to enforce data types.\n\n#### enforceDataTypes()\n\nThis will enforce data type checks. This is the default behavior.\n\n---\n\n## Helper Methods\n\nThe following helper methods are made available for developers who need quick access to flags and enforcement functionality.\n\n#### enforceRules()\n\nThis method can be used within a process to validate flags and exit with error when validation fails.\n\n#### value(flagname)\n\nRetrieve the value of a flag. This accepts flags or aliases. If the specified flag does not exist, a value of `undefined` is returned.\n\n#### exists(flagname)\n\nReturns a boolean value indicating the flag exists.\n\n---\n## Defining Metadata\n\nThe following methods are made available to manage metadata about flags.\n\n#### describe(flagname, description)\n\nUse this message to store a description of the flag. This will throw an error if the flag does not exist.\n\n#### description(flagname)\n\nRetrieve the description of a flag. Returns `null` if no description is found.\n\n---\n\n## Parser Properties\n\nThese are readable properties of the parser. For example:\n\n```javascript\nimport Args from '@author.io/arg'\n\nArgs.configure({...})\n\nconsole.log(Args.flags, Args.data, ...)\n```\n\n- `flags`: An array of the unique flag names passed to the application.\n- `data`: A key/value object representing all data passed to the application. If a flag is passed in more than once and duplicates are _not_ suppressed, the value will be an array.\n- `length` The total number of arguments passed to the application.\n- `valid` A boolean representing whether all of the validation rules passed or not.\n- `violations` An array of violations (this is an empty array when everything is valid).\n","funding_links":["https://github.com/sponsors/coreybutler"],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauthor%2Farg","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fauthor%2Farg","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fauthor%2Farg/lists"}