@tsplc/typegen 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.
package/dist/cli.js CHANGED
@@ -1,29 +1,59 @@
1
1
  #!/usr/bin/env bun
2
2
 
3
3
  // packages/typegen/src/cli.ts
4
- import { mkdir as mkdir2, readFile as readFile5, rename as rename2, rm, writeFile as writeFile2 } from "node:fs/promises";
5
- import { dirname as dirname2, resolve as resolve3 } from "node:path";
4
+ import { resolve as resolve3 } from "node:path";
6
5
  import { parseArgs } from "node:util";
6
+ import { loadTsplcConfig } from "@tsplc/config";
7
+ import { configFileName } from "@tsplc/config/project-files";
7
8
 
8
9
  // packages/typegen/src/codegen/generate.ts
9
- import { readdir, readFile } from "node:fs/promises";
10
- import { basename, join } from "node:path";
11
- import { elementaryTypesByName } from "@tsplc/iec";
10
+ import {
11
+ elementaryType as elementaryType3,
12
+ elementaryTypesByName,
13
+ fitsNumber as fitsNumber2,
14
+ isIntegerValued as isIntegerValued2,
15
+ isWholeValue,
16
+ stringTypeText
17
+ } from "@tsplc/iec";
12
18
  import { identifierPattern as identifierPattern2 } from "@tsplc/iec/st";
13
19
 
20
+ // packages/typegen/src/files.ts
21
+ import { readdir, readFile } from "node:fs/promises";
22
+ import { join } from "node:path";
23
+ var isMissingFile = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
24
+ var readIfPresent = (path) => readFile(path, "utf8").catch((error) => {
25
+ if (isMissingFile(error)) {
26
+ return null;
27
+ }
28
+ throw error;
29
+ });
30
+ async function filesUnder(directory, extension, order) {
31
+ const pattern = new RegExp(`\\.${extension}$`, "i");
32
+ const entries = await readdir(directory, { withFileTypes: true });
33
+ const paths = await Promise.all(entries.sort((a, b) => order(a.name, b.name)).map(async (entry) => {
34
+ const path = join(directory, entry.name);
35
+ if (entry.isDirectory()) {
36
+ return filesUnder(path, extension, order);
37
+ }
38
+ return entry.isFile() && pattern.test(entry.name) ? [path] : [];
39
+ }));
40
+ return paths.flat();
41
+ }
42
+ var stFiles = (directory) => filesUnder(directory, "st", (a, b) => a < b ? -1 : 1);
43
+
14
44
  // packages/typegen/src/codegen/constants.ts
15
45
  import {
16
46
  elementaryType,
17
47
  elementaryTypes,
48
+ fitsNumber,
18
49
  integerRange,
19
50
  isIntegerValued
20
51
  } from "@tsplc/iec";
21
- var isNumberInteger = (name) => {
22
- const type = elementaryType(name);
23
- return isIntegerValued(type) && type.bits <= 32;
24
- };
52
+ import { identifierPart, identifierStart, integerLiteral } from "@tsplc/iec/st";
25
53
  var integerRanges = new Map(elementaryTypes.filter(isIntegerValued).map((type) => [type.name, integerRange(type)]));
