@narumitw/pi-starship 0.49.3 → 0.49.4

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 (84) hide show
  1. package/README.md +2 -4
  2. package/package.json +4 -8
  3. package/src/command-contract.ts +13 -0
  4. package/src/command-inspector.ts +198 -0
  5. package/src/command-preview.ts +206 -0
  6. package/src/commands.ts +575 -0
  7. package/src/config.ts +794 -0
  8. package/src/format/formatter.ts +275 -0
  9. package/src/format/style.ts +278 -0
  10. package/src/index.ts +1 -1
  11. package/src/modules/activity.ts +38 -0
  12. package/src/modules/brand.ts +13 -0
  13. package/src/modules/cache.ts +23 -0
  14. package/src/modules/catalog.ts +124 -0
  15. package/src/modules/cloud.ts +74 -0
  16. package/src/modules/context.ts +33 -0
  17. package/src/modules/cost.ts +31 -0
  18. package/src/modules/deployment.ts +61 -0
  19. package/src/modules/development.ts +112 -0
  20. package/src/modules/directory.ts +151 -0
  21. package/src/modules/display.ts +14 -0
  22. package/src/modules/execution.ts +84 -0
  23. package/src/modules/extension-status.ts +93 -0
  24. package/src/modules/fill.ts +14 -0
  25. package/src/modules/git/branch.ts +31 -0
  26. package/src/modules/git/commit.ts +29 -0
  27. package/src/modules/git/metrics.ts +26 -0
  28. package/src/modules/git/runtime.ts +415 -0
  29. package/src/modules/git/state.ts +21 -0
  30. package/src/modules/git/status.ts +87 -0
  31. package/src/modules/git/worktree.ts +16 -0
  32. package/src/modules/github-pr.ts +24 -0
  33. package/src/modules/helpers.ts +5 -0
  34. package/src/modules/index.ts +31 -0
  35. package/src/modules/inspection.ts +138 -0
  36. package/src/modules/languages.ts +87 -0
  37. package/src/modules/model.ts +85 -0
  38. package/src/modules/package.ts +17 -0
  39. package/src/modules/provider.ts +13 -0
  40. package/src/modules/render.ts +166 -0
  41. package/src/modules/terminal.ts +60 -0
  42. package/src/modules/thinking.ts +13 -0
  43. package/src/modules/time.ts +20 -0
  44. package/src/modules/tokens.ts +18 -0
  45. package/src/modules/truncation.ts +37 -0
  46. package/src/modules/turn.ts +13 -0
  47. package/src/modules/types.ts +189 -0
  48. package/src/modules/workspace-helpers.ts +10 -0
  49. package/src/pi-starship.ts +609 -0
  50. package/src/runtime/cloud.ts +166 -0
  51. package/src/runtime/command.ts +123 -0
  52. package/src/runtime/deployment.ts +201 -0
  53. package/src/runtime/development.ts +153 -0
  54. package/src/runtime/execution.ts +151 -0
  55. package/src/runtime/github-pr.ts +332 -0
  56. package/src/runtime/helpers.ts +274 -0
  57. package/src/runtime/languages.ts +205 -0
  58. package/src/runtime/package.ts +112 -0
  59. package/src/runtime/refresh-controller.ts +107 -0
  60. package/src/runtime/types.ts +63 -0
  61. package/src/runtime/workspace.ts +147 -0
  62. package/src/usage.ts +53 -0
  63. package/dist/chunks/chunk-CKNSOLSW.ts +0 -10
  64. package/dist/chunks/chunk-CKNSOLSW.ts.map +0 -7
  65. package/dist/chunks/chunk-G2GG2V6Q.ts +0 -218
  66. package/dist/chunks/chunk-G2GG2V6Q.ts.map +0 -7
  67. package/dist/chunks/chunk-Q6DLIM7H.ts +0 -2492
  68. package/dist/chunks/chunk-Q6DLIM7H.ts.map +0 -7
  69. package/dist/chunks/cloud-JBSZWTB6.ts +0 -142
  70. package/dist/chunks/cloud-JBSZWTB6.ts.map +0 -7
  71. package/dist/chunks/commands-BSQZ2R4M.ts +0 -757
  72. package/dist/chunks/commands-BSQZ2R4M.ts.map +0 -7
  73. package/dist/chunks/deployment-ZNYM4B6W.ts +0 -172
  74. package/dist/chunks/deployment-ZNYM4B6W.ts.map +0 -7
  75. package/dist/chunks/development-TNWZ5SRC.ts +0 -132
  76. package/dist/chunks/development-TNWZ5SRC.ts.map +0 -7
  77. package/dist/chunks/execution-QHAP4U33.ts +0 -132
  78. package/dist/chunks/execution-QHAP4U33.ts.map +0 -7
  79. package/dist/chunks/languages-DPWDCH6Q.ts +0 -184
  80. package/dist/chunks/languages-DPWDCH6Q.ts.map +0 -7
  81. package/dist/chunks/package-MXN2YFLX.ts +0 -104
  82. package/dist/chunks/package-MXN2YFLX.ts.map +0 -7
  83. package/dist/pi-starship.ts +0 -1350
  84. package/dist/pi-starship.ts.map +0 -7
