@tsplc/build 0.2.21 → 0.4.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.
Files changed (51) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +1052 -836
  3. package/dist/cli.js.map +27 -24
  4. package/dist/images.js +165 -0
  5. package/dist/images.js.map +12 -0
  6. package/dist/index.js +888 -668
  7. package/dist/index.js.map +23 -20
  8. package/dist/libraries.js +4 -3
  9. package/dist/libraries.js.map +3 -3
  10. package/docker/Dockerfile.dockerignore +0 -4
  11. package/docker/Dockerfile.source +5 -0
  12. package/docker/build-image +30 -26
  13. package/docker/config.ts +1 -1
  14. package/docker/install/wine-signal/README.md +1 -1
  15. package/docker/runner.ts +9 -7
  16. package/package.json +24 -8
  17. package/python/build.py +231 -20
  18. package/python/codesys_online.py +121 -10
  19. package/python/worker.py +2 -0
  20. package/src/artifacts.ts +9 -7
  21. package/src/build.ts +9 -4
  22. package/src/cli.ts +11 -20
  23. package/src/controller-online.ts +145 -61
  24. package/src/controller-protocol.ts +48 -5
  25. package/src/controller-session.ts +386 -147
  26. package/src/device-tree.ts +1 -1
  27. package/src/docker-build.ts +80 -98
  28. package/src/docker-context.ts +56 -3
  29. package/src/docker-run.ts +56 -3
  30. package/src/engineering-settings.ts +3 -3
  31. package/src/host/codesys-host.ts +3 -3
  32. package/src/host/codesys-worker.ts +77 -3
  33. package/src/images.ts +105 -0
  34. package/src/import-request.ts +1 -0
  35. package/src/index.ts +30 -16
  36. package/src/io.ts +1 -1
  37. package/src/libraries.ts +3 -2
  38. package/src/project-operations.ts +48 -0
  39. package/src/run.ts +9 -6
  40. package/src/sources.ts +2 -2
  41. package/docker/install/wine-signal/check.sh +0 -34
  42. package/docker/install/wine-signal/tests/avx-registers.c +0 -53
  43. package/docker/install/wine-signal/tests/frame-and-handler.c +0 -192
  44. package/docker/install/wine-signal/tests/loader-i386.c +0 -8
  45. package/docker/install/wine-signal/tests/signal-return.c +0 -47
  46. package/python/test_build.py +0 -579
  47. package/python/test_codesys_login.py +0 -139
  48. package/python/test_codesys_online.py +0 -259
  49. package/python/test_installer_packages.py +0 -217
  50. package/python/test_installer_verification.py +0 -307
  51. package/python/test_worker.py +0 -154
package/dist/index.js CHANGED
@@ -1,3 +1,11 @@
1
+ // packages/build/src/index.ts
2
+ import {
3
+ configSchema,
4
+ defineBuildConfig,
5
+ loadConfig,
6
+ resolveConfig as resolveConfig3
7
+ } from "@tsplc/config/build";
8
+
1
9
  // packages/build/src/artifacts.ts
