@noldova/terminal 0.0.11 → 0.0.13

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.
@@ -7,7 +7,7 @@
7
7
  */
8
8
  import "@noldova/context.core";
9
9
  import path from "node:path";
10
- import { Resources as ProtocolResources, TerminalCompletion, TerminalCompletionItem, TerminalCompletionKind, TerminalMissingCommands, TerminalShellKind } from "@noldova/terminal.protocol";
10
+ import { Resources as ProtocolResources, TerminalCompletion, TerminalCompletionItem, TerminalCompletionKind, TerminalMissingCommands } from "@noldova/terminal.protocol";
11
11
  import { CommandFailedException } from "../exceptions/command-failed.exception.js";
12
12
  import { CommandListing } from "../models/command-listing.js";
13
13
  import { CompletionCandidate } from "../models/completion-candidate.js";
@@ -41,26 +41,26 @@ export class CompletionSource {
41
41
  this.adapters = new ShellAdapters(this.isWindows);
42
42
  this.shared = new SharedReads(fileSystem);
43
43
  }
44
- async completeAsync(key, kind, line, cursor, folder, environment, shellNames, shellBuiltins) {
45
- const shell = this.adapters.of(kind);
44
+ async completeAsync(key, target, line, cursor, folder, environment, shellNames, shellBuiltins) {
45
+ const shell = this.adapters.of(target);
46
46
  if (Object.isNull(shell) || this.stuck.includes(key))
47
47
  return new TerminalCompletion(cursor, []);
48
48
  const builtins = shell.listBuiltins(shellNames, shellBuiltins);
49
49
  return this.readAsync(key, t => this.completeLineAsync(t, shell, builtins, line.slice(0, cursor), folder, environment));
50
50
  }
51
- adapterOf(kind) {
52
- return this.adapters.of(kind);
51
+ adapterOf(target) {
52
+ return this.adapters.of(target);
53
53
  }
54
- toLocalFolder(folder, kind, environment) {
55
- const shell = this.adapters.of(kind);
54
+ toLocalFolder(folder, target, environment) {
55
+ const shell = this.adapters.of(target);
56
56
  return Object.isNull(shell) ? folder : shell.toLocalPath(folder, this.readVariable(environment, Resources.temporaryFolderVariable) ?? null);
57
57
  }
58
- followsCommand(kind, line, cursor) {
59
- const shell = this.adapters.of(kind);
58
+ followsCommand(target, line, cursor) {
59
+ const shell = this.adapters.of(target);
60
60
  return !Object.isNull(shell) && shell.readWords(line.slice(0, cursor)).words.length > 0;
61
61
  }
62
- addOptions(completion, kind, line, cursor, options) {
63
- const ignoresCase = this.isWindows || this.adapters.of(kind)?.ignoresCase === true;
62
+ addOptions(completion, target, line, cursor, options) {
63
+ const ignoresCase = this.adapters.of(target)?.ignoresCase === true;
64
64
  const toKey = (text) => ignoresCase ? text.toLowerCase() : text;
65
65
  const prefix = toKey(line.slice(completion.replaceFrom, cursor));
66
66
  const labels = new Set(completion.items.map(t => t.label));
@@ -73,24 +73,24 @@ export class CompletionSource {
73
73
  const items = [...completion.items, ...added].sort((a, b) => a.label.localeCompare(b.label, Resources.sortLocale));
74
74
  return new TerminalCompletion(completion.replaceFrom, items.slice(0, ProtocolResources.maximumCompletionItems));
75
75
  }
76
- async findMissingAsync(key, shell, prompt, kind, folder, names, shellNames, environment) {
77
- const adapter = this.adapters.of(kind);
76
+ async findMissingAsync(key, shell, prompt, target, folder, names, shellNames, environment) {
77
+ const adapter = this.adapters.of(target);
78
78
  if (Object.isNull(adapter) || adapter.looksUpMissing || Object.isNull(shellNames) || this.stuck.includes(key))
79
79
  return new TerminalMissingCommands([]);
80
80
  const takesBareNames = adapter.takesBareNames;
81
- const search = JSON.stringify([kind, this.readVariable(environment, Resources.pathVariable),
81
+ const search = JSON.stringify([target.kind, target.name, this.readVariable(environment, Resources.pathVariable),
82
82
  this.readVariable(environment, Resources.pathExtensionsVariable)]);
83
83
  const last = this.listed.get(shell);
84
84
  const listed = !Object.isUndefined(last) && last.prompt === prompt && last.search === search ? last.commands : null;
85
85
  return this.readAsync(key, async (reads) => {
86
- const commands = listed ?? (await this.listCommandsAsync(reads, [], environment, takesBareNames)).map(t => t.value);
86
+ const commands = listed ?? (await this.listCommandsAsync(reads, adapter, [], environment, takesBareNames)).map(t => t.value);
87
87
  if (reads.wasCutShort)
88
88
  return new TerminalMissingCommands([]);
89
89
  this.listed.set(shell, new CommandListing(prompt, search, commands));
90
90
  const found = [...shellNames, ...commands];
91
- const known = new Set(this.isWindows ? found.map(t => t.toLowerCase()) : found);
92
- const unknown = names.filter(t => !this.isPath(t) && !t.startsWith(Resources.helperNamePrefix)
93
- && !known.has(this.toCommandName(t)) && !this.hasSuffixAlias(t, shellNames));
91
+ const known = new Set(adapter.takesWindowsNames ? found.map(t => t.toLowerCase()) : found);
92
+ const unknown = names.filter(t => !this.isPath(adapter, t) && !t.startsWith(Resources.helperNamePrefix)
93
+ && !known.has(this.toCommandName(adapter, t)) && !this.hasSuffixAlias(t, shellNames));
94
94
  const missing = unknown.length > 0 && shellNames.has(Resources.autocdName)
95
95
  ? await this.dropFoldersAsync(reads, adapter, folder, environment, unknown) : unknown;
96
96
  return new TerminalMissingCommands(reads.wasCutShort ? [] : missing);
@@ -116,7 +116,7 @@ export class CompletionSource {
116
116
  const answers = !Object.isUndefined(last) && last.shellNames === shellNames && last.search === search ? last.answers : new Map();
117
117
  this.looked.set(shell, new PowerShellLookup(shellNames, search, answers));
118
118
  const known = new Set([...shellNames].map(t => t.toLowerCase()));
119
- const asked = [...new Set(names)].filter(t => !this.isPath(t) && Resources.powerShellLookupNamePattern.test(t)
119
+ const asked = [...new Set(names)].filter(t => !this.isPath(null, t) && Resources.powerShellLookupNamePattern.test(t)
120
120
  && !known.has(t.toLowerCase()) && !known.has(`${Resources.powerShellImplicitVerb}${t}`.toLowerCase()));
121
121
  const unasked = asked.filter(t => !answers.has(t));
122
122
  if (unasked.length > 0 && !this.lookups.has(shell)) {
@@ -150,8 +150,8 @@ export class CompletionSource {
150
150
  if (Object.isNull(workFolder))
151
151
  return names;
152
152
  const folders = new Set((await reads.readEntriesAsync(workFolder)).filter(t => t.isFolder)
153
- .map(t => this.isWindows ? t.name.toLowerCase() : t.name));
154
- return names.filter(t => !folders.has(this.isWindows ? t.toLowerCase() : t));
153
+ .map(t => shell.takesWindowsNames ? t.name.toLowerCase() : t.name));
154
+ return names.filter(t => !folders.has(shell.takesWindowsNames ? t.toLowerCase() : t));
155
155
  }
156
156
  async readAsync(key, list) {
157
157
  const reads = new BoundedReads(this.shared, Resources.completionReadMilliseconds);
@@ -172,38 +172,63 @@ export class CompletionSource {
172
172
  const shellLine = escapesWildcards
173
173
  ? new ShellLine(typed.words, typed.start, typed.value.replace(Resources.powerShellEscapedWildcards, Resources.completionSourceEscapedWildcardReplacement), typed.quote, typed.startsQuoted)
174
174
  : typed;
175
- const ignoresCase = this.isWindows || shell.ignoresCase;
175
+ const ignoresCase = shell.ignoresCase;
176
176
  const prefix = ignoresCase ? shellLine.value.toLowerCase() : shellLine.value;
177
177
  const expandsHome = shell.expandsHome(shellLine.startsQuoted);
178
- const keepsHome = expandsHome && this.isHome(shellLine.value);
178
+ const keepsHome = expandsHome && this.isHome(shell, shellLine.value);
179
179
  const candidates = (await this.listAsync(reads, shell, builtins, shellLine, folder, environment, expandsHome))
180
180
  .filter(t => (ignoresCase ? t.value.toLowerCase() : t.value).startsWith(prefix));
181
181
  const items = [...new Map(candidates.map(t => [t.value, t])).values()]
182
- .sort((a, b) => a.label.localeCompare(b.label, Resources.sortLocale))
182
+ .sort((a, b) => a.rank - b.rank || a.label.localeCompare(b.label, Resources.sortLocale))
183
183
  .flatMap(t => {
184
184
  const text = shell.writeWord(t.value, shellLine.quote, t.closesQuote, escapesWildcards && (t.kind === TerminalCompletionKind.File || t.kind === TerminalCompletionKind.Folder), keepsHome);
185
185
  return text.length <= ProtocolResources.maximumPathLength && !ProtocolResources.controlCharacters.test(text)
186
- ? [new TerminalCompletionItem(text, t.label, t.kind)]
186
+ ? [new TerminalCompletionItem(text, t.label, t.kind, t.description)]
187
187
  : [];
188
188
  });
189
189
  return new TerminalCompletion(shellLine.start, items.slice(0, ProtocolResources.maximumCompletionItems));
190
190
  }
191
191
  listAsync(reads, shell, builtins, shellLine, folder, environment, expandsHome) {
192
- const words = shellLine.words.map(t => this.toCommandName(t));
193
- if (words.length === 0 && !this.isPath(shellLine.value))
194
- return this.listCommandsAsync(reads, builtins, environment);
192
+ const words = shellLine.words.map(t => this.toCommandName(shell, t));
193
+ if (words.length === 0 && !this.isPath(shell, shellLine.value))
194
+ return this.listCommandsAsync(reads, shell, builtins, environment);
195
195
  const temporaryFolder = this.readVariable(environment, Resources.temporaryFolderVariable) ?? null;
196
196
  const workFolder = shell.toLocalPath(folder, temporaryFolder);
197
197
  if (!Object.isNull(workFolder) && words.length === Resources.subcommandWordCount && words[0] === Resources.gitCommand && Resources.gitBranchCommands.some(t => shellLine.words[1] === t))
198
- return this.listBranchesAsync(reads, workFolder, environment);
198
+ return this.listBranchesAsync(reads, shell, workFolder, environment);
199
199
  if (!Object.isNull(workFolder) && words.length === Resources.subcommandWordCount && words[0] === Resources.npmCommand && Resources.npmRunCommands.some(t => shellLine.words[1] === t))
200
200
  return this.listScriptsAsync(reads, workFolder);
201
- return this.listPathsAsync(reads, shell, shellLine.value, workFolder, expandsHome, temporaryFolder);
201
+ const home = this.homeOf(shell, environment);
202
+ const paths = this.listPathsAsync(reads, shell, shellLine.value, workFolder, expandsHome ? home : null, temporaryFolder);
203
+ const command = words.length === 1 ? words[0] : undefined;
204
+ if (Object.isUndefined(command) || this.isPath(shell, shellLine.value))
205
+ return paths;
206
+ return this.listToolWordsAsync(reads, shell, command, workFolder, paths);
202
207
  }
203
- async listPathsAsync(reads, shell, value, workFolder, expandsHome, temporaryFolder) {
204
- const end = Math.max(value.lastIndexOf(Resources.posixSeparator), this.isWindows ? value.lastIndexOf(Resources.windowsSeparator) : -1);
208
+ async listToolWordsAsync(reads, shell, command, workFolder, paths) {
209
+ const tool = Resources.toolCommands.find(t => t.name === command);
210
+ if (!Object.isUndefined(tool))
211
+ return [...tool.words.map(t => new CompletionCandidate(t.name, t.name, TerminalCompletionKind.Command, true, t.description)), ...(await paths).map(t => t.ranked(1))];
212
+ if (command === Resources.nodeCommand)
213
+ return (await paths).map(t => t.kind === TerminalCompletionKind.File && Resources.nodeScriptExtensions.includes(this.paths.extname(t.label).toLowerCase()) ? t : t.ranked(1));
214
+ if (command === Resources.npxCommand && !Object.isNull(workFolder))
215
+ return [...await this.listPackageBinsAsync(reads, shell, workFolder), ...(await paths).map(t => t.ranked(1))];
216
+ return paths;
217
+ }
218
+ async listPackageBinsAsync(reads, shell, folder) {
219
+ let current = folder;
220
+ for (;;) {
221
+ const entries = await reads.readEntriesAsync(this.paths.join(current, ...Resources.packageBinFolder));
222
+ const names = [...new Set(entries.filter(t => !t.isFolder).map(t => shell.takesWindowsNames ? t.name.replace(Resources.packageBinExtension, "") : t.name))];
223
+ if (names.length > 0 || this.paths.dirname(current) === current)
224
+ return names.map(t => new CompletionCandidate(t, t, TerminalCompletionKind.Command, true));
225
+ current = this.paths.dirname(current);
226
+ }
227
+ }
228
+ async listPathsAsync(reads, shell, value, workFolder, home, temporaryFolder) {
229
+ const end = Math.max(value.lastIndexOf(Resources.posixSeparator), shell.takesWindowsNames ? value.lastIndexOf(Resources.windowsSeparator) : -1);
205
230
  const typedFolder = value.slice(0, end + 1);
206
- const folder = Object.isNull(workFolder) ? null : this.toFolder(shell, typedFolder, workFolder, expandsHome, temporaryFolder);
231
+ const folder = Object.isNull(workFolder) ? null : this.toFolder(shell, typedFolder, workFolder, home, temporaryFolder);
207
232
  if (Object.isNull(folder))
208
233
  return [];
209
234
  const separator = end >= 0 ? value.charAt(end) : shell.separator;
@@ -214,12 +239,12 @@ export class CompletionSource {
214
239
  ? new CompletionCandidate(`${typedFolder}${t.name}${separator}`, `${t.name}${separator}`, TerminalCompletionKind.Folder, false)
215
240
  : new CompletionCandidate(`${typedFolder}${t.name}`, t.name, TerminalCompletionKind.File, true));
216
241
  }
217
- async listCommandsAsync(reads, builtins, environment, takesBareNames = false) {
218
- const extensions = this.isWindows
242
+ async listCommandsAsync(reads, shell, builtins, environment, takesBareNames = false) {
243
+ const extensions = shell.takesWindowsNames
219
244
  ? (this.readVariable(environment, Resources.pathExtensionsVariable) ?? Resources.defaultPathExtensions).toLowerCase()
220
245
  .split(path.win32.delimiter).filter(t => t !== "")
221
246
  : null;
222
- const entries = await Promise.all(this.searchFolders(environment).map(t => reads.readEntriesAsync(t)));
247
+ const entries = await Promise.all(this.searchFolders(shell, environment).map(t => reads.readEntriesAsync(t)));
223
248
  const names = [...builtins];
224
249
  for (const entry of entries.flat()) {
225
250
  const extension = this.paths.extname(entry.name).toLowerCase();
@@ -228,13 +253,14 @@ export class CompletionSource {
228
253
  }
229
254
  return names.map(t => new CompletionCandidate(t, t, TerminalCompletionKind.Command, true));
230
255
  }
231
- async listBranchesAsync(reads, folder, environment) {
232
- const git = await this.findProgramAsync(reads, this.isWindows ? Resources.gitExecutableFile : Resources.gitCommand, environment);
256
+ async listBranchesAsync(reads, shell, folder, environment) {
257
+ const git = await this.findProgramAsync(reads, shell, shell.takesWindowsNames ? Resources.gitExecutableFile : Resources.gitCommand, environment);
233
258
  if (Object.isNull(git))
234
259
  return [];
260
+ const call = shell.toProgramCall(git, [Resources.completionSourceGitFolderArgument, folder, ...Resources.gitBranchArguments]);
235
261
  let output;
236
262
  try {
237
- output = await this.runner.runAsync(git, [Resources.completionSourceGitFolderArgument, folder, ...Resources.gitBranchArguments], Resources.completionCommandMilliseconds);
263
+ output = await this.runner.runAsync(call.file, call.args, Resources.completionCommandMilliseconds);
238
264
  }
239
265
  catch (error) {
240
266
  if (error instanceof CommandFailedException)
@@ -273,16 +299,23 @@ export class CompletionSource {
273
299
  return [];
274
300
  return Object.keys(scripts).map(t => new CompletionCandidate(t, t, TerminalCompletionKind.Script, true));
275
301
  }
276
- async findProgramAsync(reads, name, environment) {
277
- for (const folder of this.searchFolders(environment)) {
302
+ async findProgramAsync(reads, shell, name, environment) {
303
+ for (const folder of this.searchFolders(shell, environment)) {
278
304
  const file = this.paths.join(folder, name);
279
305
  if (await reads.isProgramAsync(file))
280
306
  return file;
281
307
  }
282
308
  return null;
283
309
  }
284
- searchFolders(environment) {
285
- return [...new Set((this.readVariable(environment, Resources.pathVariable) ?? "").split(this.paths.delimiter).filter(t => this.paths.isAbsolute(t)))];
310
+ searchFolders(shell, environment) {
311
+ return [...new Set(shell.readSearchFolders(this.readVariable(environment, Resources.pathVariable) ?? ""))];
312
+ }
313
+ homeOf(shell, environment) {
314
+ if (shell.takesWindowsNames)
315
+ return this.homeFolder;
316
+ const home = this.readVariable(environment, Resources.homeVariable);
317
+ const folder = !Object.isUndefined(home) && path.posix.isAbsolute(home) ? home : this.homeFolder;
318
+ return path.posix.isAbsolute(folder) ? shell.toLocalPath(folder, null) : null;
286
319
  }
287
320
  async toLongModulePathsAsync(variables) {
288
321
  const modulePath = variables[Resources.modulePathVariable];
@@ -301,19 +334,19 @@ export class CompletionSource {
301
334
  readVariable(environment, name) {
302
335
  return this.isWindows ? Object.entries(environment).find(([t]) => t.toUpperCase() === name)?.[1] : environment[name];
303
336
  }
304
- toFolder(shell, typedFolder, workFolder, expandsHome, temporaryFolder) {
305
- const folder = expandsHome && this.isHome(typedFolder) ? this.paths.join(this.homeFolder, typedFolder.slice(Resources.homePrefix.length)) : shell.toLocalPath(typedFolder, temporaryFolder);
337
+ toFolder(shell, typedFolder, workFolder, home, temporaryFolder) {
338
+ const folder = !Object.isNull(home) && this.isHome(shell, typedFolder) ? this.paths.join(home, typedFolder.slice(Resources.homePrefix.length)) : shell.toLocalPath(typedFolder, temporaryFolder);
306
339
  return Object.isNull(folder) ? null : this.paths.resolve(workFolder, folder);
307
340
  }
308
- toCommandName(word) {
309
- const name = this.paths.basename(word);
310
- return this.isWindows ? name.toLowerCase().replace(Resources.windowsProgramExtension, "") : name;
341
+ toCommandName(shell, word) {
342
+ const name = (shell.takesWindowsNames ? path.win32 : path.posix).basename(word);
343
+ return shell.takesWindowsNames ? name.toLowerCase().replace(Resources.windowsProgramExtension, "") : name;
311
344
  }
312
- isHome(value) {
313
- return value.startsWith(Resources.homePrefix) || (this.isWindows && value.startsWith(Resources.windowsHomePrefix));
345
+ isHome(shell, value) {
346
+ return value.startsWith(Resources.homePrefix) || (shell.takesWindowsNames && value.startsWith(Resources.windowsHomePrefix));
314
347
  }
315
- isPath(value) {
316
- return value.includes(Resources.posixSeparator) || (this.isWindows && value.includes(Resources.windowsSeparator))
348
+ isPath(shell, value) {
349
+ return value.includes(Resources.posixSeparator) || ((shell?.takesWindowsNames ?? this.isWindows) && value.includes(Resources.windowsSeparator))
317
350
  || value.startsWith(Resources.hiddenPrefix) || value.startsWith(Resources.homeWord);
318
351
  }
319
352
  }
@@ -7,6 +7,7 @@
7
7
  */
8
8
  import "@noldova/context.core";
9
9
  import path from "node:path";
10
+ import { ProgramCall } from "../models/program-call.js";
10
11
  import { Resources } from "../resources.js";
11
12
  import { ShellWords } from "./shell-words.js";
12
13
  export class PosixShellAdapter {
@@ -14,12 +15,18 @@ export class PosixShellAdapter {
14
15
  separator = Resources.posixSeparator;
15
16
  takesBareNames;
16
17
  optionsKeys;
18
+ folderKeys;
19
+ takesWindowsNames;
17
20
  looksUpMissing = false;
18
21
  isGitBash;
19
- constructor(isWindows, optionsKeys, isBash) {
22
+ paths;
23
+ constructor(isWindows, optionsKeys, folderKeys, isBash) {
20
24
  this.ignoresCase = isWindows;
21
25
  this.optionsKeys = optionsKeys;
26
+ this.folderKeys = folderKeys;
22
27
  this.isGitBash = isWindows && isBash;
28
+ this.takesWindowsNames = isWindows;
29
+ this.paths = isWindows ? path.win32 : path.posix;
23
30
  this.takesBareNames = this.isGitBash;
24
31
  }
25
32
  readWords(line) {
@@ -49,4 +56,10 @@ export class PosixShellAdapter {
49
56
  return null;
50
57
  return Resources.formatCompletionSourceWindowsDrivePath(value.charAt(1).toUpperCase(), value.slice(Resources.completionSourceGitBashDrivePrefixLength).replaceAll(Resources.posixSeparator, Resources.windowsSeparator));
51
58
  }
59
+ readSearchFolders(value) {
60
+ return value.split(this.paths.delimiter).filter(t => this.paths.isAbsolute(t));
61
+ }
62
+ toProgramCall(file, args) {
63
+ return new ProgramCall(file, args);
64
+ }
52
65
  }
@@ -6,6 +6,8 @@
6
6
  * LICENSE file in the root directory of this source tree.
7
7
  */
8
8
  import "@noldova/context.core";
9
+ import path from "node:path";
10
+ import { ProgramCall } from "../models/program-call.js";
9
11
  import { Resources } from "../resources.js";
10
12
  import { PowerShellBinding } from "./powershell-binding.js";
11
13
  import { ShellWords } from "./shell-words.js";
@@ -14,11 +16,16 @@ export class PowerShellShellAdapter {
14
16
  separator;
15
17
  takesBareNames = false;
16
18
  optionsKeys = Resources.powerShellOptionsKeys;
19
+ folderKeys = Resources.powerShellFolderKeys;
20
+ takesWindowsNames;
17
21
  looksUpMissing = true;
18
22
  binding;
23
+ paths;
19
24
  constructor(isWindows) {
20
25
  this.separator = isWindows ? Resources.windowsSeparator : Resources.posixSeparator;
21
26
  this.binding = new PowerShellBinding(isWindows);
27
+ this.takesWindowsNames = isWindows;
28
+ this.paths = isWindows ? path.win32 : path.posix;
22
29
  }
23
30
  readWords(line) {
24
31
  return ShellWords.read(line, true);
@@ -38,4 +45,10 @@ export class PowerShellShellAdapter {
38
45
  toLocalPath(value) {
39
46
  return value;
40
47
  }
48
+ readSearchFolders(value) {
49
+ return value.split(this.paths.delimiter).filter(t => this.paths.isAbsolute(t));
50
+ }
51
+ toProgramCall(file, args) {
52
+ return new ProgramCall(file, args);
53
+ }
41
54
  }
@@ -11,18 +11,22 @@ export class PseudoTerminal {
11
11
  process;
12
12
  listener;
13
13
  isConPty;
14
+ asksAfterResize;
14
15
  heldKeys = [];
15
16
  hasExited = false;
16
17
  isEnding = false;
17
18
  openRequests = 0;
18
19
  isResizeAsking = false;
20
+ isRequestShared = false;
21
+ requestTime = Number.NEGATIVE_INFINITY;
19
22
  hasOutput = false;
20
23
  outputEnd = "";
21
24
  answerLimit = undefined;
22
- constructor(process, listener, isConPty = false) {
25
+ constructor(process, listener, isConPty = false, asksAfterResize = isConPty) {
23
26
  this.process = process;
24
27
  this.listener = listener;
25
28
  this.isConPty = isConPty;
29
+ this.asksAfterResize = isConPty && asksAfterResize;
26
30
  this.process.onData(t => {
27
31
  this.hasOutput = true;
28
32
  if (this.isConPty)
@@ -65,9 +69,10 @@ export class PseudoTerminal {
65
69
  if (this.hasExited)
66
70
  return;
67
71
  this.process.resize(size.columns, size.rows);
68
- if (!this.isConPty || !this.hasOutput || this.isResizeAsking)
72
+ if (!this.asksAfterResize || !this.hasOutput || this.isResizeAsking)
69
73
  return;
70
74
  this.isResizeAsking = true;
75
+ this.isRequestShared = Date.now() - this.requestTime < Resources.cursorRequestFrameMilliseconds;
71
76
  this.openRequests++;
72
77
  this.limitAnswers();
73
78
  }
@@ -93,6 +98,7 @@ export class PseudoTerminal {
93
98
  this.outputEnd = text.slice(1 - Resources.cursorRequest.length);
94
99
  if (requests === 0)
95
100
  return;
101
+ this.requestTime = Date.now();
96
102
  this.limitAnswers();
97
103
  this.openRequests += this.isResizeAsking ? requests - 1 : requests;
98
104
  this.isResizeAsking = false;
@@ -102,7 +108,7 @@ export class PseudoTerminal {
102
108
  this.answerLimit = setTimeout(() => this.releaseUnanswered(), Resources.cursorAnswerMilliseconds);
103
109
  }
104
110
  releaseUnanswered() {
105
- if (this.isResizeAsking)
111
+ if (this.isResizeAsking && !this.isRequestShared)
106
112
  this.listener.onResizeUnasked?.();
107
113
  this.releaseKeys();
108
114
  }
@@ -10,16 +10,23 @@ import { TerminalShellKind } from "@noldova/terminal.protocol";
10
10
  import { Resources } from "../resources.js";
11
11
  import { PosixShellAdapter } from "./posix-shell-adapter.js";
12
12
  import { PowerShellShellAdapter } from "./powershell-shell-adapter.js";
13
+ import { WslShellAdapter } from "./wsl-shell-adapter.js";
13
14
  export class ShellAdapters {
14
15
  adapters;
16
+ distributions = new Map();
15
17
  constructor(isWindows) {
16
18
  this.adapters = new Map([
17
19
  [TerminalShellKind.PowerShell, new PowerShellShellAdapter(isWindows)],
18
- [TerminalShellKind.Bash, new PosixShellAdapter(isWindows, null, true)],
19
- [TerminalShellKind.Zsh, new PosixShellAdapter(isWindows, Resources.zshOptionsKeys, false)]
20
+ [TerminalShellKind.Bash, new PosixShellAdapter(isWindows, null, null, true)],
21
+ [TerminalShellKind.Zsh, new PosixShellAdapter(isWindows, Resources.zshOptionsKeys, Resources.zshFolderKeys, false)]
20
22
  ]);
21
23
  }
22
- of(kind) {
23
- return this.adapters.get(kind) ?? null;
24
+ of(shell) {
25
+ if (shell.kind !== TerminalShellKind.Wsl)
26
+ return this.adapters.get(shell.kind) ?? null;
27
+ const key = JSON.stringify([shell.file, shell.name]);
28
+ const adapter = this.distributions.get(key) ?? new WslShellAdapter(shell.file, shell.name);
29
+ this.distributions.set(key, adapter);
30
+ return adapter;
24
31
  }
25
32
  }
@@ -97,6 +97,15 @@ export class ShellIntegration {
97
97
  if (Object.isNull(folder) || Object.isNull(nonceFile))
98
98
  return ShellIntegration.toPlainLaunch(shell, family);
99
99
  const noteVariables = Object.isNull(note) ? {} : { [Resources.noteVariable]: note };
100
+ if (family === ShellFamily.Wsl)
101
+ return new ShellLaunch(shell.file, [...shell.args, Resources.wslExecArgument, Resources.wslStartShell, Resources.wslStartArgument,
102
+ Resources.shellIntegrationWslStart], {
103
+ [Resources.nonceFileVariable]: nonceFile,
104
+ [Resources.integrationFolderVariable]: folder,
105
+ [Resources.loginVariable]: Resources.shellIntegrationLoginValue,
106
+ ...noteVariables,
107
+ [Resources.wslEnvironmentVariable]: ShellIntegration.toWslEnvironment(environment, !Object.isNull(note))
108
+ }, nonce, nonceFile, !Object.isNull(note));
100
109
  if (family === ShellFamily.PowerShell)
101
110
  return new ShellLaunch(shell.file, [...shell.args, ...Resources.powerShellIntegrationArguments, ShellIntegration.encode([Resources.shellIntegrationPowerShellNonce, Resources.shellIntegrationPowerShellNote, Resources.shellIntegrationPowerShellProfiles, shell.startCommand,
102
111
  Resources.shellIntegrationPowerShellScript].filter(t => !Object.isNull(t)).join(Resources.lineFeed))], {
@@ -210,6 +219,8 @@ export class ShellIntegration {
210
219
  return ShellFamily.Zsh;
211
220
  case Resources.cmdExecutable:
212
221
  return ShellFamily.CommandPrompt;
222
+ case Resources.wslExecutable:
223
+ return ShellFamily.Wsl;
213
224
  case Resources.pwshExecutable:
214
225
  case Resources.windowsPowerShellExecutable:
215
226
  return ShellFamily.PowerShell;
@@ -217,6 +228,12 @@ export class ShellIntegration {
217
228
  return ShellFamily.Other;
218
229
  }
219
230
  }
231
+ static toWslEnvironment(environment, hasNote) {
232
+ const passed = Object.entries(environment).find(([t]) => t.toUpperCase() === Resources.wslEnvironmentVariable)?.[1];
233
+ return [...Object.isUndefined(passed) || passed === "" ? [] : [passed], `${Resources.nonceFileVariable}${Resources.wslPathFlag}`,
234
+ `${Resources.integrationFolderVariable}${Resources.wslPathFlag}`, Resources.loginVariable, ...hasNote ? [Resources.noteVariable] : []]
235
+ .join(Resources.wslEnvironmentSeparator);
236
+ }
220
237
  static encode(script) {
221
238
  return Buffer.from(script, Resources.utf16Encoding).toString(Resources.base64Encoding);
222
239
  }
@@ -8,7 +8,7 @@
8
8
  import "@noldova/context.core";
9
9
  import { randomUUID } from "node:crypto";
10
10
  import { ArgumentException } from "@noldova/context.exceptions";
11
- import { EndedBy, Resources as ProtocolResources, TerminalAckParams, TerminalChangeFolderParams, TerminalCommandAdded, TerminalCommandEnded, TerminalCompleteParams, TerminalCompletion, TerminalExit, TerminalExited, TerminalFindCommandsParams, TerminalFolderChanged, TerminalInputParams, TerminalLaunched, TerminalLaunchParams, TerminalLinesParams, TerminalName, TerminalNames, TerminalOpenParams, TerminalOwnerReference, TerminalPaneReference, TerminalReference, TerminalResizeParams, TerminalRestartParams, TerminalRestoreParams, TerminalRunBusy, TerminalRunEnded, TerminalRunEndedBy, TerminalRunOutcome, TerminalRunOutputParams, TerminalRunParams, TerminalRunResult, TerminalSessions, TerminalShellKind, TerminalShells, TerminalShowOwnerParams, TerminalSize, TerminalVisibilityParams, TerminalWriteParams, WindowsPty } from "@noldova/terminal.protocol";
11
+ import { EndedBy, Resources as ProtocolResources, TerminalAckParams, TerminalChangeFolderParams, TerminalCommandAdded, TerminalCommandEnded, TerminalCompleteParams, TerminalCompletion, TerminalDescribeParams, TerminalExit, TerminalExited, TerminalFindCommandsParams, TerminalFolderChanged, TerminalInputParams, TerminalLaunched, TerminalLaunchParams, TerminalLinesParams, TerminalName, TerminalNames, TerminalOpenParams, TerminalOwnerReference, TerminalPaneReference, TerminalReference, TerminalResizeParams, TerminalRestartParams, TerminalRestoreParams, TerminalRunBusy, TerminalRunEnded, TerminalRunEndedBy, TerminalRunOutcome, TerminalRunOutputParams, TerminalRunParams, TerminalRunResult, TerminalSessions, TerminalShellKind, TerminalShells, TerminalShowOwnerParams, TerminalSize, TerminalVisibilityParams, TerminalWriteParams, WindowsPty } from "@noldova/terminal.protocol";
12
12
  import { AgentTerminalRestartException } from "../exceptions/agent-terminal-restart.exception.js";
13
13
  import { SystemRequirement } from "../enums/system-requirement.js";
14
14
  import { ConnectionClosingException } from "../exceptions/connection-closing.exception.js";
@@ -48,6 +48,7 @@ export class TerminalHost {
48
48
  events;
49
49
  saved;
50
50
  completions;
51
+ describer;
51
52
  folderKeys = new WeakMap();
52
53
  realFolderReads = new Map();
53
54
  sessions = new Map();
@@ -63,7 +64,7 @@ export class TerminalHost {
63
64
  appCloses = new Set();
64
65
  closings = new Map();
65
66
  closingConnections = new Set();
66
- constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environment, homeFolder, log, events, saved, completions) {
67
+ constructor(spawner, fileSystem, integration, historyFolder, locator, platform, osRelease, environment, homeFolder, log, events, saved, completions, describer) {
67
68
  this.spawner = spawner;
68
69
  this.fileSystem = fileSystem;
69
70
  this.integration = integration;
@@ -82,6 +83,7 @@ export class TerminalHost {
82
83
  this.events = events;
83
84
  this.saved = saved;
84
85
  this.completions = completions;
86
+ this.describer = describer;
85
87
  }
86
88
  async handleAsync(method, payload, client) {
87
89
  this.audience.see(client);
@@ -144,6 +146,8 @@ export class TerminalHost {
144
146
  return (await this.completeAsync(TerminalCompleteParams.fromJson(payload), client)).toJson();
145
147
  case TerminalNames.findCommandsMethod:
146
148
  return (await this.findCommandsAsync(TerminalFindCommandsParams.fromJson(payload), client)).toJson();
149
+ case TerminalNames.describeMethod:
150
+ return (await this.describeAsync(TerminalDescribeParams.fromJson(payload), client)).toJson();
147
151
  case TerminalNames.windowStartedMethod:
148
152
  if (!Object.isNull(client.window)) {
149
153
  this.detachLeftPanes(t => t.connection === client.connection && t.window === client.window && t.page !== client.page);
@@ -294,7 +298,7 @@ export class TerminalHost {
294
298
  },
295
299
  onTitleChanged: t => publish(this.events.titleChanged, t.toJson()),
296
300
  onCwdChanged: t => {
297
- if (isKept && terminal.countsFolderReport(t.cwd))
301
+ if (isKept && this.isAbsolute(t.cwd) && terminal.countsFolderReport(t.cwd))
298
302
  this.saved.moveTo(t.sessionId, t.cwd);
299
303
  publish(this.events.cwdChanged, t.toJson());
300
304
  },
@@ -421,9 +425,9 @@ export class TerminalHost {
421
425
  if (t !== TerminalRunOutcome.Typed || !terminal.session.commands.hasMarks || Object.isNull(terminal.session.commands.promptEndOffset) || terminal.keyCount !== 0)
422
426
  this.endLaunchCommand(terminal, null);
423
427
  }).catch((error) => this.log.write(Resources.formatLaunchCommandFailed(terminal.session.sessionId, FailureText.read(error))));
424
- return new TerminalLaunched(terminal.session.sessionId, null, terminal.shell.kind);
428
+ return new TerminalLaunched(terminal.session.sessionId, null, terminal.shell.kind, terminal.session.hasIntegration);
425
429
  }
426
- async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false, readRefusal = () => null) {
430
+ async typeCommandAsync(terminal, command, isPaste = false, waitsForFit = false, readRefusal = () => null, folderKeys = null) {
427
431
  const session = terminal.session;
428
432
  const typed = isPaste ? command.replace(Resources.leadingBlankLines, "") : command;
429
433
  const pending = new AbortController();
@@ -456,7 +460,9 @@ export class TerminalHost {
456
460
  : isPaste && ((waitsForFit ? terminal.keyCount !== keyCount : terminal.inputCount !== inputCount) || !Object.isNull(session.commands.promptEndOffset) && session.readPromptLine() !== "") ? TerminalRunOutcome.Input
457
461
  : isPaste && !isBracketed && typed.includes(Resources.tabKey) ? TerminalRunOutcome.Tab
458
462
  : readRefusal() ?? TerminalRunOutcome.Typed;
459
- if (outcome === TerminalRunOutcome.Typed) {
463
+ if (outcome === TerminalRunOutcome.Typed && !Object.isNull(folderKeys))
464
+ session.sendFolder(folderKeys, command);
465
+ else if (outcome === TerminalRunOutcome.Typed) {
460
466
  const text = isPaste ? TerminalHost.toPaste(typed, isBracketed) : `${command}${Resources.enterKey}`;
461
467
  terminal.typedEnds = isBracketed || !isPaste ? 1 : text.split(Resources.enterKey).length - 1;
462
468
  terminal.paste = isBracketed ? typed.replace(Resources.whitespace, "") : "";
@@ -819,7 +825,7 @@ export class TerminalHost {
819
825
  const cwd = terminal.session.cwd;
820
826
  if (Object.isNull(cwd))
821
827
  return terminal.folder;
822
- const local = this.completions.toLocalFolder(cwd, terminal.shell.kind, this.readCompletionEnvironment(terminal));
828
+ const local = this.completions.toLocalFolder(cwd, terminal.shell, this.readCompletionEnvironment(terminal));
823
829
  if (Object.isNull(local))
824
830
  return null;
825
831
  return this.isAbsolute(local) ? local : terminal.folder;
@@ -861,25 +867,29 @@ export class TerminalHost {
861
867
  }
862
868
  async completeAsync(params, client) {
863
869
  const terminal = this.findHosted(params.sessionId, client);
864
- const keys = params.asksShell && this.completions.followsCommand(terminal.shell.kind, params.line, params.cursor)
865
- ? this.completions.adapterOf(terminal.shell.kind)?.optionsKeys ?? undefined : undefined;
870
+ const keys = params.asksShell && this.completions.followsCommand(terminal.shell, params.line, params.cursor)
871
+ ? this.completions.adapterOf(terminal.shell)?.optionsKeys ?? undefined : undefined;
866
872
  const [completion, reply] = await Promise.all([
867
- this.completions.completeAsync(params.sessionId, terminal.shell.kind, params.line, params.cursor, terminal.session.cwd ?? terminal.folder, this.readCompletionEnvironment(terminal), terminal.session.shellNames, terminal.session.shellBuiltins),
873
+ this.completions.completeAsync(params.sessionId, terminal.shell, params.line, params.cursor, terminal.session.cwd ?? terminal.folder, this.readCompletionEnvironment(terminal), terminal.session.shellNames, terminal.session.shellBuiltins),
868
874
  Object.isUndefined(keys) ? Promise.resolve(ShellOptionsReply.none) : terminal.session.askOptionsAsync(keys)
869
875
  ]);
870
876
  if (reply.isTimedOut)
871
877
  return new TerminalCompletion(params.cursor, [], true);
872
878
  return Object.isNull(reply.options) ? completion
873
- : this.completions.addOptions(completion, terminal.shell.kind, params.line, params.cursor, reply.options);
879
+ : this.completions.addOptions(completion, terminal.shell, params.line, params.cursor, reply.options);
874
880
  }
875
881
  async findCommandsAsync(params, client) {
876
882
  const terminal = this.findHosted(params.sessionId, client);
877
883
  const shellNames = terminal.session.isShellPathReset || terminal.session.isShellModulePathReset ? null
878
884
  : terminal.session.shellNames;
879
885
  const environment = this.readCompletionEnvironment(terminal);
880
- return this.completions.adapterOf(terminal.shell.kind)?.looksUpMissing === true
886
+ return this.completions.adapterOf(terminal.shell)?.looksUpMissing === true
881
887
  ? this.completions.findMissingPowerShellAsync(terminal.session.commands, terminal.shell.file, params.names, shellNames, environment)
882
- : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell.kind, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
888
+ : this.completions.findMissingAsync(params.sessionId, terminal.session.commands, terminal.session.prompts, terminal.shell, terminal.session.cwd ?? terminal.folder, params.names, shellNames, environment);
889
+ }
890
+ async describeAsync(params, client) {
891
+ const terminal = this.findHosted(params.sessionId, client);
892
+ return await this.describer.describeAsync(terminal.shell.kind, terminal.shell.file, params.names, this.readCompletionEnvironment(terminal));
883
893
  }
884
894
  readCompletionEnvironment(terminal) {
885
895
  const replaced = {};
@@ -890,6 +900,8 @@ export class TerminalHost {
890
900
  const temporaryFolder = terminal.session.shellTemporaryFolder ?? terminal.startTemporaryFolder;
891
901
  if (!Object.isNull(temporaryFolder))
892
902
  replaced[Resources.temporaryFolderVariable] = temporaryFolder;
903
+ if (!Object.isNull(terminal.session.shellHome))
904
+ replaced[Resources.homeVariable] = terminal.session.shellHome;
893
905
  const keys = new Set(Object.keys(replaced).map(t => this.toVariableKey(t)));
894
906
  return this.withVariables(TerminalHost.toTerminalEnvironment(this.environment.read()), {
895
907
  ...Object.fromEntries(Object.entries(terminal.environment ?? {}).filter(([t]) => !keys.has(this.toVariableKey(t)))),
@@ -1010,7 +1022,9 @@ export class TerminalHost {
1010
1022
  return new TerminalFolderChanged(null, true);
1011
1023
  if (!Object.isNull(terminal.pendingCommand) || !Object.isNull(session.commands.runningCommand))
1012
1024
  return new TerminalFolderChanged(null, true, TerminalRunOutcome.Busy);
1013
- const outcome = await this.typeCommandAsync(terminal, line, false, false, () => TerminalHost.readMoveRefusal(terminal));
1025
+ const folderKeys = session.commands.hasFolderBinding ? this.completions.adapterOf(terminal.shell)?.folderKeys ?? null : null;
1026
+ const before = session.cwd;
1027
+ const outcome = await this.typeCommandAsync(terminal, Object.isNull(folderKeys) ? line : params.folder, false, false, () => TerminalHost.readMoveRefusal(terminal), folderKeys);
1014
1028
  if (outcome === TerminalRunOutcome.NoShell)
1015
1029
  return new TerminalFolderChanged(null, false);
1016
1030
  if (outcome === TerminalRunOutcome.Busy || outcome === TerminalRunOutcome.Input)
@@ -1018,11 +1032,14 @@ export class TerminalHost {
1018
1032
  if (outcome !== TerminalRunOutcome.Typed)
1019
1033
  throw new SessionNotFoundException(params.sessionId);
1020
1034
  const typedAt = session.text.endOffset;
1021
- const isMoved = () => (session.commands.promptEndOffset ?? typedAt) > typedAt;
1035
+ const prompts = session.prompts;
1036
+ const isMoved = () => Object.isNull(folderKeys) ? (session.commands.promptEndOffset ?? typedAt) > typedAt
1037
+ : session.prompts > prompts && !Object.isNull(session.commands.promptEndOffset);
1022
1038
  await session.changes.waitUntilAsync(() => session.hasExited || this.sessions.get(params.sessionId) !== terminal || isMoved(), Resources.folderChangeWaitMilliseconds, new AbortController().signal);
1023
1039
  if (session.hasExited || this.sessions.get(params.sessionId) !== terminal)
1024
1040
  throw new SessionNotFoundException(params.sessionId);
1025
- return new TerminalFolderChanged(isMoved() && session.commands.lastCommand?.exitCode === 0 ? session.cwd : null, true);
1041
+ const isChanged = Object.isNull(folderKeys) ? session.commands.lastCommand?.exitCode === 0 : session.cwd !== before || session.cwd === params.folder;
1042
+ return new TerminalFolderChanged(isMoved() && isChanged ? session.cwd : null, true);
1026
1043
  }
1027
1044
  static readMoveRefusal(terminal) {
1028
1045
  const commands = terminal.session.commands;
@@ -1112,7 +1129,7 @@ export class TerminalHost {
1112
1129
  throw new HostEndedException();
1113
1130
  }
1114
1131
  async spawnFromAsync(base, file, args, folder, size, environment, inheritCursor) {
1115
- const process = await this.spawner.spawnAsync(file, args, folder, size.columns, size.rows, { ...base, ...environment }, inheritCursor);
1132
+ const process = await this.spawner.spawnAsync(file, args, folder, size.columns, size.rows, this.withVariables(base, environment), inheritCursor);
1116
1133
  if (this.hasEnded) {
1117
1134
  if (!await process.endAsync())
1118
1135
  this.log.write(Resources.formatLateShellLeftRunning(process.pid));