@tsplc/compiler 0.4.4 → 0.5.1

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.
@@ -22,6 +22,7 @@ import {
22
22
  } from "@tsplc/config";
23
23
  import { resolveConfig } from "@tsplc/config/build";
24
24
  import { generateProject } from "@tsplc/typegen";
25
+ import { runInBun } from "../runtime/process.ts";
25
26
  import {
26
27
  buildConfigs,
27
28
  buildProject,
@@ -60,6 +61,8 @@ export interface ProjectFlags {
60
61
  server?: boolean;
61
62
  simulate?: boolean;
62
63
  runtime?: boolean;
64
+ bun?: boolean;
65
+ foreground?: boolean;
63
66
  target?: string;
64
67
  }
65
68
 
@@ -87,6 +90,14 @@ export const checkProjectFlags = (
87
90
  if (flags.runtime && command !== "configure") {
88
91
  throw new Error("--runtime applies only to configure.");
89
92
  }
93
+ if (flags.bun && (command !== "run" || !flags.simulate)) {
94
+ throw new Error(
95
+ "--bun applies only to run --simulate: the Bun runtime has no fieldbus, so a plant simulator writes its inputs.",
96
+ );
97
+ }
98
+ if (flags.foreground && !flags.bun) {
99
+ throw new Error("--foreground applies only to run --simulate --bun.");
100
+ }
90
101
  if ((flags.plc || flags.server) && command !== "build") {
91
102
  throw new Error("--plc and --server apply only to build.");
92
103
  }
@@ -247,7 +258,7 @@ const buildPlc = async (
247
258
  const { config } = loaded;
248
259
  if (config.compiler) {
249
260
  // The build's analysis already read the targets; `--format json` reports the rest.
250
- const { targets, ...built } = await buildProject(file, {
261
+ const { targets, services, ...built } = await buildProject(file, {
251
262
  progress,
252
263
  environment,
253
264
  emitOnly: flags["emit-only"],
@@ -261,7 +272,7 @@ const buildPlc = async (
261
272
  throw new DiagnosticFailure(built);
262
273
  }
263
274
  await generateProject(file, { loaded, targets });
264
- return built;
275
+ return { built, services };
265
276
  }
266
277
  if (flags["emit-only"]) {
267
278
  throw new Error("Raw Structured Text is already emitted.");
@@ -275,7 +286,7 @@ const buildPlc = async (
275
286
  { progress },
276
287
  );
277
288
  await generateProject(file, { hardwareOnly: !config.typegen, loaded });
278
- return built;
289
+ return { built, services: undefined };
279
290
  };
280
291
 
281
292
  /** The PLC program and, unless `--plc` or `--emit-only` restricts it, the configured server. */
@@ -298,7 +309,7 @@ const build = async (
298
309
  const serverCheck = withServer ? checkServer(config, root) : undefined;
299
310
  // A failed PLC build reports its own diagnostics; the check's outcome is read only after a success.
300
311
  serverCheck?.catch(() => undefined);
301
- const plc = await buildPlc("build", file, checked, flags, context);
312
+ const { built: plc } = await buildPlc("build", file, checked, flags, context);
302
313
  if (!serverCheck) {
303
314
  return plc;
304
315
  }
@@ -308,11 +319,17 @@ const build = async (
308
319
  const run = async (
309
320
  file: string,
310
321
  checked: CheckedConfig,
311
- flags: Pick<ProjectFlags, "frozen-lockfile" | "simulate">,
322
+ flags: Pick<
323
+ ProjectFlags,
324
+ "frozen-lockfile" | "simulate" | "bun" | "foreground" | "target"
325
+ >,
312
326
  context: CommandContext,
313
327
  ) => {
328
+ if (flags.bun) {
329
+ return runInBunRuntime(file, checked, flags, context);
330
+ }
314
331
  const { config, configFile } = checked.loaded;
315
- const built = await buildPlc("run", file, checked, flags, context);
332
+ const { built } = await buildPlc("run", file, checked, flags, context);
316
333
  if (!config.build) {
317
334
  throw new Error("Configure build to run this project.");
318
335
  }
@@ -327,6 +344,43 @@ const run = async (
327
344
  return built;
328
345
  };
329
346
 
347
+ /** Emits the program and runs its TypeScript in the Bun runtime instead of CODESYS. */
348
+ const runInBunRuntime = async (
349
+ file: string,
350
+ checked: CheckedConfig,
351
+ flags: Pick<
352
+ ProjectFlags,
353
+ "frozen-lockfile" | "simulate" | "foreground" | "target"
354
+ >,
355
+ context: CommandContext,
356
+ ) => {
357
+ const { config, configFile, root } = checked.loaded;
358
+ if (!config.compiler) {
359
+ throw new Error(
360
+ "The Bun runtime runs a TypeScript program; this project builds raw Structured Text.",
361
+ );
362
+ }
363
+ const { built, services } = await buildPlc(
364
+ "run",
365
+ file,
366
+ checked,
367
+ { ...flags, "emit-only": true },
368
+ context,
369
+ );
370
+ const runtime = await runInBun({
371
+ root,
372
+ launch: {
373
+ config: configFile,
374
+ target: flags.target ?? null,
375
+ services: services ?? {},
376
+ },
377
+ environment: context.environment,
378
+ foreground: flags.foreground ?? false,
379
+ progress: context.progress,
380
+ });
381
+ return { ...built, runtime };
382
+ };
383
+
330
384
  /** Downloads or online-changes the program on the configured controller. */
331
385
  const updateProgram = async (
332
386
  operation: "download" | "online-change",
@@ -49,6 +49,7 @@ import {
49
49
  type ProjectTargets,
50
50
  resolveIo,
51
51
  } from "@tsplc/typegen";
52
+ import { serviceRoutes } from "../runtime/launch.ts";
52
53
  import {
53
54
  cleanArtifacts,
54
55
  engineeringDirectory,
@@ -318,6 +319,8 @@ export async function buildProject(
318
319
  controllerConfig?: ReturnType<typeof codesysBuildConfig>;
319
320
  /** What `projectTargets` reads from the program, from this build's own analysis. */
320
321
  targets?: ProjectTargets;
322
+ /** The route of each service procedure the program calls, as `serviceRoutes` reads them. */
323
+ services?: Readonly<Record<string, string>>;
321
324
  diagnostics: readonly Diagnostic[];
322
325
  }> {
323
326
  let staging: string | undefined;
@@ -452,6 +455,7 @@ export async function buildProject(
452
455
  status,
453
456
  ...(controllerConfig && { controllerConfig }),
454
457
  targets: coreTargets(checked.plan.core),
458
+ services: serviceRoutes(checked.plan.core),
455
459
  diagnostics: [...checked.diagnostics, ...bundle.diagnostics],
456
460
  };
457
461
  } catch (cause) {
@@ -0,0 +1,200 @@
1
+ import { httpErrors, jobError } from "@tsplc/compiler/ir";
2
+ import { plcBufferBytes } from "@tsplc/server/wire";
3
+
4
+ /** How the program's HTTP calls reach their servers, as the build compiled them. */
5
+ export interface HttpSettings {
6
+ /** The services' base URL, from `server.baseUrlEnv`; null without a server. */
7
+ baseUrl: string | null;
8
+ /** Each service procedure's route, by its path such as `catalog.resolve`. */
9
+ routes: Readonly<Record<string, string>>;
10
+ /** Bearer tokens by the exact origin they are sent to. */
11
+ tokens: ReadonlyMap<string, string>;
12
+ timeoutMs: number;
13
+ }
14
+
15
+ /** Why the program's call failed, as a compiled call reports it: a job error code. */
16
+ const failure = (cause: unknown) => {
17
+ if (cause instanceof Error && cause.name === "TimeoutError") {
18
+ return jobError.timeout;
19
+ }
20
+ const code =
21
+ cause instanceof Error && "code" in cause ? String(cause.code) : "";
22
+ return /CERT|SSL|TLS|SELF_SIGNED|UNABLE_TO_VERIFY/.test(code)
23
+ ? jobError.tls
24
+ : jobError.network;
25
+ };
26
+
27
+ /** The body of a response, at most the PLC's buffer; undefined when larger. */
28
+ const boundedBody = async (response: Response) => {
29
+ const declared = response.headers.get("content-length");
30
+ if (declared !== null && Number(declared) > plcBufferBytes) {
31
+ await response.body?.cancel();
32
+ return undefined;
33
+ }
34
+ const body = new Uint8Array(await response.arrayBuffer());
35
+ return body.length > plcBufferBytes ? undefined : body;
36
+ };
37
+
38
+ /**
39
+ * One HTTP exchange as a compiled call makes it: bounded JSON both ways, the bearer token of the
40
+ * URL's origin, the configured timeout and no retry. It rejects with the compiled call's error
41
+ * code, a number, never an Error.
42
+ */
43
+ export const httpCall = async (
44
+ settings: Pick<HttpSettings, "tokens" | "timeoutMs">,
45
+ url: string,
46
+ request: { method: string; body?: string },
47
+ ): Promise<unknown> => {
48
+ const { body } = request;
49
+ if (body !== undefined && Buffer.byteLength(body, "utf8") > plcBufferBytes) {
50
+ throw jobError.tooLarge;
51
+ }
52
+ const token = settings.tokens.get(URL.parse(url)?.origin ?? "");
53
+ const response = await globalThis
54
+ .fetch(url, {
55
+ method: request.method,
56
+ headers: {
57
+ Accept: "application/json",
58
+ ...(body !== undefined && { "Content-Type": "application/json" }),
59
+ ...(token !== undefined && { Authorization: `Bearer ${token}` }),
60
+ },
61
+ ...(body !== undefined && { body }),
62
+ signal: AbortSignal.timeout(settings.timeoutMs),
63
+ })
64
+ .catch((cause: unknown) => {
65
+ throw failure(cause);
66
+ });
67
+ const reply = await boundedBody(response).catch((cause: unknown) => {
68
+ throw failure(cause);
69
+ });
70
+ if (!reply) {
71
+ throw jobError.tooLarge;
72
+ }
73
+ if (!response.ok) {
74
+ throw Math.min(httpErrors.base + response.status, httpErrors.last);
75
+ }
76
+ try {
77
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(reply));
78
+ } catch {
79
+ throw jobError.malformedResponse;
80
+ }
81
+ };
82
+
83
+ /** An SDK function the Bun runtime has no implementation of: it throws when the program calls it. */
84
+ export const unsupported = (name: string) => () => {
85
+ throw new Error(
86
+ `${name} is not supported by the Bun runtime; run this program on CODESYS.`,
87
+ );
88
+ };
89
+
90
+ /** What the program's `@tsplc/compiler/async` does in the Bun runtime. */
91
+ export const createAsync = (
92
+ settings: HttpSettings,
93
+ diagnostics: { count: number; lastError: number },
94
+ ) => {
95
+ const call = (path: string, input: unknown) => {
96
+ const route = settings.routes[path];
97
+ if (!route || settings.baseUrl === null) {
98
+ return Promise.reject(
99
+ new Error(`The build compiled no call to the service ${path}.`),
100
+ );
101
+ }
102
+ return httpCall(settings, `${settings.baseUrl}${route}`, {
103
+ method: "POST",
104
+ body: JSON.stringify(input),
105
+ });
106
+ };
107
+ /** A service client: any property is a deeper procedure path, and calling one calls that procedure. */
108
+ const client = (path: readonly string[]): unknown =>
109
+ new Proxy(() => undefined, {
110
+ get: (_, key) =>
111
+ typeof key === "string" ? client([...path, key]) : undefined,
112
+ apply: (_, __, [input]: unknown[]) => call(path.join("."), input),
113
+ });
114
+ return {
115
+ createServiceClient: () => client([]),
116
+ fetch: (url: string, options: { method?: string; json?: unknown } = {}) =>
117
+ httpCall(settings, url, {
118
+ method: options.method ?? "GET",
119
+ ...(options.json !== undefined && {
120
+ body: JSON.stringify(options.json),
121
+ }),
122
+ }),
123
+ // A sleep resumes on a later scan, even `sleep(ms(0))`: scans never yield to timers.
124
+ sleep: (duration: number) =>
125
+ new Promise<void>((resolve) => setTimeout(resolve, duration)),
126
+ errorCode: (reason: unknown) => (typeof reason === "number" ? reason : 0),
127
+ asyncDiagnostics: () => ({ valid: true, ...diagnostics }),
128
+ cancelAsync: unsupported("cancelAsync"),
129
+ opcuaCall: unsupported("opcuaCall"),
130
+ tasks: { define: unsupported("tasks.define") },
131
+ backgroundTasks: { define: unsupported("backgroundTasks.define") },
132
+ cooperativeTasks: { define: unsupported("cooperativeTasks.define") },
133
+ };
134
+ };
135
+
136
+ /** What a launch dropped because its call site was busy reports, as a compiled launch does. */
137
+ const capacityError = jobError.noRequestSlot;
138
+
139
+ /**
140
+ * A compiled program stores one invocation of each async method per instance: launching it
141
+ * from scan code while that invocation runs is dropped, counted with error 7 and never settles,
142
+ * so neither its `then` nor its `catch` runs. The program's classes get the same rule here.
143
+ * A launch from a continuation is an awaited child, which has storage of its own, so it runs.
144
+ * `failed` names a method's rejected promise for an unhandled-failure record.
145
+ */
146
+ export const oneLaunchAtATime = (
147
+ classes: Iterable<{ name: string; prototype: object }>,
148
+ options: {
149
+ scanning: () => boolean;
150
+ diagnostics: { count: number; lastError: number };
151
+ failed: WeakMap<Promise<unknown>, string>;
152
+ },
153
+ ) => {
154
+ const running = new WeakMap<object, Set<string>>();
155
+ for (const { name: className, prototype } of classes) {
156
+ for (const method of Object.getOwnPropertyNames(prototype)) {
157
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, method);
158
+ const original: unknown = descriptor?.value;
159
+ if (
160
+ typeof original !== "function" ||
161
+ original.constructor.name !== "AsyncFunction"
162
+ ) {
163
+ continue;
164
+ }
165
+ const name = `${className}.${method}`;
166
+ Object.defineProperty(prototype, method, {
167
+ ...descriptor,
168
+ value: function launch(this: object, ...input: unknown[]) {
169
+ if (!options.scanning()) {
170
+ return original.apply(this, input);
171
+ }
172
+ const methods = running.get(this) ?? new Set<string>();
173
+ running.set(this, methods);
174
+ if (methods.has(method)) {
175
+ options.diagnostics.count += 1;
176
+ options.diagnostics.lastError = capacityError;
177
+ return new Promise(() => {});
178
+ }
179
+ const started: unknown = original.apply(this, input);
180
+ if (!(started instanceof Promise)) {
181
+ return started;
182
+ }
183
+ methods.add(method);
184
+ const settled = started.then(
185
+ (value: unknown) => {
186
+ methods.delete(method);
187
+ return value;
188
+ },
189
+ (reason: unknown) => {
190
+ methods.delete(method);
191
+ throw reason;
192
+ },
193
+ );
194
+ options.failed.set(settled, name);
195
+ return settled;
196
+ },
197
+ });
198
+ }
199
+ }
200
+ };
@@ -0,0 +1,49 @@
1
+ import type { VerifiedCoreModule } from "@tsplc/compiler/ir";
2
+ import { generatedDirectory } from "@tsplc/config/project-files";
3
+ import { serviceOfPath } from "@tsplc/server";
4
+ import { z } from "zod";
5
+
6
+ /** The Bun runtime's files, relative to the directory that holds a project's config. */
7
+ export const runtimeDirectory = `${generatedDirectory}/runtime`;
8
+ export const runtimeFiles = {
9
+ /** What the runtime runs, written by `tsplc run --bun`. */
10
+ launch: "launch.json",
11
+ /** The running runtime, written once it serves and removed when it stops. */
12
+ state: "state.json",
13
+ /** Retained globals, written when the runtime stops. */
14
+ retain: "retain.json",
15
+ /** A detached runtime's output. */
16
+ log: "plc.log",
17
+ /** The OPC UA server's certificate store. */
18
+ certificates: "pki",
19
+ } as const;
20
+
21
+ /** What `tsplc run --bun` hands the runtime: the config to load, with its target, and how to reach the services the build compiled calls to. */
22
+ export const launchSchema = z.strictObject({
23
+ config: z.string().nonempty(),
24
+ target: z.string().nonempty().nullable(),
25
+ /** Each service procedure's route, with its wire-contract version: `/tsplc/services/<version>/<path>` by `<path>`. */
26
+ services: z.record(z.string(), z.string().startsWith("/tsplc/services/")),
27
+ });
28
+ export type Launch = z.infer<typeof launchSchema>;
29
+
30
+ /** A runtime that serves: its process and where it publishes OPC UA. */
31
+ export const runtimeStateSchema = z.strictObject({
32
+ pid: z.number().int().positive(),
33
+ endpoint: z.string().startsWith("opc.tcp://"),
34
+ startedAt: z.iso.datetime(),
35
+ });
36
+ export type RuntimeState = z.infer<typeof runtimeStateSchema>;
37
+
38
+ /** The route each service call the program makes goes to, as the build compiled it. */
39
+ export const serviceRoutes = (core: VerifiedCoreModule) =>
40
+ Object.fromEntries(
41
+ core.blocks.flatMap((block) => {
42
+ if (block.runtime?.kind !== "http") {
43
+ return [];
44
+ }
45
+ const route = URL.parse(block.runtime.url)?.pathname;
46
+ const procedure = route && serviceOfPath(route);
47
+ return route && procedure ? [[procedure, route] as const] : [];
48
+ }),
49
+ );
@@ -0,0 +1,54 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * The Bun runtime's process: runs the program a launch file names until SIGINT or SIGTERM, and
4
+ * writes the state file beside the launch file while it serves.
5
+ *
6
+ * Usage: bun main.ts <launch.json> [port]
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { rm, writeFile } from "node:fs/promises";
10
+ import { dirname, join } from "node:path";
11
+ import { launchSchema, type RuntimeState, runtimeFiles } from "./launch.ts";
12
+ import { runtimeEndpoint, startRuntime } from "./runtime.ts";
13
+
14
+ const [launchFile, port] = process.argv.slice(2);
15
+ if (!launchFile) {
16
+ throw new Error("Usage: main.ts <launch.json> [port]");
17
+ }
18
+ const stateFile = join(dirname(launchFile), runtimeFiles.state);
19
+ const log = (line: string) => console.log(`[tsplc runtime] ${line}`);
20
+ try {
21
+ const runtime = await startRuntime({
22
+ launch: launchSchema.parse(JSON.parse(readFileSync(launchFile, "utf8"))),
23
+ environment: process.env,
24
+ port: port === undefined ? runtimeEndpoint.port : Number(port),
25
+ log,
26
+ });
27
+ await writeFile(
28
+ stateFile,
29
+ `${JSON.stringify({
30
+ pid: process.pid,
31
+ endpoint: runtime.endpoint,
32
+ startedAt: new Date().toISOString(),
33
+ } satisfies RuntimeState)}\n`,
34
+ );
35
+ const stop = async (signal: string) => {
36
+ log(`Stopping on ${signal}.`);
37
+ try {
38
+ await runtime.stop();
39
+ } finally {
40
+ await rm(stateFile, { force: true });
41
+ process.exit(0);
42
+ }
43
+ };
44
+ process.once("SIGINT", stop);
45
+ process.once("SIGTERM", stop);
46
+ } catch (cause) {
47
+ console.error(
48
+ `[tsplc runtime] ${cause instanceof Error ? cause.message : String(cause)}`,
49
+ );
50
+ if (cause instanceof Error && cause.cause) {
51
+ console.error(cause.cause);
52
+ }
53
+ process.exit(1);
54
+ }
@@ -0,0 +1,172 @@
1
+ import { spawn, spawnSync } from "node:child_process";
2
+ import { existsSync, openSync } from "node:fs";
3
+ import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
4
+ import { join, relative } from "node:path";
5
+ import { setTimeout as delay } from "node:timers/promises";
6
+ import { fileURLToPath } from "node:url";
7
+ import { type ProgressStream, progressLog } from "@tsplc/build";
8
+ import {
9
+ type Launch,
10
+ type RuntimeState,
11
+ runtimeDirectory,
12
+ runtimeFiles,
13
+ runtimeStateSchema,
14
+ } from "./launch.ts";
15
+
16
+ /** How long a runtime has to start serving, and to stop. */
17
+ const startTimeoutMs = 60_000;
18
+ const stopTimeoutMs = 15_000;
19
+
20
+ /** The runtime's entry: this source tree's, or the bundle a built package ships beside the CLI. */
21
+ const runtimeScript = () => {
22
+ const script = ["./main.ts", "./bun-runtime.js"]
23
+ .map((path) => fileURLToPath(new URL(path, import.meta.url)))
24
+ .find((path) => existsSync(path));
25
+ if (!script) {
26
+ throw new Error("The Bun runtime's script is missing from this build.");
27
+ }
28
+ return script;
29
+ };
30
+
31
+ const alive = (pid: number) => {
32
+ try {
33
+ process.kill(pid, 0);
34
+ return true;
35
+ } catch {
36
+ return false;
37
+ }
38
+ };
39
+
40
+ /** Whether `pid` still runs this project's runtime, rather than a process that took over its number after a crash. */
41
+ const isRuntime = (pid: number, launchFile: string) => {
42
+ if (!alive(pid)) {
43
+ return false;
44
+ }
45
+ if (process.platform === "win32") {
46
+ return true;
47
+ }
48
+ const command = spawnSync("ps", ["-o", "command=", "-p", String(pid)], {
49
+ encoding: "utf8",
50
+ }).stdout;
51
+ return command.includes(launchFile);
52
+ };
53
+
54
+ const readState = async (file: string): Promise<RuntimeState | undefined> => {
55
+ const text = await readFile(file, "utf8").catch(() => undefined);
56
+ if (text === undefined) {
57
+ return undefined;
58
+ }
59
+ try {
60
+ return runtimeStateSchema.parse(JSON.parse(text));
61
+ } catch {
62
+ return undefined;
63
+ }
64
+ };
65
+
66
+ /** Stops the project's runtime that an earlier `run --bun` left running, which saves its retained values. */
67
+ const stopRunning = async (directory: string, log: (line: string) => void) => {
68
+ const stateFile = join(directory, runtimeFiles.state);
69
+ const state = await readState(stateFile);
70
+ if (!state || !isRuntime(state.pid, join(directory, runtimeFiles.launch))) {
71
+ await rm(stateFile, { force: true });
72
+ return;
73
+ }
74
+ log(`Stopping the Bun runtime that runs as process ${state.pid}`);
75
+ process.kill(state.pid, "SIGTERM");
76
+ const deadline = Date.now() + stopTimeoutMs;
77
+ while (alive(state.pid)) {
78
+ if (Date.now() >= deadline) {
79
+ process.kill(state.pid, "SIGKILL");
80
+ break;
81
+ }
82
+ await delay(100);
83
+ }
84
+ await rm(stateFile, { force: true });
85
+ };
86
+
87
+ /**
88
+ * Starts the program in the Bun runtime, as `tsplc run --simulate --bun` does, replacing the
89
+ * project's runtime that is running. Detached, the runtime keeps running after this returns,
90
+ * writing to its log, until the next `run --bun` replaces it or it is sent SIGTERM; in the
91
+ * foreground it runs, writing to this terminal, until it is interrupted.
92
+ */
93
+ export const runInBun = async (options: {
94
+ root: string;
95
+ launch: Launch;
96
+ environment: Readonly<Record<string, string | undefined>>;
97
+ foreground: boolean;
98
+ progress: ProgressStream;
99
+ }) => {
100
+ const log = progressLog(options.progress);
101
+ const directory = join(options.root, runtimeDirectory);
102
+ await mkdir(directory, { recursive: true });
103
+ await stopRunning(directory, log);
104
+ const launchFile = join(directory, runtimeFiles.launch);
105
+ await writeFile(launchFile, `${JSON.stringify(options.launch, null, 2)}\n`);
106
+ const logFile = join(directory, runtimeFiles.log);
107
+ const command = [runtimeScript(), launchFile];
108
+ if (options.foreground) {
109
+ log("Running the program in Bun; stop it with Ctrl-C");
110
+ const child = spawn(process.execPath, command, {
111
+ cwd: options.root,
112
+ env: options.environment,
113
+ stdio: "inherit",
114
+ });
115
+ // The terminal's Ctrl-C reaches the runtime too, so this process only waits for it to stop;
116
+ // a SIGTERM sent to this process alone is passed on.
117
+ const wait = () => undefined;
118
+ const forward = () => child.kill("SIGTERM");
119
+ process.on("SIGINT", wait);
120
+ process.on("SIGTERM", forward);
121
+ const code = await new Promise<number | null>((resolve) =>
122
+ child.once("exit", resolve),
123
+ );
124
+ process.off("SIGINT", wait);
125
+ process.off("SIGTERM", forward);
126
+ if (code !== 0) {
127
+ throw new Error(`The Bun runtime exited with code ${code}.`);
128
+ }
129
+ return { stopped: true };
130
+ }
131
+ const output = openSync(logFile, "w");
132
+ const child = spawn(process.execPath, command, {
133
+ cwd: options.root,
134
+ env: options.environment,
135
+ detached: true,
136
+ stdio: ["ignore", output, output],
137
+ });
138
+ const exited: { code: number | null; done: boolean } = {
139
+ code: null,
140
+ done: false,
141
+ };
142
+ child.once("exit", (code) => {
143
+ Object.assign(exited, { code, done: true });
144
+ });
145
+ const stateFile = join(directory, runtimeFiles.state);
146
+ const deadline = Date.now() + startTimeoutMs;
147
+ while (true) {
148
+ const state = await readState(stateFile);
149
+ if (state && state.pid === child.pid) {
150
+ child.unref();
151
+ const shown = relative(process.cwd(), logFile) || logFile;
152
+ log(
153
+ `The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`,
154
+ );
155
+ return { ...state, log: logFile };
156
+ }
157
+ if (exited.done || Date.now() >= deadline) {
158
+ if (!exited.done) {
159
+ child.kill("SIGTERM");
160
+ }
161
+ const tail = (await readFile(logFile, "utf8").catch(() => ""))
162
+ .trimEnd()
163
+ .split("\n")
164
+ .slice(-30)
165
+ .join("\n");
166
+ throw new Error(
167
+ `The Bun runtime ${exited.done ? `exited with code ${exited.code}` : "did not start in time"}:\n${tail}`,
168
+ );
169
+ }
170
+ await delay(100);
171
+ }
172
+ };