@kjanat/dreamcli 3.0.0-rc.4 → 3.0.0-rc.7

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.
Files changed (93) hide show
  1. package/CHANGELOG.md +82 -1
  2. package/dist/core/cli/dispatch.d.mts +0 -1
  3. package/dist/core/cli/dispatch.mjs +1 -1
  4. package/dist/core/cli/help-links.d.mts +0 -1
  5. package/dist/core/cli/index.d.mts +0 -1
  6. package/dist/core/cli/index.mjs +16 -7
  7. package/dist/core/cli/planner.d.mts +0 -1
  8. package/dist/core/cli/planner.mjs +3 -3
  9. package/dist/core/cli/plugin.d.mts +1 -1
  10. package/dist/core/cli/propagate.d.mts +1 -1
  11. package/dist/core/cli/root-help.d.mts +0 -1
  12. package/dist/core/cli/root-help.mjs +6 -1
  13. package/dist/core/cli/root-surface.d.mts +0 -1
  14. package/dist/core/cli/runtime-preflight.d.mts +5 -1
  15. package/dist/core/cli/runtime-preflight.mjs +2 -1
  16. package/dist/core/completion/index.d.mts +0 -1
  17. package/dist/core/completion/index.mjs +1 -1
  18. package/dist/core/completion/shells/bash.d.mts +0 -1
  19. package/dist/core/completion/shells/bash.mjs +3 -2
  20. package/dist/core/completion/shells/fish.d.mts +0 -1
  21. package/dist/core/completion/shells/fish.mjs +3 -2
  22. package/dist/core/completion/shells/powershell.d.mts +0 -1
  23. package/dist/core/completion/shells/powershell.mjs +2 -1
  24. package/dist/core/completion/shells/shared.d.mts +1 -1
  25. package/dist/core/completion/shells/shared.mjs +5 -0
  26. package/dist/core/completion/shells/zsh.d.mts +0 -1
  27. package/dist/core/completion/shells/zsh.mjs +3 -2
  28. package/dist/core/config/index.d.mts +0 -1
  29. package/dist/core/config/index.mjs +2 -2
  30. package/dist/core/config/package-json.d.mts +0 -1
  31. package/dist/core/execution/index.d.mts +0 -1
  32. package/dist/core/execution/index.mjs +3 -2
  33. package/dist/core/help/ansi.mjs +3 -2
  34. package/dist/core/help/index.d.mts +1 -1
  35. package/dist/core/help/index.mjs +12 -6
  36. package/dist/core/json-schema/index.d.mts +1 -1
  37. package/dist/core/json-schema/index.mjs +25 -7
  38. package/dist/core/output/activity.d.mts +0 -1
  39. package/dist/core/output/contracts.d.mts +0 -1
  40. package/dist/core/output/contracts.mjs +1 -1
  41. package/dist/core/output/index.d.mts +0 -1
  42. package/dist/core/output/index.mjs +1 -1
  43. package/dist/core/output/renderers.d.mts +0 -1
  44. package/dist/core/parse/index.d.mts +1 -1
  45. package/dist/core/parse/index.mjs +75 -9
  46. package/dist/core/prompt/index.d.mts +1 -0
  47. package/dist/core/resolve/args.d.mts +1 -1
  48. package/dist/core/resolve/coerce.d.mts +1 -1
  49. package/dist/core/resolve/coerce.mjs +71 -14
  50. package/dist/core/resolve/contracts.d.mts +6 -1
  51. package/dist/core/resolve/errors.d.mts +0 -1
  52. package/dist/core/resolve/flags.d.mts +7 -2
  53. package/dist/core/resolve/flags.mjs +61 -6
  54. package/dist/core/resolve/index.d.mts +1 -1
  55. package/dist/core/resolve/index.mjs +1 -1
  56. package/dist/core/resolve/property.d.mts +3 -0
  57. package/dist/core/resolve/property.mjs +11 -3
  58. package/dist/core/schema/activity.d.mts +31 -11
  59. package/dist/core/schema/arg.d.mts +1 -2
  60. package/dist/core/schema/command.d.mts +8 -6
  61. package/dist/core/schema/command.mjs +3 -1
  62. package/dist/core/schema/flag.d.mts +337 -10
  63. package/dist/core/schema/flag.mjs +185 -3
  64. package/dist/core/schema/index.d.mts +4 -2
  65. package/dist/core/schema/middleware.d.mts +4 -3
  66. package/dist/core/schema/prompt.d.mts +5 -2
  67. package/dist/core/schema/run.d.mts +9 -1
  68. package/dist/core/schema/string-constraints.d.mts +97 -0
  69. package/dist/core/schema/string-constraints.mjs +69 -0
  70. package/dist/core/schema/value-parsers.d.mts +78 -0
  71. package/dist/core/schema/value-parsers.mjs +142 -0
  72. package/dist/core/schema-dsl/to-json-schema.d.mts +0 -1
  73. package/dist/core/testkit/index.d.mts +0 -31
  74. package/dist/core/testkit/index.mjs +1 -1
  75. package/dist/index.d.mts +5 -2
  76. package/dist/index.mjs +5 -5
  77. package/dist/runtime/adapter.d.mts +38 -2
  78. package/dist/runtime/adapter.mjs +5 -0
  79. package/dist/runtime/auto.d.mts +2 -3
  80. package/dist/runtime/auto.mjs +4 -5
  81. package/dist/runtime/deno.d.mts +24 -5
  82. package/dist/runtime/deno.mjs +45 -0
  83. package/dist/runtime/index.d.mts +3 -4
  84. package/dist/runtime/node.d.mts +8 -2
  85. package/dist/runtime/node.mjs +51 -0
  86. package/dist/runtime.d.mts +4 -4
  87. package/dist/runtime.mjs +2 -3
  88. package/dist/testkit.d.mts +1 -0
  89. package/dist/version.mjs +2 -2
  90. package/dreamcli.schema.json +3 -1
  91. package/package.json +13 -15
  92. package/dist/runtime/bun.d.mts +0 -28
  93. package/dist/runtime/bun.mjs +0 -28
