@optique/core 1.1.0-dev.2070 → 1.1.0-dev.2083

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 CHANGED
@@ -72,6 +72,7 @@ exports.isNonEmptyString = require_nonempty.isNonEmptyString;
72
72
  exports.isSuggestionHidden = require_usage.isSuggestionHidden;
73
73
  exports.isUsageHidden = require_usage.isUsageHidden;
74
74
  exports.isValueParser = require_valueparser.isValueParser;
75
+ exports.json = require_valueparser.json;
75
76
  exports.lineBreak = require_message.lineBreak;
76
77
  exports.link = require_message.link;
77
78
  exports.locale = require_valueparser.locale;
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, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.cjs";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, 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 { ConditionalErrorOptions, ConditionalOptions, DuplicateOptionError, GroupOptions, LongestMatchErrorOptions, LongestMatchOptions, MergeOptions, NoMatchContext, ObjectErrorOptions, ObjectOptions, OrErrorOptions, OrOptions, TupleOptions, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.cjs";
@@ -12,4 +12,4 @@ import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMod
12
12
  import { CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.cjs";
13
13
  import { MultipleErrorOptions, MultipleOptions, WithDefaultError, WithDefaultOptions, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.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, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, 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, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, 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, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, 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, 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, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, 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, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, 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, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, 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, socketAddress, string, suggest, suggestAsync, suggestSync, text, 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, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, 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 { ConditionalErrorOptions, ConditionalOptions, DuplicateOptionError, GroupOptions, LongestMatchErrorOptions, LongestMatchOptions, MergeOptions, NoMatchContext, ObjectErrorOptions, ObjectOptions, OrErrorOptions, OrOptions, TupleOptions, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.js";
@@ -12,4 +12,4 @@ import { AnyDependencySource, CombineMode, CombinedDependencyMode, DependencyMod
12
12
  import { CommandSubConfig, ContextOptionsParam, ExtractRequiredOptions, OptionSubConfig, RunOptions, RunParserError, RunWithOptions, SubstituteParserValue, runParser, runParserAsync, runParserSync, runWith, runWithAsync, runWithSync } from "./facade.js";
13
13
  import { MultipleErrorOptions, MultipleOptions, WithDefaultError, WithDefaultOptions, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.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, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, 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, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, 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, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, 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, 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, CommandOptions, CommandSubConfig, ConditionalErrorOptions, ConditionalOptions, ContextOptionsParam, DeferredMap, 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, FlagErrorOptions, FlagOptions, FloatOptions, GroupOptions, HiddenVisibility, HostnameOptions, InferMode, InferValue, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, ParserResult, ParserValuePlaceholder, PassThroughFormat, PassThroughOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, Result, RunOptions, RunParserError, RunWithOptions, SemVer, SemVerOptionsObject, SemVerOptionsString, SemVerString, 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, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, 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, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
package/dist/index.js CHANGED
@@ -8,8 +8,8 @@ import { createParserContext, getDocPage, getDocPageAsync, getDocPageSync, parse
8
8
  import { DuplicateOptionError, concat, conditional, group, longestMatch, merge, object, or, tuple } from "./constructs.js";
9
9
  import { WithDefaultError, map, multiple, nonEmpty, optional, withDefault } from "./modifiers.js";
10
10
  import { ensureNonEmptyString, isNonEmptyString } from "./nonempty.js";
11
- import { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid } from "./valueparser.js";
11
+ import { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, 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, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, 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, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
15
+ export { DuplicateOptionError, RunParserError, WithDefaultError, argument, bash, checkBooleanOption, checkEnumOption, choice, cidr, cloneDocEntry, cloneUsage, cloneUsageTerm, color, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, fileSize, fish, flag, float, formatDocPage, formatMessage, formatUsage, formatUsageTerm, getAnnotations, getDocPage, getDocPageAsync, getDocPageSync, group, hostname, integer, ip, ipv4, ipv6, isDependencySource, isDerivedValueParser, isDocEntryHidden, isDocHidden, isNonEmptyString, isSuggestionHidden, isUsageHidden, isValueParser, json, 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, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
@@ -5235,6 +5235,140 @@ function semVer(options = {}) {
5235
5235
  }
5236
5236
  };
5237
5237
  }
5238
+ /**
5239
+ * Creates a {@link ValueParser} for parsing JSON-encoded strings from the
5240
+ * command line.
5241
+ *
5242
+ * The parser accepts any well-formed JSON string by default. Use the
5243
+ * `rootType` option to restrict which JSON root type is accepted and to
5244
+ * narrow the TypeScript return type accordingly.
5245
+ *
5246
+ * @example
5247
+ * ```typescript
5248
+ * // Accept any JSON value
5249
+ * const anyJson = json();
5250
+ *
5251
+ * // Accept only JSON objects (return type narrowed)
5252
+ * const objJson = json({ rootType: "object" });
5253
+ * ```
5254
+ *
5255
+ * @param options Optional configuration for the parser.
5256
+ * @returns A {@link ValueParser} that converts JSON-encoded strings to the
5257
+ * appropriate JavaScript type.
5258
+ * @throws {TypeError} If `options.metavar` is provided but is an empty string.
5259
+ * @throws {TypeError} If `options.rootType` is provided but is not one of the
5260
+ * six allowed values.
5261
+ * @throws {TypeError} If `options.placeholder` or any value nested within
5262
+ * it is a non-finite number (`Infinity`, `-Infinity`, or `NaN`).
5263
+ * @throws {TypeError} If `options.placeholder` is provided with a `rootType`
5264
+ * but its JSON type does not match the `rootType`.
5265
+ * @throws {TypeError} If the returned parser's `format()` method is called
5266
+ * with a value that contains a non-finite number anywhere in its structure.
5267
+ * @since 1.1.0
5268
+ */
5269
+ function json(options) {
5270
+ const metavar = options?.metavar ?? "JSON";
5271
+ require_nonempty.ensureNonEmptyString(metavar);
5272
+ checkEnumOption(options, "rootType", [
5273
+ "string",
5274
+ "number",
5275
+ "boolean",
5276
+ "null",
5277
+ "object",
5278
+ "array"
5279
+ ]);
5280
+ const rootType = options?.rootType;
5281
+ const invalidJsonError = options?.errors?.invalidJson;
5282
+ const invalidRootTypeError = options?.errors?.invalidRootType;
5283
+ if (options?.placeholder !== void 0) {
5284
+ const p = options.placeholder;
5285
+ const nonFinitePlaceholder = findNonFiniteNumber(p);
5286
+ if (nonFinitePlaceholder !== void 0) throw new TypeError(`Expected placeholder to contain only finite numbers, but found ${String(nonFinitePlaceholder)}.`);
5287
+ if (rootType != null && jsonTypeOf(p) !== rootType) throw new TypeError(`Expected placeholder to be a JSON ${rootType}, but got ${jsonTypeOf(p)}.`);
5288
+ }
5289
+ const defaultPlaceholder = rootType === "string" ? "" : rootType === "number" ? 0 : rootType === "boolean" ? false : rootType === "object" ? {} : rootType === "array" ? [] : null;
5290
+ const placeholder = options?.placeholder ?? defaultPlaceholder;
5291
+ return {
5292
+ mode: "sync",
5293
+ metavar,
5294
+ placeholder,
5295
+ parse(input) {
5296
+ let value;
5297
+ try {
5298
+ value = JSON.parse(input);
5299
+ } catch (e) {
5300
+ const err = e instanceof Error ? e : new Error(String(e));
5301
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [require_message.text(`Not a valid JSON: ${err.message}`)];
5302
+ return {
5303
+ success: false,
5304
+ error
5305
+ };
5306
+ }
5307
+ const nonFinite = findNonFiniteNumber(value);
5308
+ if (nonFinite !== void 0) {
5309
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [require_message.text(`Not a valid JSON: number out of range.`)];
5310
+ return {
5311
+ success: false,
5312
+ error
5313
+ };
5314
+ }
5315
+ if (rootType != null) {
5316
+ const actual = jsonTypeOf(value);
5317
+ if (actual !== rootType) {
5318
+ const error = invalidRootTypeError instanceof Function ? invalidRootTypeError(value, rootType) : invalidRootTypeError ?? [require_message.text(`Expected JSON ${rootType}, but got ${actual}.`)];
5319
+ return {
5320
+ success: false,
5321
+ error
5322
+ };
5323
+ }
5324
+ }
5325
+ return {
5326
+ success: true,
5327
+ value
5328
+ };
5329
+ },
5330
+ format(value) {
5331
+ const nonFinite = findNonFiniteNumber(value);
5332
+ if (nonFinite !== void 0) throw new TypeError(`Expected a finite JSON number, but got ${String(nonFinite)}.`);
5333
+ return JSON.stringify(value);
5334
+ }
5335
+ };
5336
+ }
5337
+ function jsonTypeOf(value) {
5338
+ if (value === null) return "null";
5339
+ if (Array.isArray(value)) return "array";
5340
+ return typeof value;
5341
+ }
5342
+ /**
5343
+ * Finds the first non-finite number (`NaN`, `Infinity`, or `-Infinity`)
5344
+ * anywhere in a JSON structure.
5345
+ *
5346
+ * Uses an explicit stack rather than recursion to avoid call-stack overflows
5347
+ * on deeply nested inputs. Tracks visited objects to handle circular
5348
+ * references without looping forever.
5349
+ *
5350
+ * @returns The first non-finite number found, or `undefined` if all numbers
5351
+ * in the structure are finite.
5352
+ */
5353
+ function findNonFiniteNumber(root) {
5354
+ const stack = [root];
5355
+ const seen = /* @__PURE__ */ new Set();
5356
+ while (stack.length > 0) {
5357
+ const value = stack.pop();
5358
+ if (typeof value === "number") {
5359
+ if (!Number.isFinite(value)) return value;
5360
+ } else if (Array.isArray(value)) {
5361
+ if (seen.has(value)) continue;
5362
+ seen.add(value);
5363
+ for (const item of value) stack.push(item);
5364
+ } else if (value !== null && typeof value === "object") {
5365
+ if (seen.has(value)) continue;
5366
+ seen.add(value);
5367
+ for (const item of Object.values(value)) stack.push(item);
5368
+ }
5369
+ }
5370
+ return void 0;
5371
+ }
5238
5372
 
5239
5373
  //#endregion
5240
5374
  exports.checkBooleanOption = checkBooleanOption;
@@ -5254,6 +5388,7 @@ exports.ipv4 = ipv4;
5254
5388
  exports.ipv6 = ipv6;
5255
5389
  exports.isNonEmptyString = require_nonempty.isNonEmptyString;
5256
5390
  exports.isValueParser = isValueParser;
5391
+ exports.json = json;
5257
5392
  exports.locale = locale;
5258
5393
  exports.macAddress = macAddress;
5259
5394
  exports.port = port;
@@ -2559,5 +2559,157 @@ declare function semVer(options?: SemVerOptionsString): ValueParser<"sync", SemV
2559
2559
  * @since 1.1.0
2560
2560
  */
2561
2561
  declare function semVer(options: SemVerOptionsObject): ValueParser<"sync", SemVer>;
2562
+ /**
2563
+ * Any JSON-serializable value.
2564
+ *
2565
+ * This type is a TypeScript approximation of JSON data values. Note that
2566
+ * certain JavaScript distinctions are not preserved through serialization:
2567
+ * for example, `-0` serializes as `"0"`, so a round-trip through
2568
+ * `format()` and `parse()` may return `0` instead.
2569
+ *
2570
+ * @since 1.1.0
2571
+ */
2572
+ type Json = string | number | boolean | null | {
2573
+ readonly [property: string]: Json;
2574
+ } | readonly Json[];
2575
+ /**
2576
+ * Options for creating a {@link json} value parser.
2577
+ *
2578
+ * @since 1.1.0
2579
+ */
2580
+ interface JsonOptions {
2581
+ /**
2582
+ * The metavariable name for this parser. This is used in help messages to
2583
+ * indicate what kind of value this parser expects. Usually a single
2584
+ * word in uppercase, like `DATA` or `CONFIG`.
2585
+ * @default `"JSON"`
2586
+ */
2587
+ readonly metavar?: NonEmptyString;
2588
+ /**
2589
+ * A custom placeholder value used during deferred prompt resolution.
2590
+ * @default Depends on `rootType`: `null` when unset, `""` for `"string"`,
2591
+ * `0` for `"number"`, `false` for `"boolean"`, `null` for `"null"`,
2592
+ * `{}` for `"object"`, `[]` for `"array"`.
2593
+ * @since 1.1.0
2594
+ */
2595
+ readonly placeholder?: Json;
2596
+ /**
2597
+ * Restricts the expected JSON root type. When set, the parser rejects
2598
+ * JSON values whose root type does not match and narrows the TypeScript
2599
+ * return type accordingly.
2600
+ *
2601
+ * @since 1.1.0
2602
+ */
2603
+ readonly rootType?: "string" | "number" | "boolean" | "null" | "object" | "array";
2604
+ /**
2605
+ * Custom error messages for JSON parsing failures.
2606
+ *
2607
+ * @since 1.1.0
2608
+ */
2609
+ readonly errors?: {
2610
+ /**
2611
+ * Custom error message when the input is not valid JSON.
2612
+ * Can be a static message or a function that receives the raw input.
2613
+ * @since 1.1.0
2614
+ */
2615
+ readonly invalidJson?: Message | ((input: string) => Message);
2616
+ /**
2617
+ * Custom error message when the parsed JSON value does not match the
2618
+ * expected `rootType`. Can be a static message or a function that
2619
+ * receives the parsed value and the expected root type name.
2620
+ * @since 1.1.0
2621
+ */
2622
+ readonly invalidRootType?: Message | ((value: Json, expected: string) => Message);
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2627
+ * a `string`.
2628
+ *
2629
+ * @param options Configuration options including `rootType: "string"`.
2630
+ * @returns A parser whose successful value is typed as `string`.
2631
+ * @since 1.1.0
2632
+ */
2633
+ declare function json(options: JsonOptions & {
2634
+ readonly rootType: "string";
2635
+ readonly placeholder?: string;
2636
+ }): ValueParser<"sync", string>;
2637
+ /**
2638
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2639
+ * a `number`.
2640
+ *
2641
+ * @param options Configuration options including `rootType: "number"`.
2642
+ * @returns A parser whose successful value is typed as `number`.
2643
+ * @since 1.1.0
2644
+ */
2645
+ declare function json(options: JsonOptions & {
2646
+ readonly rootType: "number";
2647
+ readonly placeholder?: number;
2648
+ }): ValueParser<"sync", number>;
2649
+ /**
2650
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2651
+ * a `boolean`.
2652
+ *
2653
+ * @param options Configuration options including `rootType: "boolean"`.
2654
+ * @returns A parser whose successful value is typed as `boolean`.
2655
+ * @since 1.1.0
2656
+ */
2657
+ declare function json(options: JsonOptions & {
2658
+ readonly rootType: "boolean";
2659
+ readonly placeholder?: boolean;
2660
+ }): ValueParser<"sync", boolean>;
2661
+ /**
2662
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2663
+ * `null`.
2664
+ *
2665
+ * @param options Configuration options including `rootType: "null"`.
2666
+ * @returns A parser whose successful value is typed as `null`.
2667
+ * @since 1.1.0
2668
+ */
2669
+ declare function json(options: JsonOptions & {
2670
+ readonly rootType: "null";
2671
+ readonly placeholder?: null;
2672
+ }): ValueParser<"sync", null>;
2673
+ /**
2674
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2675
+ * a plain JSON object.
2676
+ *
2677
+ * @param options Configuration options including `rootType: "object"`.
2678
+ * @returns A parser whose successful value is typed as
2679
+ * `{ readonly [property: string]: Json }`.
2680
+ * @since 1.1.0
2681
+ */
2682
+ declare function json(options: JsonOptions & {
2683
+ readonly rootType: "object";
2684
+ readonly placeholder?: {
2685
+ readonly [property: string]: Json;
2686
+ };
2687
+ }): ValueParser<"sync", {
2688
+ readonly [property: string]: Json;
2689
+ }>;
2690
+ /**
2691
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2692
+ * a JSON array.
2693
+ *
2694
+ * @param options Configuration options including `rootType: "array"`.
2695
+ * @returns A parser whose successful value is typed as `readonly Json[]`.
2696
+ * @since 1.1.0
2697
+ */
2698
+ declare function json(options: JsonOptions & {
2699
+ readonly rootType: "array";
2700
+ readonly placeholder?: readonly Json[];
2701
+ }): ValueParser<"sync", readonly Json[]>;
2702
+ /**
2703
+ * Creates a {@link ValueParser} that parses JSON-encoded strings into any
2704
+ * {@link Json} value (object, array, string, number, boolean, or null).
2705
+ *
2706
+ * Also accepts a pre-typed `JsonOptions` variable when the `rootType` is not
2707
+ * known at compile time; the return type is the widened {@link Json} union.
2708
+ *
2709
+ * @param options Optional configuration for the parser.
2710
+ * @returns A parser whose successful value is typed as {@link Json}.
2711
+ * @since 1.1.0
2712
+ */
2713
+ declare function json(options?: JsonOptions): ValueParser<"sync", Json>;
2562
2714
  //#endregion
2563
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
2715
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
@@ -2559,5 +2559,157 @@ declare function semVer(options?: SemVerOptionsString): ValueParser<"sync", SemV
2559
2559
  * @since 1.1.0
2560
2560
  */
2561
2561
  declare function semVer(options: SemVerOptionsObject): ValueParser<"sync", SemVer>;
2562
+ /**
2563
+ * Any JSON-serializable value.
2564
+ *
2565
+ * This type is a TypeScript approximation of JSON data values. Note that
2566
+ * certain JavaScript distinctions are not preserved through serialization:
2567
+ * for example, `-0` serializes as `"0"`, so a round-trip through
2568
+ * `format()` and `parse()` may return `0` instead.
2569
+ *
2570
+ * @since 1.1.0
2571
+ */
2572
+ type Json = string | number | boolean | null | {
2573
+ readonly [property: string]: Json;
2574
+ } | readonly Json[];
2575
+ /**
2576
+ * Options for creating a {@link json} value parser.
2577
+ *
2578
+ * @since 1.1.0
2579
+ */
2580
+ interface JsonOptions {
2581
+ /**
2582
+ * The metavariable name for this parser. This is used in help messages to
2583
+ * indicate what kind of value this parser expects. Usually a single
2584
+ * word in uppercase, like `DATA` or `CONFIG`.
2585
+ * @default `"JSON"`
2586
+ */
2587
+ readonly metavar?: NonEmptyString;
2588
+ /**
2589
+ * A custom placeholder value used during deferred prompt resolution.
2590
+ * @default Depends on `rootType`: `null` when unset, `""` for `"string"`,
2591
+ * `0` for `"number"`, `false` for `"boolean"`, `null` for `"null"`,
2592
+ * `{}` for `"object"`, `[]` for `"array"`.
2593
+ * @since 1.1.0
2594
+ */
2595
+ readonly placeholder?: Json;
2596
+ /**
2597
+ * Restricts the expected JSON root type. When set, the parser rejects
2598
+ * JSON values whose root type does not match and narrows the TypeScript
2599
+ * return type accordingly.
2600
+ *
2601
+ * @since 1.1.0
2602
+ */
2603
+ readonly rootType?: "string" | "number" | "boolean" | "null" | "object" | "array";
2604
+ /**
2605
+ * Custom error messages for JSON parsing failures.
2606
+ *
2607
+ * @since 1.1.0
2608
+ */
2609
+ readonly errors?: {
2610
+ /**
2611
+ * Custom error message when the input is not valid JSON.
2612
+ * Can be a static message or a function that receives the raw input.
2613
+ * @since 1.1.0
2614
+ */
2615
+ readonly invalidJson?: Message | ((input: string) => Message);
2616
+ /**
2617
+ * Custom error message when the parsed JSON value does not match the
2618
+ * expected `rootType`. Can be a static message or a function that
2619
+ * receives the parsed value and the expected root type name.
2620
+ * @since 1.1.0
2621
+ */
2622
+ readonly invalidRootType?: Message | ((value: Json, expected: string) => Message);
2623
+ };
2624
+ }
2625
+ /**
2626
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2627
+ * a `string`.
2628
+ *
2629
+ * @param options Configuration options including `rootType: "string"`.
2630
+ * @returns A parser whose successful value is typed as `string`.
2631
+ * @since 1.1.0
2632
+ */
2633
+ declare function json(options: JsonOptions & {
2634
+ readonly rootType: "string";
2635
+ readonly placeholder?: string;
2636
+ }): ValueParser<"sync", string>;
2637
+ /**
2638
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2639
+ * a `number`.
2640
+ *
2641
+ * @param options Configuration options including `rootType: "number"`.
2642
+ * @returns A parser whose successful value is typed as `number`.
2643
+ * @since 1.1.0
2644
+ */
2645
+ declare function json(options: JsonOptions & {
2646
+ readonly rootType: "number";
2647
+ readonly placeholder?: number;
2648
+ }): ValueParser<"sync", number>;
2649
+ /**
2650
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2651
+ * a `boolean`.
2652
+ *
2653
+ * @param options Configuration options including `rootType: "boolean"`.
2654
+ * @returns A parser whose successful value is typed as `boolean`.
2655
+ * @since 1.1.0
2656
+ */
2657
+ declare function json(options: JsonOptions & {
2658
+ readonly rootType: "boolean";
2659
+ readonly placeholder?: boolean;
2660
+ }): ValueParser<"sync", boolean>;
2661
+ /**
2662
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2663
+ * `null`.
2664
+ *
2665
+ * @param options Configuration options including `rootType: "null"`.
2666
+ * @returns A parser whose successful value is typed as `null`.
2667
+ * @since 1.1.0
2668
+ */
2669
+ declare function json(options: JsonOptions & {
2670
+ readonly rootType: "null";
2671
+ readonly placeholder?: null;
2672
+ }): ValueParser<"sync", null>;
2673
+ /**
2674
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2675
+ * a plain JSON object.
2676
+ *
2677
+ * @param options Configuration options including `rootType: "object"`.
2678
+ * @returns A parser whose successful value is typed as
2679
+ * `{ readonly [property: string]: Json }`.
2680
+ * @since 1.1.0
2681
+ */
2682
+ declare function json(options: JsonOptions & {
2683
+ readonly rootType: "object";
2684
+ readonly placeholder?: {
2685
+ readonly [property: string]: Json;
2686
+ };
2687
+ }): ValueParser<"sync", {
2688
+ readonly [property: string]: Json;
2689
+ }>;
2690
+ /**
2691
+ * Creates a {@link ValueParser} that parses JSON-encoded strings and returns
2692
+ * a JSON array.
2693
+ *
2694
+ * @param options Configuration options including `rootType: "array"`.
2695
+ * @returns A parser whose successful value is typed as `readonly Json[]`.
2696
+ * @since 1.1.0
2697
+ */
2698
+ declare function json(options: JsonOptions & {
2699
+ readonly rootType: "array";
2700
+ readonly placeholder?: readonly Json[];
2701
+ }): ValueParser<"sync", readonly Json[]>;
2702
+ /**
2703
+ * Creates a {@link ValueParser} that parses JSON-encoded strings into any
2704
+ * {@link Json} value (object, array, string, number, boolean, or null).
2705
+ *
2706
+ * Also accepts a pre-typed `JsonOptions` variable when the `rootType` is not
2707
+ * known at compile time; the return type is the widened {@link Json} union.
2708
+ *
2709
+ * @param options Optional configuration for the parser.
2710
+ * @returns A parser whose successful value is typed as {@link Json}.
2711
+ * @since 1.1.0
2712
+ */
2713
+ declare function json(options?: JsonOptions): ValueParser<"sync", Json>;
2562
2714
  //#endregion
2563
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, 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, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
2715
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, Color, ColorFormat, ColorOptions, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, Json, JsonOptions, 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, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
@@ -5235,6 +5235,140 @@ function semVer(options = {}) {
5235
5235
  }
5236
5236
  };
5237
5237
  }
5238
+ /**
5239
+ * Creates a {@link ValueParser} for parsing JSON-encoded strings from the
5240
+ * command line.
5241
+ *
5242
+ * The parser accepts any well-formed JSON string by default. Use the
5243
+ * `rootType` option to restrict which JSON root type is accepted and to
5244
+ * narrow the TypeScript return type accordingly.
5245
+ *
5246
+ * @example
5247
+ * ```typescript
5248
+ * // Accept any JSON value
5249
+ * const anyJson = json();
5250
+ *
5251
+ * // Accept only JSON objects (return type narrowed)
5252
+ * const objJson = json({ rootType: "object" });
5253
+ * ```
5254
+ *
5255
+ * @param options Optional configuration for the parser.
5256
+ * @returns A {@link ValueParser} that converts JSON-encoded strings to the
5257
+ * appropriate JavaScript type.
5258
+ * @throws {TypeError} If `options.metavar` is provided but is an empty string.
5259
+ * @throws {TypeError} If `options.rootType` is provided but is not one of the
5260
+ * six allowed values.
5261
+ * @throws {TypeError} If `options.placeholder` or any value nested within
5262
+ * it is a non-finite number (`Infinity`, `-Infinity`, or `NaN`).
5263
+ * @throws {TypeError} If `options.placeholder` is provided with a `rootType`
5264
+ * but its JSON type does not match the `rootType`.
5265
+ * @throws {TypeError} If the returned parser's `format()` method is called
5266
+ * with a value that contains a non-finite number anywhere in its structure.
5267
+ * @since 1.1.0
5268
+ */
5269
+ function json(options) {
5270
+ const metavar = options?.metavar ?? "JSON";
5271
+ ensureNonEmptyString(metavar);
5272
+ checkEnumOption(options, "rootType", [
5273
+ "string",
5274
+ "number",
5275
+ "boolean",
5276
+ "null",
5277
+ "object",
5278
+ "array"
5279
+ ]);
5280
+ const rootType = options?.rootType;
5281
+ const invalidJsonError = options?.errors?.invalidJson;
5282
+ const invalidRootTypeError = options?.errors?.invalidRootType;
5283
+ if (options?.placeholder !== void 0) {
5284
+ const p = options.placeholder;
5285
+ const nonFinitePlaceholder = findNonFiniteNumber(p);
5286
+ if (nonFinitePlaceholder !== void 0) throw new TypeError(`Expected placeholder to contain only finite numbers, but found ${String(nonFinitePlaceholder)}.`);
5287
+ if (rootType != null && jsonTypeOf(p) !== rootType) throw new TypeError(`Expected placeholder to be a JSON ${rootType}, but got ${jsonTypeOf(p)}.`);
5288
+ }
5289
+ const defaultPlaceholder = rootType === "string" ? "" : rootType === "number" ? 0 : rootType === "boolean" ? false : rootType === "object" ? {} : rootType === "array" ? [] : null;
5290
+ const placeholder = options?.placeholder ?? defaultPlaceholder;
5291
+ return {
5292
+ mode: "sync",
5293
+ metavar,
5294
+ placeholder,
5295
+ parse(input) {
5296
+ let value;
5297
+ try {
5298
+ value = JSON.parse(input);
5299
+ } catch (e) {
5300
+ const err = e instanceof Error ? e : new Error(String(e));
5301
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [text(`Not a valid JSON: ${err.message}`)];
5302
+ return {
5303
+ success: false,
5304
+ error
5305
+ };
5306
+ }
5307
+ const nonFinite = findNonFiniteNumber(value);
5308
+ if (nonFinite !== void 0) {
5309
+ const error = invalidJsonError instanceof Function ? invalidJsonError(input) : invalidJsonError ?? [text(`Not a valid JSON: number out of range.`)];
5310
+ return {
5311
+ success: false,
5312
+ error
5313
+ };
5314
+ }
5315
+ if (rootType != null) {
5316
+ const actual = jsonTypeOf(value);
5317
+ if (actual !== rootType) {
5318
+ const error = invalidRootTypeError instanceof Function ? invalidRootTypeError(value, rootType) : invalidRootTypeError ?? [text(`Expected JSON ${rootType}, but got ${actual}.`)];
5319
+ return {
5320
+ success: false,
5321
+ error
5322
+ };
5323
+ }
5324
+ }
5325
+ return {
5326
+ success: true,
5327
+ value
5328
+ };
5329
+ },
5330
+ format(value) {
5331
+ const nonFinite = findNonFiniteNumber(value);
5332
+ if (nonFinite !== void 0) throw new TypeError(`Expected a finite JSON number, but got ${String(nonFinite)}.`);
5333
+ return JSON.stringify(value);
5334
+ }
5335
+ };
5336
+ }
5337
+ function jsonTypeOf(value) {
5338
+ if (value === null) return "null";
5339
+ if (Array.isArray(value)) return "array";
5340
+ return typeof value;
5341
+ }
5342
+ /**
5343
+ * Finds the first non-finite number (`NaN`, `Infinity`, or `-Infinity`)
5344
+ * anywhere in a JSON structure.
5345
+ *
5346
+ * Uses an explicit stack rather than recursion to avoid call-stack overflows
5347
+ * on deeply nested inputs. Tracks visited objects to handle circular
5348
+ * references without looping forever.
5349
+ *
5350
+ * @returns The first non-finite number found, or `undefined` if all numbers
5351
+ * in the structure are finite.
5352
+ */
5353
+ function findNonFiniteNumber(root) {
5354
+ const stack = [root];
5355
+ const seen = /* @__PURE__ */ new Set();
5356
+ while (stack.length > 0) {
5357
+ const value = stack.pop();
5358
+ if (typeof value === "number") {
5359
+ if (!Number.isFinite(value)) return value;
5360
+ } else if (Array.isArray(value)) {
5361
+ if (seen.has(value)) continue;
5362
+ seen.add(value);
5363
+ for (const item of value) stack.push(item);
5364
+ } else if (value !== null && typeof value === "object") {
5365
+ if (seen.has(value)) continue;
5366
+ seen.add(value);
5367
+ for (const item of Object.values(value)) stack.push(item);
5368
+ }
5369
+ }
5370
+ return void 0;
5371
+ }
5238
5372
 
5239
5373
  //#endregion
5240
- export { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
5374
+ export { checkBooleanOption, checkEnumOption, choice, cidr, color, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, json, locale, macAddress, port, portRange, semVer, socketAddress, string, url, uuid };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@optique/core",
3
- "version": "1.1.0-dev.2070",
3
+ "version": "1.1.0-dev.2083",
4
4
  "description": "Type-safe combinatorial command-line interface parser",
5
5
  "keywords": [
6
6
  "CLI",