@tsplc/compiler 0.2.16 → 0.2.18

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 (157) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +920 -943
  3. package/dist/cli.js.map +13 -10
  4. package/dist/codesys.js +3893 -3352
  5. package/dist/codesys.js.map +29 -20
  6. package/dist/elaborate-capture.js +33 -17
  7. package/dist/elaborate-capture.js.map +3 -3
  8. package/dist/index.js +8787 -6855
  9. package/dist/index.js.map +40 -20
  10. package/dist/ir.js +1575 -1072
  11. package/dist/ir.js.map +21 -17
  12. package/dist/math.js.map +2 -2
  13. package/dist/project.js +154 -60
  14. package/dist/project.js.map +5 -5
  15. package/dist/telemetry.js +27 -9
  16. package/dist/telemetry.js.map +5 -5
  17. package/package.json +112 -112
  18. package/src/codesys/config.ts +50 -0
  19. package/src/codesys/debug.ts +670 -0
  20. package/src/codesys/emit.ts +142 -0
  21. package/src/codesys/engineering.ts +109 -0
  22. package/src/codesys/expressions.ts +92 -0
  23. package/src/codesys/global-lists.ts +250 -0
  24. package/src/codesys/global-names.ts +68 -0
  25. package/src/codesys/http.ts +890 -0
  26. package/src/codesys/index.ts +30 -0
  27. package/src/codesys/instrumentation.ts +430 -0
  28. package/src/codesys/io-paths.ts +140 -0
  29. package/src/codesys/manifest.ts +643 -0
  30. package/src/codesys/names.ts +81 -0
  31. package/src/codesys/numeric.ts +409 -0
  32. package/src/codesys/operands.ts +62 -0
  33. package/src/codesys/plan.ts +605 -0
  34. package/src/codesys/programs.ts +53 -0
  35. package/src/codesys/publication.ts +171 -0
  36. package/src/codesys/routines.ts +603 -0
  37. package/src/codesys/sources.ts +71 -0
  38. package/src/codesys/st-files.ts +115 -0
  39. package/src/codesys/storage.ts +97 -0
  40. package/src/codesys/symbols.ts +220 -0
  41. package/src/codesys/task-access.ts +320 -0
  42. package/src/codesys/telemetry.ts +732 -0
  43. package/src/codesys/types.ts +250 -0
  44. package/src/codesys/vendor.ts +150 -0
  45. package/src/frontend/analyzer.ts +794 -0
  46. package/src/frontend/async.ts +317 -1137
  47. package/src/frontend/blocks.ts +537 -403
  48. package/src/frontend/configuration.ts +176 -144
  49. package/src/frontend/const-functions.ts +183 -148
  50. package/src/frontend/cooperative.ts +73 -43
  51. package/src/frontend/coroutines.ts +1032 -0
  52. package/src/frontend/elaborate/calls.ts +535 -0
  53. package/src/frontend/elaborate/capture.ts +157 -101
  54. package/src/frontend/elaborate/dialect.ts +257 -0
  55. package/src/frontend/elaborate/expressions.ts +992 -0
  56. package/src/frontend/elaborate/frame.ts +53 -0
  57. package/src/frontend/elaborate/graph.ts +116 -71
  58. package/src/frontend/elaborate/imports.ts +70 -0
  59. package/src/frontend/elaborate/index.ts +435 -331
  60. package/src/frontend/elaborate/initializers.ts +198 -0
  61. package/src/frontend/elaborate/layouts.ts +591 -384
  62. package/src/frontend/elaborate/model.ts +264 -169
  63. package/src/frontend/elaborate/specialize.ts +343 -2586
  64. package/src/frontend/elaborate/statements.ts +606 -0
  65. package/src/frontend/elaborate/storage.ts +546 -0
  66. package/src/frontend/elaborate/values.ts +58 -0
  67. package/src/frontend/elaborate/writes.ts +100 -0
  68. package/src/frontend/exposure.ts +172 -140
  69. package/src/frontend/expressions.ts +1383 -0
  70. package/src/frontend/intrinsics.ts +337 -0
  71. package/src/frontend/module-graph.ts +89 -59
  72. package/src/frontend/positions.ts +271 -200
  73. package/src/frontend/promise-chains.ts +897 -0
  74. package/src/frontend/promises.ts +390 -747
  75. package/src/frontend/routines.ts +181 -0
  76. package/src/frontend/sdk.ts +82 -0
  77. package/src/frontend/services.ts +506 -372
  78. package/src/frontend/statements.ts +855 -0
  79. package/src/frontend/tasks.ts +471 -0
  80. package/src/frontend/telemetry.ts +174 -0
  81. package/src/frontend/types.ts +845 -551
  82. package/src/frontend/typescript.ts +323 -2543
  83. package/src/index.ts +5 -5
  84. package/src/ir/aggregates.ts +275 -0
  85. package/src/ir/allocation.ts +84 -0
  86. package/src/ir/core-model.ts +146 -0
  87. package/src/ir/declarations.ts +295 -0
  88. package/src/ir/diagnostics.ts +61 -0
  89. package/src/ir/domains.ts +152 -0
  90. package/src/ir/fold.ts +342 -0
  91. package/src/ir/index.ts +90 -0
  92. package/{ir/errors.ts → src/ir/job-errors.ts} +12 -10
  93. package/src/ir/layouts.ts +181 -0
  94. package/src/ir/link.ts +354 -0
  95. package/src/ir/model.ts +386 -0
  96. package/{ir → src/ir}/normalization-error.ts +4 -4
  97. package/src/ir/normalize.ts +70 -0
  98. package/src/ir/numeric.ts +171 -0
  99. package/src/ir/ranges.ts +256 -0
  100. package/src/ir/routine.ts +1163 -0
  101. package/src/ir/scalars.ts +321 -0
  102. package/src/ir/types.ts +127 -0
  103. package/src/project/artifacts.ts +342 -0
  104. package/src/project/cli.ts +177 -0
  105. package/src/project/debugger.ts +82 -0
  106. package/src/project/index.ts +6 -0
  107. package/src/project/plant.ts +467 -0
  108. package/src/project/project-commands.ts +372 -0
  109. package/src/project/project.ts +457 -0
  110. package/src/project/release.ts +153 -0
  111. package/src/project/server.ts +150 -0
  112. package/src/project/terminal.ts +32 -0
  113. package/stdlib/math.ts +14 -10
  114. package/stdlib/telemetry.ts +71 -47
  115. package/types/async.d.ts +46 -40
  116. package/types/data-types.d.ts +26 -26
  117. package/types/globals.d.ts +41 -38
  118. package/types/index.d.ts +96 -51
  119. package/types/plc.d.ts +3 -4
  120. package/types/telemetry.d.ts +14 -14
  121. package/backends/codesys/config.ts +0 -54
  122. package/backends/codesys/debug.ts +0 -509
  123. package/backends/codesys/emit.ts +0 -1738
  124. package/backends/codesys/engineering.ts +0 -88
  125. package/backends/codesys/global-names.ts +0 -49
  126. package/backends/codesys/http.ts +0 -675
  127. package/backends/codesys/index.ts +0 -13
  128. package/backends/codesys/io-paths.ts +0 -105
  129. package/backends/codesys/manifest.ts +0 -312
  130. package/backends/codesys/names.ts +0 -76
  131. package/backends/codesys/numeric.ts +0 -356
  132. package/backends/codesys/plan.ts +0 -457
  133. package/backends/codesys/publication.ts +0 -59
  134. package/backends/codesys/storage.ts +0 -70
  135. package/backends/codesys/task-access.ts +0 -293
  136. package/backends/codesys/telemetry.ts +0 -593
  137. package/backends/codesys/types.ts +0 -179
  138. package/backends/codesys/vendor.ts +0 -108
  139. package/ir/aggregates.ts +0 -333
  140. package/ir/allocation.ts +0 -74
  141. package/ir/core-model.ts +0 -129
  142. package/ir/core.ts +0 -64
  143. package/ir/declarations.ts +0 -208
  144. package/ir/diagnostics.ts +0 -43
  145. package/ir/domains.ts +0 -96
  146. package/ir/index.ts +0 -8
  147. package/ir/link.ts +0 -185
  148. package/ir/model.ts +0 -346
  149. package/ir/routine.ts +0 -859
  150. package/ir/scalars.ts +0 -675
  151. package/ir/types.ts +0 -76
  152. package/project/artifacts.ts +0 -277
  153. package/project/cli.ts +0 -395
  154. package/project/index.ts +0 -1
  155. package/project/plant.ts +0 -509
  156. package/project/project.ts +0 -358
  157. package/project/server.ts +0 -113
package/dist/cli.js CHANGED
@@ -1,100 +1,15 @@
1
1
  #!/usr/bin/env bun
2
2
  // @bun
3
3
 
4
- // packages/compiler/project/server.ts
5
- import { existsSync } from "node:fs";
6
- import { mkdtemp, mkdir, rm, rename } from "node:fs/promises";
7
- import { dirname, resolve, join } from "node:path";
8
- import { createRequire } from "node:module";
9
- import ts from "typescript";
10
- import { typeCheckOnly } from "@tsplc/compiler";
11
- var resolveServerModule = (root, name) => name.startsWith(".") || name.startsWith("/") || existsSync(resolve(root, name)) ? resolve(root, name) : createRequire(join(root, "package.json")).resolve(name);
12
- var kebabCase = (name) => name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
13
- var checkedServerEntry = (config, root) => {
14
- const runtime = config.server?.runtime;
15
- if (!runtime)
16
- throw new Error("Configure server.runtime to build the server.");
17
- const entry = resolveServerModule(root, runtime.entry);
18
- const tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);
19
- if (!tsconfig)
20
- throw new Error("Server entry requires a tsconfig.json.");
21
- const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
22
- if (read.error)
23
- throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, `
24
- `));
25
- const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname(tsconfig));
26
- const program = ts.createProgram({
27
- rootNames: [entry, ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))],
28
- options: { ...parsed.options, ...typeCheckOnly },
29
- projectReferences: parsed.projectReferences
30
- });
31
- const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
32
- if (diagnostics.length)
33
- throw new Error(ts.formatDiagnosticsWithColorAndContext(diagnostics, {
34
- getCanonicalFileName: (path) => path,
35
- getCurrentDirectory: () => root,
36
- getNewLine: () => `
37
- `
38
- }));
39
- return { entry, runtime };
40
- };
41
- var buildServer = async (config, root) => {
42
- const { entry, runtime } = checkedServerEntry(config, root);
43
- const windows = runtime.target ? runtime.target.includes("windows") : process.platform === "win32";
44
- const outFile = resolve(root, "build/server", `${kebabCase(config.name)}-services${windows ? ".exe" : ""}`);
45
- await mkdir(dirname(outFile), { recursive: true });
46
- const staging = await mkdtemp(join(dirname(outFile), ".tsplc-server-"));
47
- try {
48
- const binary = join(staging, "server");
49
- const result = await Bun.build({
50
- entrypoints: [entry],
51
- env: "disable",
52
- compile: {
53
- outfile: binary,
54
- ...runtime.target ? { target: runtime.target } : {},
55
- autoloadDotenv: false,
56
- autoloadBunfig: false,
57
- autoloadTsconfig: false,
58
- autoloadPackageJson: false
59
- }
60
- });
61
- if (!result.success)
62
- throw new AggregateError(result.logs, "Server executable build failed.");
63
- await rename(windows ? `${binary}.exe` : binary, outFile);
64
- return {
65
- server: {
66
- executable: outFile,
67
- target: runtime.target ?? `bun-${process.platform}-${process.arch}`
68
- }
69
- };
70
- } finally {
71
- await rm(staging, { recursive: true, force: true });
72
- }
73
- };
74
-
75
- // packages/compiler/project/cli.ts
76
- import { existsSync as existsSync4 } from "fs";
4
+ // packages/compiler/src/project/cli.ts
77
5
  import { parseArgs } from "util";
