@tsplc/compiler 0.5.5 → 0.5.7

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 (80) hide show
  1. package/dist/bun-runtime.js +152 -31
  2. package/dist/bun-runtime.js.map +10 -9
  3. package/dist/cli.js +8 -5
  4. package/dist/cli.js.map +3 -3
  5. package/dist/codesys.js +260 -85
  6. package/dist/codesys.js.map +9 -9
  7. package/dist/collections.js +395 -0
  8. package/dist/collections.js.map +10 -0
  9. package/dist/elaborate-capture.js +62 -4
  10. package/dist/elaborate-capture.js.map +4 -4
  11. package/dist/index.js +5322 -1058
  12. package/dist/index.js.map +30 -23
  13. package/dist/ir.js +122 -1
  14. package/dist/ir.js.map +6 -6
  15. package/dist/project.js +8 -5
  16. package/dist/project.js.map +3 -3
  17. package/package.json +14 -9
  18. package/src/codesys/emit.ts +8 -2
  19. package/src/codesys/http.ts +114 -72
  20. package/src/codesys/instrumentation.ts +30 -6
  21. package/src/codesys/numeric.ts +61 -0
  22. package/src/codesys/routines.ts +39 -9
  23. package/src/codesys/st-files.ts +73 -6
  24. package/src/codesys/telemetry.ts +70 -35
  25. package/src/frontend/control-flow.ts +752 -0
  26. package/src/frontend/coroutines.ts +171 -7
  27. package/src/frontend/elaborate/array-searches.ts +216 -0
  28. package/src/frontend/elaborate/assignments.ts +352 -0
  29. package/src/frontend/elaborate/calls.ts +467 -42
  30. package/src/frontend/elaborate/capture-protocol.ts +19 -0
  31. package/src/frontend/elaborate/capture.ts +80 -2
  32. package/src/frontend/elaborate/dialect.ts +116 -2
  33. package/src/frontend/elaborate/expressions.ts +927 -80
  34. package/src/frontend/elaborate/filtered-arrays.ts +607 -0
  35. package/src/frontend/elaborate/frame.ts +44 -1
  36. package/src/frontend/elaborate/generics.ts +137 -0
  37. package/src/frontend/elaborate/graph.ts +91 -0
  38. package/src/frontend/elaborate/index.ts +30 -5
  39. package/src/frontend/elaborate/initializers.ts +15 -1
  40. package/src/frontend/elaborate/iterators.ts +1677 -0
  41. package/src/frontend/elaborate/layouts.ts +41 -19
  42. package/src/frontend/elaborate/model.ts +64 -8
  43. package/src/frontend/elaborate/references.ts +749 -0
  44. package/src/frontend/elaborate/specialize.ts +459 -29
  45. package/src/frontend/elaborate/statements.ts +552 -133
  46. package/src/frontend/elaborate/storage.ts +151 -10
  47. package/src/frontend/elaborate/values.ts +72 -0
  48. package/src/frontend/elaborate/writes.ts +302 -1
  49. package/src/frontend/intrinsics.ts +32 -0
  50. package/src/frontend/module-graph.ts +2 -1
  51. package/src/frontend/positions.ts +12 -5
  52. package/src/frontend/typescript.ts +5 -1
  53. package/src/ir/core-model.ts +2 -6
  54. package/src/ir/fold.ts +30 -1
  55. package/src/ir/index.ts +5 -0
  56. package/src/ir/model.ts +53 -2
  57. package/src/ir/scalars.ts +126 -0
  58. package/src/runtime/.runtime-VaUSOu/server/router.ts +17 -0
  59. package/src/runtime/.runtime-VaUSOu/src/cell.ts +45 -0
  60. package/src/runtime/.runtime-VaUSOu/src/controller.ts +58 -0
  61. package/src/runtime/.runtime-VaUSOu/src/lane.ts +6 -0
  62. package/src/runtime/.runtime-VaUSOu/src/main.ts +11 -0
  63. package/src/runtime/.runtime-VaUSOu/src/services.ts +8 -0
  64. package/src/runtime/.runtime-VaUSOu/tsconfig.json +13 -0
  65. package/src/runtime/.runtime-VaUSOu/tsplc.config.ts +31 -0
  66. package/src/runtime/.runtime-ybIxYh/server/router.ts +17 -0
  67. package/src/runtime/.runtime-ybIxYh/src/cell.ts +45 -0
  68. package/src/runtime/.runtime-ybIxYh/src/controller.ts +58 -0
  69. package/src/runtime/.runtime-ybIxYh/src/lane.ts +6 -0
  70. package/src/runtime/.runtime-ybIxYh/src/main.ts +11 -0
  71. package/src/runtime/.runtime-ybIxYh/src/services.ts +8 -0
  72. package/src/runtime/.runtime-ybIxYh/tsconfig.json +13 -0
  73. package/src/runtime/.runtime-ybIxYh/tsplc.config.ts +31 -0
  74. package/src/runtime/async.ts +15 -12
  75. package/src/runtime/launch.ts +11 -4
  76. package/src/runtime/runtime.ts +26 -23
  77. package/src/runtime/telemetry.ts +14 -6
  78. package/src/runtime/transport.ts +172 -0
  79. package/stdlib/collections.ts +514 -0
  80. package/types/index.d.ts +18 -0
