@narumitw/pi-starship 0.55.1 → 0.56.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.
Files changed (106) hide show
  1. package/README.md +2 -0
  2. package/dist/chunks/{chunk-UX6PBXVK.js → chunk-SD7TUSSU.js} +113 -113
  3. package/dist/chunks/chunk-SD7TUSSU.js.map +7 -0
  4. package/dist/chunks/{chunk-P4XMFSQW.js → chunk-YWY5RIDQ.js} +3 -7
  5. package/dist/chunks/chunk-YWY5RIDQ.js.map +7 -0
  6. package/dist/chunks/{chunk-EOGXAMTA.js → chunk-ZQZSXXPI.js} +1 -1
  7. package/dist/chunks/chunk-ZQZSXXPI.js.map +7 -0
  8. package/dist/chunks/{cloud-BKHYWCTA.js → cloud-C4VU3TX3.js} +7 -14
  9. package/dist/chunks/cloud-C4VU3TX3.js.map +7 -0
  10. package/dist/chunks/{commands-53ZO2JUK.js → commands-MJCAK6JL.js} +18 -42
  11. package/dist/chunks/commands-MJCAK6JL.js.map +7 -0
  12. package/dist/chunks/{deployment-RKKOEQQ2.js → deployment-FMNTYRBW.js} +6 -21
  13. package/dist/chunks/deployment-FMNTYRBW.js.map +7 -0
  14. package/dist/chunks/{development-BERD42HW.js → development-OUYXDPBS.js} +4 -8
  15. package/dist/chunks/development-OUYXDPBS.js.map +7 -0
  16. package/dist/chunks/{execution-42JTEY3N.js → execution-HJOGLMWD.js} +3 -3
  17. package/dist/chunks/execution-HJOGLMWD.js.map +7 -0
  18. package/dist/chunks/{languages-RMP6DW7H.js → languages-WXMF4GOF.js} +6 -22
  19. package/dist/chunks/languages-WXMF4GOF.js.map +7 -0
  20. package/dist/chunks/{package-LG5H7BBM.js → package-YXRZQAOV.js} +5 -14
  21. package/dist/chunks/package-YXRZQAOV.js.map +7 -0
  22. package/dist/index.ts +20 -55
  23. package/dist/index.ts.map +2 -2
  24. package/package.json +60 -61
  25. package/skills/configuring-pi-starship/SKILL.md +18 -4
  26. package/skills/configuring-pi-starship/references/configuration.md +70 -2
  27. package/skills/configuring-pi-starship/references/module-catalog.md +21 -0
  28. package/skills/configuring-pi-starship/references/modules.md +2 -0
  29. package/skills/configuring-pi-starship/scripts/apply.mjs +48 -47
  30. package/skills/configuring-pi-starship/scripts/backup.mjs +118 -0
  31. package/skills/configuring-pi-starship/scripts/config-path.mjs +3 -3
  32. package/skills/configuring-pi-starship/scripts/script-support.mjs +6 -6
  33. package/skills/configuring-pi-starship/scripts/validate.mjs +18 -18
  34. package/src/command-configuration.ts +267 -286
  35. package/src/command-contract.ts +6 -6
  36. package/src/command-inspector.ts +27 -27
  37. package/src/command-preset-picker.ts +45 -50
  38. package/src/command-preview.ts +153 -166
  39. package/src/commands.ts +590 -618
  40. package/src/config.ts +635 -660
  41. package/src/effective-config.ts +49 -48
  42. package/src/format/formatter.ts +211 -227
  43. package/src/format/style.ts +205 -216
  44. package/src/modules/activity.ts +74 -74
  45. package/src/modules/brand.ts +9 -9
  46. package/src/modules/cache.ts +18 -18
  47. package/src/modules/catalog.ts +79 -83
  48. package/src/modules/cloud.ts +54 -54
  49. package/src/modules/context.ts +27 -27
  50. package/src/modules/cost.ts +23 -23
  51. package/src/modules/deployment.ts +45 -45
  52. package/src/modules/development.ts +80 -81
  53. package/src/modules/directory.ts +89 -113
  54. package/src/modules/display.ts +9 -9
  55. package/src/modules/execution.ts +62 -69
  56. package/src/modules/extension-status.ts +59 -64
  57. package/src/modules/fill.ts +10 -10
  58. package/src/modules/git/branch.ts +26 -26
  59. package/src/modules/git/commit.ts +21 -23
  60. package/src/modules/git/metrics.ts +22 -22
  61. package/src/modules/git/runtime.ts +299 -334
  62. package/src/modules/git/state.ts +17 -17
  63. package/src/modules/git/status.ts +77 -79
  64. package/src/modules/git/worktree.ts +10 -12
  65. package/src/modules/github-pr.ts +20 -20
  66. package/src/modules/helpers.ts +3 -3
  67. package/src/modules/index.ts +21 -21
  68. package/src/modules/inspection.ts +105 -108
  69. package/src/modules/languages.ts +52 -59
  70. package/src/modules/model.ts +61 -67
  71. package/src/modules/package.ts +12 -12
  72. package/src/modules/provider.ts +25 -24
  73. package/src/modules/render.ts +131 -141
  74. package/src/modules/style-rules.ts +21 -0
  75. package/src/modules/thinking.ts +31 -26
  76. package/src/modules/time.ts +10 -13
  77. package/src/modules/tokens.ts +13 -13
  78. package/src/modules/truncation.ts +14 -17
  79. package/src/modules/turn.ts +9 -9
  80. package/src/modules/types.ts +133 -132
  81. package/src/modules/workspace-helpers.ts +4 -7
  82. package/src/pi-starship.ts +567 -603
  83. package/src/presets/catalog.ts +113 -113
  84. package/src/runtime/cloud.ts +122 -150
  85. package/src/runtime/command.ts +106 -108
  86. package/src/runtime/deployment.ts +150 -179
  87. package/src/runtime/development.ts +107 -124
  88. package/src/runtime/execution.ts +110 -124
  89. package/src/runtime/github-pr.ts +223 -252
  90. package/src/runtime/helpers.ts +186 -199
  91. package/src/runtime/languages.ts +149 -180
  92. package/src/runtime/package.ts +74 -87
  93. package/src/runtime/refresh-controller.ts +82 -86
  94. package/src/runtime/types.ts +38 -38
  95. package/src/runtime/workspace.ts +108 -116
  96. package/src/usage.ts +40 -40
  97. package/dist/chunks/chunk-EOGXAMTA.js.map +0 -7
  98. package/dist/chunks/chunk-P4XMFSQW.js.map +0 -7
  99. package/dist/chunks/chunk-UX6PBXVK.js.map +0 -7
  100. package/dist/chunks/cloud-BKHYWCTA.js.map +0 -7
  101. package/dist/chunks/commands-53ZO2JUK.js.map +0 -7
  102. package/dist/chunks/deployment-RKKOEQQ2.js.map +0 -7
  103. package/dist/chunks/development-BERD42HW.js.map +0 -7
  104. package/dist/chunks/execution-42JTEY3N.js.map +0 -7
  105. package/dist/chunks/languages-RMP6DW7H.js.map +0 -7
  106. package/dist/chunks/package-LG5H7BBM.js.map +0 -7
package/src/config.ts CHANGED
@@ -1,76 +1,60 @@
1
1
  import { randomUUID } from "node:crypto";
2
- import {
3
- existsSync,
4
- lstatSync,
5
- mkdirSync,
6
- readFileSync,
7
- renameSync,
8
- rmSync,
9
- writeFileSync,
10
- } from "node:fs";
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
11
3
  import { createRequire } from "node:module";
12
4
  import { dirname, join } from "node:path";
13
5
  import type { TomlTable } from "smol-toml";
14
- import {
15
- type FormatNode,
16
- formatVariables,
17
- parseFormat,
18
- styleVariables,
19
- } from "./format/formatter.js";
6
+ import { type FormatNode, formatVariables, parseFormat, styleVariables } from "./format/formatter.js";
20
7
  import { type ColorPalette, isValidStyle, parseColor } from "./format/style.js";
21
8
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
22
- import type {
23
- ModuleDisplayConfig,
24
- ModuleOptionSchema,
25
- ModuleOptionValue,
26
- } from "./modules/types.js";
9
+ import type { ModuleDisplayConfig, ModuleOptionSchema, ModuleOptionValue, ModuleStyleRule } from "./modules/types.js";
27
10
 
