@kjanat/dreamcli 5.0.0 → 5.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/completion-B4oRc2Ae.mjs +59 -0
- package/dist/completion.d.mts +11 -1
- package/dist/completion.mjs +1 -1
- package/dist/config-DSh3QJpX.mjs +1 -0
- package/dist/config.d.mts +11 -1
- package/dist/config.mjs +1 -1
- package/dist/core-BZx351-p.mjs +21 -0
- package/dist/dynamic-BK2lQF2M.mjs +1 -0
- package/dist/{index-BidVVmln.d.mts → index-CLtWJqwn.d.mts} +8 -5
- package/dist/{index-BIMjOsR6.d.mts → index-CuhI1Ynv.d.mts} +394 -4
- package/dist/{index-DpslpOVV.d.mts → index-DDhRLoTu.d.mts} +7 -1
- package/dist/{index-jq_FJRKt.d.mts → index-DIWRV_wp.d.mts} +1 -1
- package/dist/{index-hzYPRc_O.d.mts → index-Vjl2_m23.d.mts} +5 -5
- package/dist/{index-AIC5Gler.d.mts → index-aTmg9yfl.d.mts} +1 -1
- package/dist/index.d.mts +30 -7
- package/dist/index.mjs +1 -1
- package/dist/json-schema-CYgq_hFu.mjs +59 -0
- package/dist/json-schema.d.mts +9 -1
- package/dist/json-schema.mjs +1 -1
- package/dist/{package-json-fYhxDdWD.mjs → package-json-hqUWeazy.mjs} +1 -1
- package/dist/prompt.d.mts +12 -1
- package/dist/prompt.mjs +1 -1
- package/dist/rolldown-runtime-DOYBPklu.mjs +1 -0
- package/dist/runtime.d.mts +20 -2
- package/dist/runtime.mjs +1 -1
- package/dist/session-BEKj0yLA.mjs +1 -0
- package/dist/{terminal-DRsRn4sc.mjs → terminal-Dws_b5UK.mjs} +1 -1
- package/dist/test-prompter-euLYzWWO.mjs +1 -0
- package/dist/testkit.d.mts +17 -4
- package/dist/testkit.mjs +1 -1
- package/dist/version.mjs +1 -1
- package/dreamcli.schema.json +11 -0
- package/package.json +7 -7
- package/skills/cli-creation/SKILL.md +1 -1
- package/dist/adapter-DBeedKmD.d.mts +0 -283
- package/dist/completion-Bh-qywmB.mjs +0 -6
- package/dist/config-DruA8aFV.mjs +0 -1
- package/dist/core-B9YNSJeA.mjs +0 -19
- package/dist/json-schema-DF5fXdKQ.mjs +0 -59
- package/dist/rolldown-runtime-G4Kt5YOX.mjs +0 -1
- package/dist/session-Crtzt7LY.mjs +0 -1
- package/dist/test-prompter-BLNGCOA_.mjs +0 -1
|
@@ -1,283 +0,0 @@
|
|
|
1
|
-
import { a as WriteFn, s as ReadFn } from "./index-BIMjOsR6.mjs";
|
|
2
|
-
/**
|
|
3
|
-
* Runtime adapter interface.
|
|
4
|
-
*
|
|
5
|
-
* Defines the minimal contract between the platform-agnostic core and
|
|
6
|
-
* the host runtime (Node.js, Bun, Deno). Every platform-dependent
|
|
7
|
-
* operation flows through this interface — the core never calls
|
|
8
|
-
* `process.*`, `Deno.*`, or `Bun.*` directly.
|
|
9
|
-
*
|
|
10
|
-
* Adapters are designed to be:
|
|
11
|
-
* - **Immutable in shape:** all properties are readonly
|
|
12
|
-
* - **Minimal:** only the operations the framework actually needs
|
|
13
|
-
* - **Testable:** easily stubbed in tests via {@linkcode createTestAdapter | createTestAdapter()}
|
|
14
|
-
*
|
|
15
|
-
* @example
|
|
16
|
-
* ```ts
|
|
17
|
-
* // Production: auto-detected
|
|
18
|
-
* cli('mycli').run(); // uses Node/Bun/Deno adapter
|
|
19
|
-
*
|
|
20
|
-
* // Test: explicit adapter
|
|
21
|
-
* cli('mycli').run({ adapter: createTestAdapter({ argv: ['deploy'] }) });
|
|
22
|
-
* ```
|
|
23
|
-
*/
|
|
24
|
-
interface RuntimeAdapter {
|
|
25
|
-
/** Raw argv array (including binary + script path, e.g. `['node', 'cli.js', 'deploy']`). */
|
|
26
|
-
readonly argv: readonly string[];
|
|
27
|
-
/**
|
|
28
|
-
* Environment variables.
|
|
29
|
-
* Values are `string | undefined` — mirrors Node's `process.env` semantics.
|
|
30
|
-
*/
|
|
31
|
-
readonly env: Readonly<Record<string, string | undefined>>;
|
|
32
|
-
/** Current working directory (absolute path). */
|
|
33
|
-
readonly cwd: string;
|
|
34
|
-
/** Writer for stdout. Framework routes `out.log`/`out.info` through this. */
|
|
35
|
-
readonly stdout: WriteFn;
|
|
36
|
-
/** Writer for stderr. Framework routes `out.warn`/`out.error` through this. */
|
|
37
|
-
readonly stderr: WriteFn;
|
|
38
|
-
/** Wait for pending output writes to settle, rejecting with a recorded output failure. */
|
|
39
|
-
readonly flush?: () => Promise<void>;
|
|
40
|
-
/**
|
|
41
|
-
* Line reader for stdin. Used by the prompt engine for interactive input.
|
|
42
|
-
*
|
|
43
|
-
* Returns `null` on EOF (Ctrl+D on Unix, Ctrl+Z on Windows),
|
|
44
|
-
* indicating the user closed the input stream (treated as cancel).
|
|
45
|
-
*/
|
|
46
|
-
readonly stdin: ReadFn;
|
|
47
|
-
/** Hidden terminal input. Absent when echo suppression is unsupported. */
|
|
48
|
-
readonly readSecret?: ReadFn;
|
|
49
|
-
/**
|
|
50
|
-
* Read all of stdin as a single string (for piped data).
|
|
51
|
-
*
|
|
52
|
-
* Returns the full stdin contents when data is piped (`stdinIsTTY` is
|
|
53
|
-
* false), or `null` when stdin is a TTY (no piped data available).
|
|
54
|
-
*
|
|
55
|
-
* Used by the resolve chain for args with `.stdin()` configured.
|
|
56
|
-
* Unlike {@link stdin} (which reads one line for prompts), this
|
|
57
|
-
* consumes the entire stream to EOF.
|
|
58
|
-
*
|
|
59
|
-
* @returns Full stdin contents as a string, or `null` if stdin is a TTY.
|
|
60
|
-
*/
|
|
61
|
-
readonly readStdin: () => Promise<string | null>;
|
|
62
|
-
/** Whether stdout is connected to a TTY. */
|
|
63
|
-
readonly isTTY: boolean;
|
|
64
|
-
/** Whether stdin is connected to a TTY (used for prompt gating). */
|
|
65
|
-
readonly stdinIsTTY: boolean;
|
|
66
|
-
/** Read current terminal dimensions for stdout, if available. */
|
|
67
|
-
readonly getTerminalSize: () => TerminalSize | undefined;
|
|
68
|
-
/** Subscribe to terminal resize events when the runtime supports them. */
|
|
69
|
-
readonly onTerminalResize: (listener: () => void) => (() => void) | undefined;
|
|
70
|
-
/**
|
|
71
|
-
* Exit the process with the given code.
|
|
72
|
-
* Must not return (divergent function).
|
|
73
|
-
*/
|
|
74
|
-
readonly exit: (code: number) => never;
|
|
75
|
-
/**
|
|
76
|
-
* Read a file as UTF-8 text.
|
|
77
|
-
*
|
|
78
|
-
* Returns file contents on success, `null` if the file does not exist
|
|
79
|
-
* (ENOENT/NotFound). Throws on other I/O errors (permission denied,
|
|
80
|
-
* is-directory, etc.) — those indicate unexpected failures, not
|
|
81
|
-
* "try the next path".
|
|
82
|
-
*
|
|
83
|
-
* Used by config file discovery to probe multiple candidate paths.
|
|
84
|
-
*/
|
|
85
|
-
readonly readFile: (path: string) => Promise<string | null>;
|
|
86
|
-
/**
|
|
87
|
-
* Probe what exists at a filesystem path.
|
|
88
|
-
*
|
|
89
|
-
* Returns `'file'` or `'directory'` for existing paths (other kinds such
|
|
90
|
-
* as sockets report `'file'`), or `null` when nothing exists there.
|
|
91
|
-
*
|
|
92
|
-
* Used by `flag.path()` existence/type checks after resolution.
|
|
93
|
-
*/
|
|
94
|
-
readonly stat: (path: string) => Promise<'file' | 'directory' | null>;
|
|
95
|
-
/**
|
|
96
|
-
* Create a directory, including missing parents.
|
|
97
|
-
*
|
|
98
|
-
* Succeeds when the directory already exists. Throws on other I/O errors
|
|
99
|
-
* (permission denied, existing file at the path, etc.).
|
|
100
|
-
*
|
|
101
|
-
* Used by `flag.path()` `create` checks after resolution.
|
|
102
|
-
*/
|
|
103
|
-
readonly mkdir: (path: string) => Promise<void>;
|
|
104
|
-
/**
|
|
105
|
-
* User home directory (absolute path).
|
|
106
|
-
*
|
|
107
|
-
* - Node/Bun: derived from `HOME` / `USERPROFILE` env
|
|
108
|
-
* - Deno: `Deno.env.get('HOME')` / `Deno.env.get('USERPROFILE')`
|
|
109
|
-
*/
|
|
110
|
-
readonly homedir: string;
|
|
111
|
-
/**
|
|
112
|
-
* Platform-specific user configuration directory (absolute path).
|
|
113
|
-
*
|
|
114
|
-
* - Unix: `$XDG_CONFIG_HOME` or `~/.config`
|
|
115
|
-
* - Windows: `%APPDATA%` or `~\AppData\Roaming`
|
|
116
|
-
*
|
|
117
|
-
* Config discovery appends the app-specific subdirectory.
|
|
118
|
-
*/
|
|
119
|
-
readonly configDir: string;
|
|
120
|
-
/**
|
|
121
|
-
* User-scope config roots for discovery, highest priority first.
|
|
122
|
-
*
|
|
123
|
-
* - Unix: `[configDir]`
|
|
124
|
-
* - macOS: `[configDir, ~/Library/Application Support]`
|
|
125
|
-
* - Windows: `[configDir]`
|
|
126
|
-
*
|
|
127
|
-
* When absent, discovery falls back to `[configDir]`.
|
|
128
|
-
*/
|
|
129
|
-
readonly userConfigDirs?: readonly string[];
|
|
130
|
-
/**
|
|
131
|
-
* System-scope config roots for discovery (`['/etc']` on Linux and
|
|
132
|
-
* macOS, `[]` on Windows). When absent, discovery probes none.
|
|
133
|
-
*/
|
|
134
|
-
readonly systemConfigDirs?: readonly string[];
|
|
135
|
-
}
|
|
136
|
-
/** Current terminal dimensions in columns and rows. */
|
|
137
|
-
interface TerminalSize {
|
|
138
|
-
/** Terminal width in columns. */
|
|
139
|
-
readonly columns: number;
|
|
140
|
-
/** Terminal height in rows. */
|
|
141
|
-
readonly rows: number;
|
|
142
|
-
}
|
|
143
|
-
/**
|
|
144
|
-
* Options for creating a test adapter.
|
|
145
|
-
*
|
|
146
|
-
* All fields are optional — sensible defaults are applied for testing
|
|
147
|
-
* scenarios (empty argv, empty env, noop stdout/stderr, non-TTY, exit
|
|
148
|
-
* throws instead of killing the process).
|
|
149
|
-
*/
|
|
150
|
-
interface TestAdapterOptions {
|
|
151
|
-
/** Raw argv (defaults to `['node', 'test']`). */
|
|
152
|
-
readonly argv?: readonly string[];
|
|
153
|
-
/** Environment variables (defaults to `{}`). */
|
|
154
|
-
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
155
|
-
/** Working directory (defaults to `'/test'`). */
|
|
156
|
-
readonly cwd?: string;
|
|
157
|
-
/** Stdout writer (defaults to noop). */
|
|
158
|
-
readonly stdout?: WriteFn;
|
|
159
|
-
/** Stderr writer (defaults to noop). */
|
|
160
|
-
readonly stderr?: WriteFn;
|
|
161
|
-
/**
|
|
162
|
-
* Stdin line reader (defaults to returning `null` — immediate EOF).
|
|
163
|
-
*
|
|
164
|
-
* Use a custom {@linkcode ReadFn} to simulate user input in tests.
|
|
165
|
-
*/
|
|
166
|
-
readonly stdin?: ReadFn;
|
|
167
|
-
/** Hidden reader stub; omitted adapters report unsupported hidden input. */
|
|
168
|
-
readonly readSecret?: ReadFn;
|
|
169
|
-
/**
|
|
170
|
-
* Piped stdin data for testing args with `.stdin()` configured.
|
|
171
|
-
*
|
|
172
|
-
* When provided and `stdinIsTTY` is `false`, `readStdin()` returns this
|
|
173
|
-
* string once, then `null` on subsequent reads. When absent, or when
|
|
174
|
-
* `stdinIsTTY` is `true`, `readStdin()` returns `null`.
|
|
175
|
-
*
|
|
176
|
-
* @example
|
|
177
|
-
* ```ts
|
|
178
|
-
* createTestAdapter({
|
|
179
|
-
* stdinData: '{"key": "value"}',
|
|
180
|
-
* })
|
|
181
|
-
* ```
|
|
182
|
-
*/
|
|
183
|
-
readonly stdinData?: string;
|
|
184
|
-
/** TTY flag for stdout (defaults to `false`). */
|
|
185
|
-
readonly isTTY?: boolean;
|
|
186
|
-
/** TTY flag for stdin (defaults to `false`). */
|
|
187
|
-
readonly stdinIsTTY?: boolean;
|
|
188
|
-
/** Terminal dimensions returned by `getTerminalSize()`. */
|
|
189
|
-
readonly terminalSize?: TerminalSize;
|
|
190
|
-
/** Resize subscription hook returned by `onTerminalResize()`. */
|
|
191
|
-
readonly onTerminalResize?: (listener: () => void) => (() => void) | undefined;
|
|
192
|
-
/**
|
|
193
|
-
* Exit function (defaults to throwing {@linkcode ExitError}).
|
|
194
|
-
* The default throw-based exit allows tests to catch the exit code.
|
|
195
|
-
*/
|
|
196
|
-
readonly exit?: (code: number) => never;
|
|
197
|
-
/**
|
|
198
|
-
* File reader stub (defaults to returning `null` — all files not found).
|
|
199
|
-
*
|
|
200
|
-
* Supply a custom function to simulate a virtual filesystem in tests:
|
|
201
|
-
* ```ts
|
|
202
|
-
* createTestAdapter({
|
|
203
|
-
* readFile: (path) => Promise.resolve(
|
|
204
|
-
* path === '/home/test/.config/myapp/config.json'
|
|
205
|
-
* ? '{"region":"eu"}'
|
|
206
|
-
* : null
|
|
207
|
-
* ),
|
|
208
|
-
* })
|
|
209
|
-
* ```
|
|
210
|
-
*/
|
|
211
|
-
readonly readFile?: (path: string) => Promise<string | null>;
|
|
212
|
-
/**
|
|
213
|
-
* Filesystem probe stub for `flag.path()` checks (defaults to returning
|
|
214
|
-
* `null` — nothing exists).
|
|
215
|
-
*
|
|
216
|
-
* Supply a custom function to simulate a virtual filesystem in tests:
|
|
217
|
-
* ```ts
|
|
218
|
-
* createTestAdapter({
|
|
219
|
-
* stat: (path) => Promise.resolve(path === '/data' ? 'directory' : null),
|
|
220
|
-
* })
|
|
221
|
-
* ```
|
|
222
|
-
*/
|
|
223
|
-
readonly stat?: (path: string) => Promise<'file' | 'directory' | null>;
|
|
224
|
-
/**
|
|
225
|
-
* Directory creation stub for `flag.path()` `create` checks (defaults to
|
|
226
|
-
* a noop that resolves without creating anything).
|
|
227
|
-
*/
|
|
228
|
-
readonly mkdir?: (path: string) => Promise<void>;
|
|
229
|
-
/** Home directory (defaults to `'/home/test'`). */
|
|
230
|
-
readonly homedir?: string;
|
|
231
|
-
/** Config directory (defaults to `'/home/test/.config'`). */
|
|
232
|
-
readonly configDir?: string;
|
|
233
|
-
/** User-scope config roots for discovery (defaults to `[configDir]`). */
|
|
234
|
-
readonly userConfigDirs?: readonly string[];
|
|
235
|
-
/** System-scope config roots for discovery (defaults to `[]`). */
|
|
236
|
-
readonly systemConfigDirs?: readonly string[];
|
|
237
|
-
}
|
|
238
|
-
/**
|
|
239
|
-
* Error thrown by adapter implementations that model process exit as an
|
|
240
|
-
* exception instead of terminating immediately.
|
|
241
|
-
*
|
|
242
|
-
* Runtime and CLI dispatch layers can catch this to perform real process
|
|
243
|
-
* termination, while tests can assert on exit codes without killing the
|
|
244
|
-
* runner:
|
|
245
|
-
*
|
|
246
|
-
* ```ts
|
|
247
|
-
* try {
|
|
248
|
-
* await cli.run({ adapter: createTestAdapter() });
|
|
249
|
-
* } catch (e) {
|
|
250
|
-
* if (e instanceof ExitError) expect(e.code).toBe(0);
|
|
251
|
-
* }
|
|
252
|
-
* ```
|
|
253
|
-
*/
|
|
254
|
-
declare class ExitError extends Error {
|
|
255
|
-
/** Error name — always `'ExitError'` for `instanceof` checks. */
|
|
256
|
-
readonly name = "ExitError";
|
|
257
|
-
/** The exit code passed to `exit()`. */
|
|
258
|
-
readonly code: number;
|
|
259
|
-
/** Create an ExitError for the given process exit code. */
|
|
260
|
-
constructor(code: number);
|
|
261
|
-
}
|
|
262
|
-
/**
|
|
263
|
-
* Create a test runtime adapter with injectable process state.
|
|
264
|
-
*
|
|
265
|
-
* Use this in `@kjanat/dreamcli/testkit` tests when you need to simulate argv,
|
|
266
|
-
* environment variables, TTY state, stdin, or config-file reads without
|
|
267
|
-
* touching the host process.
|
|
268
|
-
*
|
|
269
|
-
* @param options - Optional overrides for any adapter field.
|
|
270
|
-
* @returns A {@linkcode RuntimeAdapter} suitable for test scenarios.
|
|
271
|
-
*
|
|
272
|
-
* @example
|
|
273
|
-
* ```ts
|
|
274
|
-
* const adapter = createTestAdapter({
|
|
275
|
-
* argv: ['node', 'cli.js', 'deploy', '--force'],
|
|
276
|
-
* env: { DEPLOY_REGION: 'us' },
|
|
277
|
-
* });
|
|
278
|
-
*
|
|
279
|
-
* const result = await cli('mycli').run({ adapter });
|
|
280
|
-
* ```
|
|
281
|
-
*/
|
|
282
|
-
declare function createTestAdapter(options?: TestAdapterOptions): RuntimeAdapter;
|
|
283
|
-
export { createTestAdapter as a, TestAdapterOptions as i, RuntimeAdapter as n, TerminalSize as r, ExitError as t };
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{t as __exportAll}from"./rolldown-runtime-G4Kt5YOX.mjs";import{J as createFlagSchema,M as flagExpectsValue,X as getFlagAliasNames,Z as getFlagNegatedName,et as builtinEnabled,f as resolveRootSurface,k as resolvePlainHelpDescription,m as collectPropagatedFlags,tt as CLIError}from"./core-B9YNSJeA.mjs";import{DREAMCLI_REVISION,DREAMCLI_VERSION}from"./version.mjs";function versionTag(){let e=` (${DREAMCLI_REVISION})`;return`@kjanat/dreamcli v${DREAMCLI_VERSION}${e}`}function programTag(e){return e.version===void 0?e.name:`${e.name} v${e.version}`}function resolveRootCompletionSurface(e,t=`subcommands`){let n=resolveRootSurface(e),r=createRootFlags(builtinEnabled(e.builtins,`help`),e.version!==void 0),i=n.visibleDefaultCommand?.flags??{},a=t===`surface`?n.hasVisibleDefault:n.hasVisibleDefault&&!n.hasVisibleSubcommands,o=n.visibleDefaultCommand,s=o!==void 0&&n.visibleCommands.some(e=>e.name===o.name);return{visibleCommands:n.defaultRouted&&o!==void 0&&!s?[o,...n.visibleCommands]:n.defaultRouted?n.visibleCommands:n.visibleSubcommands,visibleDefaultCommand:n.visibleDefaultCommand,rootFlags:r,defaultFlags:i,includeDefaultFlags:a}}function createRootFlags(e,t){return{...e?{help:createSyntheticRootFlag(`Show help text`)}:{},...t?{version:createSyntheticRootFlag(`Show version`)}:{}}}function createSyntheticRootFlag(e){return createFlagSchema(`boolean`,{description:e})}function walkCommandTree(e,t=[]){let n=[];for(let r of e){if(r.hidden)continue;let e=[...t,r],i=collectPropagatedFlags(e),a={...i,...r.flags},o=r.commands.filter(e=>!e.hidden);n.push({path:e.map(e=>e.name),schema:r,propagatedFlags:i,mergedFlags:a,children:o}),o.length>0&&n.push(...walkCommandTree(o,e))}return n}function getVisibleNegatedName(e,t){if(!(t.negation===void 0||t.negation.hidden))return getFlagNegatedName(e,t)}function sanitizeShellIdentifier(e){let t=e.replace(/[^a-zA-Z0-9_]/g,`_`);if(t===e)return t;let n=2166136261;for(let t=0;t<e.length;t+=1)n^=e.charCodeAt(t),n=Math.imul(n,16777619);return`${t}_${(n>>>0).toString(16).padStart(8,`0`)}`}function quoteShellArg(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:`'${e.replace(/'/g,`'\\''`)}'`}function generateBashCompletion(e,t){let n=`_${sanitizeShellIdentifier(t?.functionPrefix??e.name)}_completions`,r=resolveRootCompletionSurface(e,t?.rootMode),i=r.visibleCommands,a=walkCommandTree(i),o=a.reduce((e,t)=>Math.max(e,t.path.length),0),s=[];if(s.push(`#!/usr/bin/env bash`),s.push(`# Bash completion for ${programTag(e)}`),s.push(`# Generated by ${versionTag()}`),s.push(`#`),s.push(`# Usage: source <(${e.name} completions bash)`),s.push(`#`),s.push(`# Install permanently:`),s.push(`# ${e.name} completions bash > /etc/bash_completion.d/${e.name} # Linux`),s.push(`# ${e.name} completions bash > $(brew --prefix)/etc/bash_completion.d/${e.name} # macOS`),s.push(`#`),s.push(`# Requires: bash-completion (provides _init_completion)`),s.push(``),s.push(`${n}() {`),s.push(` local cur prev words cword`),s.push(` _init_completion || return`),s.push(``),i.length>0){let e=a.filter(e=>e.children.length>0),t=collectValueFlagPattern(a,r);s.push(` # Build subcommand path by scanning COMP_WORDS`),s.push(` local subcmd_path=""`),s.push(` local i`),s.push(` for ((i = 1; i < cword; i++)); do`),s.push(' case "${words[i]}" in'),s.push(` --) break ;;`),t.length>0&&s.push(`\t\t\t${t}) ((i++)); continue ;;`),s.push(` -*) continue ;;`),s.push(` esac`),emitBashPathDetection(s,i,e,o),s.push(` done`),s.push(``),s.push(` # Complete flags and subcommands for the active path`),s.push(` case "$subcmd_path" in`);for(let e of a){let t=e.path.join(` `),n=e.mergedFlags,r=collectEnumCasesFromFlags(n),i=collectFlagWords(n),a=dedupeWords(e.children.flatMap(e=>[e.name,...e.aliases])).map(escapeForSingleQuote).join(` `),o=i.split(` `).filter(Boolean).map(escapeForSingleQuote).join(` `),c=a.length>0?`${a} ${o}`:o;if(s.push(`\t\t${quoteShellCasePattern(t)})`),r.length>0){s.push(` local enum_flag=""`),s.push(` local enum_cur="$cur"`),s.push(` local enum_prefix=""`),s.push(` if [[ "$cur" == --*=* ]]; then`),s.push(' enum_flag="${cur%%=*}"'),s.push(' enum_cur="${cur#*=}"'),s.push(' enum_prefix="${cur%%=*}="'),s.push(` fi`),s.push(' case "${enum_flag:-$prev}" in');for(let e of r)s.push(`\t\t\t\t${e.flags})`),s.push(formatBashEnumCompletion(e.values,` `,`enum_cur`,`enum_prefix`)),s.push(` return`),s.push(` ;;`);s.push(` *)`),s.push(` ;;`),s.push(` esac`)}s.push(`\t\t\tCOMPREPLY=($(compgen -W '${c.trim()}' -- "$cur"))`),s.push(` return`),s.push(` ;;`)}s.push(` *)`),s.push(` ;;`),s.push(` esac`),s.push(``);let n=collectFlagWords(r.rootFlags).split(` `).filter(Boolean),c=r.includeDefaultFlags?collectFlagWords(r.defaultFlags).split(` `).filter(Boolean):[],l=dedupeWords([...i.flatMap(e=>[e.name,...e.aliases]),...n,...c]).map(escapeForSingleQuote).join(` `);s.push(` # Root-level completions: visible root surface`),s.push(`\tCOMPREPLY=($(compgen -W '${l}' -- "$cur"))`)}else{let e=collectFlagWords({...r.rootFlags,...r.includeDefaultFlags?r.defaultFlags:{}});s.push(`\tCOMPREPLY=($(compgen -W '${e}' -- "$cur"))`)}return s.push(`}`),s.push(``),s.push(`complete -F ${n} ${quoteShellArg(e.name)}`),s.push(``),s.join(`
|
|
2
|
-
`)}function emitBashPathDetection(e,t,n,r){e.push(` case "$subcmd_path" in`),e.push(` '')`),e.push(' case "${words[i]}" in');for(let n of t){let t=[n.name,...n.aliases].map(escapeBashCasePatternValue);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="${escapeBashDoubleQuotedValue(n.name)}"`),e.push(` ;;`)}if(e.push(` esac`),e.push(` ;;`),r>1)for(let t of n){let n=t.path.join(` `);e.push(`\t\t\t${quoteShellCasePattern(n)})`),e.push(' case "${words[i]}" in');for(let n of t.children){let t=[n.name,...n.aliases].map(escapeBashCasePatternValue);e.push(`\t\t\t\t\t${t.join(`|`)})`),e.push(`\t\t\t\t\t\tsubcmd_path="$subcmd_path ${escapeBashDoubleQuotedValue(n.name)}"`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`)}e.push(` esac`)}function quoteShellCasePattern(e){return e.includes(` `)?`"${escapeBashDoubleQuotedValue(e)}"`:escapeBashCasePatternValue(e)}function escapeBashCasePatternValue(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function escapeBashDoubleQuotedValue(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\$/g,`\\$`).replace(/`/g,"\\`")}function escapeForSingleQuote(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/'/g,`'\\''`)}function formatBashEnumCompletion(e,t,n=`cur`,r){let i=[];if(e.some(e=>!/^[a-zA-Z0-9_\-.]+$/.test(e))){let r=e.map(escapeBashDollarQuote).join(`\\n`);i.push(`${t}local IFS=$'\\n'`),i.push(`${t}COMPREPLY=($(compgen -W $'${r}' -- "$${n}"))`)}else i.push(`${t}COMPREPLY=($(compgen -W '${e.join(` `)}' -- "$${n}"))`);return r!==void 0&&(i.push(`${t}if [[ -n "$${r}" && "\${#COMPREPLY[@]}" -gt 0 ]]; then`),i.push(`${t}\tlocal i`),i.push(`${t}\tfor ((i = 0; i < \${#COMPREPLY[@]}; i++)); do`),i.push(`${t}\t\tCOMPREPLY[i]="$${r}\${COMPREPLY[i]}"`),i.push(`${t}\tdone`),i.push(`${t}fi`)),i.join(`
|
|
3
|
-
`)}function escapeBashDollarQuote(e){return e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/\n/g,`\\n`)}function collectFlagWords(e){let t=[];for(let[n,r]of Object.entries(e)){t.push(`--${n}`);for(let e of getFlagAliasNames(r))t.push(e.length===1?`-${e}`:`--${e}`);let e=getVisibleNegatedName(n,r);e!==void 0&&t.push(`--${e}`)}return t.join(` `)}function collectValueFlagPattern(e,t){let n=/* @__PURE__ */ new Set,r=e=>{for(let[t,r]of Object.entries(e))if(flagExpectsValue(r)){n.add(`--${t}`);for(let e of getFlagAliasNames(r,{includeHidden:!0}))n.add(e.length===1?`-${e}`:`--${e}`)}};for(let t of e)r(t.mergedFlags);return r(t.rootFlags),t.includeDefaultFlags&&r(t.defaultFlags),[...n].map(escapeBashCasePatternValue).join(`|`)}function dedupeWords(e){return[...new Set(e)]}function collectEnumCasesFromFlags(e){let t=[];for(let[n,r]of Object.entries(e)){if(r.kind!==`enum`||r.enumValues===void 0)continue;let e=[`--${n}`,...getFlagAliasNames(r,{includeHidden:!0}).map(e=>e.length===1?`-${e}`:`--${e}`)].map(escapeBashCasePatternValue);t.push({flags:e.join(`|`),values:r.enumValues})}return t}function generateFishCompletion(e,t){let n=`__${sanitizeShellIdentifier(t?.functionPrefix??e.name)}_completions`,r=`${n}_path`,i=`${n}_path_is`,a=resolveRootCompletionSurface(e,t?.rootMode),o=a.visibleCommands,s=walkCommandTree(o),c=quoteShellArg(e.name),l=[];l.push(`# Fish completion for ${programTag(e)}`),l.push(`# Generated by ${versionTag()}`),l.push(`#`),l.push(`# Usage: source (${e.name} completions fish | psub)`),l.push(`#`),l.push(`# Install permanently:`),l.push(`# ${e.name} completions fish > ~/.config/fish/completions/${e.name}.fish`),l.push(``),l.push(`complete -c ${c} -f`),l.push(``),emitFishPathHelpers(l,r,i,o,s,a),appendFishCommandCompletions(l,c,i,``,o),appendFishFlagCompletions(l,c,i,``,a.rootFlags),a.includeDefaultFlags&&appendFishFlagCompletions(l,c,i,``,a.defaultFlags);for(let e of s){let t=e.path.join(` `);appendFishCommandCompletions(l,c,i,t,e.children),appendFishFlagCompletions(l,c,i,t,e.mergedFlags)}return l.join(`
|
|
4
|
-
`)}function emitFishPathHelpers(e,t,n,r,i,a){let o=collectFishValueFlagPatterns(i,a);e.push(`function ${t}`),e.push(` set -l words (commandline -opc)`),e.push(` if test (count $words) -gt 0`),e.push(` set -e words[1]`),e.push(` end`),e.push(` set -l subcmd_path ''`),e.push(` set -l expect_value 0`),e.push(` for word in $words`),e.push(` if test $expect_value -eq 1`),e.push(` set expect_value 0`),e.push(` continue`),e.push(` end`),e.push(` switch $word`),e.push(` case '--'`),e.push(` break`),o.exact.length>0&&(e.push(`\t\t\tcase ${o.exact.map(quoteShellArg).join(` `)}`),e.push(` set expect_value 1`),e.push(` continue`)),o.prefix.length>0&&(e.push(`\t\t\tcase ${o.prefix.map(quoteShellArg).join(` `)}`),e.push(` continue`)),e.push(` case '-*'`),e.push(` continue`),e.push(` end`),e.push(` switch "$subcmd_path|$word"`);for(let t of r)for(let n of[t.name,...t.aliases])e.push(`\t\t\tcase ${quoteShellArg(`|${n}`)}`),e.push(`\t\t\t\tset subcmd_path ${quoteShellArg(t.name)}`);for(let t of i)for(let n of t.children)for(let r of[n.name,...n.aliases])e.push(`\t\t\tcase ${quoteShellArg(`${t.path.join(` `)}|${r}`)}`),e.push(`\t\t\t\tset subcmd_path ${quoteShellArg(`${t.path.join(` `)} ${n.name}`)}`);e.push(` case '*'`),e.push(` break`),e.push(` end`),e.push(` end`),e.push(` printf '%s\\n' "$subcmd_path"`),e.push(`end`),e.push(``),e.push(`function ${n}`),e.push(` set -l expected "$argv[1]"`),e.push(`\ttest (${t}) = "$expected"`),e.push(`end`),e.push(``)}function appendFishCommandCompletions(e,t,n,r,i){let a=buildFishCondition(n,r);for(let n of i){let r=quoteShellArg(n.description??n.name);for(let i of[n.name,...n.aliases])e.push(`complete -c ${t} -n "${a}" -a ${quoteShellArg(i)} -d ${r}`)}i.length>0&&e.push(``)}function appendFishFlagCompletions(e,t,n,r,i){let a=buildFishCondition(n,r);for(let[n,r]of Object.entries(i)){let i=[`complete -c ${t}`,`-n "${a}"`];for(let e of getFlagAliasNames(r,{kind:`short`}))i.push(`-s ${quoteShellArg(e)}`);i.push(`-l ${quoteShellArg(n)}`);for(let e of getFlagAliasNames(r,{kind:`long`}))i.push(`-l ${quoteShellArg(e)}`);let o=getVisibleNegatedName(n,r);if(o!==void 0&&i.push(`-l ${quoteShellArg(o)}`),i.push(`-d ${quoteShellArg(r.description===void 0?n:resolvePlainHelpDescription(r.description))}`),flagExpectsValue(r)&&i.push(`-r`,`-f`),r.kind===`enum`&&r.enumValues!==void 0)for(let t of r.enumValues)e.push([...i,`-a ${quoteShellArg(t)}`].join(` `));else e.push(i.join(` `))}Object.keys(i).length>0&&e.push(``)}function collectFishValueFlagPatterns(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=[t.rootFlags,...t.includeDefaultFlags?[t.defaultFlags]:[],...e.map(e=>e.mergedFlags)];for(let e of i)for(let[t,i]of Object.entries(e))if(flagExpectsValue(i)){n.add(`--${t}`),r.add(`--${t}=*`);for(let e of getFlagAliasNames(i,{kind:`short`,includeHidden:!0}))n.add(`-${e}`),r.add(`-${e}*`);for(let e of getFlagAliasNames(i,{kind:`long`,includeHidden:!0}))n.add(`--${e}`),r.add(`--${e}=*`)}return{exact:[...n],prefix:[...r]}}function buildFishCondition(e,t){return`${e} ${quoteShellArg(t)}`}function generatePowerShellCompletion(e,t){let n=`__${sanitizeShellIdentifier(t?.functionPrefix??e.name)}_completions`,r=`${n}_paths`,i=resolveRootCompletionSurface(e,t?.rootMode),a=i.visibleCommands,o=walkCommandTree(a),s=[];return s.push(`# PowerShell completion for ${programTag(e)}`),s.push(`# Generated by ${versionTag()}`),s.push(`#`),s.push(`# Install for the current session:`),s.push(`# ${e.name} completions powershell | Out-String | Invoke-Expression`),s.push(`#`),s.push(`# Install permanently:`),s.push(`# ${e.name} completions powershell > $PROFILE.CurrentUserCurrentHost`),s.push(``),s.push(`using namespace System.Management.Automation`),s.push(`using namespace System.Management.Automation.Language`),s.push(``),emitPowerShellPathTable(s,r,i,o),s.push(``),emitPowerShellHelpers(s,n,r),s.push(``),s.push(`Register-ArgumentCompleter -Native -CommandName ${quotePowerShellString(e.name)} -ScriptBlock {`),s.push(` param($wordToComplete, $commandAst, $cursorPosition)`),s.push(`\t$state = ${n}_GetState -CommandAst $commandAst -CursorPosition $cursorPosition`),s.push(` if ($null -eq $state.PathData) {`),s.push(` return`),s.push(` }`),s.push(``),s.push(` $results = [System.Collections.Generic.List[CompletionResult]]::new()`),s.push(` if ($state.AfterSeparator) {`),s.push(` return $results`),s.push(` }`),s.push(``),s.push(` $wordPrefix = if ([string]::IsNullOrEmpty($wordToComplete)) { '' } else { $wordToComplete }`),s.push(``),s.push(` if ($state.ExpectingValue) {`),s.push(`\t\t${n}_AddEnumResults -Results $results -Flag $state.ValueFlag -WordToComplete $wordPrefix`),s.push(` return $results`),s.push(` }`),s.push(``),s.push(`\t$inlineValue = ${n}_ResolveInlineValueCompletion -PathData $state.PathData -WordToComplete $wordPrefix`),s.push(` if ($null -ne $inlineValue) {`),s.push(`\t\t${n}_AddInlineEnumResults -Results $results -InlineValue $inlineValue -WordToComplete $wordPrefix`),s.push(` return $results`),s.push(` }`),s.push(``),s.push(` if ($wordPrefix.StartsWith('-')) {`),s.push(`\t\t${n}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),s.push(` return $results`),s.push(` }`),s.push(``),s.push(`\t${n}_AddCommandResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),s.push(`\t${n}_AddFlagResults -Results $results -PathData $state.PathData -WordToComplete $wordPrefix`),s.push(` return $results`),s.push(`}`),s.join(`
|
|
5
|
-
`)}function emitPowerShellPathTable(e,t,n,r){e.push(`$script:${t} = @{`),appendPowerShellPathEntry(e,``,n.visibleCommands,{...n.rootFlags,...n.includeDefaultFlags?n.defaultFlags:{}});for(let t of r)appendPowerShellPathEntry(e,t.path.join(` `),t.children,t.mergedFlags);e.push(`}`)}function appendPowerShellPathEntry(e,t,n,r){e.push(`\t${quotePowerShellString(t)} = @{`),e.push(` Commands = @(`);for(let t of n)e.push(` @{`),e.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(t.name)}`),e.push(`\t\t\t\tNames = ${formatPowerShellArray([t.name,...t.aliases])}`),e.push(`\t\t\t\tDescription = ${quotePowerShellString(t.description??t.name)}`),e.push(` }`);e.push(` )`),e.push(` Flags = @(`);for(let[t,n]of Object.entries(r)){let r=getVisibleNegatedName(t,n),i=getFlagNegatedName(t,n),a=dedupeValues([`--${t}`,...getFlagAliasNames(n,{kind:`short`}).map(e=>`-${e}`),...getFlagAliasNames(n,{kind:`long`}).map(e=>`--${e}`),...r===void 0?[]:[`--${r}`]]),o=dedupeValues([`--${t}`,...getFlagAliasNames(n,{kind:`short`,includeHidden:!0}).map(e=>`-${e}`),...getFlagAliasNames(n,{kind:`long`,includeHidden:!0}).map(e=>`--${e}`),...i===void 0?[]:[`--${i}`]]);e.push(` @{`),e.push(`\t\t\t\tCanonicalName = ${quotePowerShellString(t)}`),e.push(`\t\t\t\tForms = ${formatPowerShellArray(a)}`),e.push(`\t\t\t\tParseForms = ${formatPowerShellArray(o)}`),e.push(`\t\t\t\tRequiresValue = ${flagExpectsValue(n)?`$true`:`$false`}`),e.push(`\t\t\t\tDescription = ${quotePowerShellString(n.description===void 0?t:resolvePlainHelpDescription(n.description))}`),e.push(`\t\t\t\tEnumValues = ${formatPowerShellArray(n.enumValues??[])}`),e.push(` }`)}e.push(` )`),e.push(` }`)}function emitPowerShellHelpers(e,t,n){e.push(`function ${t}_UnquoteToken {`),e.push(` param([string]$TokenText)`),e.push(` if ($TokenText.Length -lt 2) {`),e.push(` return $TokenText`),e.push(` }`),e.push(``),e.push(` if (($TokenText.StartsWith("'") -and $TokenText.EndsWith("'")) -or`),e.push(` ($TokenText.StartsWith('"') -and $TokenText.EndsWith('"'))) {`),e.push(` return $TokenText.Substring(1, $TokenText.Length - 2)`),e.push(` }`),e.push(``),e.push(` return $TokenText`),e.push(`}`),e.push(``),e.push(`function ${t}_FindCommand {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if ($name -eq $Token) {`),e.push(` return $command`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveFlagToken {`),e.push(` param($PathData, [string]$Token)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.ParseForms) {`),e.push(` if ($Token -eq $form) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $null }`),e.push(` }`),e.push(``),e.push(` if (-not $flag.RequiresValue) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('--') -and $Token.StartsWith("$form=")) {`),e.push(` return @{ Flag = $flag; InlinePrefix = "$form=" }`),e.push(` }`),e.push(``),e.push(` if ($form.StartsWith('-') -and -not $form.StartsWith('--') -and $Token.StartsWith($form) -and $Token.Length -gt $form.Length) {`),e.push(` return @{ Flag = $flag; InlinePrefix = $form }`),e.push(` }`),e.push(` }`),e.push(` }`),e.push(` return $null`),e.push(`}`),e.push(``),e.push(`function ${t}_GetState {`),e.push(` param([CommandAst]$CommandAst, [int]$CursorPosition)`),e.push(`\t$pathData = $script:${n}[${quotePowerShellString(``)}]`),e.push(` $path = ""`),e.push(` $afterSeparator = $false`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` $tokens = [System.Collections.Generic.List[string]]::new()`),e.push(``),e.push(` foreach ($element in $CommandAst.CommandElements | Select-Object -Skip 1) {`),e.push(` if ($element.Extent.EndOffset -ge $CursorPosition) {`),e.push(` break`),e.push(` }`),e.push(`\t\t$tokenText = ${t}_UnquoteToken $element.Extent.Text`),e.push(` [void]$tokens.Add($tokenText)`),e.push(` }`),e.push(``),e.push(` foreach ($token in $tokens) {`),e.push(` if ($expectingValue) {`),e.push(` $expectingValue = $false`),e.push(` $valueFlag = $null`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token -eq '--') {`),e.push(` $afterSeparator = $true`),e.push(` break`),e.push(` }`),e.push(``),e.push(`\t\t$flagMatch = ${t}_ResolveFlagToken -PathData $pathData -Token $token`),e.push(` if ($null -ne $flagMatch) {`),e.push(` if ($flagMatch.InlinePrefix -eq $null -and $flagMatch.Flag.RequiresValue) {`),e.push(` $expectingValue = $true`),e.push(` $valueFlag = $flagMatch.Flag`),e.push(` }`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` if ($token.StartsWith('-')) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(`\t\t$command = ${t}_FindCommand -PathData $pathData -Token $token`),e.push(` if ($null -eq $command) {`),e.push(` break`),e.push(` }`),e.push(``),e.push(` $path = if ([string]::IsNullOrEmpty($path)) {`),e.push(` $command.CanonicalName`),e.push(` } else {`),e.push(` "$path $($command.CanonicalName)"`),e.push(` }`),e.push(`\t\t$nextPathData = $script:${n}[$path]`),e.push(` if ($null -eq $nextPathData) {`),e.push(` break`),e.push(` }`),e.push(` $pathData = $nextPathData`),e.push(` }`),e.push(``),e.push(` return @{`),e.push(` Path = $path`),e.push(` PathData = $pathData`),e.push(` AfterSeparator = $afterSeparator`),e.push(` ExpectingValue = $expectingValue`),e.push(` ValueFlag = $valueFlag`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_ResolveInlineValueCompletion {`),e.push(` param($PathData, [string]$WordToComplete)`),e.push(`\t$flagMatch = ${t}_ResolveFlagToken -PathData $PathData -Token $WordToComplete`),e.push(` if ($null -eq $flagMatch -or $flagMatch.InlinePrefix -eq $null) {`),e.push(` return $null`),e.push(` }`),e.push(` return $flagMatch`),e.push(`}`),e.push(``),e.push(`function ${t}_FormatCompletionValue {`),e.push(` param([string]$Value)`),e.push(` if ($Value.Length -eq 0) {`),e.push(` return "''"`),e.push(` }`),e.push(``),e.push(` if ($Value -match '^[a-zA-Z0-9_./:\\\\-]+$') {`),e.push(` return $Value`),e.push(` }`),e.push(``),e.push(` return "'$([CodeGeneration]::EscapeSingleQuotedStringContent($Value))'"`),e.push(`}`),e.push(``),e.push(`function ${t}_MatchesCompletionPrefix {`),e.push(` param([string]$WordToComplete, [string]$RawText, [string]$CompletionText)`),e.push(` if ([string]::IsNullOrEmpty($WordToComplete)) {`),e.push(` return $true`),e.push(` }`),e.push(``),e.push(` return $RawText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase) -or $CompletionText.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)`),e.push(`}`),e.push(``),e.push(`function ${t}_AddCommandResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($command in $PathData.Commands) {`),e.push(` foreach ($name in $command.Names) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $name.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $name,`),e.push(` $name,`),e.push(` [CompletionResultType]::Command,`),e.push(` $command.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddFlagResults {`),e.push(` param($Results, $PathData, [string]$WordToComplete)`),e.push(` foreach ($flag in $PathData.Flags) {`),e.push(` foreach ($form in $flag.Forms) {`),e.push(` if (-not [string]::IsNullOrEmpty($WordToComplete) -and -not $form.StartsWith($WordToComplete, [System.StringComparison]::OrdinalIgnoreCase)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $form,`),e.push(` $form,`),e.push(` [CompletionResultType]::ParameterName,`),e.push(` $flag.Description`),e.push(` ))`),e.push(` }`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddEnumResults {`),e.push(` param($Results, $Flag, [string]$WordToComplete)`),e.push(` foreach ($value in $Flag.EnumValues) {`),e.push(`\t\t$completionText = ${t}_FormatCompletionValue -Value $value`),e.push(`\t\tif (-not (${t}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $value -CompletionText $completionText)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $completionText,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`),e.push(``),e.push(`function ${t}_AddInlineEnumResults {`),e.push(` param($Results, $InlineValue, [string]$WordToComplete)`),e.push(` foreach ($value in $InlineValue.Flag.EnumValues) {`),e.push(` $rawCompletion = "$($InlineValue.InlinePrefix)$value"`),e.push(`\t\t$formattedValue = ${t}_FormatCompletionValue -Value $value`),e.push(` $completionText = "$($InlineValue.InlinePrefix)$formattedValue"`),e.push(`\t\tif (-not (${t}_MatchesCompletionPrefix -WordToComplete $WordToComplete -RawText $rawCompletion -CompletionText $completionText)) {`),e.push(` continue`),e.push(` }`),e.push(``),e.push(` $Results.Add([CompletionResult]::new(`),e.push(` $completionText,`),e.push(` $value,`),e.push(` [CompletionResultType]::ParameterValue,`),e.push(` $InlineValue.Flag.Description`),e.push(` ))`),e.push(` }`),e.push(`}`)}function quotePowerShellString(e){return`'${e.replace(/'/g,`''`)}'`}function formatPowerShellArray(e){return e.length===0?`@()`:`@(${e.map(quotePowerShellString).join(`, `)})`}function dedupeValues(e){return[...new Set(e)]}function generateZshCompletion(e,t){let n=`_${sanitizeShellIdentifier(t?.functionPrefix??e.name)}`,r=resolveRootCompletionSurface(e,t?.rootMode),i=r.visibleCommands,a=walkCommandTree(i),o=[];o.push(`#compdef ${quoteShellArg(e.name)}`),o.push(`# Zsh completion for ${programTag(e)}`),o.push(`# Generated by ${versionTag()}`),o.push(`#`),o.push(`# Usage: source <(${e.name} completions zsh)`),o.push(`#`),o.push(`# Install permanently:`),o.push(`# ${e.name} completions zsh > "\${fpath[1]}/_${e.name}"`),o.push(`# # Then restart your shell`),o.push(``);let s=a.filter(e=>e.children.length>0),c=a.filter(e=>e.children.length===0);for(let e of c)e.path.length<2||emitZshLeafFunction(o,`${n}_${e.path.map(sanitizeShellIdentifier).join(`_`)}`,e);let l=[...s].sort((e,t)=>t.path.length-e.path.length);for(let e of l)emitZshGroupFunction(o,`${n}_${e.path.map(sanitizeShellIdentifier).join(`_`)}`,n,e);if(o.push(`${n}() {`),i.length>0){o.push(` local -a subcmds`),o.push(` local line state`),o.push(``);let e=buildZshFlagSpecsFromFlags({...r.rootFlags,...r.includeDefaultFlags?r.defaultFlags:{}});o.push(` _arguments -C \\`);for(let t of e)o.push(`\t\t${t} \\`);o.push(` '1: :->subcmd' \\`),o.push(` '*::arg:->args'`),o.push(``),o.push(` case "$state" in`),o.push(` subcmd)`),o.push(` subcmds=(`),appendZshCommandCandidates(o,i,` `),o.push(` )`),o.push(` _describe 'command' subcmds`),o.push(` ;;`),o.push(` args)`),o.push(` case "$line[1]" in`);for(let e of i){let t=[e.name,...e.aliases].map(escapeZshCasePatternValue),r=e.commands.filter(e=>!e.hidden);if(o.push(`\t\t\t\t${t.join(`|`)})`),r.length>0){let t=`${n}_${sanitizeShellIdentifier(e.name)}`;o.push(`\t\t\t\t\t${t}`)}else{let t=a.find(t=>t.path.length===1&&t.schema.name===e.name);if(t===void 0)throw new CLIError(`Missing completion node for command '${e.name}'`,{code:`UNEXPECTED_ERROR`});let n=buildZshFlagSpecsFromFlags(t.mergedFlags);if(n.length>0){o.push(` _arguments \\`);for(let e=0;e<n.length;e++){let t=e<n.length-1?` \\`:``;o.push(`\t\t\t\t\t\t${n[e]}${t}`)}}}o.push(` ;;`)}o.push(` esac`),o.push(` ;;`),o.push(` esac`)}else{let e=buildZshFlagSpecsFromFlags({...r.rootFlags,...r.includeDefaultFlags?r.defaultFlags:{}});o.push(` _arguments \\`);for(let t=0;t<e.length;t++){let n=t<e.length-1?` \\`:``;o.push(`\t\t${e[t]}${n}`)}}return o.push(`}`),o.push(``),o.push(`compdef ${n} ${quoteShellArg(e.name)}`),o.push(``),o.join(`
|
|
6
|
-
`)}function emitZshGroupFunction(e,t,n,r){e.push(`${t}() {`),e.push(` local -a subcmds`),e.push(` local line state`),e.push(``);let i=buildZshFlagSpecsFromFlags(r.mergedFlags);e.push(` _arguments -C \\`);for(let t of i)e.push(`\t\t${t} \\`);e.push(` '1: :->subcmd' \\`),e.push(` '*::arg:->args'`),e.push(``),e.push(` case "$state" in`),e.push(` subcmd)`),e.push(` subcmds=(`),appendZshCommandCandidates(e,r.children,` `),e.push(` )`),e.push(` _describe 'command' subcmds`),e.push(` ;;`),e.push(` args)`),e.push(` case "$line[1]" in`);for(let t of r.children){let i=[t.name,...t.aliases].map(escapeZshCasePatternValue),a=`${n}_${[...r.path,t.name].map(sanitizeShellIdentifier).join(`_`)}`;e.push(`\t\t\t\t${i.join(`|`)})`),e.push(`\t\t\t\t\t${a}`),e.push(` ;;`)}e.push(` esac`),e.push(` ;;`),e.push(` esac`),e.push(`}`),e.push(``)}function emitZshLeafFunction(e,t,n){let r=buildZshFlagSpecsFromFlags(n.mergedFlags);if(e.push(`${t}() {`),r.length>0){e.push(` _arguments \\`);for(let t=0;t<r.length;t++){let n=t<r.length-1?` \\`:``;e.push(`\t\t${r[t]}${n}`)}}e.push(`}`),e.push(``)}function appendZshCommandCandidates(e,t,n){for(let r of t){let t=r.description??r.name;for(let i of[r.name,...r.aliases])e.push(`${n}${quoteShellArg(`${i}:${t}`)}`)}}function escapeZshCasePatternValue(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/'/g,`\\'`).replace(/"/g,`\\"`).replace(/`/g,"\\`").replace(/\|/g,`\\|`).replace(/\*/g,`\\*`).replace(/\?/g,`\\?`).replace(/\[/g,`\\[`).replace(/\]/g,`\\]`).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`).replace(/\{/g,`\\{`).replace(/\}/g,`\\}`).replace(/\+/g,`\\+`).replace(/!/g,`\\!`).replace(/@/g,`\\@`).replace(/#/g,`\\#`).replace(/~/g,`\\~`).replace(/\s/g,e=>e===` `?`\\ `:`\\${e}`)}function escapeZshDescription(e){return e.replace(/\\/g,`\\\\`).replace(/\]/g,`\\]`)}function buildZshFlagSpecsFromFlags(e){let t=[];for(let[n,r]of Object.entries(e)){let e=escapeZshDescription(r.description===void 0?n:resolvePlainHelpDescription(r.description)),i=`--${n}`,a=getFlagAliasNames(r,{kind:`short`}).map(e=>`-${e}`),o=getFlagAliasNames(r,{kind:`long`}).map(e=>`--${e}`),s=getVisibleNegatedName(n,r),c=s===void 0?[]:[`--${s}`],l=[...a,i,...o,...c],u=``;if(flagExpectsValue(r)&&(u=r.kind===`enum`&&r.enumValues!==void 0?`:value:(${r.enumValues.map(escapeZshEnumValue).join(` `)})`:`:value:`),l.length>1){let n=l.map(escapeZshCasePatternValue).join(`,`);t.push(`${quoteShellArg(`(${l.join(` `)})`)}{${n}}${quoteShellArg(`[${e}]${u}`)}`)}else t.push(quoteShellArg(`${i}[${e}]${u}`))}return t}function escapeZshEnumValue(e){return/^[a-zA-Z0-9_\-.]+$/.test(e)?e:e.replace(/\\/g,`\\\\`).replace(/ /g,`\\ `).replace(/\(/g,`\\(`).replace(/\)/g,`\\)`)}var completion_exports=/* @__PURE__ */ __exportAll({generateBashCompletion:()=>generateBashCompletion,generateCompletion:()=>generateCompletion,generateFishCompletion:()=>generateFishCompletion,generatePowerShellCompletion:()=>generatePowerShellCompletion,generateZshCompletion:()=>generateZshCompletion});function generateCompletion(e,t,n){switch(t){case`bash`:return generateBashCompletion(e,n);case`zsh`:return generateZshCompletion(e,n);case`fish`:return generateFishCompletion(e,n);case`powershell`:return generatePowerShellCompletion(e,n)}}export{generateFishCompletion as a,generatePowerShellCompletion as i,generateCompletion as n,generateBashCompletion as o,generateZshCompletion as r,completion_exports as t};
|
package/dist/config-DruA8aFV.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as __exportAll}from"./rolldown-runtime-G4Kt5YOX.mjs";import{tt as CLIError}from"./core-B9YNSJeA.mjs";var config_exports=/* @__PURE__ */ __exportAll({buildConfigSearchPaths:()=>buildConfigSearchPaths,configFormat:()=>configFormat,discoverConfig:()=>discoverConfig});function isPlainObject(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}const jsonLoader={extensions:[`json`],parse:e=>{let t=JSON.parse(e);if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Config must be a JSON object`);return t}};function joinPath(e,...t){let n=e.includes(`\\`)?`\\`:`/`;return[e.endsWith(n)?e.slice(0,-1):e,...t].join(n)}function ancestorDirs(e){let t=e.includes(`\\`)?`\\`:`/`,n=e;for(;n.length>1&&n.endsWith(t)&&!n.endsWith(`:${t}`);)n=n.slice(0,-1);let r=[n];for(;;){let e=n.lastIndexOf(t);if(e<0)break;let i=n.slice(0,e);if(i===``?i=t:/^[A-Za-z]:$/.test(i)&&(i=`${i}${t}`),i===n)break;r.push(i),n=i}return r}function getExtension(e){let t=e.lastIndexOf(`.`);return t<=Math.max(e.lastIndexOf(`/`),e.lastIndexOf(`\\`))?``:e.slice(t+1).toLowerCase()}function buildConfigSearchPaths(e,t){let n=buildExtensionList(t.loaders),r=[];for(let i of ancestorDirs(t.baseDir)){for(let t of n)r.push(joinPath(i,`.${e}.${t}`));for(let t of n)r.push(joinPath(i,`${e}.config.${t}`));for(let t of n)r.push(joinPath(i,`.config`,`${e}.${t}`))}for(let i of t.userConfigDirs)for(let t of n)r.push(joinPath(i,e,`config.${t}`));for(let i of t.systemConfigDirs??[])for(let t of n)r.push(joinPath(i,e,`config.${t}`));return r}function buildExtensionList(e){let t=/* @__PURE__ */ new Set,n=[];for(let e of jsonLoader.extensions){let r=e.toLowerCase();t.has(r)||(t.add(r),n.push(r))}if(e!==void 0)for(let r of e)for(let e of r.extensions){let r=e.toLowerCase();t.has(r)||(t.add(r),n.push(r))}return n}function buildLoaderMap(e){let t=/* @__PURE__ */ new Map;for(let e of jsonLoader.extensions)t.set(e.toLowerCase(),jsonLoader);if(e!==void 0)for(let n of e)for(let e of n.extensions)t.set(e.toLowerCase(),n);return t}async function discoverConfig(e,t,n){let r=buildLoaderMap(n?.loaders),i=n?.configPath===void 0?n?.searchPaths??buildConfigSearchPaths(e,{baseDir:n?.baseDir??t.cwd,userConfigDirs:t.userConfigDirs??[t.configDir],systemConfigDirs:t.systemConfigDirs??[],...n?.loaders===void 0?{}:{loaders:n.loaders}}):[n.configPath];for(let e of i){let i=await t.readFile(e);if(i===null){if(n?.configPath!==void 0)throw new CLIError(`Config file not found: ${e}`,{code:`CONFIG_NOT_FOUND`,details:{path:e},suggest:`Create the config file or remove the --config flag`});continue}let a=getExtension(e),o=r.get(a);if(o===void 0)throw new CLIError(`No loader registered for config format: .${a}`,{code:`CONFIG_UNKNOWN_FORMAT`,details:{path:e,extension:a},suggest:`Supported formats: ${[...r.keys()].join(`, `)}`});try{let t=o.parse(i);if(!isPlainObject(t))throw Error(`Config loader must return a plain object`);return{found:!0,path:e,data:t,format:a}}catch(t){throw new CLIError(`Failed to parse config file: ${e}`,{code:`CONFIG_PARSE_ERROR`,cause:t,details:{path:e,format:a,message:t instanceof Error?t.message:String(t)},suggest:`Check the config file for syntax errors`})}}return{found:!1}}function configFormat(e,t){return{extensions:e,parse:t}}export{discoverConfig as i,configFormat as n,config_exports as r,buildConfigSearchPaths as t};
|