@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.10
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/CHANGELOG.md +217 -1
- package/dist/core/cli/dispatch.d.mts +6 -5
- package/dist/core/cli/dispatch.mjs +205 -1
- package/dist/core/cli/help-links.d.mts +0 -1
- package/dist/core/cli/help-links.mjs +41 -1
- package/dist/core/cli/index.d.mts +81 -8
- package/dist/core/cli/index.mjs +945 -1
- package/dist/core/cli/planner.d.mts +5 -1
- package/dist/core/cli/planner.mjs +300 -1
- package/dist/core/cli/plugin.d.mts +1 -1
- package/dist/core/cli/plugin.mjs +41 -1
- package/dist/core/cli/propagate.d.mts +1 -1
- package/dist/core/cli/propagate.mjs +57 -1
- package/dist/core/cli/root-help.d.mts +2 -1
- package/dist/core/cli/root-help.mjs +226 -4
- package/dist/core/cli/root-surface.d.mts +12 -1
- package/dist/core/cli/root-surface.mjs +28 -1
- package/dist/core/cli/runtime-preflight.d.mts +14 -2
- package/dist/core/cli/runtime-preflight.mjs +169 -1
- package/dist/core/completion/index.d.mts +0 -1
- package/dist/core/completion/index.mjs +90 -1
- package/dist/core/completion/shells/bash.d.mts +0 -1
- package/dist/core/completion/shells/bash.mjs +308 -3
- package/dist/core/completion/shells/fish.d.mts +0 -1
- package/dist/core/completion/shells/fish.mjs +162 -2
- package/dist/core/completion/shells/powershell.d.mts +0 -1
- package/dist/core/completion/shells/powershell.mjs +358 -2
- package/dist/core/completion/shells/shared.d.mts +13 -2
- package/dist/core/completion/shells/shared.mjs +176 -1
- package/dist/core/completion/shells/zsh.d.mts +0 -1
- package/dist/core/completion/shells/zsh.mjs +251 -2
- package/dist/core/config/index.d.mts +2 -3
- package/dist/core/config/index.mjs +246 -1
- package/dist/core/config/package-json.d.mts +27 -4
- package/dist/core/config/package-json.mjs +386 -3
- package/dist/core/errors/index.d.mts +3 -3
- package/dist/core/errors/index.mjs +87 -1
- package/dist/core/execution/index.d.mts +0 -1
- package/dist/core/execution/index.mjs +201 -1
- package/dist/core/help/ansi.d.mts +11 -5
- package/dist/core/help/ansi.mjs +121 -2
- package/dist/core/help/index.d.mts +22 -3
- package/dist/core/help/index.mjs +341 -7
- package/dist/core/help/theme.d.mts +68 -0
- package/dist/core/help/theme.mjs +46 -0
- package/dist/core/json-schema/index.d.mts +15 -2
- package/dist/core/json-schema/index.mjs +536 -12
- package/dist/core/json-schema/meta-descriptions.generated.d.mts +55 -38
- package/dist/core/json-schema/meta-descriptions.generated.mjs +102 -28
- package/dist/core/output/activity.d.mts +0 -1
- package/dist/core/output/activity.mjs +452 -1
- package/dist/core/output/bind.mjs +56 -1
- package/dist/core/output/contracts.d.mts +4 -5
- package/dist/core/output/contracts.mjs +57 -1
- package/dist/core/output/display-value.mjs +32 -1
- package/dist/core/output/index.d.mts +21 -1
- package/dist/core/output/index.mjs +442 -2
- package/dist/core/output/renderers.d.mts +0 -1
- package/dist/core/output/renderers.mjs +46 -1
- package/dist/core/output/writer.mjs +12 -1
- package/dist/core/parse/index.d.mts +40 -7
- package/dist/core/parse/index.mjs +727 -1
- package/dist/core/prompt/index.d.mts +1 -1
- package/dist/core/prompt/index.mjs +348 -6
- package/dist/core/resolve/args.d.mts +1 -1
- package/dist/core/resolve/args.mjs +105 -1
- package/dist/core/resolve/coerce.d.mts +1 -1
- package/dist/core/resolve/coerce.mjs +336 -1
- package/dist/core/resolve/config.mjs +19 -1
- package/dist/core/resolve/contracts.d.mts +9 -4
- package/dist/core/resolve/errors.d.mts +0 -1
- package/dist/core/resolve/errors.mjs +140 -2
- package/dist/core/resolve/flags.d.mts +7 -2
- package/dist/core/resolve/flags.mjs +251 -1
- package/dist/core/resolve/index.d.mts +2 -2
- package/dist/core/resolve/index.mjs +85 -1
- package/dist/core/resolve/property.d.mts +4 -2
- package/dist/core/resolve/property.mjs +53 -1
- package/dist/core/schema/activity.d.mts +31 -11
- package/dist/core/schema/arg.d.mts +3 -4
- package/dist/core/schema/arg.mjs +463 -1
- package/dist/core/schema/command.d.mts +26 -6
- package/dist/core/schema/command.mjs +726 -1
- package/dist/core/schema/flag.d.mts +485 -19
- package/dist/core/schema/flag.mjs +705 -1
- package/dist/core/schema/index.d.mts +4 -2
- package/dist/core/schema/middleware.d.mts +4 -3
- package/dist/core/schema/middleware.mjs +41 -1
- package/dist/core/schema/number-constraints.mjs +60 -1
- package/dist/core/schema/prompt.d.mts +6 -3
- package/dist/core/schema/run.d.mts +20 -1
- package/dist/core/schema/string-constraints.d.mts +97 -0
- package/dist/core/schema/string-constraints.mjs +69 -0
- package/dist/core/schema/value-parsers.d.mts +78 -0
- package/dist/core/schema/value-parsers.mjs +142 -0
- package/dist/core/schema-dsl/runtime.mjs +271 -2
- package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
- package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
- package/dist/core/testkit/index.d.mts +0 -31
- package/dist/core/testkit/index.mjs +83 -1
- package/dist/index.d.mts +11 -6
- package/dist/index.mjs +22 -1
- package/dist/runtime/adapter.d.mts +38 -2
- package/dist/runtime/adapter.mjs +87 -1
- package/dist/runtime/auto.d.mts +2 -3
- package/dist/runtime/auto.mjs +45 -1
- package/dist/runtime/deno.d.mts +24 -5
- package/dist/runtime/deno.mjs +262 -2
- package/dist/runtime/detect.mjs +45 -1
- package/dist/runtime/index.d.mts +3 -4
- package/dist/runtime/node.d.mts +8 -2
- package/dist/runtime/node.mjs +220 -2
- package/dist/runtime/paths.mjs +48 -1
- package/dist/runtime.d.mts +4 -4
- package/dist/runtime.mjs +6 -1
- package/dist/strings.mjs +22 -1
- package/dist/testkit.d.mts +1 -0
- package/dist/testkit.mjs +5 -1
- package/dist/version.d.mts +7 -3
- package/dist/version.mjs +7 -1
- package/dreamcli.schema.json +36 -7
- package/package.json +45 -42
- package/dist/runtime/bun.d.mts +0 -28
- package/dist/runtime/bun.mjs +0 -1
- package/src/core/cli/dispatch.ts +0 -355
- package/src/core/cli/help-links.ts +0 -82
- package/src/core/cli/index.ts +0 -1614
- package/src/core/cli/planner.ts +0 -656
- package/src/core/cli/plugin.ts +0 -117
- package/src/core/cli/propagate.ts +0 -97
- package/src/core/cli/root-help.ts +0 -342
- package/src/core/cli/root-surface.ts +0 -87
- package/src/core/cli/runtime-preflight.ts +0 -456
- package/src/core/completion/index.ts +0 -138
- package/src/core/completion/shells/bash.ts +0 -459
- package/src/core/completion/shells/fish.ts +0 -259
- package/src/core/completion/shells/powershell.ts +0 -439
- package/src/core/completion/shells/shared.ts +0 -310
- package/src/core/completion/shells/zsh.ts +0 -381
- package/src/core/config/index.ts +0 -417
- package/src/core/config/package-json.ts +0 -560
- package/src/core/errors/index.ts +0 -193
- package/src/core/execution/index.ts +0 -265
- package/src/core/help/ansi.ts +0 -144
- package/src/core/help/index.ts +0 -563
- package/src/core/json-schema/index.ts +0 -910
- package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
- package/src/core/output/activity.ts +0 -575
- package/src/core/output/bind.ts +0 -59
- package/src/core/output/contracts.ts +0 -194
- package/src/core/output/display-value.ts +0 -48
- package/src/core/output/index.ts +0 -704
- package/src/core/output/renderers.ts +0 -125
- package/src/core/output/writer.ts +0 -46
- package/src/core/parse/index.ts +0 -742
- package/src/core/prompt/index.ts +0 -623
- package/src/core/resolve/args.ts +0 -144
- package/src/core/resolve/coerce.ts +0 -500
- package/src/core/resolve/config.ts +0 -26
- package/src/core/resolve/contracts.ts +0 -135
- package/src/core/resolve/errors.ts +0 -227
- package/src/core/resolve/flags.ts +0 -269
- package/src/core/resolve/index.ts +0 -108
- package/src/core/resolve/property.ts +0 -99
- package/src/core/schema/activity.ts +0 -240
- package/src/core/schema/arg.ts +0 -841
- package/src/core/schema/command.ts +0 -1500
- package/src/core/schema/flag.ts +0 -917
- package/src/core/schema/index.ts +0 -96
- package/src/core/schema/middleware.ts +0 -171
- package/src/core/schema/number-constraints.ts +0 -153
- package/src/core/schema/prompt.ts +0 -171
- package/src/core/schema/run.ts +0 -198
- package/src/core/schema-dsl/index.ts +0 -109
- package/src/core/schema-dsl/parse.ts +0 -262
- package/src/core/schema-dsl/runtime.ts +0 -609
- package/src/core/schema-dsl/to-json-schema.ts +0 -102
- package/src/core/testkit/index.ts +0 -147
- package/src/index.ts +0 -181
- package/src/runtime/adapter.ts +0 -303
- package/src/runtime/auto.ts +0 -86
- package/src/runtime/bun.ts +0 -48
- package/src/runtime/deno.ts +0 -367
- package/src/runtime/detect.ts +0 -105
- package/src/runtime/index.ts +0 -21
- package/src/runtime/node-builtins.d.ts +0 -27
- package/src/runtime/node.ts +0 -289
- package/src/runtime/paths.ts +0 -64
- package/src/runtime/support.ts +0 -77
- package/src/runtime.ts +0 -31
- package/src/schema.ts +0 -16
- package/src/strings.ts +0 -34
- package/src/testkit.ts +0 -25
- package/src/version.ts +0 -20
|
@@ -2,8 +2,10 @@ import { ActivityEvent, Fallback, ProgressHandle, ProgressOptions, SpinnerHandle
|
|
|
2
2
|
import { NumberConstraintViolation, NumberConstraints, describeNumberConstraintViolation, validateNumberConstraints } from "./number-constraints.mjs";
|
|
3
3
|
import { ARG_KINDS, ARG_PRESENCES, ArgBuilder, ArgConfig, ArgFactory, ArgKind, ArgParseFn, ArgPresence, ArgSchema, InferArg, InferArgs, ResolvedArgValue, WithArgPresence, WithVariadic, arg, createArgSchema } from "./arg.mjs";
|
|
4
4
|
import { ConfirmPromptConfig, InputPromptConfig, MultiselectPromptConfig, PROMPT_KINDS, PromptConfig, PromptConfigBase, PromptKind, PromptResult, SelectChoice, SelectPromptConfig } from "./prompt.mjs";
|
|
5
|
-
import {
|
|
5
|
+
import { StringConstraintViolation, StringConstraints, describeStringConstraintViolation, validateStringConstraints } from "./string-constraints.mjs";
|
|
6
|
+
import { DateFlagOptions, UrlFlagOptions } from "./value-parsers.mjs";
|
|
7
|
+
import { DuplicatePolicy, FLAG_KINDS, FLAG_PRESENCES, FlagAlias, FlagBuilder, FlagConfig, FlagFactory, FlagKind, FlagNegation, FlagParseFn, FlagPresence, FlagSchema, FlagSchemaOverrides, InferFlag, InferFlags, PathChecks, PathFlagOptions, ResolvedValue, WithPresence, createSchema, flag, getFlagNegatedName } from "./flag.mjs";
|
|
6
8
|
import { ErasedMiddlewareHandler, Middleware, MiddlewareHandler, MiddlewareParams, middleware } from "./middleware.mjs";
|
|
7
9
|
import { RunOptions, RunResult } from "./run.mjs";
|
|
8
10
|
import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, ErasedCommand, ErasedDeriveHandler, ErasedInteractiveResolver, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group } from "./command.mjs";
|
|
9
|
-
export { ARG_KINDS, ARG_PRESENCES, type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type ConfirmPromptConfig, type DeriveHandler, type DeriveParams, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type ErasedMiddlewareHandler, FLAG_KINDS, FLAG_PRESENCES, type Fallback, type FlagAlias, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagParseFn, type FlagPresence, type FlagSchema, type FlagSchemaOverrides, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, PROMPT_KINDS, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptKind, type PromptResult, type ResolvedArgValue, type ResolvedValue, type RunOptions, type RunResult, type SelectChoice, type SelectPromptConfig, type SpinnerHandle, type SpinnerOptions, type TableColumn, type TableFormat, type TableOptions, type TableStream, type WithArgPresence, type WithPresence, type WithVariadic, arg, command, createArgSchema, createSchema, describeNumberConstraintViolation, flag, group, middleware, validateNumberConstraints };
|
|
11
|
+
export { ARG_KINDS, ARG_PRESENCES, type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type ConfirmPromptConfig, type DateFlagOptions, type DeriveHandler, type DeriveParams, type DuplicatePolicy, type ErasedCommand, type ErasedDeriveHandler, type ErasedInteractiveResolver, type ErasedMiddlewareHandler, FLAG_KINDS, FLAG_PRESENCES, type Fallback, type FlagAlias, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagNegation, type FlagParseFn, type FlagPresence, type FlagSchema, type FlagSchemaOverrides, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, PROMPT_KINDS, type PathChecks, type PathFlagOptions, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptKind, type PromptResult, type ResolvedArgValue, type ResolvedValue, type RunOptions, type RunResult, type SelectChoice, type SelectPromptConfig, type SpinnerHandle, type SpinnerOptions, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type UrlFlagOptions, type WithArgPresence, type WithPresence, type WithVariadic, arg, command, createArgSchema, createSchema, describeNumberConstraintViolation, describeStringConstraintViolation, flag, getFlagNegatedName, group, middleware, validateNumberConstraints, validateStringConstraints };
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { CommandMeta, Out } from "./command.mjs";
|
|
2
|
-
|
|
3
2
|
//#region src/core/schema/middleware.d.ts
|
|
4
3
|
/**
|
|
5
4
|
* Parameters received by a middleware function at runtime.
|
|
@@ -48,7 +47,8 @@ type MiddlewareHandler<Output extends Record<string, unknown>> = (params: {
|
|
|
48
47
|
readonly flags: Readonly<Record<string, unknown>>;
|
|
49
48
|
readonly ctx: Readonly<Record<string, unknown>>;
|
|
50
49
|
readonly out: Out;
|
|
51
|
-
readonly meta: CommandMeta;
|
|
50
|
+
readonly meta: CommandMeta;
|
|
51
|
+
/** Pass context additions downstream. Must include all `Output` properties. */
|
|
52
52
|
readonly next: (additions: Output) => Promise<void>;
|
|
53
53
|
}) => void | Promise<void>;
|
|
54
54
|
/**
|
|
@@ -80,7 +80,8 @@ interface MiddlewareImpl {
|
|
|
80
80
|
* ```
|
|
81
81
|
*/
|
|
82
82
|
type Middleware<Output extends Record<string, unknown>> = MiddlewareImpl & {
|
|
83
|
-
/** @internal Phantom type brand — compile-time only. */
|
|
83
|
+
/** @internal Phantom type brand — compile-time only. */
|
|
84
|
+
readonly _output: Output;
|
|
84
85
|
};
|
|
85
86
|
/**
|
|
86
87
|
* Create a middleware definition.
|
|
@@ -1 +1,41 @@
|
|
|
1
|
-
|
|
1
|
+
//#region src/core/schema/middleware.ts
|
|
2
|
+
/**
|
|
3
|
+
* Create a middleware definition.
|
|
4
|
+
*
|
|
5
|
+
* Middleware runs before the action handler and can add typed context,
|
|
6
|
+
* short-circuit execution, or wrap downstream processing.
|
|
7
|
+
*
|
|
8
|
+
* @param handler - Function receiving `{ args, flags, ctx, out, meta, next }`.
|
|
9
|
+
* Call `next(additions)` to continue the chain with added context.
|
|
10
|
+
* Omitting the `next()` call short-circuits (e.g., for auth guards).
|
|
11
|
+
* @returns {@linkcode Middleware} to attach via `CommandBuilder.middleware()`.
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```ts
|
|
15
|
+
* // Auth guard — adds user to context or throws
|
|
16
|
+
* const auth = middleware(async ({ next }) => {
|
|
17
|
+
* const user = await getUser();
|
|
18
|
+
* if (!user) throw new CLIError('Not authenticated', { code: 'AUTH_REQUIRED' });
|
|
19
|
+
* return next({ user });
|
|
20
|
+
* });
|
|
21
|
+
*
|
|
22
|
+
* // Timing wrapper — measures downstream execution
|
|
23
|
+
* const timing = middleware(async ({ out, next }) => {
|
|
24
|
+
* const start = Date.now();
|
|
25
|
+
* await next({});
|
|
26
|
+
* out.info(`Done in ${Date.now() - start}ms`);
|
|
27
|
+
* });
|
|
28
|
+
*
|
|
29
|
+
* command('deploy')
|
|
30
|
+
* .middleware(timing)
|
|
31
|
+
* .middleware(auth)
|
|
32
|
+
* .action(({ ctx }) => {
|
|
33
|
+
* console.log(ctx.user.name); // typed!
|
|
34
|
+
* });
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
function middleware(handler) {
|
|
38
|
+
return { _handler: handler };
|
|
39
|
+
}
|
|
40
|
+
//#endregion
|
|
41
|
+
export { middleware };
|
|
@@ -1 +1,60 @@
|
|
|
1
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Validate a numeric value against constraints.
|
|
3
|
+
*
|
|
4
|
+
* The single source of truth for numeric-constraint checks, shared by the
|
|
5
|
+
* parse and coerce paths. Checks run in a fixed order — **finite → int → min →
|
|
6
|
+
* max** — and the first failure is returned. `NaN` is always rejected as a
|
|
7
|
+
* `finite` violation, regardless of the `finite` option (a non-finite value can
|
|
8
|
+
* otherwise slip past `min`/`max`, since `NaN < x` and `NaN > x` are both false).
|
|
9
|
+
*
|
|
10
|
+
* @param value - The numeric value to validate.
|
|
11
|
+
* @param constraints - Constraints to enforce, or `undefined` for defaults.
|
|
12
|
+
* @returns The first {@link NumberConstraintViolation}, or `undefined` if valid.
|
|
13
|
+
*/
|
|
14
|
+
function validateNumberConstraints(value, constraints) {
|
|
15
|
+
if (Number.isNaN(value)) return { kind: "finite" };
|
|
16
|
+
if ((constraints?.finite ?? true) && !Number.isFinite(value)) return { kind: "finite" };
|
|
17
|
+
if (constraints?.int === true && !Number.isInteger(value)) return { kind: "int" };
|
|
18
|
+
if (constraints?.min !== void 0 && value < constraints.min) return {
|
|
19
|
+
kind: "min",
|
|
20
|
+
bound: constraints.min
|
|
21
|
+
};
|
|
22
|
+
if (constraints?.max !== void 0 && value > constraints.max) return {
|
|
23
|
+
kind: "max",
|
|
24
|
+
bound: constraints.max
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Render a terse, human-readable reason for a constraint violation.
|
|
29
|
+
*
|
|
30
|
+
* @param violation - The violation to describe.
|
|
31
|
+
* @returns A message suffix such as `must be an integer` or `must be >= 0`.
|
|
32
|
+
*/
|
|
33
|
+
function describeNumberConstraintViolation(violation) {
|
|
34
|
+
switch (violation.kind) {
|
|
35
|
+
case "finite": return "must be a finite number";
|
|
36
|
+
case "int": return "must be an integer";
|
|
37
|
+
case "min": return `must be >= ${violation.bound}`;
|
|
38
|
+
case "max": return `must be <= ${violation.bound}`;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Assert that a constraints object is well-formed at schema-construction time.
|
|
43
|
+
*
|
|
44
|
+
* `min` / `max` must be finite — an infinite or `NaN` bound is meaningless (omit
|
|
45
|
+
* the field for "no bound") and would serialize to `null` in the emitted JSON
|
|
46
|
+
* Schema. An inverted range (`min > max`) is also rejected, since it makes the
|
|
47
|
+
* flag/arg permanently unsatisfiable. Throws so the misconfiguration surfaces
|
|
48
|
+
* where the flag/arg is declared, not at parse time.
|
|
49
|
+
*
|
|
50
|
+
* @param constraints - The constraints to validate.
|
|
51
|
+
* @throws RangeError if `min` or `max` is non-finite (`Infinity` / `-Infinity` /
|
|
52
|
+
* `NaN`), or if `min` exceeds `max`.
|
|
53
|
+
*/
|
|
54
|
+
function assertNumberConstraints(constraints) {
|
|
55
|
+
if (constraints.min !== void 0 && !Number.isFinite(constraints.min)) throw new RangeError(`number constraint 'min' must be a finite number (got ${constraints.min}); omit it for no lower bound`);
|
|
56
|
+
if (constraints.max !== void 0 && !Number.isFinite(constraints.max)) throw new RangeError(`number constraint 'max' must be a finite number (got ${constraints.max}); omit it for no upper bound`);
|
|
57
|
+
if (constraints.min !== void 0 && constraints.max !== void 0 && constraints.min > constraints.max) throw new RangeError(`number constraint 'min' (${constraints.min}) must not exceed 'max' (${constraints.max})`);
|
|
58
|
+
}
|
|
59
|
+
//#endregion
|
|
60
|
+
export { assertNumberConstraints, describeNumberConstraintViolation, validateNumberConstraints };
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
* @module dreamcli/core/schema/prompt
|
|
11
11
|
*/
|
|
12
12
|
/** All prompt kind discriminators as a runtime array. */
|
|
13
|
-
declare const PROMPT_KINDS: readonly [
|
|
13
|
+
declare const PROMPT_KINDS: readonly ["confirm", "input", "select", "multiselect"];
|
|
14
14
|
/**
|
|
15
15
|
* The kind of interactive prompt to present.
|
|
16
16
|
*
|
|
@@ -123,10 +123,13 @@ type PromptConfig = ConfirmPromptConfig | InputPromptConfig | SelectPromptConfig
|
|
|
123
123
|
* prompt engine's.
|
|
124
124
|
*/
|
|
125
125
|
type PromptResult = {
|
|
126
|
-
/** User provided a value. */
|
|
126
|
+
/** User provided a value. */
|
|
127
|
+
readonly answered: true;
|
|
128
|
+
/** The raw value from the prompt engine (not yet coerced). */
|
|
127
129
|
readonly value: unknown;
|
|
128
130
|
} | {
|
|
129
|
-
/** User cancelled or aborted (Ctrl+C, ESC, etc.). */
|
|
131
|
+
/** User cancelled or aborted (Ctrl+C, ESC, etc.). */
|
|
132
|
+
readonly answered: false;
|
|
130
133
|
};
|
|
131
134
|
//#endregion
|
|
132
135
|
export { type ConfirmPromptConfig, type InputPromptConfig, type MultiselectPromptConfig, PROMPT_KINDS, type PromptConfig, type PromptConfigBase, type PromptKind, type PromptResult, type SelectChoice, type SelectPromptConfig };
|
|
@@ -6,7 +6,7 @@ import { CLIPlugin } from "../cli/plugin.mjs";
|
|
|
6
6
|
import { CLIError } from "../errors/index.mjs";
|
|
7
7
|
import { HelpOptions } from "../help/index.mjs";
|
|
8
8
|
import { CommandMeta, CommandSchema, Out } from "./command.mjs";
|
|
9
|
-
|
|
9
|
+
import { ParseOptions } from "../parse/index.mjs";
|
|
10
10
|
//#region src/core/schema/run.d.ts
|
|
11
11
|
/**
|
|
12
12
|
* Options accepted by `runCommand()` and internal command execution paths.
|
|
@@ -59,6 +59,15 @@ interface RunOptions {
|
|
|
59
59
|
* Ignored when an explicit `prompter` is provided.
|
|
60
60
|
*/
|
|
61
61
|
readonly answers?: readonly TestAnswer[];
|
|
62
|
+
/**
|
|
63
|
+
* Filesystem probe for `flag.path()` checks: reports what exists at a
|
|
64
|
+
* path (`'file'`, `'directory'`, or `null` for nothing).
|
|
65
|
+
*
|
|
66
|
+
* `CLIBuilder.run()` supplies the runtime adapter's probe automatically.
|
|
67
|
+
* When absent (process-free `.execute()` / `runCommand()` without an
|
|
68
|
+
* override), path checks are skipped.
|
|
69
|
+
*/
|
|
70
|
+
readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
|
|
62
71
|
/**
|
|
63
72
|
* Verbosity level for the output channel.
|
|
64
73
|
* @defaultValue `'normal'`
|
|
@@ -103,6 +112,16 @@ interface RunOptions {
|
|
|
103
112
|
* Used when `--help` is detected.
|
|
104
113
|
*/
|
|
105
114
|
readonly help?: HelpOptions;
|
|
115
|
+
/**
|
|
116
|
+
* Flag-parsing behavior settings.
|
|
117
|
+
*
|
|
118
|
+
* `caseParity` accepts the kebab↔camel counterpart spelling of each flag
|
|
119
|
+
* name/alias (`--doThis` for `do-this`, and vice versa). The CLI layer
|
|
120
|
+
* threads `cli(name, { flags })` settings here automatically.
|
|
121
|
+
*
|
|
122
|
+
* @defaultValue `{ caseParity: true }`
|
|
123
|
+
*/
|
|
124
|
+
readonly flags?: ParseOptions;
|
|
106
125
|
/**
|
|
107
126
|
* Command schema with propagated flags merged in.
|
|
108
127
|
*
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
//#region src/core/schema/string-constraints.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* String constraints for string-valued flags.
|
|
4
|
+
*
|
|
5
|
+
* A single, shared representation and validator so the parse path
|
|
6
|
+
* (`core/parse`) and the resolver coercion path (`core/resolve/coerce`) cannot
|
|
7
|
+
* drift: both import {@link validateStringConstraints} and apply the checks in
|
|
8
|
+
* the same order (nonEmpty → minLength → maxLength → pattern).
|
|
9
|
+
*
|
|
10
|
+
* @module dreamcli/core/schema/string-constraints
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* Runtime string constraints attached to a string flag/arg schema.
|
|
14
|
+
*
|
|
15
|
+
* Length bounds are **inclusive** and measured in UTF-16 code units
|
|
16
|
+
* (`String.prototype.length`). All fields are optional; an absent field means
|
|
17
|
+
* "no constraint".
|
|
18
|
+
*/
|
|
19
|
+
interface StringConstraints {
|
|
20
|
+
/**
|
|
21
|
+
* Reject empty strings (`''`). Whitespace-only strings are still accepted;
|
|
22
|
+
* combine with {@link StringConstraints.pattern | pattern} for stricter rules.
|
|
23
|
+
* @defaultValue `false`
|
|
24
|
+
*/
|
|
25
|
+
readonly nonEmpty?: boolean;
|
|
26
|
+
/**
|
|
27
|
+
* Inclusive minimum length. Shorter values are rejected.
|
|
28
|
+
* @defaultValue `undefined` (no minimum)
|
|
29
|
+
*/
|
|
30
|
+
readonly minLength?: number;
|
|
31
|
+
/**
|
|
32
|
+
* Inclusive maximum length. Longer values are rejected.
|
|
33
|
+
* @defaultValue `undefined` (no maximum)
|
|
34
|
+
*/
|
|
35
|
+
readonly maxLength?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Regular expression the value must match. Tested with
|
|
38
|
+
* `RegExp.prototype.test`; anchor with `^`/`$` for full-string matching.
|
|
39
|
+
* @defaultValue `undefined` (no pattern)
|
|
40
|
+
*/
|
|
41
|
+
readonly pattern?: RegExp;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* A failed string constraint, discriminated by which rule was violated.
|
|
45
|
+
*
|
|
46
|
+
* `minLength` / `maxLength` carry the offending bound and `pattern` carries
|
|
47
|
+
* the source so callers can render them.
|
|
48
|
+
*/
|
|
49
|
+
type StringConstraintViolation = {
|
|
50
|
+
readonly kind: 'nonEmpty';
|
|
51
|
+
} | {
|
|
52
|
+
readonly kind: 'minLength';
|
|
53
|
+
readonly bound: number;
|
|
54
|
+
} | {
|
|
55
|
+
readonly kind: 'maxLength';
|
|
56
|
+
readonly bound: number;
|
|
57
|
+
} | {
|
|
58
|
+
readonly kind: 'pattern';
|
|
59
|
+
readonly pattern: string;
|
|
60
|
+
};
|
|
61
|
+
/**
|
|
62
|
+
* Validate a string value against constraints.
|
|
63
|
+
*
|
|
64
|
+
* The single source of truth for string-constraint checks, shared by the
|
|
65
|
+
* parse and coerce paths. Checks run in a fixed order — **nonEmpty →
|
|
66
|
+
* minLength → maxLength → pattern** — and the first failure is returned.
|
|
67
|
+
* Stateful regexes (`g` / `y` flags) are tested from index 0 every time, so
|
|
68
|
+
* repeated validations cannot flip-flop on `lastIndex`.
|
|
69
|
+
*
|
|
70
|
+
* @param value - The string value to validate.
|
|
71
|
+
* @param constraints - Constraints to enforce, or `undefined` for none.
|
|
72
|
+
* @returns The first {@link StringConstraintViolation}, or `undefined` if valid.
|
|
73
|
+
*/
|
|
74
|
+
declare function validateStringConstraints(value: string, constraints: StringConstraints | undefined): StringConstraintViolation | undefined;
|
|
75
|
+
/**
|
|
76
|
+
* Render a terse, human-readable reason for a constraint violation.
|
|
77
|
+
*
|
|
78
|
+
* @param violation - The violation to describe.
|
|
79
|
+
* @returns A message suffix such as `must not be empty` or `must match /^ghp_/`.
|
|
80
|
+
*/
|
|
81
|
+
declare function describeStringConstraintViolation(violation: StringConstraintViolation): string;
|
|
82
|
+
/**
|
|
83
|
+
* Assert that a constraints object is well-formed at schema-construction time.
|
|
84
|
+
*
|
|
85
|
+
* Length bounds must be non-negative integers — a fractional or negative
|
|
86
|
+
* length is meaningless (omit the field for "no bound"). An inverted range
|
|
87
|
+
* (`minLength > maxLength`) is also rejected, since it makes the flag/arg
|
|
88
|
+
* permanently unsatisfiable. Throws so the misconfiguration surfaces where
|
|
89
|
+
* the flag/arg is declared, not at parse time.
|
|
90
|
+
*
|
|
91
|
+
* @param constraints - The constraints to validate.
|
|
92
|
+
* @throws RangeError if `minLength` or `maxLength` is negative, fractional, or
|
|
93
|
+
* non-finite, or if `minLength` exceeds `maxLength`.
|
|
94
|
+
*/
|
|
95
|
+
declare function assertStringConstraints(constraints: StringConstraints): void;
|
|
96
|
+
//#endregion
|
|
97
|
+
export { type StringConstraintViolation, type StringConstraints, assertStringConstraints, describeStringConstraintViolation, validateStringConstraints };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
//#region src/core/schema/string-constraints.ts
|
|
2
|
+
/**
|
|
3
|
+
* Validate a string value against constraints.
|
|
4
|
+
*
|
|
5
|
+
* The single source of truth for string-constraint checks, shared by the
|
|
6
|
+
* parse and coerce paths. Checks run in a fixed order — **nonEmpty →
|
|
7
|
+
* minLength → maxLength → pattern** — and the first failure is returned.
|
|
8
|
+
* Stateful regexes (`g` / `y` flags) are tested from index 0 every time, so
|
|
9
|
+
* repeated validations cannot flip-flop on `lastIndex`.
|
|
10
|
+
*
|
|
11
|
+
* @param value - The string value to validate.
|
|
12
|
+
* @param constraints - Constraints to enforce, or `undefined` for none.
|
|
13
|
+
* @returns The first {@link StringConstraintViolation}, or `undefined` if valid.
|
|
14
|
+
*/
|
|
15
|
+
function validateStringConstraints(value, constraints) {
|
|
16
|
+
if (constraints === void 0) return;
|
|
17
|
+
if (constraints.nonEmpty === true && value.length === 0) return { kind: "nonEmpty" };
|
|
18
|
+
if (constraints.minLength !== void 0 && value.length < constraints.minLength) return {
|
|
19
|
+
kind: "minLength",
|
|
20
|
+
bound: constraints.minLength
|
|
21
|
+
};
|
|
22
|
+
if (constraints.maxLength !== void 0 && value.length > constraints.maxLength) return {
|
|
23
|
+
kind: "maxLength",
|
|
24
|
+
bound: constraints.maxLength
|
|
25
|
+
};
|
|
26
|
+
if (constraints.pattern !== void 0) {
|
|
27
|
+
constraints.pattern.lastIndex = 0;
|
|
28
|
+
if (!constraints.pattern.test(value)) return {
|
|
29
|
+
kind: "pattern",
|
|
30
|
+
pattern: String(constraints.pattern)
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
/**
|
|
35
|
+
* Render a terse, human-readable reason for a constraint violation.
|
|
36
|
+
*
|
|
37
|
+
* @param violation - The violation to describe.
|
|
38
|
+
* @returns A message suffix such as `must not be empty` or `must match /^ghp_/`.
|
|
39
|
+
*/
|
|
40
|
+
function describeStringConstraintViolation(violation) {
|
|
41
|
+
switch (violation.kind) {
|
|
42
|
+
case "nonEmpty": return "must not be empty";
|
|
43
|
+
case "minLength": return `must be at least ${violation.bound} characters`;
|
|
44
|
+
case "maxLength": return `must be at most ${violation.bound} characters`;
|
|
45
|
+
case "pattern": return `must match ${violation.pattern}`;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Assert that a constraints object is well-formed at schema-construction time.
|
|
50
|
+
*
|
|
51
|
+
* Length bounds must be non-negative integers — a fractional or negative
|
|
52
|
+
* length is meaningless (omit the field for "no bound"). An inverted range
|
|
53
|
+
* (`minLength > maxLength`) is also rejected, since it makes the flag/arg
|
|
54
|
+
* permanently unsatisfiable. Throws so the misconfiguration surfaces where
|
|
55
|
+
* the flag/arg is declared, not at parse time.
|
|
56
|
+
*
|
|
57
|
+
* @param constraints - The constraints to validate.
|
|
58
|
+
* @throws RangeError if `minLength` or `maxLength` is negative, fractional, or
|
|
59
|
+
* non-finite, or if `minLength` exceeds `maxLength`.
|
|
60
|
+
*/
|
|
61
|
+
function assertStringConstraints(constraints) {
|
|
62
|
+
for (const field of ["minLength", "maxLength"]) {
|
|
63
|
+
const bound = constraints[field];
|
|
64
|
+
if (bound !== void 0 && (!Number.isInteger(bound) || bound < 0)) throw new RangeError(`string constraint '${field}' must be a non-negative integer (got ${bound}); omit it for no bound`);
|
|
65
|
+
}
|
|
66
|
+
if (constraints.minLength !== void 0 && constraints.maxLength !== void 0 && constraints.minLength > constraints.maxLength) throw new RangeError(`string constraint 'minLength' (${constraints.minLength}) must not exceed 'maxLength' (${constraints.maxLength})`);
|
|
67
|
+
}
|
|
68
|
+
//#endregion
|
|
69
|
+
export { assertStringConstraints, describeStringConstraintViolation, validateStringConstraints };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
//#region src/core/schema/value-parsers.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Parse functions backing the sugar flag factories (`flag.url()`,
|
|
4
|
+
* `flag.date()`, `flag.duration()`, `flag.bytes()`).
|
|
5
|
+
*
|
|
6
|
+
* Each parser converts a raw CLI/env/config value into a typed value and
|
|
7
|
+
* throws a plain `Error` with a human-readable reason on invalid input. The
|
|
8
|
+
* parse and resolve pipelines wrap thrown errors with flag context
|
|
9
|
+
* (`Failed to parse flag --x: <reason>`), so parsers only describe the value
|
|
10
|
+
* problem itself.
|
|
11
|
+
*
|
|
12
|
+
* @module dreamcli/core/schema/value-parsers
|
|
13
|
+
*/
|
|
14
|
+
/** Options accepted by `flag.url()`. */
|
|
15
|
+
interface UrlFlagOptions {
|
|
16
|
+
/**
|
|
17
|
+
* Allowed URL protocols, without the trailing colon (e.g. `['https']`).
|
|
18
|
+
* @defaultValue `undefined` (any protocol)
|
|
19
|
+
*/
|
|
20
|
+
readonly protocols?: readonly string[];
|
|
21
|
+
}
|
|
22
|
+
/** Options accepted by `flag.date()`. */
|
|
23
|
+
interface DateFlagOptions {
|
|
24
|
+
/**
|
|
25
|
+
* Inclusive earliest allowed date.
|
|
26
|
+
* @defaultValue `undefined` (no lower bound)
|
|
27
|
+
*/
|
|
28
|
+
readonly min?: Date;
|
|
29
|
+
/**
|
|
30
|
+
* Inclusive latest allowed date.
|
|
31
|
+
* @defaultValue `undefined` (no upper bound)
|
|
32
|
+
*/
|
|
33
|
+
readonly max?: Date;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Parse a strict ISO-8601 date string into a `Date`.
|
|
37
|
+
*
|
|
38
|
+
* Rejects non-string input, non-ISO shapes, and calendar-invalid components
|
|
39
|
+
* (`2026-02-31` does not silently roll over to March). Offset-less datetimes
|
|
40
|
+
* are interpreted as UTC so results never depend on the machine's timezone.
|
|
41
|
+
*
|
|
42
|
+
* @param raw - Raw flag value.
|
|
43
|
+
* @param options - Optional inclusive date bounds.
|
|
44
|
+
* @returns The parsed `Date`.
|
|
45
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
46
|
+
*/
|
|
47
|
+
declare function parseDateValue(raw: unknown, options?: DateFlagOptions): Date;
|
|
48
|
+
/**
|
|
49
|
+
* Parse a URL string into a `URL`, optionally restricting protocols.
|
|
50
|
+
*
|
|
51
|
+
* @param raw - Raw flag value.
|
|
52
|
+
* @param options - Optional protocol allowlist.
|
|
53
|
+
* @returns The parsed `URL`.
|
|
54
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
55
|
+
*/
|
|
56
|
+
declare function parseUrlValue(raw: unknown, options?: UrlFlagOptions): URL;
|
|
57
|
+
/**
|
|
58
|
+
* Parse a human duration (`'30s'`, `'5m'`, `'1.5h'`, `'250ms'`, `'2d'`) into
|
|
59
|
+
* milliseconds. A bare number (`'1500'`) is treated as milliseconds. Compound
|
|
60
|
+
* values (`'1h30m'`) are supported.
|
|
61
|
+
*
|
|
62
|
+
* @param raw - Raw flag value.
|
|
63
|
+
* @returns Duration in milliseconds.
|
|
64
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
65
|
+
*/
|
|
66
|
+
declare function parseDurationValue(raw: unknown): number;
|
|
67
|
+
/**
|
|
68
|
+
* Parse a human byte size (`'512mb'`, `'1.5gb'`, `'64kb'`, `'100b'`) into a
|
|
69
|
+
* byte count. Units are binary (`1kb` = 1024 bytes) and case-insensitive; a
|
|
70
|
+
* bare number is treated as bytes.
|
|
71
|
+
*
|
|
72
|
+
* @param raw - Raw flag value.
|
|
73
|
+
* @returns Size in bytes.
|
|
74
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
75
|
+
*/
|
|
76
|
+
declare function parseBytesValue(raw: unknown): number;
|
|
77
|
+
//#endregion
|
|
78
|
+
export { type DateFlagOptions, type UrlFlagOptions, parseBytesValue, parseDateValue, parseDurationValue, parseUrlValue };
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
//#region src/core/schema/value-parsers.ts
|
|
2
|
+
/**
|
|
3
|
+
* Strict ISO-8601 shapes accepted by {@link parseDateValue}:
|
|
4
|
+
* `YYYY-MM-DD`, optionally followed by `THH:MM`, `:SS`, `.mmm`, and a
|
|
5
|
+
* `Z` / `±HH:MM` offset. Anything else — including `Date.parse`-lenient
|
|
6
|
+
* inputs like `'0'` or `'March 5'` — is rejected.
|
|
7
|
+
*/
|
|
8
|
+
const ISO_DATE_PATTERN = /^(\d{4})-(\d{2})-(\d{2})(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?(Z|[+-]\d{2}:\d{2})?)?$/;
|
|
9
|
+
/**
|
|
10
|
+
* Parse a strict ISO-8601 date string into a `Date`.
|
|
11
|
+
*
|
|
12
|
+
* Rejects non-string input, non-ISO shapes, and calendar-invalid components
|
|
13
|
+
* (`2026-02-31` does not silently roll over to March). Offset-less datetimes
|
|
14
|
+
* are interpreted as UTC so results never depend on the machine's timezone.
|
|
15
|
+
*
|
|
16
|
+
* @param raw - Raw flag value.
|
|
17
|
+
* @param options - Optional inclusive date bounds.
|
|
18
|
+
* @returns The parsed `Date`.
|
|
19
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
20
|
+
*/
|
|
21
|
+
function parseDateValue(raw, options) {
|
|
22
|
+
if (raw instanceof Date) return validateDateBounds(raw, options);
|
|
23
|
+
if (typeof raw !== "string") throw new Error(`Invalid date '${String(raw)}': expected an ISO-8601 string`);
|
|
24
|
+
const match = ISO_DATE_PATTERN.exec(raw);
|
|
25
|
+
if (match === null) throw new Error(`Invalid date '${raw}': expected ISO-8601 (e.g. 2026-07-10 or 2026-07-10T14:30:00Z)`);
|
|
26
|
+
const [, yearPart, monthPart, dayPart, hourPart, minutePart, secondPart] = match;
|
|
27
|
+
const year = Number(yearPart);
|
|
28
|
+
const month = Number(monthPart);
|
|
29
|
+
const day = Number(dayPart);
|
|
30
|
+
if (month < 1 || month > 12) throw new Error(`Invalid date '${raw}': month must be 01-12`);
|
|
31
|
+
if (day < 1 || day > daysInMonth(year, month)) throw new Error(`Invalid date '${raw}': not a real calendar date`);
|
|
32
|
+
if (hourPart !== void 0 && Number(hourPart) > 23) throw new Error(`Invalid date '${raw}': hours must be 00-23`);
|
|
33
|
+
if (minutePart !== void 0 && Number(minutePart) > 59) throw new Error(`Invalid date '${raw}': minutes must be 00-59`);
|
|
34
|
+
if (secondPart !== void 0 && Number(secondPart) > 59) throw new Error(`Invalid date '${raw}': seconds must be 00-59`);
|
|
35
|
+
const hasTime = match[4] !== void 0;
|
|
36
|
+
const hasOffset = match[8] !== void 0;
|
|
37
|
+
const parsed = new Date(hasTime && !hasOffset ? `${raw}Z` : raw);
|
|
38
|
+
if (Number.isNaN(parsed.getTime())) throw new Error(`Invalid date '${raw}'`);
|
|
39
|
+
return validateDateBounds(parsed, options, raw);
|
|
40
|
+
}
|
|
41
|
+
/** Number of days in a month (1-12), accounting for leap years. */
|
|
42
|
+
function daysInMonth(year, month) {
|
|
43
|
+
return new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
44
|
+
}
|
|
45
|
+
/** Enforce inclusive date bounds, throwing a human-readable error on violation. */
|
|
46
|
+
function validateDateBounds(value, options, raw) {
|
|
47
|
+
const display = raw ?? value.toISOString();
|
|
48
|
+
if (options?.min !== void 0 && value.getTime() < options.min.getTime()) throw new Error(`Date '${display}' is before the earliest allowed ${options.min.toISOString()}`);
|
|
49
|
+
if (options?.max !== void 0 && value.getTime() > options.max.getTime()) throw new Error(`Date '${display}' is after the latest allowed ${options.max.toISOString()}`);
|
|
50
|
+
return value;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Parse a URL string into a `URL`, optionally restricting protocols.
|
|
54
|
+
*
|
|
55
|
+
* @param raw - Raw flag value.
|
|
56
|
+
* @param options - Optional protocol allowlist.
|
|
57
|
+
* @returns The parsed `URL`.
|
|
58
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
59
|
+
*/
|
|
60
|
+
function parseUrlValue(raw, options) {
|
|
61
|
+
if (typeof raw !== "string" && !(raw instanceof URL)) throw new Error(`Invalid URL '${String(raw)}': expected a URL string`);
|
|
62
|
+
let parsed;
|
|
63
|
+
try {
|
|
64
|
+
parsed = raw instanceof URL ? raw : new URL(raw);
|
|
65
|
+
} catch {
|
|
66
|
+
throw new Error(`Invalid URL '${String(raw)}'`);
|
|
67
|
+
}
|
|
68
|
+
if (options?.protocols !== void 0) {
|
|
69
|
+
const protocol = parsed.protocol.replace(/:$/, "");
|
|
70
|
+
if (!options.protocols.includes(protocol)) throw new Error(`URL protocol '${protocol}' is not allowed. Allowed: ${options.protocols.join(", ")}`);
|
|
71
|
+
}
|
|
72
|
+
return parsed;
|
|
73
|
+
}
|
|
74
|
+
/** Duration unit suffixes mapped to their length in milliseconds. */
|
|
75
|
+
const DURATION_UNITS = {
|
|
76
|
+
ms: 1,
|
|
77
|
+
s: 1e3,
|
|
78
|
+
m: 6e4,
|
|
79
|
+
h: 36e5,
|
|
80
|
+
d: 864e5
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Parse a human duration (`'30s'`, `'5m'`, `'1.5h'`, `'250ms'`, `'2d'`) into
|
|
84
|
+
* milliseconds. A bare number (`'1500'`) is treated as milliseconds. Compound
|
|
85
|
+
* values (`'1h30m'`) are supported.
|
|
86
|
+
*
|
|
87
|
+
* @param raw - Raw flag value.
|
|
88
|
+
* @returns Duration in milliseconds.
|
|
89
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
90
|
+
*/
|
|
91
|
+
function parseDurationValue(raw) {
|
|
92
|
+
if (typeof raw === "number") {
|
|
93
|
+
if (!Number.isFinite(raw) || raw < 0) throw new Error(`Invalid duration '${String(raw)}': must be a non-negative number`);
|
|
94
|
+
return raw;
|
|
95
|
+
}
|
|
96
|
+
if (typeof raw !== "string" || raw.length === 0) throw new Error(`Invalid duration '${String(raw)}': expected e.g. 30s, 5m, 1h30m, or 250ms`);
|
|
97
|
+
if (/^\d+(?:\.\d+)?$/.test(raw)) return Number(raw);
|
|
98
|
+
const segmentPattern = /(\d+(?:\.\d+)?)(ms|s|m|h|d)/gy;
|
|
99
|
+
let total = 0;
|
|
100
|
+
let consumed = 0;
|
|
101
|
+
for (const segment of raw.matchAll(segmentPattern)) {
|
|
102
|
+
const [text, amount, unit] = segment;
|
|
103
|
+
const scale = unit === void 0 ? void 0 : DURATION_UNITS[unit];
|
|
104
|
+
if (amount === void 0 || scale === void 0) break;
|
|
105
|
+
total += Number(amount) * scale;
|
|
106
|
+
consumed += text.length;
|
|
107
|
+
}
|
|
108
|
+
if (consumed !== raw.length || consumed === 0) throw new Error(`Invalid duration '${raw}': expected e.g. 30s, 5m, 1h30m, or 250ms`);
|
|
109
|
+
return total;
|
|
110
|
+
}
|
|
111
|
+
/** Byte unit suffixes mapped to their size (binary, 1 kb = 1024 bytes). */
|
|
112
|
+
const BYTE_UNITS = {
|
|
113
|
+
b: 1,
|
|
114
|
+
kb: 1024,
|
|
115
|
+
mb: 1024 ** 2,
|
|
116
|
+
gb: 1024 ** 3,
|
|
117
|
+
tb: 1024 ** 4
|
|
118
|
+
};
|
|
119
|
+
/**
|
|
120
|
+
* Parse a human byte size (`'512mb'`, `'1.5gb'`, `'64kb'`, `'100b'`) into a
|
|
121
|
+
* byte count. Units are binary (`1kb` = 1024 bytes) and case-insensitive; a
|
|
122
|
+
* bare number is treated as bytes.
|
|
123
|
+
*
|
|
124
|
+
* @param raw - Raw flag value.
|
|
125
|
+
* @returns Size in bytes.
|
|
126
|
+
* @throws Error with a human-readable reason on invalid input.
|
|
127
|
+
*/
|
|
128
|
+
function parseBytesValue(raw) {
|
|
129
|
+
if (typeof raw === "number") {
|
|
130
|
+
if (!Number.isFinite(raw) || raw < 0) throw new Error(`Invalid size '${String(raw)}': must be a non-negative number`);
|
|
131
|
+
return raw;
|
|
132
|
+
}
|
|
133
|
+
if (typeof raw !== "string" || raw.length === 0) throw new Error(`Invalid size '${String(raw)}': expected e.g. 512mb, 1.5gb, or 64kb`);
|
|
134
|
+
const match = /^(\d+(?:\.\d+)?)\s*(b|kb|mb|gb|tb)?$/i.exec(raw);
|
|
135
|
+
if (match === null || match[1] === void 0) throw new Error(`Invalid size '${raw}': expected e.g. 512mb, 1.5gb, or 64kb`);
|
|
136
|
+
const unit = (match[2] ?? "b").toLowerCase();
|
|
137
|
+
const scale = BYTE_UNITS[unit];
|
|
138
|
+
if (scale === void 0) throw new Error(`Invalid size '${raw}': unknown unit '${match[2] ?? ""}'`);
|
|
139
|
+
return Math.round(Number(match[1]) * scale);
|
|
140
|
+
}
|
|
141
|
+
//#endregion
|
|
142
|
+
export { parseBytesValue, parseDateValue, parseDurationValue, parseUrlValue };
|