@tsplc/compiler 0.5.13 → 0.5.15

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 (263) hide show
  1. package/README.md +33 -8
  2. package/dist/cli.js +794 -621
  3. package/dist/cli.js.map +19 -16
  4. package/dist/clock.js +5 -2
  5. package/dist/clock.js.map +5 -4
  6. package/dist/codesys.js +4162 -4157
  7. package/dist/codesys.js.map +43 -29
  8. package/dist/index.js +7852 -6549
  9. package/dist/index.js.map +53 -50
  10. package/dist/ir.js +2482 -2277
  11. package/dist/ir.js.map +28 -25
  12. package/dist/retain.js +3 -1
  13. package/dist/retain.js.map +3 -3
  14. package/dist/signals.js +115 -0
  15. package/dist/signals.js.map +10 -0
  16. package/dist/telemetry.js +25 -20
  17. package/dist/telemetry.js.map +6 -6
  18. package/package.json +19 -39
  19. package/src/codesys/config.ts +3 -3
  20. package/src/codesys/debug.ts +92 -108
  21. package/src/codesys/emit.ts +100 -88
  22. package/src/codesys/endpoints.ts +111 -0
  23. package/src/codesys/engineering.ts +30 -54
  24. package/src/codesys/explain/expressions.ts +445 -0
  25. package/src/codesys/explain/flags.ts +134 -0
  26. package/src/codesys/explain/parameters.ts +53 -0
  27. package/src/codesys/explain/rows.ts +182 -0
  28. package/src/codesys/explain/tables.ts +79 -0
  29. package/src/codesys/explain/tasks.ts +68 -0
  30. package/src/codesys/explain/writes.ts +497 -0
  31. package/src/codesys/explain.ts +85 -1401
  32. package/src/codesys/expressions.ts +41 -33
  33. package/src/codesys/global-lists.ts +114 -94
  34. package/src/codesys/global-names.ts +12 -14
  35. package/src/codesys/http.ts +428 -388
  36. package/src/codesys/instrumentation.ts +142 -148
  37. package/src/codesys/io-paths.ts +31 -23
  38. package/src/codesys/loops.ts +101 -0
  39. package/src/codesys/manifest.ts +269 -269
  40. package/src/codesys/names.ts +10 -33
  41. package/src/codesys/numeric.ts +89 -42
  42. package/src/codesys/plan.ts +202 -190
  43. package/src/codesys/programs.ts +23 -16
  44. package/src/codesys/publication.ts +13 -86
  45. package/src/codesys/required.ts +8 -0
  46. package/src/codesys/routines.ts +103 -489
  47. package/src/codesys/scheduling.ts +96 -0
  48. package/src/codesys/service-channels.ts +23 -0
  49. package/src/codesys/sources.ts +34 -28
  50. package/src/codesys/st-files.ts +112 -105
  51. package/src/codesys/statements.ts +409 -0
  52. package/src/codesys/storage.ts +41 -23
  53. package/src/codesys/symbols.ts +130 -119
  54. package/src/codesys/task-access.ts +65 -221
  55. package/src/codesys/telemetry-settings.ts +19 -0
  56. package/src/codesys/telemetry.ts +185 -148
  57. package/src/codesys/types.ts +69 -109
  58. package/src/codesys/vendor.ts +13 -50
  59. package/src/frontend/analyzer.ts +66 -111
  60. package/src/frontend/async.ts +316 -128
  61. package/src/frontend/blocks.ts +178 -154
  62. package/src/frontend/configuration.ts +49 -153
  63. package/src/frontend/const-functions.ts +50 -40
  64. package/src/frontend/control-flow.ts +164 -129
  65. package/src/frontend/cooperative.ts +17 -9
  66. package/src/frontend/coroutines.ts +539 -441
  67. package/src/frontend/dialect-names.ts +104 -0
  68. package/src/frontend/elaborate/array-searches.ts +77 -69
  69. package/src/frontend/elaborate/assignments.ts +68 -77
  70. package/src/frontend/elaborate/calls.ts +878 -512
  71. package/src/frontend/elaborate/capture-protocol.ts +118 -21
  72. package/src/frontend/elaborate/capture.ts +196 -109
  73. package/src/frontend/elaborate/declarations.ts +124 -0
  74. package/src/frontend/elaborate/dialect.ts +119 -46
  75. package/src/frontend/elaborate/expressions.ts +763 -442
  76. package/src/frontend/elaborate/filtered-arrays.ts +127 -91
  77. package/src/frontend/elaborate/frame.ts +50 -2
  78. package/src/frontend/elaborate/generics.ts +20 -34
  79. package/src/frontend/elaborate/graph.ts +13 -87
  80. package/src/frontend/elaborate/imports.ts +0 -5
  81. package/src/frontend/elaborate/index.ts +416 -169
  82. package/src/frontend/elaborate/initializers.ts +64 -42
  83. package/src/frontend/elaborate/iterators.ts +228 -364
  84. package/src/frontend/elaborate/layouts.ts +477 -116
  85. package/src/frontend/elaborate/model.ts +113 -55
  86. package/src/frontend/elaborate/references.ts +116 -138
  87. package/src/frontend/elaborate/retention.ts +137 -59
  88. package/src/frontend/elaborate/specialize.ts +617 -308
  89. package/src/frontend/elaborate/statements.ts +436 -247
  90. package/src/frontend/elaborate/storage.ts +280 -213
  91. package/src/frontend/elaborate/time-constructors.ts +34 -0
  92. package/src/frontend/elaborate/values.ts +77 -7
  93. package/src/frontend/elaborate/writes.ts +98 -84
  94. package/src/frontend/expressions.ts +149 -151
  95. package/src/frontend/generated-names.ts +3 -3
  96. package/src/frontend/intrinsics.ts +31 -17
  97. package/src/frontend/lowering-key.ts +23 -0
  98. package/src/frontend/module-graph.ts +105 -43
  99. package/src/frontend/positions.ts +43 -35
  100. package/src/frontend/promise-chains.ts +226 -266
  101. package/src/frontend/promises.ts +88 -67
  102. package/src/frontend/routines.ts +122 -65
  103. package/src/frontend/sdk.ts +104 -5
  104. package/src/frontend/services.ts +149 -102
  105. package/src/frontend/statements.ts +60 -64
  106. package/src/frontend/tasks.ts +151 -96
  107. package/src/frontend/telemetry.ts +1 -1
  108. package/src/frontend/types.ts +366 -181
  109. package/src/frontend/typescript.ts +239 -112
  110. package/src/index.ts +2 -1
  111. package/src/ir/aggregates.ts +90 -75
  112. package/src/ir/allocation.ts +29 -18
  113. package/src/ir/conditions.ts +38 -78
  114. package/src/ir/core-model.ts +128 -11
  115. package/src/ir/declarations.ts +18 -32
  116. package/src/ir/diagnostics.ts +25 -18
  117. package/src/ir/domains.ts +26 -23
  118. package/src/ir/fold.ts +55 -50
  119. package/src/ir/identity.ts +10 -0
  120. package/src/ir/index.ts +31 -7
  121. package/src/ir/job-errors.ts +30 -8
  122. package/src/ir/layouts.ts +63 -34
  123. package/src/ir/link.ts +11 -46
  124. package/src/ir/model.ts +25 -6
  125. package/src/ir/normalize.ts +3 -28
  126. package/src/ir/numeric.ts +45 -18
  127. package/src/ir/operands.ts +102 -0
  128. package/src/ir/ranges.ts +242 -67
  129. package/src/ir/routine.ts +126 -183
  130. package/src/ir/scalars.ts +29 -25
  131. package/src/ir/share.ts +323 -343
  132. package/src/ir/short-circuit.ts +140 -0
  133. package/src/ir/tables.ts +111 -0
  134. package/src/ir/temporaries.ts +15 -113
  135. package/src/ir/types.ts +32 -8
  136. package/src/project/artifacts.ts +143 -71
  137. package/src/project/cli.ts +104 -87
  138. package/src/project/debugger.ts +48 -34
  139. package/src/project/deployments.ts +12 -68
  140. package/src/project/flags.ts +14 -0
  141. package/src/project/plant.ts +293 -225
  142. package/src/project/project-commands.ts +254 -192
  143. package/src/project/project.ts +184 -141
  144. package/src/project/release.ts +22 -28
  145. package/src/project/server.ts +22 -26
  146. package/src/project/terminal.ts +13 -2
  147. package/src/runtime/async.ts +17 -13
  148. package/src/runtime/launch.ts +5 -2
  149. package/src/runtime/main.ts +8 -3
  150. package/src/runtime/missing-file.ts +3 -0
  151. package/src/runtime/process.ts +24 -19
  152. package/src/runtime/program.ts +20 -53
  153. package/src/runtime/retain.ts +18 -10
  154. package/src/runtime/runtime.ts +47 -60
  155. package/src/runtime/settings.ts +27 -0
  156. package/src/runtime/storage.ts +49 -74
  157. package/src/runtime/symbols.ts +19 -75
  158. package/src/runtime/telemetry.ts +37 -14
  159. package/src/runtime/transport.ts +26 -30
  160. package/stdlib/clock.ts +4 -2
  161. package/stdlib/plc-time.ts +2 -0
  162. package/stdlib/retain.ts +2 -0
  163. package/stdlib/signals.ts +142 -0
  164. package/stdlib/telemetry.ts +5 -12
  165. package/types/dialect.d.ts +49 -0
  166. package/types/globals.d.ts +2 -42
  167. package/types/index.d.ts +3 -1
  168. package/types/retain.d.ts +8 -2
  169. package/types/telemetry.d.ts +3 -0
  170. package/dist/bun-runtime.js +0 -1472
  171. package/dist/bun-runtime.js.map +0 -26
  172. package/dist/elaborate-capture.js +0 -304
  173. package/dist/elaborate-capture.js.map +0 -11
  174. package/dist/math.js +0 -24
  175. package/dist/math.js.map +0 -10
  176. package/dist/project.js +0 -626
  177. package/dist/project.js.map +0 -12
  178. package/dist/server-check.js +0 -59
  179. package/dist/server-check.js.map +0 -11
  180. package/src/frontend/exposure.ts +0 -181
  181. package/src/project/index.ts +0 -6
  182. package/src/runtime/.runtime-65O4JH/server/router.ts +0 -17
  183. package/src/runtime/.runtime-65O4JH/src/cell.ts +0 -45
  184. package/src/runtime/.runtime-65O4JH/src/controller.ts +0 -58
  185. package/src/runtime/.runtime-65O4JH/src/lane.ts +0 -6
  186. package/src/runtime/.runtime-65O4JH/src/main.ts +0 -11
  187. package/src/runtime/.runtime-65O4JH/src/services.ts +0 -8
  188. package/src/runtime/.runtime-65O4JH/tsconfig.json +0 -13
  189. package/src/runtime/.runtime-65O4JH/tsplc.config.ts +0 -31
  190. package/src/runtime/.runtime-Brw2kO/server/router.ts +0 -17
  191. package/src/runtime/.runtime-Brw2kO/src/cell.ts +0 -45
  192. package/src/runtime/.runtime-Brw2kO/src/controller.ts +0 -58
  193. package/src/runtime/.runtime-Brw2kO/src/lane.ts +0 -6
  194. package/src/runtime/.runtime-Brw2kO/src/main.ts +0 -11
  195. package/src/runtime/.runtime-Brw2kO/src/services.ts +0 -8
  196. package/src/runtime/.runtime-Brw2kO/tsconfig.json +0 -13
  197. package/src/runtime/.runtime-Brw2kO/tsplc.config.ts +0 -31
  198. package/src/runtime/.runtime-NHfu1D/server/router.ts +0 -17
  199. package/src/runtime/.runtime-NHfu1D/src/cell.ts +0 -45
  200. package/src/runtime/.runtime-NHfu1D/src/controller.ts +0 -58
  201. package/src/runtime/.runtime-NHfu1D/src/lane.ts +0 -6
  202. package/src/runtime/.runtime-NHfu1D/src/main.ts +0 -11
  203. package/src/runtime/.runtime-NHfu1D/src/services.ts +0 -8
  204. package/src/runtime/.runtime-NHfu1D/tsconfig.json +0 -13
  205. package/src/runtime/.runtime-NHfu1D/tsplc.config.ts +0 -31
  206. package/src/runtime/.runtime-VaUSOu/server/router.ts +0 -17
  207. package/src/runtime/.runtime-VaUSOu/src/cell.ts +0 -45
  208. package/src/runtime/.runtime-VaUSOu/src/controller.ts +0 -58
  209. package/src/runtime/.runtime-VaUSOu/src/lane.ts +0 -6
  210. package/src/runtime/.runtime-VaUSOu/src/main.ts +0 -11
  211. package/src/runtime/.runtime-VaUSOu/src/services.ts +0 -8
  212. package/src/runtime/.runtime-VaUSOu/tsconfig.json +0 -13
  213. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +0 -31
  214. package/src/runtime/.runtime-WbtNvR/server/router.ts +0 -17
  215. package/src/runtime/.runtime-WbtNvR/src/cell.ts +0 -45
  216. package/src/runtime/.runtime-WbtNvR/src/controller.ts +0 -58
  217. package/src/runtime/.runtime-WbtNvR/src/lane.ts +0 -6
  218. package/src/runtime/.runtime-WbtNvR/src/main.ts +0 -11
  219. package/src/runtime/.runtime-WbtNvR/src/services.ts +0 -8
  220. package/src/runtime/.runtime-WbtNvR/tsconfig.json +0 -13
  221. package/src/runtime/.runtime-WbtNvR/tsplc.config.ts +0 -31
  222. package/src/runtime/.runtime-opcua-GMPUt8/server/router.ts +0 -17
  223. package/src/runtime/.runtime-opcua-GMPUt8/src/cell.ts +0 -45
  224. package/src/runtime/.runtime-opcua-GMPUt8/src/controller.ts +0 -58
  225. package/src/runtime/.runtime-opcua-GMPUt8/src/lane.ts +0 -6
  226. package/src/runtime/.runtime-opcua-GMPUt8/src/main.ts +0 -11
  227. package/src/runtime/.runtime-opcua-GMPUt8/src/services.ts +0 -8
  228. package/src/runtime/.runtime-opcua-GMPUt8/tsconfig.json +0 -13
  229. package/src/runtime/.runtime-opcua-GMPUt8/tsplc.config.ts +0 -31
  230. package/src/runtime/.runtime-opcua-UwafxO/server/router.ts +0 -17
  231. package/src/runtime/.runtime-opcua-UwafxO/src/cell.ts +0 -45
  232. package/src/runtime/.runtime-opcua-UwafxO/src/controller.ts +0 -58
  233. package/src/runtime/.runtime-opcua-UwafxO/src/lane.ts +0 -6
  234. package/src/runtime/.runtime-opcua-UwafxO/src/main.ts +0 -11
  235. package/src/runtime/.runtime-opcua-UwafxO/src/services.ts +0 -8
  236. package/src/runtime/.runtime-opcua-UwafxO/tsconfig.json +0 -13
  237. package/src/runtime/.runtime-opcua-UwafxO/tsplc.config.ts +0 -31
  238. package/src/runtime/.runtime-opcua-ecaSee/server/router.ts +0 -17
  239. package/src/runtime/.runtime-opcua-ecaSee/src/cell.ts +0 -45
  240. package/src/runtime/.runtime-opcua-ecaSee/src/controller.ts +0 -58
  241. package/src/runtime/.runtime-opcua-ecaSee/src/lane.ts +0 -6
  242. package/src/runtime/.runtime-opcua-ecaSee/src/main.ts +0 -11
  243. package/src/runtime/.runtime-opcua-ecaSee/src/services.ts +0 -8
  244. package/src/runtime/.runtime-opcua-ecaSee/tsconfig.json +0 -13
  245. package/src/runtime/.runtime-opcua-ecaSee/tsplc.config.ts +0 -31
  246. package/src/runtime/.runtime-opcua-y91UCm/server/router.ts +0 -17
  247. package/src/runtime/.runtime-opcua-y91UCm/src/cell.ts +0 -45
  248. package/src/runtime/.runtime-opcua-y91UCm/src/controller.ts +0 -58
  249. package/src/runtime/.runtime-opcua-y91UCm/src/lane.ts +0 -6
  250. package/src/runtime/.runtime-opcua-y91UCm/src/main.ts +0 -11
  251. package/src/runtime/.runtime-opcua-y91UCm/src/services.ts +0 -8
  252. package/src/runtime/.runtime-opcua-y91UCm/tsconfig.json +0 -13
  253. package/src/runtime/.runtime-opcua-y91UCm/tsplc.config.ts +0 -31
  254. package/src/runtime/.runtime-ybIxYh/server/router.ts +0 -17
  255. package/src/runtime/.runtime-ybIxYh/src/cell.ts +0 -45
  256. package/src/runtime/.runtime-ybIxYh/src/controller.ts +0 -58
  257. package/src/runtime/.runtime-ybIxYh/src/lane.ts +0 -6
  258. package/src/runtime/.runtime-ybIxYh/src/main.ts +0 -11
  259. package/src/runtime/.runtime-ybIxYh/src/services.ts +0 -8
  260. package/src/runtime/.runtime-ybIxYh/tsconfig.json +0 -13
  261. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +0 -31
  262. package/stdlib/math.ts +0 -23
  263. package/types/plc.d.ts +0 -4