@@ -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 };
@@ -1,5 +1,4 @@
1
1
  import { SchemaNode } from "./runtime.mjs";
2
-
3
2
  //#region src/core/schema-dsl/to-json-schema.d.ts
4
3
  /**
5
4
  * Convert a {@link SchemaNode} AST node to a JSON Schema fragment.
@@ -1,6 +1,5 @@
1
1
  import { RunOptions, RunResult } from "../schema/run.mjs";
2
2
  import { RunnableCommand } from "../schema/command.mjs";
3
-
4
3
  //#region src/core/testkit/index.d.ts
5
4
  /**
6
5
  * Run a command builder against the given argv with injected options.
@@ -24,35 +23,5 @@ import { RunnableCommand } from "../schema/command.mjs";
24
23
  * @returns Structured run result with exit code and captured output
25
24
  */
26
25
  declare function runCommand(cmd: RunnableCommand, argv: readonly string[], options?: RunOptions): Promise<RunResult>;
27
- /**
28
- * Options for {@linkcode runCommand} — process-free command execution.
29
- *
30
- * Every field is optional. Inject env, config, prompt answers, and
31
- * output capture without touching process state.
32
- *
33
- * @example
34
- * ```ts
35
- * const result = await runCommand(cmd, ['--verbose'], {
36
- * env: { LOG_LEVEL: 'debug' },
37
- * config: { theme: 'dark' },
38
- * });
39
- * ```
40
- */
41
- /**
42
- * Structured result from {@linkcode runCommand}.
43
- *
44
- * Contains the exit code, captured stdout/stderr output, recorded
45
- * {@linkcode ActivityEvent | activity events}, and an `error` field
46
- * that is `undefined` on success and a {@linkcode CLIError} on failure.
47
- *
48
- * @example
49
- * ```ts
50
- * const result = await runCommand(greetCmd, ['World']);
51
- *
52
- * expect(result.exitCode).toBe(0);
53
- * expect(result.stdout).toContain('Hello, World!');
54
- * expect(result.error).toBeUndefined();
55
- * ```
56
- */
57
26
  //#endregion
58
27
  export { type RunOptions, type RunResult, runCommand };
@@ -1,5 +1,5 @@
1
- import { createCaptureOutput } from "../output/index.mjs";
2
1
  import { includesBeforeSeparator, stripBeforeSeparator } from "../parse/index.mjs";
2
+ import { createCaptureOutput } from "../output/index.mjs";
3
3
  import { buildRunResult, executeCommand } from "../execution/index.mjs";
4
4
  //#region src/core/testkit/index.ts
