@optique/core 1.1.0-dev.2053 → 1.1.0-dev.2057

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
@@ -45,6 +45,7 @@ exports.extractCommandNames = require_usage.extractCommandNames;
45
45
  exports.extractLiteralValues = require_usage.extractLiteralValues;
46
46
  exports.extractOptionNames = require_usage.extractOptionNames;
47
47
  exports.fail = require_primitives.fail;
48
+ exports.fileSize = require_valueparser.fileSize;
48
49
  exports.fish = require_completion.fish;
49
50
  exports.flag = require_primitives.flag;
50
51
  exports.float = require_valueparser.float;
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, DeferredMap, DomainOptions, EmailOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid } from "./valueparser.cjs";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, 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, 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, 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, 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, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, 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, 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, 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, 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, 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, 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, DeferredMap, DomainOptions, EmailOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid } from "./valueparser.js";
6
+ import { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, DeferredMap, DomainOptions, EmailOptions, FileSizeOptions, FileSizeOptionsBigInt, FileSizeOptionsNumber, FileSizeUnit, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, 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, 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, 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, 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, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, 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, 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, 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, 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, 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, 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, domain, email, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid } from "./valueparser.js";
11
+ import { checkBooleanOption, checkEnumOption, choice, cidr, domain, email, fileSize, float, hostname, integer, ip, ipv4, ipv6, isValueParser, locale, macAddress, port, portRange, 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, command, commandLine, concat, conditional, constant, createParserContext, deduplicateDocEntries, deduplicateDocFragments, dependency, deriveFrom, deriveFromAsync, deriveFromSync, domain, email, ensureNonEmptyString, envVar, extractArgumentMetavars, extractCommandNames, extractLiteralValues, extractOptionNames, fail, 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, 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, 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, socketAddress, string, suggest, suggestAsync, suggestSync, text, tuple, url, uuid, value, valueSet, values, withDefault, zsh };
@@ -504,6 +504,337 @@ function float(options = {}) {
504
504
  }
505
505
  };
506
506
  }
