@tsplc/build 0.2.17 → 0.2.18

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.
Files changed (51) hide show
  1. package/dist/cli.js +628 -352
  2. package/dist/cli.js.map +30 -28
  3. package/dist/index.js +548 -387
  4. package/dist/index.js.map +27 -25
  5. package/dist/libraries.js +68 -27
  6. package/dist/libraries.js.map +3 -3
  7. package/docker/Dockerfile +2 -0
  8. package/docker/Dockerfile.dockerignore +4 -1
  9. package/docker/Dockerfile.source +3 -0
  10. package/docker/config.ts +10 -5
  11. package/docker/runner.ts +140 -127
  12. package/package.json +54 -53
  13. package/python/build.py +183 -124
  14. package/python/codesys_online.py +44 -45
  15. package/python/hardware.py +9 -9
  16. package/python/test_build.py +3 -3
  17. package/python/test_codesys_online.py +18 -12
  18. package/python/test_installer_packages.py +1 -0
  19. package/python/worker.py +11 -7
  20. package/src/artifacts.ts +82 -60
  21. package/src/build.ts +71 -62
  22. package/src/cli.ts +109 -100
  23. package/src/controller-online.ts +400 -425
  24. package/src/controller-protocol.ts +140 -0
  25. package/src/controller-session.ts +466 -397
  26. package/src/device-tree.ts +19 -15
  27. package/src/diagnostics.ts +59 -49
  28. package/src/docker-build.ts +217 -156
  29. package/src/docker-context.ts +49 -27
  30. package/src/docker-run.ts +137 -111
  31. package/src/engineering-settings.ts +42 -0
  32. package/src/host/codesys-command.ts +35 -34
  33. package/src/host/codesys-host.ts +157 -129
  34. package/src/host/codesys-worker.ts +318 -301
  35. package/src/host/windows-path.ts +63 -59
  36. package/src/import-request.ts +24 -0
  37. package/src/index.ts +37 -31
  38. package/src/io.ts +152 -116
  39. package/src/libraries.ts +214 -146
  40. package/src/package-path.ts +3 -1
  41. package/src/run.ts +132 -108
  42. package/src/runtime-status.ts +25 -19
  43. package/src/sources.ts +264 -225
  44. package/src/st/declarations.ts +181 -193
  45. package/src/st/lexer.ts +102 -118
  46. package/src/st/parse.ts +193 -171
  47. package/src/st/reader.ts +47 -42
  48. package/src/__tests__/fixtures/xml/fb-simple.xml +0 -40
  49. package/src/__tests__/fixtures/xml/fb-state-machine.xml +0 -86
  50. package/src/__tests__/fixtures/xml/prg-cyclic.xml +0 -44
  51. package/src/config.ts +0 -12
@@ -1,357 +1,374 @@
1
1
  // Engineering CLI lifecycle and diagnostics.
2
2
  import { createHash, randomUUID } from "node:crypto";
3
3
  import {
4
- access,
5
- copyFile,
6
- mkdir,
7
- open,
8
- readFile,
9
- rename,
10
- rm,
11
- unlink,
12
- writeFile,
4
+ access,
5
+ copyFile,
6
+ mkdir,
7
+ open,
8
+ readFile,
9
+ rename,
10
+ rm,
11
+ unlink,
12
+ writeFile,
13
13
  } from "node:fs/promises";
14
14
  import { resolve } from "node:path";
15
15
  import { setTimeout as delay } from "node:timers/promises";
16
16
  import { z } from "zod";
17
- import type { ResolvedConfig } from "../config";
17
+ import type { ResolvedConfig } from "@tsplc/config/build";
18
18
  import { CodesysCompilerError, compilerDiagnosticSchema } from "../diagnostics";
19
19
  import { packageDirectory } from "../package-path";
20
20
  import { codesysCommand, getHostCommand } from "./codesys-command";
21
21
  import { createCodesysHost } from "./codesys-host";
22
22
 
23
23
  const pythonDirectory = resolve(packageDirectory, "python");
