@kjanat/dreamcli 3.0.0-rc.1 → 3.0.0-rc.3

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 (137) hide show
  1. package/CHANGELOG.md +37 -1
  2. package/dist/core/cli/dispatch.mjs +214 -1
  3. package/dist/core/cli/help-links.mjs +41 -1
  4. package/dist/core/cli/index.mjs +901 -1
  5. package/dist/core/cli/planner.mjs +300 -1
  6. package/dist/core/cli/plugin.mjs +41 -1
  7. package/dist/core/cli/propagate.mjs +57 -1
  8. package/dist/core/cli/root-help.mjs +208 -4
  9. package/dist/core/cli/root-surface.mjs +27 -1
  10. package/dist/core/cli/runtime-preflight.mjs +168 -1
  11. package/dist/core/completion/index.mjs +90 -1
  12. package/dist/core/completion/shells/bash.mjs +304 -3
  13. package/dist/core/completion/shells/fish.mjs +159 -2
  14. package/dist/core/completion/shells/powershell.mjs +353 -2
  15. package/dist/core/completion/shells/shared.mjs +154 -1
  16. package/dist/core/completion/shells/zsh.mjs +244 -2
  17. package/dist/core/config/index.mjs +246 -1
  18. package/dist/core/config/package-json.mjs +385 -3
  19. package/dist/core/errors/index.mjs +87 -1
  20. package/dist/core/execution/index.mjs +189 -1
  21. package/dist/core/help/ansi.mjs +122 -2
  22. package/dist/core/help/index.mjs +329 -7
  23. package/dist/core/json-schema/index.mjs +487 -9
  24. package/dist/core/json-schema/meta-descriptions.generated.mjs +93 -28
  25. package/dist/core/output/activity.mjs +452 -1
  26. package/dist/core/output/bind.mjs +56 -1
  27. package/dist/core/output/contracts.mjs +57 -1
  28. package/dist/core/output/display-value.mjs +32 -1
  29. package/dist/core/output/index.d.mts +21 -0
  30. package/dist/core/output/index.mjs +442 -2
  31. package/dist/core/output/renderers.mjs +46 -1
  32. package/dist/core/output/writer.mjs +12 -1
  33. package/dist/core/parse/index.mjs +555 -1
  34. package/dist/core/prompt/index.d.mts +0 -1
  35. package/dist/core/prompt/index.mjs +348 -6
  36. package/dist/core/resolve/args.mjs +105 -1
  37. package/dist/core/resolve/coerce.mjs +279 -1
  38. package/dist/core/resolve/config.mjs +19 -1
  39. package/dist/core/resolve/errors.mjs +140 -2
  40. package/dist/core/resolve/flags.mjs +196 -1
  41. package/dist/core/resolve/index.mjs +85 -1
  42. package/dist/core/resolve/property.d.mts +0 -1
  43. package/dist/core/resolve/property.mjs +45 -1
  44. package/dist/core/schema/arg.mjs +463 -1
  45. package/dist/core/schema/command.d.mts +18 -0
  46. package/dist/core/schema/command.mjs +712 -1
  47. package/dist/core/schema/flag.mjs +453 -1
  48. package/dist/core/schema/middleware.mjs +41 -1
  49. package/dist/core/schema/number-constraints.mjs +60 -1
  50. package/dist/core/schema-dsl/runtime.mjs +271 -2
  51. package/dist/core/schema-dsl/to-json-schema.mjs +74 -1
  52. package/dist/core/testkit/index.mjs +83 -1
  53. package/dist/index.d.mts +2 -1
  54. package/dist/index.mjs +22 -1
  55. package/dist/runtime/adapter.mjs +82 -1
  56. package/dist/runtime/auto.mjs +46 -1
  57. package/dist/runtime/bun.mjs +28 -1
  58. package/dist/runtime/deno.mjs +217 -2
  59. package/dist/runtime/detect.mjs +45 -1
  60. package/dist/runtime/node.mjs +169 -2
  61. package/dist/runtime/paths.mjs +48 -1
  62. package/dist/runtime.mjs +7 -1
  63. package/dist/strings.mjs +22 -1
  64. package/dist/testkit.mjs +5 -1
  65. package/dist/version.d.mts +7 -3
  66. package/dist/version.mjs +7 -1
  67. package/package.json +21 -26
  68. package/src/core/cli/dispatch.ts +0 -355
  69. package/src/core/cli/help-links.ts +0 -82
  70. package/src/core/cli/index.ts +0 -1614
  71. package/src/core/cli/planner.ts +0 -656
  72. package/src/core/cli/plugin.ts +0 -117
  73. package/src/core/cli/propagate.ts +0 -97
  74. package/src/core/cli/root-help.ts +0 -342
  75. package/src/core/cli/root-surface.ts +0 -87
  76. package/src/core/cli/runtime-preflight.ts +0 -456
  77. package/src/core/completion/index.ts +0 -138
  78. package/src/core/completion/shells/bash.ts +0 -459
  79. package/src/core/completion/shells/fish.ts +0 -259
  80. package/src/core/completion/shells/powershell.ts +0 -439
  81. package/src/core/completion/shells/shared.ts +0 -310
  82. package/src/core/completion/shells/zsh.ts +0 -381
  83. package/src/core/config/index.ts +0 -417
  84. package/src/core/config/package-json.ts +0 -560
  85. package/src/core/errors/index.ts +0 -193
  86. package/src/core/execution/index.ts +0 -265
  87. package/src/core/help/ansi.ts +0 -144
  88. package/src/core/help/index.ts +0 -563
  89. package/src/core/json-schema/index.ts +0 -910
  90. package/src/core/json-schema/meta-descriptions.generated.ts +0 -202
  91. package/src/core/output/activity.ts +0 -575
  92. package/src/core/output/bind.ts +0 -59
  93. package/src/core/output/contracts.ts +0 -194
  94. package/src/core/output/display-value.ts +0 -48
  95. package/src/core/output/index.ts +0 -704
  96. package/src/core/output/renderers.ts +0 -125
  97. package/src/core/output/writer.ts +0 -46
  98. package/src/core/parse/index.ts +0 -742
  99. package/src/core/prompt/index.ts +0 -623
  100. package/src/core/resolve/args.ts +0 -144
  101. package/src/core/resolve/coerce.ts +0 -500
  102. package/src/core/resolve/config.ts +0 -26
  103. package/src/core/resolve/contracts.ts +0 -135
  104. package/src/core/resolve/errors.ts +0 -227
  105. package/src/core/resolve/flags.ts +0 -269
  106. package/src/core/resolve/index.ts +0 -108
  107. package/src/core/resolve/property.ts +0 -99
  108. package/src/core/schema/activity.ts +0 -240
  109. package/src/core/schema/arg.ts +0 -841
  110. package/src/core/schema/command.ts +0 -1500
  111. package/src/core/schema/flag.ts +0 -917
  112. package/src/core/schema/index.ts +0 -96
  113. package/src/core/schema/middleware.ts +0 -171
  114. package/src/core/schema/number-constraints.ts +0 -153
  115. package/src/core/schema/prompt.ts +0 -171
  116. package/src/core/schema/run.ts +0 -198
  117. package/src/core/schema-dsl/index.ts +0 -109
  118. package/src/core/schema-dsl/parse.ts +0 -262
  119. package/src/core/schema-dsl/runtime.ts +0 -609
  120. package/src/core/schema-dsl/to-json-schema.ts +0 -102
  121. package/src/core/testkit/index.ts +0 -147
  122. package/src/index.ts +0 -181
  123. package/src/runtime/adapter.ts +0 -303
  124. package/src/runtime/auto.ts +0 -86
  125. package/src/runtime/bun.ts +0 -48
  126. package/src/runtime/deno.ts +0 -367
  127. package/src/runtime/detect.ts +0 -105
  128. package/src/runtime/index.ts +0 -21
  129. package/src/runtime/node-builtins.d.ts +0 -27
  130. package/src/runtime/node.ts +0 -289
  131. package/src/runtime/paths.ts +0 -64
  132. package/src/runtime/support.ts +0 -77
  133. package/src/runtime.ts +0 -31
  134. package/src/schema.ts +0 -16
  135. package/src/strings.ts +0 -34
  136. package/src/testkit.ts +0 -25
  137. package/src/version.ts +0 -20
