@tsplc/compiler 0.2.21 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +280 -223
  3. package/dist/cli.js.map +12 -12
  4. package/dist/codesys.js +452 -330
  5. package/dist/codesys.js.map +24 -24
  6. package/dist/elaborate-capture.js +112 -7
  7. package/dist/elaborate-capture.js.map +5 -4
  8. package/dist/index.js +5682 -5407
  9. package/dist/index.js.map +39 -37
  10. package/dist/ir.js +1154 -327
  11. package/dist/ir.js.map +23 -20
  12. package/dist/project.js +68 -29
  13. package/dist/project.js.map +4 -4
  14. package/dist/retain.js +8 -0
  15. package/dist/retain.js.map +10 -0
  16. package/dist/server-check.js +59 -0
  17. package/dist/server-check.js.map +11 -0
  18. package/dist/telemetry.js +19 -10
  19. package/dist/telemetry.js.map +3 -3
  20. package/package.json +33 -12
  21. package/src/codesys/config.ts +1 -1
  22. package/src/codesys/debug.ts +7 -21
  23. package/src/codesys/engineering.ts +8 -12
  24. package/src/codesys/global-lists.ts +19 -17
  25. package/src/codesys/global-names.ts +3 -3
  26. package/src/codesys/http.ts +37 -34
  27. package/src/codesys/index.ts +5 -22
  28. package/src/codesys/instrumentation.ts +3 -1
  29. package/src/codesys/io-paths.ts +2 -1
  30. package/src/codesys/manifest.ts +35 -18
  31. package/src/codesys/numeric.ts +2 -4
  32. package/src/codesys/plan.ts +94 -26
  33. package/src/codesys/publication.ts +4 -3
  34. package/src/codesys/routines.ts +2 -2
  35. package/src/codesys/sources.ts +1 -0
  36. package/src/codesys/st-files.ts +86 -50
  37. package/src/codesys/storage.ts +44 -9
  38. package/src/codesys/task-access.ts +32 -10
  39. package/src/codesys/telemetry.ts +93 -46
  40. package/src/codesys/types.ts +81 -3
  41. package/src/codesys/vendor.ts +1 -1
  42. package/src/frontend/analyzer.ts +15 -14
  43. package/src/frontend/async.ts +23 -21
  44. package/src/frontend/blocks.ts +7 -6
  45. package/src/frontend/configuration.ts +8 -6
  46. package/src/frontend/const-functions.ts +5 -5
  47. package/src/frontend/cooperative.ts +2 -1
  48. package/src/frontend/coroutines.ts +24 -21
  49. package/src/frontend/elaborate/calls.ts +12 -7
  50. package/src/frontend/elaborate/capture-protocol.ts +103 -0
  51. package/src/frontend/elaborate/capture.ts +48 -19
  52. package/src/frontend/elaborate/dialect.ts +2 -2
  53. package/src/frontend/elaborate/expressions.ts +9 -6
  54. package/src/frontend/elaborate/frame.ts +1 -1
  55. package/src/frontend/elaborate/graph.ts +27 -43
  56. package/src/frontend/elaborate/index.ts +52 -17
  57. package/src/frontend/elaborate/initializers.ts +3 -2
  58. package/src/frontend/elaborate/layouts.ts +2 -2
  59. package/src/frontend/elaborate/model.ts +34 -21
  60. package/src/frontend/elaborate/retention.ts +206 -0
  61. package/src/frontend/elaborate/specialize.ts +7 -6
  62. package/src/frontend/elaborate/statements.ts +47 -38
  63. package/src/frontend/elaborate/storage.ts +26 -6
  64. package/src/frontend/exposure.ts +6 -6
  65. package/src/frontend/expressions.ts +26 -25
  66. package/src/frontend/intrinsics.ts +3 -3
  67. package/src/frontend/module-graph.ts +1 -1
  68. package/src/frontend/positions.ts +2 -1
  69. package/src/frontend/promise-chains.ts +1 -0
  70. package/src/frontend/promises.ts +8 -7
  71. package/src/frontend/routines.ts +3 -2
  72. package/src/frontend/sdk.ts +2 -2
  73. package/src/frontend/services.ts +23 -20
  74. package/src/frontend/statements.ts +8 -6
  75. package/src/frontend/tasks.ts +11 -6
  76. package/src/frontend/telemetry.ts +1 -1
  77. package/src/frontend/types.ts +11 -9
  78. package/src/frontend/typescript.ts +92 -42
  79. package/src/index.ts +2 -1
  80. package/src/ir/aggregates.ts +4 -3
  81. package/src/ir/allocation.ts +2 -1
  82. package/src/ir/core-model.ts +38 -8
  83. package/src/ir/declarations.ts +12 -12
  84. package/src/ir/domains.ts +8 -8
  85. package/src/ir/fold.ts +2 -2
  86. package/src/ir/index.ts +53 -40
  87. package/src/ir/job-errors.ts +22 -11
  88. package/src/ir/layouts.ts +3 -2
  89. package/src/ir/link.ts +6 -24
  90. package/src/ir/model.ts +3 -2
  91. package/src/ir/normalization-error.ts +1 -1
  92. package/src/ir/normalize.ts +19 -12
  93. package/src/ir/numeric.ts +1 -0
  94. package/src/{codesys → ir}/operands.ts +2 -6
  95. package/src/ir/ranges.ts +2 -2
  96. package/src/ir/routine.ts +35 -20
  97. package/src/ir/scalars.ts +3 -3
  98. package/src/ir/share.ts +862 -0
  99. package/src/ir/temporaries.ts +236 -0
  100. package/src/ir/types.ts +1 -1
  101. package/src/project/artifacts.ts +12 -2
  102. package/src/project/cli.ts +42 -44
  103. package/src/project/debugger.ts +15 -9
  104. package/src/project/index.ts +1 -1
  105. package/src/project/plant.ts +34 -23
  106. package/src/project/project-commands.ts +92 -73
  107. package/src/project/project.ts +91 -42
  108. package/src/project/release.ts +50 -57
  109. package/src/project/server-check.ts +54 -0
  110. package/src/project/server.ts +60 -41
  111. package/src/project/terminal.ts +3 -1
  112. package/stdlib/retain.ts +2 -0
  113. package/types/globals.d.ts +1 -0
  114. package/types/retain.d.ts +6 -0
  115. package/types/telemetry.d.ts +2 -2
