1 | 'use strict'
|
2 |
|
3 | const { InvalidArgumentError } = require('commander')
|
4 |
|
5 | function integer (value) {
|
6 | const result = parseInt(value, 10)
|
7 | if (isNaN(result)) {
|
8 | throw new InvalidArgumentError('Invalid integer')
|
9 | }
|
10 | if (result < 0) {
|
11 | throw new InvalidArgumentError('Only >= 0')
|
12 | }
|
13 | return result
|
14 | }
|
15 |
|
16 | module.exports = {
|
17 | any (value) {
|
18 | return value
|
19 | },
|
20 |
|
21 | boolean (value, defaultValue) {
|
22 | if (value === undefined) {
|
23 | return !defaultValue
|
24 | }
|
25 | if (['true', 'yes', 'on'].includes(value)) {
|
26 | return true
|
27 | }
|
28 | if (['false', 'no', 'off'].includes(value)) {
|
29 | return false
|
30 | }
|
31 | throw new InvalidArgumentError('Invalid boolean')
|
32 | },
|
33 |
|
34 | regex (value) {
|
35 | try {
|
36 | return new RegExp(value)
|
37 | } catch (e) {
|
38 | throw new InvalidArgumentError('Invalid regex')
|
39 | }
|
40 | },
|
41 |
|
42 | integer,
|
43 |
|
44 | string (value) {
|
45 | return value
|
46 | },
|
47 |
|
48 | timeout (value) {
|
49 | const int = integer(value)
|
50 | if (value.endsWith('ms')) {
|
51 | return int
|
52 | }
|
53 | const specifier = value.substring(int.toString().length)
|
54 | if (['s', 'sec'].includes(specifier)) {
|
55 | return int * 1000
|
56 | }
|
57 | if (['m', 'min'].includes(specifier)) {
|
58 | return int * 60 * 1000
|
59 | }
|
60 | if (specifier) {
|
61 | throw new InvalidArgumentError('Invalid timeout')
|
62 | }
|
63 | return int
|
64 | },
|
65 |
|
66 | url (value) {
|
67 | if (!value.match(/^https?:\/\/[^ "]+$/)) {
|
68 | throw new InvalidArgumentError('Invalid URL')
|
69 | }
|
70 | return value
|
71 | },
|
72 |
|
73 | arrayOf (typeValidator) {
|
74 | return function (value, previousValue) {
|
75 | let result
|
76 | if (previousValue === undefined) {
|
77 | result = []
|
78 | } else {
|
79 | result = [...previousValue]
|
80 | }
|
81 | result.push(typeValidator(value))
|
82 | return result
|
83 | }
|
84 | },
|
85 |
|
86 | percent (value) {
|
87 | const int = integer(value)
|
88 | if (int > 100) {
|
89 | throw new InvalidArgumentError('Invalid percent')
|
90 | }
|
91 | return int
|
92 | }
|
93 | }
|