Skip to content

Latest commit

 

History

History

reference

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 

lexure

lexure

Index

Enumerations

Classes

Interfaces

Type aliases

Functions

Type aliases

MatchPrefix

  • MatchPrefix: function

A function to match a prefix.

param A string that may start with the prefix.

returns The length of the prefix if there is one.

Type declaration:

  • (s: string): number | null

Parameters:

Name Type
s string

Option

A type that can express the lack of a value. Used in this library for when a generic type could be nullable.


Result

A type used to express computations that can fail.


LoopAction

A type used to express actions in the loop. Each action can have a value with it.


Pairing

  • Pairing: Record<string, string[]>

Pairing of flag/option names to the words usable for them.

Functions

joinTokens

  • joinTokens(tokens: Token[], separator: string | null, raw: boolean): string

Joins tokens together. By default, this keeps as much of the original input as possible.

// Note three trailing spaces.
const tokens = new Lexer('hello   "world"')
  .setQuotes([['"', '"']])
  .lex();

console.log(joinTokens(tokens));
>>> 'hello   "world"'

console.log(joinTokens(tokens, ' ', false));
>>> 'hello world'

Parameters:

Name Type Default Description
tokens Token[] - Tokens to join.
separator string | null null The separator, if null, will use original trailing whitespace; defaults to null.
raw boolean true Whether to use raw values e.g. with quotes; defaults to true.

Returns: string

The joined string.


extractCommand

Extracts a command from the first one or two tokens from a list of tokens. The command format is ' ', and the space is optional.

Parameters:

Name Type Default Description
matchPrefix MatchPrefix - A function that gives the length of the prefix if there is one.
tokens Token[] - Tokens to check.
mutate boolean true Whether to mutate the list of tokens.

Returns: Token | null

The token containing the name of the command. This may be a token from the list or a new token.


emptyOutput

Creates an empty parser output.

Returns: ParserOutput

An empty output.


mergeOutputs

Merges multiple outputs into one. Flags and options that appear later will be preferred if there are duplicates.

Parameters:

Name Type Description
...ps ParserOutput[] The outputs to merge.

Returns: ParserOutput

The merged output.


outputToJSON

Converts an output to JSON, where the flags and options are turned into arrays of entries. You can recover the output with 'outputFromJSON'.

Parameters:

Name Type Description
p ParserOutput The output.

Returns: Record<string, unknown>

The JSON.


outputFromJSON

  • outputFromJSON(obj: Record<string, unknown>): ParserOutput

Converts JSON to a parser output.

Parameters:

Name Type Description
obj Record<string, unknown> A valid JSON input, following the schema from 'outputToJSON'.

Returns: ParserOutput

The output.


some

  • some<T>(x: T): Some<T>

Creates a Some.

Type parameters:

  • T

Type of results.

Parameters:

Name Type Description
x T Value to use.

Returns: Some<T>

An Option.


none

Creates a None.

Returns: None

An Option.


maybeOption

  • maybeOption<T>(x: T | null | undefined): Option<T>

Creates an Option from a value that could be null or undefined.

console.log(maybeOption(1));
>>> { exists: true, value: 1 }

console.log(maybeOption(null));
>>> { exists: false }

console.log(maybeOption(undefined));
>>> { exists: false }

Type parameters:

  • T

Parameters:

Name Type Description
x T | null | undefined A nullable value.

Returns: Option<T>

An Option.


orOption

Gets the first Some from many Options.

Type parameters:

  • T

Parameters:

Name Type Description
...xs Option<T>[] The Options.

Returns: Option<T>

The first Some, or None if there were no Some.


ok

  • ok<T>(x: T): Ok<T>

Creates an Ok.

Type parameters:

  • T

Type of results.

Parameters:

Name Type Description
x T Value to use.

Returns: Ok<T>

A Result.


err

  • err<E>(x: E): Err<E>

Creates an Err.

Type parameters:

  • E

Type of errors.

Parameters:

Name Type Description
x E Value to use.

Returns: Err<E>

A Result.


err_

  • err_(): Err<null>

Creates an Err with null value.

Returns: Err<null>

A Result.


maybeResult

  • maybeResult<T, E>(x: T | null | undefined, e: E): Result<T, E>

Creates a Result from a value that could be null or undefined.

console.log(maybeResult(1, 'bad'));
>>> { success: true, value: 1 }

console.log(maybeResult(null, 'bad'));
>>> { success: false, error: 'bad' }

console.log(maybeResult(undefined, 'bad'));
>>> { success: false, error: 'bad' }

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x T | null | undefined A nullable value.
e E The error to use.

Returns: Result<T, E>

A Result.


orResultAll

Gets the first Ok from many Results.

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Result<T, E> The first Result.
...xs Result<T, E>[] The remaining Results; this encoding is to ensure there is at least one Result.