@@ -0,0 +1,236 @@
1
+ import {
2
+ type CoreExpression,
3
+ type CoreFunction,
4
+ type CoreFunctionBlock,
5
+ type CorePath,
6
+ type CoreStatement,
7
+ nestedBodies,
8
+ type VerifiedCoreModule,
9
+ } from "./core-model.ts";
10
+ import { admitCore } from "./normalize.ts";
11
+ import { statementExpressions, subexpressions } from "./operands.ts";
12
+ import { isTemporary } from "./routine.ts";
13
+
14
+ /**
15
+ * Writes a temporary's value where it is read, when nothing can happen in between: the temporary
16
+ * is assigned once, as a whole, and read once, by the statement right after the assignment, in
17
+ * an expression that statement evaluates before it writes or calls anything. Loop bounds and
18
+ * switch values are left alone: ST evaluates them more than once.
19
+ *
20
+ * Only a load, a constant or a BOOL moves. An arithmetic value keeps its temporary, which
21
+ * stores it at its own type: written into a wider expression, ST could compute it wider.
22
+ */
23
+ export function forwardTemporaries(
24
+ core: VerifiedCoreModule,
25
+ ): VerifiedCoreModule {
26
+ const functions = core.functions.map((fn): CoreFunction => forward(fn));
27
+ const blocks = core.blocks.map((block): CoreFunctionBlock => forward(block));
28
+ return admitCore({ ...core, functions, blocks });
29
+ }
30
+
31
+ function forward<Routine extends CoreFunction | CoreFunctionBlock>(
32
+ routine: Routine,
33
+ ): Routine {
34
+ const temporaries = new Set(
35
+ routine.locals
36
+ .filter((local) => isTemporary(routine.id, local))
37
+ .map((local) => local.id),
38
+ );
39
+ if (!temporaries.size) {
40
+ return routine;
41
+ }
42
+ const writes = new Map<string, number>();
43
+ const reads = new Map<string, number>();
44
+ const count = (counts: Map<string, number>, root: string) =>
45
+ counts.set(root, (counts.get(root) ?? 0) + 1);
46
+ const expression = (value: CoreExpression): void => {
47
+ if (value.kind === "load") {
48
+ count(reads, value.root);
49
+ }
50
+ if (value.kind === "borrow") {
51
+ // A borrowed temporary is written through its reference.
52
+ count(writes, value.place.root);
53
+ count(reads, value.place.root);
54
+ }
55
+ subexpressions(value).forEach(expression);
56
+ };
57
+ const statements = (items: readonly CoreStatement[]): void => {
58
+ for (const item of items) {
59
+ if (item.kind === "assign") {
60
+ count(writes, item.root);
61
+ }
62
+ if (item.kind === "for") {
63
+ count(writes, item.counter);
64
+ }
65
+ if (item.kind === "invoke" && item.destination !== undefined) {
66
+ count(writes, item.destination);
67
+ }
68
+ statementExpressions(item).forEach(expression);
69
+ nestedBodies(item).forEach(statements);
70
+ }
71
+ };
72
+ statements(routine.body);
73
+ const movable = (
74
+ item: CoreStatement,
75
+ ): item is Extract<CoreStatement, { kind: "assign" }> =>
76
+ item.kind === "assign" &&
77
+ !item.path?.length &&
78
+ temporaries.has(item.root) &&
79
+ writes.get(item.root) === 1 &&
80
+ reads.get(item.root) === 1 &&
81
+ (item.value.kind === "load" ||
82
+ item.value.kind === "constant" ||
83
+ item.value.type === "BOOL");
84
+
85
+ const forwarded = new Set<string>();
86
+ const rewrite = (items: readonly CoreStatement[]): CoreStatement[] => {
87
+ const result = items.map((item) => withBodies(item, rewrite));
88
+ // From the end, so a value can move through a chain of temporaries.
89
+ for (let index = result.length - 2; index >= 0; index--) {
90
+ const item = result[index];
91
+ const next = result[index + 1];
92
+ if (!item || !next || !movable(item) || !readsOwn(next, item.root)) {
93
+ continue;
94
+ }
95
+ result.splice(index, 2, substitute(next, item.root, item.value));
96
+ forwarded.add(item.root);
97
+ }
98
+ return result;
99
+ };
100
+ const body = rewrite(routine.body);
101
+ if (!forwarded.size) {
102
+ return routine;
103
+ }
104
+ return {
105
+ ...routine,
106
+ locals: routine.locals.filter((local) => !forwarded.has(local.id)),
107
+ body,
108
+ };
109
+ }
110
+
111
+ /** Whether a statement reads `root` in what it evaluates once, before it writes or calls. */
112
+ function readsOwn(item: CoreStatement, root: string): boolean {
113
+ if (item.kind === "for" || item.kind === "switch") {
114
+ return false;
115
+ }
116
+ const reads = (value: CoreExpression): boolean =>
117
+ (value.kind === "load" && value.root === root) ||
118
+ subexpressions(value).some(reads);
119
+ return statementExpressions(item).some(reads);
120
+ }
121
+
122
+ /** A statement with each nested body rewritten. */
123
+ function withBodies(
124
+ item: CoreStatement,
125
+ rewrite: (items: readonly CoreStatement[]) => CoreStatement[],
126
+ ): CoreStatement {
127
+ switch (item.kind) {
128
+ case "if":
129
+ return {
130
+ ...item,
131
+ // biome-ignore lint/suspicious/noThenProperty: PLC branch data is an array, not a thenable callback.
132
+ then: rewrite(item.then),
133
+ else: rewrite(item.else),
134
+ };
135
+ case "switch":
136
+ return {
137
+ ...item,
138
+ cases: item.cases.map((branch) => ({
139
+ ...branch,
140
+ body: rewrite(branch.body),
141
+ })),
142
+ fallback: rewrite(item.fallback),
143
+ };
144
+ case "for":
145
+ return { ...item, body: rewrite(item.body) };
146
+ default:
147
+ return item;
148
+ }
149
+ }
150
+
151
+ /** A statement with its read of `root` replaced by `value`. */
152
+ function substitute(
153
+ item: CoreStatement,
154
+ root: string,
155
+ value: CoreExpression,
156
+ ): CoreStatement {
157
+ const replace = (expression: CoreExpression): CoreExpression => {
158
+ if (expression.kind === "load" && expression.root === root) {
159
+ return value;
160
+ }
161
+ switch (expression.kind) {
162
+ case "constant":
163
+ return expression;
164
+ case "load":
165
+ return expression.path
166
+ ? { ...expression, path: replacePath(expression.path) }
167
+ : expression;
168
+ case "borrow":
169
+ return {
170
+ ...expression,
171
+ place: {
172
+ ...expression.place,
173
+ path: replacePath(expression.place.path),
174
+ },
175
+ };
176
+ case "unary":
177
+ case "convert":
178
+ return { ...expression, operand: replace(expression.operand) };
179
+ case "binary":
180
+ return {
181
+ ...expression,
182
+ left: replace(expression.left),
183
+ right: replace(expression.right),
184
+ };
185
+ }
186
+ };
187
+ const replacePath = (path: CorePath): CorePath =>
188
+ path.map((segment) =>
189
+ segment.kind === "field"
190
+ ? segment
191
+ : { kind: "index", value: replace(segment.value) },
192
+ );
193
+ switch (item.kind) {
194
+ case "assign":
195
+ return {
196
+ ...item,
197
+ ...(item.path && { path: replacePath(item.path) }),
198
+ value: replace(item.value),
199
+ };
200
+ case "if":
201
+ return { ...item, condition: replace(item.condition) };
202
+ case "invoke":
203
+ return {
204
+ ...item,
205
+ ...(item.index && { index: replace(item.index) }),
206
+ arguments: item.arguments.map(replace),
207
+ };
208
+ case "blockUpdate":
209
+ return {
210
+ ...item,
211
+ ...(item.index && { index: replace(item.index) }),
212
+ inputs: Object.fromEntries(
213
+ Object.entries(item.inputs).map(([name, input]) => [
214
+ name,
215
+ replace(input),
216
+ ]),
217
+ ),
218
+ };
219
+ case "return":
220
+ return item.value ? { ...item, value: replace(item.value) } : item;
221
+ case "telemetry":
222
+ return {
223
+ ...item,
224
+ ...(item.record.kind === "exception" && {
225
+ record: { ...item.record, code: replace(item.record.code) },
226
+ }),
227
+ properties: item.properties.map((property) => ({
228
+ ...property,
229
+ value: replace(property.value),
230
+ ...(property.length && { length: replace(property.length) }),
231
+ })),
232
+ };
233
+ default:
234
+ return item;
235
+ }
236
+ }
package/src/ir/types.ts CHANGED
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  type ElementaryType,
3
- elementaryTypes,
4
3
  integerRange as elementaryIntegerRange,