@@ -0,0 +1,45 @@
1
+ import { retain } from "@tsplc/compiler/retain";
2
+ import { Lane } from "./lane";
3
+
4
+ export type Mode = "idle" | "running";
5
+
6
+ export interface Card {
7
+ input: { sensor: BOOL };
8
+ output: { motion: BOOL; speed: INT };
9
+ }
10
+
11
+ /** The cell's IO, its operator's controls and its counts: what the program publishes. */
12
+ export interface Cell {
13
+ cards: Card[];
14
+ mode: Mode;
15
+ start: BOOL;
16
+ bump: BOOL;
17
+ count: UINT;
18
+ scans: UDINT;
19
+ lanes: Record<Lane, BOOL>;
20
+ lastLane: Lane | undefined;
21
+ report: BOOL;
22
+ replies: UDINT;
23
+ answer: DINT;
24
+ failures: UDINT;
25
+ settings: { speed: INT };
26
+ }
27
+
28
+ export const createCell = (): Cell => ({
29
+ cards: Array.from({ length: 3 }, () => ({
30
+ input: { sensor: false },
31
+ output: { motion: false, speed: 0 },
32
+ })),
33
+ mode: "idle",
34
+ start: false,
35
+ bump: false,
36
+ count: 0,
37
+ scans: 0,
38
+ lanes: { [Lane.Unknown]: false, [Lane.Left]: false, [Lane.Right]: false },
39
+ lastLane: undefined,
40
+ report: false,
41
+ replies: 0,
42
+ answer: 0,
43
+ failures: 0,
44
+ settings: retain({ speed: 50 }),
45
+ });
@@ -0,0 +1,58 @@
1
+ import { telemetry } from "@tsplc/compiler/telemetry";
2
+ import type { Cell } from "./cell";
3
+ import { Lane } from "./lane";
4
+ import type { ReportReply, Services } from "./services";
5
+
6
+ export class CellController {
7
+ private sending = false;
8
+
9
+ constructor(
10
+ private readonly cell: Cell,
11
+ private readonly services: Services,
12
+ ) {}
13
+
14
+ scan(): void {
15
+ const cell = this.cell;
16
+ cell.scans += 1;
17
+ for (const card of cell.cards) {
18
+ card.output.motion = card.input.sensor && cell.mode === "running";
19
+ card.output.speed = card.input.sensor ? cell.settings.speed : 0;
20
+ }
21
+ if (cell.start) {
22
+ cell.start = false;
23
+ cell.mode = "running";
24
+ }
25
+ if (cell.bump) {
26
+ cell.bump = false;
27
+ cell.count = cell.count + 1;
28
+ }
29
+ cell.lastLane = undefined;
30
+ if (cell.lanes[Lane.Left]) {
31
+ cell.lastLane = Lane.Left;
32
+ }
33
+ if (cell.lanes[Lane.Right]) {
34
+ cell.lastLane = Lane.Right;
35
+ }
36
+ if (cell.report && !this.sending) {
37
+ cell.report = false;
38
+ void this.send();
39
+ }
40
+ }
41
+
42
+ private async send(): Promise<void> {
43
+ this.sending = true;
44
+ try {
45
+ const reply: ReportReply = await this.services.cell.report({
46
+ count: this.cell.count,
47
+ running: this.cell.mode === "running",
48
+ });
49
+ this.cell.replies += 1;
50
+ this.cell.answer = reply.answer;
51
+ telemetry.info("Report answered", { answer: reply.answer });
52
+ } catch (error) {
53
+ this.cell.failures += 1;
54
+ telemetry.captureException(error);
55
+ }
56
+ this.sending = false;
57
+ }
58
+ }
@@ -0,0 +1,6 @@
1
+ /** Where the cell sends a part. */
2
+ export enum Lane {
3
+ Unknown = 0,
4
+ Left = 1,
5
+ Right = 2,
6
+ }
@@ -0,0 +1,11 @@
1
+ import { createCell } from "./cell";
2
+ import { CellController } from "./controller";
3
+ import { services } from "./services";
4
+
5
+ export const cell = createCell();
6
+ const controller = new CellController(cell, services);
7
+
8
+ /** One PLC scan. */
9
+ export function main(): void {
10
+ controller.scan();
11
+ }
@@ -0,0 +1,8 @@
1
+ import type { inferRouterOutputs } from "@trpc/server";
2
+ import { createServiceClient } from "@tsplc/compiler/async";
3
+ import type { AppRouter } from "../server/router";
4
+
5
+ /** The server procedures the program calls. */
6
+ export const services = createServiceClient<AppRouter>();
7
+ export type Services = typeof services;
8
+ export type ReportReply = inferRouterOutputs<AppRouter>["cell"]["report"];
@@ -0,0 +1,13 @@
1
+ {
2
+ "compilerOptions": {
3
+ "strict": true,
4
+ "target": "ES2022",
5
+ "module": "ESNext",
6
+ "moduleResolution": "Bundler",
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["bun", "@tsplc/compiler/globals"],
10
+ "allowImportingTsExtensions": true
11
+ },
12
+ "include": ["src/**/*.ts", "server/**/*.ts"]
13
+ }
@@ -0,0 +1,31 @@
1
+ import { defineConfig, ms } from "@tsplc/config";
2
+
3
+ /** A cell whose plain TypeScript program the Bun runtime runs in the compiler's tests. */
4
+ export default defineConfig({
5
+ name: "BunRuntimeCell",
6
+ backend: "codesys",
7
+ build: { outDir: "build/codesys", symbols: true },
8
+ codesys: {
9
+ http: {
10
+ timeoutMs: 2000,
11
+ credentials: [
12
+ { originEnv: "CELL_SERVER_URL", bearerTokenEnv: "CELL_SERVER_TOKEN" },
13
+ ],
14
+ },
15
+ programNames: { main: "Main" },
16
+ },
17
+ compiler: {
18
+ programs: { main: { module: "src/main.ts", export: "main" } },
19
+ },
20
+ tasks: [
21
+ {
22
+ name: "MainTask",
23
+ priority: 1,
24
+ schedule: { kind: "cyclic", interval: ms(20) },
25
+ programs: ["main"],
26
+ },
27
+ ],
28
+ publish: { development: ["cell"], production: ["cell"] },
29
+ server: { transport: "http", baseUrlEnv: "CELL_SERVER_URL" },
30
+ typegen: { dir: "generated" },
31
+ });
@@ -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
  }),