24
+ /** The scripts a worker runs from its session directory; a change to any of them restarts it. */
25
+ const workerScripts = [
26
+ "build.py",
27
+ "hardware.py",
28
+ "worker.py",
29
+ "codesys_online.py",
30
+ "codesys_login.py",
31
+ ];
24
32
 
25
33
  const sessionSchema = z.object({
26
- directory: z.string(),
27
- fingerprint: z.string(),
28
- pid: z.int().positive(),
34
+ directory: z.string(),
35
+ fingerprint: z.string(),
36
+ pid: z.int().positive(),
29
37
  });
30
38
 
31
39
  type Session = z.infer<typeof sessionSchema>;
32
40
 
33
41
  type WorkerCommand =
34
- | { action: "build" | "online" | "ping" | "stop" }
35
- | { action: "prepare"; project: string }
36
- | { action: "login"; arguments: Record<string, unknown> };
42
+ | { action: "build" | "online" | "ping" | "stop" }
43
+ | { action: "prepare"; project: string }
44
+ | { action: "login"; arguments: Record<string, unknown> };
37
45
 
38
46
  const hasCode = (error: unknown, code: string) =>
39
- error instanceof Error && "code" in error && error.code === code;
47
+ error instanceof Error && "code" in error && error.code === code;
40
48
 
41
49
  const isProcessAlive = (pid: number) => {
42
- try {
43
- // Signal 0 checks process existence and permissions without killing it.
44
- // Only ESRCH means it is gone; permission errors must still propagate.
45
- process.kill(pid, 0);
46
- return true;
47
- } catch (error) {
48
- if (hasCode(error, "ESRCH")) {
49
- return false;
50
- }
51
- throw error;
52
- }
50
+ try {
51
+ // Signal 0 checks process existence and permissions without killing it.
52
+ // Only ESRCH means it is gone; permission errors must still propagate.
53
+ process.kill(pid, 0);
54
+ return true;
55
+ } catch (error) {
56
+ if (hasCode(error, "ESRCH")) {
57
+ return false;
58
+ }
59
+ throw error;
60
+ }
53
61
  };
54
62
 
55
63
  const readJson = async (path: string): Promise<unknown> => {
56
- try {
57
- return JSON.parse(await readFile(path, "utf8"));
58
- } catch (error) {
59
- if (hasCode(error, "ENOENT")) {
60
- return undefined;
61
- }
62
- throw error;
63
- }
64
+ try {
65
+ return JSON.parse(await readFile(path, "utf8"));
66
+ } catch (error) {
67
+ if (hasCode(error, "ENOENT")) {
68
+ return undefined;
69
+ }
70
+ throw error;
71
+ }
64
72
  };
65
73
 
66
74
  export const writeJson = async (path: string, value: unknown) => {
67
- // Readers may poll while we write. A temporary file in the same directory
68
- // lets rename publish the complete JSON atomically, without exposing partial data.
69
- const temporary = `${path}.${randomUUID()}.tmp`;
70
- await writeFile(temporary, JSON.stringify(value, null, 2));
71
- await rename(temporary, path);
75
+ // Readers may poll while we write. A temporary file in the same directory
76
+ // lets rename publish the complete JSON atomically, without exposing partial data.
77
+ const temporary = `${path}.${randomUUID()}.tmp`;
78
+ await writeFile(temporary, JSON.stringify(value, null, 2));
79
+ await rename(temporary, path);
72
80
  };
73
81
 
74
82
  /** Serializes startup and builds across CLI processes, including separate terminals. */
