@hop-top/kit 0.4.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (174) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/LICENSE +25 -0
  3. package/README.md +189 -0
  4. package/dist/aim.d.ts +116 -0
  5. package/dist/aim.js +417 -0
  6. package/dist/alias.d.ts +73 -0
  7. package/dist/alias.js +207 -0
  8. package/dist/api.d.ts +62 -0
  9. package/dist/api.js +165 -0
  10. package/dist/auth.d.ts +26 -0
  11. package/dist/auth.js +41 -0
  12. package/dist/cli.d.ts +309 -0
  13. package/dist/cli.js +885 -0
  14. package/dist/config.d.ts +97 -0
  15. package/dist/config.js +79 -0
  16. package/dist/errcorrect.d.ts +37 -0
  17. package/dist/errcorrect.js +69 -0
  18. package/dist/llm.d.ts +188 -0
  19. package/dist/llm.js +356 -0
  20. package/dist/output.d.ts +213 -0
  21. package/dist/output.js +447 -0
  22. package/dist/progress.d.ts +30 -0
  23. package/dist/progress.js +56 -0
  24. package/dist/provenance.d.ts +24 -0
  25. package/dist/provenance.js +32 -0
  26. package/dist/routellm.d.ts +64 -0
  27. package/dist/routellm.js +258 -0
  28. package/dist/rpc.d.ts +25 -0
  29. package/dist/rpc.js +101 -0
  30. package/dist/safety.d.ts +24 -0
  31. package/dist/safety.js +44 -0
  32. package/dist/scope.d.ts +121 -0
  33. package/dist/scope.js +380 -0
  34. package/dist/sqlstore.d.ts +84 -0
  35. package/dist/sqlstore.js +85 -0
  36. package/dist/stream.d.ts +35 -0
  37. package/dist/stream.js +52 -0
  38. package/dist/tui/index.d.ts +300 -0
  39. package/dist/tui/index.js +332 -0
  40. package/dist/upgrade.d.ts +95 -0
  41. package/dist/upgrade.js +115 -0
  42. package/dist/xdg.d.ts +169 -0
  43. package/dist/xdg.js +129 -0
  44. package/eslint.config.mjs +17 -0
  45. package/package.json +133 -0
  46. package/src/README.md +3 -0
  47. package/src/aim.test.ts +331 -0
  48. package/src/aim.ts +388 -0
  49. package/src/alias.test.ts +423 -0
  50. package/src/alias.ts +256 -0
  51. package/src/api.test.ts +190 -0
  52. package/src/api.ts +214 -0
  53. package/src/auth.test.ts +24 -0
  54. package/src/auth.ts +37 -0
  55. package/src/bus.test.ts +178 -0
  56. package/src/bus.ts +114 -0
  57. package/src/cli.test.ts +690 -0
  58. package/src/cli.ts +741 -0
  59. package/src/completion-values.test.ts +202 -0
  60. package/src/completion-values.ts +173 -0
  61. package/src/completion.test.ts +212 -0
  62. package/src/completion.ts +158 -0
  63. package/src/compliance.test.ts +134 -0
  64. package/src/compliance.ts +669 -0
  65. package/src/config.test.ts +110 -0
  66. package/src/config.ts +164 -0
  67. package/src/errcorrect.test.ts +134 -0
  68. package/src/errcorrect.ts +84 -0
  69. package/src/flagregister.test.ts +103 -0
  70. package/src/flagregister.ts +78 -0
  71. package/src/gen/crud_connect.ts +76 -0
  72. package/src/gen/crud_pb.ts +269 -0
  73. package/src/hint.test.ts +315 -0
  74. package/src/hint.ts +178 -0
  75. package/src/llm.test.ts +612 -0
  76. package/src/llm.ts +577 -0
  77. package/src/log.test.ts +145 -0
  78. package/src/log.ts +155 -0
  79. package/src/output/builtins.ts +34 -0
  80. package/src/output/dispatch.ts +195 -0
  81. package/src/output/flags.ts +151 -0
  82. package/src/output/format_help.ts +80 -0
  83. package/src/output/formatter.ts +167 -0
  84. package/src/output/formatters/csv.ts +72 -0
  85. package/src/output/formatters/json.ts +44 -0
  86. package/src/output/formatters/table.ts +44 -0
  87. package/src/output/formatters/text.ts +109 -0
  88. package/src/output/formatters/yaml.ts +47 -0
  89. package/src/output/projection.ts +126 -0
  90. package/src/output/registry.ts +88 -0
  91. package/src/output/template.ts +63 -0
  92. package/src/output.test.ts +117 -0
  93. package/src/output.ts +90 -0
  94. package/src/progress.test.ts +93 -0
  95. package/src/progress.ts +58 -0
  96. package/src/provenance.test.ts +59 -0
  97. package/src/provenance.ts +26 -0
  98. package/src/routellm.test.ts +179 -0
  99. package/src/routellm.ts +365 -0
  100. package/src/router/bert.test.ts +180 -0
  101. package/src/router/bert.ts +145 -0
  102. package/src/router/controller.test.ts +183 -0
  103. package/src/router/controller.ts +165 -0
  104. package/src/router/integration.test.ts +309 -0
  105. package/src/router/intent.test.ts +187 -0
  106. package/src/router/intent.ts +208 -0
  107. package/src/router/mf.test.ts +66 -0
  108. package/src/router/mf.ts +52 -0
  109. package/src/router/random.test.ts +23 -0
  110. package/src/router/random.ts +13 -0
  111. package/src/router/router.test.ts +31 -0
  112. package/src/router/router.ts +62 -0
  113. package/src/router/server.test.ts +193 -0
  114. package/src/router/server.ts +134 -0
  115. package/src/router/sw.test.ts +199 -0
  116. package/src/router/sw.ts +232 -0
  117. package/src/rpc.test.ts +47 -0
  118. package/src/rpc.ts +91 -0
  119. package/src/safety.test.ts +53 -0
  120. package/src/safety.ts +42 -0
  121. package/src/scope-defaults.json +72 -0
  122. package/src/scope.test.ts +177 -0
  123. package/src/scope.ts +382 -0
  124. package/src/setflag.test.ts +110 -0
  125. package/src/setflag.ts +102 -0
  126. package/src/sqlstore.test.ts +110 -0
  127. package/src/sqlstore.ts +144 -0
  128. package/src/stream.test.ts +69 -0
  129. package/src/stream.ts +47 -0
  130. package/src/textflag.test.ts +105 -0
  131. package/src/textflag.ts +68 -0
  132. package/src/toolspec.test.ts +187 -0
  133. package/src/toolspec.ts +279 -0
  134. package/src/triton/client.test.ts +205 -0
  135. package/src/triton/client.ts +261 -0
  136. package/src/tui/anim.test.ts +146 -0
  137. package/src/tui/anim.ts +134 -0
  138. package/src/tui/badge.test.ts +41 -0
  139. package/src/tui/badge.ts +55 -0
  140. package/src/tui/confirm.test.ts +68 -0
  141. package/src/tui/confirm.ts +49 -0
  142. package/src/tui/index.ts +29 -0
  143. package/src/tui/list.test.ts +84 -0
  144. package/src/tui/list.ts +72 -0
  145. package/src/tui/parity.ts +41 -0
  146. package/src/tui/pills.test.ts +40 -0
  147. package/src/tui/pills.ts +43 -0
  148. package/src/tui/progress.test.ts +164 -0
  149. package/src/tui/progress.ts +120 -0
  150. package/src/tui/spinner.test.ts +111 -0
  151. package/src/tui/spinner.ts +96 -0
  152. package/src/tui/status.test.ts +68 -0
  153. package/src/tui/status.ts +66 -0
  154. package/src/upgrade.test.ts +298 -0
  155. package/src/upgrade.ts +205 -0
  156. package/src/uri.ts +199 -0
  157. package/src/wizard.test.ts +441 -0
  158. package/src/wizard.ts +662 -0
  159. package/src/xdg.test.ts +202 -0
  160. package/src/xdg.ts +280 -0
  161. package/test/output/cols.test.ts +148 -0
  162. package/test/output/csv.test.ts +129 -0
  163. package/test/output/dispatch.test.ts +194 -0
  164. package/test/output/format_help.test.ts +131 -0
  165. package/test/output/formatter.test.ts +137 -0
  166. package/test/output/output_flag.test.ts +124 -0
  167. package/test/output/registry.test.ts +127 -0
  168. package/test/output/smoke-capture.ts +83 -0
  169. package/test/output/smoke.test.ts +142 -0
  170. package/test/output/template.test.ts +95 -0
  171. package/test/output/text.test.ts +75 -0
  172. package/test/testdata/api-fixture.json +115 -0
  173. package/test/testdata/query-vectors.json +187 -0
  174. package/tsconfig.json +12 -0