Returns: Result<T, E[]>

The first Ok, or all the Errs if there were no Ok.


orResultFirst

Gets the first Ok from many Results.

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Result<T, E> The first Result.
...xs Result<T, E>[] The remaining Results; this encoding is to ensure there is at least one Result.

Returns: Result<T, E>

The first Ok, or the first Err if there were no Ok.


orResultLast

Gets the first Ok from many Results.

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Result<T, E> The first Result.
...xs Result<T, E>[] The remaining Results; this encoding is to ensure there is at least one Result.

Returns: Result<T, E>

The first Ok, or the last Err if there were no Ok.


step

  • step<A>(x: A): Step<A>

Creates a Step.

Type parameters:

  • A

Type of step results.

Parameters:

Name Type Description
x A Value to use.

Returns: Step<A>

A LoopAction.


step_

  • step_(): Step<null>

Creates a Step with null value.

Returns: Step<null>

A LoopAction.


finish

Creates a Finish.

Type parameters:

  • B

Type of finish results.

Parameters:

Name Type Description
x B Value to use.

Returns: Finish<B>

A LoopAction.


fail

  • fail<E>(x: E): Fail<E>

Creates a Fail.

Type parameters:

  • E

Type of errors.

Parameters:

Name Type Description
x E Value to use.

Returns: Fail<E>

A LoopAction.


fail_

  • fail_(): Fail<null>

Creates a Fail with null value.

Returns: Fail<null>

A LoopAction.


loop

Runs a loop which continuously gets input and attempts to parse it. The loop strategy used will determine how the loop continues and ends.

const getInputFromSomewhere = () => '2';

const x = loop('1', {
  getInput() {
    const i = getInputFromSomewhere();
    return i == null ? fail('no input') : step(i);
  },

  parse(x: string) {
    const n = Number(x);
    return isNaN(n) ? fail('bad input') : finish(n);
  }
});

console.log(x);
>>> 1

Type parameters:

  • A

Input type.

  • Z

Output type.

  • E

Error type.

Parameters:

Name Type Description
intialInput A The first input to parse.
strat LoopStrategy<A, Z, E> The loop strategy to use.

Returns: Result<Z, E>

Either the parsed value or an error.


loop1

Runs a loop which continuously gets input and attempts to parse it. The loop strategy used will determine how the loop continues and ends. This variant has no initial input.

const getInputFromSomewhere = () => '2';

const x = loop1({
  getInput() {
    const i = getInputFromSomewhere();
    return i == null ? fail('no input') : step(i);
  },

  parse(x: string) {
    const n = Number(x);
    return isNaN(n) ? fail('bad input') : finish(n);
  }
});

console.log(x);
>>> 2

Type parameters:

  • A

Input type.

  • Z

Output type.

  • E

Error type.

Parameters:

Name Type Description
strat LoopStrategy<A, Z, E> The loop strategy to use.

Returns: Result<Z, E>

Either the parsed value or an error.


loopAsync

Runs a loop which continuously gets input and attempts to parse it. The loop strategy used will determine how the loop continues and ends. This variant of the function is asynchronous using Promise.

Type parameters:

  • A

Input type.

  • Z

Output type.

  • E

Error type.

Parameters:

Name Type Description
intialInput A The first input to parse.
strat LoopStrategyAsync<A, Z, E> The loop strategy to use.

Returns: Promise<Result<Z, E>>

Either the parsed value or an error.


loop1Async

Runs a loop which continuously gets input and attempts to parse it. The loop strategy used will determine how the loop continues and ends. This variant has no initial input. This variant of the function is asynchronous using Promise.

Type parameters:

  • A

Input type.

  • Z

Output type.

  • E

Error type.

Parameters:

Name Type Description
strat LoopStrategyAsync<A, Z, E> The loop strategy to use.

Returns: Promise<Result<Z, E>>

Either the parsed value or an error.


noStrategy

Do not match any unordered argument at all.

Returns: UnorderedStrategy

The strategy.


longStrategy

Match unordered arguments according to conventional syntax. '--flag' is a flag. '--opt=' is an option. '--opt=123' is a compact option.

Returns: UnorderedStrategy

The strategy.


longShortStrategy

Match unordered arguments according to conventional syntax. '--flag' or '-flag' is a flag. '--opt=' or '-opt=' is an option. '--opt=123' or '-opt=123' is a compact option.

Returns: UnorderedStrategy

The strategy.


prefixedStrategy

Match unordered arguments with custom prefix and separator. The prefix is the part the preceeds the key name, e.g. '--' in '--foo'. The separator is the part that delimits the key and value e.g. '=' in '--key=value'. It is expected that there are no spaces in the prefixes and separators. The matching is done in a case-sensitive manner. Also note that if the input contains multiple of the separators, the matching may be ambiguous.