75
83
  export const withWorkerLock = async <T>(
76
- config: Pick<ResolvedConfig, "outDir" | "timeouts">,
77
- run: () => Promise<T>,
84
+ config: Pick<ResolvedConfig, "outDir" | "timeouts">,
85
+ run: () => Promise<T>,
78
86
  ) => {
79
- await mkdir(resolve(config.outDir, ".codesys"), { recursive: true });
80
- const path = resolve(config.outDir, ".codesys/command.lock");
81
- const deadline = Date.now() + config.timeouts.build + config.timeouts.startup;
82
- while (true) {
83
- const lock = await open(path, "wx").catch((error: unknown) => {
84
- if (hasCode(error, "EEXIST")) {
85
- return;
86
- }
87
- throw error;
88
- });
87
+ await mkdir(resolve(config.outDir, ".codesys"), { recursive: true });
88
+ const path = resolve(config.outDir, ".codesys/command.lock");
89
+ const deadline = Date.now() + config.timeouts.build + config.timeouts.startup;
90
+ while (true) {
91
+ const lock = await open(path, "wx").catch((error: unknown) => {
92
+ if (hasCode(error, "EEXIST")) {
93
+ return;
94
+ }
95
+ throw error;
96
+ });
89
97
 
90
- if (lock) {
91
- try {
92
- await lock.writeFile(String(process.pid));
93
- return await run();
94
- } finally {
95
- await lock.close();
96
- await unlink(path);
97
- }
98
- }
98
+ if (lock) {
99
+ try {
100
+ await lock.writeFile(String(process.pid));
101
+ return await run();
102
+ } finally {
103
+ await lock.close();
104
+ await unlink(path);
105
+ }
106
+ }
99
107
 
100
- const owner = Number(
101
- await readFile(path, "utf8").catch((error: unknown) => {
102
- if (hasCode(error, "ENOENT")) {
103
- return "";
104
- }
105
- throw error;
106
- }),
107
- );
108
- if (owner > 0 && !isProcessAlive(owner)) {
109
- // Do not race another client by deleting a lock that it may have replaced.
110
- throw new Error(`An interrupted command left ${path}. Remove that lock file and retry.`);
111
- }
112
- if (Date.now() >= deadline) {
113
- throw new Error(`Timed out waiting for another CODESYS command (${path})`);
114
- }
115
- await delay(200);
116
- }
108
+ const owner = Number(
109
+ await readFile(path, "utf8").catch((error: unknown) => {
110
+ if (hasCode(error, "ENOENT")) {
111
+ return "";
112
+ }
113
+ throw error;
114
+ }),
115
+ );
116
+ if (owner > 0 && !isProcessAlive(owner)) {
117
+ // Do not race another client by deleting a lock that it may have replaced.
118
+ throw new Error(
119
+ `An interrupted command left ${path}. Remove that lock file and retry.`,
120
+ );
121
+ }
122
+ if (Date.now() >= deadline) {
123
+ throw new Error(
124
+ `Timed out waiting for another CODESYS command (${path})`,
125
+ );
126
+ }
127
+ await delay(200);
128
+ }
117
129
  };
118
130
 
119
131
  /** The caller holds withWorkerLock throughout a command, so the mailbox has one writer. */
