@hop-top/kit 0.5.0-alpha.7 → 0.5.0-alpha.8

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 CHANGED
@@ -4,6 +4,22 @@ All notable changes to `@hop-top/kit` are documented in this file.
4
4
  Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/);
5
5
  versions follow [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
+ ## [0.5.0-alpha.8](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.7...kit-ts/v0.5.0-alpha.8) (2026-10-29)
8
+
9
+ The hop-top team is happy to announce Kit's TS SDK 0.5.0-alpha.8. This release includes new features and bug fixes.
10
+
11
+
12
+ ### Features
13
+
14
+ * **ts/alias:** bridgeAliases options, validateAliasName, detectCycles ([a7c279f](https://github.com/hop-top/poly-kit/commit/a7c279f3abc08ac97dc1f69ce750e0a0e12c88fc))
15
+
16
+
17
+ ### Bug Fixes
18
+
19
+ * **ts/alias:** skip root-alias completion for real-command proxies ([0dc2251](https://github.com/hop-top/poly-kit/commit/0dc225176ed2a1a94fdb8beb4063b56da23ce05c))
20
+
21
+ Full diff: [kit-ts/v0.5.0-alpha.7...kit-ts/v0.5.0-alpha.8](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.7...kit-ts/v0.5.0-alpha.8)
22
+
7
23
  ## [0.5.0-alpha.7](https://github.com/hop-top/poly-kit/compare/kit-ts/v0.5.0-alpha.6...kit-ts/v0.5.0-alpha.7) (2026-10-29)
8
24
 
9
25
  The hop-top team is happy to announce Kit's TS SDK 0.5.0-alpha.7. This release includes new features and bug fixes.
@@ -0,0 +1,174 @@
1
+ import { Command } from 'commander';
2
+
3
+ /**
4
+ * alias.ts — YAML-file-based command alias expansion.
5
+ *
6
+ * Port of Go's cli/alias package. Aliases live in per-tool YAML
7
+ * config files with three-tier priority: seeded < global < local.
8
+ */
9
+
10
+ type AliasMap = Record<string, string>;
11
+ interface ExpanderConfig {
12
+ globalPath: string;
13
+ localPath: string;
14
+ seededAliases?: AliasMap;
15
+ builtins?: Set<string>;
16
+ }
17
+ /** Read aliases from a single YAML config file. */
18
+ declare function loadFrom(filePath: string): AliasMap;
19
+ /** Write aliases into a YAML config file, preserving other keys. */
20
+ declare function saveTo(filePath: string, aliases: AliasMap): void;
21
+ /**
22
+ * Find the first non-flag element in a slice.
23
+ * Returns [index, value]. Flags with `=` are self-contained;
24
+ * short flags without `=` consume the next element as their value.
25
+ */
26
+ declare function findFirstNonFlag(slice: string[]): [number, string];
27
+ /**
28
+ * Simple single-file alias store with load/save, set/get/remove,
29
+ * and first-arg expansion.
30
+ */
31
+ declare class AliasStore {
32
+ private filePath;
33
+ private aliases;
34
+ constructor(filePath: string);
35
+ load(): void;
36
+ save(): void;
37
+ set(name: string, target: string): void;
38
+ remove(name: string): void;
39
+ get(name: string): string | undefined;
40
+ /** Returns a shallow copy. */
41
+ all(): AliasMap;
42
+ /** Expand first arg if it matches an alias. */
43
+ expand(args: string[]): string[];
44
+ }
45
+ /**
46
+ * Three-tier alias expander matching Go's Expander.
47
+ * Priority: seeded < global < local.
48
+ */
49
+ declare class Expander {
50
+ private cfg;
51
+ constructor(cfg: ExpanderConfig);
52
+ /** Merged alias map (seeded < global < local). */
53
+ load(): AliasMap;
54
+ /**
55
+ * Rewrite args if args[1] (or first non-flag arg) matches
56
+ * an alias. Returns [rewrittenArgs, wasExpanded].
57
+ */
58
+ expand(args: string[]): [string[], boolean];
59
+ /**
60
+ * Reject names that shadow builtins or contain whitespace; see
61
+ * {@link validateAliasName}, which needs no config files.
62
+ */
63
+ validateName(name: string): void;
64
+ }
65
+ /** The rule an alias name failed; see {@link validateAliasName}. */
66
+ type AliasNameErrorKind = 'empty' | 'whitespace' | 'builtin' | 'duplicate';
67
+ /** An alias name {@link validateAliasName} refused. */
68
+ declare class AliasNameError extends Error {
69
+ readonly kind: AliasNameErrorKind;
70
+ readonly alias: string;
71
+ /** The existing alias's target, for `duplicate`. */
72
+ readonly target?: string;
73
+ constructor(kind: AliasNameErrorKind, alias: string, target?: string);
74
+ }
75
+ /** What {@link validateAliasName} checks a name against. */
76
+ interface AliasNameRules {
77
+ /** Names an alias must not take: the tool's commands and reserved words. */
78
+ builtins?: Iterable<string>;
79
+ /** The alias map the name would join. */
80
+ existing?: AliasMap;
81
+ }
82
+ /**
83
+ * Check an alias name without a store, config file or command tree.
84
+ * Rules run in order and the first failure throws an
85
+ * {@link AliasNameError}: empty, whitespace (any Unicode White_Space
86
+ * character), builtin, duplicate.
87
+ */
88
+ declare function validateAliasName(name: string, rules?: AliasNameRules): void;
89
+ /**
90
+ * Report alias cycles in `aliases` (name -> target). An alias points at
91
+ * another when the first word of its target is a key of the map. Each
92
+ * cycle is a path starting at its smallest name and ending with it
93
+ * again (`['a', 'b', 'a']`); cycles are sorted by first name. An alias
94
+ * that only leads into a cycle is not part of one.
95
+ */
96
+ declare function detectCycles(aliases: AliasMap): string[][];
97
+ /** Walk the Commander program tree to find a command by space-delimited path. */
98
+ declare function findCommand(program: Command, cmdPath: string): Command | undefined;
99
+ /** Runs an alias proxy in place of its target; `cmd.args` holds every argument after the alias, unparsed. */
100
+ type AliasDispatch = (name: string, target: string, cmd: Command) => void | Promise<void>;
101
+ /**
102
+ * Options for {@link bridgeAliases}. Setting any of them registers every
103
+ * alias as a proxy, a root command named after the alias, even for a
104
+ * single-word target that would otherwise take a Commander alias.
105
+ */
106
+ interface BridgeOptions {
107
+ /** Hide proxies from help. Default true. */
108
+ hidden?: boolean;
109
+ /** A proxy's description, in place of `Alias for <target>`. */
110
+ describe?: (name: string, target: string) => string;
111
+ /**
112
+ * true: the proxy owns -h/--help and shows its own help. false (the
113
+ * default): --help reaches the target, or the dispatch handler.
114
+ */
115
+ helpOption?: boolean;
116
+ /**
117
+ * A handler run instead of the target, or false to register proxies
118
+ * that run nothing (register-only). Default: dispatch the target
119
+ * through the program, like a native subcommand.
120
+ */
121
+ dispatch?: AliasDispatch | false;
122
+ }
123
+ /**
124
+ * Register loaded aliases with Commander's native .alias() API.
125
+ *
126
+ * Simple single-command aliases use Commander's built-in .alias(),
127
+ * giving free completion and help display. Multi-word or unresolved
128
+ * targets get a hidden proxy command that dispatches the expanded
129
+ * args from the program, like a native subcommand. With any
130
+ * {@link BridgeOptions} set, every alias gets a proxy shaped by them.
131
+ *
132
+ * Completion offers each alias at most once. A native alias, or a hidden
133
+ * proxy that dispatches its target or runs nothing, is a stand-in:
134
+ * completion lists it as `alias for <target>` and offers a proxy only
135
+ * its help flag. A visible proxy, or one with a dispatch handler, is a
136
+ * real command and completes like any subcommand, with its own flags,
137
+ * including any added after bridging; a hidden one is not listed.
138
+ *
139
+ * `source` is an {@link AliasStore} or a plain alias map, so aliases
140
+ * can come from any storage.
141
+ *
142
+ * Dispatch reuses Commander's own subcommand dispatch rather than
143
+ * calling parse()/parseAsync() again: re-parsing resets program
144
+ * option values mid-parse and fixes the sync/async mode, whereas
145
+ * dispatch returns the target's result as-is. parseAsync() callers
146
+ * thus await async targets (rejections propagate), and parse()
147
+ * callers keep synchronous throws.
148
+ */
149
+ declare function bridgeAliases(program: Command, source: AliasStore | AliasMap, opts?: BridgeOptions): void;
150
+
151
+ type alias_AliasDispatch = AliasDispatch;
152
+ type alias_AliasMap = AliasMap;
153
+ type alias_AliasNameError = AliasNameError;
154
+ declare const alias_AliasNameError: typeof AliasNameError;
155
+ type alias_AliasNameErrorKind = AliasNameErrorKind;
156
+ type alias_AliasNameRules = AliasNameRules;
157
+ type alias_AliasStore = AliasStore;
158
+ declare const alias_AliasStore: typeof AliasStore;
159
+ type alias_BridgeOptions = BridgeOptions;
160
+ type alias_Expander = Expander;
161
+ declare const alias_Expander: typeof Expander;
162
+ type alias_ExpanderConfig = ExpanderConfig;
163
+ declare const alias_bridgeAliases: typeof bridgeAliases;
164
+ declare const alias_detectCycles: typeof detectCycles;
165
+ declare const alias_findCommand: typeof findCommand;
166
+ declare const alias_findFirstNonFlag: typeof findFirstNonFlag;
167
+ declare const alias_loadFrom: typeof loadFrom;
168
+ declare const alias_saveTo: typeof saveTo;
169
+ declare const alias_validateAliasName: typeof validateAliasName;
170
+ declare namespace alias {
171
+ export { type alias_AliasDispatch as AliasDispatch, type alias_AliasMap as AliasMap, alias_AliasNameError as AliasNameError, type alias_AliasNameErrorKind as AliasNameErrorKind, type alias_AliasNameRules as AliasNameRules, alias_AliasStore as AliasStore, type alias_BridgeOptions as BridgeOptions, alias_Expander as Expander, type alias_ExpanderConfig as ExpanderConfig, alias_bridgeAliases as bridgeAliases, alias_detectCycles as detectCycles, alias_findCommand as findCommand, alias_findFirstNonFlag as findFirstNonFlag, alias_loadFrom as loadFrom, alias_saveTo as saveTo, alias_validateAliasName as validateAliasName };
172
+ }
173
+
174
+ export { type AliasDispatch as A, type BridgeOptions as B, Expander as E, alias as a, type AliasMap as b, AliasNameError as c, type AliasNameErrorKind as d, type AliasNameRules as e, AliasStore as f, type ExpanderConfig as g, bridgeAliases as h, detectCycles as i, findCommand as j, findFirstNonFlag as k, loadFrom as l, saveTo as s, validateAliasName as v };
package/dist/alias.d.ts CHANGED
@@ -1,2 +1,2 @@
1
1
  import 'commander';
2
- export { A as AliasMap, b as AliasStore, E as Expander, c as ExpanderConfig, d as bridgeAliases, f as findCommand, e as findFirstNonFlag, l as loadFrom, s as saveTo } from './alias-BsJ2jGqQ.js';
2
+ export { A as AliasDispatch, b as AliasMap, c as AliasNameError, d as AliasNameErrorKind, e as AliasNameRules, f as AliasStore, B as BridgeOptions, E as Expander, g as ExpanderConfig, h as bridgeAliases, i as detectCycles, j as findCommand, k as findFirstNonFlag, l as loadFrom, s as saveTo, v as validateAliasName } from './alias-D9_qFlyP.js';
package/dist/alias.js CHANGED
@@ -6,7 +6,10 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkDIDN4X5Cjs = require('./chunk-DIDN4X5C.js');
9
+
10
+
11
+
12
+ var _chunkBLS2OBIQjs = require('./chunk-BLS2OBIQ.js');
10
13
  require('./chunk-JZ22ZUFA.js');
11
14
  require('./chunk-JKMQSAJP.js');
12
15
  require('./chunk-R5U7XKVJ.js');
@@ -18,4 +21,7 @@ require('./chunk-R5U7XKVJ.js');
18
21
 
19
22
 
20
23
 
21
- exports.AliasStore = _chunkDIDN4X5Cjs.AliasStore; exports.Expander = _chunkDIDN4X5Cjs.Expander; exports.bridgeAliases = _chunkDIDN4X5Cjs.bridgeAliases; exports.findCommand = _chunkDIDN4X5Cjs.findCommand; exports.findFirstNonFlag = _chunkDIDN4X5Cjs.findFirstNonFlag; exports.loadFrom = _chunkDIDN4X5Cjs.loadFrom; exports.saveTo = _chunkDIDN4X5Cjs.saveTo;
24
+
25
+
26
+
27
+ exports.AliasNameError = _chunkBLS2OBIQjs.AliasNameError; exports.AliasStore = _chunkBLS2OBIQjs.AliasStore; exports.Expander = _chunkBLS2OBIQjs.Expander; exports.bridgeAliases = _chunkBLS2OBIQjs.bridgeAliases; exports.detectCycles = _chunkBLS2OBIQjs.detectCycles; exports.findCommand = _chunkBLS2OBIQjs.findCommand; exports.findFirstNonFlag = _chunkBLS2OBIQjs.findFirstNonFlag; exports.loadFrom = _chunkBLS2OBIQjs.loadFrom; exports.saveTo = _chunkBLS2OBIQjs.saveTo; exports.validateAliasName = _chunkBLS2OBIQjs.validateAliasName;
@@ -8,13 +8,16 @@ var _chunkR5U7XKVJjs = require('./chunk-R5U7XKVJ.js');
8
8
  // src/alias.ts
9
9
  var alias_exports = {};
10
10
  _chunkR5U7XKVJjs.__export.call(void 0, alias_exports, {
11
+ AliasNameError: () => AliasNameError,
11
12
  AliasStore: () => AliasStore,
12
13
  Expander: () => Expander,
13
14
  bridgeAliases: () => bridgeAliases,
15
+ detectCycles: () => detectCycles,
14
16
  findCommand: () => findCommand,
15
17
  findFirstNonFlag: () => findFirstNonFlag,
16
18
  loadFrom: () => loadFrom,
17
- saveTo: () => saveTo
19
+ saveTo: () => saveTo,
20
+ validateAliasName: () => validateAliasName
18
21
  });
19
22
  var _fs = require('fs'); var fs = _interopRequireWildcard(_fs);
20
23
  var _path = require('path'); var path = _interopRequireWildcard(_path);
@@ -125,50 +128,123 @@ var Expander = class {
125
128
  const result = [args[0], ...prefix, ...parts, ...suffix];
126
129
  return [result, true];
127
130
  }
128
- /** Reject names that shadow builtins or contain whitespace. */
131
+ /**
132
+ * Reject names that shadow builtins or contain whitespace; see
133
+ * {@link validateAliasName}, which needs no config files.
134
+ */
129
135
  validateName(name) {
130
- if (name === "") {
131
- throw new Error("alias name must not be empty");
132
- }
133
- if (/\s/.test(name)) {
134
- throw new Error("alias name must not contain whitespace");
136
+ validateAliasName(name, { builtins: this.cfg.builtins });
137
+ }
138
+ };
139
+ var AliasNameError = class extends Error {
140
+ constructor(kind, alias, target) {
141
+ super(aliasNameMessage(kind, alias, target));
142
+ this.name = "AliasNameError";
143
+ this.kind = kind;
144
+ this.alias = alias;
145
+ this.target = target;
146
+ }
147
+ };
148
+ function aliasNameMessage(kind, alias, target) {
149
+ switch (kind) {
150
+ case "empty":
151
+ return "alias name must not be empty";
152
+ case "whitespace":
153
+ return "alias name must not contain whitespace";
154
+ case "builtin":
155
+ return `alias "${alias}" conflicts with a built-in command`;
156
+ case "duplicate":
157
+ return `alias "${alias}" is already registered for "${_nullishCoalesce(target, () => ( ""))}"`;
158
+ }
159
+ }
160
+ var WHITE_SPACE = /\p{White_Space}/u;
161
+ function validateAliasName(name, rules = {}) {
162
+ if (name === "") throw new AliasNameError("empty", name);
163
+ if (WHITE_SPACE.test(name)) throw new AliasNameError("whitespace", name);
164
+ if (rules.builtins) {
165
+ for (const b of rules.builtins) {
166
+ if (b === name) throw new AliasNameError("builtin", name);
135
167
  }
136
- if (_optionalChain([this, 'access', _ => _.cfg, 'access', _2 => _2.builtins, 'optionalAccess', _3 => _3.has, 'call', _4 => _4(name)])) {
137
- throw new Error(`alias "${name}" conflicts with a built-in command`);
168
+ }
169
+ const existing = rules.existing;
170
+ if (existing && Object.prototype.hasOwnProperty.call(existing, name)) {
171
+ throw new AliasNameError("duplicate", name, existing[name]);
172
+ }
173
+ }
174
+ function detectCycles(aliases) {
175
+ const has = (n) => Object.prototype.hasOwnProperty.call(aliases, n);
176
+ const next = (n) => {
177
+ const first = aliases[n].trim().split(/\s+/)[0];
178
+ return first !== "" && has(first) ? first : void 0;
179
+ };
180
+ const cmp = (a, b) => a < b ? -1 : a > b ? 1 : 0;
181
+ const done = /* @__PURE__ */ new Set();
182
+ const cycles = [];
183
+ for (const start of Object.keys(aliases).sort(cmp)) {
184
+ if (done.has(start)) continue;
185
+ const pos = /* @__PURE__ */ new Map();
186
+ const walk = [];
187
+ let cur = start;
188
+ while (cur !== void 0 && !done.has(cur)) {
189
+ const at = pos.get(cur);
190
+ if (at !== void 0) {
191
+ const members = walk.slice(at);
192
+ let min = 0;
193
+ members.forEach((m, i) => {
194
+ if (m < members[min]) min = i;
195
+ });
196
+ const path2 = [...members.slice(min), ...members.slice(0, min)];
197
+ cycles.push([...path2, path2[0]]);
198
+ break;
199
+ }
200
+ pos.set(cur, walk.length);
201
+ walk.push(cur);
202
+ cur = next(cur);
138
203
  }
204
+ for (const n of walk) done.add(n);
139
205
  }
140
- };
206
+ return cycles.sort((a, b) => cmp(a[0], b[0]));
207
+ }
141
208
  function findCommand(program, cmdPath) {
142
209
  const parts = cmdPath.split(" ");
143
210
  let cmd = program;
144
211
  for (const part of parts) {
145
- cmd = _optionalChain([cmd, 'optionalAccess', _5 => _5.commands, 'access', _6 => _6.find, 'call', _7 => _7((c) => c.name() === part)]);
212
+ cmd = _optionalChain([cmd, 'optionalAccess', _ => _.commands, 'access', _2 => _2.find, 'call', _3 => _3((c) => c.name() === part)]);
146
213
  if (!cmd) return void 0;
147
214
  }
148
215
  return cmd;
149
216
  }
150
- function bridgeAliases(program, store) {
151
- const all = store.all();
217
+ function hasBridgeOptions(opts) {
218
+ return opts !== void 0 && Object.values(opts).some((v) => v !== void 0);
219
+ }
220
+ function bridgeAliases(program, source, opts) {
221
+ const all = typeof source.all === "function" ? source.all() : { ...source };
222
+ const proxyAll = hasBridgeOptions(opts);
223
+ const realProxy = proxyAll && (opts.hidden === false || typeof opts.dispatch === "function");
152
224
  for (const [name, target] of Object.entries(all)) {
153
- _chunkJZ22ZUFAjs.registerRootAlias.call(void 0, program, name, target);
225
+ if (!realProxy) _chunkJZ22ZUFAjs.registerRootAlias.call(void 0, program, name, target);
154
226
  const parts = target.split(/\s+/);
155
- if (parts.length === 1) {
227
+ if (!proxyAll && parts.length === 1) {
156
228
  const targetCmd = findCommand(program, target);
157
229
  if (targetCmd) {
158
230
  targetCmd.alias(name);
159
231
  continue;
160
232
  }
161
233
  }
162
- const proxy = new (0, _commander.Command)(name).description(`Alias for ${target}`).allowUnknownOption(true).allowExcessArguments(true).action(function() {
234
+ const dispatch = _optionalChain([opts, 'optionalAccess', _4 => _4.dispatch]);
235
+ const proxy = new (0, _commander.Command)(name);
236
+ if (proxyAll) proxy.copyInheritedSettings(program);
237
+ proxy.description(_nullishCoalesce(_optionalChain([opts, 'optionalAccess', _5 => _5.describe, 'optionalCall', _6 => _6(name, target)]), () => ( `Alias for ${target}`))).allowUnknownOption(true).allowExcessArguments(true).action(function() {
238
+ if (dispatch === false) return void 0;
239
+ if (dispatch) return dispatch(name, target, this);
163
240
  const expanded = target.split(/\s+/);
164
241
  return program._parseCommand(
165
242
  [],
166
243
  [...expanded, ...this.args]
167
244
  );
168
245
  });
169
- proxy.helpOption(false);
170
- proxy._hidden = true;
171
- program.addCommand(proxy);
246
+ if (_optionalChain([opts, 'optionalAccess', _7 => _7.helpOption]) !== true) proxy.helpOption(false);
247
+ program.addCommand(proxy, { hidden: _nullishCoalesce(_optionalChain([opts, 'optionalAccess', _8 => _8.hidden]), () => ( true)) });
172
248
  }
173
249
  }
174
250
 
@@ -181,4 +257,7 @@ function bridgeAliases(program, store) {
181
257
 
182
258
 
183
259
 
184
- exports.loadFrom = loadFrom; exports.saveTo = saveTo; exports.findFirstNonFlag = findFirstNonFlag; exports.AliasStore = AliasStore; exports.Expander = Expander; exports.findCommand = findCommand; exports.bridgeAliases = bridgeAliases; exports.alias_exports = alias_exports;
260
+
261
+
262
+
263
+ exports.loadFrom = loadFrom; exports.saveTo = saveTo; exports.findFirstNonFlag = findFirstNonFlag; exports.AliasStore = AliasStore; exports.Expander = Expander; exports.AliasNameError = AliasNameError; exports.validateAliasName = validateAliasName; exports.detectCycles = detectCycles; exports.findCommand = findCommand; exports.bridgeAliases = bridgeAliases; exports.alias_exports = alias_exports;
@@ -64,7 +64,10 @@ declare function bindArgs(cmd: Command, completer: Completer): void;
64
64
  /**
65
65
  * Records `name` as a root-level alias of the command at `target` (a
66
66
  * space-separated path), so root argument completion offers it as
67
- * `name<TAB>alias for <target>`. `bridgeAliases` calls this.
67
+ * `name<TAB>alias for <target>`, and a root subcommand named `name`
68
+ * completes as a flagless stand-in. `bridgeAliases` calls this for
69
+ * every alias but a visible or custom-dispatch proxy, which completes
70
+ * as an ordinary subcommand.
68
71
  */
69
72
  declare function registerRootAlias(root: Command, name: string, target: string): void;
70
73
  /** Where a request writes. */
@@ -1,3 +1,3 @@
1
1
  import 'commander';
2
2
  import './completion-values-By-mnjNt.js';
3
- export { C as CompletionIO, N as NO_DESC_REQUEST_CMD, R as REQUEST_CMD, S as SHELLS, a as Shell, b as bindArgs, d as bindFlag, e as completeRequest, f as completionCommand, g as generateBashCompletion, h as generateFishCompletion, i as generatePowerShellCompletion, j as generateZshCompletion, k as installCompletionRequest, r as registerRootAlias, l as renderCompletionScript } from './completion-sDKVXPUL.js';
3
+ export { C as CompletionIO, N as NO_DESC_REQUEST_CMD, R as REQUEST_CMD, S as SHELLS, a as Shell, b as bindArgs, d as bindFlag, e as completeRequest, f as completionCommand, g as generateBashCompletion, h as generateFishCompletion, i as generatePowerShellCompletion, j as generateZshCompletion, k as installCompletionRequest, r as registerRootAlias, l as renderCompletionScript } from './completion-csVun6SP.js';
package/dist/index.d.ts CHANGED
@@ -1,10 +1,10 @@
1
1
  export { a as aim } from './aim-DZHwwiIc.js';
2
- export { a as alias } from './alias-BsJ2jGqQ.js';
2
+ export { a as alias } from './alias-D9_qFlyP.js';
3
3
  export { l as anthropic } from './llm-anthropic-Cd_I2xXB.js';
4
4
  export { a as api } from './api-DAexsu2H.js';
5
5
  export { a as auth } from './auth-2-jfgiHn.js';
6
6
  export { c as cli } from './cli-C5B5tnpA.js';
7
- export { c as completion } from './completion-sDKVXPUL.js';
7
+ export { c as completion } from './completion-csVun6SP.js';
8
8
  export { c as completionValues } from './completion-values-By-mnjNt.js';
9
9
  export { c as compliance } from './compliance-AxFf-uMy.js';
10
10
  export { c as config } from './config-CaK60ByQ.js';
package/dist/index.js CHANGED
@@ -70,7 +70,7 @@ var _chunkQJVSKKRQjs = require('./chunk-QJVSKKRQ.js');
70
70
  var _chunk4UE5TCMQjs = require('./chunk-4UE5TCMQ.js');
71
71
 
72
72
 
73
- var _chunkDIDN4X5Cjs = require('./chunk-DIDN4X5C.js');
73
+ var _chunkBLS2OBIQjs = require('./chunk-BLS2OBIQ.js');
74
74
 
75
75
 
76
76
  var _chunkCSJWB6D3js = require('./chunk-CSJWB6D3.js');
@@ -128,4 +128,4 @@ require('./chunk-R5U7XKVJ.js');
128
128
 
129
129
 
130
130
 
131
- exports.aim = _chunkQJVSKKRQjs.aim_exports; exports.alias = _chunkDIDN4X5Cjs.alias_exports; exports.anthropic = _chunkT46YPHKNjs.llm_anthropic_exports; exports.api = _chunkCSJWB6D3js.api_exports; exports.auth = _chunkUKZIAQA7js.auth_exports; exports.cli = _chunkGHPJJV5Ljs.cli_exports; exports.completion = _chunkJZ22ZUFAjs.completion_exports; exports.completionValues = _chunkJKMQSAJPjs.completion_values_exports; exports.compliance = _chunkXJTRY453js.compliance_exports; exports.config = _chunkQQQYCWSCjs.config_exports; exports.errcorrect = _chunk3FIKGFKIjs.errcorrect_exports; exports.id = _chunkL23O2FFEjs.id_exports; exports.llm = _chunkPSFYJGDGjs.llm_exports; exports.log = _chunkNLMS7HGPjs.log_exports; exports.mcp = _chunkJTMPNXVQjs.mcp_exports; exports.netpolicy = _chunkKVG7YCTSjs.netpolicy_exports; exports.openai = _chunkABQSE7AIjs.llm_openai_exports; exports.output = _chunkIXVQ62NZjs.output_exports; exports.progress = _chunkBDNNPRX6js.progress_exports; exports.provenance = _chunk6SVOHNICjs.provenance_exports; exports.routellm = _chunkMUIQVU6Ejs.routellm_exports; exports.rpc = _chunkWUOAQVOAjs.rpc_exports; exports.safety = _chunk6HFAEZ52js.safety_exports; exports.scope = _chunkWBVO43HUjs.scope_exports; exports.serve = _chunkMQXYDYRDjs.serve_exports; exports.stream = _chunkBRNEKPWXjs.stream_exports; exports.telemetry = _chunkYOBAUCVNjs.telemetry_exports; exports.toolspec = _chunk263IZ6Z6js.toolspec_exports; exports.tui = _chunkGGWJRWWAjs.tui_exports; exports.upgrade = _chunkWWUKGJB5js.upgrade_exports; exports.xdg = _chunk4UE5TCMQjs.xdg_exports;
131
+ exports.aim = _chunkQJVSKKRQjs.aim_exports; exports.alias = _chunkBLS2OBIQjs.alias_exports; exports.anthropic = _chunkT46YPHKNjs.llm_anthropic_exports; exports.api = _chunkCSJWB6D3js.api_exports; exports.auth = _chunkUKZIAQA7js.auth_exports; exports.cli = _chunkGHPJJV5Ljs.cli_exports; exports.completion = _chunkJZ22ZUFAjs.completion_exports; exports.completionValues = _chunkJKMQSAJPjs.completion_values_exports; exports.compliance = _chunkXJTRY453js.compliance_exports; exports.config = _chunkQQQYCWSCjs.config_exports; exports.errcorrect = _chunk3FIKGFKIjs.errcorrect_exports; exports.id = _chunkL23O2FFEjs.id_exports; exports.llm = _chunkPSFYJGDGjs.llm_exports; exports.log = _chunkNLMS7HGPjs.log_exports; exports.mcp = _chunkJTMPNXVQjs.mcp_exports; exports.netpolicy = _chunkKVG7YCTSjs.netpolicy_exports; exports.openai = _chunkABQSE7AIjs.llm_openai_exports; exports.output = _chunkIXVQ62NZjs.output_exports; exports.progress = _chunkBDNNPRX6js.progress_exports; exports.provenance = _chunk6SVOHNICjs.provenance_exports; exports.routellm = _chunkMUIQVU6Ejs.routellm_exports; exports.rpc = _chunkWUOAQVOAjs.rpc_exports; exports.safety = _chunk6HFAEZ52js.safety_exports; exports.scope = _chunkWBVO43HUjs.scope_exports; exports.serve = _chunkMQXYDYRDjs.serve_exports; exports.stream = _chunkBRNEKPWXjs.stream_exports; exports.telemetry = _chunkYOBAUCVNjs.telemetry_exports; exports.toolspec = _chunk263IZ6Z6js.toolspec_exports; exports.tui = _chunkGGWJRWWAjs.tui_exports; exports.upgrade = _chunkWWUKGJB5js.upgrade_exports; exports.xdg = _chunk4UE5TCMQjs.xdg_exports;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hop-top/kit",
3
- "version": "0.5.0-alpha.7",
3
+ "version": "0.5.0-alpha.8",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "git+https://github.com/hop-top/poly-kit.git",
@@ -0,0 +1,250 @@
1
+ // Runs the shared alias corpus in contracts/alias-v1. The vectors are
2
+ // the source of truth: a failure means this port drifted from the
3
+ // contract, not that a vector should be edited to fit.
4
+ //
5
+ // Strict: unknown fields fail, `version` must be `v1` and every JSON
6
+ // file in the corpus must have a runner here.
7
+
8
+ import { readdirSync, readFileSync } from 'node:fs';
9
+ import { join } from 'node:path';
10
+ import { Command, CommanderError } from 'commander';
11
+ import { describe, expect, it } from 'vitest';
12
+
13
+ import {
14
+ AliasNameError, type AliasMap, type BridgeOptions,
15
+ bridgeAliases, detectCycles, findCommand, validateAliasName,
16
+ } from './alias';
17
+ import { completeRequest } from './completion';
18
+
19
+ const PORT = 'ts';
20
+ const CORPUS = join(__dirname, '..', '..', '..', 'contracts', 'alias-v1');
21
+ const FILES = ['bridge.json', 'cycles.json', 'validate.json'];
22
+
23
+ function strictKeys(o: object, allowed: string[], where: string): void {
24
+ for (const k of Object.keys(o)) {
25
+ if (!allowed.includes(k)) throw new Error(`${where}: unknown field ${k}`);
26
+ }
27
+ }
28
+
29
+ function load<T>(name: string, top: string[]): T {
30
+ for (const n of readdirSync(CORPUS)) {
31
+ if (n.endsWith('.json') && !FILES.includes(n)) {
32
+ throw new Error(`${n} has no runner`);
33
+ }
34
+ }
35
+ const f = JSON.parse(readFileSync(join(CORPUS, name), 'utf8'));
36
+ strictKeys(f, ['version', 'description', 'cases', ...top], name);
37
+ if (f.version !== 'v1') throw new Error(`${name}: version ${f.version}`);
38
+ if (!Array.isArray(f.cases) || f.cases.length === 0) {
39
+ throw new Error(`${name}: cases section is empty`);
40
+ }
41
+ return f as T;
42
+ }
43
+
44
+ // ── validate.json ───────────────────────────────────────────
45
+
46
+ interface ValidateCase {
47
+ name: string; alias: string; builtins?: string[];
48
+ existing?: AliasMap; expect: string;
49
+ }
50
+
51
+ describe('alias-v1 validate', () => {
52
+ const f = load<{ cases: ValidateCase[] }>('validate.json', []);
53
+ for (const c of f.cases) {
54
+ it(c.name, () => {
55
+ strictKeys(c, ['name', 'alias', 'builtins', 'existing', 'expect'], c.name);
56
+ let got = 'ok';
57
+ try {
58
+ validateAliasName(c.alias, { builtins: c.builtins, existing: c.existing });
59
+ } catch (e) {
60
+ expect(e).toBeInstanceOf(AliasNameError);
61
+ got = (e as AliasNameError).kind;
62
+ }
63
+ expect(got).toBe(c.expect);
64
+ });
65
+ }
66
+ });
67
+
68
+ // ── cycles.json ─────────────────────────────────────────────
69
+
70
+ describe('alias-v1 cycles', () => {
71
+ const f = load<{ cases: { name: string; aliases: AliasMap; cycles: string[][] }[] }>(
72
+ 'cycles.json', [],
73
+ );
74
+ for (const c of f.cases) {
75
+ it(c.name, () => {
76
+ strictKeys(c, ['name', 'aliases', 'cycles'], c.name);
77
+ expect(detectCycles(c.aliases)).toEqual(c.cycles);
78
+ });
79
+ }
80
+ });
81
+
82
+ // ── bridge.json ─────────────────────────────────────────────
83
+
84
+ interface Node {
85
+ name: string; description: string;
86
+ flags?: { name: string; default: string }[];
87
+ commands?: Node[];
88
+ }
89
+ interface Entry { kind: string; hidden?: boolean; description?: string }
90
+ interface Run {
91
+ ran: string; path?: string; env?: string | null; args?: string[];
92
+ name?: string; target?: string;
93
+ }
94
+ interface Check {
95
+ alias?: string; argv?: string[]; entry?: Entry; run?: Run; help?: string;
96
+ complete?: string[]; candidates?: string[];
97
+ by_port?: Record<string, Partial<Check>>;
98
+ }
99
+ interface BridgeCase {
100
+ name: string; aliases: AliasMap;
101
+ options?: { hidden?: boolean; describe?: boolean; help?: string; dispatch?: string };
102
+ skip?: Record<string, string>;
103
+ proxy_flags?: { name: string; short: string }[];
104
+ checks: Check[];
105
+ }
106
+ interface BridgeFile {
107
+ tree: Node; describe_template: string; cases: BridgeCase[];
108
+ }
109
+
110
+ // What a target or handler saw.
111
+ interface Seen {
112
+ ran: string; path?: string; env?: string | null; args?: string[];
113
+ name?: string; target?: string;
114
+ }
115
+
116
+ function build(
117
+ parent: Command, nodes: Node[], prefix: string, rec: { r: Seen },
118
+ descs: Map<string, string>,
119
+ ): void {
120
+ for (const n of nodes) {
121
+ strictKeys(n, ['name', 'description', 'flags', 'commands'], n.name);
122
+ const path = `${prefix} ${n.name}`.trim();
123
+ descs.set(path, n.description);
124
+ const c = parent.command(n.name).description(n.description);
125
+ const hasEnv = (n.flags ?? []).some(fl => fl.name === 'env');
126
+ for (const fl of n.flags ?? []) c.option(`--${fl.name} <v>`, '', fl.default);
127
+ if (!n.commands?.length) {
128
+ c.argument('[args...]').action((args: string[], opts: Record<string, string>) => {
129
+ rec.r = { ran: 'target', path, env: hasEnv ? opts.env : null, args };
130
+ });
131
+ }
132
+ build(c, n.commands ?? [], path, rec, descs);
133
+ }
134
+ }
135
+
136
+ function bridgeOptions(f: BridgeFile, c: BridgeCase, rec: { r: Seen }): BridgeOptions | undefined {
137
+ const o = c.options;
138
+ if (!o) return undefined;
139
+ strictKeys(o, ['hidden', 'describe', 'help', 'dispatch'], c.name);
140
+ const opts: BridgeOptions = {};
141
+ if (o.hidden !== undefined) opts.hidden = o.hidden;
142
+ if (o.describe) {
143
+ opts.describe = (name, target) =>
144
+ f.describe_template.replace('{name}', name).replace('{target}', target);
145
+ }
146
+ if (o.help === 'own') opts.helpOption = true;
147
+ else if (o.help === 'passthrough') opts.helpOption = false;
148
+ else if (o.help !== undefined) throw new Error(`unknown help ${o.help}`);
149
+ if (o.dispatch === 'handler') {
150
+ opts.dispatch = (name, target, cmd) => {
151
+ rec.r = { ran: 'handler', name, target, args: [...cmd.args] };
152
+ };
153
+ } else if (o.dispatch === 'register-only') {
154
+ opts.dispatch = false;
155
+ } else if (o.dispatch !== undefined) {
156
+ throw new Error(`unknown dispatch ${o.dispatch}`);
157
+ }
158
+ return opts;
159
+ }
160
+
161
+ describe('alias-v1 bridge', () => {
162
+ const f = load<BridgeFile>('bridge.json', ['tree', 'describe_template']);
163
+
164
+ function setup(c: BridgeCase) {
165
+ const rec: { r: Seen } = { r: { ran: 'none' } };
166
+ const descs = new Map<string, string>();
167
+ let out = '';
168
+ const program = new Command(f.tree.name)
169
+ .exitOverride()
170
+ .configureOutput({ writeOut: s => { out += s; }, writeErr: s => { out += s; } });
171
+ build(program, f.tree.commands ?? [], '', rec, descs);
172
+ const sorted = Object.fromEntries(Object.entries(c.aliases).sort(([a], [b]) => (a < b ? -1 : 1)));
173
+ bridgeAliases(program, sorted, bridgeOptions(f, c, rec));
174
+ for (const fl of c.proxy_flags ?? []) {
175
+ strictKeys(fl, ['name', 'short'], c.name);
176
+ for (const alias of Object.keys(c.aliases)) {
177
+ const proxy = program.commands.find(x => x.name() === alias);
178
+ if (!proxy) throw new Error(`${c.name}: ${alias} has no proxy`);
179
+ proxy.option(`-${fl.short}, --${fl.name} <v>`, fl.name);
180
+ }
181
+ }
182
+ return { program, rec, descs, output: () => out };
183
+ }
184
+
185
+ for (const c of f.cases) {
186
+ const skip = c.skip?.[PORT];
187
+ (skip ? it.skip : it)(skip ? `${c.name} (${skip})` : c.name, async () => {
188
+ strictKeys(c, ['name', 'aliases', 'options', 'skip', 'proxy_flags', 'checks'], c.name);
189
+ for (const raw of c.checks) {
190
+ strictKeys(
191
+ raw, ['alias', 'argv', 'entry', 'run', 'help', 'complete', 'candidates', 'by_port'], c.name,
192
+ );
193
+ const chk: Check = { ...raw, ...(raw.by_port?.[PORT] ?? {}) };
194
+ const { program, rec, descs, output } = setup(c);
195
+
196
+ if (chk.entry) {
197
+ const alias = chk.alias!;
198
+ const proxy = program.commands.find(x => x.name() === alias);
199
+ if (proxy) {
200
+ expect(chk.entry.kind, alias).toBe('proxy');
201
+ if (chk.entry.hidden !== undefined) {
202
+ expect((proxy as unknown as { _hidden: boolean })._hidden, alias)
203
+ .toBe(chk.entry.hidden);
204
+ }
205
+ if (chk.entry.description !== undefined) {
206
+ expect(proxy.description(), alias).toBe(chk.entry.description);
207
+ }
208
+ } else {
209
+ const target = findCommand(program, c.aliases[alias]);
210
+ expect(target?.aliases().includes(alias) ? 'native' : 'missing', alias)
211
+ .toBe(chk.entry.kind);
212
+ }
213
+ } else if (chk.run) {
214
+ await program.parseAsync(chk.argv!, { from: 'user' });
215
+ const r = rec.r;
216
+ expect(r.ran, chk.argv!.join(' ')).toBe(chk.run.ran);
217
+ if (chk.run.ran === 'target') {
218
+ expect({ path: r.path, env: r.env, args: r.args })
219
+ .toEqual({ path: chk.run.path, env: chk.run.env, args: chk.run.args });
220
+ } else if (chk.run.ran === 'handler') {
221
+ expect({ name: r.name, target: r.target, args: r.args })
222
+ .toEqual({ name: chk.run.name, target: chk.run.target, args: chk.run.args });
223
+ }
224
+ } else if (chk.help) {
225
+ const err = await program.parseAsync(chk.argv!, { from: 'user' })
226
+ .then(() => undefined, (e: unknown) => e);
227
+ expect(err, chk.argv!.join(' ')).toBeInstanceOf(CommanderError);
228
+ expect((err as CommanderError).code).toBe('commander.helpDisplayed');
229
+ const alias = chk.argv![0];
230
+ const text = output();
231
+ const proxy = program.commands.find(x => x.name() === alias);
232
+ let got = 'unknown';
233
+ if (text.includes(descs.get(c.aliases[alias])!)) got = 'target';
234
+ else if (proxy && text.includes(proxy.description())) got = 'alias';
235
+ expect(got, text).toBe(chk.help);
236
+ expect(rec.r.ran).toBe('none');
237
+ } else if (chk.complete) {
238
+ let out = '';
239
+ await completeRequest(program, chk.complete, true, {
240
+ out: s => { out += s; }, err: () => {},
241
+ });
242
+ const got = out.split('\n').filter(l => l !== '' && !l.startsWith(':')).sort();
243
+ expect(got, chk.complete.join(' ')).toEqual([...chk.candidates!].sort());
244
+ } else {
245
+ throw new Error(`${c.name}: check has no observable`);
246
+ }
247
+ }
248
+ });
249
+ }
250
+ });
package/src/alias.test.ts CHANGED
@@ -4,8 +4,9 @@ import * as path from 'path';
4
4
  import * as os from 'os';
5
5
  import {
6
6
  AliasStore, loadFrom, saveTo, findFirstNonFlag, Expander,
7
- bridgeAliases, findCommand,
7
+ bridgeAliases, findCommand, validateAliasName, AliasNameError,
8
8
  } from './alias';
9
+ import { completeRequest } from './completion';
9
10
  import { Command, CommanderError } from 'commander';
10
11
 
11
12
  let tmpDir: string;
@@ -530,3 +531,97 @@ describe('bridgeAliases proxy dispatch', () => {
530
531
  .rejects.toMatchObject({ code: 'commander.unknownCommand' });
531
532
  });
532
533
  });
534
+
535
+ // ── validateAliasName / bridge options ─────────────────────
536
+
537
+ describe('validateAliasName', () => {
538
+ it('keeps the Expander texts and adds duplicate', () => {
539
+ const msg = (name: string, rules = {}) => {
540
+ try { validateAliasName(name, rules); } catch (e) { return (e as Error).message; }
541
+ return 'ok';
542
+ };
543
+ expect(msg('')).toBe('alias name must not be empty');
544
+ expect(msg('a b')).toBe('alias name must not contain whitespace');
545
+ expect(msg('task', { builtins: ['task'] }))
546
+ .toBe('alias "task" conflicts with a built-in command');
547
+ expect(msg('d', { existing: { d: 'deploy' } }))
548
+ .toBe('alias "d" is already registered for "deploy"');
549
+ expect(msg('tl', { builtins: new Set(['task']) })).toBe('ok');
550
+ });
551
+
552
+ it('throws AliasNameError carrying the kind', () => {
553
+ expect(() => validateAliasName('task', { builtins: ['task'] }))
554
+ .toThrow(AliasNameError);
555
+ });
556
+ });
557
+
558
+ describe('bridgeAliases options', () => {
559
+ it('accepts a plain map and an empty options object keeps defaults', () => {
560
+ const program = new Command('test');
561
+ program.command('deploy').description('Deploy');
562
+ bridgeAliases(program, { d: 'deploy' }, {});
563
+ expect(findCommand(program, 'deploy')?.aliases()).toContain('d');
564
+ expect(program.commands.find(c => c.name() === 'd')).toBeUndefined();
565
+ });
566
+
567
+ it('options make a single-word alias a proxy', () => {
568
+ const program = new Command('test');
569
+ program.command('deploy').description('Deploy');
570
+ bridgeAliases(program, { d: 'deploy' }, {
571
+ hidden: false, describe: (n, t) => `${n} -> ${t}`,
572
+ });
573
+ const proxy = program.commands.find(c => c.name() === 'd');
574
+ expect(proxy?.description()).toBe('d -> deploy');
575
+ expect(findCommand(program, 'deploy')?.aliases()).not.toContain('d');
576
+ });
577
+
578
+ it('dispatch handler result is awaited by parseAsync', async () => {
579
+ const program = new Command('test').exitOverride();
580
+ program.command('deploy').action(() => {});
581
+ let done = false;
582
+ bridgeAliases(program, { d: 'deploy' }, {
583
+ dispatch: async () => { await new Promise(r => setTimeout(r, 5)); done = true; },
584
+ });
585
+ await program.parseAsync(['d'], { from: 'user' });
586
+ expect(done).toBe(true);
587
+ });
588
+ });
589
+
590
+ describe('bridgeAliases completion', () => {
591
+ async function complete(program: Command, words: string[]): Promise<string[]> {
592
+ let out = '';
593
+ await completeRequest(program, words, true, { out: s => { out += s; }, err: () => {} });
594
+ return out.split('\n').filter(l => l !== '' && !l.startsWith(':')).sort();
595
+ }
596
+
597
+ function tree(): Command {
598
+ const program = new Command('test');
599
+ program.command('deploy').description('Deploy').option('--env <e>');
600
+ return program;
601
+ }
602
+
603
+ it('a hidden proxy is a stand-in, offered once by name', async () => {
604
+ for (const dispatch of [undefined, false] as const) {
605
+ const program = tree();
606
+ bridgeAliases(program, { d: 'deploy' }, { describe: () => 'x', dispatch });
607
+ expect(await complete(program, ['d'])).toEqual(['d', 'deploy']);
608
+ expect(await complete(program, ['d', '--'])).toEqual(['--help']);
609
+ }
610
+ });
611
+
612
+ it('a hidden proxy with a dispatch handler completes its own flags', async () => {
613
+ const program = tree();
614
+ bridgeAliases(program, { d: 'deploy' }, { dispatch: () => {} });
615
+ program.commands.find(c => c.name() === 'd')!.option('-p, --path <p>');
616
+ expect(await complete(program, ['d'])).toEqual(['deploy']);
617
+ expect(await complete(program, ['d', '--'])).toEqual(['--path']);
618
+ });
619
+
620
+ it('a visible proxy is offered once, with its own flags', async () => {
621
+ const program = tree();
622
+ bridgeAliases(program, { d: 'deploy' }, { hidden: false, helpOption: true });
623
+ program.commands.find(c => c.name() === 'd')!.option('-p, --path <p>');
624
+ expect(await complete(program, ['d'])).toEqual(['d', 'deploy']);
625
+ expect(await complete(program, ['d', '--'])).toEqual(['--help', '--path']);
626
+ });
627
+ });
package/src/alias.ts CHANGED
@@ -186,18 +186,117 @@ export class Expander {
186
186
  return [result, true];
187
187
  }
188
188
 
189
- /** Reject names that shadow builtins or contain whitespace. */
189
+ /**
190
+ * Reject names that shadow builtins or contain whitespace; see
191
+ * {@link validateAliasName}, which needs no config files.
192
+ */
190
193
  validateName(name: string): void {
191
- if (name === '') {
192
- throw new Error('alias name must not be empty');
193
- }
194
- if (/\s/.test(name)) {
195
- throw new Error('alias name must not contain whitespace');
194
+ validateAliasName(name, { builtins: this.cfg.builtins });
195
+ }
196
+ }
197
+
198
+ // ── Standalone validation and cycle detection ───────────────
199
+
200
+ /** The rule an alias name failed; see {@link validateAliasName}. */
201
+ export type AliasNameErrorKind = 'empty' | 'whitespace' | 'builtin' | 'duplicate';
202
+
203
+ /** An alias name {@link validateAliasName} refused. */
204
+ export class AliasNameError extends Error {
205
+ readonly kind: AliasNameErrorKind;
206
+ readonly alias: string;
207
+ /** The existing alias's target, for `duplicate`. */
208
+ readonly target?: string;
209
+
210
+ constructor(kind: AliasNameErrorKind, alias: string, target?: string) {
211
+ super(aliasNameMessage(kind, alias, target));
212
+ this.name = 'AliasNameError';
213
+ this.kind = kind;
214
+ this.alias = alias;
215
+ this.target = target;
216
+ }
217
+ }
218
+
219
+ function aliasNameMessage(
220
+ kind: AliasNameErrorKind, alias: string, target?: string,
221
+ ): string {
222
+ switch (kind) {
223
+ case 'empty': return 'alias name must not be empty';
224
+ case 'whitespace': return 'alias name must not contain whitespace';
225
+ case 'builtin': return `alias "${alias}" conflicts with a built-in command`;
226
+ case 'duplicate':
227
+ return `alias "${alias}" is already registered for "${target ?? ''}"`;
228
+ }
229
+ }
230
+
231
+ /** What {@link validateAliasName} checks a name against. */
232
+ export interface AliasNameRules {
233
+ /** Names an alias must not take: the tool's commands and reserved words. */
234
+ builtins?: Iterable<string>;
235
+ /** The alias map the name would join. */
236
+ existing?: AliasMap;
237
+ }
238
+
239
+ const WHITE_SPACE = /\p{White_Space}/u;
240
+
241
+ /**
242
+ * Check an alias name without a store, config file or command tree.
243
+ * Rules run in order and the first failure throws an
244
+ * {@link AliasNameError}: empty, whitespace (any Unicode White_Space
245
+ * character), builtin, duplicate.
246
+ */
247
+ export function validateAliasName(name: string, rules: AliasNameRules = {}): void {
248
+ if (name === '') throw new AliasNameError('empty', name);
249
+ if (WHITE_SPACE.test(name)) throw new AliasNameError('whitespace', name);
250
+ if (rules.builtins) {
251
+ for (const b of rules.builtins) {
252
+ if (b === name) throw new AliasNameError('builtin', name);
196
253
  }
197
- if (this.cfg.builtins?.has(name)) {
198
- throw new Error(`alias "${name}" conflicts with a built-in command`);
254
+ }
255
+ const existing = rules.existing;
256
+ if (existing && Object.prototype.hasOwnProperty.call(existing, name)) {
257
+ throw new AliasNameError('duplicate', name, existing[name]);
258
+ }
259
+ }
260
+
261
+ /**
262
+ * Report alias cycles in `aliases` (name -> target). An alias points at
263
+ * another when the first word of its target is a key of the map. Each
264
+ * cycle is a path starting at its smallest name and ending with it
265
+ * again (`['a', 'b', 'a']`); cycles are sorted by first name. An alias
266
+ * that only leads into a cycle is not part of one.
267
+ */
268
+ export function detectCycles(aliases: AliasMap): string[][] {
269
+ const has = (n: string) => Object.prototype.hasOwnProperty.call(aliases, n);
270
+ const next = (n: string): string | undefined => {
271
+ const first = aliases[n].trim().split(/\s+/)[0];
272
+ return first !== '' && has(first) ? first : undefined;
273
+ };
274
+ const cmp = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
275
+
276
+ const done = new Set<string>();
277
+ const cycles: string[][] = [];
278
+ for (const start of Object.keys(aliases).sort(cmp)) {
279
+ if (done.has(start)) continue;
280
+ const pos = new Map<string, number>();
281
+ const walk: string[] = [];
282
+ let cur: string | undefined = start;
283
+ while (cur !== undefined && !done.has(cur)) {
284
+ const at = pos.get(cur);
285
+ if (at !== undefined) {
286
+ const members = walk.slice(at);
287
+ let min = 0;
288
+ members.forEach((m, i) => { if (m < members[min]) min = i; });
289
+ const path = [...members.slice(min), ...members.slice(0, min)];
290
+ cycles.push([...path, path[0]]);
291
+ break;
292
+ }
293
+ pos.set(cur, walk.length);
294
+ walk.push(cur);
295
+ cur = next(cur);
199
296
  }
297
+ for (const n of walk) done.add(n);
200
298
  }
299
+ return cycles.sort((a, b) => cmp(a[0], b[0]));
201
300
  }
202
301
 
203
302
  // ── Commander bridge ────────────────────────────────────────
@@ -221,13 +320,57 @@ type Dispatcher = {
221
320
  _parseCommand(operands: string[], unknown: string[]): void | Promise<void>;
222
321
  };
223
322
 
323
+ /** Runs an alias proxy in place of its target; `cmd.args` holds every argument after the alias, unparsed. */
324
+ export type AliasDispatch = (
325
+ name: string, target: string, cmd: Command,
326
+ ) => void | Promise<void>;
327
+
328
+ /**
329
+ * Options for {@link bridgeAliases}. Setting any of them registers every
330
+ * alias as a proxy, a root command named after the alias, even for a
331
+ * single-word target that would otherwise take a Commander alias.
332
+ */
333
+ export interface BridgeOptions {
334
+ /** Hide proxies from help. Default true. */
335
+ hidden?: boolean;
336
+ /** A proxy's description, in place of `Alias for <target>`. */
337
+ describe?: (name: string, target: string) => string;
338
+ /**
339
+ * true: the proxy owns -h/--help and shows its own help. false (the
340
+ * default): --help reaches the target, or the dispatch handler.
341
+ */
342
+ helpOption?: boolean;
343
+ /**
344
+ * A handler run instead of the target, or false to register proxies
345
+ * that run nothing (register-only). Default: dispatch the target
346
+ * through the program, like a native subcommand.
347
+ */
348
+ dispatch?: AliasDispatch | false;
349
+ }
350
+
351
+ function hasBridgeOptions(opts?: BridgeOptions): opts is BridgeOptions {
352
+ return opts !== undefined &&
353
+ Object.values(opts).some(v => v !== undefined);
354
+ }
355
+
224
356
  /**
225
357
  * Register loaded aliases with Commander's native .alias() API.
226
358
  *
227
359
  * Simple single-command aliases use Commander's built-in .alias(),
228
360
  * giving free completion and help display. Multi-word or unresolved
229
361
  * targets get a hidden proxy command that dispatches the expanded
230
- * args from the program, like a native subcommand.
362
+ * args from the program, like a native subcommand. With any
363
+ * {@link BridgeOptions} set, every alias gets a proxy shaped by them.
364
+ *
365
+ * Completion offers each alias at most once. A native alias, or a hidden
366
+ * proxy that dispatches its target or runs nothing, is a stand-in:
367
+ * completion lists it as `alias for <target>` and offers a proxy only
368
+ * its help flag. A visible proxy, or one with a dispatch handler, is a
369
+ * real command and completes like any subcommand, with its own flags,
370
+ * including any added after bridging; a hidden one is not listed.
371
+ *
372
+ * `source` is an {@link AliasStore} or a plain alias map, so aliases
373
+ * can come from any storage.
231
374
  *
232
375
  * Dispatch reuses Commander's own subcommand dispatch rather than
233
376
  * calling parse()/parseAsync() again: re-parsing resets program
@@ -238,14 +381,24 @@ type Dispatcher = {
238
381
  */
239
382
  export function bridgeAliases(
240
383
  program: Command,
241
- store: AliasStore,
384
+ source: AliasStore | AliasMap,
385
+ opts?: BridgeOptions,
242
386
  ): void {
243
- const all = store.all();
387
+ const all = typeof (source as AliasStore).all === 'function'
388
+ ? (source as AliasStore).all()
389
+ : { ...(source as AliasMap) };
390
+ const proxyAll = hasBridgeOptions(opts);
391
+ // A visible or custom-dispatch proxy is a real command: completion
392
+ // offers it among the subcommands and walks it for its own flags. A
393
+ // root-alias entry would list it twice and complete it as a flagless
394
+ // stand-in.
395
+ const realProxy = proxyAll &&
396
+ (opts.hidden === false || typeof opts.dispatch === 'function');
244
397
  for (const [name, target] of Object.entries(all)) {
245
- registerRootAlias(program, name, target);
398
+ if (!realProxy) registerRootAlias(program, name, target);
246
399
  const parts = target.split(/\s+/);
247
400
  // simple alias: single word target that exists as a direct subcommand
248
- if (parts.length === 1) {
401
+ if (!proxyAll && parts.length === 1) {
249
402
  const targetCmd = findCommand(program, target);
250
403
  if (targetCmd) {
251
404
  targetCmd.alias(name);
@@ -253,19 +406,26 @@ export function bridgeAliases(
253
406
  }
254
407
  }
255
408
 
256
- // multi-word target or unknown command: hidden proxy
257
- const proxy = new Command(name)
258
- .description(`Alias for ${target}`)
409
+ // multi-word target, unknown command or options: proxy
410
+ const dispatch = opts?.dispatch;
411
+ const proxy = new Command(name);
412
+ // An options proxy behaves like a subcommand made with
413
+ // program.command(): it inherits exitOverride, output and help
414
+ // settings, which matter once it renders its own help.
415
+ if (proxyAll) proxy.copyInheritedSettings(program);
416
+ proxy
417
+ .description(opts?.describe?.(name, target) ?? `Alias for ${target}`)
259
418
  .allowUnknownOption(true)
260
419
  .allowExcessArguments(true)
261
420
  .action(function (this: Command) {
421
+ if (dispatch === false) return undefined;
422
+ if (dispatch) return dispatch(name, target, this);
262
423
  const expanded = target.split(/\s+/);
263
424
  return (program as unknown as Dispatcher)._parseCommand(
264
425
  [], [...expanded, ...this.args],
265
426
  );
266
427
  });
267
- proxy.helpOption(false);
268
- (proxy as any)._hidden = true;
269
- program.addCommand(proxy);
428
+ if (opts?.helpOption !== true) proxy.helpOption(false);
429
+ program.addCommand(proxy, { hidden: opts?.hidden ?? true });
270
430
  }
271
431
  }
package/src/completion.ts CHANGED
@@ -254,7 +254,10 @@ export function bindArgs(cmd: Command, completer: Completer): void {
254
254
  /**
255
255
  * Records `name` as a root-level alias of the command at `target` (a
256
256
  * space-separated path), so root argument completion offers it as
257
- * `name<TAB>alias for <target>`. `bridgeAliases` calls this.
257
+ * `name<TAB>alias for <target>`, and a root subcommand named `name`
258
+ * completes as a flagless stand-in. `bridgeAliases` calls this for
259
+ * every alias but a visible or custom-dispatch proxy, which completes
260
+ * as an ordinary subcommand.
258
261
  */
259
262
  export function registerRootAlias(root: Command, name: string, target: string): void {
260
263
  const t = root as Tagged;
@@ -1,96 +0,0 @@
1
- import { Command } from 'commander';
2
-
3
- /**
4
- * alias.ts — YAML-file-based command alias expansion.
5
- *
6
- * Port of Go's cli/alias package. Aliases live in per-tool YAML
7
- * config files with three-tier priority: seeded < global < local.
8
- */
9
-
10
- type AliasMap = Record<string, string>;
11
- interface ExpanderConfig {
12
- globalPath: string;
13
- localPath: string;
14
- seededAliases?: AliasMap;
15
- builtins?: Set<string>;
16
- }
17
- /** Read aliases from a single YAML config file. */
18
- declare function loadFrom(filePath: string): AliasMap;
19
- /** Write aliases into a YAML config file, preserving other keys. */
20
- declare function saveTo(filePath: string, aliases: AliasMap): void;
21
- /**
22
- * Find the first non-flag element in a slice.
23
- * Returns [index, value]. Flags with `=` are self-contained;
24
- * short flags without `=` consume the next element as their value.
25
- */
26
- declare function findFirstNonFlag(slice: string[]): [number, string];
27
- /**
28
- * Simple single-file alias store with load/save, set/get/remove,
29
- * and first-arg expansion.
30
- */
31
- declare class AliasStore {
32
- private filePath;
33
- private aliases;
34
- constructor(filePath: string);
35
- load(): void;
36
- save(): void;
37
- set(name: string, target: string): void;
38
- remove(name: string): void;
39
- get(name: string): string | undefined;
40
- /** Returns a shallow copy. */
41
- all(): AliasMap;
42
- /** Expand first arg if it matches an alias. */
43
- expand(args: string[]): string[];
44
- }
45
- /**
46
- * Three-tier alias expander matching Go's Expander.
47
- * Priority: seeded < global < local.
48
- */
49
- declare class Expander {
50
- private cfg;
51
- constructor(cfg: ExpanderConfig);
52
- /** Merged alias map (seeded < global < local). */
53
- load(): AliasMap;
54
- /**
55
- * Rewrite args if args[1] (or first non-flag arg) matches
56
- * an alias. Returns [rewrittenArgs, wasExpanded].
57
- */
58
- expand(args: string[]): [string[], boolean];
59
- /** Reject names that shadow builtins or contain whitespace. */
60
- validateName(name: string): void;
61
- }
62
- /** Walk the Commander program tree to find a command by space-delimited path. */
63
- declare function findCommand(program: Command, cmdPath: string): Command | undefined;
64
- /**
65
- * Register loaded aliases with Commander's native .alias() API.
66
- *
67
- * Simple single-command aliases use Commander's built-in .alias(),
68
- * giving free completion and help display. Multi-word or unresolved
69
- * targets get a hidden proxy command that dispatches the expanded
70
- * args from the program, like a native subcommand.
71
- *
72
- * Dispatch reuses Commander's own subcommand dispatch rather than
73
- * calling parse()/parseAsync() again: re-parsing resets program
74
- * option values mid-parse and fixes the sync/async mode, whereas
75
- * dispatch returns the target's result as-is. parseAsync() callers
76
- * thus await async targets (rejections propagate), and parse()
77
- * callers keep synchronous throws.
78
- */
79
- declare function bridgeAliases(program: Command, store: AliasStore): void;
80
-
81
- type alias_AliasMap = AliasMap;
82
- type alias_AliasStore = AliasStore;
83
- declare const alias_AliasStore: typeof AliasStore;
84
- type alias_Expander = Expander;
85
- declare const alias_Expander: typeof Expander;
86
- type alias_ExpanderConfig = ExpanderConfig;
87
- declare const alias_bridgeAliases: typeof bridgeAliases;
88
- declare const alias_findCommand: typeof findCommand;
89
- declare const alias_findFirstNonFlag: typeof findFirstNonFlag;
90
- declare const alias_loadFrom: typeof loadFrom;
91
- declare const alias_saveTo: typeof saveTo;
92
- declare namespace alias {
93
- export { type alias_AliasMap as AliasMap, alias_AliasStore as AliasStore, alias_Expander as Expander, type alias_ExpanderConfig as ExpanderConfig, alias_bridgeAliases as bridgeAliases, alias_findCommand as findCommand, alias_findFirstNonFlag as findFirstNonFlag, alias_loadFrom as loadFrom, alias_saveTo as saveTo };
94
- }
95
-
96
- export { type AliasMap as A, Expander as E, alias as a, AliasStore as b, type ExpanderConfig as c, bridgeAliases as d, findFirstNonFlag as e, findCommand as f, loadFrom as l, saveTo as s };