/
index.js
358 lines (288 loc) Β· 9.9 KB
/
index.js
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
import {dirname} from 'node:path';
import process from 'node:process';
import {fileURLToPath} from 'node:url';
import buildParserOptions from 'minimist-options';
import parseArguments from 'yargs-parser';
import camelCaseKeys from 'camelcase-keys';
import decamelize from 'decamelize';
import decamelizeKeys from 'decamelize-keys';
import trimNewlines from 'trim-newlines';
import redent from 'redent';
import {readPackageUpSync} from 'read-pkg-up';
import hardRejection from 'hard-rejection';
import normalizePackageData from 'normalize-package-data';
const isFlagMissing = (flagName, definedFlags, receivedFlags, input) => {
const flag = definedFlags[flagName];
let isFlagRequired = true;
if (typeof flag.isRequired === 'function') {
isFlagRequired = flag.isRequired(receivedFlags, input);
if (typeof isFlagRequired !== 'boolean') {
throw new TypeError(`Return value for isRequired callback should be of type boolean, but ${typeof isFlagRequired} was returned.`);
}
}
if (typeof receivedFlags[flagName] === 'undefined') {
return isFlagRequired;
}
return flag.isMultiple && receivedFlags[flagName].length === 0 && isFlagRequired;
};
const getMissingRequiredFlags = (flags, receivedFlags, input) => {
const missingRequiredFlags = [];
if (typeof flags === 'undefined') {
return [];
}
for (const flagName of Object.keys(flags)) {
if (flags[flagName].isRequired && isFlagMissing(flagName, flags, receivedFlags, input)) {
missingRequiredFlags.push({key: flagName, ...flags[flagName]});
}
}
return missingRequiredFlags;
};
const decamelizeFlagKey = flagKey => `--${decamelize(flagKey, {separator: '-'})}`;
const reportMissingRequiredFlags = missingRequiredFlags => {
console.error(`Missing required flag${missingRequiredFlags.length > 1 ? 's' : ''}`);
for (const flag of missingRequiredFlags) {
console.error(`\t${decamelizeFlagKey(flag.key)}${flag.shortFlag ? `, -${flag.shortFlag}` : ''}`);
}
};
const joinFlagKeys = (flagKeys, prefix = '--') => `\`${prefix}${flagKeys.join(`\`, \`${prefix}`)}\``;
const validateOptions = options => {
const invalidOptionFilters = {
flags: {
flagsWithDashes: {
filter: ([flagKey]) => flagKey.includes('-') && flagKey !== '--',
message: flagKeys => `Flag keys may not contain '-'. Invalid flags: ${joinFlagKeys(flagKeys, '')}`,
},
flagsWithAlias: {
filter: ([, flag]) => flag.alias !== undefined,
message: flagKeys => `The option \`alias\` has been renamed to \`shortFlag\`. The following flags need to be updated: ${joinFlagKeys(flagKeys)}`,
},
flagsWithNonArrayChoices: {
filter: ([, flag]) => flag.choices !== undefined && !Array.isArray(flag.choices),
message: flagKeys => `The option \`choices\` must be an array. Invalid flags: ${joinFlagKeys(flagKeys)}`,
},
flagsWithChoicesOfDifferentTypes: {
filter: ([, flag]) => flag.type && Array.isArray(flag.choices) && flag.choices.some(choice => typeof choice !== flag.type),
message(flagKeys) {
const flagKeysAndTypes = flagKeys.map(flagKey => `(\`${decamelizeFlagKey(flagKey)}\`, type: '${options.flags[flagKey].type}')`);
return `Each value of the option \`choices\` must be of the same type as its flag. Invalid flags: ${flagKeysAndTypes.join(', ')}`;
},
},
},
};
const errorMessages = [];
for (const [optionKey, filters] of Object.entries(invalidOptionFilters)) {
const optionEntries = Object.entries(options[optionKey]);
for (const {filter, message} of Object.values(filters)) {
const invalidOptions = optionEntries.filter(option => filter(option));
const invalidOptionKeys = invalidOptions.map(([key]) => key);
if (invalidOptions.length > 0) {
errorMessages.push(message(invalidOptionKeys));
}
}
}
if (errorMessages.length > 0) {
throw new Error(errorMessages.join('\n'));
}
};
const validateChoicesByFlag = (flagKey, flagValue, receivedInput) => {
const {choices, isRequired} = flagValue;
if (!choices) {
return;
}
const valueMustBeOneOf = `Value must be one of: [\`${choices.join('`, `')}\`]`;
if (!receivedInput) {
if (isRequired) {
return `Flag \`${decamelizeFlagKey(flagKey)}\` has no value. ${valueMustBeOneOf}`;
}
return;
}
if (Array.isArray(receivedInput)) {
const unknownValues = receivedInput.filter(index => !choices.includes(index));
if (unknownValues.length > 0) {
const valuesText = unknownValues.length > 1 ? 'values' : 'value';
return `Unknown ${valuesText} for flag \`${decamelizeFlagKey(flagKey)}\`: \`${unknownValues.join('`, `')}\`. ${valueMustBeOneOf}`;
}
} else if (!choices.includes(receivedInput)) {
return `Unknown value for flag \`${decamelizeFlagKey(flagKey)}\`: \`${receivedInput}\`. ${valueMustBeOneOf}`;
}
};
const validateChoices = (flags, receivedFlags) => {
const errors = [];
for (const [flagKey, flagValue] of Object.entries(flags)) {
const receivedInput = receivedFlags[flagKey];
const errorMessage = validateChoicesByFlag(flagKey, flagValue, receivedInput);
if (errorMessage) {
errors.push(errorMessage);
}
}
if (errors.length > 0) {
throw new Error(`${errors.join('\n')}`);
}
};
const reportUnknownFlags = unknownFlags => {
console.error([
`Unknown flag${unknownFlags.length > 1 ? 's' : ''}`,
...unknownFlags,
].join('\n'));
};
const buildParserFlags = ({flags, booleanDefault}) => {
const parserFlags = {};
for (const [flagKey, flagValue] of Object.entries(flags)) {
const flag = {...flagValue};
// `buildParserOptions` expects `flag.alias`
if (flag.shortFlag) {
flag.alias = flag.shortFlag;
delete flag.shortFlag;
}
if (
typeof booleanDefault !== 'undefined'
&& flag.type === 'boolean'
&& !Object.prototype.hasOwnProperty.call(flag, 'default')
) {
flag.default = flag.isMultiple ? [booleanDefault] : booleanDefault;
}
if (flag.isMultiple) {
flag.type = flag.type ? `${flag.type}-array` : 'array';
flag.default = flag.default ?? [];
delete flag.isMultiple;
}
if (Array.isArray(flag.aliases)) {
if (flag.alias) {
flag.aliases.push(flag.alias);
}
flag.alias = flag.aliases;
delete flag.aliases;
}
parserFlags[flagKey] = flag;
}
return parserFlags;
};
const validateFlags = (flags, options) => {
for (const [flagKey, flagValue] of Object.entries(options.flags)) {
if (flagKey !== '--' && !flagValue.isMultiple && Array.isArray(flags[flagKey])) {
throw new Error(`The flag --${flagKey} can only be set once.`);
}
}
};
/* eslint complexity: off */
const meow = (helpText, options = {}) => {
if (typeof helpText !== 'string') {
options = helpText;
helpText = '';
}
if (!options.importMeta?.url) {
throw new TypeError('The `importMeta` option is required. Its value must be `import.meta`.');
}
const foundPackage = readPackageUpSync({
cwd: dirname(fileURLToPath(options.importMeta.url)),
normalize: false,
});
options = {
pkg: foundPackage ? foundPackage.packageJson : {},
argv: process.argv.slice(2),
flags: {},
inferType: false,
input: 'string',
help: helpText,
autoHelp: true,
autoVersion: true,
booleanDefault: false,
hardRejection: true,
allowUnknownFlags: true,
...options,
};
if (options.hardRejection) {
hardRejection();
}
validateOptions(options);
let parserOptions = {
arguments: options.input,
...buildParserFlags(options),
};
parserOptions = decamelizeKeys(parserOptions, '-', {exclude: ['stopEarly', '--']});
if (options.inferType) {
delete parserOptions.arguments;
}
// Add --help and --version to known flags if autoHelp or autoVersion are set
if (!options.allowUnknownFlags) {
if (options.autoHelp && !parserOptions.help) {
parserOptions.help = {type: 'boolean'};
}
if (options.autoVersion && !parserOptions.version) {
parserOptions.version = {type: 'boolean'};
}
}
parserOptions = buildParserOptions(parserOptions);
parserOptions.configuration = {
...parserOptions.configuration,
'greedy-arrays': false,
};
if (parserOptions['--']) {
parserOptions.configuration['populate--'] = true;
}
if (!options.allowUnknownFlags) {
// Collect unknown options in `argv._` to be checked later.
parserOptions.configuration['unknown-options-as-args'] = true;
}
const {pkg: package_} = options;
const argv = parseArguments(options.argv, parserOptions);
let help = redent(trimNewlines((options.help ?? '').replace(/\t+\n*$/, '')), 2);
normalizePackageData(package_);
process.title = package_.bin ? Object.keys(package_.bin)[0] : package_.name;
let {description} = options;
if (!description && description !== false) {
({description} = package_);
}
help = (description ? `\n ${description}\n` : '') + (help ? `\n${help}\n` : '\n');
const showHelp = code => {
console.log(help);
process.exit(typeof code === 'number' ? code : 2);
};
const showVersion = () => {
console.log(typeof options.version === 'string' ? options.version : package_.version);
process.exit(0);
};
if (argv._.length === 0 && options.argv.length === 1) {
if (argv.version === true && options.autoVersion) {
showVersion();
} else if (argv.help === true && options.autoHelp) {
showHelp(0);
}
}
const input = argv._;
delete argv._;
if (!options.allowUnknownFlags) {
const unknownFlags = input.filter(item => typeof item === 'string' && item.startsWith('-'));
if (unknownFlags.length > 0) {
reportUnknownFlags(unknownFlags);
process.exit(2);
}
}
const flags = camelCaseKeys(argv, {exclude: ['--', /^\w$/]});
const unnormalizedFlags = {...flags};
validateFlags(flags, options);
validateChoices(options.flags, flags);
for (const flagValue of Object.values(options.flags)) {
if (Array.isArray(flagValue.aliases)) {
for (const alias of flagValue.aliases) {
delete flags[alias];
}
}
delete flags[flagValue.shortFlag];
}
const missingRequiredFlags = getMissingRequiredFlags(options.flags, flags, input);
if (missingRequiredFlags.length > 0) {
reportMissingRequiredFlags(missingRequiredFlags);
process.exit(2);
}
return {
input,
flags,
unnormalizedFlags,
pkg: package_,
help,
showHelp,
showVersion,
};
};
export default meow;