@tsplc/tmp-compiler 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +41 -2
  3. package/dist/cli.js +2325 -0
  4. package/dist/cli.js.map +26 -0
  5. package/dist/clock.js +11 -0
  6. package/dist/clock.js.map +11 -0
  7. package/dist/codesys.js +6558 -0
  8. package/dist/codesys.js.map +51 -0
  9. package/dist/collections.js +399 -0
  10. package/dist/collections.js.map +10 -0
  11. package/dist/index.js +16076 -0
  12. package/dist/index.js.map +61 -0
  13. package/dist/ir.js +3948 -0
  14. package/dist/ir.js.map +35 -0
  15. package/dist/retain.js +10 -0
  16. package/dist/retain.js.map +10 -0
  17. package/dist/signals.js +115 -0
  18. package/dist/signals.js.map +10 -0
  19. package/dist/telemetry.js +121 -0
  20. package/dist/telemetry.js.map +12 -0
  21. package/package.json +122 -4
  22. package/src/codesys/config.ts +50 -0
  23. package/src/codesys/debug.ts +655 -0
  24. package/src/codesys/emit.ts +185 -0
  25. package/src/codesys/endpoints.ts +111 -0
  26. package/src/codesys/engineering.ts +96 -0
  27. package/src/codesys/explain/expressions.ts +445 -0
  28. package/src/codesys/explain/flags.ts +134 -0
  29. package/src/codesys/explain/parameters.ts +53 -0
  30. package/src/codesys/explain/rows.ts +182 -0
  31. package/src/codesys/explain/tables.ts +79 -0
  32. package/src/codesys/explain/tasks.ts +68 -0
  33. package/src/codesys/explain/writes.ts +497 -0
  34. package/src/codesys/explain.ts +149 -0
  35. package/src/codesys/expressions.ts +100 -0
  36. package/src/codesys/global-lists.ts +284 -0
  37. package/src/codesys/global-names.ts +66 -0
  38. package/src/codesys/http.ts +1078 -0
  39. package/src/codesys/index.ts +13 -0
  40. package/src/codesys/instrumentation.ts +574 -0
  41. package/src/codesys/io-paths.ts +149 -0
  42. package/src/codesys/loops.ts +101 -0
  43. package/src/codesys/manifest.ts +684 -0
  44. package/src/codesys/names.ts +58 -0
  45. package/src/codesys/numeric.ts +516 -0
  46. package/src/codesys/plan.ts +688 -0
  47. package/src/codesys/programs.ts +138 -0
  48. package/src/codesys/publication.ts +99 -0
  49. package/src/codesys/required.ts +8 -0
  50. package/src/codesys/routines.ts +247 -0
  51. package/src/codesys/scan-clock.ts +103 -0
  52. package/src/codesys/scheduling.ts +96 -0
  53. package/src/codesys/service-channels.ts +24 -0
  54. package/src/codesys/sources.ts +118 -0
  55. package/src/codesys/st-files.ts +219 -0
  56. package/src/codesys/statements.ts +409 -0
  57. package/src/codesys/storage.ts +150 -0
  58. package/src/codesys/symbols.ts +240 -0
  59. package/src/codesys/task-access.ts +186 -0
  60. package/src/codesys/telemetry-settings.ts +19 -0
  61. package/src/codesys/telemetry.ts +852 -0
  62. package/src/codesys/types.ts +310 -0
  63. package/src/codesys/vendor.ts +113 -0
  64. package/src/frontend/analyzer.ts +779 -0
  65. package/src/frontend/async.ts +530 -0
  66. package/src/frontend/blocks.ts +578 -0
  67. package/src/frontend/configuration.ts +83 -0
  68. package/src/frontend/const-functions.ts +204 -0
  69. package/src/frontend/control-flow.ts +787 -0
  70. package/src/frontend/cooperative.ts +114 -0
  71. package/src/frontend/coroutines.ts +1336 -0
  72. package/src/frontend/dialect-names.ts +104 -0
  73. package/src/frontend/elaborate/array-searches.ts +224 -0
  74. package/src/frontend/elaborate/assignments.ts +343 -0
  75. package/src/frontend/elaborate/calls.ts +1342 -0
  76. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  77. package/src/frontend/elaborate/capture.ts +388 -0
  78. package/src/frontend/elaborate/declarations.ts +124 -0
  79. package/src/frontend/elaborate/dialect.ts +473 -0
  80. package/src/frontend/elaborate/expressions.ts +2171 -0
  81. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  82. package/src/frontend/elaborate/frame.ts +145 -0
  83. package/src/frontend/elaborate/generics.ts +123 -0
  84. package/src/frontend/elaborate/graph.ts +141 -0
  85. package/src/frontend/elaborate/imports.ts +105 -0
  86. package/src/frontend/elaborate/index.ts +851 -0
  87. package/src/frontend/elaborate/initializers.ts +235 -0
  88. package/src/frontend/elaborate/iterators.ts +1541 -0
  89. package/src/frontend/elaborate/layouts.ts +1025 -0
  90. package/src/frontend/elaborate/model.ts +478 -0
  91. package/src/frontend/elaborate/names.ts +134 -0
  92. package/src/frontend/elaborate/reduce.ts +900 -0
  93. package/src/frontend/elaborate/references.ts +727 -0
  94. package/src/frontend/elaborate/retention.ts +284 -0
  95. package/src/frontend/elaborate/specialize.ts +1137 -0
  96. package/src/frontend/elaborate/statements.ts +1220 -0
  97. package/src/frontend/elaborate/storage.ts +836 -0
  98. package/src/frontend/elaborate/time-constructors.ts +34 -0
  99. package/src/frontend/elaborate/values.ts +200 -0
  100. package/src/frontend/elaborate/writes.ts +415 -0
  101. package/src/frontend/expressions.ts +1382 -0
  102. package/src/frontend/generated-names.ts +95 -0
  103. package/src/frontend/intrinsics.ts +382 -0
  104. package/src/frontend/lowering-key.ts +23 -0
  105. package/src/frontend/module-graph.ts +156 -0
  106. package/src/frontend/positions.ts +359 -0
  107. package/src/frontend/promise-chains.ts +872 -0
  108. package/src/frontend/promises.ts +419 -0
  109. package/src/frontend/routines.ts +239 -0
  110. package/src/frontend/sdk.ts +187 -0
  111. package/src/frontend/services.ts +609 -0
  112. package/src/frontend/statements.ts +871 -0
  113. package/src/frontend/tasks.ts +526 -0
  114. package/src/frontend/telemetry.ts +174 -0
  115. package/src/frontend/types.ts +1073 -0
  116. package/src/frontend/typescript.ts +651 -0
  117. package/src/index.ts +9 -0
  118. package/src/ir/aggregates.ts +291 -0
  119. package/src/ir/allocation.ts +96 -0
  120. package/src/ir/conditions.ts +855 -0
  121. package/src/ir/core-model.ts +289 -0
  122. package/src/ir/declarations.ts +281 -0
  123. package/src/ir/diagnostics.ts +68 -0
  124. package/src/ir/domains.ts +151 -0
  125. package/src/ir/fold.ts +279 -0
  126. package/src/ir/identity.ts +19 -0
  127. package/src/ir/index.ts +137 -0
  128. package/src/ir/job-errors.ts +69 -0
  129. package/src/ir/layouts.ts +211 -0
  130. package/src/ir/link.ts +302 -0
  131. package/src/ir/model.ts +394 -0
  132. package/src/ir/normalization-error.ts +10 -0
  133. package/src/ir/normalize.ts +52 -0
  134. package/src/ir/numeric.ts +163 -0
  135. package/src/ir/operands.ts +160 -0
  136. package/src/ir/ranges.ts +420 -0
  137. package/src/ir/routine.ts +1116 -0
  138. package/src/ir/scalars.ts +453 -0
  139. package/src/ir/share.ts +790 -0
  140. package/src/ir/short-circuit.ts +140 -0
  141. package/src/ir/tables.ts +111 -0
  142. package/src/ir/temporaries.ts +138 -0
  143. package/src/ir/types.ts +151 -0
  144. package/src/project/artifacts.ts +424 -0
  145. package/src/project/cli.ts +211 -0
  146. package/src/project/debugger.ts +111 -0
  147. package/src/project/deployments.ts +387 -0
  148. package/src/project/flags.ts +14 -0
  149. package/src/project/git.ts +35 -0
  150. package/src/project/plant.ts +629 -0
  151. package/src/project/project-commands.ts +507 -0
  152. package/src/project/project.ts +559 -0
  153. package/src/project/release.ts +152 -0
  154. package/src/project/server-check.ts +54 -0
  155. package/src/project/server.ts +165 -0
  156. package/src/project/terminal.ts +45 -0
  157. package/src/runtime/async.ts +207 -0
  158. package/src/runtime/launch.ts +59 -0
  159. package/src/runtime/main.ts +59 -0
  160. package/src/runtime/missing-file.ts +3 -0
  161. package/src/runtime/process.ts +177 -0
  162. package/src/runtime/program.ts +109 -0
  163. package/src/runtime/retain.ts +108 -0
  164. package/src/runtime/runtime.ts +324 -0
  165. package/src/runtime/settings.ts +27 -0
  166. package/src/runtime/storage.ts +456 -0
  167. package/src/runtime/symbols.ts +97 -0
  168. package/src/runtime/telemetry.ts +154 -0
  169. package/src/runtime/transport.ts +168 -0
  170. package/stdlib/clock.ts +8 -0
  171. package/stdlib/collections.ts +534 -0
  172. package/stdlib/plc-time.ts +2 -0
  173. package/stdlib/retain.ts +4 -0
  174. package/stdlib/signals.ts +142 -0
  175. package/stdlib/telemetry.ts +89 -0
  176. package/types/async.d.ts +87 -0
  177. package/types/clock.d.ts +8 -0
  178. package/types/config.d.ts +2 -0
  179. package/types/data-types.d.ts +31 -0
  180. package/types/dialect.d.ts +49 -0
  181. package/types/globals.d.ts +10 -0
  182. package/types/index.d.ts +212 -0
  183. package/types/retain.d.ts +12 -0
  184. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,629 @@
