-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparse.ts
More file actions
299 lines (273 loc) · 8.52 KB
/
parse.ts
File metadata and controls
299 lines (273 loc) · 8.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
/**
* @fileoverview Argument parsing utilities for CLI applications.
* Wraps the vendored yargs-parser with a Node.js parseArgs-compatible surface
* for booleans, strings, arrays, aliases, defaults, and coercion.
*/
import process from 'node:process'
import yargsParser from '../external/yargs-parser'
/**
* Yargs parser options interface.
*/
interface YargsOptions {
// Array of option names that should be treated as booleans.
boolean?: string[] | undefined
// Array of option names that should be treated as strings.
string?: string[] | undefined
// Array of option names that should accept multiple values.
array?: string[] | undefined
// Map of short aliases to full option names.
alias?: Record<string, string | string[]> | undefined
// Default values for options.
default?: Record<string, unknown> | undefined
// Transform functions to coerce parsed values.
coerce?: Record<string, (value: unknown) => unknown> | undefined
// Whether to treat unknown options as positional arguments.
'unknown-options-as-args'?: boolean | undefined
// Whether to parse numeric strings as numbers.
'parse-numbers'?: boolean | undefined
// Whether to parse positional arguments as numbers.
'parse-positional-numbers'?: boolean | undefined
// Whether to support --no-<option> negation for booleans.
'boolean-negation'?: boolean | undefined
// Whether to stop parsing options after the first positional.
'halt-at-non-option'?: boolean | undefined
// Advanced yargs-parser configuration options.
configuration?: Record<string, boolean | string> | undefined
// Whether to throw on unknown options.
strict?: boolean | undefined
}
/**
* Yargs parser result interface.
*/
interface YargsArguments extends Record<string, unknown> {
_: string[]
$0?: string
}
/**
* Options for configuring argument parsing, similar to Node.js util.parseArgs.
*/
export interface ParseArgsOptionsConfig {
// Whether the option accepts multiple values (array).
multiple?: boolean | undefined
// Short alias for the option (single character).
short?: string | undefined
// Type of the option value.
type?: 'boolean' | 'string' | undefined
// Default value for the option.
default?: unknown | undefined
// Transform function to coerce parsed values.
coerce?: (value: unknown) => unknown | undefined
}
/**
* Configuration object for parseArgs function, similar to Node.js util.parseArgs.
*/
export interface ParseArgsConfig {
// Command-line arguments to parse (defaults to process.argv.slice(2)).
args?: readonly string[] | undefined
// Options configuration object.
options?: Record<string, ParseArgsOptionsConfig> | undefined
// Whether to throw on unknown options (default: true).
strict?: boolean | undefined
// Whether to populate tokens array (not implemented, for API compatibility).
tokens?: boolean | undefined
// Whether to allow positional arguments after options.
allowPositionals?: boolean | undefined
// Whether to allow negative numbers as option values.
allowNegative?: boolean | undefined
// Advanced yargs-parser configuration passthrough.
configuration?: Record<string, boolean | string> | undefined
}
/**
* Result of parsing command-line arguments.
*/
export interface ParsedArgs<T = Record<string, unknown>> {
// Parsed option values.
values: T
// Positional arguments (non-option arguments).
positionals: string[]
// Raw parsed arguments object from yargs-parser.
raw: YargsArguments
}
/**
* Common parseArgs configuration for Socket registry scripts.
*/
export const commonParseArgsConfig: ParseArgsConfig = {
options: {
force: {
type: 'boolean',
short: 'f',
default: false,
},
quiet: {
type: 'boolean',
short: 'q',
default: false,
},
},
strict: false,
}
/**
* Extract positional arguments from process.argv.
* Useful for commands that accept file paths or other positional parameters.
*
* @example
* ```typescript
* // process.argv = ["node", "script.js", "src", "lib", "--verbose"]
* getPositionalArgs() // ["src", "lib"]
* ```
*/
export function getPositionalArgs(startIndex = 2): string[] {
const args = process.argv.slice(startIndex)
const positionals: string[] = []
let i = 0
while (i < args.length) {
const arg = args[i]!
// Stop at first flag
if (arg.startsWith('-')) {
break
}
positionals.push(arg)
i++
}
return positionals
}
/**
* Check if a specific flag is present in argv.
*
* @example
* ```typescript
* hasFlag('verbose') // true if --verbose is in process.argv
* hasFlag('force', ['--force', '--quiet']) // true
* ```
*/
export function hasFlag(flag: string, argv = process.argv): boolean {
return argv.includes(`--${flag}`)
}
/**
* Parse command-line arguments with a Node.js parseArgs-compatible API.
* Uses yargs-parser internally for robust argument parsing.
*
* @example
* ```typescript
* const { values, positionals } = parseArgs({
* args: ['--force', '--quiet', 'file.ts'],
* options: {
* force: { type: 'boolean' },
* quiet: { type: 'boolean', short: 'q' },
* },
* })
* ```
*/
export function parseArgs<T = Record<string, unknown>>(
config: ParseArgsConfig = {},
): ParsedArgs<T> {
const {
allowNegative = false,
allowPositionals = true,
args = process.argv.slice(2),
configuration,
options = {},
strict = true,
} = config
// Convert parseArgs options to yargs-parser options.
const yargsOptions: YargsOptions = {
// Arrays of option names to treat as specific types.
boolean: [],
string: [],
array: [],
// Maps for aliases, defaults, and transformations.
alias: {},
default: {},
coerce: {},
'unknown-options-as-args': !strict,
'parse-numbers': false,
'parse-positional-numbers': false,
'boolean-negation': !allowNegative,
'halt-at-non-option': !allowPositionals,
configuration: {
// Enable kebab-case to camelCase conversion (e.g., --temp-dir → tempDir).
'camel-case-expansion': true,
// Disable dot notation to avoid confusing nested property parsing.
'dot-notation': false,
// Convert duplicate arguments into arrays automatically.
'duplicate-arguments-array': true,
// Flatten nested arrays from duplicate arguments for cleaner output.
'flatten-duplicate-arrays': true,
// Populate the '--' key with arguments after the -- separator.
'populate--': true,
// Allow short option grouping like -abc for -a -b -c.
'short-option-groups': true,
// Keep aliased keys in the result for flexibility.
'strip-aliased': false,
// Keep both kebab-case and camelCase keys for flexibility.
'strip-dashed': false,
...configuration,
},
}
// Process each option configuration.
for (const { 0: key, 1: optionConfig } of Object.entries(options)) {
const {
coerce,
default: defaultValue,
multiple,
short,
type,
} = optionConfig
// Set the option type.
if (type === 'boolean') {
yargsOptions.boolean?.push(key)
} else if (type === 'string') {
yargsOptions.string?.push(key)
}
// Handle multiple values (arrays).
if (multiple) {
yargsOptions.array?.push(key)
}
// Set short alias.
if (short) {
;(yargsOptions.alias as Record<string, string>)[short] = key
}
// Set default value.
if (defaultValue !== undefined) {
;(yargsOptions.default as Record<string, unknown>)[key] = defaultValue
}
// Set coerce function.
if (coerce) {
;(yargsOptions.coerce as Record<string, unknown>)[key] = coerce
}
}
// Parse the arguments.
const parsed = yargsParser(args as string[], yargsOptions)
// Extract positional arguments.
const positionals = parsed._ || []
// Remove the positionals array from values to match Node.js parseArgs behavior.
const { _, ...values } = parsed
// Ensure positionals are strings.
const stringPositionals = positionals.map(String)
return {
values: values as T,
positionals: stringPositionals,
raw: parsed as YargsArguments,
}
}
/**
* Parse command-line arguments with Socket defaults.
* Provides sensible defaults for Socket CLI applications.
*
* @example
* ```typescript
* const { values, positionals } = parseArgsWithDefaults({
* args: ['--force', 'file.ts'],
* options: { force: { type: 'boolean' } },
* })
* ```
*/
export function parseArgsWithDefaults<T = Record<string, unknown>>(
config: ParseArgsConfig = {},
): ParsedArgs<T> {
return parseArgs<T>({
strict: false,
allowPositionals: true,
...config,
})
}