28
11
  export const CONFIG_FILE_NAME = "pi-starship.toml";
29
12
  export { MODULE_NAMES, type ModuleName } from "./modules/catalog.js";
30
13
 
31
14
  const MODULE_CONTENT_VARIABLES = Object.fromEntries(
32
- MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
15
+ MODULE_DEFINITIONS.map((definition) => [definition.name, definition.variables]),
33
16
  ) as Record<ModuleName, readonly string[]>;
34
17
 
35
18
  export interface ModuleConfig {
36
- format: string;
37
- formatAst: FormatNode[];
38
- symbol: string;
39
- style: string;
40
- styles: Record<string, string>;
41
- display: ModuleDisplayConfig[];
42
- disabled: boolean;
43
- options: Record<string, ModuleOptionValue>;
19
+ format: string;
20
+ formatAst: FormatNode[];
21
+ symbol: string;
22
+ style: string;
23
+ styles: Record<string, string>;
24
+ styleRules: ModuleStyleRule[];
25
+ display: ModuleDisplayConfig[];
26
+ disabled: boolean;
27
+ options: Record<string, ModuleOptionValue>;
44
28
  }
45
29
 
46
30
  export interface ExtensionStatusConfig {
47
- separator: string;
48
- maxStatuses: number;
49
- icons: Record<string, string>;
31
+ separator: string;
32
+ maxStatuses: number;
33
+ icons: Record<string, string>;
50
34
  }
51
35
 
52
36
  export interface StarshipConfig {
53
- format: string;
54
- formatAst: FormatNode[];
55
- palette?: string;
56
- palettes: Record<string, Record<string, string>>;
57
- modules: Record<ModuleName, ModuleConfig>;
58
- extensionStatus: ExtensionStatusConfig;
37
+ format: string;
38
+ formatAst: FormatNode[];
39
+ palette?: string;
40
+ palettes: Record<string, Record<string, string>>;
41
+ modules: Record<ModuleName, ModuleConfig>;
42
+ extensionStatus: ExtensionStatusConfig;
59
43
  }
60
44
 
61
45
  export interface ConfigDiagnostic {
62
- severity: "warning" | "error";
63
- path: string;
64
- message: string;
46
+ severity: "warning" | "error";
47
+ path: string;
48
+ message: string;
65
49
  }
66
50
 
67
51
  export interface LoadedStarshipConfig {
68
- config: StarshipConfig;
69
- source: "built-in" | "user";
70
- settingsPath: string;
71
- rawDocument?: string;
72
- fileIdentity?: { dev: number; ino: number };
73
- diagnostics: ConfigDiagnostic[];
52
+ config: StarshipConfig;
53
+ source: "built-in" | "user";
54
+ settingsPath: string;
55
+ rawDocument?: string;
56
+ fileIdentity?: { dev: number; ino: number };
57
+ diagnostics: ConfigDiagnostic[];
74
58
  }
75
59
 
76
60
  const BUILT_IN_FORMAT_DOCUMENT = String.raw`format = """
@@ -84,34 +68,31 @@ $activity\
84
68
  $context\
85
69
  $time"""`;
86
70
 
87
- const BUILT_IN_FORMAT =
88
- "$brand$model$thinking$directory$git_branch$git_status$activity$context$time";
71
+ const BUILT_IN_FORMAT = "$brand$model$thinking$directory$git_branch$git_status$activity$context$time";
89
72
 
90
73
  const BUILT_IN_MODULES = Object.fromEntries(
91
- MODULE_DEFINITIONS.map(({ name, defaults, styleDefaults, displayDefaults, options }) => [
92
- name,
93
- {
94
- ...defaults,
95
- formatAst: parseFormat(defaults.format),
96
- styles: { ...styleDefaults },
97
- display: structuredClone(displayDefaults ?? []),
98
- options: Object.fromEntries(
99
- Object.entries(options ?? {}).map(([key, schema]) => [
100
- key,
101
- cloneOptionValue(schema.default),
102
- ]),
103
- ),
104
- },
105
- ]),
74
+ MODULE_DEFINITIONS.map(({ name, defaults, styleDefaults, displayDefaults, options }) => [
75
+ name,
76
+ {
77
+ ...defaults,
78
+ formatAst: parseFormat(defaults.format),
79
+ styles: { ...styleDefaults },
80
+ styleRules: [] as ModuleStyleRule[],
81
+ display: structuredClone(displayDefaults ?? []),
82
+ options: Object.fromEntries(
83
+ Object.entries(options ?? {}).map(([key, schema]) => [key, cloneOptionValue(schema.default)]),
84
+ ),
85
+ },
86
+ ]),
106
87
  ) as Record<ModuleName, ModuleConfig>;
107
88
 
108
89
  export const BUILT_IN_CONFIG: StarshipConfig = {
109
- format: BUILT_IN_FORMAT,
110
- formatAst: parseFormat(BUILT_IN_FORMAT),
111
- palette: undefined,
112
- palettes: {},
113
- modules: BUILT_IN_MODULES,
114
- extensionStatus: { separator: " • ", maxStatuses: 5, icons: {} },
90
+ format: BUILT_IN_FORMAT,
91
+ formatAst: parseFormat(BUILT_IN_FORMAT),
92
+ palette: undefined,
93
+ palettes: {},
94
+ modules: BUILT_IN_MODULES,
95
+ extensionStatus: { separator: " • ", maxStatuses: 5, icons: {} },
115
96
  };
116
97
 
117
98
  export const BUILT_IN_EXAMPLE = `# Native Pi modules with Starship-compatible format and style syntax.\n${BUILT_IN_FORMAT_DOCUMENT}\n`;
@@ -120,684 +101,678 @@ const require = createRequire(import.meta.url);
120
101
  let parseTomlImplementation: typeof import("smol-toml")["parse"] | undefined;
121
102
 
122
103
  function parseToml(document: string): TomlTable {
123
- parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
124
- return parseTomlImplementation(document);
104
+ parseTomlImplementation ??= (require("smol-toml") as typeof import("smol-toml")).parse;
105
+ return parseTomlImplementation(document);
125
106
  }
126
107
 
127
108
  export function settingsFilePath(agentDir: string): string {
128
- return join(agentDir, CONFIG_FILE_NAME);
109
+ return join(agentDir, CONFIG_FILE_NAME);
129
110
  }
130
111
 
131
112
  export function loadStarshipConfig(settingsPath: string): LoadedStarshipConfig {
132
- let rawDocument: string;
133
- try {
134
- rawDocument = readFileSync(settingsPath, "utf8");
135
- } catch (error) {
136
- if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
137
- return {
138
- config: cloneBuiltInConfig(),
139
- source: "built-in",
140
- settingsPath,
141
- diagnostics: [],
142
- };
143
- }
144
- return {
145
- config: cloneBuiltInConfig(),
146
- source: "built-in",
147
- settingsPath,
148
- diagnostics: [diagnostic("error", "", `Unable to read settings: ${formatError(error)}`)],
149
- };
150
- }
151
-
152
- let parsed: TomlTable;
153
- try {
154
- parsed = parseToml(rawDocument);
155
- } catch (error) {
156
- return {
157
- config: cloneBuiltInConfig(),
158
- source: "built-in",
159
- settingsPath,
160
- rawDocument,
161
- diagnostics: [diagnostic("error", "", `Unable to parse TOML: ${formatError(error)}`)],
162
- };
163
- }
164
- const normalized = normalizeConfig(parsed);
165
- return {
166
- ...normalized,
167
- source: "user",
168
- settingsPath,
169
- rawDocument,
170
- };
113
+ let rawDocument: string;
114
+ try {
115
+ rawDocument = readFileSync(settingsPath, "utf8");
116
+ } catch (error) {
117
+ if ((error as NodeJS.ErrnoException).code === "ENOENT" && !existsSync(settingsPath)) {
118
+ return {
119
+ config: cloneBuiltInConfig(),
120
+ source: "built-in",
121
+ settingsPath,
122
+ diagnostics: [],
123
+ };
124
+ }
125
+ return {
126
+ config: cloneBuiltInConfig(),
127
+ source: "built-in",
128
+ settingsPath,
129
+ diagnostics: [diagnostic("error", "", `Unable to read settings: ${formatError(error)}`)],
130
+ };
131
+ }
132
+
133
+ let parsed: TomlTable;
134
+ try {
135
+ parsed = parseToml(rawDocument);
136
+ } catch (error) {
137
+ return {
138
+ config: cloneBuiltInConfig(),
139
+ source: "built-in",
140
+ settingsPath,
141
+ rawDocument,
142
+ diagnostics: [diagnostic("error", "", `Unable to parse TOML: ${formatError(error)}`)],
143
+ };
144
+ }
145
+ const normalized = normalizeConfig(parsed);
146
+ return {
147
+ ...normalized,
148
+ source: "user",
149
+ settingsPath,
150
+ rawDocument,
151
+ };
171
152
  }
