@tsplc/tmp-compiler 0.0.0-stage → 0.6.3

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 (185) 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 +6563 -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 +16198 -0
  12. package/dist/index.js.map +62 -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 +1090 -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-enums.ts +196 -0
  69. package/src/frontend/const-functions.ts +204 -0
  70. package/src/frontend/control-flow.ts +787 -0
  71. package/src/frontend/cooperative.ts +114 -0
  72. package/src/frontend/coroutines.ts +1344 -0
  73. package/src/frontend/dialect-names.ts +104 -0
  74. package/src/frontend/elaborate/array-searches.ts +224 -0
  75. package/src/frontend/elaborate/assignments.ts +343 -0
  76. package/src/frontend/elaborate/calls.ts +1342 -0
  77. package/src/frontend/elaborate/capture-protocol.ts +237 -0
  78. package/src/frontend/elaborate/capture.ts +388 -0
  79. package/src/frontend/elaborate/declarations.ts +124 -0
  80. package/src/frontend/elaborate/dialect.ts +473 -0
  81. package/src/frontend/elaborate/expressions.ts +2177 -0
  82. package/src/frontend/elaborate/filtered-arrays.ts +643 -0
  83. package/src/frontend/elaborate/frame.ts +145 -0
  84. package/src/frontend/elaborate/generics.ts +123 -0
  85. package/src/frontend/elaborate/graph.ts +141 -0
  86. package/src/frontend/elaborate/imports.ts +105 -0
  87. package/src/frontend/elaborate/index.ts +851 -0
  88. package/src/frontend/elaborate/initializers.ts +235 -0
  89. package/src/frontend/elaborate/iterators.ts +1541 -0
  90. package/src/frontend/elaborate/layouts.ts +1025 -0
  91. package/src/frontend/elaborate/model.ts +478 -0
  92. package/src/frontend/elaborate/names.ts +134 -0
  93. package/src/frontend/elaborate/reduce.ts +900 -0
  94. package/src/frontend/elaborate/references.ts +727 -0
  95. package/src/frontend/elaborate/retention.ts +284 -0
  96. package/src/frontend/elaborate/specialize.ts +1137 -0
  97. package/src/frontend/elaborate/statements.ts +1220 -0
  98. package/src/frontend/elaborate/storage.ts +836 -0
  99. package/src/frontend/elaborate/time-constructors.ts +34 -0
  100. package/src/frontend/elaborate/values.ts +200 -0
  101. package/src/frontend/elaborate/writes.ts +415 -0
  102. package/src/frontend/expressions.ts +1382 -0
  103. package/src/frontend/generated-names.ts +95 -0
  104. package/src/frontend/intrinsics.ts +382 -0
  105. package/src/frontend/lowering-key.ts +23 -0
  106. package/src/frontend/module-graph.ts +156 -0
  107. package/src/frontend/positions.ts +359 -0
  108. package/src/frontend/promise-chains.ts +872 -0
  109. package/src/frontend/promises.ts +419 -0
  110. package/src/frontend/routines.ts +239 -0
  111. package/src/frontend/sdk.ts +187 -0
  112. package/src/frontend/services.ts +612 -0
  113. package/src/frontend/statements.ts +871 -0
  114. package/src/frontend/tasks.ts +526 -0
  115. package/src/frontend/telemetry.ts +174 -0
  116. package/src/frontend/types.ts +1073 -0
  117. package/src/frontend/typescript.ts +659 -0
  118. package/src/index.ts +9 -0
  119. package/src/ir/aggregates.ts +291 -0
  120. package/src/ir/allocation.ts +96 -0
  121. package/src/ir/conditions.ts +855 -0
  122. package/src/ir/core-model.ts +289 -0
  123. package/src/ir/declarations.ts +281 -0
  124. package/src/ir/diagnostics.ts +68 -0
  125. package/src/ir/domains.ts +151 -0
  126. package/src/ir/fold.ts +279 -0
  127. package/src/ir/identity.ts +19 -0
  128. package/src/ir/index.ts +137 -0
  129. package/src/ir/job-errors.ts +69 -0
  130. package/src/ir/layouts.ts +211 -0
  131. package/src/ir/link.ts +302 -0
  132. package/src/ir/model.ts +394 -0
  133. package/src/ir/normalization-error.ts +10 -0
  134. package/src/ir/normalize.ts +52 -0
  135. package/src/ir/numeric.ts +163 -0
  136. package/src/ir/operands.ts +160 -0
  137. package/src/ir/ranges.ts +420 -0
  138. package/src/ir/routine.ts +1116 -0
  139. package/src/ir/scalars.ts +453 -0
  140. package/src/ir/share.ts +790 -0
  141. package/src/ir/short-circuit.ts +140 -0
  142. package/src/ir/tables.ts +111 -0
  143. package/src/ir/temporaries.ts +138 -0
  144. package/src/ir/types.ts +151 -0
  145. package/src/project/artifacts.ts +424 -0
  146. package/src/project/cli.ts +211 -0
  147. package/src/project/debugger.ts +111 -0
  148. package/src/project/deployments.ts +387 -0
  149. package/src/project/flags.ts +14 -0
  150. package/src/project/git.ts +35 -0
  151. package/src/project/plant.ts +629 -0
  152. package/src/project/project-commands.ts +507 -0
  153. package/src/project/project.ts +559 -0
  154. package/src/project/release.ts +152 -0
  155. package/src/project/server-check.ts +54 -0
  156. package/src/project/server.ts +165 -0
  157. package/src/project/terminal.ts +45 -0
  158. package/src/runtime/async.ts +207 -0
  159. package/src/runtime/launch.ts +59 -0
  160. package/src/runtime/main.ts +59 -0
  161. package/src/runtime/missing-file.ts +3 -0
  162. package/src/runtime/process.ts +177 -0
  163. package/src/runtime/program.ts +109 -0
  164. package/src/runtime/retain.ts +108 -0
  165. package/src/runtime/runtime.ts +324 -0
  166. package/src/runtime/settings.ts +27 -0
  167. package/src/runtime/storage.ts +456 -0
  168. package/src/runtime/symbols.ts +97 -0
  169. package/src/runtime/telemetry.ts +154 -0
  170. package/src/runtime/transport.ts +168 -0
  171. package/stdlib/clock.ts +8 -0
  172. package/stdlib/collections.ts +534 -0
  173. package/stdlib/plc-time.ts +2 -0
  174. package/stdlib/retain.ts +4 -0
  175. package/stdlib/signals.ts +142 -0
  176. package/stdlib/telemetry.ts +89 -0
  177. package/types/async.d.ts +87 -0
  178. package/types/clock.d.ts +8 -0
  179. package/types/config.d.ts +2 -0
  180. package/types/data-types.d.ts +31 -0
  181. package/types/dialect.d.ts +49 -0
  182. package/types/globals.d.ts +10 -0
  183. package/types/index.d.ts +212 -0
  184. package/types/retain.d.ts +12 -0
  185. package/types/telemetry.d.ts +47 -0