507
+ const SI_MULTIPLIERS = {
508
+ b: 1,
509
+ kb: 1e3,
510
+ mb: 1e6,
511
+ gb: 1e9,
512
+ tb: 1e12,
513
+ pb: 1e15,
514
+ eb: 1e18
515
+ };
516
+ const IEC_MULTIPLIERS = {
517
+ b: 1,
518
+ kb: 1024,
519
+ mb: 1024 ** 2,
520
+ gb: 1024 ** 3,
521
+ tb: 1024 ** 4,
522
+ pb: 1024 ** 5,
523
+ eb: 1024 ** 6,
524
+ kib: 1024,
525
+ mib: 1024 ** 2,
526
+ gib: 1024 ** 3,
527
+ tib: 1024 ** 4,
528
+ pib: 1024 ** 5,
529
+ eib: 1024 ** 6
530
+ };
531
+ const IEC_ONLY_MULTIPLIERS = {
532
+ kib: 1024,
533
+ mib: 1024 ** 2,
534
+ gib: 1024 ** 3,
535
+ tib: 1024 ** 4,
536
+ pib: 1024 ** 5,
537
+ eib: 1024 ** 6
538
+ };
539
+ const FILE_SIZE_REGEX = /^([+-]?(?:\d+\.?\d*|\d*\.\d+))\s*([a-zA-Z]*)$/;
540
+ /**
541
+ * Formats `bytes` using the most readable unit from the given ordered list.
542
+ * Falls back to `"${bytes}B"`.
543
+ *
544
+ * A unit is chosen only when the formatted value round-trips exactly: the
545
+ * rounded quotient must lie in [1, 1000) and `rounded * size === bytes` must
546
+ * hold in float64 arithmetic. This guarantees `parse(format(x)) === x`.
547
+ */
548
+ function formatWithUnits(bytes, units) {
549
+ if (bytes === 0) return "0B";
550
+ const absBytes = Math.abs(bytes);
551
+ for (const [unit, size] of units) {
552
+ if (absBytes < size) continue;
553
+ const v = bytes / size;
554
+ const rounded = Math.round(v * 100) / 100;
555
+ const absRounded = Math.abs(rounded);
556
+ if (absRounded >= 1 && absRounded < 1e3 && rounded * size === bytes) return `${rounded}${unit}`;
557
+ }
558
+ return `${bytes}B`;
559
+ }
560
+ const FORMAT_UNITS_DEFAULT = [
561
+ ["EiB", 1024 ** 6],
562
+ ["PiB", 1024 ** 5],
563
+ ["TiB", 1024 ** 4],
564
+ ["GiB", 1024 ** 3],
565
+ ["MiB", 1024 ** 2],
566
+ ["KiB", 1024],
567
+ ["EB", 1e18],
568
+ ["PB", 1e15],
569
+ ["TB", 1e12],
570
+ ["GB", 1e9],
571
+ ["MB", 1e6],
572
+ ["KB", 1e3]
573
+ ];
574
+ const FORMAT_UNITS_SI_AS_BINARY = [
575
+ ["EB", 1024 ** 6],
576
+ ["PB", 1024 ** 5],
577
+ ["TB", 1024 ** 4],
578
+ ["GB", 1024 ** 3],
579
+ ["MB", 1024 ** 2],
580
+ ["KB", 1024]
581
+ ];
582
+ const BIGINT_SI_MULTIPLIERS = {
583
+ b: 1n,
584
+ kb: 1000n,
585
+ mb: 1000000n,
586
+ gb: 1000000000n,
587
+ tb: 1000000000000n,
588
+ pb: 1000000000000000n,
589
+ eb: 1000000000000000000n
590
+ };
591
+ const BIGINT_IEC_MULTIPLIERS = {
592
+ b: 1n,
593
+ kb: 1024n,
594
+ mb: 1024n ** 2n,
595
+ gb: 1024n ** 3n,
596
+ tb: 1024n ** 4n,
597
+ pb: 1024n ** 5n,
598
+ eb: 1024n ** 6n,
599
+ kib: 1024n,
600
+ mib: 1024n ** 2n,
601
+ gib: 1024n ** 3n,
602
+ tib: 1024n ** 4n,
603
+ pib: 1024n ** 5n,
604
+ eib: 1024n ** 6n
605
+ };
606
+ const BIGINT_IEC_ONLY_MULTIPLIERS = {
607
+ kib: 1024n,
608
+ mib: 1024n ** 2n,
609
+ gib: 1024n ** 3n,
610
+ tib: 1024n ** 4n,
611
+ pib: 1024n ** 5n,
612
+ eib: 1024n ** 6n
613
+ };
614
+ const BIGINT_FORMAT_UNITS_DEFAULT = [
615
+ ["EiB", 1024n ** 6n],
616
+ ["PiB", 1024n ** 5n],
617
+ ["TiB", 1024n ** 4n],
618
+ ["GiB", 1024n ** 3n],
619
+ ["MiB", 1024n ** 2n],
620
+ ["KiB", 1024n],
621
+ ["EB", 1000000000000000000n],
622
+ ["PB", 1000000000000000n],
623
+ ["TB", 1000000000000n],
624
+ ["GB", 1000000000n],
625
+ ["MB", 1000000n],
626
+ ["KB", 1000n]
627
+ ];
628
+ const BIGINT_FORMAT_UNITS_SI_AS_BINARY = [
629
+ ["EB", 1024n ** 6n],
630
+ ["PB", 1024n ** 5n],
631
+ ["TB", 1024n ** 4n],
632
+ ["GB", 1024n ** 3n],
633
+ ["MB", 1024n ** 2n],
634
+ ["KB", 1024n]
635
+ ];
636
+ /**
637
+ * Formats a bigint byte count using the most readable unit. Falls back to
638
+ * `"${value}B"`. Tries exact integers, then 1 and 2 decimal places.
639
+ */
640
+ function formatBigIntBytes(value, units) {
641
+ if (value === 0n) return "0B";
642
+ const absValue = value < 0n ? -value : value;
643
+ for (const [unit, size] of units) {
644
+ if (absValue < size) continue;
645
+ if (value % size === 0n) {
646
+ const v = value / size;
647
+ const absV = v < 0n ? -v : v;
648
+ if (absV >= 1n && absV < 1000n) return `${v}${unit}`;
649
+ }
650
+ const v100 = value * 100n;
651
+ if (v100 % size === 0n) {
652
+ const q = v100 / size;
653
+ const absQ = q < 0n ? -q : q;
654
+ if (absQ >= 100n && absQ < 100000n) {
655
+ const intPart = q / 100n;
656
+ const decPart = absQ % 100n;
657
+ if (decPart % 10n === 0n) return `${intPart}.${decPart / 10n}${unit}`;
658
+ return `${intPart}.${String(decPart).padStart(2, "0")}${unit}`;
659
+ }
660
+ }
661
+ }
662
+ return `${value}B`;
663
+ }
664
+ /**
665
+ * Core computation: parses `numStr` as a decimal rational, multiplies by
666
+ * `mBig`, and returns the exact integer result as a `bigint`, or `null` when
667
+ * the result would be fractional. The safe-integer range check is NOT applied
668
+ * here; callers add it as needed.
669
+ */
670
+ function parseExactBytesRaw(numStr, mBig) {
671
+ const negative = numStr.startsWith("-");
672
+ const absStr = numStr.startsWith("+") || numStr.startsWith("-") ? numStr.slice(1) : numStr;
673
+ const dotIdx = absStr.indexOf(".");
674
+ const intPart = dotIdx < 0 ? absStr : absStr.slice(0, dotIdx);
675
+ const fracPart = dotIdx < 0 ? "" : absStr.slice(dotIdx + 1);
676
+ const numeratorStr = ((intPart || "0") + fracPart).replace(/^0+/, "") || "0";
677
+ const numerator = BigInt(numeratorStr) * (negative ? -1n : 1n);
678
+ const denominator = 10n ** BigInt(fracPart.length);
679
+ const bytesNumerator = numerator * mBig;
680
+ if (bytesNumerator % denominator !== 0n) return null;
681
+ return bytesNumerator / denominator;
682
+ }
683
+ /**
684
+ * Parses `numStr` as a decimal rational and multiplies by `multiplier`,
685
+ * returning the exact integer result as a safe `number`, or `null` when the
686
+ * result would be fractional or outside `Number.MAX_SAFE_INTEGER`.
687
+ *
688
+ * All arithmetic is performed with `bigint` to avoid float64 precision loss
689
+ * (e.g. `"1.0000000000000001"` must not silently round to `1`).
690
+ */
691
+ function parseExactBytes(numStr, multiplier) {
692
+ const bytes = parseExactBytesRaw(numStr, BigInt(multiplier));
693
+ if (bytes == null) return null;
694
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
695
+ if (bytes < -maxSafe || bytes > maxSafe) return null;
696
+ return Number(bytes);
697
+ }
698
+ const FILE_SIZE_UNITS = [
699
+ "B",
700
+ "KB",
701
+ "MB",
702
+ "GB",
703
+ "TB",
704
+ "PB",
705
+ "EB",
706
+ "KiB",
707
+ "MiB",
708
+ "GiB",
709
+ "TiB",
710
+ "PiB",
711
+ "EiB"
712
+ ];
713
+ /**
714
+ * Creates a {@link ValueParser} for human-readable file/data size strings such
715
+ * as `"10MB"`, `"1.5GiB"`, or `"512B"`. The parsed value is a `number` or
716
+ * `bigint` representing the equivalent byte count.
717
+ *
718
+ * Supported units:
719
+ *
720
+ * | Unit | Bytes (default) |
721
+ * |------|----------------|
722
+ * | B | 1 |
723
+ * | KB | 1 000 |
724
+ * | MB | 1 000 000 |
725
+ * | GB | 1 000 000 000 |
726
+ * | KiB | 1 024 |
727
+ * | MiB | 1 048 576 |
728
+ * | GiB | 1 073 741 824 |
729
+ * | … | … |
730
+ *
731
+ * Unit suffixes are matched case-insensitively, so `"1kb"`, `"1KB"`, and
732
+ * `"1Kb"` are all equivalent.
733
+ *
734
+ * @param options Configuration options for the file size parser.
735
+ * @returns A {@link ValueParser} that parses file size strings into byte
736
+ * counts.
737
+ * @throws {TypeError} If `type` is neither `"number"` nor `"bigint"`, if
738
+ * `metavar` is an empty string, if `allowNegative` or `siAsBinary` is not
739
+ * a boolean, or if `defaultUnit` is not a valid {@link FileSizeUnit}.
740
+ * @since 1.1.0
741
+ */
742
+ function fileSize(options = {}) {
743
+ if (options.type !== void 0 && options.type !== "number" && options.type !== "bigint") throw new TypeError(`Expected type to be "number" or "bigint", but got: ${String(options.type)}.`);
744
+ const metavar = options.metavar ?? "SIZE";
745
+ require_nonempty.ensureNonEmptyString(metavar);
746
+ checkBooleanOption(options, "allowNegative");
747
+ checkBooleanOption(options, "siAsBinary");
748
+ checkEnumOption(options, "defaultUnit", FILE_SIZE_UNITS);
749
+ const siAsBinary = options.siAsBinary ?? false;
750
+ function invalidFormatError(input) {
751
+ return {
752
+ success: false,
753
+ error: options.errors?.invalidFormat ? typeof options.errors.invalidFormat === "function" ? options.errors.invalidFormat(input) : options.errors.invalidFormat : require_message.message`Expected a file size like ${"10MB"} or ${"1.5GiB"}, but got ${input}.`
754
+ };
755
+ }
756
+ if (options.type === "bigint") {
757
+ const bigintMultiplierMap = siAsBinary ? BIGINT_IEC_MULTIPLIERS : {
758
+ ...BIGINT_SI_MULTIPLIERS,
759
+ ...BIGINT_IEC_ONLY_MULTIPLIERS
760
+ };
761
+ const bigintFormatUnits = siAsBinary ? BIGINT_FORMAT_UNITS_SI_AS_BINARY : BIGINT_FORMAT_UNITS_DEFAULT;
762
+ const numberFormatUnits = siAsBinary ? FORMAT_UNITS_SI_AS_BINARY : FORMAT_UNITS_DEFAULT;
763
+ return {
764
+ mode: "sync",
765
+ metavar,
766
+ placeholder: options.placeholder ?? 0n,
767
+ parse(input) {
768
+ const match = FILE_SIZE_REGEX.exec(input.trim());
769
+ if (match == null) return invalidFormatError(input);
770
+ const numStr = match[1];
771
+ const unitStr = match[2].toLowerCase();
772
+ let mBig;
773
+ if (unitStr === "") {
774
+ if (options.defaultUnit == null) return invalidFormatError(input);
775
+ mBig = bigintMultiplierMap[options.defaultUnit.toLowerCase()];
776
+ } else {
777
+ const m = bigintMultiplierMap[unitStr];
778
+ if (m == null) return invalidFormatError(input);
779
+ mBig = m;
780
+ }
781
+ const bytes = parseExactBytesRaw(numStr, mBig);
782
+ if (bytes == null) return invalidFormatError(input);
783
+ if (!(options.allowNegative ?? false) && bytes < 0n) return {
784
+ success: false,
785
+ error: options.errors?.negativeNotAllowed ? typeof options.errors.negativeNotAllowed === "function" ? options.errors.negativeNotAllowed(bytes) : options.errors.negativeNotAllowed : require_message.message`Expected a non-negative file size, but got ${input}.`
786
+ };
787
+ return {
788
+ success: true,
789
+ value: bytes
790
+ };
791
+ },
792
+ format(value) {
793
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
794
+ if (value >= -maxSafe && value <= maxSafe) return formatWithUnits(Number(value), numberFormatUnits);
795
+ return formatBigIntBytes(value, bigintFormatUnits);
796
+ }
797
+ };
798
+ }
799
+ const multiplierMap = siAsBinary ? IEC_MULTIPLIERS : {
800
+ ...SI_MULTIPLIERS,
801
+ ...IEC_ONLY_MULTIPLIERS
802
+ };
803
+ const formatUnits = siAsBinary ? FORMAT_UNITS_SI_AS_BINARY : FORMAT_UNITS_DEFAULT;
804
+ return {
805
+ mode: "sync",
806
+ metavar,
807
+ placeholder: options.placeholder ?? 0,
808
+ parse(input) {
809
+ const match = FILE_SIZE_REGEX.exec(input.trim());
810
+ if (match == null) return invalidFormatError(input);
811
+ const numStr = match[1];
812
+ const unitStr = match[2].toLowerCase();
813
+ let multiplier;
814
+ if (unitStr === "") {
815
+ if (options.defaultUnit == null) return invalidFormatError(input);
816
+ multiplier = multiplierMap[options.defaultUnit.toLowerCase()];
817
+ } else {
818
+ const m = multiplierMap[unitStr];
819
+ if (m == null) return invalidFormatError(input);
820
+ multiplier = m;
821
+ }
822
+ const bytes = parseExactBytes(numStr, multiplier);
823
+ if (bytes == null) return invalidFormatError(input);
824
+ if (!(options.allowNegative ?? false) && bytes < 0) return {
825
+ success: false,
826
+ error: options.errors?.negativeNotAllowed ? typeof options.errors.negativeNotAllowed === "function" ? options.errors.negativeNotAllowed(bytes) : options.errors.negativeNotAllowed : require_message.message`Expected a non-negative file size, but got ${input}.`
827
+ };
828
+ return {
829
+ success: true,
830
+ value: bytes
831
+ };
832
+ },
833
+ format(value) {
834
+ return formatWithUnits(value, formatUnits);
835
+ }
836
+ };
837
+ }
507
838
  /**
508
839
  * The set of URL schemes that are considered "special" by the WHATWG URL
509
840
  * Standard. These schemes always use the `://` authority syntax.
@@ -3692,6 +4023,7 @@ exports.cidr = cidr;
3692
4023
  exports.domain = domain;
3693
4024
  exports.email = email;
3694
4025
  exports.ensureNonEmptyString = require_nonempty.ensureNonEmptyString;
4026
+ exports.fileSize = fileSize;
3695
4027
  exports.float = float;
3696
4028
  exports.hostname = hostname;
3697
4029
  exports.integer = integer;
@@ -584,6 +584,169 @@ interface FloatOptions {
584
584
  * numbers.
585
585
  */