@@ -13,13 +13,19 @@ import { now } from "../../stdlib/clock";
13
13
  import { clamp, max, min } from "../../stdlib/math";
14
14
  import { retain } from "../../stdlib/retain";
15
15
  import { onTelemetry, telemetry } from "../../stdlib/telemetry";
16
- import { createAsync, httpCall, oneLaunchAtATime, unsupported } from "./async";
16
+ import {
17
+ createAsync,
18
+ type HttpSettings,
19
+ oneLaunchAtATime,
20
+ unsupported,
21
+ } from "./async";
17
22
  import { type Launch, runtimeDirectory, runtimeFiles } from "./launch";
18
23
  import { loadProgram } from "./program";
19
24
  import { createRetention } from "./retain";
20
25
  import { createStorage } from "./storage";
21
26
  import { plcGlobals, scalarPaths } from "./symbols";
22
27
  import { createTelemetry } from "./telemetry";
28
+ import { httpTransport, opcuaSlots, readServiceChannels } from "./transport";
23
29
 
24
30
  /** Where the runtime publishes OPC UA: the local CODESYS runtime's address and port. */
25
31
  export const runtimeEndpoint = { host: "127.0.0.1", port: 4840 } as const;
@@ -55,8 +61,8 @@ const projectSource = (root: string, source: unknown) => {
55
61
  /**
56
62
  * Runs a project's PLC program in this Bun process, as `tsplc run --bun` does: each task's programs
57
63
  * scan to completion on the task's cycle, services and telemetry go to the project's server over
58
- * HTTP as the compiled program sends them, and the development publication is served over OPC UA
59
- * as the local CODESYS runtime serves it. Reads the last build's artifacts.
64
+ * `server.transport` as the compiled program sends them, and the development publication is served
65
+ * over OPC UA as the local CODESYS runtime serves it. Reads the last build's artifacts.
60
66
  */
61
67
  export const startRuntime = async (options: RuntimeOptions) => {
62
68
  const { launch, log } = options;
@@ -69,22 +75,13 @@ export const startRuntime = async (options: RuntimeOptions) => {
69
75
  if (!compiler || !tasks) {
70
76
  throw new Error("The Bun runtime runs a TypeScript program.");
71
77
  }
72
- if (config.server?.transport === "opcua") {
73
- throw new Error(
74
- "The Bun runtime calls services over HTTP; this program calls them through the OPC UA gateway.",
75
- );
76
- }
77
78
  const st = resolve(root, emittedStDirectory);
78
79
  const manifest = debugManifest.parse(
79
80
  JSON.parse(await readFile(join(st, debugManifestFile), "utf8")),
80
81
  );
81
82
  const globals = plcGlobals(await readDeclarations(st));
82
83
 
83
- const baseUrlEnv = config.server?.baseUrlEnv;
84
- const baseUrl = (baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "")) || null;
85
- const http = {
86
- baseUrl,
87
- routes: launch.services,
84
+ const http: HttpSettings = {
88
85
  tokens: new Map(
89
86
  (config.codesys?.http?.credentials ?? []).flatMap(
90
87
  ({ originEnv, bearerTokenEnv }) => {
@@ -96,6 +93,16 @@ export const startRuntime = async (options: RuntimeOptions) => {
96
93
  ),
97
94
  timeoutMs: config.codesys?.http?.timeoutMs ?? 2000,
98
95
  };
96
+ const baseUrlEnv = config.server?.baseUrlEnv;
97
+ const baseUrl = (baseUrlEnv && env[baseUrlEnv]?.replace(/\/+$/, "")) || null;
98
+ // Over OPC UA the app server's gateway serves the slots this process publishes, as it serves a PLC's.
99
+ const slots =
100
+ config.server?.transport === "opcua"
101
+ ? opcuaSlots(await readServiceChannels(st), http.timeoutMs)
102
+ : null;
103
+ const transport =
104
+ slots?.transport ??
105
+ (baseUrl === null ? null : httpTransport(http, baseUrl));
99
106
 
100
107
  /** The task whose scan runs, or last ran: continuations run in their caller's task. */
101
108
  const current = { task: tasks[0]?.name ?? "", scan: 0, scanning: false };
@@ -103,14 +110,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
103
110
  const records = createTelemetry({
104
111
  build: manifest.build.id,
105
112
  capacity: config.telemetry?.capacity ?? 64,
106
- post:
107
- baseUrl === null
108
- ? null
109
- : (body) =>
110
- httpCall(http, `${baseUrl}/tsplc/telemetry`, {
111
- method: "POST",
112
- body,
113
- }),
113
+ post: transport ? (body) => transport.call("/tsplc/telemetry", body) : null,
114
114
  clock: now,
115
115
  });
116
116
  const stopTelemetry = onTelemetry((record) =>
@@ -161,7 +161,10 @@ export const startRuntime = async (options: RuntimeOptions) => {
161
161
  "@tsplc/compiler/retain": { retain },
162
162
  "@tsplc/compiler/telemetry": { telemetry, onTelemetry },
163
163
  "@tsplc/compiler/math": { min, max, clamp },
164
- "@tsplc/compiler/async": createAsync(http, diagnostics),
164
+ "@tsplc/compiler/async": createAsync(
165
+ { http, services: { routes: launch.services, transport } },
166
+ diagnostics,
167
+ ),
165
168
  "@tsplc/compiler/config": {
166
169
  env: (name: string) => {
167
170
  const value = env[name];
@@ -190,7 +193,7 @@ export const startRuntime = async (options: RuntimeOptions) => {
190
193
  const scalars = new Map<string, PublishedScalar>();
191
194
  const bound = (global: (typeof globals.published)[number]) =>
192
195
  scalarPaths(global).every(({ path }) => {
193
- const scalar = storage.scalar(path);
196
+ const scalar = storage.scalar(path) ?? slots?.scalar(path);
194
197
  if (scalar) {
195
198
  scalars.set(path, scalar);
196
199
  }
@@ -1,3 +1,4 @@
1
+ import { httpErrors } from "@tsplc/compiler/ir";
1
2
  import { plcBufferBytes } from "@tsplc/server/wire";
2
3
 
3
4
  /** A record as the program's telemetry calls make it; see `telemetryRecord` in `@tsplc/server`. */
@@ -21,7 +22,7 @@ export const createTelemetry = (options: {
21
22
  /** The build id, as the debug manifest names it. */
22
23
  build: string;
23
24
  capacity: number;
24
- /** Posts a batch's JSON; null when the program has no server to send to, which drops records. */
25
+ /** Posts a batch's JSON, rejecting with a job error code; null when the program has no server to send to, which drops records. */
25
26
  post: ((body: string) => Promise<unknown>) | null;
26
27
  clock: () => number;
27
28
  }) => {
@@ -106,12 +107,19 @@ export const createTelemetry = (options: {
106
107
  }
107
108
  const sent = state.queued.slice(0, batch.count);
108
109
  state.sending = true;
110
+ const settle = () => {
111
+ state.queued = state.queued.filter((queued) => !sent.includes(queued));
112
+ state.waitingSince = options.clock();
113
+ };
109
114
  post(batch.body)
110
- .then(() => {
111
- state.queued = state.queued.filter((queued) => !sent.includes(queued));
112
- state.waitingSince = options.clock();
113
- })
114
- .catch(() => {
115
+ .then(settle)
116
+ .catch((reason: unknown) => {
117
+ // The server can't take these records, so they are dropped rather than sent forever.
118
+ if (reason === httpErrors.base + 400) {
119
+ state.dropped += sent.length;
120
+ settle();
121
+ return;
122
+ }
115
123
  state.waitingSince = options.clock();
116
124
  })
117
125
  .finally(() => {
@@ -0,0 +1,172 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { httpErrors, jobError } from "@tsplc/compiler/ir";
4
+ import { emittedFiles } from "@tsplc/config/project-files";
5
+ import type { PublishedScalar } from "@tsplc/opcua/server";
6
+ import { plcBufferBytes } from "@tsplc/server/wire";
7
+ import { z } from "zod";
8
+ import { type HttpSettings, httpCall } from "./async";
9
+
10
+ /**
11
+ * How the program's service calls and telemetry reach the app server, as `server.transport`
12
+ * compiled them. A call rejects with the compiled call's error code, a number, never an Error.
13
+ */
14
+ export interface Transport {
15
+ /** Sends a JSON body to a route, such as a procedure's `/tsplc/services/…` or `/tsplc/telemetry`. */
16
+ call: (route: string, body: string) => Promise<unknown>;
17
+ }
18
+
19
+ /** POSTs each body to the route under the server's base URL, with its origin's bearer token. */
20
+ export const httpTransport = (
21
+ settings: HttpSettings,
22
+ baseUrl: string,
23
+ ): Transport => ({
24
+ call: (route, body) =>
25
+ httpCall(settings, `${baseUrl}${route}`, { method: "POST", body }),
26
+ });
27
+
28
+ /** One slot of a route, as the build lists it in `machines.ts`: the global symbols it is exchanged through. */
29
+ const serviceChannel = z.strictObject({
30
+ path: z.string(),
31
+ request: z.string(),
32
+ requestId: z.string(),
33
+ reply: z.string(),
34
+ replyId: z.string(),
35
+ epoch: z.string(),
36
+ });
37
+ export type ServiceChannel = z.infer<typeof serviceChannel>;
38
+
39
+ /** The slots the build compiled, from the emitted `machines.ts`. */
40
+ export const readServiceChannels = async (
41
+ st: string,
42
+ ): Promise<ServiceChannel[]> => {
43
+ const text = await readFile(join(st, emittedFiles.machines), "utf8");
44
+ const listed = /export const serviceChannels=([\s\S]*?) as const;/.exec(text);
45
+ if (!listed?.[1]) {
46
+ throw new Error(`${emittedFiles.machines} lists no service channels.`);
47
+ }
48
+ return z.array(serviceChannel).parse(JSON.parse(listed[1]));
49
+ };
50
+
51
+ /** A slot's sequence is a UDINT; wrapping to 0 retires its epoch, as the compiled block does. */
52
+ const sequenceLimit = 2 ** 32;
53
+
54
+ /** How often a waiting call looks for its reply; the gateway itself polls every 20 ms. */
55
+ const replyPollMs = 5;
56
+
57
+ /** A reply's body after its identity: `0|<json>`, `4|…` for a request the server refused, else a failure. */
58
+ const decodeReply = (rest: string): unknown => {
59
+ if (Buffer.byteLength(rest, "utf8") < 4) {
60
+ throw jobError.malformedResponse;
61
+ }
62
+ if (rest.startsWith("4|")) {
63
+ throw httpErrors.base + 400;
64
+ }
65
+ if (!rest.startsWith("0|")) {
66
+ throw jobError.network;
67
+ }
68
+ try {
69
+ return JSON.parse(rest.slice(2));
70
+ } catch {
71
+ throw jobError.malformedResponse;
72
+ }
73
+ };
74
+
75
+ /**
76
+ * The OPC UA slots a compiled program exchanges its calls through, held in this process and
77
+ * published as the program's globals are, so the app server's gateway serves them as it serves a
78
+ * PLC's. Each call claims a free slot of its route whose epoch the gateway has set, writes its
79
+ * request and then commits it with its identity, and waits for the reply that names it.
80
+ */
81
+ export const opcuaSlots = (
82
+ channels: readonly ServiceChannel[],
83
+ timeoutMs: number,
84
+ ) => {
85
+ const values = new Map<string, string>(
86
+ channels.flatMap((channel) =>
87
+ [
88
+ channel.request,
89
+ channel.requestId,
90
+ channel.reply,
91
+ channel.replyId,
92
+ channel.epoch,
93
+ ].map((path) => [path, ""] as const),
94
+ ),
95
+ );
96
+ const read = (path: string) => values.get(path) ?? "";
97
+ const slots = new Map(
98
+ channels.map((channel) => [channel, { inUse: false, sequence: 0 }]),
99
+ );
100
+
101
+ const awaitReply = async (
102
+ channel: ServiceChannel,
103
+ epoch: string,
104
+ identity: string,
105
+ deadline: number,
106
+ ): Promise<unknown> => {
107
+ const prefix = `${identity}|`;
108
+ for (;;) {
109
+ if (performance.now() >= deadline) {
110
+ throw jobError.timeout;
111
+ }
112
+ if (read(channel.epoch) !== epoch) {
113
+ throw jobError.network;
114
+ }
115
+ const reply = read(channel.reply);
116
+ if (read(channel.replyId) === identity && reply.startsWith(prefix)) {
117
+ return decodeReply(reply.slice(prefix.length));
118
+ }
119
+ await Bun.sleep(replyPollMs);
120
+ }
121
+ };
122
+
123
+ const call = async (route: string, body: string): Promise<unknown> => {
124
+ const deadline = performance.now() + timeoutMs;
125
+ const channel = channels.find(
126
+ (candidate) =>
127
+ candidate.path === route &&
128
+ read(candidate.epoch) !== "" &&
129
+ !slots.get(candidate)?.inUse,
130
+ );
131
+ const slot = channel && slots.get(channel);
132
+ if (!channel || !slot) {
133
+ throw jobError.noRequestSlot;
134
+ }
135
+ slot.inUse = true;
136
+ try {
137
+ slot.sequence = (slot.sequence + 1) % sequenceLimit;
138
+ if (slot.sequence === 0) {
139
+ values.set(channel.epoch, "");
140
+ throw jobError.network;
141
+ }
142
+ const epoch = read(channel.epoch);
143
+ const identity = `${epoch}:${slot.sequence}`;
144
+ const request = `${identity}|${body}`;
145
+ if (Buffer.byteLength(request, "utf8") > plcBufferBytes) {
146
+ throw jobError.tooLarge;
147
+ }
148
+ values.set(channel.request, request);
149
+ // The identity commits the request: the gateway ignores a request it doesn't name.
150
+ values.set(channel.requestId, identity);
151
+ return await awaitReply(channel, epoch, identity, deadline);
152
+ } finally {
153
+ values.set(channel.requestId, "");
154
+ values.set(channel.request, "");
155
+ slot.inUse = false;
156
+ }
157
+ };
158
+
159
+ return {
160
+ transport: { call } satisfies Transport,
161
+ /** The published scalar of a slot's symbol, or undefined for any other path. */
162
+ scalar: (path: string): PublishedScalar | undefined =>
163
+ values.has(path)
164
+ ? {
165
+ read: () => read(path),
166
+ write: (value) => {
167
+ values.set(path, String(value));
168
+ },
169
+ }
170
+ : undefined,
171
+ };
172
+ };