@@ -1,259 +0,0 @@
1
- /**
2
- * Fish completion script generator.
3
- *
4
- * Produces a self-contained fish script with:
5
- * - A command-path helper for nested command dispatch
6
- * - Per-path `complete` entries for visible commands and aliases
7
- * - Per-path flag definitions including propagated ancestor flags
8
- * - Enum value completions for option arguments
9
- * - Root-surface support for default-command completion policy
10
- *
11
- * @module dreamcli/core/completion/shells/fish
12
- * @internal
13
- */
14
-
15
- import type { CLISchema } from '#internals/core/cli/index.ts';
16
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
17
- import type { FlagSchema } from '#internals/core/schema/index.ts';
18
- import type { CommandNode, CompletionOptions, RootCompletionSurface } from './shared.ts';
19
- import {
20
- quoteShellArg,
21
- resolveRootCompletionSurface,
22
- sanitizeShellIdentifier,
23
- versionTag,
24
- walkCommandTree,
25
- } from './shared.ts';
26
-
27
- /**
28
- * Generate a fish completion script for the CLI.
29
- *
30
- * @param schema - The CLI schema.
31
- * @param options - Optional generator configuration.
32
- * @returns A complete fish completion script.
33
- *
34
- * @example
35
- * ```ts
36
- * const script = generateFishCompletion(app.schema);
37
- * // install with: mycli completions fish > ~/.config/fish/completions/mycli.fish
38
- * ```
39
- */
40
- function generateFishCompletion(schema: CLISchema, options?: CompletionOptions): string {
41
- const prefix = options?.functionPrefix ?? schema.name;
42
- const helperPrefix = `__${sanitizeShellIdentifier(prefix)}_completions`;
43
- const pathFuncName = `${helperPrefix}_path`;
44
- const pathIsFuncName = `${helperPrefix}_path_is`;
45
- const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
46
- const visibleCommands = rootSurface.visibleCommands;
47
- const nodes = walkCommandTree(visibleCommands);
48
- const commandName = quoteShellArg(schema.name);
49
-
50
- const lines: string[] = [];
51
-
52
- lines.push(`# Fish completion for ${schema.name}`);
53
- lines.push(`# Generated by ${versionTag()}`);
54
- lines.push('#');
55
- lines.push(`# Usage: source (${schema.name} completions fish | psub)`);
56
- lines.push('#');
57
- lines.push('# Install permanently:');
58
- lines.push(
59
- `# ${schema.name} completions fish > ~/.config/fish/completions/${schema.name}.fish`,
60
- );
61
- lines.push('');
62
- lines.push(`complete -c ${commandName} -f`);
63
- lines.push('');
64
-
65
- emitFishPathHelpers(lines, pathFuncName, pathIsFuncName, visibleCommands, nodes, rootSurface);
66
-
67
- appendFishCommandCompletions(lines, commandName, pathIsFuncName, '', visibleCommands);
68
- appendFishFlagCompletions(lines, commandName, pathIsFuncName, '', rootSurface.rootFlags);
69
- if (rootSurface.includeDefaultFlags) {
70
- appendFishFlagCompletions(lines, commandName, pathIsFuncName, '', rootSurface.defaultFlags);
71
- }
72
-
73
- for (const node of nodes) {
74
- const path = node.path.join(' ');
75
- appendFishCommandCompletions(lines, commandName, pathIsFuncName, path, node.children);
76
- appendFishFlagCompletions(lines, commandName, pathIsFuncName, path, node.mergedFlags);
77
- }
78
-
79
- return lines.join('\n');
80
- }
81
-
82
- function emitFishPathHelpers(
83
- lines: string[],
84
- pathFuncName: string,
85
- pathIsFuncName: string,
86
- visibleCommands: readonly {
87
- readonly name: string;
88
- readonly aliases: readonly string[];
89
- }[],
90
- nodes: readonly CommandNode[],
91
- rootSurface: RootCompletionSurface,
92
- ): void {
93
- const valueFlags = collectFishValueFlagPatterns(nodes, rootSurface);
94
-
95
- lines.push(`function ${pathFuncName}`);
96
- lines.push('\tset -l words (commandline -opc)');
97
- lines.push('\tif test (count $words) -gt 0');
98
- lines.push('\t\tset -e words[1]');
99
- lines.push('\tend');
100
- lines.push("\tset -l subcmd_path ''");
101
- lines.push('\tset -l expect_value 0');
102
- lines.push('\tfor word in $words');
103
- lines.push('\t\tif test $expect_value -eq 1');
104
- lines.push('\t\t\tset expect_value 0');
105
- lines.push('\t\t\tcontinue');
106
- lines.push('\t\tend');
107
- lines.push('\t\tswitch $word');
108
- lines.push("\t\t\tcase '--'");
109
- lines.push('\t\t\t\tbreak');
110
- if (valueFlags.exact.length > 0) {
111
- lines.push(`\t\t\tcase ${valueFlags.exact.map(quoteShellArg).join(' ')}`);
112
- lines.push('\t\t\t\tset expect_value 1');
113
- lines.push('\t\t\t\tcontinue');
114
- }
115
- if (valueFlags.prefix.length > 0) {
116
- lines.push(`\t\t\tcase ${valueFlags.prefix.map(quoteShellArg).join(' ')}`);
117
- lines.push('\t\t\t\tcontinue');
118
- }
119
- lines.push("\t\t\tcase '-*'");
120
- lines.push('\t\t\t\tcontinue');
121
- lines.push('\t\tend');
122
- lines.push('\t\tswitch "$subcmd_path|$word"');
123
-
124
- for (const command of visibleCommands) {
125
- for (const name of [command.name, ...command.aliases]) {
126
- lines.push(`\t\t\tcase ${quoteShellArg(`|${name}`)}`);
127
- lines.push(`\t\t\t\tset subcmd_path ${quoteShellArg(command.name)}`);
128
- }
129
- }
130
-
131
- for (const node of nodes) {
132
- for (const child of node.children) {
133
- for (const name of [child.name, ...child.aliases]) {
134
- lines.push(`\t\t\tcase ${quoteShellArg(`${node.path.join(' ')}|${name}`)}`);
135
- lines.push(
136
- `\t\t\t\tset subcmd_path ${quoteShellArg(`${node.path.join(' ')} ${child.name}`)}`,
137
- );
138
- }
139
- }
140
- }
141
-
142
- lines.push("\t\t\tcase '*'");
143
- lines.push('\t\t\t\tbreak');
144
- lines.push('\t\tend');
145
- lines.push('\tend');
146
- lines.push('\tprintf \'%s\\n\' "$subcmd_path"');
147
- lines.push('end');
148
- lines.push('');
149
- lines.push(`function ${pathIsFuncName}`);
150
- lines.push('\tset -l expected "$argv[1]"');
151
- lines.push(`\ttest (${pathFuncName}) = "$expected"`);
152
- lines.push('end');
153
- lines.push('');
154
- }
155
-
156
- function appendFishCommandCompletions(
157
- lines: string[],
158
- commandName: string,
159
- pathIsFuncName: string,
160
- path: string,
161
- commands: ReadonlyArray<{
162
- readonly name: string;
163
- readonly aliases: readonly string[];
164
- readonly description: string | undefined;
165
- }>,
166
- ): void {
167
- const condition = buildFishCondition(pathIsFuncName, path);
168
- for (const command of commands) {
169
- const description = quoteShellArg(command.description ?? command.name);
170
- for (const name of [command.name, ...command.aliases]) {
171
- lines.push(
172
- `complete -c ${commandName} -n "${condition}" -a ${quoteShellArg(name)} -d ${description}`,
173
- );
174
- }
175
- }
176
- if (commands.length > 0) {
177
- lines.push('');
178
- }
179
- }
180
-
181
- function appendFishFlagCompletions(
182
- lines: string[],
183
- commandName: string,
184
- pathIsFuncName: string,
185
- path: string,
186
- flags: Readonly<Record<string, FlagSchema>>,
187
- ): void {
188
- const condition = buildFishCondition(pathIsFuncName, path);
189
- for (const [name, schema] of Object.entries(flags)) {
190
- const parts = [`complete -c ${commandName}`, `-n "${condition}"`];
191
- for (const alias of getFlagAliasNames(schema, { kind: 'short' })) {
192
- parts.push(`-s ${quoteShellArg(alias)}`);
193
- }
194
- parts.push(`-l ${quoteShellArg(name)}`);
195
- for (const alias of getFlagAliasNames(schema, { kind: 'long' })) {
196
- parts.push(`-l ${quoteShellArg(alias)}`);
197
- }
198
- parts.push(`-d ${quoteShellArg(schema.description ?? name)}`);
199
-
200
- if (schema.kind !== 'boolean') {
201
- parts.push('-r', '-f');
202
- }
203
- if (schema.kind === 'enum' && schema.enumValues !== undefined) {
204
- for (const enumValue of schema.enumValues) {
205
- lines.push([...parts, `-a ${quoteShellArg(enumValue)}`].join(' '));
206
- }
207
- continue;
208
- }
209
-
210
- lines.push(parts.join(' '));
211
- }
212
- if (Object.keys(flags).length > 0) {
213
- lines.push('');
214
- }
215
- }
216
-
217
- function collectFishValueFlagPatterns(
218
- nodes: readonly CommandNode[],
219
- rootSurface: RootCompletionSurface,
220
- ): {
221
- readonly exact: readonly string[];
222
- readonly prefix: readonly string[];
223
- } {
224
- const exact = new Set<string>();
225
- const prefix = new Set<string>();
226
- const flagSets: ReadonlyArray<Readonly<Record<string, FlagSchema>>> = [
227
- rootSurface.rootFlags,
228
- ...(rootSurface.includeDefaultFlags ? [rootSurface.defaultFlags] : []),
229
- ...nodes.map((node) => node.mergedFlags),
230
- ];
231
-
232
- for (const flags of flagSets) {
233
- for (const [name, schema] of Object.entries(flags)) {
234
- if (schema.kind === 'boolean') continue;
235
-
236
- exact.add(`--${name}`);
237
- prefix.add(`--${name}=*`);
238
- for (const alias of getFlagAliasNames(schema, { kind: 'short', includeHidden: true })) {
239
- exact.add(`-${alias}`);
240
- prefix.add(`-${alias}*`);
241
- }
242
- for (const alias of getFlagAliasNames(schema, { kind: 'long', includeHidden: true })) {
243
- exact.add(`--${alias}`);
244
- prefix.add(`--${alias}=*`);
245
- }
246
- }
247
- }
248
-
249
- return {
250
- exact: [...exact],
251
- prefix: [...prefix],
252
- };
253
- }
254
-
255
- function buildFishCondition(pathIsFuncName: string, path: string): string {
256
- return `${pathIsFuncName} ${quoteShellArg(path)}`;
257
- }
258
-
259
- export { generateFishCompletion };
@@ -1,439 +0,0 @@
1
- /**
2
- * PowerShell completion script generator.
3
- *
4
- * Produces a self-contained PowerShell script with:
5
- * - A native `Register-ArgumentCompleter` registration
6
- * - Precomputed command-path metadata for nested dispatch
7
- * - Per-path command and flag entries including propagated ancestor flags
8
- * - Enum value completions for option arguments
9
- * - Root-surface support for default-command completion policy
10
- *
11
- * @module dreamcli/core/completion/shells/powershell
12
- * @internal
13
- */
14
-
15
- import type { CLISchema } from '#internals/core/cli/index.ts';
16
- import { getFlagAliasNames } from '#internals/core/schema/flag.ts';
17
- import type { FlagSchema } from '#internals/core/schema/index.ts';
18
- import type { CommandNode, CompletionOptions, RootCompletionSurface } from './shared.ts';
19
- import {
20
- resolveRootCompletionSurface,
21
- sanitizeShellIdentifier,
22
- versionTag,
23
- walkCommandTree,
24
- } from './shared.ts';
25
-
26
- /**
27
- * Generate a PowerShell completion script for the CLI.
28
- *
29
- * @param schema - The CLI schema.
30
- * @param options - Optional generator configuration.
31
- * @returns A complete PowerShell completion script.
32
- */
33
- function generatePowerShellCompletion(schema: CLISchema, options?: CompletionOptions): string {
34
- const prefix = options?.functionPrefix ?? schema.name;
35
- const helperPrefix = `__${sanitizeShellIdentifier(prefix)}_completions`;
36
- const dataVarName = `${helperPrefix}_paths`;
37
- const rootSurface = resolveRootCompletionSurface(schema, options?.rootMode);
38
- const visibleCommands = rootSurface.visibleCommands;
39
- const nodes = walkCommandTree(visibleCommands);
40
-
41
- const lines: string[] = [];
42
-
43
- lines.push(`# PowerShell completion for ${schema.name}`);
44
- lines.push(`# Generated by ${versionTag()}`);
45
- lines.push('#');
46
- lines.push('# Install for the current session:');
47
- lines.push(`# ${schema.name} completions powershell | Out-String | Invoke-Expression`);
48
- lines.push('#');
49
- lines.push('# Install permanently:');
50
- lines.push(`# ${schema.name} completions powershell > $PROFILE.CurrentUserCurrentHost`);
51
- lines.push('');
52
- lines.push('using namespace System.Management.Automation');
53
- lines.push('using namespace System.Management.Automation.Language');
54
- lines.push('');
55
-
56
- emitPowerShellPathTable(lines, dataVarName, rootSurface, nodes);
57
- lines.push('');
58
- emitPowerShellHelpers(lines, helperPrefix, dataVarName);
59
- lines.push('');
60
- lines.push(
61
- `Register-ArgumentCompleter -Native -CommandName ${quotePowerShellString(schema.name)} -ScriptBlock {`,
62
- );
63
- lines.push('\tparam($wordToComplete, $commandAst, $cursorPosition)');
64
- lines.push(
65
- `\t$state = ${helperPrefix}_GetState -CommandAst $commandAst -CursorPosition $cursorPosition`,
66
- );
67
- lines.push('\tif ($null -eq $state.PathData) {');
68
- lines.push('\t\treturn');
69
- lines.push('\t}');
70
- lines.push('');
71
- lines.push('\t$results = [System.Collections.Generic.List[CompletionResult]]::new()');
72
- lines.push('\tif ($state.AfterSeparator) {');
73
- lines.push('\t\treturn $results');
74
- lines.push('\t}');
75
- lines.push('');
76
- lines.push(
77
- `\t$wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`,
78
- );
79
- lines.push('');
80
- lines.push('\tif ($state.ExpectingValue) {');
81
- lines.push(
82
- `\t\t${helperPrefix}_AddEnumResults -Results $results -Flag $state.ValueFlag -WordToComplete $wordPrefix`,
83
- );
84
- lines.push('\t\treturn $results');
85
- lines.push('\t}');
86
- lines.push('');
87
- lines.push(
88
- `\t$inlineValue = ${helperPrefix}_ResolveInlineValueCompletion -PathData $state.PathData -WordToComplete $wordPrefix`,
89
- );
90
- lines.push('\tif ($null -ne $inlineValue) {');
91
- lines.push(
92
- `\t\t${helperPrefix}_AddInlineEnumResults -Results $results -InlineValue $inlineValue -WordToComplete $wordPrefix`,
93
- );
94
- lines.push('\t\treturn $results');
95
- lines.push('\t}');
96
- lines.push('');
97
- lines.push("\tif ($wordPrefix.StartsWith('-')) {");
98
- lines.push(
99
- `\t\t${helperPrefix}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
100
- );
101
- lines.push('\t\treturn $results');
102
- lines.push('\t}');
103
- lines.push('');
104
- lines.push(
105
- `\t${helperPrefix}_AddCommandResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
106
- );
107
- lines.push(
108
- `\t${helperPrefix}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`,
109
- );
110
- lines.push('\treturn $results');
111
- lines.push('}');
112
-
113
- return lines.join('\n');
114
- }
115
-
116
- function emitPowerShellPathTable(
117
- lines: string[],
118
- dataVarName: string,
119
- rootSurface: RootCompletionSurface,
120
- nodes: readonly CommandNode[],
121
- ): void {
122
- lines.push(`$script:${dataVarName} = @{`);
123
- appendPowerShellPathEntry(lines, '', rootSurface.visibleCommands, {
124
- ...rootSurface.rootFlags,
125
- ...(rootSurface.includeDefaultFlags ? rootSurface.defaultFlags : {}),
126
- });
127
-
128
- for (const node of nodes) {
129
- appendPowerShellPathEntry(lines, node.path.join(' '), node.children, node.mergedFlags);
130
- }
131
-
132
- lines.push('}');
133
- }
134
-
135
- function appendPowerShellPathEntry(
136
- lines: string[],
137
- path: string,
138
- commands: ReadonlyArray<{
139
- readonly name: string;
140
- readonly aliases: readonly string[];
141
- readonly description: string | undefined;
142
- }>,
143
- flags: Readonly<Record<string, FlagSchema>>,
144
- ): void {
145
- lines.push(`\t${quotePowerShellString(path)} = @{`);
146
- lines.push('\t\tCommands = @(');
147
- for (const command of commands) {
148
- lines.push('\t\t\t@{');
149
- lines.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(command.name)}`);
150
- lines.push(`\t\t\t\tNames = ${formatPowerShellArray([command.name, ...command.aliases])}`);
151
- lines.push(
152
- `\t\t\t\tDescription = ${quotePowerShellString(command.description ?? command.name)}`,
153
- );
154
- lines.push('\t\t\t}');
155
- }
156
- lines.push('\t\t)');
157
- lines.push('\t\tFlags = @(');
158
- for (const [name, schema] of Object.entries(flags)) {
159
- const forms = dedupeValues([
160
- `--${name}`,
161
- ...getFlagAliasNames(schema, { kind: 'short' }).map((alias) => `-${alias}`),
162
- ...getFlagAliasNames(schema, { kind: 'long' }).map((alias) => `--${alias}`),
163
- ]);
164
- const parseForms = dedupeValues([
165
- `--${name}`,
166
- ...getFlagAliasNames(schema, { kind: 'short', includeHidden: true }).map(
167
- (alias) => `-${alias}`,
168
- ),
169
- ...getFlagAliasNames(schema, { kind: 'long', includeHidden: true }).map(
170
- (alias) => `--${alias}`,
171
- ),
172
- ]);
173
- lines.push('\t\t\t@{');
174
- lines.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(name)}`);
175
- lines.push(`\t\t\t\tForms = ${formatPowerShellArray(forms)}`);
176
- lines.push(`\t\t\t\tParseForms = ${formatPowerShellArray(parseForms)}`);
177
- lines.push(`\t\t\t\tRequiresValue = ${schema.kind === 'boolean' ? '$false' : '$true'}`);
178
- lines.push(`\t\t\t\tDescription = ${quotePowerShellString(schema.description ?? name)}`);
179
- lines.push(`\t\t\t\tEnumValues = ${formatPowerShellArray(schema.enumValues ?? [])}`);
180
- lines.push('\t\t\t}');
181
- }
182
- lines.push('\t\t)');
183
- lines.push('\t}');
184
- }
185
-
186
- function emitPowerShellHelpers(lines: string[], helperPrefix: string, dataVarName: string): void {
187
- lines.push(`function ${helperPrefix}_UnquoteToken {`);
188
- lines.push('\tparam([string]$TokenText)');
189
- lines.push('\tif ($TokenText.Length -lt 2) {');
190
- lines.push('\t\treturn $TokenText');
191
- lines.push('\t}');
192
- lines.push('');
193
- lines.push('\tif (($TokenText.StartsWith("\'") -and $TokenText.EndsWith("\'")) -or');
194
- lines.push("\t\t($TokenText.StartsWith('\"') -and $TokenText.EndsWith('\"'))) {");
195
- lines.push('\t\treturn $TokenText.Substring(1, $TokenText.Length - 2)');
196
- lines.push('\t}');
197
- lines.push('');
198
- lines.push('\treturn $TokenText');
199
- lines.push('}');
200
- lines.push('');
201
- lines.push(`function ${helperPrefix}_FindCommand {`);
202
- lines.push('\tparam($PathData, [string]$Token)');
203
- lines.push('\tforeach ($command in $PathData.Commands) {');
204
- lines.push('\t\tforeach ($name in $command.Names) {');
205
- lines.push('\t\t\tif ($name -eq $Token) {');
206
- lines.push('\t\t\t\treturn $command');
207
- lines.push('\t\t\t}');
208
- lines.push('\t\t}');
209
- lines.push('\t}');
210
- lines.push('\treturn $null');
211
- lines.push('}');
212
- lines.push('');
213
- lines.push(`function ${helperPrefix}_ResolveFlagToken {`);
214
- lines.push('\tparam($PathData, [string]$Token)');
215
- lines.push('\tforeach ($flag in $PathData.Flags) {');
216
- lines.push('\t\tforeach ($form in $flag.ParseForms) {');
217
- lines.push('\t\t\tif ($Token -eq $form) {');
218
- lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = $null }');
219
- lines.push('\t\t\t}');
220
- lines.push('');
221
- lines.push('\t\t\tif (-not $flag.RequiresValue) {');
222
- lines.push('\t\t\t\tcontinue');
223
- lines.push('\t\t\t}');
224
- lines.push('');
225
- lines.push('\t\t\tif ($form.StartsWith(\'--\') -and $Token.StartsWith("$form=")) {');
226
- lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = "$form=" }');
227
- lines.push('\t\t\t}');
228
- lines.push('');
229
- lines.push(
230
- "\t\t\tif ($form.StartsWith('-') -and -not $form.StartsWith('--') -and $Token.StartsWith($form) -and $Token.Length -gt $form.Length) {",
231
- );
232
- lines.push('\t\t\t\treturn @{ Flag = $flag; InlinePrefix = $form }');
233
- lines.push('\t\t\t}');
234
- lines.push('\t\t}');
235
- lines.push('\t}');
236
- lines.push('\treturn $null');
237
- lines.push('}');
238
- lines.push('');
239
- lines.push(`function ${helperPrefix}_GetState {`);
240
- lines.push('\tparam([CommandAst]$CommandAst, [int]$CursorPosition)');
241
- lines.push(`\t$pathData = $script:${dataVarName}[${quotePowerShellString('')}]`);
242
- lines.push('\t$path = ""');
243
- lines.push('\t$afterSeparator = $false');
244
- lines.push('\t$expectingValue = $false');
245
- lines.push('\t$valueFlag = $null');
246
- lines.push('\t$tokens = [System.Collections.Generic.List[string]]::new()');
247
- lines.push('');
248
- lines.push('\tforeach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {');
249
- lines.push('\t\tif ($element.Extent.EndOffset -ge $CursorPosition) {');
250
- lines.push('\t\t\tbreak');
251
- lines.push('\t\t}');
252
- lines.push(`\t\t$tokenText = ${helperPrefix}_UnquoteToken $element.Extent.Text`);
253
- lines.push('\t\t[void]$tokens.Add($tokenText)');
254
- lines.push('\t}');
255
- lines.push('');
256
- lines.push('\tforeach ($token in $tokens) {');
257
- lines.push('\t\tif ($expectingValue) {');
258
- lines.push('\t\t\t$expectingValue = $false');
259
- lines.push('\t\t\t$valueFlag = $null');
260
- lines.push('\t\t\tcontinue');
261
- lines.push('\t\t}');
262
- lines.push('');
263
- lines.push("\t\tif ($token -eq '--') {");
264
- lines.push('\t\t\t$afterSeparator = $true');
265
- lines.push('\t\t\tbreak');
266
- lines.push('\t\t}');
267
- lines.push('');
268
- lines.push(`\t\t$flagMatch = ${helperPrefix}_ResolveFlagToken -PathData $pathData -Token $token`);
269
- lines.push('\t\tif ($null -ne $flagMatch) {');
270
- lines.push('\t\t\tif ($flagMatch.InlinePrefix -eq $null -and $flagMatch.Flag.RequiresValue) {');
271
- lines.push('\t\t\t\t$expectingValue = $true');
272
- lines.push('\t\t\t\t$valueFlag = $flagMatch.Flag');
273
- lines.push('\t\t\t}');
274
- lines.push('\t\t\tcontinue');
275
- lines.push('\t\t}');
276
- lines.push('');
277
- lines.push("\t\tif ($token.StartsWith('-')) {");
278
- lines.push('\t\t\tcontinue');
279
- lines.push('\t\t}');
280
- lines.push('');
281
- lines.push(`\t\t$command = ${helperPrefix}_FindCommand -PathData $pathData -Token $token`);
282
- lines.push('\t\tif ($null -eq $command) {');
283
- lines.push('\t\t\tbreak');
284
- lines.push('\t\t}');
285
- lines.push('');
286
- lines.push('\t\t$path = if ([string]::IsNullOrEmpty($path)) {');
287
- lines.push('\t\t\t$command.CanonicalName');
288
- lines.push('\t\t} else {');
289
- lines.push('\t\t\t"$path $($command.CanonicalName)"');
290
- lines.push('\t\t}');
291
- lines.push(`\t\t$nextPathData = $script:${dataVarName}[$path]`);
292
- lines.push('\t\tif ($null -eq $nextPathData) {');
293
- lines.push('\t\t\tbreak');
294
- lines.push('\t\t}');
295
- lines.push('\t\t$pathData = $nextPathData');
296
- lines.push('\t}');
297
- lines.push('');
298
- lines.push('\treturn @{');
299
- lines.push('\t\tPath = $path');
300
- lines.push('\t\tPathData = $pathData');
301
- lines.push('\t\tAfterSeparator = $afterSeparator');
302
- lines.push('\t\tExpectingValue = $expectingValue');
303
- lines.push('\t\tValueFlag = $valueFlag');
304
- lines.push('\t}');
305
- lines.push('}');
306
- lines.push('');
307
- lines.push(`function ${helperPrefix}_ResolveInlineValueCompletion {`);
308
- lines.push('\tparam($PathData, [string]$WordToComplete)');
309
- lines.push(
310
- `\t$flagMatch = ${helperPrefix}_ResolveFlagToken -PathData $PathData -Token $WordToComplete`,
311
- );
312
- lines.push('\tif ($null -eq $flagMatch -or $flagMatch.InlinePrefix -eq $null) {');
313
- lines.push('\t\treturn $null');
314
- lines.push('\t}');
315
- lines.push('\treturn $flagMatch');
316
- lines.push('}');
317
- lines.push('');
318
- lines.push(`function ${helperPrefix}_FormatCompletionValue {`);
319
- lines.push('\tparam([string]$Value)');
320
- lines.push('\tif ($Value.Length -eq 0) {');
321
- lines.push('\t\treturn "\'\'"');
322
- lines.push('\t}');
323
- lines.push('');
324
- lines.push("\tif ($Value -match '^[a-zA-Z0-9_./:\\\\-]+$') {");
325
- lines.push('\t\treturn $Value');
326
- lines.push('\t}');
327
- lines.push('');
328
- lines.push('\treturn "\'$([CodeGeneration]::EscapeSingleQuotedStringContent($Value))\'"');
329
- lines.push('}');
330
- lines.push('');
331
- lines.push(`function ${helperPrefix}_MatchesCompletionPrefix {`);
332
- lines.push('\tparam([string]$WordToComplete, [string]$RawText, [string]$CompletionText)');
333
- lines.push('\tif ([string]::IsNullOrEmpty($WordToComplete)) {');
334
- lines.push('\t\treturn $true');
335
- lines.push('\t}');
336
- lines.push('');
337
- lines.push(
338
- '\treturn $RawText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase) -or $CompletionText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)',
339
- );
340
- lines.push('}');
341
- lines.push('');
342
- lines.push(`function ${helperPrefix}_AddCommandResults {`);
343
- lines.push('\tparam($Results, $PathData, [string]$WordToComplete)');
344
- lines.push('\tforeach ($command in $PathData.Commands) {');
345
- lines.push('\t\tforeach ($name in $command.Names) {');
346
- lines.push(
347
- '\t\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $name.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
348
- );
349
- lines.push('\t\t\t\tcontinue');
350
- lines.push('\t\t\t}');
351
- lines.push('');
352
- lines.push('\t\t\t$Results.Add([CompletionResult]::new(');
353
- lines.push('\t\t\t\t$name,');
354
- lines.push('\t\t\t\t$name,');
355
- lines.push('\t\t\t\t[CompletionResultType]::Command,');
356
- lines.push('\t\t\t\t$command.Description');
357
- lines.push('\t\t\t))');
358
- lines.push('\t\t}');
359
- lines.push('\t}');
360
- lines.push('}');
361
- lines.push('');
362
- lines.push(`function ${helperPrefix}_AddFlagResults {`);
363
- lines.push('\tparam($Results, $PathData, [string]$WordToComplete)');
364
- lines.push('\tforeach ($flag in $PathData.Flags) {');
365
- lines.push('\t\tforeach ($form in $flag.Forms) {');
366
- lines.push(
367
- '\t\t\tif (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $form.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {',
368
- );
369
- lines.push('\t\t\t\tcontinue');
370
- lines.push('\t\t\t}');
371
- lines.push('');
372
- lines.push('\t\t\t$Results.Add([CompletionResult]::new(');
373
- lines.push('\t\t\t\t$form,');
374
- lines.push('\t\t\t\t$form,');
375
- lines.push('\t\t\t\t[CompletionResultType]::ParameterName,');
376
- lines.push('\t\t\t\t$flag.Description');
377
- lines.push('\t\t\t))');
378
- lines.push('\t\t}');
379
- lines.push('\t}');
380
- lines.push('}');
381
- lines.push('');
382
- lines.push(`function ${helperPrefix}_AddEnumResults {`);
383
- lines.push('\tparam($Results, $Flag, [string]$WordToComplete)');
384
- lines.push('\tforeach ($value in $Flag.EnumValues) {');
385
- lines.push(`\t\t$completionText = ${helperPrefix}_FormatCompletionValue -Value $value`);
386
- lines.push(
387
- `\t\tif (-not (${helperPrefix}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $value -CompletionText $completionText)) {`,
388
- );
389
- lines.push('\t\t\tcontinue');
390
- lines.push('\t\t}');
391
- lines.push('');
392
- lines.push('\t\t$Results.Add([CompletionResult]::new(');
393
- lines.push('\t\t\t$completionText,');
394
- lines.push('\t\t\t$value,');
395
- lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
396
- lines.push('\t\t\t$Flag.Description');
397
- lines.push('\t\t))');
398
- lines.push('\t}');
399
- lines.push('}');
400
- lines.push('');
401
- lines.push(`function ${helperPrefix}_AddInlineEnumResults {`);
402
- lines.push('\tparam($Results, $InlineValue, [string]$WordToComplete)');
403
- lines.push('\tforeach ($value in $InlineValue.Flag.EnumValues) {');
404
- lines.push('\t\t$rawCompletion = "$($InlineValue.InlinePrefix)$value"');
405
- lines.push(`\t\t$formattedValue = ${helperPrefix}_FormatCompletionValue -Value $value`);
406
- lines.push('\t\t$completionText = "$($InlineValue.InlinePrefix)$formattedValue"');
407
- lines.push(
408
- `\t\tif (-not (${helperPrefix}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $rawCompletion -CompletionText $completionText)) {`,
409
- );
410
- lines.push('\t\t\tcontinue');
411
- lines.push('\t\t}');
412
- lines.push('');
413
- lines.push('\t\t$Results.Add([CompletionResult]::new(');
414
- lines.push('\t\t\t$completionText,');
415
- lines.push('\t\t\t$value,');
416
- lines.push('\t\t\t[CompletionResultType]::ParameterValue,');
417
- lines.push('\t\t\t$InlineValue.Flag.Description');
418
- lines.push('\t\t))');
419
- lines.push('\t}');
420
- lines.push('}');
421
- }
422
-
423
- function quotePowerShellString(value: string): string {
424
- return `'${value.replace(/'/g, "''")}'`;
425
- }
426
-
427
- function formatPowerShellArray(values: readonly string[]): string {
428
- if (values.length === 0) {
429
- return '@()';
430
- }
431
-
432
- return `@(${values.map(quotePowerShellString).join(', ')})`;
433
- }
434
-
435
- function dedupeValues(values: readonly string[]): readonly string[] {
436
- return [...new Set(values)];
437
- }
438
-
439
- export { generatePowerShellCompletion };