120
132
  export const createCodesysWorker = (config: ResolvedConfig) => {
121
- const host = createCodesysHost(config);
122
- const statePath = resolve(config.outDir, ".codesys/session.json");
123
- const verifiedProcesses = new Set<number>();
133
+ const host = createCodesysHost(config);
134
+ const statePath = resolve(config.outDir, ".codesys/session.json");
135
+ const verifiedProcesses = new Set<number>();
124
136
 
125
- const readSession = async (): Promise<Session | undefined> => {
126
- const value = await readJson(statePath);
127
- if (value === undefined) {
128
- return undefined;
129
- }
130
- const session = sessionSchema.safeParse(value);
131
- if (!session.success) {
132
- throw new Error(`Invalid CODESYS session file: ${statePath}`, {
133
- cause: session.error,
134
- });
135
- }
136
- return session.data;
137
- };
137
+ const readSession = async (): Promise<Session | undefined> => {
138
+ const value = await readJson(statePath);
139
+ if (value === undefined) {
140
+ return undefined;
141
+ }
142
+ const session = sessionSchema.safeParse(value);
143
+ if (!session.success) {
144
+ throw new Error(`Invalid CODESYS session file: ${statePath}`, {
145
+ cause: session.error,
146
+ });
147
+ }
148
+ return session.data;
149
+ };
138
150
 
139
- const terminate = async (session: Session) => {
140
- if (isProcessAlive(session.pid)) {
141
- await host.terminate(session.pid).catch((error: unknown) => {
142
- if (isProcessAlive(session.pid)) {
143
- throw error;
144
- }
145
- });
146
- }
147
- // Let the launcher reap its child before another error handler or CLI
148
- // checks this PID. Sending a second group kill can otherwise race exit.
149
- const deadline = Date.now() + config.timeouts.terminate;
150
- while (isProcessAlive(session.pid)) {
151
- if (Date.now() >= deadline) {
152
- throw new Error("CODESYS launcher did not exit after termination");
153
- }
154
- await delay(50);
155
- }
156
- };
151
+ const terminate = async (session: Session) => {
152
+ if (isProcessAlive(session.pid)) {
153
+ await host.terminate(session.pid).catch((error: unknown) => {
154
+ if (isProcessAlive(session.pid)) {
155
+ throw error;
156
+ }
157
+ });
158
+ }
159
+ // Let the launcher reap its child before another error handler or CLI
160
+ // checks this PID. Sending a second group kill can otherwise race exit.
161
+ const deadline = Date.now() + config.timeouts.terminate;
162
+ while (isProcessAlive(session.pid)) {
163
+ if (Date.now() >= deadline) {
164
+ throw new Error("CODESYS launcher did not exit after termination");
165
+ }
166
+ await delay(50);
167
+ }
168
+ };
157
169
 
158
- const request = async (session: Session, command: WorkerCommand, timeoutMs: number) => {
159
- const id = randomUUID();
160
- const reply = resolve(session.directory, `${id}.json`);
161
- await writeJson(resolve(session.directory, "request.json"), {
162
- ...command,
163
- id,
164
- });
165
- const deadline = Date.now() + timeoutMs;
166
- while (true) {
167
- const result = await readJson(reply);
168
- if (result !== undefined) {
169
- await unlink(reply);
170
- const response = z
171
- .object({
172
- error: z.string().optional(),
173
- diagnostics: z.array(compilerDiagnosticSchema).optional(),
174
- id: z.literal(id),
175
- ok: z.boolean(),
176
- result: z.unknown(),
177
- })
178
- .safeParse(result);
179
- if (!response.success) {
180
- throw new Error("CODESYS returned an invalid worker response", {
181
- cause: response.error,
182
- });
183
- }
184
- verifiedProcesses.add(session.pid);
185
- if (!response.data.ok) {
186
- const message = response.data.error ?? "CODESYS build failed";
187
- if (response.data.diagnostics) {
188
- throw new CodesysCompilerError(message, response.data.diagnostics);
189
- }
190
- throw new Error(message);
191
- }
192
- return response.data.result;
193
- }
194
- if (!isProcessAlive(session.pid)) {
195
- throw new Error(
196
- `CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,
197
- );
198
- }
199
- if (Date.now() >= deadline) {
200
- // A saved PID can belong to another process after a reboot. Only kill
201
- // a process we launched or whose worker answered in this invocation.
202
- if (!verifiedProcesses.has(session.pid)) {
203
- throw new Error(
204
- `CODESYS ${command.action} timed out without a worker response. Close the dedicated IDE if it is still running, then retry. Log: ${session.directory}/codesys.log`,
205
- );
206
- }
207
- await terminate(session);
208
- throw new Error(
209
- `CODESYS ${command.action} timed out after ${timeoutMs} ms; the worker was stopped. See ${session.directory}/codesys.log`,
210
- );
211
- }
212
- await delay(200);
213
- }
214
- };
170
+ const request = async (
171
+ session: Session,
172
+ command: WorkerCommand,
173
+ timeoutMs: number,
174
+ ) => {
175
+ const id = randomUUID();
176
+ const reply = resolve(session.directory, `${id}.json`);
177
+ await writeJson(resolve(session.directory, "request.json"), {
178
+ ...command,
179
+ id,
180
+ });
181
+ const deadline = Date.now() + timeoutMs;
182
+ while (true) {
183
+ const result = await readJson(reply);
184
+ if (result !== undefined) {
185
+ await unlink(reply);
186
+ const response = z
187
+ .object({
188
+ error: z.string().optional(),
189
+ diagnostics: z.array(compilerDiagnosticSchema).optional(),
190
+ id: z.literal(id),
191
+ ok: z.boolean(),
192
+ result: z.unknown(),
193
+ })
194
+ .safeParse(result);
195
+ if (!response.success) {
196
+ throw new Error("CODESYS returned an invalid worker response", {
197
+ cause: response.error,
198
+ });
199
+ }
200
+ verifiedProcesses.add(session.pid);
201
+ if (!response.data.ok) {
202
+ const message = response.data.error ?? "CODESYS build failed";
203
+ if (response.data.diagnostics) {
204
+ throw new CodesysCompilerError(message, response.data.diagnostics);
205
+ }
206
+ throw new Error(message);
207
+ }
208
+ return response.data.result;
209
+ }
210
+ if (!isProcessAlive(session.pid)) {
211
+ throw new Error(
212
+ `CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,
213
+ );
214
+ }
215
+ if (Date.now() >= deadline) {
216
+ // A saved PID can belong to another process after a reboot. Only kill
217
+ // a process we launched or whose worker answered in this invocation.
218
+ if (!verifiedProcesses.has(session.pid)) {
219
+ throw new Error(
220
+ `CODESYS ${command.action} timed out without a worker response. Close the dedicated IDE if it is still running, then retry. Log: ${session.directory}/codesys.log`,
221
+ );
222
+ }
223
+ await terminate(session);
224
+ throw new Error(
225
+ `CODESYS ${command.action} timed out after ${timeoutMs} ms; the worker was stopped. See ${session.directory}/codesys.log`,
226
+ );
227
+ }
228
+ await delay(200);
229
+ }
230
+ };
215
231
 
216
- const launch = async () => {
217
- await access(config.codesys.executable);
218
- const fingerprint = createHash("sha256")
219
- .update(
220
- JSON.stringify({
221
- builder: await readFile(resolve(pythonDirectory, "build.py"), "utf8"),
222
- hardware: await readFile(resolve(pythonDirectory, "hardware.py"), "utf8"),
223
- online: await readFile(resolve(pythonDirectory, "codesys_online.py"), "utf8"),
224
- login: await readFile(resolve(pythonDirectory, "codesys_login.py"), "utf8"),
225
- command: codesysCommand,
226
- codesys: config.codesys,
227
- launcher: getHostCommand(config.codesys),
228
- worker: await readFile(resolve(pythonDirectory, "worker.py"), "utf8"),
229
- }),
230
- )
231
- .digest("hex");
232
- const previous = await readSession();
233
- if (previous && isProcessAlive(previous.pid)) {
234
- if (previous.fingerprint !== fingerprint) {
235
- throw new Error(
236
- "CODESYS settings or worker scripts changed. Run stop-worker, then launch-worker to reload them.",
237
- );
238
- }
239
- await request(previous, { action: "ping" }, config.timeouts.startup);
240
- console.log(
241
- `Reusing CODESYS worker (${previous.pid}). Log: ${previous.directory}/codesys.log`,
242
- );
243
- return previous;
244
- }
232
+ const launch = async () => {
233
+ await access(config.codesys.executable);
234
+ const fingerprint = createHash("sha256")
235
+ .update(
236
+ JSON.stringify({
237
+ scripts: await Promise.all(
238
+ workerScripts.map((script) =>
239
+ readFile(resolve(pythonDirectory, script), "utf8"),
240
+ ),
241
+ ),
242
+ command: codesysCommand,
243
+ codesys: config.codesys,
244
+ launcher: getHostCommand(config.codesys),
245
+ }),
246
+ )
247
+ .digest("hex");
248
+ const previous = await readSession();
249
+ if (previous && isProcessAlive(previous.pid)) {
250
+ if (previous.fingerprint !== fingerprint) {
251
+ throw new Error(
252
+ "CODESYS settings or worker scripts changed. Run stop-worker, then launch-worker to reload them.",
253
+ );
254
+ }
255
+ await request(previous, { action: "ping" }, config.timeouts.startup);
256
+ console.log(
257
+ `Reusing CODESYS worker (${previous.pid}). Log: ${previous.directory}/codesys.log`,
258
+ );
259
+ return previous;
260
+ }
245
261
 
246
- const directory = resolve(config.outDir, ".codesys/worker");
247
- await rm(directory, { recursive: true, force: true });
248
- await mkdir(directory, { recursive: true });
249
- for (const script of [
250
- "build.py",
251
- "hardware.py",
252
- "worker.py",
253
- "codesys_online.py",
254
- "codesys_login.py",
255
- ]) {
256
- await copyFile(resolve(pythonDirectory, script), resolve(directory, script));
257
- }
258
- console.log(`Starting CODESYS. Log: ${directory}/codesys.log`);
259
- const pid = await host.startWorker(directory);
260
- const session = { directory, fingerprint, pid };
261
- verifiedProcesses.add(pid);
262
- try {
263
- await writeJson(statePath, session);
264
- await request(session, { action: "ping" }, config.timeouts.startup);
265
- } catch (error) {
266
- await terminate(session);
267
- throw error;
268
- }
269
- console.log(`CODESYS worker ready (${session.pid})`);
270
- return session;
271
- };
262
+ const directory = resolve(config.outDir, ".codesys/worker");
263
+ await rm(directory, { recursive: true, force: true });
264
+ await mkdir(directory, { recursive: true });
265
+ for (const script of workerScripts) {
266
+ await copyFile(
267
+ resolve(pythonDirectory, script),
268
+ resolve(directory, script),
269
+ );
270
+ }
271
+ console.log(`Starting CODESYS. Log: ${directory}/codesys.log`);
272
+ const pid = await host.startWorker(directory);
273
+ const session = { directory, fingerprint, pid };
274
+ verifiedProcesses.add(pid);
275
+ try {
276
+ await writeJson(statePath, session);
277
+ await request(session, { action: "ping" }, config.timeouts.startup);
278
+ } catch (error) {
279
+ await terminate(session);
280
+ throw error;
281
+ }
282
+ console.log(`CODESYS worker ready (${session.pid})`);
283
+ return session;
284
+ };
272
285
 
273
- const checkExit = async (session: Session) => {
274
- const status = await host.exitStatus(session.directory, session.pid);
275
- if (!status) {
276
- throw new Error(
277
- `CODESYS launcher stopped but its exit status is unavailable. See ${session.directory}/codesys.log`,
278
- );
279
- }
280
- if (status.code !== 0 || status.signal !== null) {
281
- throw new Error(
282
- `CODESYS launcher exited with ${status.signal ?? status.code ?? "unknown status"}. See ${session.directory}/codesys.log`,
283
- );
284
- }
285
- };
286
+ const checkExit = async (session: Session) => {
287
+ const status = await host.exitStatus(session.directory, session.pid);
288
+ if (!status) {
289
+ throw new Error(
290
+ `CODESYS launcher stopped but its exit status is unavailable. See ${session.directory}/codesys.log`,
291
+ );
292
+ }
293
+ if (status.code !== 0 || status.signal !== null) {
294
+ throw new Error(
295
+ `CODESYS launcher exited with ${status.signal ?? status.code ?? "unknown status"}. See ${session.directory}/codesys.log`,
296
+ );
297
+ }
298
+ };
286
299
 
287
- const stop = async () => {
288
- const session = await readSession();
289
- if (!session) {
290
- console.log("CODESYS worker is already stopped");
291
- return;
292
- }
293
- if (!isProcessAlive(session.pid)) {
294
- await checkExit(session);
295
- console.log("CODESYS worker is already stopped");
296
- return;
297
- }
298
- await request(session, { action: "stop" }, config.timeouts.stop);
299
- const deadline = Date.now() + config.timeouts.stop;
300
- while (isProcessAlive(session.pid)) {
301
- if (Date.now() >= deadline) {
302
- const message = `CODESYS stop timed out after ${config.timeouts.stop} ms. See ${session.directory}/codesys.log`;
303
- try {
304
- await terminate(session);
305
- } catch (cause) {
306
- throw new Error(`${message}; the worker could not be terminated`, { cause });
307
- }
308
- throw new Error(`${message}; the worker required forced termination`);
309
- }
310
- await delay(200);
311
- }
312
- await checkExit(session);
313
- console.log("CODESYS worker stopped");
314
- };
300
+ const stop = async () => {
301
+ const session = await readSession();
302
+ if (!session) {
303
+ console.log("CODESYS worker is already stopped");
304
+ return;
305
+ }
306
+ if (!isProcessAlive(session.pid)) {
307
+ await checkExit(session);
308
+ console.log("CODESYS worker is already stopped");
309
+ return;
310
+ }
311
+ await request(session, { action: "stop" }, config.timeouts.stop);
312
+ const deadline = Date.now() + config.timeouts.stop;
313
+ while (isProcessAlive(session.pid)) {
314
+ if (Date.now() >= deadline) {
315
+ const message = `CODESYS stop timed out after ${config.timeouts.stop} ms. See ${session.directory}/codesys.log`;
316
+ try {
317
+ await terminate(session);
318
+ } catch (cause) {
319
+ throw new Error(`${message}; the worker could not be terminated`, {
320
+ cause,
321
+ });
322
+ }
323
+ throw new Error(`${message}; the worker required forced termination`);
324
+ }
325
+ await delay(200);
326
+ }
327
+ await checkExit(session);
328
+ console.log("CODESYS worker stopped");
329
+ };
315
330
 
316
- /** Whether the session's CODESYS still runs; one that died fails every request. */
317
- const alive = (session: Session) => isProcessAlive(session.pid);
331
+ /** Whether the session's CODESYS still runs; one that died fails every request. */
332
+ const alive = (session: Session) => isProcessAlive(session.pid);
318
333
 
319
- return { launch, request, stop, alive };
334
+ return { launch, request, stop, alive };
320
335
  };