@@ -8,22 +8,40 @@ import {
8
8
  rm,
9
9
  writeFile,
10
10
  } from "node:fs/promises";
11
- import { dirname, join } from "node:path";
12
- import type { buildCodesys } from "@tsplc/compiler/codesys";
13
- import { sha256Digest } from "@tsplc/config/build";
11
+ import { dirname, join, relative } from "node:path";
12
+ import { cyclicTasksSchema, sha256Digest } from "@tsplc/config/build";
14
13
  import {
15
14
  emittedStDirectory,
16
15
  generatedDirectory,
17
16
  } from "@tsplc/config/project-files";
18
17
  import { z } from "zod";
18
+ import { isMissingFile } from "../runtime/missing-file";
19
19
 
20
- const missing = (cause: unknown): boolean =>
21
- cause instanceof Error && "code" in cause && cause.code === "ENOENT";
22
20
  const digest = (value: string | Uint8Array): string =>
23
21
  createHash("sha256").update(value).digest("hex");
24
22
 
25
- // Ownership is an explicit boundary: generated files must match their manifest,
26
- // and engineering trees must belong to this configuration before vendor writes.
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
+
27
45
  const generatedFileSchema = z.object({
28
46
  path: z
29
47
  .string()
@@ -31,7 +49,8 @@ const generatedFileSchema = z.object({
31
49
  .refine(
32
50
  (path) =>
33
51
  !path.split("/").some((part) => part === "." || part === "..") &&
34
- !["manifest.json", "receipt.json"].includes(path),
52
+ path !== artifactFiles.manifest &&
53
+ path !== artifactFiles.receipt,
35
54
  ),
36
55
  sha256: sha256Digest,
37
56
  });
@@ -48,13 +67,16 @@ type Manifest = Omit<z.infer<typeof manifestSchema>, "files"> & {
48
67
  files: z.infer<typeof generatedFileSchema>[];
49
68
  };
50
69
 
51
- const buildStatusSchema = z.enum(["emitted", "vendor-compiled"]);
52
-
53
70
  const receiptSchema = z.object({
54
71
  kind: z.literal("tsplc-build"),
55
72
  version: z.literal(1),
73
+ generatedAt: z.iso.datetime(),
56
74
  configFile: z.string(),
57
- status: buildStatusSchema,
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(),
58
80
  });
59
81
 
60
82
  const engineeringMarkerSchema = z.object({
@@ -63,9 +85,16 @@ const engineeringMarkerSchema = z.object({
63
85
  configFile: z.string(),
64
86
  });
65
87
 
66
- function manifest(value: unknown, configFile: string): Manifest {
88
+ function manifest(
89
+ value: unknown,
90
+ output: string,
91
+ configFile: string,
92
+ ): Manifest {
67
93
  const parsed = manifestSchema.safeParse(value);
68
- if (!parsed.success || parsed.data.configFile !== configFile) {
94
+ if (
95
+ !parsed.success ||
96
+ !namesConfig(parsed.data.configFile, output, configFile)
97
+ ) {
69
98
  throw new Error(
70
99
  "Output directory has no matching tsPLC ownership manifest.",
71
100
  );
@@ -92,7 +121,7 @@ async function directory(path: string): Promise<boolean> {
92
121
  }
93
122
  return true;
94
123
  } catch (cause) {
95
- if (missing(cause)) {
124
+ if (isMissingFile(cause)) {
96
125
  return false;
97
126
  }
98
127
  throw cause;
@@ -116,35 +145,27 @@ export async function engineeringDirectory(
116
145
  path: string,
117
146
  configFile: string,
118
147
  ): Promise<void> {
119
- const marker = join(path, "ownership.json");
148
+ const marker = join(path, artifactFiles.marker);
120
149
  const exists = await directory(path);
121
150
  if (!exists || !(await readdir(path)).length) {
122
151
  await mkdir(path, { recursive: true });
123
152
  await writeFile(
124
153
  marker,
125
- `${JSON.stringify({ kind: "tsplc-engineering", version: 1, configFile }, null, 2)}\n`,
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`,
126
163
  { flag: "wx" },
127
164
  );
128
- } else {
129
- const entry = await lstat(marker).catch((cause: unknown) => {
130
- if (missing(cause)) {
131
- throw new Error(
132
- `Engineering cache has no matching tsPLC ownership marker: ${path}`,
133
- );
134
- }
135
- throw cause;
136
- });
137
- if (!entry.isFile() || entry.isSymbolicLink()) {
138
- throw new Error("Engineering ownership marker must be a real file.");
139
- }
140
- const value = engineeringMarkerSchema.safeParse(
141
- JSON.parse(await readFile(marker, "utf8")),
165
+ } else if (!(await ownedMarker(path, configFile))) {
166
+ throw new Error(
167
+ `Engineering cache has no matching tsPLC ownership marker: ${path}`,
142
168
  );
143
- if (!value.success || value.data.configFile !== configFile) {
144
- throw new Error(
145
- `Engineering cache has no matching tsPLC ownership marker: ${path}`,
146
- );
147
- }
148
169
  }
149
170
 
150
171
  const inspect = async (directory: string): Promise<void> => {
@@ -163,31 +184,62 @@ export async function engineeringDirectory(
163
184
  await inspect(path);
164
185
  }
165
186
 
166
- export async function owned(
167
- configFile: string,
168
- withdrawReceipt = false,
169
- ): Promise<{
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<{
170
213
  root: string;
171
214
  output: string;
172
215
  ownership?: Manifest;
173
- unknown: string[];
174
216
  }> {
175
217
  const root = join(dirname(configFile), generatedDirectory);
176
218
  const output = join(dirname(configFile), dirname(emittedStDirectory));
177
219
  if (!(await directory(root)) || !(await directory(output))) {
178
- return { root, output, unknown: [] };
220
+ return { root, output };
179
221
  }
180
222
 
181
- const manifestPath = join(output, "manifest.json");
182
- const manifestEntry = await lstat(manifestPath);
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
+ }
183
234
  if (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {
184
235
  throw new Error("Ownership manifest must be a real file.");
185
236
  }
186
237
  const ownership = manifest(
187
238
  JSON.parse(await readFile(manifestPath, "utf8")),
239
+ output,
188
240
  configFile,
189
241
  );
190
- const receipt = join(output, "receipt.json");
242
+ const receipt = join(output, artifactFiles.receipt);
191
243
  try {
192
244
  const entry = await lstat(receipt);
193
245
  if (!entry.isFile() || entry.isSymbolicLink()) {
@@ -196,22 +248,40 @@ export async function owned(
196
248
  const value = receiptSchema.safeParse(
197
249
  JSON.parse(await readFile(receipt, "utf8")),
198
250
  );
199
- if (!value.success || value.data.configFile !== configFile) {
251
+ if (
252
+ !value.success ||
253
+ !namesConfig(value.data.configFile, output, configFile)
254
+ ) {
200
255
  throw new Error("Build receipt is not owned by this configuration.");
201
256
  }
202
- if (withdrawReceipt) {
203
- await rm(receipt);
204
- }
205
257
  } catch (cause) {
206
- if (!missing(cause)) {
258
+ if (!isMissingFile(cause)) {
207
259
  throw cause;
208
260
  }
209
261
  }
262
+ return { root, output, ownership };
263
+ }
210
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
+ }
211
281
  const names = new Set([
212
282
  ...ownership.files.map((file) => file.path),
213
- "manifest.json",
214
- "receipt.json",
283
+ artifactFiles.manifest,
284
+ artifactFiles.receipt,
215
285
  ]);
216
286
  // Thousands of files share a few hundred directories; each is checked once.
217
287
  const checked = new Set<string>();
@@ -240,21 +310,23 @@ export async function owned(
240
310
  }
241
311
  }
242
312
  return {
243
- root,
244
- output,
245
- ownership,
313
+ ...claim,
246
314
  unknown: (await filesIn(output)).filter((name) => !names.has(name)),
247
315
  };
248
316
  }
249
317
 
250
- interface Receipt {
251
- configFile: string;
252
- status: z.infer<typeof buildStatusSchema>;
253
- vendor?: Pick<
254
- Awaited<ReturnType<typeof buildCodesys>>,
255
- "application" | "tasks"
256
- >;
257
- }
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
+ >;
258
330
 
259
331
  // Compile in a separate staging tree. Recheck ownership immediately before the
260
332
  // swap, because the vendor build may have given the user time to edit old files.
@@ -263,7 +335,7 @@ export async function publishArtifacts(
263
335
  previous: Awaited<ReturnType<typeof owned>>,
264
336
  receipt: Receipt,
265
337
  ): Promise<void> {
266
- const configFile = receipt.configFile;
338
+ const configFile = configReference(previous.output, receipt.configFile);
267
339
  const generated = (await filesIn(staging)).sort();
268
340
  const ownership: Manifest = {
269
341
  kind: "tsplc-artifacts",
@@ -278,24 +350,25 @@ export async function publishArtifacts(
278
350
  });
279
351
  }
280
352
  await writeFile(
281
- join(staging, "manifest.json"),
353
+ join(staging, artifactFiles.manifest),
282
354
  `${JSON.stringify(ownership, null, 2)}\n`,
283
355
  );
284
356
  await writeFile(
285
- join(staging, "receipt.json"),
357
+ join(staging, artifactFiles.receipt),
286
358
  `${JSON.stringify(
287
359
  {
288
360
  kind: "tsplc-build",
289
361
  version: 1,
290
362
  generatedAt: new Date().toISOString(),
291
363
  ...receipt,
292
- },
364
+ configFile,
365
+ } satisfies z.input<typeof receiptSchema>,
293
366
  null,
294
367
  2,
295
368
  )}\n`,
296
369
  );
297
370
 
298
- const current = await owned(configFile);
371
+ const current = await owned(await claimed(receipt.configFile));
299
372
  if (
300
373
  JSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)
301
374
  ) {
@@ -327,17 +400,16 @@ export async function publishArtifacts(
327
400
  }
328
401
 
329
402
  export async function cleanArtifacts(configFile: string): Promise<void> {
330
- const generated = await owned(configFile);
403
+ const generated = await owned(await claimed(configFile));
331
404
  if (!generated.ownership) {
332
405
  return;
333
406
  }
334
407
  for (const entry of generated.ownership.files) {
335
408
  await rm(join(generated.output, entry.path));
336
409
  }
337
- await rm(join(generated.output, "receipt.json"), { force: true });
338
- await rm(join(generated.output, "manifest.json"));
410
+ await rm(join(generated.output, artifactFiles.receipt), { force: true });
411
+ await rm(join(generated.output, artifactFiles.manifest));
339
412
 
340
- // Remove empty generated directories while preserving unrelated files.
341
413
  const removeEmpty = async (path: string): Promise<void> => {
342
414
  for (const entry of await readdir(path, { withFileTypes: true })) {
343
415
  if (entry.isDirectory() && !entry.isSymbolicLink()) {
@@ -1,25 +1,40 @@
1
1
  #!/usr/bin/env bun
2
2
  import { existsSync } from "node:fs";
3
- import { parseArgs } from "node:util";
3
+ import { type ParseArgsOptionsConfig, parseArgs } from "node:util";
4
4
  import { formatDiagnostic, hasErrors } from "@tsplc/compiler/ir";
5
- import { loadTsplcConfig } from "@tsplc/config";
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";
6
12
  import { z } from "zod";
7
- import { serveProjectDebugger } from "./debugger";
8
- import { connect, plantCommand, runPlantCommand } from "./plant";
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";
9
22
  import {
10
23
  type CommandResult,
11
24
  checkProjectFlags,
12
25
  DiagnosticFailure,
13
- projectCommand,
26
+ isProjectCommand,
27
+ projectOptions,
14
28
  runProjectCommand,
15
29
  } from "./project-commands";
16
30
 
17
- const 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]
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]
18
33
 
19
- Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:4840:
34
+ Run the TypeScript program in Bun instead of CODESYS, with OPC UA on opc.tcp://127.0.0.1:${opcuaPort}:
20
35
  tsplc run --simulate --bun [--foreground] [--target name]
21
36
 
22
- Plant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):
37
+ Plant agent (the target's agent, else ${agentUrlEnv}; ${agentTokenEnv}):
23
38
  tsplc deploy [--target name] [--download] [--select] [--initialize-user] [--simulate] [--review] [--wait]
24
39
  tsplc deployments [--format json] | dashboard
25
40
  tsplc rollback [id] [--wait] | redeploy <id> [--review] [--wait]
@@ -30,11 +45,22 @@ Plant agent (the target's agent, else TSPLC_AGENT_URL; TSPLC_AGENT_TOKEN):
30
45
  tsplc start | stop | reset warm|cold (-y skips confirmations)
31
46
  tsplc restart [warm|cold] resets and starts the application, with or without a login
32
47
 
33
- Debugger, on http://127.0.0.1, for the built .tsplc/artifacts/st/debug.json; it reads through
34
- the plant agent's login (TSPLC_AGENT_URL, TSPLC_AGENT_TOKEN), or --opcua at config monitor:
35
- tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]`;
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;
36
62
 
37
- const formatSchema = z.enum(["json", "text"]).optional();
63
+ type Values = Omit<Flags<typeof options>, "format"> & { format?: OutputFormat };
38
64
 
39
65
  /**
40
66
  * The `--format` the command line names, read before it is fully parsed so a command that fails
@@ -52,108 +78,89 @@ const requestedFormat = (argv: readonly string[]) => {
52
78
  };
53
79
 
54
80
  const outputFormat = (format: string | undefined) => {
55
- const parsed = formatSchema.safeParse(format);
81
+ const parsed = outputFormatSchema.optional().safeParse(format);
56
82
  if (!parsed.success) {
57
83
  throw new Error("--format must be json or text.");
58
84
  }
59
85
  return parsed.data;
60
86
  };
61
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
+
62
132
  async function main() {
63
133
  const { values: parsed, positionals } = parseArgs({
64
134
  allowPositionals: true,
65
- options: {
66
- config: { type: "string" },
67
- target: { type: "string" },
68
- help: { type: "boolean", short: "h" },
69
- "emit-only": { type: "boolean" },
70
- format: { type: "string" },
71
- read: { type: "string", multiple: true },
72
- "initialize-user": { type: "boolean" },
73
- "frozen-lockfile": { type: "boolean" },
74
- check: { type: "boolean" },
75
- plc: { type: "boolean" },
76
- server: { type: "boolean" },
77
- simulate: { type: "boolean" },
78
- runtime: { type: "boolean" },
79
- bun: { type: "boolean" },
80
- foreground: { type: "boolean" },
81
- download: { type: "boolean" },
82
- restore: { type: "boolean" },
83
- select: { type: "boolean" },
84
- yes: { type: "boolean", short: "y" },
85
- port: { type: "string" },
86
- "server-url": { type: "string" },
87
- opcua: { type: "boolean" },
88
- review: { type: "boolean" },
89
- wait: { type: "boolean" },
90
- },
135
+ options,
91
136
  });
92
- const values = {
93
- ...parsed,
94
- format: outputFormat(parsed.format),
95
- };
137
+ const values = { ...parsed, format: outputFormat(parsed.format) };
96
138
  const [name, ...args] = positionals;
97
- const file = values.config ?? "tsplc.config.ts";
139
+ const file = values.config ?? configFileName;
98
140
  if (!name || values.help) {
99
141
  console.log(usage);
100
142
  return 0;
101
143
  }
102
144
  if (name === "debug") {
103
- if (args.length) {
104
- throw new Error(
105
- "Usage: tsplc debug [--target name] [--port 4870] [--server-url url] [--opcua]",
106
- );
107
- }
108
- await serveProjectDebugger(
109
- await loadTsplcConfig(file, {
110
- env: process.env,
111
- target: values.target,
112
- forAgent: false,
113
- }),
114
- values,
115
- );
116
- return 0;
145
+ return debug(args, values, file);
117
146
  }
118
- const plant = plantCommand(name);
119
- if (plant) {
120
- const load = () =>
121
- loadTsplcConfig(file, {
122
- env: process.env,
123
- target: values.target,
124
- forAgent: true,
125
- });
126
- // In a project, the target names the agent; elsewhere TSPLC_AGENT_URL does.
127
- const loaded = existsSync(file) ? await load() : undefined;
128
- const env = loaded?.env ?? process.env;
129
- const outcome = await runPlantCommand(connect(env), plant, args, values, {
130
- file,
131
- load: loaded ? async () => loaded : load,
132
- environment: env,
133
- interactive: process.stdin.isTTY === true,
134
- });
135
- if (!outcome) {
136
- return 0;
137
- }
138
- return "exitCode" in outcome
139
- ? outcome.exitCode
140
- : report(outcome, values.format);
147
+ if (isPlantCommand(name)) {
148
+ return plant(name, args, values, file);
141
149
  }
142
150
  if (args.length) {
143
151
  throw new Error("Specify one command.");
144
152
  }
145
- const command = projectCommand(name);
146
- if (!command) {
153
+ if (!isProjectCommand(name)) {
147
154
  throw new Error(`Unknown command ${name}.`);
148
155
  }
149
- checkProjectFlags(command, values);
156
+ checkProjectFlags(name, values);
150
157
  return report(
151
- await runProjectCommand(command, file, values, { ...process.env }),
158
+ await runProjectCommand(name, file, values, process.env),
152
159
  values.format,
153
160
  );
154
161
  }
155
162
 
156
- function report(result: CommandResult, format: string | undefined) {
163
+ function report(result: CommandResult, format: OutputFormat | undefined) {
157
164
  const diagnostics = result.diagnostics ?? [];
158
165
  const ok = !hasErrors(diagnostics);
159
166
  if (format === "json") {
@@ -162,6 +169,9 @@ function report(result: CommandResult, format: string | undefined) {
162
169
  for (const diagnostic of diagnostics) {
163
170
  console.error(formatDiagnostic(diagnostic));
164
171
  }
172
+ for (const [expression, value] of Object.entries(result.values ?? {})) {
173
+ console.log(`${expression} = ${value}`);
174
+ }
165
175
  if (ok) {
166
176
  console.log("tsPLC completed.");
167
177
  }
@@ -169,6 +179,13 @@ function report(result: CommandResult, format: string | undefined) {
169
179
  return ok ? 0 : 1;
170
180
  }
171
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
+
172
189
  try {
173
190
  process.exitCode = await main();
174
191
  } catch (cause) {
@@ -176,7 +193,7 @@ try {
176
193
  if (cause instanceof DiagnosticFailure) {
177
194
  process.exitCode = report(cause.result, json ? "json" : undefined);
178
195
  } else {
179
- const message = cause instanceof Error ? cause.message : String(cause);
196
+ const message = causeMessage(cause);
180
197
  if (json) {
181
198
  console.log(
182
199
  JSON.stringify({