172
153
 
173
154
  export function normalizeConfig(value: unknown): {
174
- config: StarshipConfig;
175
- diagnostics: ConfigDiagnostic[];
155
+ config: StarshipConfig;
156
+ diagnostics: ConfigDiagnostic[];
176
157
  } {
177
- const config = cloneBuiltInConfig();
178
- const diagnostics: ConfigDiagnostic[] = [];
179
- if (!isRecord(value)) {
180
- return {
181
- config,
182
- diagnostics: [diagnostic("error", "", "Settings must contain a TOML table")],
183
- };
184
- }
185
-
186
- const knownRoot = new Set(["format", "palette", "palettes", ...MODULE_NAMES]);
187
- for (const key of Object.keys(value)) {
188
- if (!knownRoot.has(key)) diagnostics.push(unknownDiagnostic(key));
189
- }
190
-
191
- if (value.format !== undefined) {
192
- if (typeof value.format !== "string") {
193
- diagnostics.push(typeDiagnostic("format", "string"));
194
- } else {
195
- try {
196
- config.formatAst = parseFormat(value.format);
197
- config.format = value.format;
198
- } catch (error) {
199
- diagnostics.push(
200
- diagnostic("warning", "format", `Invalid format; using built-in: ${formatError(error)}`),
201
- );
202
- }
203
- }
204
- }
205
-
206
- if (value.palettes !== undefined) {
207
- if (!isRecord(value.palettes)) {
208
- diagnostics.push(typeDiagnostic("palettes", "table"));
209
- } else {
210
- for (const [paletteName, paletteValue] of Object.entries(value.palettes)) {
211
- if (!isRecord(paletteValue)) {
212
- diagnostics.push(typeDiagnostic(`palettes.${paletteName}`, "table"));
213
- continue;
214
- }
215
- const palette: Record<string, string> = {};
216
- for (const [name, color] of Object.entries(paletteValue)) {
217
- if (typeof color !== "string" || !parseColor(color.toLowerCase())) {
218
- diagnostics.push(
219
- diagnostic(
220
- "warning",
221
- `palettes.${paletteName}.${name}`,
222
- "Palette colors must be named, ANSI 0-255, or #RRGGBB",
223
- ),
224
- );
225
- continue;
226
- }
227
- setOwn(palette, name, color);
228
- }
229
- setOwn(config.palettes, paletteName, palette);
230
- }
231
- }
232
- }
233
-
234
- if (value.palette !== undefined) {
235
- if (typeof value.palette !== "string") diagnostics.push(typeDiagnostic("palette", "string"));
236
- else {
237
- config.palette = value.palette;
238
- if (!Object.hasOwn(config.palettes, value.palette)) {
239
- diagnostics.push(
240
- diagnostic("warning", "palette", `Unknown palette ${JSON.stringify(value.palette)}`),
241
- );
242
- }
243
- }
244
- }
245
-
246
- for (const name of MODULE_NAMES) {
247
- const moduleValue = value[name];
248
- if (moduleValue === undefined) continue;
249
- if (!isRecord(moduleValue)) {
250
- diagnostics.push(typeDiagnostic(name, "table"));
251
- continue;
252
- }
253
- normalizeModule(name, moduleValue, config, diagnostics);
254
- }
255
-
256
- validateFormatVariables(
257
- config.formatAst,
258
- new Set([...MODULE_NAMES, "all"]),
259
- "format",
260
- diagnostics,
261
- );
262
- validateStyleVariables(config.formatAst, new Set(), "format", diagnostics);
263
- const palette = activePalette(config);
264
- validateLiteralStyles(config.formatAst, palette, "format", diagnostics);
265
- for (const definition of MODULE_DEFINITIONS) {
266
- const name = definition.name;
267
- const module = config.modules[name];
268
- validateFormatVariables(
269
- module.formatAst,
270
- new Set(MODULE_CONTENT_VARIABLES[name]),
271
- `${name}.format`,
272
- diagnostics,
273
- );
274
- validateStyleVariables(
275
- module.formatAst,
276
- new Set(definition.styleVariables ?? ["style"]),
277
- `${name}.format`,
278
- diagnostics,
279
- );
280
- validateLiteralStyles(module.formatAst, palette, `${name}.format`, diagnostics);
281
- if (definition.styleDefaults) {
282
- if (definition.fallbackStyle) {
283
- validateModuleStyleField(name, "style", module, palette, diagnostics);
284
- }
285
- for (const field of Object.keys(definition.styleDefaults)) {
286
- validateModuleStyleField(name, field, module, palette, diagnostics);
287
- }
288
- } else if (!definition.displayDefaults) {
289
- validateModuleStyleField(name, "style", module, palette, diagnostics);
290
- }
291
- }
292
-
293
- return { config, diagnostics };
158
+ const config = cloneBuiltInConfig();
159
+ const diagnostics: ConfigDiagnostic[] = [];
160
+ if (!isRecord(value)) {
161
+ return {
162
+ config,
163
+ diagnostics: [diagnostic("error", "", "Settings must contain a TOML table")],
164
+ };
165
+ }
166
+
167
+ const knownRoot = new Set(["format", "palette", "palettes", ...MODULE_NAMES]);
168
+ for (const key of Object.keys(value)) {
169
+ if (!knownRoot.has(key)) diagnostics.push(unknownDiagnostic(key));
170
+ }
171
+
172
+ if (value.format !== undefined) {
173
+ if (typeof value.format !== "string") {
174
+ diagnostics.push(typeDiagnostic("format", "string"));
175
+ } else {
176
+ try {
177
+ config.formatAst = parseFormat(value.format);
178
+ config.format = value.format;
179
+ } catch (error) {
180
+ diagnostics.push(diagnostic("warning", "format", `Invalid format; using built-in: ${formatError(error)}`));
181
+ }
182
+ }
183
+ }
184
+
185
+ if (value.palettes !== undefined) {
186
+ if (!isRecord(value.palettes)) {
187
+ diagnostics.push(typeDiagnostic("palettes", "table"));
188
+ } else {
189
+ for (const [paletteName, paletteValue] of Object.entries(value.palettes)) {
190
+ if (!isRecord(paletteValue)) {
191
+ diagnostics.push(typeDiagnostic(`palettes.${paletteName}`, "table"));
192
+ continue;
193
+ }
194
+ const palette: Record<string, string> = {};
195
+ for (const [name, color] of Object.entries(paletteValue)) {
196
+ if (typeof color !== "string" || !parseColor(color.toLowerCase())) {
197
+ diagnostics.push(
198
+ diagnostic(
199
+ "warning",
200
+ `palettes.${paletteName}.${name}`,
201
+ "Palette colors must be named, ANSI 0-255, or #RRGGBB",
202
+ ),
203
+ );
204
+ continue;
205
+ }
206
+ setOwn(palette, name, color);
207
+ }
208
+ setOwn(config.palettes, paletteName, palette);
209
+ }
210
+ }
211
+ }
212
+
213
+ if (value.palette !== undefined) {
214
+ if (typeof value.palette !== "string") diagnostics.push(typeDiagnostic("palette", "string"));
215
+ else {
216
+ config.palette = value.palette;
217
+ if (!Object.hasOwn(config.palettes, value.palette)) {
218
+ diagnostics.push(diagnostic("warning", "palette", `Unknown palette ${JSON.stringify(value.palette)}`));
219
+ }
220
+ }
221
+ }
222
+
223
+ for (const name of MODULE_NAMES) {
224
+ const moduleValue = value[name];
225
+ if (moduleValue === undefined) continue;
226
+ if (!isRecord(moduleValue)) {
227
+ diagnostics.push(typeDiagnostic(name, "table"));
228
+ continue;
229
+ }
230
+ normalizeModule(name, moduleValue, config, diagnostics);
231
+ }
232
+
233
+ validateFormatVariables(config.formatAst, new Set([...MODULE_NAMES, "all"]), "format", diagnostics);
234
+ validateStyleVariables(config.formatAst, new Set(), "format", diagnostics);
235
+ const palette = activePalette(config);
236
+ validateLiteralStyles(config.formatAst, palette, "format", diagnostics);
237
+ for (const definition of MODULE_DEFINITIONS) {
238
+ const name = definition.name;
239
+ const module = config.modules[name];
240
+ validateFormatVariables(module.formatAst, new Set(MODULE_CONTENT_VARIABLES[name]), `${name}.format`, diagnostics);
241
+ validateStyleVariables(
242
+ module.formatAst,
243
+ new Set(definition.styleVariables ?? ["style"]),
244
+ `${name}.format`,
245
+ diagnostics,
246
+ );
247
+ validateLiteralStyles(module.formatAst, palette, `${name}.format`, diagnostics);
248
+ if (definition.styleDefaults) {
249
+ if (definition.fallbackStyle) {
250
+ validateModuleStyleField(name, "style", module, palette, diagnostics);
251
+ }
252
+ for (const field of Object.keys(definition.styleDefaults)) {
253
+ validateModuleStyleField(name, field, module, palette, diagnostics);
254
+ }
255
+ } else if (!definition.displayDefaults) {
256
+ validateModuleStyleField(name, "style", module, palette, diagnostics);
257
+ }
258
+ }
259
+
260
+ return { config, diagnostics };
294
261
  }
