Debian Codegraph @

node/sync-child-process/dist/lib/index.js

raw
1 "use strict";
2 // Copyright 2021 Google LLC. Use of this source code is governed by an
3 // MIT-style license that can be found in the LICENSE file or at
4 // https://opensource.org/licenses/MIT.
5 Object.defineProperty(exports, "__esModule", { value: true });
6 exports.SyncChildProcess = void 0;
7 const fs = require("fs");
8 const p = require("path");
9 const stream = require("stream");
10 const worker_threads_1 = require("worker_threads");
11 const worker_threads = require("worker_threads");
12 const sync_message_port_1 = require("sync-message-port");
13 /** Whether {@link object} can't be transferred between threads, only cloned. */
14 function isMarkedAsUntransferable(object) {
15 // TODO: Remove this check when we no longer support Node v20 (after
16 // 2026-04-30).
17 return 'isMarkedAsUntransferable' in worker_threads
18 ? // TODO - DefinitelyTyped/DefinitelyTyped#71033: Remove this cast
19 worker_threads.isMarkedAsUntransferable(object)
20 : false;
21 }
22 /**
23 * A child process that runs synchronously while also allowing the user to
24 * interact with it before it shuts down.
25 */
26 class SyncChildProcess {
27 /** The port that communicates with the worker thread. */
28 port;
29 /** The worker in which the child process runs. */
30 worker;
31 /** The standard input stream to write to the process. */
32 stdin;
33 constructor(command, argsOrOptions, options) {
34 let args;
35 if (Array.isArray(argsOrOptions)) {
36 args = argsOrOptions;
37 }
38 else {
39 args = [];
40 options = argsOrOptions;
41 }
42 const { port1, port2 } = sync_message_port_1.SyncMessagePort.createChannel();
43 this.port = new sync_message_port_1.SyncMessagePort(port1);
44 this.worker = spawnWorker(p.join(p.dirname(__filename), 'worker'), {
45 workerData: { port: port2, command, args, options },
46 transferList: [port2],
47 });
48 // The worker shouldn't emit any errors unless it breaks in development.
49 this.worker.on('error', console.error);
50 this.stdin = new stream.Writable({
51 write: (chunk, encoding, callback) => {
52 this.port.postMessage({
53 type: 'stdin',
54 data: chunk,
55 }, isMarkedAsUntransferable(chunk.buffer) ? undefined : [chunk.buffer]);
56 callback();
57 },
58 final: () => this.port.postMessage({ type: 'stdinClosed' }),
59 });
60 }
61 /**
62 * Blocks until the child process is ready to emit another event, then returns
63 * that event. This will return an [IteratorReturnResult] with an [ExitEvent]
64 * once when the process exits. If it's called again after that, it will
65 * return `{done: true}` without a value.
66 *
67 * If there's an error running the child process, this will throw that error.
68 */
69 next() {
70 if (this.stdin.destroyed)
71 return { done: true, value: undefined };
72 const message = this.port.receiveMessage();
73 switch (message.type) {
74 case 'stdout':
75 return {
76 value: { type: 'stdout', data: Buffer.from(message.data.buffer) },
77 };
78 case 'stderr':
79 return {
80 value: { type: 'stderr', data: Buffer.from(message.data.buffer) },
81 };
82 case 'error':
83 this.close();
84 throw message.error;
85 case 'exit':
86 this.close();
87 return { done: true, value: message };
88 }
89 }
90 // TODO(nex3): Add a non-blocking `yieldIfReady()` function that returns
91 // `null` if the worker hasn't queued up an event.
92 // TODO(nex3): Add a `yieldAsync()` function that returns a `Promise<Event>`.
93 /**
94 * Sends a signal (`SIGTERM` by default) to the child process.
95 *
96 * This has no effect if the process has already exited.
97 */
98 kill(signal) {
99 this.port.postMessage({ type: 'kill', signal });
100 }
101 /** Closes down the worker thread and the stdin stream. */
102 close() {
103 this.port.close();
104 void this.worker.terminate();
105 this.stdin.destroy();
106 }
107 }
108 exports.SyncChildProcess = SyncChildProcess;
109 /**
110 * Spawns a worker for the given `fileWithoutExtension` in either a JS or TS
111 * worker, depending on which file exists.
112 */
113 function spawnWorker(fileWithoutExtension, options) {
114 // The released version always spawns the JS worker. The TS worker is only
115 // used for development.
116 const jsFile = fileWithoutExtension + '.js';
117 if (fs.existsSync(jsFile))
118 return new worker_threads_1.Worker(jsFile, options);
119 const tsFile = fileWithoutExtension + '.ts';
120 if (fs.existsSync(tsFile)) {
121 return new worker_threads_1.Worker(`
122 require('ts-node').register();
123 require(${JSON.stringify(tsFile)});
124 `, { ...options, eval: true });
125 }
126 throw new Error(`Neither "${jsFile}" nor ".ts" exists.`);
127 }
128 //# sourceMappingURL=index.js.map