@tsplc/build 0.2.20 → 0.3.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/cli.js CHANGED
@@ -3,9 +3,8 @@
3
3
 
4
4
  // packages/build/src/cli.ts
5
5
  import { parseArgs } from "util";
6
- import { loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen/hardware";
7
- import { controllerFor as controllerFor2, loadTsplcConfig, rawBuildConfig as rawBuildConfig2 } from "@tsplc/config";
8
- import { z as z12 } from "zod";
6
+ import { loadTsplcConfig } from "@tsplc/config";
7
+ import { z as z15 } from "zod";
9
8
 
10
9
  // packages/build/src/artifacts.ts
11
10
  import {
@@ -18,9 +17,9 @@ import {
18
17
  writeFile
19
18
  } from "node:fs/promises";
20
19
  import { resolve } from "node:path";
20
+ import { cyclicTasksSchema } from "@tsplc/config/build";
21
21
  import { identifierPattern } from "@tsplc/iec/st";
22
22
  import { z } from "zod";
23
- import { cyclicTasksSchema } from "@tsplc/config/build";
24
23
  var buildFiles = {
25
24
  project: "Application.project",
26
25
  output: "runtime/Application.app",
@@ -60,68 +59,12 @@ var readBuild = async (directory) => {
60
59
  };
61
60
  };
62
61
 
63
- // packages/build/src/build.ts
64
- import { dockerImage as dockerImage2 } from "@tsplc/config/build";
65
-
66
62
  // packages/build/src/docker-build.ts
67
63
  import { randomUUID } from "node:crypto";
68
- import { cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, readFile as readFile3, rm as rm3 } from "node:fs/promises";
69
- import { tmpdir as tmpdir2 } from "node:os";
70
- import { resolve as resolve5 } from "node:path";
71
- import { z as z3 } from "zod";
72
- import { dockerImage } from "@tsplc/config/build";
73
-
74
- // packages/build/src/docker-context.ts
75
- import { cp as cp2, mkdir, mkdtemp, rm as rm2, writeFile as writeFile2 } from "node:fs/promises";
76
- import { createRequire } from "node:module";
77
- import { tmpdir } from "node:os";
78
- import { dirname, resolve as resolve3 } from "node:path";
79
-
80
- // packages/build/src/package-path.ts
81
- import { resolve as resolve2 } from "node:path";
82
- import { fileURLToPath } from "node:url";
83
- var packageDirectory = resolve2(fileURLToPath(new URL("..", import.meta.url)));
84
-
85
- // packages/build/src/docker-context.ts
86
- var containerPackages = [
87
- {
88
- entry: "@tsplc/config/build",
89
- directory: "shared-config",
90
- files: ["src", "templates", "package.json"]
91
- },
92
- {
93
- entry: "@tsplc/iec",
94
- directory: "shared-iec",
95
- files: ["src", "package.json"]
96
- }
97
- ];
98
- async function prepareDockerContext() {
99
- const context = await mkdtemp(resolve3(tmpdir(), "tsplc-docker-"));
100
- try {
101
- for (const directory of ["src", "python", "docker", "runtime"]) {
102
- await cp2(resolve3(packageDirectory, directory), resolve3(context, directory), {
103
- recursive: true
104
- });
105
- }
106
- for (const { entry, directory, files } of containerPackages) {
107
- const root = resolve3(dirname(createRequire(import.meta.url).resolve(entry)), "..");
108
- await mkdir(resolve3(context, directory));
109
- for (const file of files) {
110
- await cp2(resolve3(root, file), resolve3(context, directory, file), {
111
- recursive: true
112
- });
113
- }
114
- }
115
- await writeFile2(resolve3(context, "package.json"), JSON.stringify({
116
- type: "module",
117
- dependencies: { zod: "4.3.6", jiti: "2.7.0" }
118
- }));
119
- return context;
120
- } catch (cause) {
121
- await rm2(context, { recursive: true, force: true });
122
- throw cause;
123
- }
124
- }
64
+ import { mkdir as mkdir4, mkdtemp as mkdtemp3, readFile as readFile4, rm as rm4 } from "node:fs/promises";
65
+ import { tmpdir as tmpdir3 } from "node:os";
66
+ import { resolve as resolve6 } from "node:path";
67
+ import { z as z4 } from "zod";
125
68
 
126
69
  // packages/build/src/diagnostics.ts
127
70
  import { z as z2 } from "zod";
@@ -163,18 +106,28 @@ var buildFailureSchema = z2.strictObject({
163
106
  // packages/build/src/docker-run.ts
164
107
  import { execFile, spawn } from "node:child_process";
165
108
  import { createHash } from "node:crypto";
166
- import { copyFile as copyFile2, cp as cp3, mkdir as mkdir2, readFile as readFile2, writeFile as writeFile3 } from "node:fs/promises";
167
- import { basename, posix, relative, resolve as resolve4, sep } from "node:path";
109
+ import { copyFile as copyFile2, cp as cp2, mkdir, readFile as readFile2, writeFile as writeFile2 } from "node:fs/promises";
110
+ import { basename, posix, relative, resolve as resolve2, sep } from "node:path";
168
111
  import { promisify } from "node:util";
169
112
  var execute = promisify(execFile);
170
- var captureDocker = (args, timeout) => execute("docker", args, { timeout, maxBuffer: 8 * 1024 * 1024 });
171
- var runDocker = (args, failure) => new Promise((accept, reject) => {
113
+ var progressLog = (stream) => stream === "stderr" ? console.error : console.log;
114
+ var clientEnvironment = (environment) => ({
115
+ ...process.env,
116
+ ...environment
117
+ });
118
+ var captureDocker = (args, timeout, environment = {}) => execute("docker", args, {
119
+ timeout,
120
+ maxBuffer: 8 * 1024 * 1024,
121
+ env: clientEnvironment(environment)
122
+ });
123
+ var runDocker = (args, failure, output) => new Promise((accept, reject) => {
172
124
  const child = spawn("docker", args, {
173
125
  stdio: [
174
126
  "inherit",
175
- process.env["TSPLC_LOG_STDERR"] === "1" ? 2 : "inherit",
127
+ output.progress === "stderr" ? 2 : "inherit",
176
128
  "inherit"
177
- ]
129
+ ],
130
+ env: clientEnvironment(output.environment)
178
131
  });
179
132
  const interrupt = () => child.kill("SIGINT");
180
133
  const terminate = () => child.kill("SIGTERM");
@@ -204,14 +157,14 @@ async function mountLibraries(libraries, directory, root = "/input") {
204
157
  if (!libraries?.length) {
205
158
  return;
206
159
  }
207
- await mkdir2(resolve4(directory, "libraries"), { recursive: true });
160
+ await mkdir(resolve2(directory, "libraries"), { recursive: true });
208
161
  return Promise.all(libraries.map(async (library) => {
209
162
  const data = await readFile2(library.path);
210
163
  if (createHash("sha256").update(data).digest("hex") !== library.sha256) {
211
164
  throw new Error(`Library changed after installation: ${library.title}`);
212
165
  }
213
166
  const filename = `${library.sha256}-${basename(library.path)}`;
214
- await writeFile3(resolve4(directory, "libraries", filename), data);
167
+ await writeFile2(resolve2(directory, "libraries", filename), data);
215
168
  return { ...library, path: `${root}/libraries/${filename}` };
216
169
  }));
217
170
  }
@@ -228,7 +181,7 @@ var containerConfig = (config, paths, libraries) => ({
228
181
  runtime: undefined
229
182
  });
230
183
  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) : [])));
184
+ await writeFile2(resolve2(requestDirectory, "config.json"), JSON.stringify(containerConfig(config, { sourceDir: "/sources", template: "/template.project" }, options.sources ? await mountLibraries(config.libraries, requestDirectory) : [])));
232
185
  return [
233
186
  "--init",
234
187
  ...config.docker?.cpuSet ? ["--cpuset-cpus", config.docker.cpuSet] : [],
@@ -246,15 +199,157 @@ var prepareContainerRun = async (config, requestDirectory, options) => {
246
199
  ];
247
200
  };
248
201
 
249
- // packages/build/src/docker-build.ts
202
+ // packages/build/src/images.ts
203
+ import { copyFile as copyFile3, cp as cp4, mkdir as mkdir3, mkdtemp as mkdtemp2, rm as rm3 } from "node:fs/promises";
204
+ import { tmpdir as tmpdir2 } from "node:os";
205
+ import { resolve as resolve5 } from "node:path";
206
+ import { dockerImage } from "@tsplc/config/build";
207
+
208
+ // packages/build/src/docker-context.ts
209
+ import { cp as cp3, mkdir as mkdir2, mkdtemp, readFile as readFile3, rm as rm2, writeFile as writeFile3 } from "node:fs/promises";
210
+ import { createRequire } from "node:module";
211
+ import { tmpdir } from "node:os";
212
+ import { basename as basename2, dirname, resolve as resolve4 } from "node:path";
213
+ import { z as z3 } from "zod";
214
+
215
+ // packages/build/src/package-path.ts
216
+ import { resolve as resolve3 } from "node:path";
217
+ import { fileURLToPath } from "node:url";
218
+ var packageDirectory = resolve3(fileURLToPath(new URL("..", import.meta.url)));
219
+
220
+ // packages/build/src/docker-context.ts
221
+ var includeSource = (source) => {
222
+ const name = basename2(source);
223
+ return name !== "__pycache__" && !name.endsWith(".pyc") && !name.endsWith(".test.ts") && !name.endsWith(".fixtures.ts") && !(name.startsWith("test_") && name.endsWith(".py"));
224
+ };
225
+ var containerPackages = [
226
+ {
227
+ entry: "@tsplc/config/build",
228
+ directory: "shared-config",
229
+ files: ["src", "templates", "package.json"]
230
+ },
231
+ {
232
+ entry: "@tsplc/iec",
233
+ directory: "shared-iec",
234
+ files: ["src", "package.json"]
235
+ }
236
+ ];
237
+ var manifestDependencies = z3.object({
238
+ name: z3.string(),
239
+ dependencies: z3.record(z3.string(), z3.string()).default({})
240
+ });
241
+ function containerDependencies(manifests) {
242
+ const selected = new Map;
243
+ for (const manifest of manifests) {
244
+ for (const [name, version] of Object.entries(manifest.dependencies)) {
245
+ if (name.startsWith("@tsplc/")) {
246
+ continue;
247
+ }
248
+ const existing = selected.get(name);
249
+ if (existing && existing.version !== version) {
250
+ throw new Error(`The builder image cannot install ${name}: ${existing.owner} pins ${existing.version} and ${manifest.name} pins ${version}.`);
251
+ }
252
+ selected.set(name, { version, owner: manifest.name });
253
+ }
254
+ }
255
+ return Object.fromEntries([...selected].map(([name, { version }]) => [name, version]));
256
+ }
257
+ var readManifest = async (directory) => manifestDependencies.parse(JSON.parse(await readFile3(resolve4(directory, "package.json"), "utf8")));
258
+ async function prepareDockerContext() {
259
+ const context = await mkdtemp(resolve4(tmpdir(), "tsplc-docker-"));
260
+ try {
261
+ for (const directory of ["src", "python", "docker", "runtime"]) {
262
+ await cp3(resolve4(packageDirectory, directory), resolve4(context, directory), {
263
+ recursive: true,
264
+ filter: includeSource
265
+ });
266
+ }
267
+ const manifests = [await readManifest(packageDirectory)];
268
+ for (const { entry, directory, files } of containerPackages) {
269
+ const root = resolve4(dirname(createRequire(import.meta.url).resolve(entry)), "..");
270
+ manifests.push(await readManifest(root));
271
+ await mkdir2(resolve4(context, directory));
272
+ for (const file of files) {
273
+ await cp3(resolve4(root, file), resolve4(context, directory, file), {
274
+ recursive: true,
275
+ filter: includeSource
276
+ });
277
+ }
278
+ }
279
+ await writeFile3(resolve4(context, "package.json"), JSON.stringify({
280
+ type: "module",
281
+ dependencies: containerDependencies(manifests)
282
+ }));
283
+ return context;
284
+ } catch (cause) {
285
+ await rm2(context, { recursive: true, force: true });
286
+ throw cause;
287
+ }
288
+ }
289
+
290
+ // packages/build/src/images.ts
291
+ var builderImage = dockerImage;
250
292
  var runtimeImage = "tsplc-control-linux-sl:4.22.0.0";
251
- var buildInDocker = async (config, image) => {
252
- const requestDirectory = await mkdtemp2(resolve5(tmpdir2(), "codesys-docker-"));
293
+ var publishedImage = (image, version) => `ghcr.io/rip-technologies/${image.split(":")[0]}:${version}`;
294
+ var setupPlatformFor = (server) => {
295
+ if (server === "linux/aarch64" || server === "linux/arm64") {
296
+ return "linux/arm64";
297
+ }
298
+ if (server === "linux/x86_64" || server === "linux/amd64") {
299
+ return "linux/amd64";
300
+ }
301
+ return null;
302
+ };
303
+ async function buildBuilderImage(options) {
304
+ const installerContext = await mkdtemp2(resolve5(tmpdir2(), "codesys-installer-"));
305
+ let context;
306
+ try {
307
+ context = await prepareDockerContext();
308
+ const cache = resolve5(installerContext, "winetricks");
309
+ await mkdir3(cache);
310
+ if (options.winetricksCache) {
311
+ await cp4(options.winetricksCache, cache, { recursive: true });
312
+ }
313
+ if (options.installer) {
314
+ await copyFile3(options.installer, resolve5(installerContext, "codesys.exe"));
315
+ }
316
+ const arm = options.setupPlatform === "linux/arm64";
317
+ await options.docker([
318
+ "build",
319
+ "--platform",
320
+ "linux/amd64",
321
+ "--build-arg",
322
+ `SETUP_BASE=${arm ? "arm-setup" : "base"}`,
323
+ "--build-arg",
324
+ `SETUP_PLATFORM=${options.setupPlatform}`,
325
+ "--build-arg",
326
+ `INSTALLER_SOURCE=${options.installer ? "installer-local" : "installer-download"}`,
327
+ "--progress",
328
+ "plain",
329
+ "--build-context",
330
+ `installer=${installerContext}`,
331
+ "-f",
332
+ resolve5(context, "docker/Dockerfile"),
333
+ "-t",
334
+ options.tag,
335
+ context
336
+ ]);
337
+ } finally {
338
+ await Promise.all([
339
+ rm3(installerContext, { recursive: true, force: true }),
340
+ ...context ? [rm3(context, { recursive: true, force: true })] : []
341
+ ]);
342
+ }
343
+ }
344
+
345
+ // packages/build/src/docker-build.ts
346
+ var buildInDocker = async (config, image, progress) => {
347
+ const requestDirectory = await mkdtemp3(resolve6(tmpdir3(), "codesys-docker-"));
253
348
  try {
254
349
  const operationId = randomUUID();
255
- await mkdir3(config.outDir, { recursive: true });
256
- const failurePath = resolve5(config.outDir, buildFailureFile);
257
- await rm3(failurePath, { force: true });
350
+ await mkdir4(config.outDir, { recursive: true });
351
+ const failurePath = resolve6(config.outDir, buildFailureFile);
352
+ await rm4(failurePath, { force: true });
258
353
  const args = [
259
354
  "run",
260
355
  "--rm",
@@ -268,12 +363,12 @@ var buildInDocker = async (config, image) => {
268
363
  "--operation-id",
269
364
  operationId
270
365
  ];
271
- console.log(`Building with Docker (${image})`);
366
+ progressLog(progress)(`Building with Docker (${image})`);
272
367
  try {
273
- await runDocker(args, (status) => `Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`);
368
+ 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: {} });
274
369
  } catch (cause) {
275
370
  const message = cause instanceof Error ? cause.message : String(cause);
276
- const failure = await readFile3(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
371
+ const failure = await readFile4(failurePath, "utf8").then((text) => buildFailureSchema.parse(JSON.parse(text))).catch((error) => {
277
372
  if (error instanceof Error && "code" in error && error.code === "ENOENT") {
278
373
  return;
279
374
  }
@@ -298,25 +393,126 @@ ${failure.message}`;
298
393
  }
299
394
  return await readBuild(config.outDir);
300
395
  } finally {
301
- await rm3(requestDirectory, { recursive: true, force: true });
396
+ await rm4(requestDirectory, { recursive: true, force: true });
302
397
  }
303
398
  };
304
399
 
305
400
  // packages/build/src/host/codesys-worker.ts
306
401
  import {
307
402
  access,
308
- copyFile as copyFile3,
309
- mkdir as mkdir4,
403
+ copyFile as copyFile4,
404
+ mkdir as mkdir5,
310
405
  open,
311
- readFile as readFile4,
406
+ readFile as readFile5,
312
407
  rename as rename2,
313
- rm as rm4,
408
+ rm as rm5,
314
409
  unlink,
315
410
  writeFile as writeFile4
316
411
  } from "node:fs/promises";
317
- import { resolve as resolve6 } from "node:path";
412
+ import { resolve as resolve7 } from "node:path";
318
413
  import { setTimeout as delay } from "node:timers/promises";
414
+ import { z as z7 } from "zod";
415
+
416
+ // packages/build/src/controller-protocol.ts
417
+ import { createHash as createHash2 } from "node:crypto";
418
+ import {
419
+ controllerSchema,
420
+ sha256Digest,
421
+ tcpPort
422
+ } from "@tsplc/config/build";
319
423
  import { z as z5 } from "zod";
424
+ var imageIdSchema = z5.string().regex(/^sha256:[a-f0-9]{64}$/);
425
+ var endpointSchema = z5.strictObject({
426
+ host: z5.string().nonempty(),
427
+ port: tcpPort
428
+ });
429
+ var controllerResultSchema = z5.strictObject({
430
+ schemaVersion: z5.literal(1),
431
+ operationId: z5.uuid(),
432
+ operation: z5.enum(["download", "online-change", "inspect"]),
433
+ imageId: imageIdSchema,
434
+ templateHash: sha256Digest,
435
+ target: z5.strictObject({
436
+ network: z5.string().nonempty(),
437
+ gateway: endpointSchema,
438
+ device: endpointSchema,
439
+ controller: controllerSchema.optional(),
440
+ deviceTree: sha256Digest.optional()
441
+ }),
442
+ generation: z5.string().nonempty(),
443
+ application: z5.string().nonempty(),
444
+ applicationGuid: z5.string().nonempty(),
445
+ controllerIds: z5.strictObject({
446
+ codeId: z5.string().nonempty(),
447
+ dataId: z5.string().nonempty()
448
+ }),
449
+ state: z5.string().nonempty(),
450
+ values: z5.record(z5.string(), z5.string())
451
+ });
452
+ var controllerCredentialsSchema = z5.strictObject({
453
+ username: z5.string().nonempty(),
454
+ password: z5.string().nonempty()
455
+ });
456
+ var warmOperationSchema = z5.strictObject({
457
+ operation: z5.enum(["download", "online-change"]),
458
+ operationId: z5.uuid(),
459
+ request: z5.string().nonempty(),
460
+ initializeUser: z5.boolean(),
461
+ credentials: controllerCredentialsSchema.optional()
462
+ });
463
+ var tracebackFailure = (traceback) => {
464
+ const text = traceback.trim();
465
+ const lastFrame = text.lastIndexOf(`
466
+ File `);
467
+ if (lastFrame === -1) {
468
+ return text;
469
+ }
470
+ const [, ...rest] = text.slice(lastFrame + 1).split(`
471
+ `);
472
+ return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
473
+ `);
474
+ };
475
+ var controllerTarget = (config, online) => ({
476
+ network: online.network,
477
+ gateway: online.gateway,
478
+ device: online.device,
479
+ controller: config.controller,
480
+ ...config.deviceTree && {
481
+ deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
482
+ }
483
+ });
484
+ var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
485
+ var rollbackSchema = z5.enum([
486
+ "intact",
487
+ "restored",
488
+ "failed",
489
+ "unavailable"
490
+ ]);
491
+ var loginCommandSchema = z5.discriminatedUnion("command", [
492
+ z5.strictObject({ command: z5.literal("state") }),
493
+ z5.strictObject({
494
+ command: z5.literal("read"),
495
+ expressions: z5.array(z5.string().nonempty()).nonempty()
496
+ }),
497
+ z5.strictObject({
498
+ command: z5.enum(["write", "force"]),
499
+ values: z5.record(z5.string().nonempty(), z5.string().nonempty())
500
+ }),
501
+ z5.strictObject({
502
+ command: z5.literal("unforce"),
503
+ expressions: z5.array(z5.string().nonempty()),
504
+ restore: z5.boolean()
505
+ }),
506
+ z5.strictObject({ command: z5.enum(["start", "stop"]) }),
507
+ z5.strictObject({
508
+ command: z5.literal("reset"),
509
+ kind: z5.enum(["Warm", "Cold"])
510
+ })
511
+ ]);
512
+ var loginResultSchema = z5.union([
513
+ z5.strictObject({ values: z5.record(z5.string(), z5.string()) }),
514
+ z5.strictObject({ state: z5.string(), forced: z5.array(z5.string()) })
515
+ ]);
320
516
 
321
517
  // packages/build/src/host/codesys-command.ts
322
518
  var codesysCommand = [
@@ -333,7 +529,7 @@ var codesysCommand = [
333
529
  // packages/build/src/host/codesys-host.ts
334
530
  import { execFile as execFile3, spawn as spawn2 } from "node:child_process";
335
531
  import { promisify as promisify3 } from "node:util";
336
- import { z as z4 } from "zod";
532
+ import { z as z6 } from "zod";
337
533
 
338
534
  // packages/build/src/host/windows-path.ts
339
535
  import { execFile as execFile2 } from "node:child_process";
@@ -346,19 +542,20 @@ var execute2 = promisify2(execFile2);
346
542
 
347
543
  // packages/build/src/host/codesys-host.ts
348
544
  var execute3 = promisify3(execFile3);
349
- var exitSchema = z4.object({
350
- pid: z4.int().positive(),
351
- code: z4.int().nullable(),
352
- signal: z4.string().nullable()
545
+ var exitSchema = z6.object({
546
+ pid: z6.int().positive(),
547
+ code: z6.int().nullable(),
548
+ signal: z6.string().nullable()
353
549
  });
354
550
 
355
551
  // packages/build/src/host/codesys-worker.ts
356
- var pythonDirectory = resolve6(packageDirectory, "python");
357
- var sessionSchema = z5.object({
358
- directory: z5.string(),
359
- fingerprint: z5.string(),
360
- pid: z5.int().positive()
552
+ var pythonDirectory = resolve7(packageDirectory, "python");
553
+ var sessionSchema = z7.object({
554
+ directory: z7.string(),
555
+ fingerprint: z7.string(),
556
+ pid: z7.int().positive()
361
557
  });
558
+ var phaseSchema = z7.enum(["prepare", "transfer"]);
362
559
  var hasCode = (error, code) => error instanceof Error && ("code" in error) && error.code === code;
363
560
  var isProcessAlive = (pid) => {
364
561
  try {
@@ -372,8 +569,8 @@ var isProcessAlive = (pid) => {
372
569
  }
373
570
  };
374
571
  var withWorkerLock = async (config, run) => {
375
- await mkdir4(resolve6(config.outDir, ".codesys"), { recursive: true });
376
- const path = resolve6(config.outDir, ".codesys/command.lock");
572
+ await mkdir5(resolve7(config.outDir, ".codesys"), { recursive: true });
573
+ const path = resolve7(config.outDir, ".codesys/command.lock");
377
574
  const deadline = Date.now() + config.timeouts.build + config.timeouts.startup;
378
575
  while (true) {
379
576
  const lock = await open(path, "wx").catch((error) => {
@@ -391,7 +588,7 @@ var withWorkerLock = async (config, run) => {
391
588
  await unlink(path);
392
589
  }
393
590
  }
394
- const owner = Number(await readFile4(path, "utf8").catch((error) => {
591
+ const owner = Number(await readFile5(path, "utf8").catch((error) => {
395
592
  if (hasCode(error, "ENOENT")) {
396
593
  return "";
397
594
  }
@@ -408,72 +605,270 @@ var withWorkerLock = async (config, run) => {
408
605
  };
409
606
 
410
607
  // packages/build/src/sources.ts
608
+ import { readdir, readFile as readFile6 } from "node:fs/promises";
609
+ import { basename as basename4, resolve as resolve8 } from "node:path";
411
610
  import { identifierPattern as identifierPattern3 } from "@tsplc/iec/st";
412
611
 
413
- // packages/build/src/st/parse.ts
414
- import { basename as basename2 } from "node:path";
415
- import {
416
- globalSections,
417
- identifierPattern as identifierPattern2,
418
- qualifiers,
419
- variableSections as variableSections2
420
- } from "@tsplc/iec/st";
612
+ // packages/build/src/io.ts
613
+ import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
614
+ import { qualifiers, variableSections } from "@tsplc/iec/st";
421
615
 
422
- // packages/build/src/st/declarations.ts
423
- import {
424
- conditionalDirective,
425
- modifiers,
426
- variableSections
427
- } from "@tsplc/iec/st";
428
- var objectKinds = {
429
- PROGRAM: "program",
430
- FUNCTION_BLOCK: "function_block",
431
- FUNCTIONBLOCK: "function_block",
432
- FUNCTION: "function",
433
- METHOD: "method",
434
- INTERFACE: "interface",
435
- PROPERTY: "property"
436
- };
437
- var closingObjects = new Set(Object.keys(objectKinds).map((kind) => `END_${kind}`));
438
- var declarationKeywords = new Set([
439
- ...Object.keys(objectKinds),
440
- ...closingObjects,
441
- ...variableSections,
442
- "END_VAR",
443
- "TYPE",
444
- "END_TYPE",
445
- "STRUCT",
446
- "END_STRUCT",
447
- "UNION",
448
- "END_UNION",
449
- "ACTION",
450
- "END_ACTION",
451
- "CONFIGURATION",
452
- "END_CONFIGURATION"
453
- ]);
454
- var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token.value);
455
- var readDeclarationPragmas = (reader) => {
456
- while (isDeclarationPragma(reader.peek())) {
457
- reader.take();
458
- }
459
- };
460
- var readDeclarationSemicolon = (reader) => {
461
- const token = reader.peek();
462
- if (token?.value === ";" && !/[\r\n]/.test(reader.source.slice(reader.end, token.start))) {
463
- reader.take();
464
- }
465
- };
466
- var readIdentifier = (reader) => {
467
- const token = reader.take();
468
- if (token.kind !== "word" || declarationKeywords.has(token.value)) {
469
- reader.fail("Expected an IEC identifier", token);
616
+ // packages/build/src/st/lexer.ts
617
+ import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
618
+
619
+ class StSyntaxError extends Error {
620
+ constructor(source, offset, filename, message) {
621
+ const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
622
+ super(`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`);
623
+ this.name = "StSyntaxError";
470
624
  }
471
- return reader.source.slice(token.start, token.end);
472
- };
473
- var isOverrideModifier = (reader) => {
474
- const name = reader.peek(1);
475
- return name?.kind === "word" && !declarationKeywords.has(name.value) && !["(", "[", ":=", ".", "^"].includes(reader.peek(2)?.value ?? "") && !/[\r\n]/.test(reader.source.slice(reader.peek()?.end, name.start));
476
- };
625
+ }
626
+ var tokenize = (source, filename = "<source>") => {
627
+ const tokens = [];
628
+ let offset = 0;
629
+ const fail = (start, message) => {
630
+ throw new StSyntaxError(source, start, filename, message);
631
+ };
632
+ const quoted = () => {
633
+ offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
634
+ };
635
+ while (offset < source.length) {
636
+ const start = offset;
637
+ const character = source[offset] ?? "";
638
+ if (/\s|\uFEFF/.test(character)) {
639
+ offset++;
640
+ continue;
641
+ }
642
+ if (source.startsWith("//", offset)) {
643
+ offset = lineCommentEnd(source, start);
644
+ continue;
645
+ }
646
+ if (source.startsWith("(*", offset)) {
647
+ offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
648
+ continue;
649
+ }
650
+ if (character === "'" || character === '"') {
651
+ quoted();
652
+ tokens.push({
653
+ kind: "string",
654
+ value: source.slice(start, offset),
655
+ start,
656
+ end: offset
657
+ });
658
+ continue;
659
+ }
660
+ if (character === "{") {
661
+ offset++;
662
+ while (offset < source.length && source[offset] !== "}") {
663
+ if (source[offset] === "'" || source[offset] === '"') {
664
+ quoted();
665
+ } else {
666
+ offset++;
667
+ }
668
+ }
669
+ if (offset === source.length) {
670
+ fail(start, "Unterminated pragma");
671
+ }
672
+ offset++;
673
+ tokens.push({
674
+ kind: "pragma",
675
+ value: source.slice(start, offset),
676
+ start,
677
+ end: offset
678
+ });
679
+ continue;
680
+ }
681
+ if (/[A-Za-z_]/.test(character)) {
682
+ offset++;
683
+ while (/[A-Za-z_0-9]/.test(source[offset] ?? "")) {
684
+ offset++;
685
+ }
686
+ tokens.push({
687
+ kind: "word",
688
+ value: source.slice(start, offset).toUpperCase(),
689
+ start,
690
+ end: offset
691
+ });
692
+ continue;
693
+ }
694
+ offset++;
695
+ const pair = source.slice(start, offset + 1);
696
+ if ([":=", "=>", "..", "<=", ">=", "<>", "**"].includes(pair)) {
697
+ offset++;
698
+ }
699
+ tokens.push({
700
+ kind: "symbol",
701
+ value: source.slice(start, offset),
702
+ start,
703
+ end: offset
704
+ });
705
+ }
706
+ return tokens;
707
+ };
708
+
709
+ // packages/build/src/io.ts
710
+ var span = (type) => ioArray(type) ?? { element: type, length: 1 };
711
+ var addressSize = (type) => {
712
+ const bits = ioScalarBits(type);
713
+ return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
714
+ };
715
+ function bindStructuredTextIo(objects, bindings) {
716
+ const declarations = [];
717
+ const visit = (object) => {
718
+ const tokens = tokenize(object.declaration, object.source);
719
+ let section = false;
720
+ let start = 0;
721
+ for (const [index, token] of tokens.entries()) {
722
+ if (variableSections.has(token.value)) {
723
+ section = true;
724
+ start = index + 1;
725
+ continue;
726
+ }
727
+ if (token.value === "END_VAR") {
728
+ section = false;
729
+ continue;
730
+ }
731
+ if (!section || token.value !== ";") {
732
+ continue;
733
+ }
734
+ const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
735
+ start = index + 1;
736
+ const colon = part.find((t) => t.value === ":");
737
+ if (!colon) {
738
+ continue;
739
+ }
740
+ const colonIndex = part.indexOf(colon);
741
+ if (colonIndex < 1) {
742
+ continue;
743
+ }
744
+ const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers.has(t.value) && t.value !== "AT");
745
+ const at = part.find((t) => t.value === "AT");
746
+ const variables = at ? names.filter((t) => t.start < at.start) : names;
747
+ const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
748
+ const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
749
+ const [first] = typeTokens;
750
+ const last = typeTokens.at(-1);
751
+ const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
752
+ for (const name of variables) {
753
+ declarations.push({
754
+ object,
755
+ name: name.value,
756
+ names: variables,
757
+ colon,
758
+ type
759
+ });
760
+ }
761
+ }
762
+ object.children.forEach(visit);
763
+ };
764
+ objects.forEach(visit);
765
+ const edits = new Map;
766
+ for (const [symbol, binding] of Object.entries(bindings)) {
767
+ const parts = symbol.toUpperCase().split(".");
768
+ if (parts.length > 2) {
769
+ throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
770
+ }
771
+ const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
772
+ const [declaration, ...others] = matches;
773
+ if (!declaration || others.length) {
774
+ throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
775
+ }
776
+ const [variable, ...siblings] = declaration.names;
777
+ if (!variable || siblings.length) {
778
+ throw new Error(`${symbol}: declare mapped IO variables separately.`);
779
+ }
780
+ const declared = span(declaration.type);
781
+ const size = addressSize(declared.element);
782
+ if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
783
+ throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
784
+ }
785
+ const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
786
+ if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
787
+ throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
788
+ }
789
+ const list = edits.get(declaration.object) ?? [];
790
+ const start = variable.end;
791
+ if (list.some((e) => e.start === start)) {
792
+ throw new Error(`${symbol}: the variable has more than one IO binding.`);
793
+ }
794
+ list.push({
795
+ start,
796
+ end: declaration.colon.start,
797
+ text: ` AT ${binding.address} `
798
+ });
799
+ edits.set(declaration.object, list);
800
+ }
801
+ for (const [object, list] of edits) {
802
+ for (const edit of list.sort((a, b) => b.start - a.start)) {
803
+ object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
804
+ }
805
+ }
806
+ }
807
+
808
+ // packages/build/src/st/parse.ts
809
+ import { basename as basename3 } from "node:path";
810
+ import {
811
+ globalSections,
812
+ identifierPattern as identifierPattern2,
813
+ qualifiers as qualifiers2,
814
+ variableSections as variableSections3
815
+ } from "@tsplc/iec/st";
816
+
817
+ // packages/build/src/st/declarations.ts
818
+ import {
819
+ conditionalDirective,
820
+ modifiers,
821
+ variableSections as variableSections2
822
+ } from "@tsplc/iec/st";
823
+ var objectKinds = {
824
+ PROGRAM: "program",
825
+ FUNCTION_BLOCK: "function_block",
826
+ FUNCTIONBLOCK: "function_block",
827
+ FUNCTION: "function",
828
+ METHOD: "method",
829
+ INTERFACE: "interface",
830
+ PROPERTY: "property"
831
+ };
832
+ var closingObjects = new Set(Object.keys(objectKinds).map((kind) => `END_${kind}`));
833
+ var declarationKeywords = new Set([
834
+ ...Object.keys(objectKinds),
835
+ ...closingObjects,
836
+ ...variableSections2,
837
+ "END_VAR",
838
+ "TYPE",
839
+ "END_TYPE",
840
+ "STRUCT",
841
+ "END_STRUCT",
842
+ "UNION",
843
+ "END_UNION",
844
+ "ACTION",
845
+ "END_ACTION",
846
+ "CONFIGURATION",
847
+ "END_CONFIGURATION"
848
+ ]);
849
+ var isDeclarationPragma = (token) => token?.kind === "pragma" && !conditionalDirective(token.value);
850
+ var readDeclarationPragmas = (reader) => {
851
+ while (isDeclarationPragma(reader.peek())) {
852
+ reader.take();
853
+ }
854
+ };
855
+ var readDeclarationSemicolon = (reader) => {
856
+ const token = reader.peek();
857
+ if (token?.value === ";" && !/[\r\n]/.test(reader.source.slice(reader.end, token.start))) {
858
+ reader.take();
859
+ }
860
+ };
861
+ var readIdentifier = (reader) => {
862
+ const token = reader.take();
863
+ if (token.kind !== "word" || declarationKeywords.has(token.value)) {
864
+ reader.fail("Expected an IEC identifier", token);
865
+ }
866
+ return reader.source.slice(token.start, token.end);
867
+ };
868
+ var isOverrideModifier = (reader) => {
869
+ const name = reader.peek(1);
870
+ return name?.kind === "word" && !declarationKeywords.has(name.value) && !["(", "[", ":=", ".", "^"].includes(reader.peek(2)?.value ?? "") && !/[\r\n]/.test(reader.source.slice(reader.peek()?.end, name.start));
871
+ };
477
872
  var readModifiers = (reader) => {
478
873
  while (modifiers.has(reader.peek()?.value ?? "")) {
479
874
  if (reader.peek()?.value === "OVERRIDE" && !isOverrideModifier(reader)) {
@@ -542,7 +937,7 @@ var readVariableSection = (reader) => {
542
937
  const conditionals = [];
543
938
  while (reader.peek()?.value !== "END_VAR") {
544
939
  const token = reader.take();
545
- if (variableSections.has(token.value) || closingObjects.has(token.value)) {
940
+ if (variableSections2.has(token.value) || closingObjects.has(token.value)) {
546
941
  reader.fail("Missing END_VAR", token);
547
942
  }
548
943
  const directive = token.kind === "pragma" && conditionalDirective(token.value);
@@ -579,7 +974,7 @@ var readDeclarationSections = (reader) => {
579
974
  ahead++;
580
975
  }
581
976
  const next = reader.peek(ahead)?.value ?? "";
582
- if (variableSections.has(next)) {
977
+ if (variableSections2.has(next)) {
583
978
  readDeclarationPragmas(reader);
584
979
  readVariableSection(reader);
585
980
  continue;
@@ -596,99 +991,6 @@ var readDeclarationSections = (reader) => {
596
991
  }
597
992
  };
598
993
 
599
- // packages/build/src/st/lexer.ts
600
- import { blockCommentEnd, lineCommentEnd, stringEnd } from "@tsplc/iec/st";
601
-
602
- class StSyntaxError extends Error {
603
- constructor(source, offset, filename, message) {
604
- const lines = source.slice(0, offset).split(/\r\n|\r|\n/);
605
- super(`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`);
606
- this.name = "StSyntaxError";
607
- }
608
- }
609
- var tokenize = (source, filename = "<source>") => {
610
- const tokens = [];
611
- let offset = 0;
612
- const fail = (start, message) => {
613
- throw new StSyntaxError(source, start, filename, message);
614
- };
615
- const quoted = () => {
616
- offset = stringEnd(source, offset) ?? fail(offset, "Unterminated string");
617
- };
618
- while (offset < source.length) {
619
- const start = offset;
620
- const character = source[offset] ?? "";
621
- if (/\s|\uFEFF/.test(character)) {
622
- offset++;
623
- continue;
624
- }
625
- if (source.startsWith("//", offset)) {
626
- offset = lineCommentEnd(source, start);
627
- continue;
628
- }
629
- if (source.startsWith("(*", offset)) {
630
- offset = blockCommentEnd(source, start) ?? fail(start, "Unterminated block comment");
631
- continue;
632
- }
633
- if (character === "'" || character === '"') {
634
- quoted();
635
- tokens.push({
636
- kind: "string",
637
- value: source.slice(start, offset),
638
- start,
639
- end: offset
640
- });
641
- continue;
642
- }
643
- if (character === "{") {
644
- offset++;
645
- while (offset < source.length && source[offset] !== "}") {
646
- if (source[offset] === "'" || source[offset] === '"') {
647
- quoted();
648
- } else {
649
- offset++;
650
- }
651
- }
652
- if (offset === source.length) {
653
- fail(start, "Unterminated pragma");
654
- }
655
- offset++;
656
- tokens.push({
657
- kind: "pragma",
658
- value: source.slice(start, offset),
659
- start,
660
- end: offset
661
- });
662
- continue;
663
- }
664
- if (/[A-Za-z_]/.test(character)) {
665
- offset++;
666
- while (/[A-Za-z_0-9]/.test(source[offset] ?? "")) {
667
- offset++;
668
- }
669
- tokens.push({
670
- kind: "word",
671
- value: source.slice(start, offset).toUpperCase(),
672
- start,
673
- end: offset
674
- });
675
- continue;
676
- }
677
- offset++;
678
- const pair = source.slice(start, offset + 1);
679
- if ([":=", "=>", "..", "<=", ">=", "<>", "**"].includes(pair)) {
680
- offset++;
681
- }
682
- tokens.push({
683
- kind: "symbol",
684
- value: source.slice(start, offset),
685
- start,
686
- end: offset
687
- });
688
- }
689
- return tokens;
690
- };
691
-
692
994
  // packages/build/src/st/reader.ts
693
995
  var createTokenReader = (source, filename) => {
694
996
  const tokens = tokenize(source, filename);
@@ -777,13 +1079,13 @@ var parseGlobals = (reader, options) => {
777
1079
  const start = reader.index;
778
1080
  readVariableSection(reader);
779
1081
  for (const token of reader.tokens.slice(start + 1, reader.index)) {
780
- if (token.kind !== "word" || !qualifiers.has(token.value)) {
1082
+ if (token.kind !== "word" || !qualifiers2.has(token.value)) {
781
1083
  break;
782
1084
  }
783
1085
  persistent ||= token.value === "PERSISTENT";
784
1086
  }
785
1087
  }
786
- const name = options.name ?? basename2(reader.filename, ".st");
1088
+ const name = options.name ?? basename3(reader.filename, ".st");
787
1089
  if (!identifierPattern2.test(name)) {
788
1090
  reader.fail("Global list requires an IEC filename or an explicit name", header);
789
1091
  }
@@ -799,7 +1101,7 @@ var validateImplementation = (reader, tokens) => {
799
1101
  if (token.kind !== "word") {
800
1102
  continue;
801
1103
  }
802
- if (variableSections2.has(token.value) || token.value === "END_VAR") {
1104
+ if (variableSections3.has(token.value) || token.value === "END_VAR") {
803
1105
  reader.fail("Variable declaration outside the declaration section; conditional declaration envelopes are not supported", token);
804
1106
  }
805
1107
  if (declarationKeywords.has(token.value)) {
@@ -867,245 +1169,279 @@ var parseSource = (source, options = {}) => {
867
1169
  return parsePou(reader, options);
868
1170
  };
869
1171
 
870
- // packages/build/src/io.ts
871
- import { ioArray, ioScalarBits, sizePrefix } from "@tsplc/iec";
872
- import { qualifiers as qualifiers2, variableSections as variableSections3 } from "@tsplc/iec/st";
873
- var span = (type) => ioArray(type) ?? { element: type, length: 1 };
874
- var addressSize = (type) => {
875
- const bits = ioScalarBits(type);
876
- return bits === undefined || bits === 64 ? undefined : sizePrefix(bits);
1172
+ // packages/build/src/sources.ts
1173
+ var prefixes = {
1174
+ FB: "function_block",
1175
+ PRG: "program",
1176
+ FUN: "function",
1177
+ F: "function",
1178
+ I: "interface",
1179
+ ST: "dut",
1180
+ E: "dut",
1181
+ T: "dut",
1182
+ U: "dut",
1183
+ GVL: "gvl"
877
1184
  };
878
- function bindStructuredTextIo(objects, bindings) {
879
- const declarations = [];
880
- const visit = (object) => {
881
- const tokens = tokenize(object.declaration, object.source);
882
- let section = false;
883
- let start = 0;
884
- for (const [index, token] of tokens.entries()) {
885
- if (variableSections3.has(token.value)) {
886
- section = true;
887
- start = index + 1;
888
- continue;
889
- }
890
- if (token.value === "END_VAR") {
891
- section = false;
892
- continue;
893
- }
894
- if (!section || token.value !== ";") {
895
- continue;
896
- }
897
- const part = tokens.slice(start, index).filter((t) => t.kind !== "pragma");
898
- start = index + 1;
899
- const colon = part.find((t) => t.value === ":");
900
- if (!colon) {
901
- continue;
902
- }
903
- const colonIndex = part.indexOf(colon);
904
- if (colonIndex < 1) {
905
- continue;
906
- }
907
- const names = part.slice(0, colonIndex).filter((t) => t.kind === "word" && !qualifiers2.has(t.value) && t.value !== "AT");
908
- const at = part.find((t) => t.value === "AT");
909
- const variables = at ? names.filter((t) => t.start < at.start) : names;
910
- const initializer = part.findIndex((t, index) => index > colonIndex && t.value === ":=");
911
- const typeTokens = part.slice(colonIndex + 1, initializer < 0 ? undefined : initializer);
912
- const [first] = typeTokens;
913
- const last = typeTokens.at(-1);
914
- const type = first && last ? object.declaration.slice(first.start, last.end).replace(/\s+/g, " ").toUpperCase() : "";
915
- for (const name of variables) {
916
- declarations.push({
917
- object,
918
- name: name.value,
919
- names: variables,
920
- colon,
921
- type
922
- });
923
- }
924
- }
925
- object.children.forEach(visit);
926
- };
927
- objects.forEach(visit);
928
- const edits = new Map;
929
- for (const [symbol, binding] of Object.entries(bindings)) {
930
- const parts = symbol.toUpperCase().split(".");
931
- if (parts.length > 2) {
932
- throw new Error(`${symbol}: direct IO maps a scalar declaration, not a nested field.`);
933
- }
934
- const matches = declarations.filter((d) => d.name === parts.at(-1) && (parts.length === 1 || d.object.name.toUpperCase() === parts[0]));
935
- const [declaration, ...others] = matches;
936
- if (!declaration || others.length) {
937
- throw new Error(`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`);
938
- }
939
- const [variable, ...siblings] = declaration.names;
940
- if (!variable || siblings.length) {
941
- throw new Error(`${symbol}: declare mapped IO variables separately.`);
1185
+ var childFolders = {
1186
+ methods: "method",
1187
+ properties: "property",
1188
+ actions: "action"
1189
+ };
1190
+ var canOwn = (kind) => ["program", "function_block", "interface", "property"].includes(kind);
1191
+ var assertUnique = (objects, scope) => {
1192
+ const seen = new Map;
1193
+ for (const object of objects) {
1194
+ const key = object.name.toLowerCase();
1195
+ const previous = seen.get(key);
1196
+ if (previous) {
1197
+ throw new Error(`Duplicate IEC name ${object.name} in ${scope}: ${previous} and ${object.source}`);
942
1198
  }
943
- const declared = span(declaration.type);
944
- const size = addressSize(declared.element);
945
- if (!size || declared.length > 1 && declared.element === "BOOL" || binding.address[2] !== size) {
946
- throw new Error(`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`);
1199
+ seen.set(key, object.source);
1200
+ assertUnique(object.children, `${scope}.${object.name}`);
1201
+ }
1202
+ };
1203
+ var readUnit = async (name, files, role, interfaceMember = false) => {
1204
+ if (!identifierPattern3.test(name)) {
1205
+ throw new Error(`Invalid IEC object name: ${name}`);
1206
+ }
1207
+ for (const [part, candidates] of Object.entries(files)) {
1208
+ if (candidates.length > 1) {
1209
+ throw new Error(`Ambiguous ${part} for ${name}: ${candidates.join(", ")}`);
947
1210
  }
948
- const expected = binding.type && span(binding.type.replace(/\s+/g, " ").toUpperCase());
949
- if (expected && (expected.element !== declared.element || expected.length !== declared.length)) {
950
- throw new Error(`${symbol}: expected ${binding.type}, found ${declaration.type}.`);
1211
+ }
1212
+ const combined = files.combined[0];
1213
+ const declaration = files.declaration[0];
1214
+ const implementation = files.implementation[0];
1215
+ if (combined && (declaration || implementation)) {
1216
+ throw new Error(`Both combined and split sources exist for ${name}`);
1217
+ }
1218
+ const path = combined ?? declaration ?? implementation;
1219
+ if (!path) {
1220
+ throw new Error(`Missing source for ${name}`);
1221
+ }
1222
+ if (role === "action") {
1223
+ if (!combined) {
1224
+ throw new Error(`Actions use one implementation-only .st file: ${path}`);
951
1225
  }
952
- const list = edits.get(declaration.object) ?? [];
953
- const start = variable.end;
954
- if (list.some((e) => e.start === start)) {
955
- throw new Error(`${symbol}: the variable has more than one IO binding.`);
1226
+ return {
1227
+ kind: "action",
1228
+ name,
1229
+ declaration: "",
1230
+ implementation: await readFile6(combined, "utf8"),
1231
+ source: combined
1232
+ };
1233
+ }
1234
+ if (role === "get" || role === "set") {
1235
+ if (!combined) {
1236
+ throw new Error(`Property accessors use one .st file: ${path}`);
956
1237
  }
957
- list.push({
958
- start,
959
- end: declaration.colon.start,
960
- text: ` AT ${binding.address} `
1238
+ const body = await readFile6(combined, "utf8");
1239
+ const header = `METHOD ${name}
1240
+ `;
1241
+ const parsed = parseSource(`${header}${body}
1242
+ END_METHOD`, {
1243
+ filename: combined
961
1244
  });
962
- edits.set(declaration.object, list);
1245
+ return {
1246
+ ...parsed,
1247
+ kind: role,
1248
+ name,
1249
+ declaration: parsed.declaration.slice(header.length),
1250
+ source: combined
1251
+ };
963
1252
  }
964
- for (const [object, list] of edits) {
965
- for (const edit of list.sort((a, b) => b.start - a.start)) {
966
- object.declaration = object.declaration.slice(0, edit.start) + edit.text + object.declaration.slice(edit.end);
967
- }
1253
+ if (!combined && !declaration) {
1254
+ throw new Error(`Missing declaration for ${path}`);
968
1255
  }
969
- }
970
-
971
- // packages/build/src/build.ts
972
- var buildProject = async (config) => {
973
- if (!config.docker) {
974
- throw new Error("Builds require a Docker builder image.");
1256
+ const sourcePath = combined ?? declaration ?? path;
1257
+ const parsed = parseSource(await readFile6(sourcePath, "utf8"), {
1258
+ filename: sourcePath,
1259
+ name,
1260
+ declarationOnly: !combined || interfaceMember
1261
+ });
1262
+ if (parsed.name.toLowerCase() !== name.toLowerCase()) {
1263
+ throw new Error(`Source name ${name} does not match declaration ${parsed.name}: ${sourcePath}`);
975
1264
  }
976
- return buildInDocker(config, dockerImage2);
977
- };
978
-
979
- // packages/build/src/cli.ts
980
- import { resolveConfig as resolveConfig2 } from "@tsplc/config/build";
981
-
1265
+ if (role && parsed.kind !== role) {
1266
+ throw new Error(`Expected ${role}, found ${parsed.kind}: ${sourcePath}`);
1267
+ }
1268
+ if (!role && ["method", "property"].includes(parsed.kind)) {
1269
+ throw new Error(`Child object has no enclosing POU: ${sourcePath}`);
1270
+ }
1271
+ const prefix = /^([A-Z]+)_/.exec(name.toUpperCase())?.[1];
1272
+ if (!role && prefix && prefixes[prefix] && prefixes[prefix] !== parsed.kind) {
1273
+ throw new Error(`Prefix ${prefix}_ conflicts with ${parsed.kind}: ${sourcePath}`);
1274
+ }
1275
+ const declarationOnly = ["dut", "gvl", "interface", "property"].includes(parsed.kind) || interfaceMember;
1276
+ if (declarationOnly && implementation) {
1277
+ throw new Error(`This object has no implementation: ${implementation}`);
1278
+ }
1279
+ if (!combined && !declarationOnly && !implementation) {
1280
+ throw new Error(`Missing implementation for ${sourcePath}`);
1281
+ }
1282
+ return {
1283
+ ...parsed,
1284
+ ...implementation ? { implementation: await readFile6(implementation, "utf8") } : {},
1285
+ source: sourcePath
1286
+ };
1287
+ };
1288
+ var loadSources = async (config) => {
1289
+ const objects = [];
1290
+ const visit = async (directory, folder, parent, role) => {
1291
+ const entries = (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, "en"));
1292
+ const groups = new Map;
1293
+ for (const entry of entries) {
1294
+ if (entry.isSymbolicLink()) {
1295
+ throw new Error(`Source symlinks are not supported: ${resolve8(directory, entry.name)}`);
1296
+ }
1297
+ if (!entry.isFile() || !/\.st$/i.test(entry.name)) {
1298
+ continue;
1299
+ }
1300
+ const stem = entry.name.slice(0, -3);
1301
+ const suffix = /^(.*)\.(declaration|implementation)$/.exec(stem);
1302
+ const generic = ["source", "declaration", "implementation"].includes(stem);
1303
+ const name = generic ? basename4(directory) : suffix?.[1] ?? stem;
1304
+ const section = suffix?.[2] ?? stem;
1305
+ const part = section === "declaration" || section === "implementation" ? section : "combined";
1306
+ const key = name.toLowerCase();
1307
+ const group = groups.get(key) ?? {
1308
+ name,
1309
+ files: { combined: [], declaration: [], implementation: [] }
1310
+ };
1311
+ group.files[part].push(resolve8(directory, entry.name));
1312
+ groups.set(key, group);
1313
+ }
1314
+ const units = [];
1315
+ const ownKey = basename4(directory).toLowerCase();
1316
+ const ordered = [...groups].sort(([a], [b]) => Number(b === ownKey) - Number(a === ownKey));
1317
+ for (const [key, { name, files }] of ordered) {
1318
+ const ownProperty = units.find((unit) => unit.kind === "property" && unit.name.toLowerCase() === ownKey);
1319
+ const accessor = ownProperty && (key === "get" || key === "set") ? key : undefined;
1320
+ const unit = {
1321
+ ...await readUnit(accessor ? `${accessor[0]?.toUpperCase()}${accessor.slice(1)}` : name, files, accessor ?? role, parent?.kind === "interface"),
1322
+ folder: parent ? [] : folder,
1323
+ children: []
1324
+ };
1325
+ if (accessor && ownProperty) {
1326
+ if (parent?.kind === "interface") {
1327
+ throw new Error(`Interface properties cannot implement accessors: ${unit.source}`);
1328
+ }
1329
+ ownProperty.children.push(unit);
1330
+ } else {
1331
+ units.push(unit);
1332
+ if (parent) {
1333
+ parent.children.push(unit);
1334
+ } else {
1335
+ objects.push(unit);
1336
+ }
1337
+ }
1338
+ }
1339
+ const own = units.find((unit) => unit.name.toLowerCase() === ownKey && canOwn(unit.kind));
1340
+ if (own && !parent) {
1341
+ own.folder = folder.slice(0, -1);
1342
+ }
1343
+ for (const entry of entries.filter((entry) => entry.isDirectory())) {
1344
+ const childRole = childFolders[entry.name];
1345
+ if (own && childRole) {
1346
+ if (own.kind === "property" || own.kind === "interface" && childRole === "action") {
1347
+ throw new Error(`Unsupported ${entry.name} under ${own.name}`);
1348
+ }
1349
+ await visit(resolve8(directory, entry.name), [], own, childRole);
1350
+ } else if (parent) {
1351
+ await visit(resolve8(directory, entry.name), [], parent, role);
1352
+ } else {
1353
+ await visit(resolve8(directory, entry.name), [...folder, entry.name]);
1354
+ }
1355
+ }
1356
+ };
1357
+ await visit(resolve8(config.sourceDir), []);
1358
+ assertUnique(objects, "Application");
1359
+ if (config.io) {
1360
+ bindStructuredTextIo(objects, config.io);
1361
+ }
1362
+ const entry = objects.find((object) => object.source === resolve8(config.entry));
1363
+ if (!entry) {
1364
+ throw new Error(`Entry is not a discovered source: ${config.entry}`);
1365
+ }
1366
+ if (entry.kind !== "program") {
1367
+ throw new Error(`Entry must be a PROGRAM: ${config.entry}`);
1368
+ }
1369
+ if (config.tasks) {
1370
+ const programs = new Set(objects.filter((object) => object.kind === "program").map((object) => object.name));
1371
+ for (const task of config.tasks) {
1372
+ for (const program of task.programs) {
1373
+ if (!programs.has(program)) {
1374
+ throw new Error(`Task ${task.name} references an undiscovered PROGRAM ${program}`);
1375
+ }
1376
+ }
1377
+ }
1378
+ }
1379
+ return { entry: entry.name, objects };
1380
+ };
1381
+
1382
+ // packages/build/src/build.ts
1383
+ var buildProject = async (config, { progress = "stdout" } = {}) => {
1384
+ if (!config.docker) {
1385
+ throw new Error("Builds require a Docker builder image.");
1386
+ }
1387
+ return buildInDocker(config, builderImage, progress);
1388
+ };
1389
+
982
1390
  // packages/build/src/controller-online.ts
983
- import { existsSync } from "node:fs";
984
1391
  import { createHash as createHash3, randomUUID as randomUUID2 } from "node:crypto";
985
- import { mkdir as mkdir5, mkdtemp as mkdtemp3, readFile as readFile5, rm as rm5 } from "node:fs/promises";
986
- import { tmpdir as tmpdir3 } from "node:os";
987
- import { posix as posix2, resolve as resolve7 } from "node:path";
988
- import { z as z7 } from "zod";
989
- import { dockerImage as dockerImage3 } from "@tsplc/config/build";
1392
+ import { existsSync } from "node:fs";
1393
+ import { mkdir as mkdir6, mkdtemp as mkdtemp4, readFile as readFile7, rm as rm6 } from "node:fs/promises";
1394
+ import { tmpdir as tmpdir4 } from "node:os";
1395
+ import { posix as posix2, resolve as resolve10 } from "node:path";
1396
+ import { z as z9 } from "zod";
990
1397
 
991
- // packages/build/src/controller-protocol.ts
992
- import { createHash as createHash2 } from "node:crypto";
993
- import { z as z6 } from "zod";
1398
+ // packages/build/src/controller-session.ts
1399
+ import { resolve as resolve9 } from "node:path";
994
1400
  import {
995
- controllerSchema,
996
- sha256Digest,
997
- tcpPort
1401
+ controllerBudgets,
1402
+ sha256Digest as sha256Digest2
998
1403
  } from "@tsplc/config/build";
999
- var imageIdSchema = z6.string().regex(/^sha256:[a-f0-9]{64}$/);
1000
- var endpointSchema = z6.strictObject({
1001
- host: z6.string().nonempty(),
1002
- port: tcpPort
1003
- });
1004
- var controllerResultSchema = z6.strictObject({
1005
- schemaVersion: z6.literal(1),
1006
- operationId: z6.uuid(),
1007
- operation: z6.enum(["download", "online-change", "inspect"]),
1008
- imageId: imageIdSchema,
1009
- templateHash: sha256Digest,
1010
- target: z6.strictObject({
1011
- network: z6.string().nonempty(),
1012
- gateway: endpointSchema,
1013
- device: endpointSchema,
1014
- controller: controllerSchema.optional(),
1015
- deviceTree: sha256Digest.optional()
1016
- }),
1017
- generation: z6.string().nonempty(),
1018
- application: z6.string().nonempty(),
1019
- applicationGuid: z6.string().nonempty(),
1020
- controllerIds: z6.strictObject({
1021
- codeId: z6.string().nonempty(),
1022
- dataId: z6.string().nonempty()
1023
- }),
1024
- state: z6.string().nonempty(),
1025
- values: z6.record(z6.string(), z6.string())
1404
+ import { z as z8 } from "zod";
1405
+ 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);
1406
+ var pointerSchema = z8.strictObject({
1407
+ schemaVersion: z8.literal(1),
1408
+ generation: z8.uuid()
1026
1409
  });
1027
- var controllerCredentialsSchema = z6.strictObject({
1028
- username: z6.string().nonempty(),
1029
- password: z6.string().nonempty()
1410
+ var baselineSchema = controllerResultSchema.extend({
1411
+ objects: z8.array(z8.record(z8.string(), z8.unknown())),
1412
+ files: z8.record(z8.string(), sha256Digest2)
1030
1413
  });
1031
- var warmOperationSchema = z6.strictObject({
1032
- operation: z6.enum(["download", "online-change"]),
1033
- operationId: z6.uuid(),
1034
- request: z6.string().nonempty(),
1035
- initializeUser: z6.boolean(),
1036
- credentials: controllerCredentialsSchema.optional()
1414
+ var controllerDirectory = (outDir) => resolve9(outDir, ".codesys/controller");
1415
+ var restoreResultSchema = z8.object({
1416
+ restored: z8.boolean(),
1417
+ controllerIds: z8.strictObject({ codeId: guid, dataId: guid }),
1418
+ state: z8.string()
1037
1419
  });
1038
- var tracebackFailure = (traceback) => {
1039
- const text = traceback.trim();
1040
- const lastFrame = text.lastIndexOf(`
1041
- File `);
1042
- if (lastFrame === -1) {
1043
- return text;
1044
- }
1045
- const [, ...rest] = text.slice(lastFrame + 1).split(`
1046
- `);
1047
- return ((rest[0]?.startsWith(" ")) ? rest.slice(1) : rest).join(`
1048
- `);
1049
- };
1050
- var controllerTarget = (config, online) => ({
1051
- network: online.network,
1052
- gateway: online.gateway,
1053
- device: online.device,
1054
- controller: config.controller,
1055
- ...config.deviceTree && {
1056
- deviceTree: createHash2("sha256").update(JSON.stringify(config.deviceTree)).digest("hex")
1057
- }
1058
- });
1059
- var sameBaseline = (state, expected) => state.imageId === expected.imageId && state.templateHash === expected.templateHash && JSON.stringify(state.target) === JSON.stringify(expected.target);
1060
- var loginCommandSchema = z6.discriminatedUnion("command", [
1061
- z6.strictObject({ command: z6.literal("state") }),
1062
- z6.strictObject({
1063
- command: z6.literal("read"),
1064
- expressions: z6.array(z6.string().nonempty()).nonempty()
1065
- }),
1066
- z6.strictObject({
1067
- command: z6.enum(["write", "force"]),
1068
- values: z6.record(z6.string().nonempty(), z6.string().nonempty())
1069
- }),
1070
- z6.strictObject({
1071
- command: z6.literal("unforce"),
1072
- expressions: z6.array(z6.string().nonempty()),
1073
- restore: z6.boolean()
1074
- }),
1075
- z6.strictObject({ command: z6.enum(["start", "stop"]) }),
1076
- z6.strictObject({
1077
- command: z6.literal("reset"),
1078
- kind: z6.enum(["Warm", "Cold"])
1079
- })
1080
- ]);
1081
- var loginResultSchema = z6.union([
1082
- z6.strictObject({ values: z6.record(z6.string(), z6.string()) }),
1083
- z6.strictObject({ state: z6.string(), forced: z6.array(z6.string()) })
1084
- ]);
1085
1420
 
1086
1421
  // packages/build/src/controller-online.ts
1087
- var credentialEnvironment = (config) => {
1422
+ var credentialEnvironment = (config, { environment = process.env }) => {
1088
1423
  const names = config.online?.credentials ? [
1089
1424
  config.online.credentials.usernameEnv,
1090
1425
  config.online.credentials.passwordEnv
1091
1426
  ] : [];
1092
- for (const name of names) {
1093
- if (process.env[name] === undefined) {
1427
+ return Object.fromEntries(names.map((name) => {
1428
+ const value = environment[name];
1429
+ if (value === undefined) {
1094
1430
  throw new Error(`Controller credential environment variable ${name} is not set`);
1095
1431
  }
1096
- }
1097
- return names;
1432
+ return [name, value];
1433
+ }));
1098
1434
  };
1099
1435
  var controllerConnection = async (config) => {
1100
1436
  if (!config.docker || !config.online) {
1101
1437
  throw new Error("Docker image and online gateway/device configuration are required for controller operations");
1102
1438
  }
1103
- const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", dockerImage3], config.timeouts.hostCommand).catch((cause) => {
1104
- throw new Error(`Cannot inspect Docker builder image ${dockerImage3}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1439
+ const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", builderImage], config.timeouts.hostCommand).catch((cause) => {
1440
+ throw new Error(`Cannot inspect Docker builder image ${builderImage}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1105
1441
  });
1106
1442
  return {
1107
1443
  imageId: imageIdSchema.parse(stdout.trim()),
1108
- templateHash: createHash3("sha256").update(await readFile5(config.template)).digest("hex"),
1444
+ templateHash: createHash3("sha256").update(await readFile7(config.template)).digest("hex"),
1109
1445
  target: controllerTarget(config, config.online)
1110
1446
  };
1111
1447
  };
@@ -1116,21 +1452,21 @@ var checkReceipt = (result, expected, diagnostics) => {
1116
1452
  return result;
1117
1453
  };
1118
1454
  var controllerOperation = async (config, operation, options) => {
1119
- const environmentNames = credentialEnvironment(config);
1455
+ const credentials = credentialEnvironment(config, options);
1120
1456
  const { imageId, templateHash, target } = await controllerConnection(config);
1121
1457
  const operationId = randomUUID2();
1122
- const requestDirectory = await mkdtemp3(resolve7(tmpdir3(), "codesys-controller-"));
1123
- const diagnostics = resolve7(config.outDir, ".codesys/controller");
1124
- const failure = resolve7(config.outDir, controllerFailureFile);
1458
+ const requestDirectory = await mkdtemp4(resolve10(tmpdir4(), "codesys-controller-"));
1459
+ const diagnostics = controllerDirectory(config.outDir);
1460
+ const failure = resolve10(config.outDir, controllerFailureFile);
1125
1461
  try {
1126
- await mkdir5(config.outDir, { recursive: true });
1127
- await rm5(failure, { force: true });
1462
+ await mkdir6(config.outDir, { recursive: true });
1463
+ await rm6(failure, { force: true });
1128
1464
  await runDocker([
1129
1465
  "run",
1130
1466
  "--rm",
1131
1467
  ...await prepareContainerRun(config, requestDirectory, {
1132
1468
  network: target.network,
1133
- environment: environmentNames,
1469
+ environment: Object.keys(credentials),
1134
1470
  sources: operation !== "inspect"
1135
1471
  }),
1136
1472
  imageId,
@@ -1143,111 +1479,83 @@ var controllerOperation = async (config, operation, options) => {
1143
1479
  imageId,
1144
1480
  ...options.initializeUser ? ["--initialize-user"] : [],
1145
1481
  ...options.read ? ["--read", JSON.stringify(options.read)] : []
1146
- ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`).catch(async (cause) => {
1482
+ ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`, { progress: options.progress ?? "stdout", environment: credentials }).catch(async (cause) => {
1147
1483
  if (!existsSync(failure)) {
1148
1484
  throw cause;
1149
1485
  }
1150
- const reason = tracebackFailure(await readFile5(failure, "utf8"));
1486
+ const reason = tracebackFailure(await readFile7(failure, "utf8"));
1151
1487
  throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
1152
1488
  cause
1153
1489
  });
1154
1490
  });
1155
- const result = await readFile5(resolve7(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1491
+ const result = await readFile7(resolve10(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
1156
1492
  throw new Error(`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`, { cause });
1157
1493
  });
1158
1494
  return checkReceipt(result, { operationId, operation, imageId, templateHash, target }, diagnostics);
1159
1495
  } finally {
1160
- await rm5(requestDirectory, { recursive: true, force: true });
1496
+ await rm6(requestDirectory, { recursive: true, force: true });
1161
1497
  }
1162
1498
  };
1163
1499
  var updateController = (config, operation, options = {}) => controllerOperation(config, operation, options);
1164
- var inspectController = (config, read) => controllerOperation(config, "inspect", { read });
1165
- var loginReplySchema = z7.discriminatedUnion("ok", [
1166
- z7.strictObject({ ok: z7.literal(true), result: z7.unknown() }),
1167
- z7.strictObject({ ok: z7.literal(false), error: z7.string() })
1500
+ var loginReplySchema = z9.discriminatedUnion("ok", [
1501
+ z9.strictObject({ ok: z9.literal(true), result: z9.unknown() }),
1502
+ z9.strictObject({
1503
+ ok: z9.literal(false),
1504
+ error: z9.string(),
1505
+ downloadRequired: z9.literal(true).optional(),
1506
+ rollback: rollbackSchema.optional()
1507
+ })
1168
1508
  ]);
1169
1509
 
1170
1510
  // packages/build/src/docker-build.ts
1171
- import { cp as cp5, mkdir as mkdir6, mkdtemp as mkdtemp4, readFile as readFile6, rm as rm6 } from "node:fs/promises";
1172
- import { tmpdir as tmpdir4 } from "node:os";
1173
- import { resolve as resolve8 } from "node:path";
1174
- import { z as z8 } from "zod";
1175
- import { dockerImage as dockerImage4 } from "@tsplc/config/build";
1176
- var publishedImage = async (image) => {
1177
- const { version } = z8.object({ version: z8.string() }).parse(JSON.parse(await readFile6(resolve8(packageDirectory, "package.json"), "utf8")));
1178
- return `ghcr.io/livingforjesus/${image.split(":")[0]}:${version}`;
1179
- };
1180
- var pullPublished = async (image) => {
1181
- const published = await publishedImage(image);
1182
- console.log(`Pulling ${published}`);
1511
+ import { mkdir as mkdir7, mkdtemp as mkdtemp5, readFile as readFile8, rm as rm7 } from "node:fs/promises";
1512
+ import { resolve as resolve11 } from "node:path";
1513
+ import { z as z10 } from "zod";
1514
+ var packageVersion = async () => z10.object({ version: z10.string() }).parse(JSON.parse(await readFile8(resolve11(packageDirectory, "package.json"), "utf8"))).version;
1515
+ var pullPublished = async (image, progress) => {
1516
+ const published = publishedImage(image, await packageVersion());
1517
+ const output = { progress, environment: {} };
1518
+ progressLog(progress)(`Pulling ${published}`);
1183
1519
  try {
1184
- await runDocker(["pull", "--platform", "linux/amd64", published], (status) => `Docker pull failed (${status})`);
1520
+ await runDocker(["pull", "--platform", "linux/amd64", published], (status) => `Docker pull failed (${status})`, output);
1185
1521
  } catch {
1186
- console.log(`${published} is not available; building ${image} locally instead.`);
1522
+ progressLog(progress)(`${published} is not available; building ${image} locally instead.`);
1187
1523
  return false;
1188
1524
  }
1189
- await runDocker(["tag", published, image], (status) => `Docker tag failed (${status})`);
1525
+ await runDocker(["tag", published, image], (status) => `Docker tag failed (${status})`, output);
1190
1526
  return true;
1191
1527
  };
1192
- var configureDocker = async () => {
1193
- const image = dockerImage4;
1528
+ var configureDocker = async ({
1529
+ progress = "stdout"
1530
+ } = {}) => {
1531
+ const image = builderImage;
1194
1532
  const { stdout } = await captureDocker(["info", "--format", "{{.OSType}}/{{.Architecture}}"], 30000).catch((cause) => {
1195
1533
  throw new Error("Cannot connect to Docker. Install and start Docker Desktop or Docker Engine", {
1196
1534
  cause
1197
1535
  });
1198
1536
  });
1199
- const architecture = stdout.trim();
1200
- const arm = architecture === "linux/aarch64" || architecture === "linux/arm64";
1201
- if (!arm && architecture !== "linux/x86_64" && architecture !== "linux/amd64") {
1537
+ const setupPlatform = setupPlatformFor(stdout.trim());
1538
+ if (!setupPlatform) {
1202
1539
  throw new Error("The builder requires a Linux Docker server on ARM64 or AMD64");
1203
1540
  }
1204
- if (await pullPublished(image)) {
1541
+ if (await pullPublished(image, progress)) {
1205
1542
  return image;
1206
1543
  }
1207
- const context = await mkdtemp4(resolve8(tmpdir4(), "codesys-installer-"));
1208
- let buildContext;
1209
- try {
1210
- buildContext = await prepareDockerContext();
1211
- const cache = resolve8(context, "winetricks");
1212
- await mkdir6(cache);
1213
- if (process.env["CODESYS_WINETRICKS_CACHE"]) {
1214
- await cp5(process.env["CODESYS_WINETRICKS_CACHE"], cache, {
1215
- recursive: true
1216
- });
1217
- }
1218
- console.log(`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`);
1219
- await runDocker([
1220
- "build",
1221
- "--platform",
1222
- "linux/amd64",
1223
- "--build-arg",
1224
- `SETUP_BASE=${arm ? "arm-setup" : "base"}`,
1225
- "--build-arg",
1226
- `SETUP_PLATFORM=${arm ? "linux/arm64" : "linux/amd64"}`,
1227
- "--build-arg",
1228
- "INSTALLER_SOURCE=installer-download",
1229
- "--progress",
1230
- "plain",
1231
- "--build-context",
1232
- `installer=${context}`,
1233
- "-f",
1234
- resolve8(buildContext, "docker/Dockerfile"),
1235
- "-t",
1236
- image,
1237
- buildContext
1238
- ], (status) => `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`);
1239
- return image;
1240
- } finally {
1241
- await Promise.all([
1242
- rm6(context, { recursive: true, force: true }),
1243
- ...buildContext ? [rm6(buildContext, { recursive: true, force: true })] : []
1244
- ]);
1245
- }
1544
+ progressLog(progress)(`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`);
1545
+ await buildBuilderImage({
1546
+ tag: image,
1547
+ setupPlatform,
1548
+ installer: null,
1549
+ winetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,
1550
+ docker: (args) => runDocker(args, (status) => `Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`, { progress, environment: {} })
1551
+ });
1552
+ return image;
1246
1553
  };
1247
- var runtimeImage2 = "tsplc-control-linux-sl:4.22.0.0";
1248
- var configureRuntime = async () => {
1249
- const context = resolve8(packageDirectory, "docker/control-linux-sl");
1250
- console.log(`Preparing the local PLC runtime (${runtimeImage2}).`);
1554
+ var configureRuntime = async ({
1555
+ progress = "stdout"
1556
+ } = {}) => {
1557
+ const context = resolve11(packageDirectory, "docker/control-linux-sl");
1558
+ progressLog(progress)(`Preparing the local PLC runtime (${runtimeImage}).`);
1251
1559
  await runDocker([
1252
1560
  "build",
1253
1561
  "--platform",
@@ -1255,10 +1563,10 @@ var configureRuntime = async () => {
1255
1563
  "--progress",
1256
1564
  "plain",
1257
1565
  "-t",
1258
- runtimeImage2,
1566
+ runtimeImage,
1259
1567
  context
1260
- ], (status) => `Runtime image build failed (${status}). Review the image-build output`);
1261
- return runtimeImage2;
1568
+ ], (status) => `Runtime image build failed (${status}). Review the image-build output`, { progress, environment: {} });
1569
+ return runtimeImage;
1262
1570
  };
1263
1571
 
1264
1572
  // packages/build/src/engineering-settings.ts
@@ -1267,33 +1575,34 @@ import {
1267
1575
  rawBuildConfig,
1268
1576
  simulationConfig
1269
1577
  } from "@tsplc/config";
1578
+ import { resolveConfig } from "@tsplc/config/build";
1270
1579
  import { deviceTree } from "@tsplc/typegen";
1271
1580
  import { loadHardware, resolveIo } from "@tsplc/typegen/hardware";
1272
- import { resolveConfig } from "@tsplc/config/build";
1273
1581
 
1274
1582
  // packages/build/src/libraries.ts
1275
1583
  import { createHash as createHash4, randomUUID as randomUUID3 } from "node:crypto";
1276
- import { mkdir as mkdir7, readFile as readFile7, rename as rename3, writeFile as writeFile5 } from "node:fs/promises";
1277
- import { basename as basename3, relative as relative2, resolve as resolve9 } from "node:path";
1278
- import { sha256Digest as sha256Digest2 } from "@tsplc/config/build";
1279
- import { z as z9 } from "zod";
1584
+ import { mkdir as mkdir8, readFile as readFile9, rename as rename3, writeFile as writeFile5 } from "node:fs/promises";
1585
+ import { basename as basename5, relative as relative2, resolve as resolve12 } from "node:path";
1586
+ import { sha256Digest as sha256Digest3 } from "@tsplc/config/build";
1587
+ import { generatedDirectory } from "@tsplc/config/project-files";
1588
+ import { z as z11 } from "zod";
1280
1589
  var libraryRegistry = "https://store-archive.codesys.com/CODESYSLibs";
1281
1590
  var libraryFile = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1282
- var installedLibrarySchema = z9.object({
1283
- title: z9.string(),
1284
- company: z9.string().optional(),
1285
- version: z9.string().optional(),
1286
- namespace: z9.string().optional(),
1287
- path: z9.string(),
1288
- sha256: sha256Digest2,
1289
- url: z9.string().optional()
1591
+ var installedLibrarySchema = z11.object({
1592
+ title: z11.string(),
1593
+ company: z11.string().optional(),
1594
+ version: z11.string().optional(),
1595
+ namespace: z11.string().optional(),
1596
+ path: z11.string(),
1597
+ sha256: sha256Digest3,
1598
+ url: z11.string().optional()
1290
1599
  });
1291
- var libraryLockSchema = z9.object({
1292
- version: z9.literal(1),
1293
- dependencies: z9.record(z9.string(), installedLibrarySchema)
1600
+ var libraryLockSchema = z11.object({
1601
+ version: z11.literal(1),
1602
+ dependencies: z11.record(z11.string(), installedLibrarySchema)
1294
1603
  });
1295
1604
  var readLock = async (file) => {
1296
- const text = await readFile7(file, "utf8").catch((cause) => {
1605
+ const text = await readFile9(file, "utf8").catch((cause) => {
1297
1606
  if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1298
1607
  return;
1299
1608
  }
@@ -1350,21 +1659,21 @@ async function validateLibrary(title, version, company = "System", fetcher = fet
1350
1659
  };
1351
1660
  }
1352
1661
  async function installLibraries(dependencies, root, options = {}) {
1353
- const file = resolve9(root, "tsplc.lock.json");
1354
- const store = resolve9(root, ".tsplc/libraries");
1662
+ const file = resolve12(root, "tsplc.lock.json");
1663
+ const store = resolve12(root, generatedDirectory, "libraries");
1355
1664
  const previous = await readLock(file);
1356
1665
  const installed = {};
1357
1666
  const fetcher = options.fetcher ?? fetch;
1358
- await mkdir7(store, { recursive: true });
1667
+ await mkdir8(store, { recursive: true });
1359
1668
  for (const [title, dependency] of Object.entries(dependencies)) {
1360
1669
  component(title);
1361
1670
  const settings = typeof dependency === "string" ? { version: dependency } : dependency;
1362
1671
  const locked = previous.dependencies[title];
1363
- const prior = locked ? { ...locked, path: resolve9(root, locked.path) } : undefined;
1364
- 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"));
1672
+ const prior = locked ? { ...locked, path: resolve12(root, locked.path) } : undefined;
1673
+ const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve12(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1365
1674
  if (same) {
1366
1675
  try {
1367
- if (hash(await readFile7(prior.path)) === prior.sha256) {
1676
+ if (hash(await readFile9(prior.path)) === prior.sha256) {
1368
1677
  installed[title] = prior;
1369
1678
  continue;
1370
1679
  }
@@ -1376,14 +1685,14 @@ async function installLibraries(dependencies, root, options = {}) {
1376
1685
  throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1377
1686
  }
1378
1687
  if ("path" in settings) {
1379
- const path = resolve9(root, settings.path);
1688
+ const path = resolve12(root, settings.path);
1380
1689
  if (!libraryFile.test(path)) {
1381
1690
  throw new Error(`${title}: expected a .library or .compiled-library file.`);
1382
1691
  }
1383
1692
  installed[title] = {
1384
1693
  title,
1385
1694
  path,
1386
- sha256: hash(await readFile7(path)),
1695
+ sha256: hash(await readFile9(path)),
1387
1696
  ...settings.namespace ? { namespace: settings.namespace } : {}
1388
1697
  };
1389
1698
  } else {
@@ -1398,7 +1707,7 @@ async function installLibraries(dependencies, root, options = {}) {
1398
1707
  if (same && prior.sha256 !== sha256) {
1399
1708
  throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1400
1709
  }
1401
- const path = resolve9(store, `${sha256}-${basename3(payload.filename)}`);
1710
+ const path = resolve12(store, `${sha256}-${basename5(payload.filename)}`);
1402
1711
  const temp = `${path}.${randomUUID3()}.tmp`;
1403
1712
  await writeFile5(temp, data, { flag: "wx" });
1404
1713
  await rename3(temp, path);
@@ -1425,7 +1734,7 @@ async function installLibraries(dependencies, root, options = {}) {
1425
1734
  path: relative2(root, library.path).replaceAll("\\", "/")
1426
1735
  }
1427
1736
  ]));
1428
- await writeFile5(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1737
+ await writeFile5(temp, `${JSON.stringify({ version: 1, dependencies: portable }, null, 2)}
1429
1738
  `);
1430
1739
  await rename3(temp, file);
1431
1740
  }
@@ -1451,27 +1760,28 @@ var rawEngineeringSettings = async ({ config, configFile, root }, options) => {
1451
1760
 
1452
1761
  // packages/build/src/libraries.ts
1453
1762
  import { createHash as createHash5, randomUUID as randomUUID4 } from "node:crypto";
1454
- import { mkdir as mkdir8, readFile as readFile8, rename as rename4, writeFile as writeFile6 } from "node:fs/promises";
1455
- import { basename as basename4, relative as relative3, resolve as resolve10 } from "node:path";
1456
- import { sha256Digest as sha256Digest3 } from "@tsplc/config/build";
1457
- import { z as z10 } from "zod";
1763
+ import { mkdir as mkdir9, readFile as readFile10, rename as rename4, writeFile as writeFile6 } from "node:fs/promises";
1764
+ import { basename as basename6, relative as relative3, resolve as resolve13 } from "node:path";
1765
+ import { sha256Digest as sha256Digest4 } from "@tsplc/config/build";
1766
+ import { generatedDirectory as generatedDirectory2 } from "@tsplc/config/project-files";
1767
+ import { z as z12 } from "zod";
1458
1768
  var libraryRegistry2 = "https://store-archive.codesys.com/CODESYSLibs";
1459
1769
  var libraryFile2 = /\.(?:compiled-library(?:-v\d+)?|library)$/i;
1460
- var installedLibrarySchema2 = z10.object({
1461
- title: z10.string(),
1462
- company: z10.string().optional(),
1463
- version: z10.string().optional(),
1464
- namespace: z10.string().optional(),
1465
- path: z10.string(),
1466
- sha256: sha256Digest3,
1467
- url: z10.string().optional()
1770
+ var installedLibrarySchema2 = z12.object({
1771
+ title: z12.string(),
1772
+ company: z12.string().optional(),
1773
+ version: z12.string().optional(),
1774
+ namespace: z12.string().optional(),
1775
+ path: z12.string(),
1776
+ sha256: sha256Digest4,
1777
+ url: z12.string().optional()
1468
1778
  });
1469
- var libraryLockSchema2 = z10.object({
1470
- version: z10.literal(1),
1471
- dependencies: z10.record(z10.string(), installedLibrarySchema2)
1779
+ var libraryLockSchema2 = z12.object({
1780
+ version: z12.literal(1),
1781
+ dependencies: z12.record(z12.string(), installedLibrarySchema2)
1472
1782
  });
1473
1783
  var readLock2 = async (file) => {
1474
- const text = await readFile8(file, "utf8").catch((cause) => {
1784
+ const text = await readFile10(file, "utf8").catch((cause) => {
1475
1785
  if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1476
1786
  return;
1477
1787
  }
@@ -1528,21 +1838,21 @@ async function validateLibrary2(title, version, company = "System", fetcher = fe
1528
1838
  };
1529
1839
  }
1530
1840
  async function installLibraries2(dependencies, root, options = {}) {
1531
- const file = resolve10(root, "tsplc.lock.json");
1532
- const store = resolve10(root, ".tsplc/libraries");
1841
+ const file = resolve13(root, "tsplc.lock.json");
1842
+ const store = resolve13(root, generatedDirectory2, "libraries");
1533
1843
  const previous = await readLock2(file);
1534
1844
  const installed = {};
1535
1845
  const fetcher = options.fetcher ?? fetch;
1536
- await mkdir8(store, { recursive: true });
1846
+ await mkdir9(store, { recursive: true });
1537
1847
  for (const [title, dependency] of Object.entries(dependencies)) {
1538
1848
  component2(title);
1539
1849
  const settings = typeof dependency === "string" ? { version: dependency } : dependency;
1540
1850
  const locked = previous.dependencies[title];
1541
- const prior = locked ? { ...locked, path: resolve10(root, locked.path) } : undefined;
1542
- const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve10(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1851
+ const prior = locked ? { ...locked, path: resolve13(root, locked.path) } : undefined;
1852
+ const same = prior !== undefined && prior.namespace === settings.namespace && ("path" in settings ? prior.url === undefined && prior.path === resolve13(root, settings.path) : prior.version === settings.version && prior.company === (settings.company ?? "System"));
1543
1853
  if (same) {
1544
1854
  try {
1545
- if (hash2(await readFile8(prior.path)) === prior.sha256) {
1855
+ if (hash2(await readFile10(prior.path)) === prior.sha256) {
1546
1856
  installed[title] = prior;
1547
1857
  continue;
1548
1858
  }
@@ -1554,14 +1864,14 @@ async function installLibraries2(dependencies, root, options = {}) {
1554
1864
  throw new Error(`Dependency ${title} differs from tsplc.lock.json.`);
1555
1865
  }
1556
1866
  if ("path" in settings) {
1557
- const path = resolve10(root, settings.path);
1867
+ const path = resolve13(root, settings.path);
1558
1868
  if (!libraryFile2.test(path)) {
1559
1869
  throw new Error(`${title}: expected a .library or .compiled-library file.`);
1560
1870
  }
1561
1871
  installed[title] = {
1562
1872
  title,
1563
1873
  path,
1564
- sha256: hash2(await readFile8(path)),
1874
+ sha256: hash2(await readFile10(path)),
1565
1875
  ...settings.namespace ? { namespace: settings.namespace } : {}
1566
1876
  };
1567
1877
  } else {
@@ -1576,7 +1886,7 @@ async function installLibraries2(dependencies, root, options = {}) {
1576
1886
  if (same && prior.sha256 !== sha256) {
1577
1887
  throw new Error(`Registry payload changed for locked library ${title} ${settings.version}.`);
1578
1888
  }
1579
- const path = resolve10(store, `${sha256}-${basename4(payload.filename)}`);
1889
+ const path = resolve13(store, `${sha256}-${basename6(payload.filename)}`);
1580
1890
  const temp = `${path}.${randomUUID4()}.tmp`;
1581
1891
  await writeFile6(temp, data, { flag: "wx" });
1582
1892
  await rename4(temp, path);
@@ -1603,19 +1913,138 @@ async function installLibraries2(dependencies, root, options = {}) {
1603
1913
  path: relative3(root, library.path).replaceAll("\\", "/")
1604
1914
  }
1605
1915
  ]));
1606
- await writeFile6(temp, JSON.stringify({ version: 1, dependencies: portable }, null, 2) + `
1916
+ await writeFile6(temp, `${JSON.stringify({ version: 1, dependencies: portable }, null, 2)}
1607
1917
  `);
1608
1918
  await rename4(temp, file);
1609
1919
  }
1610
1920
  return Object.values(installed);
1611
1921
  }
1612
1922
 
1613
- // packages/build/src/run.ts
1614
- import { mkdtemp as mkdtemp5, readFile as readFile9, rm as rm7, writeFile as writeFile7 } from "node:fs/promises";
1923
+ // packages/build/src/project-operations.ts
1924
+ import {
1925
+ controllerFor as controllerFor2,
1926
+ rawBuildConfig as rawBuildConfig2
1927
+ } from "@tsplc/config";
1928
+ import { resolveConfig as resolveConfig2 } from "@tsplc/config/build";
1929
+ import { loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen/hardware";
1930
+
1931
+ // packages/build/src/controller-online.ts
1932
+ import { createHash as createHash6, randomUUID as randomUUID5 } from "node:crypto";
1933
+ import { existsSync as existsSync2 } from "node:fs";
1934
+ import { mkdir as mkdir10, mkdtemp as mkdtemp6, readFile as readFile11, rm as rm8 } from "node:fs/promises";
1615
1935
  import { tmpdir as tmpdir5 } from "node:os";
1616
- import { basename as basename5, dirname as dirname2, join } from "node:path";
1936
+ import { posix as posix3, resolve as resolve14 } from "node:path";
1937
+ import { z as z13 } from "zod";
1938
+ var credentialEnvironment2 = (config, { environment = process.env }) => {
1939
+ const names = config.online?.credentials ? [
1940
+ config.online.credentials.usernameEnv,
1941
+ config.online.credentials.passwordEnv
1942
+ ] : [];
1943
+ return Object.fromEntries(names.map((name) => {
1944
+ const value = environment[name];
1945
+ if (value === undefined) {
1946
+ throw new Error(`Controller credential environment variable ${name} is not set`);
1947
+ }
1948
+ return [name, value];
1949
+ }));
1950
+ };
1951
+ var controllerConnection2 = async (config) => {
1952
+ if (!config.docker || !config.online) {
1953
+ throw new Error("Docker image and online gateway/device configuration are required for controller operations");
1954
+ }
1955
+ const { stdout } = await captureDocker(["image", "inspect", "--format", "{{.Id}}", builderImage], config.timeouts.hostCommand).catch((cause) => {
1956
+ throw new Error(`Cannot inspect Docker builder image ${builderImage}. Install and start Docker, then run tsplc-build configure if the image is missing`, { cause });
1957
+ });
1958
+ return {
1959
+ imageId: imageIdSchema.parse(stdout.trim()),
1960
+ templateHash: createHash6("sha256").update(await readFile11(config.template)).digest("hex"),
1961
+ target: controllerTarget(config, config.online)
1962
+ };
1963
+ };
1964
+ var checkReceipt2 = (result, expected, diagnostics) => {
1965
+ if (result.operationId !== expected.operationId || result.operation !== expected.operation || !sameBaseline(result, expected)) {
1966
+ throw new Error(`Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`);
1967
+ }
1968
+ return result;
1969
+ };
1970
+ var controllerOperation2 = async (config, operation, options) => {
1971
+ const credentials = credentialEnvironment2(config, options);
1972
+ const { imageId, templateHash, target } = await controllerConnection2(config);
1973
+ const operationId = randomUUID5();
1974
+ const requestDirectory = await mkdtemp6(resolve14(tmpdir5(), "codesys-controller-"));
1975
+ const diagnostics = controllerDirectory(config.outDir);
1976
+ const failure = resolve14(config.outDir, controllerFailureFile);
1977
+ try {
1978
+ await mkdir10(config.outDir, { recursive: true });
1979
+ await rm8(failure, { force: true });
1980
+ await runDocker([
1981
+ "run",
1982
+ "--rm",
1983
+ ...await prepareContainerRun(config, requestDirectory, {
1984
+ network: target.network,
1985
+ environment: Object.keys(credentials),
1986
+ sources: operation !== "inspect"
1987
+ }),
1988
+ imageId,
1989
+ operation,
1990
+ "--request",
1991
+ "/input/config.json",
1992
+ "--operation-id",
1993
+ operationId,
1994
+ "--image-id",
1995
+ imageId,
1996
+ ...options.initializeUser ? ["--initialize-user"] : [],
1997
+ ...options.read ? ["--read", JSON.stringify(options.read)] : []
1998
+ ], (status) => `Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`, { progress: options.progress ?? "stdout", environment: credentials }).catch(async (cause) => {
1999
+ if (!existsSync2(failure)) {
2000
+ throw cause;
2001
+ }
2002
+ const reason = tracebackFailure(await readFile11(failure, "utf8"));
2003
+ throw new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {
2004
+ cause
2005
+ });
2006
+ });
2007
+ const result = await readFile11(resolve14(diagnostics, "result.json"), "utf8").then((content) => controllerResultSchema.parse(JSON.parse(content))).catch((cause) => {
2008
+ throw new Error(`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`, { cause });
2009
+ });
2010
+ return checkReceipt2(result, { operationId, operation, imageId, templateHash, target }, diagnostics);
2011
+ } finally {
2012
+ await rm8(requestDirectory, { recursive: true, force: true });
2013
+ }
2014
+ };
2015
+ var inspectController = (config, read, options = {}) => controllerOperation2(config, "inspect", { ...options, read });
2016
+ var loginReplySchema2 = z13.discriminatedUnion("ok", [
2017
+ z13.strictObject({ ok: z13.literal(true), result: z13.unknown() }),
2018
+ z13.strictObject({
2019
+ ok: z13.literal(false),
2020
+ error: z13.string(),
2021
+ downloadRequired: z13.literal(true).optional(),
2022
+ rollback: rollbackSchema.optional()
2023
+ })
2024
+ ]);
2025
+
2026
+ // packages/build/src/project-operations.ts
2027
+ var checkRawSources = async ({
2028
+ config,
2029
+ configFile,
2030
+ root
2031
+ }) => loadSources(resolveConfig2({
2032
+ ...rawBuildConfig2(config),
2033
+ io: resolveIo2(config, await loadHardware2(config, root))
2034
+ }, configFile));
2035
+ var inspectProjectController = ({ config, configFile }, read, options) => {
2036
+ if (!config.build) {
2037
+ throw new Error("Configure build settings and controller connection.");
2038
+ }
2039
+ return inspectController(resolveConfig2({ ...config.build, controller: controllerFor2(config, "inspect") }, configFile), read, options);
2040
+ };
2041
+
2042
+ // packages/build/src/run.ts
2043
+ import { mkdtemp as mkdtemp7, readFile as readFile12, rm as rm9, writeFile as writeFile7 } from "node:fs/promises";
2044
+ import { tmpdir as tmpdir6 } from "node:os";
2045
+ import { basename as basename7, dirname as dirname2, join } from "node:path";
1617
2046
  import { setTimeout as delay2 } from "node:timers/promises";
1618
- import { z as z11 } from "zod";
2047
+ import { z as z14 } from "zod";
1619
2048
 
1620
2049
  // packages/build/src/runtime-status.ts
1621
2050
  var getApplicationStatus = (log, application, startedAt) => {
@@ -1633,9 +2062,9 @@ var getApplicationStatus = (log, application, startedAt) => {
1633
2062
  };
1634
2063
 
1635
2064
  // packages/build/src/run.ts
1636
- var stateSchema = z11.object({
1637
- Running: z11.boolean(),
1638
- StartedAt: z11.iso.datetime({ offset: true })
2065
+ var stateSchema = z14.object({
2066
+ Running: z14.boolean(),
2067
+ StartedAt: z14.iso.datetime({ offset: true })
1639
2068
  });
1640
2069
  var service = "plc";
1641
2070
  var runtimeProject = (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-");
@@ -1657,22 +2086,22 @@ var runtimeDefinition = (name) => ({
1657
2086
  },
1658
2087
  volumes: { "control-conf": {}, "control-data": {} }
1659
2088
  });
1660
- var runProject = async (config, name) => withWorkerLock(config, async () => {
2089
+ var runProject = async (config, name, { progress = "stdout" } = {}) => withWorkerLock(config, async () => {
1661
2090
  const build = await readBuild(config.outDir).catch((cause) => {
1662
2091
  throw new Error(`No complete build in ${config.outDir}. Run tsplc-build build first.`, {
1663
2092
  cause
1664
2093
  });
1665
2094
  });
1666
- const definitionDirectory = await mkdtemp5(join(tmpdir5(), "tsplc-runtime-"));
2095
+ const definitionDirectory = await mkdtemp7(join(tmpdir6(), "tsplc-runtime-"));
1667
2096
  try {
1668
2097
  const composeFile = join(definitionDirectory, "compose.yaml");
1669
2098
  await writeFile7(composeFile, JSON.stringify(runtimeDefinition(name)));
1670
2099
  const docker = (...args) => captureDocker(args, config.timeouts.runtime);
1671
2100
  const compose = (...args) => docker("compose", "--project-name", runtimeProject(name), "--file", composeFile, ...args);
1672
- const installer = await readFile9(new URL("../runtime/install.sh", import.meta.url), "utf8");
1673
- console.log(`Installing ${build.application} in Docker service ${service}`);
2101
+ const installer = await readFile12(new URL("../runtime/install.sh", import.meta.url), "utf8");
2102
+ progressLog(progress)(`Installing ${build.application} in Docker service ${service}`);
1674
2103
  await compose("stop", service);
1675
- 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"));
2104
+ 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, basename7(build.output, ".app"));
1676
2105
  await compose("up", "--detach", "--no-deps", service);
1677
2106
  const containers = (await compose("ps", "--all", "--quiet", service)).stdout.trim().split(/\s+/).filter(Boolean);
1678
2107
  if (containers.length !== 1 || !containers[0]) {
@@ -1688,7 +2117,7 @@ var runProject = async (config, name) => withWorkerLock(config, async () => {
1688
2117
  const { stdout: log } = await docker("exec", container, "/bin/sh", "-c", "if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi");
1689
2118
  const status = getApplicationStatus(log, build.application, Date.parse(state.StartedAt));
1690
2119
  if (status === "running") {
1691
- console.log(`${build.application} is running in ${service}`);
2120
+ progressLog(progress)(`${build.application} is running in ${service}`);
1692
2121
  return { ...build, container };
1693
2122
  }
1694
2123
  if (status === "failed" || Date.now() >= deadline) {
@@ -1700,225 +2129,12 @@ ${log.split(`
1700
2129
  await delay2(250);
1701
2130
  }
1702
2131
  } finally {
1703
- await rm7(definitionDirectory, { force: true, recursive: true });
2132
+ await rm9(definitionDirectory, { force: true, recursive: true });
1704
2133
  }
1705
2134
  });
1706
2135
 
1707
- // packages/build/src/sources.ts
1708
- import { readdir, readFile as readFile10 } from "node:fs/promises";
1709
- import { basename as basename6, resolve as resolve11 } from "node:path";
1710
- import { identifierPattern as identifierPattern4 } from "@tsplc/iec/st";
1711
- var prefixes = {
1712
- FB: "function_block",
1713
- PRG: "program",
1714
- FUN: "function",
1715
- F: "function",
1716
- I: "interface",
1717
- ST: "dut",
1718
- E: "dut",
1719
- T: "dut",
1720
- U: "dut",
1721
- GVL: "gvl"
1722
- };
1723
- var childFolders = {
1724
- methods: "method",
1725
- properties: "property",
1726
- actions: "action"
1727
- };
1728
- var canOwn = (kind) => ["program", "function_block", "interface", "property"].includes(kind);
1729
- var assertUnique = (objects, scope) => {
1730
- const seen = new Map;
1731
- for (const object of objects) {
1732
- const key = object.name.toLowerCase();
1733
- const previous = seen.get(key);
1734
- if (previous) {
1735
- throw new Error(`Duplicate IEC name ${object.name} in ${scope}: ${previous} and ${object.source}`);
1736
- }
1737
- seen.set(key, object.source);
1738
- assertUnique(object.children, `${scope}.${object.name}`);
1739
- }
1740
- };
1741
- var readUnit = async (name, files, role, interfaceMember = false) => {
1742
- if (!identifierPattern4.test(name)) {
1743
- throw new Error(`Invalid IEC object name: ${name}`);
1744
- }
1745
- for (const [part, candidates] of Object.entries(files)) {
1746
- if (candidates.length > 1) {
1747
- throw new Error(`Ambiguous ${part} for ${name}: ${candidates.join(", ")}`);
1748
- }
1749
- }
1750
- const combined = files.combined[0];
1751
- const declaration = files.declaration[0];
1752
- const implementation = files.implementation[0];
1753
- if (combined && (declaration || implementation)) {
1754
- throw new Error(`Both combined and split sources exist for ${name}`);
1755
- }
1756
- const path = combined ?? declaration ?? implementation;
1757
- if (!path) {
1758
- throw new Error(`Missing source for ${name}`);
1759
- }
1760
- if (role === "action") {
1761
- if (!combined) {
1762
- throw new Error(`Actions use one implementation-only .st file: ${path}`);
1763
- }
1764
- return {
1765
- kind: "action",
1766
- name,
1767
- declaration: "",
1768
- implementation: await readFile10(combined, "utf8"),
1769
- source: combined
1770
- };
1771
- }
1772
- if (role === "get" || role === "set") {
1773
- if (!combined) {
1774
- throw new Error(`Property accessors use one .st file: ${path}`);
1775
- }
1776
- const body = await readFile10(combined, "utf8");
1777
- const header = `METHOD ${name}
1778
- `;
1779
- const parsed = parseSource(`${header}${body}
1780
- END_METHOD`, {
1781
- filename: combined
1782
- });
1783
- return {
1784
- ...parsed,
1785
- kind: role,
1786
- name,
1787
- declaration: parsed.declaration.slice(header.length),
1788
- source: combined
1789
- };
1790
- }
1791
- if (!combined && !declaration) {
1792
- throw new Error(`Missing declaration for ${path}`);
1793
- }
1794
- const sourcePath = combined ?? declaration ?? path;
1795
- const parsed = parseSource(await readFile10(sourcePath, "utf8"), {
1796
- filename: sourcePath,
1797
- name,
1798
- declarationOnly: !combined || interfaceMember
1799
- });
1800
- if (parsed.name.toLowerCase() !== name.toLowerCase()) {
1801
- throw new Error(`Source name ${name} does not match declaration ${parsed.name}: ${sourcePath}`);
1802
- }
1803
- if (role && parsed.kind !== role) {
1804
- throw new Error(`Expected ${role}, found ${parsed.kind}: ${sourcePath}`);
1805
- }
1806
- if (!role && ["method", "property"].includes(parsed.kind)) {
1807
- throw new Error(`Child object has no enclosing POU: ${sourcePath}`);
1808
- }
1809
- const prefix = /^([A-Z]+)_/.exec(name.toUpperCase())?.[1];
1810
- if (!role && prefix && prefixes[prefix] && prefixes[prefix] !== parsed.kind) {
1811
- throw new Error(`Prefix ${prefix}_ conflicts with ${parsed.kind}: ${sourcePath}`);
1812
- }
1813
- const declarationOnly = ["dut", "gvl", "interface", "property"].includes(parsed.kind) || interfaceMember;
1814
- if (declarationOnly && implementation) {
1815
- throw new Error(`This object has no implementation: ${implementation}`);
1816
- }
1817
- if (!combined && !declarationOnly && !implementation) {
1818
- throw new Error(`Missing implementation for ${sourcePath}`);
1819
- }
1820
- return {
1821
- ...parsed,
1822
- ...implementation ? { implementation: await readFile10(implementation, "utf8") } : {},
1823
- source: sourcePath
1824
- };
1825
- };
1826
- var loadSources2 = async (config) => {
1827
- const objects = [];
1828
- const visit = async (directory, folder, parent, role) => {
1829
- const entries = (await readdir(directory, { withFileTypes: true })).sort((a, b) => a.name.localeCompare(b.name, "en"));
1830
- const groups = new Map;
1831
- for (const entry of entries) {
1832
- if (entry.isSymbolicLink()) {
1833
- throw new Error(`Source symlinks are not supported: ${resolve11(directory, entry.name)}`);
1834
- }
1835
- if (!entry.isFile() || !/\.st$/i.test(entry.name)) {
1836
- continue;
1837
- }
1838
- const stem = entry.name.slice(0, -3);
1839
- const suffix = /^(.*)\.(declaration|implementation)$/.exec(stem);
1840
- const generic = ["source", "declaration", "implementation"].includes(stem);
1841
- const name = generic ? basename6(directory) : suffix?.[1] ?? stem;
1842
- const section = suffix?.[2] ?? stem;
1843
- const part = section === "declaration" || section === "implementation" ? section : "combined";
1844
- const key = name.toLowerCase();
1845
- const group = groups.get(key) ?? {
1846
- name,
1847
- files: { combined: [], declaration: [], implementation: [] }
1848
- };
1849
- group.files[part].push(resolve11(directory, entry.name));
1850
- groups.set(key, group);
1851
- }
1852
- const units = [];
1853
- const ownKey = basename6(directory).toLowerCase();
1854
- const ordered = [...groups].sort(([a], [b]) => Number(b === ownKey) - Number(a === ownKey));
1855
- for (const [key, { name, files }] of ordered) {
1856
- const ownProperty = units.find((unit) => unit.kind === "property" && unit.name.toLowerCase() === ownKey);
1857
- const accessor = ownProperty && (key === "get" || key === "set") ? key : undefined;
1858
- const unit = {
1859
- ...await readUnit(accessor ? `${accessor[0]?.toUpperCase()}${accessor.slice(1)}` : name, files, accessor ?? role, parent?.kind === "interface"),
1860
- folder: parent ? [] : folder,
1861
- children: []
1862
- };
1863
- if (accessor && ownProperty) {
1864
- if (parent?.kind === "interface") {
1865
- throw new Error(`Interface properties cannot implement accessors: ${unit.source}`);
1866
- }
1867
- ownProperty.children.push(unit);
1868
- } else {
1869
- units.push(unit);
1870
- if (parent) {
1871
- parent.children.push(unit);
1872
- } else {
1873
- objects.push(unit);
1874
- }
1875
- }
1876
- }
1877
- const own = units.find((unit) => unit.name.toLowerCase() === ownKey && canOwn(unit.kind));
1878
- if (own && !parent) {
1879
- own.folder = folder.slice(0, -1);
1880
- }
1881
- for (const entry of entries.filter((entry) => entry.isDirectory())) {
1882
- const childRole = childFolders[entry.name];
1883
- if (own && childRole) {
1884
- if (own.kind === "property" || own.kind === "interface" && childRole === "action") {
1885
- throw new Error(`Unsupported ${entry.name} under ${own.name}`);
1886
- }
1887
- await visit(resolve11(directory, entry.name), [], own, childRole);
1888
- } else if (parent) {
1889
- await visit(resolve11(directory, entry.name), [], parent, role);
1890
- } else {
1891
- await visit(resolve11(directory, entry.name), [...folder, entry.name]);
1892
- }
1893
- }
1894
- };
1895
- await visit(resolve11(config.sourceDir), []);
1896
- assertUnique(objects, "Application");
1897
- if (config.io) {
1898
- bindStructuredTextIo(objects, config.io);
1899
- }
1900
- const entry = objects.find((object) => object.source === resolve11(config.entry));
1901
- if (!entry) {
1902
- throw new Error(`Entry is not a discovered source: ${config.entry}`);
1903
- }
1904
- if (entry.kind !== "program") {
1905
- throw new Error(`Entry must be a PROGRAM: ${config.entry}`);
1906
- }
1907
- if (config.tasks) {
1908
- const programs = new Set(objects.filter((object) => object.kind === "program").map((object) => object.name));
1909
- for (const task of config.tasks) {
1910
- for (const program of task.programs) {
1911
- if (!programs.has(program)) {
1912
- throw new Error(`Task ${task.name} references an undiscovered PROGRAM ${program}`);
1913
- }
1914
- }
1915
- }
1916
- }
1917
- return { entry: entry.name, objects };
1918
- };
1919
-
1920
2136
  // packages/build/src/cli.ts
1921
- var commandSchema = z12.enum([
2137
+ var commandSchema = z15.enum([
1922
2138
  "configure",
1923
2139
  "install",
1924
2140
  "check",
@@ -1961,7 +2177,7 @@ async function main() {
1961
2177
  return;
1962
2178
  }
1963
2179
  const loaded = await loadTsplcConfig(values.config);
1964
- const { config, configFile, root } = loaded;
2180
+ const { config, root } = loaded;
1965
2181
  if (command === "install") {
1966
2182
  const libraries = await installLibraries2(config.dependencies, root, {
1967
2183
  frozen: values["frozen-lockfile"]
@@ -1973,16 +2189,16 @@ async function main() {
1973
2189
  throw new Error("Configure build options in tsplc.config.ts.");
1974
2190
  }
1975
2191
  if (command === "inspect") {
1976
- console.log(JSON.stringify(await inspectController(resolveConfig2({ ...config.build, controller: controllerFor2(config, command) }, configFile), values.read), null, 2));
2192
+ console.log(JSON.stringify(await inspectProjectController(loaded, values.read, {
2193
+ progress: "stderr"
2194
+ }), null, 2));
1977
2195
  return;
1978
2196
  }
1979
2197
  if (config.compiler) {
1980
2198
  throw new Error("Use tsplc for TypeScript projects. tsplc-build accepts raw Structured Text.");
1981
2199
  }
1982
2200
  if (command === "check") {
1983
- const build = rawBuildConfig2(config);
1984
- const hardware = await loadHardware2(config, root);
1985
- const sources = await loadSources2(resolveConfig2({ ...build, io: resolveIo2(config, hardware) }, configFile));
2201
+ const sources = await checkRawSources(loaded);
1986
2202
  console.log(`Validated ${sources.objects.length} Structured Text objects.`);
1987
2203
  return;
1988
2204
  }
@@ -2009,5 +2225,5 @@ try {
2009
2225
  process.exitCode = 1;
2010
2226
  }
2011
2227
 
2012
- //# debugId=F72D15EC02DA92D364756E2164756E21
2228
+ //# debugId=8DA75934A551C62A64756E2164756E21
2013
2229
  //# sourceMappingURL=cli.js.map