@tsplc/compiler 0.5.6 → 0.5.8

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 (49) hide show
  1. package/dist/bun-runtime.js +139 -30
  2. package/dist/bun-runtime.js.map +8 -7
  3. package/dist/cli.js +24 -9
  4. package/dist/cli.js.map +6 -6
  5. package/dist/codesys.js +3237 -1957
  6. package/dist/codesys.js.map +19 -18
  7. package/dist/index.js +54 -6
  8. package/dist/index.js.map +8 -8
  9. package/dist/ir.js +1645 -1326
  10. package/dist/ir.js.map +13 -12
  11. package/dist/project.js +12 -6
  12. package/dist/project.js.map +4 -4
  13. package/package.json +9 -9
  14. package/src/codesys/debug.ts +17 -2
  15. package/src/codesys/emit.ts +40 -12
  16. package/src/codesys/explain.ts +1465 -0
  17. package/src/codesys/global-lists.ts +21 -9
  18. package/src/codesys/http.ts +125 -71
  19. package/src/codesys/instrumentation.ts +161 -9
  20. package/src/codesys/manifest.ts +29 -12
  21. package/src/codesys/numeric.ts +5 -3
  22. package/src/codesys/plan.ts +22 -6
  23. package/src/codesys/programs.ts +2 -0
  24. package/src/codesys/routines.ts +39 -9
  25. package/src/codesys/st-files.ts +73 -6
  26. package/src/codesys/telemetry.ts +70 -35
  27. package/src/frontend/elaborate/index.ts +16 -1
  28. package/src/frontend/elaborate/storage.ts +56 -1
  29. package/src/frontend/expressions.ts +2 -2
  30. package/src/frontend/intrinsics.ts +1 -2
  31. package/src/frontend/statements.ts +3 -2
  32. package/src/frontend/typescript.ts +3 -0
  33. package/src/ir/conditions.ts +895 -0
  34. package/src/ir/core-model.ts +2 -2
  35. package/src/ir/fold.ts +15 -107
  36. package/src/ir/index.ts +10 -11
  37. package/src/ir/link.ts +1 -0
  38. package/src/ir/model.ts +16 -79
  39. package/src/ir/numeric.ts +5 -41
  40. package/src/ir/ranges.ts +8 -14
  41. package/src/ir/scalars.ts +6 -4
  42. package/src/project/debugger.ts +9 -0
  43. package/src/project/project.ts +6 -0
  44. package/src/project/release.ts +7 -4
  45. package/src/runtime/async.ts +15 -12
  46. package/src/runtime/launch.ts +11 -4
  47. package/src/runtime/runtime.ts +26 -23
  48. package/src/runtime/telemetry.ts +14 -6
  49. package/src/runtime/transport.ts +172 -0
@@ -1,6 +1,6 @@
1
+ import type { BinaryOperator, UnaryOperator } from "@tsplc/iec/arithmetic";
1
2
  import type { SourceSpan } from "./diagnostics";
