🚀 Socket Launch Week Day 5:Introducing Repository Access Permissions and Custom Roles.Learn more
Sign In

type-flag

Package Overview
Dependencies
Maintainers
1
Versions
33
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

type-flag - npm Package Compare versions

Comparing version
5.0.0-beta.14
to
5.0.0-beta.15
+1
dist/internal-CAAarqqk.mjs
var x=Object.defineProperty;var a=(e,n)=>x(e,"name",{value:n,configurable:!0});const N="known-flag",P="unknown-flag",V="argument",w=a(e=>(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e,"isStandardSchema"),k=a(e=>(n=>{const t=e["~standard"].validate(n);if(t instanceof Promise)throw new TypeError("Async schemas are not supported");if(t.issues)throw new Error(t.issues[0]?.message??"Validation failed");return t.value}),"schemaToParser"),g="--",L=3,O=/^-{1,2}\w/,C=/^-(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i,D=a((e,n)=>{if(!C.test(e))return!1;for(let t=1;t<e.length;t+=1)if(!n.has(e[t]))return!0;return!1},"isNegativeNumberValue"),E=a(e=>{if(!O.test(e))return;const n=!e.startsWith(g);let t=e.slice(n?1:2),r,s=-1;for(const c of["=",":","."]){const i=t.indexOf(c);i!==-1&&(s===-1||i<s)&&(s=i)}return s!==-1&&(r=t.slice(s+1),t=t.slice(0,s)),[t,r,n]},"parseFlagArgv"),T=a((e,{onFlag:n,onValue:t,onArgument:r,knownFlags:s})=>{let c=!1;const i=a((o,l)=>{if(!c)return!0;c=!1,t?.(o,l)},"triggerValueCallback");for(let o=0;o<e.length;o+=1){const l=e[o];if(l===g){i();const u=e.slice(o+1);r?.(u,[o],!0);break}if(c&&s&&D(l,s)){i(l,[o]);continue}const f=E(l);if(f){if(i(),!n)continue;const[u,m,$]=f;if($)for(let p=0;p<u.length;p+=1){i();const A=p===u.length-1;c=n(u[p],A?m:void 0,[o,p+1,A])===!0}else c=n(u,m,[o])===!0}else i(l,[o])&&r?.([l],[o])}i()},"argvIterator"),I=a((e,n)=>{for(let t=n.length-1;t>=0;t-=1){const[r,s,c]=n[t];if(s){const i=e[r];let o=i.slice(0,s);if(c||(o+=i.slice(s+1)),o!=="-"){e[r]=o;continue}}e.splice(r,1)}},"spliceFromArgv"),h=a((e,n)=>Object.assign(e,{[g]:n}),"createPositionalArgumentsFromParts"),_=a(e=>{const n=e.indexOf(g);if(n===-1)return h([...e],[]);const t=e.slice(0,n),r=e.slice(n+1);return h([...t,...r],r)},"createPositionalArguments"),U=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g,j=/[A-Z]/,F=a(e=>j.test(e)?e.replaceAll(U,"-").toLowerCase():e.toLowerCase(),"flagNameToKebab"),{hasOwnProperty:z}=Object.prototype,y=a((e,n)=>z.call(e,n),"hasOwn"),d=a(e=>w(e)?[k(e),!1]:typeof e=="function"?[e,!1]:Array.isArray(e)?[d(e[0])[0],!0]:d(e.type),"parseFlagType"),G=a((e,n)=>e===Boolean?n!=="false":n,"normalizeBoolean"),K=a((e,n,t)=>{if(typeof n=="boolean")return n;if(e===Number&&n==="")return Number.NaN;try{return e(n)}catch(r){throw new TypeError(`Flag "--${t}": ${r instanceof Error?r.message:r}`,{cause:r})}},"applyParser"),Z=/[\s.:=]/,B=a(e=>{const n=`Flag name "${e}"`;if(e.length===0)throw new Error(`${n} cannot be empty`);const t=e.match(Z);if(t)throw new Error(`${n} cannot contain "${t?.[0]}"`)},"validateFlagName"),b=a((e,n,t)=>{if(e.has(n))throw new Error(`Duplicate flags named "${n}"`);e.set(n,t)},"setFlag"),M=a(e=>{const n=new Map;for(const t in e){if(!y(e,t))continue;B(t);const r=e[t],s=[t,...d(r),r];b(n,t,s);const c=F(t);if(t!==c&&b(n,c,s),"alias"in r&&typeof r.alias=="string"){const{alias:i}=r,o=`Flag alias "${i}" for flag "${t}"`;if(t.length===1)throw new Error(`${o} cannot be defined for a single-character flag`);if(i.length===0)throw new Error(`${o} cannot be empty`);if(i.length>1)throw new Error(`${o} must be a single character`);b(n,i,s)}}return n},"createRegistry"),R=a(e=>{const n=new Map,t={},r=[];for(const s of e)if(s.type===N){let c=n.get(s.name);c||(c=[],n.set(s.name,c)),c.push(s.value)}else s.type===P?(y(t,s.name)||(t[s.name]=[]),t[s.name].push(s.value)):r.push(s.value);return{knownFlagValues:n,unknownFlags:t,positionals:r}},"groupEntries"),W=a((e,n,t)=>{if((!t||t.length===0)&&!w(e)&&"default"in e){const{default:r}=e;return typeof r=="function"?r():r}return n?t??[]:t&&t.at(-1)},"resolveFlagValue"),H=a((e,n,t,r)=>{const{knownFlagValues:s,unknownFlags:c,positionals:i}=R(t),o={};for(const l in e){if(!y(e,l))continue;const f=n.get(l);f&&(o[l]=W(f[3],f[2],s.get(l)))}return{flags:o,unknownFlags:c,_:h([...i,...r],r)}},"finalizeParsed");export{L as A,N as K,P as U,T as a,V as b,M as c,K as d,d as e,H as f,_ as g,F as h,w as i,G as n,E as p,I as s};
/**
* Standard Schema (https://standardschema.dev) support: the vendored v1 spec
* types plus the runtime helpers type-flag uses to detect and adapt schemas.
* The spec is vendored rather than depended on to keep type-flag zero-dependency.
*/
/**
* Minimal vendored subset of the Standard Schema spec, v1. Mirrors
* `@standard-schema/spec`. Kept byte-compatible with upstream, which relies on a
* namespace merged with an interface of the same name, so the conflicting
* stylistic rules are disabled here.
*/
declare namespace StandardSchemaV1 {
interface Props<Input = unknown, Output = Input> {
readonly version: 1;
readonly vendor: string;
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
readonly types?: Types<Input, Output> | undefined;
}
type Result<Output> = SuccessResult<Output> | FailureResult;
interface SuccessResult<Output> {
readonly value: Output;
readonly issues?: undefined;
}
interface FailureResult {
readonly issues: ReadonlyArray<Issue>;
}
interface Issue {
readonly message: string;
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
}
interface PathSegment {
readonly key: PropertyKey;
}
interface Types<Input = unknown, Output = Input> {
readonly input: Input;
readonly output: Output;
}
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
}
interface StandardSchemaV1<Input = unknown, Output = Input> {
readonly '~standard': StandardSchemaV1.Props<Input, Output>;
}
/**
* Detect a Standard Schema (Zod, Valibot, ArkType, ...). Used to accept schemas
* directly as flag types, and exported so tools built on type-flag can apply the
* same check when introspecting flag definitions.
*/
declare const isStandardSchema: (value: unknown) => value is StandardSchemaV1;
type Simplify<T> = {
[Key in keyof T]: T[Key];
} & {};
/**
* A function that processes a command-line argument and returns a typed value.
*
* @example
* ```ts
* const toUpperCase = (value: string) => value.toUpperCase();
* ```
*/
type TypeFunction<ReturnType = unknown> = (...args: any[]) => ReturnType;
/**
* The value used to type a flag: a parser function or a Standard Schema.
*/
type FlagTypeValue = TypeFunction | StandardSchemaV1;
/**
* A shorthand for defining a flag's type.
*
* - Use a single `TypeFunction` or Standard Schema to accept one value.
* - Use a readonly tuple (e.g. `[TypeFunction]`) to accept multiple values (as an array).
*
* @see FlagSchema
*/
type FlagType = (FlagTypeValue | readonly [FlagTypeValue]);
/**
* Workaround for TypeScript bug where `Readonly<T>` in parameter position breaks
* conditional type matching in return type. Adding `& AnyObject` to extends clauses
* fixes the matcher.
*
* @see https://github.com/microsoft/TypeScript/issues/62720
*/
type AnyObject = Record<PropertyKey, unknown>;
/**
* Defines the complete schema for a command-line flag.
*/
type FlagSchema = {
/**
* The function or tuple of functions that parse the `argv` string into a typed value.
*
* @example
* ```ts
* type: String
* ```
* @example
* ```ts
* type: [Boolean]
* ```
* @example
* ```ts
* type: (value: string) => moment(value).toDate()
* ```
*/
type: FlagType;
/**
* A single-character alias for the flag.
*
* @example
* ```ts
* alias: 's'
* ```
*/
alias?: string;
/**
* The default value for the flag if not provided.
* Can also be a function that returns the default.
*
* @example
* ```ts
* default: 'hello'
* ```
* @example
* ```ts
* default: () => [1, 2, 3]
* ```
*/
default?: unknown | (() => unknown);
} & AnyObject;
/**
* A flag definition can either be a `FlagType` or a full `FlagSchema` object.
*/
type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
/**
* A map of flag names to their definitions.
*/
type Flags<ExtraOptions = Record<string, unknown>> = {
[flagName: string]: FlagTypeOrSchema<ExtraOptions>;
};
/**
* Positional arguments with post-`--` values exposed separately.
*/
type PositionalArguments = string[] & {
/** Arguments that appeared after the `--` separator. */
'--': string[];
};
type InferDefaultType<Flag extends FlagTypeOrSchema, Fallback> = Flag extends {
default: infer DefaultType | (() => infer DefaultType);
} & AnyObject ? DefaultType : Fallback;
/**
* Resolves the output type of a single flag-type element: a parser function's
* return type, or a Standard Schema's output type.
*/
type InferType<Element> = (Element extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Element> : Element extends TypeFunction<infer Return> ? Return : never);
type FlagTypeOf<Flag> = (Flag extends {
type: infer Type extends FlagType;
} & AnyObject ? Type : Flag);
/**
* Infers the final JavaScript type of a flag from its schema.
*
* `FlagTypeOf` unwraps the `{ type }` object form first, so only the two
* underlying shapes (array vs scalar) need matching. `InferType` then resolves
* each element whether it is a function or a schema.
*/
type InferFlagType<Flag extends FlagTypeOrSchema> = (FlagTypeOf<Flag> extends readonly [infer Element extends FlagTypeValue] ? InferArrayType<Flag, Element> : FlagTypeOf<Flag> extends infer Element extends FlagTypeValue ? InferScalarType<Flag, Element> : unknown);
type InferArrayType<Flag extends FlagTypeOrSchema, Element> = (InferType<Element> extends infer Output ? (Output[] | InferDefaultType<Flag, never>) : never);
type InferScalarType<Flag extends FlagTypeOrSchema, Element> = (InferType<Element> extends infer Output ? ([
Output
] extends [never] ? Output : (Output | InferDefaultType<Flag, undefined>)) : never);
/**
* The fully inferred return type from a given flag schema configuration.
*/
type TypeFlag<Schemas extends Flags = Flags> = {
/** Parsed values keyed by flag name. */
flags: {
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
};
/** Flags that were passed but not defined in the schema. */
unknownFlags: {
[flagName: string]: (string | boolean)[];
};
/**
* Positional arguments (non-flag values).
* Includes a special `"--"` key for arguments after the double dash.
*/
_: PositionalArguments;
/**
* Every interpreted argv element, in the order it appeared on the command
* line. Unlike `flags` (which groups values by flag name), this preserves the
* relative order across different flags and positional arguments.
*
* Only covers what the parser interprets: elements after the `--` delimiter
* are not parsed, so they are excluded here (find them in `_['--']`).
*
* Advanced: most CLIs only need `flags`. Reach for `entries` when the order
* of operations across different flags matters — e.g. assembling a curl-style
* request body from interleaved `-d` and `--data-urlencode`.
*/
entries: ParsedArgvEntry[];
};
/** Constant indicating a known flag token type. */
declare const KNOWN_FLAG = "known-flag";
/** Constant indicating an unknown flag token type. */
declare const UNKNOWN_FLAG = "unknown-flag";
/** Constant indicating a positional argument token type. */
declare const ARGUMENT = "argument";
/**
* A single interpreted argv element from {@link TypeFlag.entries}, discriminated
* by `type`.
*/
type ParsedArgvEntry = {
type: typeof KNOWN_FLAG;
/**
* Canonical schema key — always the name as declared in the schema
* (e.g. `dataUrlencode`), regardless of whether the alias (`-d`),
* kebab-case (`--data-urlencode`), or camelCase form was used in argv.
*/
name: string;
/** Parsed value for this single occurrence. */
value: unknown;
} | {
type: typeof UNKNOWN_FLAG;
/** Raw flag name as it appeared in argv (not camelCased). */
name: string;
/** Explicit value, or `true` when the flag had no value. */
value: string | boolean;
} | {
type: typeof ARGUMENT;
/** The positional argument value. */
value: string;
};
/**
* A function to dynamically ignore specific elements during parsing.
* Return `true` to skip the element, or `false`/`undefined` to process it normally.
*
* @param type - The type of element being processed:
* - `'argument'`: A positional argument (non-flag value)
* - `'known-flag'`: A flag defined in the schema
* - `'unknown-flag'`: A flag not defined in the schema
* @param argvElement - The raw argv string. For arguments, this is the value itself.
* For flags, this is the flag name (e.g., `'--verbose'` or `'-v'`).
* @param flagValue - The value associated with a flag, if any.
* - For flags with explicit values: the string value (e.g., `'--port=3000'` → `'3000'`)
* - For boolean flags or flags without values: `undefined`
* - For arguments (`type === 'argument'`): always `undefined`
* @returns `true` to ignore/skip this element, `false` or `undefined` to process it
*
* @example
* ```ts
* // Ignore all unknown flags
* ignore: (type) => type === 'unknown-flag'
* ```
*
* @example
* ```ts
* // Ignore arguments starting with a dot
* ignore: (type, argvElement) => type === 'argument' && argvElement.startsWith('.')
* ```
*
* @example
* ```ts
* // Ignore a specific flag
* ignore: (type, argvElement) => argvElement === '--internal-only'
* ```
*/
type IgnoreFunction = (type: typeof ARGUMENT | typeof KNOWN_FLAG | typeof UNKNOWN_FLAG, argvElement: string, flagValue?: string) => boolean | void;
/**
* Options to customize the flag parsing behavior.
*/
type TypeFlagOptions = {
/**
* Optional function to skip certain argv elements from parsing.
*/
ignore?: IgnoreFunction;
/**
* Enable `--no-<flag>` negation for boolean flags.
*
* When enabled, `--no-verbose` is equivalent to `--verbose=false`.
* Only applies to flags defined as `Boolean` in the schema.
* Last-wins semantics apply between `--flag` and `--no-flag`.
*/
booleanNegation?: boolean;
};
export { StandardSchemaV1 as e, isStandardSchema as i };
export type { Flags as F, InferFlagType as I, ParsedArgvEntry as P, Simplify as S, TypeFlagOptions as T, TypeFlag as a, FlagType as b, IgnoreFunction as c, PositionalArguments as d };
+2
-2

@@ -1,3 +0,3 @@

import { F as Flags, T as TypeFlagOptions, S as Simplify, a as TypeFlag, b as FlagType, I as InferFlagType } from './types-eI9jH-uD.js';
export { c as IgnoreFunction, P as PositionalArguments } from './types-eI9jH-uD.js';
import { F as Flags, T as TypeFlagOptions, S as Simplify, a as TypeFlag, b as FlagType, I as InferFlagType } from './types-DlD92pZz.js';
export { c as IgnoreFunction, P as ParsedArgvEntry, d as PositionalArguments } from './types-DlD92pZz.js';

@@ -4,0 +4,0 @@ /**

@@ -1,1 +0,1 @@

var P=Object.defineProperty;var l=(i,o)=>P(i,"name",{value:o,configurable:!0});import{c as b,a as _,s as D,b as B,f as E,A as O,h as R,n as G,d as L,p as T,e as W}from"./internal-BrnksKa1.mjs";const m="known-flag",z="unknown-flag",K="argument",S=l((i,o=process.argv.slice(2),{ignore:h,booleanNegation:d}={})=>{const n=[],g=b(i),a={},p=[];let f=[],F,A,t,r;const u=l((s,e)=>{n.push(t),e&&n.push(e),F.push(L(A,s||"",r))},"flushFlagValue");return _(o,{knownFlags:g,onFlag(s,e,c){const V=c.length===O,v=V||s.length>1?g.get(s):void 0;let w;if(!v&&d&&!V&&s.length>3&&s.startsWith("no-")){const N=g.get(s.slice(3));N&&N[1]===Boolean&&(w=N[0])}if(!h?.(v||w?m:z,s,e)){if(v){const[N,k]=v;F=N,A=k,t=c,r=s;const y=G(k,e);if(y===void 0)return!0;u(y);return}if(w){w.push(!1),n.push(c);return}R(a,s)||(a[s]=[]),a[s].push(e===void 0?!0:e),n.push(c)}},onValue:u,onArgument:l((s,e,c)=>{h?.(K,o[e[0]])||(p.push(...s),c?(f=s,o.splice(e[0])):n.push(e))},"onArgument")}),D(o,n),{flags:E(i,g),unknownFlags:a,_:B(p,f)}},"typeFlag"),U=l((i,o,h=process.argv.slice(2))=>{const d=new Set(i.split(",").map(t=>T(t)?.[0])),[n,g]=W(o),a=[],p=[];let f,F;const A=l((t,r,u,s)=>{p.push(t),s&&p.push(s),a.push(L(n,u||"",r))},"pushValue");return _(h,{knownFlags:d,onFlag:l((t,r,u)=>{if(!d.has(t)||!g&&a.length>0)return;const s=G(n,r);if(s===void 0)return f=u,F=t,!0;A(u,t,s)},"onFlag"),onValue:l((t,r)=>{A(f,F,t,r)},"onValue")}),D(h,p),g?a:a[0]},"getFlag");export{U as getFlag,S as typeFlag};
var B=Object.defineProperty;var l=(u,n)=>B(u,"name",{value:n,configurable:!0});import{c as E,a as D,s as G,f as K,A as P,K as m,U as L,n as R,b as _,d as b,p as T,e as U}from"./internal-CAAarqqk.mjs";const W=l((u,n=process.argv.slice(2),{ignore:c,booleanNegation:N}={})=>{const r=[],p=E(u),a=[];let i=[],h,f,A,t;const o=l((s,e)=>{r.push(A),e&&r.push(e),a.push({type:m,name:h,value:b(f,s||"",t)})},"flushFlagValue");return D(n,{knownFlags:p,onFlag(s,e,g){const v=g.length===P,d=v||s.length>1?p.get(s):void 0;let y;if(!d&&N&&!v&&s.length>3&&s.startsWith("no-")){const F=p.get(s.slice(3));F&&F[1]===Boolean&&([y]=F)}if(!c?.(d||y?m:L,s,e)){if(d){const[F,V]=d;h=F,f=V,A=g,t=s;const w=R(V,e);if(w===void 0)return!0;o(w);return}if(y){a.push({type:m,name:y,value:!1}),r.push(g);return}a.push({type:L,name:s,value:e===void 0?!0:e}),r.push(g)}},onValue:o,onArgument:l((s,e,g)=>{if(!c?.(_,n[e[0]])){if(g){i=s,n.splice(e[0]);return}for(const v of s)a.push({type:_,value:v});r.push(e)}},"onArgument")}),G(n,r),{...K(u,p,a,i),entries:a}},"typeFlag"),k=l((u,n,c=process.argv.slice(2))=>{const N=new Set(u.split(",").map(t=>T(t)?.[0])),[r,p]=U(n),a=[],i=[];let h,f;const A=l((t,o,s,e)=>{i.push(t),e&&i.push(e),a.push(b(r,s||"",o))},"pushValue");return D(c,{knownFlags:N,onFlag:l((t,o,s)=>{if(!N.has(t)||!p&&a.length>0)return;const e=R(r,o);if(e===void 0)return h=s,f=t,!0;A(s,t,e)},"onFlag"),onValue:l((t,o)=>{A(h,f,t,o)},"onValue")}),G(c,i),p?a:a[0]},"getFlag");export{k as getFlag,W as typeFlag};

@@ -1,3 +0,3 @@

import { P as PositionalArguments } from './types-eI9jH-uD.js';
export { d as StandardSchemaV1, i as isStandardSchema } from './types-eI9jH-uD.js';
import { d as PositionalArguments } from './types-DlD92pZz.js';
export { e as StandardSchemaV1, i as isStandardSchema } from './types-DlD92pZz.js';

@@ -4,0 +4,0 @@ /**

@@ -1,1 +0,1 @@

import{g as s,i as o,j as r}from"./internal-BrnksKa1.mjs";export{s as createPositionalArguments,o as flagNameToKebab,r as isStandardSchema};
import{g as s,h as o,i as r}from"./internal-CAAarqqk.mjs";export{s as createPositionalArguments,o as flagNameToKebab,r as isStandardSchema};
{
"name": "type-flag",
"version": "5.0.0-beta.14",
"version": "5.0.0-beta.15",
"description": "Typed command-line arguments parser",

@@ -5,0 +5,0 @@ "keywords": [

@@ -382,2 +382,39 @@ <p align="center">

### Ordered Entries
> [!NOTE]
> Advanced. Most CLIs only need `flags`. Reach for `entries` when the order of operations _across_ different flags matters.
`flags` groups values by flag name, which discards how occurrences of different flags interleaved on the command line. `entries` is the ordered stream of every interpreted argv element, so that relative order is preserved.
```ts
const parsed = typeFlag({
data: {
type: [String],
alias: 'd'
},
dataUrlencode: [String]
})
// $ my-script -d a --data-urlencode b -d c
parsed.flags // { data: ['a', 'c'], dataUrlencode: ['b'] }
parsed.entries
// [
// { type: 'known-flag', name: 'data', value: 'a' },
// { type: 'known-flag', name: 'dataUrlencode', value: 'b' },
// { type: 'known-flag', name: 'data', value: 'c' }
// ]
```
Each entry is discriminated by `type`:
- `known-flag` — a flag defined in the schema. `name` is the **canonical schema key** (regardless of whether the alias, kebab-case, or camelCase form was used), and `value` is the parsed value for that single occurrence.
- `unknown-flag` — a flag not in the schema. `name` is the raw argv name; `value` is the explicit value or `true`.
- `argument` — a positional value.
Only parsed elements appear. Tokens after the `--` delimiter are not parsed, so they are excluded from `entries` — find them in [`_['--']`](#arguments-and---).
This is useful for curl-style data assembly (`-d` / `--data-urlencode` joined in argv order), debugging "which occurrence won", or any CLI where flags are an ordered instruction log rather than independent settings.
### Value Delimiters

@@ -557,5 +594,8 @@

}
entries: ParsedArgvEntry[]
}
```
See [Ordered Entries](#ordered-entries) for the `ParsedArgvEntry` shape.
#### flagSchema

@@ -562,0 +602,0 @@

---
name: type-flag
description: "Use when working with type-flag or building CLIs on top of it (e.g. cleye). Strongly-typed Node.js argv parser: schema syntax (String/Number/Boolean, arrays, custom parser functions, Standard Schema validators like Zod/Valibot/ArkType, aliases, defaults, single-char names), return shape (flags/unknownFlags/positional args), flag forms (long/short/grouping, =/:/. delimiters, kebab/camelCase), boolean negation via `--no-`, and the `ignore` callback for multi-command dispatch."
description: "Use when working with type-flag or building CLIs on top of it (e.g. cleye). Strongly-typed Node.js argv parser: schema syntax (String/Number/Boolean, arrays, custom parser functions, Standard Schema validators like Zod/Valibot/ArkType, aliases, defaults, single-char names), return shape (flags/unknownFlags/positional args, plus the advanced ordered `entries` stream), flag forms (long/short/grouping, =/:/. delimiters, kebab/camelCase), boolean negation via `--no-`, and the `ignore` callback for multi-command dispatch."
---

@@ -81,5 +81,19 @@

_: string[] & { '--': string[] }, // positional; everything after `--` also in `_['--']`
entries: ParsedArgvEntry[], // advanced; see below
}
```
### `entries` (advanced)
Ordered stream of every interpreted argv element, preserving relative order across different flags (which `flags` discards by grouping per name). Most CLIs ignore this; use it when order across flags matters (e.g. curl `-d`/`--data-urlencode` body assembly).
```ts
type ParsedArgvEntry =
| { type: 'known-flag'; name: string; value: unknown } // name = canonical schema key (alias/kebab resolved)
| { type: 'unknown-flag'; name: string; value: string | boolean } // name = raw argv name
| { type: 'argument'; value: string }
```
`-d a --data-urlencode b -d c` → three `known-flag` items in argv order, each `name` being the canonical schema key. Ignored elements (via `ignore`) are excluded. Tokens after `--` are not parsed, so they don't appear here (use `_['--']`).
## Flag forms

@@ -86,0 +100,0 @@

var x=Object.defineProperty;var i=(e,t)=>x(e,"name",{value:t,configurable:!0});const h=i(e=>(typeof e=="object"||typeof e=="function")&&e!==null&&"~standard"in e,"isStandardSchema"),N=i(e=>(t=>{const r=e["~standard"].validate(t);if(r instanceof Promise)throw new TypeError("Async schemas are not supported");if(r.issues)throw new Error(r.issues[0]?.message??"Validation failed");return r.value}),"schemaToParser"),D=/(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])/g,F=/[A-Z]/,P=i(e=>F.test(e)?e.replaceAll(D,"-").toLowerCase():e.toLowerCase(),"flagNameToKebab"),{hasOwnProperty:V}=Object.prototype,g=i((e,t)=>V.call(e,t),"hasOwn"),d=i(e=>h(e)?[N(e),!1]:typeof e=="function"?[e,!1]:Array.isArray(e)?[d(e[0])[0],!0]:d(e.type),"parseFlagType"),C=i((e,t)=>e===Boolean?t!=="false":t,"normalizeBoolean"),L=i((e,t,r)=>{if(typeof t=="boolean")return t;if(e===Number&&t==="")return Number.NaN;try{return e(t)}catch(s){throw new TypeError(`Flag "--${r}": ${s instanceof Error?s.message:s}`,{cause:s})}},"applyParser"),O=/[\s.:=]/,I=i(e=>{const t=`Flag name "${e}"`;if(e.length===0)throw new Error(`${t} cannot be empty`);const r=e.match(O);if(r)throw new Error(`${t} cannot contain "${r?.[0]}"`)},"validateFlagName"),w=i((e,t,r)=>{if(e.has(t))throw new Error(`Duplicate flags named "${t}"`);e.set(t,r)},"setFlag"),T=i(e=>{const t=new Map;for(const r in e){if(!g(e,r))continue;I(r);const s=e[r],a=[[],...d(s),s];w(t,r,a);const c=P(r);if(r!==c&&w(t,c,a),"alias"in s&&typeof s.alias=="string"){const{alias:o}=s,n=`Flag alias "${o}" for flag "${r}"`;if(r.length===1)throw new Error(`${n} cannot be defined for a single-character flag`);if(o.length===0)throw new Error(`${n} cannot be empty`);if(o.length>1)throw new Error(`${n} must be a single character`);w(t,o,a)}}return t},"createRegistry"),j=i((e,t)=>{const r={};for(const s in e){if(!g(e,s))continue;const a=t.get(s);if(!a)continue;const[c,,o,n]=a;if(c.length===0&&!h(n)&&"default"in n){let{default:l}=n;typeof l=="function"&&(l=l()),r[s]=l}else r[s]=o?c:c.pop()}return r},"finalizeFlags"),p="--",z=3,Z=/^-{1,2}\w/,k=/^-(?:\d+(?:\.\d*)?|\.\d+)(?:e[-+]?\d+)?$/i,B=i((e,t)=>{if(!k.test(e))return!1;for(let r=1;r<e.length;r+=1)if(!t.has(e[r]))return!0;return!1},"isNegativeNumberValue"),$=i(e=>{if(!Z.test(e))return;const t=!e.startsWith(p);let r=e.slice(t?1:2),s,a=-1;for(const c of["=",":","."]){const o=r.indexOf(c);o!==-1&&(a===-1||o<a)&&(a=o)}return a!==-1&&(s=r.slice(a+1),r=r.slice(0,a)),[r,s,t]},"parseFlagArgv"),_=i((e,{onFlag:t,onValue:r,onArgument:s,knownFlags:a})=>{let c=!1;const o=i((n,l)=>{if(!c)return!0;c=!1,r?.(n,l)},"triggerValueCallback");for(let n=0;n<e.length;n+=1){const l=e[n];if(l===p){o();const f=e.slice(n+1);s?.(f,[n],!0);break}if(c&&a&&B(l,a)){o(l,[n]);continue}const y=$(l);if(y){if(o(),!t)continue;const[f,m,E]=y;if(E)for(let u=0;u<f.length;u+=1){o();const A=u===f.length-1;c=t(f[u],A?m:void 0,[n,u+1,A])===!0}else c=t(f,m,[n])===!0}else o(l,[n])&&s?.([l],[n])}o()},"argvIterator"),H=i((e,t)=>{for(let r=t.length-1;r>=0;r-=1){const[s,a,c]=t[r];if(a){const o=e[s];let n=o.slice(0,a);if(c||(n+=o.slice(a+1)),n!=="-"){e[s]=n;continue}}e.splice(s,1)}},"spliceFromArgv"),b=i((e,t)=>Object.assign(e,{[p]:t}),"createPositionalArgumentsFromParts"),R=i(e=>{const t=e.indexOf(p);if(t===-1)return b([...e],[]);const r=e.slice(0,t),s=e.slice(t+1);return b([...r,...s],s)},"createPositionalArguments");export{z as A,_ as a,b,T as c,L as d,d as e,j as f,R as g,g as h,P as i,h as j,C as n,$ as p,H as s};
/**
* Standard Schema (https://standardschema.dev) support: the vendored v1 spec
* types plus the runtime helpers type-flag uses to detect and adapt schemas.
* The spec is vendored rather than depended on to keep type-flag zero-dependency.
*/
/**
* Minimal vendored subset of the Standard Schema spec, v1. Mirrors
* `@standard-schema/spec`. Kept byte-compatible with upstream, which relies on a
* namespace merged with an interface of the same name, so the conflicting
* stylistic rules are disabled here.
*/
declare namespace StandardSchemaV1 {
interface Props<Input = unknown, Output = Input> {
readonly version: 1;
readonly vendor: string;
readonly validate: (value: unknown) => Result<Output> | Promise<Result<Output>>;
readonly types?: Types<Input, Output> | undefined;
}
type Result<Output> = SuccessResult<Output> | FailureResult;
interface SuccessResult<Output> {
readonly value: Output;
readonly issues?: undefined;
}
interface FailureResult {
readonly issues: ReadonlyArray<Issue>;
}
interface Issue {
readonly message: string;
readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined;
}
interface PathSegment {
readonly key: PropertyKey;
}
interface Types<Input = unknown, Output = Input> {
readonly input: Input;
readonly output: Output;
}
type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema['~standard']['types']>['output'];
}
interface StandardSchemaV1<Input = unknown, Output = Input> {
readonly '~standard': StandardSchemaV1.Props<Input, Output>;
}
/**
* Detect a Standard Schema (Zod, Valibot, ArkType, ...). Used to accept schemas
* directly as flag types, and exported so tools built on type-flag can apply the
* same check when introspecting flag definitions.
*/
declare const isStandardSchema: (value: unknown) => value is StandardSchemaV1;
type Simplify<T> = {
[Key in keyof T]: T[Key];
} & {};
/**
* A function that processes a command-line argument and returns a typed value.
*
* @example
* ```ts
* const toUpperCase = (value: string) => value.toUpperCase();
* ```
*/
type TypeFunction<ReturnType = unknown> = (...args: any[]) => ReturnType;
/**
* The value used to type a flag: a parser function or a Standard Schema.
*/
type FlagTypeValue = TypeFunction | StandardSchemaV1;
/**
* A shorthand for defining a flag's type.
*
* - Use a single `TypeFunction` or Standard Schema to accept one value.
* - Use a readonly tuple (e.g. `[TypeFunction]`) to accept multiple values (as an array).
*
* @see FlagSchema
*/
type FlagType = (FlagTypeValue | readonly [FlagTypeValue]);
/**
* Workaround for TypeScript bug where `Readonly<T>` in parameter position breaks
* conditional type matching in return type. Adding `& AnyObject` to extends clauses
* fixes the matcher.
*
* @see https://github.com/microsoft/TypeScript/issues/62720
*/
type AnyObject = Record<PropertyKey, unknown>;
/**
* Defines the complete schema for a command-line flag.
*/
type FlagSchema = {
/**
* The function or tuple of functions that parse the `argv` string into a typed value.
*
* @example
* ```ts
* type: String
* ```
* @example
* ```ts
* type: [Boolean]
* ```
* @example
* ```ts
* type: (value: string) => moment(value).toDate()
* ```
*/
type: FlagType;
/**
* A single-character alias for the flag.
*
* @example
* ```ts
* alias: 's'
* ```
*/
alias?: string;
/**
* The default value for the flag if not provided.
* Can also be a function that returns the default.
*
* @example
* ```ts
* default: 'hello'
* ```
* @example
* ```ts
* default: () => [1, 2, 3]
* ```
*/
default?: unknown | (() => unknown);
} & AnyObject;
/**
* A flag definition can either be a `FlagType` or a full `FlagSchema` object.
*/
type FlagTypeOrSchema<ExtraOptions = Record<string, unknown>> = FlagType | (FlagSchema & ExtraOptions);
/**
* A map of flag names to their definitions.
*/
type Flags<ExtraOptions = Record<string, unknown>> = {
[flagName: string]: FlagTypeOrSchema<ExtraOptions>;
};
/**
* Positional arguments with post-`--` values exposed separately.
*/
type PositionalArguments = string[] & {
/** Arguments that appeared after the `--` separator. */
'--': string[];
};
type InferDefaultType<Flag extends FlagTypeOrSchema, Fallback> = Flag extends {
default: infer DefaultType | (() => infer DefaultType);
} & AnyObject ? DefaultType : Fallback;
/**
* Resolves the output type of a single flag-type element: a parser function's
* return type, or a Standard Schema's output type.
*/
type InferType<Element> = (Element extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Element> : Element extends TypeFunction<infer Return> ? Return : never);
type FlagTypeOf<Flag> = (Flag extends {
type: infer Type extends FlagType;
} & AnyObject ? Type : Flag);
/**
* Infers the final JavaScript type of a flag from its schema.
*
* `FlagTypeOf` unwraps the `{ type }` object form first, so only the two
* underlying shapes (array vs scalar) need matching. `InferType` then resolves
* each element whether it is a function or a schema.
*/
type InferFlagType<Flag extends FlagTypeOrSchema> = (FlagTypeOf<Flag> extends readonly [infer Element extends FlagTypeValue] ? InferArrayType<Flag, Element> : FlagTypeOf<Flag> extends infer Element extends FlagTypeValue ? InferScalarType<Flag, Element> : unknown);
type InferArrayType<Flag extends FlagTypeOrSchema, Element> = (InferType<Element> extends infer Output ? (Output[] | InferDefaultType<Flag, never>) : never);
type InferScalarType<Flag extends FlagTypeOrSchema, Element> = (InferType<Element> extends infer Output ? ([
Output
] extends [never] ? Output : (Output | InferDefaultType<Flag, undefined>)) : never);
/**
* The fully inferred return type from a given flag schema configuration.
*/
type TypeFlag<Schemas extends Flags = Flags> = {
/** Parsed values keyed by flag name. */
flags: {
[flag in keyof Schemas]: InferFlagType<Schemas[flag]>;
};
/** Flags that were passed but not defined in the schema. */
unknownFlags: {
[flagName: string]: (string | boolean)[];
};
/**
* Positional arguments (non-flag values).
* Includes a special `"--"` key for arguments after the double dash.
*/
_: PositionalArguments;
};
/** Constant indicating a known flag token type. */
declare const KNOWN_FLAG = "known-flag";
/** Constant indicating an unknown flag token type. */
declare const UNKNOWN_FLAG = "unknown-flag";
/** Constant indicating a positional argument token type. */
declare const ARGUMENT = "argument";
/**
* A function to dynamically ignore specific elements during parsing.
* Return `true` to skip the element, or `false`/`undefined` to process it normally.
*
* @param type - The type of element being processed:
* - `'argument'`: A positional argument (non-flag value)
* - `'known-flag'`: A flag defined in the schema
* - `'unknown-flag'`: A flag not defined in the schema
* @param argvElement - The raw argv string. For arguments, this is the value itself.
* For flags, this is the flag name (e.g., `'--verbose'` or `'-v'`).
* @param flagValue - The value associated with a flag, if any.
* - For flags with explicit values: the string value (e.g., `'--port=3000'` → `'3000'`)
* - For boolean flags or flags without values: `undefined`
* - For arguments (`type === 'argument'`): always `undefined`
* @returns `true` to ignore/skip this element, `false` or `undefined` to process it
*
* @example
* ```ts
* // Ignore all unknown flags
* ignore: (type) => type === 'unknown-flag'
* ```
*
* @example
* ```ts
* // Ignore arguments starting with a dot
* ignore: (type, argvElement) => type === 'argument' && argvElement.startsWith('.')
* ```
*
* @example
* ```ts
* // Ignore a specific flag
* ignore: (type, argvElement) => argvElement === '--internal-only'
* ```
*/
type IgnoreFunction = (type: typeof ARGUMENT | typeof KNOWN_FLAG | typeof UNKNOWN_FLAG, argvElement: string, flagValue?: string) => boolean | void;
/**
* Options to customize the flag parsing behavior.
*/
type TypeFlagOptions = {
/**
* Optional function to skip certain argv elements from parsing.
*/
ignore?: IgnoreFunction;
/**
* Enable `--no-<flag>` negation for boolean flags.
*
* When enabled, `--no-verbose` is equivalent to `--verbose=false`.
* Only applies to flags defined as `Boolean` in the schema.
* Last-wins semantics apply between `--flag` and `--no-flag`.
*/
booleanNegation?: boolean;
};
export { StandardSchemaV1 as d, isStandardSchema as i };
export type { Flags as F, InferFlagType as I, PositionalArguments as P, Simplify as S, TypeFlagOptions as T, TypeFlag as a, FlagType as b, IgnoreFunction as c };