const st = prefixedStrategy(['--'], ['=']);
console.log(st.matchFlag('--f'));
>>> 'f'

console.log(st.matchOption('--opt='));
>>> 'opt'

console.log(st.matchCompactOption('--opt=15'));
>>> ['opt', '15']

Parameters:

Name Type Description
prefixes string[] The prefixes to use for unordered arguments. They should be ordered by length in non-increasing order.
separators string[] The symbols to use to separate the key and value in options. They should be ordered by length in non-increasing order.

Returns: UnorderedStrategy

The strategy.


matchingStrategy

Match unordered arguments according to a record of the names to the list of words. Prefixes like '--' and separators like '=' should be a part of the word. This function uses https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator which can compare in different locales and different sensitivities. Note that this only works for en-US if you are below Node 13.0.0.

const st = matchingStrategy({ flag: ['--flag', '-f'] }, {});
console.log(st.matchFlag('--flag'));
>>> 'flag'

console.log(st.matchOption('-f'));
>>> 'flag'

const stbase = matchingStrategy({ flag: ['--flag'] }, {}, 'en-US', { sensitivity: 'base' });
console.log(stbase.matchFlag('--FLAG'));
>>> 'flag'

console.log(stbase.matchFlag('--flág'));
>>> 'flag'

Parameters:

Name Type Description
flags Pairing Words usable as flags.
options Pairing Words usable as options. They should be ordered by length in non-increasing order.
locales? string | string[] | undefined Locale(s) to use.
collatorOptions? Intl.CollatorOptions Options for comparing strings. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator for more information.

Returns: UnorderedStrategy

The strategy.


mapKeys

Creates a new strategy that maps the names of flags and options in an unordered strategy.

const st1 = longStrategy();

console.log(st1.matchFlag('--foo'), st1.matchFlag('--FOO'));
>>> 'foo' 'FOO'

const st2 = mapKeys(longStrategy(), k => k.toLowerCase());

console.log(st2.matchFlag('--foo'), st1.matchFlag('--FOO'));
>>> 'foo' 'foo'

Parameters:

A strategy.

  • f: function

Creates a new name from the old name, or return null to not include it.

  • (s: string): string | null

Parameters:

Name Type
s string

Returns: UnorderedStrategy

A new strategy.


renameKeys

Creates a new strategy that renames the names of flags and options of another strategy. This is done according to a record of the names to a list of words. This function uses https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator which can compare in different locales and different sensitivities. Note that this only works for en-US if you are below Node 13.0.0.

const st = renameKeys(longStrategy(), { foo: ['bar'] });

console.log(st.matchFlag('--bar'));
>>> 'foo'

Parameters:

Name Type Default Description
strat UnorderedStrategy - A strategy.
keys Pairing - The pairing of keys.
keepNotFound boolean true Whether to keep keys that are not found in keys; defaults to true.
locales? string | string[] | undefined - Locale(s) to use.
collatorOptions? Intl.CollatorOptions - Options for comparing strings. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Collator/Collator for more information.

Returns: UnorderedStrategy

A new strategy.


someToOk

Converts an Option to a Result.

  • Some -> Ok
  • None -> Err

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Option<T> The Option.
error E The error if None.

Returns: Result<T, E>

A Result.


okToSome

Converts a Result to an Option.

  • Ok -> Some
  • Err -> None

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Result<T, E> The Result.

Returns: Option<T>

An Option.


errToSome

Converts a Result to an Option.

  • Ok -> None
  • Err -> Some

Type parameters:

  • T

  • E

Parameters:

Name Type Description
x Result<T, E> The Result.

Returns: Option<E>

An Option.


someToStep

Converts an Option to a LoopAction.

  • Some -> Step
  • None -> Fail

Type parameters:

  • A

  • B

  • E

Parameters:

Name Type Description
x Option<A> The Option.
error E The error if None.

Returns: LoopAction<A, B, E>

A LoopAction.


someToFinish

Converts an Option to a LoopAction.

  • Some -> Finish
  • None -> Fail

Type parameters:

  • A

  • B

  • E

Parameters:

Name Type Description
x Option<B> The Option.
error E The error if None.

Returns: LoopAction<A, B, E>

A LoopAction.


okToStep

Converts a Result to a LoopAction.

  • Ok -> Step
  • Err -> Fail

Type parameters:

  • A

  • B

  • E

Parameters:

Name Type Description
x Result<A, E> The Result.

Returns: LoopAction<A, B, E>

A LoopAction.


okToFinish

Converts a Result to a LoopAction.

  • Ok -> Finish
  • Err -> Fail

Type parameters:

  • A

  • B

  • E

Parameters:

Name Type Description
x Result<B, E> The Result.

Returns: LoopAction<A, B, E>

A LoopAction.