@tsplc/compiler 0.5.1 → 0.5.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/rip-technologies/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.5.1",
20
+ "version": "0.5.3",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -101,17 +101,17 @@
101
101
  "bun": ">=1.4.3"
102
102
  },
103
103
  "dependencies": {
104
- "@tsplc/agent": "0.5.1",
105
- "@tsplc/build": "0.5.1",
106
- "@tsplc/config": "0.5.1",
107
- "@tsplc/debug": "0.5.1",
108
- "@tsplc/opcua": "0.5.1",
109
- "@tsplc/typegen": "0.5.1",
104
+ "@tsplc/agent": "0.5.3",
105
+ "@tsplc/build": "0.5.3",
106
+ "@tsplc/config": "0.5.3",
107
+ "@tsplc/debug": "0.5.3",
108
+ "@tsplc/opcua": "0.5.3",
109
+ "@tsplc/typegen": "0.5.3",
110
110
  "typescript": "6.0.3",
111
111
  "zod": "4.3.6",
112
112
  "@types/bun": "1.4.2",
113
- "@tsplc/server": "0.5.1",
114
- "@tsplc/iec": "0.5.1"
113
+ "@tsplc/server": "0.5.3",
114
+ "@tsplc/iec": "0.5.3"
115
115
  },
116
116
  "bin": {
117
117
  "tsplc": "./dist/cli.js"
@@ -20,6 +20,13 @@ import { type CodesysTypes, stStringLiteral } from "./types.ts";
20
20
 
21
21
  const opcuaServiceCapacity = 16;
22
22
 
23
+ /* SysSocket Interfaces' SOCKET_SOL, the socket level, and SOCKET_SO_KEEPALIVE. */
24
+ const socketLevel = "16#FFFF";
25
+ const socketKeepAliveOption = "16#8";
26
+ const keepAliveIdleMs = 2000;
27
+ const keepAliveIntervalMs = 1000;
28
+ const keepAliveProbes = 3;
29
+
23
30
  export interface HttpEndpoint {
24
31
  transport?: "http" | "opcua";
25
32
  host: string;
@@ -417,7 +424,7 @@ const httpServiceBlock = (
417
424
  network: string,
418
425
  /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
419
426
  trace: { job: string; sequence: string } | undefined,
420
- ): [GeneratedObject, GeneratedObject] =>
427
+ ): [GeneratedObject, ...GeneratedObject[]] =>
421
428
  nativeHttp({
422
429
  id: block.id,
423
430
  name,
@@ -470,7 +477,7 @@ export const nativeHttp = ({
470
477
  decode: string;
471
478
  /** The requesting job's id input and this block's request counter, sent as `x-tsplc-request`. */
472
479
  trace?: { job: string; sequence: string };
473
- }): [GeneratedObject, GeneratedObject] => {
480
+ }): [GeneratedObject, ...GeneratedObject[]] => {
474
481
  const requestHeader = trace
475
482
  ? `AppendWire(UDINT_TO_STRING(${trace.job}));AppendWire(':');AppendWire(UDINT_TO_STRING(${trace.sequence}));AppendWire('$R$NContent-Length: ');`
476
483
  : "";
@@ -492,6 +499,7 @@ VAR
492
499
  writer : NBS.TCP_Write;
493
500
  reader : NBS.TCP_Read;
494
501
  timeout : TON;
502
+ keepAlive : ${name}_KeepAlive;
495
503
  stage : UINT;
496
504
  wire : STRING(8192);
497
505
  received : STRING(8192);
@@ -520,6 +528,7 @@ END_VAR
520
528
  RETURN;
521
529
  END_IF;
522
530
  IF stage=0 THEN
531
+ client.SetOptionProvider(itfOptionProvider:=keepAlive);
523
532
  payload:=''; malformed:=FALSE; used:=0; received:='';${trace ? `\n ${trace.sequence}:=${trace.sequence}+1;` : ""}
524
533
  ${body}
525
534
  IF malformed THEN ${port("error")}:=${jobError.tooLarge}; stage:=90;
@@ -596,7 +605,69 @@ END_IF;
596
605
  ${release}
597
606
  FB_exit:=TRUE;`,
598
607
  };
599
- return [block, exit];
608
+ return [block, exit, ...tcpKeepAlive(id, name)];
609
+ };
610
+
611
+ /**
612
+ * TCP keep-alive for an HTTP client's connection, as an option provider the client applies to each socket it opens. A
613
+ * connection whose peer vanished without closing it, as when the server's PC drops off the network, otherwise stays active
614
+ * (Net Base Services' TCP_Client documentation), and a read on it holds the Net Base Services task every client shares: for
615
+ * two hours on the frame-assembly line, cutting the PLC off from its server until a download found the task unable to stop.
616
+ * With keep-alive, such a connection fails within seconds and the task moves on. A live peer's TCP stack answers the
617
+ * probes however long its server takes to reply, so they never end a slow request.
618
+ */
619
+ const tcpKeepAlive = (owner: string, name: string): GeneratedObject[] => {
620
+ const id = `${owner}:keepAlive`;
621
+ return [
622
+ {
623
+ id,
624
+ kind: "functionBlock",
625
+ name: `${name}_KeepAlive`,
626
+ // SysSocket Interfaces' RTS_SOCKET_SO_VALUE_TCP_KEEPALIVE, laid out as its seven 32-bit members: bOn, probes,
627
+ // probesResult, timeout (ms idle before the first probe), timeoutResult, interval (ms between probes),
628
+ // intervalResult. Three unanswered probes, the first after 2 s idle and a second apart, end it in 5 s.
629
+ declaration: `FUNCTION_BLOCK ${name}_KeepAlive IMPLEMENTS NBS.IOptionProvider
630
+ VAR
631
+ keepAlive : ARRAY[0..6] OF DINT := [1, ${keepAliveProbes}, 0, ${keepAliveIdleMs}, 0, ${keepAliveIntervalMs}, 0];
632
+ END_VAR`,
633
+ implementation: "",
634
+ },
635
+ {
636
+ id: `${id}:GetOptionCount`,
637
+ parent: id,
638
+ kind: "method",
639
+ name: "GetOptionCount",
640
+ declaration: `METHOD PUBLIC GetOptionCount : USINT
641
+ VAR_OUTPUT eErrorID : NBS.ERROR; END_VAR`,
642
+ implementation: "GetOptionCount:=1;eErrorID:=NBS.ERROR.NO_ERROR;",
643
+ },
644
+ {
645
+ id: `${id}:GetParams`,
646
+ parent: id,
647
+ kind: "method",
648
+ name: "GetParams",
649
+ declaration: `METHOD PUBLIC GetParams : NBS.ERROR
650
+ VAR_INPUT usiIndex : USINT; END_VAR
651
+ VAR_OUTPUT eOperation : NBS.OPERATION; optOption : NBS.OPTION; END_VAR`,
652
+ // SOCKET_SOL and SOCKET_SO_KEEPALIVE from SysSocket Interfaces, which the project doesn't reference by name.
653
+ implementation: `eOperation:=NBS.OPERATION.SET_OPTION;
654
+ optOption.diLevel:=${socketLevel};
655
+ optOption.diOption:=${socketKeepAliveOption};
656
+ optOption.pdiOptionValue:=ADR(keepAlive);
657
+ optOption.udiOptionLen:=SIZEOF(keepAlive);
658
+ GetParams:=NBS.ERROR.NO_ERROR;`,
659
+ },
660
+ {
661
+ id: `${id}:SetResult`,
662
+ parent: id,
663
+ kind: "method",
664
+ name: "SetResult",
665
+ declaration: `METHOD PUBLIC SetResult : NBS.ERROR
666
+ VAR_INPUT usiIndex : USINT; udiResult : UDINT; END_VAR`,
667
+ // A platform without keep-alive leaves the connection as it was before: nothing to undo.
668
+ implementation: "SetResult:=NBS.ERROR.NO_ERROR;",
669
+ },
670
+ ];
600
671
  };
601
672
 
602
673
  export const httpCertificateVerifier = (
@@ -1,10 +1,55 @@
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
2
  import { existsSync, readFileSync } from "node:fs";
3
- import { isAbsolute, relative } from "node:path";
3
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4
4
  import type { SourceSpan } from "@tsplc/compiler/ir";
5
5
  import type { SourceRange } from "@tsplc/debug/manifest";
6
6
 
7
- /** Project files by index. Spans outside the project, such as virtual modules and packages, have no range. */
7
+ /**
8
+ * Whether a compiled file is the project's own source: anything but an installed dependency. A
9
+ * monorepo's workspace packages count wherever they sit, as their files resolve to their real paths.
10
+ */
11
+ export const projectSource = (root: string, file: string): boolean => {
12
+ const path = relative(root, file);
13
+ return !isAbsolute(path) && !path.split(/[\\/]/).includes("node_modules");
14
+ };
15
+
16
+ /** The nearest directory at or above `directory` that holds a `package.json`. */
17
+ const packageDirectory = (directory: string): string | undefined => {
18
+ if (existsSync(join(directory, "package.json"))) {
19
+ return directory;
20
+ }
21
+ const parent = dirname(directory);
22
+ return parent === directory ? undefined : packageDirectory(parent);
23
+ };
24
+
25
+ /**
26
+ * The folders a source module's objects go in, without a leading `src`: its path in the project,
27
+ * or a workspace package's own, so its objects keep the folders they would have in its own project.
28
+ * `undefined` for a module that is not the project's own source.
29
+ */
30
+ export const sourceFolders = (
31
+ root: string,
32
+ module: string,
33
+ ): string[] | undefined => {
34
+ if (!/^[\w./ -]+\.tsx?$/.test(module)) {
35
+ return undefined;
36
+ }
37
+ const file = resolve(root, module);
38
+ if (!projectSource(root, file)) {
39
+ return undefined;
40
+ }
41
+ const base = relative(root, file).startsWith("..")
42
+ ? (packageDirectory(dirname(file)) ?? dirname(file))
43
+ : root;
44
+ const segments = relative(base, file).replaceAll("\\", "/").split("/");
45
+ const folders = segments.slice(0, -1);
46
+ return folders[0] === "src" ? folders.slice(1) : folders;
47
+ };
48
+
49
+ /**
50
+ * Project files by index, as paths relative to the project root, so a workspace package's start with
51
+ * `../`. Spans outside the project's own sources, such as virtual modules and dependencies, have no range.
52
+ */
8
53
  export class Sources {
9
54
  readonly files: string[] = [];
10
55
  private readonly loaded = new Map<
@@ -18,13 +63,8 @@ export class Sources {
18
63
  if (this.loaded.has(file)) {
19
64
  return this.loaded.get(file);
20
65
  }
21
- const path = relative(this.root, file);
22
- const inside =
23
- !path.startsWith("..") &&
24
- !isAbsolute(path) &&
25
- !path.split(/[\\/]/).includes("node_modules");
26
66
  let source: { text: string; lines: number[] } | undefined;
27
- if (inside && existsSync(file)) {
67
+ if (projectSource(this.root, file) && existsSync(file)) {
28
68
  const text = readFileSync(file, "utf8");
29
69
  const lines = [0];
30
70
  for (let index = 0; index < text.length; index++) {
@@ -1,6 +1,7 @@
1
1
  import type { EmitResult, GeneratedObject } from "@tsplc/compiler/ir";
2
2
  import type { SourceMapping } from "./emit.ts";
3
3
  import type { CodesysPlan } from "./plan.ts";
4
+ import { sourceFolders } from "./sources.ts";
4
5
  import { type CodesysSymbols, required } from "./symbols.ts";
5
6
 
6
7
  /** The file that holds an object's declaration, under its path: its only file, or `declaration.st` beside its implementation. */
@@ -128,24 +129,17 @@ function objectPaths(
128
129
  );
129
130
  return `${objectPath(owner)}/methods/${object.name}`;
130
131
  }
131
- const source = sourceModule(object);
132
- if (
133
- /^[\w./ -]+\.tsx?$/.test(source) &&
134
- !source.split(/[\\/]/).includes("..") &&
135
- !source.startsWith("/")
136
- ) {
137
- const segments = source.replaceAll("\\", "/").split("/").slice(0, -1);
138
- if (segments[0] === "src") {
139
- segments.shift();
140
- }
141
- // A DUT directory can also contain sibling input/output layouts. Keep
142
- // that directory for every DUT, or its primary type would block the folder.
143
- if (object.kind !== "dataType" && segments.at(-1) === object.name) {
144
- segments.pop();
145
- }
146
- return [...segments, object.name].join("/");
132
+ const folders = sourceFolders(plan.project.root, sourceModule(object));
133
+ if (!folders) {
134
+ return `${generatedFolder(object)}/${object.name}`;
147
135
  }
148
- return `${generatedFolder(object)}/${object.name}`;
136
+ // A DUT directory can also contain sibling input/output layouts. Keep
137
+ // that directory for every DUT, or its primary type would block the folder.
138
+ const kept =
139
+ object.kind !== "dataType" && folders.at(-1) === object.name
140
+ ? folders.slice(0, -1)
141
+ : folders;
142
+ return [...kept, object.name].join("/");
149
143
  };
150
144
  return objectPath;
151
145
  }
@@ -623,7 +623,7 @@ export function telemetryObjects({
623
623
  const helpers = httpMethods(writer).filter((item) =>
624
624
  ["ByteLength", "Append", "WriteString"].includes(item.name),
625
625
  );
626
- const [client, clientExit] = nativeHttp({
626
+ const [client, ...clientLifecycle] = nativeHttp({
627
627
  id: telemetryClient,
628
628
  name: names.client,
629
629
  ports: `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`,
@@ -773,7 +773,7 @@ WriteString(text);
773
773
  ...failures,
774
774
  ...trace,
775
775
  client,
776
- clientExit,
776
+ ...clientLifecycle,
777
777
  ...httpMethods(telemetryClient),
778
778
  ...httpCertificateVerifier(telemetryClient, names.client, endpoint),
779
779
  ];