5
5
  /**
package/dist/index.d.mts CHANGED
@@ -2,8 +2,11 @@ import { ActivityEvent, Fallback, ProgressHandle, ProgressOptions, SpinnerHandle
2
2
  import { NumberConstraintViolation, NumberConstraints } from "./core/schema/number-constraints.mjs";
3
3
  import { ArgBuilder, ArgConfig, ArgFactory, ArgKind, ArgParseFn, ArgPresence, ArgSchema, InferArg, InferArgs, ResolvedArgValue, WithArgPresence, WithVariadic, arg, createArgSchema } from "./core/schema/arg.mjs";
4
4
  import { ConfirmPromptConfig, InputPromptConfig, MultiselectPromptConfig, PromptConfig, PromptConfigBase, PromptKind, PromptResult, SelectChoice, SelectPromptConfig } from "./core/schema/prompt.mjs";
5
- import { FlagBuilder, FlagConfig, FlagFactory, FlagKind, FlagParseFn, FlagPresence, FlagSchema, InferFlag, InferFlags, ResolvedValue, WithPresence, createSchema, flag } from "./core/schema/flag.mjs";
5
+ import { StringConstraintViolation, StringConstraints } from "./core/schema/string-constraints.mjs";
6
+ import { DateFlagOptions, UrlFlagOptions } from "./core/schema/value-parsers.mjs";
7
+ import { FlagBuilder, FlagConfig, FlagFactory, FlagKind, FlagParseFn, FlagPresence, FlagSchema, InferFlag, InferFlags, PathChecks, PathFlagOptions, ResolvedValue, WithPresence, createSchema, flag } from "./core/schema/flag.mjs";
6
8
  import { Middleware, MiddlewareHandler, MiddlewareParams, middleware } from "./core/schema/middleware.mjs";
9
+ import "./core/schema/index.mjs";
7
10
  import { ParseResult, Token, parse, tokenize } from "./core/parse/index.mjs";
8
11
  import { WriteFn } from "./core/output/writer.mjs";
9
12
  import { Verbosity } from "./core/output/contracts.mjs";
@@ -29,4 +32,4 @@ import { ConfigAdapter, ConfigDiscoveryOptions, ConfigDiscoveryResult, ConfigFou
29
32
  import { CLIBuilder, CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, DefaultCommandOptions, InferNameOption, ManifestPresetSettings, ManifestSettings, PackageJsonSettings, ResolvedManifestSettings, cli } from "./core/cli/index.mjs";
30
33
  import { JsonSchemaOptions, definitionMetaSchema, generateInputSchema, generateSchema } from "./core/json-schema/index.mjs";
31
34
  import { Colors } from "ansispeck";
32
- export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type Colors, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DefaultCommandOptions, type DeprecationWarning, type DeriveHandler, type DeriveParams, type ErrorCode, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseResult, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
35
+ export { type ActionHandler, type ActionParams, type ActivityEvent, type AnyCommandBuilder, ArgBuilder, type ArgConfig, type ArgFactory, type ArgKind, type ArgParseFn, type ArgPresence, type ArgSchema, type BeforeParseParams, CLIBuilder, CLIError, type CLIErrorJSON, type CLIErrorOptions, type CLIOptions, type CLIPlugin, type CLIPluginHooks, type CLIRunOptions, type CLISchema, type Colors, type CommandArgEntry, CommandBuilder, type CommandConfig, type CommandExample, type CommandMeta, type CommandSchema, type CompletionOptions, type ConfigAdapter, type ConfigDiscoveryOptions, type ConfigDiscoveryResult, type ConfigFound, type ConfigNotFound, type ConfigSettings, type ConfirmPromptConfig, type DateFlagOptions, type DefaultCommandOptions, type DeprecationWarning, type DeriveHandler, type DeriveParams, type ErrorCode, type Fallback, FlagBuilder, type FlagConfig, type FlagFactory, type FlagKind, type FlagParseFn, type FlagPresence, type FlagSchema, type FormatLoader, type HelpLinks, type HelpOptions, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InferNameOption, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type ManifestDiscoveryOptions, type ManifestPresetSettings, type ManifestSettings, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type NumberConstraintViolation, type NumberConstraints, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, type PackageRepository, ParseError, type ParseErrorCode, type ParseErrorOptions, type ParseResult, type PathChecks, type PathFlagOptions, type PluginCommandContext, type ProgressHandle, type ProgressOptions, type PromptConfig, type PromptConfigBase, type PromptEngine, type PromptKind, type PromptResult, type ReadFn, type ResolveOptions, type ResolveResult, type ResolvedArgValue, type ResolvedCommandParams, type ResolvedManifestSettings, type ResolvedMultiselectPromptConfig, type ResolvedPromptConfig, type ResolvedSelectPromptConfig, type ResolvedValue, type RunResult, SHELLS, type SelectChoice, type SelectPromptConfig, type Shell, type SpinnerHandle, type SpinnerOptions, type StringConstraintViolation, type StringConstraints, type TableColumn, type TableFormat, type TableOptions, type TableStream, type Token, type UrlFlagOptions, ValidationError, type ValidationErrorCode, type ValidationErrorOptions, type Verbosity, type WithArgPresence, type WithPresence, type WithVariadic, type WriteFn, arg, buildConfigSearchPaths, cli, command, configFormat, createArgSchema, createOutput, createSchema, createTerminalPrompter, definitionMetaSchema, discoverConfig, discoverManifest, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, osc8, packageRepositoryUrl, parse, plugin, resolve, resolvePromptConfig, tokenize, visibleWidth };
package/dist/index.mjs CHANGED
@@ -1,17 +1,17 @@
1
+ import { CLIError, ParseError, ValidationError, isCLIError, isParseError, isValidationError } from "./core/errors/index.mjs";
1
2
  import { FlagBuilder, createSchema, flag } from "./core/schema/flag.mjs";
3
+ import { ArgBuilder, arg, createArgSchema } from "./core/schema/arg.mjs";
4
+ import { CommandBuilder, command, group } from "./core/schema/command.mjs";
5
+ import { middleware } from "./core/schema/middleware.mjs";
6
+ import { parse, tokenize } from "./core/parse/index.mjs";
2
7
  import { generateBashCompletion } from "./core/completion/shells/bash.mjs";
3
8
  import { generateFishCompletion } from "./core/completion/shells/fish.mjs";
4
9
  import { generatePowerShellCompletion } from "./core/completion/shells/powershell.mjs";
5
- import { CLIError, ParseError, ValidationError, isCLIError, isParseError, isValidationError } from "./core/errors/index.mjs";
6
10
  import { generateZshCompletion } from "./core/completion/shells/zsh.mjs";
7
11
  import { SHELLS, generateCompletion } from "./core/completion/index.mjs";
8
12
  import { osc8, visibleWidth } from "./core/help/ansi.mjs";
9
13
  import { formatHelp } from "./core/help/index.mjs";
10
14
  import { createOutput } from "./core/output/index.mjs";
11
- import { ArgBuilder, arg, createArgSchema } from "./core/schema/arg.mjs";
12
- import { CommandBuilder, command, group } from "./core/schema/command.mjs";
13
- import { middleware } from "./core/schema/middleware.mjs";
14
- import { parse, tokenize } from "./core/parse/index.mjs";
15
15
  import { createTerminalPrompter, resolvePromptConfig } from "./core/prompt/index.mjs";
16
16
  import { resolve } from "./core/resolve/index.mjs";
17
17
  import { discoverManifest, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./core/config/package-json.mjs";
@@ -1,6 +1,6 @@
1
1
  import { WriteFn } from "../core/output/writer.mjs";
2
+ import "../core/output/index.mjs";
2
3
  import { ReadFn } from "../core/prompt/index.mjs";
3
-
4
4
  //#region src/runtime/adapter.d.ts
5
5
  /**
6
6
  * Runtime adapter interface.
@@ -62,6 +62,10 @@ interface RuntimeAdapter {
62
62
  readonly isTTY: boolean;
63
63
  /** Whether stdin is connected to a TTY (used for prompt gating). */
