@dxos/react-ui-terminal 0.0.0 → 1.0.0-next-bbabc02363f18d7643ea4160e3a7a7809870fd0d
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.
- package/LICENSE +105 -0
- package/dist/lib/chunk-cli.mjs +24 -1
- package/dist/lib/chunk-cli.mjs.map +1 -1
- package/dist/lib/index.mjs +4 -3
- package/dist/lib/index.mjs.map +1 -1
- package/dist/lib/testing.mjs +14 -11
- package/dist/lib/testing.mjs.map +1 -1
- package/dist/types/src/cli/input.d.ts.map +1 -1
- package/dist/types/src/cli/line-editor.d.ts.map +1 -1
- package/dist/types/src/cli/shell.d.ts.map +1 -1
- package/dist/types/src/cli/tokenize.test.d.ts +2 -0
- package/dist/types/src/cli/tokenize.test.d.ts.map +1 -0
- package/dist/types/src/components/Terminal/Terminal.d.ts +4 -1
- package/dist/types/src/components/Terminal/Terminal.d.ts.map +1 -1
- package/dist/types/src/components/Terminal/Terminal.stories.d.ts +1 -1
- package/dist/types/src/testing.d.ts +5 -1
- package/dist/types/src/testing.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +20 -22
- package/src/cli/console.test.ts +9 -9
- package/src/cli/input.test.ts +26 -45
- package/src/cli/input.ts +33 -0
- package/src/cli/line-editor.test.ts +43 -37
- package/src/cli/line-editor.ts +6 -0
- package/src/cli/shell.ts +2 -1
- package/src/cli/tokenize.test.ts +38 -0
- package/src/components/Terminal/Terminal.tsx +16 -4
- package/src/testing.ts +27 -15
package/LICENSE
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# Functional Source License, Version 1.1, ALv2 Future License
|
|
2
|
+
|
|
3
|
+
## Abbreviation
|
|
4
|
+
|
|
5
|
+
FSL-1.1-Apache-2.0
|
|
6
|
+
|
|
7
|
+
## Notice
|
|
8
|
+
|
|
9
|
+
Copyright 2026 DXOS
|
|
10
|
+
|
|
11
|
+
## Terms and Conditions
|
|
12
|
+
|
|
13
|
+
### Licensor ("We")
|
|
14
|
+
|
|
15
|
+
The party offering the Software under these Terms and Conditions.
|
|
16
|
+
|
|
17
|
+
### The Software
|
|
18
|
+
|
|
19
|
+
The "Software" is each version of the software that we make available under
|
|
20
|
+
these Terms and Conditions, as indicated by our inclusion of these Terms and
|
|
21
|
+
Conditions with the Software.
|
|
22
|
+
|
|
23
|
+
### License Grant
|
|
24
|
+
|
|
25
|
+
Subject to your compliance with this License Grant and the Patents,
|
|
26
|
+
Redistribution and Trademark clauses below, we hereby grant you the right to
|
|
27
|
+
use, copy, modify, create derivative works, publicly perform, publicly display
|
|
28
|
+
and redistribute the Software for any Permitted Purpose identified below.
|
|
29
|
+
|
|
30
|
+
### Permitted Purpose
|
|
31
|
+
|
|
32
|
+
A Permitted Purpose is any purpose other than a Competing Use. A Competing Use
|
|
33
|
+
means making the Software available to others in a commercial product or
|
|
34
|
+
service that:
|
|
35
|
+
|
|
36
|
+
1. substitutes for the Software;
|
|
37
|
+
|
|
38
|
+
2. substitutes for any other product or service we offer using the Software
|
|
39
|
+
that exists as of the date we make the Software available; or
|
|
40
|
+
|
|
41
|
+
3. offers the same or substantially similar functionality as the Software.
|
|
42
|
+
|
|
43
|
+
Permitted Purposes specifically include using the Software:
|
|
44
|
+
|
|
45
|
+
1. for your internal use and access;
|
|
46
|
+
|
|
47
|
+
2. for non-commercial education;
|
|
48
|
+
|
|
49
|
+
3. for non-commercial research; and
|
|
50
|
+
|
|
51
|
+
4. in connection with professional services that you provide to a licensee
|
|
52
|
+
using the Software in accordance with these Terms and Conditions.
|
|
53
|
+
|
|
54
|
+
### Patents
|
|
55
|
+
|
|
56
|
+
To the extent your use for a Permitted Purpose would necessarily infringe our
|
|
57
|
+
patents, the license grant above includes a license under our patents. If you
|
|
58
|
+
make a claim against any party that the Software infringes or contributes to
|
|
59
|
+
the infringement of any patent, then your patent license to the Software ends
|
|
60
|
+
immediately.
|
|
61
|
+
|
|
62
|
+
### Redistribution
|
|
63
|
+
|
|
64
|
+
The Terms and Conditions apply to all copies, modifications and derivatives of
|
|
65
|
+
the Software.
|
|
66
|
+
|
|
67
|
+
If you redistribute any copies, modifications or derivatives of the Software,
|
|
68
|
+
you must include a copy of or a link to these Terms and Conditions and not
|
|
69
|
+
remove any copyright notices provided in or with the Software.
|
|
70
|
+
|
|
71
|
+
### Disclaimer
|
|
72
|
+
|
|
73
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND WITHOUT WARRANTIES OF ANY KIND, EXPRESS OR
|
|
74
|
+
IMPLIED, INCLUDING WITHOUT LIMITATION WARRANTIES OF FITNESS FOR A PARTICULAR
|
|
75
|
+
PURPOSE, MERCHANTABILITY, TITLE OR NON-INFRINGEMENT.
|
|
76
|
+
|
|
77
|
+
IN NO EVENT WILL WE HAVE ANY LIABILITY TO YOU ARISING OUT OF OR RELATED TO THE
|
|
78
|
+
SOFTWARE, INCLUDING INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
|
|
79
|
+
EVEN IF WE HAVE BEEN INFORMED OF THEIR POSSIBILITY IN ADVANCE.
|
|
80
|
+
|
|
81
|
+
### Trademarks
|
|
82
|
+
|
|
83
|
+
Except for displaying the License Details and identifying us as the origin of
|
|
84
|
+
the Software, you have no right under these Terms and Conditions to use our
|
|
85
|
+
trademarks, trade names, service marks or product names.
|
|
86
|
+
|
|
87
|
+
## Grant of Future License
|
|
88
|
+
|
|
89
|
+
We hereby irrevocably grant you an additional license to use the Software under
|
|
90
|
+
the Apache License, Version 2.0 that is effective on the second anniversary of
|
|
91
|
+
the date we make the Software available. On or after that date, you may use the
|
|
92
|
+
Software under the Apache License, Version 2.0, in which case the following
|
|
93
|
+
will apply:
|
|
94
|
+
|
|
95
|
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use
|
|
96
|
+
this file except in compliance with the License.
|
|
97
|
+
|
|
98
|
+
You may obtain a copy of the License at
|
|
99
|
+
|
|
100
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
101
|
+
|
|
102
|
+
Unless required by applicable law or agreed to in writing, software distributed
|
|
103
|
+
under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
|
104
|
+
CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
|
105
|
+
specific language governing permissions and limitations under the License.
|
package/dist/lib/chunk-cli.mjs
CHANGED
|
@@ -145,6 +145,23 @@ var matchEscapeSequence = (data, index) => {
|
|
|
145
145
|
};
|
|
146
146
|
};
|
|
147
147
|
/**
|
|
148
|
+
* Length of the unrecognized escape sequence at `index`, or zero if what follows is not one.
|
|
149
|
+
*
|
|
150
|
+
* The table above covers only unmodified navigation keys, so a chord like ctrl-right arrives as
|
|
151
|
+
* the parameterized `\x1b[1;5C` and matches nothing. Measuring the whole sequence lets the caller
|
|
152
|
+
* discard it; decoding it byte by byte would type `1;5C` into the line instead.
|
|
153
|
+
*/
|
|
154
|
+
var unrecognizedEscapeLength = (data, index) => {
|
|
155
|
+
const introducer = data[index];
|
|
156
|
+
if (introducer === "[") {
|
|
157
|
+
let end = index + 1;
|
|
158
|
+
while (end < data.length && !(data[end] >= "@" && data[end] <= "~")) end += 1;
|
|
159
|
+
return end < data.length ? end - index + 1 : data.length - index;
|
|
160
|
+
}
|
|
161
|
+
if (introducer === "O" && index + 1 < data.length) return 2;
|
|
162
|
+
return 0;
|
|
163
|
+
};
|
|
164
|
+
/**
|
|
148
165
|
* Decodes a chunk of xterm `onData` output into the keypress events that `@effect/platform`
|
|
149
166
|
* consumers (notably `@effect/cli` prompts) expect, using the same key names as Node's readline.
|
|
150
167
|
*
|
|
@@ -163,6 +180,11 @@ var decodeInput = (data) => {
|
|
|
163
180
|
index += escape.length + 1;
|
|
164
181
|
continue;
|
|
165
182
|
}
|
|
183
|
+
const unrecognized = unrecognizedEscapeLength(data, index + 1);
|
|
184
|
+
if (unrecognized > 0) {
|
|
185
|
+
index += unrecognized + 1;
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
166
188
|
const next = data[index + 1];
|
|
167
189
|
if (next !== void 0 && next >= " " && next !== "") {
|
|
168
190
|
inputs.push(makeInput(next.toLowerCase(), {
|
|
@@ -267,6 +289,7 @@ var readLineResult = (bridge, options = {}) => Effect.async((resume) => {
|
|
|
267
289
|
return;
|
|
268
290
|
default: return;
|
|
269
291
|
}
|
|
292
|
+
if (key.meta) return;
|
|
270
293
|
switch (key.name) {
|
|
271
294
|
case "return":
|
|
272
295
|
bridge.write("\n");
|
|
@@ -488,7 +511,7 @@ var runShell = (bridge, options) => Effect.gen(function* () {
|
|
|
488
511
|
]).pipe(Effect.catchAllCause((cause) => {
|
|
489
512
|
if (Cause.isInterruptedOnly(cause)) return Effect.void;
|
|
490
513
|
const failure = Cause.failureOption(cause);
|
|
491
|
-
if (failure
|
|
514
|
+
if (Option.isSome(failure) && ValidationError.isValidationError(failure.value)) return Effect.void;
|
|
492
515
|
return Console.error(Cause.pretty(cause));
|
|
493
516
|
}));
|
|
494
517
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chunk-cli.mjs","names":[],"sources":["../../src/cli/console.ts","../../src/cli/input.ts","../../src/cli/line-editor.ts","../../src/cli/terminal.ts","../../src/cli/context.ts","../../src/cli/bridge.ts","../../src/cli/tokenize.ts","../../src/cli/shell.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { TerminalBridge } from './bridge';\n\nconst stringify = (value: unknown): string => {\n if (typeof value === 'string') {\n return value;\n }\n if (value instanceof Error) {\n return value.stack ?? value.message;\n }\n\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst format = (args: ReadonlyArray<unknown>): string => args.map(stringify).join(' ');\n\n/**\n * Routes Effect's `Console` to the terminal.\n *\n * `@effect/cli` renders help, usage errors, and wizard output as ANSI text through this service,\n * which xterm interprets natively — so the browser gets the same styled output as a shell.\n */\nexport const make = (bridge: TerminalBridge): Console.Console => {\n const write = (args: ReadonlyArray<unknown>) => bridge.write(format(args) + '\\n');\n\n const unsafe: Console.UnsafeConsole = {\n assert: (condition, ...args) => {\n if (!condition) {\n write(['Assertion failed:', ...args]);\n }\n },\n clear: () => bridge.clear(),\n count: () => {},\n countReset: () => {},\n debug: (...args) => write(args),\n dir: (item) => write([item]),\n dirxml: (...args) => write(args),\n error: (...args) => write(args),\n group: (...args) => write(args),\n groupCollapsed: (...args) => write(args),\n groupEnd: () => {},\n info: (...args) => write(args),\n log: (...args) => write(args),\n table: (tabularData) => write([tabularData]),\n time: () => {},\n timeEnd: () => {},\n timeLog: (_label, ...args) => write(args),\n trace: (...args) => write(args),\n warn: (...args) => write(args),\n };\n\n return Console.Console.of({\n [Console.TypeId]: Console.TypeId,\n assert: (condition, ...args) => Effect.sync(() => unsafe.assert(condition, ...args)),\n clear: Effect.sync(() => unsafe.clear()),\n count: (label) => Effect.sync(() => unsafe.count(label)),\n countReset: (label) => Effect.sync(() => unsafe.countReset(label)),\n debug: (...args) => Effect.sync(() => unsafe.debug(...args)),\n dir: (item, options) => Effect.sync(() => unsafe.dir(item, options)),\n dirxml: (...args) => Effect.sync(() => unsafe.dirxml(...args)),\n error: (...args) => Effect.sync(() => unsafe.error(...args)),\n group: (options) => Effect.sync(() => unsafe.group(options?.label)),\n groupEnd: Effect.sync(() => unsafe.groupEnd()),\n info: (...args) => Effect.sync(() => unsafe.info(...args)),\n log: (...args) => Effect.sync(() => unsafe.log(...args)),\n table: (tabularData, properties) => Effect.sync(() => unsafe.table(tabularData, properties)),\n time: (label) => Effect.sync(() => unsafe.time(label)),\n timeEnd: (label) => Effect.sync(() => unsafe.timeEnd(label)),\n timeLog: (label, ...args) => Effect.sync(() => unsafe.timeLog(label, ...args)),\n trace: (...args) => Effect.sync(() => unsafe.trace(...args)),\n warn: (...args) => Effect.sync(() => unsafe.warn(...args)),\n unsafe,\n });\n};\n\n/**\n * `Console.log` resolves against the `currentServices` fiber ref rather than the layer context, so\n * this must go through `setConsole` — providing the tag with `Layer.succeed` is silently ignored.\n */\nexport const layer = (bridge: TerminalBridge): Layer.Layer<never> => Console.setConsole(make(bridge));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Option from 'effect/Option';\n\ntype KeyOptions = {\n input?: string;\n ctrl?: boolean;\n meta?: boolean;\n shift?: boolean;\n};\n\nconst makeInput = (\n name: string,\n { input, ctrl = false, meta = false, shift = false }: KeyOptions = {},\n): Terminal.UserInput => ({\n input: Option.fromNullable(input),\n key: { name, ctrl, meta, shift },\n});\n\n/**\n * Control characters that name a key directly rather than resolving to a ctrl-modified letter.\n */\nconst CONTROL_KEYS: Record<string, string> = {\n '\\r': 'return',\n '\\n': 'return',\n '\\t': 'tab',\n '\\b': 'backspace',\n '\\x7f': 'backspace',\n};\n\n/**\n * CSI/SS3 sequences (minus the leading escape) emitted by xterm for navigation keys.\n * Ordered longest-first so `[3~` is matched before a shorter entry sharing its prefix.\n */\nconst ESCAPE_SEQUENCES: ReadonlyArray<readonly [string, string]> = [\n ['[1~', 'home'],\n ['[3~', 'delete'],\n ['[4~', 'end'],\n ['[5~', 'pageup'],\n ['[6~', 'pagedown'],\n ['[A', 'up'],\n ['[B', 'down'],\n ['[C', 'right'],\n ['[D', 'left'],\n ['[F', 'end'],\n ['[H', 'home'],\n ['OA', 'up'],\n ['OB', 'down'],\n ['OC', 'right'],\n ['OD', 'left'],\n];\n\nconst matchEscapeSequence = (data: string, index: number): { name: string; length: number } | undefined => {\n for (const [sequence, name] of ESCAPE_SEQUENCES) {\n if (data.startsWith(sequence, index)) {\n return { name, length: sequence.length };\n }\n }\n\n return undefined;\n};\n\n/**\n * Decodes a chunk of xterm `onData` output into the keypress events that `@effect/platform`\n * consumers (notably `@effect/cli` prompts) expect, using the same key names as Node's readline.\n *\n * Decoding the raw data stream rather than `onKey` DOM events is what makes paste work: a pasted\n * string arrives as one chunk and expands to one event per character.\n */\nexport const decodeInput = (data: string): Terminal.UserInput[] => {\n const inputs: Terminal.UserInput[] = [];\n let index = 0;\n\n while (index < data.length) {\n const char = data[index];\n\n if (char === '\\x1b') {\n const escape = matchEscapeSequence(data, index + 1);\n if (escape) {\n inputs.push(makeInput(escape.name));\n index += escape.length + 1;\n continue;\n }\n\n // A lone escape followed by a printable character is how alt-modified keys arrive.\n const next = data[index + 1];\n if (next !== undefined && next >= ' ' && next !== '\\x7f') {\n inputs.push(makeInput(next.toLowerCase(), { input: next, meta: true }));\n index += 2;\n continue;\n }\n\n inputs.push(makeInput('escape'));\n index += 1;\n continue;\n }\n\n const control = CONTROL_KEYS[char];\n if (control) {\n inputs.push(makeInput(control));\n index += 1;\n continue;\n }\n\n const code = char.charCodeAt(0);\n if (code < 0x20) {\n inputs.push(makeInput(String.fromCharCode(code + 0x60), { ctrl: true }));\n index += 1;\n continue;\n }\n\n const lower = char.toLowerCase();\n inputs.push(\n makeInput(char === ' ' ? 'space' : lower, {\n input: char,\n shift: char !== lower,\n }),\n );\n index += 1;\n }\n\n return inputs;\n};\n\n/**\n * Ctrl-C and Ctrl-D end an input stream, matching the platform-node default.\n */\nexport const isQuitInput = (input: Terminal.UserInput): boolean =>\n input.key.ctrl && (input.key.name === 'c' || input.key.name === 'd');\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Terminal from '@effect/platform/Terminal';\nimport * as Effect from 'effect/Effect';\nimport * as Option from 'effect/Option';\n\nimport type { TerminalBridge } from './bridge';\n\nexport type LineResult =\n | { readonly type: 'line'; readonly value: string }\n | { readonly type: 'cancelled' }\n | { readonly type: 'eof' };\n\nexport type ReadLineOptions = {\n /**\n * Rendered before the editable buffer and redrawn on every keystroke.\n */\n prompt?: string;\n /**\n * Previously entered lines, oldest first. Mutated by the caller between reads; the editor only\n * reads it.\n */\n history?: ReadonlyArray<string>;\n};\n\n/**\n * Reads a single line, echoing keystrokes and supporting inline editing, history recall, and the\n * common readline control chords.\n *\n * Distinguishes cancellation (Ctrl-C) from end-of-input (Ctrl-D on an empty buffer) so a shell can\n * abandon the current line without exiting.\n */\nexport const readLineResult = (bridge: TerminalBridge, options: ReadLineOptions = {}): Effect.Effect<LineResult> =>\n Effect.async<LineResult>((resume) => {\n const { prompt = '', history = [] } = options;\n\n let buffer = '';\n let cursor = 0;\n let historyIndex = history.length;\n let draft = '';\n\n // Redraws the whole row; a buffer long enough to wrap will not repaint correctly.\n const render = () => {\n const trailing = buffer.length - cursor;\n bridge.write(`\\r\\x1b[K${prompt}${buffer}${trailing > 0 ? `\\x1b[${trailing}D` : ''}`);\n };\n\n const finish = (result: LineResult) => {\n unsubscribe();\n resume(Effect.succeed(result));\n };\n\n const recall = (index: number) => {\n if (historyIndex === history.length) {\n draft = buffer;\n }\n\n historyIndex = index;\n buffer = index === history.length ? draft : history[index];\n cursor = buffer.length;\n render();\n };\n\n const unsubscribe = bridge.subscribe((input) => {\n const { key } = input;\n\n if (key.ctrl) {\n switch (key.name) {\n case 'c': {\n bridge.write('^C\\n');\n finish({ type: 'cancelled' });\n return;\n }\n case 'd': {\n if (buffer.length === 0) {\n bridge.write('\\n');\n finish({ type: 'eof' });\n }\n return;\n }\n case 'a': {\n cursor = 0;\n render();\n return;\n }\n case 'e': {\n cursor = buffer.length;\n render();\n return;\n }\n case 'u': {\n buffer = buffer.slice(cursor);\n cursor = 0;\n render();\n return;\n }\n case 'k': {\n buffer = buffer.slice(0, cursor);\n render();\n return;\n }\n case 'l': {\n bridge.clear();\n render();\n return;\n }\n default:\n return;\n }\n }\n\n switch (key.name) {\n case 'return': {\n bridge.write('\\n');\n finish({ type: 'line', value: buffer });\n return;\n }\n case 'backspace': {\n if (cursor > 0) {\n buffer = buffer.slice(0, cursor - 1) + buffer.slice(cursor);\n cursor -= 1;\n render();\n }\n return;\n }\n case 'delete': {\n if (cursor < buffer.length) {\n buffer = buffer.slice(0, cursor) + buffer.slice(cursor + 1);\n render();\n }\n return;\n }\n case 'left': {\n if (cursor > 0) {\n cursor -= 1;\n render();\n }\n return;\n }\n case 'right': {\n if (cursor < buffer.length) {\n cursor += 1;\n render();\n }\n return;\n }\n case 'home': {\n cursor = 0;\n render();\n return;\n }\n case 'end': {\n cursor = buffer.length;\n render();\n return;\n }\n case 'up': {\n if (historyIndex > 0) {\n recall(historyIndex - 1);\n }\n return;\n }\n case 'down': {\n if (historyIndex < history.length) {\n recall(historyIndex + 1);\n }\n return;\n }\n case 'escape':\n case 'tab':\n return;\n }\n\n Option.match(input.input, {\n onNone: () => {},\n onSome: (char) => {\n buffer = buffer.slice(0, cursor) + char + buffer.slice(cursor);\n cursor += char.length;\n render();\n },\n });\n });\n\n render();\n\n return Effect.sync(unsubscribe);\n });\n\n/**\n * The `Terminal` service contract: a line, or a `QuitException` for either interrupt.\n */\nexport const readLine = (bridge: TerminalBridge, options: ReadLineOptions = {}) =>\n readLineResult(bridge, options).pipe(\n Effect.flatMap((result) =>\n result.type === 'line' ? Effect.succeed(result.value) : Effect.fail(new Terminal.QuitException()),\n ),\n );\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Terminal from '@effect/platform/Terminal';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Layer from 'effect/Layer';\nimport * as Mailbox from 'effect/Mailbox';\n\nimport type { TerminalBridge } from './bridge';\nimport { isQuitInput } from './input';\nimport { readLine } from './line-editor';\n\n/**\n * A `@effect/platform` `Terminal` backed by xterm.\n *\n * This is the only service in `CliApp.Environment` without a browser implementation upstream;\n * `Path` is already pure JS and `FileSystem` can be stubbed.\n */\nexport const make = (bridge: TerminalBridge): Terminal.Terminal =>\n Terminal.Terminal.of({\n columns: Effect.sync(() => bridge.columns),\n rows: Effect.sync(() => bridge.rows),\n isTTY: Effect.succeed(true),\n readInput: Effect.gen(function* () {\n const mailbox = yield* Mailbox.make<Terminal.UserInput>();\n const unsubscribe = bridge.subscribe((input) => {\n mailbox.unsafeOffer(input);\n if (isQuitInput(input)) {\n mailbox.unsafeDone(Exit.void);\n }\n });\n\n yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));\n return mailbox;\n }),\n readLine: readLine(bridge),\n display: (text) => Effect.sync(() => bridge.write(text)),\n });\n\nexport const layer = (bridge: TerminalBridge): Layer.Layer<Terminal.Terminal> =>\n Layer.succeed(Terminal.Terminal, make(bridge));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as FileSystem from '@effect/platform/FileSystem';\nimport * as Path from '@effect/platform/Path';\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Layer from 'effect/Layer';\n\nimport type { XtermBridge } from './bridge';\nimport * as XtermConsole from './console';\nimport * as XtermTerminal from './terminal';\n\n/**\n * The browser counterpart to `BunContext.layer`.\n *\n * `CliApp.Environment` is only `FileSystem | Path | Terminal`: `Path` is already pure JS upstream\n * and the CLI's browser-safe commands never touch the filesystem, leaving `Terminal` as the sole\n * service needing a real implementation. The console override is merged in too — contributing no\n * services of its own — so command output and the CLI's ANSI help text land in the terminal\n * instead of the devtools console.\n */\nexport type Provided = Terminal.Terminal | FileSystem.FileSystem | Path.Path;\n\nexport const layer = (bridge: XtermBridge): Layer.Layer<Provided> =>\n Layer.mergeAll(XtermTerminal.layer(bridge), XtermConsole.layer(bridge), FileSystem.layerNoop({}), Path.layer);\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Terminal from '@effect/platform/Terminal';\nimport type { IDisposable, Terminal as XtermTerminal } from '@xterm/xterm';\n\nimport { decodeInput } from './input';\n\nexport type InputHandler = (input: Terminal.UserInput) => void;\n\n/**\n * The surface the shell and the Effect `Terminal` service need from a terminal: a write sink and a\n * stack of keypress subscribers. Depending on this rather than the xterm class keeps the rest of\n * this module free of any renderer.\n */\nexport interface TerminalBridge {\n readonly columns: number;\n readonly rows: number;\n readonly atLineStart: boolean;\n write(text: string): void;\n clear(): void;\n subscribe(handler: InputHandler): () => void;\n}\n\n/**\n * Adapts an xterm instance to {@link TerminalBridge}.\n */\nexport class XtermBridge implements TerminalBridge {\n #terminal: XtermTerminal;\n #subscribers: InputHandler[] = [];\n #subscription: IDisposable;\n #atLineStart = true;\n\n constructor(terminal: XtermTerminal) {\n this.#terminal = terminal;\n this.#subscription = terminal.onData((data) => this.#handleData(data));\n }\n\n get columns(): number {\n return this.#terminal.cols;\n }\n\n get rows(): number {\n return this.#terminal.rows;\n }\n\n /**\n * Whether the cursor sits at the start of a row, so callers can avoid a blank line when a command\n * has already terminated its output with a newline.\n */\n get atLineStart(): boolean {\n return this.#atLineStart;\n }\n\n /**\n * Writes text, translating bare newlines to CRLF since xterm does not reset the column on `\\n`.\n */\n write(text: string): void {\n if (text.length === 0) {\n return;\n }\n\n this.#terminal.write(text.replace(/\\r?\\n/g, '\\r\\n'));\n this.#atLineStart = text.endsWith('\\n');\n }\n\n clear(): void {\n this.#terminal.write('\\x1b[2J\\x1b[H');\n this.#atLineStart = true;\n }\n\n /**\n * Subscribes to keypresses. The most recent subscriber wins, so a prompt opened by a running\n * command takes over from the shell's line editor and hands back when its scope closes.\n */\n subscribe(handler: InputHandler): () => void {\n this.#subscribers.push(handler);\n return () => {\n const index = this.#subscribers.indexOf(handler);\n if (index !== -1) {\n this.#subscribers.splice(index, 1);\n }\n };\n }\n\n dispose(): void {\n this.#subscription.dispose();\n this.#subscribers.length = 0;\n }\n\n #handleData(data: string): void {\n const handler = this.#subscribers.at(-1);\n if (!handler) {\n return;\n }\n\n for (const input of decodeInput(data)) {\n handler(input);\n }\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\n/**\n * Splits a raw input line into argv tokens. Supports single/double-quoted segments so quoted\n * strings with spaces survive. Intentionally simple — anything needing real shell semantics belongs\n * in a real shell.\n */\nexport const tokenize = (input: string): string[] => {\n const tokens: string[] = [];\n const regex = /\"([^\"]*)\"|'([^']*)'|(\\S+)/g;\n let match: RegExpExecArray | null;\n while ((match = regex.exec(input)) !== null) {\n tokens.push(match[1] ?? match[2] ?? match[3]);\n }\n\n return tokens;\n};\n\n/**\n * Translates shell-friendly aliases to their Effect CLI equivalents. The Effect CLI uses `--help`\n * rather than a `help` subcommand, but `help` and `?` are the natural things to type.\n */\nexport const rewriteHelpAliases = (tokens: ReadonlyArray<string>): string[] => {\n if (tokens.length === 0) {\n return [...tokens];\n }\n\n if (tokens[0] !== 'help' && tokens[0] !== '?') {\n return [...tokens];\n }\n\n return tokens.length === 1 ? ['--help'] : [...tokens.slice(1), '--help'];\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Command from '@effect/cli/Command';\nimport * as ValidationError from '@effect/cli/ValidationError';\nimport type * as FileSystem from '@effect/platform/FileSystem';\nimport type * as Path from '@effect/platform/Path';\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Cause from 'effect/Cause';\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\n\nimport type { TerminalBridge } from './bridge';\nimport { readLineResult } from './line-editor';\nimport { rewriteHelpAliases, tokenize } from './tokenize';\n\nconst EXIT_COMMANDS = ['exit', 'quit'];\n\n/**\n * The services `Command.run` itself needs, spelled out because `@effect/cli` only exposes the\n * equivalent alias inside its `CliApp` namespace.\n */\nexport type CliEnvironment = FileSystem.FileSystem | Path.Path | Terminal.Terminal;\n\nexport type ShellOptions<Name extends string, R, E, A> = {\n command: Command.Command<Name, R, E, A>;\n /**\n * Executable name, used in help output and as the argv[1] the Effect CLI parser skips.\n */\n name?: string;\n version?: string;\n prompt?: string;\n banner?: string;\n};\n\n/**\n * Runs a read-eval-print loop against an `@effect/cli` command tree.\n *\n * Each line is tokenized and dispatched through the same `Command.run` the binary uses, with a\n * synthetic argv prefix standing in for the two leading entries the parser discards. The command\n * tree and its layer are built once, so every command reuses the already-activated services.\n */\nexport const runShell = <Name extends string, R, E, A>(\n bridge: TerminalBridge,\n options: ShellOptions<Name, R, E, A>,\n): Effect.Effect<void, never, R | CliEnvironment> =>\n Effect.gen(function* () {\n const { command, name = 'dx', version = '0.0.0', prompt = `${name}> `, banner } = options;\n const run = Command.run(command, { name, version });\n const history: string[] = [];\n\n if (banner) {\n bridge.write(`${banner}\\n`);\n }\n\n while (true) {\n if (!bridge.atLineStart) {\n bridge.write('\\n');\n }\n\n const result = yield* readLineResult(bridge, { prompt, history });\n if (result.type === 'eof') {\n break;\n }\n if (result.type === 'cancelled') {\n continue;\n }\n\n const line = result.value.trim();\n if (line.length === 0) {\n continue;\n }\n if (EXIT_COMMANDS.includes(line)) {\n break;\n }\n\n history.push(line);\n const tokens = rewriteHelpAliases(tokenize(line));\n if (tokens.length === 0) {\n continue;\n }\n\n // Failures are reported rather than propagated so the shell survives to the next prompt.\n // Validation errors are skipped because the Effect CLI has already rendered them.\n yield* run([name, name, ...tokens]).pipe(\n Effect.catchAllCause((cause) => {\n if (Cause.isInterruptedOnly(cause)) {\n return Effect.void;\n }\n\n const failure = Cause.failureOption(cause);\n if (failure._tag === 'Some' && ValidationError.isValidationError(failure.value)) {\n return Effect.void;\n }\n\n return Console.error(Cause.pretty(cause));\n }),\n );\n }\n\n bridge.write('\\n');\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAUA,IAAM,aAAa,UAA2B;CAC5C,IAAI,OAAO,UAAU,UACnB,OAAO;CAET,IAAI,iBAAiB,OACnB,OAAO,MAAM,SAAS,MAAM;CAG9B,IAAI;EACF,OAAO,KAAK,UAAU,OAAO,MAAM,CAAC,KAAK,OAAO,KAAK;CACvD,QAAQ;EACN,OAAO,OAAO,KAAK;CACrB;AACF;AAEA,IAAM,UAAU,SAAyC,KAAK,IAAI,SAAS,CAAC,CAAC,KAAK,GAAG;;;;;;;AAQrF,IAAa,UAAQ,WAA4C;CAC/D,MAAM,SAAS,SAAiC,OAAO,MAAM,OAAO,IAAI,IAAI,IAAI;CAEhF,MAAM,SAAgC;EACpC,SAAS,WAAW,GAAG,SAAS;GAC9B,IAAI,CAAC,WACH,MAAM,CAAC,qBAAqB,GAAG,IAAI,CAAC;EAExC;EACA,aAAa,OAAO,MAAM;EAC1B,aA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;EAAQ,CAAC;EAChE,IAAI,OAAO,SAAS,OAClB;EAEF,IAAI,OAAO,SAAS,aAClB;EAGF,MAAM,OAAO,OAAO,MAAM,KAAK;EAC/B,IAAI,KAAK,WAAW,GAClB;EAEF,IAAI,cAAc,SAAS,IAAI,GAC7B;EAGF,QAAQ,KAAK,IAAI;EACjB,MAAM,SAAS,mBAAmB,SAAS,IAAI,CAAC;EAChD,IAAI,OAAO,WAAW,GACpB;EAKF,OAAO,IAAI;GAAC;GAAM;GAAM,GAAG;EAAM,CAAC,CAAC,CAAC,KAClC,OAAO,eAAe,UAAU;GAC9B,IAAI,MAAM,kBAAkB,KAAK,GAC/B,OAAO,OAAO;GAGhB,MAAM,UAAU,MAAM,cAAc,KAAK;GACzC,IAAI,QAAQ,SAAS,UAAU,gBAAgB,kBAAkB,QAAQ,KAAK,GAC5E,OAAO,OAAO;GAGhB,OAAO,QAAQ,MAAM,MAAM,OAAO,KAAK,CAAC;EAC1C,CAAC,CACH;CACF;CAEA,OAAO,MAAM,IAAI;AACnB,CAAC"}
|
|
1
|
+
{"version":3,"file":"chunk-cli.mjs","names":[],"sources":["../../src/cli/console.ts","../../src/cli/input.ts","../../src/cli/line-editor.ts","../../src/cli/terminal.ts","../../src/cli/context.ts","../../src/cli/bridge.ts","../../src/cli/tokenize.ts","../../src/cli/shell.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Layer from 'effect/Layer';\n\nimport type { TerminalBridge } from './bridge';\n\nconst stringify = (value: unknown): string => {\n if (typeof value === 'string') {\n return value;\n }\n if (value instanceof Error) {\n return value.stack ?? value.message;\n }\n\n try {\n return JSON.stringify(value, null, 2) ?? String(value);\n } catch {\n return String(value);\n }\n};\n\nconst format = (args: ReadonlyArray<unknown>): string => args.map(stringify).join(' ');\n\n/**\n * Routes Effect's `Console` to the terminal.\n *\n * `@effect/cli` renders help, usage errors, and wizard output as ANSI text through this service,\n * which xterm interprets natively — so the browser gets the same styled output as a shell.\n */\nexport const make = (bridge: TerminalBridge): Console.Console => {\n const write = (args: ReadonlyArray<unknown>) => bridge.write(format(args) + '\\n');\n\n const unsafe: Console.UnsafeConsole = {\n assert: (condition, ...args) => {\n if (!condition) {\n write(['Assertion failed:', ...args]);\n }\n },\n clear: () => bridge.clear(),\n count: () => {},\n countReset: () => {},\n debug: (...args) => write(args),\n dir: (item) => write([item]),\n dirxml: (...args) => write(args),\n error: (...args) => write(args),\n group: (...args) => write(args),\n groupCollapsed: (...args) => write(args),\n groupEnd: () => {},\n info: (...args) => write(args),\n log: (...args) => write(args),\n table: (tabularData) => write([tabularData]),\n time: () => {},\n timeEnd: () => {},\n timeLog: (_label, ...args) => write(args),\n trace: (...args) => write(args),\n warn: (...args) => write(args),\n };\n\n return Console.Console.of({\n [Console.TypeId]: Console.TypeId,\n assert: (condition, ...args) => Effect.sync(() => unsafe.assert(condition, ...args)),\n clear: Effect.sync(() => unsafe.clear()),\n count: (label) => Effect.sync(() => unsafe.count(label)),\n countReset: (label) => Effect.sync(() => unsafe.countReset(label)),\n debug: (...args) => Effect.sync(() => unsafe.debug(...args)),\n dir: (item, options) => Effect.sync(() => unsafe.dir(item, options)),\n dirxml: (...args) => Effect.sync(() => unsafe.dirxml(...args)),\n error: (...args) => Effect.sync(() => unsafe.error(...args)),\n group: (options) => Effect.sync(() => unsafe.group(options?.label)),\n groupEnd: Effect.sync(() => unsafe.groupEnd()),\n info: (...args) => Effect.sync(() => unsafe.info(...args)),\n log: (...args) => Effect.sync(() => unsafe.log(...args)),\n table: (tabularData, properties) => Effect.sync(() => unsafe.table(tabularData, properties)),\n time: (label) => Effect.sync(() => unsafe.time(label)),\n timeEnd: (label) => Effect.sync(() => unsafe.timeEnd(label)),\n timeLog: (label, ...args) => Effect.sync(() => unsafe.timeLog(label, ...args)),\n trace: (...args) => Effect.sync(() => unsafe.trace(...args)),\n warn: (...args) => Effect.sync(() => unsafe.warn(...args)),\n unsafe,\n });\n};\n\n/**\n * `Console.log` resolves against the `currentServices` fiber ref rather than the layer context, so\n * this must go through `setConsole` — providing the tag with `Layer.succeed` is silently ignored.\n */\nexport const layer = (bridge: TerminalBridge): Layer.Layer<never> => Console.setConsole(make(bridge));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Option from 'effect/Option';\n\ntype KeyOptions = {\n input?: string;\n ctrl?: boolean;\n meta?: boolean;\n shift?: boolean;\n};\n\nconst makeInput = (\n name: string,\n { input, ctrl = false, meta = false, shift = false }: KeyOptions = {},\n): Terminal.UserInput => ({\n input: Option.fromNullable(input),\n key: { name, ctrl, meta, shift },\n});\n\n/**\n * Control characters that name a key directly rather than resolving to a ctrl-modified letter.\n */\nconst CONTROL_KEYS: Record<string, string> = {\n '\\r': 'return',\n '\\n': 'return',\n '\\t': 'tab',\n '\\b': 'backspace',\n '\\x7f': 'backspace',\n};\n\n/**\n * CSI/SS3 sequences (minus the leading escape) emitted by xterm for navigation keys.\n * Ordered longest-first so `[3~` is matched before a shorter entry sharing its prefix.\n */\nconst ESCAPE_SEQUENCES: ReadonlyArray<readonly [string, string]> = [\n ['[1~', 'home'],\n ['[3~', 'delete'],\n ['[4~', 'end'],\n ['[5~', 'pageup'],\n ['[6~', 'pagedown'],\n ['[A', 'up'],\n ['[B', 'down'],\n ['[C', 'right'],\n ['[D', 'left'],\n ['[F', 'end'],\n ['[H', 'home'],\n ['OA', 'up'],\n ['OB', 'down'],\n ['OC', 'right'],\n ['OD', 'left'],\n];\n\nconst matchEscapeSequence = (data: string, index: number): { name: string; length: number } | undefined => {\n for (const [sequence, name] of ESCAPE_SEQUENCES) {\n if (data.startsWith(sequence, index)) {\n return { name, length: sequence.length };\n }\n }\n\n return undefined;\n};\n\n/**\n * Length of the unrecognized escape sequence at `index`, or zero if what follows is not one.\n *\n * The table above covers only unmodified navigation keys, so a chord like ctrl-right arrives as\n * the parameterized `\\x1b[1;5C` and matches nothing. Measuring the whole sequence lets the caller\n * discard it; decoding it byte by byte would type `1;5C` into the line instead.\n */\nconst unrecognizedEscapeLength = (data: string, index: number): number => {\n const introducer = data[index];\n if (introducer === '[') {\n // CSI: parameter and intermediate bytes up to a final byte in `@`–`~`.\n let end = index + 1;\n while (end < data.length && !(data[end] >= '@' && data[end] <= '~')) {\n end += 1;\n }\n\n return end < data.length ? end - index + 1 : data.length - index;\n }\n\n // SS3: a single final byte follows the introducer.\n if (introducer === 'O' && index + 1 < data.length) {\n return 2;\n }\n\n return 0;\n};\n\n/**\n * Decodes a chunk of xterm `onData` output into the keypress events that `@effect/platform`\n * consumers (notably `@effect/cli` prompts) expect, using the same key names as Node's readline.\n *\n * Decoding the raw data stream rather than `onKey` DOM events is what makes paste work: a pasted\n * string arrives as one chunk and expands to one event per character.\n */\nexport const decodeInput = (data: string): Terminal.UserInput[] => {\n const inputs: Terminal.UserInput[] = [];\n let index = 0;\n\n while (index < data.length) {\n const char = data[index];\n\n if (char === '\\x1b') {\n const escape = matchEscapeSequence(data, index + 1);\n if (escape) {\n inputs.push(makeInput(escape.name));\n index += escape.length + 1;\n continue;\n }\n\n const unrecognized = unrecognizedEscapeLength(data, index + 1);\n if (unrecognized > 0) {\n index += unrecognized + 1;\n continue;\n }\n\n // A lone escape followed by a printable character is how alt-modified keys arrive.\n const next = data[index + 1];\n if (next !== undefined && next >= ' ' && next !== '\\x7f') {\n inputs.push(makeInput(next.toLowerCase(), { input: next, meta: true }));\n index += 2;\n continue;\n }\n\n inputs.push(makeInput('escape'));\n index += 1;\n continue;\n }\n\n const control = CONTROL_KEYS[char];\n if (control) {\n inputs.push(makeInput(control));\n index += 1;\n continue;\n }\n\n const code = char.charCodeAt(0);\n if (code < 0x20) {\n inputs.push(makeInput(String.fromCharCode(code + 0x60), { ctrl: true }));\n index += 1;\n continue;\n }\n\n const lower = char.toLowerCase();\n inputs.push(\n makeInput(char === ' ' ? 'space' : lower, {\n input: char,\n shift: char !== lower,\n }),\n );\n index += 1;\n }\n\n return inputs;\n};\n\n/**\n * Ctrl-C and Ctrl-D end an input stream, matching the platform-node default.\n */\nexport const isQuitInput = (input: Terminal.UserInput): boolean =>\n input.key.ctrl && (input.key.name === 'c' || input.key.name === 'd');\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Terminal from '@effect/platform/Terminal';\nimport * as Effect from 'effect/Effect';\nimport * as Option from 'effect/Option';\n\nimport type { TerminalBridge } from './bridge';\n\nexport type LineResult =\n | { readonly type: 'line'; readonly value: string }\n | { readonly type: 'cancelled' }\n | { readonly type: 'eof' };\n\nexport type ReadLineOptions = {\n /**\n * Rendered before the editable buffer and redrawn on every keystroke.\n */\n prompt?: string;\n /**\n * Previously entered lines, oldest first. Mutated by the caller between reads; the editor only\n * reads it.\n */\n history?: ReadonlyArray<string>;\n};\n\n/**\n * Reads a single line, echoing keystrokes and supporting inline editing, history recall, and the\n * common readline control chords.\n *\n * Distinguishes cancellation (Ctrl-C) from end-of-input (Ctrl-D on an empty buffer) so a shell can\n * abandon the current line without exiting.\n */\nexport const readLineResult = (bridge: TerminalBridge, options: ReadLineOptions = {}): Effect.Effect<LineResult> =>\n Effect.async<LineResult>((resume) => {\n const { prompt = '', history = [] } = options;\n\n let buffer = '';\n let cursor = 0;\n let historyIndex = history.length;\n let draft = '';\n\n // Redraws the whole row; a buffer long enough to wrap will not repaint correctly.\n const render = () => {\n const trailing = buffer.length - cursor;\n bridge.write(`\\r\\x1b[K${prompt}${buffer}${trailing > 0 ? `\\x1b[${trailing}D` : ''}`);\n };\n\n const finish = (result: LineResult) => {\n unsubscribe();\n resume(Effect.succeed(result));\n };\n\n const recall = (index: number) => {\n if (historyIndex === history.length) {\n draft = buffer;\n }\n\n historyIndex = index;\n buffer = index === history.length ? draft : history[index];\n cursor = buffer.length;\n render();\n };\n\n const unsubscribe = bridge.subscribe((input) => {\n const { key } = input;\n\n if (key.ctrl) {\n switch (key.name) {\n case 'c': {\n bridge.write('^C\\n');\n finish({ type: 'cancelled' });\n return;\n }\n case 'd': {\n if (buffer.length === 0) {\n bridge.write('\\n');\n finish({ type: 'eof' });\n }\n return;\n }\n case 'a': {\n cursor = 0;\n render();\n return;\n }\n case 'e': {\n cursor = buffer.length;\n render();\n return;\n }\n case 'u': {\n buffer = buffer.slice(cursor);\n cursor = 0;\n render();\n return;\n }\n case 'k': {\n buffer = buffer.slice(0, cursor);\n render();\n return;\n }\n case 'l': {\n bridge.clear();\n render();\n return;\n }\n default:\n return;\n }\n }\n\n // Alt chords carry the bare character, so without this the editor types the `f` of alt-f\n // rather than ignoring a word motion it does not implement.\n if (key.meta) {\n return;\n }\n\n switch (key.name) {\n case 'return': {\n bridge.write('\\n');\n finish({ type: 'line', value: buffer });\n return;\n }\n case 'backspace': {\n if (cursor > 0) {\n buffer = buffer.slice(0, cursor - 1) + buffer.slice(cursor);\n cursor -= 1;\n render();\n }\n return;\n }\n case 'delete': {\n if (cursor < buffer.length) {\n buffer = buffer.slice(0, cursor) + buffer.slice(cursor + 1);\n render();\n }\n return;\n }\n case 'left': {\n if (cursor > 0) {\n cursor -= 1;\n render();\n }\n return;\n }\n case 'right': {\n if (cursor < buffer.length) {\n cursor += 1;\n render();\n }\n return;\n }\n case 'home': {\n cursor = 0;\n render();\n return;\n }\n case 'end': {\n cursor = buffer.length;\n render();\n return;\n }\n case 'up': {\n if (historyIndex > 0) {\n recall(historyIndex - 1);\n }\n return;\n }\n case 'down': {\n if (historyIndex < history.length) {\n recall(historyIndex + 1);\n }\n return;\n }\n case 'escape':\n case 'tab':\n return;\n }\n\n Option.match(input.input, {\n onNone: () => {},\n onSome: (char) => {\n buffer = buffer.slice(0, cursor) + char + buffer.slice(cursor);\n cursor += char.length;\n render();\n },\n });\n });\n\n render();\n\n return Effect.sync(unsubscribe);\n });\n\n/**\n * The `Terminal` service contract: a line, or a `QuitException` for either interrupt.\n */\nexport const readLine = (bridge: TerminalBridge, options: ReadLineOptions = {}) =>\n readLineResult(bridge, options).pipe(\n Effect.flatMap((result) =>\n result.type === 'line' ? Effect.succeed(result.value) : Effect.fail(new Terminal.QuitException()),\n ),\n );\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Terminal from '@effect/platform/Terminal';\nimport * as Effect from 'effect/Effect';\nimport * as Exit from 'effect/Exit';\nimport * as Layer from 'effect/Layer';\nimport * as Mailbox from 'effect/Mailbox';\n\nimport type { TerminalBridge } from './bridge';\nimport { isQuitInput } from './input';\nimport { readLine } from './line-editor';\n\n/**\n * A `@effect/platform` `Terminal` backed by xterm.\n *\n * This is the only service in `CliApp.Environment` without a browser implementation upstream;\n * `Path` is already pure JS and `FileSystem` can be stubbed.\n */\nexport const make = (bridge: TerminalBridge): Terminal.Terminal =>\n Terminal.Terminal.of({\n columns: Effect.sync(() => bridge.columns),\n rows: Effect.sync(() => bridge.rows),\n isTTY: Effect.succeed(true),\n readInput: Effect.gen(function* () {\n const mailbox = yield* Mailbox.make<Terminal.UserInput>();\n const unsubscribe = bridge.subscribe((input) => {\n mailbox.unsafeOffer(input);\n if (isQuitInput(input)) {\n mailbox.unsafeDone(Exit.void);\n }\n });\n\n yield* Effect.addFinalizer(() => Effect.sync(unsubscribe));\n return mailbox;\n }),\n readLine: readLine(bridge),\n display: (text) => Effect.sync(() => bridge.write(text)),\n });\n\nexport const layer = (bridge: TerminalBridge): Layer.Layer<Terminal.Terminal> =>\n Layer.succeed(Terminal.Terminal, make(bridge));\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as FileSystem from '@effect/platform/FileSystem';\nimport * as Path from '@effect/platform/Path';\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Layer from 'effect/Layer';\n\nimport type { XtermBridge } from './bridge';\nimport * as XtermConsole from './console';\nimport * as XtermTerminal from './terminal';\n\n/**\n * The browser counterpart to `BunContext.layer`.\n *\n * `CliApp.Environment` is only `FileSystem | Path | Terminal`: `Path` is already pure JS upstream\n * and the CLI's browser-safe commands never touch the filesystem, leaving `Terminal` as the sole\n * service needing a real implementation. The console override is merged in too — contributing no\n * services of its own — so command output and the CLI's ANSI help text land in the terminal\n * instead of the devtools console.\n */\nexport type Provided = Terminal.Terminal | FileSystem.FileSystem | Path.Path;\n\nexport const layer = (bridge: XtermBridge): Layer.Layer<Provided> =>\n Layer.mergeAll(XtermTerminal.layer(bridge), XtermConsole.layer(bridge), FileSystem.layerNoop({}), Path.layer);\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport type * as Terminal from '@effect/platform/Terminal';\nimport type { IDisposable, Terminal as XtermTerminal } from '@xterm/xterm';\n\nimport { decodeInput } from './input';\n\nexport type InputHandler = (input: Terminal.UserInput) => void;\n\n/**\n * The surface the shell and the Effect `Terminal` service need from a terminal: a write sink and a\n * stack of keypress subscribers. Depending on this rather than the xterm class keeps the rest of\n * this module free of any renderer.\n */\nexport interface TerminalBridge {\n readonly columns: number;\n readonly rows: number;\n readonly atLineStart: boolean;\n write(text: string): void;\n clear(): void;\n subscribe(handler: InputHandler): () => void;\n}\n\n/**\n * Adapts an xterm instance to {@link TerminalBridge}.\n */\nexport class XtermBridge implements TerminalBridge {\n #terminal: XtermTerminal;\n #subscribers: InputHandler[] = [];\n #subscription: IDisposable;\n #atLineStart = true;\n\n constructor(terminal: XtermTerminal) {\n this.#terminal = terminal;\n this.#subscription = terminal.onData((data) => this.#handleData(data));\n }\n\n get columns(): number {\n return this.#terminal.cols;\n }\n\n get rows(): number {\n return this.#terminal.rows;\n }\n\n /**\n * Whether the cursor sits at the start of a row, so callers can avoid a blank line when a command\n * has already terminated its output with a newline.\n */\n get atLineStart(): boolean {\n return this.#atLineStart;\n }\n\n /**\n * Writes text, translating bare newlines to CRLF since xterm does not reset the column on `\\n`.\n */\n write(text: string): void {\n if (text.length === 0) {\n return;\n }\n\n this.#terminal.write(text.replace(/\\r?\\n/g, '\\r\\n'));\n this.#atLineStart = text.endsWith('\\n');\n }\n\n clear(): void {\n this.#terminal.write('\\x1b[2J\\x1b[H');\n this.#atLineStart = true;\n }\n\n /**\n * Subscribes to keypresses. The most recent subscriber wins, so a prompt opened by a running\n * command takes over from the shell's line editor and hands back when its scope closes.\n */\n subscribe(handler: InputHandler): () => void {\n this.#subscribers.push(handler);\n return () => {\n const index = this.#subscribers.indexOf(handler);\n if (index !== -1) {\n this.#subscribers.splice(index, 1);\n }\n };\n }\n\n dispose(): void {\n this.#subscription.dispose();\n this.#subscribers.length = 0;\n }\n\n #handleData(data: string): void {\n const handler = this.#subscribers.at(-1);\n if (!handler) {\n return;\n }\n\n for (const input of decodeInput(data)) {\n handler(input);\n }\n }\n}\n","//\n// Copyright 2026 DXOS.org\n//\n\n/**\n * Splits a raw input line into argv tokens. Supports single/double-quoted segments so quoted\n * strings with spaces survive. Intentionally simple — anything needing real shell semantics belongs\n * in a real shell.\n */\nexport const tokenize = (input: string): string[] => {\n const tokens: string[] = [];\n const regex = /\"([^\"]*)\"|'([^']*)'|(\\S+)/g;\n let match: RegExpExecArray | null;\n while ((match = regex.exec(input)) !== null) {\n tokens.push(match[1] ?? match[2] ?? match[3]);\n }\n\n return tokens;\n};\n\n/**\n * Translates shell-friendly aliases to their Effect CLI equivalents. The Effect CLI uses `--help`\n * rather than a `help` subcommand, but `help` and `?` are the natural things to type.\n */\nexport const rewriteHelpAliases = (tokens: ReadonlyArray<string>): string[] => {\n if (tokens.length === 0) {\n return [...tokens];\n }\n\n if (tokens[0] !== 'help' && tokens[0] !== '?') {\n return [...tokens];\n }\n\n return tokens.length === 1 ? ['--help'] : [...tokens.slice(1), '--help'];\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Command from '@effect/cli/Command';\nimport * as ValidationError from '@effect/cli/ValidationError';\nimport type * as FileSystem from '@effect/platform/FileSystem';\nimport type * as Path from '@effect/platform/Path';\nimport type * as Terminal from '@effect/platform/Terminal';\nimport * as Cause from 'effect/Cause';\nimport * as Console from 'effect/Console';\nimport * as Effect from 'effect/Effect';\nimport * as Option from 'effect/Option';\n\nimport type { TerminalBridge } from './bridge';\nimport { readLineResult } from './line-editor';\nimport { rewriteHelpAliases, tokenize } from './tokenize';\n\nconst EXIT_COMMANDS = ['exit', 'quit'];\n\n/**\n * The services `Command.run` itself needs, spelled out because `@effect/cli` only exposes the\n * equivalent alias inside its `CliApp` namespace.\n */\nexport type CliEnvironment = FileSystem.FileSystem | Path.Path | Terminal.Terminal;\n\nexport type ShellOptions<Name extends string, R, E, A> = {\n command: Command.Command<Name, R, E, A>;\n /**\n * Executable name, used in help output and as the argv[1] the Effect CLI parser skips.\n */\n name?: string;\n version?: string;\n prompt?: string;\n banner?: string;\n};\n\n/**\n * Runs a read-eval-print loop against an `@effect/cli` command tree.\n *\n * Each line is tokenized and dispatched through the same `Command.run` the binary uses, with a\n * synthetic argv prefix standing in for the two leading entries the parser discards. The command\n * tree and its layer are built once, so every command reuses the already-activated services.\n */\nexport const runShell = <Name extends string, R, E, A>(\n bridge: TerminalBridge,\n options: ShellOptions<Name, R, E, A>,\n): Effect.Effect<void, never, R | CliEnvironment> =>\n Effect.gen(function* () {\n const { command, name = 'dx', version = '0.0.0', prompt = `${name}> `, banner } = options;\n const run = Command.run(command, { name, version });\n const history: string[] = [];\n\n if (banner) {\n bridge.write(`${banner}\\n`);\n }\n\n while (true) {\n if (!bridge.atLineStart) {\n bridge.write('\\n');\n }\n\n const result = yield* readLineResult(bridge, { prompt, history });\n if (result.type === 'eof') {\n break;\n }\n if (result.type === 'cancelled') {\n continue;\n }\n\n const line = result.value.trim();\n if (line.length === 0) {\n continue;\n }\n if (EXIT_COMMANDS.includes(line)) {\n break;\n }\n\n history.push(line);\n const tokens = rewriteHelpAliases(tokenize(line));\n if (tokens.length === 0) {\n continue;\n }\n\n // Failures are reported rather than propagated so the shell survives to the next prompt.\n // Validation errors are skipped because the Effect CLI has already rendered them.\n yield* run([name, name, ...tokens]).pipe(\n Effect.catchAllCause((cause) => {\n if (Cause.isInterruptedOnly(cause)) {\n return Effect.void;\n }\n\n const failure = Cause.failureOption(cause);\n if (Option.isSome(failure) && ValidationError.isValidationError(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MAAM,KAAK;EAC/B,IAAI,KAAK,WAAW,GAClB;EAEF,IAAI,cAAc,SAAS,IAAI,GAC7B;EAGF,QAAQ,KAAK,IAAI;EACjB,MAAM,SAAS,mBAAmB,SAAS,IAAI,CAAC;EAChD,IAAI,OAAO,WAAW,GACpB;EAKF,OAAO,IAAI;GAAC;GAAM;GAAM,GAAG;EAAM,CAAC,CAAC,CAAC,KAClC,OAAO,eAAe,UAAU;GAC9B,IAAI,MAAM,kBAAkB,KAAK,GAC/B,OAAO,OAAO;GAGhB,MAAM,UAAU,MAAM,cAAc,KAAK;GACzC,IAAI,OAAO,OAAO,OAAO,KAAK,gBAAgB,kBAAkB,QAAQ,KAAK,GAC3E,OAAO,OAAO;GAGhB,OAAO,QAAQ,MAAM,MAAM,OAAO,KAAK,CAAC;EAC1C,CAAC,CACH;CACF;CAEA,OAAO,MAAM,IAAI;AACnB,CAAC"}
|
package/dist/lib/index.mjs
CHANGED
|
@@ -133,9 +133,10 @@ var Terminal = ({ classNames, command, layer: layer$1, name, version, prompt, ba
|
|
|
133
133
|
cancelAnimationFrame(frame);
|
|
134
134
|
themeObserver.disconnect();
|
|
135
135
|
observer.disconnect();
|
|
136
|
-
Effect.runFork(Fiber.interrupt(fiber))
|
|
137
|
-
|
|
138
|
-
|
|
136
|
+
Effect.runFork(Fiber.interrupt(fiber).pipe(Effect.andThen(Effect.sync(() => {
|
|
137
|
+
bridge.dispose();
|
|
138
|
+
xterm.dispose();
|
|
139
|
+
}))));
|
|
139
140
|
};
|
|
140
141
|
}, [
|
|
141
142
|
command,
|
package/dist/lib/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../../src/components/Terminal/theme.ts","../../src/components/Terminal/Terminal.tsx"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport type { ITheme } from '@xterm/xterm';\n\n/**\n * ANSI slots mapped onto the design system's semantic hues. The theme carries one text weight per\n * hue, so a bright slot reuses its base token rather than inventing a second shade; the neutral\n * slots step through the greys so dim output stays legible against the surface.\n */\nconst ANSI_TOKENS = {\n black: '--color-subdued',\n red: '--color-red-text',\n green: '--color-green-text',\n yellow: '--color-yellow-text',\n blue: '--color-blue-text',\n magenta: '--color-fuchsia-text',\n cyan: '--color-cyan-text',\n white: '--color-description',\n brightBlack: '--color-description',\n brightRed: '--color-red-text',\n brightGreen: '--color-green-text',\n brightYellow: '--color-yellow-text',\n brightBlue: '--color-blue-text',\n brightMagenta: '--color-fuchsia-text',\n brightCyan: '--color-cyan-text',\n brightWhite: '--color-base-fg',\n} as const;\n\n/**\n * Resolves design system color tokens to the hex form xterm's parser accepts.\n *\n * Two steps, because neither alone suffices: a probe element inside the token scope turns\n * `light-dark(var(…))` into an absolute computed color, then a canvas rasterizes that color — which\n * the theme states in `oklch()` — down to sRGB channels.\n */\nconst makeResolver = (scope: Element) => {\n const probe = document.createElement('span');\n probe.style.display = 'none';\n scope.appendChild(probe);\n\n const context = document.createElement('canvas').getContext('2d', { willReadFrequently: true });\n\n const resolve = (token: string): string | undefined => {\n probe.style.color = `var(${token})`;\n const computed = getComputedStyle(probe).color;\n if (!context || computed.length === 0) {\n return undefined;\n }\n\n context.clearRect(0, 0, 1, 1);\n context.fillStyle = computed;\n context.fillRect(0, 0, 1, 1);\n const [red, green, blue] = context.getImageData(0, 0, 1, 1).data;\n return `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;\n };\n\n return { resolve, dispose: () => probe.remove() };\n};\n\n/**\n * Builds an xterm theme from the design system tokens in scope at `element`, so the terminal\n * follows light/dark and any theme override rather than carrying its own palette.\n */\nexport const createXtermTheme = (element: Element): ITheme => {\n const { resolve, dispose } = makeResolver(element);\n try {\n const surface = resolve('--color-base-surface');\n const foreground = resolve('--color-base-fg');\n const ansi = Object.fromEntries(Object.entries(ANSI_TOKENS).map(([slot, token]) => [slot, resolve(token)])) as Pick<\n ITheme,\n keyof typeof ANSI_TOKENS\n >;\n\n return {\n background: surface,\n foreground,\n cursor: foreground,\n cursorAccent: surface,\n selectionBackground: resolve('--color-accent-surface'),\n ...ansi,\n };\n } finally {\n dispose();\n }\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport '@xterm/xterm/css/xterm.css';\n\nimport type * as Command from '@effect/cli/Command';\nimport { FitAddon } from '@xterm/addon-fit';\nimport { Terminal as Xterm } from '@xterm/xterm';\nimport * as Effect from 'effect/Effect';\nimport * as Fiber from 'effect/Fiber';\nimport type * as Layer from 'effect/Layer';\nimport React, { useEffect, useRef } from 'react';\n\nimport { type ThemedClassName } from '@dxos/react-ui';\nimport { mx } from '@dxos/ui-theme';\n\nimport { XtermBridge, XtermContext, runShell } from '../../cli';\nimport { createXtermTheme } from './theme';\n\nexport type TerminalProps<Name extends string, R, E, A> = ThemedClassName<{\n /**\n * Root of an `@effect/cli` command tree; typically built with `Command.withSubcommands`.\n */\n command: Command.Command<Name, R, E, A>;\n /**\n * Services the command handlers need beyond the platform services provided internally, which is\n * why the terminal's own environment is excluded from what this must supply.\n */\n layer: Layer.Layer<Exclude<R, XtermContext.Provided>, any, never>;\n name?: string;\n version?: string;\n prompt?: string;\n banner?: string;\n fontSize?: number;\n}>;\n\n/**\n * Terminal emulator hosting an `@effect/cli` command tree entirely in the browser.\n *\n * The command tree and its layer are built once per mount, so state held by the services (a DXOS\n * client, for instance) persists across commands the way it does in a long-lived shell.\n */\nexport const Terminal = <Name extends string, R, E, A>({\n classNames,\n command,\n layer,\n name,\n version,\n prompt,\n banner,\n fontSize = 13,\n}: TerminalProps<Name, R, E, A>) => {\n const containerRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n // The face must come from the mono token rather than the container, whose inherited UI face is\n // proportional and would leave xterm's fixed cells ragged.\n const styles = getComputedStyle(container);\n const xterm = new Xterm({\n fontSize,\n fontFamily: styles.getPropertyValue('--font-mono').trim() || 'monospace',\n cursorBlink: true,\n });\n\n const fitAddon = new FitAddon();\n xterm.loadAddon(fitAddon);\n xterm.open(container);\n\n // Fitting a zero-sized container pins the terminal to its one-column minimum, and fitting\n // before xterm's render service exists throws, so the observer's initial callback — which\n // lands once the element is measurable and the renderer is up — drives the first fit too.\n const fit = () => {\n if (container.clientWidth > 0 && container.clientHeight > 0) {\n fitAddon.fit();\n }\n };\n\n // Drive the palette from the design system tokens so the terminal tracks light/dark without a\n // scheme of its own. The theme class lands on the document from a provider whose effect runs\n // after this one, so the palette is applied on the next frame and refreshed on every change.\n const applyTheme = () => {\n xterm.options.theme = createXtermTheme(container);\n };\n\n const frame = requestAnimationFrame(applyTheme);\n const themeObserver = new MutationObserver(applyTheme);\n themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });\n\n xterm.focus();\n\n const bridge = new XtermBridge(xterm);\n const shell = runShell(bridge, { command, name, version, prompt, banner }).pipe(\n Effect.provide(XtermContext.layer(bridge)),\n Effect.provide(layer),\n );\n const fiber = Effect.runFork(Effect.scoped(shell));\n\n const observer = new ResizeObserver(fit);\n observer.observe(container);\n\n return () => {\n cancelAnimationFrame(frame);\n themeObserver.disconnect();\n observer.disconnect();\n Effect.runFork(Fiber.interrupt(fiber));\n bridge.dispose();\n xterm.dispose();\n };\n }, [command, layer, name, version, prompt, banner, fontSize]);\n\n return <div ref={containerRef} className={mx('grow w-full h-full overflow-hidden bg-base-surface', classNames)} />;\n};\n"],"mappings":";;;;;;;;;;;;;;;AAWA,IAAM,cAAc;CAClB,OAAO;CACP,KAAK;CACL,OAAO;CACP,QAAQ;CACR,MAAM;CACN,SAAS;CACT,MAAM;CACN,OAAO;CACP,aAAa;CACb,WAAW;CACX,aAAa;CACb,cAAc;CACd,YAAY;CACZ,eAAe;CACf,YAAY;CACZ,aAAa;AACf;;;;;;;;AASA,IAAM,gBAAgB,UAAmB;CACvC,MAAM,QAAQ,SAAS,cAAc,MAAM;CAC3C,MAAM,MAAM,UAAU;CACtB,MAAM,YAAY,KAAK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"sources":["../../src/components/Terminal/theme.ts","../../src/components/Terminal/Terminal.tsx"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport type { ITheme } from '@xterm/xterm';\n\n/**\n * ANSI slots mapped onto the design system's semantic hues. The theme carries one text weight per\n * hue, so a bright slot reuses its base token rather than inventing a second shade; the neutral\n * slots step through the greys so dim output stays legible against the surface.\n */\nconst ANSI_TOKENS = {\n black: '--color-subdued',\n red: '--color-red-text',\n green: '--color-green-text',\n yellow: '--color-yellow-text',\n blue: '--color-blue-text',\n magenta: '--color-fuchsia-text',\n cyan: '--color-cyan-text',\n white: '--color-description',\n brightBlack: '--color-description',\n brightRed: '--color-red-text',\n brightGreen: '--color-green-text',\n brightYellow: '--color-yellow-text',\n brightBlue: '--color-blue-text',\n brightMagenta: '--color-fuchsia-text',\n brightCyan: '--color-cyan-text',\n brightWhite: '--color-base-fg',\n} as const;\n\n/**\n * Resolves design system color tokens to the hex form xterm's parser accepts.\n *\n * Two steps, because neither alone suffices: a probe element inside the token scope turns\n * `light-dark(var(…))` into an absolute computed color, then a canvas rasterizes that color — which\n * the theme states in `oklch()` — down to sRGB channels.\n */\nconst makeResolver = (scope: Element) => {\n const probe = document.createElement('span');\n probe.style.display = 'none';\n scope.appendChild(probe);\n\n const context = document.createElement('canvas').getContext('2d', { willReadFrequently: true });\n\n const resolve = (token: string): string | undefined => {\n probe.style.color = `var(${token})`;\n const computed = getComputedStyle(probe).color;\n if (!context || computed.length === 0) {\n return undefined;\n }\n\n context.clearRect(0, 0, 1, 1);\n context.fillStyle = computed;\n context.fillRect(0, 0, 1, 1);\n const [red, green, blue] = context.getImageData(0, 0, 1, 1).data;\n return `#${[red, green, blue].map((channel) => channel.toString(16).padStart(2, '0')).join('')}`;\n };\n\n return { resolve, dispose: () => probe.remove() };\n};\n\n/**\n * Builds an xterm theme from the design system tokens in scope at `element`, so the terminal\n * follows light/dark and any theme override rather than carrying its own palette.\n */\nexport const createXtermTheme = (element: Element): ITheme => {\n const { resolve, dispose } = makeResolver(element);\n try {\n const surface = resolve('--color-base-surface');\n const foreground = resolve('--color-base-fg');\n const ansi = Object.fromEntries(Object.entries(ANSI_TOKENS).map(([slot, token]) => [slot, resolve(token)])) as Pick<\n ITheme,\n keyof typeof ANSI_TOKENS\n >;\n\n return {\n background: surface,\n foreground,\n cursor: foreground,\n cursorAccent: surface,\n selectionBackground: resolve('--color-accent-surface'),\n ...ansi,\n };\n } finally {\n dispose();\n }\n};\n","//\n// Copyright 2026 DXOS.org\n//\n\nimport '@xterm/xterm/css/xterm.css';\n\nimport type * as Command from '@effect/cli/Command';\nimport { FitAddon } from '@xterm/addon-fit';\nimport { Terminal as Xterm } from '@xterm/xterm';\nimport * as Effect from 'effect/Effect';\nimport * as Fiber from 'effect/Fiber';\nimport type * as Layer from 'effect/Layer';\nimport React, { useEffect, useRef } from 'react';\n\nimport { type ThemedClassName } from '@dxos/react-ui';\nimport { mx } from '@dxos/ui-theme';\n\nimport { XtermBridge, XtermContext, runShell } from '../../cli';\nimport { createXtermTheme } from './theme';\n\nexport type TerminalProps<Name extends string, R, E, A> = ThemedClassName<{\n /**\n * Root of an `@effect/cli` command tree; typically built with `Command.withSubcommands`.\n */\n command: Command.Command<Name, R, E, A>;\n /**\n * Services the command handlers need beyond the platform services provided internally, which is\n * why the terminal's own environment is excluded from what this must supply.\n *\n * Construction must not fail: the shell runs on a forked fiber with no surface to report a layer\n * error on, so a host that can fail to build its services has to resolve that before mounting.\n */\n layer: Layer.Layer<Exclude<R, XtermContext.Provided>, never, never>;\n name?: string;\n version?: string;\n prompt?: string;\n banner?: string;\n fontSize?: number;\n}>;\n\n/**\n * Terminal emulator hosting an `@effect/cli` command tree entirely in the browser.\n *\n * The command tree and its layer are built once per mount, so state held by the services (a DXOS\n * client, for instance) persists across commands the way it does in a long-lived shell.\n */\nexport const Terminal = <Name extends string, R, E, A>({\n classNames,\n command,\n layer,\n name,\n version,\n prompt,\n banner,\n fontSize = 13,\n}: TerminalProps<Name, R, E, A>) => {\n const containerRef = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container) {\n return;\n }\n\n // The face must come from the mono token rather than the container, whose inherited UI face is\n // proportional and would leave xterm's fixed cells ragged.\n const styles = getComputedStyle(container);\n const xterm = new Xterm({\n fontSize,\n fontFamily: styles.getPropertyValue('--font-mono').trim() || 'monospace',\n cursorBlink: true,\n });\n\n const fitAddon = new FitAddon();\n xterm.loadAddon(fitAddon);\n xterm.open(container);\n\n // Fitting a zero-sized container pins the terminal to its one-column minimum, and fitting\n // before xterm's render service exists throws, so the observer's initial callback — which\n // lands once the element is measurable and the renderer is up — drives the first fit too.\n const fit = () => {\n if (container.clientWidth > 0 && container.clientHeight > 0) {\n fitAddon.fit();\n }\n };\n\n // Drive the palette from the design system tokens so the terminal tracks light/dark without a\n // scheme of its own. The theme class lands on the document from a provider whose effect runs\n // after this one, so the palette is applied on the next frame and refreshed on every change.\n const applyTheme = () => {\n xterm.options.theme = createXtermTheme(container);\n };\n\n const frame = requestAnimationFrame(applyTheme);\n const themeObserver = new MutationObserver(applyTheme);\n themeObserver.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style'] });\n\n xterm.focus();\n\n const bridge = new XtermBridge(xterm);\n const shell = runShell(bridge, { command, name, version, prompt, banner }).pipe(\n Effect.provide(XtermContext.layer(bridge)),\n Effect.provide(layer),\n );\n const fiber = Effect.runFork(Effect.scoped(shell));\n\n const observer = new ResizeObserver(fit);\n observer.observe(container);\n\n return () => {\n cancelAnimationFrame(frame);\n themeObserver.disconnect();\n observer.disconnect();\n // Disposal is chained onto the interrupt rather than run beside it: the shell's finalizers\n // still write their last output through the bridge, which throws once xterm is gone.\n Effect.runFork(\n Fiber.interrupt(fiber).pipe(\n Effect.andThen(\n Effect.sync(() => {\n bridge.dispose();\n xterm.dispose();\n }),\n ),\n ),\n );\n };\n }, [command, layer, name, version, prompt, banner, fontSize]);\n\n return <div ref={containerRef} className={mx('grow w-full h-full overflow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ACvC,SAAS,QAAQ,SAAS;EAE1B,aAAa;GACX,qBAAqB,KAAK;GAC1B,cAAc,WAAW;GACzB,SAAS,WAAW;GAGpB,OAAO,QACL,MAAM,UAAU,KAAK,CAAC,CAAC,KACrB,OAAO,QACL,OAAO,WAAW;IAChB,OAAO,QAAQ;IACf,MAAM,QAAQ;GAChB,CAAC,CACH,CACF,CACF;EACF;CACF,GAAG;EAAC;EAAS;EAAO;EAAM;EAAS;EAAQ;EAAQ;CAAQ,CAAC;CAE5D,OAAO,oBAAC,OAAD;EAAK,KAAK;EAAc,WAAW,GAAG,sDAAsD,UAAU;CAAI,CAAA;AACnH"}
|
package/dist/lib/testing.mjs
CHANGED
|
@@ -1,28 +1,31 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import * as Duration from "effect/Duration";
|
|
3
|
+
import { EffectEx } from "@dxos/effect";
|
|
1
4
|
//#region src/testing.ts
|
|
2
|
-
var POLL_INTERVAL = 50;
|
|
3
|
-
var DEFAULT_TIMEOUT =
|
|
5
|
+
var POLL_INTERVAL = Duration.millis(50);
|
|
6
|
+
var DEFAULT_TIMEOUT = Duration.seconds(15);
|
|
4
7
|
/**
|
|
5
8
|
* Reads the terminal's visible contents as plain text.
|
|
6
9
|
*
|
|
7
10
|
* xterm splits a row into a span per style run and pads with non-breaking spaces, so a story cannot
|
|
8
11
|
* assert against it with a plain text query — this flattens a row back to what the user sees.
|
|
9
12
|
*/
|
|
10
|
-
var readTerminal = (element) => Array.from(element.querySelectorAll(".xterm-rows > div")).map((row) => (row.textContent ?? "").replace(/
|
|
13
|
+
var readTerminal = (element) => Array.from(element.querySelectorAll(".xterm-rows > div")).map((row) => (row.textContent ?? "").replace(/\u00a0/g, " ").trimEnd()).join("\n");
|
|
11
14
|
/**
|
|
12
15
|
* The hidden textarea xterm reads keystrokes from.
|
|
13
16
|
*/
|
|
14
17
|
var getTerminalInput = (element) => element.querySelector(".xterm-helper-textarea");
|
|
18
|
+
var pollTerminal = (element, text) => Effect.suspend(() => readTerminal(element).includes(text) ? Effect.void : Effect.sleep(POLL_INTERVAL).pipe(Effect.flatMap(() => pollTerminal(element, text))));
|
|
15
19
|
/**
|
|
16
20
|
* Resolves once the terminal shows `text`, or throws with the current contents.
|
|
21
|
+
*
|
|
22
|
+
* The terminal is painted by a fiber writing into the DOM, so there is nothing to await — polling
|
|
23
|
+
* is the only way to observe it. Returns a promise because a story's `play` is the boundary.
|
|
17
24
|
*/
|
|
18
|
-
var waitForTerminal =
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
await new Promise((resolve) => setTimeout(resolve, POLL_INTERVAL));
|
|
23
|
-
} while (Date.now() < deadline);
|
|
24
|
-
throw new Error(`Timed out waiting for "${text}". Terminal contents:\n${readTerminal(element)}`);
|
|
25
|
-
};
|
|
25
|
+
var waitForTerminal = (element, text, timeout = DEFAULT_TIMEOUT) => EffectEx.runPromise(pollTerminal(element, text).pipe(Effect.timeoutFail({
|
|
26
|
+
duration: timeout,
|
|
27
|
+
onTimeout: () => /* @__PURE__ */ new Error(`Timed out waiting for "${text}". Terminal contents:\n${readTerminal(element)}`)
|
|
28
|
+
})));
|
|
26
29
|
/**
|
|
27
30
|
* Types a command and submits it.
|
|
28
31
|
*
|
package/dist/lib/testing.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.mjs","names":[],"sources":["../../src/testing.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nconst POLL_INTERVAL = 50;\nconst DEFAULT_TIMEOUT =
|
|
1
|
+
{"version":3,"file":"testing.mjs","names":[],"sources":["../../src/testing.ts"],"sourcesContent":["//\n// Copyright 2026 DXOS.org\n//\n\nimport * as Duration from 'effect/Duration';\nimport * as Effect from 'effect/Effect';\n\nimport { EffectEx } from '@dxos/effect';\n\nconst POLL_INTERVAL = Duration.millis(50);\nconst DEFAULT_TIMEOUT = Duration.seconds(15);\n\n/**\n * Reads the terminal's visible contents as plain text.\n *\n * xterm splits a row into a span per style run and pads with non-breaking spaces, so a story cannot\n * assert against it with a plain text query — this flattens a row back to what the user sees.\n */\nexport const readTerminal = (element: HTMLElement): string =>\n Array.from(element.querySelectorAll('.xterm-rows > div'))\n .map((row) => (row.textContent ?? '').replace(/\\u00a0/g, ' ').trimEnd())\n .join('\\n');\n\n/**\n * The hidden textarea xterm reads keystrokes from.\n */\nexport const getTerminalInput = (element: HTMLElement): HTMLTextAreaElement | null =>\n element.querySelector('.xterm-helper-textarea');\n\nconst pollTerminal = (element: HTMLElement, text: string): Effect.Effect<void> =>\n Effect.suspend(() =>\n readTerminal(element).includes(text)\n ? Effect.void\n : Effect.sleep(POLL_INTERVAL).pipe(Effect.flatMap(() => pollTerminal(element, text))),\n );\n\n/**\n * Resolves once the terminal shows `text`, or throws with the current contents.\n *\n * The terminal is painted by a fiber writing into the DOM, so there is nothing to await — polling\n * is the only way to observe it. Returns a promise because a story's `play` is the boundary.\n */\nexport const waitForTerminal = (element: HTMLElement, text: string, timeout = DEFAULT_TIMEOUT): Promise<void> =>\n EffectEx.runPromise(\n pollTerminal(element, text).pipe(\n Effect.timeoutFail({\n duration: timeout,\n onTimeout: () => new Error(`Timed out waiting for \"${text}\". Terminal contents:\\n${readTerminal(element)}`),\n }),\n ),\n );\n\n/**\n * Types a command and submits it.\n *\n * Waits for the input to echo before sending the return, because the shell drops keystrokes that\n * arrive before its line editor has subscribed — without this the command silently never runs.\n */\nexport const runCommand = async (\n element: HTMLElement,\n command: string,\n keyboard: (text: string) => Promise<unknown>,\n): Promise<void> => {\n getTerminalInput(element)?.focus();\n await keyboard(command);\n await waitForTerminal(element, command);\n await keyboard('{Enter}');\n};\n"],"mappings":";;;;AASA,IAAM,gBAAgB,SAAS,OAAO,EAAE;AACxC,IAAM,kBAAkB,SAAS,QAAQ,EAAE;;;;;;;AAQ3C,IAAa,gBAAgB,YAC3B,MAAM,KAAK,QAAQ,iBAAiB,mBAAmB,CAAC,CAAA,CACrD,KAAK,SAAS,IAAI,eAAe,GAAA,CAAI,QAAQ,WAAW,GAAG,CAAC,CAAC,QAAQ,CAAC,CAAA,CACtE,KAAK,IAAI;;;;AAKd,IAAa,oBAAoB,YAC/B,QAAQ,cAAc,wBAAwB;AAEhD,IAAM,gBAAgB,SAAsB,SAC1C,OAAO,cACL,aAAa,OAAO,CAAC,CAAC,SAAS,IAAI,IAC/B,OAAO,OACP,OAAO,MAAM,aAAa,CAAC,CAAC,KAAK,OAAO,cAAc,aAAa,SAAS,IAAI,CAAC,CAAC,CACxF;;;;;;;AAQF,IAAa,mBAAmB,SAAsB,MAAc,UAAU,oBAC5E,SAAS,WACP,aAAa,SAAS,IAAI,CAAC,CAAC,KAC1B,OAAO,YAAY;CACjB,UAAU;CACV,iCAAiB,IAAI,MAAM,0BAA0B,KAAK,yBAAyB,aAAa,OAAO,GAAG;AAC5G,CAAC,CACH,CACF;;;;;;;AAQF,IAAa,aAAa,OACxB,SACA,SACA,aACkB;CAClB,iBAAiB,OAAO,CAAC,EAAE,MAAM;CACjC,MAAM,SAAS,OAAO;CACtB,MAAM,gBAAgB,SAAS,OAAO;CACtC,MAAM,SAAS,SAAS;AAC1B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../../../src/cli/input.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,QAAQ,MAAM,2BAA2B,CAAC;
|
|
1
|
+
{"version":3,"file":"input.d.ts","sourceRoot":"","sources":["../../../../src/cli/input.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,KAAK,QAAQ,MAAM,2BAA2B,CAAC;AAwF3D;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,SAAU,MAAM,KAAG,QAAQ,CAAC,SAAS,EA2D5D,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,WAAW,UAAW,QAAQ,CAAC,SAAS,KAAG,OACc,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"line-editor.d.ts","sourceRoot":"","sources":["../../../../src/cli/line-editor.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,QAAQ,MAAM,2BAA2B,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GAC9B;IAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAA;CAAE,CAAC;AAE7B,MAAM,MAAM,eAAe,GAAG;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACjC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,WAAY,cAAc,YAAW,eAAe,KAAQ,MAAM,CAAC,MAAM,CAAC,UAAU,
|
|
1
|
+
{"version":3,"file":"line-editor.d.ts","sourceRoot":"","sources":["../../../../src/cli/line-editor.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,QAAQ,MAAM,2BAA2B,CAAC;AACtD,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAE/C,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;CAAE,GACjD;IAAE,QAAQ,CAAC,IAAI,EAAE,WAAW,CAAA;CAAE,GAC9B;IAAE,QAAQ,CAAC,IAAI,EAAE,KAAK,CAAA;CAAE,CAAC;AAE7B,MAAM,MAAM,eAAe,GAAG;IAC5B;;OAEG;IACH,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,OAAO,CAAC,EAAE,aAAa,CAAC,MAAM,CAAC,CAAC;CACjC,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,cAAc,WAAY,cAAc,YAAW,eAAe,KAAQ,MAAM,CAAC,MAAM,CAAC,UAAU,CAgK3G,CAAC;AAEL;;GAEG;AACH,eAAO,MAAM,QAAQ,WAAY,cAAc,YAAW,eAAe,yDAKtE,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../../src/cli/shell.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,OAAO,MAAM,qBAAqB,CAAC;AAE/C,OAAO,KAAK,KAAK,UAAU,MAAM,6BAA6B,CAAC;AAC/D,OAAO,KAAK,KAAK,IAAI,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,KAAK,QAAQ,MAAM,2BAA2B,CAAC;AAG3D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;
|
|
1
|
+
{"version":3,"file":"shell.d.ts","sourceRoot":"","sources":["../../../../src/cli/shell.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,OAAO,MAAM,qBAAqB,CAAC;AAE/C,OAAO,KAAK,KAAK,UAAU,MAAM,6BAA6B,CAAC;AAC/D,OAAO,KAAK,KAAK,IAAI,MAAM,uBAAuB,CAAC;AACnD,OAAO,KAAK,KAAK,QAAQ,MAAM,2BAA2B,CAAC;AAG3D,OAAO,KAAK,MAAM,MAAM,eAAe,CAAC;AAGxC,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,UAAU,CAAC;AAM/C;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,UAAU,GAAG,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,QAAQ,CAAC;AAEnF,MAAM,MAAM,YAAY,CAAC,IAAI,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI;IACvD,OAAO,EAAE,OAAO,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IACxC;;OAEG;IACH,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;CACjB,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,QAAQ,GAAI,IAAI,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,UAC3C,cAAc,WACb,YAAY,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,KACnC,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE,KAAK,EAAE,CAAC,GAAG,cAAc,CAwD5C,CAAC"}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tokenize.test.d.ts","sourceRoot":"","sources":["../../../../src/cli/tokenize.test.ts"],"names":[],"mappings":""}
|
|
@@ -12,8 +12,11 @@ export type TerminalProps<Name extends string, R, E, A> = ThemedClassName<{
|
|
|
12
12
|
/**
|
|
13
13
|
* Services the command handlers need beyond the platform services provided internally, which is
|
|
14
14
|
* why the terminal's own environment is excluded from what this must supply.
|
|
15
|
+
*
|
|
16
|
+
* Construction must not fail: the shell runs on a forked fiber with no surface to report a layer
|
|
17
|
+
* error on, so a host that can fail to build its services has to resolve that before mounting.
|
|
15
18
|
*/
|
|
16
|
-
layer: Layer.Layer<Exclude<R, XtermContext.Provided>,
|
|
19
|
+
layer: Layer.Layer<Exclude<R, XtermContext.Provided>, never, never>;
|
|
17
20
|
name?: string;
|
|
18
21
|
version?: string;
|
|
19
22
|
prompt?: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Terminal.d.ts","sourceRoot":"","sources":["../../../../../src/components/Terminal/Terminal.tsx"],"names":[],"mappings":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,EAAE,MAAM,CAAC;IACd,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB,CAAC,CAAC;AAEH;;;;;GAKG;AACH,eAAO,MAAM,QAAQ,GAAI,IAAI,SAAS,MAAM,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,4EASlD,aAAa,CAAC,IAAI,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,CAAC,sBA0E9B,CAAC"}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import * as Duration from 'effect/Duration';
|
|
1
2
|
/**
|
|
2
3
|
* Reads the terminal's visible contents as plain text.
|
|
3
4
|
*
|
|
@@ -11,8 +12,11 @@ export declare const readTerminal: (element: HTMLElement) => string;
|
|
|
11
12
|
export declare const getTerminalInput: (element: HTMLElement) => HTMLTextAreaElement | null;
|
|
12
13
|
/**
|
|
13
14
|
* Resolves once the terminal shows `text`, or throws with the current contents.
|
|
15
|
+
*
|
|
16
|
+
* The terminal is painted by a fiber writing into the DOM, so there is nothing to await — polling
|
|
17
|
+
* is the only way to observe it. Returns a promise because a story's `play` is the boundary.
|
|
14
18
|
*/
|
|
15
|
-
export declare const waitForTerminal: (element: HTMLElement, text: string, timeout?:
|
|
19
|
+
export declare const waitForTerminal: (element: HTMLElement, text: string, timeout?: Duration.Duration) => Promise<void>;
|
|
16
20
|
/**
|
|
17
21
|
* Types a command and submits it.
|
|
18
22
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../../src/testing.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../../../src/testing.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,QAAQ,MAAM,iBAAiB,CAAC;AAQ5C;;;;;GAKG;AACH,eAAO,MAAM,YAAY,YAAa,WAAW,KAAG,MAGrC,CAAC;AAEhB;;GAEG;AACH,eAAO,MAAM,gBAAgB,YAAa,WAAW,KAAG,mBAAmB,GAAG,IAC7B,CAAC;AASlD;;;;;GAKG;AACH,eAAO,MAAM,eAAe,YAAa,WAAW,QAAQ,MAAM,kCAA8B,OAAO,CAAC,IAAI,CAQzG,CAAC;AAEJ;;;;;GAKG;AACH,eAAO,MAAM,UAAU,YACZ,WAAW,WACX,MAAM,YACL,CAAC,IAAI,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,KAC3C,OAAO,CAAC,IAAI,CAKd,CAAC"}
|