78
- import { relative as relative2, resolve as resolve6 } from "path";
79
- import {
80
- buildTargetFor,
81
- controllerFor as controllerFor2,
82
- loadTsplcConfig as loadTsplcConfig3,
83
- rawBuildConfig,
84
- simulationConfig as simulationConfig2
85
- } from "@tsplc/config";
86
- import {
87
- buildProject as buildSt,
88
- configureDocker,
89
- configureRuntime,
90
- inspectController,
91
- installLibraries as installLibraries3,
92
- loadSources,
93
- resolveConfig,
94
- runProject,
95
- updateController
96
- } from "@tsplc/build";
97
- import { checkHostConfig as checkHostConfig3 } from "@tsplc/compiler";
6
+ import { loadTsplcConfig as loadTsplcConfig3 } from "@tsplc/config";
7
+ import { formatDiagnostic, hasErrors as hasErrors4 } from "@tsplc/compiler/ir";
8
+
9
+ // packages/compiler/src/project/debugger.ts
10
+ import { existsSync as existsSync3 } from "node:fs";
11
+ import { relative as relative2, resolve as resolve4 } from "node:path";
12
+ import { serverTokenEnv as serverTokenEnv2 } from "@tsplc/config";
98
13
  import {
99
14
  createDebugger,
100
15
  createLoginAdapter,
@@ -103,29 +18,43 @@ import {
103
18
  opcUaConnection,
104
19
  serveDebugger
105
20
  } from "@tsplc/debug";
106
- import { formatDiagnostic, hasErrors as hasErrors4 } from "@tsplc/compiler/ir";
107
- import { deviceTree as deviceTree3 } from "@tsplc/typegen";
108
- import { loadHardware as loadHardware3, resolveIo as resolveIo3 } from "@tsplc/typegen/hardware";
109
- import { generateProject as generateProject2 } from "@tsplc/typegen";
110
21
 
111
- // packages/compiler/project/plant.ts
112
- import { existsSync as existsSync3 } from "node:fs";
113
- import { basename, relative, resolve as resolve4, sep } from "node:path";
114
- import { createInterface } from "node:readline/promises";
115
- import { pathToFileURL } from "node:url";
22
+ // packages/compiler/src/project/plant.ts
116
23
  import {
117
24
  AgentOperationError,
118
25
  createAgentClient
119
26
  } from "@tsplc/agent/client";
120
- import { controllerFor, simulationConfig } from "@tsplc/config";
27
+ import {
28
+ ask as ask2,
29
+ askCredentials
30
+ } from "@tsplc/agent";
121
31
  import { LoginUnavailable, noLogin } from "@tsplc/debug";
32
+ import { z as z3 } from "zod";
33
+
34
+ // packages/compiler/src/project/release.ts
35
+ import { existsSync as existsSync2 } from "node:fs";
36
+ import { basename, relative, resolve as resolve3, sep } from "node:path";
37
+ import { pathToFileURL } from "node:url";
38
+ import {
39
+ buildTargetFor,
40
+ controllerFor,
41
+ serverTokenEnv
42
+ } from "@tsplc/config";
122
43
  import { hasErrors as hasErrors2 } from "@tsplc/compiler/ir";
44
+ import { contractVariables } from "@tsplc/opcua/contract";
123
45
  import { generateProject } from "@tsplc/typegen";
124
- import { z } from "zod";
46
+ import { z as z2 } from "zod";
125
47
 
126
- // packages/compiler/project/project.ts
127
- import { copyFile, mkdir as mkdir3, mkdtemp as mkdtemp2, realpath, rm as rm3, writeFile as writeFile2 } from "node:fs/promises";
128
- import { dirname as dirname3, join as join3, resolve as resolve2 } from "node:path";
48
+ // packages/compiler/src/project/project.ts
49
+ import {
50
+ copyFile,
51
+ mkdir as mkdir2,
52
+ mkdtemp,
53
+ realpath,
54
+ rm as rm2,
55
+ writeFile as writeFile2
56
+ } from "node:fs/promises";
57
+ import { dirname as dirname2, join as join2, resolve } from "node:path";
129
58
  import {
130
59
  buildCodesys,
131
60
  codesysBuildConfig,
@@ -138,32 +67,74 @@ import {
138
67
  import { analyze, checkHostConfig } from "@tsplc/compiler";
139
68
  import {
140
69
  compilerConfig,
141
- loadTsplcConfig
70
+ loadTsplcConfig,
71
+ simulationConfig
142
72
  } from "@tsplc/config";
143
- import { deviceTree, loadHardware, resolveIo } from "@tsplc/typegen";
73
+ import {
74
+ deviceTree,
75
+ loadHardware,
76
+ resolveIo
77
+ } from "@tsplc/typegen";
144
78
  import { installLibraries } from "@tsplc/build";
145
- import { hasErrors, normalizeModule } from "@tsplc/compiler/ir";
79
+ import {
80
+ hasErrors,
81
+ normalizeModule
82
+ } from "@tsplc/compiler/ir";
146
83
 
147
- // packages/compiler/project/artifacts.ts
84
+ // packages/compiler/src/project/artifacts.ts
148
85
  import { createHash } from "node:crypto";
149
- import { lstat, mkdir as mkdir2, readdir, readFile, rename as rename2, rm as rm2, writeFile } from "node:fs/promises";
150
- import { dirname as dirname2, join as join2 } from "node:path";
86
+ import {
87
+ lstat,
88
+ mkdir,
89
+ readdir,
90
+ readFile,
91
+ rename,
92
+ rm,
93
+ writeFile
94
+ } from "node:fs/promises";
95
+ import { dirname, join } from "node:path";
96
+ import { sha256Digest } from "@tsplc/config/build";
97
+ import { z } from "zod";
151
98
  var missing = (cause) => cause instanceof Error && ("code" in cause) && cause.code === "ENOENT";
152
99
  var digest = (value) => createHash("sha256").update(value).digest("hex");
100
+ var generatedFileSchema = z.object({
101
+ path: z.string().regex(/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/).refine((path) => !path.split("/").some((part) => part === "." || part === "..") && !["manifest.json", "receipt.json"].includes(path)),
102
+ sha256: sha256Digest
103
+ });
104
+ var manifestSchema = z.object({
105
+ kind: z.literal("tsplc-artifacts"),
106
+ version: z.literal(1),
107
+ configFile: z.string(),
108
+ files: z.array(z.unknown())
109
+ });
110
+ var buildStatusSchema = z.enum(["emitted", "vendor-compiled"]);
111
+ var receiptSchema = z.object({
112
+ kind: z.literal("tsplc-build"),
113
+ version: z.literal(1),
114
+ configFile: z.string(),
115
+ status: buildStatusSchema
116
+ });
117
+ var engineeringMarkerSchema = z.object({
118
+ kind: z.literal("tsplc-engineering"),
119
+ version: z.literal(1),
120
+ configFile: z.string()
121
+ });
153
122
  function manifest(value, configFile) {
154
- if (typeof value !== "object" || value === null || !("kind" in value) || value.kind !== "tsplc-artifacts" || !("version" in value) || value.version !== 1 || !("configFile" in value) || value.configFile !== configFile || !("files" in value) || !Array.isArray(value.files)) {
123
+ const parsed = manifestSchema.safeParse(value);
124
+ if (!parsed.success || parsed.data.configFile !== configFile) {
155
125
  throw new Error("Output directory has no matching tsPLC ownership manifest.");
156
126
  }
157
- const files = value.files.map((item) => {
158
- if (typeof item !== "object" || item === null || !("path" in item) || typeof item.path !== "string" || !/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/.test(item.path) || item.path.split("/").some((part) => part === "." || part === "..") || ["manifest.json", "receipt.json"].includes(item.path) || !("sha256" in item) || typeof item.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(item.sha256)) {
127
+ const files = parsed.data.files.map((item) => {
128
+ const file = generatedFileSchema.safeParse(item);
129
+ if (!file.success) {
159
130
  throw new Error("Invalid generated file ownership entry.");
160
131
  }
161
- return { path: item.path, sha256: item.sha256 };
132
+ return file.data;
162
133
  });
163
134
  if (new Set(files.map((item) => item.path)).size !== files.length) {
164
135
  throw new Error("Duplicate generated file ownership entry.");
165
136
  }
166
- return { kind: "tsplc-artifacts", version: 1, configFile, files };
137
+ return { ...parsed.data, files };
167
138
  }
168
139
  async function directory(path) {
169
140
  try {
@@ -184,7 +155,7 @@ async function filesIn(path, prefix = "") {
184
155
  for (const entry of await readdir(path, { withFileTypes: true })) {
185
156
  const name = prefix + entry.name;
186
157
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
187
- result.push(...await filesIn(join2(path, entry.name), `${name}/`));
158
+ result.push(...await filesIn(join(path, entry.name), `${name}/`));
188
159
  } else {
189
160
  result.push(name);
190
161
  }
@@ -192,10 +163,10 @@ async function filesIn(path, prefix = "") {
192
163
  return result;
193
164
  }
194
165
  async function engineeringDirectory(path, configFile) {
195
- const marker = join2(path, "ownership.json");
166
+ const marker = join(path, "ownership.json");
196
167
  const exists = await directory(path);
197
168
  if (!exists || !(await readdir(path)).length) {
198
- await mkdir2(path, { recursive: true });
169
+ await mkdir(path, { recursive: true });
199
170
  await writeFile(marker, `${JSON.stringify({ kind: "tsplc-engineering", version: 1, configFile }, null, 2)}
200
171
  `, { flag: "wx" });
201
172
  } else {
@@ -208,14 +179,14 @@ async function engineeringDirectory(path, configFile) {
208
179
  if (!entry.isFile() || entry.isSymbolicLink()) {
209
180
  throw new Error("Engineering ownership marker must be a real file.");
210
181
  }
211
- const value = JSON.parse(await readFile(marker, "utf8"));
212
- if (value?.kind !== "tsplc-engineering" || value.version !== 1 || value.configFile !== configFile) {
182
+ const value = engineeringMarkerSchema.safeParse(JSON.parse(await readFile(marker, "utf8")));
183
+ if (!value.success || value.data.configFile !== configFile) {
213
184
  throw new Error(`Engineering cache has no matching tsPLC ownership marker: ${path}`);
214
185
  }
215
186
  }
216
187
  const inspect = async (directory) => {
217
188
  for (const entry of await readdir(directory, { withFileTypes: true })) {
218
- const child = join2(directory, entry.name);
189
+ const child = join(directory, entry.name);
219
190
  if (entry.isSymbolicLink()) {
220
191
  throw new Error(`Engineering cache must not contain symlinks: ${child}`);
221
192
  }
@@ -227,29 +198,29 @@ async function engineeringDirectory(path, configFile) {
227
198
  await inspect(path);
228
199
  }
229
200
  async function owned(configFile, withdrawReceipt = false) {
230
- const root = join2(dirname2(configFile), ".tsplc");
231
- const output = join2(root, "artifacts");
201
+ const root = join(dirname(configFile), ".tsplc");
202
+ const output = join(root, "artifacts");
232
203
  if (!await directory(root) || !await directory(output)) {
233
204
  return { root, output, unknown: [] };
234
205
  }
235
- const manifestPath = join2(output, "manifest.json");
206
+ const manifestPath = join(output, "manifest.json");
236
207
  const manifestEntry = await lstat(manifestPath);
237
208
  if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
238
209
  throw new Error("Ownership manifest must be a real file.");
239
210
  }
240
211
  const ownership = manifest(JSON.parse(await readFile(manifestPath, "utf8")), configFile);
241
- const receipt = join2(output, "receipt.json");
212
+ const receipt = join(output, "receipt.json");
242
213
  try {
243
214
  const entry = await lstat(receipt);
244
215
  if (!entry.isFile() || entry.isSymbolicLink()) {
245
216
  throw new Error("Build receipt must be a real file.");
246
217
  }
247
- const value = JSON.parse(await readFile(receipt, "utf8"));
248
- if (value?.kind !== "tsplc-build" || value.version !== 1 || value.configFile !== configFile || !["emitted", "vendor-compiled"].includes(value.status)) {
218
+ const value = receiptSchema.safeParse(JSON.parse(await readFile(receipt, "utf8")));
219
+ if (!value.success || value.data.configFile !== configFile) {
249
220
  throw new Error("Build receipt is not owned by this configuration.");
250
221
  }
251
222
  if (withdrawReceipt) {
252
- await rm2(receipt);
223
+ await rm(receipt);
253
224
  }
254
225
  } catch (cause) {
255
226
  if (!missing(cause)) {
@@ -264,12 +235,12 @@ async function owned(configFile, withdrawReceipt = false) {
264
235
  for (const file of ownership.files) {
265
236
  let parent = output;
266
237
  for (const part of file.path.split("/").slice(0, -1)) {
267
- parent = join2(parent, part);
238
+ parent = join(parent, part);
268
239
  if (!await directory(parent)) {
269
240
  throw new Error(`Missing generated directory: ${parent}`);
270
241
  }
271
242
  }
272
- const path = join2(output, file.path);
243
+ const path = join(output, file.path);
273
244
  const entry = await lstat(path);
274
245
  if (!entry.isFile() || entry.isSymbolicLink() || digest(await readFile(path)) !== file.sha256) {
275
246
  throw new Error(`Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`);
@@ -285,13 +256,26 @@ async function owned(configFile, withdrawReceipt = false) {
285
256
  async function publishArtifacts(staging, previous, receipt) {
286
257
  const configFile = receipt.configFile;
287
258
  const generated = (await filesIn(staging)).sort();
288
- const ownership = { kind: "tsplc-artifacts", version: 1, configFile, files: [] };
259
+ const ownership = {
260
+ kind: "tsplc-artifacts",
261
+ version: 1,
262
+ configFile,
263
+ files: []
264
+ };
289
265
  for (const path of generated) {
290
- ownership.files.push({ path, sha256: digest(await readFile(join2(staging, path))) });
266
+ ownership.files.push({
267
+ path,
268
+ sha256: digest(await readFile(join(staging, path)))
269
+ });
291
270
  }
292
- await writeFile(join2(staging, "manifest.json"), `${JSON.stringify(ownership, null, 2)}
271
+ await writeFile(join(staging, "manifest.json"), `${JSON.stringify(ownership, null, 2)}
293
272
  `);
294
- await writeFile(join2(staging, "receipt.json"), `${JSON.stringify({ kind: "tsplc-build", version: 1, generatedAt: new Date().toISOString(), ...receipt }, null, 2)}
273
+ await writeFile(join(staging, "receipt.json"), `${JSON.stringify({
274
+ kind: "tsplc-build",
275
+ version: 1,
276
+ generatedAt: new Date().toISOString(),
277
+ ...receipt
278
+ }, null, 2)}
295
279
  `);
296
280
  const current = await owned(configFile);
297
281
  if (JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)) {
@@ -302,18 +286,18 @@ async function publishArtifacts(staging, previous, receipt) {
302
286
  }
303
287
  const backup = `${staging}-previous`;
304
288
  if (previous.ownership) {
305
- await rename2(previous.output, backup);
289
+ await rename(previous.output, backup);
306
290
  }
307
291
  try {
308
- await rename2(staging, previous.output);
292
+ await rename(staging, previous.output);
309
293
  } catch (cause) {
310
294
  if (previous.ownership) {
311
- await rename2(backup, previous.output);
295
+ await rename(backup, previous.output);
312
296
  }
313
297
  throw cause;
314
298
  }
315
299
  if (previous.ownership) {
316
- await rm2(backup, { recursive: true });
300
+ await rm(backup, { recursive: true });
317
301
  }
318
302
  }
319
303
  async function cleanArtifacts(configFile) {
@@ -322,39 +306,44 @@ async function cleanArtifacts(configFile) {
322
306
  return;
323
307
  }
324
308
  for (const entry of generated.ownership.files) {
325
- await rm2(join2(generated.output, entry.path));
309
+ await rm(join(generated.output, entry.path));
326
310
  }
327
- await rm2(join2(generated.output, "receipt.json"), { force: true });
328
- await rm2(join2(generated.output, "manifest.json"));
311
+ await rm(join(generated.output, "receipt.json"), { force: true });
312
+ await rm(join(generated.output, "manifest.json"));
329
313
  const removeEmpty = async (path) => {
330
314
  for (const entry of await readdir(path, { withFileTypes: true })) {
331
315
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
332
- await removeEmpty(join2(path, entry.name));
316
+ await removeEmpty(join(path, entry.name));
333
317
  }
334
318
  }
335
319
  if (!(await readdir(path)).length) {
336
- await rm2(path, { recursive: true });
320
+ await rm(path, { recursive: true });
337
321
  }
338
322
  };
339
323
  await removeEmpty(generated.output);
340
324
  }
341
325
 
342
- // packages/compiler/project/project.ts
326
+ // packages/compiler/src/project/project.ts
343
327
  var failure = (origin, code, cause) => ({
344
328
  origin,
345
329
  code,
346
330
  severity: "error",
347
331
  message: cause instanceof Error ? cause.message : String(cause)
348
332
  });
349
- async function loadProject(file, loaded, buildTarget, configured) {
350
- let configFile = resolve2(file);
333
+ var buildConfigs = (loaded, options) => options.simulate ? {
334
+ loaded: { ...loaded, config: simulationConfig(loaded.config) },
335
+ configured: loaded.config
336
+ } : { loaded };
337
+ async function loadProject(file, { loaded, buildTarget, configured, hostConfigDiagnostics }) {
338
+ let configFile = resolve(file);
351
339
  try {
352
340
  configFile = await realpath(configFile);
353
- const diagnostics = checkHostConfig(configFile);
354
- if (hasErrors(diagnostics))
341
+ const diagnostics = hostConfigDiagnostics ?? checkHostConfig(configFile);
342
+ if (hasErrors(diagnostics)) {
355
343
  return { configFile, diagnostics };
356
- const shared = (loaded ?? await loadTsplcConfig(configFile)).config;
357
- const root = dirname3(configFile);
344
+ }
345
+ const { config: shared, env } = loaded ?? await loadTsplcConfig(configFile);
346
+ const root = dirname2(configFile);
358
347
  const catalog = await loadHardware(shared, root);
359
348
  const config = compilerConfig(shared, resolveIo(shared, catalog), buildTarget);
360
349
  return {
@@ -363,6 +352,7 @@ async function loadProject(file, loaded, buildTarget, configured) {
363
352
  config: { ...config, ...sourceInput(config, root) },
364
353
  project: {
365
354
  root,
355
+ env,
366
356
  ...shared.debug && { debug: shared.debug },
367
357
  ...shared.telemetry && { telemetry: shared.telemetry },
368
358
  ...shared.server && { server: shared.server },
@@ -380,27 +370,29 @@ async function loadProject(file, loaded, buildTarget, configured) {
380
370
  }
381
371
  function sourceInput(compiler, root) {
382
372
  return {
383
- tsconfig: resolve2(root, compiler.tsconfig),
373
+ tsconfig: resolve(root, compiler.tsconfig),
384
374
  programs: Object.fromEntries(Object.entries(compiler.programs).map(([name, entry]) => [
385
375
  name,
386
- { ...entry, module: resolve2(root, entry.module) }
376
+ { ...entry, module: resolve(root, entry.module) }
387
377
  ]))
388
378
  };
389
379
  }
390
380
  async function projectTargets(file = "tsplc.config.ts", options = {}) {
391
- const configFile = await realpath(resolve2(file));
392
- const { config } = options.loaded ?? await loadTsplcConfig(configFile);
393
- if (!config.compiler)
381
+ const configFile = await realpath(resolve(file));
382
+ const { config, env } = options.loaded ?? await loadTsplcConfig(configFile);
383
+ if (!config.compiler) {
394
384
  return;
385
+ }
395
386
  const source = analyze({
396
- ...sourceInput(config.compiler, dirname3(configFile)),
397
- services: config.server
387
+ ...sourceInput(config.compiler, dirname2(configFile)),
388
+ services: config.server,
389
+ env
398
390
  });
399
391
  const core = source.module && normalizeModule(source.module).core;
400
392
  return core ? { io: ioTargets(core), publication: publicationSelectors(core) } : undefined;
401
393
  }
402
394
  async function checkProject(file = "tsplc.config.ts", options = {}) {
403
- const loaded = await loadProject(file, options.loaded, options.buildTarget, options.configured);
395
+ const loaded = await loadProject(file, options);
404
396
  if (!loaded.config || !loaded.project) {
405
397
  return loaded;
406
398
  }
@@ -408,13 +400,16 @@ async function checkProject(file = "tsplc.config.ts", options = {}) {
408
400
  if (config.target.kind !== "codesys") {
409
401
  return {
410
402
  ...loaded,
411
- diagnostics: [failure("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)]
403
+ diagnostics: [
404
+ failure("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)
405
+ ]
412
406
  };
413
407
  }
414
408
  const source = analyze({
415
409
  tsconfig: config.tsconfig,
416
410
  programs: config.programs,
417
- services: loaded.shared?.server
411
+ services: loaded.shared?.server,
412
+ env: loaded.project.env
418
413
  });
419
414
  if (!source.module) {
420
415
  return { ...loaded, diagnostics: source.diagnostics };
@@ -441,30 +436,29 @@ async function checkProject(file = "tsplc.config.ts", options = {}) {
441
436
  ]
442
437
  };
443
438
  }
444
- async function engineeringInputs(shared, configFile, bundle, frozen) {
445
- const root = dirname3(configFile);
439
+ async function engineeringInputs(shared, configFile, bundle, options) {
440
+ const root = dirname2(configFile);
446
441
  const tree = await deviceTree(shared, await loadHardware(shared, root));
447
442
  return {
448
- libraries: await installLibraries(shared.dependencies, root, { frozen }),
443
+ libraries: await installLibraries(shared.dependencies, root, options),
449
444
  deviceTree: tree && {
450
445
  ...tree,
451
- mappings: bundle.ioMappings.map(({ address, variable }) => ({ address, variable }))
446
+ mappings: bundle.ioMappings.map(({ address, variable }) => ({
447
+ address,
448
+ variable
449
+ }))
452
450
  }
453
451
  };
454
452
  }
455
453
  async function buildProject(file = "tsplc.config.ts", options = {}) {
456
454
  let staging;
457
455
  try {
458
- const configFile = await realpath(resolve2(file));
456
+ const configFile = await realpath(resolve(file));
459
457
  const previous = await owned(configFile, true);
460
458
  if (previous.unknown.length) {
461
459
  throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
462
460
  }
463
- const checked = await checkProject(configFile, {
464
- loaded: options.loaded,
465
- buildTarget: options.buildTarget,
466
- configured: options.configured
467
- });
461
+ const checked = await checkProject(configFile, options);
468
462
  if (!checked.plan || !checked.config) {
469
463
  return { diagnostics: checked.diagnostics };
470
464
  }
@@ -473,43 +467,58 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
473
467
  return { diagnostics: bundle.diagnostics };
474
468
  }
475
469
  const shared = checked.shared;
476
- const engineering = shared && (!options.emitOnly || options.forController) ? await engineeringInputs(shared, configFile, bundle, options.frozenLockfile) : undefined;
477
- const controllerConfig = shared?.build ? codesysBuildConfig(checked.plan, bundle, {
470
+ const engineering = shared && (!options.emitOnly || options.forController) ? await engineeringInputs(shared, configFile, bundle, {
471
+ frozen: options.frozenLockfile
472
+ }) : undefined;
473
+ const outDir = shared?.build && resolve(dirname2(configFile), shared.build.outDir);
474
+ const controllerConfig = outDir ? codesysBuildConfig(checked.plan, bundle, {
478
475
  configFile,
479
- sourceDir: join3(previous.output, "st"),
480
- outDir: resolve2(dirname3(configFile), shared.build.outDir),
476
+ sourceDir: join2(previous.output, "st"),
477
+ outDir,
481
478
  controller: options.controller,
482
479
  ...engineering
483
480
  }) : undefined;
484
- await mkdir3(previous.root, { recursive: true });
485
- staging = await mkdtemp2(join3(previous.root, "stage-"));
481
+ await mkdir2(previous.root, { recursive: true });
482
+ staging = await mkdtemp(join2(previous.root, "stage-"));
486
483
  const artifacts = [
487
484
  ...bundle.artifacts,
488
- { path: "mappings.json", content: `${JSON.stringify(compactMappings(bundle.mappings))}
489
- ` },
490
- { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
491
- ` },
492
- { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}
493
- ` },
494
- { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}
495
- ` },
485
+ {
486
+ path: "mappings.json",
487
+ content: `${JSON.stringify(compactMappings(bundle.mappings))}
488
+ `
489
+ },
490
+ {
491
+ path: "io-symbols.json",
492
+ content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
493
+ `
494
+ },
495
+ {
496
+ path: "publication.json",
497
+ content: `${JSON.stringify(bundle.publication, null, 2)}
498
+ `
499
+ },
500
+ {
501
+ path: "config.json",
502
+ content: `${JSON.stringify(checked.config, null, 2)}
503
+ `
504
+ },
496
505
  ...bundle.debug ? [{ path: "debug.json", content: `${JSON.stringify(bundle.debug)}
497
506
  ` }] : []
498
507
  ];
499
508
  for (const artifact of artifacts) {
500
- const path = join3(staging, "st", artifact.path);
501
- await mkdir3(dirname3(path), { recursive: true });
509
+ const path = join2(staging, "st", artifact.path);
510
+ await mkdir2(dirname2(path), { recursive: true });
502
511
  await writeFile2(path, artifact.content);
503
512
  }
504
513
  let vendor;
505
514
  if (!options.emitOnly) {
506
- const outDir = shared?.build ? resolve2(dirname3(configFile), shared.build.outDir ?? "build") : join3(previous.root, "engineering");
507
- await engineeringDirectory(outDir, configFile);
515
+ const engineeringDir = outDir ?? join2(previous.root, "engineering");
516
+ await engineeringDirectory(engineeringDir, configFile);
508
517
  try {
509
518
  vendor = await buildCodesys(checked.plan, bundle, {
510
519
  configFile,
511
- sourceDir: join3(staging, "st"),
512
- outDir,
520
+ sourceDir: join2(staging, "st"),
521
+ outDir: engineeringDir,
513
522
  controller: options.controller,
514
523
  ...engineering
515
524
  });
@@ -522,10 +531,11 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
522
531
  ["Application.crc", vendor.checksum]
523
532
  ];
524
533
  for (const [name, path] of vendorArtifacts) {
525
- if (!path)
534
+ if (!path) {
526
535
  continue;
527
- const destination = join3(staging, "vendor", name);
528
- await mkdir3(dirname3(destination), { recursive: true });
536
+ }
537
+ const destination = join2(staging, "vendor", name);
538
+ await mkdir2(dirname2(destination), { recursive: true });
529
539
  await copyFile(path, destination);
530
540
  }
531
541
  }
@@ -533,7 +543,9 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
533
543
  await publishArtifacts(staging, previous, {
534
544
  configFile,
535
545
  status,
536
- ...vendor && { vendor: { application: vendor.application, tasks: vendor.tasks } }
546
+ ...vendor && {
547
+ vendor: { application: vendor.application, tasks: vendor.tasks }
548
+ }
537
549
  });
538
550
  staging = undefined;
539
551
  return {
@@ -546,16 +558,20 @@ async function buildProject(file = "tsplc.config.ts", options = {}) {
546
558
  return { diagnostics: [failure("config", "PLC5004", cause)] };
547
559
  } finally {
548
560
  if (staging) {
549
- await rm3(staging, { recursive: true, force: true });
561
+ await rm2(staging, { recursive: true, force: true });
550
562
  }
551
563
  }
552
564
  }
553
565
  function compactMappings(mappings) {
554
- const objects = new Map, files = new Map;
566
+ const objects = new Map;
567
+ const files = new Map;
555
568
  const index = (table, value) => {
556
- if (!table.has(value))
557
- table.set(value, table.size);
558
- return table.get(value);
569
+ const known = table.get(value);
570
+ if (known !== undefined) {
571
+ return known;
572
+ }
573
+ table.set(value, table.size);
574
+ return table.size - 1;
559
575
  };
560
576
  const rows = mappings.map(({ path, line, span }) => [
561
577
  index(objects, path),
@@ -566,224 +582,161 @@ function compactMappings(mappings) {
566
582
  span.line,
567
583
  span.column
568
584
  ]);
569
- return { objects: [...objects.keys()], files: [...files.keys()], mappings: rows };
585
+ return {
586
+ objects: [...objects.keys()],
587
+ files: [...files.keys()],
588
+ mappings: rows
589
+ };
590
+ }
591
+ async function cleanProject(file = "tsplc.config.ts") {
592
+ try {
593
+ await cleanArtifacts(await realpath(resolve(file)));
594
+ return { diagnostics: [] };
595
+ } catch (cause) {
596
+ return { diagnostics: [failure("config", "PLC5004", cause)] };
597
+ }
570
598
  }
571
599
 
572
- // packages/compiler/project/server.ts
573
- import { existsSync as existsSync2 } from "node:fs";
574
- import { mkdtemp as mkdtemp3, mkdir as mkdir4, rm as rm4, rename as rename3 } from "node:fs/promises";
575
- import { dirname as dirname4, resolve as resolve3, join as join4 } from "node:path";
576
- import { createRequire as createRequire2 } from "node:module";
577
- import ts2 from "typescript";
578
- import { typeCheckOnly as typeCheckOnly2 } from "@tsplc/compiler";
579
- var resolveServerModule2 = (root, name) => name.startsWith(".") || name.startsWith("/") || existsSync2(resolve3(root, name)) ? resolve3(root, name) : createRequire2(join4(root, "package.json")).resolve(name);
580
- var kebabCase2 = (name) => name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
581
- var checkedServerEntry2 = (config, root) => {
600
+ // packages/compiler/src/project/server.ts
601
+ import { existsSync } from "node:fs";
602
+ import { mkdtemp as mkdtemp2, mkdir as mkdir3, rm as rm3, rename as rename2 } from "node:fs/promises";
603
+ import { dirname as dirname3, resolve as resolve2, join as join3 } from "node:path";
604
+ import { createRequire } from "node:module";
605
+ import ts from "typescript";
606
+ import { typeCheckOnly } from "@tsplc/compiler";
607
+ var resolveServerModule = (root, name) => name.startsWith(".") || name.startsWith("/") || existsSync(resolve2(root, name)) ? resolve2(root, name) : createRequire(join3(root, "package.json")).resolve(name);
608
+ var kebabCase = (name) => name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase();
609
+ var serverOutput = (config, root, extension) => resolve2(root, "build/server", `${kebabCase(config.name)}-services${extension}`);
610
+ var checkedServerEntry = (config, root) => {
582
611
  const runtime = config.server?.runtime;
583
- if (!runtime)
612
+ if (!runtime) {
584
613
  throw new Error("Configure server.runtime to build the server.");
585
- const entry = resolveServerModule2(root, runtime.entry);
586
- const tsconfig = ts2.findConfigFile(dirname4(entry), ts2.sys.fileExists);
587
- if (!tsconfig)
614
+ }
615
+ const entry = resolveServerModule(root, runtime.entry);
616
+ const tsconfig = ts.findConfigFile(dirname3(entry), ts.sys.fileExists);
617
+ if (!tsconfig) {
588
618
  throw new Error("Server entry requires a tsconfig.json.");
589
- const read = ts2.readConfigFile(tsconfig, ts2.sys.readFile);
590
- if (read.error)
591
- throw new Error(ts2.flattenDiagnosticMessageText(read.error.messageText, `
619
+ }
620
+ const read = ts.readConfigFile(tsconfig, ts.sys.readFile);
621
+ if (read.error) {
622
+ throw new Error(ts.flattenDiagnosticMessageText(read.error.messageText, `
592
623
  `));
593
- const parsed = ts2.parseJsonConfigFileContent(read.config, ts2.sys, dirname4(tsconfig));
594
- const program = ts2.createProgram({
595
- rootNames: [entry, ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))],
596
- options: { ...parsed.options, ...typeCheckOnly2 },
624
+ }
625
+ const parsed = ts.parseJsonConfigFileContent(read.config, ts.sys, dirname3(tsconfig));
626
+ const program = ts.createProgram({
627
+ rootNames: [
628
+ entry,
629
+ ...parsed.fileNames.filter((file) => /\.d\.[cm]?ts$/.test(file))
630
+ ],
631
+ options: { ...parsed.options, ...typeCheckOnly },
597
632
  projectReferences: parsed.projectReferences
598
633
  });
599
- const diagnostics = [...parsed.errors, ...ts2.getPreEmitDiagnostics(program)];
600
- if (diagnostics.length)
601
- throw new Error(ts2.formatDiagnosticsWithColorAndContext(diagnostics, {
634
+ const diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];
635
+ if (diagnostics.length) {
636
+ throw new Error(ts.formatDiagnosticsWithColorAndContext(diagnostics, {
602
637
  getCanonicalFileName: (path) => path,
603
638
  getCurrentDirectory: () => root,
604
639
  getNewLine: () => `
605
640
  `
606
641
  }));
642
+ }
607
643
  return { entry, runtime };
608
644
  };
609
645
  var bundleServer = async (config, root) => {
610
- const { entry } = checkedServerEntry2(config, root);
611
- const outFile = resolve3(root, "build/server", `${kebabCase2(config.name)}-services.js`);
646
+ const { entry } = checkedServerEntry(config, root);
647
+ const outFile = serverOutput(config, root, ".js");
612
648
  const result = await Bun.build({
613
649
  entrypoints: [entry],
614
650
  target: "bun",
615
651
  minify: true,
616
652
  env: "disable"
617
653
  });
618
- if (!result.success)
654
+ if (!result.success) {
619
655
  throw new AggregateError(result.logs, "Server bundle build failed.");
656
+ }
620
657
  const [script, ...assets] = result.outputs;
621
- if (!script || assets.length)
658
+ if (!script || assets.length) {
622
659
  throw new Error(`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(", ")}), which deployments don't carry.`);
623
- await mkdir4(dirname4(outFile), { recursive: true });
660
+ }
661
+ await mkdir3(dirname3(outFile), { recursive: true });
624
662
  await Bun.write(outFile, script);
625
663
  return outFile;
626
664
  };
627
-
628
- // packages/compiler/project/plant.ts
629
- var plantCommands = new Set([
630
- "deploy",
631
- "target",
632
- "status",
633
- "login",
634
- "logout",
635
- "vars",
636
- "read",
637
- "write",
638
- "force",
639
- "unforce",
640
- "start",
641
- "stop",
642
- "reset"
643
- ]);
644
- var ask = async (question) => {
645
- const lines = createInterface({ input: process.stdin, output: process.stdout });
665
+ var buildServer = async (config, root) => {
666
+ const { entry, runtime } = checkedServerEntry(config, root);
667
+ const windows = runtime.target ? runtime.target.includes("windows") : process.platform === "win32";
668
+ const outFile = serverOutput(config, root, windows ? ".exe" : "");
669
+ await mkdir3(dirname3(outFile), { recursive: true });
670
+ const staging = await mkdtemp2(join3(dirname3(outFile), ".tsplc-server-"));
646
671
  try {
647
- return (await lines.question(question)).trim();
648
- } finally {
649
- lines.close();
650
- }
651
- };
652
- var askSecret = (question) => new Promise((accept, reject) => {
653
- if (!process.stdin.isTTY) {
654
- reject(new Error("The controller password needs an interactive terminal."));
655
- return;
656
- }
657
- process.stdin.setRawMode(true);
658
- process.stdin.setEncoding("utf8");
659
- process.stdin.resume();
660
- process.stdout.write(question);
661
- let secret = "";
662
- const finish = () => {
663
- process.stdin.off("data", read);
664
- process.stdin.setRawMode(false);
665
- process.stdin.pause();
666
- process.stdout.write(`
667
- `);
668
- };
669
- const read = (text) => {
670
- for (const character of text) {
671
- if (character === "\r" || character === `
672
- `) {
673
- finish();
674
- accept(secret);
675
- return;
676
- }
677
- if (character === "\x03") {
678
- finish();
679
- reject(new Error("Cancelled."));
680
- return;
672
+ const binary = join3(staging, "server");
673
+ const result = await Bun.build({
674
+ entrypoints: [entry],
675
+ env: "disable",
676
+ compile: {
677
+ outfile: binary,
678
+ ...runtime.target ? { target: runtime.target } : {},
679
+ autoloadDotenv: false,
680
+ autoloadBunfig: false,
681
+ autoloadTsconfig: false,
682
+ autoloadPackageJson: false
681
683
  }
682
- secret = character === "" ? secret.slice(0, -1) : secret + character;
684
+ });
685
+ if (!result.success) {
686
+ throw new AggregateError(result.logs, "Server executable build failed.");
683
687
  }
684
- };
685
- process.stdin.on("data", read);
686
- });
687
- var choose = async (question, items, label) => {
688
- items.forEach((item, index) => console.log(` ${index + 1}. ${label(item)}`));
689
- while (true) {
690
- const item = items[Number(await ask(`${question} [1-${items.length}]: `)) - 1];
691
- if (item !== undefined)
692
- return item;
693
- }
694
- };
695
- var confirm = async (question, flags) => flags.yes || /^y(es)?$/i.test(await ask(`${question} [y/N]: `));
696
- var askCredentials = async () => ({
697
- username: await ask("Controller username: "),
698
- password: await askSecret("Controller password: ")
699
- });
700
- var progress = (message) => console.log(` ${message}`);
701
- var timedProgress = () => {
702
- const start = Date.now();
703
- return (message) => {
704
- const seconds = Math.round((Date.now() - start) / 1000);
705
- progress(`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} ${message}`);
706
- };
707
- };
708
- var connect = () => {
709
- const environment = z.object({
710
- TSPLC_AGENT_URL: z.url({
711
- error: "Set TSPLC_AGENT_URL to the plant agent, such as http://line-pc:4850"
712
- }),
713
- TSPLC_AGENT_TOKEN: z.string({ error: "Set TSPLC_AGENT_TOKEN to the plant agent's token" })
714
- }).parse(process.env);
715
- return createAgentClient({
716
- url: environment.TSPLC_AGENT_URL,
717
- token: environment.TSPLC_AGENT_TOKEN
718
- });
719
- };
720
- var readThroughAgent = (agent) => async ([first, ...rest]) => {
721
- if (!first)
722
- return {};
723
- try {
724
- const result = await agent.command({ command: "read", expressions: [first, ...rest] });
725
- if (!("values" in result))
726
- throw new Error("The agent answered a read without values");
727
- return result.values;
728
- } catch (error) {
729
- const { login } = await agent.status();
730
- if (!login)
731
- throw new LoginUnavailable(noLogin, { cause: error });
732
- if ("error" in login)
733
- throw new Error(login.error, { cause: error });
734
- throw error;
688
+ await rename2(windows ? `${binary}.exe` : binary, outFile);
689
+ return {
690
+ server: {
691
+ executable: outFile,
692
+ target: runtime.target ?? `bun-${process.platform}-${process.arch}`
693
+ }
694
+ };
695
+ } finally {
696
+ await rm3(staging, { recursive: true, force: true });
735
697
  }
736
698
  };
737
- var selectTarget = async (agent) => {
738
- const interfaces = await agent.interfaces();
739
- if (!interfaces.length)
740
- throw new Error("The plant PC has no IPv4 network.");
741
- 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}`);
742
- console.log(`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`);
743
- const found = await agent.discover(network.name);
744
- const manual = { address: "", port: 11740, hostname: null };
745
- const choice = await choose("Which controller?", [...found, manual], (item) => item === manual ? "Enter an address" : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`);
746
- const host = choice === manual ? await ask("Controller address: ") : choice.address;
747
- return agent.setTarget({ host, port: choice.port });
748
- };
749
- var contractVariables = async (config, root) => {
750
- if (!config.typegen)
699
+
700
+ // packages/compiler/src/project/release.ts
701
+ var releaseVariables = async (config, root) => {
702
+ if (!config.typegen) {
751
703
  return [];
752
- const contract = z.object({
753
- symbols: z.array(z.object({ name: z.string(), gvl: z.string(), type: z.string() })),
754
- typeFields: z.record(z.string(), z.array(z.object({ field: z.string(), type: z.string() })))
755
- }).parse(await import(pathToFileURL(resolve4(root, config.typegen.dir, "plc.ts")).href));
756
- return contract.symbols.flatMap(({ name, gvl, type }) => {
757
- const path = `${gvl}.${name}`;
758
- const fields = contract.typeFields[type];
759
- if (!fields)
760
- return [{ path, type }];
761
- return fields.map((field) => ({
762
- path: field.field === "" ? path : `${path}${field.field.startsWith("[") ? "" : "."}${field.field}`,
763
- type: field.type
764
- }));
765
- });
704
+ }
705
+ const contract = z2.object({
706
+ symbols: z2.array(z2.object({ name: z2.string(), gvl: z2.string(), type: z2.string() })),
707
+ typeFields: z2.record(z2.string(), z2.array(z2.object({
708
+ field: z2.string(),
709
+ type: z2.string(),
710
+ description: z2.string()
711
+ })))
712
+ }).parse(await import(pathToFileURL(resolve3(root, config.typegen.dir, "plc.ts")).href));
713
+ return contractVariables(contract).map(({ path, type }) => ({ path, type }));
766
714
  };
767
- var serverTokenEnv = (config) => config.codesys?.http?.credentials.find(({ originEnv }) => originEnv === config.server?.baseUrlEnv)?.bearerTokenEnv;
768
715
  var prepareRelease = async (file, loaded, flags) => {
769
716
  const { config, root } = loaded;
770
- if (!config.compiler)
717
+ if (!config.compiler) {
771
718
  throw new Error("tsplc deploy deploys tsPLC programs; configure compiler.");
719
+ }
772
720
  const command = flags.simulate ? "run" : "deploy";
773
721
  const emitted = await buildProject(file, {
774
722
  emitOnly: true,
775
723
  forController: true,
776
724
  frozenLockfile: flags["frozen-lockfile"],
777
- ...flags.simulate ? { loaded: { ...loaded, config: simulationConfig(config) }, configured: config } : { loaded },
778
- buildTarget: flags.simulate ? "development" : "production",
725
+ ...buildConfigs(loaded, flags),
726
+ buildTarget: buildTargetFor(command),
779
727
  controller: controllerFor(config, command)
780
728
  });
781
- if (hasErrors2(emitted.diagnostics))
729
+ if (hasErrors2(emitted.diagnostics)) {
782
730
  return { diagnostics: emitted.diagnostics };
731
+ }
783
732
  const settings = emitted.controllerConfig;
784
- if (!settings)
733
+ if (!settings) {
785
734
  throw new Error("Configure build settings for deployment.");
786
- await generateProject(file, { loaded, targets: await projectTargets(file, { loaded }) });
735
+ }
736
+ await generateProject(file, {
737
+ loaded,
738
+ targets: await projectTargets(file, { loaded })
739
+ });
787
740
  const portable = (path) => path.split(sep).join("/");
788
741
  const libraries = (settings.libraries ?? []).map((library) => ({
789
742
  ...library,
@@ -791,21 +744,31 @@ var prepareRelease = async (file, loaded, flags) => {
791
744
  }));
792
745
  const files = [
793
746
  { path: "template.project", content: Bun.file(settings.template) },
794
- ...libraries.map((library) => ({ path: library.release, content: Bun.file(library.path) }))
747
+ ...libraries.map((library) => ({
748
+ path: library.release,
749
+ content: Bun.file(library.path)
750
+ }))
795
751
  ];
796
- for await (const source of new Bun.Glob("**/*.st").scan({ cwd: settings.sourceDir, dot: true }))
752
+ for await (const source of new Bun.Glob("**/*.st").scan({
753
+ cwd: settings.sourceDir,
754
+ dot: true
755
+ })) {
797
756
  files.push({
798
757
  path: `st/${portable(source)}`,
799
- content: Bun.file(resolve4(settings.sourceDir, source))
758
+ content: Bun.file(resolve3(settings.sourceDir, source))
800
759
  });
801
- const debugManifest = resolve4(settings.sourceDir, "debug.json");
802
- if (existsSync3(debugManifest))
760
+ }
761
+ const debugManifest = resolve3(settings.sourceDir, "debug.json");
762
+ if (existsSync2(debugManifest)) {
803
763
  files.push({ path: "debug.json", content: Bun.file(debugManifest) });
804
- let server;
805
- if (config.server?.runtime) {
806
- const script = await bundleServer(config, root);
807
- server = `server/${basename(script)}`;
808
- files.push({ path: server, content: Bun.file(script) });
764
+ }
765
+ const serverScript = config.server?.runtime && await bundleServer(config, root);
766
+ const server = serverScript ? {
767
+ path: `server/${basename(serverScript)}`,
768
+ content: Bun.file(serverScript)
769
+ } : undefined;
770
+ if (server) {
771
+ files.push(server);
809
772
  }
810
773
  const manifest = {
811
774
  config: {
@@ -813,7 +776,10 @@ var prepareRelease = async (file, loaded, flags) => {
813
776
  deviceTree: settings.deviceTree,
814
777
  controller: settings.controller,
815
778
  libraryReferences: settings.libraryReferences,
816
- libraries: libraries.map(({ release, ...library }) => ({ ...library, path: release })),
779
+ libraries: libraries.map(({ release, ...library }) => ({
780
+ ...library,
781
+ path: release
782
+ })),
817
783
  task: settings.task,
818
784
  tasks: settings.tasks,
819
785
  removeObjects: settings.removeObjects,
@@ -823,52 +789,236 @@ var prepareRelease = async (file, loaded, flags) => {
823
789
  sourceDir: "st",
824
790
  entry: `st/${portable(relative(settings.sourceDir, settings.entry))}`
825
791
  },
826
- variables: await contractVariables(config, root),
827
- server,
792
+ variables: await releaseVariables(config, root),
793
+ server: server?.path,
828
794
  debug: config.debug,
829
- serverTokenEnv: serverTokenEnv(config)
795
+ serverTokenEnv: serverTokenEnv(config),
796
+ secrets: config.secrets
830
797
  };
831
798
  return { release: { manifest, files } };
832
799
  };
833
- var deploy = async (agent, file, loaded, flags) => {
834
- const status = await agent.status();
835
- if (status.login)
836
- throw new Error("A login is open; log out before deploying: tsplc logout");
837
- const target = !status.target || flags.select ? await selectTarget(agent) : status.target;
838
- console.log(`Building the release for ${target.host}…`);
839
- const building = timedProgress();
840
- const { release, diagnostics } = await prepareRelease(file, loaded, flags);
841
- if (!release)
842
- return { diagnostics };
843
- building("Built");
844
- if (flags.download && !await confirm("A full download stops the running application while it loads. Continue?", flags))
845
- throw new Error("Cancelled.");
846
- const credentials = await askCredentials();
847
- const settings = {
848
- credentials,
849
- download: flags.download ?? false,
850
- initializeUser: flags["initialize-user"] ?? false
851
- };
852
- console.log(release.manifest.server ? "Deploying the server and the program…" : "Deploying the program…");
853
- const deploying = timedProgress();
854
- deploying("Uploading");
855
- try {
856
- return await agent.deploy(release, settings, deploying);
800
+
801
+ // packages/compiler/src/project/terminal.ts
802
+ import { ask } from "@tsplc/agent";
803
+ var choose = async (question, items, label) => {
804
+ items.forEach((item, index) => console.log(` ${index + 1}. ${label(item)}`));
805
+ while (true) {
806
+ const item = items[Number(await ask(`${question} [1-${items.length}]: `)) - 1];
807
+ if (item !== undefined) {
808
+ return item;
809
+ }
810
+ }
811
+ };
812
+ var confirm = async (question, flags) => flags.yes || /^y(es)?$/i.test(await ask(`${question} [y/N]: `));
813
+ var progress = (message) => console.log(` ${message}`);
814
+ var timedProgress = () => {
815
+ const start = Date.now();
816
+ return (message) => {
817
+ const seconds = Math.round((Date.now() - start) / 1000);
818
+ progress(`${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")} ${message}`);
819
+ };
820
+ };
821
+
822
+ // packages/compiler/src/project/plant.ts
823
+ var connect = (env) => {
824
+ const environment = z3.object({
825
+ TSPLC_AGENT_URL: z3.url({
826
+ error: "Set TSPLC_AGENT_URL to the plant agent, such as http://line-pc:4850"
827
+ }),
828
+ TSPLC_AGENT_TOKEN: z3.string({
829
+ error: "Set TSPLC_AGENT_TOKEN to the plant agent's token"
830
+ })
831
+ }).parse(env);
832
+ return createAgentClient({
833
+ url: environment.TSPLC_AGENT_URL,
834
+ token: environment.TSPLC_AGENT_TOKEN
835
+ });
836
+ };
837
+ var readThroughAgent = (agent) => async ([first, ...rest]) => {
838
+ if (!first) {
839
+ return {};
840
+ }
841
+ try {
842
+ const result = await agent.command({
843
+ command: "read",
844
+ expressions: [first, ...rest]
845
+ });
846
+ if (!("values" in result)) {
847
+ throw new Error("The agent answered a read without values");
848
+ }
849
+ return result.values;
850
+ } catch (error) {
851
+ const { login } = await agent.status();
852
+ if (!login) {
853
+ throw new LoginUnavailable(noLogin, { cause: error });
854
+ }
855
+ if ("error" in login) {
856
+ throw new Error(login.error, { cause: error });
857
+ }
858
+ throw error;
859
+ }
860
+ };
861
+
862
+ // packages/compiler/src/project/debugger.ts
863
+ async function serveProjectDebugger({ config, root, env }, flags) {
864
+ if (flags.opcua && !config.monitor) {
865
+ throw new Error("Configure monitor with the controller's OPC UA endpoint to use --opcua.");
866
+ }
867
+ const agentUrl = env["TSPLC_AGENT_URL"];
868
+ if (!flags.opcua && !(agentUrl && env["TSPLC_AGENT_TOKEN"])) {
869
+ throw new Error("Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.");
870
+ }
871
+ const file = resolve4(root, ".tsplc/artifacts/st/debug.json");
872
+ if (!existsSync3(file)) {
873
+ throw new Error(`No debug manifest at ${relative2(process.cwd(), file)}: build with debug configured.`);
874
+ }
875
+ const port = Number(flags.port ?? 4870);
876
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
877
+ throw new Error("--port must be a TCP port.");
878
+ }
879
+ const manifest = await loadManifest(file);
880
+ const serverUrl = flags["server-url"] ?? (config.server?.baseUrlEnv && env[config.server.baseUrlEnv]);
881
+ const tokenEnv = serverTokenEnv2(config);
882
+ const token = tokenEnv && env[tokenEnv];
883
+ const log = (message) => console.log(`${new Date().toISOString()} ${message}`);
884
+ const debug = await createDebugger({
885
+ manifest,
886
+ adapter: flags.opcua && config.monitor ? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env })) : createLoginAdapter({
887
+ read: readThroughAgent(connect(env)),
888
+ probe: manifest.build.target,
889
+ endpoint: `the plant agent at ${agentUrl}`
890
+ }),
891
+ stateDirectory: resolve4(root, ".tsplc/debug"),
892
+ watch: config.debug?.watch ?? {},
893
+ ...serverUrl && token && { server: { url: serverUrl, token } },
894
+ projectRoot: root,
895
+ log
896
+ });
897
+ const server = serveDebugger(debug, { port, log });
898
+ console.log(`tsPLC debugger at ${server.url}`);
899
+ if (!serverUrl || !token) {
900
+ console.log("Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.");
901
+ }
902
+ await new Promise((stopped) => {
903
+ process.once("SIGINT", stopped);
904
+ process.once("SIGTERM", stopped);
905
+ });
906
+ await server.stop(true);
907
+ await debug.close();
908
+ }
909
+
910
+ // packages/compiler/src/project/plant.ts
911
+ import {
912
+ AgentOperationError as AgentOperationError2,
913
+ createAgentClient as createAgentClient2
914
+ } from "@tsplc/agent/client";
915
+ import {
916
+ ask as ask3,
917
+ askCredentials as askCredentials2
918
+ } from "@tsplc/agent";
919
+ import { LoginUnavailable as LoginUnavailable2, noLogin as noLogin2 } from "@tsplc/debug";
920
+ import { z as z4 } from "zod";
921
+ var plantCommands = [
922
+ "deploy",
923
+ "target",
924
+ "status",
925
+ "login",
926
+ "logout",
927
+ "vars",
928
+ "read",
929
+ "write",
930
+ "force",
931
+ "unforce",
932
+ "start",
933
+ "stop",
934
+ "reset"
935
+ ];
936
+ var plantCommand = (name) => plantCommands.find((command) => command === name);
937
+ var connect2 = (env) => {
938
+ const environment = z4.object({
939
+ TSPLC_AGENT_URL: z4.url({
940
+ error: "Set TSPLC_AGENT_URL to the plant agent, such as http://line-pc:4850"
941
+ }),
942
+ TSPLC_AGENT_TOKEN: z4.string({
943
+ error: "Set TSPLC_AGENT_TOKEN to the plant agent's token"
944
+ })
945
+ }).parse(env);
946
+ return createAgentClient2({
947
+ url: environment.TSPLC_AGENT_URL,
948
+ token: environment.TSPLC_AGENT_TOKEN
949
+ });
950
+ };
951
+ var selectTarget = async (agent) => {
952
+ const interfaces = await agent.interfaces();
953
+ if (!interfaces.length) {
954
+ throw new Error("The plant PC has no IPv4 network.");
955
+ }
956
+ 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}`);
957
+ console.log(`Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`);
958
+ const found = await agent.discover(network.name);
959
+ const manual = { address: "", port: 11740, hostname: null };
960
+ const choice = await choose("Which controller?", [...found, manual], (item) => item === manual ? "Enter an address" : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`);
961
+ const host = choice === manual ? await ask3("Controller address: ") : choice.address;
962
+ return agent.setTarget({ host, port: choice.port });
963
+ };
964
+ var controllerCredentials = async (env, agent, prompt) => {
965
+ const username = env["TSPLC_CONTROLLER_USERNAME"];
966
+ const password = env["TSPLC_CONTROLLER_PASSWORD"];
967
+ if (username && password) {
968
+ return { username, password };
969
+ }
970
+ if (username || password) {
971
+ throw new Error("Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.");
972
+ }
973
+ return agent.stored && !agent.initializeUser ? null : prompt();
974
+ };
975
+ var deploy = async (agent, file, loaded, flags, env) => {
976
+ const status = await agent.status();
977
+ if (status.login) {
978
+ throw new Error("A login is open; log out before deploying: tsplc logout");
979
+ }
980
+ const target = !status.target || flags.select ? await selectTarget(agent) : status.target;
981
+ console.log(`Building the release for ${target.host}…`);
982
+ const building = timedProgress();
983
+ const { release, diagnostics } = await prepareRelease(file, loaded, flags);
984
+ if (!release) {
985
+ return { diagnostics };
986
+ }
987
+ building("Built");
988
+ if (flags.download && !await confirm("A full download stops the running application while it loads. Continue?", flags)) {
989
+ throw new Error("Cancelled.");
990
+ }
991
+ const credentials = await controllerCredentials(env, {
992
+ stored: status.credentialsStored,
993
+ initializeUser: flags["initialize-user"] ?? false
994
+ }, askCredentials2);
995
+ const settings = {
996
+ credentials,
997
+ download: flags.download ?? false,
998
+ initializeUser: flags["initialize-user"] ?? false
999
+ };
1000
+ console.log(release.manifest.server ? "Deploying the server and the program…" : "Deploying the program…");
1001
+ const deploying = timedProgress();
1002
+ deploying("Uploading");
1003
+ try {
1004
+ return await agent.deploy(release, settings, deploying);
857
1005
  } catch (error) {
858
- if (!(error instanceof AgentOperationError && error.downloadRequired) || !await confirm(`${error.message}. A full download stops the running application while it loads. Download now?`, flags))
1006
+ if (!(error instanceof AgentOperationError2 && error.downloadRequired) || !await confirm(`${error.message}. A full download stops the running application while it loads. Download now?`, flags)) {
859
1007
  throw error;
1008
+ }
860
1009
  return agent.deploy(release, { ...settings, download: true }, timedProgress());
861
1010
  }
862
1011
  };
863
- var ensureLogin = async (agent) => {
864
- const { login } = await agent.status();
865
- if (login && "state" in login)
1012
+ var ensureLogin = async (agent, env) => {
1013
+ const { login, credentialsStored } = await agent.status();
1014
+ if (login && "state" in login) {
866
1015
  return;
1016
+ }
867
1017
  if (login) {
868
1018
  console.log(`The open login failed (${login.error}); replacing it.`);
869
1019
  await agent.logout();
870
1020
  }
871
- const credentials = await askCredentials();
1021
+ const credentials = await controllerCredentials(env, { stored: credentialsStored, initializeUser: false }, askCredentials2);
872
1022
  console.log("Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.");
873
1023
  await agent.login(credentials, progress);
874
1024
  };
@@ -877,49 +1027,83 @@ var variableChildren = (variables, prefix) => {
877
1027
  const start = prefix.toLowerCase();
878
1028
  for (const { path, type } of variables) {
879
1029
  const lower = path.toLowerCase();
880
- if (prefix && !(lower === start || lower.startsWith(`${start}.`) || lower.startsWith(`${start}[`)))
1030
+ if (prefix && !(lower === start || lower.startsWith(`${start}.`) || lower.startsWith(`${start}[`))) {
881
1031
  continue;
1032
+ }
882
1033
  const rest = path.slice(prefix.length).replace(/^\./, "");
883
- if (rest === "")
1034
+ if (rest === "") {
884
1035
  return [{ name: path, type, leaves: 1 }];
1036
+ }
885
1037
  const name = /^(\[[^\]]*\]|[^.[]+)/.exec(rest)?.[0] ?? rest;
886
1038
  const child = children.get(name) ?? { leaves: 0 };
887
- children.set(name, { type: rest === name ? type : undefined, leaves: child.leaves + 1 });
1039
+ children.set(name, {
1040
+ type: rest === name ? type : undefined,
1041
+ leaves: child.leaves + 1
1042
+ });
888
1043
  }
889
1044
  const indexes = [...children.keys()].filter((name) => /^\[\d+\]$/.test(name)).map((name) => Number(name.slice(1, -1)));
890
1045
  const listed = [...children].filter(([name]) => !/^\[\d+\]$/.test(name));
891
1046
  if (indexes.length) {
892
1047
  const first = children.get(`[${Math.min(...indexes)}]`);
893
- listed.unshift([`[${Math.min(...indexes)}..${Math.max(...indexes)}]`, first ?? { leaves: 0 }]);
1048
+ listed.unshift([
1049
+ `[${Math.min(...indexes)}..${Math.max(...indexes)}]`,
1050
+ first ?? { leaves: 0 }
1051
+ ]);
894
1052
  }
895
1053
  return listed.map(([name, child]) => ({ name, ...child }));
896
1054
  };
1055
+ var printStatus = async (agent) => {
1056
+ const status = await agent.status();
1057
+ console.log(`Controller ${status.target ? `${status.target.host}:${status.target.port}` : "not selected (tsplc target)"}`);
1058
+ console.log(`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : "none"}`);
1059
+ console.log(`Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`);
1060
+ const { login } = status;
1061
+ if (!login) {
1062
+ console.log("Login closed");
1063
+ } else if ("error" in login) {
1064
+ console.log(`Login failed: ${login.error} (tsplc logout)`);
1065
+ } else {
1066
+ console.log(`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`);
1067
+ }
1068
+ };
1069
+ var printVariables = async (agent, path) => {
1070
+ const children = variableChildren(await agent.variables(), path ?? "");
1071
+ if (!children.length) {
1072
+ throw new Error(`No published variable ${path}.`);
1073
+ }
1074
+ for (const child of children) {
1075
+ console.log(`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`);
1076
+ }
1077
+ };
897
1078
  var printLogin = (result) => {
898
1079
  if ("values" in result) {
899
- for (const [expression, value] of Object.entries(result.values))
1080
+ for (const [expression, value] of Object.entries(result.values)) {
900
1081
  console.log(`${expression} = ${value}`);
1082
+ }
901
1083
  return;
902
1084
  }
903
1085
  console.log(`Application ${result.state}`);
904
- if (result.forced.length)
1086
+ if (result.forced.length) {
905
1087
  console.log(`Forced: ${result.forced.join(", ")}`);
1088
+ }
906
1089
  };
907
- var runPlantCommand = async (command, args, flags, project) => {
908
- const agent = connect();
1090
+ var runPlantCommand = async (agent, command, args, flags, project, env) => {
909
1091
  const expect = (count, usage) => {
910
- if (args.length !== count)
1092
+ if (args.length !== count) {
911
1093
  throw new Error(`Usage: tsplc ${command} ${usage}`);
1094
+ }
912
1095
  };
913
1096
  const send = async (loginCommand) => {
914
- await ensureLogin(agent);
1097
+ await ensureLogin(agent, env);
915
1098
  printLogin(await agent.command(loginCommand));
916
1099
  };
917
1100
  switch (command) {
918
1101
  case "deploy": {
919
- expect(0, "[--download] [--select] [--initialize-user] [--simulate]");
920
- const deployed = await deploy(agent, project.file, await project.load(), flags);
921
- if ("diagnostics" in deployed)
1102
+ expect(0, "[--target name] [--download] [--select] [--initialize-user] [--simulate]");
1103
+ const deployed = await deploy(agent, project.file, await project.load(), flags, env);
1104
+ if ("diagnostics" in deployed) {
922
1105
  return deployed;
1106
+ }
923
1107
  console.log(`Deployed release ${deployed.id} (${deployed.operation}).`);
924
1108
  return;
925
1109
  }
@@ -929,343 +1113,317 @@ var runPlantCommand = async (command, args, flags, project) => {
929
1113
  console.log(`Deployments now go to ${target.host}:${target.port}.`);
930
1114
  return;
931
1115
  }
932
- case "status": {
1116
+ case "status":
933
1117
  expect(0, "");
934
- const status = await agent.status();
935
- console.log(`Controller ${status.target ? `${status.target.host}:${status.target.port}` : "not selected (tsplc target)"}`);
936
- console.log(`Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : "none"}`);
937
- console.log(`Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`);
938
- const { login } = status;
939
- if (!login)
940
- console.log("Login closed");
941
- else if ("error" in login)
942
- console.log(`Login failed: ${login.error} (tsplc logout)`);
943
- else
944
- console.log(`Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`);
945
- return;
946
- }
1118
+ return printStatus(agent);
947
1119
  case "login":
948
1120
  expect(0, "");
949
- await ensureLogin(agent);
1121
+ await ensureLogin(agent, env);
950
1122
  printLogin(await agent.command({ command: "state" }));
951
1123
  return;
952
1124
  case "logout": {
953
1125
  expect(0, "");
954
1126
  const { login } = await agent.status();
955
1127
  const forced = login && "forced" in login ? login.forced : [];
956
- if (forced.length && !await confirm(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags))
1128
+ if (forced.length && !await confirm(`Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`, flags)) {
957
1129
  throw new Error("Cancelled.");
1130
+ }
958
1131
  const { failure } = await agent.logout();
959
1132
  console.log(failure ? `The login couldn't log out (${failure}); its container was removed.` : "Logged out.");
960
1133
  return;
961
1134
  }
962
- case "vars": {
963
- if (args.length > 1)
1135
+ case "vars":
1136
+ if (args.length > 1) {
964
1137
  throw new Error("Usage: tsplc vars [path]");
965
- const variables = await agent.variables();
966
- const children = variableChildren(variables, args[0] ?? "");
967
- if (!children.length)
968
- throw new Error(`No published variable ${args[0]}.`);
969
- for (const child of children)
970
- console.log(`${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`);
971
- return;
972
- }
1138
+ }
1139
+ return printVariables(agent, args[0]);
973
1140
  case "read": {
974
1141
  const [first, ...rest] = args;
975
- if (!first)
1142
+ if (!first) {
976
1143
  throw new Error("Usage: tsplc read <expression>...");
1144
+ }
977
1145
  return send({ command: "read", expressions: [first, ...rest] });
978
1146
  }
979
1147
  case "write":
980
1148
  case "force": {
981
1149
  const [expression, value, ...extra] = args;
982
- if (!expression || !value || extra.length)
1150
+ if (!expression || !value || extra.length) {
983
1151
  throw new Error(`Usage: tsplc ${command} <expression> <value>`);
1152
+ }
984
1153
  return send({ command, values: { [expression]: value } });
985
1154
  }
986
1155
  case "unforce":
987
- return send({ command: "unforce", expressions: args, restore: flags.restore ?? false });
1156
+ return send({
1157
+ command: "unforce",
1158
+ expressions: args,
1159
+ restore: flags.restore ?? false
1160
+ });
988
1161
  case "start":
989
1162
  expect(0, "");
990
1163
  return send({ command: "start" });
991
1164
  case "stop":
992
1165
  expect(0, "");
993
- if (!await confirm("Stop the application on the controller?", flags))
1166
+ if (!await confirm("Stop the application on the controller?", flags)) {
994
1167
  throw new Error("Cancelled.");
1168
+ }
995
1169
  return send({ command: "stop" });
996
1170
  case "reset": {
997
1171
  expect(1, "warm|cold");
998
- const kind = z.enum(["warm", "cold"]).parse(args[0]);
999
- if (!await confirm(`Reset the application (${kind})? It stops and reinitializes its variables.`, flags))
1172
+ const kind = z4.enum(["warm", "cold"]).parse(args[0]);
1173
+ if (!await confirm(`Reset the application (${kind})? It stops and reinitializes its variables.`, flags)) {
1000
1174
  throw new Error("Cancelled.");
1001
- return send({ command: "reset", kind: kind === "warm" ? "Warm" : "Cold" });
1175
+ }
1176
+ return send({
1177
+ command: "reset",
1178
+ kind: kind === "warm" ? "Warm" : "Cold"
1179
+ });
1002
1180
  }
1003
1181
  }
1004
1182
  };
1005
1183
 
1006
- // packages/compiler/project/project.ts
1007
- import { copyFile as copyFile2, mkdir as mkdir5, mkdtemp as mkdtemp4, realpath as realpath2, rm as rm5, writeFile as writeFile3 } from "node:fs/promises";
1008
- import { dirname as dirname5, join as join5, resolve as resolve5 } from "node:path";
1009
- import {
1010
- buildCodesys as buildCodesys2,
1011
- codesysBuildConfig as codesysBuildConfig2,
1012
- diagnoseCodesys as diagnoseCodesys2,
1013
- emitCodesys as emitCodesys2,
1014
- ioTargets as ioTargets2,
1015
- publicationSelectors as publicationSelectors2,
1016
- planCodesys as planCodesys2
1017
- } from "@tsplc/compiler/codesys";
1018
- import { analyze as analyze2, checkHostConfig as checkHostConfig2 } from "@tsplc/compiler";
1184
+ // packages/compiler/src/project/project-commands.ts
1185
+ import { resolve as resolve5 } from "node:path";
1019
1186
  import {
1020
- compilerConfig as compilerConfig2,
1021
- loadTsplcConfig as loadTsplcConfig2
1187
+ buildTargetFor as buildTargetFor2,
1188
+ controllerFor as controllerFor2,
1189
+ loadTsplcConfig as loadTsplcConfig2,
1190
+ rawBuildConfig
1022
1191
  } from "@tsplc/config";
1023
- import { deviceTree as deviceTree2, loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen";
1024
- import { installLibraries as installLibraries2 } from "@tsplc/build";
1025
- import { hasErrors as hasErrors3, normalizeModule as normalizeModule2 } from "@tsplc/compiler/ir";
1026
- var failure2 = (origin, code, cause) => ({
1027
- origin,
1028
- code,
1029
- severity: "error",
1030
- message: cause instanceof Error ? cause.message : String(cause)
1031
- });
1032
- async function loadProject2(file, loaded, buildTarget, configured) {
1033
- let configFile = resolve5(file);
1034
- try {
1035
- configFile = await realpath2(configFile);
1036
- const diagnostics = checkHostConfig2(configFile);
1037
- if (hasErrors3(diagnostics))
1038
- return { configFile, diagnostics };
1039
- const shared = (loaded ?? await loadTsplcConfig2(configFile)).config;
1040
- const root = dirname5(configFile);
1041
- const catalog = await loadHardware2(shared, root);
1042
- const config = compilerConfig2(shared, resolveIo2(shared, catalog), buildTarget);
1043
- return {
1044
- configFile,
1045
- shared,
1046
- config: { ...config, ...sourceInput2(config, root) },
1047
- project: {
1048
- root,
1049
- ...shared.debug && { debug: shared.debug },
1050
- ...shared.telemetry && { telemetry: shared.telemetry },
1051
- ...shared.server && { server: shared.server },
1052
- hardware: {
1053
- catalog: configured ? await loadHardware2(configured, root) : catalog,
1054
- config: configured ?? shared,
1055
- tree: shared.codesys?.deviceTree !== undefined
1056
- }
1057
- },
1058
- diagnostics
1059
- };
1060
- } catch (cause) {
1061
- return { configFile, diagnostics: [failure2("config", "PLC5003", cause)] };
1192
+ import {
1193
+ buildProject as buildSt,
1194
+ configureDocker,
1195
+ configureRuntime,
1196
+ inspectController,
1197
+ installLibraries as installLibraries2,
1198
+ loadSources,
1199
+ rawEngineeringSettings,
1200
+ resolveConfig,
1201
+ runProject,
1202
+ updateController
1203
+ } from "@tsplc/build";
1204
+ import { checkHostConfig as checkHostConfig2 } from "@tsplc/compiler";
1205
+ import { hasErrors as hasErrors3 } from "@tsplc/compiler/ir";
1206
+ import { generateProject as generateProject2 } from "@tsplc/typegen";
1207
+ import { loadHardware as loadHardware2, resolveIo as resolveIo2 } from "@tsplc/typegen/hardware";
1208
+ var projectCommands = [
1209
+ "install",
1210
+ "typegen",
1211
+ "check",
1212
+ "build",
1213
+ "run",
1214
+ "download",
1215
+ "online-change",
1216
+ "inspect",
1217
+ "clean",
1218
+ "configure"
1219
+ ];
1220
+ var projectCommand = (name) => projectCommands.find((command) => command === name);
1221
+
1222
+ class DiagnosticFailure extends Error {
1223
+ result;
1224
+ constructor(result) {
1225
+ super("PLC validation failed.");
1226
+ this.result = result;
1062
1227
  }
1063
1228
  }
1064
- function sourceInput2(compiler, root) {
1065
- return {
1066
- tsconfig: resolve5(root, compiler.tsconfig),
1067
- programs: Object.fromEntries(Object.entries(compiler.programs).map(([name, entry]) => [
1068
- name,
1069
- { ...entry, module: resolve5(root, entry.module) }
1070
- ]))
1071
- };
1072
- }
1073
- async function projectTargets2(file = "tsplc.config.ts", options = {}) {
1074
- const configFile = await realpath2(resolve5(file));
1075
- const { config } = options.loaded ?? await loadTsplcConfig2(configFile);
1076
- if (!config.compiler)
1077
- return;
1078
- const source = analyze2({
1079
- ...sourceInput2(config.compiler, dirname5(configFile)),
1080
- services: config.server
1081
- });
1082
- const core = source.module && normalizeModule2(source.module).core;
1083
- return core ? { io: ioTargets2(core), publication: publicationSelectors2(core) } : undefined;
1084
- }
1085
- async function checkProject2(file = "tsplc.config.ts", options = {}) {
1086
- const loaded = await loadProject2(file, options.loaded, options.buildTarget, options.configured);
1087
- if (!loaded.config || !loaded.project) {
1088
- return loaded;
1229
+ var checkProjectFlags = (command, flags) => {
1230
+ if (flags.format && !["json", "text"].includes(flags.format)) {
1231
+ throw new Error("--format must be json or text.");
1089
1232
  }
1090
- const config = loaded.config;
1091
- if (config.target.kind !== "codesys") {
1092
- return {
1093
- ...loaded,
1094
- diagnostics: [failure2("backend", "PLC7001", `Unsupported target: ${config.target.kind}`)]
1095
- };
1233
+ if (flags["emit-only"] && command !== "build") {
1234
+ throw new Error("--emit-only is supported by build only.");
1096
1235
  }
1097
- const source = analyze2({
1098
- tsconfig: config.tsconfig,
1099
- programs: config.programs,
1100
- services: loaded.shared?.server
1101
- });
1102
- if (!source.module) {
1103
- return { ...loaded, diagnostics: source.diagnostics };
1236
+ if (flags.target && (command === "configure" || command === "clean")) {
1237
+ throw new Error("--target applies only to commands that read the config.");
1104
1238
  }
1105
- const normalized = normalizeModule2(source.module);
1106
- if (!normalized.core) {
1107
- return { ...loaded, diagnostics: normalized.diagnostics };
1239
+ if (flags.runtime && command !== "configure") {
1240
+ throw new Error("--runtime applies only to configure.");
1108
1241
  }
1109
- const tasks = config.tasks.map((task) => ({
1110
- name: task.name,
1111
- intervalNanoseconds: task.schedule.interval.nanoseconds,
1112
- priority: task.priority,
1113
- programs: task.programs
1114
- }));
1115
- const planned = planCodesys2(normalized.core, { tasks }, config.target.options, loaded.project);
1116
- return {
1117
- ...loaded,
1118
- ...planned,
1119
- diagnostics: [
1120
- ...loaded.diagnostics,
1121
- ...source.diagnostics,
1122
- ...normalized.diagnostics,
1123
- ...planned.diagnostics
1124
- ]
1125
- };
1126
- }
1127
- async function engineeringInputs2(shared, configFile, bundle, frozen) {
1128
- const root = dirname5(configFile);
1129
- const tree = await deviceTree2(shared, await loadHardware2(shared, root));
1130
- return {
1131
- libraries: await installLibraries2(shared.dependencies, root, { frozen }),
1132
- deviceTree: tree && {
1133
- ...tree,
1134
- mappings: bundle.ioMappings.map(({ address, variable }) => ({ address, variable }))
1135
- }
1136
- };
1137
- }
1138
- async function buildProject2(file = "tsplc.config.ts", options = {}) {
1139
- let staging;
1140
- try {
1141
- const configFile = await realpath2(resolve5(file));
1142
- const previous = await owned(configFile, true);
1143
- if (previous.unknown.length) {
1144
- throw new Error(`Output contains unrelated files: ${previous.unknown.join(", ")}`);
1242
+ if ((flags.plc || flags.server) && command !== "build") {
1243
+ throw new Error("--plc and --server apply only to build.");
1244
+ }
1245
+ if (flags.simulate && !["run", "download", "online-change"].includes(command)) {
1246
+ throw new Error("--simulate applies only to run, download, online-change and deploy.");
1247
+ }
1248
+ if (flags.plc && flags.server) {
1249
+ throw new Error("Choose --plc or --server, or omit both for a full build.");
1250
+ }
1251
+ if (flags.server && flags["emit-only"]) {
1252
+ throw new Error("--emit-only applies to PLC emission only.");
1253
+ }
1254
+ };
1255
+ var runProjectCommand = async (command, file, flags, env) => {
1256
+ const load = () => loadTsplcConfig2(file, { env, target: flags.target, forAgent: false });
1257
+ switch (command) {
1258
+ case "configure":
1259
+ return configure(flags);
1260
+ case "clean":
1261
+ return cleanProject(file);
1262
+ case "install":
1263
+ return install(await load(), flags);
1264
+ case "typegen":
1265
+ return typegen(file, await load(), flags);
1266
+ case "check":
1267
+ return check(file, await loadCheckedConfig(file, load));
1268
+ case "build":
1269
+ return build(file, await loadCheckedConfig(file, load), flags);
1270
+ case "run":
1271
+ return run(file, await loadCheckedConfig(file, load), flags);
1272
+ case "inspect":
1273
+ return inspect(await load(), flags);
1274
+ case "download":
1275
+ case "online-change":
1276
+ return updateProgram(command, file, await loadCheckedConfig(file, load), flags);
1277
+ }
1278
+ };
1279
+ var loadCheckedConfig = async (file, load) => {
1280
+ const hostConfigDiagnostics = checkHostConfig2(resolve5(file));
1281
+ if (hasErrors3(hostConfigDiagnostics)) {
1282
+ throw new DiagnosticFailure({ diagnostics: hostConfigDiagnostics });
1283
+ }
1284
+ return { loaded: await load(), hostConfigDiagnostics };
1285
+ };
1286
+ var configure = async (flags) => {
1287
+ await (flags.runtime ? configureRuntime() : configureDocker());
1288
+ return { ok: true };
1289
+ };
1290
+ var install = async ({ config, root }, flags) => ({
1291
+ libraries: await installLibraries2(config.dependencies, root, {
1292
+ frozen: flags["frozen-lockfile"]
1293
+ })
1294
+ });
1295
+ var typegen = async (file, loaded, flags) => {
1296
+ const targets = await projectTargets(file, { loaded });
1297
+ if (loaded.config.compiler && !flags.check) {
1298
+ await generateProject2(file, { hardwareOnly: true, loaded, targets });
1299
+ const emitted = await buildProject(file, { emitOnly: true, loaded });
1300
+ if (hasErrors3(emitted.diagnostics)) {
1301
+ throw new DiagnosticFailure(emitted);
1145
1302
  }
1146
- const checked = await checkProject2(configFile, {
1147
- loaded: options.loaded,
1148
- buildTarget: options.buildTarget,
1149
- configured: options.configured
1303
+ }
1304
+ return generateProject2(file, { check: flags.check, loaded, targets });
1305
+ };
1306
+ var check = async (file, { loaded, hostConfigDiagnostics }) => {
1307
+ const { config, configFile, root } = loaded;
1308
+ if (config.compiler) {
1309
+ return checkProject(file, { loaded, hostConfigDiagnostics });
1310
+ }
1311
+ const sources = await loadSources(resolveConfig({
1312
+ ...rawBuildConfig(config),
1313
+ io: resolveIo2(config, await loadHardware2(config, root))
1314
+ }, configFile));
1315
+ return { objects: sources.objects.length };
1316
+ };
1317
+ var buildPlc = async (command, file, { loaded, hostConfigDiagnostics }, flags) => {
1318
+ const { config } = loaded;
1319
+ if (config.compiler) {
1320
+ const built = await buildProject(file, {
1321
+ emitOnly: flags["emit-only"],
1322
+ frozenLockfile: flags["frozen-lockfile"],
1323
+ ...buildConfigs(loaded, flags),
1324
+ hostConfigDiagnostics,
1325
+ controller: controllerFor2(config, command),
1326
+ buildTarget: buildTargetFor2(command)
1150
1327
  });
1151
- if (!checked.plan || !checked.config) {
1152
- return { diagnostics: checked.diagnostics };
1153
- }
1154
- const bundle = emitCodesys2(checked.plan);
1155
- if (hasErrors3(bundle.diagnostics)) {
1156
- return { diagnostics: bundle.diagnostics };
1328
+ if (hasErrors3(built.diagnostics)) {
1329
+ throw new DiagnosticFailure(built);
1157
1330
  }
1158
- const shared = checked.shared;
1159
- const engineering = shared && (!options.emitOnly || options.forController) ? await engineeringInputs2(shared, configFile, bundle, options.frozenLockfile) : undefined;
1160
- const controllerConfig = shared?.build ? codesysBuildConfig2(checked.plan, bundle, {
1161
- configFile,
1162
- sourceDir: join5(previous.output, "st"),
1163
- outDir: resolve5(dirname5(configFile), shared.build.outDir),
1164
- controller: options.controller,
1165
- ...engineering
1166
- }) : undefined;
1167
- await mkdir5(previous.root, { recursive: true });
1168
- staging = await mkdtemp4(join5(previous.root, "stage-"));
1169
- const artifacts = [
1170
- ...bundle.artifacts,
1171
- { path: "mappings.json", content: `${JSON.stringify(compactMappings2(bundle.mappings))}
1172
- ` },
1173
- { path: "io-symbols.json", content: `${JSON.stringify(bundle.ioSymbols, null, 2)}
1174
- ` },
1175
- { path: "publication.json", content: `${JSON.stringify(bundle.publication, null, 2)}
1176
- ` },
1177
- { path: "config.json", content: `${JSON.stringify(checked.config, null, 2)}
1178
- ` },
1179
- ...bundle.debug ? [{ path: "debug.json", content: `${JSON.stringify(bundle.debug)}
1180
- ` }] : []
1181
- ];
1182
- for (const artifact of artifacts) {
1183
- const path = join5(staging, "st", artifact.path);
1184
- await mkdir5(dirname5(path), { recursive: true });
1185
- await writeFile3(path, artifact.content);
1186
- }
1187
- let vendor;
1188
- if (!options.emitOnly) {
1189
- const outDir = shared?.build ? resolve5(dirname5(configFile), shared.build.outDir ?? "build") : join5(previous.root, "engineering");
1190
- await engineeringDirectory(outDir, configFile);
1191
- try {
1192
- vendor = await buildCodesys2(checked.plan, bundle, {
1193
- configFile,
1194
- sourceDir: join5(staging, "st"),
1195
- outDir,
1196
- controller: options.controller,
1197
- ...engineering
1198
- });
1199
- } catch (cause) {
1200
- return { diagnostics: diagnoseCodesys2(cause, bundle) };
1201
- }
1202
- const vendorArtifacts = [
1203
- ["Application.project", vendor.project],
1204
- ["Application.app", vendor.output],
1205
- ["Application.crc", vendor.checksum]
1206
- ];
1207
- for (const [name, path] of vendorArtifacts) {
1208
- if (!path)
1209
- continue;
1210
- const destination = join5(staging, "vendor", name);
1211
- await mkdir5(dirname5(destination), { recursive: true });
1212
- await copyFile2(path, destination);
1213
- }
1214
- }
1215
- const status = vendor ? "vendor-compiled" : "emitted";
1216
- await publishArtifacts(staging, previous, {
1217
- configFile,
1218
- status,
1219
- ...vendor && { vendor: { application: vendor.application, tasks: vendor.tasks } }
1331
+ await generateProject2(file, {
1332
+ loaded,
1333
+ targets: await projectTargets(file, { loaded })
1220
1334
  });
1221
- staging = undefined;
1222
- return {
1223
- directory: previous.output,
1224
- status,
1225
- ...controllerConfig && { controllerConfig },
1226
- diagnostics: [...checked.diagnostics, ...bundle.diagnostics]
1227
- };
1228
- } catch (cause) {
1229
- return { diagnostics: [failure2("config", "PLC5004", cause)] };
1230
- } finally {
1231
- if (staging) {
1232
- await rm5(staging, { recursive: true, force: true });
1233
- }
1335
+ return built;
1234
1336
  }
1235
- }
1236
- function compactMappings2(mappings) {
1237
- const objects = new Map, files = new Map;
1238
- const index = (table, value) => {
1239
- if (!table.has(value))
1240
- table.set(value, table.size);
1241
- return table.get(value);
1242
- };
1243
- const rows = mappings.map(({ path, line, span }) => [
1244
- index(objects, path),
1245
- line,
1246
- index(files, span.file),
1247
- span.start,
1248
- span.end,
1249
- span.line,
1250
- span.column
1251
- ]);
1252
- return { objects: [...objects.keys()], files: [...files.keys()], mappings: rows };
1253
- }
1254
- async function cleanProject(file = "tsplc.config.ts") {
1255
- try {
1256
- await cleanArtifacts(await realpath2(resolve5(file)));
1257
- return { diagnostics: [] };
1258
- } catch (cause) {
1259
- return { diagnostics: [failure2("config", "PLC5004", cause)] };
1337
+ if (flags["emit-only"]) {
1338
+ throw new Error("Raw Structured Text is already emitted.");
1260
1339
  }
1261
- }
1340
+ const built = await buildSt(await rawEngineeringSettings(loaded, {
1341
+ command,
1342
+ frozenLockfile: flags["frozen-lockfile"],
1343
+ simulate: flags.simulate
1344
+ }));
1345
+ await generateProject2(file, { hardwareOnly: !config.typegen, loaded });
1346
+ return built;
1347
+ };
1348
+ var build = async (file, checked, flags) => {
1349
+ const { config, root } = checked.loaded;
1350
+ if (flags.server) {
1351
+ return buildServer(config, root);
1352
+ }
1353
+ const plc = await buildPlc("build", file, checked, flags);
1354
+ if (flags.plc || flags["emit-only"] || !config.server?.runtime) {
1355
+ return plc;
1356
+ }
1357
+ return { ...plc, ...await buildServer(config, root) };
1358
+ };
1359
+ var run = async (file, checked, flags) => {
1360
+ const { config, configFile } = checked.loaded;
1361
+ const built = await buildPlc("run", file, checked, flags);
1362
+ if (!config.build) {
1363
+ throw new Error("Configure build to run this project.");
1364
+ }
1365
+ await runProject(resolveConfig(config.compiler ? config.build : rawBuildConfig(config), configFile), config.name);
1366
+ return built;
1367
+ };
1368
+ var inspect = async ({ config, configFile }, flags) => {
1369
+ if (!config.build) {
1370
+ throw new Error("Configure build settings and controller connection.");
1371
+ }
1372
+ return inspectController(resolveConfig({ ...config.build, controller: controllerFor2(config, "inspect") }, configFile), flags.read);
1373
+ };
1374
+ var updateProgram = async (operation, file, checked, flags) => {
1375
+ const { config } = checked.loaded;
1376
+ if (!config.build) {
1377
+ throw new Error("Configure build settings and controller connection.");
1378
+ }
1379
+ const settings = config.compiler ? await emittedControllerSettings(operation, file, checked, flags) : await rawEngineeringSettings(checked.loaded, {
1380
+ command: operation,
1381
+ frozenLockfile: flags["frozen-lockfile"],
1382
+ simulate: flags.simulate
1383
+ });
1384
+ return updateController(settings, operation, {
1385
+ initializeUser: flags["initialize-user"],
1386
+ read: flags.read
1387
+ });
1388
+ };
1389
+ var emittedControllerSettings = async (operation, file, { loaded, hostConfigDiagnostics }, flags) => {
1390
+ const emitted = await buildProject(file, {
1391
+ emitOnly: true,
1392
+ forController: true,
1393
+ frozenLockfile: flags["frozen-lockfile"],
1394
+ ...buildConfigs(loaded, flags),
1395
+ hostConfigDiagnostics,
1396
+ controller: controllerFor2(loaded.config, operation),
1397
+ buildTarget: buildTargetFor2(operation)
1398
+ });
1399
+ if (hasErrors3(emitted.diagnostics)) {
1400
+ throw new DiagnosticFailure(emitted);
1401
+ }
1402
+ if (!emitted.controllerConfig) {
1403
+ throw new Error("Configure build settings for deployment.");
1404
+ }
1405
+ return { ...emitted.controllerConfig, io: {} };
1406
+ };
1407
+
1408
+ // packages/compiler/src/project/cli.ts
1409
+ var usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config tsplc.config.ts] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
1410
+
1411
+ Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1412
+ tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate]
1413
+ tsplc target | status | login | logout
1414
+ tsplc vars [path] | read <expression>... | write <expression> <value>
1415
+ tsplc force <expression> <value> | unforce [expression]... [--restore]
1416
+ tsplc start | stop | reset warm|cold (-y skips confirmations)
1262
1417
 
1263
- // packages/compiler/project/cli.ts
1418
+ Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
1419
+ the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
1420
+ tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;
1264
1421
  async function main() {
1265
1422
  const { values, positionals } = parseArgs({
1266
1423
  allowPositionals: true,
1267
1424
  options: {
1268
1425
  config: { type: "string" },
1426
+ target: { type: "string" },
1269
1427
  help: { type: "boolean", short: "h" },
1270
1428
  "emit-only": { type: "boolean" },
1271
1429
  format: { type: "string" },
@@ -1286,261 +1444,77 @@ async function main() {
1286
1444
  opcua: { type: "boolean" }
1287
1445
  }
1288
1446
  });
1289
- const command = positionals[0], file = values.config ?? "tsplc.config.ts";
1290
- if (!command || values.help) {
1291
- console.log(`tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config tsplc.config.ts] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
1292
-
1293
- Plant agent (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN):
1294
- tsplc deploy [--download] [--select] [--initialize-user] [--simulate]
1295
- tsplc target | status | login | logout
1296
- tsplc vars [path] | read <expression>... | write <expression> <value>
1297
- tsplc force <expression> <value> | unforce [expression]... [--restore]
1298
- tsplc start | stop | reset warm|cold (-y skips confirmations)
1299
-
1300
- Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
1301
- the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
1302
- tsplc debug [--port 4870] [--server-url url] [--opcua]`);
1447
+ const [name, ...args] = positionals;
1448
+ const file = values.config ?? "tsplc.config.ts";
1449
+ if (!name || values.help) {
1450
+ console.log(usage);
1303
1451
  return 0;
1304
1452
  }
1305
- if (command === "debug") {
1306
- if (positionals.length > 1)
1307
- throw new Error("Usage: tsplc debug [--port 4870] [--server-url url] [--opcua]");
1308
- await serveProjectDebugger(await loadTsplcConfig3(file), values);
1453
+ if (name === "debug") {
1454
+ if (args.length) {
1455
+ throw new Error("Usage: tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]");
1456
+ }
1457
+ await serveProjectDebugger(await loadTsplcConfig3(file, {
1458
+ env: process.env,
1459
+ target: values.target,
1460
+ forAgent: false
1461
+ }), values);
1309
1462
  return 0;
1310
1463
  }
1311
- if (plantCommands.has(command)) {
1312
- const failed = await runPlantCommand(command, positionals.slice(1), values, {
1464
+ const plant = plantCommand(name);
1465
+ if (plant) {
1466
+ const failed = await runPlantCommand(connect2(process.env), plant, args, values, {
1313
1467
  file,
1314
- load: () => loadTsplcConfig3(file)
1315
- });
1468
+ load: () => loadTsplcConfig3(file, {
1469
+ env: process.env,
1470
+ target: values.target,
1471
+ forAgent: true
1472
+ })
1473
+ }, process.env);
1316
1474
  return failed ? report(failed, values.format) : 0;
1317
1475
  }
1318
- if (positionals.length > 1)
1476
+ if (args.length) {
1319
1477
  throw new Error("Specify one command.");
1320
- if (![
1321
- "install",
1322
- "typegen",
1323
- "check",
1324
- "build",
1325
- "run",
1326
- "download",
1327
- "online-change",
1328
- "inspect",
1329
- "clean",
1330
- "configure"
1331
- ].includes(command))
1332
- throw new Error(`Unknown command ${command}.`);
1333
- if (values.format && !["json", "text"].includes(values.format))
1334
- throw new Error("--format must be json or text.");
1335
- if (values["emit-only"] && command !== "build")
1336
- throw new Error("--emit-only is supported by build only.");
1337
- if (values.runtime && command !== "configure")
1338
- throw new Error("--runtime applies only to configure.");
1339
- if ((values.plc || values.server) && command !== "build")
1340
- throw new Error("--plc and --server apply only to build.");
1341
- if (values.simulate && !["run", "download", "online-change", "deploy"].includes(command))
1342
- throw new Error("--simulate applies only to run, download, online-change and deploy.");
1343
- if (values.plc && values.server)
1344
- throw new Error("Choose --plc or --server, or omit both for a full build.");
1345
- if (values.server && values["emit-only"])
1346
- throw new Error("--emit-only applies to PLC emission only.");
1347
- const log = console.log, previousLogTarget = process.env["TSPLC_LOG_STDERR"];
1348
- if (values.format === "json") {
1349
- console.log = console.error;
1350
- process.env["TSPLC_LOG_STDERR"] = "1";
1351
1478
  }
1352
- let result;
1479
+ const command = projectCommand(name);
1480
+ if (!command) {
1481
+ throw new Error(`Unknown command ${name}.`);
1482
+ }
1483
+ checkProjectFlags(command, values);
1484
+ const result = await withProgressOnStderr(values.format === "json", () => runProjectCommand(command, file, values, process.env));
1485
+ return report(result, values.format);
1486
+ }
1487
+ async function withProgressOnStderr(enabled, run) {
1488
+ if (!enabled) {
1489
+ return run();
1490
+ }
1491
+ const log = console.log;
1492
+ const previousLogTarget = process.env["TSPLC_LOG_STDERR"];
1493
+ console.log = console.error;
1494
+ process.env["TSPLC_LOG_STDERR"] = "1";
1353
1495
  try {
1354
- if (command === "configure") {
1355
- await (values.runtime ? configureRuntime() : configureDocker());
1356
- result = { ok: true };
1357
- } else if (command === "clean") {
1358
- result = await cleanProject(file);
1359
- } else {
1360
- if (["check", "build", "run", "download", "online-change"].includes(command)) {
1361
- const diagnostics = checkHostConfig3(resolve6(file));
1362
- if (hasErrors4(diagnostics))
1363
- throw new DiagnosticFailure({ diagnostics });
1364
- }
1365
- const loaded = await loadTsplcConfig3(file);
1366
- const { config, configFile, root } = loaded;
1367
- const target = values.simulate ? { ...loaded, config: simulationConfig2(config) } : loaded;
1368
- if (command === "install")
1369
- result = {
1370
- libraries: await installLibraries3(config.dependencies, root, {
1371
- frozen: values["frozen-lockfile"]
1372
- })
1373
- };
1374
- else if (command === "typegen") {
1375
- const targets = await projectTargets2(file, { loaded });
1376
- if (config.compiler && !values.check) {
1377
- await generateProject2(file, { hardwareOnly: true, loaded, targets });
1378
- const emitted = await buildProject2(file, { emitOnly: true, loaded });
1379
- if (hasErrors4(emitted.diagnostics))
1380
- throw new DiagnosticFailure(emitted);
1381
- }
1382
- result = await generateProject2(file, { check: values.check, loaded, targets });
1383
- } else if (command === "check") {
1384
- result = config.compiler ? await checkProject2(file, { loaded }) : {
1385
- objects: (await loadSources(resolveConfig({
1386
- ...rawBuildConfig(config),
1387
- io: resolveIo3(config, await loadHardware3(config, root))
1388
- }, configFile))).objects.length
1389
- };
1390
- } else if (command === "build" && values.server) {
1391
- result = await buildServer(config, root);
1392
- } else if (command === "build" || command === "run") {
1393
- if (config.compiler) {
1394
- const built = await buildProject2(file, {
1395
- emitOnly: values["emit-only"],
1396
- frozenLockfile: values["frozen-lockfile"],
1397
- loaded: target,
1398
- ...values.simulate && { configured: config },
1399
- controller: controllerFor2(config, command),
1400
- buildTarget: buildTargetFor(command)
1401
- });
1402
- if (hasErrors4(built.diagnostics))
1403
- throw new DiagnosticFailure(built);
1404
- await generateProject2(file, {
1405
- loaded,
1406
- targets: await projectTargets2(file, { loaded })
1407
- });
1408
- result = built;
1409
- } else {
1410
- if (values["emit-only"])
1411
- throw new Error("Raw Structured Text is already emitted.");
1412
- if (!config.build)
1413
- throw new Error("Configure build settings.");
1414
- const build = rawBuildConfig(config);
1415
- const libraries = await installLibraries3(config.dependencies, root, {
1416
- frozen: values["frozen-lockfile"]
1417
- });
1418
- const hardware = await loadHardware3(target.config, root);
1419
- result = await buildSt(resolveConfig({
1420
- ...build,
1421
- libraries,
1422
- io: resolveIo3(target.config, hardware),
1423
- deviceTree: await deviceTree3(target.config, hardware),
1424
- controller: controllerFor2(config, command)
1425
- }, configFile));
1426
- await generateProject2(file, { hardwareOnly: !config.typegen, loaded });
1427
- }
1428
- if (command === "build" && !values.plc && !values["emit-only"] && config.server?.runtime) {
1429
- const backend = await buildServer(config, root);
1430
- result = { ...typeof result === "object" && result !== null ? result : {}, ...backend };
1431
- }
1432
- if (command === "run") {
1433
- if (!config.build)
1434
- throw new Error("Configure build to run this project.");
1435
- await runProject(resolveConfig(config.compiler ? config.build : rawBuildConfig(config), configFile), config.name);
1436
- }
1437
- } else if (command === "inspect") {
1438
- if (!config.build)
1439
- throw new Error("Configure build settings and controller connection.");
1440
- result = await inspectController(resolveConfig({ ...config.build, controller: controllerFor2(config, command) }, configFile), values.read);
1441
- } else if (["download", "online-change"].includes(command)) {
1442
- if (!config.build)
1443
- throw new Error("Configure build settings and controller connection.");
1444
- let settings;
1445
- if (config.compiler) {
1446
- const emitted = await buildProject2(file, {
1447
- emitOnly: true,
1448
- forController: true,
1449
- frozenLockfile: values["frozen-lockfile"],
1450
- loaded: target,
1451
- ...values.simulate && { configured: config },
1452
- buildTarget: buildTargetFor(command)
1453
- });
1454
- if (hasErrors4(emitted.diagnostics))
1455
- throw new DiagnosticFailure(emitted);
1456
- if (!emitted.controllerConfig)
1457
- throw new Error("Configure build settings for deployment.");
1458
- settings = { ...emitted.controllerConfig, io: {} };
1459
- } else
1460
- settings = {
1461
- ...resolveConfig({
1462
- ...rawBuildConfig(config),
1463
- io: resolveIo3(target.config, await loadHardware3(target.config, root))
1464
- }, configFile),
1465
- libraries: await installLibraries3(config.dependencies, root, {
1466
- frozen: values["frozen-lockfile"]
1467
- })
1468
- };
1469
- result = await updateController({ ...settings, controller: controllerFor2(config, command) }, command, {
1470
- initializeUser: values["initialize-user"],
1471
- read: values.read
1472
- });
1473
- } else
1474
- throw new Error(`Unknown command ${command}.`);
1475
- }
1496
+ return await run();
1476
1497
  } finally {
1477
1498
  console.log = log;
1478
- if (previousLogTarget === undefined)
1499
+ if (previousLogTarget === undefined) {
1479
1500
  delete process.env["TSPLC_LOG_STDERR"];
1480
- else
1501
+ } else {
1481
1502
  process.env["TSPLC_LOG_STDERR"] = previousLogTarget;
1482
- }
1483
- return report(result, values.format);
1484
- }
1485
- async function serveProjectDebugger({ config, root }, flags) {
1486
- if (flags.opcua && !config.monitor)
1487
- throw new Error("Configure monitor with the controller's OPC UA endpoint to use --opcua.");
1488
- const agentUrl = process.env["TSPLC_AGENT_URL"];
1489
- if (!flags.opcua && !(agentUrl && process.env["TSPLC_AGENT_TOKEN"]))
1490
- throw new Error("Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.");
1491
- const file = resolve6(root, ".tsplc/artifacts/st/debug.json");
1492
- if (!existsSync4(file))
1493
- throw new Error(`No debug manifest at ${relative2(process.cwd(), file)}: build with debug configured.`);
1494
- const port = Number(flags.port ?? 4870);
1495
- if (!Number.isInteger(port) || port < 1 || port > 65535)
1496
- throw new Error("--port must be a TCP port.");
1497
- const manifest = await loadManifest(file);
1498
- const serverUrl = flags["server-url"] ?? (config.server?.baseUrlEnv && process.env[config.server.baseUrlEnv]);
1499
- const tokenEnv = serverTokenEnv(config);
1500
- const token = tokenEnv && process.env[tokenEnv];
1501
- const log = (message) => console.log(`${new Date().toISOString()} ${message}`);
1502
- const debug = await createDebugger({
1503
- manifest,
1504
- adapter: flags.opcua && config.monitor ? createOpcUaAdapter(opcUaConnection(config.monitor, { root, env: process.env })) : createLoginAdapter({
1505
- read: readThroughAgent(connect()),
1506
- probe: manifest.build.target,
1507
- endpoint: `the plant agent at ${agentUrl}`
1508
- }),
1509
- stateDirectory: resolve6(root, ".tsplc/debug"),
1510
- watch: config.debug?.watch ?? {},
1511
- ...serverUrl && token && { server: { url: serverUrl, token } },
1512
- projectRoot: root,
1513
- log
1514
- });
1515
- const server = serveDebugger(debug, { port, log });
1516
- console.log(`tsPLC debugger at ${server.url}`);
1517
- if (!serverUrl || !token)
1518
- console.log("Not following the server's telemetry and requests: set server.baseUrlEnv or --server-url, and the server's bearer token variable.");
1519
- await new Promise((stopped) => {
1520
- process.once("SIGINT", stopped);
1521
- process.once("SIGTERM", stopped);
1522
- });
1523
- await server.stop(true);
1524
- await debug.close();
1525
- }
1526
-
1527
- class DiagnosticFailure extends Error {
1528
- result;
1529
- constructor(result) {
1530
- super("PLC validation failed.");
1531
- this.result = result;
1503
+ }
1532
1504
  }
1533
1505
  }
1534
1506
  function report(result, format) {
1535
- const diagnostics = result && typeof result === "object" && "diagnostics" in result ? result.diagnostics : [];
1507
+ const diagnostics = result.diagnostics ?? [];
1536
1508
  const ok = !hasErrors4(diagnostics);
1537
- if (format === "json")
1538
- console.log(JSON.stringify({ ok, ...result && typeof result === "object" ? result : { result } }));
1539
- else {
1540
- for (const diagnostic of diagnostics)
1509
+ if (format === "json") {
1510
+ console.log(JSON.stringify({ ok, ...result }));
1511
+ } else {
1512
+ for (const diagnostic of diagnostics) {
1541
1513
  console.error(formatDiagnostic(diagnostic));
1542
- if (ok)
1514
+ }
1515
+ if (ok) {
1543
1516
  console.log("tsPLC completed.");
1517
+ }
1544
1518
  }
1545
1519
  return ok ? 0 : 1;
1546
1520
  }
@@ -1552,16 +1526,19 @@ try {
1552
1526
  process.exitCode = report(cause.result, json ? "json" : undefined);
1553
1527
  } else {
1554
1528
  const message = cause instanceof Error ? cause.message : String(cause);
1555
- if (json)
1529
+ if (json) {
1556
1530
  console.log(JSON.stringify({
1557
1531
  ok: false,
1558
- diagnostics: [{ origin: "config", code: "PLC5003", severity: "error", message }]
1532
+ diagnostics: [
1533
+ { origin: "config", code: "PLC5003", severity: "error", message }
1534
+ ]
1559
1535
  }));
1560
- else
1536
+ } else {
1561
1537
  console.error(message);
1538
+ }
1562
1539
  process.exitCode = 1;
1563
1540
  }
1564
1541
  }
1565
1542
 
1566
- //# debugId=66EFA12A78CD380A64756E2164756E21
1543
+ //# debugId=F643A569C6B4952B64756E2164756E21
1567
1544
  //# sourceMappingURL=cli.js.map