64
64
  readonly stdinIsTTY: boolean;
65
+ /** Read current terminal dimensions for stdout, if available. */
66
+ readonly getTerminalSize: () => TerminalSize | undefined;
67
+ /** Subscribe to terminal resize events when the runtime supports them. */
68
+ readonly onTerminalResize: (listener: () => void) => (() => void) | undefined;
65
69
  /**
66
70
  * Exit the process with the given code.
67
71
  * Must not return (divergent function).
@@ -78,6 +82,15 @@ interface RuntimeAdapter {
78
82
  * Used by config file discovery to probe multiple candidate paths.
79
83
  */
80
84
  readonly readFile: (path: string) => Promise<string | null>;
85
+ /**
86
+ * Probe what exists at a filesystem path.
87
+ *
88
+ * Returns `'file'` or `'directory'` for existing paths (other kinds such
89
+ * as sockets report `'file'`), or `null` when nothing exists there.
90
+ *
91
+ * Used by `flag.path()` existence/type checks after resolution.
92
+ */
93
+ readonly stat: (path: string) => Promise<'file' | 'directory' | null>;
81
94
  /**
82
95
  * User home directory (absolute path).
83
96
  *
@@ -95,6 +108,13 @@ interface RuntimeAdapter {
95
108
  */
96
109
  readonly configDir: string;
97
110
  }
111
+ /** Current terminal dimensions in columns and rows. */
112
+ interface TerminalSize {
113
+ /** Terminal width in columns. */
114
+ readonly columns: number;
115
+ /** Terminal height in rows. */
116
+ readonly rows: number;
117
+ }
98
118
  /**
99
119
  * Options for creating a test adapter.
100
120
  *
@@ -138,6 +158,10 @@ interface TestAdapterOptions {
138
158
  readonly isTTY?: boolean;
139
159
  /** TTY flag for stdin (defaults to `false`). */
