@hop-top/kit 0.5.0-alpha.6 → 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.
Files changed (72) hide show
  1. package/CHANGELOG.md +52 -0
  2. package/LICENSE-cobra.txt +174 -0
  3. package/NOTICE +15 -0
  4. package/README.md +3 -3
  5. package/dist/alias-D9_qFlyP.d.ts +174 -0
  6. package/dist/alias.d.ts +1 -1
  7. package/dist/alias.js +10 -2
  8. package/dist/chunk-263IZ6Z6.js +915 -0
  9. package/dist/{chunk-S45UHXQF.js → chunk-BLS2OBIQ.js} +106 -25
  10. package/dist/{chunk-7FDIN5KE.js → chunk-GHPJJV5L.js} +8 -4
  11. package/dist/chunk-JKMQSAJP.js +174 -0
  12. package/dist/chunk-JZ22ZUFA.js +1131 -0
  13. package/dist/{chunk-GAZPYCQD.js → chunk-NLMS7HGP.js} +93 -35
  14. package/dist/chunk-QQQYCWSC.js +240 -0
  15. package/dist/chunk-XJTRY453.js +868 -0
  16. package/dist/cli.js +6 -4
  17. package/dist/completion-csVun6SP.d.ts +112 -0
  18. package/dist/completion-values-By-mnjNt.d.ts +142 -0
  19. package/dist/completion-values.d.ts +1 -0
  20. package/dist/completion-values.js +29 -0
  21. package/dist/completion.d.ts +2 -1
  22. package/dist/completion.js +23 -2
  23. package/dist/compliance-AxFf-uMy.d.ts +60 -0
  24. package/dist/compliance.d.ts +1 -0
  25. package/dist/compliance.js +17 -0
  26. package/dist/config-CaK60ByQ.d.ts +241 -0
  27. package/dist/config.d.ts +1 -1
  28. package/dist/config.js +4 -2
  29. package/dist/index.d.ts +7 -5
  30. package/dist/index.js +26 -18
  31. package/dist/log-CkaxMX3U.d.ts +115 -0
  32. package/dist/log.d.ts +1 -1
  33. package/dist/log.js +2 -2
  34. package/dist/toolspec-UrWnoJ3Y.d.ts +336 -0
  35. package/dist/toolspec.d.ts +2 -1
  36. package/dist/toolspec.js +27 -2
  37. package/package.json +19 -3
  38. package/src/alias.conformance.test.ts +250 -0
  39. package/src/alias.test.ts +206 -2
  40. package/src/alias.ts +196 -21
  41. package/src/cli.ts +5 -0
  42. package/src/completion-scripts.ts +16 -0
  43. package/src/completion-values.test.ts +70 -10
  44. package/src/completion-values.ts +170 -66
  45. package/src/completion.conformance.test.ts +297 -0
  46. package/src/completion.test.ts +256 -145
  47. package/src/completion.ts +767 -121
  48. package/src/config-merge.test.ts +425 -0
  49. package/src/config.test.ts +41 -0
  50. package/src/config.ts +265 -18
  51. package/src/index.test.ts +2 -1
  52. package/src/index.ts +5 -1
  53. package/src/log.test.ts +270 -1
  54. package/src/log.ts +172 -44
  55. package/src/published-types.test.ts +18 -0
  56. package/src/toolspec-internal.ts +197 -0
  57. package/src/toolspec-manifest.test.ts +82 -0
  58. package/src/toolspec-manifest.ts +404 -0
  59. package/src/toolspec-spec-schemas.ts +12 -0
  60. package/src/toolspec-spec.test.ts +273 -0
  61. package/src/toolspec-spec.ts +458 -0
  62. package/src/toolspec.from-command.test.ts +216 -0
  63. package/src/toolspec.ts +159 -0
  64. package/test/toolspec/fixture.ts +73 -0
  65. package/dist/alias-BOj0-VAr.d.ts +0 -88
  66. package/dist/chunk-6RFRV4VP.js +0 -128
  67. package/dist/chunk-IQXEISMC.js +0 -142
  68. package/dist/chunk-W7ERKNSQ.js +0 -171
  69. package/dist/completion-CVnPcWMZ.d.ts +0 -32
  70. package/dist/config-Bm9fBXch.d.ts +0 -134
  71. package/dist/log-uKjHsK-c.d.ts +0 -62
  72. package/dist/toolspec-DPBr18Ub.d.ts +0 -106
