@narumitw/pi-starship 0.60.1 → 0.63.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 (115) hide show
  1. package/README.md +67 -9
  2. package/dist/chunks/chunk-63R6R5DH.ts +679 -0
  3. package/dist/chunks/chunk-63R6R5DH.ts.map +7 -0
  4. package/dist/chunks/{chunk-KZZKGGFW.ts → chunk-A65IOGL6.ts} +858 -1007
  5. package/dist/chunks/chunk-A65IOGL6.ts.map +7 -0
  6. package/dist/chunks/chunk-IYDZ3R2T.ts +69 -0
  7. package/dist/chunks/chunk-IYDZ3R2T.ts.map +7 -0
  8. package/dist/chunks/chunk-KP33I6BR.ts +579 -0
  9. package/dist/chunks/chunk-KP33I6BR.ts.map +7 -0
  10. package/dist/chunks/{chunk-PD457PX5.ts → chunk-S2KBLHE2.ts} +75 -10
  11. package/dist/chunks/chunk-S2KBLHE2.ts.map +7 -0
  12. package/dist/chunks/chunk-XQUIQO2G.ts +20 -0
  13. package/dist/chunks/chunk-XQUIQO2G.ts.map +7 -0
  14. package/dist/chunks/{chunk-ADX4CY27.ts → chunk-XTLQ4WUL.ts} +1 -1
  15. package/dist/chunks/chunk-XTLQ4WUL.ts.map +7 -0
  16. package/dist/chunks/chunk-Y24TJYG6.ts +1586 -0
  17. package/dist/chunks/chunk-Y24TJYG6.ts.map +7 -0
  18. package/dist/chunks/{cloud-EPAEV4ZB.ts → cloud-J2ZOE3HE.ts} +6 -2
  19. package/dist/chunks/cloud-J2ZOE3HE.ts.map +7 -0
  20. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts +147 -0
  21. package/dist/chunks/command-configuration-menu-YOLN2SPR.ts.map +7 -0
  22. package/dist/chunks/command-settings-chat-5AHP3JGV.ts +1124 -0
  23. package/dist/chunks/command-settings-chat-5AHP3JGV.ts.map +7 -0
  24. package/dist/chunks/commands-IOG2PL67.ts +1026 -0
  25. package/dist/chunks/commands-IOG2PL67.ts.map +7 -0
  26. package/dist/chunks/{deployment-7J54EHNR.ts → deployment-NOJ2KCLI.ts} +85 -5
  27. package/dist/chunks/deployment-NOJ2KCLI.ts.map +7 -0
  28. package/dist/chunks/{development-IWJAAAEV.ts → development-T3XXVVDP.ts} +67 -15
  29. package/dist/chunks/development-T3XXVVDP.ts.map +7 -0
  30. package/dist/chunks/directory-OX6BWJZA.ts +31 -0
  31. package/dist/chunks/directory-OX6BWJZA.ts.map +7 -0
  32. package/dist/chunks/{execution-P4WZALW2.ts → execution-R2OHIP2L.ts} +8 -4
  33. package/dist/chunks/execution-R2OHIP2L.ts.map +7 -0
  34. package/dist/chunks/jujutsu-XLDYKSX2.ts +174 -0
  35. package/dist/chunks/jujutsu-XLDYKSX2.ts.map +7 -0
  36. package/dist/chunks/languages-CBQNNYXM.ts +262 -0
  37. package/dist/chunks/languages-CBQNNYXM.ts.map +7 -0
  38. package/dist/chunks/{package-H24VJEX3.ts → package-7KVAK3TC.ts} +6 -2
  39. package/dist/chunks/package-7KVAK3TC.ts.map +7 -0
  40. package/dist/chunks/system-574MHB4R.ts +165 -0
  41. package/dist/chunks/system-574MHB4R.ts.map +7 -0
  42. package/dist/index.ts +670 -206
  43. package/dist/index.ts.map +4 -4
  44. package/package.json +5 -1
  45. package/skills/configure-pi-starship/SKILL.md +17 -1
  46. package/skills/configure-pi-starship/references/configuration.md +119 -32
  47. package/skills/configure-pi-starship/references/module-catalog.md +278 -25
  48. package/skills/configure-pi-starship/references/modules.md +213 -36
  49. package/skills/configure-pi-starship/references/runtime-and-security.md +88 -28
  50. package/src/command-commit.ts +41 -7
  51. package/src/command-configuration-menu.ts +155 -0
  52. package/src/command-configuration.ts +15 -94
  53. package/src/command-preview.ts +3 -3
  54. package/src/command-settings-chat.ts +168 -0
  55. package/src/commands.ts +76 -124
  56. package/src/config/module-options.ts +112 -0
  57. package/src/config.ts +23 -59
  58. package/src/effective-config.ts +5 -4
  59. package/src/format/bounded-regex.ts +66 -0
  60. package/src/format/version.ts +24 -0
  61. package/src/modules/catalog.ts +10 -0
  62. package/src/modules/cloud.ts +1 -0
  63. package/src/modules/deployment.ts +8 -0
  64. package/src/modules/development.ts +20 -2
  65. package/src/modules/directory.ts +171 -51
  66. package/src/modules/execution.ts +2 -0
  67. package/src/modules/git/branch.ts +19 -4
  68. package/src/modules/git/commit.ts +9 -2
  69. package/src/modules/git/metrics.ts +9 -4
  70. package/src/modules/git/runtime.ts +122 -33
  71. package/src/modules/git/state.ts +23 -2
  72. package/src/modules/git/status-templates.ts +58 -0
  73. package/src/modules/git/status.ts +96 -30
  74. package/src/modules/jujutsu.ts +225 -0
  75. package/src/modules/languages.ts +26 -2
  76. package/src/modules/package.ts +1 -0
  77. package/src/modules/render.ts +42 -16
  78. package/src/modules/system.ts +54 -0
  79. package/src/modules/time-format.ts +188 -0
  80. package/src/modules/time.ts +11 -5
  81. package/src/modules/types.ts +42 -4
  82. package/src/pi-starship.ts +198 -88
  83. package/src/profile-store.ts +5 -0
  84. package/src/runtime/cloud.ts +3 -0
  85. package/src/runtime/command.ts +1 -1
  86. package/src/runtime/deployment.ts +120 -4
  87. package/src/runtime/development.ts +86 -13
  88. package/src/runtime/directory.ts +33 -0
  89. package/src/runtime/execution.ts +12 -2
  90. package/src/runtime/helpers.ts +57 -8
  91. package/src/runtime/jujutsu.ts +225 -0
  92. package/src/runtime/languages.ts +106 -19
  93. package/src/runtime/package.ts +3 -0
  94. package/src/runtime/system.ts +202 -0
  95. package/src/runtime/types.ts +3 -0
  96. package/src/runtime/version-requirements.ts +30 -0
  97. package/src/runtime/workspace.ts +12 -1
  98. package/src/settings-agent.ts +80 -0
  99. package/src/settings-chat-transcript.ts +192 -0
  100. package/src/settings-chat-ui.ts +526 -0
  101. package/src/settings-draft.ts +260 -0
  102. package/src/settings-snapshots.ts +41 -0
  103. package/dist/chunks/chunk-ADX4CY27.ts.map +0 -7
  104. package/dist/chunks/chunk-KZZKGGFW.ts.map +0 -7
  105. package/dist/chunks/chunk-PD457PX5.ts.map +0 -7
  106. package/dist/chunks/cloud-EPAEV4ZB.ts.map +0 -7
  107. package/dist/chunks/commands-C2VJ6ZBN.ts +0 -3374
  108. package/dist/chunks/commands-C2VJ6ZBN.ts.map +0 -7
  109. package/dist/chunks/deployment-7J54EHNR.ts.map +0 -7
  110. package/dist/chunks/development-IWJAAAEV.ts.map +0 -7
  111. package/dist/chunks/execution-P4WZALW2.ts.map +0 -7
  112. package/dist/chunks/languages-JO6R2PHL.ts +0 -168
  113. package/dist/chunks/languages-JO6R2PHL.ts.map +0 -7
  114. package/dist/chunks/package-H24VJEX3.ts.map +0 -7
  115. package/src/command-inspector.ts +0 -41