@@ -1,757 +0,0 @@
1
- // @generated by scripts/build-runtime.mjs; do not edit.
2
- // @ts-nocheck -- generated JavaScript uses a .ts extension so Pi routes chunks through Jiti.
3
- import {
4
- BUILT_IN_EXAMPLE,
5
- STARSHIP_SUBCOMMANDS,
6
- atomicRestoreConfigDocument,
7
- atomicSaveConfigDocument,
8
- completeStarshipArguments,
9
- inspectUnavailableModules,
10
- removeConfigDocumentIfMatches,
11
- validateConfigDocument
12
- } from "./chunk-Q6DLIM7H.js";
13
-
14
- // src/commands.ts
15
- import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
16
-
17
- // src/command-inspector.ts
18
- import { stripVTControlCharacters } from "node:util";
19
- import { Key, matchesKey, truncateToWidth, wrapTextWithAnsi } from "@earendil-works/pi-tui";
20
- var RESERVED_HOST_ROWS = 3;
21
- function showFooterExplanation(ctx, inspection, signal) {
22
- if (signal?.aborted) return Promise.resolve({ kind: "close" });
23
- return ctx.ui.custom((tui, theme, keybindings, done) => {
24
- let scrollOffset = 0;
25
- let lastMaximumScroll = 0;
26
- let lastViewportSize = 1;
27
- let disposed = false;
28
- let settled = false;
29
- let deferredAbort;
30
- const finish = (result) => {
31
- if (disposed || settled) return;
32
- settled = true;
33
- done(result);
34
- };
35
- const closeForAbort = () => finish({ kind: "close" });
36
- signal?.addEventListener("abort", closeForAbort, { once: true });
37
- if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
38
- return {
39
- focused: false,
40
- render(width) {
41
- const safeWidth = Math.max(1, width);
42
- const availableRows = componentRows(tui.terminal.rows);
43
- const content = explanationLines(inspection, safeWidth);
44
- const layout = detailLayout(availableRows, content.length);
45
- lastViewportSize = layout.contentRows;
46
- lastMaximumScroll = Math.max(0, content.length - layout.contentRows);
47
- scrollOffset = clamp(scrollOffset, 0, lastMaximumScroll);
48
- const lines = [
49
- ...layout.titleRows ? [theme.fg("accent", theme.bold("Explain footer"))] : [],
50
- ...content.slice(scrollOffset, scrollOffset + layout.contentRows),
51
- ...layout.positionRows ? [theme.fg("dim", positionText(scrollOffset, layout.contentRows, content.length))] : [],
52
- ...layout.hintRows ? [theme.fg("dim", detailHint(keybindings, "back"))] : []
53
- ];
54
- return boundedLines(lines, safeWidth, availableRows);
55
- },
56
- invalidate() {
57
- },
58
- handleInput(data) {
59
- if (disposed || settled) return;
60
- if (matchesKey(data, Key.ctrl("c"))) finish({ kind: "close" });
61
- else if (keybindings.matches(data, "tui.select.cancel")) finish({ kind: "back" });
62
- else if (keybindings.matches(data, "tui.select.up")) {
63
- scrollOffset = clamp(scrollOffset - 1, 0, lastMaximumScroll);
64
- } else if (keybindings.matches(data, "tui.select.down")) {
65
- scrollOffset = clamp(scrollOffset + 1, 0, lastMaximumScroll);
66
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
67
- scrollOffset = clamp(scrollOffset - lastViewportSize, 0, lastMaximumScroll);
68
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
69
- scrollOffset = clamp(scrollOffset + lastViewportSize, 0, lastMaximumScroll);
70
- } else if (matchesKey(data, Key.home)) scrollOffset = 0;
71
- else if (matchesKey(data, Key.end)) scrollOffset = lastMaximumScroll;
72
- tui.requestRender();
73
- },
74
- dispose() {
75
- if (disposed) return;
76
- disposed = true;
77
- if (deferredAbort) clearImmediate(deferredAbort);
78
- deferredAbort = void 0;
79
- signal?.removeEventListener("abort", closeForAbort);
80
- }
81
- };
82
- });
83
- }
84
- function explanationLines(inspection, width) {
85
- if (!inspection) {
86
- return wrapLines(
87
- [
88
- "Footer inspection is unavailable until the TUI footer is ready.",
89
- "No collection work was started."
90
- ],
91
- width
92
- );
93
- }
94
- if (inspection.showing.length === 0) {
95
- return wrapLines(
96
- [
97
- "No modules are currently showing.",
98
- "Open Modules to inspect empty, disabled, or unreachable modules."
99
- ],
100
- width
101
- );
102
- }
103
- const lines = inspection.showing.flatMap((module, index) => [
104
- ...index > 0 ? [""] : [],
105
- module.name,
106
- ...previewLines(module.preview),
107
- module.description
108
- ]);
109
- return wrapLines(lines, width);
110
- }
111
- function previewLines(preview) {
112
- const lines = preview ? preview.split("\n") : ["(no text)"];
113
- return lines.map((line, index) => `${index === 0 ? "Value: " : " "}${line}`);
114
- }
115
- function wrapLines(lines, width) {
116
- return lines.flatMap((line) => {
117
- const safe = safeDisplayText(line);
118
- return safe ? wrapTextWithAnsi(safe, width) : [""];
119
- });
120
- }
121
- function detailLayout(availableRows, contentLength) {
122
- if (availableRows === 1) {
123
- return { titleRows: 0, contentRows: 1, positionRows: 0, hintRows: 0 };
124
- }
125
- const titleRows = availableRows >= 4 ? 1 : 0;
126
- const hintRows = availableRows >= 3 ? 1 : 0;
127
- let contentRows = Math.max(1, availableRows - titleRows - hintRows);
128
- const positionRows = contentLength > contentRows && contentRows >= 2 ? 1 : 0;
129
- contentRows -= positionRows;
130
- return { titleRows, contentRows, positionRows, hintRows };
131
- }
132
- function componentRows(rows) {
133
- const terminalRows = Number.isFinite(rows) ? Math.floor(rows) : 24;
134
- return Math.max(1, terminalRows - RESERVED_HOST_ROWS);
135
- }
136
- function positionText(offset, viewportSize, itemCount) {
137
- if (itemCount === 0) return "0/0";
138
- return `${offset + 1}-${Math.min(itemCount, offset + viewportSize)}/${itemCount}`;
139
- }
140
- function boundedLines(lines, width, rows) {
141
- return lines.slice(0, rows).map((line) => truncateToWidth(line, width, ""));
142
- }
143
- function detailHint(keybindings, destination) {
144
- const up = bindingText(keybindings, "tui.select.up");
145
- const down = bindingText(keybindings, "tui.select.down");
146
- const cancel = bindingText(keybindings, "tui.select.cancel", "ctrl+c");
147
- const pageUp = bindingText(keybindings, "tui.select.pageUp");
148
- const pageDown = bindingText(keybindings, "tui.select.pageDown");
149
- return [
150
- ...up || down ? [`${[up, down].filter(Boolean).join("/")} scroll`] : [],
151
- ...pageUp || pageDown ? [`${[pageUp, pageDown].filter(Boolean).join("/")} page`] : [],
152
- ...cancel ? [`${cancel} ${destination}`] : [],
153
- "ctrl+c close"
154
- ].join(" \u2022 ");
155
- }
156
- function bindingText(keybindings, binding, excluded) {
157
- return keybindings.getKeys(binding).filter((key) => key !== excluded).map((key) => {
158
- if (key === "up") return "\u2191";
159
- if (key === "down") return "\u2193";
160
- if (key === "escape") return "esc";
161
- if (key === "return") return "enter";
162
- return safeDisplayText(key);
163
- }).filter(Boolean).join("/");
164
- }
165
- function safeDisplayText(value) {
166
- return Array.from(stripVTControlCharacters(value), (character) => {
167
- const codePoint = character.codePointAt(0) ?? 0;
168
- return codePoint <= 31 || codePoint >= 127 && codePoint <= 159 ? "" : character;
169
- }).join("");
170
- }
171
- function clamp(value, minimum, maximum) {
172
- return Math.max(minimum, Math.min(value, maximum));
173
- }
174
-
175
- // src/command-preview.ts
176
- import { stripVTControlCharacters as stripVTControlCharacters2 } from "node:util";
177
- import { Key as Key2, matchesKey as matchesKey2, truncateToWidth as truncateToWidth2, wrapTextWithAnsi as wrapTextWithAnsi2 } from "@earendil-works/pi-tui";
178
- var RESERVED_HOST_ROWS2 = 3;
179
- async function showPreviewActionMenu(ctx, title, body, items, signal) {
180
- if (signal?.aborted) return { kind: "closed" };
181
- return ctx.ui.custom((tui, theme, keybindings, done) => {
182
- let selectedIndex = 0;
183
- let scrollOffset = 0;
184
- let lastMaximumScroll = 0;
185
- let lastViewportSize = 1;
186
- let disposed = false;
187
- let deferredAbort;
188
- const closeForAbort = () => {
189
- if (disposed) return;
190
- if (deferredAbort) clearImmediate(deferredAbort);
191
- deferredAbort = void 0;
192
- done({ kind: "closed" });
193
- };
194
- signal?.addEventListener("abort", closeForAbort, { once: true });
195
- if (signal?.aborted) deferredAbort = setImmediate(closeForAbort);
196
- const requestRender = () => {
197
- if (!disposed) tui.requestRender();
198
- };
199
- const moveSelection = (delta) => {
200
- if (items.length === 0) return;
201
- selectedIndex = (selectedIndex + delta + items.length) % items.length;
202
- requestRender();
203
- };
204
- const movePreview = (offset) => {
205
- scrollOffset = Math.max(0, Math.min(offset, lastMaximumScroll));
206
- requestRender();
207
- };
208
- return {
209
- render(width) {
210
- const safeWidth = Math.max(1, width);
211
- const terminalRows = Number.isFinite(tui.terminal.rows) ? Math.floor(tui.terminal.rows) : 24;
212
- const availableRows = Math.max(1, terminalRows - RESERVED_HOST_ROWS2);
213
- const bodyLines = body(safeWidth).flatMap(
214
- (line) => line ? wrapTextWithAnsi2(line, safeWidth) : [""]
215
- );
216
- const layout = allocateLayout(availableRows, items.length, bodyLines.length);
217
- lastViewportSize = layout.previewRows;
218
- lastMaximumScroll = Math.max(0, bodyLines.length - layout.previewRows);
219
- scrollOffset = Math.max(0, Math.min(scrollOffset, lastMaximumScroll));
220
- const actionStart = actionWindowStart(selectedIndex, items.length, layout.actionRows);
221
- const actionLines = items.slice(actionStart, actionStart + layout.actionRows).map((item, index) => {
222
- const absoluteIndex = actionStart + index;
223
- const prefix = absoluteIndex === selectedIndex ? "\u2192 " : " ";
224
- return theme.fg(
225
- absoluteIndex === selectedIndex ? "accent" : "text",
226
- `${prefix}${safeDisplayText2(item.label)}`
227
- );
228
- });
229
- const position = layout.positionRows ? [theme.fg("dim", previewPosition(scrollOffset, layout.previewRows, bodyLines.length))] : [];
230
- const lines = [
231
- ...layout.titleRows ? [theme.fg("accent", theme.bold(safeDisplayText2(title)))] : [],
232
- ...bodyLines.slice(scrollOffset, scrollOffset + layout.previewRows),
233
- ...position,
234
- ...actionLines,
235
- ...layout.hintRows ? [theme.fg("dim", previewHint(keybindings))] : []
236
- ];
237
- return lines.map((line) => truncateToWidth2(line, safeWidth, ""));
238
- },
239
- invalidate() {
240
- },
241
- handleInput(data) {
242
- if (disposed) return;
243
- if (matchesKey2(data, Key2.ctrl("c"))) {
244
- done({ kind: "closed" });
245
- } else if (keybindings.matches(data, "tui.select.cancel")) {
246
- done({ kind: "cancelled" });
247
- } else if (keybindings.matches(data, "tui.select.up")) {
248
- moveSelection(-1);
249
- } else if (keybindings.matches(data, "tui.select.down")) {
250
- moveSelection(1);
251
- } else if (keybindings.matches(data, "tui.select.pageUp")) {
252
- movePreview(scrollOffset - lastViewportSize);
253
- } else if (keybindings.matches(data, "tui.select.pageDown")) {
254
- movePreview(scrollOffset + lastViewportSize);
255
- } else if (matchesKey2(data, Key2.home)) {
256
- movePreview(0);
257
- } else if (matchesKey2(data, Key2.end)) {
258
- movePreview(lastMaximumScroll);
259
- } else if (keybindings.matches(data, "tui.select.confirm")) {
260
- const item = items[selectedIndex];
261
- if (item) done({ kind: "selected", value: item.value });
262
- }
263
- },
264
- dispose() {
265
- if (disposed) return;
266
- disposed = true;
267
- if (deferredAbort) clearImmediate(deferredAbort);
268
- deferredAbort = void 0;
269
- signal?.removeEventListener("abort", closeForAbort);
270
- }
271
- };
272
- });
273
- }
274
- function allocateLayout(availableRows, actionCount, bodyLineCount) {
275
- if (availableRows === 1) {
276
- return { titleRows: 0, previewRows: 0, positionRows: 0, actionRows: 1, hintRows: 0 };
277
- }
278
- const titleRows = availableRows >= 3 ? 1 : 0;
279
- const hintRows = availableRows >= 3 ? 1 : 0;
280
- const minimumPreviewRows = bodyLineCount > 0 && availableRows >= 4 ? 1 : 0;
281
- const availableActionRows = Math.max(
282
- 1,
283
- availableRows - titleRows - hintRows - minimumPreviewRows
284
- );
285
- const actionRows = Math.min(Math.max(1, actionCount), availableActionRows);
286
- let previewRows = Math.max(0, availableRows - titleRows - hintRows - actionRows);
287
- const positionRows = previewRows >= 2 && bodyLineCount > previewRows ? 1 : 0;
288
- previewRows -= positionRows;
289
- return { titleRows, previewRows, positionRows, actionRows, hintRows };
290
- }
291
- function actionWindowStart(selectedIndex, itemCount, viewportSize) {
292
- if (itemCount <= viewportSize) return 0;
293
- return Math.max(0, Math.min(selectedIndex, itemCount - viewportSize));
294
- }
295
- function previewPosition(offset, viewportSize, lineCount) {
296
- if (lineCount === 0) return "0/0";
297
- return `${offset + 1}-${Math.min(lineCount, offset + viewportSize)}/${lineCount}`;
298
- }
299
- function previewHint(keybindings) {
300
- const up = bindingText2(keybindings, "tui.select.up");
301
- const down = bindingText2(keybindings, "tui.select.down");
302
- const confirm = bindingText2(keybindings, "tui.select.confirm");
303
- const cancel = bindingText2(keybindings, "tui.select.cancel", "ctrl+c");
304
- const pageUp = bindingText2(keybindings, "tui.select.pageUp");
305
- const pageDown = bindingText2(keybindings, "tui.select.pageDown");
306
- return [
307
- ...up || down ? [`${[up, down].filter(Boolean).join("/")} navigate`] : [],
308
- ...confirm ? [`${confirm} select`] : [],
309
- ...cancel ? [`${cancel} discard`] : [],
310
- "ctrl+c close",
311
- ...pageUp || pageDown ? [`${[pageUp, pageDown].filter(Boolean).join("/")} preview`] : []
312
- ].join(" \u2022 ");
313
- }
314
- function bindingText2(keybindings, binding, excluded) {
315
- return keybindings.getKeys(binding).filter((key) => key !== excluded).map((key) => {
316
- if (key === "up") return "\u2191";
317
- if (key === "down") return "\u2193";
318
- if (key === "escape") return "esc";
319
- if (key === "return") return "enter";
320
- return safeDisplayText2(key);
321
- }).join("/");
322
- }
323
- function safeDisplayText2(value) {
324
- return Array.from(stripVTControlCharacters2(value), (character) => {
325
- const codePoint = character.codePointAt(0) ?? 0;
326
- const control = codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
327
- return control ? "" : character;
328
- }).join("");
329
- }
330
-
331
- // src/commands.ts
332
- var MAIN_ACTIONS = {
333
- customize: "customize",
334
- explain: "explain",
335
- modules: "modules",
336
- configuration: "configuration",
337
- help: "help",
338
- restore: "restore"
339
- };
340
- var PREVIEW_ACTIONS = {
341
- continue: "continue",
342
- edit: "edit",
343
- cancel: "cancel"
344
- };
345
- function registerStarshipCommand(pi, options) {
346
- pi.registerCommand("starship", {
347
- description: "Customize or inspect the native Starship-style footer",
348
- getArgumentCompletions: completeStarshipArguments,
349
- handler: (args, ctx) => handleStarshipCommand(args, ctx, options)
350
- });
351
- }
352
- async function handleStarshipCommand(args, ctx, options) {
353
- const normalized = args.trim();
354
- if (!normalized) {
355
- if (ctx.mode === "tui") await showMainMenu(ctx, options);
356
- else showHelp(ctx, options.settingsPath);
357
- return;
358
- }
359
- const [subcommand = "", ...trailing] = normalized.split(/\s+/u);
360
- const route = subcommand.toLowerCase();
361
- if (trailing.length > 0 || !STARSHIP_SUBCOMMANDS.some((item) => item.value === route)) {
362
- if (canNotify(ctx)) {
363
- const reason = trailing.length > 0 ? `Unexpected arguments for /starship ${safeText(route)}.` : `Unknown /starship subcommand: ${safeText(route)}.`;
364
- ctx.ui.notify(`${reason} Usage: /starship [settings|status|help]`, "warning");
365
- }
366
- return;
367
- }
368
- switch (route) {
369
- case "settings":
370
- await editSettings(ctx, options);
371
- return;
372
- case "status":
373
- showStatus(ctx, options);
374
- return;
375
- case "help":
376
- showHelp(ctx, options.settingsPath);
377
- return;
378
- }
379
- }
380
- async function showMainMenu(ctx, options) {
381
- const fallbackController = new AbortController();
382
- const owner = options.getMenuOwner?.() ?? {
383
- signal: fallbackController.signal,
384
- isCurrent: () => !fallbackController.signal.aborted
385
- };
386
- const menu = defineMenu({
387
- start: "main",
388
- screens: {
389
- main: () => {
390
- const loaded = options.getLoaded();
391
- const presentation = configurationPresentation(loaded);
392
- return {
393
- kind: "actions",
394
- title: "pi-starship",
395
- lines: [`${presentation.state} \xB7 ${presentation.health}`],
396
- items: [
397
- {
398
- id: MAIN_ACTIONS.customize,
399
- label: "Customize footer",
400
- description: `${presentation.state} \xB7 preview before applying`,
401
- action: "customize"
402
- },
403
- {
404
- id: MAIN_ACTIONS.explain,
405
- label: "Explain footer",
406
- description: "Why each visible module appears",
407
- action: "explain"
408
- },
409
- {
410
- id: MAIN_ACTIONS.modules,
411
- label: "Modules",
412
- description: "Browse supported modules and current states",
413
- to: "modules"
414
- },
415
- {
416
- id: MAIN_ACTIONS.configuration,
417
- label: "Configuration",
418
- description: presentation.health,
419
- to: "configuration"
420
- },
421
- {
422
- id: MAIN_ACTIONS.help,
423
- label: "Help",
424
- description: "Formats, modules, and commands",
425
- to: "help"
426
- },
427
- {
428
- id: MAIN_ACTIONS.restore,
429
- label: "Restore built-in\u2026",
430
- description: presentation.restoreDescription,
431
- disabled: presentation.restoreDisabled,
432
- action: "restore"
433
- }
434
- ],
435
- hint: "close"
436
- };
437
- },
438
- modules: () => {
439
- const inspection = options.getInspection?.() ?? inspectUnavailableModules(options.getLoaded().config);
440
- return {
441
- kind: "browse",
442
- title: "Modules",
443
- items: inspection.modules.map((module) => ({
444
- id: module.name,
445
- label: module.name,
446
- statusText: module.state,
447
- description: module.description,
448
- searchText: [...module.variables, ...module.styleFields, ...module.displayRules].join(
449
- " "
450
- ),
451
- details: [
452
- `Root: ${module.rootReferenced ? "Referenced" : "Not referenced"}`,
453
- `Reachable: ${module.reachable ? "Yes" : "No"}`,
454
- ...modulePreviewDetails(module.preview),
455
- `Reason: ${module.reason}`,
456
- `Variables: ${module.variables.join(", ") || "none"}`,
457
- `Style fields: ${module.styleFields.join(", ") || "none"}`,
458
- `Display rules: ${module.displayRules.join(" \xB7 ") || "none"}`
459
- ]
460
- })),
461
- viewportSize: "adaptive",
462
- hint: "back"
463
- };
464
- },
465
- configuration: () => {
466
- const loaded = options.getLoaded();
467
- const presentation = configurationPresentation(loaded);
468
- return {
469
- kind: "detail",
470
- title: "Configuration",
471
- lines: [
472
- `State: ${presentation.state}`,
473
- `Source: ${presentation.source}`,
474
- `Path: ${safeText(options.settingsPath)}`,
475
- ...diagnosticLines(loaded, true)
476
- ],
477
- hint: "back"
478
- };
479
- },
480
- help: () => ({
481
- kind: "detail",
482
- title: "pi-starship help",
483
- lines: [
484
- "Customize footer opens the TOML editor, then previews and confirms before saving.",
485
- "Explain footer breaks down the modules currently showing from the existing snapshot.",
486
- "Modules searches every supported module and explains its current read-only state.",
487
- "Configuration explains state, source, path, and warnings without changing the footer.",
488
- `Settings: ${safeText(options.settingsPath)}`,
489
- "Docs: https://github.com/narumiruna/pi-extensions/tree/main/extensions/pi-starship"
490
- ],
491
- hint: "back"
492
- })
493
- },
494
- actions: {
495
- customize: async () => {
496
- const result = await editSettings(ctx, options);
497
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
498
- },
499
- explain: async () => {
500
- const result = await showFooterExplanation(ctx, options.getInspection?.(), owner.signal);
501
- if (!isCurrentOwner(owner)) return { kind: "stay" };
502
- return result?.kind === "back" ? { kind: "stay" } : { kind: "close" };
503
- },
504
- restore: async () => {
505
- const presentation = configurationPresentation(options.getLoaded());
506
- if (presentation.restoreDisabled) {
507
- ctx.ui.notify(presentation.restoreDescription, "info");
508
- return { kind: "stay" };
509
- }
510
- const result = await restoreBuiltIn(ctx, options);
511
- return result === "applied" || result === "close" ? { kind: "close" } : { kind: "stay" };
512
- }
513
- }
514
- });
515
- try {
516
- await runMenu(ctx, menu, {
517
- getState: () => void 0,
518
- signal: owner.signal,
519
- isCurrent: owner.isCurrent
520
- });
521
- } finally {
522
- fallbackController.abort(new DOMException("Starship menu closed", "AbortError"));
523
- }
524
- }
525
- async function editSettings(ctx, options) {
526
- const owner = workflowOwner(options);
527
- if (!isCurrentOwner(owner)) return "cancel";
528
- if (ctx.mode !== "tui") {
529
- if (ctx.hasUI) ctx.ui.notify(`Edit settings manually: ${options.settingsPath}`, "info");
530
- return "cancel";
531
- }
532
- let draft = options.getLoaded().rawDocument ?? BUILT_IN_EXAMPLE;
533
- while (true) {
534
- const edited = await ctx.ui.editor("Customize footer \u2014 close to preview", draft);
535
- if (!isCurrentOwner(owner) || edited === void 0) return "cancel";
536
- draft = edited;
537
- let validated;
538
- try {
539
- validated = (options.validate ?? validateConfigDocument)(options.settingsPath, draft);
540
- } catch (error) {
541
- ctx.ui.notify(`Footer draft is invalid: ${safeText(formatError(error))}`, "error");
542
- const action = await showPreviewActionMenu(
543
- ctx,
544
- "Configuration needs attention",
545
- () => [safeText(formatError(error)), "The current footer has not changed."],
546
- [
547
- { value: PREVIEW_ACTIONS.edit, label: "Continue editing" },
548
- { value: PREVIEW_ACTIONS.cancel, label: "Discard draft" }
549
- ],
550
- owner.signal
551
- );
552
- if (!isCurrentOwner(owner)) return "cancel";
553
- if (action?.kind === "closed") return "close";
554
- if (selectedPreviewAction(action) === PREVIEW_ACTIONS.edit) continue;
555
- return "cancel";
556
- }
557
- const result = await reviewAndApply(ctx, options, validated, "Footer preview", false, owner);
558
- if (result === "edit") continue;
559
- return result;
560
- }
561
- }
562
- async function restoreBuiltIn(ctx, options) {
563
- const owner = workflowOwner(options);
564
- if (!isCurrentOwner(owner)) return "cancel";
565
- const validated = (options.validate ?? validateConfigDocument)(
566
- options.settingsPath,
567
- BUILT_IN_EXAMPLE
568
- );
569
- const result = await reviewAndApply(ctx, options, validated, "Restore preview", true, owner);
570
- return result === "edit" ? "cancel" : result;
571
- }
572
- async function reviewAndApply(ctx, options, validated, title, restore, owner) {
573
- while (true) {
574
- const selection = await showPreviewActionMenu(
575
- ctx,
576
- title,
577
- (width) => restore ? restorePreviewBody(ctx, options, validated, width) : previewBody(ctx, options, validated, width),
578
- [
579
- {
580
- value: PREVIEW_ACTIONS.continue,
581
- label: restore ? "Replace with built-in\u2026" : "Apply changes\u2026"
582
- },
583
- ...restore ? [] : [{ value: PREVIEW_ACTIONS.edit, label: "Continue editing" }],
584
- {
585
- value: PREVIEW_ACTIONS.cancel,
586
- label: restore ? "Cancel" : "Discard draft"
587
- }
588
- ],
589
- owner.signal
590
- );
591
- if (!isCurrentOwner(owner)) return "cancel";
592
- if (selection?.kind === "closed") return "close";
593
- const selected = selectedPreviewAction(selection);
594
- if (selected === PREVIEW_ACTIONS.edit) return "edit";
595
- if (selected !== PREVIEW_ACTIONS.continue) return "cancel";
596
- const confirmed = await ctx.ui.confirm(
597
- restore ? "Restore built-in footer?" : "Apply footer changes?",
598
- restore ? `Replace ${safeText(options.settingsPath)} entirely with the built-in configuration? All custom settings, unknown fields, and comments will be removed. No backup is kept after success.` : "Save this configuration and apply it immediately?"
599
- );
600
- if (!isCurrentOwner(owner)) return "cancel";
601
- if (!confirmed) continue;
602
- const save = options.save ?? atomicSaveConfigDocument;
603
- const previous = options.getLoaded();
604
- let saved;
605
- try {
606
- saved = save(options.settingsPath, validated.rawDocument ?? BUILT_IN_EXAMPLE);
607
- } catch (error) {
608
- ctx.ui.notify(
609
- `Footer settings were not saved: ${safeText(formatError(error))}. The previous footer remains active.`,
610
- "error"
611
- );
612
- continue;
613
- }
614
- try {
615
- options.apply(saved, ctx);
616
- } catch (error) {
617
- const rollbackError = restorePreviousConfiguration(ctx, options, previous, saved);
618
- ctx.ui.notify(
619
- rollbackError ? `Footer settings could not be applied: ${safeText(formatError(error))}. Restoring the previous configuration also failed: ${safeText(formatError(rollbackError))}.` : `Footer settings could not be applied: ${safeText(formatError(error))}. The previous configuration was restored.`,
620
- "error"
621
- );
622
- continue;
623
- }
624
- const warningSuffix = saved.diagnostics.length > 0 ? ` (${saved.diagnostics.length} warning${saved.diagnostics.length === 1 ? "" : "s"})` : "";
625
- ctx.ui.notify(
626
- restore ? `Built-in footer restored and applied${warningSuffix}.` : `Footer settings saved and applied${warningSuffix}.`,
627
- "info"
628
- );
629
- return "applied";
630
- }
631
- }
632
- function modulePreviewDetails(preview) {
633
- const lines = preview ? preview.split("\n") : ["(no current preview)"];
634
- return lines.map((line, index) => `${index === 0 ? "Preview: " : " "}${line}`);
635
- }
636
- function workflowOwner(options) {
637
- if (options.getMenuOwner) return options.getMenuOwner();
638
- const controller = new AbortController();
639
- return { signal: controller.signal, isCurrent: () => true };
640
- }
641
- function isCurrentOwner(owner) {
642
- return !owner.signal.aborted && owner.isCurrent();
643
- }
644
- function restorePreviousConfiguration(ctx, options, previous, saved) {
645
- try {
646
- if (saved.rawDocument === void 0 || saved.fileIdentity === void 0) {
647
- throw new Error("The saved settings document identity is unavailable");
648
- }
649
- removeConfigDocumentIfMatches(options.settingsPath, saved.rawDocument, saved.fileIdentity);
650
- if (previous.rawDocument !== void 0) {
651
- (options.restore ?? atomicRestoreConfigDocument)(options.settingsPath, previous.rawDocument);
652
- }
653
- options.apply(previous, ctx);
654
- return void 0;
655
- } catch (error) {
656
- return error;
657
- }
658
- }
659
- function restorePreviewBody(ctx, options, loaded, width) {
660
- const current = configurationPresentation(options.getLoaded());
661
- return [
662
- `Current: ${current.state}`,
663
- `Path: ${safeText(options.settingsPath)}`,
664
- "The entire settings document will be replaced, including custom settings, unknown fields, and comments.",
665
- "No backup is kept after a successful restore.",
666
- "",
667
- ...previewBody(ctx, options, loaded, width)
668
- ];
669
- }
670
- function previewBody(ctx, options, loaded, width) {
671
- let lines;
672
- try {
673
- lines = options.renderPreview?.(loaded, width, ctx) ?? [
674
- "Live preview is unavailable until the footer is ready.",
675
- "The draft is valid and can still be applied."
676
- ];
677
- } catch (error) {
678
- lines = [`Preview unavailable: ${safeText(formatError(error))}`];
679
- }
680
- const warning = loaded.diagnostics.length === 0 ? "Draft validation: Healthy" : `Draft validation: ${loaded.diagnostics.length} warning${loaded.diagnostics.length === 1 ? "" : "s"}`;
681
- return [...lines, "", warning];
682
- }
683
- function selectedPreviewAction(result) {
684
- return result?.kind === "selected" ? result.value : null;
685
- }
686
- function diagnosticLines(loaded, includeSummary) {
687
- const diagnostics = loaded.diagnostics.slice(0, 8).map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`);
688
- const remaining = loaded.diagnostics.length - diagnostics.length;
689
- return [
690
- ...includeSummary ? [`Health: ${configurationHealth(loaded)}`] : [],
691
- ...diagnostics.length > 0 ? diagnostics : ["No configuration warnings."],
692
- ...remaining > 0 ? [`${remaining} additional warnings not shown.`] : []
693
- ];
694
- }
695
- function configurationPresentation(loaded) {
696
- const healthyMissing = loaded.source === "built-in" && loaded.rawDocument === void 0 && loaded.diagnostics.length === 0;
697
- const savedBuiltIn = loaded.source === "user" && loaded.rawDocument === BUILT_IN_EXAMPLE;
698
- const fallback = loaded.source === "built-in" && loaded.diagnostics.length > 0;
699
- return {
700
- state: healthyMissing ? "Built-in defaults" : savedBuiltIn ? "Saved built-in configuration" : fallback ? "Built-in fallback" : "Custom configuration",
701
- source: healthyMissing ? "No settings file" : loaded.source === "user" ? "User file" : "Built-in fallback",
702
- health: configurationHealth(loaded),
703
- restoreDisabled: healthyMissing || savedBuiltIn,
704
- restoreDescription: healthyMissing ? "Already using defaults \xB7 no file to replace" : savedBuiltIn ? "Built-in configuration already saved" : fallback ? "Preview before replacing invalid settings" : "Preview before replacing the document"
705
- };
706
- }
707
- function configurationHealth(loaded) {
708
- const errors = loaded.diagnostics.filter((item) => item.severity === "error").length;
709
- if (errors > 0) return `${errors} error${errors === 1 ? "" : "s"}`;
710
- const warnings = loaded.diagnostics.length;
711
- return warnings === 0 ? "Healthy" : `${warnings} warning${warnings === 1 ? "" : "s"}`;
712
- }
713
- function showStatus(ctx, options) {
714
- if (!canNotify(ctx)) return;
715
- const loaded = options.getLoaded();
716
- const diagnostics = loaded.diagnostics.slice(0, 5).map((item) => `${safeText(item.path || "root")}: ${safeText(item.message)}`).join("; ");
717
- ctx.ui.notify(
718
- [
719
- `pi-starship source: ${loaded.source}`,
720
- `path: ${options.settingsPath}`,
721
- diagnostics ? `warnings: ${diagnostics}` : "warnings: none"
722
- ].join("\n"),
723
- loaded.diagnostics.length > 0 ? "warning" : "info"
724
- );
725
- }
726
- function showHelp(ctx, settingsPath) {
727
- if (!canNotify(ctx)) return;
728
- ctx.ui.notify(
729
- [
730
- "/starship \u2014 customize, explain, or inspect the footer in TUI mode",
731
- "/starship settings \u2014 customize, preview, and apply TOML",
732
- "/starship status \u2014 show source, path, and warnings",
733
- "/starship help \u2014 show this help",
734
- `Settings: ${settingsPath}`,
735
- "Format/module docs: https://github.com/narumiruna/pi-extensions/tree/main/extensions/pi-starship"
736
- ].join("\n"),
737
- "info"
738
- );
739
- }
740
- function canNotify(ctx) {
741
- return ctx.mode === "tui" || ctx.hasUI;
742
- }
743
- function safeText(value) {
744
- return Array.from(value, (character) => {
745
- const codePoint = character.codePointAt(0) ?? 0;
746
- const unsafe = codePoint <= 8 || codePoint >= 11 && codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
747
- return unsafe ? `\\u${codePoint.toString(16).padStart(4, "0")}` : character;
748
- }).join("");
749
- }
750
- function formatError(error) {
751
- return error instanceof Error ? error.message : String(error);
752
- }
753
- export {
754
- handleStarshipCommand,
755
- registerStarshipCommand
756
- };
757
- //# sourceMappingURL=commands-BSQZ2R4M.ts.map