295
262
 
296
263
  function normalizeModule(
297
- name: ModuleName,
298
- value: Record<string, unknown>,
299
- config: StarshipConfig,
300
- diagnostics: ConfigDiagnostic[],
264
+ name: ModuleName,
265
+ value: Record<string, unknown>,
266
+ config: StarshipConfig,
267
+ diagnostics: ConfigDiagnostic[],
301
268
  ) {
302
- const definition = MODULE_DEFINITIONS.find((candidate) => candidate.name === name);
303
- if (!definition) return;
304
- const optionSchemas: Readonly<Record<string, ModuleOptionSchema>> = definition.options ?? {};
305
- const known = new Set(["format", "symbol", "disabled", ...Object.keys(optionSchemas)]);
306
- if (definition.styleDefaults) {
307
- if (definition.fallbackStyle) known.add("style");
308
- for (const field of Object.keys(definition.styleDefaults)) known.add(field);
309
- } else if (!definition.displayDefaults) known.add("style");
310
- if (definition.displayDefaults) known.add("display");
311
- if (name === "extension_status") {
312
- known.add("separator");
313
- known.add("max_statuses");
314
- known.add("icons");
315
- }
316
- for (const key of Object.keys(value)) {
317
- if (!known.has(key)) diagnostics.push(unknownDiagnostic(`${name}.${key}`));
318
- }
319
- const module = config.modules[name];
320
- if (value.format !== undefined) {
321
- if (typeof value.format !== "string")
322
- diagnostics.push(typeDiagnostic(`${name}.format`, "string"));
323
- else {
324
- try {
325
- module.formatAst = parseFormat(value.format);
326
- module.format = value.format;
327
- } catch (error) {
328
- diagnostics.push(
329
- diagnostic(
330
- "warning",
331
- `${name}.format`,
332
- `Invalid format; using module default: ${formatError(error)}`,
333
- ),
334
- );
335
- }
336
- }
337
- }
338
- if (value.symbol !== undefined) {
339
- if (typeof value.symbol !== "string") {
340
- diagnostics.push(typeDiagnostic(`${name}.symbol`, "string"));
341
- } else module.symbol = value.symbol;
342
- }
343
- if (definition.styleDefaults && definition.fallbackStyle && value.style !== undefined) {
344
- if (typeof value.style !== "string") {
345
- diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
346
- } else module.style = value.style;
347
- }
348
- if (definition.styleDefaults) {
349
- for (const field of Object.keys(definition.styleDefaults)) {
350
- if (value[field] === undefined) continue;
351
- if (typeof value[field] !== "string") {
352
- diagnostics.push(typeDiagnostic(`${name}.${field}`, "string"));
353
- } else module.styles[field] = value[field];
354
- }
355
- } else if (!definition.displayDefaults && value.style !== undefined) {
356
- if (typeof value.style !== "string") {
357
- diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
358
- } else module.style = value.style;
359
- }
360
- if (definition.displayDefaults && value.display !== undefined) {
361
- module.display = normalizeDisplay(
362
- name,
363
- value.display,
364
- definition.displayDefaults,
365
- activePalette(config),
366
- diagnostics,
367
- );
368
- }
369
- if (value.disabled !== undefined) {
370
- if (typeof value.disabled !== "boolean") {
371
- diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
372
- } else module.disabled = value.disabled;
373
- }
374
- for (const [key, schema] of Object.entries(optionSchemas)) {
375
- if (value[key] === undefined) continue;
376
- const normalized = normalizeModuleOption(value[key], schema);
377
- if (normalized.ok) module.options[key] = normalized.value;
378
- else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
379
- }
380
- if (name !== "extension_status") return;
381
- if (value.separator !== undefined) {
382
- if (typeof value.separator !== "string") {
383
- diagnostics.push(typeDiagnostic("extension_status.separator", "string"));
384
- } else config.extensionStatus.separator = value.separator;
385
- }
386
- if (value.max_statuses !== undefined) {
387
- if (
388
- typeof value.max_statuses !== "number" ||
389
- !Number.isInteger(value.max_statuses) ||
390
- value.max_statuses < 0 ||
391
- value.max_statuses > 100
392
- ) {
393
- diagnostics.push(
394
- diagnostic(
395
- "warning",
396
- "extension_status.max_statuses",
397
- "Expected an integer from 0 through 100",
398
- ),
399
- );
400
- } else config.extensionStatus.maxStatuses = value.max_statuses;
401
- }
402
- if (value.icons !== undefined) {
403
- if (!isRecord(value.icons)) diagnostics.push(typeDiagnostic("extension_status.icons", "table"));
404
- else {
405
- config.extensionStatus.icons = Object.fromEntries(
406
- Object.entries(value.icons).flatMap(([key, icon]) => {
407
- if (typeof icon === "string") return [[key, icon]];
408
- diagnostics.push(typeDiagnostic(`extension_status.icons.${key}`, "string"));
409
- return [];
410
- }),
411
- );
412
- }
413
- }
269
+ const definition = MODULE_DEFINITIONS.find((candidate) => candidate.name === name);
270
+ if (!definition) return;
271
+ const optionSchemas: Readonly<Record<string, ModuleOptionSchema>> = definition.options ?? {};
272
+ const known = new Set(["format", "symbol", "disabled", ...Object.keys(optionSchemas)]);
273
+ if (definition.styleDefaults) {
274
+ if (definition.fallbackStyle) known.add("style");
275
+ for (const field of Object.keys(definition.styleDefaults)) known.add(field);
276
+ } else if (!definition.displayDefaults) known.add("style");
277
+ if (definition.displayDefaults) known.add("display");
278
+ if (definition.styleRuleSelectors) known.add("style_rules");
279
+ if (name === "extension_status") {
280
+ known.add("separator");
281
+ known.add("max_statuses");
282
+ known.add("icons");
283
+ }
284
+ for (const key of Object.keys(value)) {
285
+ if (!known.has(key)) diagnostics.push(unknownDiagnostic(`${name}.${key}`));
286
+ }
287
+ const module = config.modules[name];
288
+ if (value.format !== undefined) {
289
+ if (typeof value.format !== "string") diagnostics.push(typeDiagnostic(`${name}.format`, "string"));
290
+ else {
291
+ try {
292
+ module.formatAst = parseFormat(value.format);
293
+ module.format = value.format;
294
+ } catch (error) {
295
+ diagnostics.push(
296
+ diagnostic("warning", `${name}.format`, `Invalid format; using module default: ${formatError(error)}`),
297
+ );
298
+ }
299
+ }
300
+ }
301
+ if (value.symbol !== undefined) {
302
+ if (typeof value.symbol !== "string") {
303
+ diagnostics.push(typeDiagnostic(`${name}.symbol`, "string"));
304
+ } else module.symbol = value.symbol;
305
+ }
306
+ if (definition.styleDefaults && definition.fallbackStyle && value.style !== undefined) {
307
+ if (typeof value.style !== "string") {
308
+ diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
309
+ } else module.style = value.style;
310
+ }
311
+ if (definition.styleDefaults) {
312
+ for (const field of Object.keys(definition.styleDefaults)) {
313
+ if (value[field] === undefined) continue;
314
+ if (typeof value[field] !== "string") {
315
+ diagnostics.push(typeDiagnostic(`${name}.${field}`, "string"));
316
+ } else module.styles[field] = value[field];
317
+ }
318
+ } else if (!definition.displayDefaults && value.style !== undefined) {
319
+ if (typeof value.style !== "string") {
320
+ diagnostics.push(typeDiagnostic(`${name}.style`, "string"));
321
+ } else module.style = value.style;
322
+ }
323
+ if (definition.displayDefaults && value.display !== undefined) {
324
+ module.display = normalizeDisplay(
325
+ name,
326
+ value.display,
327
+ definition.displayDefaults,
328
+ activePalette(config),
329
+ diagnostics,
330
+ );
331
+ }
332
+ if (definition.styleRuleSelectors && value.style_rules !== undefined) {
333
+ module.styleRules = normalizeStyleRules(
334
+ name,
335
+ value.style_rules,
336
+ new Set(Object.keys(definition.styleRuleSelectors)),
337
+ activePalette(config),
338
+ diagnostics,
339
+ );
340
+ }
341
+ if (value.disabled !== undefined) {
342
+ if (typeof value.disabled !== "boolean") {
343
+ diagnostics.push(typeDiagnostic(`${name}.disabled`, "boolean"));
344
+ } else module.disabled = value.disabled;
345
+ }
346
+ for (const [key, schema] of Object.entries(optionSchemas)) {
347
+ if (value[key] === undefined) continue;
348
+ const normalized = normalizeModuleOption(value[key], schema);
349
+ if (normalized.ok) module.options[key] = normalized.value;
350
+ else diagnostics.push(diagnostic("warning", `${name}.${key}`, normalized.message));
351
+ }
352
+ if (name !== "extension_status") return;
353
+ if (value.separator !== undefined) {
354
+ if (typeof value.separator !== "string") {
355
+ diagnostics.push(typeDiagnostic("extension_status.separator", "string"));
356
+ } else config.extensionStatus.separator = value.separator;
357
+ }
358
+ if (value.max_statuses !== undefined) {
359
+ if (
360
+ typeof value.max_statuses !== "number" ||
361
+ !Number.isInteger(value.max_statuses) ||
362
+ value.max_statuses < 0 ||
363
+ value.max_statuses > 100
364
+ ) {
365
+ diagnostics.push(
366
+ diagnostic("warning", "extension_status.max_statuses", "Expected an integer from 0 through 100"),
367
+ );
368
+ } else config.extensionStatus.maxStatuses = value.max_statuses;
369
+ }
370
+ if (value.icons !== undefined) {
371
+ if (!isRecord(value.icons)) diagnostics.push(typeDiagnostic("extension_status.icons", "table"));
372
+ else {
373
+ config.extensionStatus.icons = Object.fromEntries(
374
+ Object.entries(value.icons).flatMap(([key, icon]) => {
375
+ if (typeof icon === "string") return [[key, icon]];
376
+ diagnostics.push(typeDiagnostic(`extension_status.icons.${key}`, "string"));
377
+ return [];
378
+ }),
379
+ );
380
+ }
381
+ }
414
382
  }