@@ -0,0 +1,225 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import type { FormatValue } from "../format/formatter.js";
3
+ import { type LayoutChunk, parseStyle } from "../format/style.js";
4
+ import { renderStatusTemplate } from "./git/status-templates.js";
5
+ import { truncateLeadingGraphemes } from "./truncation.js";
6
+ import { defineModule, type ModuleValueContext } from "./types.js";
7
+ import { workspaceModuleValues } from "./workspace-helpers.js";
8
+
9
+ export const jjBookmarkModule = defineModule({
10
+ name: "jj_bookmark",
11
+ variables: ["symbol", "bookmark", "remote", "diverged", "overflow_count"],
12
+ defaults: {
13
+ format: "on [$symbol$bookmark(@$remote)$diverged( \\(+$overflow_count others\\))]($style) ",
14
+ symbol: " ",
15
+ style: "bold purple",
16
+ disabled: true,
17
+ },
18
+ options: {
19
+ truncation_length: { kind: "integer", default: 65_535, minimum: 0, maximum: 65_535 },
20
+ truncation_symbol: { kind: "string", default: "…", allowEmpty: true },
21
+ diverged_symbol: { kind: "string", default: "*", allowEmpty: true },
22
+ ignore_names: { kind: "string-array", default: [] },
23
+ ignore_remotes: { kind: "string-array", default: [] },
24
+ },
25
+ values(context) {
26
+ const values = workspaceModuleValues("jj_bookmark", context);
27
+ if (!values?.bookmarks) return undefined;
28
+ let raw: unknown;
29
+ try {
30
+ raw = JSON.parse(values.bookmarks);
31
+ } catch {
32
+ return undefined;
33
+ }
34
+ if (!Array.isArray(raw)) return undefined;
35
+ const parsed = raw.map(parseBookmark);
36
+ if (parsed.some((bookmark) => bookmark === undefined)) return undefined;
37
+ const ignoredNames = stringList(context, "ignore_names");
38
+ const ignoredRemotes = stringList(context, "ignore_remotes");
39
+ const bookmarks = parsed
40
+ .filter((bookmark): bookmark is NonNullable<typeof bookmark> => bookmark !== undefined)
41
+ .filter(
42
+ ({ name, remote }) =>
43
+ !ignoredNames.includes(name) && (remote === undefined || !ignoredRemotes.includes(remote)),
44
+ );
45
+ const bookmark = bookmarks[0];
46
+ if (!bookmark) return undefined;
47
+ const length = integerOption(context, "truncation_length", 65_535);
48
+ const symbol = stringOption(context, "truncation_symbol", "…");
49
+ const truncate = (value: string) => truncateLeadingGraphemes(value, length, symbol);
50
+ return {
51
+ bookmark: truncate(bookmark.name),
52
+ remote: bookmark.remote === undefined ? "" : truncate(bookmark.remote),
53
+ diverged: bookmark.diverged ? stringOption(context, "diverged_symbol", "*") : "",
54
+ overflow_count: bookmarks.length > 1 ? String(bookmarks.length - 1) : "",
55
+ };
56
+ },
57
+ });
58
+
59
+ export const jjChangeModule = defineModule({
60
+ name: "jj_change",
61
+ variables: ["change", "commit", "change_prefix", "change_suffix", "change_offset", "commit_prefix", "commit_suffix"],
62
+ defaults: { format: "$change ", symbol: "", style: "none", disabled: true },
63
+ styleDefaults: { prefix_style: "green bold", suffix_style: "dimmed", change_offset_style: "bold" },
64
+ styleVariables: ["prefix_style", "suffix_style", "change_offset_style"],
65
+ resolveStyleVariables: ({ styles }) => styles,
66
+ options: {
67
+ change_hash_length: { kind: "integer", default: 7, minimum: 0, maximum: 255 },
68
+ commit_hash_length: { kind: "integer", default: 7, minimum: 0, maximum: 255 },
69
+ },
70
+ values(context) {
71
+ const values = workspaceModuleValues("jj_change", context);
72
+ if (!values) return undefined;
73
+ const change = idParts(
74
+ values.change_id ?? "",
75
+ Number(values.change_prefix_len),
76
+ integerOption(context, "change_hash_length", 7),
77
+ );
78
+ const commit = idParts(
79
+ values.commit_id ?? "",
80
+ Number(values.commit_prefix_len),
81
+ integerOption(context, "commit_hash_length", 7),
82
+ );
83
+ const styled = (text: string, role: string): LayoutChunk => ({
84
+ text,
85
+ style: parseStyle(context.styles?.[role] ?? "", context.palette),
86
+ });
87
+ const changeChunks = [styled(change.prefix, "prefix_style"), styled(change.suffix, "suffix_style")];
88
+ if (values.change_offset !== undefined)
89
+ changeChunks.push(styled(`/${values.change_offset}`, "change_offset_style"));
90
+ return {
91
+ change: changeChunks,
92
+ commit: [styled(commit.prefix, "prefix_style"), styled(commit.suffix, "suffix_style")],
93
+ change_prefix: change.prefix,
94
+ change_suffix: change.suffix,
95
+ change_offset: values.change_offset ?? "",
96
+ commit_prefix: commit.prefix,
97
+ commit_suffix: commit.suffix,
98
+ };
99
+ },
100
+ });
101
+
102
+ export const jjMetricsModule = defineModule({
103
+ name: "jj_metrics",
104
+ variables: ["added", "deleted"],
105
+ defaults: {
106
+ format: "([+$added]($added_style) )([-$deleted]($deleted_style) )",
107
+ symbol: "",
108
+ style: "none",
109
+ disabled: true,
110
+ },
111
+ styleDefaults: { added_style: "bold green", deleted_style: "bold red" },
112
+ styleVariables: ["added_style", "deleted_style"],
113
+ resolveStyleVariables: ({ styles }) => styles,
114
+ options: { only_nonzero_diffs: { kind: "boolean", default: true } },
115
+ values(context) {
116
+ const values = workspaceModuleValues("jj_metrics", context);
117
+ if (!values) return undefined;
118
+ if (context.options.only_nonzero_diffs === false) return values;
119
+ return { added: values.added === "0" ? "" : values.added, deleted: values.deleted === "0" ? "" : values.deleted };
120
+ },
121
+ });
122
+
123
+ const statusTemplates = {
124
+ conflicted: "!",
125
+ description_empty: "◌",
126
+ description_present: "",
127
+ hidden: "",
128
+ immutable: "◆",
129
+ added: "+",
130
+ copied: "=",
131
+ deleted: "✘",
132
+ modified: "~",
133
+ renamed: "»",
134
+ } as const;
135
+
136
+ export const jjStatusModule = defineModule({
137
+ name: "jj_status",
138
+ variables: [
139
+ "all",
140
+ "conflicted",
141
+ "description",
142
+ "hidden",
143
+ "immutable",
144
+ "added",
145
+ "copied",
146
+ "deleted",
147
+ "modified",
148
+ "renamed",
149
+ ],
150
+ defaults: { format: "([\\[$all\\]]($style) )", symbol: "", style: "bold red", disabled: true },
151
+ options: Object.fromEntries(
152
+ Object.entries(statusTemplates).map(([key, value]) => [
153
+ key,
154
+ {
155
+ kind: "string" as const,
156
+ default: value,
157
+ allowEmpty: true,
158
+ templateVariables: ["added", "copied", "deleted", "modified", "renamed"].includes(key) ? ["count"] : [],
159
+ },
160
+ ]),
161
+ ),
162
+ values(context) {
163
+ const snapshot = workspaceModuleValues("jj_status", context);
164
+ if (!snapshot) return undefined;
165
+ const values: Record<string, FormatValue> = {};
166
+ const symbol = (name: keyof typeof statusTemplates, active = true, count?: string) =>
167
+ active ? statusValue(stringOption(context, name, statusTemplates[name]), count, context) : [];
168
+ values.conflicted = symbol("conflicted", snapshot.conflicted === "true");
169
+ values.description = symbol(snapshot.has_description === "true" ? "description_present" : "description_empty");
170
+ values.hidden = symbol("hidden", snapshot.hidden === "true");
171
+ values.immutable = symbol("immutable", snapshot.immutable === "true");
172
+ for (const name of ["added", "copied", "deleted", "modified", "renamed"] as const) {
173
+ values[name] = symbol(name, Number(snapshot[name]) > 0, snapshot[name]);
174
+ }
175
+ values.all = Object.values(values).flatMap((value) => (Array.isArray(value) ? value : []));
176
+ return values;
177
+ },
178
+ });
179
+
180
+ export const jujutsuModules = [jjBookmarkModule, jjChangeModule, jjMetricsModule, jjStatusModule] as const;
181
+
182
+ function parseBookmark(raw: unknown): { name: string; remote?: string; diverged: boolean } | undefined {
183
+ if (
184
+ !raw ||
185
+ typeof raw !== "object" ||
186
+ !("name" in raw) ||
187
+ !("remote" in raw) ||
188
+ !("diverged" in raw) ||
189
+ typeof raw.name !== "string" ||
190
+ typeof raw.remote !== "string" ||
191
+ typeof raw.diverged !== "boolean"
192
+ )
193
+ return undefined;
194
+ // Transport raw fields, not JJ revset display labels: @, quotes and trailing *
195
+ // can be literal name characters. Sanitize before filtering and truncation.
196
+ const remote = sanitizeTerminalText(raw.remote);
197
+ return { name: sanitizeTerminalText(raw.name), remote: remote || undefined, diverged: raw.diverged };
198
+ }
199
+
200
+ function idParts(id: string, prefixLength: number, hashLength: number) {
201
+ const text = sanitizeTerminalText(id);
202
+ const start = Math.min(text.length, Number.isFinite(prefixLength) ? Math.max(0, prefixLength) : 0);
203
+ return { prefix: text.slice(0, start), suffix: text.slice(start, Math.max(start, hashLength)) };
204
+ }
205
+
206
+ function stringOption(context: ModuleValueContext, key: string, fallback: string): string {
207
+ const value = context.options[key];
208
+ return typeof value === "string" ? sanitizeTerminalText(value) : fallback;
209
+ }
210
+
211
+ function integerOption(context: ModuleValueContext, key: string, fallback: number): number {
212
+ const value = context.options[key];
213
+ return typeof value === "number" && Number.isInteger(value) && value >= 0 ? value : fallback;
214
+ }
215
+
216
+ function stringList(context: ModuleValueContext, key: string): readonly string[] {
217
+ const value = context.options[key];
218
+ return Array.isArray(value)
219
+ ? value.filter((item): item is string => typeof item === "string").map(sanitizeTerminalText)
220
+ : [];
221
+ }
222
+
223
+ function statusValue(template: string, count: string | undefined, context: ModuleValueContext): readonly LayoutChunk[] {
224
+ return renderStatusTemplate(template, count === undefined ? {} : { count }, context.palette);
225
+ }
@@ -1,4 +1,4 @@
1
- import { defineModule, type ModuleDefinition } from "./types.js";
1
+ import { defineModule, type ModuleDefinition, type ModuleOptionSchema, type ModuleStyleContext } from "./types.js";
2
2
  import { workspaceModuleValues } from "./workspace-helpers.js";