321
336
 
322
337
  /** Container jobs own a temporary worker; always stop it before returning a result. */
323
338
  export const withWorkerShutdown = async <T>(
324
- config: ResolvedConfig,
325
- worker: Pick<ReturnType<typeof createCodesysWorker>, "stop">,
326
- operation: () => Promise<T>,
339
+ config: ResolvedConfig,
340
+ worker: Pick<ReturnType<typeof createCodesysWorker>, "stop">,
341
+ operation: () => Promise<T>,
327
342
  ) => {
328
- const stop = async () => {
329
- try {
330
- await withWorkerLock(config, () => worker.stop());
331
- } finally {
332
- await rm(resolve(config.outDir, ".codesys/session.json"), { force: true });
333
- }
334
- };
335
- return Promise.resolve()
336
- .then(operation)
337
- .then(
338
- async (result) => {
339
- await stop();
340
- return result;
341
- },
342
- async (failure: unknown) => {
343
- await stop().catch((shutdownFailure: unknown) => {
344
- // Diagnostic mapping follows cause; keep the operation there and
345
- // expose its shutdown failure alongside it in errors.
346
- throw new AggregateError(
347
- [failure, shutdownFailure],
348
- "CODESYS operation and worker shutdown failed",
349
- {
350
- cause: failure,
351
- },
352
- );
353
- });
354
- throw failure;
355
- },
356
- );
343
+ const stop = async () => {
344
+ try {
345
+ await withWorkerLock(config, () => worker.stop());
346
+ } finally {
347
+ await rm(resolve(config.outDir, ".codesys/session.json"), {
348
+ force: true,
349
+ });
350
+ }
351
+ };
352
+ return Promise.resolve()
353
+ .then(operation)
354
+ .then(
355
+ async (result) => {
356
+ await stop();
357
+ return result;
358
+ },
359
+ async (failure: unknown) => {
360
+ await stop().catch((shutdownFailure: unknown) => {
361
+ // Diagnostic mapping follows cause; keep the operation there and
362
+ // expose its shutdown failure alongside it in errors.
363
+ throw new AggregateError(
364
+ [failure, shutdownFailure],
365
+ "CODESYS operation and worker shutdown failed",
366
+ {
367
+ cause: failure,
368
+ },
369
+ );
370
+ });
371
+ throw failure;
372
+ },
373
+ );
357
374
  };