lexure
npm i lexure
Parser and utilities for non-technical user input.
Documentation (includes reference and cookbook) available here.
Features
- Parses quoted input with multiple quote types.
- Parses flags and options with customizable parsing implementation.
- Keeps trailing whitespace.
- Always parses input by allowing some mis-inputs.
- Includes a convenient wrapper to retrieve arguments.
- Includes abstractions for creating an input loop.
Example
Check out the cookbook for complete examples.
First, import lexure:
// TypeScript or ES Module; // CommonJS;
Consider some user input in the form of a command like so:
;
We first tokenize the input string to individual tokens.
As you can see, lexure supports custom open and close quotes for devices with special keyboards and other locales.
The !hello
part of the input is usually interpreted as a command, which the Lexer class can handle too.
The remaining input is delayed as a function so that you can ignore the rest of the input if it is an invalid command.
.setQuotes; ;if res == null ;>>> ;>>>
Now, we can take the tokens and parse them into a structure.
In lexure, you are free to describe how you want to match unordered arguments like flags.
There are also several built-in strategies for common usecases.
.setUnorderedStrategylexure.longStrategy; ;>>> lexure.joinTokensout.ordered>>> 'world "cool stuff" a b c'
A wrapper class Args is available for us to retrieve the arguments from the output of the parser.
It keeps track of what has already been retrieved and has several helpful methods.
; args.single>>> 'world' args.single>>> 'cool stuff' args.findMapx === 'c' ? lexure.some'it was a C' : lexure.none>>> args.many>>> args.flag'foo'>>> true args.option'bar'>>> 'baz'
Suppose we would like to prompt the user input, and retry until a valid input is given.
lexure has various functions for this, in which the logic of an input loop is abstracted out.
// Suppose we have access to this function that prompts the user.// You can imagine this as a CLI or chat bot. ; result>>>