-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
shell.ts
374 lines (349 loc) · 10.1 KB
/
shell.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
// Copyright 2019-2021 Tauri Programme within The Commons Conservancy
// SPDX-License-Identifier: Apache-2.0
// SPDX-License-Identifier: MIT
import { invokeTauriCommand } from './helpers/tauri'
import { transformCallback } from './tauri'
/**
* Access the system shell.
* Allows you to spawn child processes and manage files and URLs using their default application.
*
* This package is also accessible with `window.__TAURI__.shell` when `tauri.conf.json > build > withGlobalTauri` is set to true.
*
* The APIs must be allowlisted on `tauri.conf.json`:
* ```json
* {
* "tauri": {
* "allowlist": {
* "shell": {
* "all": true, // enable all shell APIs
* "execute": true, // enable process spawn APIs
* "open": true // enable opening files/URLs using the default program
* }
* }
* }
* }
* ```
* It is recommended to allowlist only the APIs you use for optimal bundle size and security.
* @module
*/
interface SpawnOptions {
/** Current working directory. */
cwd?: string
/** Environment variables. set to `null` to clear the process env. */
env?: { [name: string]: string }
}
/** @ignore */
interface InternalSpawnOptions extends SpawnOptions {
sidecar?: boolean
}
interface ChildProcess {
/** Exit code of the process. `null` if the process was terminated by a signal on Unix. */
code: number | null
/** If the process was terminated by a signal, represents that signal. */
signal: number | null
/** The data that the process wrote to `stdout`. */
stdout: string
/** The data that the process wrote to `stderr`. */
stderr: string
}
/**
* Spawns a process.
*
* @ignore
* @param program The name of the scoped command.
* @param onEvent Event handler.
* @param args Program arguments.
* @param options Configuration for the process spawn.
* @returns A promise resolving to the process id.
*/
async function execute(
onEvent: (event: CommandEvent) => void,
program: string,
args?: string | string[] | { [key: string]: string },
options?: InternalSpawnOptions
): Promise<number> {
if (typeof args === 'object') {
Object.freeze(args)
}
return invokeTauriCommand<number>({
__tauriModule: 'Shell',
message: {
cmd: 'execute',
program,
args,
options,
onEventFn: transformCallback(onEvent)
}
})
}
class EventEmitter<E extends string> {
/** @ignore */
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
private eventListeners: {
[key: string]: Array<(arg: any) => void>
} = Object.create(null)
/** @ignore */
private addEventListener(event: string, handler: (arg: any) => void): void {
if (event in this.eventListeners) {
// eslint-disable-next-line security/detect-object-injection
this.eventListeners[event].push(handler)
} else {
// eslint-disable-next-line security/detect-object-injection
this.eventListeners[event] = [handler]
}
}
/** @ignore */
_emit(event: E, payload: any): void {
if (event in this.eventListeners) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access
const listeners = this.eventListeners[event as any]
for (const listener of listeners) {
listener(payload)
}
}
}
/**
* Listen to an event from the child process.
*
* @param event The event name.
* @param handler The event handler.
*
* @return The `this` instance for chained calls.
*/
on(event: E, handler: (arg: any) => void): EventEmitter<E> {
this.addEventListener(event, handler)
return this
}
}
class Child {
/** The child process `pid`. */
pid: number
constructor(pid: number) {
this.pid = pid
}
/**
* Writes `data` to the `stdin`.
*
* @param data The message to write, either a string or a byte array.
* @example
* ```typescript
* const command = new Command('node')
* const child = await command.spawn()
* await child.write('message')
* await child.write([0, 1, 2, 3, 4, 5])
* ```
*
* @return A promise indicating the success or failure of the operation.
*/
async write(data: string | Uint8Array): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Shell',
message: {
cmd: 'stdinWrite',
pid: this.pid,
// correctly serialize Uint8Arrays
buffer: typeof data === 'string' ? data : Array.from(data)
}
})
}
/**
* Kills the child process.
*
* @return A promise indicating the success or failure of the operation.
*/
async kill(): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Shell',
message: {
cmd: 'killChild',
pid: this.pid
}
})
}
}
/**
* The entry point for spawning child processes.
* It emits the `close` and `error` events.
* @example
* ```typescript
* const command = new Command('node')
* command.on('close', data => {
* console.log(`command finished with code ${data.code} and signal ${data.signal}`)
* })
* command.on('error', error => console.error(`command error: "${error}"`))
* command.stdout.on('data', line => console.log(`command stdout: "${line}"`))
* command.stderr.on('data', line => console.log(`command stderr: "${line}"`))
*
* const child = await command.spawn()
* console.log('pid:', child.pid)
* ```
*/
class Command extends EventEmitter<'close' | 'error'> {
/** @ignore Program to execute. */
private readonly program: string
/** @ignore Program arguments */
private readonly args: string[]
/** @ignore Spawn options. */
private readonly options: InternalSpawnOptions
/** Event emitter for the `stdout`. Emits the `data` event. */
readonly stdout = new EventEmitter<'data'>()
/** Event emitter for the `stderr`. Emits the `data` event. */
readonly stderr = new EventEmitter<'data'>()
/**
* Creates a new `Command` instance.
*
* @param program The program to execute.
* @param args Program arguments.
* @param options Spawn options.
*/
constructor(
program: string,
args: string | string[] = [],
options?: SpawnOptions
) {
super()
this.program = program
this.args = typeof args === 'string' ? [args] : args
this.options = options ?? {}
}
/**
* Creates a command to execute the given sidecar program.
* @example
* ```typescript
* const command = Command.sidecar('my-sidecar')
* const output = await command.execute()
* ```
*
* @param program The program to execute.
* @param args Program arguments.
* @param options Spawn options.
* @returns
*/
static sidecar(
program: string,
args: string | string[] = [],
options?: SpawnOptions
): Command {
const instance = new Command(program, args, options)
instance.options.sidecar = true
return instance
}
/**
* Executes the command as a child process, returning a handle to it.
*
* @return A promise resolving to the child process handle.
*/
async spawn(): Promise<Child> {
return execute(
(event) => {
switch (event.event) {
case 'Error':
this._emit('error', event.payload)
break
case 'Terminated':
this._emit('close', event.payload)
break
case 'Stdout':
this.stdout._emit('data', event.payload)
break
case 'Stderr':
this.stderr._emit('data', event.payload)
break
}
},
this.program,
this.args,
this.options
).then((pid) => new Child(pid))
}
/**
* Executes the command as a child process, waiting for it to finish and collecting all of its output.
* @example
* ```typescript
* const output = await new Command('echo', 'message').execute()
* assert(output.code === 0)
* assert(output.signal === null)
* assert(output.stdout === 'message')
* assert(output.stderr === '')
* ```
*
* @return A promise resolving to the child process output.
*/
async execute(): Promise<ChildProcess> {
return new Promise((resolve, reject) => {
this.on('error', reject)
const stdout: string[] = []
const stderr: string[] = []
this.stdout.on('data', (line: string) => {
stdout.push(line)
})
this.stderr.on('data', (line: string) => {
stderr.push(line)
})
this.on('close', (payload: TerminatedPayload) => {
resolve({
code: payload.code,
signal: payload.signal,
stdout: stdout.join('\n'),
stderr: stderr.join('\n')
})
})
this.spawn().catch(reject)
})
}
}
/**
* Describes the event message received from the command.
*/
interface Event<T, V> {
event: T
payload: V
}
/**
* Payload for the `Terminated` command event.
*/
interface TerminatedPayload {
/** Exit code of the process. `null` if the process was terminated by a signal on Unix. */
code: number | null
/** If the process was terminated by a signal, represents that signal. */
signal: number | null
}
/** Events emitted by the child process. */
type CommandEvent =
| Event<'Stdout', string>
| Event<'Stderr', string>
| Event<'Terminated', TerminatedPayload>
| Event<'Error', string>
/**
* Opens a path or URL with the system's default app,
* or the one specified with `openWith`.
*
* The `openWith` value must be one of `firefox`, `google chrome`, `chromium` `safari`,
* `open`, `start`, `xdg-open`, `gio`, gnome-open`, `kde-open` or `wslview`.
*
* @example
* ```typescript
* // opens the given URL on the default browser:
* await open('https://github.com/tauri-apps/tauri')
* // opens the given URL using `firefox`:
* await open('https://github.com/tauri-apps/tauri', 'firefox')
* // opens a file using the default program:
* await open('/path/to/file')
* ```
*
* @param path The path or URL to open.
* @param openWith The app to open the file or URL with. Defaults to the system default application for the specified path type.
* @returns
*/
async function open(path: string, openWith?: string): Promise<void> {
return invokeTauriCommand({
__tauriModule: 'Shell',
message: {
cmd: 'open',
path,
with: openWith
}
})
}
export { Command, Child, open }
export type { ChildProcess, SpawnOptions }