@@ -0,0 +1,424 @@
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ lstat,
4
+ mkdir,
5
+ readdir,
6
+ readFile,
7
+ rename,
8
+ rm,
9
+ writeFile,
10
+ } from "node:fs/promises";
11
+ import { dirname, join, relative } from "node:path";
12
+ import { cyclicTasksSchema, sha256Digest } from "@tsplc/config/build";
13
+ import {
14
+ emittedStDirectory,
15
+ generatedDirectory,
16
+ } from "@tsplc/config/project-files";
17
+ import { z } from "zod";
18
+ import { isMissingFile } from "../runtime/missing-file";
19
+
20
+ const digest = (value: string | Uint8Array): string =>
21
+ createHash("sha256").update(value).digest("hex");
22
+
23
+ /** The files that record who owns the artifacts and the engineering cache, beside what they own. */
24
+ const artifactFiles = {
25
+ /** Every generated file with its digest, in the artifacts directory. */
26
+ manifest: "manifest.json",
27
+ /** The last successful build, beside the manifest. */
28
+ receipt: "receipt.json",
29
+ /** The configuration an engineering cache belongs to, in the cache. */
30
+ marker: "ownership.json",
31
+ } as const;
32
+
33
+ /**
34
+ * How an ownership record names its configuration: relative to the directory the record sits in,
35
+ * so the whole project keeps its outputs when it moves or is copied.
36
+ */
37
+ const configReference = (directory: string, configFile: string) =>
38
+ relative(directory, configFile);
39
+
40
+ /** Whether a record in `directory` names `configFile`; older records hold its absolute path. */
41
+ const namesConfig = (recorded: string, directory: string, configFile: string) =>
42
+ recorded === configReference(directory, configFile) ||
43
+ recorded === configFile;
44
+
45
+ const generatedFileSchema = z.object({
46
+ path: z
47
+ .string()
48
+ .regex(/^[A-Za-z0-9_ .-]+(?:\/[A-Za-z0-9_ .-]+)*$/)
49
+ .refine(
50
+ (path) =>
51
+ !path.split("/").some((part) => part === "." || part === "..") &&
52
+ path !== artifactFiles.manifest &&
53
+ path !== artifactFiles.receipt,
54
+ ),
55
+ sha256: sha256Digest,
56
+ });
57
+
58
+ /** The manifest's envelope; its entries are checked one by one to name the failure. */
59
+ const manifestSchema = z.object({
60
+ kind: z.literal("tsplc-artifacts"),
61
+ version: z.literal(1),
62
+ configFile: z.string(),
63
+ files: z.array(z.unknown()),
64
+ });
65
+
66
+ type Manifest = Omit<z.infer<typeof manifestSchema>, "files"> & {
67
+ files: z.infer<typeof generatedFileSchema>[];
68
+ };
69
+
70
+ const receiptSchema = z.object({
71
+ kind: z.literal("tsplc-build"),
72
+ version: z.literal(1),
73
+ generatedAt: z.iso.datetime(),
74
+ configFile: z.string(),
75
+ status: z.enum(["emitted", "vendor-compiled"]),
76
+ /** The application and tasks CODESYS compiled. */
77
+ vendor: z
78
+ .object({ application: z.string(), tasks: cyclicTasksSchema.optional() })
79
+ .optional(),
80
+ });
81
+
82
+ const engineeringMarkerSchema = z.object({
83
+ kind: z.literal("tsplc-engineering"),
84
+ version: z.literal(1),
85
+ configFile: z.string(),
86
+ });
87
+
88
+ function manifest(
89
+ value: unknown,
90
+ output: string,
91
+ configFile: string,
92
+ ): Manifest {
93
+ const parsed = manifestSchema.safeParse(value);
94
+ if (
95
+ !parsed.success ||
96
+ !namesConfig(parsed.data.configFile, output, configFile)
97
+ ) {
98
+ throw new Error(
99
+ "Output directory has no matching tsPLC ownership manifest.",
100
+ );
101
+ }
102
+
103
+ const files = parsed.data.files.map((item) => {
104
+ const file = generatedFileSchema.safeParse(item);
105
+ if (!file.success) {
106
+ throw new Error("Invalid generated file ownership entry.");
107
+ }
108
+ return file.data;
109
+ });
110
+ if (new Set(files.map((item) => item.path)).size !== files.length) {
111
+ throw new Error("Duplicate generated file ownership entry.");
112
+ }
113
+ return { ...parsed.data, files };
114
+ }
115
+
116
+ async function directory(path: string): Promise<boolean> {
117
+ try {
118
+ const entry = await lstat(path);
119
+ if (!entry.isDirectory() || entry.isSymbolicLink()) {
120
+ throw new Error(`Generated directory must be a real directory: ${path}`);
121
+ }
122
+ return true;
123
+ } catch (cause) {
124
+ if (isMissingFile(cause)) {
125
+ return false;
126
+ }
127
+ throw cause;
128
+ }
129
+ }
130
+
131
+ async function filesIn(path: string, prefix = ""): Promise<string[]> {
132
+ const result: string[] = [];
133
+ for (const entry of await readdir(path, { withFileTypes: true })) {
134
+ const name = prefix + entry.name;
135
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
136
+ result.push(...(await filesIn(join(path, entry.name), `${name}/`)));
137
+ } else {
138
+ result.push(name);
139
+ }
140
+ }
141
+ return result;
142
+ }
143
+
144
+ export async function engineeringDirectory(
145
+ path: string,
146
+ configFile: string,
147
+ ): Promise<void> {
148
+ const marker = join(path, artifactFiles.marker);
149
+ const exists = await directory(path);
150
+ if (!exists || !(await readdir(path)).length) {
151
+ await mkdir(path, { recursive: true });
152
+ await writeFile(
153
+ marker,
154
+ `${JSON.stringify(
155
+ {
156
+ kind: "tsplc-engineering",
157
+ version: 1,
158
+ configFile: configReference(path, configFile),
159
+ } satisfies z.infer<typeof engineeringMarkerSchema>,
160
+ null,
161
+ 2,
162
+ )}\n`,
163
+ { flag: "wx" },
164
+ );
165
+ } else if (!(await ownedMarker(path, configFile))) {
166
+ throw new Error(
167
+ `Engineering cache has no matching tsPLC ownership marker: ${path}`,
168
+ );
169
+ }
170
+
171
+ const inspect = async (directory: string): Promise<void> => {
172
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
173
+ const child = join(directory, entry.name);
174
+ if (entry.isSymbolicLink()) {
175
+ throw new Error(
176
+ `Engineering cache must not contain symlinks: ${child}`,
177
+ );
178
+ }
179
+ if (entry.isDirectory()) {
180
+ await inspect(child);
181
+ }
182
+ }
183
+ };
184
+ await inspect(path);
185
+ }
186
+
187
+ /** Whether the engineering cache at `path` has a marker that names `configFile`; false when there is none. */
188
+ const ownedMarker = async (path: string, configFile: string) => {
189
+ const marker = join(path, artifactFiles.marker);
190
+ const entry = await lstat(marker).catch((cause: unknown) => {
191
+ if (isMissingFile(cause)) {
192
+ return undefined;
193
+ }
194
+ throw cause;
195
+ });
196
+ if (!entry) {
197
+ return false;
198
+ }
199
+ if (!entry.isFile() || entry.isSymbolicLink()) {
200
+ throw new Error("Engineering ownership marker must be a real file.");
201
+ }
202
+ const value = engineeringMarkerSchema.safeParse(
203
+ JSON.parse(await readFile(marker, "utf8")),
204
+ );
205
+ return value.success && namesConfig(value.data.configFile, path, configFile);
206
+ };
207
+
208
+ /**
209
+ * The artifacts directory of `configFile` and the manifest of what it owns there, once its
210
+ * manifest and receipt name this configuration. `owned` goes on to check the owned files.
211
+ */
212
+ export async function claimed(configFile: string): Promise<{
213
+ root: string;
214
+ output: string;
215
+ ownership?: Manifest;
216
+ }> {
217
+ const root = join(dirname(configFile), generatedDirectory);
218
+ const output = join(dirname(configFile), dirname(emittedStDirectory));
219
+ if (!(await directory(root)) || !(await directory(output))) {
220
+ return { root, output };
221
+ }
222
+
223
+ const manifestPath = join(output, artifactFiles.manifest);
224
+ const manifestEntry = await lstat(manifestPath).catch((cause: unknown) => {
225
+ if (isMissingFile(cause)) {
226
+ return undefined;
227
+ }
228
+ throw cause;
229
+ });
230
+ // Without a manifest nothing here is owned; `owned` lists whatever is there as unrelated.
231
+ if (!manifestEntry) {
232
+ return { root, output };
233
+ }
234
+ if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
235
+ throw new Error("Ownership manifest must be a real file.");
236
+ }
237
+ const ownership = manifest(
238
+ JSON.parse(await readFile(manifestPath, "utf8")),
239
+ output,
240
+ configFile,
241
+ );
242
+ const receipt = join(output, artifactFiles.receipt);
243
+ try {
244
+ const entry = await lstat(receipt);
245
+ if (!entry.isFile() || entry.isSymbolicLink()) {
246
+ throw new Error("Build receipt must be a real file.");
247
+ }
248
+ const value = receiptSchema.safeParse(
249
+ JSON.parse(await readFile(receipt, "utf8")),
250
+ );
251
+ if (
252
+ !value.success ||
253
+ !namesConfig(value.data.configFile, output, configFile)
254
+ ) {
255
+ throw new Error("Build receipt is not owned by this configuration.");
256
+ }
257
+ } catch (cause) {
258
+ if (!isMissingFile(cause)) {
259
+ throw cause;
260
+ }
261
+ }
262
+ return { root, output, ownership };
263
+ }
264
+
265
+ /** The artifacts `claimed` found, with every owned file checked unchanged, and the files they don't own. */
266
+ export async function owned(
267
+ claim: Awaited<ReturnType<typeof claimed>>,
268
+ ): Promise<{
269
+ root: string;
270
+ output: string;
271
+ ownership?: Manifest;
272
+ unknown: string[];
273
+ }> {
274
+ const { output, ownership } = claim;
275
+ if (!ownership) {
276
+ return {
277
+ ...claim,
278
+ unknown: (await directory(output)) ? await filesIn(output) : [],
279
+ };
280
+ }
281
+ const names = new Set([
282
+ ...ownership.files.map((file) => file.path),
283
+ artifactFiles.manifest,
284
+ artifactFiles.receipt,
285
+ ]);
286
+ // Thousands of files share a few hundred directories; each is checked once.
287
+ const checked = new Set<string>();
288
+ for (const file of ownership.files) {
289
+ let parent = output;
290
+ for (const part of file.path.split("/").slice(0, -1)) {
291
+ parent = join(parent, part);
292
+ if (checked.has(parent)) {
293
+ continue;
294
+ }
295
+ if (!(await directory(parent))) {
296
+ throw new Error(`Missing generated directory: ${parent}`);
297
+ }
298
+ checked.add(parent);
299
+ }
300
+ const path = join(output, file.path);
301
+ const entry = await lstat(path);
302
+ if (
303
+ !entry.isFile() ||
304
+ entry.isSymbolicLink() ||
305
+ digest(await readFile(path)) !== file.sha256
306
+ ) {
307
+ throw new Error(
308
+ `Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`,
309
+ );
310
+ }
311
+ }
312
+ return {
313
+ ...claim,
314
+ unknown: (await filesIn(output)).filter((name) => !names.has(name)),
315
+ };
316
+ }
317
+
318
+ /** Removes the last successful build's receipt from the artifacts `claimed` found, if they have one. */
319
+ export const withdrawReceipt = async ({
320
+ output,
321
+ }: Awaited<ReturnType<typeof claimed>>) => {
322
+ await rm(join(output, artifactFiles.receipt), { force: true });
323
+ };
324
+
325
+ /** What a build's receipt records about it, with the absolute path of its config file. */
326
+ type Receipt = Omit<
327
+ z.input<typeof receiptSchema>,
328
+ "kind" | "version" | "generatedAt"
329
+ >;
330
+
331
+ // Compile in a separate staging tree. Recheck ownership immediately before the
332
+ // swap, because the vendor build may have given the user time to edit old files.
333
+ export async function publishArtifacts(
334
+ staging: string,
335
+ previous: Awaited<ReturnType<typeof owned>>,
336
+ receipt: Receipt,
337
+ ): Promise<void> {
338
+ const configFile = configReference(previous.output, receipt.configFile);
339
+ const generated = (await filesIn(staging)).sort();
340
+ const ownership: Manifest = {
341
+ kind: "tsplc-artifacts",
342
+ version: 1,
343
+ configFile,
344
+ files: [],
345
+ };
346
+ for (const path of generated) {
347
+ ownership.files.push({
348
+ path,
349
+ sha256: digest(await readFile(join(staging, path))),
350
+ });
351
+ }
352
+ await writeFile(
353
+ join(staging, artifactFiles.manifest),
354
+ `${JSON.stringify(ownership, null, 2)}\n`,
355
+ );
356
+ await writeFile(
357
+ join(staging, artifactFiles.receipt),
358
+ `${JSON.stringify(
359
+ {
360
+ kind: "tsplc-build",
361
+ version: 1,
362
+ generatedAt: new Date().toISOString(),
363
+ ...receipt,
364
+ configFile,
365
+ } satisfies z.input<typeof receiptSchema>,
366
+ null,
367
+ 2,
368
+ )}\n`,
369
+ );
370
+
371
+ const current = await owned(await claimed(receipt.configFile));
372
+ if (
373
+ JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)
374
+ ) {
375
+ throw new Error(
376
+ "Output ownership changed during the build; preserve it before rebuilding.",
377
+ );
378
+ }
379
+ if (current.unknown.length) {
380
+ throw new Error(
381
+ `Output contains unrelated files: ${current.unknown.join(", ")}`,
382
+ );
383
+ }
384
+
385
+ const backup = `${staging}-previous`;
386
+ if (previous.ownership) {
387
+ await rename(previous.output, backup);
388
+ }
389
+ try {
390
+ await rename(staging, previous.output);
391
+ } catch (cause) {
392
+ if (previous.ownership) {
393
+ await rename(backup, previous.output);
394
+ }
395
+ throw cause;
396
+ }
397
+ if (previous.ownership) {
398
+ await rm(backup, { recursive: true });
399
+ }
400
+ }
401
+
402
+ export async function cleanArtifacts(configFile: string): Promise<void> {
403
+ const generated = await owned(await claimed(configFile));
404
+ if (!generated.ownership) {
405
+ return;
406
+ }
407
+ for (const entry of generated.ownership.files) {
408
+ await rm(join(generated.output, entry.path));
409
+ }
410
+ await rm(join(generated.output, artifactFiles.receipt), { force: true });
411
+ await rm(join(generated.output, artifactFiles.manifest));
412
+
413
+ const removeEmpty = async (path: string): Promise<void> => {
414
+ for (const entry of await readdir(path, { withFileTypes: true })) {
415
+ if (entry.isDirectory() && !entry.isSymbolicLink()) {
416
+ await removeEmpty(join(path, entry.name));
417
+ }
418
+ }
419
+ if (!(await readdir(path)).length) {
420
+ await rm(path, { recursive: true });
421
+ }
422
+ };
423
+ await removeEmpty(generated.output);
424
+ }
@@ -0,0 +1,211 @@
1
+ #!/usr/bin/env bun
2
+ import { existsSync } from "node:fs";
3
+ import { type ParseArgsOptionsConfig, parseArgs } from "node:util";
4
+ import { formatDiagnostic, hasErrors } from "@tsplc/compiler/ir";
5
+ import { agentTokenEnv, agentUrlEnv, loadTsplcConfig } from "@tsplc/config";
6
+ import { opcuaPort } from "@tsplc/config/build";
7
+ import {
8
+ configFileName,
9
+ emittedStDirectory,
10
+ } from "@tsplc/config/project-files";
11
+ import { debugManifestFile } from "@tsplc/debug/manifest";
12
+ import { z } from "zod";
13
+ import { debugOptions, debugUsage, serveProjectDebugger } from "./debugger";
14
+ import { type Flags, type OutputFormat, outputFormatSchema } from "./flags";
15
+ import {
16
+ connect,
17
+ isPlantCommand,
18
+ type PlantCommand,
19
+ plantOptions,
20
+ runPlantCommand,
21
+ } from "./plant";
22
+ import {
23
+ type CommandResult,
24
+ checkProjectFlags,
25
+ DiagnosticFailure,
26
+ isProjectCommand,
27
+ projectOptions,
28
+ runProjectCommand,
29
+ } from "./project-commands";
30
+
31
+ const usage = `tsplc install|typegen|check|build|run|download|online-change|inspect|clean|configure [--config ${configFileName}] [--target name] [--plc|--server] [--simulate] [--runtime] [--emit-only] [--format json] [--read symbol]
32
+ [--frozen-lockfile] [--check] [--initialize-user]
33
+
34
+ Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:${opcuaPort}:
35
+ tsplc run --simulate --bun [--foreground] [--target name]
36
+
37
+ Plant agent (the target's agent, else ${agentUrlEnv}; ${agentTokenEnv}):
38
+ tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]
39
+ tsplc deployments [--format json] | dashboard
40
+ tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]
41
+ (--wait follows the deployment and exits 2 while it waits for approval; -y approves)
42
+ tsplc target | status | login | logout
43
+ tsplc vars [path] | read <expression>... | write <expression> <value>
44
+ tsplc force <expression> <value> | unforce [expression]... [--restore]
45
+ tsplc start | stop | reset warm|cold (-y skips confirmations)
46
+ tsplc restart [warm|cold] resets and starts the application, with or without a login
47
+
48
+ Debugger, on http://127.0.0.1, for the built ${emittedStDirectory}/${debugManifestFile}; it reads through
49
+ the plant agent's login (${agentUrlEnv}, ${agentTokenEnv}), or --opcua at config monitor:
50
+ tsplc debug ${debugUsage}`;
51
+
52
+ /** Every command's flags, and those of the CLI itself. */
53
+ const options = {
54
+ config: { type: "string" },
55
+ target: { type: "string" },
56
+ help: { type: "boolean", short: "h" },
57
+ format: { type: "string" },
58
+ ...projectOptions,
59
+ ...plantOptions,
60
+ ...debugOptions,
61
+ } as const satisfies ParseArgsOptionsConfig;
62
+
63
+ type Values = Omit<Flags<typeof options>, "format"> & { format?: OutputFormat };
64
+
65
+ /**
66
+ * The `--format` the command line names, read before it is fully parsed so a command that fails
67
+ * to parse still answers in that format. A positional `json` is an argument, not a format.
68
+ */
69
+ const requestedFormat = (argv: readonly string[]) => {
70
+ const index = argv.findIndex(
71
+ (argument) => argument === "--format" || argument.startsWith("--format="),
72
+ );
73
+ const flag = argv[index];
74
+ if (index < 0 || flag === undefined) {
75
+ return undefined;
76
+ }
77
+ return flag === "--format" ? argv[index + 1] : flag.slice("--format=".length);
78
+ };
79
+
80
+ const outputFormat = (format: string | undefined) => {
81
+ const parsed = outputFormatSchema.optional().safeParse(format);
82
+ if (!parsed.success) {
83
+ throw new Error("--format must be json or text.");
84
+ }
85
+ return parsed.data;
86
+ };
87
+
88
+ /** `tsplc debug`: serves the debugger until interrupted. */
89
+ const debug = async (args: string[], values: Values, file: string) => {
90
+ if (args.length) {
91
+ throw new Error(`Usage: tsplc debug ${debugUsage}`);
92
+ }
93
+ await serveProjectDebugger(
94
+ await loadTsplcConfig(file, {
95
+ env: process.env,
96
+ target: values.target,
97
+ forAgent: false,
98
+ }),
99
+ values,
100
+ );
101
+ return 0;
102
+ };
103
+
104
+ /** A plant command, against the target's agent in a project and the environment's elsewhere. */
105
+ const plant = async (
106
+ command: PlantCommand,
107
+ args: string[],
108
+ values: Values,
109
+ file: string,
110
+ ) => {
111
+ const load = () =>
112
+ loadTsplcConfig(file, {
113
+ env: process.env,
114
+ target: values.target,
115
+ forAgent: true,
116
+ });
117
+ const loaded = existsSync(file) ? await load() : undefined;
118
+ const env = loaded?.env ?? process.env;
119
+ const outcome = await runPlantCommand(connect(env), command, args, values, {
120
+ load: loaded ? async () => loaded : load,
121
+ environment: env,
122
+ interactive: process.stdin.isTTY === true,
123
+ });
124
+ if (!outcome) {
125
+ return 0;
126
+ }
127
+ return "exitCode" in outcome
128
+ ? outcome.exitCode
129
+ : report(outcome, values.format);
130
+ };
131
+
132
+ async function main() {
133
+ const { values: parsed, positionals } = parseArgs({
134
+ allowPositionals: true,
135
+ options,
136
+ });
137
+ const values = { ...parsed, format: outputFormat(parsed.format) };
138
+ const [name, ...args] = positionals;
139
+ const file = values.config ?? configFileName;
140
+ if (!name || values.help) {
141
+ console.log(usage);
142
+ return 0;
143
+ }
144
+ if (name === "debug") {
145
+ return debug(args, values, file);
146
+ }
147
+ if (isPlantCommand(name)) {
148
+ return plant(name, args, values, file);
149
+ }
150
+ if (args.length) {
151
+ throw new Error("Specify one command.");
152
+ }
153
+ if (!isProjectCommand(name)) {
154
+ throw new Error(`Unknown command ${name}.`);
155
+ }
156
+ checkProjectFlags(name, values);
157
+ return report(
158
+ await runProjectCommand(name, file, values, process.env),
159
+ values.format,
160
+ );
161
+ }
162
+
163
+ function report(result: CommandResult, format: OutputFormat | undefined) {
164
+ const diagnostics = result.diagnostics ?? [];
165
+ const ok = !hasErrors(diagnostics);
166
+ if (format === "json") {
167
+ console.log(JSON.stringify({ ok, ...result }));
168
+ } else {
169
+ for (const diagnostic of diagnostics) {
170
+ console.error(formatDiagnostic(diagnostic));
171
+ }
172
+ for (const [expression, value] of Object.entries(result.values ?? {})) {
173
+ console.log(`${expression} = ${value}`);
174
+ }
175
+ if (ok) {
176
+ console.log("tsPLC completed.");
177
+ }
178
+ }
179
+ return ok ? 0 : 1;
180
+ }
181
+
182
+ function causeMessage(cause: unknown) {
183
+ if (cause instanceof z.ZodError) {
184
+ return z.prettifyError(cause);
185
+ }
186
+ return cause instanceof Error ? cause.message : String(cause);
187
+ }
188
+
189
+ try {
190
+ process.exitCode = await main();
191
+ } catch (cause) {
192
+ const json = requestedFormat(process.argv.slice(2)) === "json";
193
+ if (cause instanceof DiagnosticFailure) {
194
+ process.exitCode = report(cause.result, json ? "json" : undefined);
195
+ } else {
196
+ const message = causeMessage(cause);
197
+ if (json) {
198
+ console.log(
199
+ JSON.stringify({
200
+ ok: false,
201
+ diagnostics: [
202
+ { origin: "config", code: "PLC5003", severity: "error", message },
203
+ ],
204
+ }),
205
+ );
206
+ } else {
207
+ console.error(message);
208
+ }
209
+ process.exitCode = 1;
210
+ }
211
+ }