dsh-bash-terminal-ts 0.7.2-compat.2 → 0.8.1

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 (86) hide show
  1. package/README.de.md +3 -2
  2. package/README.en.md +102 -3
  3. package/README.es.md +3 -2
  4. package/README.fr.md +3 -2
  5. package/README.it.md +3 -2
  6. package/README.md +198 -4
  7. package/README.ru.md +3 -2
  8. package/cordis.patch.yml +66 -0
  9. package/dist/client.core.js +7888 -79
  10. package/dist/client.js +7888 -79
  11. package/dsh.plugin.json +22 -22
  12. package/lib/browser-i18n.d.ts +4 -0
  13. package/lib/browser-i18n.js +23 -0
  14. package/lib/client.js +7888 -79
  15. package/lib/dsh-types.d.ts +10 -0
  16. package/lib/dsh.d.ts +2 -0
  17. package/lib/index.d.ts +43 -0
  18. package/lib/index.js +176 -91
  19. package/lib/locales.d.ts +4 -0
  20. package/lib/locales.js +422 -0
  21. package/lib/settings-surface.d.ts +20 -0
  22. package/lib/settings-surface.js +49 -0
  23. package/lib/shell-id.d.ts +2 -0
  24. package/lib/shell-id.js +9 -0
  25. package/lib/shells.d.ts +114 -0
  26. package/lib/shells.js +187 -0
  27. package/lib/terminal.d.ts +30 -1
  28. package/lib/terminal.js +18 -5
  29. package/lib/webterminals/catalog.d.ts +36 -0
  30. package/lib/webterminals/catalog.js +93 -0
  31. package/lib/webterminals/host.d.ts +67 -0
  32. package/lib/webterminals/host.js +278 -0
  33. package/lib/webterminals/mount.d.ts +46 -0
  34. package/lib/webterminals/mount.js +171 -0
  35. package/lib/webterminals/protocol.d.ts +94 -0
  36. package/lib/webterminals/protocol.js +9 -0
  37. package/lib/webterminals/pty.d.ts +42 -0
  38. package/lib/webterminals/pty.js +64 -0
  39. package/lib/webterminals/registry.d.ts +139 -0
  40. package/lib/webterminals/registry.js +353 -0
  41. package/lib/webterminals/ws.d.ts +54 -0
  42. package/lib/webterminals/ws.js +140 -0
  43. package/locale/de.json +4 -0
  44. package/locale/en.json +4 -0
  45. package/locale/es.json +4 -0
  46. package/locale/fr.json +4 -0
  47. package/locale/it.json +4 -0
  48. package/locale/ja.json +4 -0
  49. package/locale/ko.json +4 -0
  50. package/locale/ru.json +4 -0
  51. package/locale/zh.json +4 -0
  52. package/package.json +131 -121
  53. package/scripts/build-browser-tests.mjs +36 -0
  54. package/scripts/build-client.mjs +10 -0
  55. package/scripts/check-artifacts.mjs +93 -0
  56. package/scripts/link-shells.mjs +75 -0
  57. package/src/browser-i18n.ts +27 -0
  58. package/src/client.tsx +539 -134
  59. package/src/dsh-types.ts +6 -0
  60. package/src/dsh.ts +2 -0
  61. package/src/index.ts +146 -35
  62. package/src/locales.ts +434 -0
  63. package/src/settings-surface.ts +59 -0
  64. package/src/shell-id.ts +11 -0
  65. package/src/shells.ts +250 -0
  66. package/src/terminal.ts +34 -5
  67. package/src/webterminals/browser/api.ts +212 -0
  68. package/src/webterminals/browser/bridge.ts +188 -0
  69. package/src/webterminals/browser/css.d.ts +16 -0
  70. package/src/webterminals/browser/face.ts +151 -0
  71. package/src/webterminals/browser/shell-picker.tsx +98 -0
  72. package/src/webterminals/browser/store.ts +40 -0
  73. package/src/webterminals/browser/tab.tsx +136 -0
  74. package/src/webterminals/browser/testkit.ts +21 -0
  75. package/src/webterminals/browser/url.ts +70 -0
  76. package/src/webterminals/browser/view.ts +381 -0
  77. package/src/webterminals/browser/xterm.ts +269 -0
  78. package/src/webterminals/catalog.ts +114 -0
  79. package/src/webterminals/host.ts +361 -0
  80. package/src/webterminals/mount.ts +227 -0
  81. package/src/webterminals/protocol.ts +78 -0
  82. package/src/webterminals/pty.ts +90 -0
  83. package/src/webterminals/registry.ts +447 -0
  84. package/src/webterminals/ws.ts +166 -0
  85. package/tsconfig.client.json +9 -1
  86. package/tsconfig.json +1 -1
