@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

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 (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
package/dist/cli.js ADDED
@@ -0,0 +1,2325 @@
1
+ #!/usr/bin/env bun
2
+ // @bun
3
+
4
+ // packages/compiler/src/project/cli.ts
5
+ import { existsSync as existsSync3 } from "fs";
6
+ import { parseArgs } from "util";
7
+ import { formatDiagnostic, hasErrors as hasErrors4 } from "@tsplc/compiler/ir";
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";
16
+
17
+ // packages/compiler/src/project/debugger.ts
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";
25
+ import { tcpPort } from "@tsplc/config/build";
26
+ import {
27
+ emittedStDirectory as emittedStDirectory3,
28
+ generatedDirectory as generatedDirectory4
29
+ } from "@tsplc/config/project-files";
30
+ import {
31
+ createDebugger,
32
+ createOpcUaAdapter,
33
+ loadDebugBuild,
34
+ loginReader,
35
+ opcUaConnection,
36
+ serveDebugger
37
+ } from "@tsplc/debug";
38
+ import { debugManifestFile as debugManifestFile3 } from "@tsplc/debug/manifest";
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
+
45
+ // packages/compiler/src/project/plant.ts
46
+ import {
47
+ ask as ask2,
48
+ askCredentials
49
+ } from "@tsplc/agent";
50
+ import { createAgentClient } from "@tsplc/agent/client";
51
+ import { resetLabel } from "@tsplc/build";
52
+ import {
53
+ agentTokenEnv,
54
+ agentUrlEnv,
55
+ releaseEnvironment
56
+ } from "@tsplc/config";
57
+ import { runtimePort } from "@tsplc/config/build";
58
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
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";
63
+
64
+ // packages/compiler/src/project/deployments.ts
65
+ import { spawn } from "node:child_process";
66
+ import { AgentUnreachable } from "@tsplc/agent/client";
67
+ import { describeFinding } from "@tsplc/build";
68
+
69
+ // packages/compiler/src/project/terminal.ts
70
+ import { ask } from "@tsplc/agent";
71
+ var choose = async (question, items, label) => {
72
+ items.forEach((item, index) => {
73
+ console.log(` ${index + 1}. ${label(item)}`);
74
+ });
75
+ while (true) {
76
+ const item = items[Number(await ask(`${question} [1-${items.length}]: `)) - 1];
77
+ if (item !== undefined) {
78
+ return item;
79
+ }
80
+ }
81
+ };
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
+ };
88
+ var progress = (message) => console.log(` ${message}`);
89
+ var timedProgress = () => {
90
+ const start = Date.now();
91
+ return (message) => {
92
+ const seconds = Math.round((Date.now() - start) / 1000);
93
+ progress(`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} ${message}`);
94
+ };
95
+ };
96
+
97
+ // packages/compiler/src/project/deployments.ts
98
+ var awaitingApprovalExit = 2;
99
+ var reconnectAttempts = 5;
100
+ var reconnectDelay = 1000;
101
+ var stateMessage = (record) => {
102
+ switch (record.state) {
103
+ case "queued":
104
+ return "Queued.";
105
+ case "building":
106
+ return "Building the release…";
107
+ case "applying":
108
+ return record.operation === "download" ? "Downloading the program; the application stops while it loads…" : "Applying the online change…";
109
+ case "starting":
110
+ return "Starting the server…";
111
+ case "verifying":
112
+ return "Checking the deployment's health…";
113
+ default:
114
+ return;
115
+ }
116
+ };
117
+ var printFindings = (record) => {
118
+ if (!record.findings.length) {
119
+ progress("No findings.");
120
+ return;
121
+ }
122
+ for (const finding of record.findings) {
123
+ progress(`${finding.refuses ? "refuses" : "note"}: ${describeFinding(finding)}`);
124
+ }
125
+ };
126
+ var decide = async (approval, question) => {
127
+ if (approval.yes) {
128
+ return true;
129
+ }
130
+ if (!approval.interactive) {
131
+ return null;
132
+ }
133
+ return approval.confirm(question);
134
+ };
135
+ var approve = async (agent, record, reason, { url, approval }) => {
136
+ const download = reason === "downloadRequired";
137
+ if (download) {
138
+ console.log("Only a full download can deploy this release, and a full download stops the running application while it loads.");
139
+ } else {
140
+ console.log("The review found what the online change would do:");
141
+ }
142
+ printFindings(record);
143
+ const approved = await decide(approval, download ? "Download now?" : "Apply it?");
144
+ if (!approved) {
145
+ console.log(approved === null ? `It waits for approval on the dashboard: ${url}` : `It waits for approval or cancellation on the dashboard: ${url}`);
146
+ return false;
147
+ }
148
+ await agent.approve(record.id, { download });
149
+ console.log(download ? "Approved the full download." : "Approved.");
150
+ return true;
151
+ };
152
+ var followDeployment = async (agent, deployment, approval) => {
153
+ const seen = { after: 0, state: null, approval: null, failures: 0 };
154
+ const onRecord = async (record) => {
155
+ if (record.state !== seen.state) {
156
+ seen.state = record.state;
157
+ const message = stateMessage(record);
158
+ if (message) {
159
+ console.log(message);
160
+ }
161
+ }
162
+ if (record.state !== "awaitingApproval" || !record.approval) {
163
+ seen.approval = null;
164
+ } else {
165
+ const asked = `${record.approval.reason}: ${record.approval.message}`;
166
+ if (asked !== seen.approval) {
167
+ seen.approval = asked;
168
+ console.log(record.approval.message);
169
+ const approved = await approve(agent, record, record.approval.reason, {
170
+ url: deployment.url,
171
+ approval
172
+ });
173
+ if (!approved) {
174
+ return awaitingApprovalExit;
175
+ }
176
+ }
177
+ }
178
+ if (record.state === "ready") {
179
+ const { health } = record;
180
+ console.log(health ? `Ready: controller ${health.controller}, server ${health.server}, PLC ${health.plc}.${health.detail ? ` ${health.detail}` : ""}` : "Ready.");
181
+ return 0;
182
+ }
183
+ if (record.state === "error") {
184
+ throw new Error(`The deployment failed: ${record.error?.message ?? "no reason given"}. ${deployment.url}`);
185
+ }
186
+ if (record.state === "canceled") {
187
+ throw new Error(`The deployment was canceled. ${deployment.url}`);
188
+ }
189
+ return;
190
+ };
191
+ while (true) {
192
+ try {
193
+ for await (const event of agent.deploymentEvents(deployment.id, seen.after)) {
194
+ seen.failures = 0;
195
+ if (event.kind === "record") {
196
+ const exit = await onRecord(event.record);
197
+ if (exit !== undefined) {
198
+ return exit;
199
+ }
200
+ } else if (event.line.seq > seen.after) {
201
+ seen.after = event.line.seq;
202
+ progress(event.line.level === "info" ? event.line.message : `${event.line.level}: ${event.line.message}`);
203
+ }
204
+ }
205
+ } catch (error) {
206
+ if (!(error instanceof AgentUnreachable)) {
207
+ throw error;
208
+ }
209
+ }
210
+ seen.failures += 1;
211
+ if (seen.failures > reconnectAttempts) {
212
+ throw new Error(`Lost the connection to the plant agent; the deployment goes on: ${deployment.url}`);
213
+ }
214
+ await Bun.sleep(reconnectDelay);
215
+ }
216
+ };
217
+ var queued = async (agent, created, follow) => {
218
+ console.log(`Deployment ${created.id} queued: ${created.url}`);
219
+ if (!follow.wait) {
220
+ return 0;
221
+ }
222
+ return followDeployment(agent, created, follow.approval);
223
+ };
224
+ var submitDeployment = async (agent, release, settings, request, follow) => {
225
+ const uploading = timedProgress();
226
+ const created = await agent.queueDeployment(release, { ...settings, deployment: request }, uploading);
227
+ uploading("Uploaded");
228
+ if (request.mode === "review" && !follow.wait) {
229
+ console.log("Once reviewed, it waits for approval on its page.");
230
+ }
231
+ return queued(agent, created, follow);
232
+ };
233
+ var rollbackTarget = ({
234
+ deployments,
235
+ current,
236
+ lastGood
237
+ }) => {
238
+ const index = deployments.findIndex(({ id }) => id === current);
239
+ const running = deployments[index];
240
+ if (!running) {
241
+ return deployments.find(({ id }) => id === lastGood);
242
+ }
243
+ return deployments.slice(index + 1).find((deployment) => deployment.state === "ready" && deployment.activeFrom !== null && deployment.release !== running.release);
244
+ };
245
+ var age = (from, now) => {
246
+ const seconds = Math.max(0, Math.round((now - Date.parse(from)) / 1000));
247
+ if (seconds < 60) {
248
+ return `${seconds}s`;
249
+ }
250
+ if (seconds < 3600) {
251
+ return `${Math.floor(seconds / 60)}m`;
252
+ }
253
+ if (seconds < 48 * 3600) {
254
+ return `${Math.floor(seconds / 3600)}h`;
255
+ }
256
+ return `${Math.floor(seconds / 86400)}d`;
257
+ };
258
+ var commitLabel = (git) => git ? `${git.commit.slice(0, 7)}${git.dirty ? "*" : ""}` : "-";
259
+ var requester = ({ requestedBy }) => requestedBy.user && requestedBy.host ? `${requestedBy.user}@${requestedBy.host}` : requestedBy.user ?? requestedBy.identity.name;
260
+ var printDeployments = async (agent, flags) => {
261
+ const list = await agent.deployments();
262
+ if (flags.format === "json") {
263
+ console.log(JSON.stringify({ ok: true, ...list }));
264
+ return;
265
+ }
266
+ if (!list.deployments.length) {
267
+ console.log("No deployments yet.");
268
+ return;
269
+ }
270
+ const now = Date.now();
271
+ const header = ["ID", "STATE", "AGE", "RELEASE", "COMMIT", "BY", ""];
272
+ const rows = [
273
+ header,
274
+ ...list.deployments.map((deployment) => [
275
+ deployment.id,
276
+ deployment.state,
277
+ age(deployment.createdAt, now),
278
+ deployment.release,
279
+ commitLabel(deployment.git),
280
+ requester(deployment),
281
+ [
282
+ deployment.id === list.current ? "current" : "",
283
+ deployment.id === list.lastGood ? "last good" : ""
284
+ ].filter(Boolean).join(", ")
285
+ ])
286
+ ];
287
+ const widths = header.map((_, column) => Math.max(...rows.map((row) => row[column]?.length ?? 0)));
288
+ for (const row of rows) {
289
+ console.log(row.map((cell, column) => cell.padEnd(widths[column] ?? 0)).join(" ").trimEnd());
290
+ }
291
+ };
292
+ var rollBack = async (agent, id, follow) => {
293
+ const target = id ?? rollbackTarget(await agent.deployments())?.id;
294
+ if (!target) {
295
+ throw new Error("No earlier healthy deployment to roll back to; name one: tsplc rollback <id>");
296
+ }
297
+ console.log(`Rolling back to ${target}…`);
298
+ return queued(agent, await agent.rollback(target), follow);
299
+ };
300
+ var redeploy = async (agent, id, mode, follow) => queued(agent, await agent.redeploy(id, mode), follow);
301
+ var openers = {
302
+ darwin: ["open"],
303
+ win32: ["cmd", "/c", "start", ""]
304
+ };
305
+ var openDashboard = (agent, interactive) => {
306
+ const url = new URL("/", agent.url).href;
307
+ console.log(url);
308
+ if (!interactive) {
309
+ return;
310
+ }
311
+ const [command = "xdg-open", ...args] = openers[process.platform] ?? [
312
+ "xdg-open"
313
+ ];
314
+ spawn(command, [...args, url], { stdio: "ignore", detached: true }).on("error", () => {}).unref();
315
+ };
316
+
317
+ // packages/compiler/src/project/git.ts
318
+ import { execFile } from "node:child_process";
319
+ var git = (directory, args) => new Promise((resolve) => {
320
+ execFile("git", args, { cwd: directory }, (error, stdout) => {
321
+ resolve(error ? null : stdout.trim());
322
+ });
323
+ });
324
+ var gitSource = async (directory) => {
325
+ const commit = await git(directory, ["rev-parse", "--verify", "HEAD"]);
326
+ if (!commit) {
327
+ return null;
328
+ }
329
+ const [branch, status, message] = await Promise.all([
330
+ git(directory, ["symbolic-ref", "--quiet", "--short", "HEAD"]),
331
+ git(directory, ["status", "--porcelain"]),
332
+ git(directory, ["log", "-1", "--format=%s"])
333
+ ]);
334
+ return {
335
+ commit,
336
+ branch: branch || null,
337
+ dirty: status !== "",
338
+ message: message || null
339
+ };
340
+ };
341
+
342
+ // packages/compiler/src/project/release.ts
343
+ import { basename as basename2, relative as relative2, resolve as resolve3, sep } from "node:path";
344
+ import { pathToFileURL } from "node:url";
345
+ import { checkHostConfig } from "@tsplc/compiler";
346
+ import { hasErrors as hasErrors2 } from "@tsplc/compiler/ir";
347
+ import {
348
+ buildTargetFor,
349
+ controllerFor,
350
+ serverTokenEnv
351
+ } from "@tsplc/config";
352
+ import { explainFileName as explainFileName2 } from "@tsplc/debug/explain-file";
353
+ import { debugManifestFile as debugManifestFile2 } from "@tsplc/debug/manifest";
354
+ import { contractVariables, plcContractSchema } from "@tsplc/opcua/contract";
355
+ import { generateProject } from "@tsplc/typegen";
356
+
357
+ // packages/compiler/src/project/project.ts
358
+ import {
359
+ copyFile,
360
+ mkdir as mkdir2,
361
+ mkdtemp,
362
+ realpath,
363
+ rm as rm2,
364
+ writeFile as writeFile2
365
+ } from "node:fs/promises";
366
+ import { basename, dirname as dirname2, join as join2, resolve } from "node:path";
367
+ import {
368
+ buildFiles,
369
+ installLibraries
370
+ } from "@tsplc/build";
371
+ import { analyze } from "@tsplc/compiler";
372
+ import {
373
+ buildCodesys,
374
+ codesysBuildConfig,
375
+ diagnoseCodesys,
376
+ emitCodesys,
377
+ ioTargets,
378
+ planCodesys,
379
+ publicationSelectors
380
+ } from "@tsplc/compiler/codesys";
381
+ import {
382
+ hasErrors,
383
+ normalizeModule
384
+ } from "@tsplc/compiler/ir";
385
+ import {
386
+ compilerConfig,
387
+ serverBaseUrl,
388
+ simulationConfig,
389
+ taskPlan
390
+ } from "@tsplc/config";
391
+ import {
392
+ configFileName,
393
+ emittedFiles,
394
+ emittedStDirectory as emittedStDirectory2
395
+ } from "@tsplc/config/project-files";
396
+ import { explainFileName } from "@tsplc/debug/explain-file";
397
+ import { debugManifestFile } from "@tsplc/debug/manifest";
398
+ import {
399
+ deviceTree,
400
+ loadHardware,
401
+ resolveIo
402
+ } from "@tsplc/typegen";
403
+
404
+ // packages/compiler/src/runtime/launch.ts
405
+ import { generatedDirectory } from "@tsplc/config/project-files";
406
+ import { serviceOfPath } from "@tsplc/server/wire";
407
+ import { z as z2 } from "zod";
408
+ var runtimeDirectory = `${generatedDirectory}/runtime`;
409
+ var runtimeFiles = {
410
+ launch: "launch.json",
411
+ state: "state.json",
412
+ retain: "retain.json",
413
+ log: "plc.log",
414
+ certificates: "pki"
415
+ };
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))
420
+ });
421
+ var runtimeStateSchema = z2.strictObject({
422
+ pid: z2.number().int().positive(),
423
+ endpoint: z2.string().startsWith("opc.tcp://"),
424
+ startedAt: z2.iso.datetime()
425
+ });
426
+ var blockRoute = (runtime) => {
427
+ if (runtime?.kind === "http") {
428
+ return URL.parse(runtime.url)?.pathname;
429
+ }
430
+ return runtime?.kind === "rpc" ? runtime.path : undefined;
431
+ };
432
+ var serviceRoutes = (core) => Object.fromEntries(core.blocks.flatMap((block) => {
433
+ const route = blockRoute(block.runtime);
434
+ const procedure = route && serviceOfPath(route);
435
+ return route && procedure ? [[procedure, route]] : [];
436
+ }));
437
+
438
+ // packages/compiler/src/project/artifacts.ts
439
+ import { createHash } from "node:crypto";
440
+ import {
441
+ lstat,
442
+ mkdir,
443
+ readdir,
444
+ readFile,
445
+ rename,
446
+ rm,
447
+ writeFile
448
+ } from "node:fs/promises";
449
+ import { dirname, join, relative } from "node:path";
450
+ import { cyclicTasksSchema, sha256Digest } from "@tsplc/config/build";
451
+ import {
452
+ emittedStDirectory,
453
+ generatedDirectory as generatedDirectory2
454
+ } from "@tsplc/config/project-files";
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
461
+ var digest = (value) => createHash("sha256").update(value).digest("hex");
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),
471
+ sha256: sha256Digest
472
+ });
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())
478
+ });
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()
486
+ });
487
+ var engineeringMarkerSchema = z3.object({
488
+ kind: z3.literal("tsplc-engineering"),
489
+ version: z3.literal(1),
490
+ configFile: z3.string()
491
+ });
492
+ function manifest(value, output, configFile) {
493
+ const parsed = manifestSchema.safeParse(value);
494
+ if (!parsed.success || !namesConfig(parsed.data.configFile, output, configFile)) {
495
+ throw new Error("Output directory has no matching tsPLC ownership manifest.");
496
+ }
497
+ const files = parsed.data.files.map((item) => {
498
+ const file = generatedFileSchema.safeParse(item);
499
+ if (!file.success) {
500
+ throw new Error("Invalid generated file ownership entry.");
501
+ }
502
+ return file.data;
503
+ });
504
+ if (new Set(files.map((item) => item.path)).size !== files.length) {
505
+ throw new Error("Duplicate generated file ownership entry.");
506
+ }
507
+ return { ...parsed.data, files };
508
+ }
509
+ async function directory(path) {
510
+ try {
511
+ const entry = await lstat(path);
512
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
513
+ throw new Error(`Generated directory must be a real directory: ${path}`);
514
+ }
515
+ return true;
516
+ } catch (cause) {
517
+ if (isMissingFile(cause)) {
518
+ return false;
519
+ }
520
+ throw cause;
521
+ }
522
+ }
523
+ async function filesIn(path, prefix = "") {
524
+ const result = [];
525
+ for (const entry of await readdir(path, { withFileTypes: true })) {
526
+ const name = prefix + entry.name;
527
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
528
+ result.push(...await filesIn(join(path, entry.name), `${name}/`));
529
+ } else {
530
+ result.push(name);
531
+ }
532
+ }
533
+ return result;
534
+ }
535
+ async function engineeringDirectory(path, configFile) {
536
+ const marker = join(path, artifactFiles.marker);
537
+ const exists = await directory(path);
538
+ if (!exists || !(await readdir(path)).length) {
539
+ await mkdir(path, { recursive: true });
540
+ await writeFile(marker, `${JSON.stringify({
541
+ kind: "tsplc-engineering",
542
+ version: 1,
543
+ configFile: configReference(path, configFile)
544
+ }, null, 2)}
545
+ `, { flag: "wx" });
546
+ } else if (!await ownedMarker(path, configFile)) {
547
+ throw new Error(`Engineering cache has no matching tsPLC ownership marker: ${path}`);
548
+ }
549
+ const inspect = async (directory) => {
550
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
551
+ const child = join(directory, entry.name);
552
+ if (entry.isSymbolicLink()) {
553
+ throw new Error(`Engineering cache must not contain symlinks: ${child}`);
554
+ }
555
+ if (entry.isDirectory()) {
556
+ await inspect(child);
557
+ }
558
+ }
559
+ };
560
+ await inspect(path);
561
+ }
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) {
580
+ const root = join(dirname(configFile), generatedDirectory2);
581
+ const output = join(dirname(configFile), dirname(emittedStDirectory));
582
+ if (!await directory(root) || !await directory(output)) {
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 };
594
+ }
595
+ if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
596
+ throw new Error("Ownership manifest must be a real file.");
597
+ }
598
+ const ownership = manifest(JSON.parse(await readFile(manifestPath, "utf8")), output, configFile);
599
+ const receipt = join(output, artifactFiles.receipt);
600
+ try {
601
+ const entry = await lstat(receipt);
602
+ if (!entry.isFile() || entry.isSymbolicLink()) {
603
+ throw new Error("Build receipt must be a real file.");
604
+ }
605
+ const value = receiptSchema.safeParse(JSON.parse(await readFile(receipt, "utf8")));
606
+ if (!value.success || !namesConfig(value.data.configFile, output, configFile)) {
607
+ throw new Error("Build receipt is not owned by this configuration.");
608
+ }
609
+ } catch (cause) {
610
+ if (!isMissingFile(cause)) {
611
+ throw cause;
612
+ }
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
+ }
624
+ const names = new Set([
625
+ ...ownership.files.map((file) => file.path),
626
+ artifactFiles.manifest,
627
+ artifactFiles.receipt
628
+ ]);
629
+ const checked = new Set;
630
+ for (const file of ownership.files) {
631
+ let parent = output;
632
+ for (const part of file.path.split("/").slice(0, -1)) {
633
+ parent = join(parent, part);
634
+ if (checked.has(parent)) {
635
+ continue;
636
+ }
637
+ if (!await directory(parent)) {
638
+ throw new Error(`Missing generated directory: ${parent}`);
639
+ }
640
+ checked.add(parent);
641
+ }
642
+ const path = join(output, file.path);
643
+ const entry = await lstat(path);
644
+ if (!entry.isFile() || entry.isSymbolicLink() || digest(await readFile(path)) !== file.sha256) {
645
+ throw new Error(`Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`);
646
+ }
647
+ }
648
+ return {
649
+ ...claim,
650
+ unknown: (await filesIn(output)).filter((name) => !names.has(name))
651
+ };
652
+ }
653
+ var withdrawReceipt = async ({
654
+ output
655
+ }) => {
656
+ await rm(join(output, artifactFiles.receipt), { force: true });
657
+ };
658
+ async function publishArtifacts(staging, previous, receipt) {
659
+ const configFile = configReference(previous.output, receipt.configFile);
660
+ const generated = (await filesIn(staging)).sort();
661
+ const ownership = {
662
+ kind: "tsplc-artifacts",
663
+ version: 1,
664
+ configFile,
665
+ files: []
666
+ };
667
+ for (const path of generated) {
668
+ ownership.files.push({
669
+ path,
670
+ sha256: digest(await readFile(join(staging, path)))
671
+ });
672
+ }
673
+ await writeFile(join(staging, artifactFiles.manifest), `${JSON.stringify(ownership, null, 2)}
674
+ `);
675
+ await writeFile(join(staging, artifactFiles.receipt), `${JSON.stringify({
676
+ kind: "tsplc-build",
677
+ version: 1,
678
+ generatedAt: new Date().toISOString(),
679
+ ...receipt,
680
+ configFile
681
+ }, null, 2)}
682
+ `);
683
+ const current = await owned(await claimed(receipt.configFile));
684
+ if (JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)) {
685
+ throw new Error("Output ownership changed during the build; preserve it before rebuilding.");
686
+ }
687
+ if (current.unknown.length) {
688
+ throw new Error(`Output contains unrelated files: ${current.unknown.join(", ")}`);
689
+ }
690
+ const backup = `${staging}-previous`;
691
+ if (previous.ownership) {
692
+ await rename(previous.output, backup);
693
+ }
694
+ try {
695
+ await rename(staging, previous.output);
696
+ } catch (cause) {
697
+ if (previous.ownership) {
698
+ await rename(backup, previous.output);
699
+ }
700
+ throw cause;
701
+ }
702
+ if (previous.ownership) {
703
+ await rm(backup, { recursive: true });
704
+ }
705
+ }
706
+ async function cleanArtifacts(configFile) {
707
+ const generated = await owned(await claimed(configFile));
708
+ if (!generated.ownership) {
709
+ return;
710
+ }
711
+ for (const entry of generated.ownership.files) {
712
+ await rm(join(generated.output, entry.path));
713
+ }
714
+ await rm(join(generated.output, artifactFiles.receipt), { force: true });
715
+ await rm(join(generated.output, artifactFiles.manifest));
716
+ const removeEmpty = async (path) => {
717
+ for (const entry of await readdir(path, { withFileTypes: true })) {
718
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
719
+ await removeEmpty(join(path, entry.name));
720
+ }
721
+ }
722
+ if (!(await readdir(path)).length) {
723
+ await rm(path, { recursive: true });
724
+ }
725
+ };
726
+ await removeEmpty(generated.output);
727
+ }
728
+
729
+ // packages/compiler/src/project/project.ts
730
+ var emittedSt = basename(emittedStDirectory2);
731
+ var failure = (origin, code, cause) => ({
732
+ origin,
733
+ code,
734
+ severity: "error",
735
+ message: cause instanceof Error ? cause.message : String(cause)
736
+ });
737
+ var buildConfigs = (loaded, options) => options.simulate ? {
738
+ loaded: { ...loaded, config: simulationConfig(loaded.config) },
739
+ configured: loaded.config
740
+ } : { loaded };
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
+ }
747
+ try {
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".');
754
+ }
755
+ const root = dirname2(configFile);
756
+ const catalog = await loadHardware(shared, root);
757
+ const config = compilerConfig(shared, resolveIo(shared, catalog), buildTarget);
758
+ const hardware = configured ? { config: configured, catalog: await loadHardware(configured, root) } : { config: shared, catalog };
759
+ return {
760
+ configFile,
761
+ shared,
762
+ config: { ...config, ...sourceInput(config, root) },
763
+ project: {
764
+ root,
765
+ environment: env,
766
+ ...shared.debug && { debug: shared.debug },
767
+ ...shared.telemetry && { telemetry: shared.telemetry },
768
+ ...shared.server && { server: shared.server },
769
+ ...shared.hmi && { hmi: shared.hmi },
770
+ hardware: {
771
+ ...hardware,
772
+ tree: shared.codesys?.deviceTree !== undefined
773
+ }
774
+ },
775
+ bound: boundPaths(resolveIo(hardware.config, hardware.catalog)),
776
+ diagnostics: hostConfigDiagnostics
777
+ };
778
+ } catch (cause) {
779
+ return unloaded(configFile, cause);
780
+ }
781
+ }
782
+ var unloaded = (configFile, cause) => ({
783
+ configFile,
784
+ diagnostics: [failure("config", "PLC5003", cause)]
785
+ });
786
+ function sourceInput(compiler, root) {
787
+ return {
788
+ tsconfig: resolve(root, compiler.tsconfig),
789
+ programs: Object.fromEntries(Object.entries(compiler.programs).map(([name, entry]) => [
790
+ name,
791
+ { ...entry, module: resolve(root, entry.module) }
792
+ ]))
793
+ };
794
+ }
795
+ async function projectTargets(file, { config, env }) {
796
+ const configFile = await realpath(resolve(file));
797
+ if (!config.compiler) {
798
+ return;
799
+ }
800
+ const source = analyze({
801
+ ...sourceInput(config.compiler, dirname2(configFile)),
802
+ services: config.server,
803
+ environment: env,
804
+ io: boundPaths(config.io)
805
+ });
806
+ const core = source.module && normalizeModule(source.module).core;
807
+ return core ? coreTargets(core) : undefined;
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
+ }));
813
+ var coreTargets = (core) => ({
814
+ io: ioTargets(core),
815
+ publication: publicationSelectors(core)
816
+ });
817
+ async function checkProject(file, options) {
818
+ const loaded = await loadProject(file, options);
819
+ if (!("project" in loaded)) {
820
+ return loaded;
821
+ }
822
+ const { config } = loaded;
823
+ const source = analyze({
824
+ tsconfig: config.tsconfig,
825
+ programs: config.programs,
826
+ services: loaded.shared.server,
827
+ environment: loaded.project.environment,
828
+ io: loaded.bound
829
+ });
830
+ if (!source.module) {
831
+ return { ...loaded, diagnostics: source.diagnostics };
832
+ }
833
+ const normalized = normalizeModule(source.module);
834
+ if (!normalized.core) {
835
+ return { ...loaded, diagnostics: normalized.diagnostics };
836
+ }
837
+ const tasks = taskPlan(config.tasks);
838
+ const planned = planCodesys(normalized.core, { tasks }, config.target.options, loaded.project);
839
+ return {
840
+ ...loaded,
841
+ ...planned,
842
+ diagnostics: [
843
+ ...loaded.diagnostics,
844
+ ...source.diagnostics,
845
+ ...normalized.diagnostics,
846
+ ...planned.diagnostics
847
+ ]
848
+ };
849
+ }
850
+ async function engineeringInputs(shared, configFile, bundle, options) {
851
+ const root = dirname2(configFile);
852
+ const tree = await deviceTree(shared, await loadHardware(shared, root));
853
+ return {
854
+ libraries: await installLibraries(shared.dependencies, root, options),
855
+ deviceTree: tree && {
856
+ ...tree,
857
+ mappings: bundle.ioMappings.map(({ address, variable }) => ({
858
+ address,
859
+ variable
860
+ }))
861
+ }
862
+ };
863
+ }
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) {
866
+ let staging;
867
+ try {
868
+ const configFile = await realpath(resolve(file));
869
+ const claim = await claimed(configFile);
870
+ await withdrawReceipt(claim);
871
+ const previous = await owned(claim);
872
+ if (previous.unknown.length) {
873
+ throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
874
+ }
875
+ const checked = await checkProject(configFile, options);
876
+ if (!checked.plan || !checked.config) {
877
+ return { diagnostics: checked.diagnostics };
878
+ }
879
+ const bundle = emitCodesys(checked.plan);
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
+ }
890
+ const engineering = shared && (!options.emitOnly || options.forController) ? await engineeringInputs(shared, configFile, bundle, {
891
+ frozen: options.frozenLockfile
892
+ }) : 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;
903
+ await mkdir2(previous.root, { recursive: true });
904
+ staging = await mkdtemp(join2(previous.root, "stage-"));
905
+ const artifacts = [
906
+ ...bundle.artifacts,
907
+ {
908
+ path: "mappings.json",
909
+ content: `${JSON.stringify(compactMappings(bundle.mappings))}
910
+ `
911
+ },
912
+ {
913
+ path: emittedFiles.ioSymbols,
914
+ content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
915
+ `
916
+ },
917
+ {
918
+ path: emittedFiles.publication,
919
+ content: `${JSON.stringify(bundle.publication, null, 2)}
920
+ `
921
+ },
922
+ {
923
+ path: "config.json",
924
+ content: `${JSON.stringify(checked.config, null, 2)}
925
+ `
926
+ },
927
+ {
928
+ path: debugManifestFile,
929
+ content: `${JSON.stringify(bundle.debug)}
930
+ `
931
+ },
932
+ { path: explainFileName, content: bundle.explain }
933
+ ];
934
+ const stagedSt = join2(staging, emittedSt);
935
+ const directories = new Set(artifacts.map((artifact) => dirname2(join2(stagedSt, artifact.path))));
936
+ for (const directory of directories) {
937
+ await mkdir2(directory, { recursive: true });
938
+ }
939
+ for (const artifact of artifacts) {
940
+ await writeFile2(join2(stagedSt, artifact.path), artifact.content);
941
+ }
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;
952
+ }
953
+ const status = vendor ? "vendor-compiled" : "emitted";
954
+ await publishArtifacts(staging, previous, {
955
+ configFile,
956
+ status,
957
+ ...vendor && {
958
+ vendor: { application: vendor.application, tasks: vendor.tasks }
959
+ }
960
+ });
961
+ staging = undefined;
962
+ return {
963
+ directory: previous.output,
964
+ status,
965
+ ...controllerConfig && { controllerConfig },
966
+ targets: coreTargets(checked.plan.core),
967
+ services: serviceRoutes(checked.plan.core),
968
+ diagnostics: checked.diagnostics
969
+ };
970
+ } catch (cause) {
971
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
972
+ } finally {
973
+ if (staging) {
974
+ await rm2(staging, { recursive: true, force: true });
975
+ }
976
+ }
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
+ }
1003
+ function compactMappings(mappings) {
1004
+ const objects = new Map;
1005
+ const files = new Map;
1006
+ const index = (table, value) => {
1007
+ const known = table.get(value);
1008
+ if (known !== undefined) {
1009
+ return known;
1010
+ }
1011
+ table.set(value, table.size);
1012
+ return table.size - 1;
1013
+ };
1014
+ const rows = mappings.map(({ path, line, span }) => [
1015
+ index(objects, path),
1016
+ line,
1017
+ index(files, span.file),
1018
+ span.start,
1019
+ span.end,
1020
+ span.line,
1021
+ span.column
1022
+ ]);
1023
+ return {
1024
+ objects: [...objects.keys()],
1025
+ files: [...files.keys()],
1026
+ mappings: rows
1027
+ };
1028
+ }
1029
+ async function cleanProject(file = configFileName) {
1030
+ try {
1031
+ await cleanArtifacts(await realpath(resolve(file)));
1032
+ return { diagnostics: [] };
1033
+ } catch (cause) {
1034
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
1035
+ }
1036
+ }
1037
+
1038
+ // packages/compiler/src/project/server.ts
1039
+ import { existsSync } from "node:fs";
1040
+ import { mkdir as mkdir3, mkdtemp as mkdtemp2, rename as rename2, rm as rm3 } from "node:fs/promises";
1041
+ import { createRequire } from "node:module";
1042
+ import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
1043
+ import { projectSlugs } from "@tsplc/config";
1044
+ import { generatedDirectory as generatedDirectory3 } from "@tsplc/config/project-files";
1045
+ import { z as z4 } from "zod";
1046
+ var resolveServerModule = (root, name) => name.startsWith(".") || name.startsWith("/") || existsSync(resolve2(root, name)) ? resolve2(root, name) : createRequire(join3(root, "package.json")).resolve(name);
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()
1051
+ });
1052
+ var serverCheckResultSchema = z4.strictObject({
1053
+ failure: z4.string().nullable()
1054
+ });
1055
+ var checkServer = async (config, root) => {
1056
+ const runtime = config.server?.runtime;
1057
+ if (!runtime) {
1058
+ throw new Error("Configure server.runtime to build the server.");
1059
+ }
1060
+ const entry = resolveServerModule(root, runtime.entry);
1061
+ const worker = new Worker(import.meta.resolve("#server-check"));
1062
+ try {
1063
+ const answer = await new Promise((resolve, reject) => {
1064
+ worker.onmessage = (event) => resolve(event.data);
1065
+ worker.onerror = (event) => reject(new Error(event.message));
1066
+ const request = {
1067
+ entry,
1068
+ root
1069
+ };
1070
+ worker.postMessage(request);
1071
+ });
1072
+ const { failure } = serverCheckResultSchema.parse(answer);
1073
+ if (failure !== null) {
1074
+ throw new Error(failure);
1075
+ }
1076
+ return { entry, runtime };
1077
+ } finally {
1078
+ worker.terminate();
1079
+ }
1080
+ };
1081
+ var startServerCheck = (config, root) => {
1082
+ const check = checkServer(config, root);
1083
+ check.catch(() => {
1084
+ return;
1085
+ });
1086
+ return check;
1087
+ };
1088
+ var bundleServer = async ({ entry }, config, root) => {
1089
+ const outFile = serverOutput(config, root, ".js");
1090
+ const result = await Bun.build({
1091
+ entrypoints: [entry],
1092
+ target: "bun",
1093
+ minify: true,
1094
+ env: "disable"
1095
+ });
1096
+ if (!result.success) {
1097
+ throw new AggregateError(result.logs, "Server bundle build failed.");
1098
+ }
1099
+ const [script, ...assets] = result.outputs;
1100
+ if (!script || assets.length) {
1101
+ throw new Error(`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(", ")}), which deployments don't carry.`);
1102
+ }
1103
+ await mkdir3(dirname3(outFile), { recursive: true });
1104
+ await Bun.write(outFile, script);
1105
+ return outFile;
1106
+ };
1107
+ var buildServer = async ({ entry, runtime }, config, root) => {
1108
+ const windows = runtime.target ? runtime.target.includes("windows") : process.platform === "win32";
1109
+ const outFile = serverOutput(config, root, windows ? ".exe" : "");
1110
+ await mkdir3(dirname3(outFile), { recursive: true });
1111
+ const staging = await mkdtemp2(join3(dirname3(outFile), ".tsplc-server-"));
1112
+ try {
1113
+ const binary = join3(staging, "server");
1114
+ const result = await Bun.build({
1115
+ entrypoints: [entry],
1116
+ env: "disable",
1117
+ compile: {
1118
+ outfile: binary,
1119
+ ...runtime.target ? { target: runtime.target } : {},
1120
+ autoloadDotenv: false,
1121
+ autoloadBunfig: false,
1122
+ autoloadTsconfig: false,
1123
+ autoloadPackageJson: false
1124
+ }
1125
+ });
1126
+ if (!result.success) {
1127
+ throw new AggregateError(result.logs, "Server executable build failed.");
1128
+ }
1129
+ await rename2(windows ? `${binary}.exe` : binary, outFile);
1130
+ return {
1131
+ server: {
1132
+ executable: outFile,
1133
+ target: runtime.target ?? `bun-${process.platform}-${process.arch}`
1134
+ }
1135
+ };
1136
+ } finally {
1137
+ await rm3(staging, { recursive: true, force: true });
1138
+ }
1139
+ };
1140
+
1141
+ // packages/compiler/src/project/release.ts
1142
+ var releaseVariables = async (file) => {
1143
+ if (file === null) {
1144
+ return [];
1145
+ }
1146
+ const contract = plcContractSchema.parse(await import(pathToFileURL(file).href));
1147
+ return contractVariables(contract).map(({ path, type }) => ({ path, type }));
1148
+ };
1149
+ var prepareRelease = async (loaded, flags, built) => {
1150
+ const project = { ...loaded, env: built.env };
1151
+ const { config, root } = project;
1152
+ if (!config.compiler) {
1153
+ throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
1154
+ }
1155
+ const command = flags.simulate ? "run" : "deploy";
1156
+ const serverCheck = config.server?.runtime ? startServerCheck(config, root) : undefined;
1157
+ const emitted = await buildTypeScriptProject(project.configFile, {
1158
+ emitOnly: true,
1159
+ forController: true,
1160
+ frozenLockfile: flags["frozen-lockfile"],
1161
+ ...buildConfigs(project, flags),
1162
+ hostConfigDiagnostics: checkHostConfig(project.configFile),
1163
+ buildTarget: buildTargetFor(command),
1164
+ controller: controllerFor(config, command)
1165
+ });
1166
+ if (hasErrors2(emitted.diagnostics)) {
1167
+ return { diagnostics: emitted.diagnostics };
1168
+ }
1169
+ const settings = emitted.controllerConfig;
1170
+ if (!settings) {
1171
+ throw new Error("Configure build settings for deployment.");
1172
+ }
1173
+ const { contract } = await generateProject(project, {
1174
+ targets: emitted.targets
1175
+ });
1176
+ const portable = (path) => path.split(sep).join("/");
1177
+ const libraries = (settings.libraries ?? []).map((library) => ({
1178
+ ...library,
1179
+ release: `libraries/${library.sha256}-${basename2(library.path)}`
1180
+ }));
1181
+ const files = [
1182
+ { path: "template.project", content: Bun.file(settings.template) },
1183
+ ...libraries.map((library) => ({
1184
+ path: library.release,
1185
+ content: Bun.file(library.path)
1186
+ }))
1187
+ ];
1188
+ for await (const source of new Bun.Glob("**/*.st").scan({
1189
+ cwd: settings.sourceDir,
1190
+ dot: true
1191
+ })) {
1192
+ files.push({
1193
+ path: `st/${portable(source)}`,
1194
+ content: Bun.file(resolve3(settings.sourceDir, source))
1195
+ });
1196
+ }
1197
+ for (const name of [debugManifestFile2, explainFileName2]) {
1198
+ files.push({
1199
+ path: name,
1200
+ content: Bun.file(resolve3(settings.sourceDir, name))
1201
+ });
1202
+ }
1203
+ const serverScript = serverCheck && await bundleServer(await serverCheck, config, root);
1204
+ const server = serverScript ? {
1205
+ path: `server/${basename2(serverScript)}`,
1206
+ content: Bun.file(serverScript)
1207
+ } : undefined;
1208
+ if (server) {
1209
+ files.push(server);
1210
+ }
1211
+ const releaseConfig = {
1212
+ io: settings.io,
1213
+ deviceTree: settings.deviceTree,
1214
+ controller: settings.controller,
1215
+ libraryReferences: settings.libraryReferences,
1216
+ libraries: libraries.map(({ release, ...library }) => ({
1217
+ ...library,
1218
+ path: release
1219
+ })),
1220
+ task: settings.task,
1221
+ tasks: settings.tasks,
1222
+ removeObjects: settings.removeObjects,
1223
+ symbols: settings.symbols,
1224
+ timeouts: settings.timeouts,
1225
+ template: "template.project",
1226
+ sourceDir: "st",
1227
+ entry: `st/${portable(relative2(settings.sourceDir, settings.entry))}`
1228
+ };
1229
+ const manifest = {
1230
+ config: releaseConfig,
1231
+ variables: await releaseVariables(contract),
1232
+ server: server?.path,
1233
+ debug: config.debug,
1234
+ serverTokenEnv: serverTokenEnv(config),
1235
+ secrets: built.secrets,
1236
+ values: built.values
1237
+ };
1238
+ return { release: { manifest, files } };
1239
+ };
1240
+
1241
+ // packages/compiler/src/project/plant.ts
1242
+ var connect = (env) => {
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`
1246
+ }),
1247
+ [agentTokenEnv]: z5.string({
1248
+ error: `Set ${agentTokenEnv} to the plant agent's token`
1249
+ })
1250
+ }).parse(env);
1251
+ return createAgentClient({
1252
+ url: environment[agentUrlEnv],
1253
+ token: environment[agentTokenEnv]
1254
+ });
1255
+ };
1256
+ var readThroughAgent = (agent) => async ([first, ...rest]) => {
1257
+ if (!first) {
1258
+ return {};
1259
+ }
1260
+ try {
1261
+ const result = await agent.command({
1262
+ command: "read",
1263
+ expressions: [first, ...rest]
1264
+ });
1265
+ if (!("values" in result)) {
1266
+ throw new Error("The agent answered a read without values");
1267
+ }
1268
+ return result.values;
1269
+ } catch (error) {
1270
+ const { login } = await agent.status();
1271
+ if (!login) {
1272
+ throw new LoginUnavailable(noLogin, { cause: error });
1273
+ }
1274
+ if ("error" in login) {
1275
+ throw new Error(login.error, { cause: error });
1276
+ }
1277
+ throw error;
1278
+ }
1279
+ };
1280
+
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]`;
1289
+ async function serveProjectDebugger({ config, root, env }, flags) {
1290
+ if (flags.opcua && !config.monitor) {
1291
+ throw new Error("Configure monitor with the controller's OPC UA endpoint to use --opcua.");
1292
+ }
1293
+ const reader = flags.opcua && config.monitor ? { monitor: config.monitor } : { agent: connect(env) };
1294
+ const file = resolve4(root, emittedStDirectory3, debugManifestFile3);
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.`);
1297
+ }
1298
+ const port = tcpPort.safeParse(Number(flags.port ?? debuggerPort));
1299
+ if (!port.success) {
1300
+ throw new Error("--port must be a TCP port.");
1301
+ }
1302
+ const serverUrl = flags["server-url"] ?? serverBaseUrl2(config, env);
1303
+ const tokenEnv = serverTokenEnv2(config);
1304
+ const token = tokenEnv && env[tokenEnv];
1305
+ const log = (message) => console.log(`${new Date().toISOString()} ${message}`);
1306
+ const build = await loadDebugBuild(file);
1307
+ const debug = await createDebugger({
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]}`
1316
+ }),
1317
+ stateDirectory: resolve4(root, generatedDirectory4, "debug"),
1318
+ watch: config.debug?.watch ?? {},
1319
+ ...serverUrl && token && { server: { url: serverUrl, token } },
1320
+ projectRoot: root,
1321
+ log
1322
+ });
1323
+ const server = serveDebugger(debug, { port: port.data, log });
1324
+ console.log(`tsPLC debugger at ${server.url}`);
1325
+ if (!serverUrl || !token) {
1326
+ console.log("Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.");
1327
+ }
1328
+ await new Promise((stopped) => {
1329
+ process.once("SIGINT", stopped);
1330
+ process.once("SIGTERM", stopped);
1331
+ });
1332
+ await server.stop(true);
1333
+ await debug.close();
1334
+ }
1335
+
1336
+ // packages/compiler/src/project/flags.ts
1337
+ import { z as z6 } from "zod";
1338
+ var outputFormatSchema2 = z6.enum(["json", "text"]);
1339
+
1340
+ // packages/compiler/src/project/plant.ts
1341
+ import {
1342
+ ask as ask3,
1343
+ askCredentials as askCredentials2
1344
+ } from "@tsplc/agent";
1345
+ import { createAgentClient as createAgentClient2 } from "@tsplc/agent/client";
1346
+ import { resetLabel as resetLabel2 } from "@tsplc/build";
1347
+ import {
1348
+ agentTokenEnv as agentTokenEnv2,
1349
+ agentUrlEnv as agentUrlEnv3,
1350
+ releaseEnvironment as releaseEnvironment2
1351
+ } from "@tsplc/config";
1352
+ import { runtimePort as runtimePort2 } from "@tsplc/config/build";
1353
+ import { LoginUnavailable as LoginUnavailable2, noLogin as noLogin2 } from "@tsplc/debug";
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
+ };
1369
+ var connect2 = (env) => {
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`
1373
+ }),
1374
+ [agentTokenEnv2]: z7.string({
1375
+ error: `Set ${agentTokenEnv2} to the plant agent's token`
1376
+ })
1377
+ }).parse(env);
1378
+ return createAgentClient2({
1379
+ url: environment[agentUrlEnv3],
1380
+ token: environment[agentTokenEnv2]
1381
+ });
1382
+ };
1383
+ var selectTarget = async (agent) => {
1384
+ const interfaces = await agent.interfaces();
1385
+ if (!interfaces.length) {
1386
+ throw new Error("The plant PC has no IPv4 network.");
1387
+ }
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}`);
1389
+ console.log(`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`);
1390
+ const found = await agent.discover(network.name);
1391
+ const manual = { address: "", port: runtimePort2, hostname: null };
1392
+ const choice = await choose("Which controller?", [...found, manual], (item) => item === manual ? "Enter an address" : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`);
1393
+ const host = choice === manual ? await ask3("Controller address: ") : choice.address;
1394
+ return agent.setTarget({ host, port: choice.port });
1395
+ };
1396
+ var controllerCredentials = async (environment, agent, prompt) => {
1397
+ const username = environment.TSPLC_CONTROLLER_USERNAME;
1398
+ const password = environment.TSPLC_CONTROLLER_PASSWORD;
1399
+ if (username && password) {
1400
+ return { username, password };
1401
+ }
1402
+ if (username || password) {
1403
+ throw new Error("Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.");
1404
+ }
1405
+ return agent.stored && !agent.initializeUser ? null : prompt();
1406
+ };
1407
+ var plantSummary = ({ values, secrets }) => {
1408
+ const named = (noun, names) => names.length ? `${noun}${names.length === 1 ? "" : "s"} ${names.join(", ")}` : null;
1409
+ const parts = [
1410
+ named("variable", Object.keys(values)),
1411
+ named("secret", secrets)
1412
+ ].filter((part) => part !== null);
1413
+ return parts.length ? parts.join(" and ") : null;
1414
+ };
1415
+ var deploy = async (agent, loaded, flags, follow) => {
1416
+ const status = await agent.status();
1417
+ if (status.login) {
1418
+ throw new Error("A login is open; log out before deploying: tsplc logout");
1419
+ }
1420
+ const target = !status.target || flags.select ? await selectTarget(agent) : status.target;
1421
+ const initializeUser = flags["initialize-user"] ?? false;
1422
+ const plant = await agent.releaseVariables(loaded.config.secrets?.service ?? null);
1423
+ const built = releaseEnvironment2(loaded.config, loaded, plant);
1424
+ console.log(`Building the release for ${target.host}…`);
1425
+ const held = plantSummary(plant);
1426
+ if (held) {
1427
+ console.log(` With the plant PC's ${held}`);
1428
+ }
1429
+ const building = timedProgress();
1430
+ const { release, diagnostics } = await prepareRelease(loaded, flags, built);
1431
+ if (!release) {
1432
+ return { diagnostics };
1433
+ }
1434
+ building("Built");
1435
+ if (flags.download) {
1436
+ await confirmOrCancel("A full download stops the running application while it loads. Continue?", flags);
1437
+ }
1438
+ const credentials = await controllerCredentials(loaded.env, { stored: status.credentialsStored, initializeUser }, askCredentials2);
1439
+ const settings = {
1440
+ credentials,
1441
+ download: flags.download ?? false,
1442
+ initializeUser
1443
+ };
1444
+ console.log(release.manifest.server ? "Uploading the server and the program…" : "Uploading the program…");
1445
+ return {
1446
+ exitCode: await submitDeployment(agent, release, settings, {
1447
+ mode: flags.review ? "review" : "apply",
1448
+ git: await gitSource(loaded.root)
1449
+ }, follow)
1450
+ };
1451
+ };
1452
+ var ensureLogin = async (agent, environment) => {
1453
+ const { login, credentialsStored } = await agent.status();
1454
+ if (login && "state" in login) {
1455
+ return;
1456
+ }
1457
+ if (login) {
1458
+ console.log(`The open login failed (${login.error}); replacing it.`);
1459
+ await agent.logout();
1460
+ }
1461
+ const credentials = await controllerCredentials(environment, { stored: credentialsStored, initializeUser: false }, askCredentials2);
1462
+ console.log("Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.");
1463
+ await agent.login(credentials, progress);
1464
+ };
1465
+ var variableChildren = (variables, prefix) => {
1466
+ const children = new Map;
1467
+ for (const { path, type } of variables) {
1468
+ if (prefix && !isWithin2(prefix, path)) {
1469
+ continue;
1470
+ }
1471
+ const rest = path.slice(prefix.length).replace(/^\./, "");
1472
+ if (rest === "") {
1473
+ return [{ name: path, type, leaves: 1 }];
1474
+ }
1475
+ const name = symbolPathSegments2(rest)[0] ?? rest;
1476
+ const child = children.get(name) ?? { leaves: 0 };
1477
+ children.set(name, {
1478
+ type: rest === name ? type : undefined,
1479
+ leaves: child.leaves + 1
1480
+ });
1481
+ }
1482
+ const indexes = [...children.keys()].map(arrayIndex2).filter((index) => index !== undefined);
1483
+ const listed = [...children].filter(([name]) => arrayIndex2(name) === undefined);
1484
+ if (indexes.length) {
1485
+ const first = children.get(`[${Math.min(...indexes)}]`);
1486
+ listed.unshift([
1487
+ `[${Math.min(...indexes)}..${Math.max(...indexes)}]`,
1488
+ first ?? { leaves: 0 }
1489
+ ]);
1490
+ }
1491
+ return listed.map(([name, child]) => ({ name, ...child }));
1492
+ };
1493
+ var printStatus = async (agent) => {
1494
+ const status = await agent.status();
1495
+ console.log(`Controller ${status.target ? `${status.target.host}:${status.target.port}` : "not selected (tsplc target)"}`);
1496
+ console.log(`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : "none"}`);
1497
+ console.log(`Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`);
1498
+ const { login } = status;
1499
+ if (!login) {
1500
+ console.log("Login closed");
1501
+ } else if ("error" in login) {
1502
+ console.log(`Login failed: ${login.error} (tsplc logout)`);
1503
+ } else {
1504
+ console.log(`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`);
1505
+ }
1506
+ };
1507
+ var printVariables = async (agent, path) => {
1508
+ const children = variableChildren(await agent.variables(), path ?? "");
1509
+ if (!children.length) {
1510
+ throw new Error(`No published variable ${path}.`);
1511
+ }
1512
+ for (const child of children) {
1513
+ console.log(`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`);
1514
+ }
1515
+ };
1516
+ var printLogin = (result) => {
1517
+ if ("values" in result) {
1518
+ for (const [expression, value] of Object.entries(result.values)) {
1519
+ console.log(`${expression} = ${value}`);
1520
+ }
1521
+ return;
1522
+ }
1523
+ console.log(`Application ${result.state}`);
1524
+ if (result.forced.length) {
1525
+ console.log(`Forced: ${result.forced.join(", ")}`);
1526
+ }
1527
+ };
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;
1548
+ }
1549
+ },
1550
+ rollback: {
1551
+ usage: "[id] [--wait] [-y]",
1552
+ run: async ({ agent, args, follow, usage }) => {
1553
+ if (args.length > 1) {
1554
+ usage();
1555
+ }
1556
+ return { exitCode: await rollBack(agent, args[0], follow) };
1557
+ }
1558
+ },
1559
+ redeploy: {
1560
+ usage: "<id> [--review] [--wait] [-y]",
1561
+ run: async ({ agent, args: [id, ...extra], flags, follow, usage }) => {
1562
+ if (!id || extra.length) {
1563
+ return usage();
1564
+ }
1565
+ return {
1566
+ exitCode: await redeploy(agent, id, flags.review ? "review" : "apply", follow)
1567
+ };
1568
+ }
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);
1583
+ console.log(`Deployments now go to ${target.host}:${target.port}.`);
1584
+ return;
1585
+ }
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" }));
1601
+ return;
1602
+ }
1603
+ },
1604
+ logout: {
1605
+ usage: "",
1606
+ run: async (context) => {
1607
+ none(context);
1608
+ const { agent, flags } = context;
1609
+ const { login } = await agent.status();
1610
+ const forced = login && "forced" in login ? login.forced : [];
1611
+ if (forced.length) {
1612
+ await confirmOrCancel(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags);
1613
+ }
1614
+ const { failure } = await agent.logout();
1615
+ console.log(failure ? `The login couldn't log out (${failure}); its container was removed.` : "Logged out.");
1616
+ return;
1617
+ }
1618
+ },
1619
+ vars: {
1620
+ usage: "[path]",
1621
+ run: async ({ agent, args, usage }) => {
1622
+ if (args.length > 1) {
1623
+ usage();
1624
+ }
1625
+ await printVariables(agent, args[0]);
1626
+ return;
1627
+ }
1628
+ },
1629
+ read: {
1630
+ usage: "<expression>...",
1631
+ run: async ({ args: [first, ...rest], send, usage }) => {
1632
+ if (!first) {
1633
+ return usage();
1634
+ }
1635
+ await send({ command: "read", expressions: [first, ...rest] });
1636
+ return;
1637
+ }
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({
1651
+ command: "unforce",
1652
+ expressions: args,
1653
+ restore: flags.restore ?? false
1654
+ });
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();
1680
+ }
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 }) => {
1690
+ if (args.length > 1) {
1691
+ usage();
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);
1695
+ const { state } = await agent.restartController({ reset });
1696
+ console.log(`Reset ${reset}; the application is ${state === "run" ? "running" : state}.`);
1697
+ return;
1698
+ }
1699
+ }
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
+ };
1731
+
1732
+ // packages/compiler/src/project/project-commands.ts
1733
+ import { resolve as resolve5 } from "node:path";
1734
+ import {
1735
+ checkRawSources,
1736
+ compileStructuredText,
1737
+ configureDocker,
1738
+ configureRuntime,
1739
+ inspectProjectController,
1740
+ installLibraries as installLibraries2,
1741
+ rawEngineeringSettings,
1742
+ runProject,
1743
+ updateController
1744
+ } from "@tsplc/build";
1745
+ import { checkHostConfig as checkHostConfig2 } from "@tsplc/compiler";
1746
+ import { hasErrors as hasErrors3 } from "@tsplc/compiler/ir";
1747
+ import {
1748
+ buildTargetFor as buildTargetFor2,
1749
+ controllerFor as controllerFor2,
1750
+ loadTsplcConfig,
1751
+ rawBuildConfig
1752
+ } from "@tsplc/config";
1753
+ import { resolveConfig } from "@tsplc/config/build";
1754
+ import { generateProject as generateProject2 } from "@tsplc/typegen";
1755
+
1756
+ // packages/compiler/src/runtime/process.ts
1757
+ import { spawn as spawn2, spawnSync } from "node:child_process";
1758
+ import { openSync } from "node:fs";
1759
+ import { mkdir as mkdir4, readFile as readFile2, rm as rm4, writeFile as writeFile3 } from "node:fs/promises";
1760
+ import { join as join4, relative as relative4 } from "node:path";
1761
+ import { setTimeout as delay } from "node:timers/promises";
1762
+ import { fileURLToPath } from "node:url";
1763
+ import { progressLog } from "@tsplc/build";
1764
+ var startTimeoutMs = 60000;
1765
+ var stopTimeoutMs = 15000;
1766
+ var alive = (pid) => {
1767
+ try {
1768
+ process.kill(pid, 0);
1769
+ return true;
1770
+ } catch (cause) {
1771
+ return cause instanceof Error && "code" in cause && cause.code === "EPERM";
1772
+ }
1773
+ };
1774
+ var isRuntime = (pid, launchFile) => {
1775
+ if (!alive(pid)) {
1776
+ return false;
1777
+ }
1778
+ if (process.platform === "win32") {
1779
+ return true;
1780
+ }
1781
+ const command = spawnSync("ps", ["-o", "command=", "-p", String(pid)], {
1782
+ encoding: "utf8"
1783
+ }).stdout;
1784
+ return command.includes(launchFile);
1785
+ };
1786
+ var readState = async (file) => {
1787
+ const text = await readFile2(file, "utf8").catch((cause) => {
1788
+ if (isMissingFile(cause)) {
1789
+ return;
1790
+ }
1791
+ throw cause;
1792
+ });
1793
+ if (text === undefined) {
1794
+ return;
1795
+ }
1796
+ try {
1797
+ return runtimeStateSchema.parse(JSON.parse(text));
1798
+ } catch (cause) {
1799
+ throw new Error(`${file} is not a Bun runtime's state: delete it once no runtime runs.`, { cause });
1800
+ }
1801
+ };
1802
+ var stopRunning = async (directory, log) => {
1803
+ const stateFile = join4(directory, runtimeFiles.state);
1804
+ const state = await readState(stateFile);
1805
+ if (!state || !isRuntime(state.pid, join4(directory, runtimeFiles.launch))) {
1806
+ await rm4(stateFile, { force: true });
1807
+ return;
1808
+ }
1809
+ log(`Stopping the Bun runtime that runs as process ${state.pid}`);
1810
+ process.kill(state.pid, "SIGTERM");
1811
+ const deadline = Date.now() + stopTimeoutMs;
1812
+ while (alive(state.pid)) {
1813
+ if (Date.now() >= deadline) {
1814
+ process.kill(state.pid, "SIGKILL");
1815
+ break;
1816
+ }
1817
+ await delay(100);
1818
+ }
1819
+ await rm4(stateFile, { force: true });
1820
+ };
1821
+ var runInBun = async (options) => {
1822
+ const log = progressLog(options.progress);
1823
+ const directory = join4(options.root, runtimeDirectory);
1824
+ await mkdir4(directory, { recursive: true });
1825
+ await stopRunning(directory, log);
1826
+ const launchFile = join4(directory, runtimeFiles.launch);
1827
+ await writeFile3(launchFile, `${JSON.stringify(options.launch, null, 2)}
1828
+ `);
1829
+ const logFile = join4(directory, runtimeFiles.log);
1830
+ const command = [
1831
+ fileURLToPath(import.meta.resolve("#bun-runtime")),
1832
+ launchFile
1833
+ ];
1834
+ if (options.foreground) {
1835
+ log("Running the program in Bun; stop it with Ctrl-C");
1836
+ const child = spawn2(process.execPath, command, {
1837
+ cwd: options.root,
1838
+ env: options.environment,
1839
+ stdio: "inherit"
1840
+ });
1841
+ const wait = () => {
1842
+ return;
1843
+ };
1844
+ const forward = () => child.kill("SIGTERM");
1845
+ process.on("SIGINT", wait);
1846
+ process.on("SIGTERM", forward);
1847
+ const code = await new Promise((resolve) => child.once("exit", resolve));
1848
+ process.off("SIGINT", wait);
1849
+ process.off("SIGTERM", forward);
1850
+ if (code !== 0) {
1851
+ throw new Error(`The Bun runtime exited with code ${code}.`);
1852
+ }
1853
+ return { stopped: true };
1854
+ }
1855
+ const output = openSync(logFile, "w");
1856
+ const child = spawn2(process.execPath, command, {
1857
+ cwd: options.root,
1858
+ env: options.environment,
1859
+ detached: true,
1860
+ stdio: ["ignore", output, output]
1861
+ });
1862
+ const exited = {
1863
+ code: null,
1864
+ done: false
1865
+ };
1866
+ child.once("exit", (code) => {
1867
+ Object.assign(exited, { code, done: true });
1868
+ });
1869
+ const stateFile = join4(directory, runtimeFiles.state);
1870
+ const deadline = Date.now() + startTimeoutMs;
1871
+ while (true) {
1872
+ const state = await readState(stateFile);
1873
+ if (state && state.pid === child.pid) {
1874
+ child.unref();
1875
+ const shown = relative4(process.cwd(), logFile) || logFile;
1876
+ log(`The program runs in Bun as process ${state.pid}: OPC UA at ${state.endpoint}, output in ${shown}`);
1877
+ return { ...state, log: logFile };
1878
+ }
1879
+ if (exited.done || Date.now() >= deadline) {
1880
+ if (!exited.done) {
1881
+ child.kill("SIGTERM");
1882
+ }
1883
+ const tail = (await readFile2(logFile, "utf8").catch(() => "")).trimEnd().split(`
1884
+ `).slice(-30).join(`
1885
+ `);
1886
+ throw new Error(`The Bun runtime ${exited.done ? `exited with code ${exited.code}` : "did not start in time"}:
1887
+ ${tail}`);
1888
+ }
1889
+ await delay(100);
1890
+ }
1891
+ };
1892
+
1893
+ // packages/compiler/src/project/project-commands.ts
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
+ };
1907
+
1908
+ class DiagnosticFailure extends Error {
1909
+ result;
1910
+ constructor(result) {
1911
+ super("PLC validation failed.");
1912
+ this.result = result;
1913
+ }
1914
+ }
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)
1996
+ }
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
+ }
2007
+ }
2008
+ entry.check?.(flags);
2009
+ };
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, {
2016
+ env: environment,
2017
+ target: flags.target,
2018
+ forAgent: false
2019
+ })
2020
+ });
2021
+ var loadCheckedConfig = async (file, load) => {
2022
+ const hostConfigDiagnostics = checkHostConfig2(resolve5(file));
2023
+ if (hasErrors3(hostConfigDiagnostics)) {
2024
+ throw new DiagnosticFailure({ diagnostics: hostConfigDiagnostics });
2025
+ }
2026
+ return { loaded: await load(), hostConfigDiagnostics };
2027
+ };
2028
+ var configure = async (flags, progress, environment) => {
2029
+ await (flags.runtime ? configureRuntime({ progress }) : configureDocker({
2030
+ progress,
2031
+ winetricksCache: environment.CODESYS_WINETRICKS_CACHE || null
2032
+ }));
2033
+ return { ok: true };
2034
+ };
2035
+ var install = async ({ config, root }, flags) => ({
2036
+ libraries: await installLibraries2(config.dependencies, root, {
2037
+ frozen: flags["frozen-lockfile"]
2038
+ })
2039
+ });
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, {
2047
+ emitOnly: true,
2048
+ loaded,
2049
+ hostConfigDiagnostics: checkHostConfig2(loaded.configFile)
2050
+ });
2051
+ if (hasErrors3(emitted.diagnostics)) {
2052
+ throw new DiagnosticFailure(emitted);
2053
+ }
2054
+ }
2055
+ const { catalog, io, files } = await generateProject2(loaded, {
2056
+ check: flags.check,
2057
+ targets
2058
+ });
2059
+ return { catalog, io, files };
2060
+ };
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 };
2065
+ }
2066
+ return { objects: (await checkRawSources(checked.loaded)).objects.length };
2067
+ };
2068
+ var buildPlc = async (command, { loaded, hostConfigDiagnostics }, flags, progress) => {
2069
+ const { config, configFile } = loaded;
2070
+ if (config.compiler) {
2071
+ const { targets, services, ...built } = await buildTypeScriptProject(configFile, {
2072
+ progress,
2073
+ emitOnly: flags["emit-only"],
2074
+ frozenLockfile: flags["frozen-lockfile"],
2075
+ ...buildConfigs(loaded, flags),
2076
+ hostConfigDiagnostics,
2077
+ controller: controllerFor2(config, command),
2078
+ buildTarget: buildTargetFor2(command)
2079
+ });
2080
+ if (hasErrors3(built.diagnostics)) {
2081
+ throw new DiagnosticFailure(built);
2082
+ }
2083
+ await generateProject2(loaded, { targets });
2084
+ return { built, services };
2085
+ }
2086
+ if (flags["emit-only"]) {
2087
+ throw new Error("Raw Structured Text is already emitted.");
2088
+ }
2089
+ const built = await compileStructuredText(await rawEngineeringSettings(loaded, {
2090
+ command,
2091
+ frozenLockfile: flags["frozen-lockfile"],
2092
+ simulate: flags.simulate
2093
+ }), { progress });
2094
+ await generateProject2(loaded);
2095
+ return { built, services: undefined };
2096
+ };
2097
+ var build = async (checked, flags, progress) => {
2098
+ const { config, root } = checked.loaded;
2099
+ if (flags.server) {
2100
+ return buildServer(await checkServer(config, root), config, root);
2101
+ }
2102
+ const withServer = !flags.plc && !flags["emit-only"] && config.server?.runtime;
2103
+ const serverCheck = withServer ? startServerCheck(config, root) : undefined;
2104
+ const { built: plc } = await buildPlc("build", checked, flags, progress);
2105
+ if (!serverCheck) {
2106
+ return plc;
2107
+ }
2108
+ return { ...plc, ...await buildServer(await serverCheck, config, root) };
2109
+ };
2110
+ var run = async (checked, flags, progress) => {
2111
+ if (flags.bun) {
2112
+ return runInBunRuntime(checked, flags, progress);
2113
+ }
2114
+ const { config, configFile } = checked.loaded;
2115
+ const { built } = await buildPlc("run", checked, flags, progress);
2116
+ if (!config.build) {
2117
+ throw new Error("Configure build to run this project.");
2118
+ }
2119
+ await runProject(resolveConfig(config.compiler ? config.build : rawBuildConfig(config), configFile), config.name, { progress });
2120
+ return built;
2121
+ };
2122
+ var runInBunRuntime = async (checked, flags, progress) => {
2123
+ const { config, configFile, env, root } = checked.loaded;
2124
+ if (!config.compiler) {
2125
+ throw new Error("The Bun runtime runs a TypeScript program; this project builds raw Structured Text.");
2126
+ }
2127
+ const { built, services } = await buildPlc("run", checked, { ...flags, "emit-only": true }, progress);
2128
+ const runtime = await runInBun({
2129
+ root,
2130
+ launch: {
2131
+ config: configFile,
2132
+ target: flags.target ?? null,
2133
+ services: services ?? {}
2134
+ },
2135
+ environment: env,
2136
+ foreground: flags.foreground ?? false,
2137
+ progress
2138
+ });
2139
+ return { ...built, runtime };
2140
+ };
2141
+ var updateProgram = async (operation, checked, flags, progress) => {
2142
+ const { config, env } = checked.loaded;
2143
+ if (!config.build) {
2144
+ throw new Error("Configure build settings and controller connection.");
2145
+ }
2146
+ const settings = config.compiler ? await emittedControllerSettings(operation, checked, flags) : await rawEngineeringSettings(checked.loaded, {
2147
+ command: operation,
2148
+ frozenLockfile: flags["frozen-lockfile"],
2149
+ simulate: flags.simulate
2150
+ });
2151
+ return updateController(settings, operation, {
2152
+ initializeUser: flags["initialize-user"],
2153
+ read: flags.read,
2154
+ progress,
2155
+ environment: env
2156
+ });
2157
+ };
2158
+ var emittedControllerSettings = async (operation, { loaded, hostConfigDiagnostics }, flags) => {
2159
+ const emitted = await buildTypeScriptProject(loaded.configFile, {
2160
+ emitOnly: true,
2161
+ forController: true,
2162
+ frozenLockfile: flags["frozen-lockfile"],
2163
+ ...buildConfigs(loaded, flags),
2164
+ hostConfigDiagnostics,
2165
+ controller: controllerFor2(loaded.config, operation),
2166
+ buildTarget: buildTargetFor2(operation)
2167
+ });
2168
+ if (hasErrors3(emitted.diagnostics)) {
2169
+ throw new DiagnosticFailure(emitted);
2170
+ }
2171
+ if (!emitted.controllerConfig) {
2172
+ throw new Error("Configure build settings for deployment.");
2173
+ }
2174
+ return emitted.controllerConfig;
2175
+ };
2176
+
2177
+ // packages/compiler/src/project/cli.ts
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]
2180
+
2181
+ Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:${opcuaPort}:
2182
+ tsplc run --simulate --bun [--foreground] [--target name]
2183
+
2184
+ Plant agent (the target's agent, else ${agentUrlEnv4}; ${agentTokenEnv3}):
2185
+ tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]
2186
+ tsplc deployments [--format json] | dashboard
2187
+ tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]
2188
+ (--wait follows the deployment and exits 2 while it waits for approval; -y approves)
2189
+ tsplc target | status | login | logout
2190
+ tsplc vars [path] | read <expression>... | write <expression> <value>
2191
+ tsplc force <expression> <value> | unforce [expression]... [--restore]
2192
+ tsplc start | stop | reset warm|cold (-y skips confirmations)
2193
+ tsplc restart [warm|cold] resets and starts the application, with or without a login
2194
+
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
+ };
2207
+ var requestedFormat = (argv) => {
2208
+ const index = argv.findIndex((argument) => argument === "--format" || argument.startsWith("--format="));
2209
+ const flag = argv[index];
2210
+ if (index < 0 || flag === undefined) {
2211
+ return;
2212
+ }
2213
+ return flag === "--format" ? argv[index + 1] : flag.slice("--format=".length);
2214
+ };
2215
+ var outputFormat = (format) => {
2216
+ const parsed = outputFormatSchema2.optional().safeParse(format);
2217
+ if (!parsed.success) {
2218
+ throw new Error("--format must be json or text.");
2219
+ }
2220
+ return parsed.data;
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
+ };
2251
+ async function main() {
2252
+ const { values: parsed, positionals } = parseArgs({
2253
+ allowPositionals: true,
2254
+ options
2255
+ });
2256
+ const values = { ...parsed, format: outputFormat(parsed.format) };
2257
+ const [name, ...args] = positionals;
2258
+ const file = values.config ?? configFileName2;
2259
+ if (!name || values.help) {
2260
+ console.log(usage);
2261
+ return 0;
2262
+ }
2263
+ if (name === "debug") {
2264
+ return debug(args, values, file);
2265
+ }
2266
+ if (isPlantCommand(name)) {
2267
+ return plant(name, args, values, file);
2268
+ }
2269
+ if (args.length) {
2270
+ throw new Error("Specify one command.");
2271
+ }
2272
+ if (!isProjectCommand(name)) {
2273
+ throw new Error(`Unknown command ${name}.`);
2274
+ }
2275
+ checkProjectFlags(name, values);
2276
+ return report(await runProjectCommand(name, file, values, process.env), values.format);
2277
+ }
2278
+ function report(result, format) {
2279
+ const diagnostics = result.diagnostics ?? [];
2280
+ const ok = !hasErrors4(diagnostics);
2281
+ if (format === "json") {
2282
+ console.log(JSON.stringify({ ok, ...result }));
2283
+ } else {
2284
+ for (const diagnostic of diagnostics) {
2285
+ console.error(formatDiagnostic(diagnostic));
2286
+ }
2287
+ for (const [expression, value] of Object.entries(result.values ?? {})) {
2288
+ console.log(`${expression} = ${value}`);
2289
+ }
2290
+ if (ok) {
2291
+ console.log("tsPLC completed.");
2292
+ }
2293
+ }
2294
+ return ok ? 0 : 1;
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
+ }
2302
+ try {
2303
+ process.exitCode = await main();
2304
+ } catch (cause) {
2305
+ const json = requestedFormat(process.argv.slice(2)) === "json";
2306
+ if (cause instanceof DiagnosticFailure) {
2307
+ process.exitCode = report(cause.result, json ? "json" : undefined);
2308
+ } else {
2309
+ const message = causeMessage(cause);
2310
+ if (json) {
2311
+ console.log(JSON.stringify({
2312
+ ok: false,
2313
+ diagnostics: [
2314
+ { origin: "config", code: "PLC5003", severity: "error", message }
2315
+ ]
2316
+ }));
2317
+ } else {
2318
+ console.error(message);
2319
+ }
2320
+ process.exitCode = 1;
2321
+ }
2322
+ }
2323
+
2324
+ //# debugId=7351DCADA818881664756E2164756E21
2325
+ //# sourceMappingURL=cli.js.map