claudeup 4.17.0 → 4.19.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/package.json +1 -1
- package/src/__tests__/alias-adopt.test.ts +364 -0
- package/src/__tests__/alias-parser.test.ts +409 -0
- package/src/__tests__/alias-shell-writer.test.ts +668 -0
- package/src/__tests__/alias-store.test.ts +163 -0
- package/src/__tests__/gitignore-fixer.test.ts +64 -1
- package/src/__tests__/gitignore-prerun.test.ts +2 -2
- package/src/__tests__/gitignore-service.test.ts +42 -0
- package/src/__tests__/marketplaces.test.ts +40 -0
- package/src/__tests__/plugin-manager-fallback.test.ts +120 -0
- package/src/__tests__/plugin-setup.test.ts +111 -0
- package/src/__tests__/useGitignoreModal.test.ts +2 -2
- package/src/data/alias-flags.js +205 -0
- package/src/data/alias-flags.ts +301 -0
- package/src/data/gitignore-reasons.js +97 -0
- package/src/data/gitignore-reasons.ts +103 -0
- package/src/data/marketplaces.js +5 -3
- package/src/data/marketplaces.ts +5 -4
- package/src/services/alias-settings.js +51 -0
- package/src/services/alias-settings.ts +63 -0
- package/src/services/alias-shell-writer.js +1018 -0
- package/src/services/alias-shell-writer.ts +1247 -0
- package/src/services/alias-store.js +129 -0
- package/src/services/alias-store.ts +172 -0
- package/src/services/gitignore-fixer.js +70 -10
- package/src/services/gitignore-fixer.ts +76 -9
- package/src/services/gitignore-prerun.js +3 -3
- package/src/services/gitignore-prerun.ts +3 -3
- package/src/services/gitignore-service.js +20 -2
- package/src/services/gitignore-service.ts +23 -1
- package/src/services/marketplace-fetcher.js +96 -0
- package/src/services/marketplace-fetcher.ts +137 -0
- package/src/services/plugin-manager.js +6 -59
- package/src/services/plugin-manager.ts +16 -91
- package/src/services/plugin-setup.js +59 -4
- package/src/services/plugin-setup.ts +61 -4
- package/src/services/skillsmp-client.js +29 -9
- package/src/services/skillsmp-client.ts +38 -8
- package/src/types/gitignore.ts +1 -1
- package/src/ui/App.js +26 -11
- package/src/ui/App.tsx +25 -10
- package/src/ui/components/FlagDetailEditor.js +0 -0
- package/src/ui/components/FlagDetailEditor.tsx +0 -0
- package/src/ui/components/TabBar.js +2 -1
- package/src/ui/components/TabBar.tsx +2 -1
- package/src/ui/components/layout/FooterHints.js +29 -0
- package/src/ui/components/layout/FooterHints.tsx +52 -0
- package/src/ui/components/layout/ScreenLayout.js +2 -1
- package/src/ui/components/layout/ScreenLayout.tsx +12 -3
- package/src/ui/components/layout/index.js +1 -0
- package/src/ui/components/layout/index.ts +5 -0
- package/src/ui/components/modals/ConfirmModal.js +1 -1
- package/src/ui/components/modals/ConfirmModal.tsx +1 -1
- package/src/ui/components/modals/SelectModal.js +8 -1
- package/src/ui/components/modals/SelectModal.tsx +12 -1
- package/src/ui/hooks/useGitignoreModal.js +7 -8
- package/src/ui/hooks/useGitignoreModal.ts +8 -9
- package/src/ui/renderers/gitignoreRenderers.js +36 -23
- package/src/ui/renderers/gitignoreRenderers.tsx +50 -41
- package/src/ui/screens/AliasScreen.js +1111 -0
- package/src/ui/screens/AliasScreen.tsx +1534 -0
- package/src/ui/screens/CliToolsScreen.js +6 -1
- package/src/ui/screens/CliToolsScreen.tsx +6 -1
- package/src/ui/screens/EnvVarsScreen.js +6 -1
- package/src/ui/screens/EnvVarsScreen.tsx +6 -1
- package/src/ui/screens/GitignoreScreen.js +189 -88
- package/src/ui/screens/GitignoreScreen.tsx +312 -132
- package/src/ui/screens/McpRegistryScreen.js +13 -2
- package/src/ui/screens/McpRegistryScreen.tsx +13 -2
- package/src/ui/screens/McpScreen.js +6 -1
- package/src/ui/screens/McpScreen.tsx +6 -1
- package/src/ui/screens/ModelSelectorScreen.js +8 -2
- package/src/ui/screens/ModelSelectorScreen.tsx +8 -2
- package/src/ui/screens/PluginsScreen.js +17 -3
- package/src/ui/screens/PluginsScreen.tsx +16 -3
- package/src/ui/screens/ProfilesScreen.js +8 -1
- package/src/ui/screens/ProfilesScreen.tsx +8 -1
- package/src/ui/screens/SkillsScreen.js +21 -4
- package/src/ui/screens/SkillsScreen.tsx +39 -5
- package/src/ui/screens/StatusLineScreen.js +7 -1
- package/src/ui/screens/StatusLineScreen.tsx +7 -1
- package/src/ui/screens/index.js +1 -0
- package/src/ui/screens/index.ts +1 -0
- package/src/ui/state/reducer.js +5 -1
- package/src/ui/state/reducer.ts +6 -1
- package/src/ui/state/types.ts +12 -2
|
@@ -0,0 +1,1247 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Render the managed `claude` alias and splice it into shell rc files.
|
|
3
|
+
*
|
|
4
|
+
* Two layers:
|
|
5
|
+
* - Pure render functions (POSIX vs fish) that take a config and emit text.
|
|
6
|
+
* - I/O helpers that detect installed shells and replace the managed block
|
|
7
|
+
* idempotently using sentinel comment markers.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { readFile, writeFile, stat } from "node:fs/promises";
|
|
11
|
+
import { existsSync } from "node:fs";
|
|
12
|
+
import { join } from "node:path";
|
|
13
|
+
import { homedir } from "node:os";
|
|
14
|
+
import {
|
|
15
|
+
ALIAS_FLAGS,
|
|
16
|
+
getFlagById,
|
|
17
|
+
type AliasFlag,
|
|
18
|
+
} from "../data/alias-flags.js";
|
|
19
|
+
import {
|
|
20
|
+
CHANNELS_FLAG_ID,
|
|
21
|
+
defaultValueFor,
|
|
22
|
+
derivedChannelValues,
|
|
23
|
+
listValues,
|
|
24
|
+
type AliasConfig,
|
|
25
|
+
type FlagValue,
|
|
26
|
+
} from "./alias-store.js";
|
|
27
|
+
|
|
28
|
+
export type ShellKind = "zsh" | "bash" | "fish";
|
|
29
|
+
|
|
30
|
+
export interface ShellTarget {
|
|
31
|
+
kind: ShellKind;
|
|
32
|
+
/** Absolute path to the rc file. */
|
|
33
|
+
path: string;
|
|
34
|
+
/** True if the file currently exists on disk. */
|
|
35
|
+
exists: boolean;
|
|
36
|
+
/** True if `$SHELL` points at this shell — the default write target. */
|
|
37
|
+
isDefault: boolean;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const BLOCK_BEGIN = "# >>> claudeup managed alias >>>";
|
|
41
|
+
const BLOCK_END = "# <<< claudeup managed alias <<<";
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Probe the user's home dir for the three supported shell rc files.
|
|
45
|
+
*
|
|
46
|
+
* Path discovery is intentionally simple: we don't follow `$ZDOTDIR` or
|
|
47
|
+
* fish's `$XDG_CONFIG_HOME` overrides yet. If users hit those, we expose
|
|
48
|
+
* a path override later — for now the conventional locations cover the
|
|
49
|
+
* default install on macOS / Linux.
|
|
50
|
+
*/
|
|
51
|
+
export async function detectShells(
|
|
52
|
+
home: string = homedir(),
|
|
53
|
+
shellEnv: string = process.env.SHELL ?? "",
|
|
54
|
+
): Promise<ShellTarget[]> {
|
|
55
|
+
const candidates: Array<{ kind: ShellKind; path: string }> = [
|
|
56
|
+
{ kind: "zsh", path: join(home, ".zshrc") },
|
|
57
|
+
{ kind: "bash", path: join(home, ".bashrc") },
|
|
58
|
+
{ kind: "fish", path: join(home, ".config", "fish", "config.fish") },
|
|
59
|
+
];
|
|
60
|
+
|
|
61
|
+
const defaultKind = inferDefaultShell(shellEnv);
|
|
62
|
+
|
|
63
|
+
const results: ShellTarget[] = [];
|
|
64
|
+
for (const c of candidates) {
|
|
65
|
+
let exists = existsSync(c.path);
|
|
66
|
+
if (exists) {
|
|
67
|
+
// existsSync can lie on broken symlinks — check stat too
|
|
68
|
+
try {
|
|
69
|
+
await stat(c.path);
|
|
70
|
+
} catch {
|
|
71
|
+
exists = false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
results.push({
|
|
75
|
+
kind: c.kind,
|
|
76
|
+
path: c.path,
|
|
77
|
+
exists,
|
|
78
|
+
isDefault: c.kind === defaultKind,
|
|
79
|
+
});
|
|
80
|
+
}
|
|
81
|
+
return results;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function inferDefaultShell(shellEnv: string): ShellKind | null {
|
|
85
|
+
if (shellEnv.endsWith("/zsh")) return "zsh";
|
|
86
|
+
if (shellEnv.endsWith("/bash")) return "bash";
|
|
87
|
+
if (shellEnv.endsWith("/fish")) return "fish";
|
|
88
|
+
return null;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// ─── Rendering ────────────────────────────────────────────────────────────
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* One emitted argv token in the alias body. A token can be:
|
|
95
|
+
*
|
|
96
|
+
* - A plain `literal` token like `--ide` or `low` (gets single-quoted in
|
|
97
|
+
* the outer alias body).
|
|
98
|
+
* - A `composite` token, where the actual argv value is the concatenation
|
|
99
|
+
* of multiple parts. Used by templated flags so a value like
|
|
100
|
+
* `dev-{folder}-{day}` becomes ONE shell argument with two embedded
|
|
101
|
+
* substitutions, not three separate tokens.
|
|
102
|
+
*
|
|
103
|
+
* Composite parts are rendered together with no separating whitespace and
|
|
104
|
+
* with the appropriate close-outer / reopen-outer dance per shell.
|
|
105
|
+
*/
|
|
106
|
+
export type Segment =
|
|
107
|
+
| { kind: "literal"; text: string }
|
|
108
|
+
| { kind: "composite"; parts: SegmentPart[] };
|
|
109
|
+
|
|
110
|
+
export type SegmentPart =
|
|
111
|
+
| { kind: "literal"; text: string }
|
|
112
|
+
| { kind: "raw"; posix: string; fish: string };
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Build the alias body as a list of segments. Pure function.
|
|
116
|
+
*
|
|
117
|
+
* Validation:
|
|
118
|
+
* - `xorGroup` collisions are resolved by emitting only the first enabled
|
|
119
|
+
* flag in the group. The UI is responsible for warning the user; the
|
|
120
|
+
* renderer never silently keeps both.
|
|
121
|
+
* - `requires` is enforced: a flag whose dependency is disabled is dropped.
|
|
122
|
+
*/
|
|
123
|
+
export function renderArgs(config: AliasConfig): Segment[] {
|
|
124
|
+
const out: Segment[] = [];
|
|
125
|
+
const seenXor = new Set<string>();
|
|
126
|
+
|
|
127
|
+
for (const flag of ALIAS_FLAGS) {
|
|
128
|
+
if (flag.requires) {
|
|
129
|
+
const dep = config.flags[flag.requires];
|
|
130
|
+
if (!isFlagEnabled(dep)) continue;
|
|
131
|
+
}
|
|
132
|
+
if (flag.xorGroup) {
|
|
133
|
+
if (seenXor.has(flag.xorGroup)) continue;
|
|
134
|
+
}
|
|
135
|
+
const value = config.flags[flag.id];
|
|
136
|
+
if (!value) continue;
|
|
137
|
+
|
|
138
|
+
// `--channels` is the union (own ∪ dev-load-if-enabled), computed here at
|
|
139
|
+
// render time — the union is NOT stored, so own/derived stay distinct in
|
|
140
|
+
// the UI. A dev-loaded channel must run, so derived values force `--channels`
|
|
141
|
+
// to emit even when the user's own channels list is disabled/empty.
|
|
142
|
+
const renderValue =
|
|
143
|
+
flag.id === CHANNELS_FLAG_ID
|
|
144
|
+
? channelsUnionValue(config.flags, value)
|
|
145
|
+
: value;
|
|
146
|
+
|
|
147
|
+
const rendered = renderFlag(flag, renderValue);
|
|
148
|
+
if (rendered.length === 0) continue;
|
|
149
|
+
out.push(...rendered);
|
|
150
|
+
if (flag.xorGroup) seenXor.add(flag.xorGroup);
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return out;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Convenience: render each segment to its literal-token approximation.
|
|
158
|
+
* Composite segments are stringified by joining their literal parts with
|
|
159
|
+
* `<sub>` placeholders for raw parts. Used by tests and validation summaries
|
|
160
|
+
* where the actual shell substitution doesn't matter.
|
|
161
|
+
*/
|
|
162
|
+
export function renderArgsAsTokens(config: AliasConfig): string[] {
|
|
163
|
+
return renderArgs(config).map((seg) => {
|
|
164
|
+
if (seg.kind === "literal") return seg.text;
|
|
165
|
+
return seg.parts
|
|
166
|
+
.map((p) => (p.kind === "literal" ? p.text : `<${p.posix}>`))
|
|
167
|
+
.join("");
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
function isFlagEnabled(value: FlagValue | undefined): boolean {
|
|
172
|
+
if (!value) return false;
|
|
173
|
+
switch (value.kind) {
|
|
174
|
+
case "boolean":
|
|
175
|
+
return value.enabled;
|
|
176
|
+
case "tri-state":
|
|
177
|
+
return value.state !== "unset";
|
|
178
|
+
case "select":
|
|
179
|
+
case "text":
|
|
180
|
+
case "optional-text":
|
|
181
|
+
case "text-list":
|
|
182
|
+
case "multi-with-custom":
|
|
183
|
+
return value.enabled;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function lit(text: string): Segment {
|
|
188
|
+
return { kind: "literal", text };
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Wrap a templated value as a composite segment if it contains any tokens,
|
|
193
|
+
* otherwise return it as a plain literal.
|
|
194
|
+
*/
|
|
195
|
+
function templatedSegment(value: string): Segment {
|
|
196
|
+
const parts = expandTemplateValue(value);
|
|
197
|
+
if (parts.length === 1 && parts[0].kind === "literal") {
|
|
198
|
+
return { kind: "literal", text: parts[0].text };
|
|
199
|
+
}
|
|
200
|
+
return { kind: "composite", parts };
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* Build the effective `--channels` value for rendering: the user's own
|
|
205
|
+
* channels unioned with the dev-load flag's values (when dev-load is enabled),
|
|
206
|
+
* deduped, own-first. Enabled when EITHER source contributes a value, so a
|
|
207
|
+
* dev-loaded channel still forces `--channels` to emit even if the user never
|
|
208
|
+
* enabled their own channels list. The union lives here, at render time — it
|
|
209
|
+
* is never written back to `channels.values`, so provenance is preserved.
|
|
210
|
+
*/
|
|
211
|
+
function channelsUnionValue(
|
|
212
|
+
flags: Record<string, FlagValue>,
|
|
213
|
+
own: FlagValue,
|
|
214
|
+
): FlagValue {
|
|
215
|
+
const ownValues = own.kind === "text-list" && own.enabled
|
|
216
|
+
? listValues(own)
|
|
217
|
+
: [];
|
|
218
|
+
const derived = derivedChannelValues(flags);
|
|
219
|
+
const merged = dedupe([...ownValues, ...derived]).filter((v) => v.length > 0);
|
|
220
|
+
return { kind: "text-list", enabled: merged.length > 0, values: merged };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function renderFlag(flag: AliasFlag, value: FlagValue): Segment[] {
|
|
224
|
+
switch (value.kind) {
|
|
225
|
+
case "boolean":
|
|
226
|
+
return value.enabled ? [lit(flag.flag)] : [];
|
|
227
|
+
case "tri-state":
|
|
228
|
+
if (value.state === "on") return [lit(flag.flag)];
|
|
229
|
+
if (value.state === "off" && flag.triStateOff)
|
|
230
|
+
return [lit(flag.triStateOff)];
|
|
231
|
+
return [];
|
|
232
|
+
case "select":
|
|
233
|
+
if (!value.enabled) return [];
|
|
234
|
+
// Empty value means "bare flag, default variant" (e.g. `--tmux` alone).
|
|
235
|
+
return value.value === ""
|
|
236
|
+
? [lit(flag.flag)]
|
|
237
|
+
: [lit(flag.flag), lit(value.value)];
|
|
238
|
+
case "text":
|
|
239
|
+
if (!value.enabled || !value.value) return [];
|
|
240
|
+
return [
|
|
241
|
+
lit(flag.flag),
|
|
242
|
+
flag.templated ? templatedSegment(value.value) : lit(value.value),
|
|
243
|
+
];
|
|
244
|
+
case "optional-text":
|
|
245
|
+
if (!value.enabled) return [];
|
|
246
|
+
if (!value.value) return [lit(flag.flag)];
|
|
247
|
+
return [
|
|
248
|
+
lit(flag.flag),
|
|
249
|
+
flag.templated ? templatedSegment(value.value) : lit(value.value),
|
|
250
|
+
];
|
|
251
|
+
case "text-list": {
|
|
252
|
+
if (!value.enabled || value.values.length === 0) return [];
|
|
253
|
+
const out: Segment[] = [];
|
|
254
|
+
for (const v of value.values) {
|
|
255
|
+
if (!v) continue;
|
|
256
|
+
out.push(
|
|
257
|
+
lit(flag.flag),
|
|
258
|
+
flag.templated ? templatedSegment(v) : lit(v),
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return out;
|
|
262
|
+
}
|
|
263
|
+
case "multi-with-custom": {
|
|
264
|
+
if (!value.enabled) return [];
|
|
265
|
+
const tokens = dedupe([...value.picked, ...value.custom]).filter(
|
|
266
|
+
(t) => t.length > 0,
|
|
267
|
+
);
|
|
268
|
+
if (tokens.length === 0) return [lit(flag.flag)];
|
|
269
|
+
return [lit(flag.flag), lit(tokens.join(","))];
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/**
|
|
275
|
+
* Per-token shell-substitution code. POSIX and fish forms diverge slightly:
|
|
276
|
+
*
|
|
277
|
+
* - POSIX: classic `$(cmd)` with double quotes around `$PWD` so paths with
|
|
278
|
+
* spaces survive word-splitting in `basename`. The double quotes are
|
|
279
|
+
* tolerable inside the outer-double-quoted segment because we're already
|
|
280
|
+
* committed to a "embedded substitution" layer.
|
|
281
|
+
* - fish: `(cmd)` and fish handles variable expansion without the
|
|
282
|
+
* word-splitting concern, so `$PWD` doesn't need inner quoting.
|
|
283
|
+
*
|
|
284
|
+
* Note for POSIX: when this segment is emitted as `'"$(basename "$PWD")"'`,
|
|
285
|
+
* the shell sees `"$(basename "$PWD")"` — outer `"…"` enclosing an inner
|
|
286
|
+
* `"$PWD"`. POSIX (and bash/zsh) handle nested double quotes inside command
|
|
287
|
+
* substitution correctly: the inner `"$PWD"` is parsed within the `$(...)`
|
|
288
|
+
* subshell scope, not the outer shell's scope.
|
|
289
|
+
*/
|
|
290
|
+
const TOKEN_TO_SUB: Record<string, { posix: string; fish: string }> = {
|
|
291
|
+
"{folder}": {
|
|
292
|
+
posix: '$(basename "$PWD")',
|
|
293
|
+
fish: "(basename $PWD)",
|
|
294
|
+
},
|
|
295
|
+
"{day}": { posix: "$(date +%d)", fish: "(date +%d)" },
|
|
296
|
+
"{month}": { posix: "$(date +%m)", fish: "(date +%m)" },
|
|
297
|
+
"{year}": { posix: "$(date +%Y)", fish: "(date +%Y)" },
|
|
298
|
+
};
|
|
299
|
+
|
|
300
|
+
const TEMPLATE_RE = /\{(folder|day|month|year)\}/g;
|
|
301
|
+
|
|
302
|
+
/**
|
|
303
|
+
* Split a templated value into alternating literal and raw parts.
|
|
304
|
+
* Empty literal pieces are dropped. If the value contains no tokens, returns
|
|
305
|
+
* a single literal part covering the full string.
|
|
306
|
+
*/
|
|
307
|
+
export function expandTemplateValue(value: string): SegmentPart[] {
|
|
308
|
+
const out: SegmentPart[] = [];
|
|
309
|
+
let last = 0;
|
|
310
|
+
for (const match of value.matchAll(TEMPLATE_RE)) {
|
|
311
|
+
const start = match.index;
|
|
312
|
+
if (start > last) {
|
|
313
|
+
out.push({ kind: "literal", text: value.slice(last, start) });
|
|
314
|
+
}
|
|
315
|
+
const sub = TOKEN_TO_SUB[match[0]];
|
|
316
|
+
if (sub) {
|
|
317
|
+
out.push({ kind: "raw", posix: sub.posix, fish: sub.fish });
|
|
318
|
+
}
|
|
319
|
+
last = start + match[0].length;
|
|
320
|
+
}
|
|
321
|
+
if (last < value.length) {
|
|
322
|
+
out.push({ kind: "literal", text: value.slice(last) });
|
|
323
|
+
}
|
|
324
|
+
if (out.length === 0) {
|
|
325
|
+
out.push({ kind: "literal", text: value });
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function dedupe(arr: string[]): string[] {
|
|
331
|
+
return Array.from(new Set(arr));
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/**
|
|
335
|
+
* Fish quoting. Fish single quotes are simpler — only `\` and `'` need escapes.
|
|
336
|
+
*/
|
|
337
|
+
function quoteFish(s: string): string {
|
|
338
|
+
return `'${s.replace(/\\/g, "\\\\").replace(/'/g, "\\'")}'`;
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export interface RenderedAlias {
|
|
342
|
+
shell: ShellKind;
|
|
343
|
+
/** The full block including BEGIN/END markers, ending with a newline. */
|
|
344
|
+
block: string;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
export function renderAlias(
|
|
348
|
+
config: AliasConfig,
|
|
349
|
+
shell: ShellKind,
|
|
350
|
+
): RenderedAlias {
|
|
351
|
+
const args = renderArgs(config);
|
|
352
|
+
const name = config.aliasName;
|
|
353
|
+
if (shell === "fish") {
|
|
354
|
+
return { shell, block: renderFishBlock(name, args) };
|
|
355
|
+
}
|
|
356
|
+
return { shell, block: renderPosixBlock(name, args) };
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
function renderPosixBlock(name: string, segments: Segment[]): string {
|
|
360
|
+
// The alias body lives inside outer single quotes:
|
|
361
|
+
// alias <name>='claude … '
|
|
362
|
+
// Each segment becomes one shell-arg inside that body. Composite segments
|
|
363
|
+
// (templated values) interleave literal text with double-quoted shell
|
|
364
|
+
// substitutions via close-outer + double-quote + reopen-outer.
|
|
365
|
+
const body =
|
|
366
|
+
segments.length === 0
|
|
367
|
+
? ""
|
|
368
|
+
: " " + segments.map(renderPosixSegment).join(" ");
|
|
369
|
+
const line = `alias ${name}='claude${body}'`;
|
|
370
|
+
return `${BLOCK_BEGIN}\n${line}\n${BLOCK_END}\n`;
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
function renderPosixSegment(seg: Segment): string {
|
|
374
|
+
if (seg.kind === "literal") return quoteInsidePosixAlias(seg.text);
|
|
375
|
+
return seg.parts
|
|
376
|
+
.map((p) =>
|
|
377
|
+
p.kind === "literal"
|
|
378
|
+
? quoteInsidePosixAlias(p.text)
|
|
379
|
+
: embedPosixSubstitution(p.posix),
|
|
380
|
+
)
|
|
381
|
+
.join("");
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/**
|
|
385
|
+
* Embed shell substitution code inside the outer single-quoted alias body
|
|
386
|
+
* so it fires when the alias is expanded, not when the alias is defined.
|
|
387
|
+
*
|
|
388
|
+
* The outer alias body is `'…'`. To inject `$(cmd)` and have it evaluate at
|
|
389
|
+
* expansion time, we close the outer `'`, switch to double quotes (which
|
|
390
|
+
* interpolate), emit the substitution, close the double quotes, reopen the
|
|
391
|
+
* outer `'`. Net source text: `'"$(cmd)"'`.
|
|
392
|
+
*
|
|
393
|
+
* Any inner double quotes in the substitution code (e.g. `"$PWD"` for
|
|
394
|
+
* spaces-in-paths protection) survive because POSIX command substitution
|
|
395
|
+
* has its own quoting context inside `$(...)`.
|
|
396
|
+
*/
|
|
397
|
+
function embedPosixSubstitution(posixCode: string): string {
|
|
398
|
+
return `'"${posixCode}"'`;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
const POSIX_BARE = /^[A-Za-z0-9_\-=,:.\/!@%+]+$/;
|
|
402
|
+
|
|
403
|
+
function quoteInsidePosixAlias(token: string): string {
|
|
404
|
+
if (POSIX_BARE.test(token)) return token;
|
|
405
|
+
// No internal single quotes guaranteed by upstream validation.
|
|
406
|
+
return `'\\''${token}'\\''`;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Tokens with embedded single quotes can't be cleanly nested inside an outer
|
|
411
|
+
* single-quoted alias body without compounding escape layers that make the
|
|
412
|
+
* file unreadable. The UI surfaces this as an error before write.
|
|
413
|
+
*
|
|
414
|
+
* Composite segments are not checked here — their literal parts are checked
|
|
415
|
+
* via the same recursion. A `'` in a templated value's literal portion would
|
|
416
|
+
* still be unrenderable, so we walk the parts.
|
|
417
|
+
*/
|
|
418
|
+
export function findUnquotableTokens(segments: Segment[]): string[] {
|
|
419
|
+
const out: string[] = [];
|
|
420
|
+
for (const seg of segments) {
|
|
421
|
+
if (seg.kind === "literal") {
|
|
422
|
+
if (seg.text.includes("'")) out.push(seg.text);
|
|
423
|
+
continue;
|
|
424
|
+
}
|
|
425
|
+
for (const p of seg.parts) {
|
|
426
|
+
if (p.kind === "literal" && p.text.includes("'")) out.push(p.text);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
return out;
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
function renderFishBlock(name: string, segments: Segment[]): string {
|
|
433
|
+
// Fish: `alias <name> 'claude --foo bar'` — outer single quotes, no `=`.
|
|
434
|
+
const body =
|
|
435
|
+
segments.length === 0
|
|
436
|
+
? ""
|
|
437
|
+
: " " + segments.map(renderFishSegment).join(" ");
|
|
438
|
+
const line = `alias ${name} 'claude${body}'`;
|
|
439
|
+
return `${BLOCK_BEGIN}\n${line}\n${BLOCK_END}\n`;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function renderFishSegment(seg: Segment): string {
|
|
443
|
+
if (seg.kind === "literal") return quoteFish(seg.text);
|
|
444
|
+
return seg.parts
|
|
445
|
+
.map((p) =>
|
|
446
|
+
p.kind === "literal"
|
|
447
|
+
? quoteFish(p.text)
|
|
448
|
+
: embedFishSubstitution(p.fish),
|
|
449
|
+
)
|
|
450
|
+
.join("");
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Fish substitution embedding mirrors POSIX. Outer `'…'` is fish's literal
|
|
455
|
+
* single-quote (no interpolation), so close-and-double-quote-reopen is the
|
|
456
|
+
* same dance: `'"(cmd)"'` becomes literal-' + `(cmd)` evaluated at expansion
|
|
457
|
+
* time + literal-'.
|
|
458
|
+
*/
|
|
459
|
+
function embedFishSubstitution(fishCode: string): string {
|
|
460
|
+
return `'"${fishCode}"'`;
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
// ─── Splicing ─────────────────────────────────────────────────────────────
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Replace the existing managed block in `existing` with `block`, or append
|
|
467
|
+
* `block` to the end if no block is present. Pure function — no I/O.
|
|
468
|
+
*/
|
|
469
|
+
export function spliceManagedBlock(existing: string, block: string): string {
|
|
470
|
+
const beginIdx = existing.indexOf(BLOCK_BEGIN);
|
|
471
|
+
if (beginIdx === -1) {
|
|
472
|
+
if (existing.length === 0) return block;
|
|
473
|
+
const sep = existing.endsWith("\n") ? "" : "\n";
|
|
474
|
+
return existing + sep + "\n" + block;
|
|
475
|
+
}
|
|
476
|
+
const endIdx = existing.indexOf(BLOCK_END, beginIdx);
|
|
477
|
+
if (endIdx === -1) {
|
|
478
|
+
// Malformed block — replace from BEGIN to EOF to be safe.
|
|
479
|
+
return existing.slice(0, beginIdx) + block;
|
|
480
|
+
}
|
|
481
|
+
// Consume the trailing newline of the END marker if present.
|
|
482
|
+
let cutEnd = endIdx + BLOCK_END.length;
|
|
483
|
+
if (existing[cutEnd] === "\n") cutEnd += 1;
|
|
484
|
+
return existing.slice(0, beginIdx) + block + existing.slice(cutEnd);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
export interface WriteResult {
|
|
488
|
+
shell: ShellKind;
|
|
489
|
+
path: string;
|
|
490
|
+
/** "created" if the file did not exist; "updated" otherwise. */
|
|
491
|
+
action: "created" | "updated";
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
export interface WriteOptions {
|
|
495
|
+
/**
|
|
496
|
+
* Line range [start, end] (zero-based, inclusive) of a hand-written alias
|
|
497
|
+
* to REPLACE in place with the managed block — the adoption path. Only
|
|
498
|
+
* honored when the file has no managed block yet (a first write after
|
|
499
|
+
* adoption); subsequent writes find the markers and ignore this. Guarantees
|
|
500
|
+
* the adopted line is removed so no duplicate alias survives.
|
|
501
|
+
*/
|
|
502
|
+
adoptLineRange?: [number, number];
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
export async function writeAliasToShell(
|
|
506
|
+
config: AliasConfig,
|
|
507
|
+
target: ShellTarget,
|
|
508
|
+
options: WriteOptions = {},
|
|
509
|
+
): Promise<WriteResult> {
|
|
510
|
+
const args = renderArgs(config);
|
|
511
|
+
const unquotable = findUnquotableTokens(args);
|
|
512
|
+
if (unquotable.length > 0) {
|
|
513
|
+
throw new Error(
|
|
514
|
+
`Cannot render alias: ${unquotable.length} value${
|
|
515
|
+
unquotable.length === 1 ? "" : "s"
|
|
516
|
+
} contain a single quote, which can't be embedded in a shell alias. Edit the offending value(s) and try again: ${unquotable
|
|
517
|
+
.map((t) => JSON.stringify(t))
|
|
518
|
+
.join(", ")}`,
|
|
519
|
+
);
|
|
520
|
+
}
|
|
521
|
+
const rendered = renderAlias(config, target.kind);
|
|
522
|
+
const existing = target.exists ? await readFile(target.path, "utf8") : "";
|
|
523
|
+
|
|
524
|
+
// Adoption: when a line range was supplied AND the file has no managed block
|
|
525
|
+
// yet, replace the adopted alias line in place — the managed block takes its
|
|
526
|
+
// slot, so the original can't survive as a duplicate. Once a managed block
|
|
527
|
+
// exists, marker-based splicing is position-independent and takes over.
|
|
528
|
+
const hasBlock = existing.includes(BLOCK_BEGIN);
|
|
529
|
+
const next =
|
|
530
|
+
options.adoptLineRange && !hasBlock
|
|
531
|
+
? spliceManagedBlockAtRange(existing, rendered.block, options.adoptLineRange)
|
|
532
|
+
: spliceManagedBlock(existing, rendered.block);
|
|
533
|
+
|
|
534
|
+
await writeFile(target.path, next, "utf8");
|
|
535
|
+
return {
|
|
536
|
+
shell: target.kind,
|
|
537
|
+
path: target.path,
|
|
538
|
+
action: target.exists ? "updated" : "created",
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
// ─── Validation summary (UI helper) ───────────────────────────────────────
|
|
543
|
+
|
|
544
|
+
export interface FlagValidationIssue {
|
|
545
|
+
flagId: string;
|
|
546
|
+
reason: string;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* Summarize which flags are in conflict given the current config.
|
|
551
|
+
* The UI uses this to grey out / annotate rows. The renderer enforces the
|
|
552
|
+
* same rules independently — this helper is purely for display.
|
|
553
|
+
*/
|
|
554
|
+
export function validateConfig(config: AliasConfig): FlagValidationIssue[] {
|
|
555
|
+
const issues: FlagValidationIssue[] = [];
|
|
556
|
+
|
|
557
|
+
// xor groups
|
|
558
|
+
const groups = new Map<string, string[]>();
|
|
559
|
+
for (const flag of ALIAS_FLAGS) {
|
|
560
|
+
if (!flag.xorGroup) continue;
|
|
561
|
+
if (!isFlagEnabled(config.flags[flag.id])) continue;
|
|
562
|
+
const list = groups.get(flag.xorGroup) ?? [];
|
|
563
|
+
list.push(flag.id);
|
|
564
|
+
groups.set(flag.xorGroup, list);
|
|
565
|
+
}
|
|
566
|
+
for (const [group, ids] of groups) {
|
|
567
|
+
if (ids.length > 1) {
|
|
568
|
+
const winner = ids[0];
|
|
569
|
+
const losers = ids.slice(1);
|
|
570
|
+
for (const loser of losers) {
|
|
571
|
+
issues.push({
|
|
572
|
+
flagId: loser,
|
|
573
|
+
reason: `Mutually exclusive with --${winner}; will be dropped on write.`,
|
|
574
|
+
});
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// requires
|
|
580
|
+
for (const flag of ALIAS_FLAGS) {
|
|
581
|
+
if (!flag.requires) continue;
|
|
582
|
+
if (!isFlagEnabled(config.flags[flag.id])) continue;
|
|
583
|
+
if (!isFlagEnabled(config.flags[flag.requires])) {
|
|
584
|
+
const dep = getFlagById(flag.requires);
|
|
585
|
+
issues.push({
|
|
586
|
+
flagId: flag.id,
|
|
587
|
+
reason: `Requires ${dep.flag}; will be dropped on write.`,
|
|
588
|
+
});
|
|
589
|
+
}
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
return issues;
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
// ─── Parser ──────────────────────────────────────────────────────────────
|
|
596
|
+
//
|
|
597
|
+
// Reverses what the writer emits. Read shell rc text, extract the managed
|
|
598
|
+
// block, find the `alias <name>='claude <body>'` line, tokenize the body
|
|
599
|
+
// into argv strings (undoing POSIX nested-quote escapes and template
|
|
600
|
+
// substitution embeds), then map argv to a FlagValue per the catalog.
|
|
601
|
+
//
|
|
602
|
+
// Only the POSIX dialect (zsh/bash) is supported on parse today. Fish round-
|
|
603
|
+
// trip isn't symmetric to POSIX in our writer's output anyway (fish's auto-
|
|
604
|
+
// concat of adjacent quoted strings makes parsing more involved), and the
|
|
605
|
+
// vast majority of users are on zsh.
|
|
606
|
+
|
|
607
|
+
export interface ParseResult {
|
|
608
|
+
aliasName: string | null;
|
|
609
|
+
args: string[];
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Find the managed block in shell rc text, parse the alias line, and return
|
|
614
|
+
* the alias name plus the argv tokens after `claude`.
|
|
615
|
+
*
|
|
616
|
+
* Returns `null` when no managed block exists, the block is malformed, or
|
|
617
|
+
* the alias line can't be parsed. Callers treat null as "no managed alias
|
|
618
|
+
* on disk — start from defaults".
|
|
619
|
+
*/
|
|
620
|
+
export function parseManagedBlock(rcText: string): ParseResult | null {
|
|
621
|
+
const beginIdx = rcText.indexOf(BLOCK_BEGIN);
|
|
622
|
+
if (beginIdx === -1) return null;
|
|
623
|
+
const endIdx = rcText.indexOf(BLOCK_END, beginIdx);
|
|
624
|
+
if (endIdx === -1) return null;
|
|
625
|
+
|
|
626
|
+
// Lines inside the block, sans markers.
|
|
627
|
+
const inner = rcText.slice(beginIdx + BLOCK_BEGIN.length, endIdx);
|
|
628
|
+
// Find the `alias <name>=...` line (skip blank lines, comments, the markers).
|
|
629
|
+
const aliasLine = inner
|
|
630
|
+
.split("\n")
|
|
631
|
+
.map((l) => l.trim())
|
|
632
|
+
.find((l) => /^alias\s+[A-Za-z_][A-Za-z0-9_-]*\s*=/.test(l));
|
|
633
|
+
if (!aliasLine) return null;
|
|
634
|
+
|
|
635
|
+
return parseAliasLine(aliasLine);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
const ALIAS_LINE_RE = /^alias\s+([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*'(.*)'\s*$/;
|
|
639
|
+
|
|
640
|
+
/**
|
|
641
|
+
* Parse a single `alias <name>='<body>'` line. Body is the raw text inside
|
|
642
|
+
* the outer single quotes; the tokenizer below undoes the writer's escape
|
|
643
|
+
* scheme.
|
|
644
|
+
*/
|
|
645
|
+
export function parseAliasLine(line: string): ParseResult | null {
|
|
646
|
+
const match = ALIAS_LINE_RE.exec(line);
|
|
647
|
+
if (!match) return null;
|
|
648
|
+
const [, aliasName, body] = match;
|
|
649
|
+
// First token is the command itself (claude). Drop it; we only want argv.
|
|
650
|
+
const tokens = tokenizePosixAliasBody(body);
|
|
651
|
+
if (tokens.length === 0 || tokens[0] !== "claude") return null;
|
|
652
|
+
return { aliasName, args: tokens.slice(1) };
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
/**
|
|
656
|
+
* Tokenize the body of a POSIX alias inside the outer single quotes.
|
|
657
|
+
*
|
|
658
|
+
* Our writer emits three shapes inside the outer `'…'`:
|
|
659
|
+
* 1. Bare tokens (matching POSIX_BARE) — emitted as-is.
|
|
660
|
+
* 2. Quoted literals: `'\''text without single quotes'\''` — these survive
|
|
661
|
+
* the outer single quotes by closing them, emitting a literal `'`,
|
|
662
|
+
* single-quoting the inner content, then a literal `'`, and reopening.
|
|
663
|
+
* 3. Substitution embeds: `'"$(cmd)"'` — close outer ', open ", embed,
|
|
664
|
+
* close ", reopen outer '. Result is one shell arg with the
|
|
665
|
+
* substitution that fires on alias expansion.
|
|
666
|
+
*
|
|
667
|
+
* Reading the body left-to-right, we expect to see:
|
|
668
|
+
* - bare chars (collect into the current token's value)
|
|
669
|
+
* - whitespace (delimits tokens)
|
|
670
|
+
* - `'\''<text>'\''` (collect inner text verbatim into the current token)
|
|
671
|
+
* - `'"<sub>"'` (record as a raw substitution and unparse it back into
|
|
672
|
+
* the closest matching template token via `unparseSubstitution`)
|
|
673
|
+
*
|
|
674
|
+
* Tokens emitted as `composite` segments (template values) re-tokenize into
|
|
675
|
+
* a single shell arg whose pieces are interleaved literal+raw. We rebuild
|
|
676
|
+
* those as `{token}` strings to match what the UI stores.
|
|
677
|
+
*/
|
|
678
|
+
export function tokenizePosixAliasBody(body: string): string[] {
|
|
679
|
+
const tokens: string[] = [];
|
|
680
|
+
let current = "";
|
|
681
|
+
let inToken = false;
|
|
682
|
+
let i = 0;
|
|
683
|
+
const len = body.length;
|
|
684
|
+
|
|
685
|
+
const flush = () => {
|
|
686
|
+
if (inToken) {
|
|
687
|
+
tokens.push(current);
|
|
688
|
+
current = "";
|
|
689
|
+
inToken = false;
|
|
690
|
+
}
|
|
691
|
+
};
|
|
692
|
+
|
|
693
|
+
while (i < len) {
|
|
694
|
+
const ch = body[i];
|
|
695
|
+
|
|
696
|
+
if (ch === " " || ch === "\t") {
|
|
697
|
+
flush();
|
|
698
|
+
i += 1;
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
// Quoted literal: '\''…'\''
|
|
703
|
+
if (body.startsWith(`'\\''`, i)) {
|
|
704
|
+
// Skip the opening sequence.
|
|
705
|
+
i += 4;
|
|
706
|
+
const end = body.indexOf(`'\\''`, i);
|
|
707
|
+
if (end === -1) return tokens; // malformed — bail, return what we have
|
|
708
|
+
current += body.slice(i, end);
|
|
709
|
+
inToken = true;
|
|
710
|
+
i = end + 4;
|
|
711
|
+
continue;
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Substitution embed: '"<sub>"'
|
|
715
|
+
if (body.startsWith(`'"`, i)) {
|
|
716
|
+
const inner = i + 2;
|
|
717
|
+
const close = body.indexOf(`"'`, inner);
|
|
718
|
+
if (close === -1) return tokens;
|
|
719
|
+
const subCode = body.slice(inner, close);
|
|
720
|
+
const token = unparseSubstitution(subCode);
|
|
721
|
+
current += token;
|
|
722
|
+
inToken = true;
|
|
723
|
+
i = close + 2;
|
|
724
|
+
continue;
|
|
725
|
+
}
|
|
726
|
+
|
|
727
|
+
// Bare character.
|
|
728
|
+
current += ch;
|
|
729
|
+
inToken = true;
|
|
730
|
+
i += 1;
|
|
731
|
+
}
|
|
732
|
+
flush();
|
|
733
|
+
return tokens;
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
/**
|
|
737
|
+
* Map a POSIX substitution code back to its template token, if one matches.
|
|
738
|
+
* Falls through to a `$(...)` literal when no token matches — that way we
|
|
739
|
+
* preserve hand-edited substitutions as opaque values rather than dropping
|
|
740
|
+
* them.
|
|
741
|
+
*
|
|
742
|
+
* Mirror of TOKEN_TO_SUB in the writer.
|
|
743
|
+
*/
|
|
744
|
+
function unparseSubstitution(posixCode: string): string {
|
|
745
|
+
switch (posixCode) {
|
|
746
|
+
case '$(basename "$PWD")':
|
|
747
|
+
return "{folder}";
|
|
748
|
+
case "$(date +%d)":
|
|
749
|
+
return "{day}";
|
|
750
|
+
case "$(date +%m)":
|
|
751
|
+
return "{month}";
|
|
752
|
+
case "$(date +%Y)":
|
|
753
|
+
return "{year}";
|
|
754
|
+
default:
|
|
755
|
+
// Unknown substitution: pass through the raw code so the user can see
|
|
756
|
+
// it in the UI and decide whether to keep it. The writer can't faithfully
|
|
757
|
+
// round-trip it, but at least we don't silently drop it.
|
|
758
|
+
return posixCode;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
|
|
762
|
+
/**
|
|
763
|
+
* Apply parsed argv tokens to a FlagValue map. Walks the catalog in order,
|
|
764
|
+
* consuming tokens that match each flag's pattern. Tokens that don't match
|
|
765
|
+
* any flag are dropped silently (e.g. the user hand-added a flag we don't
|
|
766
|
+
* know about). Returns a fresh `Record<flagId, FlagValue>` suitable for
|
|
767
|
+
* splicing into an AliasConfig.
|
|
768
|
+
*
|
|
769
|
+
* Ordering: the writer emits flags in catalog order, so a left-to-right
|
|
770
|
+
* scan is sufficient. We pre-index by flag string for `--foo` lookups.
|
|
771
|
+
*/
|
|
772
|
+
export function argsToFlagValues(args: string[]): Record<string, FlagValue> {
|
|
773
|
+
return argsToFlagValuesWithLeftovers(args).flags;
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* Result of {@link argsToFlagValuesWithLeftovers}: the parsed flag map plus the
|
|
778
|
+
* argv tokens that didn't map to any catalog flag.
|
|
779
|
+
*
|
|
780
|
+
* `leftovers` is the lossless gate for alias adoption: a hand-written alias is
|
|
781
|
+
* safe to absorb into the managed block ONLY when `leftovers` is empty, i.e.
|
|
782
|
+
* every token was recognized. Any leftover token would be silently lost if we
|
|
783
|
+
* deleted the original line and re-rendered from the parsed flags, so a
|
|
784
|
+
* non-empty `leftovers` means "import the flags for the user to see, but do NOT
|
|
785
|
+
* take ownership / do NOT remove their line".
|
|
786
|
+
*/
|
|
787
|
+
export interface ParsedFlagsWithLeftovers {
|
|
788
|
+
flags: Record<string, FlagValue>;
|
|
789
|
+
/** argv tokens that matched no catalog flag (and so would be dropped). */
|
|
790
|
+
leftovers: string[];
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
/**
|
|
794
|
+
* Like {@link argsToFlagValues}, but reports every token it couldn't map to a
|
|
795
|
+
* catalog flag. Unknown `--flag value` pairs contribute BOTH tokens to
|
|
796
|
+
* `leftovers` (the flag and its consumed value) so the adoption gate sees the
|
|
797
|
+
* full extent of what wouldn't round-trip.
|
|
798
|
+
*/
|
|
799
|
+
export function argsToFlagValuesWithLeftovers(
|
|
800
|
+
args: string[],
|
|
801
|
+
): ParsedFlagsWithLeftovers {
|
|
802
|
+
// Index every flag by its primary `flag` string AND its triStateOff variant.
|
|
803
|
+
const byFlag = new Map<string, { flag: AliasFlag; off?: boolean }>();
|
|
804
|
+
for (const flag of ALIAS_FLAGS) {
|
|
805
|
+
byFlag.set(flag.flag, { flag, off: false });
|
|
806
|
+
if (flag.triStateOff) {
|
|
807
|
+
byFlag.set(flag.triStateOff, { flag, off: true });
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const out: Record<string, FlagValue> = {};
|
|
812
|
+
const leftovers: string[] = [];
|
|
813
|
+
let i = 0;
|
|
814
|
+
while (i < args.length) {
|
|
815
|
+
const tok = args[i];
|
|
816
|
+
const entry = byFlag.get(tok);
|
|
817
|
+
if (!entry) {
|
|
818
|
+
// Unknown token — record it. If the next token looks like its value
|
|
819
|
+
// (doesn't start with `-`), consume and record that too so unknown
|
|
820
|
+
// flag/value pairs don't cascade-corrupt the rest of the parse, and so
|
|
821
|
+
// the adoption gate sees the full unrecognized span.
|
|
822
|
+
leftovers.push(tok);
|
|
823
|
+
i += 1;
|
|
824
|
+
if (i < args.length && !args[i].startsWith("-")) {
|
|
825
|
+
leftovers.push(args[i]);
|
|
826
|
+
i += 1;
|
|
827
|
+
}
|
|
828
|
+
continue;
|
|
829
|
+
}
|
|
830
|
+
const { flag, off } = entry;
|
|
831
|
+
const peek = (): string | undefined => args[i + 1];
|
|
832
|
+
const takeValue = (): string => {
|
|
833
|
+
const v = args[i + 1];
|
|
834
|
+
i += 2;
|
|
835
|
+
return v;
|
|
836
|
+
};
|
|
837
|
+
|
|
838
|
+
switch (flag.kind) {
|
|
839
|
+
case "boolean":
|
|
840
|
+
out[flag.id] = { kind: "boolean", enabled: true };
|
|
841
|
+
i += 1;
|
|
842
|
+
break;
|
|
843
|
+
case "tri-state":
|
|
844
|
+
out[flag.id] = { kind: "tri-state", state: off ? "off" : "on" };
|
|
845
|
+
i += 1;
|
|
846
|
+
break;
|
|
847
|
+
case "select": {
|
|
848
|
+
// The writer emits `--flag` alone for "bare" empty value, or
|
|
849
|
+
// `--flag <value>` for a selection. We can't tell without peeking
|
|
850
|
+
// at whether the next token is a known value.
|
|
851
|
+
const opts = flag.options ?? [];
|
|
852
|
+
const next = peek();
|
|
853
|
+
const valid = next !== undefined && opts.some((o) => o.value === next);
|
|
854
|
+
if (valid) {
|
|
855
|
+
out[flag.id] = { kind: "select", enabled: true, value: takeValue() };
|
|
856
|
+
} else {
|
|
857
|
+
out[flag.id] = { kind: "select", enabled: true, value: "" };
|
|
858
|
+
i += 1;
|
|
859
|
+
}
|
|
860
|
+
break;
|
|
861
|
+
}
|
|
862
|
+
case "text":
|
|
863
|
+
// `text` always emits a value; if there's no next token we treat as
|
|
864
|
+
// disabled (defensive).
|
|
865
|
+
if (peek() !== undefined) {
|
|
866
|
+
out[flag.id] = { kind: "text", enabled: true, value: takeValue() };
|
|
867
|
+
} else {
|
|
868
|
+
out[flag.id] = { kind: "text", enabled: false, value: "" };
|
|
869
|
+
i += 1;
|
|
870
|
+
}
|
|
871
|
+
break;
|
|
872
|
+
case "optional-text": {
|
|
873
|
+
// Optional-text: next token is the value if it doesn't look like a
|
|
874
|
+
// flag. We can't perfectly distinguish a deliberately-bare emission
|
|
875
|
+
// from one followed by an unrelated flag, but the writer's emission
|
|
876
|
+
// of bare is `flag.flag` alone with the next token being another
|
|
877
|
+
// catalog flag — so checking the lookup tells us.
|
|
878
|
+
const next = peek();
|
|
879
|
+
if (next === undefined || byFlag.has(next)) {
|
|
880
|
+
out[flag.id] = { kind: "optional-text", enabled: true, value: "" };
|
|
881
|
+
i += 1;
|
|
882
|
+
} else {
|
|
883
|
+
out[flag.id] = {
|
|
884
|
+
kind: "optional-text",
|
|
885
|
+
enabled: true,
|
|
886
|
+
value: takeValue(),
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
break;
|
|
890
|
+
}
|
|
891
|
+
case "text-list": {
|
|
892
|
+
// Each instance of the flag emits one value. Collect repeats.
|
|
893
|
+
const values: string[] = [];
|
|
894
|
+
// Consume the first pair.
|
|
895
|
+
if (peek() !== undefined) values.push(takeValue());
|
|
896
|
+
else i += 1;
|
|
897
|
+
// Consume additional pairs of the same flag.
|
|
898
|
+
while (i < args.length && args[i] === flag.flag) {
|
|
899
|
+
if (i + 1 < args.length) {
|
|
900
|
+
values.push(args[i + 1]);
|
|
901
|
+
i += 2;
|
|
902
|
+
} else {
|
|
903
|
+
i += 1;
|
|
904
|
+
break;
|
|
905
|
+
}
|
|
906
|
+
}
|
|
907
|
+
out[flag.id] = {
|
|
908
|
+
kind: "text-list",
|
|
909
|
+
enabled: true,
|
|
910
|
+
values,
|
|
911
|
+
};
|
|
912
|
+
break;
|
|
913
|
+
}
|
|
914
|
+
case "multi-with-custom": {
|
|
915
|
+
// Either bare `--debug` (no filter) or `--debug a,b,c`.
|
|
916
|
+
const next = peek();
|
|
917
|
+
if (next === undefined || byFlag.has(next)) {
|
|
918
|
+
out[flag.id] = {
|
|
919
|
+
kind: "multi-with-custom",
|
|
920
|
+
enabled: true,
|
|
921
|
+
picked: [],
|
|
922
|
+
custom: [],
|
|
923
|
+
};
|
|
924
|
+
i += 1;
|
|
925
|
+
} else {
|
|
926
|
+
const tokens = takeValue()
|
|
927
|
+
.split(",")
|
|
928
|
+
.map((s) => s.trim())
|
|
929
|
+
.filter((s) => s.length > 0);
|
|
930
|
+
const picklist = new Set(flag.picklist ?? []);
|
|
931
|
+
const picked: string[] = [];
|
|
932
|
+
const custom: string[] = [];
|
|
933
|
+
for (const t of tokens) {
|
|
934
|
+
if (picklist.has(t)) picked.push(t);
|
|
935
|
+
else custom.push(t);
|
|
936
|
+
}
|
|
937
|
+
out[flag.id] = {
|
|
938
|
+
kind: "multi-with-custom",
|
|
939
|
+
enabled: true,
|
|
940
|
+
picked,
|
|
941
|
+
custom,
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
break;
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// Restore channels provenance: the writer emits `--channels` as
|
|
950
|
+
// (own ∪ dev-load), so a naive parse folds derived values back into
|
|
951
|
+
// channels.values. Subtract the dev-load values (when that flag was
|
|
952
|
+
// emitted/enabled) so channels.values holds only the user's OWN channels —
|
|
953
|
+
// the derived ones come from the dev-load flag at display/render time.
|
|
954
|
+
const channels = out[CHANNELS_FLAG_ID];
|
|
955
|
+
const derived = derivedChannelValues(out);
|
|
956
|
+
if (channels && channels.kind === "text-list" && derived.length > 0) {
|
|
957
|
+
const ownOnly = channels.values.filter((v) => !derived.includes(v));
|
|
958
|
+
out[CHANNELS_FLAG_ID] = {
|
|
959
|
+
kind: "text-list",
|
|
960
|
+
// Keep enabled only if the user has their own channels; a channels list
|
|
961
|
+
// that was purely derived shouldn't appear enabled after the subtraction.
|
|
962
|
+
enabled: ownOnly.length > 0,
|
|
963
|
+
values: ownOnly,
|
|
964
|
+
};
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
return { flags: out, leftovers };
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
/**
|
|
971
|
+
* High-level entry point: read shell rc text, parse the managed block, and
|
|
972
|
+
* return a populated flag map plus the parsed alias name. Returns null when
|
|
973
|
+
* there's no managed block to parse from.
|
|
974
|
+
*/
|
|
975
|
+
export function parseAliasFromRc(rcText: string): {
|
|
976
|
+
aliasName: string;
|
|
977
|
+
flags: Record<string, FlagValue>;
|
|
978
|
+
} | null {
|
|
979
|
+
const parsed = parseManagedBlock(rcText);
|
|
980
|
+
if (!parsed || !parsed.aliasName) return null;
|
|
981
|
+
return {
|
|
982
|
+
aliasName: parsed.aliasName,
|
|
983
|
+
flags: argsToFlagValues(parsed.args),
|
|
984
|
+
};
|
|
985
|
+
}
|
|
986
|
+
|
|
987
|
+
// ─── Adoption (detect & offer to import a hand-written alias) ───────────────
|
|
988
|
+
//
|
|
989
|
+
// When the screen opens and there is NO managed block, the user may still have
|
|
990
|
+
// a hand-written `alias c='claude …'` line elsewhere in the rc file. Rather
|
|
991
|
+
// than ignore it (and look broken), we DETECT it and OFFER to adopt it: import
|
|
992
|
+
// its flags into the editor and, on the next write, replace that line in place
|
|
993
|
+
// with the managed block so ownership transfers cleanly with no duplicate.
|
|
994
|
+
//
|
|
995
|
+
// Safety is built on a single invariant: we only mark an alias `lossless` —
|
|
996
|
+
// and therefore safe to remove — when every token round-trips. Two checks:
|
|
997
|
+
// 1. Leftover-empty: every argv token mapped to a catalog flag.
|
|
998
|
+
// 2. Fixpoint: re-rendering the parsed flags and re-parsing yields the same
|
|
999
|
+
// flag map (catches peek-based mis-maps that consume a token into the
|
|
1000
|
+
// wrong bucket without surfacing as a leftover).
|
|
1001
|
+
// Both are order- and quote-insensitive by construction. A NON-lossless alias
|
|
1002
|
+
// is still offered (the user sees its recognized flags) but its original line
|
|
1003
|
+
// is never removed — we keep what we couldn't fully understand.
|
|
1004
|
+
|
|
1005
|
+
/**
|
|
1006
|
+
* A hand-written `claude`-wrapping alias found OUTSIDE the managed block.
|
|
1007
|
+
*/
|
|
1008
|
+
export interface AdoptableAlias {
|
|
1009
|
+
/** The alias name (e.g. `c`). */
|
|
1010
|
+
name: string;
|
|
1011
|
+
/** Parsed flag values from the alias body. */
|
|
1012
|
+
flags: Record<string, FlagValue>;
|
|
1013
|
+
/**
|
|
1014
|
+
* Zero-based line indices [start, end] of the alias line in the rc file.
|
|
1015
|
+
* Single-line today (start === end), but kept as a range so the splice
|
|
1016
|
+
* helper has the exact span to replace.
|
|
1017
|
+
*/
|
|
1018
|
+
lineRange: [number, number];
|
|
1019
|
+
/** argv tokens that didn't map to any catalog flag (data we'd drop). */
|
|
1020
|
+
leftovers: string[];
|
|
1021
|
+
/**
|
|
1022
|
+
* True when the alias round-trips exactly: leftovers empty AND the parsed
|
|
1023
|
+
* flags survive a render→reparse fixpoint. Only a lossless alias may have
|
|
1024
|
+
* its original line removed on adoption.
|
|
1025
|
+
*/
|
|
1026
|
+
lossless: boolean;
|
|
1027
|
+
/** The raw alias line, verbatim (for display / preservation). */
|
|
1028
|
+
rawLine: string;
|
|
1029
|
+
/**
|
|
1030
|
+
* Other top-level `claude`-wrapping alias lines we found but did NOT pick.
|
|
1031
|
+
* Surfaced so the UI can note "also found N other claude aliases" rather
|
|
1032
|
+
* than silently choosing the first.
|
|
1033
|
+
*/
|
|
1034
|
+
others: string[];
|
|
1035
|
+
}
|
|
1036
|
+
|
|
1037
|
+
const ANY_ALIAS_LINE_RE =
|
|
1038
|
+
/^alias\s+([A-Za-z_][A-Za-z0-9_-]*)\s*=\s*(['"])(.*)\2\s*$/;
|
|
1039
|
+
|
|
1040
|
+
/**
|
|
1041
|
+
* Tokenize a general (hand-written) POSIX alias body into argv strings.
|
|
1042
|
+
*
|
|
1043
|
+
* Unlike {@link tokenizePosixAliasBody} — which only undoes OUR writer's escape
|
|
1044
|
+
* scheme — this handles the shapes a human would type: bare words, single-
|
|
1045
|
+
* quoted runs (literal, no escapes), and double-quoted runs (we treat the
|
|
1046
|
+
* content literally; we do NOT expand `$VAR` or `$(cmd)`). Adjacent quoted and
|
|
1047
|
+
* bare pieces with no whitespace between them concatenate into one argv token,
|
|
1048
|
+
* matching shell word-joining (`foo' bar'` → `foo bar`).
|
|
1049
|
+
*
|
|
1050
|
+
* Returns `null` for anything we can't cleanly tokenize: unterminated quotes,
|
|
1051
|
+
* or a body containing a shell substitution (`$(`, backtick) or variable (`$`)
|
|
1052
|
+
* — those can't be faithfully represented as a static flag value, so the
|
|
1053
|
+
* caller treats the whole alias as not-adoptable rather than guessing.
|
|
1054
|
+
*/
|
|
1055
|
+
export function tokenizeGeneralAliasBody(body: string): string[] | null {
|
|
1056
|
+
const tokens: string[] = [];
|
|
1057
|
+
let current = "";
|
|
1058
|
+
let inToken = false;
|
|
1059
|
+
let i = 0;
|
|
1060
|
+
const len = body.length;
|
|
1061
|
+
|
|
1062
|
+
const flush = () => {
|
|
1063
|
+
if (inToken) {
|
|
1064
|
+
tokens.push(current);
|
|
1065
|
+
current = "";
|
|
1066
|
+
inToken = false;
|
|
1067
|
+
}
|
|
1068
|
+
};
|
|
1069
|
+
|
|
1070
|
+
while (i < len) {
|
|
1071
|
+
const ch = body[i];
|
|
1072
|
+
|
|
1073
|
+
if (ch === " " || ch === "\t") {
|
|
1074
|
+
flush();
|
|
1075
|
+
i += 1;
|
|
1076
|
+
continue;
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
// Bail on dynamic content — we can't round-trip a variable/substitution.
|
|
1080
|
+
if (ch === "$" || ch === "`") return null;
|
|
1081
|
+
|
|
1082
|
+
if (ch === "'") {
|
|
1083
|
+
// Single-quoted run: literal until the next single quote.
|
|
1084
|
+
const end = body.indexOf("'", i + 1);
|
|
1085
|
+
if (end === -1) return null; // unterminated
|
|
1086
|
+
current += body.slice(i + 1, end);
|
|
1087
|
+
inToken = true;
|
|
1088
|
+
i = end + 1;
|
|
1089
|
+
continue;
|
|
1090
|
+
}
|
|
1091
|
+
|
|
1092
|
+
if (ch === '"') {
|
|
1093
|
+
// Double-quoted run: literal until the next double quote. We reject any
|
|
1094
|
+
// `$` or backtick inside (caught at the top of the loop on the next
|
|
1095
|
+
// pass only if unquoted — so scan the run explicitly here).
|
|
1096
|
+
const end = body.indexOf('"', i + 1);
|
|
1097
|
+
if (end === -1) return null; // unterminated
|
|
1098
|
+
const inner = body.slice(i + 1, end);
|
|
1099
|
+
if (inner.includes("$") || inner.includes("`")) return null;
|
|
1100
|
+
current += inner;
|
|
1101
|
+
inToken = true;
|
|
1102
|
+
i = end + 1;
|
|
1103
|
+
continue;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// Bare character.
|
|
1107
|
+
current += ch;
|
|
1108
|
+
inToken = true;
|
|
1109
|
+
i += 1;
|
|
1110
|
+
}
|
|
1111
|
+
flush();
|
|
1112
|
+
return tokens;
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1115
|
+
/**
|
|
1116
|
+
* Parse a single hand-written `alias <name>=<quote><body><quote>` line into an
|
|
1117
|
+
* AdoptableAlias (sans `lineRange`/`others`, which the scanner fills in), or
|
|
1118
|
+
* null when the line isn't a `claude`-wrapping alias we can tokenize.
|
|
1119
|
+
*/
|
|
1120
|
+
function parseAdoptableLine(line: string): Omit<
|
|
1121
|
+
AdoptableAlias,
|
|
1122
|
+
"lineRange" | "others"
|
|
1123
|
+
> | null {
|
|
1124
|
+
const match = ANY_ALIAS_LINE_RE.exec(line.trim());
|
|
1125
|
+
if (!match) return null;
|
|
1126
|
+
const [, name, , body] = match;
|
|
1127
|
+
const tokens = tokenizeGeneralAliasBody(body);
|
|
1128
|
+
if (!tokens || tokens.length === 0 || tokens[0] !== "claude") return null;
|
|
1129
|
+
|
|
1130
|
+
const args = tokens.slice(1);
|
|
1131
|
+
const { flags, leftovers } = argsToFlagValuesWithLeftovers(args);
|
|
1132
|
+
|
|
1133
|
+
// Fixpoint: render the parsed flags back to tokens and re-parse. If the
|
|
1134
|
+
// result differs, a token was mis-bucketed (e.g. a select value mistaken
|
|
1135
|
+
// for bare). Only an exact fixpoint with no leftovers is lossless.
|
|
1136
|
+
const config: AliasConfig = { aliasName: name, flags: withDefaults(flags) };
|
|
1137
|
+
const reparsed = argsToFlagValues(renderArgsAsTokens(config));
|
|
1138
|
+
const fixpoint = flagsDeepEqual(withDefaults(flags), withDefaults(reparsed));
|
|
1139
|
+
const lossless = leftovers.length === 0 && fixpoint;
|
|
1140
|
+
|
|
1141
|
+
return { name, flags, leftovers, lossless, rawLine: line };
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* Scan rc text for a top-level, hand-written `claude`-wrapping alias OUTSIDE
|
|
1146
|
+
* the managed block. Returns the first such alias (with any others noted), or
|
|
1147
|
+
* null when none is found.
|
|
1148
|
+
*
|
|
1149
|
+
* "Top-level" = the line's indentation is zero. We deliberately skip indented
|
|
1150
|
+
* lines: an alias nested in a function or `if` block can't be replaced by the
|
|
1151
|
+
* managed block without dragging the block into that scope.
|
|
1152
|
+
*
|
|
1153
|
+
* Lines inside an existing managed block are ignored — adoption is only for
|
|
1154
|
+
* the no-managed-block case (the screen's mount checks that separately, but we
|
|
1155
|
+
* guard here too so the function is correct in isolation).
|
|
1156
|
+
*/
|
|
1157
|
+
export function findAdoptableAlias(rcText: string): AdoptableAlias | null {
|
|
1158
|
+
const lines = rcText.split("\n");
|
|
1159
|
+
|
|
1160
|
+
// Compute the [begin, end] line span of the managed block, if present, so we
|
|
1161
|
+
// can exclude any alias inside it.
|
|
1162
|
+
let blockStart = -1;
|
|
1163
|
+
let blockEnd = -1;
|
|
1164
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1165
|
+
if (lines[i].includes(BLOCK_BEGIN)) blockStart = i;
|
|
1166
|
+
else if (lines[i].includes(BLOCK_END)) {
|
|
1167
|
+
blockEnd = i;
|
|
1168
|
+
break;
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
const insideBlock = (i: number) =>
|
|
1172
|
+
blockStart !== -1 && blockEnd !== -1 && i >= blockStart && i <= blockEnd;
|
|
1173
|
+
|
|
1174
|
+
let picked: AdoptableAlias | null = null;
|
|
1175
|
+
const others: string[] = [];
|
|
1176
|
+
|
|
1177
|
+
for (let i = 0; i < lines.length; i++) {
|
|
1178
|
+
const line = lines[i];
|
|
1179
|
+
if (insideBlock(i)) continue;
|
|
1180
|
+
// Top-level only: no leading whitespace.
|
|
1181
|
+
if (/^\s/.test(line)) continue;
|
|
1182
|
+
const parsed = parseAdoptableLine(line);
|
|
1183
|
+
if (!parsed) continue;
|
|
1184
|
+
if (picked === null) {
|
|
1185
|
+
picked = { ...parsed, lineRange: [i, i], others: [] };
|
|
1186
|
+
} else {
|
|
1187
|
+
others.push(line.trim());
|
|
1188
|
+
}
|
|
1189
|
+
}
|
|
1190
|
+
|
|
1191
|
+
if (picked) picked.others = others;
|
|
1192
|
+
return picked;
|
|
1193
|
+
}
|
|
1194
|
+
|
|
1195
|
+
/**
|
|
1196
|
+
* Replace a line range in `existing` (inclusive, zero-based) with `block`.
|
|
1197
|
+
* Used to absorb an adopted hand-written alias: the original line is removed
|
|
1198
|
+
* and the managed block takes its place, guaranteeing no duplicate alias.
|
|
1199
|
+
* Pure function — no I/O. Falls back to {@link spliceManagedBlock} semantics
|
|
1200
|
+
* (append) when the range is out of bounds.
|
|
1201
|
+
*/
|
|
1202
|
+
export function spliceManagedBlockAtRange(
|
|
1203
|
+
existing: string,
|
|
1204
|
+
block: string,
|
|
1205
|
+
range: [number, number],
|
|
1206
|
+
): string {
|
|
1207
|
+
const lines = existing.split("\n");
|
|
1208
|
+
const [start, end] = range;
|
|
1209
|
+
if (start < 0 || end >= lines.length || start > end) {
|
|
1210
|
+
return spliceManagedBlock(existing, block);
|
|
1211
|
+
}
|
|
1212
|
+
// `block` ends with a newline; splice it as its own line(s) where the old
|
|
1213
|
+
// alias line was. Rejoin and drop the duplicate trailing newline `block`
|
|
1214
|
+
// would introduce when followed by more lines.
|
|
1215
|
+
const before = lines.slice(0, start);
|
|
1216
|
+
const after = lines.slice(end + 1);
|
|
1217
|
+
const blockLines = block.replace(/\n$/, "").split("\n");
|
|
1218
|
+
return [...before, ...blockLines, ...after].join("\n");
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/** Fill any catalog flags missing from a partial map with their defaults. */
|
|
1222
|
+
function withDefaults(
|
|
1223
|
+
partial: Record<string, FlagValue>,
|
|
1224
|
+
): Record<string, FlagValue> {
|
|
1225
|
+
const out: Record<string, FlagValue> = {};
|
|
1226
|
+
for (const flag of ALIAS_FLAGS) {
|
|
1227
|
+
out[flag.id] = partial[flag.id] ?? defaultValueFor(flag);
|
|
1228
|
+
}
|
|
1229
|
+
return out;
|
|
1230
|
+
}
|
|
1231
|
+
|
|
1232
|
+
/** Deep-equal two flag maps via per-key JSON compare (small maps). */
|
|
1233
|
+
function flagsDeepEqual(
|
|
1234
|
+
a: Record<string, FlagValue>,
|
|
1235
|
+
b: Record<string, FlagValue>,
|
|
1236
|
+
): boolean {
|
|
1237
|
+
const aKeys = Object.keys(a).sort();
|
|
1238
|
+
const bKeys = Object.keys(b).sort();
|
|
1239
|
+
if (aKeys.length !== bKeys.length) return false;
|
|
1240
|
+
for (let i = 0; i < aKeys.length; i++) {
|
|
1241
|
+
if (aKeys[i] !== bKeys[i]) return false;
|
|
1242
|
+
}
|
|
1243
|
+
for (const k of aKeys) {
|
|
1244
|
+
if (JSON.stringify(a[k]) !== JSON.stringify(b[k])) return false;
|
|
1245
|
+
}
|
|
1246
|
+
return true;
|
|
1247
|
+
}
|