@tsplc/typegen 0.2.20 → 0.3.0

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/README.md CHANGED
@@ -4,4 +4,4 @@ Part of [tsPLC](https://github.com/rip-technologies/tsplc).
4
4
 
5
5
  Generates TypeScript contracts for host clients from Structured Text declarations, and parses EtherNet/IP EDS files into typed hardware IO channels. In a tsPLC project, `tsplc typegen` writes `generated/hardware.ts`, whose `HardwareIoMapping` type checks every `io` key and channel in `tsplc.config.ts`.
6
6
 
7
- See the [documentation](https://github.com/rip-technologies/tsplc/tree/main/docs). MIT licensed.
7
+ See the [documentation](https://github.com/rip-technologies/tsplc/tree/master/docs). MIT licensed.
package/dist/cli.js CHANGED
@@ -5,20 +5,11 @@ import { mkdir as mkdir2, readFile as readFile4, rename as rename2, rm, writeFil
5
5
  import { dirname as dirname2, resolve as resolve3 } from "node:path";
6
6
  import { parseArgs } from "node:util";
7
7
 
8
- // packages/typegen/src/project.ts
9
- import { mkdir, readFile as readFile3, rename, writeFile } from "node:fs/promises";
10
- import { dirname, resolve as resolve2 } from "node:path";
11
- import { format } from "prettier";
12
- import {
13
- loadTsplcConfig,
14
- publicationSchema,
15
- typegenSchema
16
- } from "@tsplc/config";
17
- import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
18
-
19
8
  // packages/typegen/src/codegen/generate.ts
20
9
  import { readdir, readFile } from "node:fs/promises";
21
10
  import { basename, join } from "node:path";
11
+ import { elementaryTypesByName } from "@tsplc/iec";
12
+ import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
22
13
 
23
14
  // packages/typegen/src/codegen/constants.ts
24
15
  import {
@@ -144,10 +135,6 @@ function constantResolver(lists) {
144
135
  return constant;
145
136
  }
146
137
 
147
- // packages/typegen/src/codegen/generate.ts
148
- import { elementaryTypesByName } from "@tsplc/iec";
149
- import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
150
-
151
138
  // packages/typegen/src/codegen/parser.ts
152
139
  import {
153
140
  blockCommentEnd,
@@ -595,7 +582,8 @@ function emit(declarations, globals, {
595
582
  const visited = new Set;
596
583
  function visitReference(type) {
597
584
  if (type.kind === "array") {
598
- return visitReference(type.element);
585
+ visitReference(type.element);
586
+ return;
599
587
  }
600
588
  if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
601
589
  visit(declaration(type.name));
@@ -610,7 +598,9 @@ function emit(declarations, globals, {
610
598
  }
611
599
  visiting.add(type.name);
612
600
  if (type.kind === "struct") {
613
- type.members.forEach((member) => visitReference(member.type));
601
+ type.members.forEach((member) => {
602
+ visitReference(member.type);
603
+ });
614
604
  }
615
605
  if (type.kind === "alias") {
616
606
  visitReference(type.type);
@@ -741,10 +731,197 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
741
731
  `);
742
732
  }
743
733
 
734
+ // packages/typegen/src/project.ts
735
+ import { mkdir, readFile as readFile3, rename, writeFile } from "node:fs/promises";
736
+ import { dirname, resolve as resolve2 } from "node:path";
737
+ import {
738
+ ioSymbolsSchema,
739
+ loadTsplcConfig,
740
+ publicationSchema,
741
+ typegenSchema
742
+ } from "@tsplc/config";
743
+ import {
744
+ emittedFiles,
745
+ emittedStDirectory,
746
+ projectSnapshotFile
747
+ } from "@tsplc/config/project-files";
748
+ import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
749
+ import { format } from "prettier";
750
+
744
751
  // packages/typegen/src/hardware.ts
745
752
  import { readdir as readdir2, readFile as readFile2 } from "node:fs/promises";
746
753
  import { resolve } from "node:path";
747
754
 
755
+ // packages/typegen/src/hardware/channels.ts
756
+ import { ioScalarBits } from "@tsplc/iec";
757
+
758
+ // packages/typegen/src/hardware/process-image.ts
759
+ import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
760
+ function ioLayout(type) {
761
+ const array = ioArray(type.trim());
762
+ if (array) {
763
+ const element = ioLayout(array.element);
764
+ return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
765
+ }
766
+ const scalar = ioScalar(type);
767
+ if (scalar?.family === "integer" || scalar?.family === "bits") {
768
+ return `INT${scalar.bits}`;
769
+ }
770
+ return scalar?.name;
771
+ }
772
+ var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
773
+ function directAddress(region, base, offsetBits, bits) {
774
+ const size = addressSize(bits);
775
+ if (!size) {
776
+ return;
777
+ }
778
+ const byte = base + Math.floor(offsetBits / 8);
779
+ if (bits === 1) {
780
+ return `%${region}X${byte}.${offsetBits % 8}`;
781
+ }
782
+ if ((base * 8 + offsetBits) % bits) {
783
+ return;
784
+ }
785
+ return `%${region}${size}${byte / (bits / 8)}`;
786
+ }
787
+ var byteOffset = (address) => Number(address.slice(3));
788
+ function regionPlacer(regions, { generatedTree }) {
789
+ const taken = regions.flatMap(({ region, size, address }) => address ? [
790
+ {
791
+ region,
792
+ start: byteOffset(address),
793
+ end: byteOffset(address) + size
794
+ }
795
+ ] : []);
796
+ const cursors = { I: 0, Q: 0 };
797
+ const aligned = (offset) => Math.ceil(offset / 4) * 4;
798
+ return ({ id, region, size, address }) => {
799
+ if (address) {
800
+ return address;
801
+ }
802
+ if (!generatedTree) {
803
+ throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
804
+ }
805
+ const clear = (start) => {
806
+ const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
807
+ return overlap ? clear(aligned(overlap.end)) : start;
808
+ };
809
+ const start = clear(aligned(cursors[region]));
810
+ taken.push({ region, start, end: start + size });
811
+ cursors[region] = start + size;
812
+ return `%${region}B${start}`;
813
+ };
814
+ }
815
+
816
+ // packages/typegen/src/hardware/channels.ts
817
+ function assemblyChannels({
818
+ device,
819
+ direction,
820
+ instance,
821
+ members,
822
+ base,
823
+ payloadSize
824
+ }) {
825
+ const prefix = `${direction}s`;
826
+ const region = direction === "input" ? "I" : "Q";
827
+ const payloadBits = payloadSize * 8;
828
+ const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
829
+ const channels = [];
830
+ for (let i = 0;i < payloadSize; i++) {
831
+ const key = `${prefix}.Byte${i}`;
832
+ channels.push({
833
+ device,
834
+ id: key,
835
+ name: `Byte ${i}`,
836
+ direction,
837
+ assembly: instance,
838
+ offsetBits: i * 8,
839
+ bits: 8,
840
+ type: "BYTE",
841
+ address: address(i * 8, 8),
842
+ unit: "",
843
+ description: "Assembly payload byte"
844
+ });
845
+ for (let bit = 0;bit < 8; bit++) {
846
+ channels.push({
847
+ device,
848
+ id: `${key}.Bit${bit}`,
849
+ parent: key,
850
+ name: `Bit ${bit}`,
851
+ direction,
852
+ assembly: instance,
853
+ offsetBits: i * 8 + bit,
854
+ bits: 1,
855
+ type: "BOOL",
856
+ address: address(i * 8 + bit, 1),
857
+ unit: "",
858
+ description: "Assembly payload bit"
859
+ });
860
+ }
861
+ }
862
+ const named = members.filter((member) => member.parameter).map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
863
+ const seen = new Set;
864
+ const repeated = new Set;
865
+ for (const { name } of named) {
866
+ if (seen.has(name)) {
867
+ repeated.add(name);
868
+ }
869
+ seen.add(name);
870
+ }
871
+ const counts = new Map;
872
+ for (const { member, name } of named) {
873
+ if (member.offsetBits >= payloadBits) {
874
+ continue;
875
+ }
876
+ const count = counts.get(name) ?? 0;
877
+ counts.set(name, count + 1);
878
+ const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
879
+ const scalarBits = ioScalarBits(member.type);
880
+ const channel = {
881
+ device,
882
+ id: key,
883
+ name: member.name,
884
+ direction,
885
+ assembly: instance,
886
+ offsetBits: member.offsetBits,
887
+ bits: member.bits,
888
+ type: member.type,
889
+ address: scalarBits === member.bits ? address(member.offsetBits, member.bits) : undefined,
890
+ unit: member.unit,
891
+ description: member.description
892
+ };
893
+ const spansScalars = scalarBits !== undefined && scalarBits >= 8 && member.bits > scalarBits && member.bits % scalarBits === 0 && member.offsetBits % scalarBits === 0;
894
+ if (!spansScalars) {
895
+ if (member.offsetBits + member.bits <= payloadBits) {
896
+ channels.push(channel);
897
+ }
898
+ continue;
899
+ }
900
+ const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
901
+ const span = {
902
+ ...channel,
903
+ bits: length * scalarBits,
904
+ type: `ARRAY[0..${length - 1}] OF ${member.type}`,
905
+ address: address(member.offsetBits, scalarBits)
906
+ };
907
+ channels.push(span);
908
+ for (let index = 0;index < length; index++) {
909
+ const offset = member.offsetBits + index * scalarBits;
910
+ channels.push({
911
+ ...span,
912
+ id: `${key}[${index}]`,
913
+ parent: key,
914
+ name: `${member.name}[${index}]`,
915
+ type: member.type,
916
+ bits: scalarBits,
917
+ offsetBits: offset,
918
+ address: address(offset, scalarBits)
919
+ });
920
+ }
921
+ }
922
+ return channels;
923
+ }
924
+
748
925
  // packages/typegen/src/hardware/eds.ts
749
926
  var cipTypes = {
750
927
  193: "BOOL",
@@ -1023,176 +1200,6 @@ function parseEds(text, file = "device.eds") {
1023
1200
  };
1024
1201
  }
1025
1202
 
1026
- // packages/typegen/src/hardware/channels.ts
1027
- import { ioScalarBits } from "@tsplc/iec";
1028
-
1029
- // packages/typegen/src/hardware/process-image.ts
1030
- import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
1031
- function ioLayout(type) {
1032
- const array = ioArray(type.trim());
1033
- if (array) {
1034
- const element = ioLayout(array.element);
1035
- return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
1036
- }
1037
- const scalar = ioScalar(type);
1038
- if (scalar?.family === "integer" || scalar?.family === "bits") {
1039
- return `INT${scalar.bits}`;
1040
- }
1041
- return scalar?.name;
1042
- }
1043
- var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
1044
- function directAddress(region, base, offsetBits, bits) {
1045
- const size = addressSize(bits);
1046
- if (!size) {
1047
- return;
1048
- }
1049
- const byte = base + Math.floor(offsetBits / 8);
1050
- if (bits === 1) {
1051
- return `%${region}X${byte}.${offsetBits % 8}`;
1052
- }
1053
- if ((base * 8 + offsetBits) % bits) {
1054
- return;
1055
- }
1056
- return `%${region}${size}${byte / (bits / 8)}`;
1057
- }
1058
- var byteOffset = (address) => Number(address.slice(3));
1059
- function regionPlacer(regions, { generatedTree }) {
1060
- const taken = regions.flatMap(({ region, size, address }) => address ? [
1061
- {
1062
- region,
1063
- start: byteOffset(address),
1064
- end: byteOffset(address) + size
1065
- }
1066
- ] : []);
1067
- const cursors = { I: 0, Q: 0 };
1068
- const aligned = (offset) => Math.ceil(offset / 4) * 4;
1069
- return ({ id, region, size, address }) => {
1070
- if (address) {
1071
- return address;
1072
- }
1073
- if (!generatedTree) {
1074
- throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
1075
- }
1076
- const clear = (start) => {
1077
- const overlap = taken.find((item) => item.region === region && item.start < start + size && start < item.end);
1078
- return overlap ? clear(aligned(overlap.end)) : start;
1079
- };
1080
- const start = clear(aligned(cursors[region]));
1081
- taken.push({ region, start, end: start + size });
1082
- cursors[region] = start + size;
1083
- return `%${region}B${start}`;
1084
- };
1085
- }
1086
-
1087
- // packages/typegen/src/hardware/channels.ts
1088
- function assemblyChannels({
1089
- device,
1090
- direction,
1091
- instance,
1092
- members,
1093
- base,
1094
- payloadSize
1095
- }) {
1096
- const prefix = `${direction}s`;
1097
- const region = direction === "input" ? "I" : "Q";
1098
- const payloadBits = payloadSize * 8;
1099
- const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
1100
- const channels = [];
1101
- for (let i = 0;i < payloadSize; i++) {
1102
- const key = `${prefix}.Byte${i}`;
1103
- channels.push({
1104
- device,
1105
- id: key,
1106
- name: `Byte ${i}`,
1107
- direction,
1108
- assembly: instance,
1109
- offsetBits: i * 8,
1110
- bits: 8,
1111
- type: "BYTE",
1112
- address: address(i * 8, 8),
1113
- unit: "",
1114
- description: "Assembly payload byte"
1115
- });
1116
- for (let bit = 0;bit < 8; bit++) {
1117
- channels.push({
1118
- device,
1119
- id: `${key}.Bit${bit}`,
1120
- parent: key,
1121
- name: `Bit ${bit}`,
1122
- direction,
1123
- assembly: instance,
1124
- offsetBits: i * 8 + bit,
1125
- bits: 1,
1126
- type: "BOOL",
1127
- address: address(i * 8 + bit, 1),
1128
- unit: "",
1129
- description: "Assembly payload bit"
1130
- });
1131
- }
1132
- }
1133
- const named = members.filter((member) => member.parameter).map((member) => ({ member, name: member.name.replace(/[^\w]/g, "_") }));
1134
- const seen = new Set;
1135
- const repeated = new Set;
1136
- for (const { name } of named) {
1137
- if (seen.has(name)) {
1138
- repeated.add(name);
1139
- }
1140
- seen.add(name);
1141
- }
1142
- const counts = new Map;
1143
- for (const { member, name } of named) {
1144
- if (member.offsetBits >= payloadBits) {
1145
- continue;
1146
- }
1147
- const count = counts.get(name) ?? 0;
1148
- counts.set(name, count + 1);
1149
- const key = `${prefix}.${name}${repeated.has(name) ? `[${count}]` : ""}`;
1150
- const scalarBits = ioScalarBits(member.type);
1151
- const channel = {
1152
- device,
1153
- id: key,
1154
- name: member.name,
1155
- direction,
1156
- assembly: instance,
1157
- offsetBits: member.offsetBits,
1158
- bits: member.bits,
1159
- type: member.type,
1160
- address: scalarBits === member.bits ? address(member.offsetBits, member.bits) : undefined,
1161
- unit: member.unit,
1162
- description: member.description
1163
- };
1164
- const spansScalars = scalarBits !== undefined && scalarBits >= 8 && member.bits > scalarBits && member.bits % scalarBits === 0 && member.offsetBits % scalarBits === 0;
1165
- if (!spansScalars) {
1166
- if (member.offsetBits + member.bits <= payloadBits) {
1167
- channels.push(channel);
1168
- }
1169
- continue;
1170
- }
1171
- const length = Math.floor(Math.min(member.bits, payloadBits - member.offsetBits) / scalarBits);
1172
- const span = {
1173
- ...channel,
1174
- bits: length * scalarBits,
1175
- type: `ARRAY[0..${length - 1}] OF ${member.type}`,
1176
- address: address(member.offsetBits, scalarBits)
1177
- };
1178
- channels.push(span);
1179
- for (let index = 0;index < length; index++) {
1180
- const offset = member.offsetBits + index * scalarBits;
1181
- channels.push({
1182
- ...span,
1183
- id: `${key}[${index}]`,
1184
- parent: key,
1185
- name: `${member.name}[${index}]`,
1186
- type: member.type,
1187
- bits: scalarBits,
1188
- offsetBits: offset,
1189
- address: address(offset, scalarBits)
1190
- });
1191
- }
1192
- }
1193
- return channels;
1194
- }
1195
-
1196
1203
  // packages/typegen/src/hardware/modbus.ts
1197
1204
  var registerBytes = { Q: 4, I: 8 };
1198
1205
  function placeModbusRegisters(device, registers, place) {
@@ -1448,9 +1455,27 @@ function resolveIo(config, catalog) {
1448
1455
  }
1449
1456
 
1450
1457
  // packages/typegen/src/project.ts
1451
- var emittedSt = ".tsplc/artifacts/st";
1452
1458
  var formatTypeScript = (source) => format(source, { parser: "typescript" });
1453
- var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile3(resolve2(root, emittedSt, "publication.json"), "utf8")));
1459
+ var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile3(resolve2(root, emittedStDirectory, emittedFiles.publication), "utf8")));
1460
+ var generatedFiles = {
1461
+ hardware: "hardware.ts",
1462
+ contract: "plc.ts",
1463
+ machines: "machines.ts"
1464
+ };
1465
+ async function readIoSymbols(root) {
1466
+ const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
1467
+ const text = await readFile3(file, "utf8").catch((error) => {
1468
+ if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1469
+ return "{}";
1470
+ }
1471
+ throw error;
1472
+ });
1473
+ const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
1474
+ if (!symbols.success) {
1475
+ throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
1476
+ }
1477
+ return symbols.data;
1478
+ }
1454
1479
  async function contractSources(config, root, settings) {
1455
1480
  const directories = (setting) => setting ? [setting].flat().map((path) => resolve2(root, path)) : [];
1456
1481
  const types = directories(settings.types);
@@ -1466,7 +1491,7 @@ async function contractSources(config, root, settings) {
1466
1491
  }
1467
1492
  return sources;
1468
1493
  }
1469
- const source = config.compiler ? emittedSt : config.build?.sourceDir;
1494
+ const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
1470
1495
  if (!source) {
1471
1496
  if (config.typegen) {
1472
1497
  throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
@@ -1547,16 +1572,16 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1547
1572
  version: 1,
1548
1573
  configFile,
1549
1574
  config,
1550
- symbols: config.compiler ? JSON.parse(await readFile3(resolve2(root, emittedSt, "io-symbols.json"), "utf8").catch(() => "{}")) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
1575
+ symbols: config.compiler ? await readIoSymbols(root) : Object.fromEntries(Object.keys(io).filter((symbol) => symbol.includes(".")).map((symbol) => [symbol, symbol]))
1551
1576
  };
1552
1577
  const outputs = [
1553
1578
  {
1554
- path: resolve2(root, settings.dir, "hardware.ts"),
1579
+ path: resolve2(root, settings.dir, generatedFiles.hardware),
1555
1580
  content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
1556
1581
  },
1557
1582
  {
1558
- path: resolve2(root, ".tsplc/project.json"),
1559
- content: JSON.stringify(project, null, 2) + `
1583
+ path: resolve2(root, projectSnapshotFile),
1584
+ content: `${JSON.stringify(project, null, 2)}
1560
1585
  `
1561
1586
  }
1562
1587
  ];
@@ -1564,7 +1589,7 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1564
1589
  if (sources) {
1565
1590
  const inferred = !!config.compiler && !sources.explicit;
1566
1591
  outputs.push({
1567
- path: resolve2(root, settings.dir, "plc.ts"),
1592
+ path: resolve2(root, settings.dir, generatedFiles.contract),
1568
1593
  content: await formatTypeScript(await generateTypes({
1569
1594
  types: sources.types,
1570
1595
  globals: sources.globals,
@@ -1578,12 +1603,12 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1578
1603
  checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
1579
1604
  }
1580
1605
  if (config.compiler && !options.hardwareOnly) {
1581
- const machine = await readFile3(resolve2(root, emittedSt, "machines.ts"), "utf8").catch(() => {
1606
+ const machine = await readFile3(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
1582
1607
  return;
1583
1608
  });
1584
1609
  if (machine) {
1585
1610
  outputs.push({
1586
- path: resolve2(root, settings.dir, "machines.ts"),
1611
+ path: resolve2(root, settings.dir, generatedFiles.machines),
1587
1612
  content: await formatTypeScript(machine)
1588
1613
  });
1589
1614
  }
@@ -1657,5 +1682,5 @@ main().catch((error) => {
1657
1682
  process.exitCode = 1;
1658
1683
  });
1659
1684
 
1660
- //# debugId=6E079C222AB7798D64756E2164756E21
1685
+ //# debugId=A1A5D032EDF6796E64756E2164756E21
1661
1686
  //# sourceMappingURL=cli.js.map