4
+ elementaryTypes,
5
5
  } from "@tsplc/iec";
6
6
 
7
7
  export type TypeId = string;
@@ -11,6 +11,10 @@ import {
11
11
  import { dirname, join } from "node:path";
12
12
  import type { buildCodesys } from "@tsplc/compiler/codesys";
13
13
  import { sha256Digest } from "@tsplc/config/build";
14
+ import {
15
+ emittedStDirectory,
16
+ generatedDirectory,
17
+ } from "@tsplc/config/project-files";
14
18
  import { z } from "zod";
15
19
 
16
20
  const missing = (cause: unknown): boolean =>
@@ -168,8 +172,8 @@ export async function owned(
168
172
  ownership?: Manifest;
169
173
  unknown: string[];
170
174
  }> {
171
- const root = join(dirname(configFile), ".tsplc");
172
- const output = join(root, "artifacts");
175
+ const root = join(dirname(configFile), generatedDirectory);
176
+ const output = join(dirname(configFile), dirname(emittedStDirectory));
173
177
  if (!(await directory(root)) || !(await directory(output))) {
174
178
  return { root, output, unknown: [] };
175
179
  }
@@ -209,13 +213,19 @@ export async function owned(
209
213
  "manifest.json",
210
214
  "receipt.json",
211
215
  ]);
216
+ // Thousands of files share a few hundred directories; each is checked once.
217
+ const checked = new Set<string>();
212
218
  for (const file of ownership.files) {
213
219
  let parent = output;
214
220
  for (const part of file.path.split("/").slice(0, -1)) {
215
221
  parent = join(parent, part);
222
+ if (checked.has(parent)) {
223
+ continue;
224
+ }
216
225
  if (!(await directory(parent))) {
217
226
  throw new Error(`Missing generated directory: ${parent}`);
218
227
  }
228
+ checked.add(parent);
219
229
  }
220
230
  const path = join(output, file.path);
221
231
  const entry = await lstat(path);
@@ -1,14 +1,15 @@
1
1
  #!/usr/bin/env bun
2
2
  import { existsSync } from "node:fs";
3
3
  import { parseArgs } from "node:util";
4
- import { loadTsplcConfig } from "@tsplc/config";
5
4
  import { formatDiagnostic, hasErrors } from "@tsplc/compiler/ir";
5
+ import { loadTsplcConfig } from "@tsplc/config";
6
+ import { z } from "zod";
6
7
  import { serveProjectDebugger } from "./debugger.ts";
7
8
  import { connect, plantCommand, runPlantCommand } from "./plant.ts";
8
9
  import {
9
10
  type CommandResult,
10
- DiagnosticFailure,
11
11
  checkProjectFlags,
12
+ DiagnosticFailure,
12
13
  projectCommand,
13
14
  runProjectCommand,
14
15
  } from "./project-commands.ts";
@@ -26,8 +27,33 @@ Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it
26
27
  the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
27
28
  tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;
28
29
 
30
+ const formatSchema = z.enum(["json", "text"]).optional();
31
+
32
+ /**
33
+ * The `--format` the command line names, read before it is fully parsed so a command that fails
34
+ * to parse still answers in that format. A positional `json` is an argument, not a format.
35
+ */
36
+ const requestedFormat = (argv: readonly string[]) => {
37
+ const index = argv.findIndex(
38
+ (argument) => argument === "--format" || argument.startsWith("--format="),
39
+ );
40
+ const flag = argv[index];
41
+ if (index < 0 || flag === undefined) {
42
+ return undefined;
43
+ }
44
+ return flag === "--format" ? argv[index + 1] : flag.slice("--format=".length);
45
+ };
46
+
47
+ const outputFormat = (format: string | undefined) => {
48
+ const parsed = formatSchema.safeParse(format);
49
+ if (!parsed.success) {
50
+ throw new Error("--format must be json or text.");
51
+ }
52
+ return parsed.data;
53
+ };
54
+
29
55
  async function main() {
30
- const { values, positionals } = parseArgs({
56
+ const { values: parsed, positionals } = parseArgs({
31
57
  allowPositionals: true,
32
58
  options: {
33
59
  config: { type: "string" },
@@ -52,6 +78,10 @@ async function main() {
52
78
  opcua: { type: "boolean" },
53
79
  },
54
80
  });
81
+ const values = {
82
+ ...parsed,
83
+ format: outputFormat(parsed.format),
84
+ };
55
85
  const [name, ...args] = positionals;
56
86
  const file = values.config ?? "tsplc.config.ts";
57
87
  if (!name || values.help) {
@@ -85,14 +115,11 @@ async function main() {
85
115
  // In a project, the target names the agent; elsewhere TSPLC_AGENT_URL does.
86
116
  const loaded = existsSync(file) ? await load() : undefined;
87
117
  const env = loaded?.env ?? process.env;
88
- const failed = await runPlantCommand(
89
- connect(env),
90
- plant,
91
- args,
92
- values,
93
- { file, load: loaded ? async () => loaded : load },
94
- env,
95
- );
118
+ const failed = await runPlantCommand(connect(env), plant, args, values, {
119
+ file,
120
+ load: loaded ? async () => loaded : load,
121
+ environment: env,
122
+ });
96
123
  return failed ? report(failed, values.format) : 0;
97
124
  }
98
125
  if (args.length) {
@@ -103,37 +130,10 @@ async function main() {
103
130
  throw new Error(`Unknown command ${name}.`);
104
131
  }
105
132
  checkProjectFlags(command, values);
106
- const result = await withProgressOnStderr(values.format === "json", () =>
107
- runProjectCommand(command, file, values, process.env),
133
+ return report(
134
+ await runProjectCommand(command, file, values, { ...process.env }),
135
+ values.format,
108
136
  );
109
- return report(result, values.format);
110
- }
111
-
112
- /**
113
- * Sends progress to stderr while `run` runs, so stdout holds only the JSON result. Docker
114
- * commands that `@tsplc/build` runs follow `TSPLC_LOG_STDERR`.
115
- */
116
- async function withProgressOnStderr<T>(
117
- enabled: boolean,
118
- run: () => Promise<T>,
119
- ) {
120
- if (!enabled) {
121
- return run();
122
- }
123
- const log = console.log;
124
- const previousLogTarget = process.env["TSPLC_LOG_STDERR"];
125
- console.log = console.error;
126
- process.env["TSPLC_LOG_STDERR"] = "1";
127
- try {
128
- return await run();
129
- } finally {
130
- console.log = log;
131
- if (previousLogTarget === undefined) {
132
- delete process.env["TSPLC_LOG_STDERR"];
133
- } else {
134
- process.env["TSPLC_LOG_STDERR"] = previousLogTarget;
135
- }
136
- }
137
137
  }
138
138
 
139
139
  function report(result: CommandResult, format: string | undefined) {
@@ -155,9 +155,7 @@ function report(result: CommandResult, format: string | undefined) {
155
155
  try {
156
156
  process.exitCode = await main();
157
157
  } catch (cause) {
158
- // main() may fail before its options parse, so detect JSON output from raw argv.
159
- const json =
160
- process.argv.includes("json") || process.argv.includes("--format=json");
158
+ const json = requestedFormat(process.argv.slice(2)) === "json";
161
159
  if (cause instanceof DiagnosticFailure) {
162
160
  process.exitCode = report(cause.result, json ? "json" : undefined);
163
161
  } else {
@@ -1,6 +1,11 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { relative, resolve } from "node:path";
3
- import { serverTokenEnv, type loadTsplcConfig } from "@tsplc/config";
3
+ import { type LoadedConfig, serverTokenEnv } from "@tsplc/config";
4
+ import { tcpPort } from "@tsplc/config/build";
5
+ import {
6
+ emittedStDirectory,
7
+ generatedDirectory,
8
+ } from "@tsplc/config/project-files";
4
9
  import {
5
10
  createDebugger,
6
11
  createLoginAdapter,
@@ -9,6 +14,7 @@ import {
9
14
  opcUaConnection,
10
15
  serveDebugger,
11
16
  } from "@tsplc/debug";
17
+ import { debugManifestFile } from "@tsplc/debug/manifest";
12
18
  import { connect, readThroughAgent } from "./plant.ts";
13
19
 
14
20
  /**
@@ -18,7 +24,7 @@ import { connect, readThroughAgent } from "./plant.ts";
18
24
  * `server.baseUrlEnv`) and the PLC's bearer token are in the config's environment.
19
25
  */
20
26
  export async function serveProjectDebugger(
21
- { config, root, env }: Awaited<ReturnType<typeof loadTsplcConfig>>,
27
+ { config, root, env }: LoadedConfig,
22
28
  flags: { port?: string; "server-url"?: string; opcua?: boolean },
23
29
  ) {
24
30
  if (flags.opcua && !config.monitor) {
@@ -26,20 +32,20 @@ export async function serveProjectDebugger(
26
32
  "Configure monitor with the controller's OPC UA endpoint to use --opcua.",
27
33
  );
28
34
  }
29
- const agentUrl = env["TSPLC_AGENT_URL"];
30
- if (!flags.opcua && !(agentUrl && env["TSPLC_AGENT_TOKEN"])) {
35
+ const agentUrl = env.TSPLC_AGENT_URL;
36
+ if (!flags.opcua && !(agentUrl && env.TSPLC_AGENT_TOKEN)) {
31
37
  throw new Error(
32
38
  "Set TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN to read through the plant agent's login, or pass --opcua for a local virtual PLC.",
33
39
  );
34
40
  }
35
- const file = resolve(root, ".tsplc/artifacts/st/debug.json");
41
+ const file = resolve(root, emittedStDirectory, debugManifestFile);
36
42
  if (!existsSync(file)) {
37
43
  throw new Error(
38
44
  `No debug manifest at ${relative(process.cwd(), file)}: build with debug configured.`,
39
45
  );
40
46
  }
41
- const port = Number(flags.port ?? 4870);
42
- if (!Number.isInteger(port) || port < 1 || port > 65535) {
47
+ const port = tcpPort.safeParse(Number(flags.port ?? 4870));
48
+ if (!port.success) {
43
49
  throw new Error("--port must be a TCP port.");
44
50
  }
45
51
  const manifest = await loadManifest(file);
@@ -60,13 +66,13 @@ export async function serveProjectDebugger(
60
66
  probe: manifest.build.target,
61
67
  endpoint: `the plant agent at ${agentUrl}`,
62
68
  }),
63
- stateDirectory: resolve(root, ".tsplc/debug"),
69
+ stateDirectory: resolve(root, generatedDirectory, "debug"),
64
70
  watch: config.debug?.watch ?? {},
65
71
  ...(serverUrl && token && { server: { url: serverUrl, token } }),
66
72
  projectRoot: root,
67
73
  log,
68
74
  });
69
- const server = serveDebugger(debug, { port, log });
75
+ const server = serveDebugger(debug, { port: port.data, log });
70
76
  console.log(`tsPLC debugger at ${server.url}`);
71
77
  if (!serverUrl || !token) {
72
78
  console.log(
@@ -1,6 +1,6 @@
1
1
  export {
2
- checkProject,
3
2
  buildProject,
3
+ checkProject,
4
4
  cleanProject,
5
5
  projectTargets,
6
6
  } from "./project.ts";
@@ -1,8 +1,3 @@
1
- import {
2
- AgentOperationError,
3
- type AgentClient,
4
- createAgentClient,
5
- } from "@tsplc/agent/client";
6
1
  import {
7
2
  ask,
8
3
  askCredentials,
@@ -10,8 +5,14 @@ import {
10
5
  type Target,
11
6
  type Variable,
12
7
  } from "@tsplc/agent";
8
+ import {
9
+ type AgentClient,
10
+ AgentOperationError,
11
+ createAgentClient,
12
+ } from "@tsplc/agent/client";
13
13
  import type { LoginCommand, LoginResult } from "@tsplc/build";
14
- import type { Environment, loadTsplcConfig } from "@tsplc/config";
14
+ import type { CompileEnvironment } from "@tsplc/compiler";
15
+ import type { LoadedConfig } from "@tsplc/config";
15
16
  import { LoginUnavailable, noLogin } from "@tsplc/debug";
16
17
  import { z } from "zod";
17
18
  import { prepareRelease } from "./release.ts";
@@ -48,15 +49,13 @@ export interface PlantFlags {
48
49
  "frozen-lockfile"?: boolean;
49
50
  }
50
51
 
51
- type LoadedConfig = Awaited<ReturnType<typeof loadTsplcConfig>>;
52
-
53
52
  /** The plant agent named by TSPLC_AGENT_URL and TSPLC_AGENT_TOKEN in `env`, where a target's agent sets the URL. */
54
53
  export const connect = (env: Record<string, string | undefined>) => {
55
54
  const environment = z
56
55
  .object({
57
56
  TSPLC_AGENT_URL: z.url({
58
57
  error:
59
- "Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://line-pc:4850",
58
+ "Configure the target's agent, or set TSPLC_AGENT_URL to the plant agent, such as http://plant-pc:4850",
60
59
  }),
61
60
  TSPLC_AGENT_TOKEN: z.string({
62
61
  error: "Set TSPLC_AGENT_TOKEN to the plant agent's token",
@@ -133,16 +132,16 @@ const selectTarget = async (agent: AgentClient): Promise<Target> => {
133
132
 
134
133
  /**
135
134
  * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from
136
- * `env`, else null for the user stored on the agent, else what `prompt` asks for. Initializing
135
+ * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing
137
136
  * the controller's user creates the one sent, so it never leaves it to the stored one.
138
137
  */
139
138
  export const controllerCredentials = async (
140
- env: Environment,
139
+ environment: CompileEnvironment,
141
140
  agent: { stored: boolean; initializeUser: boolean },
142
141
  prompt: () => Promise<Credentials>,
143
142
  ): Promise<Credentials | null> => {
144
- const username = env["TSPLC_CONTROLLER_USERNAME"];
145
- const password = env["TSPLC_CONTROLLER_PASSWORD"];
143
+ const username = environment.TSPLC_CONTROLLER_USERNAME;
144
+ const password = environment.TSPLC_CONTROLLER_PASSWORD;
146
145
  if (username && password) {
147
146
  return { username, password };
148
147
  }
@@ -159,7 +158,7 @@ const deploy = async (
159
158
  file: string,
160
159
  loaded: LoadedConfig,
161
160
  flags: PlantFlags,
162
- env: Environment,
161
+ environment: CompileEnvironment,
163
162
  ) => {
164
163
  const status = await agent.status();
165
164
  if (status.login) {
@@ -169,7 +168,12 @@ const deploy = async (
169
168
  !status.target || flags.select ? await selectTarget(agent) : status.target;
170
169
  console.log(`Building the release for ${target.host}…`);
171
170
  const building = timedProgress();
172
- const { release, diagnostics } = await prepareRelease(file, loaded, flags);
171
+ const { release, diagnostics } = await prepareRelease(
172
+ file,
173
+ loaded,
174
+ flags,
175
+ environment,
176
+ );
173
177
  if (!release) {
174
178
  return { diagnostics };
175
179
  }
@@ -184,7 +188,7 @@ const deploy = async (
184
188
  throw new Error("Cancelled.");
185
189
  }
186
190
  const credentials = await controllerCredentials(
187
- env,
191
+ environment,
188
192
  {
189
193
  stored: status.credentialsStored,
190
194
  initializeUser: flags["initialize-user"] ?? false,
@@ -224,7 +228,10 @@ const deploy = async (
224
228
  };
225
229
 
226
230
  /** Opens a login when none is working; it stays open across commands until `tsplc logout`. */
227
- const ensureLogin = async (agent: AgentClient, env: Environment) => {
231
+ const ensureLogin = async (
232
+ agent: AgentClient,
233
+ environment: CompileEnvironment,
234
+ ) => {
228
235
  const { login, credentialsStored } = await agent.status();
229
236
  if (login && "state" in login) {
230
237
  return;
@@ -234,7 +241,7 @@ const ensureLogin = async (agent: AgentClient, env: Environment) => {
234
241
  await agent.logout();
235
242
  }
236
243
  const credentials = await controllerCredentials(
237
- env,
244
+ environment,
238
245
  { stored: credentialsStored, initializeUser: false },
239
246
  askCredentials,
240
247
  );
@@ -346,8 +353,12 @@ export const runPlantCommand = async (
346
353
  command: PlantCommand,
347
354
  args: string[],
348
355
  flags: PlantFlags,
349
- project: { file: string; load: () => Promise<LoadedConfig> },
350
- env: Environment,
356
+ project: {
357
+ file: string;
358
+ load: () => Promise<LoadedConfig>;
359
+ /** What the release's compilation reads. */
360
+ environment: CompileEnvironment;
361
+ },
351
362
  ) => {
352
363
  const expect = (count: number, usage: string) => {
353
364
  if (args.length !== count) {
@@ -355,7 +366,7 @@ export const runPlantCommand = async (
355
366
  }
356
367
  };
357
368
  const send = async (loginCommand: LoginCommand) => {
358
- await ensureLogin(agent, env);
369
+ await ensureLogin(agent, project.environment);
359
370
  printLogin(await agent.command(loginCommand));
360
371
  };
361
372
  switch (command) {
@@ -369,7 +380,7 @@ export const runPlantCommand = async (
369
380
  project.file,
370
381
  await project.load(),
371
382
  flags,
372
- env,
383
+ project.environment,
373
384
  );
374
385
  if ("diagnostics" in deployed) {
375
386
  return deployed;
@@ -388,7 +399,7 @@ export const runPlantCommand = async (
388
399
  return printStatus(agent);
389
400
  case "login":
390
401
  expect(0, "");
391
- await ensureLogin(agent, env);
402
+ await ensureLogin(agent, project.environment);
392
403
  printLogin(await agent.command({ command: "state" }));
393
404
  return;
394
405
  case "logout": {