@narumitw/pi-starship 0.28.0 → 0.31.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/src/commands.ts CHANGED
@@ -1,30 +1,79 @@
1
1
  import type { ExtensionAPI, ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
2
- import type { AutocompleteItem } from "@earendil-works/pi-tui";
3
- import { atomicSaveConfigDocument, BUILT_IN_EXAMPLE, type LoadedStarshipConfig } from "./config.js";
2
+ import {
3
+ type AutocompleteItem,
4
+ type SelectItem,
5
+ SelectList,
6
+ truncateToWidth,
7
+ wrapTextWithAnsi,
8
+ } from "@earendil-works/pi-tui";
9
+ import {
10
+ atomicRestoreConfigDocument,
11
+ atomicSaveConfigDocument,
12
+ BUILT_IN_EXAMPLE,
13
+ type LoadedStarshipConfig,
14
+ validateConfigDocument,
15
+ } from "./config.js";
4
16
 
5
17
  const SUBCOMMANDS: AutocompleteItem[] = [
6
- { value: "settings", label: "settings", description: "Edit pi-starship.toml" },
7
- { value: "status", label: "status", description: "Show the effective settings source" },
18
+ { value: "settings", label: "settings", description: "Customize the footer TOML" },
19
+ { value: "status", label: "status", description: "Show configuration health and source" },
8
20
  { value: "help", label: "help", description: "Show configuration help" },
9
21
  ];
10
22
 
23
+ const MAIN_ACTIONS = {
24
+ customize: "customize",
25
+ diagnostics: "diagnostics",
26
+ help: "help",
27
+ advanced: "advanced",
28
+ } as const;
29
+
30
+ const ADVANCED_ACTIONS = {
31
+ details: "details",
32
+ restore: "restore",
33
+ back: "back",
34
+ } as const;
35
+
36
+ const PREVIEW_ACTIONS = {
37
+ continue: "continue",
38
+ edit: "edit",
39
+ cancel: "cancel",
40
+ } as const;
41
+
11
42
  export interface StarshipCommandOptions {
12
43
  getLoaded(): LoadedStarshipConfig;
13
44
  apply(loaded: LoadedStarshipConfig, ctx: ExtensionCommandContext): void;
14
45
  settingsPath: string;
46
+ renderPreview?(
47
+ loaded: LoadedStarshipConfig,
48
+ width: number,
49
+ ctx: ExtensionCommandContext,
50
+ ): string[];
15
51
  save?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
52
+ restore?: (settingsPath: string, rawDocument: string) => void;
53
+ validate?: (settingsPath: string, rawDocument: string) => LoadedStarshipConfig;
54
+ }
55
+
56
+ interface MenuItem extends SelectItem {
57
+ value: string;
16
58
  }
17
59
 
18
60
  export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipCommandOptions) {
19
61
  pi.registerCommand("starship", {
20
- description: "Edit or inspect the native Starship-style footer settings",
62
+ description: "Customize or inspect the native Starship-style footer",
21
63
  getArgumentCompletions(prefix: string): AutocompleteItem[] | null {
22
64
  const normalized = prefix.trim().toLowerCase();
23
65
  const matches = SUBCOMMANDS.filter((item) => item.value.startsWith(normalized));
24
66
  return matches.length > 0 ? matches : null;
25
67
  },
26
68
  handler: async (args, ctx) => {
27
- const subcommand = args.trim().split(/\s+/u)[0]?.toLowerCase() || "help";
69
+ const normalized = args.trim();
70
+ if (!normalized) {
71
+ if (ctx.mode === "tui") await showMainMenu(ctx, options);
72
+ else showHelp(ctx, options.settingsPath);
73
+ return;
74
+ }
75
+
76
+ const subcommand = normalized.split(/\s+/u)[0]?.toLowerCase() ?? "";
28
77
  switch (subcommand) {
29
78
  case "settings":
30
79
  await editSettings(ctx, options);
@@ -44,36 +93,358 @@ export function registerStarshipCommand(pi: ExtensionAPI, options: StarshipComma
44
93
  });
45
94
  }
46
95
 
47
- async function editSettings(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
96
+ async function showMainMenu(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
97
+ while (true) {
98
+ const loaded = options.getLoaded();
99
+ const state = configurationState(loaded);
100
+ const health = configurationHealth(loaded);
101
+ const selection = await showActionMenu(ctx, "pi-starship", () => [`${state} · ${health}`], [
102
+ {
103
+ value: MAIN_ACTIONS.customize,
104
+ label: "Customize footer",
105
+ description: `${state} · preview before applying`,
106
+ },
107
+ {
108
+ value: MAIN_ACTIONS.diagnostics,
109
+ label: "Check configuration",
110
+ description: health,
111
+ },
112
+ { value: MAIN_ACTIONS.help, label: "Help", description: "Formats, modules, and commands" },
113
+ {
114
+ value: MAIN_ACTIONS.advanced,
115
+ label: "Advanced",
116
+ description: "Details and restore controls",
117
+ },
118
+ ]);
119
+ switch (selection) {
120
+ case MAIN_ACTIONS.customize:
121
+ if (await editSettings(ctx, options)) return;
122
+ break;
123
+ case MAIN_ACTIONS.diagnostics:
124
+ await showDiagnosticsScreen(ctx, loaded);
125
+ break;
126
+ case MAIN_ACTIONS.help:
127
+ await showHelpScreen(ctx, options.settingsPath);
128
+ break;
129
+ case MAIN_ACTIONS.advanced:
130
+ if (!(await showAdvancedMenu(ctx, options))) return;
131
+ break;
132
+ default:
133
+ return;
134
+ }
135
+ }
136
+ }
137
+
138
+ async function showAdvancedMenu(
139
+ ctx: ExtensionCommandContext,
140
+ options: StarshipCommandOptions,
141
+ ): Promise<boolean> {
142
+ while (true) {
143
+ const loaded = options.getLoaded();
144
+ const alreadyBuiltIn = loaded.rawDocument === BUILT_IN_EXAMPLE;
145
+ const selection = await showActionMenu(ctx, "Advanced", () => [configurationState(loaded)], [
146
+ {
147
+ value: ADVANCED_ACTIONS.details,
148
+ label: "Configuration details",
149
+ description: `${configurationSource(loaded)} · ${fileName(options.settingsPath)}`,
150
+ },
151
+ {
152
+ value: ADVANCED_ACTIONS.restore,
153
+ label: "Restore built-in",
154
+ description: alreadyBuiltIn ? "Already active" : "Preview before replacing the document",
155
+ },
156
+ { value: ADVANCED_ACTIONS.back, label: "Back", description: "Return to pi-starship" },
157
+ ]);
158
+ if (selection === ADVANCED_ACTIONS.details) {
159
+ await showConfigurationDetails(ctx, loaded, options.settingsPath);
160
+ continue;
161
+ }
162
+ if (selection === ADVANCED_ACTIONS.restore) {
163
+ if (alreadyBuiltIn) {
164
+ ctx.ui.notify("The built-in footer configuration is already active.", "info");
165
+ continue;
166
+ }
167
+ if (await restoreBuiltIn(ctx, options)) return false;
168
+ continue;
169
+ }
170
+ return selection === ADVANCED_ACTIONS.back;
171
+ }
172
+ }
173
+
174
+ async function editSettings(
175
+ ctx: ExtensionCommandContext,
176
+ options: StarshipCommandOptions,
177
+ ): Promise<boolean> {
48
178
  if (ctx.mode !== "tui") {
49
179
  if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
50
- return;
180
+ return false;
51
181
  }
52
- const current = options.getLoaded();
53
- const edited = await ctx.ui.editor(
54
- "pi-starship.toml — save and close to apply",
55
- current.rawDocument ?? BUILT_IN_EXAMPLE,
182
+ let draft = options.getLoaded().rawDocument ?? BUILT_IN_EXAMPLE;
183
+ while (true) {
184
+ const edited = await ctx.ui.editor("Customize footer — close to preview", draft);
185
+ if (edited === undefined) return false;
186
+ draft = edited;
187
+ let validated: LoadedStarshipConfig;
188
+ try {
189
+ validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
190
+ } catch (error) {
191
+ ctx.ui.notify(`Footer draft is invalid: ${safeText(formatError(error))}`, "error");
192
+ const action = await showActionMenu(
193
+ ctx,
194
+ "Configuration needs attention",
195
+ () => [safeText(formatError(error)), "The current footer has not changed."],
196
+ [
197
+ { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
198
+ { value: PREVIEW_ACTIONS.cancel, label: "Back" },
199
+ ],
200
+ );
201
+ if (action === PREVIEW_ACTIONS.edit) continue;
202
+ return false;
203
+ }
204
+
205
+ const result = await reviewAndApply(ctx, options, validated, "Footer preview", false);
206
+ if (result === "edit") continue;
207
+ return result === "applied";
208
+ }
209
+ }
210
+
211
+ async function restoreBuiltIn(
212
+ ctx: ExtensionCommandContext,
213
+ options: StarshipCommandOptions,
214
+ ): Promise<boolean> {
215
+ const validated = (options.validate ?? validateConfigDocument)(
216
+ options.settingsPath,
217
+ BUILT_IN_EXAMPLE,
56
218
  );
57
- if (edited === undefined) return;
58
- try {
59
- const loaded = (options.save ?? atomicSaveConfigDocument)(options.settingsPath, edited);
60
- options.apply(loaded, ctx);
219
+ return (await reviewAndApply(ctx, options, validated, "Restore preview", true)) === "applied";
220
+ }
221
+
222
+ async function reviewAndApply(
223
+ ctx: ExtensionCommandContext,
224
+ options: StarshipCommandOptions,
225
+ validated: LoadedStarshipConfig,
226
+ title: string,
227
+ restore: boolean,
228
+ ): Promise<"applied" | "edit" | "cancel"> {
229
+ while (true) {
230
+ const selection = await showActionMenu(
231
+ ctx,
232
+ title,
233
+ (width) => previewBody(ctx, options, validated, width),
234
+ [
235
+ { value: PREVIEW_ACTIONS.continue, label: "Continue to apply" },
236
+ ...(restore ? [] : [{ value: PREVIEW_ACTIONS.edit, label: "Continue editing" }]),
237
+ { value: PREVIEW_ACTIONS.cancel, label: "Cancel" },
238
+ ],
239
+ );
240
+ if (selection === PREVIEW_ACTIONS.edit) return "edit";
241
+ if (selection !== PREVIEW_ACTIONS.continue) return "cancel";
242
+
243
+ const confirmed = await ctx.ui.confirm(
244
+ restore ? "Restore built-in footer?" : "Apply footer changes?",
245
+ restore
246
+ ? `Replace ${options.settingsPath} with the built-in configuration?`
247
+ : "Save this configuration and apply it immediately?",
248
+ );
249
+ if (!confirmed) continue;
250
+
251
+ const save = options.save ?? atomicSaveConfigDocument;
252
+ const previous = options.getLoaded();
253
+ let saved: LoadedStarshipConfig;
254
+ try {
255
+ saved = save(options.settingsPath, validated.rawDocument ?? BUILT_IN_EXAMPLE);
256
+ } catch (error) {
257
+ ctx.ui.notify(
258
+ `Footer settings were not saved: ${safeText(formatError(error))}. The previous footer remains active.`,
259
+ "error",
260
+ );
261
+ continue;
262
+ }
263
+
264
+ try {
265
+ options.apply(saved, ctx);
266
+ } catch (error) {
267
+ const rollbackError = restorePreviousConfiguration(ctx, options, previous);
268
+ ctx.ui.notify(
269
+ rollbackError
270
+ ? `Footer settings could not be applied: ${safeText(formatError(error))}. Restoring the previous configuration also failed: ${safeText(formatError(rollbackError))}.`
271
+ : `Footer settings could not be applied: ${safeText(formatError(error))}. The previous configuration was restored.`,
272
+ "error",
273
+ );
274
+ continue;
275
+ }
276
+
61
277
  const warningSuffix =
62
- loaded.diagnostics.length > 0
63
- ? ` (${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"})`
278
+ saved.diagnostics.length > 0
279
+ ? ` (${saved.diagnostics.length} warning${saved.diagnostics.length === 1 ? "" : "s"})`
64
280
  : "";
65
- ctx.ui.notify(`pi-starship settings saved and applied${warningSuffix}.`, "info");
281
+ ctx.ui.notify(
282
+ restore
283
+ ? `Built-in footer restored and applied${warningSuffix}.`
284
+ : `Footer settings saved and applied${warningSuffix}.`,
285
+ "info",
286
+ );
287
+ return "applied";
288
+ }
289
+ }
290
+
291
+ function restorePreviousConfiguration(
292
+ ctx: ExtensionCommandContext,
293
+ options: StarshipCommandOptions,
294
+ previous: LoadedStarshipConfig,
295
+ ): unknown {
296
+ try {
297
+ if (previous.rawDocument === undefined) {
298
+ throw new Error("The previous settings document is unavailable");
299
+ }
300
+ (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
301
+ options.apply(previous, ctx);
302
+ return undefined;
66
303
  } catch (error) {
67
- ctx.ui.notify(`pi-starship settings were not saved: ${formatError(error)}`, "error");
304
+ return error;
68
305
  }
69
306
  }
70
307
 
308
+ function previewBody(
309
+ ctx: ExtensionCommandContext,
310
+ options: StarshipCommandOptions,
311
+ loaded: LoadedStarshipConfig,
312
+ width: number,
313
+ ): string[] {
314
+ let lines: string[];
315
+ try {
316
+ lines = options.renderPreview?.(loaded, width, ctx) ?? [
317
+ "Live preview is unavailable until the footer is ready.",
318
+ "The draft is valid and can still be applied.",
319
+ ];
320
+ } catch (error) {
321
+ lines = [`Preview unavailable: ${safeText(formatError(error))}`];
322
+ }
323
+ const warning =
324
+ loaded.diagnostics.length === 0
325
+ ? "Draft validation: Healthy"
326
+ : `Draft validation: ${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"}`;
327
+ return [...lines, "", warning];
328
+ }
329
+
330
+ async function showDiagnosticsScreen(ctx: ExtensionCommandContext, loaded: LoadedStarshipConfig) {
331
+ await showActionMenu(ctx, "Configuration health", () => diagnosticLines(loaded, false), [
332
+ { value: ADVANCED_ACTIONS.back, label: "Back" },
333
+ ]);
334
+ }
335
+
336
+ async function showConfigurationDetails(
337
+ ctx: ExtensionCommandContext,
338
+ loaded: LoadedStarshipConfig,
339
+ settingsPath: string,
340
+ ) {
341
+ await showActionMenu(
342
+ ctx,
343
+ "Configuration details",
344
+ () => [
345
+ `State: ${configurationState(loaded)}`,
346
+ `Source: ${configurationSource(loaded)}`,
347
+ `Path: ${safeText(settingsPath)}`,
348
+ ...diagnosticLines(loaded, true),
349
+ ],
350
+ [{ value: ADVANCED_ACTIONS.back, label: "Back" }],
351
+ );
352
+ }
353
+
354
+ async function showHelpScreen(ctx: ExtensionCommandContext, settingsPath: string) {
355
+ await showActionMenu(
356
+ ctx,
357
+ "pi-starship help",
358
+ () => [
359
+ "Customize footer opens the TOML editor, then previews and confirms before saving.",
360
+ "Check configuration explains warnings without changing the footer.",
361
+ `Settings: ${safeText(settingsPath)}`,
362
+ "Docs: https://github.com/narumiruna/pi-extensions/tree/main/extensions/pi-starship",
363
+ ],
364
+ [{ value: ADVANCED_ACTIONS.back, label: "Back" }],
365
+ );
366
+ }
367
+
368
+ async function showActionMenu(
369
+ ctx: ExtensionCommandContext,
370
+ title: string,
371
+ body: (width: number) => readonly string[],
372
+ items: readonly MenuItem[],
373
+ ): Promise<string | null> {
374
+ return ctx.ui.custom<string | null>((tui, theme, _keybindings, done) => {
375
+ const list = new SelectList([...items], Math.min(items.length, 8), {
376
+ selectedPrefix: (text) => theme.fg("accent", text),
377
+ selectedText: (text) => theme.fg("accent", text),
378
+ description: (text) => theme.fg("muted", text),
379
+ scrollInfo: (text) => theme.fg("dim", text),
380
+ noMatch: (text) => theme.fg("warning", text),
381
+ });
382
+ list.onSelect = (item) => done(String(item.value));
383
+ list.onCancel = () => done(null);
384
+ return {
385
+ render(width: number): string[] {
386
+ const safeWidth = Math.max(1, width);
387
+ const content = [
388
+ ...wrapTextWithAnsi(theme.fg("accent", theme.bold(title)), safeWidth),
389
+ ...body(safeWidth).flatMap((line) => (line ? wrapTextWithAnsi(line, safeWidth) : [""])),
390
+ "",
391
+ ...list.render(safeWidth),
392
+ ...wrapTextWithAnsi(
393
+ theme.fg("dim", "↑↓ navigate • enter select • esc cancel"),
394
+ safeWidth,
395
+ ),
396
+ ];
397
+ return content.map((line) => truncateToWidth(line, safeWidth));
398
+ },
399
+ invalidate() {
400
+ list.invalidate();
401
+ },
402
+ handleInput(data: string) {
403
+ list.handleInput(data);
404
+ tui.requestRender();
405
+ },
406
+ };
407
+ });
408
+ }
409
+
410
+ function diagnosticLines(loaded: LoadedStarshipConfig, includeSummary: boolean): string[] {
411
+ const diagnostics = loaded.diagnostics
412
+ .slice(0, 8)
413
+ .map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`);
414
+ const remaining = loaded.diagnostics.length - diagnostics.length;
415
+ return [
416
+ ...(includeSummary ? [`Health: ${configurationHealth(loaded)}`] : []),
417
+ ...(diagnostics.length > 0 ? diagnostics : ["No configuration warnings."]),
418
+ ...(remaining > 0 ? [`${remaining} additional warnings not shown.`] : []),
419
+ ];
420
+ }
421
+
422
+ function configurationState(loaded: LoadedStarshipConfig): string {
423
+ if (loaded.source === "built-in") return "Built-in fallback";
424
+ return loaded.rawDocument === BUILT_IN_EXAMPLE ? "Built-in footer" : "Custom footer";
425
+ }
426
+
427
+ function configurationSource(loaded: LoadedStarshipConfig): string {
428
+ return loaded.source === "user" ? "User file" : "Built-in fallback";
429
+ }
430
+
431
+ function configurationHealth(loaded: LoadedStarshipConfig): string {
432
+ const errors = loaded.diagnostics.filter((item) => item.severity === "error").length;
433
+ if (errors > 0) return `${errors} error${errors === 1 ? "" : "s"}`;
434
+ const warnings = loaded.diagnostics.length;
435
+ return warnings === 0 ? "Healthy" : `${warnings} warning${warnings === 1 ? "" : "s"}`;
436
+ }
437
+
438
+ function fileName(path: string): string {
439
+ return path.replaceAll("\\", "/").split("/").at(-1) || path;
440
+ }
441
+
71
442
  function showStatus(ctx: ExtensionCommandContext, options: StarshipCommandOptions) {
72
443
  if (!canNotify(ctx)) return;
73
444
  const loaded = options.getLoaded();
74
445
  const diagnostics = loaded.diagnostics
75
446
  .slice(0, 5)
76
- .map((item) => `${item.path || "root"}: ${item.message}`)
447
+ .map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`)
77
448
  .join("; ");
78
449
  ctx.ui.notify(
79
450
  [
@@ -89,7 +460,8 @@ function showHelp(ctx: ExtensionCommandContext, settingsPath: string) {
89
460
  if (!canNotify(ctx)) return;
90
461
  ctx.ui.notify(
91
462
  [
92
- "/starship settings — edit and apply TOML",
463
+ "/starship — open the interactive footer menu",
464
+ "/starship settings — customize, preview, and apply TOML",
93
465
  "/starship status — show source, path, and warnings",
94
466
  "/starship help — show this help",
95
467
  `Settings: ${settingsPath}`,
@@ -103,6 +475,17 @@ function canNotify(ctx: ExtensionCommandContext): boolean {
103
475
  return ctx.mode === "tui" || ctx.hasUI;
104
476
  }
105
477
 
478
+ function safeText(value: string): string {
479
+ return Array.from(value, (character) => {
480
+ const codePoint = character.codePointAt(0) ?? 0;
481
+ const unsafe =
482
+ codePoint <= 0x08 ||
483
+ (codePoint >= 0x0b && codePoint <= 0x1f) ||
484
+ (codePoint >= 0x7f && codePoint <= 0x9f);
485
+ return unsafe ? `\\u${codePoint.toString(16).padStart(4, "0")}` : character;
486
+ }).join("");
487
+ }
488
+
106
489
  function formatError(error: unknown): string {
107
490
  return error instanceof Error ? error.message : String(error);
108
491
  }
package/src/config.ts CHANGED
@@ -18,6 +18,7 @@ import {
18
18
  } from "./format/formatter.js";
19
19
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
20
20
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
21
+ import type { ModuleOptionSchema } from "./modules/types.js";
21
22
 
22
23
  export const CONFIG_FILE_NAME = "pi-starship.toml";
23
24
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
@@ -26,12 +27,20 @@ const MODULE_CONTENT_VARIABLES = Object.fromEntries(
26
27
  MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
27
28
  ) as Record<ModuleName, readonly string[]>;
28
29
 
30
+ export type ModuleOptionValue =
31
+ | string
32
+ | boolean
33
+ | number
34
+ | readonly string[]
35
+ | Readonly<Record<string, string>>;
36
+
29
37
  export interface ModuleConfig {
30
38
  format: string;
31
39
  formatAst: FormatNode[];
32
40
  symbol: string;
33
41
  style: string;
34
42
  disabled: boolean;
43
+ options: Record<string, ModuleOptionValue>;
35
44
  }
36
45
 
37
46
  export interface ExtensionStatusConfig {
@@ -103,11 +112,17 @@ const BUILT_IN_PALETTE = {
103
112
  };
104
113
 
105
114
  const BUILT_IN_MODULES = Object.fromEntries(
106
- MODULE_DEFINITIONS.map(({ name, defaults }) => [
115
+ MODULE_DEFINITIONS.map(({ name, defaults, options }) => [
107
116
  name,
108
117
  {
109
118
  ...defaults,
110
119
  formatAst: parseFormat(defaults.format),
120
+ options: Object.fromEntries(
121
+ Object.entries(options ?? {}).map(([key, schema]) => [
122
+ key,
123
+ cloneOptionValue(schema.default),
124
+ ]),
125
+ ),
111
126
  },
112
127
  ]),
113
128
  ) as Record<ModuleName, ModuleConfig>;
@@ -339,7 +354,9 @@ function normalizeModule(
339
354
  config: StarshipConfig,
340
355
  diagnostics: ConfigDiagnostic[],
341
356
  ) {
342
- const known = new Set(["format", "symbol", "style", "disabled"]);
357
+ const definition = MODULE_DEFINITIONS.find((candidate) => candidate.name === name);
358
+ const optionSchemas: Readonly<Record<string, ModuleOptionSchema>> = definition?.options ?? {};
359
+ const known = new Set(["format", "symbol", "style", "disabled", ...Object.keys(optionSchemas)]);
343
360
  if (name === "extension_status") {
344
361
  known.add("separator");
345
362
  known.add("max_statuses");
@@ -378,6 +395,12 @@ function normalizeModule(
378
395
  diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
379
396
  } else module.disabled = value.disabled;
380
397
  }
398
+ for (const [key, schema] of Object.entries(optionSchemas)) {
399
+ if (value[key] === undefined) continue;
400
+ const normalized = normalizeModuleOption(value[key], schema);
401
+ if (normalized.ok) module.options[key] = normalized.value;
402
+ else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
403
+ }
381
404
  if (name !== "extension_status") return;
382
405
  if (value.separator !== undefined) {
383
406
  if (typeof value.separator !== "string") {
@@ -421,10 +444,9 @@ interface AtomicFileSystem {
421
444
  rmSync: typeof rmSync;
422
445
  }
423
446
 
424
- export function atomicSaveConfigDocument(
447
+ export function validateConfigDocument(
425
448
  settingsPath: string,
426
449
  rawDocument: string,
427
- overrides: Partial<AtomicFileSystem> = {},
428
450
  ): LoadedStarshipConfig {
429
451
  let parsed: TomlTable;
430
452
  try {
@@ -436,7 +458,37 @@ export function atomicSaveConfigDocument(
436
458
  if (normalized.diagnostics.some((item) => item.severity === "error")) {
437
459
  throw new Error(normalized.diagnostics.map((item) => item.message).join("\n"));
438
460
  }
461
+ return {
462
+ ...normalized,
463
+ source: "user",
464
+ settingsPath,
465
+ rawDocument,
466
+ };
467
+ }
439
468
 
469
+ export function atomicSaveConfigDocument(
470
+ settingsPath: string,
471
+ rawDocument: string,
472
+ overrides: Partial<AtomicFileSystem> = {},
473
+ ): LoadedStarshipConfig {
474
+ const validated = validateConfigDocument(settingsPath, rawDocument);
475
+ atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
476
+ return validated;
477
+ }
478
+
479
+ export function atomicRestoreConfigDocument(
480
+ settingsPath: string,
481
+ rawDocument: string,
482
+ overrides: Partial<AtomicFileSystem> = {},
483
+ ) {
484
+ atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
485
+ }
486
+
487
+ function atomicWriteConfigDocument(
488
+ settingsPath: string,
489
+ rawDocument: string,
490
+ overrides: Partial<AtomicFileSystem>,
491
+ ) {
440
492
  const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
441
493
  fs.mkdirSync(dirname(settingsPath), { recursive: true });
442
494
  const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
@@ -447,15 +499,9 @@ export function atomicSaveConfigDocument(
447
499
  try {
448
500
  fs.rmSync(tempPath, { force: true });
449
501
  } catch {
450
- // Best-effort cleanup must not replace the original save error.
502
+ // Best-effort cleanup must not replace the publication result.
451
503
  }
452
504
  }
453
- return {
454
- ...normalized,
455
- source: "user",
456
- settingsPath,
457
- rawDocument,
458
- };
459
505
  }
460
506
 
461
507
  function cloneBuiltInConfig(): StarshipConfig {
@@ -471,6 +517,7 @@ function cloneBuiltInConfig(): StarshipConfig {
471
517
  {
472
518
  ...BUILT_IN_CONFIG.modules[name],
473
519
  formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
520
+ options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
474
521
  },
475
522
  ]),
476
523
  ) as Record<ModuleName, ModuleConfig>,
@@ -517,6 +564,61 @@ function validateStyleVariables(
517
564
  }
518
565
  }
519
566
 
567
+ function normalizeModuleOption(
568
+ value: unknown,
569
+ schema: ModuleOptionSchema,
570
+ ): { ok: true; value: ModuleOptionValue } | { ok: false; message: string } {
571
+ switch (schema.kind) {
572
+ case "string":
573
+ return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
574
+ ? { ok: true, value }
575
+ : { ok: false, message: "Expected a non-empty string; using the default value" };
576
+ case "boolean":
577
+ return typeof value === "boolean"
578
+ ? { ok: true, value }
579
+ : { ok: false, message: "Expected boolean; using the default value" };
580
+ case "integer":
581
+ return typeof value === "number" &&
582
+ Number.isInteger(value) &&
583
+ value >= schema.minimum &&
584
+ value <= schema.maximum
585
+ ? { ok: true, value }
586
+ : {
587
+ ok: false,
588
+ message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
589
+ };
590
+ case "string-array": {
591
+ if (
592
+ !Array.isArray(value) ||
593
+ value.some(
594
+ (item) =>
595
+ typeof item !== "string" ||
596
+ item.length === 0 ||
597
+ (!schema.allowNegative && item.startsWith("!")),
598
+ )
599
+ ) {
600
+ return {
601
+ ok: false,
602
+ message: "Expected an array of valid strings; using the default value",
603
+ };
604
+ }
605
+ return { ok: true, value: [...value] as string[] };
606
+ }
607
+ case "string-map": {
608
+ if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
609
+ return { ok: false, message: "Expected a table of strings; using the default value" };
610
+ }
611
+ const result: Record<string, string> = {};
612
+ for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
613
+ return { ok: true, value: result };
614
+ }
615
+ }
616
+ }
617
+
618
+ function cloneOptionValue(value: ModuleOptionValue): ModuleOptionValue {
619
+ return typeof value === "object" ? structuredClone(value) : value;
620
+ }
621
+
520
622
  function setOwn<T>(record: Record<string, T>, key: string, value: T) {
521
623
  Object.defineProperty(record, key, {
522
624
  value,