140
160
  readonly stdinIsTTY?: boolean;
161
+ /** Terminal dimensions returned by `getTerminalSize()`. */
162
+ readonly terminalSize?: TerminalSize;
163
+ /** Resize subscription hook returned by `onTerminalResize()`. */
164
+ readonly onTerminalResize?: (listener: () => void) => (() => void) | undefined;
141
165
  /**
142
166
  * Exit function (defaults to throwing {@linkcode ExitError}).
143
167
  * The default throw-based exit allows tests to catch the exit code.
@@ -158,6 +182,18 @@ interface TestAdapterOptions {
158
182
  * ```
159
183
  */
160
184
  readonly readFile?: (path: string) => Promise<string | null>;
185
+ /**
186
+ * Filesystem probe stub for `flag.path()` checks (defaults to returning
187
+ * `null` — nothing exists).
188
+ *
189
+ * Supply a custom function to simulate a virtual filesystem in tests:
190
+ * ```ts
191
+ * createTestAdapter({
192
+ * stat: (path) => Promise.resolve(path === '/data' ? 'directory' : null),
193
+ * })
194
+ * ```
195
+ */
196
+ readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
161
197
  /** Home directory (defaults to `'/home/test'`). */
162
198
  readonly homedir?: string;
163
199
  /** Config directory (defaults to `'/home/test/.config'`). */
