nopt-lib.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. const abbrev = require('abbrev')
  2. const debug = require('./debug')
  3. const defaultTypeDefs = require('./type-defs')
  4. const hasOwn = (o, k) => Object.prototype.hasOwnProperty.call(o, k)
  5. const getType = (k, { types, dynamicTypes }) => {
  6. let hasType = hasOwn(types, k)
  7. let type = types[k]
  8. if (!hasType && typeof dynamicTypes === 'function') {
  9. const matchedType = dynamicTypes(k)
  10. if (matchedType !== undefined) {
  11. type = matchedType
  12. hasType = true
  13. }
  14. }
  15. return [hasType, type]
  16. }
  17. const isTypeDef = (type, def) => def && type === def
  18. const hasTypeDef = (type, def) => def && type.indexOf(def) !== -1
  19. const doesNotHaveTypeDef = (type, def) => def && !hasTypeDef(type, def)
  20. function nopt (args, {
  21. types,
  22. shorthands,
  23. typeDefs,
  24. invalidHandler, // opt is configured but its value does not validate against given type
  25. unknownHandler, // opt is not configured
  26. abbrevHandler, // opt is being expanded via abbrev
  27. typeDefault,
  28. dynamicTypes,
  29. } = {}) {
  30. debug(types, shorthands, args, typeDefs)
  31. const data = {}
  32. const argv = {
  33. remain: [],
  34. cooked: args,
  35. original: args.slice(0),
  36. }
  37. parse(args, data, argv.remain, {
  38. typeDefs, types, dynamicTypes, shorthands, unknownHandler, abbrevHandler,
  39. })
  40. // now data is full
  41. clean(data, { types, dynamicTypes, typeDefs, invalidHandler, typeDefault })
  42. data.argv = argv
  43. Object.defineProperty(data.argv, 'toString', {
  44. value: function () {
  45. return this.original.map(JSON.stringify).join(' ')
  46. },
  47. enumerable: false,
  48. })
  49. return data
  50. }
  51. function clean (data, {
  52. types = {},
  53. typeDefs = {},
  54. dynamicTypes,
  55. invalidHandler,
  56. typeDefault,
  57. } = {}) {
  58. const StringType = typeDefs.String?.type
  59. const NumberType = typeDefs.Number?.type
  60. const ArrayType = typeDefs.Array?.type
  61. const BooleanType = typeDefs.Boolean?.type
  62. const DateType = typeDefs.Date?.type
  63. const hasTypeDefault = typeof typeDefault !== 'undefined'
  64. if (!hasTypeDefault) {
  65. typeDefault = [false, true, null]
  66. if (StringType) {
  67. typeDefault.push(StringType)
  68. }
  69. if (ArrayType) {
  70. typeDefault.push(ArrayType)
  71. }
  72. }
  73. const remove = {}
  74. Object.keys(data).forEach((k) => {
  75. if (k === 'argv') {
  76. return
  77. }
  78. let val = data[k]
  79. debug('val=%j', val)
  80. const isArray = Array.isArray(val)
  81. let [hasType, rawType] = getType(k, { types, dynamicTypes })
  82. let type = rawType
  83. if (!isArray) {
  84. val = [val]
  85. }
  86. if (!type) {
  87. type = typeDefault
  88. }
  89. if (isTypeDef(type, ArrayType)) {
  90. type = typeDefault.concat(ArrayType)
  91. }
  92. if (!Array.isArray(type)) {
  93. type = [type]
  94. }
  95. debug('val=%j', val)
  96. debug('types=', type)
  97. val = val.map((v) => {
  98. // if it's an unknown value, then parse false/true/null/numbers/dates
  99. if (typeof v === 'string') {
  100. debug('string %j', v)
  101. v = v.trim()
  102. if ((v === 'null' && ~type.indexOf(null))
  103. || (v === 'true' &&
  104. (~type.indexOf(true) || hasTypeDef(type, BooleanType)))
  105. || (v === 'false' &&
  106. (~type.indexOf(false) || hasTypeDef(type, BooleanType)))) {
  107. v = JSON.parse(v)
  108. debug('jsonable %j', v)
  109. } else if (hasTypeDef(type, NumberType) && !isNaN(v)) {
  110. debug('convert to number', v)
  111. v = +v
  112. } else if (hasTypeDef(type, DateType) && !isNaN(Date.parse(v))) {
  113. debug('convert to date', v)
  114. v = new Date(v)
  115. }
  116. }
  117. if (!hasType) {
  118. if (!hasTypeDefault) {
  119. return v
  120. }
  121. // if the default type has been passed in then we want to validate the
  122. // unknown data key instead of bailing out earlier. we also set the raw
  123. // type which is passed to the invalid handler so that it can be
  124. // determined if during validation if it is unknown vs invalid
  125. rawType = typeDefault
  126. }
  127. // allow `--no-blah` to set 'blah' to null if null is allowed
  128. if (v === false && ~type.indexOf(null) &&
  129. !(~type.indexOf(false) || hasTypeDef(type, BooleanType))) {
  130. v = null
  131. }
  132. const d = {}
  133. d[k] = v
  134. debug('prevalidated val', d, v, rawType)
  135. if (!validate(d, k, v, rawType, { typeDefs })) {
  136. if (invalidHandler) {
  137. invalidHandler(k, v, rawType, data)
  138. } else if (invalidHandler !== false) {
  139. debug('invalid: ' + k + '=' + v, rawType)
  140. }
  141. return remove
  142. }
  143. debug('validated v', d, v, rawType)
  144. return d[k]
  145. }).filter((v) => v !== remove)
  146. // if we allow Array specifically, then an empty array is how we
  147. // express 'no value here', not null. Allow it.
  148. if (!val.length && doesNotHaveTypeDef(type, ArrayType)) {
  149. debug('VAL HAS NO LENGTH, DELETE IT', val, k, type.indexOf(ArrayType))
  150. delete data[k]
  151. } else if (isArray) {
  152. debug(isArray, data[k], val)
  153. data[k] = val
  154. } else {
  155. data[k] = val[0]
  156. }
  157. debug('k=%s val=%j', k, val, data[k])
  158. })
  159. }
  160. function validate (data, k, val, type, { typeDefs } = {}) {
  161. const ArrayType = typeDefs?.Array?.type
  162. // arrays are lists of types.
  163. if (Array.isArray(type)) {
  164. for (let i = 0, l = type.length; i < l; i++) {
  165. if (isTypeDef(type[i], ArrayType)) {
  166. continue
  167. }
  168. if (validate(data, k, val, type[i], { typeDefs })) {
  169. return true
  170. }
  171. }
  172. delete data[k]
  173. return false
  174. }
  175. // an array of anything?
  176. if (isTypeDef(type, ArrayType)) {
  177. return true
  178. }
  179. // Original comment:
  180. // NaN is poisonous. Means that something is not allowed.
  181. // New comment: Changing this to an isNaN check breaks a lot of tests.
  182. // Something is being assumed here that is not actually what happens in
  183. // practice. Fixing it is outside the scope of getting linting to pass in
  184. // this repo. Leaving as-is for now.
  185. /* eslint-disable-next-line no-self-compare */
  186. if (type !== type) {
  187. debug('Poison NaN', k, val, type)
  188. delete data[k]
  189. return false
  190. }
  191. // explicit list of values
  192. if (val === type) {
  193. debug('Explicitly allowed %j', val)
  194. data[k] = val
  195. return true
  196. }
  197. // now go through the list of typeDefs, validate against each one.
  198. let ok = false
  199. const types = Object.keys(typeDefs)
  200. for (let i = 0, l = types.length; i < l; i++) {
  201. debug('test type %j %j %j', k, val, types[i])
  202. const t = typeDefs[types[i]]
  203. if (t && (
  204. (type && type.name && t.type && t.type.name) ?
  205. (type.name === t.type.name) :
  206. (type === t.type)
  207. )) {
  208. const d = {}
  209. ok = t.validate(d, k, val) !== false
  210. val = d[k]
  211. if (ok) {
  212. data[k] = val
  213. break
  214. }
  215. }
  216. }
  217. debug('OK? %j (%j %j %j)', ok, k, val, types[types.length - 1])
  218. if (!ok) {
  219. delete data[k]
  220. }
  221. return ok
  222. }
  223. function parse (args, data, remain, {
  224. types = {},
  225. typeDefs = {},
  226. shorthands = {},
  227. dynamicTypes,
  228. unknownHandler,
  229. abbrevHandler,
  230. } = {}) {
  231. const StringType = typeDefs.String?.type
  232. const NumberType = typeDefs.Number?.type
  233. const ArrayType = typeDefs.Array?.type
  234. const BooleanType = typeDefs.Boolean?.type
  235. debug('parse', args, data, remain)
  236. const abbrevs = abbrev(Object.keys(types))
  237. debug('abbrevs=%j', abbrevs)
  238. const shortAbbr = abbrev(Object.keys(shorthands))
  239. for (let i = 0; i < args.length; i++) {
  240. let arg = args[i]
  241. debug('arg', arg)
  242. if (arg.match(/^-{2,}$/)) {
  243. // done with keys.
  244. // the rest are args.
  245. remain.push.apply(remain, args.slice(i + 1))
  246. args[i] = '--'
  247. break
  248. }
  249. let hadEq = false
  250. if (arg.charAt(0) === '-' && arg.length > 1) {
  251. const at = arg.indexOf('=')
  252. if (at > -1) {
  253. hadEq = true
  254. const v = arg.slice(at + 1)
  255. arg = arg.slice(0, at)
  256. args.splice(i, 1, arg, v)
  257. }
  258. // see if it's a shorthand
  259. // if so, splice and back up to re-parse it.
  260. const shRes = resolveShort(arg, shortAbbr, abbrevs, { shorthands, abbrevHandler })
  261. debug('arg=%j shRes=%j', arg, shRes)
  262. if (shRes) {
  263. args.splice.apply(args, [i, 1].concat(shRes))
  264. if (arg !== shRes[0]) {
  265. i--
  266. continue
  267. }
  268. }
  269. arg = arg.replace(/^-+/, '')
  270. let no = null
  271. while (arg.toLowerCase().indexOf('no-') === 0) {
  272. no = !no
  273. arg = arg.slice(3)
  274. }
  275. // abbrev includes the original full string in its abbrev list
  276. if (abbrevs[arg] && abbrevs[arg] !== arg) {
  277. if (abbrevHandler) {
  278. abbrevHandler(arg, abbrevs[arg])
  279. } else if (abbrevHandler !== false) {
  280. debug(`abbrev: ${arg} -> ${abbrevs[arg]}`)
  281. }
  282. arg = abbrevs[arg]
  283. }
  284. let [hasType, argType] = getType(arg, { types, dynamicTypes })
  285. let isTypeArray = Array.isArray(argType)
  286. if (isTypeArray && argType.length === 1) {
  287. isTypeArray = false
  288. argType = argType[0]
  289. }
  290. let isArray = isTypeDef(argType, ArrayType) ||
  291. isTypeArray && hasTypeDef(argType, ArrayType)
  292. // allow unknown things to be arrays if specified multiple times.
  293. if (!hasType && hasOwn(data, arg)) {
  294. if (!Array.isArray(data[arg])) {
  295. data[arg] = [data[arg]]
  296. }
  297. isArray = true
  298. }
  299. let val
  300. let la = args[i + 1]
  301. const isBool = typeof no === 'boolean' ||
  302. isTypeDef(argType, BooleanType) ||
  303. isTypeArray && hasTypeDef(argType, BooleanType) ||
  304. (typeof argType === 'undefined' && !hadEq) ||
  305. (la === 'false' &&
  306. (argType === null ||
  307. isTypeArray && ~argType.indexOf(null)))
  308. if (typeof argType === 'undefined') {
  309. // la is going to unexpectedly be parsed outside the context of this arg
  310. const hangingLa = !hadEq && la && !la?.startsWith('-') && !['true', 'false'].includes(la)
  311. if (unknownHandler) {
  312. if (hangingLa) {
  313. unknownHandler(arg, la)
  314. } else {
  315. unknownHandler(arg)
  316. }
  317. } else if (unknownHandler !== false) {
  318. debug(`unknown: ${arg}`)
  319. if (hangingLa) {
  320. debug(`unknown: ${la} parsed as normal opt`)
  321. }
  322. }
  323. }
  324. if (isBool) {
  325. // just set and move along
  326. val = !no
  327. // however, also support --bool true or --bool false
  328. if (la === 'true' || la === 'false') {
  329. val = JSON.parse(la)
  330. la = null
  331. if (no) {
  332. val = !val
  333. }
  334. i++
  335. }
  336. // also support "foo":[Boolean, "bar"] and "--foo bar"
  337. if (isTypeArray && la) {
  338. if (~argType.indexOf(la)) {
  339. // an explicit type
  340. val = la
  341. i++
  342. } else if (la === 'null' && ~argType.indexOf(null)) {
  343. // null allowed
  344. val = null
  345. i++
  346. } else if (!la.match(/^-{2,}[^-]/) &&
  347. !isNaN(la) &&
  348. hasTypeDef(argType, NumberType)) {
  349. // number
  350. val = +la
  351. i++
  352. } else if (!la.match(/^-[^-]/) && hasTypeDef(argType, StringType)) {
  353. // string
  354. val = la
  355. i++
  356. }
  357. }
  358. if (isArray) {
  359. (data[arg] = data[arg] || []).push(val)
  360. } else {
  361. data[arg] = val
  362. }
  363. continue
  364. }
  365. if (isTypeDef(argType, StringType)) {
  366. if (la === undefined) {
  367. la = ''
  368. } else if (la.match(/^-{1,2}[^-]+/)) {
  369. la = ''
  370. i--
  371. }
  372. }
  373. if (la && la.match(/^-{2,}$/)) {
  374. la = undefined
  375. i--
  376. }
  377. val = la === undefined ? true : la
  378. if (isArray) {
  379. (data[arg] = data[arg] || []).push(val)
  380. } else {
  381. data[arg] = val
  382. }
  383. i++
  384. continue
  385. }
  386. remain.push(arg)
  387. }
  388. }
  389. const SINGLES = Symbol('singles')
  390. const singleCharacters = (arg, shorthands) => {
  391. let singles = shorthands[SINGLES]
  392. if (!singles) {
  393. singles = Object.keys(shorthands).filter((s) => s.length === 1).reduce((l, r) => {
  394. l[r] = true
  395. return l
  396. }, {})
  397. shorthands[SINGLES] = singles
  398. debug('shorthand singles', singles)
  399. }
  400. const chrs = arg.split('').filter((c) => singles[c])
  401. return chrs.join('') === arg ? chrs : null
  402. }
  403. function resolveShort (arg, ...rest) {
  404. const { abbrevHandler, types = {}, shorthands = {} } = rest.length ? rest.pop() : {}
  405. const shortAbbr = rest[0] ?? abbrev(Object.keys(shorthands))
  406. const abbrevs = rest[1] ?? abbrev(Object.keys(types))
  407. // handle single-char shorthands glommed together, like
  408. // npm ls -glp, but only if there is one dash, and only if
  409. // all of the chars are single-char shorthands, and it's
  410. // not a match to some other abbrev.
  411. arg = arg.replace(/^-+/, '')
  412. // if it's an exact known option, then don't go any further
  413. if (abbrevs[arg] === arg) {
  414. return null
  415. }
  416. // if it's an exact known shortopt, same deal
  417. if (shorthands[arg]) {
  418. // make it an array, if it's a list of words
  419. if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
  420. shorthands[arg] = shorthands[arg].split(/\s+/)
  421. }
  422. return shorthands[arg]
  423. }
  424. // first check to see if this arg is a set of single-char shorthands
  425. const chrs = singleCharacters(arg, shorthands)
  426. if (chrs) {
  427. return chrs.map((c) => shorthands[c]).reduce((l, r) => l.concat(r), [])
  428. }
  429. // if it's an arg abbrev, and not a literal shorthand, then prefer the arg
  430. if (abbrevs[arg] && !shorthands[arg]) {
  431. return null
  432. }
  433. // if it's an abbr for a shorthand, then use that
  434. // exact match has already happened so we don't need to account for that here
  435. if (shortAbbr[arg]) {
  436. if (abbrevHandler) {
  437. abbrevHandler(arg, shortAbbr[arg])
  438. } else if (abbrevHandler !== false) {
  439. debug(`abbrev: ${arg} -> ${shortAbbr[arg]}`)
  440. }
  441. arg = shortAbbr[arg]
  442. }
  443. // make it an array, if it's a list of words
  444. if (shorthands[arg] && !Array.isArray(shorthands[arg])) {
  445. shorthands[arg] = shorthands[arg].split(/\s+/)
  446. }
  447. return shorthands[arg]
  448. }
  449. module.exports = {
  450. nopt,
  451. clean,
  452. parse,
  453. validate,
  454. resolveShort,
  455. typeDefs: defaultTypeDefs,
  456. }