@inventarch/cli 3.5.1 → 3.6.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 (203) hide show
  1. package/NOTICE +2 -0
  2. package/README.md +2 -1
  3. package/SPEC.md +13 -4
  4. package/THIRD_PARTY_NOTICES.txt +49 -0
  5. package/assets/host/44dc1fa77e0235df35e1dd05d5a5ce8c2b19d4545caf0b8579f2f4e1b9efbbc6.tgz +0 -0
  6. package/assets/host.json +4 -4
  7. package/dist/args.d.ts +9 -0
  8. package/dist/args.d.ts.map +1 -1
  9. package/dist/args.js.map +1 -1
  10. package/dist/bin.d.ts +3 -0
  11. package/dist/bin.d.ts.map +1 -0
  12. package/dist/bin.js +53 -0
  13. package/dist/bin.js.map +1 -0
  14. package/dist/claude-cli.d.ts +13 -1
  15. package/dist/claude-cli.d.ts.map +1 -1
  16. package/dist/claude-cli.js +31 -1
  17. package/dist/claude-cli.js.map +1 -1
  18. package/dist/commands.d.ts +17 -0
  19. package/dist/commands.d.ts.map +1 -1
  20. package/dist/commands.js +66 -3
  21. package/dist/commands.js.map +1 -1
  22. package/dist/committed-host.d.ts.map +1 -1
  23. package/dist/committed-host.js +14 -2
  24. package/dist/committed-host.js.map +1 -1
  25. package/dist/console/app.d.ts +47 -0
  26. package/dist/console/app.d.ts.map +1 -0
  27. package/dist/console/app.js +921 -0
  28. package/dist/console/app.js.map +1 -0
  29. package/dist/console/batch-next.d.ts +54 -0
  30. package/dist/console/batch-next.d.ts.map +1 -0
  31. package/dist/console/batch-next.js +260 -0
  32. package/dist/console/batch-next.js.map +1 -0
  33. package/dist/console/batch-plan.d.ts +109 -0
  34. package/dist/console/batch-plan.d.ts.map +1 -0
  35. package/dist/console/batch-plan.js +308 -0
  36. package/dist/console/batch-plan.js.map +1 -0
  37. package/dist/console/batch-run.d.ts +195 -0
  38. package/dist/console/batch-run.d.ts.map +1 -0
  39. package/dist/console/batch-run.js +868 -0
  40. package/dist/console/batch-run.js.map +1 -0
  41. package/dist/console/batch-screen.d.ts +36 -0
  42. package/dist/console/batch-screen.d.ts.map +1 -0
  43. package/dist/console/batch-screen.js +113 -0
  44. package/dist/console/batch-screen.js.map +1 -0
  45. package/dist/console/grid.d.ts +30 -0
  46. package/dist/console/grid.d.ts.map +1 -0
  47. package/dist/console/grid.js +87 -0
  48. package/dist/console/grid.js.map +1 -0
  49. package/dist/console/keys.d.ts +54 -0
  50. package/dist/console/keys.d.ts.map +1 -0
  51. package/dist/console/keys.js +204 -0
  52. package/dist/console/keys.js.map +1 -0
  53. package/dist/console/layout-all.d.ts +70 -0
  54. package/dist/console/layout-all.d.ts.map +1 -0
  55. package/dist/console/layout-all.js +401 -0
  56. package/dist/console/layout-all.js.map +1 -0
  57. package/dist/console/layout-repo.d.ts +65 -0
  58. package/dist/console/layout-repo.d.ts.map +1 -0
  59. package/dist/console/layout-repo.js +275 -0
  60. package/dist/console/layout-repo.js.map +1 -0
  61. package/dist/console/load.d.ts +33 -0
  62. package/dist/console/load.d.ts.map +1 -0
  63. package/dist/console/load.js +166 -0
  64. package/dist/console/load.js.map +1 -0
  65. package/dist/console/offers.d.ts +39 -0
  66. package/dist/console/offers.d.ts.map +1 -0
  67. package/dist/console/offers.js +285 -0
  68. package/dist/console/offers.js.map +1 -0
  69. package/dist/console/run.d.ts +56 -0
  70. package/dist/console/run.d.ts.map +1 -0
  71. package/dist/console/run.js +210 -0
  72. package/dist/console/run.js.map +1 -0
  73. package/dist/console/state.d.ts +127 -0
  74. package/dist/console/state.d.ts.map +1 -0
  75. package/dist/console/state.js +273 -0
  76. package/dist/console/state.js.map +1 -0
  77. package/dist/console/terminal.d.ts +60 -0
  78. package/dist/console/terminal.d.ts.map +1 -0
  79. package/dist/console/terminal.js +114 -0
  80. package/dist/console/terminal.js.map +1 -0
  81. package/dist/console/width-table.d.ts +10 -0
  82. package/dist/console/width-table.d.ts.map +1 -0
  83. package/dist/console/width-table.js +753 -0
  84. package/dist/console/width-table.js.map +1 -0
  85. package/dist/console/width.d.ts +18 -0
  86. package/dist/console/width.d.ts.map +1 -0
  87. package/dist/console/width.js +114 -0
  88. package/dist/console/width.js.map +1 -0
  89. package/dist/console/workspaces-state.d.ts +93 -0
  90. package/dist/console/workspaces-state.d.ts.map +1 -0
  91. package/dist/console/workspaces-state.js +192 -0
  92. package/dist/console/workspaces-state.js.map +1 -0
  93. package/dist/consumer.d.ts +13 -8
  94. package/dist/consumer.d.ts.map +1 -1
  95. package/dist/consumer.js +22 -34
  96. package/dist/consumer.js.map +1 -1
  97. package/dist/discovery.d.ts +8 -0
  98. package/dist/discovery.d.ts.map +1 -0
  99. package/dist/discovery.js +36 -0
  100. package/dist/discovery.js.map +1 -0
  101. package/dist/distribute.d.ts +9 -0
  102. package/dist/distribute.d.ts.map +1 -1
  103. package/dist/distribute.js +70 -13
  104. package/dist/distribute.js.map +1 -1
  105. package/dist/doctor-authority.d.ts.map +1 -1
  106. package/dist/doctor-authority.js +7 -4
  107. package/dist/doctor-authority.js.map +1 -1
  108. package/dist/doctor-extensions.d.ts +36 -0
  109. package/dist/doctor-extensions.d.ts.map +1 -0
  110. package/dist/doctor-extensions.js +118 -0
  111. package/dist/doctor-extensions.js.map +1 -0
  112. package/dist/doctor-mounts.d.ts.map +1 -1
  113. package/dist/doctor-mounts.js +3 -2
  114. package/dist/doctor-mounts.js.map +1 -1
  115. package/dist/doctor-user.d.ts +64 -0
  116. package/dist/doctor-user.d.ts.map +1 -1
  117. package/dist/doctor-user.js +309 -34
  118. package/dist/doctor-user.js.map +1 -1
  119. package/dist/doctor.d.ts +22 -1
  120. package/dist/doctor.d.ts.map +1 -1
  121. package/dist/doctor.js +81 -32
  122. package/dist/doctor.js.map +1 -1
  123. package/dist/fix.d.ts +67 -0
  124. package/dist/fix.d.ts.map +1 -0
  125. package/dist/fix.js +136 -0
  126. package/dist/fix.js.map +1 -0
  127. package/dist/handoff.d.ts +65 -0
  128. package/dist/handoff.d.ts.map +1 -0
  129. package/dist/handoff.js +264 -0
  130. package/dist/handoff.js.map +1 -0
  131. package/dist/host-projection.d.ts.map +1 -1
  132. package/dist/host-projection.js +1 -8
  133. package/dist/host-projection.js.map +1 -1
  134. package/dist/host.d.ts +9 -3
  135. package/dist/host.d.ts.map +1 -1
  136. package/dist/host.js +23 -7
  137. package/dist/host.js.map +1 -1
  138. package/dist/init.d.ts +4 -6
  139. package/dist/init.d.ts.map +1 -1
  140. package/dist/init.js +80 -9
  141. package/dist/init.js.map +1 -1
  142. package/dist/local-cli.d.ts +67 -0
  143. package/dist/local-cli.d.ts.map +1 -0
  144. package/dist/local-cli.js +269 -0
  145. package/dist/local-cli.js.map +1 -0
  146. package/dist/main.d.ts +47 -3
  147. package/dist/main.d.ts.map +1 -1
  148. package/dist/main.js +121 -26
  149. package/dist/main.js.map +1 -1
  150. package/dist/marketplace-record.d.ts +7 -1
  151. package/dist/marketplace-record.d.ts.map +1 -1
  152. package/dist/marketplace-record.js +6 -3
  153. package/dist/marketplace-record.js.map +1 -1
  154. package/dist/package-manager.d.ts +43 -0
  155. package/dist/package-manager.d.ts.map +1 -0
  156. package/dist/package-manager.js +164 -0
  157. package/dist/package-manager.js.map +1 -0
  158. package/dist/position.d.ts.map +1 -1
  159. package/dist/position.js +16 -2
  160. package/dist/position.js.map +1 -1
  161. package/dist/preview.d.ts.map +1 -1
  162. package/dist/preview.js +11 -3
  163. package/dist/preview.js.map +1 -1
  164. package/dist/profile.d.ts +1 -1
  165. package/dist/profile.d.ts.map +1 -1
  166. package/dist/profile.js +3 -4
  167. package/dist/profile.js.map +1 -1
  168. package/dist/program.d.ts +10 -0
  169. package/dist/program.d.ts.map +1 -1
  170. package/dist/program.js +38 -1
  171. package/dist/program.js.map +1 -1
  172. package/dist/project.js +2 -2
  173. package/dist/project.js.map +1 -1
  174. package/dist/render.d.ts +7 -2
  175. package/dist/render.d.ts.map +1 -1
  176. package/dist/render.js +42 -3
  177. package/dist/render.js.map +1 -1
  178. package/dist/self.d.ts +6 -0
  179. package/dist/self.d.ts.map +1 -0
  180. package/dist/self.js +20 -0
  181. package/dist/self.js.map +1 -0
  182. package/dist/tracked-lock.d.ts +15 -0
  183. package/dist/tracked-lock.d.ts.map +1 -0
  184. package/dist/tracked-lock.js +37 -0
  185. package/dist/tracked-lock.js.map +1 -0
  186. package/dist/tracked.d.ts +125 -0
  187. package/dist/tracked.d.ts.map +1 -0
  188. package/dist/tracked.js +436 -0
  189. package/dist/tracked.js.map +1 -0
  190. package/dist/user-host.d.ts +7 -3
  191. package/dist/user-host.d.ts.map +1 -1
  192. package/dist/user-host.js +24 -11
  193. package/dist/user-host.js.map +1 -1
  194. package/dist/workspace-state.d.ts +15 -0
  195. package/dist/workspace-state.d.ts.map +1 -0
  196. package/dist/workspace-state.js +35 -0
  197. package/dist/workspace-state.js.map +1 -0
  198. package/dist/workspaces.d.ts +37 -0
  199. package/dist/workspaces.d.ts.map +1 -0
  200. package/dist/workspaces.js +319 -0
  201. package/dist/workspaces.js.map +1 -0
  202. package/package.json +9 -8
  203. package/assets/host/e594fd978a0f8a9f042bf40ab124779067e1c88e4a72b7ce57261ca0e48a984c.tgz +0 -0