@@ -0,0 +1,423 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as os from 'os';
5
+ import {
6
+ AliasStore, loadFrom, saveTo, findFirstNonFlag, Expander,
7
+ bridgeAliases, findCommand,
8
+ } from './alias';
9
+ import { Command } from 'commander';
10
+
11
+ let tmpDir: string;
12
+
13
+ beforeEach(() => {
14
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'alias-test-'));
15
+ });
16
+
17
+ afterEach(() => {
18
+ fs.rmSync(tmpDir, { recursive: true, force: true });
19
+ });
20
+
21
+ function writeConfig(name: string, expansion: string): string {
22
+ const cfgDir = path.join(tmpDir, '.tool');
23
+ fs.mkdirSync(cfgDir, { recursive: true });
24
+ const p = path.join(cfgDir, 'config.yaml');
25
+ fs.writeFileSync(p, `aliases:\n ${name}: ${expansion}\n`);
26
+ return p;
27
+ }
28
+
29
+ function makeExpander(localPath: string): Expander {
30
+ return new Expander({
31
+ globalPath: '/nonexistent/global.yaml',
32
+ localPath,
33
+ seededAliases: { setup: 'config interactive' },
34
+ builtins: new Set(['task', 'config', 'help']),
35
+ });
36
+ }
37
+
38
+ // ── AliasStore ──────────────────────────────────────────────
39
+
40
+ describe('AliasStore', () => {
41
+ it('load/save round-trip', async () => {
42
+ const p = path.join(tmpDir, 'cfg', 'config.yaml');
43
+ const store = new AliasStore(p);
44
+ store.set('x', 'y');
45
+ await store.save();
46
+
47
+ const store2 = new AliasStore(p);
48
+ await store2.load();
49
+ expect(store2.get('x')).toBe('y');
50
+ });
51
+
52
+ it('set/get/remove', () => {
53
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
54
+ store.set('tl', 'task list');
55
+ expect(store.get('tl')).toBe('task list');
56
+ store.remove('tl');
57
+ expect(store.get('tl')).toBeUndefined();
58
+ });
59
+
60
+ it('all() returns copy', () => {
61
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
62
+ store.set('a', 'b');
63
+ const copy = store.all();
64
+ copy['a'] = 'changed';
65
+ expect(store.get('a')).toBe('b');
66
+ });
67
+
68
+ it('expand replaces first arg', () => {
69
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
70
+ store.set('tl', 'task list');
71
+ const result = store.expand(['tool', 'tl', '--mine']);
72
+ expect(result).toEqual(['tool', 'task', 'list', '--mine']);
73
+ });
74
+
75
+ it('expand no match returns original', () => {
76
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
77
+ const args = ['tool', 'task', 'show'];
78
+ expect(store.expand(args)).toEqual(args);
79
+ });
80
+
81
+ it('expand with flag defaults', () => {
82
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
83
+ store.set('dp', 'deploy --env prod --dry-run');
84
+ const result = store.expand(['tool', 'dp', 'starman']);
85
+ expect(result).toEqual(['tool', 'deploy', '--env', 'prod', '--dry-run', 'starman']);
86
+ });
87
+
88
+ it('expand preserves user override args', () => {
89
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
90
+ store.set('dp', 'deploy --env prod');
91
+ const result = store.expand(['tool', 'dp', 'starman', '--env', 'staging']);
92
+ expect(result).toEqual([
93
+ 'tool', 'deploy', '--env', 'prod', 'starman', '--env', 'staging',
94
+ ]);
95
+ });
96
+
97
+ it('expand with boolean flag defaults', () => {
98
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
99
+ store.set('dp', 'deploy --dry-run');
100
+ const result = store.expand(['tool', 'dp', 'starman', '--no-dry-run']);
101
+ expect(result).toEqual([
102
+ 'tool', 'deploy', '--dry-run', 'starman', '--no-dry-run',
103
+ ]);
104
+ });
105
+
106
+ it('expand alias no flags user adds flags', () => {
107
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
108
+ store.set('d', 'deploy');
109
+ const result = store.expand(['tool', 'd', 'starman', '--env', 'prod', '--dry-run']);
110
+ expect(result).toEqual([
111
+ 'tool', 'deploy', 'starman', '--env', 'prod', '--dry-run',
112
+ ]);
113
+ });
114
+
115
+ it('expand with empty args', () => {
116
+ const store = new AliasStore(path.join(tmpDir, 'c.yaml'));
117
+ expect(store.expand(['tool'])).toEqual(['tool']);
118
+ });
119
+
120
+ it('load from non-existent file is empty', async () => {
121
+ const store = new AliasStore('/nonexistent/x.yaml');
122
+ await store.load();
123
+ expect(store.all()).toEqual({});
124
+ });
125
+ });
126
+
127
+ // ── loadFrom / saveTo ───────────────────────────────────────
128
+
129
+ describe('loadFrom', () => {
130
+ it('reads aliases from YAML', () => {
131
+ const p = writeConfig('tl', 'task list');
132
+ const m = loadFrom(p);
133
+ expect(m['tl']).toBe('task list');
134
+ });
135
+
136
+ it('returns empty for non-existent file', () => {
137
+ const m = loadFrom('/nonexistent/config.yaml');
138
+ expect(m).toEqual({});
139
+ });
140
+
141
+ it('returns empty when no aliases key', () => {
142
+ const p = path.join(tmpDir, 'config.yaml');
143
+ fs.writeFileSync(p, 'other: value\n');
144
+ expect(loadFrom(p)).toEqual({});
145
+ });
146
+ });
147
+
148
+ describe('saveTo', () => {
149
+ it('round-trip', () => {
150
+ const p = path.join(tmpDir, 'cfg', 'config.yaml');
151
+ saveTo(p, { x: 'y' });
152
+ expect(loadFrom(p)['x']).toBe('y');
153
+ });
154
+
155
+ it('preserves other keys', () => {
156
+ const p = path.join(tmpDir, 'config.yaml');
157
+ fs.writeFileSync(p, 'other: value\n');
158
+ saveTo(p, { x: 'y' });
159
+ const data = fs.readFileSync(p, 'utf-8');
160
+ expect(data).toContain('other: value');
161
+ expect(data).toContain("x: 'y'");
162
+ });
163
+
164
+ it('empty aliases removes section', () => {
165
+ const p = path.join(tmpDir, 'config.yaml');
166
+ saveTo(p, { x: 'y' });
167
+ saveTo(p, {});
168
+ const data = fs.readFileSync(p, 'utf-8');
169
+ expect(data).not.toContain('aliases');
170
+ });
171
+ });
172
+
173
+ // ── findFirstNonFlag ────────────────────────────────────────
174
+
175
+ describe('findFirstNonFlag', () => {
176
+ const cases: Array<{ name: string; slice: string[]; idx: number; val: string }> = [
177
+ { name: 'simple', slice: ['cmd'], idx: 0, val: 'cmd' },
178
+ { name: 'short flag consumes next', slice: ['-v', 'cmd'], idx: -1, val: '' },
179
+ { name: 'flag=val', slice: ['--config=/tmp', 'cmd'], idx: 1, val: 'cmd' },
180
+ { name: 'flag val', slice: ['-c', '/tmp', 'cmd'], idx: 2, val: 'cmd' },
181
+ { name: 'only flags', slice: ['-v', '--debug'], idx: -1, val: '' },
182
+ ];
183
+
184
+ for (const tc of cases) {
185
+ it(tc.name, () => {
186
+ const [idx, val] = findFirstNonFlag(tc.slice);
187
+ expect(idx).toBe(tc.idx);
188
+ expect(val).toBe(tc.val);
189
+ });
190
+ }
191
+ });
192
+
193
+ // ── Expander ────────────────────────────────────────────────
194
+
195
+ describe('Expander', () => {
196
+ it('no match', () => {
197
+ const p = writeConfig('tl', 'task list');
198
+ const e = makeExpander(p);
199
+ const args = ['tool', 'task', 'show', 'T-0001'];
200
+ const [got, ok] = e.expand(args);
201
+ expect(ok).toBe(false);
202
+ expect(got).toEqual(args);
203
+ });
204
+
205
+ it('match', () => {
206
+ const p = writeConfig('tl', 'task list');
207
+ const e = makeExpander(p);
208
+ const [got, ok] = e.expand(['tool', 'tl']);
209
+ expect(ok).toBe(true);
210
+ expect(got).toEqual(['tool', 'task', 'list']);
211
+ });
212
+
213
+ it('match with extra args', () => {
214
+ const p = writeConfig('tl', 'task list');
215
+ const e = makeExpander(p);
216
+ const [got, ok] = e.expand(['tool', 'tl', '--status', 'OPEN']);
217
+ expect(ok).toBe(true);
218
+ expect(got).toEqual(['tool', 'task', 'list', '--status', 'OPEN']);
219
+ });
220
+
221
+ it('flag before alias', () => {
222
+ const p = writeConfig('tl', 'task list');
223
+ const e = makeExpander(p);
224
+ const [got, ok] = e.expand(['tool', '-c', '/tmp/config.yaml', 'tl']);
225
+ expect(ok).toBe(true);
226
+ expect(got).toEqual(['tool', '-c', '/tmp/config.yaml', 'task', 'list']);
227
+ });
228
+
229
+ it('empty args', () => {
230
+ const e = makeExpander('/nonexistent');
231
+ const args = ['tool'];
232
+ const [got, ok] = e.expand(args);
233
+ expect(ok).toBe(false);
234
+ expect(got).toEqual(args);
235
+ });
236
+
237
+ it('seeded alias', () => {
238
+ const e = makeExpander('/nonexistent');
239
+ const [got, ok] = e.expand(['tool', 'setup']);
240
+ expect(ok).toBe(true);
241
+ expect(got).toEqual(['tool', 'config', 'interactive']);
242
+ });
243
+
244
+ it('seeded with trailing args', () => {
245
+ const e = makeExpander('/nonexistent');
246
+ const [got, ok] = e.expand(['tool', 'setup', '--verbose']);
247
+ expect(ok).toBe(true);
248
+ expect(got).toEqual(['tool', 'config', 'interactive', '--verbose']);
249
+ });
250
+
251
+ it('expand with flag defaults in alias', () => {
252
+ const p = writeConfig('dp', 'deploy --env prod --dry-run');
253
+ const e = makeExpander(p);
254
+ const [got, ok] = e.expand(['tool', 'dp', 'starman']);
255
+ expect(ok).toBe(true);
256
+ expect(got).toEqual(['tool', 'deploy', '--env', 'prod', '--dry-run', 'starman']);
257
+ });
258
+
259
+ it('expand preserves user override of alias flag', () => {
260
+ const p = writeConfig('dp', 'deploy --env prod');
261
+ const e = makeExpander(p);
262
+ const [got, ok] = e.expand(['tool', 'dp', 'starman', '--env', 'staging']);
263
+ expect(ok).toBe(true);
264
+ expect(got).toEqual([
265
+ 'tool', 'deploy', '--env', 'prod', 'starman', '--env', 'staging',
266
+ ]);
267
+ });
268
+
269
+ it('expand with boolean flag negation', () => {
270
+ const p = writeConfig('dp', 'deploy --dry-run');
271
+ const e = makeExpander(p);
272
+ const [got, ok] = e.expand(['tool', 'dp', 'starman', '--no-dry-run']);
273
+ expect(ok).toBe(true);
274
+ expect(got).toEqual([
275
+ 'tool', 'deploy', '--dry-run', 'starman', '--no-dry-run',
276
+ ]);
277
+ });
278
+
279
+ it('load merges priority', () => {
280
+ const globalPath = path.join(tmpDir, 'global', 'config.yaml');
281
+ saveTo(globalPath, { tl: 'task list', setup: 'global-override' });
282
+
283
+ const localPath = path.join(tmpDir, 'local', 'config.yaml');
284
+ saveTo(localPath, { tl: 'task list --mine' });
285
+
286
+ const e = new Expander({
287
+ globalPath,
288
+ localPath,
289
+ seededAliases: { setup: 'config interactive' },
290
+ });
291
+
292
+ const m = e.load();
293
+ // local overrides global
294
+ expect(m['tl']).toBe('task list --mine');
295
+ // global overrides seeded
296
+ expect(m['setup']).toBe('global-override');
297
+ });
298
+
299
+ it('validateName empty', () => {
300
+ const e = makeExpander('/nonexistent');
301
+ expect(() => e.validateName('')).toThrow(/empty/);
302
+ });
303
+
304
+ it('validateName whitespace', () => {
305
+ const e = makeExpander('/nonexistent');
306
+ expect(() => e.validateName('a b')).toThrow(/whitespace/);
307
+ });
308
+
309
+ it('validateName builtin', () => {
310
+ const e = makeExpander('/nonexistent');
311
+ expect(() => e.validateName('task')).toThrow(/conflicts/);
312
+ });
313
+
314
+ it('validateName ok', () => {
315
+ const e = makeExpander('/nonexistent');
316
+ expect(() => e.validateName('tl')).not.toThrow();
317
+ });
318
+ });
319
+
320
+ // ── findCommand ─────────────────────────────────────────────
321
+
322
+ describe('findCommand', () => {
323
+ it('finds top-level command', () => {
324
+ const program = new Command('test');
325
+ program.command('deploy').description('Deploy');
326
+ const cmd = findCommand(program, 'deploy');
327
+ expect(cmd?.name()).toBe('deploy');
328
+ });
329
+
330
+ it('finds nested command', () => {
331
+ const program = new Command('test');
332
+ const task = program.command('task').description('Tasks');
333
+ task.command('list').description('List tasks');
334
+ const cmd = findCommand(program, 'task list');
335
+ expect(cmd?.name()).toBe('list');
336
+ });
337
+
338
+ it('returns undefined for missing command', () => {
339
+ const program = new Command('test');
340
+ program.command('deploy').description('Deploy');
341
+ expect(findCommand(program, 'build')).toBeUndefined();
342
+ });
343
+
344
+ it('returns undefined for partial nested path', () => {
345
+ const program = new Command('test');
346
+ program.command('task').description('Tasks');
347
+ expect(findCommand(program, 'task list')).toBeUndefined();
348
+ });
349
+ });
350
+
351
+ // ── bridgeAliases ───────────────────────────────────────────
352
+
353
+ describe('bridgeAliases', () => {
354
+ it('registers alias on target command', () => {
355
+ const program = new Command('test');
356
+ program.command('deploy').description('Deploy');
357
+ const store = new AliasStore('/dev/null');
358
+ store.set('d', 'deploy');
359
+ bridgeAliases(program, store);
360
+
361
+ const deploy = program.commands.find(c => c.name() === 'deploy');
362
+ expect(deploy?.aliases()).toContain('d');
363
+ });
364
+
365
+ it('registers multiple aliases on same target', () => {
366
+ const program = new Command('test');
367
+ program.command('deploy').description('Deploy');
368
+ const store = new AliasStore('/dev/null');
369
+ store.set('d', 'deploy');
370
+ store.set('dp', 'deploy');
371
+ bridgeAliases(program, store);
372
+
373
+ const deploy = program.commands.find(c => c.name() === 'deploy');
374
+ expect(deploy?.aliases()).toContain('d');
375
+ expect(deploy?.aliases()).toContain('dp');
376
+ });
377
+
378
+ it('adds hidden proxy for multi-word alias target', () => {
379
+ const program = new Command('test');
380
+ const task = program.command('task').description('Tasks');
381
+ task.command('list').description('List tasks');
382
+ const store = new AliasStore('/dev/null');
383
+ store.set('tl', 'task list');
384
+ bridgeAliases(program, store);
385
+
386
+ // multi-word target => proxy command added at top level
387
+ const proxy = program.commands.find(c => c.name() === 'tl');
388
+ expect(proxy).toBeDefined();
389
+ expect(proxy?.description()).toBe('Alias for task list');
390
+ });
391
+
392
+ it('adds hidden proxy for unknown target', () => {
393
+ const program = new Command('test');
394
+ const store = new AliasStore('/dev/null');
395
+ store.set('x', 'nonexistent');
396
+ bridgeAliases(program, store);
397
+
398
+ const proxy = program.commands.find(c => c.name() === 'x');
399
+ expect(proxy).toBeDefined();
400
+ });
401
+
402
+ it('preserves existing aliases on target command', () => {
403
+ const program = new Command('test');
404
+ const deploy = program.command('deploy').description('Deploy');
405
+ deploy.alias('dep');
406
+ const store = new AliasStore('/dev/null');
407
+ store.set('d', 'deploy');
408
+ bridgeAliases(program, store);
409
+
410
+ expect(deploy.aliases()).toContain('dep');
411
+ expect(deploy.aliases()).toContain('d');
412
+ });
413
+
414
+ it('empty store is a no-op', () => {
415
+ const program = new Command('test');
416
+ program.command('deploy').description('Deploy');
417
+ const store = new AliasStore('/dev/null');
418
+ bridgeAliases(program, store);
419
+
420
+ const deploy = program.commands.find(c => c.name() === 'deploy');
421
+ expect(deploy?.aliases()).toEqual([]);
422
+ });
423
+ });
package/src/alias.ts ADDED
@@ -0,0 +1,256 @@
1
+ /**
2
+ * alias.ts — YAML-file-based command alias expansion.
3
+ *
4
+ * Port of Go's cli/alias package. Aliases live in per-tool YAML
5
+ * config files with three-tier priority: seeded < global < local.
6
+ */
7
+
8
+ import * as fs from 'fs';
9
+ import * as path from 'path';
10
+ import * as yaml from 'js-yaml';
11
+ import { Command } from 'commander';
12
+
13
+ export type AliasMap = Record<string, string>;
14
+
15
+ export interface ExpanderConfig {
16
+ globalPath: string;
17
+ localPath: string;
18
+ seededAliases?: AliasMap;
19
+ builtins?: Set<string>;
20
+ }
21
+
22
+ // ── Low-level helpers ───────────────────────────────────────
23
+
24
+ /** Read aliases from a single YAML config file. */
25
+ export function loadFrom(filePath: string): AliasMap {
26
+ let data: string;
27
+ try {
28
+ data = fs.readFileSync(filePath, 'utf-8');
29
+ } catch {
30
+ return {};
31
+ }
32
+
33
+ const raw = yaml.load(data) as Record<string, unknown> | null;
34
+ if (!raw || typeof raw !== 'object' || !raw['aliases']) return {};
35
+ return raw['aliases'] as AliasMap;
36
+ }
37
+
38
+ /** Write aliases into a YAML config file, preserving other keys. */
39
+ export function saveTo(filePath: string, aliases: AliasMap): void {
40
+ fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o750 });
41
+
42
+ let existing: Record<string, unknown> = {};
43
+ try {
44
+ const data = fs.readFileSync(filePath, 'utf-8');
45
+ existing = (yaml.load(data) as Record<string, unknown>) ?? {};
46
+ } catch {
47
+ // file doesn't exist yet
48
+ }
49
+
50
+ if (Object.keys(aliases).length === 0) {
51
+ delete existing['aliases'];
52
+ } else {
53
+ existing['aliases'] = { ...aliases };
54
+ }
55
+
56
+ fs.writeFileSync(filePath, yaml.dump(existing), { mode: 0o600 });
57
+ }
58
+
59
+ /**
60
+ * Find the first non-flag element in a slice.
61
+ * Returns [index, value]. Flags with `=` are self-contained;
62
+ * short flags without `=` consume the next element as their value.
63
+ */
64
+ export function findFirstNonFlag(
65
+ slice: string[],
66
+ ): [number, string] {
67
+ for (let i = 0; i < slice.length; i++) {
68
+ const a = slice[i];
69
+ if (!a.startsWith('-')) return [i, a];
70
+ if (a.includes('=')) continue;
71
+ // short/long flag consumes next arg as its value
72
+ if (i + 1 < slice.length && !slice[i + 1].startsWith('-')) {
73
+ i++;
74
+ }
75
+ }
76
+ return [-1, ''];
77
+ }
78
+
79
+ // ── AliasStore ──────────────────────────────────────────────
80
+
81
+ /**
82
+ * Simple single-file alias store with load/save, set/get/remove,
83
+ * and first-arg expansion.
84
+ */
85
+ export class AliasStore {
86
+ private filePath: string;
87
+ private aliases: AliasMap = {};
88
+
89
+ constructor(filePath: string) {
90
+ this.filePath = filePath;
91
+ }
92
+
93
+ load(): void {
94
+ this.aliases = loadFrom(this.filePath);
95
+ }
96
+
97
+ save(): void {
98
+ saveTo(this.filePath, this.aliases);
99
+ }
100
+
101
+ set(name: string, target: string): void {
102
+ this.aliases[name] = target;
103
+ }
104
+
105
+ remove(name: string): void {
106
+ delete this.aliases[name];
107
+ }
108
+
109
+ get(name: string): string | undefined {
110
+ return this.aliases[name];
111
+ }
112
+
113
+ /** Returns a shallow copy. */
114
+ all(): AliasMap {
115
+ return { ...this.aliases };
116
+ }
117
+
118
+ /** Expand first arg if it matches an alias. */
119
+ expand(args: string[]): string[] {
120
+ if (args.length < 2) return args;
121
+
122
+ const candidate = args[1];
123
+ const expansion = this.aliases[candidate];
124
+ if (!expansion) return args;
125
+
126
+ const parts = expansion.split(/\s+/);
127
+ return [args[0], ...parts, ...args.slice(2)];
128
+ }
129
+ }
130
+
131
+ // ── Expander (multi-file, three-tier) ───────────────────────
132
+
133
+ /**
134
+ * Three-tier alias expander matching Go's Expander.
135
+ * Priority: seeded < global < local.
136
+ */
137
+ export class Expander {
138
+ private cfg: ExpanderConfig;
139
+
140
+ constructor(cfg: ExpanderConfig) {
141
+ this.cfg = cfg;
142
+ }
143
+
144
+ /** Merged alias map (seeded < global < local). */
145
+ load(): AliasMap {
146
+ const merged: AliasMap = {};
147
+
148
+ // seeded (lowest priority)
149
+ if (this.cfg.seededAliases) {
150
+ Object.assign(merged, this.cfg.seededAliases);
151
+ }
152
+
153
+ // global overrides seeded
154
+ const global = loadFrom(this.cfg.globalPath);
155
+ Object.assign(merged, global);
156
+
157
+ // local overrides global
158
+ const local = loadFrom(this.cfg.localPath);
159
+ Object.assign(merged, local);
160
+
161
+ return merged;
162
+ }
163
+
164
+ /**
165
+ * Rewrite args if args[1] (or first non-flag arg) matches
166
+ * an alias. Returns [rewrittenArgs, wasExpanded].
167
+ */
168
+ expand(args: string[]): [string[], boolean] {
169
+ if (args.length < 2) return [args, false];
170
+
171
+ const aliases = this.load();
172
+ if (Object.keys(aliases).length === 0) return [args, false];
173
+
174
+ const [firstNonFlag, candidate] = findFirstNonFlag(args.slice(1));
175
+ if (candidate === '') return [args, false];
176
+
177
+ const expansion = aliases[candidate];
178
+ if (!expansion) return [args, false];
179
+
180
+ const parts = expansion.split(/\s+/);
181
+ const prefix = args.slice(1, 1 + firstNonFlag);
182
+ const suffix = args.slice(1 + firstNonFlag + 1);
183
+
184
+ const result = [args[0], ...prefix, ...parts, ...suffix];
185
+ return [result, true];
186
+ }
187
+
188
+ /** Reject names that shadow builtins or contain whitespace. */
189
+ validateName(name: string): void {
190
+ if (name === '') {
191
+ throw new Error('alias name must not be empty');
192
+ }
193
+ if (/\s/.test(name)) {
194
+ throw new Error('alias name must not contain whitespace');
195
+ }
196
+ if (this.cfg.builtins?.has(name)) {
197
+ throw new Error(`alias "${name}" conflicts with a built-in command`);
198
+ }
199
+ }
200
+ }
201
+
202
+ // ── Commander bridge ────────────────────────────────────────
203
+
204
+ /** Walk the Commander program tree to find a command by space-delimited path. */
205
+ export function findCommand(
206
+ program: Command,
207
+ cmdPath: string,
208
+ ): Command | undefined {
209
+ const parts = cmdPath.split(' ');
210
+ let cmd: Command | undefined = program;
211
+ for (const part of parts) {
212
+ cmd = cmd?.commands.find(c => c.name() === part);
213
+ if (!cmd) return undefined;
214
+ }
215
+ return cmd;
216
+ }
217
+
218
+ /**
219
+ * Register loaded aliases with Commander's native .alias() API.
220
+ *
221
+ * Simple single-command aliases use Commander's built-in .alias(),
222
+ * giving free completion and help display. Multi-word or unresolved
223
+ * targets get a hidden proxy command that re-parses with expanded args.
224
+ */
225
+ export function bridgeAliases(
226
+ program: Command,
227
+ store: AliasStore,
228
+ ): void {
229
+ const all = store.all();
230
+ for (const [name, target] of Object.entries(all)) {
231
+ const parts = target.split(/\s+/);
232
+ // simple alias: single word target that exists as a direct subcommand
233
+ if (parts.length === 1) {
234
+ const targetCmd = findCommand(program, target);
235
+ if (targetCmd) {
236
+ targetCmd.alias(name);
237
+ continue;
238
+ }
239
+ }
240
+
241
+ // multi-word target or unknown command: hidden proxy
242
+ const proxy = new Command(name)
243
+ .description(`Alias for ${target}`)
244
+ .allowUnknownOption(true)
245
+ .allowExcessArguments(true)
246
+ .action(function (this: Command) {
247
+ const expanded = target.split(/\s+/);
248
+ program.parse([
249
+ 'node', program.name(), ...expanded, ...this.args,
250
+ ]);
251
+ });
252
+ proxy.helpOption(false);
253
+ (proxy as any)._hidden = true;
254
+ program.addCommand(proxy);
255
+ }
256
+ }