@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
@@ -1,41 +1,59 @@
1
- // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
1
  import {
3
2
  type CoreStatement,
3
+ coreTables,
4
4
  type Deployment,
5
5
  errorName,
6
6
  type GeneratedObject,
7
7
  httpErrors,
8
+ instancedBlock,
8
9
  jobErrors,
9
10
  nestedBodies,
10
11
  type PlcType,
11
12
  type SourceSpan,
12
13
  type VerifiedCoreModule,
13
14
  } from "@tsplc/compiler/ir";
14
- import { type ResolvedTelemetryConfig, telemetrySchema } from "@tsplc/config";
15
+ import {
16
+ type Environment,
17
+ type ResolvedTelemetryConfig,
18
+ serverBaseUrl,
19
+ } from "@tsplc/config";
20
+ import { elementaryType } from "@tsplc/iec";
21
+ import {
22
+ buildIdLength,
23
+ taskNameLength,
24
+ telemetryPath,
25
+ } from "@tsplc/server/telemetry";
15
26
  import { plcBufferBytes } from "@tsplc/server/wire";
16
27
  import type { CodesysOptions } from "./config";
17
28
  import { blockInstances, type InstancePath } from "./debug";
18
29
  import {
19
30
  type HttpEndpoint,
31
+ type NativeEndpoint,
32
+ resolveHttpEndpoint,
33
+ routeBase,
34
+ } from "./endpoints";
35
+ import {
36
+ decimalLength,
20
37
  httpCertificateVerifier,
21
- httpMethods,
38
+ httpClientMethods,
39
+ jsonEncoders,
22
40
  jsonScalar,
23
41
  nativeHttp,
24
42
  opcuaClient,
25
- resolveHttpEndpoint,
43
+ opcuaClientMethods,
26
44
  } from "./http";
45
+ import type { Report } from "./plan";
46
+ import { required } from "./required";
27
47
  import { Sources } from "./sources";
28
48
  import { routineTasks } from "./task-access";
49
+ import { ringSettings, telemetrySendIntervalMs } from "./telemetry-settings";
29
50
  import { type CodesysTypes, stStringLiteral } from "./types";
30
51
 
31
- /** The sender's key in `CodesysPlan.http`, and its HTTP block's id. */
52
+ /** The id of the sender's client block. */
32
53
  export const telemetryClient = "tsplc:telemetry";
33
- /** Where each task posts its records, below the server's base URL. */
34
- const telemetryPath = "/tsplc/telemetry";
35
- /** A sender waits this long for a batch to fill. */
36
- const sendIntervalMs = 200;
37
- /** The longest task name a batch carries, as the wire allows. */
38
- const taskBytes = 64;
54
+ const telemetryWriter = "tsplc:telemetryWriter";
55
+ /** Stands for the build id in the sender until the id, a hash over everything else, is known. */
56
+ const buildPlaceholder = "<build>";
39
57
 
40
58
  type TelemetryStatement = Extract<CoreStatement, { kind: "telemetry" }>;
41
59
 
@@ -61,6 +79,8 @@ interface FailureSite {
61
79
  }
62
80
 