@@ -8,6 +8,9 @@ import {
8
8
  configKeysCompleter,
9
9
  fileCompleter,
10
10
  dirCompleter,
11
+ resolveCompletions,
12
+ directiveName,
13
+ ShellCompDirective,
11
14
  type CompletionItem,
12
15
  } from './completion-values';
13
16
 
@@ -84,7 +87,7 @@ describe('prefixedCompleter', () => {
84
87
  const inner = staticValues('a', 'b');
85
88
  const c = prefixedCompleter('env', inner);
86
89
  const result = c.complete('');
87
- expect(result).toEqual([{ value: 'env:', description: 'env:...' }]);
90
+ expect(result).toEqual([{ value: 'env:', description: 'env values' }]);
88
91
  });
89
92
 
90
93
  it('completes values after colon', () => {
@@ -129,6 +132,14 @@ describe('configKeysCompleter', () => {
129
132
  expect(values).toContain('db.port');
130
133
  });
131
134
 
135
+ it('returns leaf keys only, lowercased', async () => {
136
+ const c = configKeysCompleter({ Server: { Port: 1 }, tags: ['a'] });
137
+ const values = (await c.complete('')).map((i: CompletionItem) => i.value);
138
+ expect(values).toEqual(['server.port', 'tags']);
139
+ expect((await c.complete('SER')).map((i: CompletionItem) => i.value))
140
+ .toEqual(['server.port']);
141
+ });
142
+
132
143
  it('filters by prefix', async () => {
133
144
  const c = configKeysCompleter({ name: 'x', namespace: 'y', version: '1' });
134
145
  const items = await c.complete('na');
@@ -138,21 +149,70 @@ describe('configKeysCompleter', () => {
138
149
  });
139
150
 
140
151
  describe('fileCompleter', () => {
141
- it('returns items with value field', async () => {
152
+ it('returns its extensions and filters by extension', async () => {
142
153
  const c = fileCompleter('.ts', '.js');
143
- const items = await c.complete('');
144
- // file completer returns a marker item for shell-level file completion
145
- expect(items.length).toBeGreaterThanOrEqual(1);
146
- expect(items[0]).toHaveProperty('value');
154
+ expect(await c.complete('')).toEqual([{ value: '.ts' }, { value: '.js' }]);
155
+ expect(await resolveCompletions(c, 'x')).toEqual({
156
+ completions: ['.ts', '.js'], directive: ShellCompDirective.FilterFileExt,
157
+ });
158
+ });
159
+
160
+ it('without extensions falls back to default completion', async () => {
161
+ expect(await resolveCompletions(fileCompleter(), '')).toEqual({
162
+ completions: [], directive: ShellCompDirective.Default,
163
+ });
147
164
  });
148
165
  });
149
166
 
150
167
  describe('dirCompleter', () => {
151
- it('returns items with value field', async () => {
168
+ it('completes directories only', async () => {
152
169
  const c = dirCompleter();
153
- const items = await c.complete('');
154
- expect(items.length).toBeGreaterThanOrEqual(1);
155
- expect(items[0]).toHaveProperty('value');
170
+ expect(await c.complete('')).toEqual([]);
171
+ expect(await resolveCompletions(c, 'src')).toEqual({
172
+ completions: [], directive: ShellCompDirective.FilterDirs,
173
+ });
174
+ });
175
+ });
176
+
177
+ describe('resolveCompletions', () => {
178
+ it('joins descriptions with a tab and completes no files', async () => {
179
+ const c = staticCompleter({ value: 'a', description: 'A' }, { value: 'b' });
180
+ expect(await resolveCompletions(c, '')).toEqual({
181
+ completions: ['a\tA', 'b'], directive: ShellCompDirective.NoFileComp,
182
+ });
183
+ });
184
+
185
+ it('turns a thrown or rejected completer into the error directive', async () => {
186
+ const sync = funcCompleter(() => { throw new Error('down'); });
187
+ const rejected = funcCompleter(async () => { throw new Error('down'); });
188
+ for (const c of [sync, rejected, prefixedCompleter('env', rejected)]) {
189
+ expect(await resolveCompletions(c, 'env:')).toEqual({
190
+ completions: [], directive: ShellCompDirective.Error,
191
+ });
192
+ }
193
+ });
194
+
195
+ it('passes the context through to the completer', async () => {
196
+ let seen;
197
+ const c = funcCompleter((_p, ctx) => { seen = ctx; return []; });
198
+ await resolveCompletions(c, '', { commandPath: 'deploy', args: ['x'] });
199
+ expect(seen).toEqual({ commandPath: 'deploy', args: ['x'] });
200
+ });
201
+
202
+ it('awaits async inner completers of prefixed', async () => {
203
+ const c = prefixedCompleter('env', funcCompleter(async () => [{ value: 'prod' }]));
204
+ expect(await resolveCompletions(c, 'env:')).toEqual({
205
+ completions: ['env:prod'], directive: ShellCompDirective.NoFileComp,
206
+ });
207
+ });
208
+ });
209
+
210
+ describe('directiveName', () => {
211
+ it('names cobra directives', () => {
212
+ expect(directiveName(0)).toBe('ShellCompDirectiveDefault');
213
+ expect(directiveName(4)).toBe('ShellCompDirectiveNoFileComp');
214
+ expect(directiveName(6)).toBe('ShellCompDirectiveNoSpace, ShellCompDirectiveNoFileComp');
215
+ expect(directiveName(64)).toBe('ERROR: unexpected ShellCompDirective value: 64');
156
216
  });
157
217
  });
158
218
 
@@ -2,10 +2,28 @@
2
2
  * @module completion-values
3
3
  * @package @hop-top/kit
4
4
  *
5
- * Dynamic value completion system for Commander-based CLIs.
6
- * Provides a Completer interface and built-in completers for
7
- * flags and positional arguments. Shell scripts (from completion.ts)
8
- * call back via __complete; the registry resolves the right completer.
5
+ * Dynamic value completion for Commander-based CLIs. Ports Go
6
+ * `console/cli/completion`; behaviour is pinned by
7
+ * `contracts/completion-v1/completers.json`.
8
+ *
9
+ * A {@link Completer} turns the word being completed into
10
+ * {@link CompletionItem}s. `bindFlag` / `bindArgs` (in `completion`)
11
+ * attach one to a flag or to a command's positional arguments; the
12
+ * scripts `completion <shell>` writes call back into the program's
13
+ * hidden `__complete` entry point, which runs the bound completer and
14
+ * prints the result through {@link resolveCompletions} in cobra's wire
15
+ * format.
16
+ *
17
+ * Contract:
18
+ * - Prefix matching in static, config-key and the dimension half of
19
+ * prefixed completers is case-insensitive; an empty prefix returns
20
+ * every item. {@link funcCompleter} sees the raw prefix, unfiltered.
21
+ * - A completer fails by throwing (or rejecting); the bridge turns that
22
+ * into {@link ShellCompDirective.Error}.
23
+ * - {@link fileCompleter} and {@link dirCompleter} yield a directive,
24
+ * not suggestions: filter by extension (the extensions travel as the
25
+ * completions), directories only, or plain file completion when no
26
+ * extension is given.
9
27
  */
10
28
 
11
29
  export interface CompletionItem {
@@ -13,10 +31,102 @@ export interface CompletionItem {
13
31
  description?: string;
14
32
  }
15
33
 
34
+ /** What a completer knows about the command line it completes. */
35
+ export interface CompletionContext {
36
+ /** Space-separated path of the command below the root; empty for the root. */
37
+ commandPath: string;
38
+ /** Positional arguments already given, flags removed. */
39
+ args: string[];
40
+ }
41
+
42
+ /** What a file completer asks the shell for. */
43
+ export type FileFilter =
44
+ | { kind: 'extensions'; extensions: string[] }
45
+ | { kind: 'dirs' };
46
+
16
47
  export interface Completer {
17
- complete(prefix: string): CompletionItem[] | Promise<CompletionItem[]>;
48
+ complete(
49
+ prefix: string,
50
+ ctx?: CompletionContext,
51
+ ): CompletionItem[] | Promise<CompletionItem[]>;
52
+ /** Set by {@link fileCompleter} and {@link dirCompleter}. */
53
+ readonly fileFilter?: FileFilter;
54
+ }
55
+
56
+ /** cobra's shell directive bits, read by the scripts from the `:<n>` line. */
57
+ export const ShellCompDirective = {
58
+ Default: 0,
59
+ Error: 1,
60
+ NoSpace: 2,
61
+ NoFileComp: 4,
62
+ FilterFileExt: 8,
63
+ FilterDirs: 16,
64
+ KeepOrder: 32,
65
+ } as const;
66
+
67
+ /** cobra's name for a directive, as printed on stderr after a request. */
68
+ export function directiveName(d: number): string {
69
+ if (d >= 64) return `ERROR: unexpected ShellCompDirective value: ${d}`;
70
+ const names: [number, string][] = [
71
+ [ShellCompDirective.Error, 'ShellCompDirectiveError'],
72
+ [ShellCompDirective.NoSpace, 'ShellCompDirectiveNoSpace'],
73
+ [ShellCompDirective.NoFileComp, 'ShellCompDirectiveNoFileComp'],
74
+ [ShellCompDirective.FilterFileExt, 'ShellCompDirectiveFilterFileExt'],
75
+ [ShellCompDirective.FilterDirs, 'ShellCompDirectiveFilterDirs'],
76
+ [ShellCompDirective.KeepOrder, 'ShellCompDirectiveKeepOrder'],
77
+ ];
78
+ const set = names.filter(([bit]) => (d & bit) === bit).map(([, n]) => n);
79
+ return set.length ? set.join(', ') : 'ShellCompDirectiveDefault';
80
+ }
81
+
82
+ /** Completions in wire form plus the directive. */
83
+ export interface ResolvedCompletions {
84
+ /** `value`, or `value\tdescription` when there is one. */
85
+ completions: string[];
86
+ directive: number;
87
+ }
88
+
89
+ /**
90
+ * Runs `c` for `toComplete` and converts the result to the shell wire
91
+ * format: values with any description joined by a tab, plus the
92
+ * directive (no file completion on success, error when `c` fails).
93
+ */
94
+ export async function resolveCompletions(
95
+ c: Completer,
96
+ toComplete: string,
97
+ ctx: CompletionContext = { commandPath: '', args: [] },
98
+ ): Promise<ResolvedCompletions> {
99
+ const f = c.fileFilter;
100
+ if (f?.kind === 'dirs') {
101
+ return { completions: [], directive: ShellCompDirective.FilterDirs };
102
+ }
103
+ if (f?.kind === 'extensions') {
104
+ // An empty filter list would filter every candidate out.
105
+ return f.extensions.length === 0
106
+ ? { completions: [], directive: ShellCompDirective.Default }
107
+ : { completions: [...f.extensions], directive: ShellCompDirective.FilterFileExt };
108
+ }
109
+ try {
110
+ const items = await c.complete(toComplete, ctx);
111
+ return {
112
+ completions: items.map(withDescription),
113
+ directive: ShellCompDirective.NoFileComp,
114
+ };
115
+ } catch {
116
+ return { completions: [], directive: ShellCompDirective.Error };
117
+ }
118
+ }
119
+
120
+ /** `value`, or `value\tdescription` when there is one. */
121
+ export function withDescription(i: CompletionItem): string {
122
+ return i.description ? `${i.value}\t${i.description}` : i.value;
18
123
  }
19
124
 
125
+ /**
126
+ * Maps flag names and argument positions to completers, for sharing
127
+ * completers across a command tree (Go `Registry`). A lookup table
128
+ * only: `bindFlag` / `bindArgs` wire a completer into completion.
129
+ */
20
130
  export class CompletionRegistry {
21
131
  private flags = new Map<string, Completer>();
22
132
  private args = new Map<string, Completer>();
@@ -38,12 +148,12 @@ export class CompletionRegistry {
38
148
  }
39
149
  }
40
150
 
41
- /** Filter items by case-insensitive prefix match. */
151
+ /** Filter items by case-insensitive prefix match; keeps duplicates. */
42
152
  function filterByPrefix(
43
153
  items: CompletionItem[],
44
154
  prefix: string,
45
155
  ): CompletionItem[] {
46
- if (!prefix) return items;
156
+ if (!prefix) return [...items];
47
157
  const lp = prefix.toLowerCase();
48
158
  return items.filter(i => i.value.toLowerCase().startsWith(lp));
49
159
  }
@@ -65,109 +175,103 @@ export function staticValues(...values: string[]): Completer {
65
175
  return staticCompleter(...items);
66
176
  }
67
177
 
68
- /** Completer backed by a callback function. */
178
+ /**
179
+ * Completer backed by a callback. The callback sees the raw prefix;
180
+ * nothing is filtered for it. Throw (or reject) to fail.
181
+ */
69
182
  export function funcCompleter(
70
- fn: (prefix: string) => CompletionItem[],
183
+ fn: (
184
+ prefix: string,
185
+ ctx: CompletionContext,
186
+ ) => CompletionItem[] | Promise<CompletionItem[]>,
71
187
  ): Completer {
72
- return { complete: fn };
188
+ return {
189
+ complete(prefix, ctx = { commandPath: '', args: [] }) {
190
+ return fn(prefix, ctx);
191
+ },
192
+ };
73
193
  }
74
194
 
75
195
  /**
76
- * Completer for dimensioned values like `env:prod`.
77
- * Before the colon, suggests the dimension prefix.
78
- * After the colon, delegates to the inner completer.
196
+ * Completer for dimensioned values like `env:prod`. While no colon is
197
+ * typed it suggests `dimension:` (matched case-insensitively); after
198
+ * the first colon it delegates the rest to `values` and re-prepends
199
+ * the declared `dimension:`.
79
200
  */
80
201
  export function prefixedCompleter(
81
202
  dimension: string,
82
203
  values: Completer,
83
204
  ): Completer {
205
+ const lower = dimension.toLowerCase();
206
+ const prepend = (items: CompletionItem[]) =>
207
+ items.map(i => {
208
+ const v = `${dimension}:${i.value}`;
209
+ return i.description ? { value: v, description: i.description } : { value: v };
210
+ });
84
211
  return {
85
- complete(prefix: string) {
212
+ complete(prefix, ctx) {
86
213
  const colonIdx = prefix.indexOf(':');
87
214
  if (colonIdx < 0) {
88
- // no colon yet — suggest dimension prefix
89
- return [{ value: `${dimension}:`, description: `${dimension}:...` }];
90
- }
91
-
92
- const dim = prefix.slice(0, colonIdx);
93
- if (dim !== dimension) return [];
94
-
95
- const valPrefix = prefix.slice(colonIdx + 1);
96
- const inner = values.complete(valPrefix);
97
- if (Array.isArray(inner)) {
98
- return inner.map(i => ({
99
- value: `${dimension}:${i.value}`,
100
- description: i.description,
101
- }));
215
+ const dim = `${dimension}:`;
216
+ return dim.toLowerCase().startsWith(prefix.toLowerCase())
217
+ ? [{ value: dim, description: `${dimension} values` }]
218
+ : [];
102
219
  }
103
- // async path
104
- return (inner as Promise<CompletionItem[]>).then(items =>
105
- items.map(i => ({
106
- value: `${dimension}:${i.value}`,
107
- description: i.description,
108
- })),
109
- );
220
+ if (prefix.slice(0, colonIdx).toLowerCase() !== lower) return [];
221
+ const inner = values.complete(prefix.slice(colonIdx + 1), ctx);
222
+ return Array.isArray(inner) ? prepend(inner) : inner.then(prepend);
110
223
  },
111
224
  };
112
225
  }
113
226
 
114
- /** Flatten object keys into dot-notation paths. */
115
- function flattenKeys(
116
- obj: Record<string, any>,
117
- prefix = '',
118
- ): string[] {
119
- const keys: string[] = [];
227
+ /** The dotted leaf keys of a config tree, lowercased like viper's AllKeys. */
228
+ function leafKeys(obj: Record<string, unknown>, prefix: string, out: Set<string>): void {
120
229
  for (const [k, v] of Object.entries(obj)) {
121
- const full = prefix ? `${prefix}.${k}` : k;
122
- keys.push(full);
230
+ const full = prefix ? `${prefix}.${k.toLowerCase()}` : k.toLowerCase();
123
231
  if (v != null && typeof v === 'object' && !Array.isArray(v)) {
124
- keys.push(...flattenKeys(v, full));
232
+ leafKeys(v as Record<string, unknown>, full, out);
233
+ } else {
234
+ out.add(full);
125
235
  }
126
236
  }
127
- return keys;
128
237
  }
129
238
 
130
- /** Completer that suggests config keys in dot-notation. */
239
+ /**
240
+ * Completer that suggests config keys: the dotted leaf keys of
241
+ * `config`, lowercased, matched case-insensitively.
242
+ */
131
243
  export function configKeysCompleter(
132
- config: Record<string, any>,
244
+ config: Record<string, unknown>,
133
245
  ): Completer {
134
246
  return {
135
247
  complete(prefix: string) {
136
- const all = flattenKeys(config);
137
- return filterByPrefix(
138
- all.map(k => ({ value: k })),
139
- prefix,
140
- );
248
+ const keys = new Set<string>();
249
+ leafKeys(config, '', keys);
250
+ return filterByPrefix([...keys].map(k => ({ value: k })), prefix);
141
251
  },
142
252
  };
143
253
  }
144
254
 
145
255
  /**
146
- * Completer that signals shell-level file completion.
147
- * Returns a marker item; the __complete handler translates
148
- * this to shell-native file glob directives.
256
+ * Completer that asks the shell for files with these extensions (e.g.
257
+ * `.yaml`); none means any file. Its items are the extensions, which
258
+ * travel as the completions of a filter-by-extension directive.
149
259
  */
150
260
  export function fileCompleter(...extensions: string[]): Completer {
151
- const desc = extensions.length
152
- ? `Files: ${extensions.join(', ')}`
153
- : 'Files';
154
261
  return {
262
+ fileFilter: { kind: 'extensions', extensions: [...extensions] },
155
263
  complete() {
156
- return [
157
- {
158
- value: '__file__',
159
- description: desc,
160
- },
161
- ];
264
+ return extensions.map(e => ({ value: e }));
162
265
  },
163
266
  };
164
267
  }
165
268
 
166
- /** Completer that signals shell-level directory completion. */
269
+ /** Completer that asks the shell for directories only. */
167
270
  export function dirCompleter(): Completer {
168
271
  return {
272
+ fileFilter: { kind: 'dirs' },
169
273
  complete() {
170
- return [{ value: '__dir__', description: 'Directories' }];
274
+ return [];
171
275
  },
172
276
  };
173
277
  }