26
- var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|[A-Za-z_]\w*(?:\s*\.\s*[A-Za-z_]\w*)?|[()+\-*/]`, "g");
54
+ var identifier = `${identifierStart}${identifierPart}*`;
55
+ var startsWithIdentifier = new RegExp(`^${identifierStart}`);
56
+ var integerToken = new RegExp(String.raw`(?:${[...integerRanges.keys()].join("|")})\s*#\s*[+-]?(?:(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*)|(?:2|8|16)#[\da-fA-F_]+|\d[\d_]*|${identifier}(?:\s*\.\s*${identifier})?|[()+\-*/]`, "g");
27
57
  function integerExpression(text, lookup) {
28
58
  const compact = text.replace(/\s+/g, "");
29
59
  const tokens = (text.match(integerToken) ?? []).map((token) => token.replace(/\s+/g, ""));
@@ -62,13 +92,13 @@ function integerExpression(text, lookup) {
62
92
  return value;
63
93
  }
64
94
  if (token && /^\d/.test(token)) {
65
- const [base, digits] = token.replace(/_/g, "").split("#");
66
- if (digits !== undefined && ![...digits].every((digit) => parseInt(digit, 16) < Number(base))) {
67
- throw new Error(`invalid base-${base} literal: ${token}`);
95
+ const literal = integerLiteral(token);
96
+ if (literal === undefined) {
97
+ throw new Error(`invalid integer literal: ${token}`);
68
98
  }
69
- return safe(digits === undefined ? Number(base) : parseInt(digits, Number(base)));
99
+ return safe(Number(literal));
70
100
  }
71
- if (token && /^[A-Za-z_]/.test(token)) {
101
+ if (token && startsWithIdentifier.test(token)) {
72
102
  return lookup(token);
73
103
  }
74
104
  throw new Error(`invalid integer expression: ${text}`);
@@ -95,11 +125,12 @@ function integerExpression(text, lookup) {
95
125
  return value;
96
126
  }
97
127
  const value = sum();
98
- if (position !== tokens.length || !Number.isSafeInteger(value)) {
99
- throw new Error(`invalid or unsafe integer expression: ${text}`);
128
+ if (position !== tokens.length) {
129
+ throw new Error(`invalid integer expression: ${text}`);
100
130
  }
101
131
  return value;
102
132
  }
133
+ var isIntegerConstant = (member) => member.type.kind === "named" && fitsNumber(elementaryType(member.type.name.toUpperCase()));
103
134
  function constantResolver(lists) {
104
135
  const values = new Map;
105
136
  const resolving = new Set;
@@ -123,7 +154,7 @@ function constantResolver(lists) {
123
154
  throw new Error(`cyclic constant ${name}`);
124
155
  }
125
156
  const { member, list } = definition;
126
- if (member.initial === undefined || member.type.kind !== "named" || !isNumberInteger(member.type.name.toUpperCase())) {
157
+ if (member.initial === undefined || !isIntegerConstant(member)) {
127
158
  throw new Error(`${list.source}: constant ${member.name} must have an integer type and initializer`);
128
159
  }
129
160
  resolving.add(definition.key);
@@ -136,72 +167,89 @@ function constantResolver(lists) {
136
167
  }
137
168
 
138
169
  // packages/typegen/src/codegen/parser.ts
170
+ import { readFile as readFile2 } from "node:fs/promises";
171
+ import { basename } from "node:path";
172
+ import { defaultStringLength } from "@tsplc/iec";
139
173
  import {
140
174
  blockCommentEnd,
141
175
  directAddressEnd,
176
+ identifierPart as identifierPart2,
142
177
  identifierPattern,
178
+ identifierStart as identifierStart2,
143
179
  lineCommentEnd,
144
- qualifiers
180
+ qualifiers,
181
+ stringEnd
145
182
  } from "@tsplc/iec/st";
183
+ var pragmaEnd = (text, offset) => {
184
+ const next = text.slice(offset).search(/[}'"]/);
185
+ if (next < 0) {
186
+ return null;
187
+ }
188
+ const at = offset + next;
189
+ if (text[at] === "}") {
190
+ return at + 1;
191
+ }
192
+ const end = stringEnd(text, at);
193
+ return end === null ? null : pragmaEnd(text, end);
194
+ };
195
+ var codeToken = new RegExp(String.raw`^(?:\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|${identifierStart2}${identifierPart2}*|:=|\.\.|[[\]():;,.+\-*/#])`, "i");
196
+ function tokenAt(source, start) {
197
+ const { text } = source;
198
+ const offset = start + text.slice(start).search(/\S|$/);
199
+ if (offset === text.length) {
200
+ return;
201
+ }
202
+ const rest = text.slice(offset);
203
+ if (rest.startsWith("(*")) {
204
+ const end = blockCommentEnd(text, offset);
205
+ if (end === null) {
206
+ throw new Error(`${source.name}: unterminated comment`);
207
+ }
208
+ const comment = text.slice(offset + 2, end - 2).trim();
209
+ return { text: comment, offset, end, kind: "comment" };
210
+ }
211
+ if (rest.startsWith("//")) {
212
+ const end = lineCommentEnd(text, offset);
213
+ const comment = text.slice(offset + 2, end).trim();
214
+ return { text: comment, offset, end, kind: "comment" };
215
+ }
216
+ const code = (kind, end) => ({
217
+ text: text.slice(offset, end),
218
+ offset,
219
+ end,
220
+ kind
221
+ });
222
+ const attributeEnd = rest.startsWith("{") ? pragmaEnd(text, offset + 1) : null;
223
+ if (attributeEnd !== null) {
224
+ return code("attribute", attributeEnd);
225
+ }
226
+ const addressEnd = directAddressEnd(text, offset);
227
+ if (addressEnd !== null) {
228
+ return code("code", addressEnd);
229
+ }
230
+ const literalEnd = rest.startsWith("'") || rest.startsWith('"') ? stringEnd(text, offset) : null;
231
+ if (literalEnd !== null) {
232
+ return code("code", literalEnd);
233
+ }
234
+ const word = codeToken.exec(rest);
235
+ if (!word) {
236
+ throw new Error(`${source.name}:${text.slice(0, offset).split(`
237
+ `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
238
+ }
239
+ return code("code", offset + word[0].length);
240
+ }
146
241
  function tokenize(source) {
147
242
  const tokens = [];
148
- let offset = 0;
149
- while (offset < source.text.length) {
150
- const rest = source.text.slice(offset);
151
- const whitespace = /^\s+/.exec(rest);
152
- if (whitespace) {
153
- offset += whitespace[0].length;
154
- continue;
155
- }
156
- if (rest.startsWith("(*")) {
157
- const end = blockCommentEnd(source.text, offset);
158
- if (end === null) {
159
- throw new Error(`${source.name}: unterminated comment`);
160
- }
161
- tokens.push({
162
- text: source.text.slice(offset + 2, end - 2).trim(),
163
- offset,
164
- kind: "comment"
165
- });
166
- offset = end;
167
- continue;
168
- }
169
- if (rest.startsWith("//")) {
170
- const end = lineCommentEnd(source.text, offset);
171
- tokens.push({
172
- text: source.text.slice(offset + 2, end).trim(),
173
- offset,
174
- kind: "comment"
175
- });
176
- offset = end;
177
- continue;
178
- }
179
- const attribute = /^\{(?:[^}'"]|'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*")*\}/.exec(rest);
180
- if (attribute) {
181
- tokens.push({ text: attribute[0], offset, kind: "attribute" });
182
- offset += attribute[0].length;
183
- continue;
184
- }
185
- const addressEnd = directAddressEnd(source.text, offset);
186
- if (addressEnd !== null) {
187
- tokens.push({
188
- text: source.text.slice(offset, addressEnd),
189
- offset,
190
- kind: "code"
191
- });
192
- offset = addressEnd;
193
- continue;
194
- }
195
- const code = /^(?:'(?:\$[\s\S]|''|[^'])*'|"(?:\$[\s\S]|""|[^"])*"|\d[\d_]*#[\da-fA-F_]+|\d[\d_]*(?:\.(?!\.)[\d_]+)?(?:[eE][+-]?\d+)?|[A-Za-z_]\w*|:=|\.\.|[[\]():;,.+\-*/#])/i.exec(rest);
196
- if (!code) {
197
- throw new Error(`${source.name}:${source.text.slice(0, offset).split(`
198
- `).length}: unsupported token ${JSON.stringify(rest.slice(0, 24))}`);
199
- }
200
- tokens.push({ text: code[0], offset, kind: "code" });
201
- offset += code[0].length;
243
+ for (let token = tokenAt(source, 0);token; token = tokenAt(source, token.end)) {
244
+ tokens.push(token);
202
245
  }
203
246
  return tokens;
204
247
  }
248
+ var codeTokenAt = (source, offset) => {
249
+ const token = tokenAt(source, offset);
250
+ return token && token.kind !== "code" ? codeTokenAt(source, token.end) : token;
251
+ };
252
+ var firstCodeToken = (source) => codeTokenAt(source, 0)?.text;
205
253
 
206
254
  class Parser {
207
255
  source;
@@ -303,7 +351,11 @@ class Parser {
303
351
  if (upper === "STRING" || upper === "WSTRING") {
304
352
  const opening = this.peek();
305
353
  if (opening !== "(" && opening !== "[") {
306
- return { kind: "string", name: upper, length: "80" };
354
+ return {
355
+ kind: "string",
356
+ name: upper,
357
+ length: String(defaultStringLength)
358
+ };
307
359
  }
308
360
  this.take();
309
361
  const closing = opening === "(" ? ")" : "]";
@@ -442,126 +494,143 @@ function parseDeclarations(source) {
442
494
  function parseGlobals(source, name) {
443
495
  return new Parser(source).globals(name);
444
496
  }
497
+ var readSource = async (name) => ({
498
+ name,
499
+ text: await readFile2(name, "utf8")
500
+ });
501
+ async function parseSources(files) {
502
+ return {
503
+ types: (await Promise.all(files.types.map(readSource))).flatMap(parseDeclarations),
504
+ globals: (await Promise.all(files.globals.map(readSource))).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")))
505
+ };
506
+ }
507
+
508
+ // packages/typegen/src/codegen/resolution.ts
509
+ import { elementaryType as elementaryType2 } from "@tsplc/iec";
510
+ function resolveDeclarations({
511
+ types,
512
+ globals
513
+ }) {
514
+ const declarations = new Map(types.map((declaration) => [declaration.name.toUpperCase(), declaration]));
515
+ const constant = constantResolver(globals.filter((list) => list.constant));
516
+ const integer = (expression) => integerExpression(expression, (name) => constant(name, null));
517
+ const declaration = (name) => {
518
+ const found = declarations.get(name.toUpperCase());
519
+ if (!found) {
520
+ throw new Error(`unknown IEC type ${name}`);
521
+ }
522
+ return found;
523
+ };
524
+ const aliasTarget = (reference) => {
525
+ if (reference.kind !== "named" || elementaryType2(reference.name.toUpperCase())) {
526
+ return reference;
527
+ }
528
+ const named = declaration(reference.name);
529
+ return named.kind === "alias" ? aliasTarget(named.type) : reference;
530
+ };
531
+ const bounds = (array) => array.dimensions.map(({ lower, upper }) => {
532
+ const start = integer(lower);
533
+ const end = integer(upper);
534
+ if (end < start || !Number.isSafeInteger(end - start + 1)) {
535
+ throw new Error(`invalid array bounds ${lower}..${upper}`);
536
+ }
537
+ return { start, end };
538
+ });
539
+ const enumMembers = (enumeration) => {
540
+ const members = [];
541
+ for (const member of enumeration.members) {
542
+ const value = member.value === undefined ? (members.at(-1)?.value ?? -1) + 1 : integerExpression(member.value, (name) => members.find((item) => item.name.toUpperCase() === name.toUpperCase())?.value ?? constant(name, null));
543
+ members.push({ name: member.name, value });
544
+ }
545
+ return members;
546
+ };
547
+ return { constant, integer, declaration, aliasTarget, bounds, enumMembers };
548
+ }
445
549
 
446
550
  // packages/typegen/src/codegen/generate.ts
447
551
  var scalarType = (type) => {
448
- switch (type.family) {
449
- case "bool":
450
- return "boolean";
451
- case "integer":
452
- case "bits":
453
- return type.bits === 64 ? "bigint" : "number";
454
- case "real":
455
- return "number";
456
- case "duration":
457
- case "date":
458
- case "timeOfDay":
459
- case "dateTime":
460
- return type.bits === 32 ? "number" : undefined;
461
- case "char":
462
- case "string":
463
- return;
552
+ if (type.family === "bool") {
553
+ return "boolean";
464
554
  }
555
+ return isIntegerValued2(type) && !fitsNumber2(type) ? "bigint" : "number";
465
556
  };
466
- var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => {
467
- const typescript = scalarType(type);
468
- return typescript ? [[name, typescript]] : [];
469
- }));
470
- async function stFiles(directory) {
471
- const entries = await readdir(directory, { withFileTypes: true });
472
- const paths = await Promise.all(entries.sort((a, b) => {
473
- if (a.name === b.name) {
474
- return 0;
475
- }
476
- return a.name < b.name ? -1 : 1;
477
- }).map(async (entry) => {
478
- const file = join(directory, entry.name);
479
- if (entry.isDirectory()) {
480
- return stFiles(file);
481
- }
482
- return entry.isFile() && /\.st$/i.test(file) ? [file] : [];
483
- }));
484
- return paths.flat();
485
- }
557
+ var scalars = Object.fromEntries([...elementaryTypesByName].flatMap(([name, type]) => isWholeValue(type) ? [[name, scalarType(type)]] : []));
558
+ var sourceFiles = async (setting) => typeof setting === "string" ? stFiles(setting) : setting;
559
+ var contractNames = {
560
+ field: "PlcField",
561
+ globals: "PlcGlobals",
562
+ typeFields: "typeFields",
563
+ globalVariableLists: "globalVariableLists",
564
+ symbols: "symbols",
565
+ publication: "publication"
566
+ };
567
+ var fieldList = (index) => `_fields${index}`;
568
+ var isFieldList = (name) => /^_fields\d+$/.test(name);
569
+ var javascriptReserved = "break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval".split(" ");
486
570
  var quote = (value) => JSON.stringify(value);
487
571
  var documentation = (value) => value ? `/** ${value.replace(/\*\//g, "* /").replace(/\r?\n/g, `
488
572
  * `)} */
489
573
  ` : "";
490
- function unique(items) {
491
- const result = new Map;
492
- for (const item of items) {
493
- const key = item.name.toUpperCase();
494
- if (result.has(key)) {
495
- throw new Error(`${item.source}: duplicate declaration ${item.name} (also in ${result.get(key)?.source})`);
574
+ function assertUniqueNames(items) {
575
+ const seen = new Map;
576
+ for (const { name, source } of items) {
577
+ const key = name.toUpperCase();
578
+ const previous = seen.get(key);
579
+ if (previous !== undefined) {
580
+ throw new Error(`${source}: duplicate declaration ${name} (also in ${previous})`);
496
581
  }
497
- result.set(key, item);
582
+ seen.set(key, source);
498
583
  }
499
- return result;
500
584
  }
501
- var readSources = (files) => Promise.all(files.map(async (name) => ({ name, text: await readFile(name, "utf8") })));
502
585
  async function generateTypes(options) {
503
- const typeFiles = typeof options.types === "string" ? await stFiles(options.types) : options.types;
504
- const declarations = (await readSources(typeFiles)).flatMap((source) => parseDeclarations(source));
505
- const globalFiles = typeof options.globals === "string" ? await stFiles(options.globals) : options.globals ?? [];
586
+ const typeFiles = await sourceFiles(options.types);
587
+ const globalFiles = await sourceFiles(options.globals);
506
588
  if (!typeFiles.length && !globalFiles.length && (typeof options.types === "string" || typeof options.globals === "string")) {
507
589
  throw new Error(`no .st declarations found in ${typeof options.types === "string" ? options.types : "the selected source files"}`);
508
590
  }
509
- const globals = (await readSources(globalFiles)).map((source) => parseGlobals(source, basename(source.name).replace(/\.st$/i, "")));
510
- const publishedGlobalsOnly = options.publishedGlobalsOnly ?? false;
511
- const contract = emit(declarations, publishedGlobalsOnly ? published(globals, options.publication) : globals, { publishedGlobalsOnly, emitDeclarations: options.declarations ?? true });
512
- return options.publication ? `${contract}
513
- export const publication = ${JSON.stringify(options.publication, null, 2)} as const;
591
+ const { types: declarations, globals } = await parseSources({
592
+ types: typeFiles,
593
+ globals: globalFiles
594
+ });
595
+ const { publication } = options;
596
+ const contract = emit(declarations, publication ? published(globals, publication) : globals, {
597
+ publishedGlobalsOnly: publication !== null,
598
+ emitDeclarations: options.declarations
599
+ });
600
+ return publication ? `${contract}
601
+ export const ${contractNames.publication} = ${JSON.stringify(publication, null, 2)} as const;
514
602
  ` : contract;
515
603
  }
516
604
  function published(globals, publication) {
605
+ const selected = new Set([
606
+ ...publication.production,
607
+ ...publication.development
608
+ ]);
517
609
  return globals.map((list) => list.constant ? list : {
518
610
  ...list,
519
- members: list.members.filter((member) => publication ? [
520
- ...publication.production,
521
- ...publication.development
522
- ].includes(`${list.name}.${member.name}`) : member.symbol !== undefined)
611
+ members: list.members.filter((member) => selected.has(`${list.name}.${member.name}`))
523
612
  }).filter((list) => list.constant || list.members.length);
524
613
  }
525
614
  function emit(declarations, globals, {
526
615
  publishedGlobalsOnly,
527
616
  emitDeclarations
528
617
  }) {
529
- const types = unique(declarations);
530
- unique(globals);
618
+ assertUniqueNames(declarations);
619
+ assertUniqueNames(globals);
531
620
  const constants = globals.filter((list) => list.constant);
532
621
  const constantLists = publishedGlobalsOnly ? constants.map((list) => ({
533
622
  ...list,
534
- members: list.members.filter((member) => member.type.kind === "named" && isNumberInteger(member.type.name.toUpperCase()))
623
+ members: list.members.filter(isIntegerConstant)
535
624
  })).filter((list) => list.members.length) : constants;
536
625
  const variableLists = globals.filter((list) => !list.constant);
537
- const constant = constantResolver(constants);
538
- function bound(expression) {
539
- return integerExpression(expression, (name) => constant(name, null));
540
- }
541
- function dimensions(type) {
542
- return type.dimensions.map(({ lower, upper }) => {
543
- const start = bound(lower);
544
- const end = bound(upper);
545
- if (end < start || !Number.isSafeInteger(end - start + 1)) {
546
- throw new Error(`invalid array bounds ${lower}..${upper}`);
547
- }
548
- return { start, end };
549
- });
550
- }
551
- function declaration(name) {
552
- const found = types.get(name.toUpperCase());
553
- if (!found) {
554
- throw new Error(`unknown IEC type ${name}`);
555
- }
556
- return found;
557
- }
626
+ const { constant, integer, declaration, aliasTarget, bounds, enumMembers } = resolveDeclarations({ types: declarations, globals });
558
627
  function tsType(type) {
559
628
  if (type.kind === "array") {
560
- dimensions(type);
629
+ bounds(type);
561
630
  return type.dimensions.reduce((child) => `Array<${child}>`, tsType(type.element));
562
631
  }
563
632
  if (type.kind === "string") {
564
- const length = bound(type.length);
633
+ const length = integer(type.length);
565
634
  if (length < 1) {
566
635
  throw new Error(`invalid ${type.name} length ${length}`);
567
636
  }
@@ -570,25 +639,23 @@ function emit(declarations, globals, {
570
639
  return scalars[type.name.toUpperCase()] ?? declaration(type.name).name;
571
640
  }
572
641
  function resolved(type) {
573
- if (type.kind !== "named" || scalars[type.name.toUpperCase()]) {
574
- return type;
575
- }
576
- const definition = declaration(type.name);
577
- if (definition.kind === "alias") {
578
- return resolved(definition.type);
579
- }
580
- if (definition.kind === "enum") {
581
- return { kind: "named", name: definition.base };
642
+ const target = aliasTarget(type);
643
+ if (target.kind !== "named" || scalars[target.name.toUpperCase()]) {
644
+ return target;
582
645
  }
583
- return type;
646
+ const definition = declaration(target.name);
647
+ return definition.kind === "enum" ? { kind: "named", name: definition.base } : target;
584
648
  }
585
649
  function iecType(type) {
586
650
  const actual = resolved(type);
587
651
  if (actual.kind === "string") {
588
- return `${actual.name}(${bound(actual.length)})`;
652
+ return stringTypeText({
653
+ wide: actual.name === "WSTRING",
654
+ capacity: integer(actual.length)
655
+ });
589
656
  }
590
657
  if (actual.kind === "array") {
591
- return `ARRAY[${dimensions(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
658
+ return `ARRAY[${bounds(actual).map(({ start, end }) => `${start}..${end}`).join(", ")}] OF ${iecType(actual.element)}`;
592
659
  }
593
660
  return scalars[actual.name.toUpperCase()] ? actual.name.toUpperCase() : declaration(actual.name).name;
594
661
  }
@@ -625,17 +692,19 @@ function emit(declarations, globals, {
625
692
  ordered.push(type);
626
693
  }
627
694
  declarations.forEach(visit);
628
- const reserved = new Set("break case catch class const continue debugger default delete do else enum export extends false finally for function if import in instanceof new null return super switch this throw true try typeof var void while with yield let static implements interface package private protected public await arguments eval PlcGlobals PlcField typeFields symbols globalVariableLists publication".split(" "));
695
+ const reserved = new Set([
696
+ ...javascriptReserved,
697
+ ...Object.values(contractNames)
698
+ ]);
629
699
  for (const name of [
630
700
  ...declarations.map((type) => type.name),
631
701
  ...constantLists.map((list) => list.name)
632
702
  ]) {
633
- if (!identifierPattern2.test(name) || reserved.has(name) || /^_fields\d+$/.test(name)) {
703
+ if (!identifierPattern2.test(name) || reserved.has(name) || isFieldList(name)) {
634
704
  throw new Error(`name cannot be exported to TypeScript: ${name}`);
635
705
  }
636
706
  reserved.add(name);
637
707
  }
638
- const indexes = new Map(ordered.map((type, index) => [type.name, index]));
639
708
  function complex(type) {
640
709
  const actual = resolved(type);
641
710
  if (actual.kind === "array") {
@@ -653,14 +722,14 @@ function emit(declarations, globals, {
653
722
  function fields(type, path, description, depth = 0) {
654
723
  const actual = resolved(type);
655
724
  if (actual.kind === "named" && complex(actual)) {
656
- const children = `_fields${indexes.get(declaration(actual.name).name)}`;
725
+ const children = fieldList(ordered.indexOf(declaration(actual.name)));
657
726
  if (path === '""') {
658
727
  return children;
659
728
  }
660
729
  return `${children}.map((member) => ({ ...member, field: ${path} + "." + member.field }))`;
661
730
  }
662
731
  if (actual.kind === "array" && (complex(actual.element) || keyed(type))) {
663
- const ranges = dimensions(actual);
732
+ const ranges = bounds(actual);
664
733
  const coordinates = ranges.map((range, index) => `String(i${depth}_${index} + (${range.start}))`);
665
734
  const arrayPath = `${path} + "[" + ${coordinates.join(' + "," + ')} + "]"`;
666
735
  return ranges.reduceRight((child, range, index) => `Array.from({ length: ${range.end - range.start + 1} }, (_, i${depth}_${index}) => ${child}).flat()`, fields(actual.element, `(${arrayPath})`, description, depth + 1));
@@ -671,10 +740,10 @@ function emit(declarations, globals, {
671
740
  const output = [
672
741
  `// Generated by @tsplc/typegen. Edit the PLC sources and regenerate.
673
742
  `,
674
- `export interface PlcField { field: string; type: string; description: string; }
743
+ `export interface ${contractNames.field} { field: string; type: string; description: string; }
675
744
  `
676
745
  ];
677
- for (const type of ordered) {
746
+ for (const [index, type] of ordered.entries()) {
678
747
  try {
679
748
  const doc = documentation(type.description);
680
749
  if (type.kind === "struct") {
@@ -683,7 +752,7 @@ ${type.members.map((member) => `${documentation(member.description)}${quote(memb
683
752
  `)}
684
753
  }
685
754
  `));
686
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = [
755
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = [
687
756
  ${type.members.map((member) => `...${fields(member.type, quote(member.name), member.description)},`).join(`
688
757
  `)}
689
758
  ];
@@ -691,22 +760,17 @@ ${type.members.map((member) => `...${fields(member.type, quote(member.name), mem
691
760
  } else if (type.kind === "alias") {
692
761
  output.push(...declare(`${doc}export type ${type.name} = ${tsType(type.type)};
693
762
  `));
694
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
763
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.name }, '""', type.description)};
695
764
  `);
696
765
  } else {
697
- if (!isNumberInteger(type.base)) {
766
+ if (!fitsNumber2(elementaryType3(type.base))) {
698
767
  throw new Error(`unsupported enum base ${type.base}`);
699
768
  }
700
- const entries = new Map;
701
- for (const member of type.members) {
702
- const previous = [...entries.values()].at(-1) ?? -1;
703
- const value = member.value === undefined ? previous + 1 : integerExpression(member.value, (name) => entries.get(name.toUpperCase()) ?? constant(name, null));
704
- entries.set(member.name.toUpperCase(), value);
705
- }
706
- output.push(...declare(`${doc}export const ${type.name} = { ${type.members.map((member) => `${quote(member.name)}: ${entries.get(member.name.toUpperCase())}`).join(", ")} } as const;
769
+ const members = enumMembers(type);
770
+ output.push(...declare(`${doc}export const ${type.name} = { ${members.map(({ name, value }) => `${quote(name)}: ${value}`).join(", ")} } as const;
707
771
  export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
708
772
  `));
709
- output.push(`const _fields${indexes.get(type.name)}: PlcField[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
773
+ output.push(`const ${fieldList(index)}: ${contractNames.field}[] = ${fields({ kind: "named", name: type.base }, '""', type.description)};
710
774
  `);
711
775
  }
712
776
  } catch (error) {
@@ -717,9 +781,9 @@ export type ${type.name} = (typeof ${type.name})[keyof typeof ${type.name}];
717
781
  iecType(member.type),
718
782
  fields(member.type, '""', member.description)
719
783
  ]));
720
- output.push(`export const typeFields = {
784
+ output.push(`export const ${contractNames.typeFields} = {
721
785
  ${[
722
- ...ordered.map((type) => `${quote(type.name)}: _fields${indexes.get(type.name)},`),
786
+ ...ordered.map((type, index) => `${quote(type.name)}: ${fieldList(index)},`),
723
787
  ...[...inlineArrays].map(([type, members]) => `${quote(type)}: ${members},`)
724
788
  ].join(`
725
789
  `)}
@@ -732,7 +796,7 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
732
796
  } as const;
733
797
  `);
734
798
  }
735
- output.push(...declare(`export interface PlcGlobals {
799
+ output.push(...declare(`export interface ${contractNames.globals} {
736
800
  ${variableLists.map((list) => `${documentation(list.description)}${quote(list.name)}: {
737
801
  ${list.members.map((member) => `${documentation(member.description)}${quote(member.name)}: ${tsType(member.type)};`).join(`
738
802
  `)}
@@ -740,9 +804,9 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
740
804
  `)}
741
805
  }
742
806
  `));
743
- output.push(`export const globalVariableLists = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
807
+ output.push(`export const ${contractNames.globalVariableLists} = ${JSON.stringify(Object.fromEntries(variableLists.map((list) => [list.name, list.description])), null, "\t")} as const;
744
808
  `);
745
- output.push(`export const symbols = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
809
+ output.push(`export const ${contractNames.symbols} = ${JSON.stringify(variableLists.flatMap((list) => list.members.map((member) => ({
746
810
  name: member.name,
747
811
  gvl: list.name,
748
812
  type: member.type.kind === "named" && !scalars[member.type.name.toUpperCase()] ? declaration(member.type.name).name : iecType(member.type),
@@ -753,51 +817,68 @@ ${list.members.map((member) => `${documentation(member.description)}${quote(memb
753
817
  `);
754
818
  }
755
819
 
820
+ // packages/typegen/src/outputs.ts
821
+ import { randomUUID } from "node:crypto";
822
+ import { mkdir, rename, rm, writeFile } from "node:fs/promises";
823
+ import { dirname } from "node:path";
824
+ import { format } from "prettier";
825
+ var formatTypeScript = (source) => format(source, { parser: "typescript" });
826
+ async function writeOutputs(outputs) {
827
+ for (const { path, content } of outputs) {
828
+ if (content === null) {
829
+ await rm(path, { force: true });
830
+ continue;
831
+ }
832
+ await mkdir(dirname(path), { recursive: true });
833
+ const temporary = `${path}.${randomUUID()}.tmp`;
834
+ try {
835
+ await writeFile(temporary, content);
836
+ await rename(temporary, path);
837
+ } finally {
838
+ await rm(temporary, { force: true });
839
+ }
840
+ }
841
+ }
842
+ async function checkOutputs(outputs) {
843
+ for (const { path, content } of outputs) {
844
+ const actual = await readIfPresent(path);
845
+ const normalized = actual !== null && /\.ts$/i.test(path) ? await formatTypeScript(actual).catch(() => actual) : actual;
846
+ if (normalized !== content) {
847
+ throw new Error(`Generated file is missing or stale: ${path}`);
848
+ }
849
+ }
850
+ }
851
+
756
852
  // packages/typegen/src/project.ts
757
- import { mkdir, readFile as readFile4, rename, writeFile } from "node:fs/promises";
758
- import { dirname, resolve as resolve2 } from "node:path";
853
+ import { resolve as resolve2 } from "node:path";
759
854
  import {
760
855
  ioSymbolsSchema,
761
- loadTsplcConfig,
762
856
  publicationSchema,
763
- typegenSchema
857
+ typegenSettings
764
858
  } from "@tsplc/config";
765
859
  import {
766
860
  emittedFiles,
767
861
  emittedStDirectory,
768
- projectSnapshotFile
862
+ projectSnapshotFile,
863
+ stRoot
769
864
  } from "@tsplc/config/project-files";
770
- import { format } from "prettier";
865
+ import { isWithin } from "@tsplc/iec/st";
771
866
 
772
867
  // packages/typegen/src/codegen/declarations.ts
773
- import { readFile as readFile2 } from "node:fs/promises";
774
- import { blockCommentEnd as blockCommentEnd2, lineCommentEnd as lineCommentEnd2 } from "@tsplc/iec/st";
775
- var codeStart = (text, offset) => {
776
- const start = offset + text.slice(offset).search(/\S|$/);
777
- if (text.startsWith("(*", start)) {
778
- const end = blockCommentEnd2(text, start);
779
- return end === null ? start : codeStart(text, end);
780
- }
781
- if (text.startsWith("//", start)) {
782
- return codeStart(text, lineCommentEnd2(text, start));
783
- }
784
- if (text.startsWith("{", start)) {
785
- const end = text.indexOf("}", start);
786
- return end < 0 ? start : codeStart(text, end + 1);
787
- }
788
- return start;
789
- };
868
+ import { readFile as readFile3 } from "node:fs/promises";
790
869
  var declarationFiles = async (files) => {
791
870
  const sorted = {
792
871
  types: [],
793
872
  globals: []
794
873
  };
795
874
  for (const file of files) {
796
- const text = await readFile2(file, "utf8");
797
- const code = text.slice(codeStart(text, 0));
798
- if (/^TYPE\b/i.test(code)) {
875
+ const keyword = firstCodeToken({
876
+ name: file,
877
+ text: await readFile3(file, "utf8")
878
+ })?.toUpperCase();
879
+ if (keyword === "TYPE") {
799
880
  sorted.types.push(file);
800
- } else if (/^VAR_GLOBAL\b/i.test(code)) {
881
+ } else if (keyword === "VAR_GLOBAL") {
801
882
  sorted.globals.push(file);
802
883
  }
803
884
  }
@@ -805,14 +886,35 @@ var declarationFiles = async (files) => {
805
886
  };
806
887
 
807
888
  // packages/typegen/src/hardware.ts
808
- import { readdir as readdir2, readFile as readFile3 } from "node:fs/promises";
889
+ import { readFile as readFile4 } from "node:fs/promises";
809
890
  import { resolve } from "node:path";
891
+ import { tsplcConfigSchema } from "@tsplc/config/schema";
892
+
893
+ // packages/typegen/src/hardware/catalog.ts
894
+ var deviceChannel = (catalog, binding) => catalog.devices.find((device) => device.id === binding.device)?.channels.find((channel) => channel.id === binding.channel);
895
+ function boundChannel(catalog, symbol, binding) {
896
+ const channel = deviceChannel(catalog, binding);
897
+ if (!channel?.address) {
898
+ throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
899
+ }
900
+ return { ...channel, address: channel.address };
901
+ }
810
902
 
811
903
  // packages/typegen/src/hardware/channels.ts
812
- import { ioScalarBits } from "@tsplc/iec";
904
+ import { arrayTypeText, ioScalarBits } from "@tsplc/iec";
813
905
 
814
906
  // packages/typegen/src/hardware/process-image.ts
815
- import { ioArray, ioScalar, sizePrefix } from "@tsplc/iec";
907
+ import {
908
+ elementaryTypes as elementaryTypes2,
909
+ ioArray,
910
+ ioScalar,
911
+ isIntegerValued as isIntegerValued3,
912
+ isWholeValue as isWholeValue2,
913
+ sizePrefix,
914
+ sizePrefixes
915
+ } from "@tsplc/iec";
916
+ var scalarLayout = (scalar) => isIntegerValued3(scalar) ? `INT${scalar.bits}` : scalar.name;
917
+ var scalarLayoutBits = new Map(elementaryTypes2.filter(isWholeValue2).map((scalar) => [scalarLayout(scalar), scalar.bits]));
816
918
  function ioLayout(type) {
817
919
  const array = ioArray(type.trim());
818
920
  if (array) {
@@ -820,11 +922,9 @@ function ioLayout(type) {
820
922
  return element && element !== "BOOL" ? `${array.length}x${element}` : undefined;
821
923
  }
822
924
  const scalar = ioScalar(type);
823
- if (scalar?.family === "integer" || scalar?.family === "bits") {
824
- return `INT${scalar.bits}`;
825
- }
826
- return scalar?.name;
925
+ return scalar && scalarLayout(scalar);
827
926
  }
927
+ var layoutBits = (layout) => scalarLayoutBits.get(layout.replace(/^\d+x/, ""));
828
928
  var addressSize = (bits) => bits === 64 ? undefined : sizePrefix(bits);
829
929
  function directAddress(region, base, offsetBits, bits) {
830
930
  const size = addressSize(bits);
@@ -840,20 +940,23 @@ function directAddress(region, base, offsetBits, bits) {
840
940
  }
841
941
  return `%${region}${size}${byte / (bits / 8)}`;
842
942
  }
843
- var byteOffset = (address) => Number(address.slice(3));
943
+ function addressBits(address) {
944
+ const [, region, size, index, bit] = /^%([IQ])([A-Z])(\d+)(?:\.([0-7]))?$/.exec(address) ?? [];
945
+ const bits = size === undefined ? undefined : sizePrefixes.get(size)?.bits;
946
+ if (region !== "I" && region !== "Q" || bits === undefined || addressSize(bits) !== size || bits === 1 !== (bit !== undefined)) {
947
+ return;
948
+ }
949
+ const offsetBits = bits === 1 ? Number(index) * 8 + Number(bit) : Number(index) * bits;
950
+ return { region, offsetBits, bits };
951
+ }
952
+ var regionOf = (direction) => direction === "input" ? "I" : "Q";
844
953
  function regionPlacer(regions, { generatedTree }) {
845
- const taken = regions.flatMap(({ region, size, address }) => address ? [
846
- {
847
- region,
848
- start: byteOffset(address),
849
- end: byteOffset(address) + size
850
- }
851
- ] : []);
954
+ const taken = regions.flatMap(({ region, size, offset }) => offset === undefined ? [] : [{ region, start: offset, end: offset + size }]);
852
955
  const cursors = { I: 0, Q: 0 };
853
956
  const aligned = (offset) => Math.ceil(offset / 4) * 4;
854
- return ({ id, region, size, address }) => {
855
- if (address) {
856
- return address;
957
+ return ({ id, region, size, offset }) => {
958
+ if (offset !== undefined) {
959
+ return offset;
857
960
  }
858
961
  if (!generatedTree) {
859
962
  throw new Error(`${id}: set the %${region}B address the template assigns to this assembly, or let codesys.deviceTree place it.`);
@@ -865,7 +968,7 @@ function regionPlacer(regions, { generatedTree }) {
865
968
  const start = clear(aligned(cursors[region]));
866
969
  taken.push({ region, start, end: start + size });
867
970
  cursors[region] = start + size;
868
- return `%${region}B${start}`;
971
+ return start;
869
972
  };
870
973
  }
871
974
 
@@ -879,7 +982,7 @@ function assemblyChannels({
879
982
  payloadSize
880
983
  }) {
881
984
  const prefix = `${direction}s`;
882
- const region = direction === "input" ? "I" : "Q";
985
+ const region = regionOf(direction);
883
986
  const payloadBits = payloadSize * 8;
884
987
  const address = (offsetBits, bits) => directAddress(region, base, offsetBits, bits);
885
988
  const channels = [];
@@ -957,7 +1060,11 @@ function assemblyChannels({
957
1060
  const span = {
958
1061
  ...channel,
959
1062
  bits: length * scalarBits,
960
- type: `ARRAY[0..${length - 1}] OF ${member.type}`,
1063
+ type: arrayTypeText({
1064
+ lower: 0,
1065
+ upper: length - 1,
1066
+ element: member.type
1067
+ }),
961
1068
  address: address(member.offsetBits, scalarBits)
962
1069
  };
963
1070
  channels.push(span);
@@ -996,6 +1103,23 @@ var cipTypes = {
996
1103
  211: "DWORD",
997
1104
  212: "LWORD"
998
1105
  };
1106
+ var connectionFields = {
1107
+ transport: 0,
1108
+ outputSize: 3,
1109
+ outputFormat: 4,
1110
+ inputSize: 6,
1111
+ inputFormat: 7,
1112
+ name: 12,
1113
+ path: 14
1114
+ };
1115
+ var assemblyFields = {
1116
+ name: 0,
1117
+ path: 1,
1118
+ size: 2,
1119
+ descriptor: 3,
1120
+ firstMember: 6
1121
+ };
1122
+ var isConnection = (key) => /^Connection\d+$/.test(key);
999
1123
  function stripComments(text) {
1000
1124
  let clean = "";
1001
1125
  const offsets = [];
@@ -1075,14 +1199,15 @@ function edsSections(text) {
1075
1199
  if (!section) {
1076
1200
  throw new Error("EDS record outside a section.");
1077
1201
  }
1202
+ const start = offsets[match.index];
1203
+ const last = offsets[end - 1];
1204
+ if (key === undefined || body === undefined || start === undefined || last === undefined) {
1205
+ throw new Error("Malformed EDS record or section.");
1206
+ }
1078
1207
  if (section.has(key)) {
1079
1208
  throw new Error(`Duplicate EDS record ${key}.`);
1080
1209
  }
1081
- section.set(key, {
1082
- fields: recordFields(body),
1083
- start: offsets[match.index],
1084
- end: offsets[end - 1] + 1
1085
- });
1210
+ section.set(key, { fields: recordFields(body), start, end: last + 1 });
1086
1211
  }
1087
1212
  if (clean.slice(end).trim()) {
1088
1213
  throw new Error("Unterminated EDS record.");
@@ -1128,21 +1253,29 @@ function logicalSegments(bytes) {
1128
1253
  ...logicalSegments(data.slice(length))
1129
1254
  ];
1130
1255
  }
1131
- function logicalPath(path) {
1132
- const bytes = path.trim() ? path.trim().split(/\s+/).map((token) => {
1133
- if (!/^[0-9a-f]{2}$/i.test(token)) {
1256
+ function pathBytes(path, params) {
1257
+ return path.trim().split(/\s+/).filter(Boolean).flatMap((token) => {
1258
+ if (/^[0-9a-f]{2}$/i.test(token)) {
1259
+ return [parseInt(token, 16)];
1260
+ }
1261
+ const reference = /^\[(Param\d+)\]$/.exec(token)?.[1];
1262
+ const parameter = reference ? params.get(reference) : undefined;
1263
+ if (!parameter || parameter.default === undefined) {
1134
1264
  throw new Error(`Unsupported EDS path token ${token}.`);
1135
1265
  }
1136
- return parseInt(token, 16);
1137
- }) : [];
1138
- const segments = logicalSegments(bytes);
1266
+ const value = parameter.default;
1267
+ return Array.from({ length: parameter.size }, (_, index) => Math.floor(value / 2 ** (index * 8)) % 256);
1268
+ });
1269
+ }
1270
+ function logicalPath(path, params) {
1271
+ const segments = logicalSegments(pathBytes(path, params));
1139
1272
  return {
1140
1273
  instance: segments.filter(({ type }) => type === 36).at(-1)?.value,
1141
1274
  points: segments.filter(({ type }) => type === 44).map(({ value }) => value)
1142
1275
  };
1143
1276
  }
1144
1277
  var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
1145
- function parseEds(text, file = "device.eds") {
1278
+ function parseEds(text, file) {
1146
1279
  const records = readEdsRecords(text);
1147
1280
  const device = records.Device;
1148
1281
  if (!device?.ProdName?.[0]) {
@@ -1161,6 +1294,7 @@ function parseEds(text, file = "device.eds") {
1161
1294
  }));
1162
1295
  const params = new Map(parameters.map((parameter) => [parameter.id, parameter]));
1163
1296
  const instances = new Map;
1297
+ const recordless = new Map;
1164
1298
  const size = (value) => {
1165
1299
  if (!value) {
1166
1300
  return;
@@ -1179,18 +1313,24 @@ function parseEds(text, file = "device.eds") {
1179
1313
  maximum: parameter.maximum
1180
1314
  };
1181
1315
  };
1182
- const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => /^Connection\d+$/.test(id)).map(([id, fields]) => {
1183
- const path = fields[14] ?? "";
1184
- const points = logicalPath(path).points;
1185
- const assembly = (reference, point) => {
1316
+ const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => isConnection(id)).map(([id, fields]) => {
1317
+ const path = fields[connectionFields.path] ?? "";
1318
+ const points = logicalPath(path, params).points;
1319
+ const outputSize = size(fields[connectionFields.outputSize]);
1320
+ const inputSize = size(fields[connectionFields.inputSize]);
1321
+ const assembly = (reference, point, payload) => {
1186
1322
  if (!reference) {
1187
- return;
1323
+ if (!payload || payload.value <= 0 || point === undefined) {
1324
+ return;
1325
+ }
1326
+ recordless.set(point, Math.max(recordless.get(point) ?? 0, payload.maximum ?? payload.value));
1327
+ return point;
1188
1328
  }
1189
1329
  const record = records.Assembly?.[reference];
1190
1330
  if (!/^Assem\d+$/.test(reference) || !record) {
1191
1331
  throw new Error(`${file}: unknown connection assembly ${reference}.`);
1192
1332
  }
1193
- const instance = point ?? logicalPath(record[1] ?? "").instance;
1333
+ const instance = point ?? logicalPath(record[assemblyFields.path] ?? "", params).instance;
1194
1334
  if (instance === undefined) {
1195
1335
  throw new Error(`${file}: no runtime instance for ${reference}.`);
1196
1336
  }
@@ -1203,19 +1343,19 @@ function parseEds(text, file = "device.eds") {
1203
1343
  };
1204
1344
  return {
1205
1345
  id,
1206
- name: fields[12] || id,
1207
- owner: /^0x[\da-f]{8}$/i.test(fields[0] ?? "") && (Number(fields[0]) >>> 24 & 15) === 4,
1346
+ name: fields[connectionFields.name] || id,
1347
+ owner: /^0x[\da-f]{8}$/i.test(fields[connectionFields.transport] ?? "") && (Number(fields[connectionFields.transport]) >>> 24 & 15) === 4,
1208
1348
  path,
1209
- outputAssembly: assembly(fields[4], points.at(-2)),
1210
- inputAssembly: assembly(fields[7], points.at(-1)),
1211
- outputSize: size(fields[3]),
1212
- inputSize: size(fields[6])
1349
+ outputAssembly: assembly(fields[connectionFields.outputFormat], points.at(-2), outputSize),
1350
+ inputAssembly: assembly(fields[connectionFields.inputFormat], points.at(-1), inputSize),
1351
+ outputSize,
1352
+ inputSize
1213
1353
  };
1214
1354
  });
1215
1355
  const assemblies = Object.entries(records.Assembly ?? {}).filter(([id]) => /^Assem\d+$/.test(id)).map(([id, fields]) => {
1216
1356
  const members = [];
1217
1357
  let offsetBits = 0;
1218
- for (let index = 6;index < fields.length; index += 2) {
1358
+ for (let index = assemblyFields.firstMember;index < fields.length; index += 2) {
1219
1359
  if (!fields[index] && !fields[index + 1]) {
1220
1360
  continue;
1221
1361
  }
@@ -1238,13 +1378,31 @@ function parseEds(text, file = "device.eds") {
1238
1378
  });
1239
1379
  offsetBits += bits;
1240
1380
  }
1241
- const size = fields[2] ? integer(fields[2], `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
1381
+ const declared = fields[assemblyFields.size];
1382
+ const size = declared ? integer(declared, `${id} size`, { minimum: 0 }) : Math.ceil(offsetBits / 8);
1242
1383
  if (offsetBits > size * 8) {
1243
1384
  throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
1244
1385
  }
1245
- const instance = logicalPath(fields[1] ?? "").instance ?? instances.get(id);
1246
- return { id, instance, name: fields[0] || id, size, members };
1386
+ const instance = logicalPath(fields[assemblyFields.path] ?? "", params).instance ?? instances.get(id);
1387
+ return {
1388
+ id,
1389
+ instance,
1390
+ name: fields[assemblyFields.name] || id,
1391
+ size,
1392
+ members
1393
+ };
1247
1394
  });
1395
+ for (const [instance, payloadSize] of recordless) {
1396
+ if (!assemblies.some((assembly) => assembly.instance === instance)) {
1397
+ assemblies.push({
1398
+ id: `Instance${instance}`,
1399
+ instance,
1400
+ name: `Assembly ${instance}`,
1401
+ size: payloadSize,
1402
+ members: []
1403
+ });
1404
+ }
1405
+ }
1248
1406
  return {
1249
1407
  file,
1250
1408
  name: device.ProdName[0],
@@ -1263,21 +1421,35 @@ function placeModbusRegisters(device, registers, place) {
1263
1421
  if (!entries.length) {
1264
1422
  return [];
1265
1423
  }
1266
- const outputBase = byteOffset(place({ id: device, region: "Q", size: entries.length * registerBytes.Q }));
1267
- const inputBase = byteOffset(place({ id: device, region: "I", size: entries.length * registerBytes.I }));
1424
+ const outputBase = place({
1425
+ id: device,
1426
+ region: "Q",
1427
+ size: entries.length * registerBytes.Q
1428
+ });
1429
+ const inputBase = place({
1430
+ id: device,
1431
+ region: "I",
1432
+ size: entries.length * registerBytes.I
1433
+ });
1268
1434
  return entries.map(([name, offset], index) => {
1269
- const channel = (field, direction, offsetBits, bits, type, description) => ({
1270
- device,
1271
- id: `modbus.${name}.${field}`,
1272
- name: `${name} ${field}`,
1273
- direction,
1274
- offsetBits,
1275
- bits,
1276
- type,
1277
- address: directAddress(direction === "input" ? "I" : "Q", direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits),
1278
- unit: "",
1279
- description
1280
- });
1435
+ const channel = (field, direction, offsetBits, bits, type, description) => {
1436
+ const address = directAddress(regionOf(direction), direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits);
1437
+ if (!address) {
1438
+ throw new Error(`${device}: Modbus register ${name} ${field} has no direct address.`);
1439
+ }
1440
+ return {
1441
+ device,
1442
+ id: `modbus.${name}.${field}`,
1443
+ name: `${name} ${field}`,
1444
+ direction,
1445
+ offsetBits,
1446
+ bits,
1447
+ type,
1448
+ address,
1449
+ unit: "",
1450
+ description
1451
+ };
1452
+ };
1281
1453
  const value = channel("value", "output", 0, 16, "WORD", "Value to write");
1282
1454
  const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
1283
1455
  const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
@@ -1316,6 +1488,14 @@ function selectConnection(id, settings, descriptor) {
1316
1488
  const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
1317
1489
  throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
1318
1490
  }
1491
+ function configuredByte(id, direction, address) {
1492
+ const region = regionOf(direction);
1493
+ const location = addressBits(address);
1494
+ if (location?.region !== region || location.bits !== 8) {
1495
+ throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
1496
+ }
1497
+ return location.offsetBits / 8;
1498
+ }
1319
1499
  function selectAssemblies(id, settings, descriptor, connection) {
1320
1500
  return ["input", "output"].flatMap((direction) => {
1321
1501
  const selection = direction === "input" ? settings.inputs : settings.outputs;
@@ -1330,10 +1510,8 @@ function selectAssemblies(id, settings, descriptor, connection) {
1330
1510
  if (!assembly) {
1331
1511
  throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
1332
1512
  }
1333
- const region = direction === "input" ? "I" : "Q";
1334
- if (selection?.address && !selection.address.startsWith(`%${region}B`)) {
1335
- throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
1336
- }
1513
+ const region = regionOf(direction);
1514
+ const offset = selection?.address === undefined ? undefined : configuredByte(id, direction, selection.address);
1337
1515
  const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
1338
1516
  const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
1339
1517
  if (!Number.isSafeInteger(payloadSize) || payloadSize <= 0 || payloadSize > assembly.size || declaredSize?.minimum !== undefined && payloadSize < declaredSize.minimum || declaredSize?.maximum !== undefined && payloadSize > declaredSize.maximum || selection?.size !== undefined && declaredSize && !declaredSize.parameter && payloadSize !== declaredSize.value) {
@@ -1347,29 +1525,51 @@ function selectAssemblies(id, settings, descriptor, connection) {
1347
1525
  instance,
1348
1526
  assembly,
1349
1527
  size: payloadSize,
1350
- address: selection?.address
1528
+ offset
1351
1529
  }
1352
1530
  ];
1353
1531
  });
1354
1532
  }
1355
1533
 
1356
1534
  // packages/typegen/src/hardware.ts
1357
- import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
1535
+ import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
1358
1536
 
1537
+ // packages/typegen/src/device-tree.ts
1538
+ import { iecName } from "@tsplc/config/build";
1359
1539
  // packages/typegen/src/hardware/mapping-types.ts
1360
- import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
1540
+ import { relative, sep } from "node:path";
1541
+ import { sizePrefixes as sizePrefixes2 } from "@tsplc/iec";
1542
+ var region = '${"I" | "Q"}';
1543
+ var bitAddress = `\`%${region}X\${number}.\${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}\``;
1544
+ var byteSizes = [...sizePrefixes2].filter(([prefix, type]) => type.bits > 1 && addressSize(type.bits) === prefix).map(([prefix]) => JSON.stringify(prefix)).join(" | ");
1545
+ var addressBinding = (address) => `{ address: ${address}; type?: string }`;
1361
1546
  var directBinding = (layout) => {
1362
- const scalar = layout.replace(/^\d+x/, "");
1363
- const integer = /^INT(\d+)$/.exec(scalar);
1364
- const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
1547
+ const bits = layoutBits(layout);
1365
1548
  const size = bits === undefined ? undefined : addressSize(bits);
1366
1549
  if (!size) {
1367
1550
  return;
1368
1551
  }
1369
- return size === "X" ? '{ address: `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }' : `{ address: \`%\${"I" | "Q"}${size}\${number}\`; type?: string }`;
1552
+ return addressBinding(size === "X" ? bitAddress : `\`%${region}${size}\${number}\``);
1553
+ };
1554
+ var portableCatalog = (catalog, root) => {
1555
+ const portable = (file) => relative(root, file).split(sep).join("/");
1556
+ return {
1557
+ descriptors: catalog.descriptors.map((descriptor) => ({
1558
+ ...descriptor,
1559
+ file: portable(descriptor.file)
1560
+ })),
1561
+ devices: catalog.devices.map((device) => ({
1562
+ ...device,
1563
+ descriptor: portable(device.descriptor)
1564
+ }))
1565
+ };
1370
1566
  };
1371
- function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
1372
- const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
1567
+ function generateHardwareTypes(catalog, {
1568
+ root,
1569
+ targets,
1570
+ ioTypes
1571
+ }) {
1572
+ const selectors = targets?.publication.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
1373
1573
  const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
1374
1574
  export type PublicationSelector = ${selectors || "never"};
1375
1575
  export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
@@ -1382,11 +1582,11 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1382
1582
  binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
1383
1583
  layout: ioLayout(item.type)
1384
1584
  })));
1385
- const direct = '{ address: `%${"I" | "Q"}${"B" | "W" | "D"}${number}` | `%${"I" | "Q"}X${number}.${0 | 1 | 2 | 3 | 4 | 5 | 6 | 7}`; type?: string }';
1585
+ const direct = addressBinding(`\`%${region}\${${byteSizes}}\${number}\` | ${bitAddress}`);
1386
1586
  const anyBinding = [...channels.map((item) => item.binding), direct].join(`
1387
1587
  | `);
1388
- const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
1389
- const keys = targets.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
1588
+ const mapping = targets ? [...new Set(targets.io.map((target) => target.layout))].sort().map((layout) => {
1589
+ const keys = targets.io.filter((target) => target.layout === layout).map((target) => `\`${target.key}\``);
1390
1590
  const bindings = [
1391
1591
  ...channels.filter((item) => item.layout === layout).map((item) => item.binding),
1392
1592
  directBinding(layout)
@@ -1397,45 +1597,37 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1397
1597
  }).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
1398
1598
  return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
1399
1599
  export type HardwareIoMapping = ${mapping};
1400
- export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
1600
+ export const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;
1401
1601
  `;
1402
1602
  }
1403
1603
 
1404
1604
  // packages/typegen/src/hardware.ts
1405
- async function edsFiles(directory) {
1406
- const entries = await readdir2(directory, { withFileTypes: true }).catch((cause) => {
1407
- if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1408
- return [];
1409
- }
1410
- throw cause;
1411
- });
1412
- const files = [];
1413
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
1414
- const path = resolve(directory, entry.name);
1415
- if (entry.isDirectory()) {
1416
- files.push(...await edsFiles(path));
1417
- } else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
1418
- files.push(path);
1419
- }
1605
+ var defaultEds = tsplcConfigSchema.shape.eds.parse(undefined);
1606
+ var edsFiles = (config, directory) => filesUnder(directory, "eds", (a, b) => a.localeCompare(b)).catch((error) => {
1607
+ if (config.eds === defaultEds && isMissingFile(error)) {
1608
+ return [];
1420
1609
  }
1421
- return files;
1422
- }
1610
+ throw error;
1611
+ });
1423
1612
  async function readDescriptors(config, root) {
1424
1613
  const files = new Set;
1425
1614
  for (const directory of [config.eds].flat()) {
1426
- for (const file of await edsFiles(resolve(root, directory))) {
1615
+ for (const file of await edsFiles(config, resolve(root, directory))) {
1427
1616
  files.add(file);
1428
1617
  }
1429
1618
  }
1430
1619
  for (const device of Object.values(config.devices)) {
1431
1620
  files.add(resolve(root, device.file));
1432
1621
  }
1433
- return Promise.all([...files].map(async (file) => parseEds(await readFile3(file, "utf8"), file)));
1622
+ return new Map(await Promise.all([...files].map(async (file) => [file, parseEds(await readFile4(file, "utf8"), file)])));
1434
1623
  }
1435
1624
  async function loadHardware(config, root) {
1436
1625
  const descriptors = await readDescriptors(config, root);
1437
1626
  const selected = Object.entries(config.devices).map(([id, settings]) => {
1438
- const descriptor = descriptors.find((d) => d.file === resolve(root, settings.file));
1627
+ const descriptor = descriptors.get(resolve(root, settings.file));
1628
+ if (!descriptor) {
1629
+ throw new Error(`${id}: ${settings.file} was not read.`);
1630
+ }
1439
1631
  const connection = selectConnection(id, settings, descriptor);
1440
1632
  const selections = selectAssemblies(id, settings, descriptor, connection);
1441
1633
  return { id, settings, descriptor, connection, selections };
@@ -1443,10 +1635,14 @@ async function loadHardware(config, root) {
1443
1635
  const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
1444
1636
  const placed = selected.map((device) => ({
1445
1637
  ...device,
1446
- assemblies: device.selections.map((selection) => ({
1447
- ...selection,
1448
- address: place(selection)
1449
- }))
1638
+ assemblies: device.selections.map((selection) => {
1639
+ const offset = place(selection);
1640
+ const address = directAddress(selection.region, offset, 0, 8);
1641
+ if (!address) {
1642
+ throw new Error(`${device.id}: byte ${offset} has no direct address.`);
1643
+ }
1644
+ return { ...selection, offset, address };
1645
+ })
1450
1646
  }));
1451
1647
  const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
1452
1648
  const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
@@ -1468,12 +1664,12 @@ async function loadHardware(config, root) {
1468
1664
  })),
1469
1665
  channels: [
1470
1666
  ...registers.flatMap((register) => register.channels),
1471
- ...assemblies.flatMap(({ direction, instance, assembly, size, address }) => assemblyChannels({
1667
+ ...assemblies.flatMap(({ direction, instance, assembly, size, offset }) => assemblyChannels({
1472
1668
  device: id,
1473
1669
  direction,
1474
1670
  instance,
1475
1671
  members: assembly.members,
1476
- base: byteOffset(address),
1672
+ base: offset,
1477
1673
  payloadSize: size
1478
1674
  }))
1479
1675
  ],
@@ -1486,18 +1682,14 @@ async function loadHardware(config, root) {
1486
1682
  }
1487
1683
  };
1488
1684
  });
1489
- return { descriptors, devices };
1685
+ return { descriptors: [...descriptors.values()], devices };
1490
1686
  }
1491
1687
  function resolveIo(config, catalog) {
1492
1688
  return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
1493
1689
  if ("address" in binding) {
1494
1690
  return [symbol, binding];
1495
1691
  }
1496
- const device = catalog.devices.find((d) => d.id === binding.device);
1497
- const channel = device?.channels.find((c) => c.id === binding.channel);
1498
- if (!channel?.address) {
1499
- throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
1500
- }
1692
+ const channel = boundChannel(catalog, symbol, binding);
1501
1693
  return [
1502
1694
  symbol,
1503
1695
  {
@@ -1511,22 +1703,24 @@ function resolveIo(config, catalog) {
1511
1703
  }
1512
1704
 
1513
1705
  // packages/typegen/src/project.ts
1514
- var formatTypeScript = (source) => format(source, { parser: "typescript" });
1515
- var readPublication = async (root) => publicationSchema.parse(JSON.parse(await readFile4(resolve2(root, emittedStDirectory, emittedFiles.publication), "utf8")));
1706
+ var emittedPath = (root, file) => resolve2(root, emittedStDirectory, file);
1707
+ var missingEmission = (root) => new Error(`No emitted Structured Text in ${resolve2(root, emittedStDirectory)}: emit the program with tsplc build --emit-only, or check with tsplc typegen --check, which emits it first.`);
1708
+ var readPublication = async (root) => {
1709
+ const text = await readIfPresent(emittedPath(root, emittedFiles.publication));
1710
+ if (text === null) {
1711
+ throw missingEmission(root);
1712
+ }
1713
+ return publicationSchema.parse(JSON.parse(text));
1714
+ };
1516
1715
  var generatedFiles = {
1517
1716
  hardware: "hardware.ts",
1518
1717
  contract: "plc.ts",
1519
1718
  machines: "machines.ts"
1520
1719
  };
1521
1720
  async function readIoSymbols(root) {
1522
- const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
1523
- const text = await readFile4(file, "utf8").catch((error) => {
1524
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1525
- return "{}";
1526
- }
1527
- throw error;
1528
- });
1529
- const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
1721
+ const file = emittedPath(root, emittedFiles.ioSymbols);
1722
+ const text = await readIfPresent(file);
1723
+ const symbols = ioSymbolsSchema.safeParse(JSON.parse(text ?? "{}"));
1530
1724
  if (!symbols.success) {
1531
1725
  throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
1532
1726
  }
@@ -1537,6 +1731,7 @@ async function contractSources(config, root, settings) {
1537
1731
  const types = directories(settings.types);
1538
1732
  const globals = directories(settings.globals);
1539
1733
  if (types.length || globals.length) {
1734
+ const filesIn = async (directories) => (await Promise.all(directories.map(stFiles))).flat();
1540
1735
  const sources = {
1541
1736
  types: await filesIn(types),
1542
1737
  globals: await filesIn(globals),
@@ -1547,56 +1742,32 @@ async function contractSources(config, root, settings) {
1547
1742
  }
1548
1743
  return sources;
1549
1744
  }
1550
- const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
1745
+ const source = stRoot(config);
1551
1746
  if (!source) {
1552
- if (config.typegen) {
1553
- throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1554
- }
1555
- return;
1747
+ throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1556
1748
  }
1557
1749
  const sourceRoot = resolve2(root, source);
1558
- const files = await stFiles(sourceRoot);
1750
+ const files = await stFiles(sourceRoot).catch((cause) => {
1751
+ if (!isMissingFile(cause)) {
1752
+ throw cause;
1753
+ }
1754
+ throw config.compiler ? missingEmission(root) : new Error(`build.sourceDir ${sourceRoot} doesn't exist.`);
1755
+ });
1559
1756
  if (!files.length) {
1560
1757
  throw new Error(`no .st declarations found in ${sourceRoot}`);
1561
1758
  }
1562
1759
  return { ...await declarationFiles(files), explicit: false };
1563
1760
  }
1564
- async function filesIn(directories) {
1565
- const files = [];
1566
- for (const directory of directories) {
1567
- files.push(...await stFiles(directory));
1568
- }
1569
- return files;
1570
- }
1571
1761
  function checkHmiTargets(controls, published) {
1572
1762
  for (const { target } of controls) {
1573
- if (!published.some((symbol) => target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`))) {
1763
+ if (!published.some((symbol) => isWithin(symbol, target))) {
1574
1764
  throw new Error(`HMI control ${target} is not in the production publication.`);
1575
1765
  }
1576
1766
  }
1577
1767
  }
1578
- async function writeOutputs(outputs) {
1579
- for (const output of outputs) {
1580
- await mkdir(dirname(output.path), { recursive: true });
1581
- const temp = `${output.path}.${process.pid}.tmp`;
1582
- await writeFile(temp, output.content);
1583
- await rename(temp, output.path);
1584
- }
1585
- }
1586
- async function checkOutputs(outputs) {
1587
- for (const output of outputs) {
1588
- const actual = await readFile4(output.path, "utf8").catch(() => {
1589
- return;
1590
- });
1591
- const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await formatTypeScript(actual) : actual;
1592
- if (normalized !== output.content) {
1593
- throw new Error(`Generated file is missing or stale: ${output.path}`);
1594
- }
1595
- }
1596
- }
1597
- async function generateProject(file = "tsplc.config.ts", options = {}) {
1598
- const { config, root, configFile } = options.loaded ?? await loadTsplcConfig(file);
1599
- const settings = typegenSchema.parse(config.typegen ?? {});
1768
+ async function generateProject({ config, root, configFile }, options = {}) {
1769
+ const hardwareOnly = options.hardwareOnly || !config.compiler && !config.typegen;
1770
+ const settings = typegenSettings(config);
1600
1771
  const catalog = await loadHardware(config, root);
1601
1772
  const io = resolveIo(config, catalog);
1602
1773
  const project = {
@@ -1608,44 +1779,53 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1608
1779
  const outputs = [
1609
1780
  {
1610
1781
  path: resolve2(root, settings.dir, generatedFiles.hardware),
1611
- content: await formatTypeScript(generateHardwareTypes(catalog, options.targets?.io, options.targets?.publication, settings.ioTypes))
1782
+ content: await formatTypeScript(generateHardwareTypes(catalog, {
1783
+ root,
1784
+ targets: options.targets ?? null,
1785
+ ioTypes: settings.ioTypes
1786
+ }))
1612
1787
  },
1613
- {
1614
- path: resolve2(root, projectSnapshotFile),
1615
- content: `${JSON.stringify(project, null, 2)}
1788
+ ...options.check ? [] : [
1789
+ {
1790
+ path: resolve2(root, projectSnapshotFile),
1791
+ content: `${JSON.stringify(project, null, 2)}
1616
1792
  `
1617
- }
1793
+ }
1794
+ ]
1618
1795
  ];
1619
- const sources = options.hardwareOnly ? undefined : await contractSources(config, root, settings);
1620
- if (sources) {
1621
- const inferred = !!config.compiler && !sources.explicit;
1622
- outputs.push({
1623
- path: resolve2(root, settings.dir, generatedFiles.contract),
1624
- content: await formatTypeScript(await generateTypes({
1625
- types: sources.types,
1626
- globals: sources.globals,
1627
- publishedGlobalsOnly: inferred,
1628
- declarations: settings.declarations,
1629
- publication: inferred ? await readPublication(root) : undefined
1630
- }))
1631
- });
1796
+ const sources = hardwareOnly ? null : await contractSources(config, root, settings);
1797
+ const inferred = sources !== null && !!config.compiler && !sources.explicit;
1798
+ const hmi = config.compiler && config.publish && !hardwareOnly ? config.hmi : undefined;
1799
+ const publication = inferred || hmi ? await readPublication(root) : null;
1800
+ const contract = sources && {
1801
+ path: resolve2(root, settings.dir, generatedFiles.contract),
1802
+ content: await formatTypeScript(await generateTypes({
1803
+ types: sources.types,
1804
+ globals: sources.globals,
1805
+ publication: inferred ? publication : null,
1806
+ declarations: settings.declarations
1807
+ }))
1808
+ };
1809
+ if (contract) {
1810
+ outputs.push(contract);
1632
1811
  }
1633
- if (config.hmi && config.publish && config.compiler && !options.hardwareOnly) {
1634
- checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
1812
+ if (hmi && publication) {
1813
+ checkHmiTargets(hmi.controls, publication.production);
1635
1814
  }
1636
- if (config.compiler && !options.hardwareOnly) {
1637
- const machine = await readFile4(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
1638
- return;
1815
+ if (config.compiler && !hardwareOnly) {
1816
+ const machines = await readIfPresent(emittedPath(root, emittedFiles.machines));
1817
+ outputs.push({
1818
+ path: resolve2(root, settings.dir, generatedFiles.machines),
1819
+ content: machines === null ? null : await formatTypeScript(machines)
1639
1820
  });
1640
- if (machine) {
1641
- outputs.push({
1642
- path: resolve2(root, settings.dir, generatedFiles.machines),
1643
- content: await formatTypeScript(machine)
1644
- });
1645
- }
1646
1821
  }
1647
1822
  await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
1648
- return { catalog, io, files: outputs.map((output) => output.path) };
1823
+ return {
1824
+ catalog,
1825
+ io,
1826
+ files: outputs.flatMap((output) => output.content === null ? [] : [output.path]),
1827
+ contract: contract?.path ?? null
1828
+ };
1649
1829
  }
1650
1830
 
1651
1831
  // packages/typegen/src/cli.ts
@@ -1661,17 +1841,23 @@ async function main() {
1661
1841
  }
1662
1842
  });
1663
1843
  if (values.help) {
1664
- console.log(`Usage: tsplc-typegen --types src/types [--globals src/globals] --out generated.ts [--check]
1844
+ console.log(`Usage: tsplc-typegen [--config ${configFileName}] [--check]
1845
+ tsplc-typegen --types src/types [--globals src/globals] --out generated.ts [--check]
1665
1846
 
1666
1847
  Generate TypeScript types and runtime field metadata from CODESYS ST declarations.
1848
+ Without --types and --out, generates the files the project's config names.
1667
1849
  --check exits unsuccessfully if the output is missing or stale, without writing files.`);
1668
1850
  return;
1669
1851
  }
1670
1852
  if (!values.types && !values.out) {
1671
- const result = await generateProject(values.config, {
1672
- check: values.check
1853
+ const loaded = await loadTsplcConfig(values.config ?? configFileName, {
1854
+ env: process.env,
1855
+ target: undefined,
1856
+ forAgent: false
1673
1857
  });
1674
- console.log(`Generated ${result.files.join(", ")}`);
1858
+ const result = await generateProject(loaded, { check: values.check });
1859
+ const files = result.files.join(", ");
1860
+ console.log(values.check ? `Up to date: ${files}` : `Generated ${files}`);
1675
1861
  return;
1676
1862
  }
1677
1863
  if (!values.types || !values.out) {
@@ -1681,31 +1867,21 @@ Generate TypeScript types and runtime field metadata from CODESYS ST declaration
1681
1867
  if (!/\.ts$/i.test(out) || /\.d\.ts$/i.test(out)) {
1682
1868
  throw new Error("--out must be a .ts file (the generated file contains runtime metadata)");
1683
1869
  }
1684
- const result = await generateTypes({
1685
- types: resolve3(values.types),
1686
- globals: values.globals ? resolve3(values.globals) : undefined
1687
- });
1870
+ const contract = {
1871
+ path: out,
1872
+ content: await formatTypeScript(await generateTypes({
1873
+ types: resolve3(values.types),
1874
+ globals: values.globals ? resolve3(values.globals) : [],
1875
+ publication: null,
1876
+ declarations: true
1877
+ }))
1878
+ };
1688
1879
  if (values.check) {
1689
- const existing = await readFile5(out, "utf8").catch((error) => {
1690
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1691
- return;
1692
- }
1693
- throw error;
1694
- });
1695
- if (existing !== result) {
1696
- throw new Error(`${out} is missing or stale; rerun tsplc-typegen without --check`);
1697
- }
1880
+ await checkOutputs([contract]);
1698
1881
  console.log(`Up to date: ${out}`);
1699
1882
  return;
1700
1883
  }
1701
- await mkdir2(dirname2(out), { recursive: true });
1702
- const temporary = `${out}.${process.pid}.tmp`;
1703
- try {
1704
- await writeFile2(temporary, result, { flag: "wx" });
1705
- await rename2(temporary, out);
1706
- } finally {
1707
- await rm(temporary, { force: true });
1708
- }
1884
+ await writeOutputs([contract]);
1709
1885
  console.log(`Generated ${out}`);
1710
1886
  }
1711
1887
  main().catch((error) => {
@@ -1713,5 +1889,5 @@ main().catch((error) => {
1713
1889
  process.exitCode = 1;
1714
1890
  });
1715
1891
 
1716
- //# debugId=96730D0D05C9571664756E2164756E21
1892
+ //# debugId=D17F9A6BF987DBC364756E2164756E21
1717
1893
  //# sourceMappingURL=cli.js.map