415
383
 
416
384
  interface AtomicFileSystem {
417
- mkdirSync: typeof mkdirSync;
418
- writeFileSync: typeof writeFileSync;
419
- renameSync: typeof renameSync;
420
- rmSync: typeof rmSync;
421
- }
422
-
423
- export function validateConfigDocument(
424
- settingsPath: string,
425
- rawDocument: string,
426
- ): LoadedStarshipConfig {
427
- let parsed: TomlTable;
428
- try {
429
- parsed = parseToml(rawDocument);
430
- } catch (error) {
431
- throw new Error(`Unable to parse TOML: ${formatError(error)}`);
432
- }
433
- const normalized = normalizeConfig(parsed);
434
- if (normalized.diagnostics.some((item) => item.severity === "error")) {
435
- throw new Error(normalized.diagnostics.map((item) => item.message).join("\n"));
436
- }
437
- return {
438
- ...normalized,
439
- source: "user",
440
- settingsPath,
441
- rawDocument,
442
- };
385
+ mkdirSync: typeof mkdirSync;
386
+ writeFileSync: typeof writeFileSync;
387
+ renameSync: typeof renameSync;
388
+ rmSync: typeof rmSync;
389
+ }
390
+
391
+ export function validateConfigDocument(settingsPath: string, rawDocument: string): LoadedStarshipConfig {
392
+ let parsed: TomlTable;
393
+ try {
394
+ parsed = parseToml(rawDocument);
395
+ } catch (error) {
396
+ throw new Error(`Unable to parse TOML: ${formatError(error)}`);
397
+ }
398
+ const normalized = normalizeConfig(parsed);
399
+ if (normalized.diagnostics.some((item) => item.severity === "error")) {
400
+ throw new Error(normalized.diagnostics.map((item) => item.message).join("\n"));
401
+ }
402
+ return {
403
+ ...normalized,
404
+ source: "user",
405
+ settingsPath,
406
+ rawDocument,
407
+ };
443
408
  }
444
409
 
445
410
  export function atomicSaveConfigDocument(
446
- settingsPath: string,
447
- rawDocument: string,
448
- overrides: Partial<AtomicFileSystem> = {},
411
+ settingsPath: string,
412
+ rawDocument: string,
413
+ overrides: Partial<AtomicFileSystem> = {},
449
414
  ): LoadedStarshipConfig {
450
- const validated = validateConfigDocument(settingsPath, rawDocument);
451
- return {
452
- ...validated,
453
- fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
454
- };
415
+ const validated = validateConfigDocument(settingsPath, rawDocument);
416
+ return {
417
+ ...validated,
418
+ fileIdentity: atomicWriteConfigDocument(settingsPath, rawDocument, overrides),
419
+ };
455
420
  }
456
421
 
457
422
  export function atomicRestoreConfigDocument(
458
- settingsPath: string,
459
- rawDocument: string,
460
- overrides: Partial<AtomicFileSystem> = {},
423
+ settingsPath: string,
424
+ rawDocument: string,
425
+ overrides: Partial<AtomicFileSystem> = {},
461
426
  ) {
462
- atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
427
+ atomicWriteConfigDocument(settingsPath, rawDocument, overrides);
463
428
  }
464
429
 