586
586
  declare function float(options?: FloatOptions): ValueParser<"sync", number>;
587
+ /**
588
+ * A canonical file size unit string. SI units use powers of 1 000 by
589
+ * default; IEC units always use powers of 1 024.
590
+ * @since 1.1.0
591
+ */
592
+ type FileSizeUnit = "B" | "KB" | "MB" | "GB" | "TB" | "PB" | "EB" | "KiB" | "MiB" | "GiB" | "TiB" | "PiB" | "EiB";
593
+ /**
594
+ * Options for creating a {@link fileSize} parser that returns `number`.
595
+ * @since 1.1.0
596
+ */
597
+ interface FileSizeOptionsNumber {
598
+ /**
599
+ * The return type. Defaults to `"number"`.
600
+ * @default `"number"`
601
+ */
602
+ readonly type?: "number";
603
+ /**
604
+ * The metavariable name for this parser. Used in help messages to
605
+ * indicate what kind of value this parser expects.
606
+ * @default `"SIZE"`
607
+ */
608
+ readonly metavar?: NonEmptyString;
609
+ /**
610
+ * If `true`, negative byte values are accepted. Most size-related CLI
611
+ * options do not accept negative values, so this defaults to `false`.
612
+ * @default `false`
613
+ */
614
+ readonly allowNegative?: boolean;
615
+ /**
616
+ * The unit to assume when the input contains only a number with no unit
617
+ * suffix (e.g., `"100"` with `defaultUnit: "MB"` → 100 000 000 bytes).
618
+ * When this option is absent, a bare number without a unit is rejected.
619
+ */
620
+ readonly defaultUnit?: FileSizeUnit;
621
+ /**
622
+ * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as
623
+ * binary powers of 1 024 rather than decimal powers of 1 000. This
624
+ * matches a widespread but technically incorrect convention where
625
+ * "1 KB" means 1 024 bytes. IEC suffixes (`KiB`, `MiB`, …) are
626
+ * unaffected by this option.
627
+ *
628
+ * @default `false`
629
+ * @since 1.1.0
630
+ */
631
+ readonly siAsBinary?: boolean;
632
+ /**
633
+ * A custom placeholder value used during deferred prompt resolution.
634
+ * @default `0`
635
+ * @since 1.1.0
636
+ */
637
+ readonly placeholder?: number;
638
+ /**
639
+ * Custom error messages for file size parsing failures.
640
+ * @since 1.1.0
641
+ */
642
+ readonly errors?: {
643
+ /**
644
+ * Custom error message when the input is not a valid file size string.
645
+ * Can be a static message or a function that receives the raw input.
646
+ */
647
+ readonly invalidFormat?: Message | ((input: string) => Message);
648
+ /**
649
+ * Custom error message when a negative value is provided but
650
+ * {@link FileSizeOptionsNumber.allowNegative} is `false`.
651
+ * Can be a static message or a function that receives the byte value.
652
+ */
653
+ readonly negativeNotAllowed?: Message | ((value: number) => Message);
654
+ };
655
+ }
656
+ /**
657
+ * Options for creating a {@link fileSize} parser that returns `bigint`.
658
+ * Use this when byte counts may exceed `Number.MAX_SAFE_INTEGER` (roughly
659
+ * 9 PB), for example when working with EB/EiB-range values.
660
+ * @since 1.1.0
661
+ */
662
+ interface FileSizeOptionsBigInt {
663
+ /**
664
+ * Must be set to `"bigint"` to select bigint output.
665
+ */
666
+ readonly type: "bigint";
667
+ /**
668
+ * The metavariable name for this parser. Used in help messages to
669
+ * indicate what kind of value this parser expects.
670
+ * @default `"SIZE"`
671
+ */
672
+ readonly metavar?: NonEmptyString;
673
+ /**
674
+ * If `true`, negative byte values are accepted.
675
+ * @default `false`
676
+ */
677
+ readonly allowNegative?: boolean;
678
+ /**
679
+ * The unit to assume when the input contains only a number with no unit
680
+ * suffix. When absent, a bare number is rejected.
681
+ */
682
+ readonly defaultUnit?: FileSizeUnit;
683
+ /**
684
+ * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as
685
+ * binary powers of 1 024 rather than decimal powers of 1 000.
686
+ * @default `false`
687
+ * @since 1.1.0
688
+ */
689
+ readonly siAsBinary?: boolean;
690
+ /**
691
+ * A custom placeholder value used during deferred prompt resolution.
692
+ * @default `0n`
693
+ * @since 1.1.0
694
+ */
695
+ readonly placeholder?: bigint;
696
+ /**
697
+ * Custom error messages for file size parsing failures.
698
+ * @since 1.1.0
699
+ */
700
+ readonly errors?: {
701
+ /**
702
+ * Custom error message when the input is not a valid file size string.
703
+ * Can be a static message or a function that receives the raw input.
704
+ */
705
+ readonly invalidFormat?: Message | ((input: string) => Message);
706
+ /**
707
+ * Custom error message when a negative value is provided but
708
+ * {@link FileSizeOptionsBigInt.allowNegative} is `false`.
709
+ * Can be a static message or a function that receives the byte value.
710
+ */
711
+ readonly negativeNotAllowed?: Message | ((value: bigint) => Message);
712
+ };
713
+ }
714
+ /**
715
+ * Options for creating a {@link fileSize} parser.
716
+ * @since 1.1.0
717
+ */
718
+ type FileSizeOptions = FileSizeOptionsNumber | FileSizeOptionsBigInt;
719
+ /**
720
+ * Creates a {@link ValueParser} for human-readable file/data size strings
721
+ * that returns a `number` byte count.
722
+ *
723
+ * @param options Configuration options for the file size parser.
724
+ * @returns A {@link ValueParser} that parses file size strings into `number`
725
+ * byte counts.
726
+ * @throws {TypeError} If {@link FileSizeOptionsNumber.metavar} is an empty
727
+ * string, if {@link FileSizeOptionsNumber.allowNegative} or
728
+ * {@link FileSizeOptionsNumber.siAsBinary} is not a boolean, or if
729
+ * {@link FileSizeOptionsNumber.defaultUnit} is not a valid
730
+ * {@link FileSizeUnit}.
731
+ * @since 1.1.0
732
+ */
733
+ declare function fileSize(options?: FileSizeOptionsNumber): ValueParser<"sync", number>;
734
+ /**
735
+ * Creates a {@link ValueParser} for human-readable file/data size strings
736
+ * that returns a `bigint` byte count. Use this when byte counts may exceed
737
+ * `Number.MAX_SAFE_INTEGER` (~9 PB), for example with EB/EiB-range values.
738
+ *
739
+ * @param options Configuration options for the file size parser.
740
+ * @returns A {@link ValueParser} that parses file size strings into `bigint`
741
+ * byte counts.
742
+ * @throws {TypeError} If {@link FileSizeOptionsBigInt.metavar} is an empty
743
+ * string, if {@link FileSizeOptionsBigInt.allowNegative} or
744
+ * {@link FileSizeOptionsBigInt.siAsBinary} is not a boolean, or if
745
+ * {@link FileSizeOptionsBigInt.defaultUnit} is not a valid
746
+ * {@link FileSizeUnit}.
747
+ * @since 1.1.0
748
+ */
749
+ declare function fileSize(options: FileSizeOptionsBigInt): ValueParser<"sync", bigint>;
587
750
  /**
588
751
  * Options for creating a {@link url} parser.
589
752
  */
