@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
package/dist/cli.js CHANGED
@@ -2,50 +2,68 @@
2
2
  // @bun
3
3
 
4
4
  // packages/compiler/src/project/cli.ts
5
- import { existsSync as existsSync5 } from "fs";
5
+ import { existsSync as existsSync3 } from "fs";
6
6
  import { parseArgs } from "util";
7
7
  import { formatDiagnostic, hasErrors as hasErrors4 } from "@tsplc/compiler/ir";
8
- import { loadTsplcConfig as loadTsplcConfig3 } from "@tsplc/config";
9
- import { z as z6 } from "zod";
8
+ import { agentTokenEnv as agentTokenEnv3, agentUrlEnv as agentUrlEnv4, loadTsplcConfig as loadTsplcConfig2 } from "@tsplc/config";
9
+ import { opcuaPort } from "@tsplc/config/build";
10
+ import {
11
+ configFileName as configFileName2,
12
+ emittedStDirectory as emittedStDirectory4
13
+ } from "@tsplc/config/project-files";
14
+ import { debugManifestFile as debugManifestFile4 } from "@tsplc/debug/manifest";
15
+ import { z as z8 } from "zod";
10
16
 
11
17
  // packages/compiler/src/project/debugger.ts
12
- import { existsSync as existsSync3 } from "node:fs";
13
- import { relative as relative2, resolve as resolve4 } from "node:path";
14
- import { serverTokenEnv as serverTokenEnv2 } from "@tsplc/config";
18
+ import { existsSync as existsSync2 } from "node:fs";
19
+ import { relative as relative3, resolve as resolve4 } from "node:path";
20
+ import {
21
+ agentUrlEnv as agentUrlEnv2,
22
+ serverBaseUrl as serverBaseUrl2,
23
+ serverTokenEnv as serverTokenEnv2
24
+ } from "@tsplc/config";
15
25
  import { tcpPort } from "@tsplc/config/build";
16
26
  import {
17
27
  emittedStDirectory as emittedStDirectory3,
18
- generatedDirectory as generatedDirectory3
28
+ generatedDirectory as generatedDirectory4
19
29
  } from "@tsplc/config/project-files";
20
30
  import {
21
31
  createDebugger,
22
- createLoginAdapter,
23
32
  createOpcUaAdapter,
24
- loadExplanations,
25
- loadManifest,
33
+ loadDebugBuild,
34
+ loginReader,
26
35
  opcUaConnection,
27
36
  serveDebugger
28
37
  } from "@tsplc/debug";
29
38
  import { debugManifestFile as debugManifestFile3 } from "@tsplc/debug/manifest";
30
39
 
40
+ // packages/compiler/src/project/flags.ts
41
+ import { z } from "zod";
42
+ var flag = { type: "boolean" };
43
+ var outputFormatSchema = z.enum(["json", "text"]);
44
+
31
45
  // packages/compiler/src/project/plant.ts
32
46
  import {
33
47
  ask as ask2,
34
48
  askCredentials
35
49
  } from "@tsplc/agent";
36
50
  import { createAgentClient } from "@tsplc/agent/client";
51
+ import { resetLabel } from "@tsplc/build";
37
52
  import {
53
+ agentTokenEnv,
54
+ agentUrlEnv,
38
55
  releaseEnvironment
39
56
  } from "@tsplc/config";
57
+ import { runtimePort } from "@tsplc/config/build";
40
58
  import { LoginUnavailable, noLogin } from "@tsplc/debug";
41
- import { z as z4 } from "zod";
59
+ import { isWithin } from "@tsplc/iec/st";
60
+ import { arrayIndex, symbolPathSegments } from "@tsplc/opcua/contract";
61
+ import { controllerRestartSchema } from "@tsplc/server/plant-agent";
62
+ import { z as z5 } from "zod";
42
63
 
43
64
  // packages/compiler/src/project/deployments.ts
44
65
  import { spawn } from "node:child_process";
45
- import {
46
- AgentOperationError,
47
- AgentUnreachable
48
- } from "@tsplc/agent/client";
66
+ import { AgentUnreachable } from "@tsplc/agent/client";
49
67
  import { describeFinding } from "@tsplc/build";
50
68
 
51
69
  // packages/compiler/src/project/terminal.ts
@@ -61,7 +79,12 @@ var choose = async (question, items, label) => {
61
79
  }
62
80
  }
63
81
  };
64
- var confirm = async (question, flags) => flags.yes || /^y(es)?$/i.test(await ask(`${question} [y/N]: `));
82
+ var confirm = async (question) => /^y(es)?$/i.test(await ask(`${question} [y/N]: `));
83
+ var confirmOrCancel = async (question, flags) => {
84
+ if (!flags.yes && !await confirm(question)) {
85
+ throw new Error("Cancelled.");
86
+ }
87
+ };
65
88
  var progress = (message) => console.log(` ${message}`);