@@ -209,4 +245,4 @@ declare class ExitError extends Error {
209
245
  */
210
246
  declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
211
247
  //#endregion
212
- export { ExitError, type RuntimeAdapter, type TestAdapterOptions, createTestAdapter };
248
+ export { ExitError, type RuntimeAdapter, type TerminalSize, type TestAdapterOptions, createTestAdapter };
@@ -32,6 +32,8 @@ const noopWrite = () => {};
32
32
  const eofRead = () => Promise.resolve(null);
33
33
  /** Noop file reader — returns `null` (not found) for all paths. */
34
34
  const noopReadFile = () => Promise.resolve(null);
35
+ /** Noop stat — reports `null` (nothing exists) for all paths. */
36
+ const noopStat = () => Promise.resolve(null);
35
37
  /**
36
38
  * Create a test runtime adapter with injectable process state.
37
39
  *
@@ -70,10 +72,13 @@ function createTestAdapter(options) {
70
72
  },
71
73
  isTTY: options?.isTTY ?? false,
72
74
  stdinIsTTY,
75
+ getTerminalSize: () => options?.terminalSize,
76
+ onTerminalResize: (listener) => options?.onTerminalResize?.(listener),
73
77
  exit: options?.exit ?? ((code) => {
74
78
  throw new ExitError(code);
75
79
  }),
76
80
  readFile: options?.readFile ?? noopReadFile,
81
+ stat: options?.stat ?? noopStat,
77
82
  homedir: options?.homedir ?? "/home/test",
78
83
  configDir: options?.configDir ?? "/home/test/.config"
79
84
  };
@@ -1,13 +1,12 @@
1
1
  import { RuntimeAdapter } from "./adapter.mjs";
2
2
  import { GlobalForDetect } from "./detect.mjs";
3
-
4
3
  //#region src/runtime/auto.d.ts
5
4
  /**
6
5
  * Create a runtime adapter for the current environment.
7
6
  *
8
7
  * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
9
- * Unknown runtimes fall back to the Node adapter because most JS runtimes
10
- * expose a Node-compatible `process` global.
8
+ * Only Deno needs a distinct adapter; Bun, Node, and unknown runtimes all use
9
+ * the Node adapter because they expose a Node-compatible `process` global.
11
10
  *
12
11
  * @param globals - Override `globalThis` for testing. Production callers
13
12
  * should omit this parameter.
@@ -1,7 +1,6 @@
1
- import { createNodeAdapter } from "./node.mjs";
2
- import { createBunAdapter } from "./bun.mjs";
3
1
  import { createDenoAdapter } from "./deno.mjs";
4
2
  import { detectRuntime } from "./detect.mjs";
3
+ import { createNodeAdapter } from "./node.mjs";
5
4
  //#region src/runtime/auto.ts
6
5
  function isDenoNamespace(value) {
7
6
  if (typeof value !== "object" || value === null) return false;
@@ -16,8 +15,8 @@ function getInjectedDenoNamespace(globals) {
16
15
  * Create a runtime adapter for the current environment.
17
16
  *
18
17
  * Detection order follows {@link detectRuntime}: Bun → Deno → Node → unknown.
19
- * Unknown runtimes fall back to the Node adapter because most JS runtimes
20
- * expose a Node-compatible `process` global.
18
+ * Only Deno needs a distinct adapter; Bun, Node, and unknown runtimes all use
19
+ * the Node adapter because they expose a Node-compatible `process` global.
21
20
  *
22
21
  * @param globals - Override `globalThis` for testing. Production callers
23
22
  * should omit this parameter.
@@ -35,8 +34,8 @@ function createAdapter(globals) {
35
34
  const runtimeGlobals = globals ?? globalThis;
36
35
  const runtime = detectRuntime(runtimeGlobals);
37
36
  switch (runtime) {
38
- case "bun": return createBunAdapter();
39
37
  case "deno": return createDenoAdapter(getInjectedDenoNamespace(runtimeGlobals));
38
+ case "bun":
40
39
  case "node":
41
40
  case "unknown": return createNodeAdapter();
42
41
  default: return runtime;
@@ -1,5 +1,4 @@
1
1
  import { RuntimeAdapter } from "./adapter.mjs";
2
-
3
2
  //#region src/runtime/deno.d.ts
4
3
  /**
5
4
  * Minimal subset of the Deno namespace needed by the adapter.
@@ -24,29 +23,49 @@ interface DenoNamespace {
24
23
  readonly args: readonly string[];
25
24
  /** Environment variable access (requires `--allow-env`). */
26
25
  readonly env: {
27
- /** Get a single env var. Returns `undefined` if unset or permission denied. */get(key: string): string | undefined; /** Get all env vars as a plain object. Throws on permission denied. */
26
+ /** Get a single env var. Returns `undefined` if unset or permission denied. */
27
+ get(key: string): string | undefined;
28
+ /** Get all env vars as a plain object. Throws on permission denied. */
28
29
  toObject(): Record<string, string>;
29
30
  };
30
31
  /** Current working directory (may throw if `--allow-read` is denied for cwd). */
31
32
  cwd(): string;
32
33
  /** Standard output — synchronous byte writer with TTY detection. */
33
34
  readonly stdout: {
34
- /** Write raw bytes to stdout synchronously. */writeSync(p: Uint8Array): number; /** Whether stdout is connected to a TTY. */
35
+ /** Write raw bytes to stdout synchronously. */
36
+ writeSync(p: Uint8Array): number;
37
+ /** Whether stdout is connected to a TTY. */
35
38
  isTerminal(): boolean;
36
39
  };
40
+ /** Current console dimensions. */
41
+ consoleSize?(): {
42
+ readonly columns: number;
43
+ readonly rows: number;
44
+ };
45
+ /** Register a native signal listener. */
46
+ addSignalListener?(signal: 'SIGWINCH', listener: () => void): void;
47
+ /** Remove a native signal listener. */
48
+ removeSignalListener?(signal: 'SIGWINCH', listener: () => void): void;
37
49
  /** Standard error — synchronous byte writer. */
38
50
  readonly stderr: {
39
- /** Write raw bytes to stderr synchronously. */writeSync(p: Uint8Array): number;
51
+ /** Write raw bytes to stderr synchronously. */
52
+ writeSync(p: Uint8Array): number;
40
53
  };
41
54
  /** Standard input — TTY detection and readable byte stream. */
42
55
  readonly stdin: {
43
- /** Whether stdin is connected to a TTY. */isTerminal(): boolean; /** Readable stream for stdin bytes. */
56
+ /** Whether stdin is connected to a TTY. */
57
+ isTerminal(): boolean;
58
+ /** Readable stream for stdin bytes. */
44
59
  readonly readable: ReadableStream<Uint8Array>;
45
60
  };
46
61
  /** Exit the process with the given code. */
47
62
  exit(code: number): never;
48
63
  /** Read a file as UTF-8 text (requires `--allow-read`). */
49
64
  readTextFile(path: string): Promise<string>;
65
+ /** Probe a filesystem path (requires `--allow-read`). */
66
+ stat(path: string): Promise<{
67
+ readonly isDirectory: boolean;
68
+ }>;
50
69
  }