@@ -2166,4 +2329,4 @@ interface CidrOptions {
2166
2329
  */
2167
2330
  declare function cidr(options?: CidrOptions): ValueParser<"sync", CidrValue>;
2168
2331
  //#endregion
2169
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, DeferredMap, DomainOptions, EmailOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid };
2332
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, 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, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid };
@@ -584,6 +584,169 @@ interface FloatOptions {
584
584
  * numbers.
585
585
  */
586
586
  declare function float(options?: FloatOptions): ValueParser<"sync", number>;
587
+ /**
588
+ * A canonical file size unit string. SI units use powers of 1 000 by
589
+ * default; IEC units always use powers of 1 024.
590
+ * @since 1.1.0
591
+ */
592
+ type FileSizeUnit = "B" | "KB" | "MB" | "GB" | "TB" | "PB" | "EB" | "KiB" | "MiB" | "GiB" | "TiB" | "PiB" | "EiB";
593
+ /**
594
+ * Options for creating a {@link fileSize} parser that returns `number`.
595
+ * @since 1.1.0
596
+ */
597
+ interface FileSizeOptionsNumber {
598
+ /**
599
+ * The return type. Defaults to `"number"`.
600
+ * @default `"number"`
601
+ */
602
+ readonly type?: "number";
603
+ /**
604
+ * The metavariable name for this parser. Used in help messages to
605
+ * indicate what kind of value this parser expects.
606
+ * @default `"SIZE"`
607
+ */
608
+ readonly metavar?: NonEmptyString;
609
+ /**
610
+ * If `true`, negative byte values are accepted. Most size-related CLI
611
+ * options do not accept negative values, so this defaults to `false`.
612
+ * @default `false`
613
+ */
614
+ readonly allowNegative?: boolean;
615
+ /**
616
+ * The unit to assume when the input contains only a number with no unit
617
+ * suffix (e.g., `"100"` with `defaultUnit: "MB"` → 100 000 000 bytes).
618
+ * When this option is absent, a bare number without a unit is rejected.
619
+ */
620
+ readonly defaultUnit?: FileSizeUnit;
621
+ /**
622
+ * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as
623
+ * binary powers of 1 024 rather than decimal powers of 1 000. This
624
+ * matches a widespread but technically incorrect convention where
625
+ * "1 KB" means 1 024 bytes. IEC suffixes (`KiB`, `MiB`, …) are
626
+ * unaffected by this option.
627
+ *
628
+ * @default `false`
629
+ * @since 1.1.0
630
+ */
631
+ readonly siAsBinary?: boolean;
632
+ /**
633
+ * A custom placeholder value used during deferred prompt resolution.
634
+ * @default `0`
635
+ * @since 1.1.0
636
+ */
637
+ readonly placeholder?: number;
638
+ /**
639
+ * Custom error messages for file size parsing failures.
640
+ * @since 1.1.0
641
+ */
642
+ readonly errors?: {
643
+ /**
644
+ * Custom error message when the input is not a valid file size string.
645
+ * Can be a static message or a function that receives the raw input.
646
+ */
647
+ readonly invalidFormat?: Message | ((input: string) => Message);
648
+ /**
649
+ * Custom error message when a negative value is provided but
650
+ * {@link FileSizeOptionsNumber.allowNegative} is `false`.
651
+ * Can be a static message or a function that receives the byte value.
652
+ */
653
+ readonly negativeNotAllowed?: Message | ((value: number) => Message);
654
+ };
655
+ }
656
+ /**
657
+ * Options for creating a {@link fileSize} parser that returns `bigint`.
658
+ * Use this when byte counts may exceed `Number.MAX_SAFE_INTEGER` (roughly
659
+ * 9 PB), for example when working with EB/EiB-range values.
660
+ * @since 1.1.0
661
+ */
662
+ interface FileSizeOptionsBigInt {
663
+ /**
664
+ * Must be set to `"bigint"` to select bigint output.
665
+ */
666
+ readonly type: "bigint";
667
+ /**
668
+ * The metavariable name for this parser. Used in help messages to
669
+ * indicate what kind of value this parser expects.
670
+ * @default `"SIZE"`
671
+ */
672
+ readonly metavar?: NonEmptyString;
673
+ /**
674
+ * If `true`, negative byte values are accepted.
675
+ * @default `false`
676
+ */
677
+ readonly allowNegative?: boolean;
678
+ /**
679
+ * The unit to assume when the input contains only a number with no unit
680
+ * suffix. When absent, a bare number is rejected.
681
+ */
682
+ readonly defaultUnit?: FileSizeUnit;
683
+ /**
684
+ * When `true`, SI suffixes (`KB`, `MB`, `GB`, …) are interpreted as
685
+ * binary powers of 1 024 rather than decimal powers of 1 000.
686
+ * @default `false`
687
+ * @since 1.1.0
688
+ */
689
+ readonly siAsBinary?: boolean;
690
+ /**
691
+ * A custom placeholder value used during deferred prompt resolution.
692
+ * @default `0n`
693
+ * @since 1.1.0
694
+ */
695
+ readonly placeholder?: bigint;
696
+ /**
697
+ * Custom error messages for file size parsing failures.
698
+ * @since 1.1.0
699
+ */
700
+ readonly errors?: {
701
+ /**
702
+ * Custom error message when the input is not a valid file size string.
703
+ * Can be a static message or a function that receives the raw input.
704
+ */
705
+ readonly invalidFormat?: Message | ((input: string) => Message);
706
+ /**
707
+ * Custom error message when a negative value is provided but
708
+ * {@link FileSizeOptionsBigInt.allowNegative} is `false`.
709
+ * Can be a static message or a function that receives the byte value.
710
+ */
711
+ readonly negativeNotAllowed?: Message | ((value: bigint) => Message);
712
+ };
713
+ }
714
+ /**
715
+ * Options for creating a {@link fileSize} parser.
716
+ * @since 1.1.0
717
+ */
718
+ type FileSizeOptions = FileSizeOptionsNumber | FileSizeOptionsBigInt;
719
+ /**
720
+ * Creates a {@link ValueParser} for human-readable file/data size strings
721
+ * that returns a `number` byte count.
722
+ *
723
+ * @param options Configuration options for the file size parser.
724
+ * @returns A {@link ValueParser} that parses file size strings into `number`
725
+ * byte counts.
726
+ * @throws {TypeError} If {@link FileSizeOptionsNumber.metavar} is an empty
727
+ * string, if {@link FileSizeOptionsNumber.allowNegative} or
728
+ * {@link FileSizeOptionsNumber.siAsBinary} is not a boolean, or if
729
+ * {@link FileSizeOptionsNumber.defaultUnit} is not a valid
730
+ * {@link FileSizeUnit}.
731
+ * @since 1.1.0
732
+ */
733
+ declare function fileSize(options?: FileSizeOptionsNumber): ValueParser<"sync", number>;
734
+ /**
735
+ * Creates a {@link ValueParser} for human-readable file/data size strings
736
+ * that returns a `bigint` byte count. Use this when byte counts may exceed
737
+ * `Number.MAX_SAFE_INTEGER` (~9 PB), for example with EB/EiB-range values.
738
+ *
739
+ * @param options Configuration options for the file size parser.
740
+ * @returns A {@link ValueParser} that parses file size strings into `bigint`
741
+ * byte counts.
742
+ * @throws {TypeError} If {@link FileSizeOptionsBigInt.metavar} is an empty
743
+ * string, if {@link FileSizeOptionsBigInt.allowNegative} or
744
+ * {@link FileSizeOptionsBigInt.siAsBinary} is not a boolean, or if
745
+ * {@link FileSizeOptionsBigInt.defaultUnit} is not a valid
746
+ * {@link FileSizeUnit}.
747
+ * @since 1.1.0
748
+ */
749
+ declare function fileSize(options: FileSizeOptionsBigInt): ValueParser<"sync", bigint>;
587
750
  /**
588
751
  * Options for creating a {@link url} parser.
589
752
  */
@@ -2166,4 +2329,4 @@ interface CidrOptions {
2166
2329
  */
2167
2330
  declare function cidr(options?: CidrOptions): ValueParser<"sync", CidrValue>;
2168
2331
  //#endregion
2169
- export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, DeferredMap, DomainOptions, EmailOptions, FloatOptions, HostnameOptions, IntegerOptionsBigInt, IntegerOptionsNumber, IpOptions, Ipv4Options, Ipv6Options, LocaleOptions, MacAddressOptions, type Mode, type ModeIterable, type ModeValue, type NonEmptyString, PortOptionsBigInt, PortOptionsNumber, PortRangeOptionsBigInt, PortRangeOptionsNumber, PortRangeValueBigInt, PortRangeValueNumber, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid };
2332
+ export { ChoiceOptions, ChoiceOptionsBase, ChoiceOptionsNumber, ChoiceOptionsString, CidrOptions, CidrValue, 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, SocketAddressOptions, SocketAddressValue, StringOptions, UrlOptions, Uuid, UuidOptions, ValueParser, ValueParserResult, checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid };
@@ -504,6 +504,337 @@ function float(options = {}) {
504
504
  }
505
505
  };