66
89
  var timedProgress = () => {
67
90
  const start = Date.now();
@@ -201,31 +224,11 @@ var queued = async (agent, created, follow) => {
201
224
  var submitDeployment = async (agent, release, settings, request, follow) => {
202
225
  const uploading = timedProgress();
203
226
  const created = await agent.queueDeployment(release, { ...settings, deployment: request }, uploading);
204
- if (created) {
205
- uploading("Uploaded");
206
- if (request.mode === "review" && !follow.wait) {
207
- console.log("Once reviewed, it waits for approval on its page.");
208
- }
209
- return queued(agent, created, follow);
210
- }
211
- if (request.mode === "review") {
212
- throw new Error("This plant agent can't review a deployment before applying it; deploy without --review.");
213
- }
214
- console.log("This plant agent can't queue deployments; deploying at once.");
215
- const deployed = await deployAtOnce(agent, release, settings, follow.approval);
216
- console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
217
- return 0;
218
- };
219
- var deployAtOnce = async (agent, release, settings, approval) => {
220
- const deploying = timedProgress();
221
- try {
222
- return await agent.deploy(release, settings, deploying);
223
- } catch (error) {
224
- if (!(error instanceof AgentOperationError && error.downloadRequired) || !(approval.yes || await approval.confirm(`${error.message}. A full download stops the running application while it loads. Download now?`))) {
225
- throw error;
226
- }
227
- return agent.deploy(release, { ...settings, download: true }, timedProgress());
227
+ uploading("Uploaded");
228
+ if (request.mode === "review" && !follow.wait) {
229
+ console.log("Once reviewed, it waits for approval on its page.");
228
230
  }
231
+ return queued(agent, created, follow);
229
232
  };
230
233
  var rollbackTarget = ({
231
234
  deployments,
@@ -265,8 +268,9 @@ var printDeployments = async (agent, flags) => {
265
268
  return;
266
269
  }
267
270
  const now = Date.now();
271
+ const header = ["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""];
268
272
  const rows = [
269
- ["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""],
273
+ header,
270
274
  ...list.deployments.map((deployment) => [
271
275
  deployment.id,
272
276
  deployment.state,
@@ -280,9 +284,9 @@ var printDeployments = async (agent, flags) => {
280
284
  ].filter(Boolean).join(", ")
281
285
  ])
282
286
  ];
283
- const widths = rows[0]?.map((_, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0)));
287
+ const widths = header.map((_, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0)));
284
288
  for (const row of rows) {
285
- console.log(row.map((cell, column) => cell.padEnd(widths?.[column] ?? 0)).join(" ").trimEnd());
289
+ console.log(row.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd());
286
290
  }
287
291
  };
288
292
  var rollBack = async (agent, id, follow) => {
@@ -336,9 +340,9 @@ var gitSource = async (directory) => {
336
340
  };
337
341
 
338
342
  // packages/compiler/src/project/release.ts
339
- import { existsSync as existsSync2 } from "node:fs";
340
- import { basename as basename2, relative, resolve as resolve3, sep } from "node:path";
343
+ import { basename as basename2, relative as relative2, resolve as resolve3, sep } from "node:path";
341
344
  import { pathToFileURL } from "node:url";
345
+ import { checkHostConfig } from "@tsplc/compiler";
342
346
  import { hasErrors as hasErrors2 } from "@tsplc/compiler/ir";
343
347
  import {
344
348
  buildTargetFor,
@@ -348,7 +352,7 @@ import {
348
352
  import { explainFileName as explainFileName2 } from "@tsplc/debug/explain-file";
349
353
  import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
350
354
  import { contractVariables, plcContractSchema } from "@tsplc/opcua/contract";
351
- import { generatedFiles, generateProject } from "@tsplc/typegen";
355
+ import { generateProject } from "@tsplc/typegen";
352
356
 
353
357
  // packages/compiler/src/project/project.ts
354
358
  import {
@@ -360,11 +364,11 @@ import {
360
364
  writeFile as writeFile2
361
365
  } from "node:fs/promises";
362
366
  import { basename, dirname as dirname2, join as join2, resolve } from "node:path";
363
- import { installLibraries } from "@tsplc/build";
364
367
  import {
365
- analyze,
366
- checkHostConfig
367
- } from "@tsplc/compiler";
368
+ buildFiles,
369
+ installLibraries
370
+ } from "@tsplc/build";
371
+ import { analyze } from "@tsplc/compiler";
368
372
  import {
369
373
  buildCodesys,
370
374
  codesysBuildConfig,
@@ -380,10 +384,15 @@ import {
380
384
  } from "@tsplc/compiler/ir";
381
385
  import {
382
386
  compilerConfig,
383
- loadTsplcConfig,
384
- simulationConfig
387
+ serverBaseUrl,
388
+ simulationConfig,
389
+ taskPlan
385
390
  } from "@tsplc/config";
386
- import { emittedFiles, emittedStDirectory as emittedStDirectory2 } from "@tsplc/config/project-files";
391
+ import {
392
+ configFileName,
393
+ emittedFiles,
394
+ emittedStDirectory as emittedStDirectory2
395
+ } from "@tsplc/config/project-files";
387
396
  import { explainFileName } from "@tsplc/debug/explain-file";
388
397
  import { debugManifestFile } from "@tsplc/debug/manifest";
389
398
  import {
@@ -394,8 +403,8 @@ import {
394
403
 
395
404
  // packages/compiler/src/runtime/launch.ts
396
405
  import { generatedDirectory } from "@tsplc/config/project-files";
397
- import { serviceOfPath } from "@tsplc/server";
398
- import { z } from "zod";
406
+ import { serviceOfPath } from "@tsplc/server/wire";
407
+ import { z as z2 } from "zod";
399
408
  var runtimeDirectory = `${generatedDirectory}/runtime`;
400
409
  var runtimeFiles = {
401
410
  launch: "launch.json",
@@ -404,15 +413,15 @@ var runtimeFiles = {
404
413
  log: "plc.log",
405
414
  certificates: "pki"
406
415
  };
407
- var launchSchema = z.strictObject({
408
- config: z.string().nonempty(),
409
- target: z.string().nonempty().nullable(),
410
- services: z.record(z.string(), z.string().startsWith("/tsplc/services/"))
416
+ var launchSchema = z2.strictObject({
417
+ config: z2.string().nonempty(),
418
+ target: z2.string().nonempty().nullable(),
419
+ services: z2.record(z2.string(), z2.string().refine((route) => serviceOfPath(route) !== undefined))
411
420
  });
412
- var runtimeStateSchema = z.strictObject({
413
- pid: z.number().int().positive(),
414
- endpoint: z.string().startsWith("opc.tcp://"),
415
- startedAt: z.iso.datetime()
421
+ var runtimeStateSchema = z2.strictObject({
422
+ pid: z2.number().int().positive(),
423
+ endpoint: z2.string().startsWith("opc.tcp://"),
424
+ startedAt: z2.iso.datetime()
416
425
  });
417
426
  var blockRoute = (runtime) => {
418
427
  if (runtime?.kind === "http") {
@@ -437,40 +446,52 @@ import {
437
446
  rm,
438
447
  writeFile
439
448
  } from "node:fs/promises";
440
- import { dirname, join } from "node:path";
441
- import { sha256Digest } from "@tsplc/config/build";
449
+ import { dirname, join, relative } from "node:path";
450
+ import { cyclicTasksSchema, sha256Digest } from "@tsplc/config/build";
442
451
  import {
443
452
  emittedStDirectory,
444
453
  generatedDirectory as generatedDirectory2
445
454
  } from "@tsplc/config/project-files";
446
- import { z as z2 } from "zod";
447
- var missing = (cause) => cause instanceof Error && ("code" in cause) && cause.code === "ENOENT";
455
+ import { z as z3 } from "zod";
456
+
457
+ // packages/compiler/src/runtime/missing-file.ts
458
+ var isMissingFile = (cause) => cause instanceof Error && ("code" in cause) && cause.code === "ENOENT";
459
+
460
+ // packages/compiler/src/project/artifacts.ts
448
461
  var digest = (value) => createHash("sha256").update(value).digest("hex");
449
- var generatedFileSchema = z2.object({
450
- path: z2.string().regex(/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/).refine((path) => !path.split("/").some((part) => part === "." || part === "..") && !["manifest.json", "receipt.json"].includes(path)),
462
+ var artifactFiles = {
463
+ manifest: "manifest.json",
464
+ receipt: "receipt.json",
465
+ marker: "ownership.json"
466
+ };
467
+ var configReference = (directory, configFile) => relative(directory, configFile);
468
+ var namesConfig = (recorded, directory, configFile) => recorded === configReference(directory, configFile) || recorded === configFile;
469
+ var generatedFileSchema = z3.object({
470
+ path: z3.string().regex(/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/).refine((path) => !path.split("/").some((part) => part === "." || part === "..") && path !== artifactFiles.manifest && path !== artifactFiles.receipt),
451
471
  sha256: sha256Digest
452
472
  });
453
- var manifestSchema = z2.object({
454
- kind: z2.literal("tsplc-artifacts"),
455
- version: z2.literal(1),
456
- configFile: z2.string(),
457
- files: z2.array(z2.unknown())
473
+ var manifestSchema = z3.object({
474
+ kind: z3.literal("tsplc-artifacts"),
475
+ version: z3.literal(1),
476
+ configFile: z3.string(),
477
+ files: z3.array(z3.unknown())
458
478
  });
459
- var buildStatusSchema = z2.enum(["emitted", "vendor-compiled"]);
460
- var receiptSchema = z2.object({
461
- kind: z2.literal("tsplc-build"),
462
- version: z2.literal(1),
463
- configFile: z2.string(),
464
- status: buildStatusSchema
479
+ var receiptSchema = z3.object({
480
+ kind: z3.literal("tsplc-build"),
481
+ version: z3.literal(1),
482
+ generatedAt: z3.iso.datetime(),
483
+ configFile: z3.string(),
484
+ status: z3.enum(["emitted", "vendor-compiled"]),
485
+ vendor: z3.object({ application: z3.string(), tasks: cyclicTasksSchema.optional() }).optional()
465
486
  });
466
- var engineeringMarkerSchema = z2.object({
467
- kind: z2.literal("tsplc-engineering"),
468
- version: z2.literal(1),
469
- configFile: z2.string()
487
+ var engineeringMarkerSchema = z3.object({
488
+ kind: z3.literal("tsplc-engineering"),
489
+ version: z3.literal(1),
490
+ configFile: z3.string()
470
491
  });
471
- function manifest(value, configFile) {
492
+ function manifest(value, output, configFile) {
472
493
  const parsed = manifestSchema.safeParse(value);
473
- if (!parsed.success || parsed.data.configFile !== configFile) {
494
+ if (!parsed.success || !namesConfig(parsed.data.configFile, output, configFile)) {
474
495
  throw new Error("Output directory has no matching tsPLC ownership manifest.");
475
496
  }
476
497
  const files = parsed.data.files.map((item) => {
@@ -493,7 +514,7 @@ async function directory(path) {
493
514
  }
494
515
  return true;
495
516
  } catch (cause) {
496
- if (missing(cause)) {
517
+ if (isMissingFile(cause)) {
497
518
  return false;
498
519
  }
499
520
  throw cause;
@@ -512,26 +533,18 @@ async function filesIn(path, prefix = "") {
512
533
  return result;
513
534
  }
514
535
  async function engineeringDirectory(path, configFile) {
515
- const marker = join(path, "ownership.json");
536
+ const marker = join(path, artifactFiles.marker);
516
537
  const exists = await directory(path);
517
538
  if (!exists || !(await readdir(path)).length) {
518
539
  await mkdir(path, { recursive: true });
519
- await writeFile(marker, `${JSON.stringify({ kind: "tsplc-engineering", version: 1, configFile }, null, 2)}
540
+ await writeFile(marker, `${JSON.stringify({
541
+ kind: "tsplc-engineering",
542
+ version: 1,
543
+ configFile: configReference(path, configFile)
544
+ }, null, 2)}
520
545
  `, { flag: "wx" });
521
- } else {
522
- const entry = await lstat(marker).catch((cause) => {
523
- if (missing(cause)) {
524
- throw new Error(`Engineering cache has no matching tsPLC ownership marker: ${path}`);
525
- }
526
- throw cause;
527
- });
528
- if (!entry.isFile() || entry.isSymbolicLink()) {
529
- throw new Error("Engineering ownership marker must be a real file.");
530
- }
531
- const value = engineeringMarkerSchema.safeParse(JSON.parse(await readFile(marker, "utf8")));
532
- if (!value.success || value.data.configFile !== configFile) {
533
- throw new Error(`Engineering cache has no matching tsPLC ownership marker: ${path}`);
534
- }
546
+ } else if (!await ownedMarker(path, configFile)) {
547
+ throw new Error(`Engineering cache has no matching tsPLC ownership marker: ${path}`);
535
548
  }
536
549
  const inspect = async (directory) => {
537
550
  for (const entry of await readdir(directory, { withFileTypes: true })) {
@@ -546,40 +559,72 @@ async function engineeringDirectory(path, configFile) {
546
559
  };
547
560
  await inspect(path);
548
561
  }
549
- async function owned(configFile, withdrawReceipt = false) {
562
+ var ownedMarker = async (path, configFile) => {
563
+ const marker = join(path, artifactFiles.marker);
564
+ const entry = await lstat(marker).catch((cause) => {
565
+ if (isMissingFile(cause)) {
566
+ return;
567
+ }
568
+ throw cause;
569
+ });
570
+ if (!entry) {
571
+ return false;
572
+ }
573
+ if (!entry.isFile() || entry.isSymbolicLink()) {
574
+ throw new Error("Engineering ownership marker must be a real file.");
575
+ }
576
+ const value = engineeringMarkerSchema.safeParse(JSON.parse(await readFile(marker, "utf8")));
577
+ return value.success && namesConfig(value.data.configFile, path, configFile);
578
+ };
579
+ async function claimed(configFile) {
550
580
  const root = join(dirname(configFile), generatedDirectory2);
551
581
  const output = join(dirname(configFile), dirname(emittedStDirectory));
552
582
  if (!await directory(root) || !await directory(output)) {
553
- return { root, output, unknown: [] };
583
+ return { root, output };
584
+ }
585
+ const manifestPath = join(output, artifactFiles.manifest);
586
+ const manifestEntry = await lstat(manifestPath).catch((cause) => {
587
+ if (isMissingFile(cause)) {
588
+ return;
589
+ }
590
+ throw cause;
591
+ });
592
+ if (!manifestEntry) {
593
+ return { root, output };
554
594
  }
555
- const manifestPath = join(output, "manifest.json");
556
- const manifestEntry = await lstat(manifestPath);
557
595
  if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
558
596
  throw new Error("Ownership manifest must be a real file.");
559
597
  }
560
- const ownership = manifest(JSON.parse(await readFile(manifestPath, "utf8")), configFile);
561
- const receipt = join(output, "receipt.json");
598
+ const ownership = manifest(JSON.parse(await readFile(manifestPath, "utf8")), output, configFile);
599
+ const receipt = join(output, artifactFiles.receipt);
562
600
  try {
563
601
  const entry = await lstat(receipt);
564
602
  if (!entry.isFile() || entry.isSymbolicLink()) {
565
603
  throw new Error("Build receipt must be a real file.");
566
604
  }
567
605
  const value = receiptSchema.safeParse(JSON.parse(await readFile(receipt, "utf8")));
568
- if (!value.success || value.data.configFile !== configFile) {
606
+ if (!value.success || !namesConfig(value.data.configFile, output, configFile)) {
569
607
  throw new Error("Build receipt is not owned by this configuration.");
570
608
  }
571
- if (withdrawReceipt) {
572
- await rm(receipt);
573
- }
574
609
  } catch (cause) {
575
- if (!missing(cause)) {
610
+ if (!isMissingFile(cause)) {
576
611
  throw cause;
577
612
  }
578
613
  }
614
+ return { root, output, ownership };
615
+ }
616
+ async function owned(claim) {
617
+ const { output, ownership } = claim;
618
+ if (!ownership) {
619
+ return {
620
+ ...claim,
621
+ unknown: await directory(output) ? await filesIn(output) : []
622
+ };
623
+ }
579
624
  const names = new Set([
580
625
  ...ownership.files.map((file) => file.path),
581
- "manifest.json",
582
- "receipt.json"
626
+ artifactFiles.manifest,
627
+ artifactFiles.receipt
583
628
  ]);
584
629
  const checked = new Set;
585
630
  for (const file of ownership.files) {
@@ -601,14 +646,17 @@ async function owned(configFile, withdrawReceipt = false) {
601
646
  }
602
647
  }
603
648
  return {
604
- root,
605
- output,
606
- ownership,
649
+ ...claim,
607
650
  unknown: (await filesIn(output)).filter((name) => !names.has(name))
608
651
  };
609
652
  }
653
+ var withdrawReceipt = async ({
654
+ output
655
+ }) => {
656
+ await rm(join(output, artifactFiles.receipt), { force: true });
657
+ };
610
658
  async function publishArtifacts(staging, previous, receipt) {
611
- const configFile = receipt.configFile;
659
+ const configFile = configReference(previous.output, receipt.configFile);
612
660
  const generated = (await filesIn(staging)).sort();
613
661
  const ownership = {
614
662
  kind: "tsplc-artifacts",
@@ -622,16 +670,17 @@ async function publishArtifacts(staging, previous, receipt) {
622
670
  sha256: digest(await readFile(join(staging, path)))
623
671
  });
624
672
  }
625
- await writeFile(join(staging, "manifest.json"), `${JSON.stringify(ownership, null, 2)}
673
+ await writeFile(join(staging, artifactFiles.manifest), `${JSON.stringify(ownership, null, 2)}
626
674
  `);
627
- await writeFile(join(staging, "receipt.json"), `${JSON.stringify({
675
+ await writeFile(join(staging, artifactFiles.receipt), `${JSON.stringify({
628
676
  kind: "tsplc-build",
629
677
  version: 1,
630
678
  generatedAt: new Date().toISOString(),
631
- ...receipt
679
+ ...receipt,
680
+ configFile
632
681
  }, null, 2)}
633
682
  `);
634
- const current = await owned(configFile);
683
+ const current = await owned(await claimed(receipt.configFile));
635
684
  if (JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)) {
636
685
  throw new Error("Output ownership changed during the build; preserve it before rebuilding.");
637
686
  }
@@ -655,15 +704,15 @@ async function publishArtifacts(staging, previous, receipt) {
655
704
  }
656
705
  }
657
706
  async function cleanArtifacts(configFile) {
658
- const generated = await owned(configFile);
707
+ const generated = await owned(await claimed(configFile));
659
708
  if (!generated.ownership) {
660
709
  return;
661
710
  }
662
711
  for (const entry of generated.ownership.files) {
663
712
  await rm(join(generated.output, entry.path));
664
713
  }
665
- await rm(join(generated.output, "receipt.json"), { force: true });
666
- await rm(join(generated.output, "manifest.json"));
714
+ await rm(join(generated.output, artifactFiles.receipt), { force: true });
715
+ await rm(join(generated.output, artifactFiles.manifest));
667
716
  const removeEmpty = async (path) => {
668
717
  for (const entry of await readdir(path, { withFileTypes: true })) {
669
718
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
@@ -689,29 +738,24 @@ var buildConfigs = (loaded, options) => options.simulate ? {
689
738
  loaded: { ...loaded, config: simulationConfig(loaded.config) },
690
739
  configured: loaded.config
691
740
  } : { loaded };
692
- var loadEnvironment = (environment) => ({
693
- env: environment ?? process.env,
694
- target: undefined,
695
- forAgent: false
696
- });
697
- async function loadProject(file, {
698
- loaded,
699
- buildTarget,
700
- configured,
701
- hostConfigDiagnostics,
702
- environment
703
- }) {
704
- let configFile = resolve(file);
741
+ async function loadProject(file, { loaded, buildTarget, configured, hostConfigDiagnostics }) {
742
+ const unresolved = resolve(file);
743
+ const configFile = await realpath(unresolved).catch((cause) => unloaded(unresolved, cause));
744
+ if (typeof configFile !== "string") {
745
+ return configFile;
746
+ }
705
747
  try {
706
- configFile = await realpath(configFile);
707
- const diagnostics = hostConfigDiagnostics ?? checkHostConfig(configFile);
708
- if (hasErrors(diagnostics)) {
709
- return { configFile, diagnostics };
748
+ if (hasErrors(hostConfigDiagnostics)) {
749
+ return { configFile, diagnostics: hostConfigDiagnostics };
750
+ }
751
+ const { config: shared, env } = loaded;
752
+ if (shared.debug?.trace && shared.server?.transport !== "opcua" && !serverBaseUrl(shared, env)) {
753
+ throw new Error('debug.trace sends its records to the app server: configure server with baseUrlEnv and set that variable, or use server.transport "opcua".');
710
754
  }
711
- const { config: shared, env } = loaded ?? await loadTsplcConfig(configFile, loadEnvironment(environment));
712
755
  const root = dirname2(configFile);
713
756
  const catalog = await loadHardware(shared, root);
714
757
  const config = compilerConfig(shared, resolveIo(shared, catalog), buildTarget);
758
+ const hardware = configured ? { config: configured, catalog: await loadHardware(configured, root) } : { config: shared, catalog };
715
759
  return {
716
760
  configFile,
717
761
  shared,
@@ -724,17 +768,21 @@ async function loadProject(file, {
724
768
  ...shared.server && { server: shared.server },
725
769
  ...shared.hmi && { hmi: shared.hmi },
726
770
  hardware: {
727
- catalog: configured ? await loadHardware(configured, root) : catalog,
728
- config: configured ?? shared,
771
+ ...hardware,
729
772
  tree: shared.codesys?.deviceTree !== undefined
730
773
  }
731
774
  },
732
- diagnostics
775
+ bound: boundPaths(resolveIo(hardware.config, hardware.catalog)),
776
+ diagnostics: hostConfigDiagnostics
733
777
  };
734
778
  } catch (cause) {
735
- return { configFile, diagnostics: [failure("config", "PLC5003", cause)] };
779
+ return unloaded(configFile, cause);
736
780
  }
737
781
  }
782
+ var unloaded = (configFile, cause) => ({
783
+ configFile,
784
+ diagnostics: [failure("config", "PLC5003", cause)]
785
+ });
738
786
  function sourceInput(compiler, root) {
739
787
  return {
740
788
  tsconfig: resolve(root, compiler.tsconfig),
@@ -744,43 +792,40 @@ function sourceInput(compiler, root) {
744
792
  ]))
745
793
  };
746
794
  }
747
- async function projectTargets(file = "tsplc.config.ts", options = {}) {
795
+ async function projectTargets(file, { config, env }) {
748
796
  const configFile = await realpath(resolve(file));
749
- const { config, env } = options.loaded ?? await loadTsplcConfig(configFile, loadEnvironment(options.environment));
750
797
  if (!config.compiler) {
751
798
  return;
752
799
  }
753
800
  const source = analyze({
754
801
  ...sourceInput(config.compiler, dirname2(configFile)),
755
802
  services: config.server,
756
- environment: env
803
+ environment: env,
804
+ io: boundPaths(config.io)
757
805
  });
758
806
  const core = source.module && normalizeModule(source.module).core;
759
807
  return core ? coreTargets(core) : undefined;
760
808
  }
809
+ var boundPaths = (io) => Object.entries(io).map(([path, binding]) => ({
810
+ path,
811
+ input: "address" in binding && binding.address.startsWith("%I") ? binding.address : null
812
+ }));
761
813
  var coreTargets = (core) => ({
762
814
  io: ioTargets(core),
763
815
  publication: publicationSelectors(core)
764
816
  });
765
- async function checkProject(file = "tsplc.config.ts", options = {}) {
817
+ async function checkProject(file, options) {
766
818
  const loaded = await loadProject(file, options);
767
- if (!loaded.config || !loaded.project) {
819
+ if (!("project" in loaded)) {
768
820
  return loaded;
769
821
  }
770
- const config = loaded.config;
771
- if (config.target.kind !== "codesys") {
772
- return {
773
- ...loaded,
774
- diagnostics: [
775
- failure("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)
776
- ]
777
- };
778
- }
822
+ const { config } = loaded;
779
823
  const source = analyze({
780
824
  tsconfig: config.tsconfig,
781
825
  programs: config.programs,
782
- services: loaded.shared?.server,
783
- environment: loaded.project.environment
826
+ services: loaded.shared.server,
827
+ environment: loaded.project.environment,
828
+ io: loaded.bound
784
829
  });
785
830
  if (!source.module) {
786
831
  return { ...loaded, diagnostics: source.diagnostics };
@@ -789,12 +834,7 @@ async function checkProject(file = "tsplc.config.ts", options = {}) {
789
834
  if (!normalized.core) {
790
835
  return { ...loaded, diagnostics: normalized.diagnostics };
791
836
  }
792
- const tasks = config.tasks.map((task) => ({
793
- name: task.name,
794
- intervalNanoseconds: task.schedule.interval.nanoseconds,
795
- priority: task.priority,
796
- programs: task.programs
797
- }));
837
+ const tasks = taskPlan(config.tasks);
798
838
  const planned = planCodesys(normalized.core, { tasks }, config.target.options, loaded.project);
799
839
  return {
800
840
  ...loaded,
@@ -821,11 +861,14 @@ async function engineeringInputs(shared, configFile, bundle, options) {
821
861
  }
822
862
  };
823
863
  }
824
- async function buildProject(file = "tsplc.config.ts", options = {}) {
864
+ var missingBuildSection = 'Compiling with CODESYS needs a build section in the config, for example build: { outDir: "build/codesys" }. Add one, or emit the Structured Text only with build --emit-only.';
865
+ async function buildTypeScriptProject(file, options) {
825
866
  let staging;
826
867
  try {
827
868
  const configFile = await realpath(resolve(file));
828
- const previous = await owned(configFile, true);
869
+ const claim = await claimed(configFile);
870
+ await withdrawReceipt(claim);
871
+ const previous = await owned(claim);
829
872
  if (previous.unknown.length) {
830
873
  throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
831
874
  }
@@ -834,21 +877,29 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
834
877
  return { diagnostics: checked.diagnostics };
835
878
  }
836
879
  const bundle = emitCodesys(checked.plan);
837
- if (hasErrors(bundle.diagnostics)) {
838
- return { diagnostics: bundle.diagnostics };
839
- }
840
880
  const shared = checked.shared;
881
+ const outDir = shared?.build && resolve(dirname2(configFile), shared.build.outDir);
882
+ if (!options.emitOnly && !outDir) {
883
+ return {
884
+ diagnostics: [
885
+ ...checked.diagnostics,
886
+ failure("config", "PLC5003", missingBuildSection)
887
+ ]
888
+ };
889
+ }
841
890
  const engineering = shared && (!options.emitOnly || options.forController) ? await engineeringInputs(shared, configFile, bundle, {
842
891
  frozen: options.frozenLockfile
843
892
  }) : undefined;
844
- const outDir = shared?.build && resolve(dirname2(configFile), shared.build.outDir);
845
- const controllerConfig = outDir ? codesysBuildConfig(checked.plan, bundle, {
846
- configFile,
847
- sourceDir: join2(previous.output, emittedSt),
848
- outDir,
849
- controller: options.controller,
850
- ...engineering
851
- }) : undefined;
893
+ const controllerConfig = outDir ? {
894
+ ...codesysBuildConfig(checked.plan, bundle, {
895
+ configFile,
896
+ sourceDir: join2(previous.output, emittedSt),
897
+ outDir,
898
+ controller: options.controller,
899
+ ...engineering
900
+ }),
901
+ io: {}
902
+ } : undefined;
852
903
  await mkdir2(previous.root, { recursive: true });
853
904
  staging = await mkdtemp(join2(previous.root, "stage-"));
854
905
  const artifacts = [
@@ -873,14 +924,12 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
873
924
  content: `${JSON.stringify(checked.config, null, 2)}
874
925
  `
875
926
  },
876
- ...bundle.debug ? [
877
- {
878
- path: debugManifestFile,
879
- content: `${JSON.stringify(bundle.debug)}
927
+ {
928
+ path: debugManifestFile,
929
+ content: `${JSON.stringify(bundle.debug)}
880
930
  `
881
- }
882
- ] : [],
883
- ...bundle.explain === undefined ? [] : [{ path: explainFileName, content: bundle.explain }]
931
+ },
932
+ { path: explainFileName, content: bundle.explain }
884
933
  ];
885
934
  const stagedSt = join2(staging, emittedSt);
886
935
  const directories = new Set(artifacts.map((artifact) => dirname2(join2(stagedSt, artifact.path))));
@@ -890,34 +939,16 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
890
939
  for (const artifact of artifacts) {
891
940
  await writeFile2(join2(stagedSt, artifact.path), artifact.content);
892
941
  }
893
- let vendor;
894
- if (!options.emitOnly) {
895
- const engineeringDir = outDir ?? join2(previous.root, "engineering");
896
- await engineeringDirectory(engineeringDir, configFile);
897
- try {
898
- vendor = await buildCodesys(checked.plan, bundle, {
899
- configFile,
900
- sourceDir: join2(staging, emittedSt),
901
- outDir: engineeringDir,
902
- controller: options.controller,
903
- ...engineering
904
- }, { progress: options.progress });
905
- } catch (cause) {
906
- return { diagnostics: diagnoseCodesys(cause, bundle) };
907
- }
908
- const vendorArtifacts = [
909
- ["Application.project", vendor.project],
910
- ["Application.app", vendor.output],
911
- ["Application.crc", vendor.checksum]
912
- ];
913
- for (const [name, path] of vendorArtifacts) {
914
- if (!path) {
915
- continue;
916
- }
917
- const destination = join2(staging, "vendor", name);
918
- await mkdir2(dirname2(destination), { recursive: true });
919
- await copyFile(path, destination);
920
- }
942
+ const vendor = options.emitOnly || !outDir ? undefined : await compileVendor(checked.plan, bundle, {
943
+ configFile,
944
+ staging,
945
+ engineeringDir: outDir,
946
+ controller: options.controller,
947
+ engineering,
948
+ progress: options.progress
949
+ });
950
+ if (vendor && "diagnostics" in vendor) {
951
+ return vendor;
921
952
  }
922
953
  const status = vendor ? "vendor-compiled" : "emitted";
923
954
  await publishArtifacts(staging, previous, {
@@ -934,7 +965,7 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
934
965
  ...controllerConfig && { controllerConfig },
935
966
  targets: coreTargets(checked.plan.core),
936
967
  services: serviceRoutes(checked.plan.core),
937
- diagnostics: [...checked.diagnostics, ...bundle.diagnostics]
968
+ diagnostics: checked.diagnostics
938
969
  };
939
970
  } catch (cause) {
940
971
  return { diagnostics: [failure("config", "PLC5004", cause)] };
@@ -944,6 +975,31 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
944
975
  }
945
976
  }
946
977
  }
978
+ async function compileVendor(plan, bundle, options) {
979
+ await engineeringDirectory(options.engineeringDir, options.configFile);
980
+ const vendor = await buildCodesys(plan, bundle, {
981
+ configFile: options.configFile,
982
+ sourceDir: join2(options.staging, emittedSt),
983
+ outDir: options.engineeringDir,
984
+ controller: options.controller,
985
+ ...options.engineering
986
+ }, { progress: options.progress }).catch((cause) => ({
987
+ diagnostics: diagnoseCodesys(cause, bundle)
988
+ }));
989
+ if ("diagnostics" in vendor) {
990
+ return vendor;
991
+ }
992
+ for (const artifact of ["project", "output", "checksum"]) {
993
+ const path = vendor[artifact];
994
+ if (!path) {
995
+ continue;
996
+ }
997
+ const destination = join2(options.staging, "vendor", basename(buildFiles[artifact]));
998
+ await mkdir2(dirname2(destination), { recursive: true });
999
+ await copyFile(path, destination);
1000
+ }
1001
+ return vendor;
1002
+ }
947
1003
  function compactMappings(mappings) {
948
1004
  const objects = new Map;
949
1005
  const files = new Map;
@@ -970,7 +1026,7 @@ function compactMappings(mappings) {
970
1026
  mappings: rows
971
1027
  };
972
1028
  }
973
- async function cleanProject(file = "tsplc.config.ts") {
1029
+ async function cleanProject(file = configFileName) {
974
1030
  try {
975
1031
  await cleanArtifacts(await realpath(resolve(file)));
976
1032
  return { diagnostics: [] };
@@ -984,32 +1040,25 @@ import { existsSync } from "node:fs";
984
1040
  import { mkdir as mkdir3, mkdtemp as mkdtemp2, rename as rename2, rm as rm3 } from "node:fs/promises";
985
1041
  import { createRequire } from "node:module";
986
1042
  import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
987
- import { fileURLToPath } from "node:url";
988
- import { z as z3 } from "zod";
1043
+ import { projectSlugs } from "@tsplc/config";
1044
+ import { generatedDirectory as generatedDirectory3 } from "@tsplc/config/project-files";
1045
+ import { z as z4 } from "zod";
989
1046
  var resolveServerModule = (root, name) => name.startsWith(".") || name.startsWith("/") || existsSync(resolve2(root, name)) ? resolve2(root, name) : createRequire(join3(root, "package.json")).resolve(name);
990
- var kebabCase = (name) => name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
991
- var serverOutput = (config, root, extension) => resolve2(root, "build/server", `${kebabCase(config.name)}-services${extension}`);
992
- var serverCheckRequestSchema = z3.strictObject({
993
- entry: z3.string(),
994
- root: z3.string()
1047
+ var serverOutput = (config, root, extension) => resolve2(root, generatedDirectory3, "server", `${projectSlugs.kebab(config.name)}-services${extension}`);
1048
+ var serverCheckRequestSchema = z4.strictObject({
1049
+ entry: z4.string(),
1050
+ root: z4.string()
995
1051
  });
996
- var serverCheckResultSchema = z3.strictObject({
997
- failure: z3.string().nullable()
1052
+ var serverCheckResultSchema = z4.strictObject({
1053
+ failure: z4.string().nullable()
998
1054
  });
999
- var serverCheckScript = () => {
1000
- const script = ["./server-check.ts", "./server-check.js"].map((path) => fileURLToPath(new URL(path, import.meta.url))).find((path) => existsSync(path));
1001
- if (!script) {
1002
- throw new Error("The server type-check script is missing from this build.");
1003
- }
1004
- return script;
1005
- };
1006
1055
  var checkServer = async (config, root) => {
1007
1056
  const runtime = config.server?.runtime;
1008
1057
  if (!runtime) {
1009
1058
  throw new Error("Configure server.runtime to build the server.");
1010
1059
  }
1011
1060
  const entry = resolveServerModule(root, runtime.entry);
1012
- const worker = new Worker(serverCheckScript());
1061
+ const worker = new Worker(import.meta.resolve("#server-check"));
1013
1062
  try {
1014
1063
  const answer = await new Promise((resolve, reject) => {
1015
1064
  worker.onmessage = (event) => resolve(event.data);
@@ -1029,6 +1078,13 @@ var checkServer = async (config, root) => {
1029
1078
  worker.terminate();
1030
1079
  }
1031
1080
  };
1081
+ var startServerCheck = (config, root) => {
1082
+ const check = checkServer(config, root);
1083
+ check.catch(() => {
1084
+ return;
1085
+ });
1086
+ return check;
1087
+ };
1032
1088
  var bundleServer = async ({ entry }, config, root) => {
1033
1089
  const outFile = serverOutput(config, root, ".js");
1034
1090
  const result = await Bun.build({
@@ -1083,29 +1139,27 @@ var buildServer = async ({ entry, runtime }, config, root) => {
1083
1139
  };
1084
1140
 
1085
1141
  // packages/compiler/src/project/release.ts
1086
- var releaseVariables = async (config, root) => {
1087
- if (!config.typegen) {
1142
+ var releaseVariables = async (file) => {
1143
+ if (file === null) {
1088
1144
  return [];
1089
1145
  }
1090
- const contract = plcContractSchema.parse(await import(pathToFileURL(resolve3(root, config.typegen.dir, generatedFiles.contract)).href));
1146
+ const contract = plcContractSchema.parse(await import(pathToFileURL(file).href));
1091
1147
  return contractVariables(contract).map(({ path, type }) => ({ path, type }));
1092
1148
  };
1093
- var prepareRelease = async (file, loaded, flags, built) => {
1149
+ var prepareRelease = async (loaded, flags, built) => {
1094
1150
  const project = { ...loaded, env: built.env };
1095
1151
  const { config, root } = project;
1096
1152
  if (!config.compiler) {
1097
1153
  throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
1098
1154
  }
1099
1155
  const command = flags.simulate ? "run" : "deploy";
1100
- const serverCheck = config.server?.runtime ? checkServer(config, root) : undefined;
1101
- serverCheck?.catch(() => {
1102
- return;
1103
- });
1104
- const emitted = await buildProject(file, {
1156
+ const serverCheck = config.server?.runtime ? startServerCheck(config, root) : undefined;
1157
+ const emitted = await buildTypeScriptProject(project.configFile, {
1105
1158
  emitOnly: true,
1106
1159
  forController: true,
1107
1160
  frozenLockfile: flags["frozen-lockfile"],
1108
1161
  ...buildConfigs(project, flags),
1162
+ hostConfigDiagnostics: checkHostConfig(project.configFile),
1109
1163
  buildTarget: buildTargetFor(command),
1110
1164
  controller: controllerFor(config, command)
1111
1165
  });
@@ -1116,7 +1170,9 @@ var prepareRelease = async (file, loaded, flags, built) => {
1116
1170
  if (!settings) {
1117
1171
  throw new Error("Configure build settings for deployment.");
1118
1172
  }
1119
- await generateProject(file, { loaded: project, targets: emitted.targets });
1173
+ const { contract } = await generateProject(project, {
1174
+ targets: emitted.targets
1175
+ });
1120
1176
  const portable = (path) => path.split(sep).join("/");
1121
1177
  const libraries = (settings.libraries ?? []).map((library) => ({
1122
1178
  ...library,
@@ -1139,10 +1195,10 @@ var prepareRelease = async (file, loaded, flags, built) => {
1139
1195
  });
1140
1196
  }
1141
1197
  for (const name of [debugManifestFile2, explainFileName2]) {
1142
- const path = resolve3(settings.sourceDir, name);
1143
- if (existsSync2(path)) {
1144
- files.push({ path: name, content: Bun.file(path) });
1145
- }
1198
+ files.push({
1199
+ path: name,
1200
+ content: Bun.file(resolve3(settings.sourceDir, name))
1201
+ });
1146
1202
  }
1147
1203
  const serverScript = serverCheck && await bundleServer(await serverCheck, config, root);
1148
1204
  const server = serverScript ? {
@@ -1153,7 +1209,7 @@ var prepareRelease = async (file, loaded, flags, built) => {
1153
1209
  files.push(server);
1154
1210
  }
1155
1211
  const releaseConfig = {
1156
- io: {},
1212
+ io: settings.io,
1157
1213
  deviceTree: settings.deviceTree,
1158
1214
  controller: settings.controller,
1159
1215
  libraryReferences: settings.libraryReferences,
@@ -1168,11 +1224,11 @@ var prepareRelease = async (file, loaded, flags, built) => {
1168
1224
  timeouts: settings.timeouts,
1169
1225
  template: "template.project",
1170
1226
  sourceDir: "st",
1171
- entry: `st/${portable(relative(settings.sourceDir, settings.entry))}`
1227
+ entry: `st/${portable(relative2(settings.sourceDir, settings.entry))}`
1172
1228
  };
1173
1229
  const manifest = {
1174
1230
  config: releaseConfig,
1175
- variables: await releaseVariables(config, root),
1231
+ variables: await releaseVariables(contract),
1176
1232
  server: server?.path,
1177
1233
  debug: config.debug,
1178
1234
  serverTokenEnv: serverTokenEnv(config),
@@ -1184,17 +1240,17 @@ var prepareRelease = async (file, loaded, flags, built) => {
1184
1240
 
1185
1241
  // packages/compiler/src/project/plant.ts
1186
1242
  var connect = (env) => {
1187
- const environment = z4.object({
1188
- TSPLC_AGENT_URL: z4.url({
1189
- error: "Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://plant-pc:4850"
1243
+ const environment = z5.object({
1244
+ [agentUrlEnv]: z5.url({
1245
+ error: `Configure the target's agent, or set ${agentUrlEnv} to the plant agent, such as http://plant-pc:4850`
1190
1246
  }),
1191
- TSPLC_AGENT_TOKEN: z4.string({
1192
- error: "Set TSPLC_AGENT_TOKEN to the plant agent's token"
1247
+ [agentTokenEnv]: z5.string({
1248
+ error: `Set ${agentTokenEnv} to the plant agent's token`
1193
1249
  })
1194
1250
  }).parse(env);
1195
1251
  return createAgentClient({
1196
- url: environment.TSPLC_AGENT_URL,
1197
- token: environment.TSPLC_AGENT_TOKEN
1252
+ url: environment[agentUrlEnv],
1253
+ token: environment[agentTokenEnv]
1198
1254
  });
1199
1255
  };
1200
1256
  var readThroughAgent = (agent) => async ([first, ...rest]) => {
@@ -1223,43 +1279,45 @@ var readThroughAgent = (agent) => async ([first, ...rest]) => {
1223
1279
  };
1224
1280
 
1225
1281
  // packages/compiler/src/project/debugger.ts
1282
+ var debuggerPort = 4870;
1283
+ var debugOptions = {
1284
+ port: { type: "string" },
1285
+ "server-url": { type: "string" },
1286
+ opcua: flag
1287
+ };
1288
+ var debugUsage = `[--target name] [--port ${debuggerPort}] [--server-url url] [--opcua]`;
1226
1289
  async function serveProjectDebugger({ config, root, env }, flags) {
1227
1290
  if (flags.opcua && !config.monitor) {
1228
1291
  throw new Error("Configure monitor with the controller's OPC UA endpoint to use --opcua.");
1229
1292
  }
1230
- const agentUrl = env.TSPLC_AGENT_URL;
1231
- if (!flags.opcua && !(agentUrl && env.TSPLC_AGENT_TOKEN)) {
1232
- throw new Error("Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.");
1233
- }
1293
+ const reader = flags.opcua && config.monitor ? { monitor: config.monitor } : { agent: connect(env) };
1234
1294
  const file = resolve4(root, emittedStDirectory3, debugManifestFile3);
1235
- if (!existsSync3(file)) {
1236
- throw new Error(`No debug manifest at ${relative2(process.cwd(), file)}: build with debug configured.`);
1295
+ if (!existsSync2(file)) {
1296
+ throw new Error(`No debug manifest at ${relative3(process.cwd(), file)}: build the program first, with tsplc build or tsplc build --emit-only.`);
1237
1297
  }
1238
- const port = tcpPort.safeParse(Number(flags.port ?? 4870));
1298
+ const port = tcpPort.safeParse(Number(flags.port ?? debuggerPort));
1239
1299
  if (!port.success) {
1240
1300
  throw new Error("--port must be a TCP port.");
1241
1301
  }
1242
- const manifest = await loadManifest(file);
1243
- const serverUrl = flags["server-url"] ?? (config.server?.baseUrlEnv && env[config.server.baseUrlEnv]);
1302
+ const serverUrl = flags["server-url"] ?? serverBaseUrl2(config, env);
1244
1303
  const tokenEnv = serverTokenEnv2(config);
1245
1304
  const token = tokenEnv && env[tokenEnv];
1246
1305
  const log = (message) => console.log(`${new Date().toISOString()} ${message}`);
1306
+ const build = await loadDebugBuild(file);
1247
1307
  const debug = await createDebugger({
1248
- manifest,
1249
- adapter: flags.opcua && config.monitor ? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env })) : createLoginAdapter({
1250
- read: readThroughAgent(connect(env)),
1251
- probe: manifest.build.target,
1252
- endpoint: `the plant agent at ${agentUrl}`
1308
+ ...build,
1309
+ ..."monitor" in reader ? {
1310
+ adapter: createOpcUaAdapter(opcUaConnection(reader.monitor, { root, env })),
1311
+ forced: null
1312
+ } : loginReader(build.manifest, {
1313
+ read: readThroughAgent(reader.agent),
1314
+ status: async () => (await reader.agent.status()).login,
1315
+ endpoint: `the plant agent at ${env[agentUrlEnv2]}`
1253
1316
  }),
1254
- stateDirectory: resolve4(root, generatedDirectory3, "debug"),
1317
+ stateDirectory: resolve4(root, generatedDirectory4, "debug"),
1255
1318
  watch: config.debug?.watch ?? {},
1256
1319
  ...serverUrl && token && { server: { url: serverUrl, token } },
1257
1320
  projectRoot: root,
1258
- explanations: await loadExplanations(file, manifest),
1259
- forced: flags.opcua ? null : async () => {
1260
- const { login } = await connect(env).status();
1261
- return login && "forced" in login ? login.forced : null;
1262
- },
1263
1321
  log
1264
1322
  });
1265
1323
  const server = serveDebugger(debug, { port: port.data, log });
@@ -1275,50 +1333,51 @@ async function serveProjectDebugger({ config, root, env }, flags) {
1275
1333
  await debug.close();
1276
1334
  }
1277
1335
 
1336
+ // packages/compiler/src/project/flags.ts
1337
+ import { z as z6 } from "zod";
1338
+ var outputFormatSchema2 = z6.enum(["json", "text"]);
1339
+
1278
1340
  // packages/compiler/src/project/plant.ts
1279
1341
  import {
1280
1342
  ask as ask3,
1281
1343
  askCredentials as askCredentials2
1282
1344
  } from "@tsplc/agent";
1283
1345
  import { createAgentClient as createAgentClient2 } from "@tsplc/agent/client";
1346
+ import { resetLabel as resetLabel2 } from "@tsplc/build";
1284
1347
  import {
1348
+ agentTokenEnv as agentTokenEnv2,
1349
+ agentUrlEnv as agentUrlEnv3,
1285
1350
  releaseEnvironment as releaseEnvironment2
1286
1351
  } from "@tsplc/config";
1352
+ import { runtimePort as runtimePort2 } from "@tsplc/config/build";
1287
1353
  import { LoginUnavailable as LoginUnavailable2, noLogin as noLogin2 } from "@tsplc/debug";
1288
- import { z as z5 } from "zod";
1289
- var plantCommands = [
1290
- "deploy",
1291
- "deployments",
1292
- "rollback",
1293
- "redeploy",
1294
- "dashboard",
1295
- "target",
1296
- "status",
1297
- "login",
1298
- "logout",
1299
- "vars",
1300
- "read",
1301
- "write",
1302
- "force",
1303
- "unforce",
1304
- "start",
1305
- "stop",
1306
- "reset",
1307
- "restart"
1308
- ];
1309
- var plantCommand = (name) => plantCommands.find((command) => command === name);
1354
+ import { isWithin as isWithin2 } from "@tsplc/iec/st";
1355
+ import { arrayIndex as arrayIndex2, symbolPathSegments as symbolPathSegments2 } from "@tsplc/opcua/contract";
1356
+ import { controllerRestartSchema as controllerRestartSchema2 } from "@tsplc/server/plant-agent";
1357
+ import { z as z7 } from "zod";
1358
+ var plantOptions = {
1359
+ download: flag,
1360
+ review: flag,
1361
+ wait: flag,
1362
+ "initialize-user": flag,
1363
+ restore: flag,
1364
+ select: flag,
1365
+ simulate: flag,
1366
+ yes: { type: "boolean", short: "y" },
1367
+ "frozen-lockfile": flag
1368
+ };
1310
1369
  var connect2 = (env) => {
1311
- const environment = z5.object({
1312
- TSPLC_AGENT_URL: z5.url({
1313
- error: "Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://plant-pc:4850"
1370
+ const environment = z7.object({
1371
+ [agentUrlEnv3]: z7.url({
1372
+ error: `Configure the target's agent, or set ${agentUrlEnv3} to the plant agent, such as http://plant-pc:4850`
1314
1373
  }),
1315
- TSPLC_AGENT_TOKEN: z5.string({
1316
- error: "Set TSPLC_AGENT_TOKEN to the plant agent's token"
1374
+ [agentTokenEnv2]: z7.string({
1375
+ error: `Set ${agentTokenEnv2} to the plant agent's token`
1317
1376
  })
1318
1377
  }).parse(env);
1319
1378
  return createAgentClient2({
1320
- url: environment.TSPLC_AGENT_URL,
1321
- token: environment.TSPLC_AGENT_TOKEN
1379
+ url: environment[agentUrlEnv3],
1380
+ token: environment[agentTokenEnv2]
1322
1381
  });
1323
1382
  };
1324
1383
  var selectTarget = async (agent) => {
@@ -1329,7 +1388,7 @@ var selectTarget = async (agent) => {
1329
1388
  const network = interfaces.length === 1 && interfaces[0] ? interfaces[0] : await choose("Which network is the controller on?", interfaces, (item) => `${item.name} ${item.address}/${item.prefixLength}`);
1330
1389
  console.log(`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`);
1331
1390
  const found = await agent.discover(network.name);
1332
- const manual = { address: "", port: 11740, hostname: null };
1391
+ const manual = { address: "", port: runtimePort2, hostname: null };
1333
1392
  const choice = await choose("Which controller?", [...found, manual], (item) => item === manual ? "Enter an address" : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`);
1334
1393
  const host = choice === manual ? await ask3("Controller address: ") : choice.address;
1335
1394
  return agent.setTarget({ host, port: choice.port });
@@ -1353,36 +1412,34 @@ var plantSummary = ({ values, secrets }) => {
1353
1412
  ].filter((part) => part !== null);
1354
1413
  return parts.length ? parts.join(" and ") : null;
1355
1414
  };
1356
- var deploy = async (agent, file, loaded, flags, environment, follow) => {
1415
+ var deploy = async (agent, loaded, flags, follow) => {
1357
1416
  const status = await agent.status();
1358
1417
  if (status.login) {
1359
1418
  throw new Error("A login is open; log out before deploying: tsplc logout");
1360
1419
  }
1361
1420
  const target = !status.target || flags.select ? await selectTarget(agent) : status.target;
1421
+ const initializeUser = flags["initialize-user"] ?? false;
1362
1422
  const plant = await agent.releaseVariables(loaded.config.secrets?.service ?? null);
1363
- const built = releaseEnvironment2(loaded.config, { env: environment, values: loaded.values }, plant);
1423
+ const built = releaseEnvironment2(loaded.config, loaded, plant);
1364
1424
  console.log(`Building the release for ${target.host}…`);
1365
1425
  const held = plantSummary(plant);
1366
1426
  if (held) {
1367
1427
  console.log(` With the plant PC's ${held}`);
1368
1428
  }
1369
1429
  const building = timedProgress();
1370
- const { release, diagnostics } = await prepareRelease(file, loaded, flags, built);
1430
+ const { release, diagnostics } = await prepareRelease(loaded, flags, built);
1371
1431
  if (!release) {
1372
1432
  return { diagnostics };
1373
1433
  }
1374
1434
  building("Built");
1375
- if (flags.download && !await confirm("A full download stops the running application while it loads. Continue?", flags)) {
1376
- throw new Error("Cancelled.");
1435
+ if (flags.download) {
1436
+ await confirmOrCancel("A full download stops the running application while it loads. Continue?", flags);
1377
1437
  }
1378
- const credentials = await controllerCredentials(environment, {
1379
- stored: status.credentialsStored,
1380
- initializeUser: flags["initialize-user"] ?? false
1381
- }, askCredentials2);
1438
+ const credentials = await controllerCredentials(loaded.env, { stored: status.credentialsStored, initializeUser }, askCredentials2);
1382
1439
  const settings = {
1383
1440
  credentials,
1384
1441
  download: flags.download ?? false,
1385
- initializeUser: flags["initialize-user"] ?? false
1442
+ initializeUser
1386
1443
  };
1387
1444
  console.log(release.manifest.server ? "Uploading the server and the program…" : "Uploading the program…");
1388
1445
  return {
@@ -1407,25 +1464,23 @@ var ensureLogin = async (agent, environment) => {
1407
1464
  };
1408
1465
  var variableChildren = (variables, prefix) => {
1409
1466
  const children = new Map;
1410
- const start = prefix.toLowerCase();
1411
1467
  for (const { path, type } of variables) {
1412
- const lower = path.toLowerCase();
1413
- if (prefix && !(lower === start || lower.startsWith(`${start}.`) || lower.startsWith(`${start}[`))) {
1468
+ if (prefix && !isWithin2(prefix, path)) {
1414
1469
  continue;
1415
1470
  }
1416
1471
  const rest = path.slice(prefix.length).replace(/^\./, "");
1417
1472
  if (rest === "") {
1418
1473
  return [{ name: path, type, leaves: 1 }];
1419
1474
  }
1420
- const name = /^(\[[^\]]*\]|[^.[]+)/.exec(rest)?.[0] ?? rest;
1475
+ const name = symbolPathSegments2(rest)[0] ?? rest;
1421
1476
  const child = children.get(name) ?? { leaves: 0 };
1422
1477
  children.set(name, {
1423
1478
  type: rest === name ? type : undefined,
1424
1479
  leaves: child.leaves + 1
1425
1480
  });
1426
1481
  }
1427
- const indexes = [...children.keys()].filter((name) => /^\[\d+\]$/.test(name)).map((name) => Number(name.slice(1, -1)));
1428
- const listed = [...children].filter(([name]) => !/^\[\d+\]$/.test(name));
1482
+ const indexes = [...children.keys()].map(arrayIndex2).filter((index) => index !== undefined);
1483
+ const listed = [...children].filter(([name]) => arrayIndex2(name) === undefined);
1429
1484
  if (indexes.length) {
1430
1485
  const first = children.get(`[${Math.min(...indexes)}]`);
1431
1486
  listed.unshift([
@@ -1470,137 +1525,215 @@ var printLogin = (result) => {
1470
1525
  console.log(`Forced: ${result.forced.join(", ")}`);
1471
1526
  }
1472
1527
  };
1473
- var runPlantCommand = async (agent, command, args, flags, project) => {
1474
- const approval = {
1475
- yes: flags.yes ?? false,
1476
- interactive: project.interactive,
1477
- confirm: (question) => confirm(question, {})
1478
- };
1479
- const follow = { wait: flags.wait ?? false, approval };
1480
- const expect = (count, usage) => {
1481
- if (args.length !== count) {
1482
- throw new Error(`Usage: tsplc ${command} ${usage}`);
1528
+ var none = ({ args, usage }) => {
1529
+ if (args.length) {
1530
+ usage();
1531
+ }
1532
+ };
1533
+ var plantCommands = {
1534
+ deploy: {
1535
+ usage: "[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]",
1536
+ run: async (context) => {
1537
+ none(context);
1538
+ const { agent, project, flags, follow } = context;
1539
+ return deploy(agent, await project.load(), flags, follow);
1540
+ }
1541
+ },
1542
+ deployments: {
1543
+ usage: "[--format json]",
1544
+ run: async (context) => {
1545
+ none(context);
1546
+ await printDeployments(context.agent, context.flags);
1547
+ return;
1483
1548
  }
1484
- };
1485
- const send = async (loginCommand) => {
1486
- await ensureLogin(agent, project.environment);
1487
- printLogin(await agent.command(loginCommand));
1488
- };
1489
- switch (command) {
1490
- case "deploy":
1491
- expect(0, "[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]");
1492
- return deploy(agent, project.file, await project.load(), flags, project.environment, follow);
1493
- case "deployments":
1494
- expect(0, "[--format json]");
1495
- return printDeployments(agent, flags);
1496
- case "rollback":
1549
+ },
1550
+ rollback: {
1551
+ usage: "[id] [--wait] [-y]",
1552
+ run: async ({ agent, args, follow, usage }) => {
1497
1553
  if (args.length > 1) {
1498
- throw new Error("Usage: tsplc rollback [id] [--wait] [-y]");
1554
+ usage();
1499
1555
  }
1500
1556
  return { exitCode: await rollBack(agent, args[0], follow) };
1501
- case "redeploy": {
1502
- const [id, ...extra] = args;
1557
+ }
1558
+ },
1559
+ redeploy: {
1560
+ usage: "<id> [--review] [--wait] [-y]",
1561
+ run: async ({ agent, args: [id, ...extra], flags, follow, usage }) => {
1503
1562
  if (!id || extra.length) {
1504
- throw new Error("Usage: tsplc redeploy <id> [--review] [--wait] [-y]");
1563
+ return usage();
1505
1564
  }
1506
1565
  return {
1507
1566
  exitCode: await redeploy(agent, id, flags.review ? "review" : "apply", follow)
1508
1567
  };
1509
1568
  }
1510
- case "dashboard":
1511
- expect(0, "");
1512
- return openDashboard(agent, project.interactive);
1513
- case "target": {
1514
- expect(0, "");
1515
- const target = await selectTarget(agent);
1569
+ },
1570
+ dashboard: {
1571
+ usage: "",
1572
+ run: async (context) => {
1573
+ none(context);
1574
+ openDashboard(context.agent, context.project.interactive);
1575
+ return;
1576
+ }
1577
+ },
1578
+ target: {
1579
+ usage: "",
1580
+ run: async (context) => {
1581
+ none(context);
1582
+ const target = await selectTarget(context.agent);
1516
1583
  console.log(`Deployments now go to ${target.host}:${target.port}.`);
1517
1584
  return;
1518
1585
  }
1519
- case "status":
1520
- expect(0, "");
1521
- return printStatus(agent);
1522
- case "login":
1523
- expect(0, "");
1524
- await ensureLogin(agent, project.environment);
1525
- printLogin(await agent.command({ command: "state" }));
1586
+ },
1587
+ status: {
1588
+ usage: "",
1589
+ run: async (context) => {
1590
+ none(context);
1591
+ await printStatus(context.agent);
1592
+ return;
1593
+ }
1594
+ },
1595
+ login: {
1596
+ usage: "",
1597
+ run: async (context) => {
1598
+ none(context);
1599
+ await ensureLogin(context.agent, context.project.environment);
1600
+ printLogin(await context.agent.command({ command: "state" }));
1526
1601
  return;
1527
- case "logout": {
1528
- expect(0, "");
1602
+ }
1603
+ },
1604
+ logout: {
1605
+ usage: "",
1606
+ run: async (context) => {
1607
+ none(context);
1608
+ const { agent, flags } = context;
1529
1609
  const { login } = await agent.status();
1530
1610
  const forced = login && "forced" in login ? login.forced : [];
1531
- if (forced.length && !await confirm(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags)) {
1532
- throw new Error("Cancelled.");
1611
+ if (forced.length) {
1612
+ await confirmOrCancel(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags);
1533
1613
  }
1534
1614
  const { failure } = await agent.logout();
1535
1615
  console.log(failure ? `The login couldn't log out (${failure}); its container was removed.` : "Logged out.");
1536
1616
  return;
1537
1617
  }
1538
- case "vars":
1618
+ },
1619
+ vars: {
1620
+ usage: "[path]",
1621
+ run: async ({ agent, args, usage }) => {
1539
1622
  if (args.length > 1) {
1540
- throw new Error("Usage: tsplc vars [path]");
1623
+ usage();
1541
1624
  }
1542
- return printVariables(agent, args[0]);
1543
- case "read": {
1544
- const [first, ...rest] = args;
1545
- if (!first) {
1546
- throw new Error("Usage: tsplc read <expression>...");
1547
- }
1548
- return send({ command: "read", expressions: [first, ...rest] });
1625
+ await printVariables(agent, args[0]);
1626
+ return;
1549
1627
  }
1550
- case "write":
1551
- case "force": {
1552
- const [expression, value, ...extra] = args;
1553
- if (!expression || !value || extra.length) {
1554
- throw new Error(`Usage: tsplc ${command} <expression> <value>`);
1628
+ },
1629
+ read: {
1630
+ usage: "<expression>...",
1631
+ run: async ({ args: [first, ...rest], send, usage }) => {
1632
+ if (!first) {
1633
+ return usage();
1555
1634
  }
1556
- return send({ command, values: { [expression]: value } });
1635
+ await send({ command: "read", expressions: [first, ...rest] });
1636
+ return;
1557
1637
  }
1558
- case "unforce":
1559
- return send({
1638
+ },
1639
+ write: {
1640
+ usage: "<expression> <value>",
1641
+ run: (context) => setValue("write", context)
1642
+ },
1643
+ force: {
1644
+ usage: "<expression> <value>",
1645
+ run: (context) => setValue("force", context)
1646
+ },
1647
+ unforce: {
1648
+ usage: "[expression]... [--restore]",
1649
+ run: async ({ args, flags, send }) => {
1650
+ await send({
1560
1651
  command: "unforce",
1561
1652
  expressions: args,
1562
1653
  restore: flags.restore ?? false
1563
1654
  });
1564
- case "start":
1565
- expect(0, "");
1566
- return send({ command: "start" });
1567
- case "stop":
1568
- expect(0, "");
1569
- if (!await confirm("Stop the application on the controller?", flags)) {
1570
- throw new Error("Cancelled.");
1655
+ return;
1656
+ }
1657
+ },
1658
+ start: {
1659
+ usage: "",
1660
+ run: async (context) => {
1661
+ none(context);
1662
+ await context.send({ command: "start" });
1663
+ return;
1664
+ }
1665
+ },
1666
+ stop: {
1667
+ usage: "",
1668
+ run: async (context) => {
1669
+ none(context);
1670
+ await confirmOrCancel("Stop the application on the controller?", context.flags);
1671
+ await context.send({ command: "stop" });
1672
+ return;
1673
+ }
1674
+ },
1675
+ reset: {
1676
+ usage: "warm|cold",
1677
+ run: async ({ args, flags, send, usage }) => {
1678
+ if (args.length !== 1) {
1679
+ usage();
1571
1680
  }
1572
- return send({ command: "stop" });
1573
- case "restart": {
1681
+ const kind = controllerRestartSchema2.shape.reset.parse(args[0]);
1682
+ await confirmOrCancel(`Reset the application (${kind})? It stops and reinitializes its variables.`, flags);
1683
+ await send({ command: "reset", kind: resetLabel2(kind) });
1684
+ return;
1685
+ }
1686
+ },
1687
+ restart: {
1688
+ usage: "[warm|cold] [-y]",
1689
+ run: async ({ agent, args, flags, usage }) => {
1574
1690
  if (args.length > 1) {
1575
- throw new Error("Usage: tsplc restart [warm|cold] [-y]");
1576
- }
1577
- const reset = z5.enum(["warm", "cold"]).parse(args[0] ?? "warm");
1578
- if (!await confirm(`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === "warm" ? ", but for retain ones" : ""}.`, flags)) {
1579
- throw new Error("Cancelled.");
1691
+ usage();
1580
1692
  }
1693
+ const reset = controllerRestartSchema2.shape.reset.parse(args[0] ?? "warm");
1694
+ await confirmOrCancel(`Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === "warm" ? ", but for retain ones" : ""}.`, flags);
1581
1695
  const { state } = await agent.restartController({ reset });
1582
1696
  console.log(`Reset ${reset}; the application is ${state === "run" ? "running" : state}.`);
1583
1697
  return;
1584
1698
  }
1585
- case "reset": {
1586
- expect(1, "warm|cold");
1587
- const kind = z5.enum(["warm", "cold"]).parse(args[0]);
1588
- if (!await confirm(`Reset the application (${kind})? It stops and reinitializes its variables.`, flags)) {
1589
- throw new Error("Cancelled.");
1590
- }
1591
- return send({
1592
- command: "reset",
1593
- kind: kind === "warm" ? "Warm" : "Cold"
1594
- });
1595
- }
1596
1699
  }
1597
1700
  };
1701
+ async function setValue(command, { args: [expression, value, ...extra], send, usage }) {
1702
+ if (!expression || !value || extra.length) {
1703
+ return usage();
1704
+ }
1705
+ await send({ command, values: { [expression]: value } });
1706
+ return;
1707
+ }
1708
+ var isPlantCommand = (name) => Object.hasOwn(plantCommands, name);
1709
+ var runPlantCommand = (agent, command, args, flags, project) => {
1710
+ const entry = plantCommands[command];
1711
+ const approval = {
1712
+ yes: flags.yes ?? false,
1713
+ interactive: project.interactive,
1714
+ confirm
1715
+ };
1716
+ return entry.run({
1717
+ agent,
1718
+ args,
1719
+ flags,
1720
+ project,
1721
+ follow: { wait: flags.wait ?? false, approval },
1722
+ usage: () => {
1723
+ throw new Error(`Usage: tsplc ${command} ${entry.usage}`);
1724
+ },
1725
+ send: async (loginCommand) => {
1726
+ await ensureLogin(agent, project.environment);
1727
+ printLogin(await agent.command(loginCommand));
1728
+ }
1729
+ });
1730
+ };
1598
1731
 
1599
1732
  // packages/compiler/src/project/project-commands.ts
1600
1733
  import { resolve as resolve5 } from "node:path";
1601
1734
  import {
1602
- buildProject as buildSt,
1603
1735
  checkRawSources,
1736
+ compileStructuredText,
1604
1737
  configureDocker,
1605
1738
  configureRuntime,
1606
1739
  inspectProjectController,
@@ -1614,7 +1747,7 @@ import { hasErrors as hasErrors3 } from "@tsplc/compiler/ir";
1614
1747
  import {
1615
1748
  buildTargetFor as buildTargetFor2,
1616
1749
  controllerFor as controllerFor2,
1617
- loadTsplcConfig as loadTsplcConfig2,
1750
+ loadTsplcConfig,
1618
1751
  rawBuildConfig
1619
1752
  } from "@tsplc/config";
1620
1753
  import { resolveConfig } from "@tsplc/config/build";
@@ -1622,27 +1755,20 @@ import { generateProject as generateProject2 } from "@tsplc/typegen";
1622
1755
 
1623
1756
  // packages/compiler/src/runtime/process.ts
1624
1757
  import { spawn as spawn2, spawnSync } from "node:child_process";
1625
- import { existsSync as existsSync4, openSync } from "node:fs";
1758
+ import { openSync } from "node:fs";
1626
1759
  import { mkdir as mkdir4, readFile as readFile2, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
1627
- import { join as join4, relative as relative3 } from "node:path";
1760
+ import { join as join4, relative as relative4 } from "node:path";
1628
1761
  import { setTimeout as delay } from "node:timers/promises";
1629
- import { fileURLToPath as fileURLToPath2 } from "node:url";
1762
+ import { fileURLToPath } from "node:url";
1630
1763
  import { progressLog } from "@tsplc/build";
1631
1764
  var startTimeoutMs = 60000;
1632
1765
  var stopTimeoutMs = 15000;
1633
- var runtimeScript = () => {
1634
- const script = ["./main.ts", "./bun-runtime.js"].map((path) => fileURLToPath2(new URL(path, import.meta.url))).find((path) => existsSync4(path));
1635
- if (!script) {
1636
- throw new Error("The Bun runtime's script is missing from this build.");
1637
- }
1638
- return script;
1639
- };
1640
1766
  var alive = (pid) => {
1641
1767
  try {
1642
1768
  process.kill(pid, 0);
1643
1769
  return true;
1644
- } catch {
1645
- return false;
1770
+ } catch (cause) {
1771
+ return cause instanceof Error && "code" in cause && cause.code === "EPERM";
1646
1772
  }
1647
1773
  };
1648
1774
  var isRuntime = (pid, launchFile) => {
@@ -1658,16 +1784,19 @@ var isRuntime = (pid, launchFile) => {
1658
1784
  return command.includes(launchFile);
1659
1785
  };
1660
1786
  var readState = async (file) => {
1661
- const text = await readFile2(file, "utf8").catch(() => {
1662
- return;
1787
+ const text = await readFile2(file, "utf8").catch((cause) => {
1788
+ if (isMissingFile(cause)) {
1789
+ return;
1790
+ }
1791
+ throw cause;
1663
1792
  });
1664
1793
  if (text === undefined) {
1665
1794
  return;
1666
1795
  }
1667
1796
  try {
1668
1797
  return runtimeStateSchema.parse(JSON.parse(text));
1669
- } catch {
1670
- return;
1798
+ } catch (cause) {
1799
+ throw new Error(`${file} is not a Bun runtime's state: delete it once no runtime runs.`, { cause });
1671
1800
  }
1672
1801
  };
1673
1802
  var stopRunning = async (directory, log) => {
@@ -1698,7 +1827,10 @@ var runInBun = async (options) => {
1698
1827
  await writeFile3(launchFile, `${JSON.stringify(options.launch, null, 2)}
1699
1828
  `);
1700
1829
  const logFile = join4(directory, runtimeFiles.log);
1701
- const command = [runtimeScript(), launchFile];
1830
+ const command = [
1831
+ fileURLToPath(import.meta.resolve("#bun-runtime")),
1832
+ launchFile
1833
+ ];
1702
1834
  if (options.foreground) {
1703
1835
  log("Running the program in Bun; stop it with Ctrl-C");
1704
1836
  const child = spawn2(process.execPath, command, {
@@ -1740,7 +1872,7 @@ var runInBun = async (options) => {
1740
1872
  const state = await readState(stateFile);
1741
1873
  if (state && state.pid === child.pid) {
1742
1874
  child.unref();
1743
- const shown = relative3(process.cwd(), logFile) || logFile;
1875
+ const shown = relative4(process.cwd(), logFile) || logFile;
1744
1876
  log(`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`);
1745
1877
  return { ...state, log: logFile };
1746
1878
  }
@@ -1759,19 +1891,19 @@ ${tail}`);
1759
1891
  };
1760
1892
 
1761
1893
  // packages/compiler/src/project/project-commands.ts
1762
- var projectCommands = [
1763
- "install",
1764
- "typegen",
1765
- "check",
1766
- "build",
1767
- "run",
1768
- "download",
1769
- "online-change",
1770
- "inspect",
1771
- "clean",
1772
- "configure"
1773
- ];
1774
- var projectCommand = (name) => projectCommands.find((command) => command === name);
1894
+ var projectOptions = {
1895
+ "emit-only": flag,
1896
+ read: { type: "string", multiple: true },
1897
+ "initialize-user": flag,
1898
+ "frozen-lockfile": flag,
1899
+ check: flag,
1900
+ plc: flag,
1901
+ server: flag,
1902
+ simulate: flag,
1903
+ runtime: flag,
1904
+ bun: flag,
1905
+ foreground: flag
1906
+ };
1775
1907
 
1776
1908
  class DiagnosticFailure extends Error {
1777
1909
  result;
@@ -1780,70 +1912,112 @@ class DiagnosticFailure extends Error {
1780
1912
  this.result = result;
1781
1913
  }
1782
1914
  }
1783
- var checkProjectFlags = (command, flags) => {
1784
- if (flags["emit-only"] && command !== "build") {
1785
- throw new Error("--emit-only is supported by build only.");
1786
- }
1787
- if (flags.target && (command === "configure" || command === "clean")) {
1788
- throw new Error("--target applies only to commands that read the config.");
1789
- }
1790
- if (flags.runtime && command !== "configure") {
1791
- throw new Error("--runtime applies only to configure.");
1792
- }
1793
- if (flags.bun && (command !== "run" || !flags.simulate)) {
1794
- throw new Error("--bun applies only to run --simulate: the Bun runtime has no fieldbus, so a plant simulator writes its inputs.");
1795
- }
1796
- if (flags.foreground && !flags.bun) {
1797
- throw new Error("--foreground applies only to run --simulate --bun.");
1798
- }
1799
- if ((flags.plc || flags.server) && command !== "build") {
1800
- throw new Error("--plc and --server apply only to build.");
1801
- }
1802
- if (flags.simulate && !["run", "download", "online-change"].includes(command)) {
1803
- throw new Error("--simulate applies only to run, download, online-change and deploy.");
1804
- }
1805
- if (flags.plc && flags.server) {
1806
- throw new Error("Choose --plc or --server, or omit both for a full build.");
1915
+ var restrictedFlags = [
1916
+ ["emit-only", "--emit-only is supported by build only."],
1917
+ ["target", "--target applies only to commands that read the config."],
1918
+ ["runtime", "--runtime applies only to configure."],
1919
+ [
1920
+ "bun",
1921
+ "--bun applies only to run --simulate: the Bun runtime has no fieldbus, so a plant simulator writes its inputs."
1922
+ ],
1923
+ ["foreground", "--foreground applies only to run --simulate --bun."],
1924
+ ["plc", "--plc and --server apply only to build."],
1925
+ ["server", "--plc and --server apply only to build."],
1926
+ [
1927
+ "simulate",
1928
+ "--simulate applies only to run, download, online-change and deploy."
1929
+ ],
1930
+ ["check", "--check applies only to typegen."],
1931
+ ["read", "--read applies only to inspect, download and online-change."],
1932
+ [
1933
+ "frozen-lockfile",
1934
+ "--frozen-lockfile applies only to install, build, run, download, online-change and deploy."
1935
+ ],
1936
+ ["initialize-user", "--initialize-user applies only to download and deploy."],
1937
+ ["download", "--download applies only to deploy."],
1938
+ ["select", "--select applies only to deploy."],
1939
+ ["review", "--review applies only to deploy and redeploy."],
1940
+ ["wait", "--wait applies only to deploy, rollback and redeploy."],
1941
+ ["restore", "--restore applies only to unforce."],
1942
+ ["yes", "-y applies only to plant agent commands."],
1943
+ ["port", "--port applies only to debug."],
1944
+ ["server-url", "--server-url applies only to debug."],
1945
+ ["opcua", "--opcua applies only to debug."]
1946
+ ];
1947
+ var prerequisites = {
1948
+ bun: "simulate",
1949
+ foreground: "bun"
1950
+ };
1951
+ var projectCommands = {
1952
+ install: {
1953
+ takes: ["target", "frozen-lockfile"],
1954
+ run: async ({ load, flags }) => install(await load(), flags)
1955
+ },
1956
+ typegen: {
1957
+ takes: ["target", "check"],
1958
+ run: async ({ load, flags }) => typegen(await load(), flags)
1959
+ },
1960
+ check: {
1961
+ takes: ["target"],
1962
+ run: async ({ file, load }) => check(await loadCheckedConfig(file, load))
1963
+ },
1964
+ build: {
1965
+ takes: ["target", "emit-only", "plc", "server", "frozen-lockfile"],
1966
+ check: (flags) => {
1967
+ if (flags.plc && flags.server) {
1968
+ throw new Error("Choose --plc or --server, or omit both for a full build.");
1969
+ }
1970
+ if (flags.server && flags["emit-only"]) {
1971
+ throw new Error("--emit-only applies to PLC emission only.");
1972
+ }
1973
+ },
1974
+ run: async ({ file, load, flags, progress }) => build(await loadCheckedConfig(file, load), flags, progress)
1975
+ },
1976
+ run: {
1977
+ takes: ["target", "simulate", "bun", "foreground", "frozen-lockfile"],
1978
+ run: async ({ file, load, flags, progress }) => run(await loadCheckedConfig(file, load), flags, progress)
1979
+ },
1980
+ download: {
1981
+ takes: ["target", "simulate", "read", "frozen-lockfile", "initialize-user"],
1982
+ run: async ({ file, load, flags, progress }) => updateProgram("download", await loadCheckedConfig(file, load), flags, progress)
1983
+ },
1984
+ "online-change": {
1985
+ takes: ["target", "simulate", "read", "frozen-lockfile"],
1986
+ run: async ({ file, load, flags, progress }) => updateProgram("online-change", await loadCheckedConfig(file, load), flags, progress)
1987
+ },
1988
+ inspect: {
1989
+ takes: ["target", "read"],
1990
+ run: async ({ load, flags, progress }) => inspectProjectController(await load(), flags.read, { progress })
1991
+ },
1992
+ clean: { takes: [], run: ({ file }) => cleanProject(file) },
1993
+ configure: {
1994
+ takes: ["runtime"],
1995
+ run: ({ flags, progress, environment }) => configure(flags, progress, environment)
1807
1996
  }
1808
- if (flags.server && flags["emit-only"]) {
1809
- throw new Error("--emit-only applies to PLC emission only.");
1997
+ };
1998
+ var isProjectCommand = (name) => Object.hasOwn(projectCommands, name);
1999
+ var checkProjectFlags = (command, flags) => {
2000
+ const entry = projectCommands[command];
2001
+ for (const [name, message] of restrictedFlags) {
2002
+ const prerequisite = prerequisites[name];
2003
+ const applies = entry.takes.includes(name) && (prerequisite === undefined || flags[prerequisite]);
2004
+ if (flags[name] && !applies) {
2005
+ throw new Error(message);
2006
+ }
1810
2007
  }
2008
+ entry.check?.(flags);
1811
2009
  };
1812
- var runProjectCommand = async (command, file, flags, environment) => {
1813
- const context = {
1814
- progress: flags.format === "json" ? "stderr" : "stdout",
1815
- environment
1816
- };
1817
- const { progress } = context;
1818
- const load = () => loadTsplcConfig2(file, {
2010
+ var runProjectCommand = (command, file, flags, environment) => projectCommands[command].run({
2011
+ file,
2012
+ flags,
2013
+ environment,
2014
+ progress: flags.format === "json" ? "stderr" : "stdout",
2015
+ load: () => loadTsplcConfig(file, {
1819
2016
  env: environment,
1820
2017
  target: flags.target,
1821
2018
  forAgent: false
1822
- });
1823
- switch (command) {
1824
- case "configure":
1825
- return configure(flags, progress);
1826
- case "clean":
1827
- return cleanProject(file);
1828
- case "install":
1829
- return install(await load(), flags);
1830
- case "typegen":
1831
- return typegen(file, await load(), flags, environment);
1832
- case "check":
1833
- return check(file, await loadCheckedConfig(file, load), environment);
1834
- case "build":
1835
- return build(file, await loadCheckedConfig(file, load), flags, context);
1836
- case "run":
1837
- return run(file, await loadCheckedConfig(file, load), flags, context);
1838
- case "inspect":
1839
- return inspectProjectController(await load(), flags.read, {
1840
- progress
1841
- });
1842
- case "download":
1843
- case "online-change":
1844
- return updateProgram(command, file, await loadCheckedConfig(file, load), flags, context);
1845
- }
1846
- };
2019
+ })
2020
+ });
1847
2021
  var loadCheckedConfig = async (file, load) => {
1848
2022
  const hostConfigDiagnostics = checkHostConfig2(resolve5(file));
1849
2023
  if (hasErrors3(hostConfigDiagnostics)) {
@@ -1851,8 +2025,11 @@ var loadCheckedConfig = async (file, load) => {
1851
2025
  }
1852
2026
  return { loaded: await load(), hostConfigDiagnostics };
1853
2027
  };
1854
- var configure = async (flags, progress) => {
1855
- await (flags.runtime ? configureRuntime({ progress }) : configureDocker({ progress }));
2028
+ var configure = async (flags, progress, environment) => {
2029
+ await (flags.runtime ? configureRuntime({ progress }) : configureDocker({
2030
+ progress,
2031
+ winetricksCache: environment.CODESYS_WINETRICKS_CACHE || null
2032
+ }));
1856
2033
  return { ok: true };
1857
2034
  };
1858
2035
  var install = async ({ config, root }, flags) => ({
@@ -1860,33 +2037,39 @@ var install = async ({ config, root }, flags) => ({
1860
2037
  frozen: flags["frozen-lockfile"]
1861
2038
  })
1862
2039
  });
1863
- var typegen = async (file, loaded, flags, environment) => {
1864
- const targets = await projectTargets(file, { loaded, environment });
1865
- if (loaded.config.compiler && !flags.check) {
1866
- await generateProject2(file, { hardwareOnly: true, loaded, targets });
1867
- const emitted = await buildProject(file, {
2040
+ var typegen = async (loaded, flags) => {
2041
+ const targets = await projectTargets(loaded.configFile, loaded);
2042
+ if (loaded.config.compiler) {
2043
+ if (!flags.check) {
2044
+ await generateProject2(loaded, { hardwareOnly: true, targets });
2045
+ }
2046
+ const emitted = await buildTypeScriptProject(loaded.configFile, {
1868
2047
  emitOnly: true,
1869
2048
  loaded,
1870
- environment
2049
+ hostConfigDiagnostics: checkHostConfig2(loaded.configFile)
1871
2050
  });
1872
2051
  if (hasErrors3(emitted.diagnostics)) {
1873
2052
  throw new DiagnosticFailure(emitted);
1874
2053
  }
1875
2054
  }
1876
- return generateProject2(file, { check: flags.check, loaded, targets });
2055
+ const { catalog, io, files } = await generateProject2(loaded, {
2056
+ check: flags.check,
2057
+ targets
2058
+ });
2059
+ return { catalog, io, files };
1877
2060
  };
1878
- var check = async (file, { loaded, hostConfigDiagnostics }, environment) => {
1879
- if (loaded.config.compiler) {
1880
- return checkProject(file, { loaded, hostConfigDiagnostics, environment });
2061
+ var check = async (checked) => {
2062
+ if (checked.loaded.config.compiler) {
2063
+ const { configFile, diagnostics } = await checkProject(checked.loaded.configFile, checked);
2064
+ return { configFile, diagnostics };
1881
2065
  }
1882
- return { objects: (await checkRawSources(loaded)).objects.length };
2066
+ return { objects: (await checkRawSources(checked.loaded)).objects.length };
1883
2067
  };
1884
- var buildPlc = async (command, file, { loaded, hostConfigDiagnostics }, flags, { progress, environment }) => {
1885
- const { config } = loaded;
2068
+ var buildPlc = async (command, { loaded, hostConfigDiagnostics }, flags, progress) => {
2069
+ const { config, configFile } = loaded;
1886
2070
  if (config.compiler) {
1887
- const { targets, services, ...built } = await buildProject(file, {
2071
+ const { targets, services, ...built } = await buildTypeScriptProject(configFile, {
1888
2072
  progress,
1889
- environment,
1890
2073
  emitOnly: flags["emit-only"],
1891
2074
  frozenLockfile: flags["frozen-lockfile"],
1892
2075
  ...buildConfigs(loaded, flags),
@@ -1897,54 +2080,51 @@ var buildPlc = async (command, file, { loaded, hostConfigDiagnostics }, flags, {
1897
2080
  if (hasErrors3(built.diagnostics)) {
1898
2081
  throw new DiagnosticFailure(built);
1899
2082
  }
1900
- await generateProject2(file, { loaded, targets });
2083
+ await generateProject2(loaded, { targets });
1901
2084
  return { built, services };
1902
2085
  }
1903
2086
  if (flags["emit-only"]) {
1904
2087
  throw new Error("Raw Structured Text is already emitted.");
1905
2088
  }
1906
- const built = await buildSt(await rawEngineeringSettings(loaded, {
2089
+ const built = await compileStructuredText(await rawEngineeringSettings(loaded, {
1907
2090
  command,
1908
2091
  frozenLockfile: flags["frozen-lockfile"],
1909
2092
  simulate: flags.simulate
1910
2093
  }), { progress });
1911
- await generateProject2(file, { hardwareOnly: !config.typegen, loaded });
2094
+ await generateProject2(loaded);
1912
2095
  return { built, services: undefined };
1913
2096
  };
1914
- var build = async (file, checked, flags, context) => {
2097
+ var build = async (checked, flags, progress) => {
1915
2098
  const { config, root } = checked.loaded;
1916
2099
  if (flags.server) {
1917
2100
  return buildServer(await checkServer(config, root), config, root);
1918
2101
  }
1919
2102
  const withServer = !flags.plc && !flags["emit-only"] && config.server?.runtime;
1920
- const serverCheck = withServer ? checkServer(config, root) : undefined;
1921
- serverCheck?.catch(() => {
1922
- return;
1923
- });
1924
- const { built: plc } = await buildPlc("build", file, checked, flags, context);
2103
+ const serverCheck = withServer ? startServerCheck(config, root) : undefined;
2104
+ const { built: plc } = await buildPlc("build", checked, flags, progress);
1925
2105
  if (!serverCheck) {
1926
2106
  return plc;
1927
2107
  }
1928
2108
  return { ...plc, ...await buildServer(await serverCheck, config, root) };
1929
2109
  };
1930
- var run = async (file, checked, flags, context) => {
2110
+ var run = async (checked, flags, progress) => {
1931
2111
  if (flags.bun) {
1932
- return runInBunRuntime(file, checked, flags, context);
2112
+ return runInBunRuntime(checked, flags, progress);
1933
2113
  }
1934
2114
  const { config, configFile } = checked.loaded;
1935
- const { built } = await buildPlc("run", file, checked, flags, context);
2115
+ const { built } = await buildPlc("run", checked, flags, progress);
1936
2116
  if (!config.build) {
1937
2117
  throw new Error("Configure build to run this project.");
1938
2118
  }
1939
- await runProject(resolveConfig(config.compiler ? config.build : rawBuildConfig(config), configFile), config.name, { progress: context.progress });
2119
+ await runProject(resolveConfig(config.compiler ? config.build : rawBuildConfig(config), configFile), config.name, { progress });
1940
2120
  return built;
1941
2121
  };
1942
- var runInBunRuntime = async (file, checked, flags, context) => {
1943
- const { config, configFile, root } = checked.loaded;
2122
+ var runInBunRuntime = async (checked, flags, progress) => {
2123
+ const { config, configFile, env, root } = checked.loaded;
1944
2124
  if (!config.compiler) {
1945
2125
  throw new Error("The Bun runtime runs a TypeScript program; this project builds raw Structured Text.");
1946
2126
  }
1947
- const { built, services } = await buildPlc("run", file, checked, { ...flags, "emit-only": true }, context);
2127
+ const { built, services } = await buildPlc("run", checked, { ...flags, "emit-only": true }, progress);
1948
2128
  const runtime = await runInBun({
1949
2129
  root,
1950
2130
  launch: {
@@ -1952,18 +2132,18 @@ var runInBunRuntime = async (file, checked, flags, context) => {
1952
2132
  target: flags.target ?? null,
1953
2133
  services: services ?? {}
1954
2134
  },
1955
- environment: context.environment,
2135
+ environment: env,
1956
2136
  foreground: flags.foreground ?? false,
1957
- progress: context.progress
2137
+ progress
1958
2138
  });
1959
2139
  return { ...built, runtime };
1960
2140
  };
1961
- var updateProgram = async (operation, file, checked, flags, { progress, environment }) => {
1962
- const { config } = checked.loaded;
2141
+ var updateProgram = async (operation, checked, flags, progress) => {
2142
+ const { config, env } = checked.loaded;
1963
2143
  if (!config.build) {
1964
2144
  throw new Error("Configure build settings and controller connection.");
1965
2145
  }
1966
- const settings = config.compiler ? await emittedControllerSettings(operation, file, checked, flags, environment) : await rawEngineeringSettings(checked.loaded, {
2146
+ const settings = config.compiler ? await emittedControllerSettings(operation, checked, flags) : await rawEngineeringSettings(checked.loaded, {
1967
2147
  command: operation,
1968
2148
  frozenLockfile: flags["frozen-lockfile"],
1969
2149
  simulate: flags.simulate
@@ -1971,14 +2151,14 @@ var updateProgram = async (operation, file, checked, flags, { progress, environm
1971
2151
  return updateController(settings, operation, {
1972
2152
  initializeUser: flags["initialize-user"],
1973
2153
  read: flags.read,
1974
- progress
2154
+ progress,
2155
+ environment: env
1975
2156
  });
1976
2157
  };
1977
- var emittedControllerSettings = async (operation, file, { loaded, hostConfigDiagnostics }, flags, environment) => {
1978
- const emitted = await buildProject(file, {
2158
+ var emittedControllerSettings = async (operation, { loaded, hostConfigDiagnostics }, flags) => {
2159
+ const emitted = await buildTypeScriptProject(loaded.configFile, {
1979
2160
  emitOnly: true,
1980
2161
  forController: true,
1981
- environment,
1982
2162
  frozenLockfile: flags["frozen-lockfile"],
1983
2163
  ...buildConfigs(loaded, flags),
1984
2164
  hostConfigDiagnostics,
@@ -1991,16 +2171,17 @@ var emittedControllerSettings = async (operation, file, { loaded, hostConfigDiag
1991
2171
  if (!emitted.controllerConfig) {
1992
2172
  throw new Error("Configure build settings for deployment.");
1993
2173
  }
1994
- return { ...emitted.controllerConfig, io: {} };
2174
+ return emitted.controllerConfig;
1995
2175
  };
1996
2176
 
1997
2177
  // packages/compiler/src/project/cli.ts
1998
- var usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config tsplc.config.ts] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
2178
+ var usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config ${configFileName2}] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
2179
+ [--frozen-lockfile] [--check] [--initialize-user]
1999
2180
 
2000
- Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:4840:
2181
+ Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:${opcuaPort}:
2001
2182
  tsplc run --simulate --bun [--foreground] [--target name]
2002
2183
 
2003
- Plant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):
2184
+ Plant agent (the target's agent, else ${agentUrlEnv4}; ${agentTokenEnv3}):
2004
2185
  tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]
2005
2186
  tsplc deployments [--format json] | dashboard
2006
2187
  tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]
@@ -2011,10 +2192,18 @@ Plant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):
2011
2192
  tsplc start | stop | reset warm|cold (-y skips confirmations)
2012
2193
  tsplc restart [warm|cold] resets and starts the application, with or without a login
2013
2194
 
2014
- Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
2015
- the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
2016
- tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;
2017
- var formatSchema = z6.enum(["json", "text"]).optional();
2195
+ Debugger, on http://127.0.0.1, for the built ${emittedStDirectory4}/${debugManifestFile4}; it reads through
2196
+ the plant agent's login (${agentUrlEnv4}, ${agentTokenEnv3}), or --opcua at config monitor:
2197
+ tsplc debug ${debugUsage}`;
2198
+ var options = {
2199
+ config: { type: "string" },
2200
+ target: { type: "string" },
2201
+ help: { type: "boolean", short: "h" },
2202
+ format: { type: "string" },
2203
+ ...projectOptions,
2204
+ ...plantOptions,
2205
+ ...debugOptions
2206
+ };
2018
2207
  var requestedFormat = (argv) => {
2019
2208
  const index = argv.findIndex((argument) => argument === "--format" || argument.startsWith("--format="));
2020
2209
  const flag = argv[index];
@@ -2024,92 +2213,67 @@ var requestedFormat = (argv) => {
2024
2213
  return flag === "--format" ? argv[index + 1] : flag.slice("--format=".length);
2025
2214
  };
2026
2215
  var outputFormat = (format) => {
2027
- const parsed = formatSchema.safeParse(format);
2216
+ const parsed = outputFormatSchema2.optional().safeParse(format);
2028
2217
  if (!parsed.success) {
2029
2218
  throw new Error("--format must be json or text.");
2030
2219
  }
2031
2220
  return parsed.data;
2032
2221
  };
2222
+ var debug = async (args, values, file) => {
2223
+ if (args.length) {
2224
+ throw new Error(`Usage: tsplc debug ${debugUsage}`);
2225
+ }
2226
+ await serveProjectDebugger(await loadTsplcConfig2(file, {
2227
+ env: process.env,
2228
+ target: values.target,
2229
+ forAgent: false
2230
+ }), values);
2231
+ return 0;
2232
+ };
2233
+ var plant = async (command, args, values, file) => {
2234
+ const load = () => loadTsplcConfig2(file, {
2235
+ env: process.env,
2236
+ target: values.target,
2237
+ forAgent: true
2238
+ });
2239
+ const loaded = existsSync3(file) ? await load() : undefined;
2240
+ const env = loaded?.env ?? process.env;
2241
+ const outcome = await runPlantCommand(connect2(env), command, args, values, {
2242
+ load: loaded ? async () => loaded : load,
2243
+ environment: env,
2244
+ interactive: process.stdin.isTTY === true
2245
+ });
2246
+ if (!outcome) {
2247
+ return 0;
2248
+ }
2249
+ return "exitCode" in outcome ? outcome.exitCode : report(outcome, values.format);
2250
+ };
2033
2251
  async function main() {
2034
2252
  const { values: parsed, positionals } = parseArgs({
2035
2253
  allowPositionals: true,
2036
- options: {
2037
- config: { type: "string" },
2038
- target: { type: "string" },
2039
- help: { type: "boolean", short: "h" },
2040
- "emit-only": { type: "boolean" },
2041
- format: { type: "string" },
2042
- read: { type: "string", multiple: true },
2043
- "initialize-user": { type: "boolean" },
2044
- "frozen-lockfile": { type: "boolean" },
2045
- check: { type: "boolean" },
2046
- plc: { type: "boolean" },
2047
- server: { type: "boolean" },
2048
- simulate: { type: "boolean" },
2049
- runtime: { type: "boolean" },
2050
- bun: { type: "boolean" },
2051
- foreground: { type: "boolean" },
2052
- download: { type: "boolean" },
2053
- restore: { type: "boolean" },
2054
- select: { type: "boolean" },
2055
- yes: { type: "boolean", short: "y" },
2056
- port: { type: "string" },
2057
- "server-url": { type: "string" },
2058
- opcua: { type: "boolean" },
2059
- review: { type: "boolean" },
2060
- wait: { type: "boolean" }
2061
- }
2254
+ options
2062
2255
  });
2063
- const values = {
2064
- ...parsed,
2065
- format: outputFormat(parsed.format)
2066
- };
2256
+ const values = { ...parsed, format: outputFormat(parsed.format) };
2067
2257
  const [name, ...args] = positionals;
2068
- const file = values.config ?? "tsplc.config.ts";
2258
+ const file = values.config ?? configFileName2;
2069
2259
  if (!name || values.help) {
2070
2260
  console.log(usage);
2071
2261
  return 0;
2072
2262
  }
2073
2263
  if (name === "debug") {
2074
- if (args.length) {
2075
- throw new Error("Usage: tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]");
2076
- }
2077
- await serveProjectDebugger(await loadTsplcConfig3(file, {
2078
- env: process.env,
2079
- target: values.target,
2080
- forAgent: false
2081
- }), values);
2082
- return 0;
2264
+ return debug(args, values, file);
2083
2265
  }
2084
- const plant = plantCommand(name);
2085
- if (plant) {
2086
- const load = () => loadTsplcConfig3(file, {
2087
- env: process.env,
2088
- target: values.target,
2089
- forAgent: true
2090
- });
2091
- const loaded = existsSync5(file) ? await load() : undefined;
2092
- const env = loaded?.env ?? process.env;
2093
- const outcome = await runPlantCommand(connect2(env), plant, args, values, {
2094
- file,
2095
- load: loaded ? async () => loaded : load,
2096
- environment: env,
2097
- interactive: process.stdin.isTTY === true
2098
- });
2099
- if (!outcome) {
2100
- return 0;
2101
- }
2102
- return "exitCode" in outcome ? outcome.exitCode : report(outcome, values.format);
2266
+ if (isPlantCommand(name)) {
2267
+ return plant(name, args, values, file);
2103
2268
  }
2104
2269
  if (args.length) {
2105
2270
  throw new Error("Specify one command.");
2106
2271
  }
2107
- const command = projectCommand(name);
2108
- if (!command) {
2272
+ if (!isProjectCommand(name)) {
2109
2273
  throw new Error(`Unknown command ${name}.`);
2110
2274
  }
2111
- checkProjectFlags(command, values);
2112
- return report(await runProjectCommand(command, file, values, { ...process.env }), values.format);
2275
+ checkProjectFlags(name, values);
2276
+ return report(await runProjectCommand(name, file, values, process.env), values.format);
2113
2277
  }
2114
2278
  function report(result, format) {
2115
2279
  const diagnostics = result.diagnostics ?? [];
@@ -2120,12 +2284,21 @@ function report(result, format) {
2120
2284
  for (const diagnostic of diagnostics) {
2121
2285
  console.error(formatDiagnostic(diagnostic));
2122
2286
  }
2287
+ for (const [expression, value] of Object.entries(result.values ?? {})) {
2288
+ console.log(`${expression} = ${value}`);
2289
+ }
2123
2290
  if (ok) {
2124
2291
  console.log("tsPLC completed.");
2125
2292
  }
2126
2293
  }
2127
2294
  return ok ? 0 : 1;
2128
2295
  }
2296
+ function causeMessage(cause) {
2297
+ if (cause instanceof z8.ZodError) {
2298
+ return z8.prettifyError(cause);
2299
+ }
2300
+ return cause instanceof Error ? cause.message : String(cause);
2301
+ }
2129
2302
  try {
2130
2303
  process.exitCode = await main();
2131
2304
  } catch (cause) {
@@ -2133,7 +2306,7 @@ try {
2133
2306
  if (cause instanceof DiagnosticFailure) {
2134
2307
  process.exitCode = report(cause.result, json ? "json" : undefined);
2135
2308
  } else {
2136
- const message = cause instanceof Error ? cause.message : String(cause);
2309
+ const message = causeMessage(cause);
2137
2310
  if (json) {
2138
2311
  console.log(JSON.stringify({
2139
2312
  ok: false,
@@ -2148,5 +2321,5 @@ try {
2148
2321
  }
2149
2322
  }
2150
2323
 
2151
- //# debugId=4E4AFC84CE5CE5BF64756E2164756E21
2324
+ //# debugId=7351DCADA818881664756E2164756E21
2152
2325
  //# sourceMappingURL=cli.js.map