@@ -0,0 +1,269 @@
1
+ // The embedded xterm controller for this plugin's OWN bottom-dock tab.
2
+ //
3
+ // Why a second consumer at all: on a host that ships its terminal controller
4
+ // (DSH 0.2.0+ mounts `terminal-controller` + `ui-sidebar-terminal`), the service
5
+ // `webTerminals` is the HOST's, so the shim in `bridge.ts` stands down - and the
6
+ // official shell menu de-duplicates entries by executable FILE NAME, which means
7
+ // Git Bash and MSYS2 (both `bash.exe`) can never both appear there. This tab is the
8
+ // path that still gives the user all four shells side by side, because the shell is
9
+ // chosen by catalog ROW through our own route, not by a menu that collapses names.
10
+ //
11
+ // xterm is IMPORTED normally, so it is BUNDLED into this artifact. That is not a
12
+ // preference: the client module table only resolves platform seed words, shell-owned
13
+ // modules, registered package factories and boot modules, so an external
14
+ // `require("@xterm/xterm")` fails at mount with "missed the module table" (measured on a
15
+ // live desktop host). dsh-better-sidebar escapes the same limit with its own chunk
16
+ // loader; duplicating that machinery for one dependency is not worth it.
17
+
18
+ import { FitAddon } from "@xterm/addon-fit";
19
+ import { Terminal } from "@xterm/xterm";
20
+ import xtermCss from "@xterm/xterm/css/xterm.css";
21
+ import { openTerminal, terminalSocketUrl } from "./api";
22
+ import type { CatalogEntry, ConfigSnapshot } from "./api";
23
+
24
+ /** The slice of xterm's `Terminal` this controller uses. */
25
+ interface XtermTerminal {
26
+ open(host: HTMLElement): void;
27
+ write(data: string): void;
28
+ reset(): void;
29
+ resize(cols: number, rows: number): void;
30
+ loadAddon(addon: unknown): void;
31
+ focus(): void;
32
+ dispose(): void;
33
+ onData(cb: (data: string) => void): { dispose(): void };
34
+ onResize?(cb: (size: { cols: number; rows: number }) => void): { dispose(): void };
35
+ }
36
+
37
+ /** The controller's own view of the emulator, narrowed to what it calls. */
38
+ type XtermFit = Pick<FitAddon, "fit"> & { proposeDimensions?(): { cols: number; rows: number } | undefined };
39
+ /**
40
+ * Install xterm's stylesheet once per document.
41
+ *
42
+ * The CSS arrives as text (the client build maps `.css` to the `text` loader, because
43
+ * esbuild refuses to inject a stylesheet into a CJS bundle) and is mounted as a
44
+ * `<style>` tag on first terminal. Importing it as a plain module would instead make
45
+ * esbuild emit a sidecar `.css` file that no DSH client bundle ever loads - silently
46
+ * unstyled.
47
+ */
48
+ function ensureXtermCss(): void {
49
+ if (typeof document === "undefined") return;
50
+ if (document.head.querySelector('style[data-xterm-css]') !== null) return;
51
+ const tag = document.createElement("style");
52
+ tag.dataset.xtermCss = "1";
53
+ tag.textContent = xtermCss;
54
+ document.head.appendChild(tag);
55
+ }
56
+
57
+ /** What the controller reports upward; the React shell only renders it. */
58
+ export type EmbeddedPhase = "allocating" | "connecting" | "running" | "exited" | "failed";
59
+
60
+ /** The callbacks the tab component supplies. */
61
+ export interface EmbeddedHooks {
62
+ onPhase?(phase: EmbeddedPhase, detail?: string): void;
63
+ onTitle?(title: string): void;
64
+ }
65
+
66
+ /** One live embedded terminal. */
67
+ export class EmbeddedTerminal {
68
+ private term?: XtermTerminal;
69
+ private fit?: XtermFit;
70
+ private socket?: WebSocket;
71
+ private observer?: ResizeObserver;
72
+ private disposed = false;
73
+ /** The host's terminal id; absent until the allocation answers. */
74
+ id = "";
75
+
76
+ private constructor(private readonly host: HTMLElement, private readonly hooks: EmbeddedHooks) {}
77
+
78
+ /**
79
+ * Mount one terminal into `host` and allocate the shell the caller asked for.
80
+ * @param shell - a catalog id; the host refuses one that is not activated+available.
81
+ * @returns a controller (already disposed on failure) or the reason nothing mounted.
82
+ */
83
+ static async create(host: HTMLElement, sessionId: string, shell: string | undefined, hooks: EmbeddedHooks): Promise<EmbeddedTerminal | { ok: false; message: string }> {
84
+ const controller = new EmbeddedTerminal(host, hooks);
85
+ const failure = controller.build();
86
+ if (failure !== undefined) return failure;
87
+ await controller.allocate(sessionId, shell);
88
+ return controller;
89
+ }
90
+
91
+ /** Instantiate the emulator; returns the reason it could not mount. */
92
+ private build(): { ok: false; message: string } | undefined {
93
+ try {
94
+ ensureXtermCss();
95
+ const term = new Terminal({
96
+ cursorBlink: true,
97
+ // The user's own colours are the point of an embedded shell; a fixed dark
98
+ // theme here would fight the host's light mode.
99
+ scrollback: 4000,
100
+ });
101
+ const addon = new FitAddon();
102
+ term.loadAddon(addon);
103
+ term.open(this.host);
104
+ this.term = term;
105
+ this.fit = addon;
106
+ term.onData((data) => this.send({ t: "input", data }));
107
+ term.onResize?.(({ cols, rows }) => this.send({ t: "resize", cols, rows }));
108
+ if (typeof ResizeObserver !== "undefined") {
109
+ this.observer = new ResizeObserver(() => this.fitNow());
110
+ this.observer.observe(this.host);
111
+ } else {
112
+ window.addEventListener("resize", this.fitNow);
113
+ }
114
+ this.hooks.onPhase?.("allocating");
115
+ return undefined;
116
+ } catch (error) {
117
+ const message = error instanceof Error ? error.message : String(error);
118
+ this.hooks.onPhase?.("failed", message);
119
+ return { ok: false, message };
120
+ }
121
+ }
122
+
123
+ /** Allocate the shell, then dial the socket that carries its screen. */
124
+ private async allocate(sessionId: string, shell: string | undefined): Promise<void> {
125
+ const size = this.propose();
126
+ try {
127
+ const result = await openTerminal({ sessionId, shell, cols: size.cols, rows: size.rows });
128
+ const info = result.info as { id: string; title: string; state: string };
129
+ this.id = info.id;
130
+ this.hooks.onTitle?.(info.title);
131
+ this.hooks.onPhase?.("connecting");
132
+ this.connect(info.id);
133
+ } catch (error) {
134
+ this.hooks.onPhase?.("failed", error instanceof Error ? error.message : String(error));
135
+ }
136
+ }
137
+
138
+ /** Open the screen socket for one allocated terminal. */
139
+ private connect(id: string): void {
140
+ if (this.disposed) return;
141
+ let socket: WebSocket;
142
+ try {
143
+ socket = new WebSocket(terminalSocketUrl(id).toString());
144
+ } catch (error) {
145
+ this.hooks.onPhase?.("failed", error instanceof Error ? error.message : String(error));
146
+ return;
147
+ }
148
+ this.socket = socket;
149
+ socket.onopen = () => {
150
+ if (this.socket !== socket) return;
151
+ this.hooks.onPhase?.("running");
152
+ this.fitNow();
153
+ socket.send(JSON.stringify({ t: "resize", ...this.propose() }));
154
+ this.term?.focus();
155
+ };
156
+ socket.onmessage = (event: { data: unknown }) => {
157
+ if (this.socket !== socket || typeof event.data !== "string") return;
158
+ let frame: Record<string, unknown>;
159
+ try {
160
+ frame = JSON.parse(event.data) as Record<string, unknown>;
161
+ } catch {
162
+ return;
163
+ }
164
+ const term = this.term;
165
+ if (term === undefined) return;
166
+ switch (frame.t) {
167
+ case "snapshot": {
168
+ // Replay, never append: a snapshot is the whole screen a late attachment
169
+ // has to reconstruct, and appending it would double what is already drawn.
170
+ term.reset();
171
+ term.write(String(frame.screen ?? ""));
172
+ const info = frame.info as { title?: string; state?: string } | undefined;
173
+ if (info?.title !== undefined) this.hooks.onTitle?.(info.title);
174
+ return;
175
+ }
176
+ case "data":
177
+ term.write(String(frame.data ?? ""));
178
+ return;
179
+ case "exit": {
180
+ const info = frame.info as { state?: string; exitCode?: number | null } | undefined;
181
+ this.hooks.onPhase?.("exited", info?.exitCode === null || info?.exitCode === undefined ? undefined : `exit ${info.exitCode}`);
182
+ return;
183
+ }
184
+ case "error":
185
+ this.hooks.onPhase?.("failed", `${String(frame.code ?? "error")}: ${String(frame.message ?? "")}`);
186
+ return;
187
+ default:
188
+ // pong / resized carry nothing the emulator needs.
189
+ return;
190
+ }
191
+ };
192
+ socket.onclose = () => {
193
+ if (this.socket !== socket) return;
194
+ this.socket = undefined;
195
+ };
196
+ socket.onerror = () => {
197
+ /* onclose owns the state */
198
+ };
199
+ }
200
+
201
+ /** The size xterm should be, from the host element's box. */
202
+ private propose(): { cols: number; rows: number } {
203
+ const proposed = this.fit?.proposeDimensions?.();
204
+ return { cols: Math.max(20, proposed?.cols ?? 80), rows: Math.max(6, proposed?.rows ?? 24) };
205
+ }
206
+
207
+ private readonly fitNow = (): void => {
208
+ try {
209
+ this.fit?.fit();
210
+ } catch {
211
+ // A detached or zero-sized host cannot be fit; the next resize event retries.
212
+ }
213
+ };
214
+
215
+ /** Send one client frame; a closed socket is not an error worth surfacing. */
216
+ private send(frame: Record<string, unknown>): void {
217
+ const socket = this.socket;
218
+ if (socket === undefined || socket.readyState !== WebSocket.OPEN) return;
219
+ try {
220
+ socket.send(JSON.stringify(frame));
221
+ } catch {
222
+ // The matching onclose leaves the tab in a state the component can show.
223
+ }
224
+ }
225
+
226
+ /** Re-fit after the host element changes size (the tab expands). */
227
+ refit(): void {
228
+ this.fitNow();
229
+ }
230
+
231
+ /** Close the tab: end the process AND release the emulator. */
232
+ dispose(): void {
233
+ if (this.disposed) return;
234
+ this.disposed = true;
235
+ this.observer?.disconnect();
236
+ this.observer = undefined;
237
+ window.removeEventListener("resize", this.fitNow);
238
+ // The tab closing IS the user's intent to end the shell (the host's own rule),
239
+ // so this sends `close` rather than merely dropping the socket.
240
+ this.send({ t: "close" });
241
+ try {
242
+ this.socket?.close();
243
+ } catch {
244
+ // already closed
245
+ }
246
+ this.socket = undefined;
247
+ this.term?.dispose();
248
+ this.term = undefined;
249
+ }
250
+ }
251
+
252
+ /** The catalog rows a user may pick in the tab's toolbar. */
253
+ export function pickableRows(snapshot: ConfigSnapshot | null): CatalogEntry[] {
254
+ if (!Array.isArray(snapshot?.catalog)) return [];
255
+ return snapshot.catalog.filter((row) => row.activated && row.available);
256
+ }
257
+
258
+ /**
259
+ * Which rows deserve a SWITCH (level 2), as opposed to a status badge.
260
+ *
261
+ * A control that cannot change anything is worse than no control: the floor backend
262
+ * has no choice to make, and a shell the machine does not have would accept a click,
263
+ * persist it, and still not appear in the picker. So both get a reason instead.
264
+ * Exported because the settings row renders from here and `renderToString` never runs
265
+ * the effect that fetches the catalog - a DOM assertion could not cover this rule.
266
+ */
267
+ export function switchableRows(rows: readonly CatalogEntry[]): CatalogEntry[] {
268
+ return rows.filter((row) => row.togglable && row.available);
269
+ }
@@ -0,0 +1,114 @@
1
+ // The host-side catalog provider: the filesystem and WSL probes, and the short
2
+ // cache the routes read through.
3
+ //
4
+ // Two decisions worth their comments:
5
+ //
6
+ // - **The cache lives here, not inside `buildCatalog`.** The catalog builder is a
7
+ // pure function so it can be table-tested without a filesystem; discovery hits
8
+ // disk and spawns `wsl.exe`, so the caller owns the TTL and invalidates it after
9
+ // a switch is written (a settings row that reports a stale answer right after
10
+ // the user changed it is worse than a slow one).
11
+ // - **`wsl -l -q` gets a hard timeout.** A WSL service that is starting up can sit
12
+ // on that call for tens of seconds; the settings page must render meanwhile, so
13
+ // an unreachable WSL reports "unknown" rather than blocking the row.
14
+
15
+ import { statSync } from "node:fs";
16
+ import { execFile } from "node:child_process";
17
+ import { buildCatalog, uiEnv } from "../shells.js";
18
+ import type { CatalogFacts, ShellEntry, ShellSwitches } from "../shells.js";
19
+ import type { ResolvedPaths } from "../dsh-types.js";
20
+
21
+ /** How long one catalog answer is trusted. */
22
+ export const CATALOG_TTL_MS = 5000;
23
+
24
+ /** Is this path a launchable file? */
25
+ export function fsProbe(path: string): boolean {
26
+ try {
27
+ return statSync(path).isFile();
28
+ } catch {
29
+ return false;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * The installed WSL distributions (quiet listing, one per line).
35
+ * @returns [] when wsl.exe is absent; undefined when the probe could not answer
36
+ * (a timeout is NOT "no distro" - reporting it as such would disable a working
37
+ * backend, which is the all-false-positive trap).
38
+ */
39
+ export function listWslDistros(wslPath: string | undefined, timeoutMs = 1500): Promise<readonly string[] | undefined> {
40
+ if (wslPath === undefined) return Promise.resolve([]);
41
+ return new Promise((resolve) => {
42
+ let settled = false;
43
+ const child = execFile(wslPath, ["-l", "-q"], { windowsHide: true, timeout: timeoutMs, encoding: "utf8" }, (error, stdout) => {
44
+ if (settled) return;
45
+ settled = true;
46
+ if (error !== null && error.signal !== undefined) {
47
+ resolve(undefined);
48
+ return;
49
+ }
50
+ // A non-zero exit with text output still means "reachable"; `wsl -l -q`
51
+ // exits 1 on a machine with no distro installed, which is a real answer.
52
+ const distros = String(stdout ?? "")
53
+ .split(/\r?\n/)
54
+ .map((line) => line.trim())
55
+ .filter((line) => line.length > 0 && !/^<.+>$/i.test(line));
56
+ resolve(distros);
57
+ });
58
+ child.on("error", () => {
59
+ if (settled) return;
60
+ settled = true;
61
+ resolve(undefined);
62
+ });
63
+ });
64
+ }
65
+
66
+ /** What the provider reads from the plugin's live config. */
67
+ export interface CatalogSource {
68
+ paths(): ResolvedPaths;
69
+ switches(): ShellSwitches;
70
+ wslDistro(): string;
71
+ /** Cached distro list; undefined means "unknown", [] means "none installed". */
72
+ distros(): readonly string[] | undefined;
73
+ }
74
+
75
+ /** The catalog with its TTL, as the routes consume it. */
76
+ export interface CatalogProvider {
77
+ /** The current rows (re-probed when the cache aged out). */
78
+ catalog(): ShellEntry[];
79
+ /** Forget the cached answer (call after any switch/path config write). */
80
+ invalidate(): void;
81
+ /** The UI environment for one backend (process.env plus its own rules). */
82
+ env(id: ShellEntry["id"]): Record<string, string | undefined>;
83
+ }
84
+
85
+ /**
86
+ * Build the TTL-backed provider.
87
+ * @param source - live config reads (never a snapshot: settings hot-reload).
88
+ * @param now - injectable clock for specs.
89
+ */
90
+ export function createCatalogProvider(source: CatalogSource, now: () => number = Date.now): CatalogProvider {
91
+ let cache: { at: number; rows: ShellEntry[] } | undefined;
92
+ const facts = (): CatalogFacts => ({
93
+ paths: source.paths(),
94
+ fsProbe,
95
+ // Passed through as-is: `undefined` is "the probe could not answer", which the
96
+ // catalog treats as neutral (available), while `[]` is the real "no distro".
97
+ distros: source.distros(),
98
+ switches: source.switches(),
99
+ wslDistro: source.wslDistro(),
100
+ });
101
+ return {
102
+ catalog: () => {
103
+ const at = now();
104
+ if (cache !== undefined && at - cache.at < CATALOG_TTL_MS) return cache.rows;
105
+ const rows = buildCatalog(facts());
106
+ cache = { at, rows };
107
+ return rows;
108
+ },
109
+ invalidate: () => {
110
+ cache = undefined;
111
+ },
112
+ env: (id) => uiEnv(id, process.env),
113
+ };
114
+ }