@@ -0,0 +1,921 @@
1
+ /**
2
+ * The console's event loop: bare `ia` on an interactive terminal (consumer CLI contract §1.2). It loads the state and
3
+ * draws one of two views: inside a workspace, that workspace's own view; outside any, the all-workspaces view over the
4
+ * tracked list, with Find highlighted when the list is empty. Tab switches between them. It feeds stdin through one key
5
+ * decoder, arming a short timer while a lone ESC could still start a sequence.
6
+ *
7
+ * In a workspace's view, enter runs the selected offer in the normal screen (run.ts) and reloads; `r` reloads; `?`
8
+ * shows the keys; `q`, Ctrl-C, or Escape in the offers view quits with 0 (Escape elsewhere returns to the offers view). In the all-workspaces view space selects a row,
9
+ * `a` selects every row a batchable offer fires on, enter opens a row's own view (Escape returns), `b` moves to the
10
+ * batch list, where enter shows a batch's preview and enter again runs it in the normal screen (batch-screen.ts), and
11
+ * `f` opens a folder line to find workspaces in. `b` and `f` are keys only while no line is open: in the folder line
12
+ * every character is text. The tracked rows load in the background, each repainting as it arrives; quitting aborts
13
+ * the loads still running.
14
+ *
15
+ * One offer or batch runs at a time. Once a run starts or the console begins to finish, the rest of an already-decoded
16
+ * read is discarded, and no key navigates while a run goes on. stdin has one owner at a time: the console's decoder, a
17
+ * confirmation line or a one-key wait; before a child starts the console pauses stdin and lets go of it, and takes it
18
+ * back only for its own input.
19
+ *
20
+ * One teardown restores the terminal (console/terminal.ts) on quit, on a throw anywhere in the loop (exit 1, the error
21
+ * printed in the normal screen), on an output failure such as a closed pipe (exit 1), on `uncaughtException` and
22
+ * `unhandledRejection` (exit 1), and on `SIGINT`, `SIGTERM`, `SIGHUP` and, on Windows, `SIGBREAK` (exit 128 plus the
23
+ * signal's number: 130, 143, 129, 149). A process `exit` restores it synchronously. These handlers exist only while the
24
+ * console runs. A signal while a step's child runs is the child's to handle; Ctrl-C at the console's own confirmation
25
+ * declines it, and during a batch stops it: batch-run.ts passes the signal on to the command in flight, in a process
26
+ * group of its own, and nothing further starts.
27
+ */
28
+ import { statSync } from 'node:fs';
29
+ import { dirname, resolve as resolvePath } from 'node:path';
30
+ import { readIaConfig } from '@inventarch/distribution/updates';
31
+ import { consents } from '../consumer.js';
32
+ import { iaHomeOf } from '../discovery.js';
33
+ import { collectDoctor } from '../doctor.js';
34
+ import { rememberCommitted, runnableCopy } from '../handoff.js';
35
+ import { resolveCapabilities } from '../render.js';
36
+ import { findWorkspaces, readTracked, trackedRow, trackedState, trackWorkspaces } from '../tracked.js';
37
+ import { batchChoices, planBatch, selectNeeding } from './batch-plan.js';
38
+ import { defaultRunner, enclosingTop, gitTop } from './batch-run.js';
39
+ import { batchScreen } from './batch-screen.js';
40
+ import { sanitize } from './grid.js';
41
+ import { KeyDecoder } from './keys.js';
42
+ import { itemAt, itemCount, layoutAll } from './layout-all.js';
43
+ import { geometry, layoutRepo, listScroll } from './layout-repo.js';
44
+ import { loadState } from './load.js';
45
+ import { offersFor } from './offers.js';
46
+ import { runOffer, spawnInherited } from './run.js';
47
+ import { Screen } from './terminal.js';
48
+ import { graphemes } from './width.js';
49
+ import { doctorPool, loadAll, loadingRow, ownRoot, NOT_ITSELF, setAside, summarize, WORKSPACE_DOCTOR_TIMEOUT_MS, } from './workspaces-state.js';
50
+ export const ESCAPE_TIMEOUT_MS = 50;
51
+ /** The signals the console tears down on: Ctrl-Break (`SIGBREAK`) exists on Windows only. */
52
+ export const consoleSignals = (platform) => platform === 'win32' ? ['SIGINT', 'SIGTERM', 'SIGHUP', 'SIGBREAK'] : ['SIGINT', 'SIGTERM', 'SIGHUP'];
53
+ /** 128 plus the signal's number, as a shell reports a process a signal ended. */
54
+ export const SIGNAL_EXIT = {
55
+ SIGINT: 130,
56
+ SIGTERM: 143,
57
+ SIGHUP: 129,
58
+ SIGBREAK: 149,
59
+ };
60
+ const PROCESS = {
61
+ on: (event, listener) => process.on(event, listener),
62
+ off: (event, listener) => process.off(event, listener),
63
+ exit: (code) => process.exit(code),
64
+ platform: process.platform,
65
+ };
66
+ /**
67
+ * The workspace's own copy as the disk has it now, by the rule hand-off applies (handoff.ts `runnableCopy`): found up to
68
+ * the workspaces root that hoists it, and none when the repository commits it or the user set `IA_NO_HANDOFF=1`. Then
69
+ * every `ia` step runs on the running copy (`running`), as when no copy is installed.
70
+ */
71
+ export function resolveRepo(root, env, running, committed) {
72
+ return runnableCopy(root, { env, running, ...(committed === undefined ? {} : { committed }) });
73
+ }
74
+ const isDirectory = (path) => {
75
+ try {
76
+ return statSync(path).isDirectory();
77
+ }
78
+ catch {
79
+ return false;
80
+ }
81
+ };
82
+ export async function runConsole(input) {
83
+ const { io, env } = input;
84
+ const hooks = input.hooks ?? PROCESS;
85
+ const setTimer = input.setTimer ?? setTimeout, clearTimer = input.clearTimer ?? clearTimeout;
86
+ const spawner = input.spawn ?? spawnInherited;
87
+ const extensions = input.extensions ?? [];
88
+ const consoles = extensions.flatMap((extension) => (extension.console === undefined ? [] : [extension.console]));
89
+ // Bare `ia` has no flags: colour and ASCII come from the environment and the terminal.
90
+ const caps = resolveCapabilities({ env, isTTY: true, columns: io.columns() }, {});
91
+ const screen = new Screen(io, caps.color);
92
+ const print = (text) => io.write(`${text}\n`);
93
+ const collect = input.collect ?? collectDoctor;
94
+ // Every step and batch run resolves the workspace's copy by the hand-off rule (handoff.ts `runnableCopy`).
95
+ // Whether git tracks a copy is asked once per copy for the console's life, not at each load and step (the call is
96
+ // synchronous and can take up to 2 s). It is asked again when the copy at that path or the repository's index changes,
97
+ // and an answer git could not give is not remembered (handoff.ts `rememberCommitted`).
98
+ const committed = rememberCommitted();
99
+ const repoOf = input.resolveRepo ?? ((root) => resolveRepo(root, env, input.packageRoot, committed));
100
+ // One controller per load, aborted when the console finishes, so quitting never waits for a reload's doctor run.
101
+ const loads = new Set();
102
+ const load = async (cwd) => {
103
+ const controller = new AbortController();
104
+ loads.add(controller);
105
+ try {
106
+ return await loadState({
107
+ cwd,
108
+ env,
109
+ packageRoot: input.packageRoot,
110
+ version: input.version,
111
+ collect,
112
+ extensions,
113
+ signal: controller.signal,
114
+ committed,
115
+ ...(input.spawnDoctor === undefined ? {} : { spawnDoctor: input.spawnDoctor }),
116
+ });
117
+ }
118
+ finally {
119
+ loads.delete(controller);
120
+ }
121
+ };
122
+ /** The console's own workspace, or the running copy's view outside one. */
123
+ let home;
124
+ /** The workspace view's state: `home`, or a workspace opened from the table. */
125
+ let state;
126
+ let offers;
127
+ const ui = {
128
+ mode: 'repo',
129
+ drilled: null,
130
+ selected: 0,
131
+ scroll: { list: 0, pane: 0 },
132
+ view: 'offers',
133
+ message: null,
134
+ prompt: null,
135
+ };
136
+ const all = {
137
+ rows: [],
138
+ loaded: false,
139
+ controller: null,
140
+ selected: new Set(),
141
+ cursor: 0,
142
+ preview: null,
143
+ found: null,
144
+ message: null,
145
+ };
146
+ let batchController = null;
147
+ // Every workspace doctor the console starts, the table's and an opened workspace's refresh, shares these slots.
148
+ const pool = doctorPool();
149
+ /** The opened workspace's refresh in flight, and how many have been asked for: only the newest may land. */
150
+ let refresh = null;
151
+ let refreshes = 0;
152
+ const homeDir = () => home?.facts.home ?? iaHomeOf(env) ?? null;
153
+ const decoder = new KeyDecoder();
154
+ // stdin's one owner, or null. `epoch` changes whenever ownership changes or a run starts, which ends the dispatch of
155
+ // keys already decoded from one read.
156
+ let consumer = null;
157
+ let attached = false, epoch = 0;
158
+ let timer = null;
159
+ const onData = (chunk) => {
160
+ consumer?.(typeof chunk === 'string' ? chunk : chunk.toString('utf8'));
161
+ };
162
+ const own = (next) => {
163
+ consumer = next;
164
+ epoch += 1;
165
+ if (!attached) {
166
+ input.input.on('data', onData);
167
+ attached = true;
168
+ }
169
+ input.input.resume?.();
170
+ };
171
+ const release = () => {
172
+ consumer = null;
173
+ epoch += 1;
174
+ if (timer !== null) {
175
+ clearTimer(timer);
176
+ timer = null;
177
+ }
178
+ if (attached) {
179
+ input.input.off('data', onData);
180
+ attached = false;
181
+ }
182
+ input.input.pause?.();
183
+ };
184
+ return new Promise((resolve) => {
185
+ let finished = false, running = false, opening = false, child = false;
186
+ // A confirmation, one-key wait or batch the console itself owns; Ctrl-C cancels it.
187
+ let waiting = null;
188
+ let keyHandler = () => { };
189
+ let unsubscribe = null, unsubscribeError = null;
190
+ const signals = consoleSignals(hooks.platform ?? process.platform);
191
+ const removeHooks = () => {
192
+ for (const [event, listener] of handlers)
193
+ hooks.off(event, listener);
194
+ unsubscribe?.();
195
+ unsubscribe = null;
196
+ unsubscribeError?.();
197
+ unsubscribeError = null;
198
+ };
199
+ /** The one teardown: stdin let go, handlers removed, background loads aborted, the terminal given back. */
200
+ const finish = (code, error, sync = false) => {
201
+ if (finished)
202
+ return;
203
+ finished = true;
204
+ for (const controller of loads)
205
+ controller.abort();
206
+ release();
207
+ removeHooks();
208
+ all.controller?.abort();
209
+ batchController?.abort();
210
+ refresh?.abort();
211
+ screen.leave(sync);
212
+ waiting?.cancel();
213
+ if (error !== undefined) {
214
+ const text = error instanceof Error ? (error.stack ?? error.message) : String(error);
215
+ try {
216
+ const say = sync && io.writeSync !== undefined ? io.writeSync.bind(io) : io.write.bind(io);
217
+ for (const line of `ia: the console stopped: ${text}`.split(/\r?\n/))
218
+ say(`${sanitize(line)}\n`);
219
+ }
220
+ catch {
221
+ // The terminal itself failed; there is nowhere left to say so.
222
+ }
223
+ }
224
+ resolve(code);
225
+ };
226
+ const crash = (error) => {
227
+ // The process ends right after: restore synchronously, since an ordinary write may still be queued then.
228
+ finish(1, error, true);
229
+ hooks.exit(1);
230
+ };
231
+ const onSignal = (name) => () => {
232
+ // A running child receives the terminal's signals itself and decides; the console waits for it.
233
+ if (child)
234
+ return;
235
+ if (name === 'SIGINT' && waiting !== null) {
236
+ waiting.cancel();
237
+ return;
238
+ }
239
+ finish(SIGNAL_EXIT[name], undefined, true);
240
+ hooks.exit(SIGNAL_EXIT[name]);
241
+ };
242
+ const handlers = [
243
+ ['exit', () => finish(0, undefined, true)],
244
+ ['uncaughtException', crash],
245
+ ['unhandledRejection', crash],
246
+ ...signals.map((name) => [name, onSignal(name)]),
247
+ ];
248
+ for (const [event, listener] of handlers)
249
+ hooks.on(event, listener);
250
+ // The failed stream is not trusted with the restoration: it is written synchronously, through what survives.
251
+ unsubscribeError = io.onError?.((error) => finish(1, error, true)) ?? null;
252
+ const choices = () => batchChoices(all.rows, all.selected);
253
+ const render = () => {
254
+ if (finished)
255
+ return;
256
+ // Only the console's own screen is drawn on; elsewhere a resize only marks the next frame as a full one.
257
+ if (!screen.active) {
258
+ screen.invalidate();
259
+ return;
260
+ }
261
+ const columns = io.columns(), rows = io.rows();
262
+ if (ui.mode === 'all') {
263
+ screen.frame(layoutAll({
264
+ repos: all.rows,
265
+ summary: summarize(all.rows, { latest: home.facts.latest }, input.version),
266
+ selected: all.selected,
267
+ cursor: all.cursor,
268
+ choices: choices(),
269
+ preview: all.preview,
270
+ found: all.found,
271
+ message: all.message,
272
+ prompt: ui.prompt,
273
+ repoTab: home.root !== null,
274
+ caps,
275
+ columns,
276
+ rows,
277
+ }));
278
+ return;
279
+ }
280
+ const at = geometry(state.areas.length, columns, rows);
281
+ if (at !== null)
282
+ ui.scroll.list = listScroll(offers, ui.selected, at.list.height, ui.scroll.list);
283
+ screen.frame(layoutRepo({
284
+ state,
285
+ offers,
286
+ selected: ui.selected,
287
+ scroll: ui.scroll,
288
+ view: ui.view,
289
+ message: ui.message,
290
+ prompt: ui.prompt,
291
+ caps,
292
+ columns,
293
+ rows,
294
+ drilled: ui.drilled !== null,
295
+ }));
296
+ };
297
+ const guard = (work) => {
298
+ try {
299
+ const result = work();
300
+ if (result instanceof Promise)
301
+ result.catch((error) => finish(1, error));
302
+ }
303
+ catch (error) {
304
+ finish(1, error);
305
+ }
306
+ };
307
+ /** Keys from one read, dispatched until the console finishes, a run starts or stdin changes owner. */
308
+ const dispatch = (keys) => {
309
+ const at = epoch;
310
+ for (const key of keys) {
311
+ if (finished || epoch !== at)
312
+ return;
313
+ keyHandler(key);
314
+ }
315
+ };
316
+ const consoleInput = (chunk) => {
317
+ if (timer !== null) {
318
+ clearTimer(timer);
319
+ timer = null;
320
+ }
321
+ dispatch(decoder.push(chunk));
322
+ if (!finished && consumer === consoleInput && decoder.pending())
323
+ timer = setTimer(() => {
324
+ timer = null;
325
+ dispatch(decoder.flush());
326
+ }, ESCAPE_TIMEOUT_MS);
327
+ };
328
+ const takeConsole = () => own(consoleInput);
329
+ /** A tracked row rebuilt from a freshly loaded state. */
330
+ const rowFrom = (tracked, loaded) => ({
331
+ tracked,
332
+ state: loaded.repoFailure === null ? 'ready' : 'failed',
333
+ console: loaded,
334
+ offers: offersFor(loaded, consoles),
335
+ failure: loaded.repoFailure,
336
+ });
337
+ /** Stops the opened workspace's refresh, if one is in flight: its result could only be stale now. */
338
+ const dropRefresh = () => {
339
+ refresh?.abort();
340
+ refresh = null;
341
+ refreshes += 1;
342
+ };
343
+ const reload = async () => {
344
+ const target = ui.drilled;
345
+ if (target === null) {
346
+ // Guarded like the opened workspace's refresh below: a newer refresh, or a workspace opened from the table
347
+ // while this one loads, makes its result stale, and it is dropped rather than drawn over that view.
348
+ dropRefresh();
349
+ const mine = refreshes;
350
+ const loaded = await load(input.cwd);
351
+ if (finished || mine !== refreshes || ui.drilled !== target)
352
+ return;
353
+ home = loaded;
354
+ state = home;
355
+ }
356
+ else {
357
+ // A workspace opened from the table is read in the shared slots, bounded and cancellable; a newer refresh
358
+ // cancels this one, and a result is kept only while that same opening is still on screen.
359
+ dropRefresh();
360
+ const rowOf = () => {
361
+ const row = target.row === null ? undefined : all.rows[target.row];
362
+ return row !== undefined && row.tracked.root === target.root ? row : undefined;
363
+ };
364
+ /** Back to the table, the opened row set aside as its root reads, rather than offer another place's actions. */
365
+ const putAside = (set) => {
366
+ const row = rowOf();
367
+ const aside = row === undefined ? null : setAside(row.tracked, set);
368
+ if (aside !== null)
369
+ all.rows[target.row] = aside;
370
+ toAll();
371
+ all.message =
372
+ aside === null
373
+ ? 'The opened workspace can no longer be read.'
374
+ : aside.state === 'failed'
375
+ ? `${aside.tracked.id}: ${NOT_ITSELF}.`
376
+ : `${aside.tracked.id} is ${aside.state}.`;
377
+ };
378
+ // Checked first, as `loadAll` checks every row: a root gone or unreadable is never loaded, since discovery
379
+ // would walk up from it and run the copy of the workspace around it only for the result to be thrown away.
380
+ const before = trackedState(target);
381
+ if (before !== 'present')
382
+ return putAside(before);
383
+ const controller = new AbortController();
384
+ refresh = controller;
385
+ const mine = refreshes;
386
+ const loaded = await pool.run(controller.signal, () => loadState({
387
+ cwd: target.root,
388
+ env,
389
+ packageRoot: input.packageRoot,
390
+ version: input.version,
391
+ collect,
392
+ extensions,
393
+ signal: controller.signal,
394
+ timeoutMs: WORKSPACE_DOCTOR_TIMEOUT_MS,
395
+ committed,
396
+ ...(input.spawnDoctor === undefined ? {} : { spawnDoctor: input.spawnDoctor }),
397
+ }));
398
+ if (refresh === controller)
399
+ refresh = null;
400
+ if (loaded === null || finished || mine !== refreshes || ui.drilled !== target || controller.signal.aborted)
401
+ return;
402
+ // The backstop for a race: a root that went missing or unreadable during the load loads as the workspace
403
+ // around it, or as none, with that place's offers; the view goes back to the table rather than offer them.
404
+ if (!ownRoot(target.root, loaded))
405
+ return putAside();
406
+ state = loaded;
407
+ const row = rowOf();
408
+ if (row !== undefined)
409
+ all.rows[target.row] = rowFrom(row.tracked, loaded);
410
+ }
411
+ offers = offersFor(state, consoles);
412
+ ui.selected = Math.min(ui.selected, Math.max(0, offers.length - 1));
413
+ };
414
+ /** The tracked list, every row loading, then each loaded through its own copy in the background. */
415
+ const loadRows = () => {
416
+ all.controller?.abort();
417
+ const controller = new AbortController();
418
+ all.controller = controller;
419
+ all.loaded = true;
420
+ all.preview = null;
421
+ const dir = homeDir();
422
+ let tracked = [];
423
+ try {
424
+ tracked = dir === null ? [] : readTracked(dir);
425
+ if (dir === null)
426
+ all.message = 'The IA home cannot be found, so no workspaces are tracked.';
427
+ }
428
+ catch (error) {
429
+ all.message = error instanceof Error ? error.message : String(error);
430
+ }
431
+ const before = all.rows.map((row) => row.tracked.root);
432
+ all.rows = tracked.map(loadingRow);
433
+ // A selection survives a reload when the rows are the same.
434
+ if (before.join('\n') !== all.rows.map((row) => row.tracked.root).join('\n'))
435
+ all.selected = new Set();
436
+ all.cursor = Math.min(all.cursor, itemCount(all.rows.length, choices().length) - 1);
437
+ guard(() => loadAll({
438
+ tracked,
439
+ env,
440
+ packageRoot: input.packageRoot,
441
+ version: input.version,
442
+ signal: controller.signal,
443
+ collect,
444
+ extensions,
445
+ pool,
446
+ committed,
447
+ ...(input.spawnDoctor === undefined ? {} : { spawnDoctor: input.spawnDoctor }),
448
+ onRow: (index, row) => {
449
+ if (controller.signal.aborted || finished)
450
+ return;
451
+ all.rows[index] = row;
452
+ render();
453
+ },
454
+ }));
455
+ };
456
+ const prompt = (label, accept, initial = '') => new Promise((settle) => {
457
+ decoder.mode = 'text';
458
+ ui.prompt = { label, value: initial, error: null };
459
+ const back = keyHandler;
460
+ const done = (value) => {
461
+ decoder.mode = 'keys';
462
+ ui.prompt = null;
463
+ keyHandler = back;
464
+ // The rest of the read that ended the prompt is not navigation.
465
+ epoch += 1;
466
+ render();
467
+ settle(value);
468
+ };
469
+ keyHandler = (entry) => {
470
+ const current = ui.prompt;
471
+ if (entry.kind === 'text')
472
+ ui.prompt = { ...current, value: current.value + entry.text, error: null };
473
+ else if (entry.key === 'backspace')
474
+ ui.prompt = { ...current, value: graphemes(current.value).slice(0, -1).join(''), error: null };
475
+ else if (entry.key === 'escape' || entry.key === 'interrupt')
476
+ return done(null);
477
+ else if (entry.key === 'enter') {
478
+ const refusal = accept(current.value);
479
+ if (refusal === null)
480
+ return done(current.value);
481
+ ui.prompt = { ...current, error: refusal };
482
+ }
483
+ render();
484
+ };
485
+ render();
486
+ });
487
+ /** A wait on the console's own input in the normal screen, cancelled by Ctrl-C or the console finishing. */
488
+ const wait = (reader, cancelled) => new Promise((settle) => {
489
+ if (finished)
490
+ return settle(cancelled);
491
+ const end = (value) => {
492
+ waiting = null;
493
+ release();
494
+ settle(value);
495
+ };
496
+ waiting = { cancel: () => end(cancelled) };
497
+ own(reader(end));
498
+ });
499
+ /** One line typed in the normal screen after `question`; null when cancelled. */
500
+ const readLine = async (question) => {
501
+ if (finished)
502
+ return null;
503
+ io.write(question);
504
+ const answer = await wait((settle) => {
505
+ let buffer = '';
506
+ return (chunk) => {
507
+ buffer += chunk;
508
+ const end = buffer.search(/\r?\n|\r/);
509
+ if (end !== -1)
510
+ settle(buffer.slice(0, end));
511
+ };
512
+ }, null);
513
+ if (answer === null)
514
+ io.write('\n');
515
+ return answer;
516
+ };
517
+ const waitKey = async () => {
518
+ if (finished)
519
+ return;
520
+ screen.raw(true);
521
+ await wait((settle) => () => settle(), undefined);
522
+ };
523
+ const backToConsole = () => {
524
+ if (finished)
525
+ return;
526
+ screen.enter();
527
+ takeConsole();
528
+ screen.invalidate();
529
+ };
530
+ const run = async (offer, on = state) => {
531
+ running = true;
532
+ // Keys already decoded from the read that started this run are dropped.
533
+ epoch += 1;
534
+ try {
535
+ const result = await runOffer(offer, on, {
536
+ screen: {
537
+ leave: () => {
538
+ release();
539
+ screen.leave();
540
+ },
541
+ enter: () => {
542
+ if (finished)
543
+ return;
544
+ screen.enter();
545
+ takeConsole();
546
+ },
547
+ invalidate: () => screen.invalidate(),
548
+ },
549
+ spawn: async (file, args, options) => {
550
+ if (finished)
551
+ return null;
552
+ release();
553
+ child = true;
554
+ try {
555
+ return await spawner(file, args, options);
556
+ }
557
+ finally {
558
+ child = false;
559
+ }
560
+ },
561
+ ask: async (question) => consents(await readLine(`${question} [y/N] `)),
562
+ prompt,
563
+ waitKey,
564
+ print,
565
+ resolveRepo: repoOf,
566
+ env,
567
+ cwd: input.cwd,
568
+ });
569
+ ui.message = result.exitCode !== null ? `${offer.title}: stopped with exit ${result.exitCode}` : null;
570
+ }
571
+ finally {
572
+ running = false;
573
+ }
574
+ if (finished)
575
+ return;
576
+ if (consumer !== consoleInput)
577
+ takeConsole();
578
+ await reload();
579
+ render();
580
+ };
581
+ /** The preview's batch, in the normal screen; then whatever its "next" choice leads to. */
582
+ const runBatchFlow = async (preview) => {
583
+ running = true;
584
+ epoch += 1;
585
+ let controller = new AbortController();
586
+ batchController = controller;
587
+ let outcome = { next: 'return' };
588
+ try {
589
+ release();
590
+ screen.leave();
591
+ outcome = await batchScreen(preview, home.running, {
592
+ print: (text) => print(sanitize(text)),
593
+ line: readLine,
594
+ run: (file, args, options) => {
595
+ // Ctrl-C while a batch command runs stops the batch: that command gets the signal too (the runner sends it
596
+ // to the command's own process group when this run's signal aborts, and on Windows it shares the console),
597
+ // acts on it and usually ends, and nothing further starts.
598
+ waiting = { cancel: () => controller.abort() };
599
+ return (input.runner ?? defaultRunner(env))(file, args, { ...options, signal: controller.signal }).finally(() => {
600
+ waiting = null;
601
+ });
602
+ },
603
+ resolveRepo: repoOf,
604
+ env,
605
+ signal: controller.signal,
606
+ // Each choice after the run gets its own controller, so a Ctrl-C during the run leaves them choosable.
607
+ nextSignal: () => {
608
+ controller = new AbortController();
609
+ batchController = controller;
610
+ return controller.signal;
611
+ },
612
+ });
613
+ print('Press any key to return to the console.');
614
+ await waitKey();
615
+ }
616
+ finally {
617
+ running = false;
618
+ batchController = null;
619
+ }
620
+ backToConsole();
621
+ all.preview = null;
622
+ if (outcome.next === 'open') {
623
+ dropRefresh();
624
+ ui.drilled = { root: outcome.root, row: null };
625
+ ui.view = 'offers';
626
+ ui.selected = 0;
627
+ // Its view holds the console's own state and offers until this returns: the table stays up, and no key but quit
628
+ // acts, so nothing can draw or run those under this workspace's name.
629
+ opening = true;
630
+ all.message = `Reading ${outcome.root}…`;
631
+ render();
632
+ try {
633
+ await reload();
634
+ }
635
+ finally {
636
+ opening = false;
637
+ all.message = null;
638
+ }
639
+ if (finished)
640
+ return;
641
+ ui.mode = 'repo';
642
+ }
643
+ else if (outcome.next === 'deferred') {
644
+ const steps = outcome.steps;
645
+ await run({
646
+ id: 'deferred',
647
+ answers: [],
648
+ title: 'Steps left out of the batch',
649
+ explain: '',
650
+ steps,
651
+ changes: [],
652
+ group: 'more',
653
+ area: null,
654
+ writesTo: [...new Set(steps.map((step) => step.writesTo))],
655
+ batchable: false,
656
+ }, home);
657
+ }
658
+ if (finished)
659
+ return;
660
+ loadRows();
661
+ render();
662
+ };
663
+ const openFind = () => guard(async () => {
664
+ const accept = (value) => value.trim() === ''
665
+ ? 'Enter a folder.'
666
+ : isDirectory(resolvePath(input.cwd, value.trim()))
667
+ ? null
668
+ : 'Not a folder.';
669
+ const folder = await prompt('Folder', accept, dirname(input.cwd));
670
+ if (folder === null || finished)
671
+ return;
672
+ const dir = homeDir();
673
+ const absolute = resolvePath(input.cwd, folder.trim());
674
+ try {
675
+ const roots = findWorkspaces(absolute, { iaHome: dir ?? undefined });
676
+ const tracked = dir === null ? [] : readTracked(dir);
677
+ const known = new Set(roots.flatMap((root, index) => (trackedRow(tracked, root) === undefined ? [] : [index])));
678
+ all.found = {
679
+ folder: absolute,
680
+ roots,
681
+ tracked: known,
682
+ selected: new Set(roots.flatMap((_, index) => (known.has(index) ? [] : [index]))),
683
+ cursor: 0,
684
+ };
685
+ all.message = roots.length === 0 ? `No workspaces under ${absolute}.` : null;
686
+ }
687
+ catch (error) {
688
+ all.message = error instanceof Error ? error.message : String(error);
689
+ }
690
+ render();
691
+ });
692
+ /** Set while a tracking waits on the store lock: keys other than quit do nothing until it settles. */
693
+ let tracking = false;
694
+ const trackFound = (found) => {
695
+ const dir = homeDir();
696
+ const roots = found.roots.filter((_, index) => found.selected.has(index));
697
+ all.found = null;
698
+ if (dir === null) {
699
+ all.message = 'The IA home cannot be found.';
700
+ loadRows();
701
+ return;
702
+ }
703
+ // The lock wait is async and yields to the event loop, so a quit during it aborts the wait through `loads`.
704
+ const controller = new AbortController();
705
+ loads.add(controller);
706
+ tracking = true;
707
+ guard(async () => {
708
+ try {
709
+ const added = await trackWorkspaces(dir, roots, new Date(), { signal: controller.signal });
710
+ if (finished)
711
+ return;
712
+ all.message = `Tracked ${added.length} ${added.length === 1 ? 'workspace' : 'workspaces'}.`;
713
+ }
714
+ catch (error) {
715
+ if (finished)
716
+ return;
717
+ all.message = error instanceof Error ? error.message : String(error);
718
+ }
719
+ finally {
720
+ loads.delete(controller);
721
+ tracking = false;
722
+ }
723
+ loadRows();
724
+ render();
725
+ });
726
+ };
727
+ const toAll = () => {
728
+ ui.mode = 'all';
729
+ if (ui.drilled !== null)
730
+ dropRefresh();
731
+ ui.drilled = null;
732
+ state = home;
733
+ offers = offersFor(home, consoles);
734
+ if (!all.loaded)
735
+ loadRows();
736
+ };
737
+ const navigateAll = (key) => {
738
+ const found = all.found;
739
+ const count = itemCount(all.rows.length, choices().length);
740
+ const name = key.key;
741
+ if (name === 'quit' || name === 'interrupt')
742
+ return finish(0);
743
+ if (tracking)
744
+ return;
745
+ if (name === 'escape') {
746
+ if (found !== null)
747
+ all.found = null;
748
+ else if (all.preview !== null)
749
+ all.preview = null;
750
+ else
751
+ return finish(0);
752
+ }
753
+ else if (found !== null) {
754
+ if (name === 'up' || name === 'down')
755
+ all.found = {
756
+ ...found,
757
+ cursor: Math.max(0, Math.min(found.roots.length - 1, found.cursor + (name === 'up' ? -1 : 1))),
758
+ };
759
+ else if (name === 'space' && !found.tracked.has(found.cursor) && found.roots.length > 0) {
760
+ const selected = new Set(found.selected);
761
+ if (selected.has(found.cursor))
762
+ selected.delete(found.cursor);
763
+ else
764
+ selected.add(found.cursor);
765
+ all.found = { ...found, selected };
766
+ }
767
+ else if (name === 'enter')
768
+ return trackFound(found);
769
+ }
770
+ else if (name === 'tab') {
771
+ if (home.root !== null) {
772
+ ui.mode = 'repo';
773
+ ui.view = 'offers';
774
+ }
775
+ }
776
+ else if (name === 'up' || name === 'down') {
777
+ all.cursor = Math.max(0, Math.min(count - 1, all.cursor + (name === 'up' ? -1 : 1)));
778
+ all.preview = null;
779
+ }
780
+ else if (name === 'space') {
781
+ const item = itemAt(all.cursor, all.rows.length, choices().length);
782
+ if (item.kind === 'repo') {
783
+ if (all.selected.has(item.index))
784
+ all.selected.delete(item.index);
785
+ else
786
+ all.selected.add(item.index);
787
+ all.preview = null;
788
+ }
789
+ }
790
+ else if (name === 'select-all') {
791
+ all.selected = new Set(selectNeeding(all.rows));
792
+ all.preview = null;
793
+ }
794
+ else if (name === 'batch')
795
+ all.cursor = all.rows.length;
796
+ else if (name === 'find')
797
+ return openFind();
798
+ else if (name === 'refresh')
799
+ loadRows();
800
+ else if (name === 'enter') {
801
+ const listed = choices();
802
+ const item = itemAt(all.cursor, all.rows.length, listed.length);
803
+ all.message = null;
804
+ if (item.kind === 'find')
805
+ return openFind();
806
+ if (item.kind === 'repo') {
807
+ const row = all.rows[item.index];
808
+ if (row.console === null)
809
+ all.message =
810
+ row.state === 'missing' || row.state === 'unreadable'
811
+ ? `${row.tracked.id} is ${row.state}.`
812
+ : 'Still reading this workspace.';
813
+ else {
814
+ ui.mode = 'repo';
815
+ dropRefresh();
816
+ ui.drilled = { root: row.tracked.root, row: item.index };
817
+ ui.view = 'offers';
818
+ ui.selected = 0;
819
+ state = row.console;
820
+ offers = row.offers;
821
+ }
822
+ }
823
+ else {
824
+ const choice = listed[item.index];
825
+ if (all.preview !== null && all.preview.choice.offerId === choice.offerId) {
826
+ const preview = all.preview;
827
+ return guard(() => runBatchFlow(preview));
828
+ }
829
+ const dir = homeDir();
830
+ if (dir === null)
831
+ all.message = 'The IA home cannot be found.';
832
+ else {
833
+ const root = readIaConfig(dir)?.worktreeRoot;
834
+ const plan = planBatch(choice.offerId, all.rows, all.selected, { iaHome: dir, ...(root === undefined ? {} : { worktreeRoot: root }) }, { top: (path) => gitTop(path, env), enclosing: (path) => enclosingTop(path, env) });
835
+ all.preview = { choice, ...plan };
836
+ }
837
+ }
838
+ }
839
+ render();
840
+ };
841
+ const navigate = (entry) => {
842
+ if (entry.kind !== 'key' || running || finished)
843
+ return;
844
+ if (opening) {
845
+ if (entry.key === 'quit' || entry.key === 'interrupt')
846
+ finish(0);
847
+ return;
848
+ }
849
+ if (ui.mode === 'all')
850
+ return navigateAll(entry);
851
+ const key = entry.key;
852
+ const top = ui.view === 'offers';
853
+ if (ui.drilled !== null && top && (key === 'quit' || key === 'escape')) {
854
+ dropRefresh();
855
+ ui.mode = 'all';
856
+ ui.drilled = null;
857
+ state = home;
858
+ offers = offersFor(home, consoles);
859
+ render();
860
+ return;
861
+ }
862
+ if (key === 'quit' || key === 'interrupt' || (key === 'escape' && top))
863
+ return finish(0);
864
+ if (key === 'escape' || (key === 'tab' && !top))
865
+ ui.view = 'offers';
866
+ else if (key === 'tab') {
867
+ toAll();
868
+ }
869
+ else if (key === 'help')
870
+ ui.view = 'help';
871
+ else if (key === 'up' || key === 'down') {
872
+ const step = key === 'up' ? -1 : 1;
873
+ if (ui.view === 'offers') {
874
+ ui.selected = Math.max(0, Math.min(offers.length - 1, ui.selected + step));
875
+ ui.scroll.pane = 0;
876
+ }
877
+ else
878
+ ui.scroll.pane = Math.max(0, ui.scroll.pane + step);
879
+ }
880
+ else if (key === 'page-up' || key === 'page-down')
881
+ ui.scroll.pane = Math.max(0, ui.scroll.pane + (key === 'page-up' ? -10 : 10));
882
+ else if (key === 'refresh') {
883
+ ui.message = null;
884
+ return guard(async () => {
885
+ await reload();
886
+ render();
887
+ });
888
+ }
889
+ else if (key === 'enter' && top) {
890
+ const offer = offers[ui.selected];
891
+ if (offer === undefined)
892
+ return;
893
+ ui.message = null;
894
+ if (offer.disabled !== undefined)
895
+ ui.message = `${offer.title}: ${offer.disabled}`;
896
+ else if (offer.view === 'diagnostics')
897
+ ui.view = 'diagnostics';
898
+ else
899
+ return guard(() => run(offer));
900
+ }
901
+ // select-all, batch and find belong to the all-workspaces view.
902
+ render();
903
+ };
904
+ keyHandler = navigate;
905
+ guard(async () => {
906
+ await reload();
907
+ if (finished)
908
+ return;
909
+ // Outside any workspace the console opens on every tracked one; with none tracked, Find is the first item.
910
+ if (home.root === null)
911
+ toAll();
912
+ screen.enter();
913
+ unsubscribe = io.onResize(() => guard(render));
914
+ if (typeof input.input.setEncoding === 'function')
915
+ input.input.setEncoding('utf8');
916
+ takeConsole();
917
+ render();
918
+ });
919
+ });
920
+ }
921
+ //# sourceMappingURL=app.js.map