2
10
  import {
3
11
  copyFile,
@@ -9,9 +17,9 @@ import {
9
17
  writeFile
10
18
  } from "node:fs/promises";
11
19
  import { resolve } from "node:path";
20
+ import { cyclicTasksSchema } from "@tsplc/config/build";
12
21
  import { identifierPattern } from "@tsplc/iec/st";
13
22
  import { z } from "zod";
14
- import { cyclicTasksSchema } from "@tsplc/config/build";
15
23
  var buildFiles = {
16
24
  project: "Application.project",
17
25
  output: "runtime/Application.app",
@@ -50,69 +58,12 @@ var readBuild = async (directory) => {
50
58
  checksum: resolve(directory, buildFiles.checksum)
51
59
  };
52
60
  };
53
-
54
- // packages/build/src/build.ts
55
- import { dockerImage as dockerImage2 } from "@tsplc/config/build";
56
-
57
61
  // packages/build/src/docker-build.ts
58
62
  import { randomUUID } from "node:crypto";
59
- import { cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm3 } from "node:fs/promises";
60
- import { tmpdir as tmpdir2 } from "node:os";
61
- import { resolve as resolve5 } from "node:path";
62
- import { z as z3 } from "zod";
63
- import { dockerImage } from "@tsplc/config/build";
64
-
65
- // packages/build/src/docker-context.ts
66
- import { cp as cp2, mkdir, mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
67
- import { createRequire } from "node:module";
68
- import { tmpdir } from "node:os";
69
- import { dirname, resolve as resolve3 } from "node:path";
70
-
71
- // packages/build/src/package-path.ts
72
- import { resolve as resolve2 } from "node:path";
73
- import { fileURLToPath } from "node:url";
74
- var packageDirectory = resolve2(fileURLToPath(new URL("..", import.meta.url)));
75
-
76
- // packages/build/src/docker-context.ts
77
- var containerPackages = [
78
- {
79
- entry: "@tsplc/config/build",
80
- directory: "shared-config",
81
- files: ["src", "templates", "package.json"]
82
- },
83
- {
84
- entry: "@tsplc/iec",
85
- directory: "shared-iec",
86
- files: ["src", "package.json"]
87
- }
88
- ];
89
- async function prepareDockerContext() {
90
- const context = await mkdtemp(resolve3(tmpdir(), "tsplc-docker-"));
91
- try {
92
- for (const directory of ["src", "python", "docker", "runtime"]) {
93
- await cp2(resolve3(packageDirectory, directory), resolve3(context, directory), {
94
- recursive: true
95
- });
96
- }
97
- for (const { entry, directory, files } of containerPackages) {
98
- const root = resolve3(dirname(createRequire(import.meta.url).resolve(entry)), "..");
99
- await mkdir(resolve3(context, directory));
100
- for (const file of files) {
101
- await cp2(resolve3(root, file), resolve3(context, directory, file), {
102
- recursive: true
103
- });
104
- }
105
- }
106
- await writeFile2(resolve3(context, "package.json"), JSON.stringify({
107
- type: "module",
108
- dependencies: { zod: "4.3.6", jiti: "2.7.0" }
109
- }));
110
- return context;
111
- } catch (cause) {
112
- await rm2(context, { recursive: true, force: true });
113
- throw cause;
114
- }
115
- }
63
+ import { mkdir as mkdir4, mkdtemp as mkdtemp3, readFile as readFile4, rm as rm4 } from "node:fs/promises";
64
+ import { tmpdir as tmpdir3 } from "node:os";
65
+ import { resolve as resolve6 } from "node:path";
66
+ import { z as z4 } from "zod";
116
67
 
117
68
  // packages/build/src/diagnostics.ts
118
69
  import { z as z2 } from "zod";
@@ -154,18 +105,41 @@ var buildFailureSchema = z2.strictObject({
154
105
  // packages/build/src/docker-run.ts
155
106
  import { execFile, spawn } from "node:child_process";
156
107
  import { createHash } from "node:crypto";
157
- import { copyFile as copyFile2, cp as cp3, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
158
- import { basename, posix, relative, resolve as resolve4, sep } from "node:path";
108
+ import { copyFile as copyFile2, cp as cp2, mkdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
109
+ import { basename, posix, relative, resolve as resolve2, sep } from "node:path";
159
110
  import { promisify } from "node:util";
160
111
  var execute = promisify(execFile);
161
- var captureDocker = (args, timeout) => execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
162
- var runDocker = (args, failure) => new Promise((accept, reject) => {
112
+ var progressLog = (stream) => stream === "stderr" ? console.error : console.log;
113
+ var clientEnvironment = (environment) => ({
114
+ ...process.env,
115
+ ...environment
116
+ });
117
+ var captureDocker = (args, timeout, environment = {}) => execute("docker", args, {
118
+ timeout,
119
+ maxBuffer: 8 * 1024 * 1024,
120
+ env: clientEnvironment(environment)
121
+ });
122
+ var pipeDocker = async (args, input) => {
123
+ const child = Bun.spawn(["docker", ...args], {
124
+ stdin: input === null ? "ignore" : new Blob([input]),
125
+ stdout: "pipe",
126
+ stderr: "pipe"
127
+ });
128
+ const [stdout, stderr, status] = await Promise.all([
129
+ new Response(child.stdout).text(),
130
+ new Response(child.stderr).text(),
131
+ child.exited
132
+ ]);
133
+ return { stdout, stderr, status };
134
+ };
135
+ var runDocker = (args, failure, output) => new Promise((accept, reject) => {
163
136
  const child = spawn("docker", args, {
164
137
  stdio: [
165
138
  "inherit",
166
- process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
139
+ output.progress === "stderr" ? 2 : "inherit",
167
140
  "inherit"
168
- ]
141
+ ],
142
+ env: clientEnvironment(output.environment)
169
143
  });
170
144
  const interrupt = () => child.kill("SIGINT");
171
145
  const terminate = () => child.kill("SIGTERM");
@@ -195,14 +169,14 @@ async function mountLibraries(libraries, directory, root = "/input") {
195
169
  if (!libraries?.length) {
196
170
  return;
197
171
  }
198
- await mkdir2(resolve4(directory, "libraries"), { recursive: true });
172
+ await mkdir(resolve2(directory, "libraries"), { recursive: true });
199
173
  return Promise.all(libraries.map(async (library) => {
200
174
  const data = await readFile2(library.path);
201
175
  if (createHash("sha256").update(data).digest("hex") !== library.sha256) {
202
176
  throw new Error(`Library changed after installation: ${library.title}`);
203
177
  }
204
178
  const filename = `${library.sha256}-${basename(library.path)}`;
205
- await writeFile3(resolve4(directory, "libraries", filename), data);
179
+ await writeFile2(resolve2(directory, "libraries", filename), data);
206
180
  return { ...library, path: `${root}/libraries/${filename}` };
207
181
  }));
208
182
  }
@@ -219,16 +193,16 @@ var containerConfig = (config, paths, libraries) => ({
219
193
  runtime: undefined
220
194
  });
221
195
  var writeOperationRequest = async (config, directory, root) => {
222
- await mkdir2(directory, { recursive: true });
223
- await cp3(config.sourceDir, resolve4(directory, "sources"), {
196
+ await mkdir(directory, { recursive: true });
197
+ await cp2(config.sourceDir, resolve2(directory, "sources"), {
224
198
  recursive: true
225
199
  });
226
- await copyFile2(config.template, resolve4(directory, "template.project"));
227
- await writeFile3(resolve4(directory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: `${root}/sources`, template: `${root}/template.project` }, await mountLibraries(config.libraries, directory, root))));
200
+ await copyFile2(config.template, resolve2(directory, "template.project"));
201
+ await writeFile2(resolve2(directory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: `${root}/sources`, template: `${root}/template.project` }, await mountLibraries(config.libraries, directory, root))));
228
202
  return `${root}/config.json`;
229
203
  };
230
204
  var prepareContainerRun = async (config, requestDirectory, options) => {
231
- await writeFile3(resolve4(requestDirectory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: "/sources", template: "/template.project" }, options.sources ? await mountLibraries(config.libraries, requestDirectory) : [])));
205
+ await writeFile2(resolve2(requestDirectory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: "/sources", template: "/template.project" }, options.sources ? await mountLibraries(config.libraries, requestDirectory) : [])));
232
206
  return [
233
207
  "--init",
234
208
  ...config.docker?.cpuSet ? ["--cpuset-cpus", config.docker.cpuSet] : [],
@@ -246,82 +220,206 @@ var prepareContainerRun = async (config, requestDirectory, options) => {
246
220
  ];
247
221
  };
248
222
 
249
- // packages/build/src/docker-build.ts
250
- var publishedImage = async (image) => {
251
- const { version } = z3.object({ version: z3.string() }).parse(JSON.parse(await readFile3(resolve5(packageDirectory, "package.json"), "utf8")));
252
- return `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
223
+ // packages/build/src/images.ts
224
+ import { copyFile as copyFile3, cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, rm as rm3 } from "node:fs/promises";
225
+ import { tmpdir as tmpdir2 } from "node:os";
226
+ import { resolve as resolve5 } from "node:path";
227
+ import { dockerImage } from "@tsplc/config/build";
228
+
229
+ // packages/build/src/docker-context.ts
230
+ import { cp as cp3, mkdir as mkdir2, mkdtemp, readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
231
+ import { createRequire } from "node:module";
232
+ import { tmpdir } from "node:os";
233
+ import { basename as basename2, dirname, resolve as resolve4 } from "node:path";
234
+ import { z as z3 } from "zod";
235
+
236
+ // packages/build/src/package-path.ts
237
+ import { resolve as resolve3 } from "node:path";
238
+ import { fileURLToPath } from "node:url";
239
+ var packageDirectory = resolve3(fileURLToPath(new URL("..", import.meta.url)));
240
+
241
+ // packages/build/src/docker-context.ts
242
+ var includeSource = (source) => {
243
+ const name = basename2(source);
244
+ return name !== "__pycache__" && !name.endsWith(".pyc") && !name.endsWith(".test.ts") && !name.endsWith(".fixtures.ts") && !(name.startsWith("test_") && name.endsWith(".py"));
253
245
  };
254
- var pullPublished = async (image) => {
255
- const published = await publishedImage(image);
256
- console.log(`Pulling ${published}`);
246
+ var containerPackages = [
247
+ {
248
+ entry: "@tsplc/config/build",
249
+ directory: "shared-config",
250
+ files: ["src", "templates", "package.json"]
251
+ },
252
+ {
253
+ entry: "@tsplc/iec",
254
+ directory: "shared-iec",
255
+ files: ["src", "package.json"]
256
+ }
257
+ ];
258
+ var manifestDependencies = z3.object({
259
+ name: z3.string(),
260
+ dependencies: z3.record(z3.string(), z3.string()).default({})
261
+ });
262
+ function containerDependencies(manifests) {
263
+ const selected = new Map;
264
+ for (const manifest of manifests) {
265
+ for (const [name, version] of Object.entries(manifest.dependencies)) {
266
+ if (name.startsWith("@tsplc/")) {
267
+ continue;
268
+ }
269
+ const existing = selected.get(name);
270
+ if (existing && existing.version !== version) {
271
+ throw new Error(`The builder image cannot install ${name}: ${existing.owner} pins ${existing.version} and ${manifest.name} pins ${version}.`);
272
+ }
273
+ selected.set(name, { version, owner: manifest.name });
274
+ }
275
+ }
276
+ return Object.fromEntries([...selected].map(([name, { version }]) => [name, version]));
277
+ }
278
+ var readManifest = async (directory) => manifestDependencies.parse(JSON.parse(await readFile3(resolve4(directory, "package.json"), "utf8")));
279
+ async function prepareDockerContext() {
280
+ const context = await mkdtemp(resolve4(tmpdir(), "tsplc-docker-"));
257
281
  try {
258
- await runDocker(["pull", "--platform", "linux/amd64", published], (status) => `Docker pull failed (${status})`);
259
- } catch {
260
- console.log(`${published} is not available; building ${image} locally instead.`);
261
- return false;
282
+ for (const directory of ["src", "python", "docker", "runtime"]) {
283
+ await cp3(resolve4(packageDirectory, directory), resolve4(context, directory), {
284
+ recursive: true,
285
+ filter: includeSource
286
+ });
287
+ }
288
+ const manifests = [await readManifest(packageDirectory)];
289
+ for (const { entry, directory, files } of containerPackages) {
290
+ const root = resolve4(dirname(createRequire(import.meta.url).resolve(entry)), "..");
291
+ manifests.push(await readManifest(root));
292
+ await mkdir2(resolve4(context, directory));
293
+ for (const file of files) {
294
+ await cp3(resolve4(root, file), resolve4(context, directory, file), {
295
+ recursive: true,
296
+ filter: includeSource
297
+ });
298
+ }
299
+ }
300
+ await writeFile3(resolve4(context, "package.json"), JSON.stringify({
301
+ type: "module",
302
+ dependencies: containerDependencies(manifests)
303
+ }));
304
+ return context;
305
+ } catch (cause) {
306
+ await rm2(context, { recursive: true, force: true });
307
+ throw cause;
262
308
  }
263
- await runDocker(["tag", published, image], (status) => `Docker tag failed (${status})`);
264
- return true;
265
- };
266
- var configureDocker = async () => {
267
- const image = dockerImage;
268
- const { stdout } = await captureDocker(["info", "--format", "{{.OSType}}/{{.Architecture}}"], 30000).catch((cause) => {
269
- throw new Error("Cannot connect to Docker. Install and start Docker Desktop or Docker Engine", {
270
- cause
271
- });
272
- });
273
- const architecture = stdout.trim();
274
- const arm = architecture === "linux/aarch64" || architecture === "linux/arm64";
275
- if (!arm && architecture !== "linux/x86_64" && architecture !== "linux/amd64") {
276
- throw new Error("The builder requires a Linux Docker server on ARM64 or AMD64");
309
+ }
310
+
311
+ // packages/build/src/images.ts
312
+ var builderImage = dockerImage;
313
+ var gatewayImage = "tsplc-edge-gateway:4.22.0.0";
314
+ var runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
315
+ var publishedImage = (image, version) => `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
316
+ var setupPlatformFor = (server) => {
317
+ if (server === "linux/aarch64" || server === "linux/arm64") {
318
+ return "linux/arm64";
277
319
  }
278
- if (await pullPublished(image)) {
279
- return image;
320
+ if (server === "linux/x86_64" || server === "linux/amd64") {
321
+ return "linux/amd64";
280
322
  }
281
- const context = await mkdtemp2(resolve5(tmpdir2(), "codesys-installer-"));
282
- let buildContext;
323
+ return null;
324
+ };
325
+ async function buildBuilderImage(options) {
326
+ const installerContext = await mkdtemp2(resolve5(tmpdir2(), "codesys-installer-"));
327
+ let context;
283
328
  try {
284
- buildContext = await prepareDockerContext();
285
- const cache = resolve5(context, "winetricks");
329
+ context = await prepareDockerContext();
330
+ const cache = resolve5(installerContext, "winetricks");
286
331
  await mkdir3(cache);
287
- if (process.env["CODESYS_WINETRICKS_CACHE"]) {
288
- await cp4(process.env["CODESYS_WINETRICKS_CACHE"], cache, {
289
- recursive: true
290
- });
332
+ if (options.winetricksCache) {
333
+ await cp4(options.winetricksCache, cache, { recursive: true });
291
334
  }
292
- console.log(`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`);
293
- await runDocker([
335
+ if (options.installer) {
336
+ await copyFile3(options.installer, resolve5(installerContext, "codesys.exe"));
337
+ }
338
+ const arm = options.setupPlatform === "linux/arm64";
339
+ await options.docker([
294
340
  "build",
295
341
  "--platform",
296
342
  "linux/amd64",
297
343
  "--build-arg",
298
344
  `SETUP_BASE=${arm ? "arm-setup" : "base"}`,
299
345
  "--build-arg",
300
- `SETUP_PLATFORM=${arm ? "linux/arm64" : "linux/amd64"}`,
346
+ `SETUP_PLATFORM=${options.setupPlatform}`,
301
347
  "--build-arg",
302
- "INSTALLER_SOURCE=installer-download",
348
+ `INSTALLER_SOURCE=${options.installer ? "installer-local" : "installer-download"}`,
303
349
  "--progress",
304
350
  "plain",
305
351
  "--build-context",
306
- `installer=${context}`,
352
+ `installer=${installerContext}`,
307
353
  "-f",
308
- resolve5(buildContext, "docker/Dockerfile"),
354
+ resolve5(context, "docker/Dockerfile"),
309
355
  "-t",
310
- image,
311
- buildContext
312
- ], (status) => `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`);
313
- return image;
356
+ options.tag,
357
+ context
358
+ ]);
314
359
  } finally {
315
360
  await Promise.all([
316
- rm3(context, { recursive: true, force: true }),
317
- ...buildContext ? [rm3(buildContext, { recursive: true, force: true })] : []
361
+ rm3(installerContext, { recursive: true, force: true }),
362
+ ...context ? [rm3(context, { recursive: true, force: true })] : []
318
363
  ]);
319
364
  }
365
+ }
366
+ var buildGatewayImage = (options) => options.docker([
367
+ "build",
368
+ "--platform",
369
+ "linux/amd64",
370
+ "--progress",
371
+ "plain",
372
+ "-t",
373
+ options.tag,
374
+ resolve5(packageDirectory, "docker/edge-gateway")
375
+ ]);
376
+
377
+ // packages/build/src/docker-build.ts
378
+ var packageVersion = async () => z4.object({ version: z4.string() }).parse(JSON.parse(await readFile4(resolve6(packageDirectory, "package.json"), "utf8"))).version;
379
+ var pullPublished = async (image, progress) => {
380
+ const published = publishedImage(image, await packageVersion());
381
+ const output = { progress, environment: {} };
382
+ progressLog(progress)(`Pulling ${published}`);
383
+ try {
384
+ await runDocker(["pull", "--platform", "linux/amd64", published], (status) => `Docker pull failed (${status})`, output);
385
+ } catch {
386
+ progressLog(progress)(`${published} is not available; building ${image} locally instead.`);
387
+ return false;
388
+ }
389
+ await runDocker(["tag", published, image], (status) => `Docker tag failed (${status})`, output);
390
+ return true;
320
391
  };
321
- var runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
322
- var configureRuntime = async () => {
323
- const context = resolve5(packageDirectory, "docker/control-linux-sl");
324
- console.log(`Preparing the local PLC runtime (${runtimeImage}).`);
392
+ var configureDocker = async ({
393
+ progress = "stdout"
394
+ } = {}) => {
395
+ const image = builderImage;
396
+ const { stdout } = await captureDocker(["info", "--format", "{{.OSType}}/{{.Architecture}}"], 30000).catch((cause) => {
397
+ throw new Error("Cannot connect to Docker. Install and start Docker Desktop or Docker Engine", {
398
+ cause
399
+ });
400
+ });
401
+ const setupPlatform = setupPlatformFor(stdout.trim());
402
+ if (!setupPlatform) {
403
+ throw new Error("The builder requires a Linux Docker server on ARM64 or AMD64");
404
+ }
405
+ if (await pullPublished(image, progress)) {
406
+ return image;
407
+ }
408
+ progressLog(progress)(`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`);
409
+ await buildBuilderImage({
410
+ tag: image,
411
+ setupPlatform,
412
+ installer: null,
413
+ winetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,
414
+ docker: (args) => runDocker(args, (status) => `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`, { progress, environment: {} })
415
+ });
416
+ return image;
417
+ };
418
+ var configureRuntime = async ({
419
+ progress = "stdout"
420
+ } = {}) => {
421
+ const context = resolve6(packageDirectory, "docker/control-linux-sl");
422
+ progressLog(progress)(`Preparing the local PLC runtime (${runtimeImage}).`);
325
423
  await runDocker([
326
424
  "build",
327
425
  "--platform",
@@ -331,35 +429,29 @@ var configureRuntime = async () => {
331
429
  "-t",
332
430
  runtimeImage,
333
431
  context
334
- ], (status) => `Runtime image build failed (${status}). Review the image-build output`);
432
+ ], (status) => `Runtime image build failed (${status}). Review the image-build output`, { progress, environment: {} });
335
433
  return runtimeImage;
336
434
  };
337
- var gatewayImage = "tsplc-edge-gateway:4.22.0.0";
338
- var configureGateway = async () => {
339
- if (await pullPublished(gatewayImage)) {
435
+ var configureGateway = async ({
436
+ progress = "stdout"
437
+ } = {}) => {
438
+ if (await pullPublished(gatewayImage, progress)) {
340
439
  return gatewayImage;
341
440
  }
342
- const context = resolve5(packageDirectory, "docker/edge-gateway");
343
- console.log(`Preparing the CODESYS gateway (${gatewayImage}).`);
344
- await runDocker([
345
- "build",
346
- "--platform",
347
- "linux/amd64",
348
- "--progress",
349
- "plain",
350
- "-t",
351
- gatewayImage,
352
- context
353
- ], (status) => `Gateway image build failed (${status}). Review the image-build output`);
441
+ progressLog(progress)(`Preparing the CODESYS gateway (${gatewayImage}).`);
442
+ await buildGatewayImage({
443
+ tag: gatewayImage,
444
+ docker: (args) => runDocker(args, (status) => `Gateway image build failed (${status}). Review the image-build output`, { progress, environment: {} })
445
+ });
354
446
  return gatewayImage;
355
447
  };
356
- var buildInDocker = async (config, image) => {
357
- const requestDirectory = await mkdtemp2(resolve5(tmpdir2(), "codesys-docker-"));
448
+ var buildInDocker = async (config, image, progress) => {
449
+ const requestDirectory = await mkdtemp3(resolve6(tmpdir3(), "codesys-docker-"));
358
450
  try {
359
451
  const operationId = randomUUID();
360
- await mkdir3(config.outDir, { recursive: true });
361
- const failurePath = resolve5(config.outDir, buildFailureFile);
362
- await rm3(failurePath, { force: true });
452
+ await mkdir4(config.outDir, { recursive: true });
453
+ const failurePath = resolve6(config.outDir, buildFailureFile);
454
+ await rm4(failurePath, { force: true });
363
455
  const args = [
364
456
  "run",
365
457
  "--rm",
@@ -373,12 +465,12 @@ var buildInDocker = async (config, image) => {
373
465
  "--operation-id",
374
466
  operationId
375
467
  ];
376
- console.log(`Building with Docker (${image})`);
468
+ progressLog(progress)(`Building with Docker (${image})`);
377
469
  try {
378
- await runDocker(args, (status) => `Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`);
470
+ await runDocker(args, (status) => `Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`, { progress, environment: {} });
379
471
  } catch (cause) {
380
472
  const message = cause instanceof Error ? cause.message : String(cause);
381
- const failure = await readFile3(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
473
+ const failure = await readFile4(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
382
474
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
383
475
  return;
384
476
  }
@@ -403,25 +495,148 @@ ${failure.message}`;
403
495
  }
404
496
  return await readBuild(config.outDir);
405
497
  } finally {
406
- await rm3(requestDirectory, { recursive: true, force: true });
498
+ await rm4(requestDirectory, { recursive: true, force: true });
407
499
  }
408
500
  };
409
501
 
410
502
  // packages/build/src/host/codesys-worker.ts
503
+ import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
411
504
  import {
412
505
  access,
413
- copyFile as copyFile3,
414
- mkdir as mkdir4,
506
+ copyFile as copyFile4,
507
+ mkdir as mkdir5,
415
508
  open,
416
- readFile as readFile4,
509
+ readFile as readFile5,
417
510
  rename as rename2,
418
- rm as rm4,
511
+ rm as rm5,
419
512
  unlink,
420
513
  writeFile as writeFile4
421
514
  } from "node:fs/promises";
422
- import { resolve as resolve6 } from "node:path";
515
+ import { resolve as resolve7 } from "node:path";
423
516
  import { setTimeout as delay } from "node:timers/promises";
517
+ import { z as z7 } from "zod";
518
+
519
+ // packages/build/src/controller-protocol.ts
520
+ import { createHash as createHash2 } from "node:crypto";
521
+ import {
522
+ controllerSchema,
523
+ sha256Digest,
524
+ tcpPort
525
+ } from "@tsplc/config/build";
424
526
  import { z as z5 } from "zod";
527
+ var imageIdSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
528
+ var endpointSchema = z5.strictObject({
529
+ host: z5.string().nonempty(),
530
+ port: tcpPort
531
+ });
532
+ var controllerResultSchema = z5.strictObject({
533
+ schemaVersion: z5.literal(1),
534
+ operationId: z5.uuid(),
535
+ operation: z5.enum(["download", "online-change", "inspect"]),
536
+ imageId: imageIdSchema,
537
+ templateHash: sha256Digest,
538
+ target: z5.strictObject({
539
+ network: z5.string().nonempty(),
540
+ gateway: endpointSchema,
541
+ device: endpointSchema,
542
+ controller: controllerSchema.optional(),
543
+ deviceTree: sha256Digest.optional()
544
+ }),
545
+ generation: z5.string().nonempty(),
546
+ application: z5.string().nonempty(),
547
+ applicationGuid: z5.string().nonempty(),
548
+ controllerIds: z5.strictObject({
549
+ codeId: z5.string().nonempty(),
550
+ dataId: z5.string().nonempty()
551
+ }),
552
+ state: z5.string().nonempty(),
553
+ values: z5.record(z5.string(), z5.string())
554
+ });
555
+ var controllerCredentialsSchema = z5.strictObject({
556
+ username: z5.string().nonempty(),
557
+ password: z5.string().nonempty()
558
+ });
559
+ var warmOperationSchema = z5.strictObject({
560
+ operation: z5.enum(["download", "online-change"]),
561
+ operationId: z5.uuid(),
562
+ request: z5.string().nonempty(),
563
+ initializeUser: z5.boolean(),
564
+ credentials: controllerCredentialsSchema.optional()
565
+ });
566
+ var tracebackFailure = (traceback) => {
567
+ const text = traceback.trim();
568
+ const lastFrame = text.lastIndexOf(`
569
+ File `);
570
+ if (lastFrame === -1) {
571
+ return text;
572
+ }
573
+ const [, ...rest] = text.slice(lastFrame + 1).split(`
574
+ `);
575
+ return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
576
+ `);
577
+ };
578
+ var failureReason = (error) => tracebackFailure(error instanceof Error ? error.message : String(error)).replace(/^\w+: /, "");
579
+ var controllerTarget = (config, online) => ({
580
+ network: online.network,
581
+ gateway: online.gateway,
582
+ device: online.device,
583
+ controller: config.controller,
584
+ ...config.deviceTree && {
585
+ deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
586
+ }
587
+ });
588
+ var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
589
+ var explicitDownload = "use an explicit download";
590
+
591
+ class DownloadRequiredError extends Error {
592
+ downloadRequired = true;
593
+ }
594
+ var rollbackSchema = z5.enum([
595
+ "intact",
596
+ "restored",
597
+ "failed",
598
+ "unavailable"
599
+ ]);
600
+
601
+ class TransferFailedError extends Error {
602
+ rollback;
603
+ constructor(message, rollback, options) {
604
+ super(message, options);
605
+ this.rollback = rollback;
606
+ }
607
+ }
608
+ var transferRollback = (error) => {
609
+ if (!(error instanceof Error) || !("rollback" in error)) {
610
+ return;
611
+ }
612
+ return rollbackSchema.safeParse(error.rollback).data;
613
+ };
614
+ var requiresDownload = (error) => error instanceof Error && ("downloadRequired" in error) && error.downloadRequired === true;
615
+ var loginCommandSchema = z5.discriminatedUnion("command", [
616
+ z5.strictObject({ command: z5.literal("state") }),
617
+ z5.strictObject({
618
+ command: z5.literal("read"),
619
+ expressions: z5.array(z5.string().nonempty()).nonempty()
620
+ }),
621
+ z5.strictObject({
622
+ command: z5.enum(["write", "force"]),
623
+ values: z5.record(z5.string().nonempty(), z5.string().nonempty())
624
+ }),
625
+ z5.strictObject({
626
+ command: z5.literal("unforce"),
627
+ expressions: z5.array(z5.string().nonempty()),
628
+ restore: z5.boolean()
629
+ }),
630
+ z5.strictObject({ command: z5.enum(["start", "stop"]) }),
631
+ z5.strictObject({
632
+ command: z5.literal("reset"),
633
+ kind: z5.enum(["Warm", "Cold"])
634
+ })
635
+ ]);
636
+ var loginResultSchema = z5.union([
637
+ z5.strictObject({ values: z5.record(z5.string(), z5.string()) }),
638
+ z5.strictObject({ state: z5.string(), forced: z5.array(z5.string()) })
639
+ ]);
425
640
 
426
641
  // packages/build/src/host/codesys-command.ts
427
642
  var codesysCommand = [
@@ -438,7 +653,7 @@ var codesysCommand = [
438
653
  // packages/build/src/host/codesys-host.ts
439
654
  import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
440
655
  import { promisify as promisify3 } from "node:util";
441
- import { z as z4 } from "zod";
656
+ import { z as z6 } from "zod";
442
657
 
443
658
  // packages/build/src/host/windows-path.ts
444
659
  import { execFile as execFile2 } from "node:child_process";
@@ -451,19 +666,28 @@ var execute2 = promisify2(execFile2);
451
666
 
452
667
  // packages/build/src/host/codesys-host.ts
453
668
  var execute3 = promisify3(execFile3);
454
- var exitSchema = z4.object({
455
- pid: z4.int().positive(),
456
- code: z4.int().nullable(),
457
- signal: z4.string().nullable()
669
+ var exitSchema = z6.object({
670
+ pid: z6.int().positive(),
671
+ code: z6.int().nullable(),
672
+ signal: z6.string().nullable()
458
673
  });
459
674
 
460
675
  // packages/build/src/host/codesys-worker.ts
461
- var pythonDirectory = resolve6(packageDirectory, "python");
462
- var sessionSchema = z5.object({
463
- directory: z5.string(),
464
- fingerprint: z5.string(),
465
- pid: z5.int().positive()
676
+ var pythonDirectory = resolve7(packageDirectory, "python");
677
+ var workerScripts = [
678
+ "build.py",
679
+ "hardware.py",
680
+ "worker.py",
681
+ "codesys_online.py",
682
+ "codesys_login.py"
683
+ ];
684
+ var workerScriptsDigest = async () => createHash3("sha256").update(JSON.stringify(await Promise.all(workerScripts.map((script) => readFile5(resolve7(pythonDirectory, script), "utf8"))))).digest("hex");
685
+ var sessionSchema = z7.object({
686
+ directory: z7.string(),
687
+ fingerprint: z7.string(),
688
+ pid: z7.int().positive()
466
689
  });
690
+ var phaseSchema = z7.enum(["prepare", "transfer"]);
467
691
  var hasCode = (error, code) => error instanceof Error && ("code" in error) && error.code === code;
468
692
  var isProcessAlive = (pid) => {
469
693
  try {
@@ -477,8 +701,8 @@ var isProcessAlive = (pid) => {
477
701
  }
478
702
  };
479
703
  var withWorkerLock = async (config, run) => {
480
- await mkdir4(resolve6(config.outDir, ".codesys"), { recursive: true });
481
- const path = resolve6(config.outDir, ".codesys/command.lock");
704
+ await mkdir5(resolve7(config.outDir, ".codesys"), { recursive: true });
705
+ const path = resolve7(config.outDir, ".codesys/command.lock");
482
706
  const deadline = Date.now() + config.timeouts.build + config.timeouts.startup;
483
707
  while (true) {
484
708
  const lock = await open(path, "wx").catch((error) => {
@@ -496,7 +720,7 @@ var withWorkerLock = async (config, run) => {
496
720
  await unlink(path);
497
721
  }
498
722
  }
499
- const owner = Number(await readFile4(path, "utf8").catch((error) => {
723
+ const owner = Number(await readFile5(path, "utf8").catch((error) => {
500
724
  if (hasCode(error, "ENOENT")) {
501
725
  return "";
502
726
  }
@@ -513,31 +737,227 @@ var withWorkerLock = async (config, run) => {
513
737
  };
514
738
 
515
739
  // packages/build/src/sources.ts
516
- import { readdir, readFile as readFile5 } from "node:fs/promises";
517
- import { basename as basename3, resolve as resolve7 } from "node:path";
740
+ import { readdir, readFile as readFile6 } from "node:fs/promises";
741
+ import { basename as basename4, resolve as resolve8 } from "node:path";
518
742
  import { identifierPattern as identifierPattern3 } from "@tsplc/iec/st";
519
743
 
520
- // packages/build/src/st/parse.ts
521
- import { basename as basename2 } from "node:path";
522
- import {
523
- globalSections,
524
- identifierPattern as identifierPattern2,
525
- qualifiers,
526
- variableSections as variableSections2
527
- } from "@tsplc/iec/st";
744
+ // packages/build/src/io.ts
745
+ import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
746
+ import { qualifiers, variableSections } from "@tsplc/iec/st";
528
747
 
529
- // packages/build/src/st/declarations.ts
530
- import {
531
- conditionalDirective,
532
- modifiers,
533
- variableSections
534
- } from "@tsplc/iec/st";
535
- var objectKinds = {
536
- PROGRAM: "program",
537
- FUNCTION_BLOCK: "function_block",
538
- FUNCTIONBLOCK: "function_block",
539
- FUNCTION: "function",
540
- METHOD: "method",
748
+ // packages/build/src/st/lexer.ts
749
+ import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
750
+
751
+ class StSyntaxError extends Error {
752
+ constructor(source, offset, filename, message) {
753
+ const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
754
+ super(`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`);
755
+ this.name = "StSyntaxError";
756
+ }
757
+ }
758
+ var tokenize = (source, filename = "<source>") => {
759
+ const tokens = [];
760
+ let offset = 0;
761
+ const fail = (start, message) => {
762
+ throw new StSyntaxError(source, start, filename, message);
763
+ };
764
+ const quoted = () => {
765
+ offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
766
+ };
767
+ while (offset < source.length) {
768
+ const start = offset;
769
+ const character = source[offset] ?? "";
770
+ if (/\s|\uFEFF/.test(character)) {
771
+ offset++;
772
+ continue;
773
+ }
774
+ if (source.startsWith("//", offset)) {
775
+ offset = lineCommentEnd(source, start);
776
+ continue;
777
+ }
778
+ if (source.startsWith("(*", offset)) {
779
+ offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
780
+ continue;
781
+ }
782
+ if (character === "'" || character === '"') {
783
+ quoted();
784
+ tokens.push({
785
+ kind: "string",
786
+ value: source.slice(start, offset),
787
+ start,
788
+ end: offset
789
+ });
790
+ continue;
791
+ }
792
+ if (character === "{") {
793
+ offset++;
794
+ while (offset < source.length && source[offset] !== "}") {
795
+ if (source[offset] === "'" || source[offset] === '"') {
796
+ quoted();
797
+ } else {
798
+ offset++;
799
+ }
800
+ }
801
+ if (offset === source.length) {
802
+ fail(start, "Unterminated pragma");
803
+ }
804
+ offset++;
805
+ tokens.push({
806
+ kind: "pragma",
807
+ value: source.slice(start, offset),
808
+ start,
809
+ end: offset
810
+ });
811
+ continue;
812
+ }
813
+ if (/[A-Za-z_]/.test(character)) {
814
+ offset++;
815
+ while (/[A-Za-z_0-9]/.test(source[offset] ?? "")) {
816
+ offset++;
817
+ }
818
+ tokens.push({
819
+ kind: "word",
820
+ value: source.slice(start, offset).toUpperCase(),
821
+ start,
822
+ end: offset
823
+ });
824
+ continue;
825
+ }
826
+ offset++;
827
+ const pair = source.slice(start, offset + 1);
828
+ if ([":=", "=>", "..", "<=", ">=", "<>", "**"].includes(pair)) {
829
+ offset++;
830
+ }
831
+ tokens.push({
832
+ kind: "symbol",
833
+ value: source.slice(start, offset),
834
+ start,
835
+ end: offset
836
+ });
837
+ }
838
+ return tokens;
839
+ };
840
+
841
+ // packages/build/src/io.ts
842
+ var span = (type) => ioArray(type) ?? { element: type, length: 1 };
843
+ var addressSize = (type) => {
844
+ const bits = ioScalarBits(type);
845
+ return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
846
+ };
847
+ function bindStructuredTextIo(objects, bindings) {
848
+ const declarations = [];
849
+ const visit = (object) => {
850
+ const tokens = tokenize(object.declaration, object.source);
851
+ let section = false;
852
+ let start = 0;
853
+ for (const [index, token] of tokens.entries()) {
854
+ if (variableSections.has(token.value)) {
855
+ section = true;
856
+ start = index + 1;
857
+ continue;
858
+ }
859
+ if (token.value === "END_VAR") {
860
+ section = false;
861
+ continue;
862
+ }
863
+ if (!section || token.value !== ";") {
864
+ continue;
865
+ }
866
+ const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
867
+ start = index + 1;
868
+ const colon = part.find((t) => t.value === ":");
869
+ if (!colon) {
870
+ continue;
871
+ }
872
+ const colonIndex = part.indexOf(colon);
873
+ if (colonIndex < 1) {
874
+ continue;
875
+ }
876
+ const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers.has(t.value) && t.value !== "AT");
877
+ const at = part.find((t) => t.value === "AT");
878
+ const variables = at ? names.filter((t) => t.start < at.start) : names;
879
+ const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
880
+ const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
881
+ const [first] = typeTokens;
882
+ const last = typeTokens.at(-1);
883
+ const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
884
+ for (const name of variables) {
885
+ declarations.push({
886
+ object,
887
+ name: name.value,
888
+ names: variables,
889
+ colon,
890
+ type
891
+ });
892
+ }
893
+ }
894
+ object.children.forEach(visit);
895
+ };
896
+ objects.forEach(visit);
897
+ const edits = new Map;
898
+ for (const [symbol, binding] of Object.entries(bindings)) {
899
+ const parts = symbol.toUpperCase().split(".");
900
+ if (parts.length > 2) {
901
+ throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
902
+ }
903
+ const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
904
+ const [declaration, ...others] = matches;
905
+ if (!declaration || others.length) {
906
+ throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
907
+ }
908
+ const [variable, ...siblings] = declaration.names;
909
+ if (!variable || siblings.length) {
910
+ throw new Error(`${symbol}: declare mapped IO variables separately.`);
911
+ }
912
+ const declared = span(declaration.type);
913
+ const size = addressSize(declared.element);
914
+ if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
915
+ throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
916
+ }
917
+ const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
918
+ if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
919
+ throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
920
+ }
921
+ const list = edits.get(declaration.object) ?? [];
922
+ const start = variable.end;
923
+ if (list.some((e) => e.start === start)) {
924
+ throw new Error(`${symbol}: the variable has more than one IO binding.`);
925
+ }
926
+ list.push({
927
+ start,
928
+ end: declaration.colon.start,
929
+ text: ` AT ${binding.address} `
930
+ });
931
+ edits.set(declaration.object, list);
932
+ }
933
+ for (const [object, list] of edits) {
934
+ for (const edit of list.sort((a, b) => b.start - a.start)) {
935
+ object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
936
+ }
937
+ }
938
+ }
939
+
940
+ // packages/build/src/st/parse.ts
941
+ import { basename as basename3 } from "node:path";
942
+ import {
943
+ globalSections,
944
+ identifierPattern as identifierPattern2,
945
+ qualifiers as qualifiers2,
946
+ variableSections as variableSections3
947
+ } from "@tsplc/iec/st";
948
+
949
+ // packages/build/src/st/declarations.ts
950
+ import {
951
+ conditionalDirective,
952
+ modifiers,
953
+ variableSections as variableSections2
954
+ } from "@tsplc/iec/st";
955
+ var objectKinds = {
956
+ PROGRAM: "program",
957
+ FUNCTION_BLOCK: "function_block",
958
+ FUNCTIONBLOCK: "function_block",
959
+ FUNCTION: "function",
960
+ METHOD: "method",
541
961
  INTERFACE: "interface",
542
962
  PROPERTY: "property"
543
963
  };
@@ -545,7 +965,7 @@ var closingObjects = new Set(Object.keys(objectKinds).map((kind) => `END_${kind}
545
965
  var declarationKeywords = new Set([
546
966
  ...Object.keys(objectKinds),
547
967
  ...closingObjects,
548
- ...variableSections,
968
+ ...variableSections2,
549
969
  "END_VAR",
550
970
  "TYPE",
551
971
  "END_TYPE",
@@ -649,151 +1069,58 @@ var readVariableSection = (reader) => {
649
1069
  const conditionals = [];
650
1070
  while (reader.peek()?.value !== "END_VAR") {
651
1071
  const token = reader.take();
652
- if (variableSections.has(token.value) || closingObjects.has(token.value)) {
1072
+ if (variableSections2.has(token.value) || closingObjects.has(token.value)) {
653
1073
  reader.fail("Missing END_VAR", token);
654
1074
  }
655
- const directive = token.kind === "pragma" && conditionalDirective(token.value);
656
- if (!directive) {
657
- continue;
658
- }
659
- if (directive === "IF") {
660
- conditionals.push({ hasElse: false });
661
- continue;
662
- }
663
- const current = conditionals.at(-1);
664
- if (!current) {
665
- return reader.fail("Unmatched conditional pragma", token);
666
- }
667
- if (directive === "END_IF") {
668
- conditionals.pop();
669
- continue;
670
- }
671
- if (current.hasElse) {
672
- reader.fail("Conditional branch after ELSE", token);
673
- }
674
- current.hasElse = directive === "ELSE";
675
- }
676
- if (conditionals.length) {
677
- reader.fail("Conditional pragmas must remain inside one variable section");
678
- }
679
- reader.take();
680
- readDeclarationSemicolon(reader);
681
- };
682
- var readDeclarationSections = (reader) => {
683
- while (reader.peek()) {
684
- let ahead = 0;
685
- while (isDeclarationPragma(reader.peek(ahead))) {
686
- ahead++;
687
- }
688
- const next = reader.peek(ahead)?.value ?? "";
689
- if (variableSections.has(next)) {
690
- readDeclarationPragmas(reader);
691
- readVariableSection(reader);
692
- continue;
693
- }
694
- if (next !== "EXTENDS" && next !== "IMPLEMENTS") {
695
- return;
696
- }
697
- readDeclarationPragmas(reader);
698
- reader.take();
699
- readType(reader);
700
- while (reader.consume(",")) {
701
- readType(reader);
702
- }
703
- }
704
- };
705
-
706
- // packages/build/src/st/lexer.ts
707
- import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
708
-
709
- class StSyntaxError extends Error {
710
- constructor(source, offset, filename, message) {
711
- const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
712
- super(`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`);
713
- this.name = "StSyntaxError";
714
- }
715
- }
716
- var tokenize = (source, filename = "<source>") => {
717
- const tokens = [];
718
- let offset = 0;
719
- const fail = (start, message) => {
720
- throw new StSyntaxError(source, start, filename, message);
721
- };
722
- const quoted = () => {
723
- offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
724
- };
725
- while (offset < source.length) {
726
- const start = offset;
727
- const character = source[offset] ?? "";
728
- if (/\s|\uFEFF/.test(character)) {
729
- offset++;
730
- continue;
731
- }
732
- if (source.startsWith("//", offset)) {
733
- offset = lineCommentEnd(source, start);
734
- continue;
735
- }
736
- if (source.startsWith("(*", offset)) {
737
- offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
738
- continue;
739
- }
740
- if (character === "'" || character === '"') {
741
- quoted();
742
- tokens.push({
743
- kind: "string",
744
- value: source.slice(start, offset),
745
- start,
746
- end: offset
747
- });
748
- continue;
749
- }
750
- if (character === "{") {
751
- offset++;
752
- while (offset < source.length && source[offset] !== "}") {
753
- if (source[offset] === "'" || source[offset] === '"') {
754
- quoted();
755
- } else {
756
- offset++;
757
- }
758
- }
759
- if (offset === source.length) {
760
- fail(start, "Unterminated pragma");
761
- }
762
- offset++;
763
- tokens.push({
764
- kind: "pragma",
765
- value: source.slice(start, offset),
766
- start,
767
- end: offset
768
- });
1075
+ const directive = token.kind === "pragma" && conditionalDirective(token.value);
1076
+ if (!directive) {
769
1077
  continue;
770
1078
  }
771
- if (/[A-Za-z_]/.test(character)) {
772
- offset++;
773
- while (/[A-Za-z_0-9]/.test(source[offset] ?? "")) {
774
- offset++;
775
- }
776
- tokens.push({
777
- kind: "word",
778
- value: source.slice(start, offset).toUpperCase(),
779
- start,
780
- end: offset
781
- });
1079
+ if (directive === "IF") {
1080
+ conditionals.push({ hasElse: false });
782
1081
  continue;
783
1082
  }
784
- offset++;
785
- const pair = source.slice(start, offset + 1);
786
- if ([":=", "=>", "..", "<=", ">=", "<>", "**"].includes(pair)) {
787
- offset++;
1083
+ const current = conditionals.at(-1);
1084
+ if (!current) {
1085
+ return reader.fail("Unmatched conditional pragma", token);
1086
+ }
1087
+ if (directive === "END_IF") {
1088
+ conditionals.pop();
1089
+ continue;
1090
+ }
1091
+ if (current.hasElse) {
1092
+ reader.fail("Conditional branch after ELSE", token);
1093
+ }
1094
+ current.hasElse = directive === "ELSE";
1095
+ }
1096
+ if (conditionals.length) {
1097
+ reader.fail("Conditional pragmas must remain inside one variable section");
1098
+ }
1099
+ reader.take();
1100
+ readDeclarationSemicolon(reader);
1101
+ };
1102
+ var readDeclarationSections = (reader) => {
1103
+ while (reader.peek()) {
1104
+ let ahead = 0;
1105
+ while (isDeclarationPragma(reader.peek(ahead))) {
1106
+ ahead++;
1107
+ }
1108
+ const next = reader.peek(ahead)?.value ?? "";
1109
+ if (variableSections2.has(next)) {
1110
+ readDeclarationPragmas(reader);
1111
+ readVariableSection(reader);
1112
+ continue;
1113
+ }
1114
+ if (next !== "EXTENDS" && next !== "IMPLEMENTS") {
1115
+ return;
1116
+ }
1117
+ readDeclarationPragmas(reader);
1118
+ reader.take();
1119
+ readType(reader);
1120
+ while (reader.consume(",")) {
1121
+ readType(reader);
788
1122
  }
789
- tokens.push({
790
- kind: "symbol",
791
- value: source.slice(start, offset),
792
- start,
793
- end: offset
794
- });
795
1123
  }
796
- return tokens;
797
1124
  };
798
1125
 
799
1126
  // packages/build/src/st/reader.ts
@@ -884,13 +1211,13 @@ var parseGlobals = (reader, options) => {
884
1211
  const start = reader.index;
885
1212
  readVariableSection(reader);
886
1213
  for (const token of reader.tokens.slice(start + 1, reader.index)) {
887
- if (token.kind !== "word" || !qualifiers.has(token.value)) {
1214
+ if (token.kind !== "word" || !qualifiers2.has(token.value)) {
888
1215
  break;
889
1216
  }
890
1217
  persistent ||= token.value === "PERSISTENT";
891
1218
  }
892
1219
  }
893
- const name = options.name ?? basename2(reader.filename, ".st");
1220
+ const name = options.name ?? basename3(reader.filename, ".st");
894
1221
  if (!identifierPattern2.test(name)) {
895
1222
  reader.fail("Global list requires an IEC filename or an explicit name", header);
896
1223
  }
@@ -906,7 +1233,7 @@ var validateImplementation = (reader, tokens) => {
906
1233
  if (token.kind !== "word") {
907
1234
  continue;
908
1235
  }
909
- if (variableSections2.has(token.value) || token.value === "END_VAR") {
1236
+ if (variableSections3.has(token.value) || token.value === "END_VAR") {
910
1237
  reader.fail("Variable declaration outside the declaration section; conditional declaration envelopes are not supported", token);
911
1238
  }
912
1239
  if (declarationKeywords.has(token.value)) {
@@ -974,107 +1301,6 @@ var parseSource = (source, options = {}) => {
974
1301
  return parsePou(reader, options);
975
1302
  };
976
1303
 
977
- // packages/build/src/io.ts
978
- import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
979
- import { qualifiers as qualifiers2, variableSections as variableSections3 } from "@tsplc/iec/st";
980
- var span = (type) => ioArray(type) ?? { element: type, length: 1 };
981
- var addressSize = (type) => {
982
- const bits = ioScalarBits(type);
983
- return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
984
- };
985
- function bindStructuredTextIo(objects, bindings) {
986
- const declarations = [];
987
- const visit = (object) => {
988
- const tokens = tokenize(object.declaration, object.source);
989
- let section = false;
990
- let start = 0;
991
- for (const [index, token] of tokens.entries()) {
992
- if (variableSections3.has(token.value)) {
993
- section = true;
994
- start = index + 1;
995
- continue;
996
- }
997
- if (token.value === "END_VAR") {
998
- section = false;
999
- continue;
1000
- }
1001
- if (!section || token.value !== ";") {
1002
- continue;
1003
- }
1004
- const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
1005
- start = index + 1;
1006
- const colon = part.find((t) => t.value === ":");
1007
- if (!colon) {
1008
- continue;
1009
- }
1010
- const colonIndex = part.indexOf(colon);
1011
- if (colonIndex < 1) {
1012
- continue;
1013
- }
1014
- const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers2.has(t.value) && t.value !== "AT");
1015
- const at = part.find((t) => t.value === "AT");
1016
- const variables = at ? names.filter((t) => t.start < at.start) : names;
1017
- const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
1018
- const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
1019
- const [first] = typeTokens;
1020
- const last = typeTokens.at(-1);
1021
- const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
1022
- for (const name of variables) {
1023
- declarations.push({
1024
- object,
1025
- name: name.value,
1026
- names: variables,
1027
- colon,
1028
- type
1029
- });
1030
- }
1031
- }
1032
- object.children.forEach(visit);
1033
- };
1034
- objects.forEach(visit);
1035
- const edits = new Map;
1036
- for (const [symbol, binding] of Object.entries(bindings)) {
1037
- const parts = symbol.toUpperCase().split(".");
1038
- if (parts.length > 2) {
1039
- throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
1040
- }
1041
- const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
1042
- const [declaration, ...others] = matches;
1043
- if (!declaration || others.length) {
1044
- throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
1045
- }
1046
- const [variable, ...siblings] = declaration.names;
1047
- if (!variable || siblings.length) {
1048
- throw new Error(`${symbol}: declare mapped IO variables separately.`);
1049
- }
1050
- const declared = span(declaration.type);
1051
- const size = addressSize(declared.element);
1052
- if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
1053
- throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
1054
- }
1055
- const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
1056
- if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
1057
- throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
1058
- }
1059
- const list = edits.get(declaration.object) ?? [];
1060
- const start = variable.end;
1061
- if (list.some((e) => e.start === start)) {
1062
- throw new Error(`${symbol}: the variable has more than one IO binding.`);
1063
- }
1064
- list.push({
1065
- start,
1066
- end: declaration.colon.start,
1067
- text: ` AT ${binding.address} `
1068
- });
1069
- edits.set(declaration.object, list);
1070
- }
1071
- for (const [object, list] of edits) {
1072
- for (const edit of list.sort((a, b) => b.start - a.start)) {
1073
- object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
1074
- }
1075
- }
1076
- }
1077
-
1078
1304
  // packages/build/src/sources.ts
1079
1305
  var prefixes = {
1080
1306
  FB: "function_block",
@@ -1133,7 +1359,7 @@ var readUnit = async (name, files, role, interfaceMember = false) => {
1133
1359
  kind: "action",
1134
1360
  name,
1135
1361
  declaration: "",
1136
- implementation: await readFile5(combined, "utf8"),
1362
+ implementation: await readFile6(combined, "utf8"),
1137
1363
  source: combined
1138
1364
  };
1139
1365
  }
@@ -1141,7 +1367,7 @@ var readUnit = async (name, files, role, interfaceMember = false) => {
1141
1367
  if (!combined) {
1142
1368
  throw new Error(`Property accessors use one .st file: ${path}`);
1143
1369
  }
1144
- const body = await readFile5(combined, "utf8");
1370
+ const body = await readFile6(combined, "utf8");
1145
1371
  const header = `METHOD ${name}
1146
1372
  `;
1147
1373
  const parsed = parseSource(`${header}${body}
@@ -1160,7 +1386,7 @@ END_METHOD`, {
1160
1386
  throw new Error(`Missing declaration for ${path}`);
1161
1387
  }
1162
1388
  const sourcePath = combined ?? declaration ?? path;
1163
- const parsed = parseSource(await readFile5(sourcePath, "utf8"), {
1389
+ const parsed = parseSource(await readFile6(sourcePath, "utf8"), {
1164
1390
  filename: sourcePath,
1165
1391
  name,
1166
1392
  declarationOnly: !combined || interfaceMember
@@ -1187,7 +1413,7 @@ END_METHOD`, {
1187
1413
  }
1188
1414
  return {
1189
1415
  ...parsed,
1190
- ...implementation ? { implementation: await readFile5(implementation, "utf8") } : {},
1416
+ ...implementation ? { implementation: await readFile6(implementation, "utf8") } : {},
1191
1417
  source: sourcePath
1192
1418
  };
1193
1419
  };
@@ -1198,7 +1424,7 @@ var loadSources = async (config) => {
1198
1424
  const groups = new Map;
1199
1425
  for (const entry of entries) {
1200
1426
  if (entry.isSymbolicLink()) {
1201
- throw new Error(`Source symlinks are not supported: ${resolve7(directory, entry.name)}`);
1427
+ throw new Error(`Source symlinks are not supported: ${resolve8(directory, entry.name)}`);
1202
1428
  }
1203
1429
  if (!entry.isFile() || !/\.st$/i.test(entry.name)) {
1204
1430
  continue;
@@ -1206,7 +1432,7 @@ var loadSources = async (config) => {
1206
1432
  const stem = entry.name.slice(0, -3);
1207
1433
  const suffix = /^(.*)\.(declaration|implementation)$/.exec(stem);
1208
1434
  const generic = ["source", "declaration", "implementation"].includes(stem);
1209
- const name = generic ? basename3(directory) : suffix?.[1] ?? stem;
1435
+ const name = generic ? basename4(directory) : suffix?.[1] ?? stem;
1210
1436
  const section = suffix?.[2] ?? stem;
1211
1437
  const part = section === "declaration" || section === "implementation" ? section : "combined";
1212
1438
  const key = name.toLowerCase();
@@ -1214,11 +1440,11 @@ var loadSources = async (config) => {
1214
1440
  name,
1215
1441
  files: { combined: [], declaration: [], implementation: [] }
1216
1442
  };
1217
- group.files[part].push(resolve7(directory, entry.name));
1443
+ group.files[part].push(resolve8(directory, entry.name));
1218
1444
  groups.set(key, group);
1219
1445
  }
1220
1446
  const units = [];
1221
- const ownKey = basename3(directory).toLowerCase();
1447
+ const ownKey = basename4(directory).toLowerCase();
1222
1448
  const ordered = [...groups].sort(([a], [b]) => Number(b === ownKey) - Number(a === ownKey));
1223
1449
  for (const [key, { name, files }] of ordered) {
1224
1450
  const ownProperty = units.find((unit) => unit.kind === "property" && unit.name.toLowerCase() === ownKey);
@@ -1252,20 +1478,20 @@ var loadSources = async (config) => {
1252
1478
  if (own.kind === "property" || own.kind === "interface" && childRole === "action") {
1253
1479
  throw new Error(`Unsupported ${entry.name} under ${own.name}`);
1254
1480
  }
1255
- await visit(resolve7(directory, entry.name), [], own, childRole);
1481
+ await visit(resolve8(directory, entry.name), [], own, childRole);
1256
1482
  } else if (parent) {
1257
- await visit(resolve7(directory, entry.name), [], parent, role);
1483
+ await visit(resolve8(directory, entry.name), [], parent, role);
1258
1484
  } else {
1259
- await visit(resolve7(directory, entry.name), [...folder, entry.name]);
1485
+ await visit(resolve8(directory, entry.name), [...folder, entry.name]);
1260
1486
  }
1261
1487
  }
1262
1488
  };
1263
- await visit(resolve7(config.sourceDir), []);
1489
+ await visit(resolve8(config.sourceDir), []);
1264
1490
  assertUnique(objects, "Application");
1265
1491
  if (config.io) {
1266
1492
  bindStructuredTextIo(objects, config.io);
1267
1493
  }
1268
- const entry = objects.find((object) => object.source === resolve7(config.entry));
1494
+ const entry = objects.find((object) => object.source === resolve8(config.entry));
1269
1495
  if (!entry) {
1270
1496
  throw new Error(`Entry is not a discovered source: ${config.entry}`);
1271
1497
  }
@@ -1286,151 +1512,86 @@ var loadSources = async (config) => {
1286
1512
  };
1287
1513
 
1288
1514
  // packages/build/src/build.ts
1289
- var buildProject = async (config) => {
1515
+ var buildProject = async (config, { progress = "stdout" } = {}) => {
1290
1516
  if (!config.docker) {
1291
1517
  throw new Error("Builds require a Docker builder image.");
1292
1518
  }
1293
- return buildInDocker(config, dockerImage2);
1519
+ return buildInDocker(config, builderImage, progress);
1294
1520
  };
1295
-
1296
- // packages/build/src/index.ts
1297
- import {
1298
- configSchema,
1299
- defineBuildConfig,
1300
- loadConfig,
1301
- resolveConfig as resolveConfig2
1302
- } from "@tsplc/config/build";
1303
-
1304
1521
  // packages/build/src/controller-online.ts
1522
+ import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
1305
1523
  import { existsSync } from "node:fs";
1306
- import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
1307
- import { mkdir as mkdir5, mkdtemp as mkdtemp3, readFile as readFile6, rm as rm5 } from "node:fs/promises";
1308
- import { tmpdir as tmpdir3 } from "node:os";
1309
- import { posix as posix2, resolve as resolve8 } from "node:path";
1524
+ import { mkdir as mkdir7, mkdtemp as mkdtemp4, readFile as readFile8, rm as rm7 } from "node:fs/promises";
1525
+ import { tmpdir as tmpdir4 } from "node:os";
1526
+ import { posix as posix2, resolve as resolve10 } from "node:path";
1310
1527
  import { setTimeout as delay2 } from "node:timers/promises";
1311
- import { z as z7 } from "zod";
1312
- import { dockerImage as dockerImage3 } from "@tsplc/config/build";
1528
+ import { z as z9 } from "zod";
1313
1529
 
1314
- // packages/build/src/controller-protocol.ts
1315
- import { createHash as createHash2 } from "node:crypto";
1316
- import { z as z6 } from "zod";
1530
+ // packages/build/src/controller-session.ts
1531
+ import { cp as cp5, mkdir as mkdir6, readdir as readdir2, readFile as readFile7, rm as rm6, writeFile as writeFile5 } from "node:fs/promises";
1532
+ import { resolve as resolve9 } from "node:path";
1317
1533
  import {
1318
- controllerSchema,
1319
- sha256Digest,
1320
- tcpPort
1534
+ controllerBudgets,
1535
+ sha256Digest as sha256Digest2
1321
1536
  } from "@tsplc/config/build";
1322
- var imageIdSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
1323
- var endpointSchema = z6.strictObject({
1324
- host: z6.string().nonempty(),
1325
- port: tcpPort
1326
- });
1327
- var controllerResultSchema = z6.strictObject({
1328
- schemaVersion: z6.literal(1),
1329
- operationId: z6.uuid(),
1330
- operation: z6.enum(["download", "online-change", "inspect"]),
1331
- imageId: imageIdSchema,
1332
- templateHash: sha256Digest,
1333
- target: z6.strictObject({
1334
- network: z6.string().nonempty(),
1335
- gateway: endpointSchema,
1336
- device: endpointSchema,
1337
- controller: controllerSchema.optional(),
1338
- deviceTree: sha256Digest.optional()
1339
- }),
1340
- generation: z6.string().nonempty(),
1341
- application: z6.string().nonempty(),
1342
- applicationGuid: z6.string().nonempty(),
1343
- controllerIds: z6.strictObject({
1344
- codeId: z6.string().nonempty(),
1345
- dataId: z6.string().nonempty()
1346
- }),
1347
- state: z6.string().nonempty(),
1348
- values: z6.record(z6.string(), z6.string())
1349
- });
1350
- var controllerCredentialsSchema = z6.strictObject({
1351
- username: z6.string().nonempty(),
1352
- password: z6.string().nonempty()
1537
+ import { z as z8 } from "zod";
1538
+ var guid = z8.string().regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i);
1539
+ var pointerSchema = z8.strictObject({
1540
+ schemaVersion: z8.literal(1),
1541
+ generation: z8.uuid()
1353
1542
  });
1354
- var warmOperationSchema = z6.strictObject({
1355
- operation: z6.enum(["download", "online-change"]),
1356
- operationId: z6.uuid(),
1357
- request: z6.string().nonempty(),
1358
- initializeUser: z6.boolean(),
1359
- credentials: controllerCredentialsSchema.optional()
1543
+ var baselineSchema = controllerResultSchema.extend({
1544
+ objects: z8.array(z8.record(z8.string(), z8.unknown())),
1545
+ files: z8.record(z8.string(), sha256Digest2)
1360
1546
  });
1361
- var tracebackFailure = (traceback) => {
1362
- const text = traceback.trim();
1363
- const lastFrame = text.lastIndexOf(`
1364
- File `);
1365
- if (lastFrame === -1) {
1366
- return text;
1547
+ var controllerDirectory = (outDir) => resolve9(outDir, ".codesys/controller");
1548
+ var jobOutput = (outDir, operationId) => resolve9(controllerDirectory(outDir), "jobs", operationId);
1549
+ var jobProgressLog = (outDir, operationId) => resolve9(controllerDirectory(jobOutput(outDir, operationId)), "progress.log");
1550
+ var missingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
1551
+ var controllerBaseline = async (outDir) => {
1552
+ const root = controllerDirectory(outDir);
1553
+ const pointer = await readFile7(resolve9(root, "current.json"), "utf8").then((text) => ({ text }), (error) => ({ error }));
1554
+ if ("error" in pointer) {
1555
+ return missingFile(pointer.error) ? "missing" : "malformed";
1367
1556
  }
1368
- const [, ...rest] = text.slice(lastFrame + 1).split(`
1369
- `);
1370
- return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
1371
- `);
1372
- };
1373
- var failureReason = (error) => tracebackFailure(error instanceof Error ? error.message : String(error)).replace(/^\w+: /, "");
1374
- var controllerTarget = (config, online) => ({
1375
- network: online.network,
1376
- gateway: online.gateway,
1377
- device: online.device,
1378
- controller: config.controller,
1379
- ...config.deviceTree && {
1380
- deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
1557
+ try {
1558
+ const { generation } = pointerSchema.parse(JSON.parse(pointer.text));
1559
+ baselineSchema.parse(JSON.parse(await readFile7(resolve9(root, "generations", generation, "manifest.json"), "utf8")));
1560
+ return "valid";
1561
+ } catch {
1562
+ return "malformed";
1381
1563
  }
1564
+ };
1565
+ var restoreResultSchema = z8.object({
1566
+ restored: z8.boolean(),
1567
+ controllerIds: z8.strictObject({ codeId: guid, dataId: guid }),
1568
+ state: z8.string()
1382
1569
  });
1383
- var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
1384
- var explicitDownload = "use an explicit download";
1385
- var loginCommandSchema = z6.discriminatedUnion("command", [
1386
- z6.strictObject({ command: z6.literal("state") }),
1387
- z6.strictObject({
1388
- command: z6.literal("read"),
1389
- expressions: z6.array(z6.string().nonempty()).nonempty()
1390
- }),
1391
- z6.strictObject({
1392
- command: z6.enum(["write", "force"]),
1393
- values: z6.record(z6.string().nonempty(), z6.string().nonempty())
1394
- }),
1395
- z6.strictObject({
1396
- command: z6.literal("unforce"),
1397
- expressions: z6.array(z6.string().nonempty()),
1398
- restore: z6.boolean()
1399
- }),
1400
- z6.strictObject({ command: z6.enum(["start", "stop"]) }),
1401
- z6.strictObject({
1402
- command: z6.literal("reset"),
1403
- kind: z6.enum(["Warm", "Cold"])
1404
- })
1405
- ]);
1406
- var loginResultSchema = z6.union([
1407
- z6.strictObject({ values: z6.record(z6.string(), z6.string()) }),
1408
- z6.strictObject({ state: z6.string(), forced: z6.array(z6.string()) })
1409
- ]);
1410
1570
 
1411
1571
  // packages/build/src/controller-online.ts
1412
- var credentialEnvironment = (config) => {
1572
+ var credentialEnvironment = (config, { environment = process.env }) => {
1413
1573
  const names = config.online?.credentials ? [
1414
1574
  config.online.credentials.usernameEnv,
1415
1575
  config.online.credentials.passwordEnv
1416
1576
  ] : [];
1417
- for (const name of names) {
1418
- if (process.env[name] === undefined) {
1577
+ return Object.fromEntries(names.map((name) => {
1578
+ const value = environment[name];
1579
+ if (value === undefined) {
1419
1580
  throw new Error(`Controller credential environment variable ${name} is not set`);
1420
1581
  }
1421
- }
1422
- return names;
1582
+ return [name, value];
1583
+ }));
1423
1584
  };
1424
1585
  var controllerConnection = async (config) => {
1425
1586
  if (!config.docker || !config.online) {
1426
1587
  throw new Error("Docker image and online gateway/device configuration are required for controller operations");
1427
1588
  }
1428
- const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", dockerImage3], config.timeouts.hostCommand).catch((cause) => {
1429
- throw new Error(`Cannot inspect Docker builder image ${dockerImage3}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1589
+ const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", builderImage], config.timeouts.hostCommand).catch((cause) => {
1590
+ throw new Error(`Cannot inspect Docker builder image ${builderImage}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1430
1591
  });
1431
1592
  return {
1432
1593
  imageId: imageIdSchema.parse(stdout.trim()),
1433
- templateHash: createHash3("sha256").update(await readFile6(config.template)).digest("hex"),
1594
+ templateHash: createHash4("sha256").update(await readFile8(config.template)).digest("hex"),
1434
1595
  target: controllerTarget(config, config.online)
1435
1596
  };
1436
1597
  };
@@ -1441,21 +1602,21 @@ var checkReceipt = (result, expected, diagnostics) => {
1441
1602
  return result;
1442
1603
  };
1443
1604
  var controllerOperation = async (config, operation, options) => {
1444
- const environmentNames = credentialEnvironment(config);
1605
+ const credentials = credentialEnvironment(config, options);
1445
1606
  const { imageId, templateHash, target } = await controllerConnection(config);
1446
- const operationId = randomUUID2();
1447
- const requestDirectory = await mkdtemp3(resolve8(tmpdir3(), "codesys-controller-"));
1448
- const diagnostics = resolve8(config.outDir, ".codesys/controller");
1449
- const failure = resolve8(config.outDir, controllerFailureFile);
1607
+ const operationId = randomUUID3();
1608
+ const requestDirectory = await mkdtemp4(resolve10(tmpdir4(), "codesys-controller-"));
1609
+ const diagnostics = controllerDirectory(config.outDir);
1610
+ const failure = resolve10(config.outDir, controllerFailureFile);
1450
1611
  try {
1451
- await mkdir5(config.outDir, { recursive: true });
1452
- await rm5(failure, { force: true });
1612
+ await mkdir7(config.outDir, { recursive: true });
1613
+ await rm7(failure, { force: true });
1453
1614
  await runDocker([
1454
1615
  "run",
1455
1616
  "--rm",
1456
1617
  ...await prepareContainerRun(config, requestDirectory, {
1457
1618
  network: target.network,
1458
- environment: environmentNames,
1619
+ environment: Object.keys(credentials),
1459
1620
  sources: operation !== "inspect"
1460
1621
  }),
1461
1622
  imageId,
@@ -1468,40 +1629,44 @@ var controllerOperation = async (config, operation, options) => {
1468
1629
  imageId,
1469
1630
  ...options.initializeUser ? ["--initialize-user"] : [],
1470
1631
  ...options.read ? ["--read", JSON.stringify(options.read)] : []
1471
- ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`).catch(async (cause) => {
1632
+ ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`, { progress: options.progress ?? "stdout", environment: credentials }).catch(async (cause) => {
1472
1633
  if (!existsSync(failure)) {
1473
1634
  throw cause;
1474
1635
  }
1475
- const reason = tracebackFailure(await readFile6(failure, "utf8"));
1636
+ const reason = tracebackFailure(await readFile8(failure, "utf8"));
1476
1637
  throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
1477
1638
  cause
1478
1639
  });
1479
1640
  });
1480
- const result = await readFile6(resolve8(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1641
+ const result = await readFile8(resolve10(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1481
1642
  throw new Error(`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`, { cause });
1482
1643
  });
1483
1644
  return checkReceipt(result, { operationId, operation, imageId, templateHash, target }, diagnostics);
1484
1645
  } finally {
1485
- await rm5(requestDirectory, { recursive: true, force: true });
1646
+ await rm7(requestDirectory, { recursive: true, force: true });
1486
1647
  }
1487
1648
  };
1488
1649
  var updateController = (config, operation, options = {}) => controllerOperation(config, operation, options);
1489
- var inspectController = (config, read) => controllerOperation(config, "inspect", { read });
1490
- var loginReplySchema = z7.discriminatedUnion("ok", [
1491
- z7.strictObject({ ok: z7.literal(true), result: z7.unknown() }),
1492
- z7.strictObject({ ok: z7.literal(false), error: z7.string() })
1650
+ var inspectController = (config, read, options = {}) => controllerOperation(config, "inspect", { ...options, read });
1651
+ var loginReplySchema = z9.discriminatedUnion("ok", [
1652
+ z9.strictObject({ ok: z9.literal(true), result: z9.unknown() }),
1653
+ z9.strictObject({
1654
+ ok: z9.literal(false),
1655
+ error: z9.string(),
1656
+ downloadRequired: z9.literal(true).optional(),
1657
+ rollback: rollbackSchema.optional()
1658
+ })
1493
1659
  ]);
1494
1660
  var loginPort = 4851;
1495
1661
  var warmPort = 4852;
1496
- var docker = (args, timeout) => captureDocker(args, timeout).then(({ stdout }) => stdout.trim());
1662
+ var docker = (args, timeout, environment = {}) => captureDocker(args, timeout, environment).then(({ stdout }) => stdout.trim());
1497
1663
  var recentLogs = async (name, timeout) => {
1498
1664
  const logs = await captureDocker(["logs", "--tail", "40", name], timeout);
1499
1665
  return `${logs.stdout}${logs.stderr}`;
1500
1666
  };
1501
1667
  var isRunning = async (name, timeout) => await docker(["container", "ls", "--quiet", "--filter", `name=^${name}$`], timeout) !== "";
1502
1668
  var callContainer = async (name, port, method, body) => {
1503
- const child = Bun.spawn([
1504
- "docker",
1669
+ const { stdout, stderr, status } = await pipeDocker([
1505
1670
  "exec",
1506
1671
  ...body === undefined ? [] : ["--interactive"],
1507
1672
  name,
@@ -1518,22 +1683,16 @@ var callContainer = async (name, port, method, body) => {
1518
1683
  "@-"
1519
1684
  ],
1520
1685
  `http://127.0.0.1:${port}/`
1521
- ], {
1522
- stdin: body === undefined ? "ignore" : new Blob([JSON.stringify(body)]),
1523
- stdout: "pipe",
1524
- stderr: "pipe"
1525
- });
1526
- const [output, errors, code] = await Promise.all([
1527
- new Response(child.stdout).text(),
1528
- new Response(child.stderr).text(),
1529
- child.exited
1530
- ]);
1531
- if (code !== 0) {
1532
- throw new Error(errors.trim() || `docker exec failed (${code})`);
1686
+ ], body === undefined ? null : JSON.stringify(body));
1687
+ if (status !== 0) {
1688
+ throw new Error(stderr.trim() || `docker exec failed (${status})`);
1533
1689
  }
1534
- const reply = loginReplySchema.parse(JSON.parse(output));
1690
+ const reply = loginReplySchema.parse(JSON.parse(stdout));
1535
1691
  if (!reply.ok) {
1536
- throw new Error(reply.error);
1692
+ if (reply.rollback) {
1693
+ throw new TransferFailedError(reply.error, reply.rollback);
1694
+ }
1695
+ throw reply.downloadRequired || reply.error.endsWith(explicitDownload) ? new DownloadRequiredError(reply.error) : new Error(reply.error);
1537
1696
  }
1538
1697
  return reply.result;
1539
1698
  };
@@ -1559,13 +1718,13 @@ var attachLogin = (name, timeout) => ({
1559
1718
  }
1560
1719
  });
1561
1720
  var findControllerLogin = async (name) => await isRunning(name, 15000) ? attachLogin(name, 15000) : undefined;
1562
- var openControllerLogin = async (config, name) => {
1563
- const environmentNames = credentialEnvironment(config);
1721
+ var openControllerLogin = async (config, name, options = {}) => {
1722
+ const credentials = credentialEnvironment(config, options);
1564
1723
  const { imageId, target } = await controllerConnection(config);
1565
1724
  const timeout = config.timeouts.hostCommand;
1566
1725
  await docker(["rm", "--force", name], timeout);
1567
- const requestDirectory = resolve8(config.outDir, ".codesys/login-request");
1568
- await mkdir5(requestDirectory, { recursive: true });
1726
+ const requestDirectory = resolve10(config.outDir, ".codesys/login-request");
1727
+ await mkdir7(requestDirectory, { recursive: true });
1569
1728
  await docker([
1570
1729
  "run",
1571
1730
  "--detach",
@@ -1573,7 +1732,7 @@ var openControllerLogin = async (config, name) => {
1573
1732
  name,
1574
1733
  ...await prepareContainerRun(config, requestDirectory, {
1575
1734
  network: target.network,
1576
- environment: environmentNames,
1735
+ environment: Object.keys(credentials),
1577
1736
  sources: false
1578
1737
  }),
1579
1738
  imageId,
@@ -1584,7 +1743,7 @@ var openControllerLogin = async (config, name) => {
1584
1743
  imageId,
1585
1744
  "--port",
1586
1745
  String(loginPort)
1587
- ], timeout);
1746
+ ], timeout, credentials);
1588
1747
  const login = attachLogin(name, timeout);
1589
1748
  const deadline = Date.now() + config.timeouts.startup + config.timeouts.build;
1590
1749
  while (Date.now() < deadline) {
@@ -1600,15 +1759,10 @@ ${await recentLogs(name, timeout)}`);
1600
1759
  await docker(["rm", "--force", name], timeout);
1601
1760
  throw new Error("The controller login did not open in time");
1602
1761
  };
1603
- var warmController = async (config, name, connection) => {
1762
+ var warmController = async (config, name, connection, report) => {
1604
1763
  const timeout = config.timeouts.hostCommand;
1605
1764
  const { imageId, target } = connection;
1606
- const settings = createHash3("sha256").update(JSON.stringify({
1607
- imageId,
1608
- target,
1609
- timeouts: config.timeouts,
1610
- docker: config.docker
1611
- })).digest("hex");
1765
+ const settings = createHash4("sha256").update(JSON.stringify({ imageId, target, docker: config.docker })).digest("hex");
1612
1766
  const label = `tsplc.warm=${settings}`;
1613
1767
  const running = async () => await docker([
1614
1768
  "container",
@@ -1620,9 +1774,10 @@ var warmController = async (config, name, connection) => {
1620
1774
  `label=${label}`
1621
1775
  ], timeout) !== "";
1622
1776
  if (!await running() || !await answers(name, warmPort)) {
1777
+ report("Starting CODESYS: no running builder matches this image, controller and Docker settings, which takes minutes");
1623
1778
  await docker(["rm", "--force", name], timeout);
1624
- const requestDirectory = resolve8(config.outDir, ".codesys/warm-request");
1625
- await mkdir5(requestDirectory, { recursive: true });
1779
+ const requestDirectory = resolve10(config.outDir, ".codesys/warm-request");
1780
+ await mkdir7(requestDirectory, { recursive: true });
1626
1781
  await docker([
1627
1782
  "run",
1628
1783
  "--detach",
@@ -1658,17 +1813,47 @@ ${await recentLogs(name, timeout)}`);
1658
1813
  await docker(["rm", "--force", name], timeout);
1659
1814
  throw new Error("CODESYS did not start in time");
1660
1815
  };
1816
+ var followProgress = (log, report) => {
1817
+ const stopped = new AbortController;
1818
+ const done = (async () => {
1819
+ let offset = 0;
1820
+ while (!stopped.signal.aborted) {
1821
+ await delay2(2000);
1822
+ if (!existsSync(log)) {
1823
+ continue;
1824
+ }
1825
+ const text = await readFile8(log, "utf8");
1826
+ for (const line of text.slice(offset).split(`
1827
+ `).filter(Boolean)) {
1828
+ report(line.replace(/^\S+Z /, ""));
1829
+ }
1830
+ offset = text.length;
1831
+ }
1832
+ })();
1833
+ return async () => {
1834
+ stopped.abort();
1835
+ await done;
1836
+ };
1837
+ };
1661
1838
  var startWarmController = async (config, name) => {
1662
- await warmController(config, name, await controllerConnection(config));
1839
+ await warmController(config, name, await controllerConnection(config), () => {});
1663
1840
  };
1664
1841
  var updateWarmController = async (config, name, operation, options = {}) => {
1842
+ const report = options.onProgress ?? (() => {});
1665
1843
  const connection = await controllerConnection(config);
1666
- await warmController(config, name, connection);
1667
- const operationId = randomUUID2();
1668
- const diagnostics = resolve8(config.outDir, ".codesys/controller");
1669
- const directory = resolve8(config.outDir, ".codesys/requests", operationId);
1844
+ const operationId = randomUUID3();
1845
+ const diagnostics = controllerDirectory(config.outDir);
1846
+ const directory = resolve10(config.outDir, ".codesys/requests", operationId);
1847
+ report("Copying the release for CODESYS");
1848
+ const [request] = await Promise.all([
1849
+ writeOperationRequest(config, directory, posix2.join("/output/.codesys/requests", operationId)),
1850
+ warmController(config, name, connection, report)
1851
+ ]).catch(async (error) => {
1852
+ await rm7(directory, { recursive: true, force: true });
1853
+ throw error;
1854
+ });
1855
+ const stopFollowing = options.onProgress ? followProgress(jobProgressLog(config.outDir, operationId), options.onProgress) : async () => {};
1670
1856
  try {
1671
- const request = await writeOperationRequest(config, directory, posix2.join("/output/.codesys/requests", operationId));
1672
1857
  const result = await callContainer(name, warmPort, "POST", {
1673
1858
  operation,
1674
1859
  operationId,
@@ -1676,9 +1861,12 @@ var updateWarmController = async (config, name, operation, options = {}) => {
1676
1861
  initializeUser: options.initializeUser ?? false,
1677
1862
  credentials: options.credentials
1678
1863
  }).catch((error) => {
1679
- throw new Error(`${failureReason(error)}. Inspect ${diagnostics} for diagnostics`, {
1680
- cause: error
1681
- });
1864
+ const message = `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`;
1865
+ const rollback = transferRollback(error);
1866
+ if (rollback) {
1867
+ throw new TransferFailedError(message, rollback, { cause: error });
1868
+ }
1869
+ throw requiresDownload(error) ? new DownloadRequiredError(message, { cause: error }) : new Error(message, { cause: error });
1682
1870
  });
1683
1871
  return checkReceipt(controllerResultSchema.parse(result), {
1684
1872
  operationId,
@@ -1688,7 +1876,8 @@ var updateWarmController = async (config, name, operation, options = {}) => {
1688
1876
  target: connection.target
1689
1877
  }, diagnostics);
1690
1878
  } finally {
1691
- await rm5(directory, { recursive: true, force: true });
1879
+ await stopFollowing();
1880
+ await rm7(directory, { recursive: true, force: true });
1692
1881
  }
1693
1882
  };
1694
1883
  // packages/build/src/engineering-settings.ts
@@ -1697,33 +1886,34 @@ import {
1697
1886
  rawBuildConfig,
1698
1887
  simulationConfig
1699
1888
  } from "@tsplc/config";
1889
+ import { resolveConfig } from "@tsplc/config/build";
1700
1890
  import { deviceTree } from "@tsplc/typegen";
1701
1891
  import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
1702
- import { resolveConfig } from "@tsplc/config/build";
1703
1892
 
1704
1893
  // packages/build/src/libraries.ts
1705
- import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
1706
- import { mkdir as mkdir6, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "node:fs/promises";
1707
- import { basename as basename4, relative as relative2, resolve as resolve9 } from "node:path";
1708
- import { sha256Digest as sha256Digest2 } from "@tsplc/config/build";
1709
- import { z as z8 } from "zod";
1894
+ import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
1895
+ import { mkdir as mkdir8, readFile as readFile9, rename as rename3, writeFile as writeFile6 } from "node:fs/promises";
1896
+ import { basename as basename5, relative as relative2, resolve as resolve11 } from "node:path";
1897
+ import { sha256Digest as sha256Digest3 } from "@tsplc/config/build";
1898
+ import { generatedDirectory } from "@tsplc/config/project-files";
1899
+ import { z as z10 } from "zod";
1710
1900
  var libraryRegistry = "https://store-archive.codesys.com/CODESYSLibs";
1711
1901
  var libraryFile = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1712
- var installedLibrarySchema = z8.object({
1713
- title: z8.string(),
1714
- company: z8.string().optional(),
1715
- version: z8.string().optional(),
1716
- namespace: z8.string().optional(),
1717
- path: z8.string(),
1718
- sha256: sha256Digest2,
1719
- url: z8.string().optional()
1902
+ var installedLibrarySchema = z10.object({
1903
+ title: z10.string(),
1904
+ company: z10.string().optional(),
1905
+ version: z10.string().optional(),
1906
+ namespace: z10.string().optional(),
1907
+ path: z10.string(),
1908
+ sha256: sha256Digest3,
1909
+ url: z10.string().optional()
1720
1910
  });
1721
- var libraryLockSchema = z8.object({
1722
- version: z8.literal(1),
1723
- dependencies: z8.record(z8.string(), installedLibrarySchema)
1911
+ var libraryLockSchema = z10.object({
1912
+ version: z10.literal(1),
1913
+ dependencies: z10.record(z10.string(), installedLibrarySchema)
1724
1914
  });
1725
1915
  var readLock = async (file) => {
1726
- const text = await readFile7(file, "utf8").catch((cause) => {
1916
+ const text = await readFile9(file, "utf8").catch((cause) => {
1727
1917
  if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1728
1918
  return;
1729
1919
  }
@@ -1738,7 +1928,7 @@ var readLock = async (file) => {
1738
1928
  }
1739
1929
  return lock.data;
1740
1930
  };
1741
- var hash = (data) => createHash4("sha256").update(data).digest("hex");
1931
+ var hash = (data) => createHash5("sha256").update(data).digest("hex");
1742
1932
  var component = (name) => {
1743
1933
  if (!name.trim() || /[/\\\0\r\n]/.test(name) || name === "." || name === "..") {
1744
1934
  throw new Error(`Invalid library registry component: ${name}.`);
@@ -1780,21 +1970,21 @@ async function validateLibrary(title, version, company = "System", fetcher = fet
1780
1970
  };
1781
1971
  }
1782
1972
  async function installLibraries(dependencies, root, options = {}) {
1783
- const file = resolve9(root, "tsplc.lock.json");
1784
- const store = resolve9(root, ".tsplc/libraries");
1973
+ const file = resolve11(root, "tsplc.lock.json");
1974
+ const store = resolve11(root, generatedDirectory, "libraries");
1785
1975
  const previous = await readLock(file);
1786
1976
  const installed = {};
1787
1977
  const fetcher = options.fetcher ?? fetch;
1788
- await mkdir6(store, { recursive: true });
1978
+ await mkdir8(store, { recursive: true });
1789
1979
  for (const [title, dependency] of Object.entries(dependencies)) {
1790
1980
  component(title);
1791
1981
  const settings = typeof dependency === "string" ? { version: dependency } : dependency;
1792
1982
  const locked = previous.dependencies[title];
1793
- const prior = locked ? { ...locked, path: resolve9(root, locked.path) } : undefined;
1794
- const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve9(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1983
+ const prior = locked ? { ...locked, path: resolve11(root, locked.path) } : undefined;
1984
+ const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve11(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1795
1985
  if (same) {
1796
1986
  try {
1797
- if (hash(await readFile7(prior.path)) === prior.sha256) {
1987
+ if (hash(await readFile9(prior.path)) === prior.sha256) {
1798
1988
  installed[title] = prior;
1799
1989
  continue;
1800
1990
  }
@@ -1806,14 +1996,14 @@ async function installLibraries(dependencies, root, options = {}) {
1806
1996
  throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1807
1997
  }
1808
1998
  if ("path" in settings) {
1809
- const path = resolve9(root, settings.path);
1999
+ const path = resolve11(root, settings.path);
1810
2000
  if (!libraryFile.test(path)) {
1811
2001
  throw new Error(`${title}: expected a .library or .compiled-library file.`);
1812
2002
  }
1813
2003
  installed[title] = {
1814
2004
  title,
1815
2005
  path,
1816
- sha256: hash(await readFile7(path)),
2006
+ sha256: hash(await readFile9(path)),
1817
2007
  ...settings.namespace ? { namespace: settings.namespace } : {}
1818
2008
  };
1819
2009
  } else {
@@ -1828,9 +2018,9 @@ async function installLibraries(dependencies, root, options = {}) {
1828
2018
  if (same && prior.sha256 !== sha256) {
1829
2019
  throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1830
2020
  }
1831
- const path = resolve9(store, `${sha256}-${basename4(payload.filename)}`);
1832
- const temp = `${path}.${randomUUID3()}.tmp`;
1833
- await writeFile5(temp, data, { flag: "wx" });
2021
+ const path = resolve11(store, `${sha256}-${basename5(payload.filename)}`);
2022
+ const temp = `${path}.${randomUUID4()}.tmp`;
2023
+ await writeFile6(temp, data, { flag: "wx" });
1834
2024
  await rename3(temp, path);
1835
2025
  installed[title] = {
1836
2026
  title,
@@ -1847,7 +2037,7 @@ async function installLibraries(dependencies, root, options = {}) {
1847
2037
  throw new Error("Removed dependencies differ from tsplc.lock.json.");
1848
2038
  }
1849
2039
  if (!options.frozen) {
1850
- const temp = `${file}.${randomUUID3()}.tmp`;
2040
+ const temp = `${file}.${randomUUID4()}.tmp`;
1851
2041
  const portable = Object.fromEntries(Object.entries(installed).map(([title, library]) => [
1852
2042
  title,
1853
2043
  {
@@ -1855,7 +2045,7 @@ async function installLibraries(dependencies, root, options = {}) {
1855
2045
  path: relative2(root, library.path).replaceAll("\\", "/")
1856
2046
  }
1857
2047
  ]));
1858
- await writeFile5(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
2048
+ await writeFile6(temp, `${JSON.stringify({ version: 1, dependencies: portable }, null, 2)}
1859
2049
  `);
1860
2050
  await rename3(temp, file);
1861
2051
  }
@@ -1878,12 +2068,33 @@ var rawEngineeringSettings = async ({ config, configFile, root }, options) => {
1878
2068
  controller: controllerFor(config, options.command)
1879
2069
  }, configFile);
1880
2070
  };
2071
+ // packages/build/src/project-operations.ts
2072
+ import {
2073
+ controllerFor as controllerFor2,
2074
+ rawBuildConfig as rawBuildConfig2
2075
+ } from "@tsplc/config";
2076
+ import { resolveConfig as resolveConfig2 } from "@tsplc/config/build";
2077
+ import { loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen/hardware";
2078
+ var checkRawSources = async ({
2079
+ config,
2080
+ configFile,
2081
+ root
2082
+ }) => loadSources(resolveConfig2({
2083
+ ...rawBuildConfig2(config),
2084
+ io: resolveIo2(config, await loadHardware2(config, root))
2085
+ }, configFile));
2086
+ var inspectProjectController = ({ config, configFile }, read, options) => {
2087
+ if (!config.build) {
2088
+ throw new Error("Configure build settings and controller connection.");
2089
+ }
2090
+ return inspectController(resolveConfig2({ ...config.build, controller: controllerFor2(config, "inspect") }, configFile), read, options);
2091
+ };
1881
2092
  // packages/build/src/run.ts
1882
- import { mkdtemp as mkdtemp4, readFile as readFile8, rm as rm6, writeFile as writeFile6 } from "node:fs/promises";
1883
- import { tmpdir as tmpdir4 } from "node:os";
1884
- import { basename as basename5, dirname as dirname2, join } from "node:path";
2093
+ import { mkdtemp as mkdtemp5, readFile as readFile10, rm as rm8, writeFile as writeFile7 } from "node:fs/promises";
2094
+ import { tmpdir as tmpdir5 } from "node:os";
2095
+ import { basename as basename6, dirname as dirname2, join } from "node:path";
1885
2096
  import { setTimeout as delay3 } from "node:timers/promises";
1886
- import { z as z9 } from "zod";
2097
+ import { z as z11 } from "zod";
1887
2098
 
1888
2099
  // packages/build/src/runtime-status.ts
1889
2100
  var getApplicationStatus = (log, application, startedAt) => {
@@ -1901,9 +2112,9 @@ var getApplicationStatus = (log, application, startedAt) => {
1901
2112
  };
1902
2113
 
1903
2114
  // packages/build/src/run.ts
1904
- var stateSchema = z9.object({
1905
- Running: z9.boolean(),
1906
- StartedAt: z9.iso.datetime({ offset: true })
2115
+ var stateSchema = z11.object({
2116
+ Running: z11.boolean(),
2117
+ StartedAt: z11.iso.datetime({ offset: true })
1907
2118
  });
1908
2119
  var service = "plc";
1909
2120
  var runtimeProject = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
@@ -1925,22 +2136,22 @@ var runtimeDefinition = (name) => ({
1925
2136
  },
1926
2137
  volumes: { "control-conf": {}, "control-data": {} }
1927
2138
  });
1928
- var runProject = async (config, name) => withWorkerLock(config, async () => {
2139
+ var runProject = async (config, name, { progress = "stdout" } = {}) => withWorkerLock(config, async () => {
1929
2140
  const build = await readBuild(config.outDir).catch((cause) => {
1930
2141
  throw new Error(`No complete build in ${config.outDir}. Run tsplc-build build first.`, {
1931
2142
  cause
1932
2143
  });
1933
2144
  });
1934
- const definitionDirectory = await mkdtemp4(join(tmpdir4(), "tsplc-runtime-"));
2145
+ const definitionDirectory = await mkdtemp5(join(tmpdir5(), "tsplc-runtime-"));
1935
2146
  try {
1936
2147
  const composeFile = join(definitionDirectory, "compose.yaml");
1937
- await writeFile6(composeFile, JSON.stringify(runtimeDefinition(name)));
2148
+ await writeFile7(composeFile, JSON.stringify(runtimeDefinition(name)));
1938
2149
  const docker = (...args) => captureDocker(args, config.timeouts.runtime);
1939
2150
  const compose = (...args) => docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
1940
- const installer = await readFile8(new URL("../runtime/install.sh", import.meta.url), "utf8");
1941
- console.log(`Installing ${build.application} in Docker service ${service}`);
2151
+ const installer = await readFile10(new URL("../runtime/install.sh", import.meta.url), "utf8");
2152
+ progressLog(progress)(`Installing ${build.application} in Docker service ${service}`);
1942
2153
  await compose("stop", service);
1943
- await compose("run", "--rm", "--no-deps", "-T", "--volume", `${dirname2(build.output)}:/codesys-build:ro`, "--entrypoint", "/bin/sh", service, "-c", installer, "codesys-build-install", build.application, basename5(build.output, ".app"));
2154
+ await compose("run", "--rm", "--no-deps", "-T", "--volume", `${dirname2(build.output)}:/codesys-build:ro`, "--entrypoint", "/bin/sh", service, "-c", installer, "codesys-build-install", build.application, basename6(build.output, ".app"));
1944
2155
  await compose("up", "--detach", "--no-deps", service);
1945
2156
  const containers = (await compose("ps", "--all", "--quiet", service)).stdout.trim().split(/\s+/).filter(Boolean);
1946
2157
  if (containers.length !== 1 || !containers[0]) {
@@ -1956,7 +2167,7 @@ var runProject = async (config, name) => withWorkerLock(config, async () => {
1956
2167
  const { stdout: log } = await docker("exec", container, "/bin/sh", "-c", "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi");
1957
2168
  const status = getApplicationStatus(log, build.application, Date.parse(state.StartedAt));
1958
2169
  if (status === "running") {
1959
- console.log(`${build.application} is running in ${service}`);
2170
+ progressLog(progress)(`${build.application} is running in ${service}`);
1960
2171
  return { ...build, container };
1961
2172
  }
1962
2173
  if (status === "failed" || Date.now() >= deadline) {
@@ -1968,23 +2179,28 @@ ${log.split(`
1968
2179
  await delay3(250);
1969
2180
  }
1970
2181
  } finally {
1971
- await rm6(definitionDirectory, { force: true, recursive: true });
2182
+ await rm8(definitionDirectory, { force: true, recursive: true });
1972
2183
  }
1973
2184
  });
1974
2185
  export {
1975
2186
  CodesysCompilerError,
1976
2187
  StSyntaxError,
2188
+ TransferFailedError,
1977
2189
  buildProject,
2190
+ captureDocker,
2191
+ checkRawSources,
1978
2192
  configSchema,
1979
2193
  configureDocker,
1980
2194
  configureGateway,
1981
2195
  configureRuntime,
2196
+ controllerBaseline,
1982
2197
  defineBuildConfig as defineConfig,
1983
2198
  explicitDownload,
1984
2199
  failureReason,
1985
2200
  findControllerLogin,
1986
2201
  gatewayImage,
1987
2202
  inspectController,
2203
+ inspectProjectController,
1988
2204
  installLibraries,
1989
2205
  libraryIndex,
1990
2206
  loadConfig,
@@ -1995,13 +2211,17 @@ export {
1995
2211
  parseSource,
1996
2212
  rawEngineeringSettings,
1997
2213
  readBuild,
1998
- resolveConfig2 as resolveConfig,
2214
+ requiresDownload,
2215
+ resolveConfig3 as resolveConfig,
2216
+ rollbackSchema,
1999
2217
  runProject,
2000
2218
  startWarmController,
2219
+ transferRollback,
2001
2220
  updateController,
2002
2221
  updateWarmController,
2003
- validateLibrary
2222
+ validateLibrary,
2223
+ workerScriptsDigest
2004
2224
  };
2005
2225
 
2006
- //# debugId=184411194E92563564756E2164756E21
2226
+ //# debugId=5EBE823A1A5EB77664756E2164756E21
2007
2227
  //# sourceMappingURL=index.js.map