1
+ import type { ParseArgsOptionsConfig } from "node:util";
2
+ import {
3
+ ask,
4
+ askCredentials,
5
+ type Credentials,
6
+ type Target,
7
+ type Variable,
8
+ } from "@tsplc/agent";
9
+ import { type AgentClient, createAgentClient } from "@tsplc/agent/client";
10
+ import { type LoginCommand, type LoginResult, resetLabel } from "@tsplc/build";
11
+ import type { Diagnostic } from "@tsplc/compiler/ir";
12
+ import {
13
+ agentTokenEnv,
14
+ agentUrlEnv,
15
+ type Environment,
16
+ type LoadedConfig,
17
+ type PlantVariables,
18
+ releaseEnvironment,
19
+ } from "@tsplc/config";
20
+ import { runtimePort } from "@tsplc/config/build";
21
+ import { LoginUnavailable, noLogin } from "@tsplc/debug";
22
+ import { isWithin } from "@tsplc/iec/st";
23
+ import { arrayIndex, symbolPathSegments } from "@tsplc/opcua/contract";
24
+ import { controllerRestartSchema } from "@tsplc/server/plant-agent";
25
+ import { z } from "zod";
26
+ import {
27
+ type Approval,
28
+ type Follow,
29
+ openDashboard,
30
+ printDeployments,
31
+ redeploy,
32
+ rollBack,
33
+ submitDeployment,
34
+ } from "./deployments";
35
+ import { type Flags, flag, type OutputFormat } from "./flags";
36
+ import { gitSource } from "./git";
37
+ import { prepareRelease } from "./release";
38
+ import {
39
+ choose,
40
+ confirm,
41
+ confirmOrCancel,
42
+ progress,
43
+ timedProgress,
44
+ } from "./terminal";
45
+
46
+ /** The flags of the plant commands. */
47
+ export const plantOptions = {
48
+ download: flag,
49
+ review: flag,
50
+ wait: flag,
51
+ "initialize-user": flag,
52
+ restore: flag,
53
+ select: flag,
54
+ simulate: flag,
55
+ yes: { type: "boolean", short: "y" },
56
+ "frozen-lockfile": flag,
57
+ } as const satisfies ParseArgsOptionsConfig;
58
+
59
+ export type PlantFlags = Flags<typeof plantOptions> & { format?: OutputFormat };
60
+
61
+ /** The plant agent named by `agentUrlEnv` and `agentTokenEnv` in `env`, where a target's agent sets the URL. */
62
+ export const connect = (env: Record<string, string | undefined>) => {
63
+ const environment = z
64
+ .object({
65
+ [agentUrlEnv]: z.url({
66
+ error: `Configure the target's agent, or set ${agentUrlEnv} to the plant agent, such as http://plant-pc:4850`,
67
+ }),
68
+ [agentTokenEnv]: z.string({
69
+ error: `Set ${agentTokenEnv} to the plant agent's token`,
70
+ }),
71
+ })
72
+ .parse(env);
73
+ return createAgentClient({
74
+ url: environment[agentUrlEnv],
75
+ token: environment[agentTokenEnv],
76
+ });
77
+ };
78
+
79
+ /**
80
+ * Reads through the agent's open login, as `tsplc read` does, without opening one: the
81
+ * debugger has no controller credentials.
82
+ */
83
+ export const readThroughAgent =
84
+ (agent: AgentClient) =>
85
+ async ([first, ...rest]: string[]) => {
86
+ if (!first) {
87
+ return {};
88
+ }
89
+ try {
90
+ const result = await agent.command({
91
+ command: "read",
92
+ expressions: [first, ...rest],
93
+ });
94
+ if (!("values" in result)) {
95
+ throw new Error("The agent answered a read without values");
96
+ }
97
+ return result.values;
98
+ } catch (error) {
99
+ const { login } = await agent.status();
100
+ if (!login) {
101
+ throw new LoginUnavailable(noLogin, { cause: error });
102
+ }
103
+ if ("error" in login) {
104
+ throw new Error(login.error, { cause: error });
105
+ }
106
+ throw error;
107
+ }
108
+ };
109
+
110
+ const selectTarget = async (agent: AgentClient): Promise<Target> => {
111
+ const interfaces = await agent.interfaces();
112
+ if (!interfaces.length) {
113
+ throw new Error("The plant PC has no IPv4 network.");
114
+ }
115
+ const network =
116
+ interfaces.length === 1 && interfaces[0]
117
+ ? interfaces[0]
118
+ : await choose(
119
+ "Which network is the controller on?",
120
+ interfaces,
121
+ (item) => `${item.name} ${item.address}/${item.prefixLength}`,
122
+ );
123
+ console.log(
124
+ `Scanning ${network.address}/${network.prefixLength} for CODESYS controllers…`,
125
+ );
126
+ const found = await agent.discover(network.name);
127
+ const manual = { address: "", port: runtimePort, hostname: null };
128
+ const choice = await choose(
129
+ "Which controller?",
130
+ [...found, manual],
131
+ (item) =>
132
+ item === manual
133
+ ? "Enter an address"
134
+ : `${item.address}${item.hostname ? ` (${item.hostname})` : ""}`,
135
+ );
136
+ const host =
137
+ choice === manual ? await ask("Controller address: ") : choice.address;
138
+ return agent.setTarget({ host, port: choice.port });
139
+ };
140
+
141
+ /**
142
+ * The controller user to send: TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD from
143
+ * `environment`, else null for the user stored on the agent, else what `prompt` asks for. Initializing
144
+ * the controller's user creates the one sent, so it never leaves it to the stored one.
145
+ */
146
+ export const controllerCredentials = async (
147
+ environment: Environment,
148
+ agent: { stored: boolean; initializeUser: boolean },
149
+ prompt: () => Promise<Credentials>,
150
+ ): Promise<Credentials | null> => {
151
+ const username = environment.TSPLC_CONTROLLER_USERNAME;
152
+ const password = environment.TSPLC_CONTROLLER_PASSWORD;
153
+ if (username && password) {
154
+ return { username, password };
155
+ }
156
+ if (username || password) {
157
+ throw new Error(
158
+ "Set both TSPLC_CONTROLLER_USERNAME and TSPLC_CONTROLLER_PASSWORD, or neither.",
159
+ );
160
+ }
161
+ return agent.stored && !agent.initializeUser ? null : prompt();
162
+ };
163
+
164
+ /** The plant PC's variables and secrets by name, as `variables A, B and secret C`, or null when it holds none. */
165
+ const plantSummary = ({ values, secrets }: PlantVariables) => {
166
+ const named = (noun: string, names: readonly string[]) =>
167
+ names.length
168
+ ? `${noun}${names.length === 1 ? "" : "s"} ${names.join(", ")}`
169
+ : null;
170
+ const parts = [
171
+ named("variable", Object.keys(values)),
172
+ named("secret", secrets),
173
+ ].filter((part) => part !== null);
174
+ return parts.length ? parts.join(" and ") : null;
175
+ };
176
+
177
+ const deploy = async (
178
+ agent: AgentClient,
179
+ loaded: LoadedConfig,
180
+ flags: PlantFlags,
181
+ follow: Follow,
182
+ ) => {
183
+ const status = await agent.status();
184
+ if (status.login) {
185
+ throw new Error("A login is open; log out before deploying: tsplc logout");
186
+ }
187
+ const target =
188
+ !status.target || flags.select ? await selectTarget(agent) : status.target;
189
+ const initializeUser = flags["initialize-user"] ?? false;
190
+ const plant = await agent.releaseVariables(
191
+ loaded.config.secrets?.service ?? null,
192
+ );
193
+ const built = releaseEnvironment(loaded.config, loaded, plant);
194
+ console.log(`Building the release for ${target.host}…`);
195
+ const held = plantSummary(plant);
196
+ if (held) {
197
+ console.log(` With the plant PC's ${held}`);
198
+ }
199
+ const building = timedProgress();
200
+ const { release, diagnostics } = await prepareRelease(loaded, flags, built);
201
+ if (!release) {
202
+ return { diagnostics };
203
+ }
204
+ building("Built");
205
+ if (flags.download) {
206
+ await confirmOrCancel(
207
+ "A full download stops the running application while it loads. Continue?",
208
+ flags,
209
+ );
210
+ }
211
+ const credentials = await controllerCredentials(
212
+ loaded.env,
213
+ { stored: status.credentialsStored, initializeUser },
214
+ askCredentials,
215
+ );
216
+ const settings = {
217
+ credentials,
218
+ download: flags.download ?? false,
219
+ initializeUser,
220
+ };
221
+ console.log(
222
+ release.manifest.server
223
+ ? "Uploading the server and the program…"
224
+ : "Uploading the program…",
225
+ );
226
+ return {
227
+ exitCode: await submitDeployment(
228
+ agent,
229
+ release,
230
+ settings,
231
+ {
232
+ mode: flags.review ? "review" : "apply",
233
+ git: await gitSource(loaded.root),
234
+ },
235
+ follow,
236
+ ),
237
+ };
238
+ };
239
+
240
+ /** Opens a login when none is working; it stays open across commands until `tsplc logout`. */
241
+ const ensureLogin = async (agent: AgentClient, environment: Environment) => {
242
+ const { login, credentialsStored } = await agent.status();
243
+ if (login && "state" in login) {
244
+ return;
245
+ }
246
+ if (login) {
247
+ console.log(`The open login failed (${login.error}); replacing it.`);
248
+ await agent.logout();
249
+ }
250
+ const credentials = await controllerCredentials(
251
+ environment,
252
+ { stored: credentialsStored, initializeUser: false },
253
+ askCredentials,
254
+ );
255
+ console.log(
256
+ "Logging in. CODESYS takes a few minutes to start; the login stays open until tsplc logout.",
257
+ );
258
+ await agent.login(credentials, progress);
259
+ };
260
+
261
+ /** The children of `prefix` in the variable tree, with array indexes folded into one range. */
262
+ export const variableChildren = (
263
+ variables: readonly Variable[],
264
+ prefix: string,
265
+ ) => {
266
+ const children = new Map<string, { type?: string; leaves: number }>();
267
+ for (const { path, type } of variables) {
268
+ if (prefix && !isWithin(prefix, path)) {
269
+ continue;
270
+ }
271
+ const rest = path.slice(prefix.length).replace(/^\./, "");
272
+ if (rest === "") {
273
+ return [{ name: path, type, leaves: 1 }];
274
+ }
275
+ const name = symbolPathSegments(rest)[0] ?? rest;
276
+ const child = children.get(name) ?? { leaves: 0 };
277
+ children.set(name, {
278
+ type: rest === name ? type : undefined,
279
+ leaves: child.leaves + 1,
280
+ });
281
+ }
282
+ const indexes = [...children.keys()]
283
+ .map(arrayIndex)
284
+ .filter((index) => index !== undefined);
285
+ const listed = [...children].filter(
286
+ ([name]) => arrayIndex(name) === undefined,
287
+ );
288
+ if (indexes.length) {
289
+ const first = children.get(`[${Math.min(...indexes)}]`);
290
+ listed.unshift([
291
+ `[${Math.min(...indexes)}..${Math.max(...indexes)}]`,
292
+ first ?? { leaves: 0 },
293
+ ]);
294
+ }
295
+ return listed.map(([name, child]) => ({ name, ...child }));
296
+ };
297
+
298
+ const printStatus = async (agent: AgentClient) => {
299
+ const status = await agent.status();
300
+ console.log(
301
+ `Controller ${status.target ? `${status.target.host}:${status.target.port}` : "not selected (tsplc target)"}`,
302
+ );
303
+ console.log(
304
+ `Release ${status.release ? `${status.release.id}, ${status.release.operation} at ${status.release.deployedAt}` : "none"}`,
305
+ );
306
+ console.log(
307
+ `Server ${status.server ? `${status.server.running ? "running" : "restarting"} (${status.server.executable})` : "none"}`,
308
+ );
309
+ const { login } = status;
310
+ if (!login) {
311
+ console.log("Login closed");
312
+ } else if ("error" in login) {
313
+ console.log(`Login failed: ${login.error} (tsplc logout)`);
314
+ } else {
315
+ console.log(
316
+ `Login open; application ${login.state}${login.forced.length ? `; forced: ${login.forced.join(", ")}` : ""}`,
317
+ );
318
+ }
319
+ };
320
+
321
+ /** Lists the deployed release's published variables under `path`, or its roots. */
322
+ const printVariables = async (agent: AgentClient, path: string | undefined) => {
323
+ const children = variableChildren(await agent.variables(), path ?? "");
324
+ if (!children.length) {
325
+ throw new Error(`No published variable ${path}.`);
326
+ }
327
+ for (const child of children) {
328
+ console.log(
329
+ `${child.name.padEnd(32)} ${child.type ?? `${child.leaves} variables`}`,
330
+ );
331
+ }
332
+ };
333
+
334
+ const printLogin = (result: LoginResult) => {
335
+ if ("values" in result) {
336
+ for (const [expression, value] of Object.entries(result.values)) {
337
+ console.log(`${expression} = ${value}`);
338
+ }
339
+ return;
340
+ }
341
+ console.log(`Application ${result.state}`);
342
+ if (result.forced.length) {
343
+ console.log(`Forced: ${result.forced.join(", ")}`);
344
+ }
345
+ };
346
+
347
+ interface PlantContext {
348
+ agent: AgentClient;
349
+ args: string[];
350
+ flags: PlantFlags;
351
+ project: {
352
+ load: () => Promise<LoadedConfig>;
353
+ /**
354
+ * Where a login-backed command reads the controller user: the loaded config's environment
355
+ * in a project, else this process's.
356
+ */
357
+ environment: Environment;
358
+ /** Someone at a terminal can answer prompts. */
359
+ interactive: boolean;
360
+ };
361
+ follow: Follow;
362
+ /** Throws the command's usage. */
363
+ usage: () => never;
364
+ /** Sends a login command through a login that is open, opening one first if none works. */
365
+ send: (command: LoginCommand) => Promise<void>;
366
+ }
367
+
368
+ interface PlantCommandEntry {
369
+ /** Its arguments and flags, after `tsplc <command>`. */
370
+ usage: string;
371
+ /** A deployment's compiler diagnostics when the program doesn't compile, the exit code of a command that queues a deployment. */
372
+ run: (
373
+ context: PlantContext,
374
+ ) => Promise<
375
+ { diagnostics: readonly Diagnostic[] } | { exitCode: number } | undefined
376
+ >;
377
+ }
378
+
379
+ /** Throws `usage` unless the command has no arguments. */
380
+ const none = ({ args, usage }: PlantContext) => {
381
+ if (args.length) {
382
+ usage();
383
+ }
384
+ };
385
+
386
+ const plantCommands = {
387
+ deploy: {
388
+ usage:
389
+ "[--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait] [-y]",
390
+ run: async (context) => {
391
+ none(context);
392
+ const { agent, project, flags, follow } = context;
393
+ return deploy(agent, await project.load(), flags, follow);
394
+ },
395
+ },
396
+ deployments: {
397
+ usage: "[--format json]",
398
+ run: async (context) => {
399
+ none(context);
400
+ await printDeployments(context.agent, context.flags);
401
+ return undefined;
402
+ },
403
+ },
404
+ rollback: {
405
+ usage: "[id] [--wait] [-y]",
406
+ run: async ({ agent, args, follow, usage }) => {
407
+ if (args.length > 1) {
408
+ usage();
409
+ }
410
+ return { exitCode: await rollBack(agent, args[0], follow) };
411
+ },
412
+ },
413
+ redeploy: {
414
+ usage: "<id> [--review] [--wait] [-y]",
415
+ run: async ({ agent, args: [id, ...extra], flags, follow, usage }) => {
416
+ if (!id || extra.length) {
417
+ return usage();
418
+ }
419
+ return {
420
+ exitCode: await redeploy(
421
+ agent,
422
+ id,
423
+ flags.review ? "review" : "apply",
424
+ follow,
425
+ ),
426
+ };
427
+ },
428
+ },
429
+ dashboard: {
430
+ usage: "",
431
+ run: async (context) => {
432
+ none(context);
433
+ openDashboard(context.agent, context.project.interactive);
434
+ return undefined;
435
+ },
436
+ },
437
+ target: {
438
+ usage: "",
439
+ run: async (context) => {
440
+ none(context);
441
+ const target = await selectTarget(context.agent);
442
+ console.log(`Deployments now go to ${target.host}:${target.port}.`);
443
+ return undefined;
444
+ },
445
+ },
446
+ status: {
447
+ usage: "",
448
+ run: async (context) => {
449
+ none(context);
450
+ await printStatus(context.agent);
451
+ return undefined;
452
+ },
453
+ },
454
+ login: {
455
+ usage: "",
456
+ run: async (context) => {
457
+ none(context);
458
+ await ensureLogin(context.agent, context.project.environment);
459
+ printLogin(await context.agent.command({ command: "state" }));
460
+ return undefined;
461
+ },
462
+ },
463
+ logout: {
464
+ usage: "",
465
+ run: async (context) => {
466
+ none(context);
467
+ const { agent, flags } = context;
468
+ const { login } = await agent.status();
469
+ const forced = login && "forced" in login ? login.forced : [];
470
+ if (forced.length) {
471
+ await confirmOrCancel(
472
+ `Forced: ${forced.join(", ")}. Forces stay on the controller after logout. Log out anyway?`,
473
+ flags,
474
+ );
475
+ }
476
+ const { failure } = await agent.logout();
477
+ console.log(
478
+ failure
479
+ ? `The login couldn't log out (${failure}); its container was removed.`
480
+ : "Logged out.",
481
+ );
482
+ return undefined;
483
+ },
484
+ },
485
+ vars: {
486
+ usage: "[path]",
487
+ run: async ({ agent, args, usage }) => {
488
+ if (args.length > 1) {
489
+ usage();
490
+ }
491
+ await printVariables(agent, args[0]);
492
+ return undefined;
493
+ },
494
+ },
495
+ read: {
496
+ usage: "<expression>...",
497
+ run: async ({ args: [first, ...rest], send, usage }) => {
498
+ if (!first) {
499
+ return usage();
500
+ }
501
+ await send({ command: "read", expressions: [first, ...rest] });
502
+ return undefined;
503
+ },
504
+ },
505
+ write: {
506
+ usage: "<expression> <value>",
507
+ run: (context) => setValue("write", context),
508
+ },
509
+ force: {
510
+ usage: "<expression> <value>",
511
+ run: (context) => setValue("force", context),
512
+ },
513
+ unforce: {
514
+ usage: "[expression]... [--restore]",
515
+ run: async ({ args, flags, send }) => {
516
+ await send({
517
+ command: "unforce",
518
+ expressions: args,
519
+ restore: flags.restore ?? false,
520
+ });
521
+ return undefined;
522
+ },
523
+ },
524
+ start: {
525
+ usage: "",
526
+ run: async (context) => {
527
+ none(context);
528
+ await context.send({ command: "start" });
529
+ return undefined;
530
+ },
531
+ },
532
+ stop: {
533
+ usage: "",
534
+ run: async (context) => {
535
+ none(context);
536
+ await confirmOrCancel(
537
+ "Stop the application on the controller?",
538
+ context.flags,
539
+ );
540
+ await context.send({ command: "stop" });
541
+ return undefined;
542
+ },
543
+ },
544
+ reset: {
545
+ usage: "warm|cold",
546
+ run: async ({ args, flags, send, usage }) => {
547
+ if (args.length !== 1) {
548
+ usage();
549
+ }
550
+ const kind = controllerRestartSchema.shape.reset.parse(args[0]);
551
+ await confirmOrCancel(
552
+ `Reset the application (${kind})? It stops and reinitializes its variables.`,
553
+ flags,
554
+ );
555
+ await send({ command: "reset", kind: resetLabel(kind) });
556
+ return undefined;
557
+ },
558
+ },
559
+ restart: {
560
+ usage: "[warm|cold] [-y]",
561
+ run: async ({ agent, args, flags, usage }) => {
562
+ if (args.length > 1) {
563
+ usage();
564
+ }
565
+ const reset = controllerRestartSchema.shape.reset.parse(
566
+ args[0] ?? "warm",
567
+ );
568
+ await confirmOrCancel(
569
+ `Reset the application (${reset}) and start it again? Its variables go back to their initial values${reset === "warm" ? ", but for retain ones" : ""}.`,
570
+ flags,
571
+ );
572
+ const { state } = await agent.restartController({ reset });
573
+ console.log(
574
+ `Reset ${reset}; the application is ${state === "run" ? "running" : state}.`,
575
+ );
576
+ return undefined;
577
+ },
578
+ },
579
+ } satisfies Record<string, PlantCommandEntry>;
580
+
581
+ /** `tsplc write` and `tsplc force`: one expression and its value. */
582
+ async function setValue(
583
+ command: "write" | "force",
584
+ { args: [expression, value, ...extra], send, usage }: PlantContext,
585
+ ) {
586
+ if (!expression || !value || extra.length) {
587
+ return usage();
588
+ }
589
+ await send({ command, values: { [expression]: value } });
590
+ return undefined;
591
+ }
592
+
593
+ export type PlantCommand = keyof typeof plantCommands;
594
+
595
+ export const isPlantCommand = (name: string): name is PlantCommand =>
596
+ Object.hasOwn(plantCommands, name);
597
+
598
+ /**
599
+ * Runs a command against the plant agent. Returns a deployment's compiler diagnostics when the
600
+ * program doesn't compile, and the exit code of a command that queues a deployment.
601
+ */
602
+ export const runPlantCommand = (
603
+ agent: AgentClient,
604
+ command: PlantCommand,
605
+ args: string[],
606
+ flags: PlantFlags,
607
+ project: PlantContext["project"],
608
+ ) => {
609
+ const entry: PlantCommandEntry = plantCommands[command];
610
+ const approval: Approval = {
611
+ yes: flags.yes ?? false,
612
+ interactive: project.interactive,
613
+ confirm,
614
+ };
615
+ return entry.run({
616
+ agent,
617
+ args,
618
+ flags,
619
+ project,
620
+ follow: { wait: flags.wait ?? false, approval },
621
+ usage: () => {
622
+ throw new Error(`Usage: tsplc ${command} ${entry.usage}`);
623
+ },
624
+ send: async (loginCommand) => {
625
+ await ensureLogin(agent, project.environment);
626
+ printLogin(await agent.command(loginCommand));
627
+ },
628
+ });
629
+ };