@xenosystem/primitives 0.4.0 → 0.5.0

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.
@@ -0,0 +1 @@
1
+ export declare const moduleDir: string;
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.moduleDir = __dirname;
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
3
+ *
4
+ * A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
5
+ * shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
6
+ * groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
7
+ * Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
8
+ * kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
9
+ * breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
10
+ *
11
+ * Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
12
+ * as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
13
+ * started anything yet; only then does it start the real command, with the same stdio.
14
+ *
15
+ * The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
16
+ * is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
17
+ * Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
18
+ * that needs the guarantee can refuse rather than assume it.
19
+ */
20
+ import { type ChildProcess } from 'node:child_process';
21
+ /** How stopping reaches the command's descendants. */
22
+ export type Containment = 'job' | 'process-group' | 'tree-walk';
23
+ export interface ProcessGroupOptions {
24
+ cwd?: string;
25
+ env?: NodeJS.ProcessEnv;
26
+ windowsHide?: boolean;
27
+ /** Pass argv to the program exactly as given (needed when the program is `cmd.exe`, which has its own parser). */
28
+ windowsVerbatimArguments?: boolean;
29
+ /** stdin, stdout, stderr. Default: all piped. */
30
+ stdio?: readonly ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
31
+ }
32
+ export interface ProcessGroup {
33
+ /** The process that was started. On Windows with a job, this is the launcher; its exit code is the command's. */
34
+ readonly child: ChildProcess;
35
+ readonly containment: Containment;
36
+ /** Stop the command and everything it started. `force` matters on POSIX only (SIGKILL instead of SIGTERM). */
37
+ stop(force?: boolean): void;
38
+ /** Processes still running in the group, where the platform can count them (Windows job only). */
39
+ activeProcesses(): number | undefined;
40
+ }
41
+ /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
42
+ export declare function processGroupSupport(): {
43
+ containment: Containment;
44
+ reason?: string;
45
+ };
46
+ /**
47
+ * Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
48
+ * `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
49
+ */
50
+ export declare function spawnProcessGroup(command: string, args: readonly string[], options?: ProcessGroupOptions): ProcessGroup;
@@ -0,0 +1,203 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.processGroupSupport = processGroupSupport;
4
+ exports.spawnProcessGroup = spawnProcessGroup;
5
+ /**
6
+ * `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
7
+ *
8
+ * A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
9
+ * shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
10
+ * groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
11
+ * Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
12
+ * kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
13
+ * breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
14
+ *
15
+ * Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
16
+ * as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
17
+ * started anything yet; only then does it start the real command, with the same stdio.
18
+ *
19
+ * The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
20
+ * is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
21
+ * Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
22
+ * that needs the guarantee can refuse rather than assume it.
23
+ */
24
+ const node_child_process_1 = require("node:child_process");
25
+ const node_fs_1 = require("node:fs");
26
+ const node_module_1 = require("node:module");
27
+ const node_path_1 = require("node:path");
28
+ const here_ts_1 = require("./here.js");
29
+ let nativeCache;
30
+ /** The native job binding, or why it is not available. Windows only. */
31
+ function loadNative() {
32
+ if (nativeCache)
33
+ return nativeCache;
34
+ if (process.platform !== 'win32')
35
+ return (nativeCache = { reason: 'not Windows' });
36
+ const name = `win32-${process.arch}`;
37
+ // src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
38
+ const candidates = [(0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', 'native', name, 'process.node'), (0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', '..', 'native', name, 'process.node')];
39
+ const file = candidates.find((p) => (0, node_fs_1.existsSync)(p));
40
+ if (!file)
41
+ return (nativeCache = { reason: `no native binary for ${name}` });
42
+ try {
43
+ const binding = (0, node_module_1.createRequire)(file)(file);
44
+ if (typeof binding.ProcessJob !== 'function')
45
+ return (nativeCache = { reason: 'native binary has no ProcessJob' });
46
+ return (nativeCache = { ctor: binding.ProcessJob });
47
+ }
48
+ catch (error) {
49
+ return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
50
+ }
51
+ }
52
+ /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
53
+ function processGroupSupport() {
54
+ if (process.platform !== 'win32')
55
+ return { containment: 'process-group' };
56
+ const native = loadNative();
57
+ return native.ctor ? { containment: 'job' } : { containment: 'tree-walk', ...(native.reason ? { reason: native.reason } : {}) };
58
+ }
59
+ // The launcher: reads one JSON line of instructions from fd 3, then starts the real command with fds 0-2 inherited
60
+ // and exits with its exit code. A failure to start is reported back on fd 3 so the caller can raise `error`.
61
+ const LAUNCHER = [
62
+ "const fs=require('fs'),cp=require('child_process');",
63
+ "let t='';const b=Buffer.alloc(65536);",
64
+ "for(;;){const n=fs.readSync(3,b,0,b.length,null);if(n===0)process.exit(126);t+=b.toString('utf8',0,n);const i=t.indexOf('\\n');if(i>=0){t=t.slice(0,i);break}}",
65
+ 'const s=JSON.parse(t);const env={...process.env};if(!s.keepRunAsNode)delete env.ELECTRON_RUN_AS_NODE;',
66
+ "const fail=(e)=>{try{fs.writeSync(3,JSON.stringify({error:{message:String(e&&e.message||e),code:e&&e.code}})+'\\n')}catch{}process.exit(127)};",
67
+ "let c;try{c=cp.spawn(s.command,s.args,{stdio:'inherit',windowsHide:s.windowsHide,windowsVerbatimArguments:s.verbatim,env})}catch(e){fail(e)}",
68
+ "c.on('error',fail);c.on('exit',(code)=>process.exit(code===null?1:code));",
69
+ ].join('');
70
+ /**
71
+ * Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
72
+ * `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
73
+ */
74
+ function spawnProcessGroup(command, args, options = {}) {
75
+ const stdio = options.stdio ?? ['pipe', 'pipe', 'pipe'];
76
+ const env = options.env ?? process.env;
77
+ const base = { cwd: options.cwd, env, windowsHide: options.windowsHide ?? true, shell: false };
78
+ if (process.platform !== 'win32') {
79
+ const child = (0, node_child_process_1.spawn)(command, [...args], { ...base, stdio: [...stdio], detached: true });
80
+ return {
81
+ child,
82
+ containment: 'process-group',
83
+ stop(force = false) {
84
+ const pid = child.pid;
85
+ if (pid === undefined)
86
+ return;
87
+ try {
88
+ process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
89
+ }
90
+ catch {
91
+ try {
92
+ child.kill(force ? 'SIGKILL' : 'SIGTERM');
93
+ }
94
+ catch { /* already gone */ }
95
+ }
96
+ },
97
+ activeProcesses: () => undefined,
98
+ };
99
+ }
100
+ const native = loadNative();
101
+ if (!native.ctor) {
102
+ const child = (0, node_child_process_1.spawn)(command, [...args], { ...base, stdio: [...stdio], windowsVerbatimArguments: options.windowsVerbatimArguments ?? false });
103
+ return {
104
+ child,
105
+ containment: 'tree-walk',
106
+ stop() {
107
+ const pid = child.pid;
108
+ if (pid === undefined)
109
+ return;
110
+ const killer = (0, node_child_process_1.spawn)('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
111
+ killer.on('error', () => { try {
112
+ child.kill();
113
+ }
114
+ catch { /* already gone */ } });
115
+ },
116
+ activeProcesses: () => undefined,
117
+ };
118
+ }
119
+ const job = new native.ctor();
120
+ let jobOpen = true;
121
+ const endJob = (how) => {
122
+ if (!jobOpen)
123
+ return;
124
+ jobOpen = false;
125
+ try {
126
+ if (how === 'terminate')
127
+ job.close();
128
+ else
129
+ job.release();
130
+ }
131
+ catch { /* the handle is gone either way */ }
132
+ };
133
+ const runAsNode = process.versions.electron !== undefined;
134
+ const launcherEnv = runAsNode ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : env;
135
+ const child = (0, node_child_process_1.spawn)(process.execPath, ['-e', LAUNCHER], { ...base, env: launcherEnv, stdio: [...stdio, 'pipe'] });
136
+ const control = child.stdio[3];
137
+ if (child.pid !== undefined && control) {
138
+ try {
139
+ job.assign(child.pid);
140
+ }
141
+ catch (error) {
142
+ // A command that is not in its group is not started: stopping it could not reach what it starts.
143
+ try {
144
+ child.kill();
145
+ }
146
+ catch { /* already gone */ }
147
+ endJob('terminate');
148
+ queueMicrotask(() => child.emit('error', new Error(`could not place the command in a job: ${error.message}`)));
149
+ return { child, containment: 'job', stop() { }, activeProcesses: () => undefined };
150
+ }
151
+ let received = '';
152
+ control.on('data', (chunk) => {
153
+ received += chunk.toString();
154
+ const line = received.split('\n')[0];
155
+ if (received.includes('\n') && line) {
156
+ try {
157
+ const message = JSON.parse(line);
158
+ if (message.error)
159
+ child.emit('error', Object.assign(new Error(message.error.message), message.error.code ? { code: message.error.code } : {}));
160
+ }
161
+ catch { /* not ours */ }
162
+ }
163
+ });
164
+ control.on('error', () => { });
165
+ control.write(JSON.stringify({
166
+ command,
167
+ args,
168
+ verbatim: options.windowsVerbatimArguments ?? false,
169
+ windowsHide: options.windowsHide ?? true,
170
+ keepRunAsNode: runAsNode && env.ELECTRON_RUN_AS_NODE !== undefined,
171
+ }) + '\n');
172
+ }
173
+ else {
174
+ endJob('terminate');
175
+ }
176
+ // A command that ended on its own keeps today's behaviour for anything it left running; only stop() ends those.
177
+ child.once('close', () => endJob('release'));
178
+ child.once('error', () => { if (child.exitCode !== null || child.pid === undefined)
179
+ endJob('release'); });
180
+ return {
181
+ child,
182
+ containment: 'job',
183
+ stop() {
184
+ if (!jobOpen)
185
+ return;
186
+ try {
187
+ job.terminate(1);
188
+ }
189
+ catch { /* fall through: closing the handle ends every member too */ }
190
+ endJob('terminate');
191
+ },
192
+ activeProcesses() {
193
+ if (!jobOpen)
194
+ return 0;
195
+ try {
196
+ return job.activeProcesses();
197
+ }
198
+ catch {
199
+ return undefined;
200
+ }
201
+ },
202
+ };
203
+ }
@@ -0,0 +1 @@
1
+ export declare const moduleDir: string;
@@ -0,0 +1,6 @@
1
+ import { dirname } from 'node:path';
2
+ import { fileURLToPath } from 'node:url';
3
+ // This module's own directory, used to find the bundled native binary. The CommonJS build replaces this file with
4
+ // `exports.moduleDir = __dirname` (scripts/build-ts.mjs), because CommonJS cannot parse `import.meta`.
5
+ // @ts-ignore TS1343 in the CommonJS compile only; that emitted file is overwritten.
6
+ export const moduleDir = dirname(fileURLToPath(import.meta.url));
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
3
+ *
4
+ * A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
5
+ * shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
6
+ * groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
7
+ * Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
8
+ * kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
9
+ * breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
10
+ *
11
+ * Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
12
+ * as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
13
+ * started anything yet; only then does it start the real command, with the same stdio.
14
+ *
15
+ * The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
16
+ * is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
17
+ * Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
18
+ * that needs the guarantee can refuse rather than assume it.
19
+ */
20
+ import { type ChildProcess } from 'node:child_process';
21
+ /** How stopping reaches the command's descendants. */
22
+ export type Containment = 'job' | 'process-group' | 'tree-walk';
23
+ export interface ProcessGroupOptions {
24
+ cwd?: string;
25
+ env?: NodeJS.ProcessEnv;
26
+ windowsHide?: boolean;
27
+ /** Pass argv to the program exactly as given (needed when the program is `cmd.exe`, which has its own parser). */
28
+ windowsVerbatimArguments?: boolean;
29
+ /** stdin, stdout, stderr. Default: all piped. */
30
+ stdio?: readonly ['pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit', 'pipe' | 'ignore' | 'inherit'];
31
+ }
32
+ export interface ProcessGroup {
33
+ /** The process that was started. On Windows with a job, this is the launcher; its exit code is the command's. */
34
+ readonly child: ChildProcess;
35
+ readonly containment: Containment;
36
+ /** Stop the command and everything it started. `force` matters on POSIX only (SIGKILL instead of SIGTERM). */
37
+ stop(force?: boolean): void;
38
+ /** Processes still running in the group, where the platform can count them (Windows job only). */
39
+ activeProcesses(): number | undefined;
40
+ }
41
+ /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
42
+ export declare function processGroupSupport(): {
43
+ containment: Containment;
44
+ reason?: string;
45
+ };
46
+ /**
47
+ * Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
48
+ * `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
49
+ */
50
+ export declare function spawnProcessGroup(command: string, args: readonly string[], options?: ProcessGroupOptions): ProcessGroup;
@@ -0,0 +1,199 @@
1
+ /**
2
+ * `@xenosystem/primitives/process` — start a command so that stopping it stops everything it started.
3
+ *
4
+ * A command usually runs through a shell, and the shell starts the real program. `child.kill()` ends only the
5
+ * shell. On POSIX the child leads its own process group and the group is signalled. Windows has no process
6
+ * groups, and walking the tree by parent id (`taskkill /T`) is not reliable: measured 2026-11-09 on a loaded
7
+ * Windows 11 machine it failed for a `node` grandchild ("not found" / "operation not supported") and the program
8
+ * kept running after Stop. So on Windows each command runs in its own **job object** (`KILL_ON_JOB_CLOSE`, no
9
+ * breakaway): the kernel adds every descendant at creation, and terminating the job ends all of them.
10
+ *
11
+ * Race-free by construction: the first process started is a small launcher (this runtime's own executable, run
12
+ * as Node). It is added to the job while it waits for its instructions on a private pipe, so it cannot have
13
+ * started anything yet; only then does it start the real command, with the same stdio.
14
+ *
15
+ * The job comes from a native binary that ships inside this package (`native/win32-<arch>/process.node`). Nothing
16
+ * is compiled at run time: a launcher compiled into TEMP was quarantined by Microsoft Defender on 2026-11-01.
17
+ * Where that binary is missing, `containment` says `tree-walk` and the old `taskkill /T` is used, so a caller
18
+ * that needs the guarantee can refuse rather than assume it.
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ import { existsSync } from 'node:fs';
22
+ import { createRequire } from 'node:module';
23
+ import { join } from 'node:path';
24
+ import { moduleDir } from "./here.js";
25
+ let nativeCache;
26
+ /** The native job binding, or why it is not available. Windows only. */
27
+ function loadNative() {
28
+ if (nativeCache)
29
+ return nativeCache;
30
+ if (process.platform !== 'win32')
31
+ return (nativeCache = { reason: 'not Windows' });
32
+ const name = `win32-${process.arch}`;
33
+ // src/process (tests) and dist/{esm,cjs}/process (published) both sit under the package directory.
34
+ const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
35
+ const file = candidates.find((p) => existsSync(p));
36
+ if (!file)
37
+ return (nativeCache = { reason: `no native binary for ${name}` });
38
+ try {
39
+ const binding = createRequire(file)(file);
40
+ if (typeof binding.ProcessJob !== 'function')
41
+ return (nativeCache = { reason: 'native binary has no ProcessJob' });
42
+ return (nativeCache = { ctor: binding.ProcessJob });
43
+ }
44
+ catch (error) {
45
+ return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
46
+ }
47
+ }
48
+ /** What `spawnProcessGroup` will use on this machine, and why when it is not the strongest form. */
49
+ export function processGroupSupport() {
50
+ if (process.platform !== 'win32')
51
+ return { containment: 'process-group' };
52
+ const native = loadNative();
53
+ return native.ctor ? { containment: 'job' } : { containment: 'tree-walk', ...(native.reason ? { reason: native.reason } : {}) };
54
+ }
55
+ // The launcher: reads one JSON line of instructions from fd 3, then starts the real command with fds 0-2 inherited
56
+ // and exits with its exit code. A failure to start is reported back on fd 3 so the caller can raise `error`.
57
+ const LAUNCHER = [
58
+ "const fs=require('fs'),cp=require('child_process');",
59
+ "let t='';const b=Buffer.alloc(65536);",
60
+ "for(;;){const n=fs.readSync(3,b,0,b.length,null);if(n===0)process.exit(126);t+=b.toString('utf8',0,n);const i=t.indexOf('\\n');if(i>=0){t=t.slice(0,i);break}}",
61
+ 'const s=JSON.parse(t);const env={...process.env};if(!s.keepRunAsNode)delete env.ELECTRON_RUN_AS_NODE;',
62
+ "const fail=(e)=>{try{fs.writeSync(3,JSON.stringify({error:{message:String(e&&e.message||e),code:e&&e.code}})+'\\n')}catch{}process.exit(127)};",
63
+ "let c;try{c=cp.spawn(s.command,s.args,{stdio:'inherit',windowsHide:s.windowsHide,windowsVerbatimArguments:s.verbatim,env})}catch(e){fail(e)}",
64
+ "c.on('error',fail);c.on('exit',(code)=>process.exit(code===null?1:code));",
65
+ ].join('');
66
+ /**
67
+ * Start `command args` as a group. Use `group.child` exactly like the result of `child_process.spawn` (its stdio,
68
+ * `exit`, `close` and `error` events), and `group.stop()` to end it with everything it started.
69
+ */
70
+ export function spawnProcessGroup(command, args, options = {}) {
71
+ const stdio = options.stdio ?? ['pipe', 'pipe', 'pipe'];
72
+ const env = options.env ?? process.env;
73
+ const base = { cwd: options.cwd, env, windowsHide: options.windowsHide ?? true, shell: false };
74
+ if (process.platform !== 'win32') {
75
+ const child = spawn(command, [...args], { ...base, stdio: [...stdio], detached: true });
76
+ return {
77
+ child,
78
+ containment: 'process-group',
79
+ stop(force = false) {
80
+ const pid = child.pid;
81
+ if (pid === undefined)
82
+ return;
83
+ try {
84
+ process.kill(-pid, force ? 'SIGKILL' : 'SIGTERM');
85
+ }
86
+ catch {
87
+ try {
88
+ child.kill(force ? 'SIGKILL' : 'SIGTERM');
89
+ }
90
+ catch { /* already gone */ }
91
+ }
92
+ },
93
+ activeProcesses: () => undefined,
94
+ };
95
+ }
96
+ const native = loadNative();
97
+ if (!native.ctor) {
98
+ const child = spawn(command, [...args], { ...base, stdio: [...stdio], windowsVerbatimArguments: options.windowsVerbatimArguments ?? false });
99
+ return {
100
+ child,
101
+ containment: 'tree-walk',
102
+ stop() {
103
+ const pid = child.pid;
104
+ if (pid === undefined)
105
+ return;
106
+ const killer = spawn('taskkill', ['/PID', String(pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' });
107
+ killer.on('error', () => { try {
108
+ child.kill();
109
+ }
110
+ catch { /* already gone */ } });
111
+ },
112
+ activeProcesses: () => undefined,
113
+ };
114
+ }
115
+ const job = new native.ctor();
116
+ let jobOpen = true;
117
+ const endJob = (how) => {
118
+ if (!jobOpen)
119
+ return;
120
+ jobOpen = false;
121
+ try {
122
+ if (how === 'terminate')
123
+ job.close();
124
+ else
125
+ job.release();
126
+ }
127
+ catch { /* the handle is gone either way */ }
128
+ };
129
+ const runAsNode = process.versions.electron !== undefined;
130
+ const launcherEnv = runAsNode ? { ...env, ELECTRON_RUN_AS_NODE: '1' } : env;
131
+ const child = spawn(process.execPath, ['-e', LAUNCHER], { ...base, env: launcherEnv, stdio: [...stdio, 'pipe'] });
132
+ const control = child.stdio[3];
133
+ if (child.pid !== undefined && control) {
134
+ try {
135
+ job.assign(child.pid);
136
+ }
137
+ catch (error) {
138
+ // A command that is not in its group is not started: stopping it could not reach what it starts.
139
+ try {
140
+ child.kill();
141
+ }
142
+ catch { /* already gone */ }
143
+ endJob('terminate');
144
+ queueMicrotask(() => child.emit('error', new Error(`could not place the command in a job: ${error.message}`)));
145
+ return { child, containment: 'job', stop() { }, activeProcesses: () => undefined };
146
+ }
147
+ let received = '';
148
+ control.on('data', (chunk) => {
149
+ received += chunk.toString();
150
+ const line = received.split('\n')[0];
151
+ if (received.includes('\n') && line) {
152
+ try {
153
+ const message = JSON.parse(line);
154
+ if (message.error)
155
+ child.emit('error', Object.assign(new Error(message.error.message), message.error.code ? { code: message.error.code } : {}));
156
+ }
157
+ catch { /* not ours */ }
158
+ }
159
+ });
160
+ control.on('error', () => { });
161
+ control.write(JSON.stringify({
162
+ command,
163
+ args,
164
+ verbatim: options.windowsVerbatimArguments ?? false,
165
+ windowsHide: options.windowsHide ?? true,
166
+ keepRunAsNode: runAsNode && env.ELECTRON_RUN_AS_NODE !== undefined,
167
+ }) + '\n');
168
+ }
169
+ else {
170
+ endJob('terminate');
171
+ }
172
+ // A command that ended on its own keeps today's behaviour for anything it left running; only stop() ends those.
173
+ child.once('close', () => endJob('release'));
174
+ child.once('error', () => { if (child.exitCode !== null || child.pid === undefined)
175
+ endJob('release'); });
176
+ return {
177
+ child,
178
+ containment: 'job',
179
+ stop() {
180
+ if (!jobOpen)
181
+ return;
182
+ try {
183
+ job.terminate(1);
184
+ }
185
+ catch { /* fall through: closing the handle ends every member too */ }
186
+ endJob('terminate');
187
+ },
188
+ activeProcesses() {
189
+ if (!jobOpen)
190
+ return 0;
191
+ try {
192
+ return job.activeProcesses();
193
+ }
194
+ catch {
195
+ return undefined;
196
+ }
197
+ },
198
+ };
199
+ }