2
3
  import type {
3
- BinaryOperator,
4
4
  Constant,
5
5
  FunctionBlock,
6
6
  MethodOwner,
@@ -8,7 +8,6 @@ import type {
8
8
  PlcModule,
9
9
  PlcProgram,
10
10
  TelemetryCall,
11
- UnaryOperator,
12
11
  Variable,
13
12
  } from "./model";
14
13
  import type { PlcType } from "./types";
@@ -164,6 +163,7 @@ export const verified: unique symbol = Symbol("verified core");
164
163
  export interface VerifiedCoreModule {
165
164
  readonly [verified]: true;
166
165
  readonly folded?: PlcModule["folded"];
166
+ readonly references?: PlcModule["references"];
167
167
  readonly types: readonly PlcType[];
168
168
  readonly variables: readonly Variable[];
169
169
  readonly functions: readonly CoreFunction[];
package/src/ir/fold.ts CHANGED
@@ -1,18 +1,17 @@
1
- import { nanosecondsPerMillisecond } from "./domains";
2
1
  import {
3
- type BinaryOperator,
4
- type Constant,
5
- type Expression,
2
+ applyIntegerPolicy,
3
+ booleanOperation,
4
+ compare,
6
5
  elementaryValue,
6
+ floatArithmetic,
7
+ integerArithmetic,
7
8
  isElementary,
8
- type Variable,
9
- } from "./model";
10
- import {
11
- applyIntegerPolicy,
12
- integerType,
13
9
  roundFloat,
14
10
  saturateFloat,
15
- } from "./numeric";
11
+ } from "@tsplc/iec/arithmetic";
12
+ import { nanosecondsPerMillisecond } from "./domains";
13
+ import type { Constant, Expression, Variable } from "./model";
14
+ import { integerType } from "./numeric";
16
15
  import type { PlcType } from "./types";
17
16
 
18
17
  type Types = ReadonlyMap<string, PlcType> | undefined;
@@ -215,7 +214,12 @@ const foldBinary = (
215
214
  target: PlcType | undefined,
216
215
  ): Constant | undefined => {
217
216
  if (left.kind === "bool" && right.kind === "bool") {
218
- return foldLogical(expression.operator, left.value, right.value);
217
+ const value = booleanOperation(
218
+ expression.operator,
219
+ left.value,
220
+ right.value,
221
+ );
222
+ return value === undefined ? undefined : { kind: "bool", value };
219
223
  }
220
224
  if (left.kind !== right.kind || !ordered(left) || !ordered(right)) {
221
225
  return undefined;
@@ -258,102 +262,6 @@ const foldBinary = (
258
262
  return undefined;
259
263
  };
260
264
 
261
- const foldLogical = (
262
- operator: BinaryOperator,
263
- left: boolean,
264
- right: boolean,
265
- ): Constant | undefined => {
266
- switch (operator) {
267
- case "and":
268
- return { kind: "bool", value: left && right };
269
- case "or":
270
- return { kind: "bool", value: left || right };
271
- case "equal":
272
- return { kind: "bool", value: left === right };
273
- case "notEqual":
274
- return { kind: "bool", value: left !== right };
275
- default:
276
- return undefined;
277
- }
278
- };
279
-
280
- const compare = <Value extends bigint | number | string>(
281
- operator: BinaryOperator,
282
- left: Value,
283
- right: Value,
284
- ): boolean | undefined => {
285
- switch (operator) {
286
- case "equal":
287
- return left === right;
288
- case "notEqual":
289
- return left !== right;
290
- case "less":
291
- return left < right;
292
- case "lessEqual":
293
- return left <= right;
294
- case "greater":
295
- return left > right;
296
- case "greaterEqual":
297
- return left >= right;
298
- default:
299
- return undefined;
300
- }
301
- };
302
-
303
- const integerArithmetic = (
304
- operator: BinaryOperator,
305
- left: bigint,
306
- right: bigint,
307
- ): bigint | undefined => {
308
- switch (operator) {
309
- case "add":
310
- return left + right;
311
- case "subtract":
312
- return left - right;
313
- case "multiply":
314
- return left * right;
315
- case "divide":
316
- return right === 0n ? undefined : left / right;
317
- case "remainder":
318
- return right === 0n ? undefined : left % right;
319
- case "bitAnd":
320
- return left & right;
321
- case "bitOr":
322
- return left | right;
323
- case "bitXor":
324
- return left ^ right;
325
- case "shiftLeft":
326
- return right < 0n || right > 63n ? undefined : left << right;
327
- case "shiftRight":
328
- return right < 0n || right > 63n ? undefined : left >> right;
329
- default:
330
- return undefined;
331
- }
332
- };
333
-
334
- const floatArithmetic = (
335
- operator: BinaryOperator,
336
- left: number,
337
- right: number,
338
- ): number | undefined => {
339
- switch (operator) {
340
- case "add":
341
- return left + right;
342
- case "subtract":
343
- return left - right;
344
- case "multiply":
345
- return left * right;
346
- case "divide":
347
- return left / right;
348
- case "remainder":
349
- return left % right;
350
- case "power":
351
- return left ** right;
352
- default:
353
- return undefined;
354
- }
355
- };
356
-
357
265
  /** A float result as its type holds it, or nothing when it isn't finite, as NaN and infinities aren't constants. */
358
266
  const finiteFloat = (
359
267
  value: number,
package/src/ir/index.ts CHANGED
@@ -6,6 +6,16 @@ export {
6
6
  placeType,
7
7
  valueFits,
8
8
  } from "./aggregates";
9
+ export {
10
+ type LoopConditions,
11
+ type PathCondition,
12
+ pathConditions,
13
+ projectReconstruction,
14
+ type ReconstructedSegment,
15
+ type Reconstruction,
16
+ type RoutineConditions,
17
+ type StatementConditions,
18
+ } from "./conditions";
9
19
  export {
10
20
  type CheckedPlace,
11
21
  type CoreExpression,
@@ -36,18 +46,13 @@ export { errorName, httpErrors, jobError, jobErrors } from "./job-errors";
36
46
  export { layoutIssue, maxNestingDepth, maxScalarElements } from "./layouts";
37
47
  export {
38
48
  type Artifact,
39
- type BinaryOperator,
40
49
  type Constant,
41
50
  comparisonOperators,
42
51
  type Deployment,
43
- type ElementaryFunction,
44
52
  type EmitResult,
45
53
  type Expression,
46
- elementaryFunctions,
47
- elementaryValue,
48
54
  type FunctionBlock,
49
55
  type GeneratedObject,
50
- isElementary,
51
56
  type MathHelper,
52
57
  type MethodOwner,
53
58
  type Place,
@@ -60,20 +65,15 @@ export {
60
65
  type Task,
61
66
  type TelemetryCall,
62
67
  telemetryOperands,
63
- type UnaryOperator,
64
68
  type Variable,
65
69
  } from "./model";
66
70
  export { isVerifiedCore, normalizeModule } from "./normalize";
67
71
  export {
68
- applyIntegerPolicy,
69
72
  canAssign,
70
73
  constantFits,
71
- floatMaximum,
72
74
  type IntegerInterval,
73
75
  integerType,
74
76
  parseInteger,
75
- roundFloat,
76
- saturateFloat,
77
77
  wrapsNatively,
78
78
  } from "./numeric";
79
79
  export {
@@ -84,7 +84,6 @@ export {
84
84
  export {
85
85
  interval,
86
86
  loopBounds,
87
- loopIterations,
88
87
  maxLoopIterations,
89
88
  narrowRanges,
90
89
  valueRange,
package/src/ir/link.ts CHANGED
@@ -55,6 +55,7 @@ export function linkModule(
55
55
  blocks: linkedBlocks,
56
56
  programs: module.programs,
57
57
  ...(module.folded && { folded: module.folded }),
58
+ ...(module.references && { references: module.references }),
58
59
  };
59
60
  }
60
61
 
package/src/ir/model.ts CHANGED
@@ -1,3 +1,8 @@
1
+ import {
2
+ type BinaryOperator,
3
+ comparisonOperatorNames,
4
+ type UnaryOperator,
5
+ } from "@tsplc/iec/arithmetic";
1
6
  import type { Diagnostic, SourceSpan } from "./diagnostics";
2
7
  import type { PlcType, SymbolId, TypeId } from "./types";
3
8
 
@@ -42,85 +47,9 @@ export interface Place {
42
47
  )[];
43
48
  }
44
49
 
45
- /**
46
- * The elementary functions on REAL and LREAL, Structured Text's SQRT, LN, LOG, EXP and the
47
- * trigonometric functions; each returns its operand's type.
48
- */
49
- export const elementaryFunctions = [
50
- "sqrt",
51
- "ln",
52
- "log10",
53
- "exp",
54
- "sin",
55
- "cos",
56
- "tan",
57
- "asin",
58
- "acos",
59
- "atan",
60
- ] as const;
61
- export type ElementaryFunction = (typeof elementaryFunctions)[number];
62
-
63
- /** Each elementary function as JavaScript computes it, which constants fold and simulations run with. */
64
- export const elementaryValue: Readonly<
65
- Record<ElementaryFunction, (value: number) => number>
66
- > = {
67
- sqrt: Math.sqrt,
68
- ln: Math.log,
69
- log10: Math.log10,
70
- exp: Math.exp,
71
- sin: Math.sin,
72
- cos: Math.cos,
73
- tan: Math.tan,
74
- asin: Math.asin,
75
- acos: Math.acos,
76
- atan: Math.atan,
77
- };
78
-
79
- export const isElementary = (
80
- operator: string,
81
- ): operator is ElementaryFunction =>
82
- (elementaryFunctions as readonly string[]).includes(operator);
83
-
84
- /** `truncate` is TRUNC, a REAL or LREAL toward zero as DINT. */
85
- export type UnaryOperator =
86
- | "not"
87
- | "negate"
88
- | "bitNot"
89
- | "timeToMilliseconds"
90
- | "clock"
91
- | "truncate"
92
- | ElementaryFunction;
93
-
94
- /** `power` is EXPT on REAL or LREAL. */
95
- export type BinaryOperator =
96
- | "add"
97
- | "subtract"
98
- | "multiply"
99
- | "divide"
100
- | "remainder"
101
- | "equal"
102
- | "notEqual"
103
- | "less"
104
- | "lessEqual"
105
- | "greater"
106
- | "greaterEqual"
107
- | "and"
108
- | "or"
109
- | "bitAnd"
110
- | "bitOr"
111
- | "bitXor"
112
- | "shiftLeft"
113
- | "shiftRight"
114
- | "power";
115
-
116
- export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set([
117
- "equal",
118
- "notEqual",
119
- "less",
120
- "lessEqual",
121
- "greater",
122
- "greaterEqual",
123
- ]);
50
+ export const comparisonOperators: ReadonlySet<BinaryOperator> = new Set(
51
+ comparisonOperatorNames,
52
+ );
124
53
 
125
54
  export type Expression = { type: TypeId; span: SourceSpan } & (
126
55
  | { kind: "constant"; value: Constant }
@@ -392,6 +321,14 @@ export interface PlcModule {
392
321
  type?: TypeId;
393
322
  span: SourceSpan;
394
323
  }[];
324
+ /**
325
+ * Object references: the module storage path of each object by the id a reference holds (−1 is
326
+ * `undefined`), and the storage paths of the fields that hold a reference.
327
+ */
328
+ references?: {
329
+ objects: readonly { id: number; path: string }[];
330
+ fields: readonly string[];
331
+ };
395
332
  types: readonly PlcType[];
396
333
  variables: readonly Variable[];
397
334
  functions: readonly PlcFunction[];
package/src/ir/numeric.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
+ import { roundFloat } from "@tsplc/iec/arithmetic";
2
3
  import type { Constant } from "./model";
3
4
  import { integerRange, type PlcType } from "./types";
4
5
 
@@ -26,36 +27,13 @@ export const canonicalInteger = /^(?:0|-?[1-9][0-9]*)$/;
26
27
  export const integerType = (type: PlcType): type is IntegerType =>
27
28
  type.kind === "integer" || type.kind === "bits";
28
29
 
29
- // IEEE 754 binary32 (REAL) and binary64 (LREAL): the largest finite value, and the significand
30
- // precision, which bounds the integers the format holds exactly.
31
- const floatFormats = {
32
- 32: { maximum: Math.fround((2 - 2 ** -23) * 2 ** 127), precision: 24 },
33
- 64: { maximum: Number.MAX_VALUE, precision: 53 },
34
- } as const;
35
-
36
- export const floatMaximum = (type: FloatType): number =>
37
- floatFormats[type.bits].maximum;
30
+ // The significand precision of REAL (IEEE 754 binary32) and LREAL (binary64), which bounds the
31
+ // integers each format holds exactly.
32
+ const floatPrecision = { 32: 24, 64: 53 } as const;
38
33
 
39
34
  /** Every integer from minus this limit to this limit converts to the float type exactly. */
40
35
  export const exactIntegerLimit = (type: FloatType): bigint =>
41
- 1n << BigInt(floatFormats[type.bits].precision);
42
-
43
- /** The nearest value of the float type, as each typed REAL result rounds. */
44
- export const roundFloat = (value: number, type: FloatType): number =>
45
- type.bits === 32 ? Math.fround(value) : value;
46
-
47
- export const saturateFloat = (value: number, type: FloatType): number => {
48
- // Clamp before target rounding so a finite source cannot round to infinity.
49
- // Comparisons leave signed zero intact; min/max substitution is unnecessary.
50
- const maximum = floatMaximum(type);
51
- if (value < -maximum) {
52
- return -maximum;
53
- }
54
- if (value > maximum) {
55
- return maximum;
56
- }
57
- return roundFloat(value, type);
58
- };
36
+ 1n << BigInt(floatPrecision[type.bits]);
59
37
 
60
38
  type DecimalIssue = "malformed" | "exponent" | "fraction";
61
39
 
@@ -156,17 +134,3 @@ export const wrapsNatively = (expression: {
156
134
  (expression.operator === "add" ||
157
135
  expression.operator === "subtract" ||
158
136
  expression.operator === "multiply");
159
-
160
- export const applyIntegerPolicy = (
161
- value: bigint,
162
- type: IntegerType,
163
- policy: "wrap" | "saturate",
164
- ): bigint => {
165
- if (policy === "saturate") {
166
- const [minimum, maximum] = integerRange(type);
167
- return highest(minimum, lowest(value, maximum));
168
- }
169
- return type.kind === "integer" && type.signed
170
- ? BigInt.asIntN(type.bits, value)
171
- : BigInt.asUintN(type.bits, value);
172
- };
package/src/ir/ranges.ts CHANGED
@@ -1,5 +1,6 @@
1
+ import { type BinaryOperator, loopIterations } from "@tsplc/iec/arithmetic";
1
2
  import { fold } from "./fold";
2
- import type { BinaryOperator, Expression, MathHelper, Variable } from "./model";
3
+ import type { Expression, MathHelper, Variable } from "./model";
3
4
  import {
4
5
  admits,
5
6
  highest,
@@ -101,18 +102,6 @@ const arithmeticInterval = (
101
102
  /** The most iterations a bounded loop may prove. */
102
103
  export const maxLoopIterations = 1_000_000n;
103
104
 
104
- // FOR iterations from first to last inclusive; step is nonzero.
105
- export const loopIterations = (
106
- first: bigint,
107
- last: bigint,
108
- step: bigint,
109
- ): bigint => {
110
- if (step > 0n) {
111
- return last >= first ? (last - first) / step + 1n : 0n;
112
- }
113
- return last <= first ? (first - last) / -step + 1n : 0n;
114
- };
115
-
116
105
  export const loopBounds = (
117
106
  start: IntegerInterval,
118
107
  limit: IntegerInterval,
@@ -122,7 +111,12 @@ export const loopBounds = (
122
111
  const excluded = exclusive ? 1n : 0n;
123
112
  const first = step > 0n ? start[0] : start[1];
124
113
  const last = step > 0n ? limit[1] - excluded : limit[0] + excluded;
125
- const count = loopIterations(first, last, step);
114
+ const count = loopIterations(
115
+ first,
116
+ limit[step > 0n ? 1 : 0],
117
+ exclusive,
118
+ step,
119
+ );
126
120
  const range: IntegerInterval = first <= last ? [first, last] : [last, first];
127
121
  return { first, last, count, range };
128
122
  };
package/src/ir/scalars.ts CHANGED
@@ -1,10 +1,14 @@
1
+ import {
2
+ type ElementaryFunction,
3
+ floatMaximum,
4
+ isElementary,
5
+ roundFloat,
6
+ } from "@tsplc/iec/arithmetic";
1
7
  import { fold } from "./fold";
2
8
  import {
3
9
  type Constant,
4
10
  comparisonOperators,
5
- type ElementaryFunction,
6
11
  type Expression,
7
- isElementary,
8
12
  type Variable,
9
13
  } from "./model";
10
14
  import {
@@ -12,10 +16,8 @@ import {
12
16
  canAssign,
13
17
  constantFits,
14
18
  exactIntegerLimit,
15
- floatMaximum,
16
19
  type IntegerInterval,
17
20
  integerType,
18
- roundFloat,
19
21
  within,
20
22
  wrapsNatively,
21
23
  } from "./numeric";
@@ -10,6 +10,7 @@ import {
10
10
  createDebugger,
11
11
  createLoginAdapter,
12
12
  createOpcUaAdapter,
13
+ loadExplanations,
13
14
  loadManifest,
14
15
  opcUaConnection,
15
16
  serveDebugger,
@@ -70,6 +71,14 @@ export async function serveProjectDebugger(
70
71
  watch: config.debug?.watch ?? {},
71
72
  ...(serverUrl && token && { server: { url: serverUrl, token } }),
72
73
  projectRoot: root,
74
+ explanations: await loadExplanations(file, manifest),
75
+ // The forced list comes from the agent's login; an OPC UA endpoint has no such list.
76
+ forced: flags.opcua
77
+ ? null
78
+ : async () => {
79
+ const { login } = await connect(env).status();
80
+ return login && "forced" in login ? login.forced : null;
81
+ },
73
82
  log,
74
83
  });
75
84
  const server = serveDebugger(debug, { port: port.data, log });
@@ -42,6 +42,7 @@ import {
42
42
  simulationConfig,
43
43
  } from "@tsplc/config";
44
44
  import { emittedFiles, emittedStDirectory } from "@tsplc/config/project-files";
45
+ import { explainFileName } from "@tsplc/debug/explain-file";
45
46
  import { debugManifestFile } from "@tsplc/debug/manifest";
46
47
  import {
47
48
  deviceTree,
@@ -152,6 +153,7 @@ async function loadProject(
152
153
  ...(shared.debug && { debug: shared.debug }),
153
154
  ...(shared.telemetry && { telemetry: shared.telemetry }),
154
155
  ...(shared.server && { server: shared.server }),
156
+ ...(shared.hmi && { hmi: shared.hmi }),
155
157
  // A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.
156
158
  hardware: {
157
159
  catalog: configured ? await loadHardware(configured, root) : catalog,
@@ -390,6 +392,10 @@ export async function buildProject(
390
392
  },
391
393
  ]
392
394
  : []),
395
+ // The manifest's digest covers these exact bytes.
396
+ ...(bundle.explain === undefined
397
+ ? []
398
+ : [{ path: explainFileName, content: bundle.explain }]),
393
399
  ];
394
400
  const stagedSt = join(staging, emittedSt);
395
401
  // Thousands of artifacts share a few hundred directories; each is made once.
@@ -12,6 +12,7 @@ import {
12
12
  serverTokenEnv,
13
13
  } from "@tsplc/config";
14
14
  import type { ReleaseConfig } from "@tsplc/config/build";
15
+ import { explainFileName } from "@tsplc/debug/explain-file";
15
16
  import { debugManifestFile } from "@tsplc/debug/manifest";
16
17
  import { contractVariables, plcContractSchema } from "@tsplc/opcua/contract";
17
18
  import { generatedFiles, generateProject } from "@tsplc/typegen";
@@ -96,10 +97,12 @@ export const prepareRelease = async (
96
97
  content: Bun.file(resolve(settings.sourceDir, source)),
97
98
  });
98
99
  }
99
- // The agent's debugger reads the program through its debug manifest.
100
- const debugManifest = resolve(settings.sourceDir, debugManifestFile);
101
- if (existsSync(debugManifest)) {
102
- files.push({ path: debugManifestFile, content: Bun.file(debugManifest) });
100
+ // The agent's debugger reads the program through its debug manifest, and explains it with `explain.json`.
101
+ for (const name of [debugManifestFile, explainFileName]) {
102
+ const path = resolve(settings.sourceDir, name);
103
+ if (existsSync(path)) {
104
+ files.push({ path: name, content: Bun.file(path) });
105
+ }
103
106
  }
104
107
  const serverScript =
105
108
  serverCheck && (await bundleServer(await serverCheck, config, root));
@@ -1,17 +1,22 @@
1
1
  import { httpErrors, jobError } from "@tsplc/compiler/ir";
2
2
  import { plcBufferBytes } from "@tsplc/server/wire";
3
+ import type { Transport } from "./transport";
3
4
 
4
5
  /** How the program's HTTP calls reach their servers, as the build compiled them. */
5
6
  export interface HttpSettings {
6
- /** The services' base URL, from `server.baseUrlEnv`; null without a server. */
7
- baseUrl: string | null;
8
- /** Each service procedure's route, by its path such as `catalog.resolve`. */
9
- routes: Readonly<Record<string, string>>;
10
7
  /** Bearer tokens by the exact origin they are sent to. */
11
8
  tokens: ReadonlyMap<string, string>;
12
9
  timeoutMs: number;
13
10
  }
14
11
 
12
+ /** How the program's service calls reach the app server. */
13
+ export interface ServiceSettings {
14
+ /** Each service procedure's route, by its path such as `catalog.resolve`. */
15
+ routes: Readonly<Record<string, string>>;
16
+ /** The configured transport; null when HTTP has no server base URL to send to. */
17
+ transport: Transport | null;
18
+ }
19
+
15
20
  /** Why the program's call failed, as a compiled call reports it: a job error code. */
16
21
  const failure = (cause: unknown) => {
17
22
  if (cause instanceof Error && cause.name === "TimeoutError") {
@@ -89,20 +94,18 @@ export const unsupported = (name: string) => () => {
89
94
 
90
95
  /** What the program's `@tsplc/compiler/async` does in the Bun runtime. */
91
96
  export const createAsync = (
92
- settings: HttpSettings,
97
+ settings: { http: HttpSettings; services: ServiceSettings },
93
98
  diagnostics: { count: number; lastError: number },
94
99
  ) => {
95
100
  const call = (path: string, input: unknown) => {
96
- const route = settings.routes[path];
97
- if (!route || settings.baseUrl === null) {
101
+ const route = settings.services.routes[path];
102
+ const { transport } = settings.services;
103
+ if (!route || !transport) {
98
104
  return Promise.reject(
99
105
  new Error(`The build compiled no call to the service ${path}.`),
100
106
  );
101
107
  }
102
- return httpCall(settings, `${settings.baseUrl}${route}`, {
103
- method: "POST",
104
- body: JSON.stringify(input),
105
- });
108
+ return transport.call(route, JSON.stringify(input));
106
109
  };
107
110
  /** A service client: any property is a deeper procedure path, and calling one calls that procedure. */
108
111
  const client = (path: readonly string[]): unknown =>
@@ -114,7 +117,7 @@ export const createAsync = (
114
117
  return {
115
118
  createServiceClient: () => client([]),
116
119
  fetch: (url: string, options: { method?: string; json?: unknown } = {}) =>
117
- httpCall(settings, url, {
120
+ httpCall(settings.http, url, {
118
121
  method: options.method ?? "GET",
119
122
  ...(options.json !== undefined && {
120
123
  body: JSON.stringify(options.json),
@@ -35,14 +35,21 @@ export const runtimeStateSchema = z.strictObject({
35
35
  });
36
36
  export type RuntimeState = z.infer<typeof runtimeStateSchema>;
37
37
 
38
+ /** A service block's route: its URL's path over HTTP, the path its slots carry over OPC UA. */
39
+ const blockRoute = (
40
+ runtime: VerifiedCoreModule["blocks"][number]["runtime"],
41
+ ) => {
42
+ if (runtime?.kind === "http") {
43
+ return URL.parse(runtime.url)?.pathname;
44
+ }
45
+ return runtime?.kind === "rpc" ? runtime.path : undefined;
46
+ };
47
+
38
48
  /** The route each service call the program makes goes to, as the build compiled it. */
39
49
  export const serviceRoutes = (core: VerifiedCoreModule) =>
40
50
  Object.fromEntries(
41
51
  core.blocks.flatMap((block) => {
42
- if (block.runtime?.kind !== "http") {
43
- return [];
44
- }
45
- const route = URL.parse(block.runtime.url)?.pathname;
52
+ const route = blockRoute(block.runtime);
46
53
  const procedure = route && serviceOfPath(route);
47
54
  return route && procedure ? [[procedure, route] as const] : [];
48
55
  }),