51
70
  /**
52
71
  * Create a runtime adapter backed by the Deno namespace.
@@ -87,6 +87,14 @@ function createDenoAdapter(ns) {
87
87
  throw err;
88
88
  }
89
89
  };
90
+ const stat = async (path) => {
91
+ try {
92
+ return (await d.stat(path)).isDirectory ? "directory" : "file";
93
+ } catch (err) {
94
+ if (isDenoErrorNamed(err, "NotFound")) return null;
95
+ throw err;
96
+ }
97
+ };
90
98
  const homedir = resolveDenoHomedir(env, d.build.os === "windows");
91
99
  const configDir = resolveDenoConfigDir(env, homedir, d.build.os === "windows");
92
100
  const stdinIsTTY = d.stdin.isTerminal();
@@ -100,12 +108,49 @@ function createDenoAdapter(ns) {
100
108
  readStdin: () => readDenoStdinAll(d, stdinIsTTY),
101
109
  isTTY: d.stdout.isTerminal(),
102
110
  stdinIsTTY,
111
+ getTerminalSize: () => readDenoTerminalSize(d),
112
+ onTerminalResize: (listener) => onDenoTerminalResize(d, listener),
103
113
  exit: (code) => d.exit(code),
104
114
  readFile,
115
+ stat,
105
116
  homedir,
106
117
  configDir
107
118
  };
108
119
  }
120
+ /** Normalize terminal dimensions and discard unusable values. @internal */
121
+ function normalizeTerminalSize(columns, rows) {
122
+ if (columns === void 0 || rows === void 0) return void 0;
123
+ if (!Number.isFinite(columns) || !Number.isFinite(rows)) return void 0;
124
+ if (columns <= 0 || rows <= 0) return void 0;
125
+ return {
126
+ columns,
127
+ rows
128
+ };
129
+ }
130
+ /** Read native Deno terminal dimensions. @internal */
131
+ function readDenoTerminalSize(deno) {
132
+ if (!deno.stdout.isTerminal() || deno.consoleSize === void 0) return void 0;
133
+ try {
134
+ const size = deno.consoleSize();
135
+ return normalizeTerminalSize(size.columns, size.rows);
136
+ } catch {
137
+ return;
138
+ }
139
+ }
140
+ /** Subscribe to native Deno resize signals where SIGWINCH exists. @internal */
141
+ function onDenoTerminalResize(deno, listener) {
142
+ if (!deno.stdout.isTerminal()) return void 0;
143
+ if (deno.build.os === "windows") return void 0;
144
+ if (deno.addSignalListener === void 0 || deno.removeSignalListener === void 0) return;
145
+ try {
146
+ deno.addSignalListener("SIGWINCH", listener);
147
+ } catch {
148
+ return;
149
+ }
150
+ return () => {
151
+ deno.removeSignalListener?.("SIGWINCH", listener);
152
+ };
153
+ }
109
154
  /**
110
155
  * Access the global `Deno` namespace.
111
156
  *
@@ -1,7 +1,6 @@
1
- import { ExitError, RuntimeAdapter, TestAdapterOptions, createTestAdapter } from "./adapter.mjs";
1
+ import { ExitError, RuntimeAdapter, TerminalSize, TestAdapterOptions, createTestAdapter } from "./adapter.mjs";
2
2
  import { GlobalForDetect, RUNTIMES, Runtime, detectRuntime } from "./detect.mjs";
3
3
  import { createAdapter } from "./auto.mjs";
4
- import { NodeProcess, createNodeAdapter } from "./node.mjs";
5
- import { createBunAdapter } from "./bun.mjs";
6
4
  import { DenoNamespace, createDenoAdapter } from "./deno.mjs";
7
- export { type DenoNamespace, ExitError, type GlobalForDetect, type NodeProcess, RUNTIMES, type Runtime, type RuntimeAdapter, type TestAdapterOptions, createAdapter, createBunAdapter, createDenoAdapter, createNodeAdapter, createTestAdapter, detectRuntime };
5
+ import { NodeProcess, createNodeAdapter } from "./node.mjs";
6
+ export { type DenoNamespace, ExitError, type GlobalForDetect, type NodeProcess, RUNTIMES, type Runtime, type RuntimeAdapter, type TerminalSize, type TestAdapterOptions, createAdapter, createDenoAdapter, createNodeAdapter, createTestAdapter, detectRuntime };
@@ -1,5 +1,4 @@
1
1
  import { RuntimeAdapter } from "./adapter.mjs";
2
-
3
2
  //#region src/runtime/node.d.ts
4
3
  /**
5
4
  * Minimal subset of the Node.js `process` object needed by the adapter.
@@ -24,12 +23,19 @@ interface NodeProcess {
24
23
  readonly platform: string;
25
24
  /** Standard input stream with TTY detection and async iteration. */
26
25
  readonly stdin: {
27
- readonly isTTY?: boolean; /** Async iterable for reading all of stdin (used by readStdin). */
26
+ readonly isTTY?: boolean;
27
+ /** Async iterable for reading all of stdin (used by readStdin). */
28
28
  [Symbol.asyncIterator](): AsyncIterator<Uint8Array>;
29
29
  };
30
30
  /** Standard output stream with TTY detection and write. */
