@hsworks/args-lite 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 hsworks
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,90 @@
1
- # Temporary Holding Version
1
+ # @hsworks/args-lite
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ [![npm](https://img.shields.io/npm/v/@hsworks/args-lite.svg)](https://www.npmjs.com/package/@hsworks/args-lite)
4
+ [![CI](https://github.com/harshasuraweera/hsworks/actions/workflows/ci.yml/badge.svg)](https://github.com/harshasuraweera/hsworks/actions/workflows/ci.yml)
5
+ [![license](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
6
+
7
+ Parse an already-split argument list into flags, positionals and a pass-through tail, with identical rules in JavaScript and Python.
8
+
9
+ Zero dependencies. ESM and CommonJS. Fully typed.
10
+
11
+ ## Install
12
+
13
+ ```sh
14
+ npm install @hsworks/args-lite
15
+ ```
16
+
17
+ ## Usage
18
+
19
+ ```ts
20
+ import { parseArgs } from '@hsworks/args-lite';
21
+
22
+ const result = parseArgs(
23
+ ['-v', '--out=a.txt', 'in.txt', '--inc', 'x', '--inc', 'y', '--', '--raw'],
24
+ { boolean: ['verbose'], string: ['out'], array: ['inc'], alias: { v: 'verbose' } },
25
+ );
26
+ // result.flags -> { verbose: true, out: 'a.txt', inc: ['x', 'y'] }
27
+ // result.positionals -> ['in.txt']
28
+ // result.rest -> ['--raw']
29
+
30
+ parseArgs(['--no-color']).flags; // { color: false }
31
+ parseArgs(['--watch', 'build', '--minify'], { stopAtFirstPositional: true }).positionals;
32
+ // ['build', '--minify']
33
+ parseArgs([], { string: ['level'], default: { level: 'info' } }).flags; // { level: 'info' }
34
+ parseArgs(['--zzz'], { strict: true }); // throws ArgsError: unknown option "--zzz"
35
+ ```
36
+
37
+ Pass `process.argv.slice(2)` yourself; the library never reads process state.
38
+
39
+ ## API
40
+
41
+ ### `parseArgs(argv: readonly string[], options?: ArgsOptions): ParsedArgs`
42
+
43
+ Parses an already-split argument list.
44
+
45
+ | Option | Type | Default | Description |
46
+ | --- | --- | --- | --- |
47
+ | `boolean` | `readonly string[]` | `[]` | Canonical names parsed as booleans. |
48
+ | `string` | `readonly string[]` | `[]` | Canonical names that take a string value. |
49
+ | `array` | `readonly string[]` | `[]` | Canonical names that take a value and may repeat. |
50
+ | `alias` | `Record<string, string>` | `{}` | Alias name to canonical name. |
51
+ | `default` | `Record<string, string \| boolean \| readonly string[]>` | `{}` | Values for names not seen. The type must match the declaration. |
52
+ | `strict` | `boolean` | `false` | Throw on undeclared options. |
53
+ | `stopAtFirstPositional` | `boolean` | `false` | Stop option parsing at the first positional. |
54
+
55
+ Returns `{ flags, positionals, rest }`. `flags` is a null-prototype object, so keys such as `constructor` are ordinary entries and nothing writes through to `Object.prototype`.
56
+
57
+ Errors:
58
+
59
+ - `TypeError` if `argv` is not an array of strings, an option list is not an array of strings, `alias` or `default` is not an object, a flag option is not a boolean, or a default has the wrong type.
60
+ - `RangeError` if a declared name, alias or default key is invalid, an alias target is itself an alias, a declared name is also an alias, or a name is declared in two lists.
61
+ - `ArgsError` for an invalid option, an unknown option in strict mode, a missing value or an invalid boolean value.
62
+
63
+ ### `ArgsError`
64
+
65
+ Subclass of `Error` thrown for invalid command-line input.
66
+
67
+ ### Parsing rules
68
+
69
+ - Names are never case-folded or converted: `--dry-run` stays `dry-run`. A long name must match `[A-Za-z0-9][A-Za-z0-9_-]*`, so `--__proto__`, `---x` and `--=x` are invalid.
70
+ - `--` ends option parsing; everything after it goes to `rest` untouched. A lone `-` and arguments such as `-5` or `-1.5` (a dash followed by an ASCII digit) are positionals.
71
+ - Boolean and undeclared ("loose") options take no value: `--verbose` is `true`. `--name=value` sets a loose option to the string, and a boolean option accepts only `true` or `false`.
72
+ - String and array options take the next argument unconditionally, even when it starts with `-`, or the text after `=`. `--out=a=b` splits at the first `=`.
73
+ - `--no-name` stores `name: false` when `name` is not a string or array option and `no-name` is not itself declared. It does not apply with `=value`.
74
+ - Short options are ASCII letters. `-abc` sets `a`, `b` and `c`. A string or array option in a cluster takes the rest of the cluster as its value, with one leading `=` removed (`-ofile`, `-o=file`, `-o file`). Anything else after a short flag, such as a digit, `=` or a non-ASCII letter, is an invalid option.
75
+ - Boolean, loose and string options keep the last value. Array options append in order, and are always present in `flags` (an empty list when absent). `--inc=a,b` is one item.
76
+ - Defaults apply after parsing to canonical names that were not seen. Aliases map an alias name to its canonical name; declared names and default keys must be canonical.
77
+ - With `strict`, an option whose canonical name is not declared throws `unknown option`.
78
+ - With the stop-at-first-positional mode, the first positional and all later arguments, including ones that start with `-`, are positionals, unparsed. A leading `--` still fills `rest`.
79
+ - Error messages are prefixed with the function name (`parseArgs: ` or `parse_args: `).
80
+ - Out of scope: help text, subcommands, numeric coercion, required options, environment fallback, camelCase conversion, `@file` expansion and abbreviations.
81
+
82
+ Differences from Python: `flags` is a null-prototype object, and JS orders integer-like keys first (a flag named `1` is reordered, only in JS). The returned object is a plain object, not a frozen dataclass.
83
+
84
+ ## Python
85
+
86
+ A Python version with the same behaviour is available: `pip install hsworks-args-lite` ([source](https://github.com/harshasuraweera/hsworks/tree/main/packages/py/args-lite)).
87
+
88
+ ## License
89
+
90
+ MIT
package/dist/index.cjs ADDED
@@ -0,0 +1,258 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ ArgsError: () => ArgsError,
24
+ parseArgs: () => parseArgs
25
+ });
26
+ module.exports = __toCommonJS(index_exports);
27
+ var ArgsError = class extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "ArgsError";
31
+ }
32
+ };
33
+ var NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
34
+ function isLetter(ch) {
35
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
36
+ }
37
+ function isDigit(ch) {
38
+ return ch >= "0" && ch <= "9";
39
+ }
40
+ function isStringArray(value) {
41
+ if (!Array.isArray(value)) return false;
42
+ for (let i = 0; i < value.length; i++) {
43
+ if (typeof value[i] !== "string") return false;
44
+ }
45
+ return true;
46
+ }
47
+ function isRecord(value) {
48
+ return typeof value === "object" && value !== null && !Array.isArray(value);
49
+ }
50
+ function checkList(value, label) {
51
+ if (value === void 0) return [];
52
+ if (!isStringArray(value)) {
53
+ throw new TypeError(`parseArgs: options.${label} must be an array of strings`);
54
+ }
55
+ return value;
56
+ }
57
+ function checkFlag(value, label) {
58
+ if (value === void 0) return false;
59
+ if (typeof value !== "boolean") {
60
+ throw new TypeError(`parseArgs: options.${label} must be a boolean`);
61
+ }
62
+ return value;
63
+ }
64
+ function parseArgs(argv, options) {
65
+ if (!isStringArray(argv)) {
66
+ throw new TypeError("parseArgs: argv must be an array of strings");
67
+ }
68
+ if (options !== void 0 && !isRecord(options)) {
69
+ throw new TypeError("parseArgs: options must be an object");
70
+ }
71
+ const opts = options ?? {};
72
+ const lists = [
73
+ ["boolean", checkList(opts.boolean, "boolean")],
74
+ ["string", checkList(opts.string, "string")],
75
+ ["array", checkList(opts.array, "array")]
76
+ ];
77
+ if (opts.alias !== void 0 && !isRecord(opts.alias)) {
78
+ throw new TypeError("parseArgs: options.alias must be an object");
79
+ }
80
+ if (opts.default !== void 0 && !isRecord(opts.default)) {
81
+ throw new TypeError("parseArgs: options.default must be an object");
82
+ }
83
+ const strict = checkFlag(opts.strict, "strict");
84
+ const stopAtFirst = checkFlag(opts.stopAtFirstPositional, "stopAtFirstPositional");
85
+ const aliases = /* @__PURE__ */ new Map();
86
+ const aliasInput = opts.alias ?? {};
87
+ for (const key of Object.keys(aliasInput)) {
88
+ const target = aliasInput[key];
89
+ if (typeof target !== "string") {
90
+ throw new TypeError(`parseArgs: alias "${key}" must map to a string`);
91
+ }
92
+ if (!NAME_RE.test(key) || !NAME_RE.test(target)) {
93
+ throw new RangeError(`parseArgs: invalid alias "${key}" -> "${target}"`);
94
+ }
95
+ aliases.set(key, target);
96
+ }
97
+ for (const [key, target] of aliases) {
98
+ if (aliases.has(target)) {
99
+ throw new RangeError(`parseArgs: alias "${key}" targets "${target}", which is an alias`);
100
+ }
101
+ }
102
+ const kinds = /* @__PURE__ */ new Map();
103
+ for (const [kind, names] of lists) {
104
+ for (const name of names) {
105
+ if (!NAME_RE.test(name)) {
106
+ throw new RangeError(`parseArgs: invalid option name "${name}"`);
107
+ }
108
+ if (aliases.has(name)) {
109
+ throw new RangeError(`parseArgs: "${name}" is declared but is also an alias`);
110
+ }
111
+ const existing = kinds.get(name);
112
+ if (existing !== void 0 && existing !== kind) {
113
+ throw new RangeError(`parseArgs: "${name}" is declared as both ${existing} and ${kind}`);
114
+ }
115
+ kinds.set(name, kind);
116
+ }
117
+ }
118
+ const defaults = [];
119
+ const defaultInput = opts.default ?? {};
120
+ for (const key of Object.keys(defaultInput)) {
121
+ if (!NAME_RE.test(key) || aliases.has(key)) {
122
+ throw new RangeError(`parseArgs: invalid default name "${key}"`);
123
+ }
124
+ const value = defaultInput[key];
125
+ const kind = kinds.get(key);
126
+ let ok;
127
+ if (kind === "boolean") ok = typeof value === "boolean";
128
+ else if (kind === "string") ok = typeof value === "string";
129
+ else if (kind === "array") ok = isStringArray(value);
130
+ else ok = typeof value === "boolean" || typeof value === "string" || isStringArray(value);
131
+ if (!ok) {
132
+ throw new TypeError(`parseArgs: default for "${key}" has the wrong type`);
133
+ }
134
+ defaults.push([key, Array.isArray(value) ? [...value] : value]);
135
+ }
136
+ const flags = /* @__PURE__ */ Object.create(null);
137
+ const seen = /* @__PURE__ */ new Set();
138
+ const positionals = [];
139
+ let rest = [];
140
+ const canon = (name) => aliases.get(name) ?? name;
141
+ const store = (name, kind, value) => {
142
+ seen.add(name);
143
+ if (kind === "array") {
144
+ const current = flags[name];
145
+ if (Array.isArray(current)) current.push(value);
146
+ else flags[name] = [value];
147
+ } else {
148
+ flags[name] = value;
149
+ }
150
+ };
151
+ const n = argv.length;
152
+ let i = 0;
153
+ while (i < n) {
154
+ const arg = argv[i];
155
+ i++;
156
+ if (arg === "--") {
157
+ rest = argv.slice(i);
158
+ break;
159
+ }
160
+ if (arg.startsWith("--")) {
161
+ const eq = arg.indexOf("=", 2);
162
+ const hasEq = eq !== -1;
163
+ const name = hasEq ? arg.slice(2, eq) : arg.slice(2);
164
+ if (!NAME_RE.test(name)) {
165
+ throw new ArgsError(`parseArgs: invalid option "${arg}"`);
166
+ }
167
+ const inline = hasEq ? arg.slice(eq + 1) : "";
168
+ const canonical = canon(name);
169
+ const kind = kinds.get(canonical);
170
+ if (!hasEq && kind === void 0 && name.startsWith("no-")) {
171
+ const base = name.slice(3);
172
+ if (NAME_RE.test(base)) {
173
+ const target = canon(base);
174
+ const targetKind = kinds.get(target);
175
+ if (targetKind !== "string" && targetKind !== "array") {
176
+ if (strict && targetKind === void 0) {
177
+ throw new ArgsError(`parseArgs: unknown option "--${name}"`);
178
+ }
179
+ store(target, targetKind, false);
180
+ continue;
181
+ }
182
+ }
183
+ }
184
+ if (strict && kind === void 0) {
185
+ throw new ArgsError(`parseArgs: unknown option "--${name}"`);
186
+ }
187
+ if (kind === "string" || kind === "array") {
188
+ let value = inline;
189
+ if (!hasEq) {
190
+ if (i >= n) {
191
+ throw new ArgsError(`parseArgs: option "--${name}" requires a value`);
192
+ }
193
+ value = argv[i];
194
+ i++;
195
+ }
196
+ store(canonical, kind, value);
197
+ } else if (!hasEq) {
198
+ store(canonical, kind, true);
199
+ } else if (kind === "boolean") {
200
+ if (inline !== "true" && inline !== "false") {
201
+ throw new ArgsError(
202
+ `parseArgs: invalid value "${inline}" for boolean option "--${name}"`
203
+ );
204
+ }
205
+ store(canonical, kind, inline === "true");
206
+ } else {
207
+ store(canonical, kind, inline);
208
+ }
209
+ } else if (arg.length > 1 && arg[0] === "-" && !isDigit(arg[1])) {
210
+ for (let k = 1; k < arg.length; k++) {
211
+ const ch = arg[k];
212
+ if (!isLetter(ch)) {
213
+ throw new ArgsError(`parseArgs: invalid option "${arg}"`);
214
+ }
215
+ const canonical = canon(ch);
216
+ const kind = kinds.get(canonical);
217
+ if (strict && kind === void 0) {
218
+ throw new ArgsError(`parseArgs: unknown option "-${ch}"`);
219
+ }
220
+ if (kind === "string" || kind === "array") {
221
+ let value = arg.slice(k + 1);
222
+ if (value.length === 0) {
223
+ if (i >= n) {
224
+ throw new ArgsError(`parseArgs: option "-${ch}" requires a value`);
225
+ }
226
+ value = argv[i];
227
+ i++;
228
+ } else if (value[0] === "=") {
229
+ value = value.slice(1);
230
+ }
231
+ store(canonical, kind, value);
232
+ break;
233
+ }
234
+ store(canonical, kind, true);
235
+ }
236
+ } else {
237
+ positionals.push(arg);
238
+ if (stopAtFirst) {
239
+ while (i < n) {
240
+ positionals.push(argv[i]);
241
+ i++;
242
+ }
243
+ }
244
+ }
245
+ }
246
+ for (const [key, value] of defaults) {
247
+ if (!seen.has(key)) flags[key] = value;
248
+ }
249
+ for (const [name, kind] of kinds) {
250
+ if (kind === "array" && flags[name] === void 0) flags[name] = [];
251
+ }
252
+ return { flags, positionals, rest };
253
+ }
254
+ // Annotate the CommonJS export names for ESM import in node:
255
+ 0 && (module.exports = {
256
+ ArgsError,
257
+ parseArgs
258
+ });
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Minimal command-line argument parser with flags and positionals.
3
+ */
4
+ /** Options for {@link parseArgs}. Declared names must be canonical (not aliases). */
5
+ interface ArgsOptions {
6
+ /** Names parsed as booleans. */
7
+ boolean?: readonly string[];
8
+ /** Names that take a string value. */
9
+ string?: readonly string[];
10
+ /** Names that take a string value and may repeat. */
11
+ array?: readonly string[];
12
+ /** Alias name to canonical name. */
13
+ alias?: Readonly<Record<string, string>>;
14
+ /** Values for canonical names not seen on the command line. */
15
+ default?: Readonly<Record<string, string | boolean | readonly string[]>>;
16
+ /** When true, undeclared options throw. Default false. */
17
+ strict?: boolean;
18
+ /** When true, the first positional and everything after it are positionals. Default false. */
19
+ stopAtFirstPositional?: boolean;
20
+ }
21
+ /** Result of {@link parseArgs}. `flags` has a null prototype. */
22
+ interface ParsedArgs {
23
+ flags: Record<string, string | boolean | string[]>;
24
+ positionals: string[];
25
+ rest: string[];
26
+ }
27
+ /** Thrown for invalid command-line input (unknown option, missing or bad value). */
28
+ declare class ArgsError extends Error {
29
+ constructor(message: string);
30
+ }
31
+ /**
32
+ * Parses an already-split argument list into flags, positionals and a pass-through tail.
33
+ *
34
+ * @param argv Arguments, for example `process.argv.slice(2)`.
35
+ * @param options Declarations, aliases, defaults and parsing mode.
36
+ * @returns `flags` (null-prototype object), `positionals` and `rest` (everything after `--`).
37
+ * @throws {TypeError} If `argv` is not an array of strings, or an option has the wrong type.
38
+ * @throws {RangeError} If a declared name, alias or default key is invalid, an alias target is
39
+ * itself an alias, or a name is declared in two lists.
40
+ * @throws {ArgsError} For an invalid or unknown option, a missing value or a bad boolean value.
41
+ */
42
+ declare function parseArgs(argv: readonly string[], options?: ArgsOptions): ParsedArgs;
43
+
44
+ export { ArgsError, type ArgsOptions, type ParsedArgs, parseArgs };
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Minimal command-line argument parser with flags and positionals.
3
+ */
4
+ /** Options for {@link parseArgs}. Declared names must be canonical (not aliases). */
5
+ interface ArgsOptions {
6
+ /** Names parsed as booleans. */
7
+ boolean?: readonly string[];
8
+ /** Names that take a string value. */
9
+ string?: readonly string[];
10
+ /** Names that take a string value and may repeat. */
11
+ array?: readonly string[];
12
+ /** Alias name to canonical name. */
13
+ alias?: Readonly<Record<string, string>>;
14
+ /** Values for canonical names not seen on the command line. */
15
+ default?: Readonly<Record<string, string | boolean | readonly string[]>>;
16
+ /** When true, undeclared options throw. Default false. */
17
+ strict?: boolean;
18
+ /** When true, the first positional and everything after it are positionals. Default false. */
19
+ stopAtFirstPositional?: boolean;
20
+ }
21
+ /** Result of {@link parseArgs}. `flags` has a null prototype. */
22
+ interface ParsedArgs {
23
+ flags: Record<string, string | boolean | string[]>;
24
+ positionals: string[];
25
+ rest: string[];
26
+ }
27
+ /** Thrown for invalid command-line input (unknown option, missing or bad value). */
28
+ declare class ArgsError extends Error {
29
+ constructor(message: string);
30
+ }
31
+ /**
32
+ * Parses an already-split argument list into flags, positionals and a pass-through tail.
33
+ *
34
+ * @param argv Arguments, for example `process.argv.slice(2)`.
35
+ * @param options Declarations, aliases, defaults and parsing mode.
36
+ * @returns `flags` (null-prototype object), `positionals` and `rest` (everything after `--`).
37
+ * @throws {TypeError} If `argv` is not an array of strings, or an option has the wrong type.
38
+ * @throws {RangeError} If a declared name, alias or default key is invalid, an alias target is
39
+ * itself an alias, or a name is declared in two lists.
40
+ * @throws {ArgsError} For an invalid or unknown option, a missing value or a bad boolean value.
41
+ */
42
+ declare function parseArgs(argv: readonly string[], options?: ArgsOptions): ParsedArgs;
43
+
44
+ export { ArgsError, type ArgsOptions, type ParsedArgs, parseArgs };
package/dist/index.js ADDED
@@ -0,0 +1,232 @@
1
+ // src/index.ts
2
+ var ArgsError = class extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "ArgsError";
6
+ }
7
+ };
8
+ var NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_-]*$/;
9
+ function isLetter(ch) {
10
+ return ch >= "a" && ch <= "z" || ch >= "A" && ch <= "Z";
11
+ }
12
+ function isDigit(ch) {
13
+ return ch >= "0" && ch <= "9";
14
+ }
15
+ function isStringArray(value) {
16
+ if (!Array.isArray(value)) return false;
17
+ for (let i = 0; i < value.length; i++) {
18
+ if (typeof value[i] !== "string") return false;
19
+ }
20
+ return true;
21
+ }
22
+ function isRecord(value) {
23
+ return typeof value === "object" && value !== null && !Array.isArray(value);
24
+ }
25
+ function checkList(value, label) {
26
+ if (value === void 0) return [];
27
+ if (!isStringArray(value)) {
28
+ throw new TypeError(`parseArgs: options.${label} must be an array of strings`);
29
+ }
30
+ return value;
31
+ }
32
+ function checkFlag(value, label) {
33
+ if (value === void 0) return false;
34
+ if (typeof value !== "boolean") {
35
+ throw new TypeError(`parseArgs: options.${label} must be a boolean`);
36
+ }
37
+ return value;
38
+ }
39
+ function parseArgs(argv, options) {
40
+ if (!isStringArray(argv)) {
41
+ throw new TypeError("parseArgs: argv must be an array of strings");
42
+ }
43
+ if (options !== void 0 && !isRecord(options)) {
44
+ throw new TypeError("parseArgs: options must be an object");
45
+ }
46
+ const opts = options ?? {};
47
+ const lists = [
48
+ ["boolean", checkList(opts.boolean, "boolean")],
49
+ ["string", checkList(opts.string, "string")],
50
+ ["array", checkList(opts.array, "array")]
51
+ ];
52
+ if (opts.alias !== void 0 && !isRecord(opts.alias)) {
53
+ throw new TypeError("parseArgs: options.alias must be an object");
54
+ }
55
+ if (opts.default !== void 0 && !isRecord(opts.default)) {
56
+ throw new TypeError("parseArgs: options.default must be an object");
57
+ }
58
+ const strict = checkFlag(opts.strict, "strict");
59
+ const stopAtFirst = checkFlag(opts.stopAtFirstPositional, "stopAtFirstPositional");
60
+ const aliases = /* @__PURE__ */ new Map();
61
+ const aliasInput = opts.alias ?? {};
62
+ for (const key of Object.keys(aliasInput)) {
63
+ const target = aliasInput[key];
64
+ if (typeof target !== "string") {
65
+ throw new TypeError(`parseArgs: alias "${key}" must map to a string`);
66
+ }
67
+ if (!NAME_RE.test(key) || !NAME_RE.test(target)) {
68
+ throw new RangeError(`parseArgs: invalid alias "${key}" -> "${target}"`);
69
+ }
70
+ aliases.set(key, target);
71
+ }
72
+ for (const [key, target] of aliases) {
73
+ if (aliases.has(target)) {
74
+ throw new RangeError(`parseArgs: alias "${key}" targets "${target}", which is an alias`);
75
+ }
76
+ }
77
+ const kinds = /* @__PURE__ */ new Map();
78
+ for (const [kind, names] of lists) {
79
+ for (const name of names) {
80
+ if (!NAME_RE.test(name)) {
81
+ throw new RangeError(`parseArgs: invalid option name "${name}"`);
82
+ }
83
+ if (aliases.has(name)) {
84
+ throw new RangeError(`parseArgs: "${name}" is declared but is also an alias`);
85
+ }
86
+ const existing = kinds.get(name);
87
+ if (existing !== void 0 && existing !== kind) {
88
+ throw new RangeError(`parseArgs: "${name}" is declared as both ${existing} and ${kind}`);
89
+ }
90
+ kinds.set(name, kind);
91
+ }
92
+ }
93
+ const defaults = [];
94
+ const defaultInput = opts.default ?? {};
95
+ for (const key of Object.keys(defaultInput)) {
96
+ if (!NAME_RE.test(key) || aliases.has(key)) {
97
+ throw new RangeError(`parseArgs: invalid default name "${key}"`);
98
+ }
99
+ const value = defaultInput[key];
100
+ const kind = kinds.get(key);
101
+ let ok;
102
+ if (kind === "boolean") ok = typeof value === "boolean";
103
+ else if (kind === "string") ok = typeof value === "string";
104
+ else if (kind === "array") ok = isStringArray(value);
105
+ else ok = typeof value === "boolean" || typeof value === "string" || isStringArray(value);
106
+ if (!ok) {
107
+ throw new TypeError(`parseArgs: default for "${key}" has the wrong type`);
108
+ }
109
+ defaults.push([key, Array.isArray(value) ? [...value] : value]);
110
+ }
111
+ const flags = /* @__PURE__ */ Object.create(null);
112
+ const seen = /* @__PURE__ */ new Set();
113
+ const positionals = [];
114
+ let rest = [];
115
+ const canon = (name) => aliases.get(name) ?? name;
116
+ const store = (name, kind, value) => {
117
+ seen.add(name);
118
+ if (kind === "array") {
119
+ const current = flags[name];
120
+ if (Array.isArray(current)) current.push(value);
121
+ else flags[name] = [value];
122
+ } else {
123
+ flags[name] = value;
124
+ }
125
+ };
126
+ const n = argv.length;
127
+ let i = 0;
128
+ while (i < n) {
129
+ const arg = argv[i];
130
+ i++;
131
+ if (arg === "--") {
132
+ rest = argv.slice(i);
133
+ break;
134
+ }
135
+ if (arg.startsWith("--")) {
136
+ const eq = arg.indexOf("=", 2);
137
+ const hasEq = eq !== -1;
138
+ const name = hasEq ? arg.slice(2, eq) : arg.slice(2);
139
+ if (!NAME_RE.test(name)) {
140
+ throw new ArgsError(`parseArgs: invalid option "${arg}"`);
141
+ }
142
+ const inline = hasEq ? arg.slice(eq + 1) : "";
143
+ const canonical = canon(name);
144
+ const kind = kinds.get(canonical);
145
+ if (!hasEq && kind === void 0 && name.startsWith("no-")) {
146
+ const base = name.slice(3);
147
+ if (NAME_RE.test(base)) {
148
+ const target = canon(base);
149
+ const targetKind = kinds.get(target);
150
+ if (targetKind !== "string" && targetKind !== "array") {
151
+ if (strict && targetKind === void 0) {
152
+ throw new ArgsError(`parseArgs: unknown option "--${name}"`);
153
+ }
154
+ store(target, targetKind, false);
155
+ continue;
156
+ }
157
+ }
158
+ }
159
+ if (strict && kind === void 0) {
160
+ throw new ArgsError(`parseArgs: unknown option "--${name}"`);
161
+ }
162
+ if (kind === "string" || kind === "array") {
163
+ let value = inline;
164
+ if (!hasEq) {
165
+ if (i >= n) {
166
+ throw new ArgsError(`parseArgs: option "--${name}" requires a value`);
167
+ }
168
+ value = argv[i];
169
+ i++;
170
+ }
171
+ store(canonical, kind, value);
172
+ } else if (!hasEq) {
173
+ store(canonical, kind, true);
174
+ } else if (kind === "boolean") {
175
+ if (inline !== "true" && inline !== "false") {
176
+ throw new ArgsError(
177
+ `parseArgs: invalid value "${inline}" for boolean option "--${name}"`
178
+ );
179
+ }
180
+ store(canonical, kind, inline === "true");
181
+ } else {
182
+ store(canonical, kind, inline);
183
+ }
184
+ } else if (arg.length > 1 && arg[0] === "-" && !isDigit(arg[1])) {
185
+ for (let k = 1; k < arg.length; k++) {
186
+ const ch = arg[k];
187
+ if (!isLetter(ch)) {
188
+ throw new ArgsError(`parseArgs: invalid option "${arg}"`);
189
+ }
190
+ const canonical = canon(ch);
191
+ const kind = kinds.get(canonical);
192
+ if (strict && kind === void 0) {
193
+ throw new ArgsError(`parseArgs: unknown option "-${ch}"`);
194
+ }
195
+ if (kind === "string" || kind === "array") {
196
+ let value = arg.slice(k + 1);
197
+ if (value.length === 0) {
198
+ if (i >= n) {
199
+ throw new ArgsError(`parseArgs: option "-${ch}" requires a value`);
200
+ }
201
+ value = argv[i];
202
+ i++;
203
+ } else if (value[0] === "=") {
204
+ value = value.slice(1);
205
+ }
206
+ store(canonical, kind, value);
207
+ break;
208
+ }
209
+ store(canonical, kind, true);
210
+ }
211
+ } else {
212
+ positionals.push(arg);
213
+ if (stopAtFirst) {
214
+ while (i < n) {
215
+ positionals.push(argv[i]);
216
+ i++;
217
+ }
218
+ }
219
+ }
220
+ }
221
+ for (const [key, value] of defaults) {
222
+ if (!seen.has(key)) flags[key] = value;
223
+ }
224
+ for (const [name, kind] of kinds) {
225
+ if (kind === "array" && flags[name] === void 0) flags[name] = [];
226
+ }
227
+ return { flags, positionals, rest };
228
+ }
229
+ export {
230
+ ArgsError,
231
+ parseArgs
232
+ };
package/package.json CHANGED
@@ -1,6 +1,45 @@
1
1
  {
2
2
  "name": "@hsworks/args-lite",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Minimal, dependency-free command-line argument parser: flags, positionals and a pass-through tail.",
5
+ "license": "MIT",
6
+ "author": "hsworks",
7
+ "keywords": ["args", "argv", "cli", "command-line", "parser", "flags", "options"],
8
+ "type": "module",
9
+ "sideEffects": false,
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "exports": {
14
+ ".": {
15
+ "import": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "require": {
20
+ "types": "./dist/index.d.cts",
21
+ "default": "./dist/index.cjs"
22
+ }
23
+ }
24
+ },
25
+ "files": ["dist", "README.md", "LICENSE"],
26
+ "scripts": {
27
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
28
+ "typecheck": "tsc --noEmit",
29
+ "test": "vitest run --coverage"
30
+ },
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/harshasuraweera/hsworks.git",
34
+ "directory": "packages/js/args-lite"
35
+ },
36
+ "homepage": "https://hsworks.harshasuraweera.com/#args-lite",
37
+ "bugs": "https://github.com/harshasuraweera/hsworks/issues",
38
+ "publishConfig": {
39
+ "access": "public",
40
+ "provenance": true
41
+ },
42
+ "engines": {
43
+ "node": ">=18"
44
+ }
45
+ }