506
506
  }
507
+ const SI_MULTIPLIERS = {
508
+ b: 1,
509
+ kb: 1e3,
510
+ mb: 1e6,
511
+ gb: 1e9,
512
+ tb: 1e12,
513
+ pb: 1e15,
514
+ eb: 1e18
515
+ };
516
+ const IEC_MULTIPLIERS = {
517
+ b: 1,
518
+ kb: 1024,
519
+ mb: 1024 ** 2,
520
+ gb: 1024 ** 3,
521
+ tb: 1024 ** 4,
522
+ pb: 1024 ** 5,
523
+ eb: 1024 ** 6,
524
+ kib: 1024,
525
+ mib: 1024 ** 2,
526
+ gib: 1024 ** 3,
527
+ tib: 1024 ** 4,
528
+ pib: 1024 ** 5,
529
+ eib: 1024 ** 6
530
+ };
531
+ const IEC_ONLY_MULTIPLIERS = {
532
+ kib: 1024,
533
+ mib: 1024 ** 2,
534
+ gib: 1024 ** 3,
535
+ tib: 1024 ** 4,
536
+ pib: 1024 ** 5,
537
+ eib: 1024 ** 6
538
+ };
539
+ const FILE_SIZE_REGEX = /^([+-]?(?:\d+\.?\d*|\d*\.\d+))\s*([a-zA-Z]*)$/;
540
+ /**
541
+ * Formats `bytes` using the most readable unit from the given ordered list.
542
+ * Falls back to `"${bytes}B"`.
543
+ *
544
+ * A unit is chosen only when the formatted value round-trips exactly: the
545
+ * rounded quotient must lie in [1, 1000) and `rounded * size === bytes` must
546
+ * hold in float64 arithmetic. This guarantees `parse(format(x)) === x`.
547
+ */
548
+ function formatWithUnits(bytes, units) {
549
+ if (bytes === 0) return "0B";
550
+ const absBytes = Math.abs(bytes);
551
+ for (const [unit, size] of units) {
552
+ if (absBytes < size) continue;
553
+ const v = bytes / size;
554
+ const rounded = Math.round(v * 100) / 100;
555
+ const absRounded = Math.abs(rounded);
556
+ if (absRounded >= 1 && absRounded < 1e3 && rounded * size === bytes) return `${rounded}${unit}`;
557
+ }
558
+ return `${bytes}B`;
559
+ }
560
+ const FORMAT_UNITS_DEFAULT = [
561
+ ["EiB", 1024 ** 6],
562
+ ["PiB", 1024 ** 5],
563
+ ["TiB", 1024 ** 4],
564
+ ["GiB", 1024 ** 3],
565
+ ["MiB", 1024 ** 2],
566
+ ["KiB", 1024],
567
+ ["EB", 1e18],
568
+ ["PB", 1e15],
569
+ ["TB", 1e12],
570
+ ["GB", 1e9],
571
+ ["MB", 1e6],
572
+ ["KB", 1e3]
573
+ ];
574
+ const FORMAT_UNITS_SI_AS_BINARY = [
575
+ ["EB", 1024 ** 6],
576
+ ["PB", 1024 ** 5],
577
+ ["TB", 1024 ** 4],
578
+ ["GB", 1024 ** 3],
579
+ ["MB", 1024 ** 2],
580
+ ["KB", 1024]
581
+ ];
582
+ const BIGINT_SI_MULTIPLIERS = {
583
+ b: 1n,
584
+ kb: 1000n,
585
+ mb: 1000000n,
586
+ gb: 1000000000n,
587
+ tb: 1000000000000n,
588
+ pb: 1000000000000000n,
589
+ eb: 1000000000000000000n
590
+ };
591
+ const BIGINT_IEC_MULTIPLIERS = {
592
+ b: 1n,
593
+ kb: 1024n,
594
+ mb: 1024n ** 2n,
595
+ gb: 1024n ** 3n,
596
+ tb: 1024n ** 4n,
597
+ pb: 1024n ** 5n,
598
+ eb: 1024n ** 6n,
599
+ kib: 1024n,
600
+ mib: 1024n ** 2n,
601
+ gib: 1024n ** 3n,
602
+ tib: 1024n ** 4n,
603
+ pib: 1024n ** 5n,
604
+ eib: 1024n ** 6n
605
+ };
606
+ const BIGINT_IEC_ONLY_MULTIPLIERS = {
607
+ kib: 1024n,
608
+ mib: 1024n ** 2n,
609
+ gib: 1024n ** 3n,
610
+ tib: 1024n ** 4n,
611
+ pib: 1024n ** 5n,
612
+ eib: 1024n ** 6n
613
+ };
614
+ const BIGINT_FORMAT_UNITS_DEFAULT = [
615
+ ["EiB", 1024n ** 6n],
616
+ ["PiB", 1024n ** 5n],
617
+ ["TiB", 1024n ** 4n],
618
+ ["GiB", 1024n ** 3n],
619
+ ["MiB", 1024n ** 2n],
620
+ ["KiB", 1024n],
621
+ ["EB", 1000000000000000000n],
622
+ ["PB", 1000000000000000n],
623
+ ["TB", 1000000000000n],
624
+ ["GB", 1000000000n],
625
+ ["MB", 1000000n],
626
+ ["KB", 1000n]
627
+ ];
628
+ const BIGINT_FORMAT_UNITS_SI_AS_BINARY = [
629
+ ["EB", 1024n ** 6n],
630
+ ["PB", 1024n ** 5n],
631
+ ["TB", 1024n ** 4n],
632
+ ["GB", 1024n ** 3n],
633
+ ["MB", 1024n ** 2n],
634
+ ["KB", 1024n]
635
+ ];
636
+ /**
637
+ * Formats a bigint byte count using the most readable unit. Falls back to
638
+ * `"${value}B"`. Tries exact integers, then 1 and 2 decimal places.
639
+ */
640
+ function formatBigIntBytes(value, units) {
641
+ if (value === 0n) return "0B";
642
+ const absValue = value < 0n ? -value : value;
643
+ for (const [unit, size] of units) {
644
+ if (absValue < size) continue;
645
+ if (value % size === 0n) {
646
+ const v = value / size;
647
+ const absV = v < 0n ? -v : v;
648
+ if (absV >= 1n && absV < 1000n) return `${v}${unit}`;
649
+ }
650
+ const v100 = value * 100n;
651
+ if (v100 % size === 0n) {
652
+ const q = v100 / size;
653
+ const absQ = q < 0n ? -q : q;
654
+ if (absQ >= 100n && absQ < 100000n) {
655
+ const intPart = q / 100n;
656
+ const decPart = absQ % 100n;
657
+ if (decPart % 10n === 0n) return `${intPart}.${decPart / 10n}${unit}`;
658
+ return `${intPart}.${String(decPart).padStart(2, "0")}${unit}`;
659
+ }
660
+ }
661
+ }
662
+ return `${value}B`;
663
+ }
664
+ /**
665
+ * Core computation: parses `numStr` as a decimal rational, multiplies by
666
+ * `mBig`, and returns the exact integer result as a `bigint`, or `null` when
667
+ * the result would be fractional. The safe-integer range check is NOT applied
668
+ * here; callers add it as needed.
669
+ */
670
+ function parseExactBytesRaw(numStr, mBig) {
671
+ const negative = numStr.startsWith("-");
672
+ const absStr = numStr.startsWith("+") || numStr.startsWith("-") ? numStr.slice(1) : numStr;
673
+ const dotIdx = absStr.indexOf(".");
674
+ const intPart = dotIdx < 0 ? absStr : absStr.slice(0, dotIdx);
675
+ const fracPart = dotIdx < 0 ? "" : absStr.slice(dotIdx + 1);
676
+ const numeratorStr = ((intPart || "0") + fracPart).replace(/^0+/, "") || "0";
677
+ const numerator = BigInt(numeratorStr) * (negative ? -1n : 1n);
678
+ const denominator = 10n ** BigInt(fracPart.length);
679
+ const bytesNumerator = numerator * mBig;
680
+ if (bytesNumerator % denominator !== 0n) return null;
681
+ return bytesNumerator / denominator;
682
+ }
683
+ /**
684
+ * Parses `numStr` as a decimal rational and multiplies by `multiplier`,
685
+ * returning the exact integer result as a safe `number`, or `null` when the
686
+ * result would be fractional or outside `Number.MAX_SAFE_INTEGER`.
687
+ *
688
+ * All arithmetic is performed with `bigint` to avoid float64 precision loss
689
+ * (e.g. `"1.0000000000000001"` must not silently round to `1`).
690
+ */
691
+ function parseExactBytes(numStr, multiplier) {
692
+ const bytes = parseExactBytesRaw(numStr, BigInt(multiplier));
693
+ if (bytes == null) return null;
694
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
695
+ if (bytes < -maxSafe || bytes > maxSafe) return null;
696
+ return Number(bytes);
697
+ }
698
+ const FILE_SIZE_UNITS = [
699
+ "B",
700
+ "KB",
701
+ "MB",
702
+ "GB",
703
+ "TB",
704
+ "PB",
705
+ "EB",
706
+ "KiB",
707
+ "MiB",
708
+ "GiB",
709
+ "TiB",
710
+ "PiB",
711
+ "EiB"
712
+ ];
713
+ /**
714
+ * Creates a {@link ValueParser} for human-readable file/data size strings such
715
+ * as `"10MB"`, `"1.5GiB"`, or `"512B"`. The parsed value is a `number` or
716
+ * `bigint` representing the equivalent byte count.
717
+ *
718
+ * Supported units:
719
+ *
720
+ * | Unit | Bytes (default) |
721
+ * |------|----------------|
722
+ * | B | 1 |
723
+ * | KB | 1 000 |
724
+ * | MB | 1 000 000 |
725
+ * | GB | 1 000 000 000 |
726
+ * | KiB | 1 024 |
727
+ * | MiB | 1 048 576 |
728
+ * | GiB | 1 073 741 824 |
729
+ * | … | … |
730
+ *
731
+ * Unit suffixes are matched case-insensitively, so `"1kb"`, `"1KB"`, and
732
+ * `"1Kb"` are all equivalent.
733
+ *
734
+ * @param options Configuration options for the file size parser.
735
+ * @returns A {@link ValueParser} that parses file size strings into byte
736
+ * counts.
737
+ * @throws {TypeError} If `type` is neither `"number"` nor `"bigint"`, if
738
+ * `metavar` is an empty string, if `allowNegative` or `siAsBinary` is not
739
+ * a boolean, or if `defaultUnit` is not a valid {@link FileSizeUnit}.
740
+ * @since 1.1.0
741
+ */
742
+ function fileSize(options = {}) {
743
+ if (options.type !== void 0 && options.type !== "number" && options.type !== "bigint") throw new TypeError(`Expected type to be "number" or "bigint", but got: ${String(options.type)}.`);
744
+ const metavar = options.metavar ?? "SIZE";
745
+ ensureNonEmptyString(metavar);
746
+ checkBooleanOption(options, "allowNegative");
747
+ checkBooleanOption(options, "siAsBinary");
748
+ checkEnumOption(options, "defaultUnit", FILE_SIZE_UNITS);
749
+ const siAsBinary = options.siAsBinary ?? false;
750
+ function invalidFormatError(input) {
751
+ return {
752
+ success: false,
753
+ error: options.errors?.invalidFormat ? typeof options.errors.invalidFormat === "function" ? options.errors.invalidFormat(input) : options.errors.invalidFormat : message`Expected a file size like ${"10MB"} or ${"1.5GiB"}, but got ${input}.`
754
+ };
755
+ }
756
+ if (options.type === "bigint") {
757
+ const bigintMultiplierMap = siAsBinary ? BIGINT_IEC_MULTIPLIERS : {
758
+ ...BIGINT_SI_MULTIPLIERS,
759
+ ...BIGINT_IEC_ONLY_MULTIPLIERS
760
+ };
761
+ const bigintFormatUnits = siAsBinary ? BIGINT_FORMAT_UNITS_SI_AS_BINARY : BIGINT_FORMAT_UNITS_DEFAULT;
762
+ const numberFormatUnits = siAsBinary ? FORMAT_UNITS_SI_AS_BINARY : FORMAT_UNITS_DEFAULT;
763
+ return {
764
+ mode: "sync",
765
+ metavar,
766
+ placeholder: options.placeholder ?? 0n,
767
+ parse(input) {
768
+ const match = FILE_SIZE_REGEX.exec(input.trim());
769
+ if (match == null) return invalidFormatError(input);
770
+ const numStr = match[1];
771
+ const unitStr = match[2].toLowerCase();
772
+ let mBig;
773
+ if (unitStr === "") {
774
+ if (options.defaultUnit == null) return invalidFormatError(input);
775
+ mBig = bigintMultiplierMap[options.defaultUnit.toLowerCase()];
776
+ } else {
777
+ const m = bigintMultiplierMap[unitStr];
778
+ if (m == null) return invalidFormatError(input);
779
+ mBig = m;
780
+ }
781
+ const bytes = parseExactBytesRaw(numStr, mBig);
782
+ if (bytes == null) return invalidFormatError(input);
783
+ if (!(options.allowNegative ?? false) && bytes < 0n) return {
784
+ success: false,
785
+ error: options.errors?.negativeNotAllowed ? typeof options.errors.negativeNotAllowed === "function" ? options.errors.negativeNotAllowed(bytes) : options.errors.negativeNotAllowed : message`Expected a non-negative file size, but got ${input}.`
786
+ };
787
+ return {
788
+ success: true,
789
+ value: bytes
790
+ };
791
+ },
792
+ format(value) {
793
+ const maxSafe = BigInt(Number.MAX_SAFE_INTEGER);
794
+ if (value >= -maxSafe && value <= maxSafe) return formatWithUnits(Number(value), numberFormatUnits);
795
+ return formatBigIntBytes(value, bigintFormatUnits);
796
+ }
797
+ };
798
+ }
799
+ const multiplierMap = siAsBinary ? IEC_MULTIPLIERS : {
800
+ ...SI_MULTIPLIERS,
801
+ ...IEC_ONLY_MULTIPLIERS
802
+ };
803
+ const formatUnits = siAsBinary ? FORMAT_UNITS_SI_AS_BINARY : FORMAT_UNITS_DEFAULT;
804
+ return {
805
+ mode: "sync",
806
+ metavar,
807
+ placeholder: options.placeholder ?? 0,
808
+ parse(input) {
809
+ const match = FILE_SIZE_REGEX.exec(input.trim());
810
+ if (match == null) return invalidFormatError(input);
811
+ const numStr = match[1];
812
+ const unitStr = match[2].toLowerCase();
813
+ let multiplier;
814
+ if (unitStr === "") {
815
+ if (options.defaultUnit == null) return invalidFormatError(input);
816
+ multiplier = multiplierMap[options.defaultUnit.toLowerCase()];
817
+ } else {
818
+ const m = multiplierMap[unitStr];
819
+ if (m == null) return invalidFormatError(input);
820
+ multiplier = m;
821
+ }
822
+ const bytes = parseExactBytes(numStr, multiplier);
823
+ if (bytes == null) return invalidFormatError(input);
824
+ if (!(options.allowNegative ?? false) && bytes < 0) return {
825
+ success: false,
826
+ error: options.errors?.negativeNotAllowed ? typeof options.errors.negativeNotAllowed === "function" ? options.errors.negativeNotAllowed(bytes) : options.errors.negativeNotAllowed : message`Expected a non-negative file size, but got ${input}.`
827
+ };
828
+ return {
829
+ success: true,
830
+ value: bytes
831
+ };
832
+ },
833
+ format(value) {
834
+ return formatWithUnits(value, formatUnits);
835
+ }
836
+ };
837
+ }
507
838
  /**
508
839
  * The set of URL schemes that are considered "special" by the WHATWG URL
509
840
  * Standard. These schemes always use the `://` authority syntax.
@@ -3685,4 +4016,4 @@ function cidr(options) {
3685
4016
  }
3686
4017
 
3687
4018
  //#endregion
3688
- export { checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, socketAddress, string, url, uuid };
4019
+ export { checkBooleanOption, checkEnumOption, choice, cidr, domain, email, ensureNonEmptyString, fileSize, float, hostname, integer, ip, ipv4, ipv6, isNonEmptyString, isValueParser, locale, macAddress, port, portRange, 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.2053",
3
+ "version": "1.1.0-dev.2057",
4
4
  "description": "Type-safe combinatorial command-line interface parser",
5
5
  "keywords": [
6
6
  "CLI",