63
81
  export interface TelemetryPlan extends ResolvedTelemetryConfig {
82
+ /** Where the senders post their batches. */
83
+ endpoint: HttpEndpoint;
64
84
  calls: ReadonlyMap<CoreStatement, CallSite>;
65
85
  /** By job block id. */
66
86
  failures: ReadonlyMap<string, FailureSite>;
@@ -82,43 +102,76 @@ export const generated = (name: string) => name.startsWith("tsplc");
82
102
  const maximum = (values: readonly number[]) =>
83
103
  values.reduce((a, b) => Math.max(a, b), 0);
84
104
 
85
- /** `Commit` ends every record with the task's scan and clock. */
86
- const commitSize = ',"scan":,"time":}'.length + 2 * 10;
87
- /** `ErrorName` names a known error code. */
105
+ const digits = {
106
+ uint: decimalLength(elementaryType("UINT")),
107
+ dint: decimalLength(elementaryType("DINT")),
108
+ udint: decimalLength(elementaryType("UDINT")),
109
+ ulint: decimalLength(elementaryType("ULINT")),
110
+ };
111
+
112
+ /** The members `Commit` ends every record with, and the writer's UDINT each one prints. */
113
+ const commitMembers = [
114
+ { member: ',"scan":', value: "scan" },
115
+ { member: ',"time":', value: "now" },
116
+ ] as const;
117
+ const commitSize =
118
+ commitMembers.reduce(
119
+ (total, { member }) => total + member.length + digits.udint,
120
+ 0,
121
+ ) + "}".length;
122
+
123
+ const codeMember = ',"code":';
124
+ const nameMember = ',"name":';
88
125
  const errorNames = Object.keys(jobErrors).flatMap((code) => {
89
126
  const name = errorName(Number(code));
90
127
  return name === undefined ? [] : [[code, name] as const];
91
128
  });
129
+ /** What an exception record's error code and its name take after its properties. */
92
130
  const codeSize =
93
- ',"code":'.length +
94
- 10 +
95
- ',"name":'.length +
131
+ codeMember.length +
132
+ digits.udint +
133
+ nameMember.length +
96
134
  maximum([
97
135
  ...errorNames.map(([, name]) => asciiJson(name).length),
98
- asciiJson("HTTP 999").length,
136
+ asciiJson(`HTTP ${httpErrors.last - httpErrors.base}`).length,
99
137
  ]);
100
138
 
101
- /** The most bytes a property's value takes. */
102
- function valueSize(type: PlcType, text: boolean): number {
139
+ const nullJson = "null";
140
+
141
+ /** A property's value in a record: the most bytes it takes, and the ST that appends parameter `value`. */
142
+ function propertyJson(
143
+ type: PlcType,
144
+ text: boolean,
145
+ ): { size: number; encode: (value: string, target: CodesysTypes) => string } {
103
146
  if (text && type.kind === "array") {
104
- return type.length * 6 + 2;
147
+ return {
148
+ size: type.length * 6 + 2,
149
+ encode: (value) =>
150
+ `WriteText(ADR(${value}), LINT_TO_DINT(LIMIT(0, TO_LINT(${value}Length), ${type.length})));`,
151
+ };
105
152
  }
106
153
  if (type.kind === "enum") {
107
- return maximum([
108
- 4,
109
- ...type.members.map(
110
- (member) => asciiJson(member.text ?? member.name).length,
111
- ),
112
- ]);
154
+ const texts = type.members.map((member) =>
155
+ asciiJson(member.text ?? member.name),
156
+ );
157
+ return {
158
+ size: maximum([nullJson.length, ...texts.map((item) => item.length)]),
159
+ encode: (value, target) =>
160
+ `CASE ${value} OF ${type.members.map((member, index) => `${target.name(type.id)}.${target.field(type.id, member.name)}: Append(${stStringLiteral(required(texts[index]))});`).join(" ")} ELSE Append('${nullJson}'); END_CASE;`,
161
+ };
113
162
  }
114
163
  if (type.kind === "float") {
115
- return type.bits === 32 ? 16 : 25;
164
+ return {
165
+ size: type.bits === 32 ? 16 : 25,
166
+ encode: (value) =>
167
+ `IF ${value} = ${value} AND ABS(${value}) < ${type.id}#${type.bits === 32 ? "3.4E38" : "1.7E308"} THEN Append(${type.id}_TO_STRING(${value})); ELSE Append('${nullJson}'); END_IF;`,
168
+ };
116
169
  }
117
- const scalar = jsonScalar(type, "");
170
+ const scalar = jsonScalar(type);
118
171
  if (!scalar) {
119
172
  throw new Error(`Unverified telemetry value type ${type.id}.`);
120
173
  }
121
- return scalar.size;
174
+ return scalar;
122
175
  }
123
176
 
124
177
  /** A call's record up to its source: its kind and what it names. */
@@ -133,15 +186,38 @@ const recordHead = (record: TelemetryStatement["record"]): string => {
133
186
  }
134
187
  };
135
188
 
136
- const traceRecord = (operands: number) => ({
137
- prefix: '{"kind":"trace","site":',
138
- size:
139
- '{"kind":"trace","site":,"value":,"operands":[]'.length +
140
- 5 +
141
- 11 +
142
- operands * 12 +
143
- commitSize,
144
- });
189
+ /** A `debug.trace` record with `operands` operands: the ST of the writer's `Trace`, and the most bytes it takes. */
190
+ const traceRecord = (operands: number) => {
191
+ const site = '{"kind":"trace","site":';
192
+ const value = ',"value":';
193
+ const list = ',"operands":[';
194
+ return {
195
+ implementation: `${[
196
+ "payload := '';",
197
+ `Append(${stStringLiteral(site)});`,
198
+ "Append(UINT_TO_STRING(site));",
199
+ `Append(${stStringLiteral(value)});`,
200
+ "Append(DINT_TO_STRING(value));",
201
+ `Append(${stStringLiteral(list)});`,
202
+ ...Array.from(
203
+ { length: operands },
204
+ (_, index) =>
205
+ `IF operands > ${index} THEN ${index ? "Append(','); " : ""}Append(DINT_TO_STRING(operand${index})); END_IF;`,
206
+ ),
207
+ "Append(']');",
208
+ "Commit();",
209
+ ].join("\n")}\n`,
210
+ size:
211
+ site.length +
212
+ digits.uint +
213
+ value.length +
214
+ digits.dint +
215
+ list.length +
216
+ operands * (digits.dint + ",".length) +
217
+ "]".length +
218
+ commitSize,
219
+ };
220
+ };
145
221
 
146
222
  function telemetryCalls(core: VerifiedCoreModule) {
147
223
  const routines = [
@@ -180,21 +256,19 @@ function planJobFailures(
180
256
  tasks: ReadonlyMap<string, string | undefined>,
181
257
  location: (span: SourceSpan) => string,
182
258
  ): ReadonlyMap<string, JobFailure> {
183
- const types = new Map(core.types.map((type) => [type.id, type]));
259
+ const { types, blockOf } = coreTables(core);
184
260
  const failures = new Map<string, JobFailure>();
185
- const blocks = new Map(core.blocks.map((block) => [block.id, block]));
186
261
  const instances = blockInstances(core);
187
262
  const awaited = (path: InstancePath) =>
188
263
  path.slice(0, -1).some(({ variable }) => {
189
- const type = types.get(variable.type);
190
- const element = type?.kind === "array" ? types.get(type.element) : type;
191
- return element?.kind === "block" && blocks.get(element.block)?.job;
264
+ const type = instancedBlock(variable.type, types);
265
+ return type !== undefined && blockOf(type.block).job !== undefined;
192
266
  });
193
267
 
194
268
  for (const block of core.blocks) {
195
269
  const { job } = block;
196
270
  const task = tasks.get(block.id);
197
- const paths = instances.get(block.id)!;
271
+ const paths = required(instances.get(block.id));
198
272
  if (!job || !task || !paths.length || paths.some(awaited)) {
199
273
  continue;
200
274
  }
@@ -203,7 +277,7 @@ function planJobFailures(
203
277
  const children = block.state.flatMap((child) => {
204
278
  const type = types.get(child.type);
205
279
  const called =
206
- type?.kind === "block" ? blocks.get(type.block)?.job : undefined;
280
+ type?.kind === "block" ? blockOf(type.block).job : undefined;
207
281
  return called && !generated(called.name) ? [called] : [];
208
282
  });
209
283
  const [onlyChild] = children;
@@ -247,17 +321,17 @@ export function planTelemetry(
247
321
  telemetry?: ResolvedTelemetryConfig;
248
322
  trace?: { capacity: number; operands: number } | false;
249
323
  server?: { transport: "http" | "opcua"; baseUrlEnv?: string };
250
- environment: Readonly<Record<string, string | undefined>>;
324
+ environment: Environment;
251
325
  },
252
- report: (message: string, span?: SourceSpan) => void,
253
- ): { telemetry?: TelemetryPlan; endpoint?: HttpEndpoint } {
254
- const types = new Map(core.types.map((type) => [type.id, type]));
326
+ report: Report,
327
+ ): TelemetryPlan | undefined {
328
+ const { typeOf } = coreTables(core);
255
329
  const statements = telemetryCalls(core);
256
330
  if (!statements.length && !project.telemetry && !project.trace) {
257
- return {};
331
+ return undefined;
258
332
  }
259
333
 
260
- const settings = project.telemetry ?? telemetrySchema.parse({});
334
+ const settings = ringSettings(project.telemetry, project.trace);
261
335
  const sources = new Sources(project.root);
262
336
  const location = (span: SourceSpan) => {
263
337
  const range = sources.range(span);
@@ -295,7 +369,7 @@ export function planTelemetry(
295
369
  (index ? 1 : 0) +
296
370
  asciiJson(name).length +
297
371
  1 +
298
- valueSize(types.get(value.type)!, length !== undefined),
372
+ propertyJson(typeOf(value.type), length !== undefined).size,
299
373
  0,
300
374
  ) +
301
375
  1 +
@@ -360,31 +434,20 @@ export function planTelemetry(
360
434
  );
361
435
  }
362
436
 
363
- const server = project.server;
364
- const base = server?.baseUrlEnv && project.environment[server.baseUrlEnv];
365
- const plan: TelemetryPlan = {
437
+ const base = serverBaseUrl(project, project.environment);
438
+ const plan = {
366
439
  ...settings,
367
- // One ring per task holds the trace too.
368
- capacity: Math.max(
369
- settings.capacity,
370
- project.trace ? project.trace.capacity : 0,
371
- ),
372
440
  calls,
373
441
  failures,
374
442
  ...(project.trace && { traceOperands: project.trace.operands }),
375
443
  };
376
- if (server?.transport === "opcua") {
444
+ if (project.server?.transport === "opcua") {
377
445
  return {
378
- telemetry: plan,
446
+ ...plan,
379
447
  endpoint: {
380
448
  transport: "opcua",
381
- host: "",
382
- port: 0,
383
- authority: "",
384
449
  path: telemetryPath,
385
- token: "",
386
450
  timeoutMs: options.http.timeoutMs,
387
- tls: false,
388
451
  },
389
452
  };
390
453
  }
@@ -392,21 +455,18 @@ export function planTelemetry(
392
455
  report(
393
456
  `Telemetry posts to the app server: set server.baseUrlEnv and that environment variable to its base URL.`,
394
457
  );
395
- return {};
458
+ return undefined;
396
459
  }
397
- try {
398
- return {
399
- telemetry: plan,
400
- endpoint: resolveHttpEndpoint(
401
- `${base.replace(/\/+$/, "")}${telemetryPath}`,
402
- options.http,
403
- project.environment,
404
- ),
405
- };
406
- } catch (cause) {
407
- report(cause instanceof Error ? cause.message : String(cause));
408
- return {};
460
+ const endpoint = resolveHttpEndpoint(
461
+ `${routeBase(base)}${telemetryPath}`,
462
+ options.http,
463
+ project.environment,
464
+ );
465
+ if ("error" in endpoint) {
466
+ report(endpoint.error);
467
+ return undefined;
409
468
  }
469
+ return { ...plan, endpoint };
410
470
  }
411
471
 
412
472
  /** A call's method parameters, in declaration order: `p<n>` for each property, `code` for an exception. */
@@ -447,43 +507,41 @@ const header = (build: string) => ({
447
507
 
448
508
  /** Records that always fit a batch beside its header: a sender with this many unsent sends at once. */
449
509
  const batchRecords = (recordBytes: number) => {
450
- const { start, rest } = header("0".repeat(16));
510
+ const { start, rest } = header("0".repeat(buildIdLength));
451
511
  const fixed =
452
512
  start.length +
453
- taskBytes +
513
+ taskNameLength +
454
514
  rest.join("").length +
455
- 2 * 10 +
456
- 2 * 20 +
515
+ 2 * digits.udint +
516
+ 2 * digits.ulint +
457
517
  "]}".length;
458
518
  return Math.max(1, Math.floor((plcBufferBytes - fixed) / (recordBytes + 1)));
459
519
  };
460
520
 
461
- /**
462
- * The ring and sender of a task, `FB_TsplcTelemetry`: one method per call site and root job, a
463
- * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
464
- * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block.
465
- */
466
521
  /** How the sender reaches the server: its HTTP client's endpoint and network, or the OPC UA slots it posts through. */
467
522
  export type TelemetryTransport =
468
- | { kind: "http"; endpoint: HttpEndpoint; network: string }
523
+ | { kind: "http"; endpoint: NativeEndpoint; network: string }
469
524
  | { kind: "opcua"; timeoutMs: number; rpcGlobal: string };
470
525
 
526
+ /**
527
+ * The ring and sender of a task, `FB_TsplcTelemetry`: one method per call site and root job, a
528
+ * shared `Trace`, and a body each scan runs first that counts the scan, reads the clock and
529
+ * sends. It encodes with the HTTP blocks' JSON methods, and sends through a native HTTP block
530
+ * or over OPC UA. Its batches name the build once `fillBuildId` has run.
531
+ */
471
532
  export function telemetryObjects({
472
533
  plan,
473
534
  names,
474
535
  target,
475
536
  transport,
476
- build,
477
537
  types,
478
538
  }: {
479
539
  plan: TelemetryPlan;
480
540
  names: { writer: string; record: string; client: string };
481
541
  target: CodesysTypes;
482
542
  transport: TelemetryTransport;
483
- build: string;
484
543
  types: ReadonlyMap<string, PlcType>;
485
544
  }): GeneratedObject[] {
486
- const writer = "tsplc:telemetryWriter";
487
545
  const { capacity, recordBytes } = plan;
488
546
  const method = (
489
547
  name: string,
@@ -491,36 +549,23 @@ export function telemetryObjects({
491
549
  implementation: string,
492
550
  access = "",
493
551
  ): GeneratedObject => ({
494
- id: `${writer}:${name}`,
495
- parent: writer,
552
+ id: `${telemetryWriter}:${name}`,
553
+ parent: telemetryWriter,
496
554
  kind: "method",
497
555
  name,
498
556
  declaration: `METHOD ${access}${name}\n${declaration}`,
499
557
  implementation,
500
558
  });
501
- const encode = (type: PlcType, parameter: string, text: boolean): string => {
502
- if (text && type.kind === "array") {
503
- return `WriteText(ADR(${parameter}), LINT_TO_DINT(LIMIT(0, TO_LINT(${parameter}Length), ${type.length})));`;
504
- }
505
- if (type.kind === "enum") {
506
- return `CASE ${parameter} OF ${type.members.map((member) => `${target.name(type.id)}.${target.field(type.id, member.name)}: Append(${stStringLiteral(asciiJson(member.text ?? member.name))});`).join(" ")} ELSE Append('null'); END_CASE;`;
507
- }
508
- if (type.kind === "float") {
509
- return `IF ${parameter} = ${parameter} AND ABS(${parameter}) < ${type.id}#${type.bits === 32 ? "3.4E38" : "1.7E308"} THEN Append(${type.id}_TO_STRING(${parameter})); ELSE Append('null'); END_IF;`;
510
- }
511
- return jsonScalar(type, parameter)!.code;
512
- };
513
559
 
514
560
  const calls = firstOfEach(plan.calls.values()).map(({ id, record, call }) => {
515
561
  const parameters = callParameters(call);
516
562
  const inputs = parameters.filter((parameter) => !parameter.text);
517
563
  const references = parameters.filter((parameter) => parameter.text);
518
564
  const properties = call.properties.map(({ name, value, length }, index) => {
519
- const code = encode(
520
- types.get(value.type)!,
521
- `p${index}`,
565
+ const code = propertyJson(
566
+ required(types.get(value.type)),
522
567
  length !== undefined,
523
- );
568
+ ).encode(`p${index}`, target);
524
569
  return `Append(${stStringLiteral(`${index ? "," : ""}${asciiJson(name)}:`)});\n${code}`;
525
570
  });
526
571
  return method(
@@ -556,7 +601,7 @@ export function telemetryObjects({
556
601
  "Append('}');",
557
602
  ...(call.record.kind === "exception"
558
603
  ? [
559
- "Append(',\"code\":');",
604
+ `Append(${stStringLiteral(codeMember)});`,
560
605
  "Append(UDINT_TO_STRING(code));",
561
606
  "ErrorName(code);",
562
607
  ]
@@ -580,7 +625,7 @@ export function telemetryObjects({
580
625
  "payload := '';",
581
626
  `Append(${stStringLiteral(record)});`,
582
627
  ...(instances.length ? ["Append(instance);"] : []),
583
- `Append(${stStringLiteral('"properties":{},"code":')});`,
628
+ `Append(${stStringLiteral(`"properties":{}${codeMember}`)});`,
584
629
  "Append(UDINT_TO_STRING(code));",
585
630
  "ErrorName(code);",
586
631
  `Append(',"source":"');`,
@@ -615,28 +660,11 @@ export function telemetryObjects({
615
660
  ),
616
661
  "END_VAR",
617
662
  ].join("\n")}\n`,
618
- `${[
619
- "payload := '';",
620
- `Append(${stStringLiteral(traceRecord(operands).prefix)});`,
621
- "Append(UINT_TO_STRING(site));",
622
- `Append(',"value":');`,
623
- "Append(DINT_TO_STRING(value));",
624
- `Append(',"operands":[');`,
625
- ...Array.from(
626
- { length: operands },
627
- (_, index) =>
628
- `IF operands > ${index} THEN ${index ? "Append(','); " : ""}Append(DINT_TO_STRING(operand${index})); END_IF;`,
629
- ),
630
- "Append(']');",
631
- "Commit();",
632
- ].join("\n")}\n`,
663
+ traceRecord(operands).implementation,
633
664
  ),
634
665
  ];
635
666
 
636
- const { start, rest } = header(build);
637
- const helpers = httpMethods(writer).filter((item) =>
638
- ["ByteLength", "Append", "WriteString"].includes(item.name),
639
- );
667
+ const { start, rest } = header(buildPlaceholder);
640
668
  const clientPorts = `VAR_INPUT\nstart : BOOL;\ncancel : BOOL;\nEND_VAR\nVAR_IN_OUT\nbody : STRING(${plcBufferBytes});\nEND_VAR\nVAR_OUTPUT\nbusy : BOOL;\ndone : BOOL;\nerror : UDINT;\nEND_VAR`;
641
669
  const clientObjects =
642
670
  transport.kind === "opcua"
@@ -651,7 +679,7 @@ export function telemetryObjects({
651
679
  body: "Append(body);",
652
680
  decode: "",
653
681
  }),
654
- ...httpMethods(telemetryClient, "opcua"),
682
+ ...opcuaClientMethods(telemetryClient),
655
683
  ]
656
684
  : [
657
685
  ...nativeHttp({
@@ -666,7 +694,7 @@ export function telemetryObjects({
666
694
  body: "Append(body);",
667
695
  decode: "",
668
696
  }),
669
- ...httpMethods(telemetryClient),
697
+ ...httpClientMethods(telemetryClient),
670
698
  ...httpCertificateVerifier(
671
699
  telemetryClient,
672
700
  names.client,
@@ -681,12 +709,12 @@ export function telemetryObjects({
681
709
  declaration: `TYPE ${names.record} :\nSTRUCT\n sequence : ULINT;\n json : STRING(${recordBytes});\nEND_STRUCT\nEND_TYPE\n`,
682
710
  },
683
711
  {
684
- id: writer,
712
+ id: telemetryWriter,
685
713
  kind: "functionBlock",
686
714
  name: names.writer,
687
715
  declaration: `FUNCTION_BLOCK ${names.writer}
688
716
  VAR_INPUT
689
- task : STRING(${taskBytes});
717
+ task : STRING(${taskNameLength});
690
718
  END_VAR
691
719
  VAR_OUTPUT
692
720
  scan : UDINT;
@@ -714,17 +742,17 @@ now := TIME_TO_UDINT(TIME());
714
742
  IF sending THEN
715
743
  client(start := TRUE, cancel := FALSE, body := batch);
716
744
  IF client.done THEN
717
- IF client.error = ${httpErrors.base + 400} THEN
745
+ IF client.error = ${httpErrors.refused} THEN
718
746
  dropped := dropped + (batched - sent);
719
747
  END_IF;
720
- IF client.error = 0 OR client.error = ${httpErrors.base + 400} THEN
748
+ IF client.error = 0 OR client.error = ${httpErrors.refused} THEN
721
749
  sent := batched;
722
750
  END_IF;
723
751
  sending := FALSE;
724
752
  lastSend := now;
725
753
  client(start := FALSE, cancel := FALSE, body := batch);
726
754
  END_IF;
727
- ELSIF head <> sent AND_THEN (head - sent >= ${batchRecords(recordBytes)} OR now - lastSend >= ${sendIntervalMs}) THEN
755
+ ELSIF head <> sent AND_THEN (head - sent >= ${batchRecords(recordBytes)} OR now - lastSend >= ${telemetrySendIntervalMs}) THEN
728
756
  Send();
729
757
  END_IF;
730
758
  `,
@@ -771,11 +799,7 @@ client(start := TRUE, cancel := FALSE, body := batch);
771
799
  method(
772
800
  "Commit",
773
801
  "VAR\n slot : UDINT;\nEND_VAR\n",
774
- `Append(',"scan":');
775
- Append(UDINT_TO_STRING(scan));
776
- Append(',"time":');
777
- Append(UDINT_TO_STRING(now));
778
- Append('}');
802
+ `${commitMembers.map(({ member, value }) => `Append(${stStringLiteral(member)});\nAppend(UDINT_TO_STRING(${value}));\n`).join("")}Append('}');
779
803
  slot := ULINT_TO_UDINT((head + 1) MOD ${capacity});
780
804
  records[slot].json := payload;
781
805
  records[slot].sequence := head + 1;
@@ -787,8 +811,8 @@ head := head + 1;
787
811
  "ErrorName",
788
812
  "VAR_INPUT\n code : UDINT;\nEND_VAR\n",
789
813
  `CASE code OF
790
- ${errorNames.map(([code, name]) => `${code}: Append(${stStringLiteral(`,"name":${asciiJson(name)}`)});`).join("\n")}
791
- ${httpErrors.base + 1}..${httpErrors.last}: Append(',"name":"HTTP '); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
814
+ ${errorNames.map(([code, name]) => `${code}: Append(${stStringLiteral(`${nameMember}${asciiJson(name)}`)});`).join("\n")}
815
+ ${httpErrors.base + 1}..${httpErrors.last}: Append(${stStringLiteral(`${nameMember}"HTTP `)}); Append(UDINT_TO_STRING(code - ${httpErrors.base})); Append('"');
792
816
  END_CASE;
793
817
  `,
794
818
  "PRIVATE ",
@@ -806,10 +830,23 @@ WriteString(text);
806
830
  `,
807
831
  "PRIVATE ",
808
832
  ),
809
- ...helpers,
833
+ ...jsonEncoders(telemetryWriter),
810
834
  ...calls,
811
835
  ...failures,
812
836
  ...trace,
813
837
  ...clientObjects,
814
838
  ];
815
839
  }
840
+
841
+ /** Writes the build id into the sender's batch header, where `telemetryObjects` left a placeholder. */
842
+ export function fillBuildId(
843
+ objects: readonly GeneratedObject[],
844
+ build: string,
845
+ ): void {
846
+ const send = objects.find(
847
+ (object) => object.id === `${telemetryWriter}:Send`,
848
+ );
849
+ if (send?.implementation !== undefined) {
850
+ send.implementation = send.implementation.replace(buildPlaceholder, build);
851
+ }
852
+ }