31
31
  readonly stdout: {
32
32
  readonly isTTY?: boolean;
33
+ readonly columns?: number;
34
+ readonly rows?: number;
35
+ getWindowSize?(): readonly [number, number];
36
+ on?(event: 'resize', listener: () => void): unknown;
37
+ off?(event: 'resize', listener: () => void): unknown;
38
+ removeListener?(event: 'resize', listener: () => void): unknown;
33
39
  write(data: string): unknown;
34
40
  };
35
41
  /** Standard error stream with write. */
@@ -90,6 +90,15 @@ function createNodeAdapter(proc) {
90
90
  throw err;
91
91
  }
92
92
  };
93
+ const stat = async (path) => {
94
+ const fs = await import("node:fs/promises");
95
+ try {
96
+ return (await fs.stat(path)).isDirectory() ? "directory" : "file";
97
+ } catch (err) {
98
+ if (isNodeSystemError(err) && (err.code === "ENOENT" || err.code === "ENOTDIR")) return null;
99
+ throw err;
100
+ }
101
+ };
93
102
  const homedir = resolveHomedir(p.env, p.platform);
94
103
  const configDir = resolveConfigDir(p.env, p.platform, homedir);
95
104
  const stdinIsTTY = p.stdin.isTTY === true;
@@ -103,12 +112,54 @@ function createNodeAdapter(proc) {
103
112
  readStdin: () => readNodeStdinAll(p, stdinIsTTY),
104
113
  isTTY: p.stdout.isTTY === true,
105
114
  stdinIsTTY,
115
+ getTerminalSize: () => readNodeTerminalSize(p),
116
+ onTerminalResize: (listener) => onNodeTerminalResize(p, listener),
106
117
  exit: (code) => p.exit(code),
107
118
  readFile,
119
+ stat,
108
120
  homedir,
109
121
  configDir
110
122
  };
111
123
  }
124
+ /** Normalize terminal dimensions and discard unusable values. @internal */
125
+ function normalizeTerminalSize(columns, rows) {
126
+ if (columns === void 0 || rows === void 0) return void 0;
127
+ if (!Number.isFinite(columns) || !Number.isFinite(rows)) return void 0;
128
+ if (columns <= 0 || rows <= 0) return void 0;
129
+ return {
130
+ columns,
131
+ rows
132
+ };
133
+ }
134
+ /** Read Node/Bun terminal dimensions from stdout. @internal */
135
+ function readNodeTerminalSize(proc) {
136
+ if (proc.stdout.isTTY !== true) return void 0;
137
+ try {
138
+ const size = proc.stdout.getWindowSize?.();
139
+ if (size !== void 0) {
140
+ const [columns, rows] = size;
141
+ const normalized = normalizeTerminalSize(columns, rows);
142
+ if (normalized !== void 0) return normalized;
143
+ }
144
+ } catch {}
145
+ return normalizeTerminalSize(proc.stdout.columns, proc.stdout.rows);
146
+ }
147
+ /** Subscribe to Node/Bun stdout resize events when available. @internal */
148
+ function onNodeTerminalResize(proc, listener) {
149
+ if (proc.stdout.isTTY !== true || proc.stdout.on === void 0) return void 0;
150
+ if (proc.stdout.off !== void 0) {
151
+ proc.stdout.on("resize", listener);
152
+ return () => {
153
+ proc.stdout.off?.("resize", listener);
154
+ };
155
+ }
156
+ if (proc.stdout.removeListener !== void 0) {
157
+ proc.stdout.on("resize", listener);
158
+ return () => {
159
+ proc.stdout.removeListener?.("resize", listener);
160
+ };
161
+ }
162
+ }
112
163
  /**
113
164
  * Read all of stdin as a single string (for piped data).
114
165
  *
@@ -1,7 +1,7 @@
1
- import { ExitError, RuntimeAdapter } from "./runtime/adapter.mjs";
1
+ import { ExitError, RuntimeAdapter, TerminalSize } from "./runtime/adapter.mjs";
2
2
  import { RUNTIMES, Runtime, detectRuntime } from "./runtime/detect.mjs";
3
3
  import { createAdapter } from "./runtime/auto.mjs";
4
- import { createNodeAdapter } from "./runtime/node.mjs";
5
- import { createBunAdapter } from "./runtime/bun.mjs";
6
4
  import { createDenoAdapter } from "./runtime/deno.mjs";
7
- export { ExitError, RUNTIMES, type Runtime, type RuntimeAdapter, createAdapter, createBunAdapter, createDenoAdapter, createNodeAdapter, detectRuntime };
5
+ import { createNodeAdapter } from "./runtime/node.mjs";
6
+ import "./runtime/index.mjs";
7
+ export { ExitError, RUNTIMES, type Runtime, type RuntimeAdapter, type TerminalSize, createAdapter, createDenoAdapter, createNodeAdapter, detectRuntime };