3
3
 
4
4
  const detectionOptions = {
@@ -14,6 +14,8 @@ function languageModule<const Name extends string>(definition: {
14
14
  format: string;
15
15
  symbol: string;
16
16
  style: string;
17
+ options?: Readonly<Record<string, ModuleOptionSchema>>;
18
+ requirementStyle?: boolean;
17
19
  }): ModuleDefinition<Name> {
18
20
  return defineModule({
19
21
  name: definition.name,
@@ -24,7 +26,20 @@ function languageModule<const Name extends string>(definition: {
24
26
  style: definition.style,
25
27
  disabled: false,
26
28
  },
27
- options: detectionOptions,
29
+ ...(definition.requirementStyle
30
+ ? {
31
+ // Opt in to requirement styling without changing existing output or symbol-only work.
32
+ styleDefaults: { not_capable_style: "none" },
33
+ fallbackStyle: true,
34
+ resolveStyleVariables: ({ runtime, style, styles }: ModuleStyleContext) => ({
35
+ style:
36
+ runtime.workspace?.styleSelectors?.[definition.name] === "not_capable"
37
+ ? (styles.not_capable_style ?? style)
38
+ : style,
39
+ }),
40
+ }
41
+ : {}),
42
+ options: { ...detectionOptions, ...definition.options },
28
43
  values: (context) => workspaceModuleValues(definition.name, context),
29
44
  });
30
45
  }
@@ -35,6 +50,7 @@ export const nodejsModule = languageModule({
35
50
  format: "via [$symbol($version )]($style)",
36
51
  symbol: " ",
37
52
  style: "bold green",
53
+ requirementStyle: true,
38
54
  });
39
55
 
40
56
  export const pythonModule = languageModule({
@@ -43,6 +59,13 @@ export const pythonModule = languageModule({
43
59
  format: "via [$symbol$pyenv_prefix($version )(\\($virtualenv\\) )]($style)",
44
60
  symbol: " ",
45
61
  style: "yellow bold",
62
+ options: {
63
+ pyenv_version_name: { kind: "boolean", default: false },
64
+ pyenv_prefix: { kind: "string", default: "pyenv " },
65
+ python_binary: { kind: "command-alternatives", default: [] },
66
+ detect_env_vars: { kind: "string-array", default: [], allowNegative: true },
67
+ generic_venv_names: { kind: "string-array", default: [] },
68
+ },
46
69
  });
47
70
 
48
71
  export const rustModule = languageModule({
@@ -59,6 +82,7 @@ export const golangModule = languageModule({
59
82
  format: "via [$symbol($version )]($style)",
60
83
  symbol: " ",
61
84
  style: "bold cyan",
85
+ requirementStyle: true,
62
86
  });
63
87
 
64
88
  export const bunModule = languageModule({
@@ -12,6 +12,7 @@ export const packageModule = defineModule({
12
12
  },
13
13
  options: {
14
14
  version_format: { kind: "string", default: "v$raw" },
15
+ display_private: { kind: "boolean", default: true },
15
16
  },
16
17
  values: (context) => workspaceModuleValues("package", context),
17
18
  });
@@ -1,7 +1,7 @@
1
1
  import { visibleWidth } from "@earendil-works/pi-tui";
2
2
  import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
3
3
  import { activePalette, type ModuleConfig, type StarshipConfig } from "../config.js";
4
- import { type FormatValue, formatVariables, renderFormat } from "../format/formatter.js";
4
+ import { type FormatValue, formatVariables, parseFormat, renderFormat } from "../format/formatter.js";
5
5
  import {
6
6
  type ColorPalette,
7
7
  isFillChunk,
@@ -12,8 +12,15 @@ import {
12
12
  import { sanitizeFormatText } from "../format/terminal-safety.js";
13
13
  import type { ThemeColors } from "../format/theme-colors.js";
14
14
  import { MODULE_DEFINITIONS, MODULE_NAMES, type ModuleName } from "./catalog.js";
15
+ import { directoryAlternateFormat } from "./directory.js";
15
16
  import { resolveStyleRule } from "./style-rules.js";
16
- import type { ModuleStyleContext, ModuleValueContext, RenderedStatusline, StarshipRuntimeSnapshot } from "./types.js";
17
+ import type {
18
+ ModuleOptionValue,
19
+ ModuleStyleContext,
20
+ ModuleValueContext,
21
+ RenderedStatusline,
22
+ StarshipRuntimeSnapshot,
23
+ } from "./types.js";
17
24
 
18
25
  export function renderStatusline(
19
26
  config: StarshipConfig,
@@ -32,13 +39,15 @@ export function renderStatusline(
32
39
  for (const definition of MODULE_DEFINITIONS) {
33
40
  const name = definition.name;
34
41
  const module = config.modules[name];
35
- const values = definition.values(valueContext(config, name, runtime, palette));
42
+ const context = valueContext(config, name, runtime, palette);
43
+ const values = definition.values(context);
36
44
  if (!values) continue;
37
45
  const styleContext: ModuleStyleContext = {
38
46
  runtime,
39
47
  style: module.style,
40
48
  styles: module.styles,
41
49
  display: module.display,
50
+ options: context.options,
42
51
  };
43
52
  const baseStyleVariables = definition.resolveStyleVariables
44
53
  ? definition.resolveStyleVariables(styleContext)
@@ -50,10 +59,16 @@ export function renderStatusline(
50
59
  const styleVariables = ruleStyle === undefined ? baseStyleVariables : { ...baseStyleVariables, style: ruleStyle };
51
60
  const contentValues: Record<string, FormatValue> = Object.fromEntries(
52
61
  definition.variables.flatMap((variable) =>
53
- variable !== "symbol" && Object.hasOwn(values, variable) ? [[variable, values[variable]]] : [],
62
+ Object.hasOwn(values, variable) ? [[variable, values[variable]]] : [],
54
63
  ),
55
64
  );
56
- const rendered = renderModule(module, contentValues, styleVariables, palette);
65
+ const alternate = definition.resolveFormat?.(context, values);
66
+ const rendered = renderModule(
67
+ alternate === undefined ? module : { ...module, formatAst: parseFormat(alternate) },
68
+ contentValues,
69
+ styleVariables,
70
+ palette,
71
+ );
57
72
  modules[name] = rendered;
58
73
  layoutModules[name] =
59
74
  definition.layout === "fill" && !module.disabled ? [{ type: "fill", pattern: rendered }] : rendered;
@@ -84,17 +99,10 @@ function valueContext(
84
99
  runtime: runtimeForDisplay(name, runtime),
85
100
  palette,
86
101
  symbol: sanitizeFormatText(config.modules[name].symbol),
102
+ styles: config.modules[name].styles,
103
+ requestedVariables: formatVariables(config.modules[name].formatAst),
87
104
  options: Object.fromEntries(
88
- Object.entries(config.modules[name].options).map(([key, value]) => [
89
- key,
90
- typeof value === "string"
91
- ? sanitizeTerminalText(value)
92
- : Array.isArray(value)
93
- ? value.map(sanitizeTerminalText)
94
- : value && typeof value === "object"
95
- ? sanitizeFields(value)
96
- : value,
97
- ]),
105
+ Object.entries(config.modules[name].options).map(([key, value]) => [key, sanitizeOption(value)]),
98
106
  ),
99
107
  extensionStatus: {
100
108
  ...config.extensionStatus,
@@ -106,6 +114,17 @@ function valueContext(
106
114
  };
107
115
  }
108
116
 
117
+ function sanitizeOption(value: ModuleOptionValue): ModuleOptionValue {
118
+ if (typeof value === "string") return sanitizeTerminalText(value);
119
+ if (Array.isArray(value)) return value.map((item) => sanitizeOption(item as ModuleOptionValue)) as ModuleOptionValue;
120
+ if (value && typeof value === "object") {
121
+ return Object.fromEntries(
122
+ Object.entries(value).map(([key, item]) => [key, sanitizeOption(item)]),
123
+ ) as ModuleOptionValue;
124
+ }
125
+ return value;
126
+ }
127
+
109
128
  // Shallow presentation copies retain keys used for aliases and status policies.
110
129
  function sanitizeFields<T extends object>(value: T): T {
111
130
  return Object.fromEntries(
@@ -176,7 +195,14 @@ export function reachableModuleRequirements(config: StarshipConfig): ReadonlyMap
176
195
  for (const definition of MODULE_DEFINITIONS) {
177
196
  if (config.modules[definition.name].disabled) continue;
178
197
  if (!includeAll && !rootVariables.has(definition.name)) continue;
179
- requirements.set(definition.name, formatVariables(config.modules[definition.name].formatAst));
198
+ const variables = formatVariables(config.modules[definition.name].formatAst);
199
+ if (definition.name === "directory") {
200
+ const alternate = directoryAlternateFormat(config.modules.directory.options, config.modules.directory.styles);
201
+ if (alternate) {
202
+ for (const variable of formatVariables(parseFormat(alternate))) variables.add(variable);
203
+ }
204
+ }
205
+ requirements.set(definition.name, variables);
180
206
  }
181
207
  return requirements;
182
208
  }
@@ -0,0 +1,54 @@
1
+ import { sanitizeTerminalText } from "@narumitw/pi-tui-kit/terminal-text";
2
+ import { defineModule } from "./types.js";
3
+ import { workspaceModuleValues } from "./workspace-helpers.js";
4
+
5
+ export const memoryUsageModule = defineModule({
6
+ name: "memory_usage",
7
+ variables: ["symbol", "ram", "ram_pct", "swap", "swap_pct"],
8
+ defaults: {
9
+ format: "via $symbol[$ram( | $swap)]($style) ",
10
+ symbol: "🐏 ",
11
+ style: "white bold dimmed",
12
+ disabled: true,
13
+ },
14
+ options: { threshold: { kind: "number", default: 75, minimum: -100, maximum: 10_000 } },
15
+ values: (context) => workspaceModuleValues("memory_usage", context),
16
+ });
17
+
18
+ export const batteryModule = defineModule({
19
+ name: "battery",
20
+ variables: ["symbol", "percentage"],
21
+ defaults: { format: "[$symbol$percentage]($style) ", symbol: "", style: "none", disabled: true },
22
+ displayDefaults: [{ threshold: 10, style: "red bold", hidden: false }],
23
+ styleVariables: ["style"],
24
+ resolveStyleVariables: ({ runtime, display }) => {
25
+ const raw = runtime.workspace?.modules.battery?.percentage_raw;
26
+ if (raw === undefined) return undefined;
27
+ const percentage = Number(raw);
28
+ if (!Number.isFinite(percentage)) return undefined;
29
+ // Battery thresholds are upper bounds, unlike context-usage display rules.
30
+ const selected = display.reduce<(typeof display)[number] | undefined>(
31
+ (best, rule) =>
32
+ percentage <= rule.threshold && (best === undefined || rule.threshold < best.threshold) ? rule : best,
33
+ undefined,
34
+ );
35
+ return selected && !selected.hidden ? { style: selected.style } : undefined;
36
+ },
37
+ options: {
38
+ full_symbol: { kind: "string", default: "󰁹 ", allowEmpty: true },
39
+ charging_symbol: { kind: "string", default: "󰂄 ", allowEmpty: true },
40
+ discharging_symbol: { kind: "string", default: "󰂃 ", allowEmpty: true },
41
+ unknown_symbol: { kind: "string", default: "󰂑 ", allowEmpty: true },
42
+ empty_symbol: { kind: "string", default: "󰂎 ", allowEmpty: true },
43
+ },
44
+ values(context) {
45
+ const values = workspaceModuleValues("battery", context);
46
+ if (!values) return undefined;
47
+ const state = values.state;
48
+ const key = `${state === "full" || state === "charging" || state === "discharging" || state === "empty" ? state : "unknown"}_symbol`;
49
+ const symbol = context.options[key];
50
+ return { percentage: values.percentage, symbol: typeof symbol === "string" ? sanitizeTerminalText(symbol) : "" };
51
+ },
52
+ });
53
+
54
+ export const systemModules = [memoryUsageModule, batteryModule] as const;
@@ -0,0 +1,188 @@
1
+ const MAX_TIME_FORMAT_LENGTH = 256;
2
+ const MAX_TIME_ZONE_LENGTH = 128;
3
+ const MAX_TIME_RANGE_LENGTH = 64;
4
+ const FORMAT_TOKEN = /%%|%:z|%[HIMSpPRTrYmdFz]/gu;
5
+
6
+ interface ClockParts {
7
+ year: number;
8
+ month: number;
9
+ day: number;
10
+ hour: number;
11
+ minute: number;
12
+ second: number;
13
+ offsetSeconds: number;
14
+ }
15
+
16
+ interface TimeOptions {
17
+ use_12hr?: unknown;
18
+ time_format?: unknown;
19
+ utc_time_offset?: unknown;
20
+ time_range?: unknown;
21
+ }
22
+
23
+ // Only the latest configured zone is retained. The default local clock does not
24
+ // construct an Intl formatter, and no timer or filesystem operation is used here.
25
+ let cachedZone: { name: string; formatter: Intl.DateTimeFormat } | undefined;
26
+
27
+ /**
28
+ * Supported strftime tokens: %% %H %I %M %S %p %P %R %T %r %Y %m %d %F %z %:z.
29
+ * Other directives, flags, and formats over 256 characters fall back to the
30
+ * minutes-only Pi default. An empty format selects that default as well.
31
+ */
32
+ export function formatClockTime(now: Date, options: TimeOptions): string | undefined {
33
+ if (!Number.isFinite(now.getTime())) return undefined;
34
+ // Starship gates visibility against local wall time, not the output zone.
35
+ if (!isInsideTimeRange(now, options.time_range)) return undefined;
36
+ const fallback = options.use_12hr === true ? "%I:%M %p" : "%H:%M";
37
+ const format = validTimeFormat(options.time_format) ? options.time_format : fallback;
38
+ const parts = clockParts(now, options.utc_time_offset);
39
+ const hour12 = parts.hour % 12 || 12;
40
+ const period = parts.hour < 12 ? "AM" : "PM";
41
+ const hours = pad(parts.hour);
42
+ const minutes = pad(parts.minute);
43
+ const seconds = pad(parts.second);
44
+ const date = `${parts.year.toString().padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)}`;
45
+ const tokens: Readonly<Record<string, string>> = {
46
+ "%%": "%",
47
+ "%H": hours,
48
+ "%I": pad(hour12),
49
+ "%M": minutes,
50
+ "%S": seconds,
51
+ "%p": period,
52
+ "%P": period.toLowerCase(),
53
+ "%R": `${hours}:${minutes}`,
54
+ "%T": `${hours}:${minutes}:${seconds}`,
55
+ // Jiff's %r uses an unpadded 12-hour value.
56
+ "%r": `${hour12}:${minutes}:${seconds} ${period}`,
57
+ "%Y": parts.year.toString().padStart(4, "0"),
58
+ "%m": pad(parts.month),
59
+ "%d": pad(parts.day),
60
+ "%F": date,
61
+ "%z": offsetText(parts.offsetSeconds, ""),
62
+ "%:z": offsetText(parts.offsetSeconds, ":"),
63
+ };
64
+ return format.replace(FORMAT_TOKEN, (token) => tokens[token] ?? token);
65
+ }
66
+
67
+ export function validTimeFormat(format: unknown): format is string {
68
+ return (
69
+ typeof format === "string" &&
70
+ format.length > 0 &&
71
+ format.length <= MAX_TIME_FORMAT_LENGTH &&
72
+ !format.replace(FORMAT_TOKEN, "").includes("%")
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Range endpoints use HH:MM, HH:MM:SS, or HH:MM:SS.sss (1–3 fractional
78
+ * digits). Each endpoint is optional. Invalid endpoints are ignored separately;
79
+ * a missing or repeated hyphen disables the gate. Endpoints are exclusive,
80
+ * including equal endpoints, which exclude only that exact local wall time.
81
+ * Inputs over 64 characters disable the gate.
82
+ */
83
+ export function isInsideTimeRange(now: Date, range: unknown): boolean {
84
+ if (typeof range !== "string" || range.length > MAX_TIME_RANGE_LENGTH) return true;
85
+ const endpoints = range.split("-");
86
+ if (endpoints.length !== 2) return true;
87
+ const start = parseRangeEndpoint(endpoints[0] ?? "");
88
+ const end = parseRangeEndpoint(endpoints[1] ?? "");
89
+ const current = ((now.getHours() * 60 + now.getMinutes()) * 60 + now.getSeconds()) * 1_000 + now.getMilliseconds();
90
+ if (start === undefined && end === undefined) return true;
91
+ if (start === undefined) return current < (end as number);
92
+ if (end === undefined) return current > start;
93
+ return start < end ? current > start && current < end : current > start || current < end;
94
+ }
95
+
96
+ function parseRangeEndpoint(value: string): number | undefined {
97
+ const match = /^(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,3}))?)?$/u.exec(value);
98
+ if (!match) return undefined;
99
+ const hour = Number(match[1]);
100
+ const minute = Number(match[2]);
101
+ const second = Number(match[3] ?? 0);
102
+ if (hour > 23 || minute > 59 || second > 59) return undefined;
103
+ return ((hour * 60 + minute) * 60 + second) * 1_000 + Number((match[4] ?? "").padEnd(3, "0"));
104
+ }
105
+
106
+ // Zones are local, UTC, or an Intl-supported Area/Zone identifier. Numeric
107
+ // offsets allow an optional sign, 1–2 integer digits, and an optional 1–6 digit
108
+ // fraction, strictly between -24 and 24, truncated to seconds. Inputs over 128 characters
109
+ // and all other syntax fall back to local time.
110
+ function clockParts(now: Date, zone: unknown): ClockParts {
111
+ if (typeof zone !== "string" || zone === "local" || zone.length > MAX_TIME_ZONE_LENGTH) return localParts(now);
112
+ if (/^[+-]?\d{1,2}(?:\.\d{1,6})?$/u.test(zone)) {
113
+ const hours = Number(zone);
114
+ if (hours > -24 && hours < 24) {
115
+ const offsetSeconds = Math.trunc(hours * 3_600);
116
+ const shifted = new Date(now.getTime() + offsetSeconds * 1_000);
117
+ return {
118
+ year: shifted.getUTCFullYear(),
119
+ month: shifted.getUTCMonth() + 1,
120
+ day: shifted.getUTCDate(),
121
+ hour: shifted.getUTCHours(),
122
+ minute: shifted.getUTCMinutes(),
123
+ second: shifted.getUTCSeconds(),
124
+ offsetSeconds,
125
+ };
126
+ }
127
+ return localParts(now);
128
+ }
129
+ if (!/^(?:UTC|[A-Za-z_]+(?:\/[A-Za-z0-9_+.-]+)+)$/u.test(zone)) return localParts(now);
130
+ try {
131
+ if (cachedZone?.name !== zone) {
132
+ cachedZone = {
133
+ name: zone,
134
+ formatter: new Intl.DateTimeFormat("en-US", {
135
+ timeZone: zone,
136
+ calendar: "iso8601",
137
+ numberingSystem: "latn",
138
+ year: "numeric",
139
+ month: "2-digit",
140
+ day: "2-digit",
141
+ hour: "2-digit",
142
+ minute: "2-digit",
143
+ second: "2-digit",
144
+ hourCycle: "h23",
145
+ }),
146
+ };
147
+ }
148
+ const values = Object.fromEntries(cachedZone.formatter.formatToParts(now).map(({ type, value }) => [type, value]));
149
+ const parts = {
150
+ year: Number(values.year),
151
+ month: Number(values.month),
152
+ day: Number(values.day),
153
+ hour: Number(values.hour),
154
+ minute: Number(values.minute),
155
+ second: Number(values.second),
156
+ };
157
+ const wallTime = new Date(0);
158
+ wallTime.setUTCFullYear(parts.year, parts.month - 1, parts.day);
159
+ wallTime.setUTCHours(parts.hour, parts.minute, parts.second, 0);
160
+ return {
161
+ ...parts,
162
+ offsetSeconds: (wallTime.getTime() - Math.floor(now.getTime() / 1_000) * 1_000) / 1_000,
163
+ };
164
+ } catch {
165
+ return localParts(now);
166
+ }
167
+ }
168
+
169
+ function localParts(now: Date): ClockParts {
170
+ return {
171
+ year: now.getFullYear(),
172
+ month: now.getMonth() + 1,
173
+ day: now.getDate(),
174
+ hour: now.getHours(),
175
+ minute: now.getMinutes(),
176
+ second: now.getSeconds(),
177
+ offsetSeconds: -now.getTimezoneOffset() * 60,
178
+ };
179
+ }
180
+
181
+ function pad(value: number): string {
182
+ return value.toString().padStart(2, "0");
183
+ }
184
+
185
+ function offsetText(seconds: number, separator: string): string {
186
+ const absolute = Math.abs(seconds);
187
+ return `${seconds < 0 ? "-" : "+"}${pad(Math.floor(absolute / 3_600))}${separator}${pad(Math.floor((absolute % 3_600) / 60))}`;
188
+ }
@@ -1,3 +1,4 @@
1
+ import { formatClockTime } from "./time-format.js";
1
2
  import { defineModule } from "./types.js";
2
3
 
3
4
  export const timeModule = defineModule({
@@ -9,9 +10,14 @@ export const timeModule = defineModule({
9
10
  style: "bold yellow",
10
11
  disabled: false,
11
12
  },
12
- values: ({ runtime }) => ({ time: formatTime(runtime.now) }),
13
+ options: {
14
+ use_12hr: { kind: "boolean", default: false },
15
+ time_format: { kind: "string", default: "", allowEmpty: true },
16
+ utc_time_offset: { kind: "string", default: "local" },
17
+ time_range: { kind: "string", default: "-", allowEmpty: true },
18
+ },
19
+ values: ({ runtime, options }) => {
20
+ const time = formatClockTime(runtime.now, options);
21
+ return time === undefined ? undefined : { time };
22
+ },
13
23
  });
14
-
15
- function formatTime(now: Date): string {
16
- return `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}`;
17
- }