@optique/core 1.2.0-dev.2301 → 1.2.0-dev.2308
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +2 -0
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/internal/mode-dispatch.cjs +40 -1
- package/dist/internal/mode-dispatch.d.cts +8 -5
- package/dist/internal/mode-dispatch.d.ts +8 -5
- package/dist/internal/mode-dispatch.js +38 -1
- package/dist/valueparser.cjs +218 -0
- package/dist/valueparser.d.cts +83 -1
- package/dist/valueparser.d.ts +83 -1
- package/dist/valueparser.js +218 -2
- package/package.json +2 -2
- package/skills/optique/SKILL.md +31 -5
package/dist/index.cjs
CHANGED
|
@@ -17,6 +17,7 @@ exports.RunParserError = require_facade.RunParserError;
|
|
|
17
17
|
exports.WithDefaultError = require_modifiers.WithDefaultError;
|
|
18
18
|
exports.argument = require_primitives.argument;
|
|
19
19
|
exports.bash = require_completion.bash;
|
|
20
|
+
exports.biject = require_valueparser.biject;
|
|
20
21
|
exports.checkBooleanOption = require_valueparser.checkBooleanOption;
|
|
21
22
|
exports.checkEnumOption = require_valueparser.checkEnumOption;
|
|
22
23
|
exports.choice = require_valueparser.choice;
|
|
@@ -121,6 +122,7 @@ exports.suggest = require_internal_parser.suggest;
|
|
|
121
122
|
exports.suggestAsync = require_internal_parser.suggestAsync;
|
|
122
123
|
exports.suggestSync = require_internal_parser.suggestSync;
|
|
123
124
|
exports.text = require_message.text;
|
|
125
|
+
exports.transform = require_valueparser.transform;
|
|
124
126
|
exports.tuple = require_constructs.tuple;
|
|
125
127
|
exports.url = require_valueparser.url;
|
|
126
128
|
exports.uuid = require_valueparser.uuid;
|
package/dist/index.d.cts
CHANGED
|
@@ -3,7 +3,7 @@ import { NonEmptyString, ensureNonEmptyString, isNonEmptyString } from "./nonemp
|
|
|
3
3
|
import { Message, MessageFormatOptions, MessageTerm, ValueSetOptions, commandLine, envVar, formatMessage, lineBreak, link, message, metavar, optionName, optionNames, text, value, valueSet, values } from "./message.cjs";
|
|
4
4
|
import { HiddenVisibility, OptionName, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, cloneUsage, cloneUsageTerm, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, formatUsage, formatUsageTerm, isDocHidden, isSuggestionHidden, isUsageHidden, mergeHidden, normalizeUsage } from "./usage.cjs";
|
|
5
5
|
import { DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, ShowChoicesOptions, ShowDefaultOptions, cloneDocEntry, deduplicateDocEntries, deduplicateDocFragments, formatDocPage, isDocEntryHidden } from "./doc.cjs";
|
|
6
|
-
import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.cjs";
|
|
6
|
+
import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, TransformMapping, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid } from "./valueparser.cjs";
|
|
7
7
|
import { CombineModes, DocState, ExecutionContext, ExecutionPhase, InferMode, InferValue, Mode, ModeIterable, ModeValue, ParseFrame, Parser, ParserContext, ParserResult, Result, Suggestion, createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse, parseAsync, parseSync, suggest, suggestAsync, suggestSync } from "./internal/parser.cjs";
|
|
8
8
|
import { ShellCompletion, bash, fish, nu, pwsh, zsh } from "./completion.cjs";
|
|
9
9
|
import { DeferredValue, DeferredValueOptions, DeferredValueSource, FluentParser, MultipleErrorOptions, MultipleOptions, ParserModifiers, WithDefaultError, WithDefaultOptions, deferredValue, fluent, isDeferredValue, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.cjs";
|
|
@@ -12,4 +12,4 @@ import { ParserValuePlaceholder, SourceContext, SourceContextRequest } from "./c
|
|
|
12
12
|
import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, dependency, deriveFrom, deriveFromAsync, deriveFromSync, isDependencySource, isDerivedValueParser } from "./internal/dependency.cjs";
|
|
13
13
|
import { CommandListMode, CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.cjs";
|
|
14
14
|
import { ArgumentErrorOptions, ArgumentOptions, CommandErrorOptions, CommandOptions, FlagErrorOptions, FlagOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, OptionErrorOptions, OptionOptions, OptionState, PassThroughFormat, PassThroughOptions, argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.cjs";
|
|
15
|
-
export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandListMode, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DeferredValue, DeferredValueOptions, DeferredValueSource, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FlagErrorOptions, FlagOptions, FloatOptions, FluentParser, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserModifiers, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SeqOptions, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
|
15
|
+
export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandListMode, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DeferredValue, DeferredValueOptions, DeferredValueSource, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FlagErrorOptions, FlagOptions, FloatOptions, FluentParser, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserModifiers, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SeqOptions, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TransformMapping, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, biject, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, transform, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
package/dist/index.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { NonEmptyString, ensureNonEmptyString, isNonEmptyString } from "./nonemp
|
|
|
3
3
|
import { Message, MessageFormatOptions, MessageTerm, ValueSetOptions, commandLine, envVar, formatMessage, lineBreak, link, message, metavar, optionName, optionNames, text, value, valueSet, values } from "./message.js";
|
|
4
4
|
import { HiddenVisibility, OptionName, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, cloneUsage, cloneUsageTerm, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, formatUsage, formatUsageTerm, isDocHidden, isSuggestionHidden, isUsageHidden, mergeHidden, normalizeUsage } from "./usage.js";
|
|
5
5
|
import { DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, ShowChoicesOptions, ShowDefaultOptions, cloneDocEntry, deduplicateDocEntries, deduplicateDocFragments, formatDocPage, isDocEntryHidden } from "./doc.js";
|
|
6
|
-
import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
|
|
6
|
+
import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, TransformMapping, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid } from "./valueparser.js";
|
|
7
7
|
import { CombineModes, DocState, ExecutionContext, ExecutionPhase, InferMode, InferValue, Mode, ModeIterable, ModeValue, ParseFrame, Parser, ParserContext, ParserResult, Result, Suggestion, createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse, parseAsync, parseSync, suggest, suggestAsync, suggestSync } from "./internal/parser.js";
|
|
8
8
|
import { ShellCompletion, bash, fish, nu, pwsh, zsh } from "./completion.js";
|
|
9
9
|
import { DeferredValue, DeferredValueOptions, DeferredValueSource, FluentParser, MultipleErrorOptions, MultipleOptions, ParserModifiers, WithDefaultError, WithDefaultOptions, deferredValue, fluent, isDeferredValue, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.js";
|
|
@@ -12,4 +12,4 @@ import { ParserValuePlaceholder, SourceContext, SourceContextRequest } from "./c
|
|
|
12
12
|
import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, dependency, deriveFrom, deriveFromAsync, deriveFromSync, isDependencySource, isDerivedValueParser } from "./internal/dependency.js";
|
|
13
13
|
import { CommandListMode, CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.js";
|
|
14
14
|
import { ArgumentErrorOptions, ArgumentOptions, CommandErrorOptions, CommandOptions, FlagErrorOptions, FlagOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, OptionErrorOptions, OptionOptions, OptionState, PassThroughFormat, PassThroughOptions, argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.js";
|
|
15
|
-
export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandListMode, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DeferredValue, DeferredValueOptions, DeferredValueSource, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FlagErrorOptions, FlagOptions, FloatOptions, FluentParser, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserModifiers, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SeqOptions, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
|
15
|
+
export { type Annotations, AnyDependencySource, ArgumentErrorOptions, ArgumentOptions, ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CombineMode, CombineModes, CombinedDependencyMode, CommandErrorOptions, CommandListMode, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DeferredValue, DeferredValueOptions, DeferredValueSource, DependencyMode, DependencySource, DependencyValue, DependencyValues, DeriveAsyncOptions, DeriveFromAsyncOptions, DeriveFromOptions, DeriveFromSyncOptions, DeriveOptions, DeriveSyncOptions, DerivedValueParser, DocEntry, DocFragment, DocFragments, DocPage, DocPageFormatOptions, DocSection, DocState, DomainOptions, DuplicateOptionError, EmailOptions, ExecutionContext, ExecutionPhase, ExtractRequiredOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FlagErrorOptions, FlagOptions, FloatOptions, FluentParser, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, LongestMatchErrorOptions, LongestMatchOptions, MacAddressOptions, MergeOptions, type Message, type MessageFormatOptions, type MessageTerm, Mode, ModeIterable, ModeValue, MultipleErrorOptions, MultipleOptions, NegatableFlagErrorOptions, NegatableFlagNameList, NegatableFlagNames, NegatableFlagOptions, NegatableFlagState, NoMatchContext, NonEmptyString, ObjectErrorOptions, ObjectOptions, OptionErrorOptions, OptionName, OptionOptions, OptionState, OptionSubConfig, OrErrorOptions, OrOptions, ParseFrame, type ParseOptions, Parser, ParserContext, ParserModifiers, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SeqOptions, ShellCompletion, ShowChoicesOptions, ShowDefaultOptions, SocketAddressOptions, SocketAddressValue, SourceContext, SourceContextRequest, StringOptions, SubstituteParserValue, Suggestion, TransformMapping, TupleOptions, UrlOptions, Usage, UsageFormatOptions, UsageTerm, UsageTermFormatOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, type ValueSetOptions, WithDefaultError, WithDefaultOptions, argument, bash, biject, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, transform, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
package/dist/index.js
CHANGED
|
@@ -8,8 +8,8 @@ import { bash, fish, nu, pwsh, zsh } from "./completion.js";
|
|
|
8
8
|
import { WithDefaultError, deferredValue, fluent, isDeferredValue, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.js";
|
|
9
9
|
import { DuplicateOptionError, concat, conditional, group, longestMatch, merge, object, or, seq, tuple } from "./constructs.js";
|
|
10
10
|
import { ensureNonEmptyString, isNonEmptyString } from "./nonempty.js";
|
|
11
|
-
import { checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
|
|
11
|
+
import { biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid } from "./valueparser.js";
|
|
12
12
|
import { argument, command, constant, fail, flag, negatableFlag, option, passThrough } from "./primitives.js";
|
|
13
13
|
import { RunParserError, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.js";
|
|
14
14
|
|
|
15
|
-
export { DuplicateOptionError, RunParserError, WithDefaultError, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
|
15
|
+
export { DuplicateOptionError, RunParserError, WithDefaultError, argument, bash, biject, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, cron, deduplicateDocEntries, deduplicateDocFragments, deferredValue, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, firstOf, fish, flag, float, fluent, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDeferredValue, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, keyValue, lineBreak, link, locale, longestMatch, macAddress, map, merge, mergeHidden, message, metavar, multiple, negatableFlag, nonEmpty, normalizeUsage, nu, object, option, optionName, optionNames, optional, or, parse, parseAsync, parseSync, passThrough, port, portRange, pwsh, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync, semVer, seq, socketAddress, string, suggest, suggestAsync, suggestSync, text, transform, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
|
|
@@ -37,6 +37,43 @@ function mapModeValue(mode, value, mapFn) {
|
|
|
37
37
|
return mapFn(value);
|
|
38
38
|
}
|
|
39
39
|
/**
|
|
40
|
+
* Maps a value or promise while preserving the declared execution mode.
|
|
41
|
+
*
|
|
42
|
+
* Some internal extension hooks predate `ModeValue` and expose a plain
|
|
43
|
+
* `T | Promise<T>` return type. This helper adapts those hooks back into the
|
|
44
|
+
* mode-dispatch boundary before applying a mapping function.
|
|
45
|
+
*
|
|
46
|
+
* @param mode The execution mode.
|
|
47
|
+
* @param value The value or promise to transform.
|
|
48
|
+
* @param mapFn Mapping function applied to the unwrapped value.
|
|
49
|
+
* @returns The mapped value with correct mode wrapping.
|
|
50
|
+
* @internal
|
|
51
|
+
*/
|
|
52
|
+
function mapMaybePromiseByMode(mode, value, mapFn) {
|
|
53
|
+
return mapModeValue(mode, wrapForMode(mode, value), mapFn);
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Adapts an iterable or async iterable to the declared execution mode.
|
|
57
|
+
*
|
|
58
|
+
* @param mode The execution mode.
|
|
59
|
+
* @param value The iterable to adapt.
|
|
60
|
+
* @returns The iterable with correct mode wrapping.
|
|
61
|
+
* @throws {TypeError} If a synchronous mode receives an async iterable.
|
|
62
|
+
* @internal
|
|
63
|
+
*/
|
|
64
|
+
function wrapIterableForMode(mode, value) {
|
|
65
|
+
const canCheckAsyncIterator = value != null && (typeof value === "object" || typeof value === "function");
|
|
66
|
+
return dispatchIterableByMode(mode, () => {
|
|
67
|
+
if (canCheckAsyncIterator && Symbol.asyncIterator in value) throw new TypeError("Synchronous mode cannot wrap AsyncIterable value.");
|
|
68
|
+
return value;
|
|
69
|
+
}, () => {
|
|
70
|
+
if (canCheckAsyncIterator && Symbol.asyncIterator in value) return value;
|
|
71
|
+
return async function* () {
|
|
72
|
+
yield* value;
|
|
73
|
+
}();
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
40
77
|
* Dispatches iterable to sync or async implementation based on mode.
|
|
41
78
|
*
|
|
42
79
|
* @param mode The execution mode.
|
|
@@ -54,5 +91,7 @@ function dispatchIterableByMode(mode, syncFn, asyncFn) {
|
|
|
54
91
|
//#endregion
|
|
55
92
|
exports.dispatchByMode = dispatchByMode;
|
|
56
93
|
exports.dispatchIterableByMode = dispatchIterableByMode;
|
|
94
|
+
exports.mapMaybePromiseByMode = mapMaybePromiseByMode;
|
|
57
95
|
exports.mapModeValue = mapModeValue;
|
|
58
|
-
exports.wrapForMode = wrapForMode;
|
|
96
|
+
exports.wrapForMode = wrapForMode;
|
|
97
|
+
exports.wrapIterableForMode = wrapIterableForMode;
|
|
@@ -38,14 +38,17 @@ declare function wrapForMode<M extends Mode, T>(mode: M, value: T | Promise<T>):
|
|
|
38
38
|
*/
|
|
39
39
|
declare function mapModeValue<M extends Mode, T, U>(mode: M, value: ModeValue<M, T>, mapFn: (value: T) => U): ModeValue<M, U>;
|
|
40
40
|
/**
|
|
41
|
-
*
|
|
41
|
+
* Maps a value or promise while preserving the declared execution mode.
|
|
42
|
+
*
|
|
43
|
+
* Some internal extension hooks predate `ModeValue` and expose a plain
|
|
44
|
+
* `T | Promise<T>` return type. This helper adapts those hooks back into the
|
|
45
|
+
* mode-dispatch boundary before applying a mapping function.
|
|
42
46
|
*
|
|
43
47
|
* @param mode The execution mode.
|
|
44
|
-
* @param
|
|
45
|
-
* @param
|
|
46
|
-
* @returns The
|
|
48
|
+
* @param value The value or promise to transform.
|
|
49
|
+
* @param mapFn Mapping function applied to the unwrapped value.
|
|
50
|
+
* @returns The mapped value with correct mode wrapping.
|
|
47
51
|
* @internal
|
|
48
|
-
* @since 0.10.0
|
|
49
52
|
*/
|
|
50
53
|
//#endregion
|
|
51
54
|
export { dispatchByMode, mapModeValue, wrapForMode };
|
|
@@ -38,14 +38,17 @@ declare function wrapForMode<M extends Mode, T>(mode: M, value: T | Promise<T>):
|
|
|
38
38
|
*/
|
|
39
39
|
declare function mapModeValue<M extends Mode, T, U>(mode: M, value: ModeValue<M, T>, mapFn: (value: T) => U): ModeValue<M, U>;
|
|
40
40
|
/**
|
|
41
|
-
*
|
|
41
|
+
* Maps a value or promise while preserving the declared execution mode.
|
|
42
|
+
*
|
|
43
|
+
* Some internal extension hooks predate `ModeValue` and expose a plain
|
|
44
|
+
* `T | Promise<T>` return type. This helper adapts those hooks back into the
|
|
45
|
+
* mode-dispatch boundary before applying a mapping function.
|
|
42
46
|
*
|
|
43
47
|
* @param mode The execution mode.
|
|
44
|
-
* @param
|
|
45
|
-
* @param
|
|
46
|
-
* @returns The
|
|
48
|
+
* @param value The value or promise to transform.
|
|
49
|
+
* @param mapFn Mapping function applied to the unwrapped value.
|
|
50
|
+
* @returns The mapped value with correct mode wrapping.
|
|
47
51
|
* @internal
|
|
48
|
-
* @since 0.10.0
|
|
49
52
|
*/
|
|
50
53
|
//#endregion
|
|
51
54
|
export { dispatchByMode, mapModeValue, wrapForMode };
|
|
@@ -36,6 +36,43 @@ function mapModeValue(mode, value, mapFn) {
|
|
|
36
36
|
return mapFn(value);
|
|
37
37
|
}
|
|
38
38
|
/**
|
|
39
|
+
* Maps a value or promise while preserving the declared execution mode.
|
|
40
|
+
*
|
|
41
|
+
* Some internal extension hooks predate `ModeValue` and expose a plain
|
|
42
|
+
* `T | Promise<T>` return type. This helper adapts those hooks back into the
|
|
43
|
+
* mode-dispatch boundary before applying a mapping function.
|
|
44
|
+
*
|
|
45
|
+
* @param mode The execution mode.
|
|
46
|
+
* @param value The value or promise to transform.
|
|
47
|
+
* @param mapFn Mapping function applied to the unwrapped value.
|
|
48
|
+
* @returns The mapped value with correct mode wrapping.
|
|
49
|
+
* @internal
|
|
50
|
+
*/
|
|
51
|
+
function mapMaybePromiseByMode(mode, value, mapFn) {
|
|
52
|
+
return mapModeValue(mode, wrapForMode(mode, value), mapFn);
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Adapts an iterable or async iterable to the declared execution mode.
|
|
56
|
+
*
|
|
57
|
+
* @param mode The execution mode.
|
|
58
|
+
* @param value The iterable to adapt.
|
|
59
|
+
* @returns The iterable with correct mode wrapping.
|
|
60
|
+
* @throws {TypeError} If a synchronous mode receives an async iterable.
|
|
61
|
+
* @internal
|
|
62
|
+
*/
|
|
63
|
+
function wrapIterableForMode(mode, value) {
|
|
64
|
+
const canCheckAsyncIterator = value != null && (typeof value === "object" || typeof value === "function");
|
|
65
|
+
return dispatchIterableByMode(mode, () => {
|
|
66
|
+
if (canCheckAsyncIterator && Symbol.asyncIterator in value) throw new TypeError("Synchronous mode cannot wrap AsyncIterable value.");
|
|
67
|
+
return value;
|
|
68
|
+
}, () => {
|
|
69
|
+
if (canCheckAsyncIterator && Symbol.asyncIterator in value) return value;
|
|
70
|
+
return async function* () {
|
|
71
|
+
yield* value;
|
|
72
|
+
}();
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
39
76
|
* Dispatches iterable to sync or async implementation based on mode.
|
|
40
77
|
*
|
|
41
78
|
* @param mode The execution mode.
|
|
@@ -51,4 +88,4 @@ function dispatchIterableByMode(mode, syncFn, asyncFn) {
|
|
|
51
88
|
}
|
|
52
89
|
|
|
53
90
|
//#endregion
|
|
54
|
-
export { dispatchByMode, dispatchIterableByMode, mapModeValue, wrapForMode };
|
|
91
|
+
export { dispatchByMode, dispatchIterableByMode, mapMaybePromiseByMode, mapModeValue, wrapForMode, wrapIterableForMode };
|
package/dist/valueparser.cjs
CHANGED
|
@@ -1,9 +1,34 @@
|
|
|
1
1
|
const require_message = require('./message.cjs');
|
|
2
|
+
const require_mode_dispatch = require('./internal/mode-dispatch.cjs');
|
|
2
3
|
const require_internal_dependency = require('./internal/dependency.cjs');
|
|
3
4
|
const require_suggestion = require('./suggestion.cjs');
|
|
4
5
|
const require_nonempty = require('./nonempty.cjs');
|
|
5
6
|
|
|
6
7
|
//#region src/valueparser.ts
|
|
8
|
+
function transformValueParserResult(result, mapping) {
|
|
9
|
+
if (!result.success) return result;
|
|
10
|
+
const preserveSnapshot = (mapped) => {
|
|
11
|
+
const snapshot = require_internal_dependency.getSnapshottedDefaultDependencyValues(result);
|
|
12
|
+
return snapshot == null ? mapped : require_internal_dependency.snapshotDefaultDependencyValues(mapped, snapshot);
|
|
13
|
+
};
|
|
14
|
+
if (result.deferred) try {
|
|
15
|
+
return preserveSnapshot({
|
|
16
|
+
success: true,
|
|
17
|
+
value: mapping.map(result.value),
|
|
18
|
+
deferred: true
|
|
19
|
+
});
|
|
20
|
+
} catch {
|
|
21
|
+
return preserveSnapshot({
|
|
22
|
+
success: true,
|
|
23
|
+
value: void 0,
|
|
24
|
+
deferred: true
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return preserveSnapshot({
|
|
28
|
+
success: true,
|
|
29
|
+
value: mapping.map(result.value)
|
|
30
|
+
});
|
|
31
|
+
}
|
|
7
32
|
/**
|
|
8
33
|
* A predicate function that checks if an object is a {@link ValueParser}.
|
|
9
34
|
* @param object The object to check.
|
|
@@ -191,6 +216,197 @@ function choice(choices, options = {}) {
|
|
|
191
216
|
}
|
|
192
217
|
};
|
|
193
218
|
}
|
|
219
|
+
function biject(mapping) {
|
|
220
|
+
if (mapping === null || typeof mapping !== "object") throw new TypeError("Expected object.");
|
|
221
|
+
if (Array.isArray(mapping)) throw new TypeError("Expected object, got array.");
|
|
222
|
+
const keys = [];
|
|
223
|
+
for (const key in mapping) if (Object.prototype.hasOwnProperty.call(mapping, key)) keys.push(key);
|
|
224
|
+
if (keys.length < 1) throw new RangeError("Expected at least one biject entry.");
|
|
225
|
+
const source = choice(keys);
|
|
226
|
+
const forward = /* @__PURE__ */ new Map();
|
|
227
|
+
const reverse = /* @__PURE__ */ new Map();
|
|
228
|
+
for (const key of keys) {
|
|
229
|
+
const value = mapping[key];
|
|
230
|
+
if (reverse.has(value)) throw new RangeError(`Duplicate biject value for key ${JSON.stringify(key)}.`);
|
|
231
|
+
forward.set(key, value);
|
|
232
|
+
reverse.set(value, key);
|
|
233
|
+
}
|
|
234
|
+
const parser = transform(source, {
|
|
235
|
+
map(value) {
|
|
236
|
+
return forward.get(value);
|
|
237
|
+
},
|
|
238
|
+
unmap(value) {
|
|
239
|
+
const key = reverse.get(value);
|
|
240
|
+
if (key !== void 0) return key;
|
|
241
|
+
try {
|
|
242
|
+
return String(value);
|
|
243
|
+
} catch {
|
|
244
|
+
return "";
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
Object.defineProperty(parser, "validate", {
|
|
249
|
+
value(value) {
|
|
250
|
+
if (reverse.has(value)) return {
|
|
251
|
+
success: true,
|
|
252
|
+
value
|
|
253
|
+
};
|
|
254
|
+
let input;
|
|
255
|
+
try {
|
|
256
|
+
input = String(value);
|
|
257
|
+
} catch {
|
|
258
|
+
input = "";
|
|
259
|
+
}
|
|
260
|
+
const result = source.parse(input);
|
|
261
|
+
if (!result.success) return result;
|
|
262
|
+
return {
|
|
263
|
+
success: false,
|
|
264
|
+
error: formatDefaultChoiceError(input, keys)
|
|
265
|
+
};
|
|
266
|
+
},
|
|
267
|
+
configurable: true,
|
|
268
|
+
enumerable: true
|
|
269
|
+
});
|
|
270
|
+
return parser;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Creates a value parser that transforms the result of another value parser.
|
|
274
|
+
*
|
|
275
|
+
* This is useful when an existing value parser already describes the accepted
|
|
276
|
+
* CLI spelling, suggestions, and error messages, but your application wants a
|
|
277
|
+
* different result type. For example, a string `choice()` can be transformed
|
|
278
|
+
* into an internal enum, tagged object, or other domain type.
|
|
279
|
+
*
|
|
280
|
+
* Unlike parser-level `map()`, value parser transformation needs an inverse
|
|
281
|
+
* mapping. The `unmap` function lets the transformed parser format values,
|
|
282
|
+
* validate fallback/default values, and reuse the wrapped parser's metadata
|
|
283
|
+
* without guessing how to serialize the transformed type.
|
|
284
|
+
*
|
|
285
|
+
* Transform functions are synchronous. If the wrapped parser is async, the
|
|
286
|
+
* returned parser is async too, but `map` and `unmap` still run synchronously
|
|
287
|
+
* after the wrapped parser resolves.
|
|
288
|
+
*
|
|
289
|
+
* @template M The execution mode of the wrapped parser.
|
|
290
|
+
* @template T The value type produced by the wrapped parser.
|
|
291
|
+
* @template U The value type produced by the transformed parser.
|
|
292
|
+
* @param parser The value parser to transform.
|
|
293
|
+
* @param mapping Mapping functions between the wrapped and transformed value
|
|
294
|
+
* types.
|
|
295
|
+
* @returns A value parser that accepts the same input as `parser` and produces
|
|
296
|
+
* transformed values.
|
|
297
|
+
* @since 1.2.0
|
|
298
|
+
*/
|
|
299
|
+
function transform(parser, mapping) {
|
|
300
|
+
const normalize = parser.normalize?.bind(parser);
|
|
301
|
+
const suggest = parser.suggest?.bind(parser);
|
|
302
|
+
const transformedChoices = parser.choices == null ? void 0 : Object.freeze(parser.choices.map((choice$1) => mapping.map(choice$1)));
|
|
303
|
+
const transformed = {
|
|
304
|
+
mode: parser.mode,
|
|
305
|
+
metavar: parser.metavar,
|
|
306
|
+
placeholder: void 0,
|
|
307
|
+
...transformedChoices == null ? {} : { choices: transformedChoices },
|
|
308
|
+
parse(input) {
|
|
309
|
+
return require_mode_dispatch.mapMaybePromiseByMode(parser.mode, parser.parse(input), (result) => transformValueParserResult(result, mapping));
|
|
310
|
+
},
|
|
311
|
+
format(value) {
|
|
312
|
+
return parser.format(mapping.unmap(value));
|
|
313
|
+
},
|
|
314
|
+
...normalize == null ? {} : { normalize(value) {
|
|
315
|
+
return mapping.map(normalize(mapping.unmap(value)));
|
|
316
|
+
} },
|
|
317
|
+
...suggest == null ? {} : { suggest(prefix) {
|
|
318
|
+
return suggest(prefix);
|
|
319
|
+
} }
|
|
320
|
+
};
|
|
321
|
+
Object.defineProperty(transformed, "placeholder", {
|
|
322
|
+
get() {
|
|
323
|
+
if (parser.placeholder === void 0) return void 0;
|
|
324
|
+
try {
|
|
325
|
+
return mapping.map(parser.placeholder);
|
|
326
|
+
} catch {
|
|
327
|
+
return void 0;
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
configurable: true,
|
|
331
|
+
enumerable: true
|
|
332
|
+
});
|
|
333
|
+
if (typeof parser.validate === "function") {
|
|
334
|
+
const validate = parser.validate.bind(parser);
|
|
335
|
+
Object.defineProperty(transformed, "validate", {
|
|
336
|
+
value(value) {
|
|
337
|
+
const result = validate(mapping.unmap(value));
|
|
338
|
+
return result.success ? {
|
|
339
|
+
success: true,
|
|
340
|
+
value: mapping.map(result.value)
|
|
341
|
+
} : result;
|
|
342
|
+
},
|
|
343
|
+
configurable: true,
|
|
344
|
+
enumerable: true
|
|
345
|
+
});
|
|
346
|
+
} else if (parser.mode === "sync") {
|
|
347
|
+
const syncParser = parser;
|
|
348
|
+
Object.defineProperty(transformed, "validate", {
|
|
349
|
+
value(value) {
|
|
350
|
+
let result;
|
|
351
|
+
try {
|
|
352
|
+
result = syncParser.parse(syncParser.format(mapping.unmap(value)));
|
|
353
|
+
} catch {
|
|
354
|
+
return {
|
|
355
|
+
success: true,
|
|
356
|
+
value
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
return result.success ? {
|
|
360
|
+
success: true,
|
|
361
|
+
value: mapping.map(result.value)
|
|
362
|
+
} : result;
|
|
363
|
+
},
|
|
364
|
+
configurable: true,
|
|
365
|
+
enumerable: true
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (require_internal_dependency.isDerivedValueParser(parser)) preserveTransformedDerivedMetadata(transformed, parser, mapping);
|
|
369
|
+
return transformed;
|
|
370
|
+
}
|
|
371
|
+
function preserveTransformedDerivedMetadata(transformed, parser, mapping) {
|
|
372
|
+
Object.defineProperties(transformed, {
|
|
373
|
+
[require_internal_dependency.derivedValueParserMarker]: {
|
|
374
|
+
value: true,
|
|
375
|
+
enumerable: true
|
|
376
|
+
},
|
|
377
|
+
[require_internal_dependency.dependencyId]: {
|
|
378
|
+
value: parser[require_internal_dependency.dependencyId],
|
|
379
|
+
enumerable: true
|
|
380
|
+
},
|
|
381
|
+
[require_internal_dependency.parseWithDependency]: {
|
|
382
|
+
value(input, dependencyValue) {
|
|
383
|
+
return require_mode_dispatch.mapMaybePromiseByMode(parser.mode, parser[require_internal_dependency.parseWithDependency](input, dependencyValue), (result) => transformValueParserResult(result, mapping));
|
|
384
|
+
},
|
|
385
|
+
enumerable: true
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
if (require_internal_dependency.dependencyIds in parser && parser[require_internal_dependency.dependencyIds] != null) Object.defineProperty(transformed, require_internal_dependency.dependencyIds, {
|
|
389
|
+
value: parser[require_internal_dependency.dependencyIds],
|
|
390
|
+
enumerable: true
|
|
391
|
+
});
|
|
392
|
+
if (require_internal_dependency.defaultValues in parser && parser[require_internal_dependency.defaultValues] != null) Object.defineProperty(transformed, require_internal_dependency.defaultValues, {
|
|
393
|
+
value: parser[require_internal_dependency.defaultValues],
|
|
394
|
+
enumerable: true
|
|
395
|
+
});
|
|
396
|
+
if (require_internal_dependency.singleDefaultValue in parser && parser[require_internal_dependency.singleDefaultValue] != null) Object.defineProperty(transformed, require_internal_dependency.singleDefaultValue, {
|
|
397
|
+
value: parser[require_internal_dependency.singleDefaultValue],
|
|
398
|
+
enumerable: true
|
|
399
|
+
});
|
|
400
|
+
if (require_internal_dependency.suggestWithDependency in parser && parser[require_internal_dependency.suggestWithDependency] != null) {
|
|
401
|
+
const suggest = parser[require_internal_dependency.suggestWithDependency];
|
|
402
|
+
Object.defineProperty(transformed, require_internal_dependency.suggestWithDependency, {
|
|
403
|
+
value(prefix, dependencyValue) {
|
|
404
|
+
return require_mode_dispatch.wrapIterableForMode(parser.mode, suggest(prefix, dependencyValue));
|
|
405
|
+
},
|
|
406
|
+
enumerable: true
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
194
410
|
/**
|
|
195
411
|
* Validates that an option value, if present, is a boolean.
|
|
196
412
|
* Throws a {@link TypeError} if the value is defined but not a boolean.
|
|
@@ -6336,6 +6552,7 @@ function plainObjectsEqual(a, b) {
|
|
|
6336
6552
|
}
|
|
6337
6553
|
|
|
6338
6554
|
//#endregion
|
|
6555
|
+
exports.biject = biject;
|
|
6339
6556
|
exports.checkBooleanOption = checkBooleanOption;
|
|
6340
6557
|
exports.checkEnumOption = checkEnumOption;
|
|
6341
6558
|
exports.choice = choice;
|
|
@@ -6364,5 +6581,6 @@ exports.portRange = portRange;
|
|
|
6364
6581
|
exports.semVer = semVer;
|
|
6365
6582
|
exports.socketAddress = socketAddress;
|
|
6366
6583
|
exports.string = string;
|
|
6584
|
+
exports.transform = transform;
|
|
6367
6585
|
exports.url = url;
|
|
6368
6586
|
exports.uuid = uuid;
|
package/dist/valueparser.d.cts
CHANGED
|
@@ -327,6 +327,36 @@ interface ChoiceOptionsNumber extends ChoiceOptionsBase {
|
|
|
327
327
|
* {@link ChoiceOptionsNumber} for number choices.
|
|
328
328
|
*/
|
|
329
329
|
type ChoiceOptions = ChoiceOptionsString;
|
|
330
|
+
/**
|
|
331
|
+
* Mapping functions for the {@link transform} value parser combinator.
|
|
332
|
+
*
|
|
333
|
+
* `map` converts values produced by the wrapped parser into the public result
|
|
334
|
+
* type. `unmap` converts public values back to the wrapped parser's type so
|
|
335
|
+
* `format()`, `validate()`, and default-value handling can keep using the
|
|
336
|
+
* wrapped parser's own validation and formatting rules.
|
|
337
|
+
*
|
|
338
|
+
* The two functions should be inverses for the values your CLI accepts:
|
|
339
|
+
* `unmap(map(input))` should return a value accepted by the wrapped parser,
|
|
340
|
+
* and `map(unmap(output))` should preserve valid public values.
|
|
341
|
+
*
|
|
342
|
+
* @template T The value type produced by the wrapped parser.
|
|
343
|
+
* @template U The value type produced by the transformed parser.
|
|
344
|
+
* @since 1.2.0
|
|
345
|
+
*/
|
|
346
|
+
interface TransformMapping<T, U> {
|
|
347
|
+
/**
|
|
348
|
+
* Converts a value produced by the wrapped parser into the transformed
|
|
349
|
+
* parser's public value type.
|
|
350
|
+
*/
|
|
351
|
+
map(value: T): U;
|
|
352
|
+
/**
|
|
353
|
+
* Converts a public transformed value back into the wrapped parser's value
|
|
354
|
+
* type for formatting and fallback validation.
|
|
355
|
+
*/
|
|
356
|
+
unmap(value: U): T;
|
|
357
|
+
}
|
|
358
|
+
type BijectKey<T> = Extract<keyof T, string | number>;
|
|
359
|
+
type BijectValue<T> = T[BijectKey<T>];
|
|
330
360
|
/**
|
|
331
361
|
* A predicate function that checks if an object is a {@link ValueParser}.
|
|
332
362
|
* @param object The object to check.
|
|
@@ -374,6 +404,58 @@ declare function choice<const T extends string>(choices: readonly T[], options?:
|
|
|
374
404
|
* @since 0.9.0
|
|
375
405
|
*/
|
|
376
406
|
declare function choice<const T extends number>(choices: readonly T[], options?: ChoiceOptionsNumber): ValueParser<"sync", T>;
|
|
407
|
+
/**
|
|
408
|
+
* Creates a value parser from a one-to-one mapping of CLI spellings to values.
|
|
409
|
+
*
|
|
410
|
+
* The mapping's string keys are accepted as command-line input, and each key
|
|
411
|
+
* is parsed into its corresponding value. Values must also be unique using
|
|
412
|
+
* the same equality semantics as `Map` keys, so the parser can format a value
|
|
413
|
+
* back to the original key.
|
|
414
|
+
*
|
|
415
|
+
* This is a convenience wrapper around `choice(Object.keys(mapping))` and
|
|
416
|
+
* {@link transform}. It keeps the input-side metadata from `choice()` while
|
|
417
|
+
* exposing the mapped values as the parser result type.
|
|
418
|
+
*
|
|
419
|
+
* @template T The one-to-one mapping from input strings to parsed values.
|
|
420
|
+
* @param mapping A mapping whose own enumerable string keys are valid inputs.
|
|
421
|
+
* @returns A value parser that accepts one of the mapping keys and returns the
|
|
422
|
+
* corresponding value.
|
|
423
|
+
* @throws {TypeError} If `mapping` is not an object, if it is an array, or if
|
|
424
|
+
* any key is the empty string.
|
|
425
|
+
* @throws {RangeError} If the mapping has no own enumerable string keys, or if
|
|
426
|
+
* two keys map to the same value according to `Map` key equality.
|
|
427
|
+
* @since 1.2.0
|
|
428
|
+
*/
|
|
429
|
+
declare function biject<const T extends readonly unknown[]>(mapping: T): never;
|
|
430
|
+
declare function biject<const T extends object>(mapping: T): ValueParser<"sync", BijectValue<T>>;
|
|
431
|
+
/**
|
|
432
|
+
* Creates a value parser that transforms the result of another value parser.
|
|
433
|
+
*
|
|
434
|
+
* This is useful when an existing value parser already describes the accepted
|
|
435
|
+
* CLI spelling, suggestions, and error messages, but your application wants a
|
|
436
|
+
* different result type. For example, a string `choice()` can be transformed
|
|
437
|
+
* into an internal enum, tagged object, or other domain type.
|
|
438
|
+
*
|
|
439
|
+
* Unlike parser-level `map()`, value parser transformation needs an inverse
|
|
440
|
+
* mapping. The `unmap` function lets the transformed parser format values,
|
|
441
|
+
* validate fallback/default values, and reuse the wrapped parser's metadata
|
|
442
|
+
* without guessing how to serialize the transformed type.
|
|
443
|
+
*
|
|
444
|
+
* Transform functions are synchronous. If the wrapped parser is async, the
|
|
445
|
+
* returned parser is async too, but `map` and `unmap` still run synchronously
|
|
446
|
+
* after the wrapped parser resolves.
|
|
447
|
+
*
|
|
448
|
+
* @template M The execution mode of the wrapped parser.
|
|
449
|
+
* @template T The value type produced by the wrapped parser.
|
|
450
|
+
* @template U The value type produced by the transformed parser.
|
|
451
|
+
* @param parser The value parser to transform.
|
|
452
|
+
* @param mapping Mapping functions between the wrapped and transformed value
|
|
453
|
+
* types.
|
|
454
|
+
* @returns A value parser that accepts the same input as `parser` and produces
|
|
455
|
+
* transformed values.
|
|
456
|
+
* @since 1.2.0
|
|
457
|
+
*/
|
|
458
|
+
declare function transform<M extends Mode, T, U>(parser: ValueParser<M, T>, mapping: TransformMapping<T, U>): ValueParser<M, U>;
|
|
377
459
|
/**
|
|
378
460
|
* Validates that an option value, if present, is a boolean.
|
|
379
461
|
* Throws a {@link TypeError} if the value is defined but not a boolean.
|
|
@@ -3197,4 +3279,4 @@ declare function firstOf<const TParsers extends readonly [ValueParser<"sync", un
|
|
|
3197
3279
|
*/
|
|
3198
3280
|
declare function firstOf<const TParsers extends readonly ValueParser<"sync", unknown>[]>(parsers: TParsers, options?: FirstOfOptions): ValueParser<"sync", ValueParserValue<TParsers[number]>>;
|
|
3199
3281
|
//#endregion
|
|
3200
|
-
export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
|
|
3282
|
+
export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, TransformMapping, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid };
|
package/dist/valueparser.d.ts
CHANGED
|
@@ -327,6 +327,36 @@ interface ChoiceOptionsNumber extends ChoiceOptionsBase {
|
|
|
327
327
|
* {@link ChoiceOptionsNumber} for number choices.
|
|
328
328
|
*/
|
|
329
329
|
type ChoiceOptions = ChoiceOptionsString;
|
|
330
|
+
/**
|
|
331
|
+
* Mapping functions for the {@link transform} value parser combinator.
|
|
332
|
+
*
|
|
333
|
+
* `map` converts values produced by the wrapped parser into the public result
|
|
334
|
+
* type. `unmap` converts public values back to the wrapped parser's type so
|
|
335
|
+
* `format()`, `validate()`, and default-value handling can keep using the
|
|
336
|
+
* wrapped parser's own validation and formatting rules.
|
|
337
|
+
*
|
|
338
|
+
* The two functions should be inverses for the values your CLI accepts:
|
|
339
|
+
* `unmap(map(input))` should return a value accepted by the wrapped parser,
|
|
340
|
+
* and `map(unmap(output))` should preserve valid public values.
|
|
341
|
+
*
|
|
342
|
+
* @template T The value type produced by the wrapped parser.
|
|
343
|
+
* @template U The value type produced by the transformed parser.
|
|
344
|
+
* @since 1.2.0
|
|
345
|
+
*/
|
|
346
|
+
interface TransformMapping<T, U> {
|
|
347
|
+
/**
|
|
348
|
+
* Converts a value produced by the wrapped parser into the transformed
|
|
349
|
+
* parser's public value type.
|
|
350
|
+
*/
|
|
351
|
+
map(value: T): U;
|
|
352
|
+
/**
|
|
353
|
+
* Converts a public transformed value back into the wrapped parser's value
|
|
354
|
+
* type for formatting and fallback validation.
|
|
355
|
+
*/
|
|
356
|
+
unmap(value: U): T;
|
|
357
|
+
}
|
|
358
|
+
type BijectKey<T> = Extract<keyof T, string | number>;
|
|
359
|
+
type BijectValue<T> = T[BijectKey<T>];
|
|
330
360
|
/**
|
|
331
361
|
* A predicate function that checks if an object is a {@link ValueParser}.
|
|
332
362
|
* @param object The object to check.
|
|
@@ -374,6 +404,58 @@ declare function choice<const T extends string>(choices: readonly T[], options?:
|
|
|
374
404
|
* @since 0.9.0
|
|
375
405
|
*/
|
|
376
406
|
declare function choice<const T extends number>(choices: readonly T[], options?: ChoiceOptionsNumber): ValueParser<"sync", T>;
|
|
407
|
+
/**
|
|
408
|
+
* Creates a value parser from a one-to-one mapping of CLI spellings to values.
|
|
409
|
+
*
|
|
410
|
+
* The mapping's string keys are accepted as command-line input, and each key
|
|
411
|
+
* is parsed into its corresponding value. Values must also be unique using
|
|
412
|
+
* the same equality semantics as `Map` keys, so the parser can format a value
|
|
413
|
+
* back to the original key.
|
|
414
|
+
*
|
|
415
|
+
* This is a convenience wrapper around `choice(Object.keys(mapping))` and
|
|
416
|
+
* {@link transform}. It keeps the input-side metadata from `choice()` while
|
|
417
|
+
* exposing the mapped values as the parser result type.
|
|
418
|
+
*
|
|
419
|
+
* @template T The one-to-one mapping from input strings to parsed values.
|
|
420
|
+
* @param mapping A mapping whose own enumerable string keys are valid inputs.
|
|
421
|
+
* @returns A value parser that accepts one of the mapping keys and returns the
|
|
422
|
+
* corresponding value.
|
|
423
|
+
* @throws {TypeError} If `mapping` is not an object, if it is an array, or if
|
|
424
|
+
* any key is the empty string.
|
|
425
|
+
* @throws {RangeError} If the mapping has no own enumerable string keys, or if
|
|
426
|
+
* two keys map to the same value according to `Map` key equality.
|
|
427
|
+
* @since 1.2.0
|
|
428
|
+
*/
|
|
429
|
+
declare function biject<const T extends readonly unknown[]>(mapping: T): never;
|
|
430
|
+
declare function biject<const T extends object>(mapping: T): ValueParser<"sync", BijectValue<T>>;
|
|
431
|
+
/**
|
|
432
|
+
* Creates a value parser that transforms the result of another value parser.
|
|
433
|
+
*
|
|
434
|
+
* This is useful when an existing value parser already describes the accepted
|
|
435
|
+
* CLI spelling, suggestions, and error messages, but your application wants a
|
|
436
|
+
* different result type. For example, a string `choice()` can be transformed
|
|
437
|
+
* into an internal enum, tagged object, or other domain type.
|
|
438
|
+
*
|
|
439
|
+
* Unlike parser-level `map()`, value parser transformation needs an inverse
|
|
440
|
+
* mapping. The `unmap` function lets the transformed parser format values,
|
|
441
|
+
* validate fallback/default values, and reuse the wrapped parser's metadata
|
|
442
|
+
* without guessing how to serialize the transformed type.
|
|
443
|
+
*
|
|
444
|
+
* Transform functions are synchronous. If the wrapped parser is async, the
|
|
445
|
+
* returned parser is async too, but `map` and `unmap` still run synchronously
|
|
446
|
+
* after the wrapped parser resolves.
|
|
447
|
+
*
|
|
448
|
+
* @template M The execution mode of the wrapped parser.
|
|
449
|
+
* @template T The value type produced by the wrapped parser.
|
|
450
|
+
* @template U The value type produced by the transformed parser.
|
|
451
|
+
* @param parser The value parser to transform.
|
|
452
|
+
* @param mapping Mapping functions between the wrapped and transformed value
|
|
453
|
+
* types.
|
|
454
|
+
* @returns A value parser that accepts the same input as `parser` and produces
|
|
455
|
+
* transformed values.
|
|
456
|
+
* @since 1.2.0
|
|
457
|
+
*/
|
|
458
|
+
declare function transform<M extends Mode, T, U>(parser: ValueParser<M, T>, mapping: TransformMapping<T, U>): ValueParser<M, U>;
|
|
377
459
|
/**
|
|
378
460
|
* Validates that an option value, if present, is a boolean.
|
|
379
461
|
* Throws a {@link TypeError} if the value is defined but not a boolean.
|
|
@@ -3197,4 +3279,4 @@ declare function firstOf<const TParsers extends readonly [ValueParser<"sync", un
|
|
|
3197
3279
|
*/
|
|
3198
3280
|
declare function firstOf<const TParsers extends readonly ValueParser<"sync", unknown>[]>(parsers: TParsers, options?: FirstOfOptions): ValueParser<"sync", ValueParserValue<TParsers[number]>>;
|
|
3199
3281
|
//#endregion
|
|
3200
|
-
export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
|
|
3282
|
+
export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, CronExpression, CronExpressionForOptions, CronOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FirstOfOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, KeyValueOptions, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, SocketAddressOptions, SocketAddressValue, StringOptions, TransformMapping, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid };
|
package/dist/valueparser.js
CHANGED
|
@@ -1,9 +1,34 @@
|
|
|
1
1
|
import { cloneMessage, lineBreak, message, metavar, text, valueSet } from "./message.js";
|
|
2
|
-
import {
|
|
2
|
+
import { mapMaybePromiseByMode, wrapIterableForMode } from "./internal/mode-dispatch.js";
|
|
3
|
+
import { defaultValues, dependencyId, dependencyIds, derivedValueParserMarker, getSnapshottedDefaultDependencyValues, isDerivedValueParser, parseWithDependency, singleDefaultValue, snapshotDefaultDependencyValues, suggestWithDependency } from "./internal/dependency.js";
|
|
3
4
|
import { appendValueHint, appendValueSuggestions, deduplicateSuggestions } from "./suggestion.js";
|
|
4
5
|
import { ensureNonEmptyString, isNonEmptyString } from "./nonempty.js";
|
|
5
6
|
|
|
6
7
|
//#region src/valueparser.ts
|
|
8
|
+
function transformValueParserResult(result, mapping) {
|
|
9
|
+
if (!result.success) return result;
|
|
10
|
+
const preserveSnapshot = (mapped) => {
|
|
11
|
+
const snapshot = getSnapshottedDefaultDependencyValues(result);
|
|
12
|
+
return snapshot == null ? mapped : snapshotDefaultDependencyValues(mapped, snapshot);
|
|
13
|
+
};
|
|
14
|
+
if (result.deferred) try {
|
|
15
|
+
return preserveSnapshot({
|
|
16
|
+
success: true,
|
|
17
|
+
value: mapping.map(result.value),
|
|
18
|
+
deferred: true
|
|
19
|
+
});
|
|
20
|
+
} catch {
|
|
21
|
+
return preserveSnapshot({
|
|
22
|
+
success: true,
|
|
23
|
+
value: void 0,
|
|
24
|
+
deferred: true
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
return preserveSnapshot({
|
|
28
|
+
success: true,
|
|
29
|
+
value: mapping.map(result.value)
|
|
30
|
+
});
|
|
31
|
+
}
|
|
7
32
|
/**
|
|
8
33
|
* A predicate function that checks if an object is a {@link ValueParser}.
|
|
9
34
|
* @param object The object to check.
|
|
@@ -191,6 +216,197 @@ function choice(choices, options = {}) {
|
|
|
191
216
|
}
|
|
192
217
|
};
|
|
193
218
|
}
|
|
219
|
+
function biject(mapping) {
|
|
220
|
+
if (mapping === null || typeof mapping !== "object") throw new TypeError("Expected object.");
|
|
221
|
+
if (Array.isArray(mapping)) throw new TypeError("Expected object, got array.");
|
|
222
|
+
const keys = [];
|
|
223
|
+
for (const key in mapping) if (Object.prototype.hasOwnProperty.call(mapping, key)) keys.push(key);
|
|
224
|
+
if (keys.length < 1) throw new RangeError("Expected at least one biject entry.");
|
|
225
|
+
const source = choice(keys);
|
|
226
|
+
const forward = /* @__PURE__ */ new Map();
|
|
227
|
+
const reverse = /* @__PURE__ */ new Map();
|
|
228
|
+
for (const key of keys) {
|
|
229
|
+
const value = mapping[key];
|
|
230
|
+
if (reverse.has(value)) throw new RangeError(`Duplicate biject value for key ${JSON.stringify(key)}.`);
|
|
231
|
+
forward.set(key, value);
|
|
232
|
+
reverse.set(value, key);
|
|
233
|
+
}
|
|
234
|
+
const parser = transform(source, {
|
|
235
|
+
map(value) {
|
|
236
|
+
return forward.get(value);
|
|
237
|
+
},
|
|
238
|
+
unmap(value) {
|
|
239
|
+
const key = reverse.get(value);
|
|
240
|
+
if (key !== void 0) return key;
|
|
241
|
+
try {
|
|
242
|
+
return String(value);
|
|
243
|
+
} catch {
|
|
244
|
+
return "";
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
});
|
|
248
|
+
Object.defineProperty(parser, "validate", {
|
|
249
|
+
value(value) {
|
|
250
|
+
if (reverse.has(value)) return {
|
|
251
|
+
success: true,
|
|
252
|
+
value
|
|
253
|
+
};
|
|
254
|
+
let input;
|
|
255
|
+
try {
|
|
256
|
+
input = String(value);
|
|
257
|
+
} catch {
|
|
258
|
+
input = "";
|
|
259
|
+
}
|
|
260
|
+
const result = source.parse(input);
|
|
261
|
+
if (!result.success) return result;
|
|
262
|
+
return {
|
|
263
|
+
success: false,
|
|
264
|
+
error: formatDefaultChoiceError(input, keys)
|
|
265
|
+
};
|
|
266
|
+
},
|
|
267
|
+
configurable: true,
|
|
268
|
+
enumerable: true
|
|
269
|
+
});
|
|
270
|
+
return parser;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* Creates a value parser that transforms the result of another value parser.
|
|
274
|
+
*
|
|
275
|
+
* This is useful when an existing value parser already describes the accepted
|
|
276
|
+
* CLI spelling, suggestions, and error messages, but your application wants a
|
|
277
|
+
* different result type. For example, a string `choice()` can be transformed
|
|
278
|
+
* into an internal enum, tagged object, or other domain type.
|
|
279
|
+
*
|
|
280
|
+
* Unlike parser-level `map()`, value parser transformation needs an inverse
|
|
281
|
+
* mapping. The `unmap` function lets the transformed parser format values,
|
|
282
|
+
* validate fallback/default values, and reuse the wrapped parser's metadata
|
|
283
|
+
* without guessing how to serialize the transformed type.
|
|
284
|
+
*
|
|
285
|
+
* Transform functions are synchronous. If the wrapped parser is async, the
|
|
286
|
+
* returned parser is async too, but `map` and `unmap` still run synchronously
|
|
287
|
+
* after the wrapped parser resolves.
|
|
288
|
+
*
|
|
289
|
+
* @template M The execution mode of the wrapped parser.
|
|
290
|
+
* @template T The value type produced by the wrapped parser.
|
|
291
|
+
* @template U The value type produced by the transformed parser.
|
|
292
|
+
* @param parser The value parser to transform.
|
|
293
|
+
* @param mapping Mapping functions between the wrapped and transformed value
|
|
294
|
+
* types.
|
|
295
|
+
* @returns A value parser that accepts the same input as `parser` and produces
|
|
296
|
+
* transformed values.
|
|
297
|
+
* @since 1.2.0
|
|
298
|
+
*/
|
|
299
|
+
function transform(parser, mapping) {
|
|
300
|
+
const normalize = parser.normalize?.bind(parser);
|
|
301
|
+
const suggest = parser.suggest?.bind(parser);
|
|
302
|
+
const transformedChoices = parser.choices == null ? void 0 : Object.freeze(parser.choices.map((choice$1) => mapping.map(choice$1)));
|
|
303
|
+
const transformed = {
|
|
304
|
+
mode: parser.mode,
|
|
305
|
+
metavar: parser.metavar,
|
|
306
|
+
placeholder: void 0,
|
|
307
|
+
...transformedChoices == null ? {} : { choices: transformedChoices },
|
|
308
|
+
parse(input) {
|
|
309
|
+
return mapMaybePromiseByMode(parser.mode, parser.parse(input), (result) => transformValueParserResult(result, mapping));
|
|
310
|
+
},
|
|
311
|
+
format(value) {
|
|
312
|
+
return parser.format(mapping.unmap(value));
|
|
313
|
+
},
|
|
314
|
+
...normalize == null ? {} : { normalize(value) {
|
|
315
|
+
return mapping.map(normalize(mapping.unmap(value)));
|
|
316
|
+
} },
|
|
317
|
+
...suggest == null ? {} : { suggest(prefix) {
|
|
318
|
+
return suggest(prefix);
|
|
319
|
+
} }
|
|
320
|
+
};
|
|
321
|
+
Object.defineProperty(transformed, "placeholder", {
|
|
322
|
+
get() {
|
|
323
|
+
if (parser.placeholder === void 0) return void 0;
|
|
324
|
+
try {
|
|
325
|
+
return mapping.map(parser.placeholder);
|
|
326
|
+
} catch {
|
|
327
|
+
return void 0;
|
|
328
|
+
}
|
|
329
|
+
},
|
|
330
|
+
configurable: true,
|
|
331
|
+
enumerable: true
|
|
332
|
+
});
|
|
333
|
+
if (typeof parser.validate === "function") {
|
|
334
|
+
const validate = parser.validate.bind(parser);
|
|
335
|
+
Object.defineProperty(transformed, "validate", {
|
|
336
|
+
value(value) {
|
|
337
|
+
const result = validate(mapping.unmap(value));
|
|
338
|
+
return result.success ? {
|
|
339
|
+
success: true,
|
|
340
|
+
value: mapping.map(result.value)
|
|
341
|
+
} : result;
|
|
342
|
+
},
|
|
343
|
+
configurable: true,
|
|
344
|
+
enumerable: true
|
|
345
|
+
});
|
|
346
|
+
} else if (parser.mode === "sync") {
|
|
347
|
+
const syncParser = parser;
|
|
348
|
+
Object.defineProperty(transformed, "validate", {
|
|
349
|
+
value(value) {
|
|
350
|
+
let result;
|
|
351
|
+
try {
|
|
352
|
+
result = syncParser.parse(syncParser.format(mapping.unmap(value)));
|
|
353
|
+
} catch {
|
|
354
|
+
return {
|
|
355
|
+
success: true,
|
|
356
|
+
value
|
|
357
|
+
};
|
|
358
|
+
}
|
|
359
|
+
return result.success ? {
|
|
360
|
+
success: true,
|
|
361
|
+
value: mapping.map(result.value)
|
|
362
|
+
} : result;
|
|
363
|
+
},
|
|
364
|
+
configurable: true,
|
|
365
|
+
enumerable: true
|
|
366
|
+
});
|
|
367
|
+
}
|
|
368
|
+
if (isDerivedValueParser(parser)) preserveTransformedDerivedMetadata(transformed, parser, mapping);
|
|
369
|
+
return transformed;
|
|
370
|
+
}
|
|
371
|
+
function preserveTransformedDerivedMetadata(transformed, parser, mapping) {
|
|
372
|
+
Object.defineProperties(transformed, {
|
|
373
|
+
[derivedValueParserMarker]: {
|
|
374
|
+
value: true,
|
|
375
|
+
enumerable: true
|
|
376
|
+
},
|
|
377
|
+
[dependencyId]: {
|
|
378
|
+
value: parser[dependencyId],
|
|
379
|
+
enumerable: true
|
|
380
|
+
},
|
|
381
|
+
[parseWithDependency]: {
|
|
382
|
+
value(input, dependencyValue) {
|
|
383
|
+
return mapMaybePromiseByMode(parser.mode, parser[parseWithDependency](input, dependencyValue), (result) => transformValueParserResult(result, mapping));
|
|
384
|
+
},
|
|
385
|
+
enumerable: true
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
if (dependencyIds in parser && parser[dependencyIds] != null) Object.defineProperty(transformed, dependencyIds, {
|
|
389
|
+
value: parser[dependencyIds],
|
|
390
|
+
enumerable: true
|
|
391
|
+
});
|
|
392
|
+
if (defaultValues in parser && parser[defaultValues] != null) Object.defineProperty(transformed, defaultValues, {
|
|
393
|
+
value: parser[defaultValues],
|
|
394
|
+
enumerable: true
|
|
395
|
+
});
|
|
396
|
+
if (singleDefaultValue in parser && parser[singleDefaultValue] != null) Object.defineProperty(transformed, singleDefaultValue, {
|
|
397
|
+
value: parser[singleDefaultValue],
|
|
398
|
+
enumerable: true
|
|
399
|
+
});
|
|
400
|
+
if (suggestWithDependency in parser && parser[suggestWithDependency] != null) {
|
|
401
|
+
const suggest = parser[suggestWithDependency];
|
|
402
|
+
Object.defineProperty(transformed, suggestWithDependency, {
|
|
403
|
+
value(prefix, dependencyValue) {
|
|
404
|
+
return wrapIterableForMode(parser.mode, suggest(prefix, dependencyValue));
|
|
405
|
+
},
|
|
406
|
+
enumerable: true
|
|
407
|
+
});
|
|
408
|
+
}
|
|
409
|
+
}
|
|
194
410
|
/**
|
|
195
411
|
* Validates that an option value, if present, is a boolean.
|
|
196
412
|
* Throws a {@link TypeError} if the value is defined but not a boolean.
|
|
@@ -6336,4 +6552,4 @@ function plainObjectsEqual(a, b) {
|
|
|
6336
6552
|
}
|
|
6337
6553
|
|
|
6338
6554
|
//#endregion
|
|
6339
|
-
export { checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
|
|
6555
|
+
export { biject, checkBooleanOption, checkEnumOption, choice, cidr, color, cron, domain, email, ensureNonEmptyString, fileSize, firstOf, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, keyValue, locale, macAddress, port, portRange, semVer, socketAddress, string, transform, url, uuid };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@optique/core",
|
|
3
|
-
"version": "1.2.0-dev.
|
|
3
|
+
"version": "1.2.0-dev.2308",
|
|
4
4
|
"description": "Type-safe combinatorial command-line interface parser",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"CLI",
|
|
@@ -225,7 +225,7 @@
|
|
|
225
225
|
"fast-check": "^4.7.0",
|
|
226
226
|
"tsdown": "^0.13.0",
|
|
227
227
|
"typescript": "^5.8.3",
|
|
228
|
-
"@optique/env": "1.2.0-dev.
|
|
228
|
+
"@optique/env": "1.2.0-dev.2308+ddd68ea0"
|
|
229
229
|
},
|
|
230
230
|
"scripts": {
|
|
231
231
|
"build": "tsdown",
|
package/skills/optique/SKILL.md
CHANGED
|
@@ -40,8 +40,11 @@ Core rules
|
|
|
40
40
|
- Use `message` from *@optique/core/message* for descriptions, help text, and
|
|
41
41
|
custom errors. Prefer semantic message helpers such as `optionName()` and
|
|
42
42
|
`metavar()` over string concatenation when naming CLI elements.
|
|
43
|
-
- Use value parsers such as `integer()`, `choice()`, `
|
|
44
|
-
instead of validating raw strings after parsing. Use
|
|
43
|
+
- Use value parsers such as `integer()`, `choice()`, `biject()`, `url()`,
|
|
44
|
+
and `uuid()` instead of validating raw strings after parsing. Use
|
|
45
|
+
`biject()` for one-to-one string-to-value choices, and use `transform()`
|
|
46
|
+
when an existing value parser describes the accepted CLI spelling but your
|
|
47
|
+
app needs a different result type. Use `path()` from
|
|
45
48
|
`@optique/run/valueparser` for file-system paths. Write a custom
|
|
46
49
|
`{ mode, metavar, parse, format }` value parser only when the catalog does
|
|
47
50
|
not cover the domain.
|
|
@@ -138,9 +141,32 @@ if (result.success) {
|
|
|
138
141
|
Custom value parsers
|
|
139
142
|
--------------------
|
|
140
143
|
|
|
141
|
-
Prefer the built-in catalog first.
|
|
142
|
-
|
|
143
|
-
|
|
144
|
+
Prefer the built-in catalog first. If a one-to-one dictionary can describe the
|
|
145
|
+
input tokens and domain values, use `biject()`. If an existing parser already
|
|
146
|
+
accepts the right input syntax, wrap it with `transform()` before writing a
|
|
147
|
+
custom parser:
|
|
148
|
+
|
|
149
|
+
~~~~ typescript
|
|
150
|
+
import { biject, choice, transform } from "@optique/core/valueparser";
|
|
151
|
+
|
|
152
|
+
const exitCode = biject({
|
|
153
|
+
ok: 0,
|
|
154
|
+
warning: 1,
|
|
155
|
+
error: 2,
|
|
156
|
+
});
|
|
157
|
+
|
|
158
|
+
const logLevel = transform(choice(["debug", "info", "warn", "error"] as const), {
|
|
159
|
+
map(value) {
|
|
160
|
+
return value.toUpperCase() as "DEBUG" | "INFO" | "WARN" | "ERROR";
|
|
161
|
+
},
|
|
162
|
+
unmap(value) {
|
|
163
|
+
return value.toLowerCase() as "debug" | "info" | "warn" | "error";
|
|
164
|
+
},
|
|
165
|
+
});
|
|
166
|
+
~~~~
|
|
167
|
+
|
|
168
|
+
When a custom domain is needed, keep the validation in a value parser so help,
|
|
169
|
+
errors, defaults, prompts, and completion all see the same typed value.
|
|
144
170
|
|
|
145
171
|
~~~~ typescript
|
|
146
172
|
import { message } from "@optique/core/message";
|