@kjanat/dreamcli 2.2.0 → 2.3.0
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 +43 -1
- package/dist/core/cli/dispatch.d.mts +30 -2
- package/dist/core/cli/dispatch.mjs +1 -1
- package/dist/core/cli/help-links.d.mts +28 -0
- package/dist/core/cli/help-links.mjs +1 -0
- package/dist/core/cli/index.d.mts +53 -2
- package/dist/core/cli/index.mjs +1 -1
- package/dist/core/cli/planner.mjs +1 -1
- package/dist/core/cli/root-help.d.mts +4 -0
- package/dist/core/cli/root-help.mjs +4 -5
- package/dist/core/cli/runtime-preflight.d.mts +3 -0
- package/dist/core/cli/runtime-preflight.mjs +1 -1
- package/dist/core/config/index.d.mts +2 -2
- package/dist/core/config/package-json.d.mts +36 -1
- package/dist/core/config/package-json.mjs +1 -1
- package/dist/core/execution/index.mjs +1 -1
- package/dist/core/help/ansi.d.mts +78 -0
- package/dist/core/help/ansi.mjs +2 -0
- package/dist/core/help/index.d.mts +9 -1
- package/dist/core/help/index.mjs +4 -5
- package/dist/core/parse/index.d.mts +31 -1
- package/dist/core/parse/index.mjs +1 -1
- package/dist/index.d.mts +4 -2
- package/dist/index.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/package.json +5 -2
- package/src/core/cli/dispatch.ts +70 -7
- package/src/core/cli/help-links.ts +82 -0
- package/src/core/cli/index.ts +104 -6
- package/src/core/cli/planner.ts +23 -5
- package/src/core/cli/root-help.ts +36 -53
- package/src/core/cli/runtime-preflight.ts +5 -0
- package/src/core/config/index.ts +2 -2
- package/src/core/config/package-json.ts +119 -2
- package/src/core/execution/index.ts +1 -9
- package/src/core/help/ansi.ts +144 -0
- package/src/core/help/index.ts +9 -50
- package/src/core/parse/index.ts +21 -1
- package/src/index.ts +4 -1
package/dist/core/help/index.mjs
CHANGED
|
@@ -1,8 +1,7 @@
|
|
|
1
|
-
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{formatDisplayValue as t}from"../output/display-value.mjs";function
|
|
2
|
-
`)}function a(e){return typeof e==`string`?`[deprecated: ${e}]`:`[deprecated]`}function o(e){return e===void 0?`undefined`:e===null?`null`:t(e)}function s(t,n){let r=e(n,{kind:`short`}),i=e(n,{kind:`long`}),a=[...r.map(e=>`-${e}`),`--${t}`,...i.map(e=>`--${e}`)];return n.kind===`boolean`?a.join(`, `):`${a.join(`, `)} ${c(n)}`}function c(e){switch(e.kind){case`string`:return`<string>`;case`number`:return`<number>`;case`enum`:return`<${(e.enumValues??[]).join(`|`)}>`;case`array`:return`<${e.elementSchema===void 0?`value`:c(e.elementSchema).slice(1,-1)}>...`;case`boolean`:return``;case`custom`:return`<value>`}}function l(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.configPath!==void 0&&t.push(`[config: ${e.configPath}]`),e.prompt!==void 0&&t.push(`[prompt]`),e.presence===`required`?t.push(`[required]`):e.presence===`defaulted`&&e.kind!==`boolean`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function u(t){let n=Object.keys(t);if(n.length===0)return[];let r=[...n].sort((n,r)=>{let i=t[n],a=t[r];if(i===void 0||a===void 0)return 0;let o=e(i,{kind:`short`}).length>0,s=e(a,{kind:`short`}).length>0;return o&&!s?-1:!o&&s?1:n.localeCompare(r)}),i=[];for(let e of r){let n=t[e];n!==void 0&&i.push({left:s(e,n),description:l(n)})}return i}function d(e){let{name:t,schema:n}=e,r=n.kind===`enum`&&n.enumValues!==void 0?n.enumValues.join(`|`):t,i=n.variadic?`...`:``;return n.presence===`required`?`<${r}>${i}`:`[${r}]${i}`}function f(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.presence===`defaulted`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function p(e,t){let r=n(t),i=[];i.push(h(e,r)),e.description!==void 0&&i.push(e.description);let a=e.commands.filter(e=>!e.hidden);return a.length>0&&i.push(v(a,r)),e.args.length>0&&i.push(g(e.args,r)),Object.keys(e.flags).length>0&&i.push(_(e.flags,r)),e.examples.length>0&&i.push(y(e.examples)),i}function m(e,t){return`${p(e,t).join(`
|
|
1
|
+
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{formatDisplayValue as t}from"../output/display-value.mjs";import{padEnd as n,wrapText as r}from"./ansi.mjs";function i(e){return{width:e?.width??80,binName:e?.binName,isDefaultHelp:e?.isDefaultHelp??!1}}function a(e){return typeof e==`string`?`[deprecated: ${e}]`:`[deprecated]`}function o(e){return e===void 0?`undefined`:e===null?`null`:t(e)}function s(t,n){let r=e(n,{kind:`short`}),i=e(n,{kind:`long`}),a=[...r.map(e=>`-${e}`),`--${t}`,...i.map(e=>`--${e}`)];return n.kind===`boolean`?a.join(`, `):`${a.join(`, `)} ${c(n)}`}function c(e){switch(e.kind){case`string`:return`<string>`;case`number`:return`<number>`;case`enum`:return`<${(e.enumValues??[]).join(`|`)}>`;case`array`:return`<${e.elementSchema===void 0?`value`:c(e.elementSchema).slice(1,-1)}>...`;case`boolean`:return``;case`custom`:return`<value>`}}function l(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.configPath!==void 0&&t.push(`[config: ${e.configPath}]`),e.prompt!==void 0&&t.push(`[prompt]`),e.presence===`required`?t.push(`[required]`):e.presence===`defaulted`&&e.kind!==`boolean`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function u(t){let n=Object.keys(t);if(n.length===0)return[];let r=[...n].sort((n,r)=>{let i=t[n],a=t[r];if(i===void 0||a===void 0)return 0;let o=e(i,{kind:`short`}).length>0,s=e(a,{kind:`short`}).length>0;return o&&!s?-1:!o&&s?1:n.localeCompare(r)}),i=[];for(let e of r){let n=t[e];n!==void 0&&i.push({left:s(e,n),description:l(n)})}return i}function d(e){let{name:t,schema:n}=e,r=n.kind===`enum`&&n.enumValues!==void 0?n.enumValues.join(`|`):t,i=n.variadic?`...`:``;return n.presence===`required`?`<${r}>${i}`:`[${r}]${i}`}function f(e){let t=[];return e.description!==void 0&&t.push(e.description),e.deprecated!==void 0&&t.push(a(e.deprecated)),e.envVar!==void 0&&t.push(`[env: ${e.envVar}]`),e.presence===`defaulted`&&t.push(`(default: ${o(e.defaultValue)})`),t.join(` `)}function p(e,t){let n=i(t),r=[];r.push(h(e,n)),e.description!==void 0&&r.push(e.description);let a=e.commands.filter(e=>!e.hidden);return a.length>0&&r.push(v(a,n)),e.args.length>0&&r.push(g(e.args,n)),Object.keys(e.flags).length>0&&r.push(_(e.flags,n)),e.examples.length>0&&r.push(y(e.examples)),r}function m(e,t){return`${p(e,t).join(`
|
|
3
2
|
|
|
4
|
-
`)}\n`}function h(e,t){let n=[`Usage:`],r=t.binName===void 0||t.isDefaultHelp&&t.binName===e.name?e.name:`${t.binName} ${e.name}`;n.push(r),e.commands.length>0&&n.push(`<command>`),Object.keys(e.flags).length>0&&n.push(`[flags]`);for(let t of e.args)n.push(d(t));return n.join(` `)}function g(e,t){let
|
|
5
|
-
`)}function _(e,t){let
|
|
6
|
-
`)}function v(e,t){let
|
|
3
|
+
`)}\n`}function h(e,t){let n=[`Usage:`],r=t.binName===void 0||t.isDefaultHelp&&t.binName===e.name?e.name:`${t.binName} ${e.name}`;n.push(r),e.commands.length>0&&n.push(`<command>`),Object.keys(e.flags).length>0&&n.push(`[flags]`);for(let t of e.args)n.push(d(t));return n.join(` `)}function g(e,t){let i=[`Arguments:`],a=0,o=[];for(let t of e){let e=` ${d(t)}`,n=f(t.schema);o.push({left:e,desc:n}),e.length>a&&(a=e.length)}let s=a+2;for(let{left:e,desc:a}of o)if(a.length===0)i.push(e);else{let o=n(e,s),c=r(a,t.width,s);i.push(`${o}${c}`)}return i.join(`
|
|
4
|
+
`)}function _(e,t){let i=[`Flags:`],a=u(e);if(a.length===0)return``;let o=0;for(let e of a){let t=` ${e.left}`;t.length>o&&(o=t.length)}let s=o+2;for(let e of a){let a=` ${e.left}`;if(e.description.length===0)i.push(a);else{let o=n(a,s),c=r(e.description,t.width,s);i.push(`${o}${c}`)}}return i.join(`
|
|
5
|
+
`)}function v(e,t){let i=[`Commands:`],a=0;for(let t of e)t.name.length>a&&(a=t.name.length);let o=2+a+2;for(let a of e){let e=` ${a.name}`,s=a.description??``;if(s.length===0)i.push(e);else{let a=n(e,o),c=r(s,t.width,o);i.push(`${a}${c}`)}}return i.join(`
|
|
7
6
|
`)}function y(e){let t=[`Examples:`];for(let n of e)n.description===void 0?t.push(` $ ${n.command}`):(t.push(` ${n.description}:`),t.push(` $ ${n.command}`));return t.join(`
|
|
8
7
|
`)}export{m as formatHelp,p as formatHelpSections};
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { FlagSchema } from "../schema/flag.mjs";
|
|
1
2
|
import { CommandSchema } from "../schema/command.mjs";
|
|
2
3
|
|
|
3
4
|
//#region src/core/parse/index.d.ts
|
|
@@ -44,6 +45,19 @@ type Token = {
|
|
|
44
45
|
* ```
|
|
45
46
|
*/
|
|
46
47
|
declare function tokenize(argv: readonly string[]): readonly Token[];
|
|
48
|
+
/**
|
|
49
|
+
* Whether `token` appears in argv before the `--` end-of-options separator.
|
|
50
|
+
*
|
|
51
|
+
* Everything at or after the first `--` is a literal positional, so root-level
|
|
52
|
+
* flag interception (`--help` / `--version` / `--json`) must use this instead of
|
|
53
|
+
* a naive `Array.includes()` — otherwise a post-separator literal (`-- --json`)
|
|
54
|
+
* is wrongly treated as the flag.
|
|
55
|
+
*
|
|
56
|
+
* @param argv - Raw argument strings.
|
|
57
|
+
* @param token - Exact flag token to look for (e.g. `--version`).
|
|
58
|
+
* @returns `true` if `token` occurs before any `--` separator.
|
|
59
|
+
*/
|
|
60
|
+
declare function includesBeforeSeparator(argv: readonly string[], token: string): boolean;
|
|
47
61
|
/**
|
|
48
62
|
* Raw parsed values before resolution (defaults, env, config, etc.).
|
|
49
63
|
*
|
|
@@ -56,6 +70,22 @@ interface ParseResult {
|
|
|
56
70
|
/** Positional arg values keyed by arg name. */
|
|
57
71
|
readonly args: Readonly<Record<string, unknown>>;
|
|
58
72
|
}
|
|
73
|
+
/**
|
|
74
|
+
* Build a map from flag name/alias → [canonicalName, {@link FlagSchema}].
|
|
75
|
+
*
|
|
76
|
+
* Supports both long names and single-char aliases for short flag expansion.
|
|
77
|
+
*
|
|
78
|
+
* @param flags - Flag schemas keyed by canonical name
|
|
79
|
+
* @returns Lookup map covering all names and aliases
|
|
80
|
+
*/
|
|
81
|
+
declare function buildFlagLookup(flags: Readonly<Record<string, FlagSchema>>): ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
|
|
82
|
+
/**
|
|
83
|
+
* Whether a flag kind expects a value argument (vs. being a bare boolean).
|
|
84
|
+
*
|
|
85
|
+
* @param schema - Flag schema to check
|
|
86
|
+
* @returns `true` if the flag expects a value token after it
|
|
87
|
+
*/
|
|
88
|
+
declare function flagExpectsValue(schema: FlagSchema): boolean;
|
|
59
89
|
/**
|
|
60
90
|
* Parse tokenized argv against a command schema.
|
|
61
91
|
*
|
|
@@ -76,4 +106,4 @@ interface ParseResult {
|
|
|
76
106
|
*/
|
|
77
107
|
declare function parse(schema: CommandSchema, argv: readonly string[]): ParseResult;
|
|
78
108
|
//#endregion
|
|
79
|
-
export { type ParseResult, type Token, parse, tokenize };
|
|
109
|
+
export { type ParseResult, type Token, buildFlagLookup, flagExpectsValue, includesBeforeSeparator, parse, tokenize };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function r(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function
|
|
1
|
+
import{getFlagAliasNames as e}from"../schema/flag.mjs";import{ParseError as t}from"../errors/index.mjs";function n(e){let t=[],n=!1;for(let r of e){if(n){t.push({kind:`positional`,value:r});continue}if(r===`--`){t.push({kind:`separator`}),n=!0;continue}if(r.startsWith(`--`)){let e=r.indexOf(`=`);e===-1?t.push({kind:`long-flag`,name:r.slice(2),value:void 0}):t.push({kind:`long-flag`,name:r.slice(2,e),value:r.slice(e+1)});continue}if(r.startsWith(`-`)&&r.length>1){t.push({kind:`short-flags`,chars:r.slice(1)});continue}t.push({kind:`positional`,value:r})}return t}function r(e,t){for(let n of e){if(n===`--`)return!1;if(n===t)return!0}return!1}function i(t){let n=new Map;for(let[r,i]of Object.entries(t)){n.set(r,[r,i]);for(let t of e(i,{includeHidden:!0}))n.set(t,[r,i])}return n}function a(e){return e.kind!==`boolean`}function o(e,n,r,i=`--${e}`){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for flag ${i}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`number`}});return r}case`boolean`:if(n===`true`||n===`1`)return!0;if(n===`false`||n===`0`)return!1;throw new t(`Invalid boolean value '${n}' for flag ${i}. Use true/false or 1/0`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,expected:`boolean`}});case`enum`:{let a=r.enumValues;if(a===void 0)throw new t(`Enum flag --${e} is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{flag:e,kind:`enum`,missing:`enumValues`}});if(!a.includes(n))throw new t(`Invalid value '${n}' for flag ${i}. Allowed: ${a.join(`, `)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n,allowed:a}});return n}case`array`:return r.elementSchema?o(e,n,r.elementSchema):n;case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse flag ${i}: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{flag:e,input:i,value:n},cause:r})}}}function s(e,n,r){switch(r.kind){case`string`:return n;case`number`:{let r=Number(n);if(Number.isNaN(r))throw new t(`Invalid number value '${n}' for argument <${e}>`,{code:`INVALID_VALUE`,details:{arg:e,value:n,expected:`number`}});return r}case`enum`:{let i=r.enumValues;if(i===void 0)throw new t(`Enum argument <${e}> is misconfigured: no allowed values declared`,{code:`INVALID_SCHEMA`,details:{arg:e,kind:`enum`,missing:`enumValues`}});if(!i.includes(n))throw new t(`Invalid value '${n}' for argument <${e}>. Allowed: ${i.join(`, `)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n,allowed:i}});return n}case`custom`:if(!r.parseFn)return n;try{return r.parseFn(n)}catch(r){throw r instanceof t?r:new t(`Failed to parse argument <${e}>: ${r instanceof Error?r.message:String(r)}`,{code:`INVALID_VALUE`,details:{arg:e,value:n},cause:r})}}}function c(e,t){let r=n(t),a=i(e.flags),o={},s=[],c=0;for(;c<r.length;){let e=r[c];if(e===void 0)break;if(e.kind===`separator`){c++;continue}if(e.kind===`positional`){s.push(e.value),c++;continue}if(e.kind===`long-flag`){c=l(e,r,c,a,o);continue}c=u(e,r,c,a,o)}return{flags:o,args:f(e.args,s)}}function l(e,n,r,i,s){let c=i.get(e.name);if(!c){let n=p(e.name,i);throw new t(`Unknown flag --${e.name}${n?`. Did you mean --${n}?`:``}`,{code:`UNKNOWN_FLAG`,details:{flag:e.name,...n?{suggestion:n}:{}},...n?{suggest:`--${n}`}:{}})}let[l,u]=c;if(!a(u))return e.value===void 0?s[l]=!0:s[l]=o(l,e.value,u,`--${e.name}`),r+1;if(e.value!==void 0)return d(s,l,u,e.value),r+1;let f=n[r+1];if(!f||f.kind!==`positional`)throw new t(`Flag --${e.name} requires a value`,{code:`MISSING_VALUE`,details:{flag:l,input:e.name,kind:u.kind}});return d(s,l,u,f.value,`--${e.name}`),r+2}function u(e,n,r,i,o){let{chars:s}=e,c=r+1;for(let e=0;e<s.length;e++){let r=s.charAt(e),l=i.get(r);if(!l)throw new t(`Unknown flag -${r}`,{code:`UNKNOWN_FLAG`,details:{flag:r}});let[u,f]=l;if(!a(f)){o[u]=!0;continue}if(e<s.length-1){d(o,u,f,s.slice(e+1),`-${r}`);break}let p=n[c];if(!p||p.kind!==`positional`)throw new t(`Flag -${r} requires a value`,{code:`MISSING_VALUE`,details:{flag:u,input:r,kind:f.kind}});d(o,u,f,p.value,`-${r}`),c++}return c}function d(e,t,n,r,i=`--${t}`){let a=o(t,r,n,i);if(n.kind===`array`){let n=e[t];Array.isArray(n)?n.push(a):e[t]=[a]}else e[t]=a}function f(e,n){let r={},i=0;for(let t of e){if(t.schema.variadic){let e=n.slice(i);r[t.name]=e.map(e=>s(t.name,e,t.schema)),i=n.length;break}let e=n[i];e!==void 0&&(r[t.name]=s(t.name,e,t.schema),i++)}if(i<n.length){let r=n.slice(i);throw new t(`Unexpected positional argument${r.length>1?`s`:``}: ${r.join(`, `)}`,{code:`UNEXPECTED_POSITIONAL`,details:{excess:r,expected:e.length}})}return r}function p(e,t){let n,r=1/0,i=Math.max(2,Math.floor(e.length/2));for(let a of t.keys()){let o=t.get(a);if(o===void 0)continue;let[s,c]=o,l=c.aliases.find(e=>e.name===a);if(a.length<2||a!==s&&l?.hidden)continue;let u=m(e,a);u<r&&u<=i&&(r=u,n=a)}return n}function m(e,t){if(e===t)return 0;if(e.length===0)return t.length;if(t.length===0)return e.length;let n=e.length<=t.length?e:t,r=e.length<=t.length?t:e,i=n.length,a=r.length,o=Array.from({length:i+1},(e,t)=>t);for(let e=1;e<=a;e++){let t=o[0]??0;o[0]=e;for(let a=1;a<=i;a++){let i=n.charAt(a-1)===r.charAt(e-1)?0:1,s=Math.min((o[a]??0)+1,(o[a-1]??0)+1,t+i);t=o[a]??0,o[a]=s}}return o[i]??0}export{i as buildFlagLookup,a as flagExpectsValue,r as includesBeforeSeparator,c as parse,n as tokenize};
|
package/dist/index.d.mts
CHANGED
|
@@ -12,17 +12,19 @@ import { DeprecationWarning, ResolveOptions, ResolveResult } from "./core/resolv
|
|
|
12
12
|
import { resolve } from "./core/resolve/index.mjs";
|
|
13
13
|
import { BeforeParseParams, CLIPlugin, CLIPluginHooks, PluginCommandContext, ResolvedCommandParams, plugin } from "./core/cli/plugin.mjs";
|
|
14
14
|
import { CLIError, CLIErrorJSON, CLIErrorOptions, ErrorCode, ParseError, ParseErrorCode, ParseErrorOptions, ValidationError, ValidationErrorCode, ValidationErrorOptions, isCLIError, isParseError, isValidationError } from "./core/errors/index.mjs";
|
|
15
|
+
import { osc8, visibleWidth } from "./core/help/ansi.mjs";
|
|
15
16
|
import { HelpOptions, formatHelp } from "./core/help/index.mjs";
|
|
16
17
|
import { RunResult } from "./core/schema/run.mjs";
|
|
17
18
|
import { ActionHandler, ActionParams, AnyCommandBuilder, CommandArgEntry, CommandBuilder, CommandConfig, CommandExample, CommandMeta, CommandSchema, DeriveHandler, DeriveParams, InteractiveParams, InteractiveResolver, InteractiveResult, Out, command, group } from "./core/schema/command.mjs";
|
|
19
|
+
import { PackageJsonAdapter, PackageJsonData, PackageRepository, discoverPackageJson, inferCliName, packageRepositoryUrl } from "./core/config/package-json.mjs";
|
|
20
|
+
import { HelpLinks } from "./core/cli/help-links.mjs";
|
|
18
21
|
import { CompletionOptions } from "./core/completion/shells/shared.mjs";
|
|
19
22
|
import { generateBashCompletion } from "./core/completion/shells/bash.mjs";
|
|
20
23
|
import { generateFishCompletion } from "./core/completion/shells/fish.mjs";
|
|
21
24
|
import { generatePowerShellCompletion } from "./core/completion/shells/powershell.mjs";
|
|
22
25
|
import { generateZshCompletion } from "./core/completion/shells/zsh.mjs";
|
|
23
26
|
import { SHELLS, Shell, generateCompletion } from "./core/completion/index.mjs";
|
|
24
|
-
import { PackageJsonAdapter, PackageJsonData, discoverPackageJson, inferCliName } from "./core/config/package-json.mjs";
|
|
25
27
|
import { ConfigAdapter, ConfigDiscoveryOptions, ConfigDiscoveryResult, ConfigFound, ConfigNotFound, FormatLoader, buildConfigSearchPaths, configFormat, discoverConfig } from "./core/config/index.mjs";
|
|
26
28
|
import { CLIBuilder, CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings, cli } from "./core/cli/index.mjs";
|
|
27
29
|
import { JsonSchemaOptions, definitionMetaSchema, generateInputSchema, generateSchema } from "./core/json-schema/index.mjs";
|
|
28
|
-
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 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 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 HelpOptions, type InferArg, type InferArgs, type InferFlag, type InferFlags, type InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, type Out, type OutputOptions, type PackageJsonAdapter, type PackageJsonData, type PackageJsonSettings, 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 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, discoverPackageJson, flag, formatHelp, generateBashCompletion, generateCompletion, generateFishCompletion, generateInputSchema, generatePowerShellCompletion, generateSchema, generateZshCompletion, group, inferCliName, isCLIError, isParseError, isValidationError, middleware, parse, plugin, resolve, resolvePromptConfig, tokenize };
|
|
30
|
+
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 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 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 InputPromptConfig, type InteractiveParams, type InteractiveResolver, type InteractiveResult, type JsonSchemaOptions, type Middleware, type MiddlewareHandler, type MiddlewareParams, type MultiselectPromptConfig, 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 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, 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 +1 @@
|
|
|
1
|
-
import{FlagBuilder as e,createSchema as t,flag as n}from"./core/schema/flag.mjs";import{generateBashCompletion as r}from"./core/completion/shells/bash.mjs";import{generateFishCompletion as i}from"./core/completion/shells/fish.mjs";import{generatePowerShellCompletion as a}from"./core/completion/shells/powershell.mjs";import{CLIError as o,ParseError as s,ValidationError as c,isCLIError as l,isParseError as u,isValidationError as d}from"./core/errors/index.mjs";import{generateZshCompletion as f}from"./core/completion/shells/zsh.mjs";import{SHELLS as p,generateCompletion as m}from"./core/completion/index.mjs";import{
|
|
1
|
+
import{FlagBuilder as e,createSchema as t,flag as n}from"./core/schema/flag.mjs";import{generateBashCompletion as r}from"./core/completion/shells/bash.mjs";import{generateFishCompletion as i}from"./core/completion/shells/fish.mjs";import{generatePowerShellCompletion as a}from"./core/completion/shells/powershell.mjs";import{CLIError as o,ParseError as s,ValidationError as c,isCLIError as l,isParseError as u,isValidationError as d}from"./core/errors/index.mjs";import{generateZshCompletion as f}from"./core/completion/shells/zsh.mjs";import{SHELLS as p,generateCompletion as m}from"./core/completion/index.mjs";import{osc8 as h,visibleWidth as g}from"./core/help/ansi.mjs";import{formatHelp as _}from"./core/help/index.mjs";import{parse as v,tokenize as y}from"./core/parse/index.mjs";import{createTerminalPrompter as b,resolvePromptConfig as x}from"./core/prompt/index.mjs";import{resolve as S}from"./core/resolve/index.mjs";import{createOutput as C}from"./core/output/index.mjs";import{ArgBuilder as w,arg as T,createArgSchema as E}from"./core/schema/arg.mjs";import{CommandBuilder as D,command as O,group as k}from"./core/schema/command.mjs";import{discoverPackageJson as A,inferCliName as j,packageRepositoryUrl as M}from"./core/config/package-json.mjs";import{plugin as N}from"./core/cli/plugin.mjs";import{buildConfigSearchPaths as P,configFormat as F,discoverConfig as I}from"./core/config/index.mjs";import{CLIBuilder as L,cli as R}from"./core/cli/index.mjs";import{definitionMetaSchema as z,generateInputSchema as B,generateSchema as V}from"./core/json-schema/index.mjs";import{middleware as H}from"./core/schema/middleware.mjs";export{w as ArgBuilder,L as CLIBuilder,o as CLIError,D as CommandBuilder,e as FlagBuilder,s as ParseError,p as SHELLS,c as ValidationError,T as arg,P as buildConfigSearchPaths,R as cli,O as command,F as configFormat,E as createArgSchema,C as createOutput,t as createSchema,b as createTerminalPrompter,z as definitionMetaSchema,I as discoverConfig,A as discoverPackageJson,n as flag,_ as formatHelp,r as generateBashCompletion,m as generateCompletion,i as generateFishCompletion,B as generateInputSchema,a as generatePowerShellCompletion,V as generateSchema,f as generateZshCompletion,k as group,j as inferCliName,l as isCLIError,u as isParseError,d as isValidationError,H as middleware,h as osc8,M as packageRepositoryUrl,v as parse,N as plugin,S as resolve,x as resolvePromptConfig,y as tokenize,g as visibleWidth};
|
package/dist/version.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const e=`2.
|
|
1
|
+
const e=`2.3.0`,t=`23cad0f`;export{t as DREAMCLI_REVISION,e as DREAMCLI_VERSION};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kjanat/dreamcli",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.3.0",
|
|
4
4
|
"description": "Schema-first, fully typed TypeScript CLI framework",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"cli",
|
|
@@ -82,6 +82,8 @@
|
|
|
82
82
|
"docs:dev": "bunx --bun vitepress@next dev docs",
|
|
83
83
|
"docs:preview": "bunx --bun vitepress@next preview docs",
|
|
84
84
|
"fmt": "dprint fmt",
|
|
85
|
+
"fmt:autofix": "dprint fmt --allow-no-files --excludes .github",
|
|
86
|
+
"fmt:update": "dprint config update --yes --recursive",
|
|
85
87
|
"format": "dprint fmt",
|
|
86
88
|
"format:check": "dprint check",
|
|
87
89
|
"gh-project": "bun scripts/gh-project.ts",
|
|
@@ -92,6 +94,7 @@
|
|
|
92
94
|
"gh-project:sync": "bun gh-project sync",
|
|
93
95
|
"knip": "knip",
|
|
94
96
|
"lint": "biome lint",
|
|
97
|
+
"lint:autofix": "biome check --skip-parse-errors --no-errors-on-unmatched --changed --write",
|
|
95
98
|
"lint:fix": "biome lint --fix",
|
|
96
99
|
"meta-descriptions": "bun --bun scripts/build-meta-descriptions.ts",
|
|
97
100
|
"meta-descriptions:check": "bun --bun scripts/build-meta-descriptions.ts --check",
|
|
@@ -130,7 +133,7 @@
|
|
|
130
133
|
"wrangler": "^4.80.0",
|
|
131
134
|
"yaml": "^2.8.3"
|
|
132
135
|
},
|
|
133
|
-
"packageManager": "bun@1.3.
|
|
136
|
+
"packageManager": "bun@1.3.14",
|
|
134
137
|
"engines": {
|
|
135
138
|
"bun": ">=1.3",
|
|
136
139
|
"deno": ">=2.6.0",
|
package/src/core/cli/dispatch.ts
CHANGED
|
@@ -10,7 +10,18 @@
|
|
|
10
10
|
* @internal
|
|
11
11
|
*/
|
|
12
12
|
|
|
13
|
+
import { buildFlagLookup, flagExpectsValue } from '#internals/core/parse/index.ts';
|
|
13
14
|
import type { CommandSchema, ErasedCommand } from '#internals/core/schema/command.ts';
|
|
15
|
+
import type { FlagSchema } from '#internals/core/schema/flag.ts';
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Flag lookup (name/alias → `[canonicalName, schema]`) used to make the
|
|
19
|
+
* command-name scan aware of value-flag arity. Built from the flags valid at
|
|
20
|
+
* the current dispatch level via {@link buildFlagLookup}.
|
|
21
|
+
*
|
|
22
|
+
* @internal
|
|
23
|
+
*/
|
|
24
|
+
type ValueFlagLookup = ReadonlyMap<string, readonly [name: string, schema: FlagSchema]>;
|
|
14
25
|
|
|
15
26
|
// --- Dispatch result types (discriminated union)
|
|
16
27
|
|
|
@@ -72,6 +83,9 @@ type DispatchResult = DispatchMatch | DispatchNeedsSubcommand | DispatchUnknown;
|
|
|
72
83
|
* @param argv - Remaining argv tokens (command names + flags + args).
|
|
73
84
|
* @param commands - Command map at the current tree level.
|
|
74
85
|
* @param ancestorPath - Schema path from root to current level (exclusive).
|
|
86
|
+
* @param valueFlags - Lookup of flags valid at this level, used so a
|
|
87
|
+
* space-separated value-flag's value (`--region eu`) is not mistaken for a
|
|
88
|
+
* command name. Empty by default (arity-unaware, legacy behaviour).
|
|
75
89
|
* @returns Discriminated dispatch result.
|
|
76
90
|
*
|
|
77
91
|
* @internal
|
|
@@ -80,22 +94,29 @@ function dispatch(
|
|
|
80
94
|
argv: readonly string[],
|
|
81
95
|
commands: ReadonlyMap<string, ErasedCommand>,
|
|
82
96
|
ancestorPath: readonly CommandSchema[] = [],
|
|
97
|
+
valueFlags: ValueFlagLookup = new Map(),
|
|
83
98
|
): DispatchResult {
|
|
84
99
|
// Find first non-flag token (potential command name).
|
|
85
100
|
// Flags may appear before the command name (e.g. `--verbose db migrate`).
|
|
86
101
|
// `--` terminates flag scanning — the next token is treated as a command name.
|
|
102
|
+
// Value-flags in space-separated form (`--region eu`, `-r eu`) consume the
|
|
103
|
+
// following token as their value, so it must be skipped rather than matched
|
|
104
|
+
// as a command name (see #25).
|
|
87
105
|
let cmdIdx = -1;
|
|
88
106
|
for (let i = 0; i < argv.length; i++) {
|
|
89
107
|
const token = argv[i];
|
|
108
|
+
if (token === undefined) continue;
|
|
90
109
|
if (token === '--') {
|
|
91
110
|
// End-of-flags marker: next token (if any) is the command name.
|
|
92
111
|
if (i + 1 < argv.length) cmdIdx = i + 1;
|
|
93
112
|
break;
|
|
94
113
|
}
|
|
95
|
-
if (token
|
|
96
|
-
|
|
97
|
-
|
|
114
|
+
if (token.startsWith('-')) {
|
|
115
|
+
if (consumesFollowingToken(token, valueFlags)) i++; // skip the flag's value
|
|
116
|
+
continue;
|
|
98
117
|
}
|
|
118
|
+
cmdIdx = i;
|
|
119
|
+
break;
|
|
99
120
|
}
|
|
100
121
|
|
|
101
122
|
if (cmdIdx === -1) {
|
|
@@ -132,9 +153,15 @@ function dispatch(
|
|
|
132
153
|
const remaining = [...argv.slice(0, cmdIdx), ...argv.slice(cmdIdx + 1)];
|
|
133
154
|
const currentPath = [...ancestorPath, matched.schema];
|
|
134
155
|
|
|
135
|
-
// If command has subcommands, try to descend.
|
|
156
|
+
// If command has subcommands, try to descend. The matched command's own
|
|
157
|
+
// flags govern arity at the child level (e.g. `db --config x migrate`).
|
|
136
158
|
if (matched.subcommands.size > 0) {
|
|
137
|
-
const subResult = dispatch(
|
|
159
|
+
const subResult = dispatch(
|
|
160
|
+
remaining,
|
|
161
|
+
matched.subcommands,
|
|
162
|
+
currentPath,
|
|
163
|
+
buildFlagLookup(matched.schema.flags),
|
|
164
|
+
);
|
|
138
165
|
|
|
139
166
|
switch (subResult.kind) {
|
|
140
167
|
case 'match':
|
|
@@ -188,6 +215,42 @@ function dispatch(
|
|
|
188
215
|
};
|
|
189
216
|
}
|
|
190
217
|
|
|
218
|
+
// --- Flag-arity awareness
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Whether a flag token consumes the following argv token as its value.
|
|
222
|
+
*
|
|
223
|
+
* Mirrors the parser's value-consumption rules (`parseLongFlag` /
|
|
224
|
+
* `parseShortFlags`) so the command-name scan skips exactly the tokens the
|
|
225
|
+
* parser would treat as flag values:
|
|
226
|
+
* - `--flag value` → consumes when `--flag` is a known value-flag.
|
|
227
|
+
* - `--flag=value` → self-contained, consumes nothing.
|
|
228
|
+
* - `-abc value` → consumes only when the trailing short flag is a value-flag;
|
|
229
|
+
* an earlier value-flag char takes the rest of the group as an inline value.
|
|
230
|
+
*
|
|
231
|
+
* Unknown flags conservatively consume nothing (the parser reports them later).
|
|
232
|
+
*
|
|
233
|
+
* @internal
|
|
234
|
+
*/
|
|
235
|
+
function consumesFollowingToken(token: string, valueFlags: ValueFlagLookup): boolean {
|
|
236
|
+
if (token.startsWith('--')) {
|
|
237
|
+
if (token.includes('=')) return false;
|
|
238
|
+
const entry = valueFlags.get(token.slice(2));
|
|
239
|
+
return entry !== undefined && flagExpectsValue(entry[1]);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Short flag group (`-abc`). A value attaches to the trailing flag only; an
|
|
243
|
+
// earlier value-flag char swallows the remaining chars as an inline value.
|
|
244
|
+
const chars = token.slice(1);
|
|
245
|
+
for (let i = 0; i < chars.length; i++) {
|
|
246
|
+
const entry = valueFlags.get(chars.charAt(i));
|
|
247
|
+
if (entry === undefined) return false;
|
|
248
|
+
if (!flagExpectsValue(entry[1])) continue;
|
|
249
|
+
return i === chars.length - 1;
|
|
250
|
+
}
|
|
251
|
+
return false;
|
|
252
|
+
}
|
|
253
|
+
|
|
191
254
|
// --- "Did you mean?" suggestion
|
|
192
255
|
|
|
193
256
|
/**
|
|
@@ -282,5 +345,5 @@ function uniqueCommands(commands: ReadonlyMap<string, ErasedCommand>): readonly
|
|
|
282
345
|
|
|
283
346
|
// --- Exports
|
|
284
347
|
|
|
285
|
-
export type { DispatchMatch, DispatchNeedsSubcommand, DispatchResult, DispatchUnknown };
|
|
286
|
-
export { dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
348
|
+
export type { DispatchMatch, DispatchNeedsSubcommand, DispatchResult, DispatchUnknown, ValueFlagLookup };
|
|
349
|
+
export { consumesFollowingToken, dispatch, findClosestCommand, levenshtein, uniqueCommands };
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Root-help header hyperlink resolution.
|
|
3
|
+
*
|
|
4
|
+
* Stores explicit `.links()` URLs and derives missing ones from package.json
|
|
5
|
+
* metadata (`repository` / `homepage`) once that data is available — during
|
|
6
|
+
* runtime preflight for `.run()`, or directly from pre-loaded
|
|
7
|
+
* `.packageJson(data)` for `.execute()`.
|
|
8
|
+
*
|
|
9
|
+
* @module dreamcli/core/cli/help-links
|
|
10
|
+
* @internal
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { PackageJsonData } from '#internals/core/config/package-json.ts';
|
|
14
|
+
import { packageRepositoryUrl } from '#internals/core/config/package-json.ts';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* OSC 8 hyperlink targets for the root-help header.
|
|
18
|
+
*
|
|
19
|
+
* Set via `CLIBuilder.links()`; fields left `undefined` are derived from
|
|
20
|
+
* package.json metadata when `.packageJson()` is active.
|
|
21
|
+
*/
|
|
22
|
+
interface HelpLinks {
|
|
23
|
+
/** URL the program name links to (e.g. the repository or homepage). */
|
|
24
|
+
readonly name: string | undefined;
|
|
25
|
+
/** URL the version links to (e.g. the release tag). */
|
|
26
|
+
readonly version: string | undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Build the release-tag URL for a version on a known forge.
|
|
31
|
+
*
|
|
32
|
+
* GitHub and GitLab have stable release-tag routes; other hosts return
|
|
33
|
+
* `undefined` rather than guessing.
|
|
34
|
+
*
|
|
35
|
+
* @internal
|
|
36
|
+
*/
|
|
37
|
+
function releaseTagUrl(repoUrl: string, version: string): string | undefined {
|
|
38
|
+
let hostname: string;
|
|
39
|
+
try {
|
|
40
|
+
hostname = new URL(repoUrl).hostname;
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
if (hostname === 'github.com') return `${repoUrl}/releases/tag/v${version}`;
|
|
45
|
+
if (hostname === 'gitlab.com') return `${repoUrl}/-/releases/v${version}`;
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Fill `undefined` link fields from package.json metadata.
|
|
51
|
+
*
|
|
52
|
+
* Explicit URLs always win. The name falls back to the normalized
|
|
53
|
+
* `repository` URL, then `homepage`; the version falls back to the forge
|
|
54
|
+
* release-tag URL when both a repository and a version are known.
|
|
55
|
+
* Idempotent — already-resolved fields pass through unchanged.
|
|
56
|
+
*
|
|
57
|
+
* @internal
|
|
58
|
+
*/
|
|
59
|
+
function deriveHelpLinks(
|
|
60
|
+
links: HelpLinks | undefined,
|
|
61
|
+
pkg: PackageJsonData | undefined,
|
|
62
|
+
version: string | undefined,
|
|
63
|
+
): HelpLinks | undefined {
|
|
64
|
+
if (links === undefined) return undefined;
|
|
65
|
+
if (pkg === undefined || (links.name !== undefined && links.version !== undefined)) {
|
|
66
|
+
return links;
|
|
67
|
+
}
|
|
68
|
+
const repoUrl = packageRepositoryUrl(pkg);
|
|
69
|
+
return {
|
|
70
|
+
name: links.name ?? repoUrl ?? pkg.homepage,
|
|
71
|
+
version:
|
|
72
|
+
links.version ??
|
|
73
|
+
(repoUrl !== undefined && version !== undefined
|
|
74
|
+
? releaseTagUrl(repoUrl, version)
|
|
75
|
+
: undefined),
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// --- Exports
|
|
80
|
+
|
|
81
|
+
export type { HelpLinks };
|
|
82
|
+
export { deriveHelpLinks };
|
package/src/core/cli/index.ts
CHANGED
|
@@ -19,6 +19,7 @@ import type { HelpOptions } from '#internals/core/help/index.ts';
|
|
|
19
19
|
import { formatHelp } from '#internals/core/help/index.ts';
|
|
20
20
|
import type { CapturedOutput } from '#internals/core/output/index.ts';
|
|
21
21
|
import { createCaptureOutput, createOutput } from '#internals/core/output/index.ts';
|
|
22
|
+
import { includesBeforeSeparator } from '#internals/core/parse/index.ts';
|
|
22
23
|
import type { ArgBuilder, ArgConfig } from '#internals/core/schema/arg.ts';
|
|
23
24
|
import { arg } from '#internals/core/schema/arg.ts';
|
|
24
25
|
import type {
|
|
@@ -35,6 +36,8 @@ import type { RunOptions, RunResult } from '#internals/core/schema/run.ts';
|
|
|
35
36
|
import { runCommand } from '#internals/core/testkit/index.ts';
|
|
36
37
|
import type { RuntimeAdapter } from '#internals/runtime/adapter.ts';
|
|
37
38
|
import { createAdapter } from '#internals/runtime/auto.ts';
|
|
39
|
+
import type { HelpLinks } from './help-links.ts';
|
|
40
|
+
import { deriveHelpLinks } from './help-links.ts';
|
|
38
41
|
import type { OutputPolicy } from './planner.ts';
|
|
39
42
|
import { planInvocation } from './planner.ts';
|
|
40
43
|
import type { CLIPlugin } from './plugin.ts';
|
|
@@ -185,6 +188,14 @@ interface CLISchema {
|
|
|
185
188
|
* Set via the {@linkcode CLIBuilder.packageJson | .packageJson()} builder method.
|
|
186
189
|
*/
|
|
187
190
|
readonly packageJsonSettings: PackageJsonSettings | undefined;
|
|
191
|
+
/**
|
|
192
|
+
* OSC 8 hyperlink targets for the root-help header (name/version).
|
|
193
|
+
*
|
|
194
|
+
* Set via the {@linkcode CLIBuilder.links | .links()} builder method.
|
|
195
|
+
* Fields left `undefined` are derived from package.json metadata
|
|
196
|
+
* (`repository` / `homepage`) when `.packageJson()` is active.
|
|
197
|
+
*/
|
|
198
|
+
readonly helpLinks: HelpLinks | undefined;
|
|
188
199
|
/** Whether built-in `.completions()` command registration is active. */
|
|
189
200
|
readonly hasBuiltInCompletions: boolean;
|
|
190
201
|
/** Registered CLI plugins. */
|
|
@@ -364,6 +375,54 @@ class CLIBuilder {
|
|
|
364
375
|
return new CLIBuilder({ ...this.schema, description: text });
|
|
365
376
|
}
|
|
366
377
|
|
|
378
|
+
/**
|
|
379
|
+
* Make the root-help header clickable with OSC 8 hyperlinks.
|
|
380
|
+
*
|
|
381
|
+
* Links the program name and version on the first line of root `--help`
|
|
382
|
+
* output in terminals that support
|
|
383
|
+
* [OSC 8 hyperlinks](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda).
|
|
384
|
+
* The escapes are only emitted when stdout is a TTY (overridable via
|
|
385
|
+
* `options.help.hyperlinks`), and only in the header — usage lines, the
|
|
386
|
+
* `--help` hint, the commands table, and completion scripts stay plain.
|
|
387
|
+
*
|
|
388
|
+
* URLs not provided here are derived from package.json metadata when
|
|
389
|
+
* `.packageJson()` is active (works with both filesystem discovery and
|
|
390
|
+
* pre-loaded data):
|
|
391
|
+
* - **name** → normalized `repository` URL, falling back to `homepage`
|
|
392
|
+
* - **version** → forge release tag (`{repo}/releases/tag/v{version}` on
|
|
393
|
+
* GitHub, `{repo}/-/releases/v{version}` on GitLab)
|
|
394
|
+
*
|
|
395
|
+
* @param links - Explicit URLs; omit to derive everything from package.json.
|
|
396
|
+
* @returns The builder (for chaining).
|
|
397
|
+
*
|
|
398
|
+
* @example
|
|
399
|
+
* ```ts
|
|
400
|
+
* // Derive both links from package.json repository/homepage:
|
|
401
|
+
* cli('mycli')
|
|
402
|
+
* .packageJson()
|
|
403
|
+
* .links()
|
|
404
|
+
* .run();
|
|
405
|
+
*
|
|
406
|
+
* // Explicit URLs (no package.json required):
|
|
407
|
+
* cli('mycli')
|
|
408
|
+
* .version('1.0.0')
|
|
409
|
+
* .links({
|
|
410
|
+
* name: 'https://github.com/me/mycli',
|
|
411
|
+
* version: 'https://github.com/me/mycli/releases/tag/v1.0.0',
|
|
412
|
+
* })
|
|
413
|
+
* .run();
|
|
414
|
+
* ```
|
|
415
|
+
*/
|
|
416
|
+
links(links?: { readonly name?: string | URL; readonly version?: string | URL }): CLIBuilder {
|
|
417
|
+
return new CLIBuilder({
|
|
418
|
+
...this.schema,
|
|
419
|
+
helpLinks: {
|
|
420
|
+
name: toUrlString(links?.name),
|
|
421
|
+
version: toUrlString(links?.version),
|
|
422
|
+
},
|
|
423
|
+
});
|
|
424
|
+
}
|
|
425
|
+
|
|
367
426
|
/**
|
|
368
427
|
* Enable automatic config file discovery.
|
|
369
428
|
*
|
|
@@ -747,7 +806,9 @@ class CLIBuilder {
|
|
|
747
806
|
*/
|
|
748
807
|
async execute(argv: readonly string[], options?: CLIRunOptions): Promise<RunResult> {
|
|
749
808
|
// -- Detect global --json mode before building output ---------------------
|
|
750
|
-
|
|
809
|
+
// Only a `--json` before the `--` separator toggles JSON mode; a literal
|
|
810
|
+
// `--json` positional (after `--`) must reach the command unchanged (#28).
|
|
811
|
+
const hasJsonFlag = includesBeforeSeparator(argv, '--json');
|
|
751
812
|
const jsonMode = hasJsonFlag || options?.jsonMode === true;
|
|
752
813
|
|
|
753
814
|
const captureOptions = {
|
|
@@ -766,10 +827,12 @@ class CLIBuilder {
|
|
|
766
827
|
);
|
|
767
828
|
}
|
|
768
829
|
|
|
769
|
-
// Resolve help options — default binName to CLI program name
|
|
830
|
+
// Resolve help options — default binName to CLI program name,
|
|
831
|
+
// hyperlinks to TTY detection (escapes never leak into piped output)
|
|
770
832
|
const helpOptions: HelpOptions = {
|
|
771
833
|
...options?.help,
|
|
772
834
|
binName: options?.help?.binName ?? this.schema.name,
|
|
835
|
+
hyperlinks: options?.help?.hyperlinks ?? out.isTTY,
|
|
773
836
|
};
|
|
774
837
|
|
|
775
838
|
// -- Shared options for command execution ----------------------------------
|
|
@@ -796,7 +859,7 @@ class CLIBuilder {
|
|
|
796
859
|
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
797
860
|
|
|
798
861
|
case 'root-help': {
|
|
799
|
-
const helpText = formatRootHelp(this.schema, planned.help);
|
|
862
|
+
const helpText = formatRootHelp(resolveHelpLinksSchema(this.schema), planned.help);
|
|
800
863
|
out.log(helpText);
|
|
801
864
|
return buildRunResult({ exitCode: 0, error: undefined }, captured);
|
|
802
865
|
}
|
|
@@ -974,6 +1037,32 @@ function inferInvocationName(argv: readonly string[]): string | undefined {
|
|
|
974
1037
|
return argv0 !== undefined ? basename(argv0) : undefined;
|
|
975
1038
|
}
|
|
976
1039
|
|
|
1040
|
+
// --- Help link helpers
|
|
1041
|
+
|
|
1042
|
+
/** Coerce a `string | URL` link input to its string form. @internal */
|
|
1043
|
+
function toUrlString(value: string | URL | undefined): string | undefined {
|
|
1044
|
+
if (value === undefined) return undefined;
|
|
1045
|
+
return value instanceof URL ? value.href : value;
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
/**
|
|
1049
|
+
* Resolve derived help links against pre-loaded package.json data.
|
|
1050
|
+
*
|
|
1051
|
+
* `.run()` resolves links during runtime preflight (where discovered
|
|
1052
|
+
* package.json metadata lives); this covers the filesystem-free
|
|
1053
|
+
* `.execute()` path, where only the `.packageJson(data)` overload can
|
|
1054
|
+
* contribute. Idempotent — already-resolved fields pass through unchanged.
|
|
1055
|
+
*
|
|
1056
|
+
* @internal
|
|
1057
|
+
*/
|
|
1058
|
+
function resolveHelpLinksSchema(schema: CLISchema): CLISchema {
|
|
1059
|
+
if (schema.helpLinks === undefined) return schema;
|
|
1060
|
+
return {
|
|
1061
|
+
...schema,
|
|
1062
|
+
helpLinks: deriveHelpLinks(schema.helpLinks, schema.packageJsonSettings?.data, schema.version),
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
|
|
977
1066
|
// --- packageJson.from normalisation
|
|
978
1067
|
|
|
979
1068
|
/**
|
|
@@ -1016,14 +1105,21 @@ function normalizeFromSetting(from: string | URL | undefined): string | undefine
|
|
|
1016
1105
|
*
|
|
1017
1106
|
* A value is treated as `PackageJsonData` when it's a plain object that
|
|
1018
1107
|
* carries at least one recognised field (`name`, `version`, `description`,
|
|
1019
|
-
* or `
|
|
1020
|
-
* `from`) falls through to the settings overload.
|
|
1108
|
+
* `bin`, `homepage`, or `repository`). An empty `{}` or a settings-shaped
|
|
1109
|
+
* object (`inferName` / `from`) falls through to the settings overload.
|
|
1021
1110
|
*
|
|
1022
1111
|
* @internal
|
|
1023
1112
|
*/
|
|
1024
1113
|
function isPackageJsonData(value: unknown): value is PackageJsonData {
|
|
1025
1114
|
if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;
|
|
1026
|
-
return
|
|
1115
|
+
return (
|
|
1116
|
+
'name' in value ||
|
|
1117
|
+
'version' in value ||
|
|
1118
|
+
'description' in value ||
|
|
1119
|
+
'bin' in value ||
|
|
1120
|
+
'homepage' in value ||
|
|
1121
|
+
'repository' in value
|
|
1122
|
+
);
|
|
1027
1123
|
}
|
|
1028
1124
|
|
|
1029
1125
|
// --- Factory function
|
|
@@ -1093,6 +1189,7 @@ function cli(nameOrOptions: string | CLIOptions): CLIBuilder {
|
|
|
1093
1189
|
defaultCommand: undefined,
|
|
1094
1190
|
configSettings: undefined,
|
|
1095
1191
|
packageJsonSettings: undefined,
|
|
1192
|
+
helpLinks: undefined,
|
|
1096
1193
|
hasBuiltInCompletions: false,
|
|
1097
1194
|
plugins: [],
|
|
1098
1195
|
});
|
|
@@ -1107,5 +1204,6 @@ export type {
|
|
|
1107
1204
|
PluginCommandContext,
|
|
1108
1205
|
ResolvedCommandParams,
|
|
1109
1206
|
} from './plugin.ts';
|
|
1207
|
+
export type { HelpLinks } from './help-links.ts';
|
|
1110
1208
|
export type { CLIOptions, CLIRunOptions, CLISchema, ConfigSettings, PackageJsonSettings };
|
|
1111
1209
|
export { CLIBuilder, cli, formatRootHelp, plugin };
|