465
430
  export function removeConfigDocumentIfMatches(
466
- settingsPath: string,
467
- expectedRawDocument: string,
468
- expectedIdentity: { dev: number; ino: number },
469
- overrides: Pick<Partial<AtomicFileSystem>, "rmSync"> = {},
431
+ settingsPath: string,
432
+ expectedRawDocument: string,
433
+ expectedIdentity: { dev: number; ino: number },
434
+ overrides: Pick<Partial<AtomicFileSystem>, "rmSync"> = {},
470
435
  ) {
471
- const quarantinePath = join(
472
- dirname(settingsPath),
473
- `.${CONFIG_FILE_NAME}.${randomUUID()}.rollback`,
474
- );
475
- const before = lstatSync(settingsPath);
476
- if (before.dev !== expectedIdentity.dev || before.ino !== expectedIdentity.ino) {
477
- throw new Error("Starship settings changed concurrently; the newer file was preserved");
478
- }
479
- renameSync(settingsPath, quarantinePath);
480
- const quarantined = lstatSync(quarantinePath);
481
- const quarantinedSavedFile =
482
- quarantined.isFile() &&
483
- !quarantined.isSymbolicLink() &&
484
- quarantined.dev === expectedIdentity.dev &&
485
- quarantined.ino === expectedIdentity.ino;
486
- if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
487
- (overrides.rmSync ?? rmSync)(quarantinePath);
488
- return;
489
- }
490
- if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
491
- try {
492
- renameSync(quarantinePath, settingsPath);
493
- } catch {
494
- // Keep the quarantine for recovery when its atomic restoration fails.
495
- }
496
- }
497
- throw new Error("Starship settings changed concurrently; the newer file was preserved");
436
+ const quarantinePath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.rollback`);
437
+ const before = lstatSync(settingsPath);
438
+ if (before.dev !== expectedIdentity.dev || before.ino !== expectedIdentity.ino) {
439
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
440
+ }
441
+ renameSync(settingsPath, quarantinePath);
442
+ const quarantined = lstatSync(quarantinePath);
443
+ const quarantinedSavedFile =
444
+ quarantined.isFile() &&
445
+ !quarantined.isSymbolicLink() &&
446
+ quarantined.dev === expectedIdentity.dev &&
447
+ quarantined.ino === expectedIdentity.ino;
448
+ if (quarantinedSavedFile && readFileSync(quarantinePath, "utf8") === expectedRawDocument) {
449
+ (overrides.rmSync ?? rmSync)(quarantinePath);
450
+ return;
451
+ }
452
+ if (quarantinedSavedFile && !pathEntryExists(settingsPath)) {
453
+ try {
454
+ renameSync(quarantinePath, settingsPath);
455
+ } catch {
456
+ // Keep the quarantine for recovery when its atomic restoration fails.
457
+ }
458
+ }
459
+ throw new Error("Starship settings changed concurrently; the newer file was preserved");
498
460
  }
499
461
 
500
462
  function atomicWriteConfigDocument(
501
- settingsPath: string,
502
- rawDocument: string,
503
- overrides: Partial<AtomicFileSystem>,
463
+ settingsPath: string,
464
+ rawDocument: string,
465
+ overrides: Partial<AtomicFileSystem>,
504
466
  ): { dev: number; ino: number } {
505
- const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
506
- const replaceExisting = pathEntryExists(settingsPath);
507
- fs.mkdirSync(dirname(settingsPath), { recursive: true });
508
- const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
509
- try {
510
- fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
511
- const info = lstatSync(tempPath);
512
- if (!replaceExisting && pathEntryExists(settingsPath)) {
513
- throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
514
- }
515
- fs.renameSync(tempPath, settingsPath);
516
- return { dev: info.dev, ino: info.ino };
517
- } finally {
518
- try {
519
- fs.rmSync(tempPath, { force: true });
520
- } catch {
521
- // Best-effort cleanup must not replace the publication result.
522
- }
523
- }
467
+ const fs = { mkdirSync, writeFileSync, renameSync, rmSync, ...overrides };
468
+ const replaceExisting = pathEntryExists(settingsPath);
469
+ fs.mkdirSync(dirname(settingsPath), { recursive: true });
470
+ const tempPath = join(dirname(settingsPath), `.${CONFIG_FILE_NAME}.${randomUUID()}.tmp`);
471
+ try {
472
+ fs.writeFileSync(tempPath, rawDocument, { encoding: "utf8", flag: "wx" });
473
+ const info = lstatSync(tempPath);
474
+ if (!replaceExisting && pathEntryExists(settingsPath)) {
475
+ throw new Error(`${CONFIG_FILE_NAME} was created concurrently; reopen settings and retry.`);
476
+ }
477
+ fs.renameSync(tempPath, settingsPath);
478
+ return { dev: info.dev, ino: info.ino };
479
+ } finally {
480
+ try {
481
+ fs.rmSync(tempPath, { force: true });
482
+ } catch {
483
+ // Best-effort cleanup must not replace the publication result.
484
+ }
485
+ }
524
486
  }
525
487
 
526
488
  function cloneBuiltInConfig(): StarshipConfig {
527
- return {
528
- ...BUILT_IN_CONFIG,
529
- formatAst: structuredClone(BUILT_IN_CONFIG.formatAst),
530
- palettes: Object.fromEntries(
531
- Object.entries(BUILT_IN_CONFIG.palettes).map(([name, colors]) => [name, { ...colors }]),
532
- ),
533
- modules: Object.fromEntries(
534
- MODULE_NAMES.map((name) => [
535
- name,
536
- {
537
- ...BUILT_IN_CONFIG.modules[name],
538
- formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
539
- styles: { ...BUILT_IN_CONFIG.modules[name].styles },
540
- display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
541
- options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
542
- },
543
- ]),
544
- ) as Record<ModuleName, ModuleConfig>,
545
- extensionStatus: {
546
- ...BUILT_IN_CONFIG.extensionStatus,
547
- icons: { ...BUILT_IN_CONFIG.extensionStatus.icons },
548
- },
549
- };
489
+ return {
490
+ ...BUILT_IN_CONFIG,
491
+ formatAst: structuredClone(BUILT_IN_CONFIG.formatAst),
492
+ palettes: Object.fromEntries(
493
+ Object.entries(BUILT_IN_CONFIG.palettes).map(([name, colors]) => [name, { ...colors }]),
494
+ ),
495
+ modules: Object.fromEntries(
496
+ MODULE_NAMES.map((name) => [
497
+ name,
498
+ {
499
+ ...BUILT_IN_CONFIG.modules[name],
500
+ formatAst: structuredClone(BUILT_IN_CONFIG.modules[name].formatAst),
501
+ styles: { ...BUILT_IN_CONFIG.modules[name].styles },
502
+ styleRules: structuredClone(BUILT_IN_CONFIG.modules[name].styleRules),
503
+ display: structuredClone(BUILT_IN_CONFIG.modules[name].display),
504
+ options: structuredClone(BUILT_IN_CONFIG.modules[name].options),
505
+ },
506
+ ]),
507
+ ) as Record<ModuleName, ModuleConfig>,
508
+ extensionStatus: {
509
+ ...BUILT_IN_CONFIG.extensionStatus,
510
+ icons: { ...BUILT_IN_CONFIG.extensionStatus.icons },
511
+ },
512
+ };
550
513
  }
551
514
 
552
515
  function validateFormatVariables(
553
- ast: readonly FormatNode[],
554
- allowed: ReadonlySet<string>,
555
- path: string,
556
- diagnostics: ConfigDiagnostic[],
516
+ ast: readonly FormatNode[],
517
+ allowed: ReadonlySet<string>,
518
+ path: string,
519
+ diagnostics: ConfigDiagnostic[],
557
520
  ) {
558
- for (const variable of formatVariables(ast)) {
559
- if (allowed.has(variable)) continue;
560
- diagnostics.push(
561
- diagnostic(
562
- "warning",
563
- path,
564
- `Unknown variable ${JSON.stringify(variable)} in ${path} was ignored`,
565
- ),
566
- );
567
- }
521
+ for (const variable of formatVariables(ast)) {
522
+ if (allowed.has(variable)) continue;
523
+ diagnostics.push(
524
+ diagnostic("warning", path, `Unknown variable ${JSON.stringify(variable)} in ${path} was ignored`),
525
+ );
526
+ }
568
527
  }
569
528
 
570
529
  function validateStyleVariables(
571
- ast: readonly FormatNode[],
572
- allowed: ReadonlySet<string>,
573
- path: string,
574
- diagnostics: ConfigDiagnostic[],
530
+ ast: readonly FormatNode[],
531
+ allowed: ReadonlySet<string>,
532
+ path: string,
533
+ diagnostics: ConfigDiagnostic[],
575
534
  ) {
576
- for (const variable of styleVariables(ast)) {
577
- if (allowed.has(variable)) continue;
578
- diagnostics.push(
579
- diagnostic(
580
- "warning",
581
- path,
582
- `Unknown style variable ${JSON.stringify(variable)} in ${path} was ignored`,
583
- ),
584
- );
585
- }
535
+ for (const variable of styleVariables(ast)) {
536
+ if (allowed.has(variable)) continue;
537
+ diagnostics.push(
538
+ diagnostic("warning", path, `Unknown style variable ${JSON.stringify(variable)} in ${path} was ignored`),
539
+ );
540
+ }
586
541
  }
587
542
 
588
543
  function validateModuleStyleField(
589
- name: ModuleName,
590
- field: string,
591
- module: ModuleConfig,
592
- palette: ColorPalette,
593
- diagnostics: ConfigDiagnostic[],
544
+ name: ModuleName,
545
+ field: string,
546
+ module: ModuleConfig,
547
+ palette: ColorPalette,
548
+ diagnostics: ConfigDiagnostic[],
594
549
  ) {
595
- const style = field === "style" ? module.style : module.styles[field];
596
- if (style === undefined || isValidStyle(style, palette)) return;
597
- diagnostics.push(
598
- diagnostic(
599
- "warning",
600
- `${name}.${field}`,
601
- `Invalid style ${JSON.stringify(style)}; using the module default`,
602
- ),
603
- );
604
- if (field === "style") module.style = BUILT_IN_CONFIG.modules[name].style;
605
- else {
606
- const fallback = BUILT_IN_CONFIG.modules[name].styles[field];
607
- if (fallback !== undefined) module.styles[field] = fallback;
608
- }
550
+ const style = field === "style" ? module.style : module.styles[field];
551
+ if (style === undefined || isValidStyle(style, palette)) return;
552
+ diagnostics.push(
553
+ diagnostic("warning", `${name}.${field}`, `Invalid style ${JSON.stringify(style)}; using the module default`),
554
+ );
555
+ if (field === "style") module.style = BUILT_IN_CONFIG.modules[name].style;
556
+ else {
557
+ const fallback = BUILT_IN_CONFIG.modules[name].styles[field];
558
+ if (fallback !== undefined) module.styles[field] = fallback;
559
+ }
560
+ }
561
+
562
+ function normalizeStyleRules(
563
+ name: ModuleName,
564
+ value: unknown,
565
+ allowedSelectors: ReadonlySet<string>,
566
+ palette: ColorPalette,
567
+ diagnostics: ConfigDiagnostic[],
568
+ ): ModuleStyleRule[] {
569
+ if (!Array.isArray(value)) {
570
+ diagnostics.push(typeDiagnostic(`${name}.style_rules`, "array of tables"));
571
+ return [];
572
+ }
573
+ const result: ModuleStyleRule[] = [];
574
+ for (const [index, entry] of value.entries()) {
575
+ const path = `${name}.style_rules.${index}`;
576
+ if (!isRecord(entry)) {
577
+ diagnostics.push(diagnostic("warning", path, "Expected a table; rule ignored"));
578
+ continue;
579
+ }
580
+ let valid = true;
581
+ for (const field of Object.keys(entry)) {
582
+ if (field !== "style" && !allowedSelectors.has(field)) {
583
+ diagnostics.push(diagnostic("warning", `${path}.${field}`, "Unknown style-rule field; rule ignored"));
584
+ valid = false;
585
+ }
586
+ }
587
+ if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
588
+ diagnostics.push(diagnostic("warning", `${path}.style`, "Expected a valid Starship style string; rule ignored"));
589
+ valid = false;
590
+ }
591
+ const selectors: Record<string, string> = {};
592
+ for (const selector of allowedSelectors) {
593
+ if (entry[selector] === undefined) continue;
594
+ if (typeof entry[selector] !== "string") {
595
+ diagnostics.push(diagnostic("warning", `${path}.${selector}`, "Expected string; rule ignored"));
596
+ valid = false;
597
+ } else setOwn(selectors, selector, entry[selector]);
598
+ }
599
+ if (valid) result.push({ style: entry.style as string, selectors });
600
+ }
601
+ return result;
609
602
  }
610
603
 
611
604
  function normalizeDisplay(
612
- name: ModuleName,
613
- value: unknown,
614
- defaults: readonly ModuleDisplayConfig[],
615
- palette: ColorPalette,
616
- diagnostics: ConfigDiagnostic[],
605
+ name: ModuleName,
606
+ value: unknown,
607
+ defaults: readonly ModuleDisplayConfig[],
608
+ palette: ColorPalette,
609
+ diagnostics: ConfigDiagnostic[],
617
610
  ): ModuleDisplayConfig[] {
618
- if (!Array.isArray(value)) {
619
- diagnostics.push(typeDiagnostic(`${name}.display`, "array of tables"));
620
- return defaults.map((entry) => ({ ...entry }));
621
- }
622
- const result: ModuleDisplayConfig[] = [];
623
- for (const [index, entry] of value.entries()) {
624
- const path = `${name}.display.${index}`;
625
- if (!isRecord(entry)) {
626
- diagnostics.push(typeDiagnostic(path, "table"));
627
- continue;
628
- }
629
- for (const field of Object.keys(entry)) {
630
- if (!new Set(["threshold", "style", "hidden"]).has(field)) {
631
- diagnostics.push(unknownDiagnostic(`${path}.${field}`));
632
- }
633
- }
634
- let valid = true;
635
- if (typeof entry.threshold !== "number" || !Number.isFinite(entry.threshold)) {
636
- diagnostics.push(diagnostic("warning", `${path}.threshold`, "Expected a finite number"));
637
- valid = false;
638
- }
639
- if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
640
- diagnostics.push(
641
- diagnostic("warning", `${path}.style`, "Expected a valid Starship style string"),
642
- );
643
- valid = false;
644
- }
645
- if (typeof entry.hidden !== "boolean") {
646
- diagnostics.push(typeDiagnostic(`${path}.hidden`, "boolean"));
647
- valid = false;
648
- }
649
- if (valid) {
650
- result.push({
651
- threshold: entry.threshold as number,
652
- style: entry.style as string,
653
- hidden: entry.hidden as boolean,
654
- });
655
- }
656
- }
657
- if (result.length > 0) return result;
658
- diagnostics.push(
659
- diagnostic("warning", `${name}.display`, "Expected at least one valid entry; using defaults"),
660
- );
661
- return defaults.map((entry) => ({ ...entry }));
611
+ if (!Array.isArray(value)) {
612
+ diagnostics.push(typeDiagnostic(`${name}.display`, "array of tables"));
613
+ return defaults.map((entry) => ({ ...entry }));
614
+ }
615
+ const result: ModuleDisplayConfig[] = [];
616
+ for (const [index, entry] of value.entries()) {
617
+ const path = `${name}.display.${index}`;
618
+ if (!isRecord(entry)) {
619
+ diagnostics.push(typeDiagnostic(path, "table"));
620
+ continue;
621
+ }
622
+ for (const field of Object.keys(entry)) {
623
+ if (!new Set(["threshold", "style", "hidden"]).has(field)) {
624
+ diagnostics.push(unknownDiagnostic(`${path}.${field}`));
625
+ }
626
+ }
627
+ let valid = true;
628
+ if (typeof entry.threshold !== "number" || !Number.isFinite(entry.threshold)) {
629
+ diagnostics.push(diagnostic("warning", `${path}.threshold`, "Expected a finite number"));
630
+ valid = false;
631
+ }
632
+ if (typeof entry.style !== "string" || !isValidStyle(entry.style, palette)) {
633
+ diagnostics.push(diagnostic("warning", `${path}.style`, "Expected a valid Starship style string"));
634
+ valid = false;
635
+ }
636
+ if (typeof entry.hidden !== "boolean") {
637
+ diagnostics.push(typeDiagnostic(`${path}.hidden`, "boolean"));
638
+ valid = false;
639
+ }
640
+ if (valid) {
641
+ result.push({
642
+ threshold: entry.threshold as number,
643
+ style: entry.style as string,
644
+ hidden: entry.hidden as boolean,
645
+ });
646
+ }
647
+ }
648
+ if (result.length > 0) return result;
649
+ diagnostics.push(diagnostic("warning", `${name}.display`, "Expected at least one valid entry; using defaults"));
650
+ return defaults.map((entry) => ({ ...entry }));
662
651
  }
663
652
 
664
653
  function validateLiteralStyles(
665
- ast: readonly FormatNode[],
666
- palette: ColorPalette,
667
- path: string,
668
- diagnostics: ConfigDiagnostic[],
654
+ ast: readonly FormatNode[],
655
+ palette: ColorPalette,
656
+ path: string,
657
+ diagnostics: ConfigDiagnostic[],
669
658
  ) {
670
- for (const node of ast) {
671
- if (node.type === "group" && node.style.every((part) => part.type === "text")) {
672
- const style = node.style.map((part) => (part.type === "text" ? part.value : "")).join("");
673
- if (!isValidStyle(style, palette)) {
674
- diagnostics.push(
675
- diagnostic(
676
- "warning",
677
- path,
678
- `Invalid literal style ${JSON.stringify(style)}; rendered unstyled`,
679
- ),
680
- );
681
- }
682
- }
683
- if (node.type === "group" || node.type === "conditional") {
684
- validateLiteralStyles(node.children, palette, path, diagnostics);
685
- }
686
- }
659
+ for (const node of ast) {
660
+ if (node.type === "group" && node.style.every((part) => part.type === "text")) {
661
+ const style = node.style.map((part) => (part.type === "text" ? part.value : "")).join("");
662
+ if (!isValidStyle(style, palette)) {
663
+ diagnostics.push(
664
+ diagnostic("warning", path, `Invalid literal style ${JSON.stringify(style)}; rendered unstyled`),
665
+ );
666
+ }
667
+ }
668
+ if (node.type === "group" || node.type === "conditional") {
669
+ validateLiteralStyles(node.children, palette, path, diagnostics);
670
+ }
671
+ }
687
672
  }
688
673
 
689
674
  function normalizeModuleOption(
690
- value: unknown,
691
- schema: ModuleOptionSchema,
675
+ value: unknown,
676
+ schema: ModuleOptionSchema,
692
677
  ): { ok: true; value: ModuleOptionValue } | { ok: false; message: string } {
693
- switch (schema.kind) {
694
- case "string":
695
- return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
696
- ? { ok: true, value }
697
- : { ok: false, message: "Expected a non-empty string; using the default value" };
698
- case "string-enum":
699
- return typeof value === "string" && schema.values.includes(value)
700
- ? { ok: true, value }
701
- : {
702
- ok: false,
703
- message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
704
- };
705
- case "boolean":
706
- return typeof value === "boolean"
707
- ? { ok: true, value }
708
- : { ok: false, message: "Expected boolean; using the default value" };
709
- case "integer":
710
- return typeof value === "number" &&
711
- Number.isInteger(value) &&
712
- value >= schema.minimum &&
713
- value <= schema.maximum
714
- ? { ok: true, value }
715
- : {
716
- ok: false,
717
- message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
718
- };
719
- case "string-array": {
720
- if (
721
- !Array.isArray(value) ||
722
- value.some(
723
- (item) =>
724
- typeof item !== "string" ||
725
- item.length === 0 ||
726
- (!schema.allowNegative && item.startsWith("!")),
727
- )
728
- ) {
729
- return {
730
- ok: false,
731
- message: "Expected an array of valid strings; using the default value",
732
- };
733
- }
734
- return { ok: true, value: [...value] as string[] };
735
- }
736
- case "string-map": {
737
- if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
738
- return { ok: false, message: "Expected a table of strings; using the default value" };
739
- }
740
- const result: Record<string, string> = {};
741
- for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
742
- return { ok: true, value: result };
743
- }
744
- }
678
+ switch (schema.kind) {
679
+ case "string":
680
+ return typeof value === "string" && (schema.allowEmpty !== false || value.length > 0)
681
+ ? { ok: true, value }
682
+ : { ok: false, message: "Expected a non-empty string; using the default value" };
683
+ case "string-enum":
684
+ return typeof value === "string" && schema.values.includes(value)
685
+ ? { ok: true, value }
686
+ : {
687
+ ok: false,
688
+ message: `Expected one of: ${schema.values.join(", ")}; using the default value`,
689
+ };
690
+ case "boolean":
691
+ return typeof value === "boolean"
692
+ ? { ok: true, value }
693
+ : { ok: false, message: "Expected boolean; using the default value" };
694
+ case "integer":
695
+ return typeof value === "number" && Number.isInteger(value) && value >= schema.minimum && value <= schema.maximum
696
+ ? { ok: true, value }
697
+ : {
698
+ ok: false,
699
+ message: `Expected an integer from ${schema.minimum} through ${schema.maximum}; using the default value`,
700
+ };
701
+ case "string-array": {
702
+ if (
703
+ !Array.isArray(value) ||
704
+ value.some(
705
+ (item) => typeof item !== "string" || item.length === 0 || (!schema.allowNegative && item.startsWith("!")),
706
+ )
707
+ ) {
708
+ return {
709
+ ok: false,
710
+ message: "Expected an array of valid strings; using the default value",
711
+ };
712
+ }
713
+ return { ok: true, value: [...value] as string[] };
714
+ }
715
+ case "string-map": {
716
+ if (!isRecord(value) || Object.values(value).some((item) => typeof item !== "string")) {
717
+ return { ok: false, message: "Expected a table of strings; using the default value" };
718
+ }
719
+ const result: Record<string, string> = {};
720
+ for (const [key, item] of Object.entries(value)) setOwn(result, key, item as string);
721
+ return { ok: true, value: result };
722
+ }
723
+ }
745
724
  }
746
725
 
747
726
  function cloneOptionValue(value: ModuleOptionValue): ModuleOptionValue {
748
- return typeof value === "object" ? structuredClone(value) : value;
727
+ return typeof value === "object" ? structuredClone(value) : value;
749
728
  }
750
729
 
751
730
  function setOwn<T>(record: Record<string, T>, key: string, value: T) {
752
- Object.defineProperty(record, key, {
753
- value,
754
- writable: true,
755
- enumerable: true,
756
- configurable: true,
757
- });
731
+ Object.defineProperty(record, key, {
732
+ value,
733
+ writable: true,
734
+ enumerable: true,
735
+ configurable: true,
736
+ });
758
737
  }
759
738
 
760
739
  function isRecord(value: unknown): value is Record<string, unknown> {
761
- return typeof value === "object" && value !== null && !Array.isArray(value);
740
+ return typeof value === "object" && value !== null && !Array.isArray(value);
762
741
  }
763
742
 
764
743
  function typeDiagnostic(path: string, type: string): ConfigDiagnostic {
765
- return diagnostic("warning", path, `Expected ${type}; using the default value`);
744
+ return diagnostic("warning", path, `Expected ${type}; using the default value`);
766
745
  }
767
746
 
768
747
  function unknownDiagnostic(path: string): ConfigDiagnostic {
769
- return diagnostic("warning", path, `Unknown setting ${JSON.stringify(path)} was ignored`);
748
+ return diagnostic("warning", path, `Unknown setting ${JSON.stringify(path)} was ignored`);
770
749
  }
771
750
 
772
- function diagnostic(
773
- severity: ConfigDiagnostic["severity"],
774
- path: string,
775
- message: string,
776
- ): ConfigDiagnostic {
777
- return { severity, path, message };
751
+ function diagnostic(severity: ConfigDiagnostic["severity"], path: string, message: string): ConfigDiagnostic {
752
+ return { severity, path, message };
778
753
  }
779
754
 
780
755
  function pathEntryExists(path: string): boolean {
781
- try {
782
- lstatSync(path);
783
- return true;
784
- } catch (error) {
785
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
786
- throw error;
787
- }
756
+ try {
757
+ lstatSync(path);
758
+ return true;
759
+ } catch (error) {
760
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
761
+ throw error;
762
+ }
788
763
  }
789
764
 
790
765
  function formatError(error: unknown): string {
791
- return error instanceof Error ? error.message : String(error);
766
+ return error instanceof Error ? error.message : String(error);
792
767
  }
793
768
 
794
769
  export function activePalette(config: StarshipConfig): ColorPalette {
795
- return ownPalette(config.palettes, config.palette) ?? {};
770
+ return ownPalette(config.palettes, config.palette) ?? {};
796
771
  }
797
772
 
798
773
  function ownPalette(
799
- palettes: Readonly<Record<string, Record<string, string>>>,
800
- name: string | undefined,
774
+ palettes: Readonly<Record<string, Record<string, string>>>,
775
+ name: string | undefined,
801
776
  ): Record<string, string> | undefined {
802
- return name !== undefined && Object.hasOwn(palettes, name) ? palettes[name] : undefined;
777
+ return name !== undefined && Object.hasOwn(palettes, name) ? palettes[name] : undefined;
803
778
  }