@tsplc/typegen 0.5.14 → 0.5.16

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.");
@@ -1150,7 +1275,7 @@ function logicalPath(path, params) {
1150
1275
  };
1151
1276
  }
1152
1277
  var optionalNumber = (value) => value?.trim() && Number.isFinite(Number(value)) ? Number(value) : undefined;
1153
- function parseEds(text, file = "device.eds") {
1278
+ function parseEds(text, file) {
1154
1279
  const records = readEdsRecords(text);
1155
1280
  const device = records.Device;
1156
1281
  if (!device?.ProdName?.[0]) {
@@ -1188,11 +1313,11 @@ function parseEds(text, file = "device.eds") {
1188
1313
  maximum: parameter.maximum
1189
1314
  };
1190
1315
  };
1191
- const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => /^Connection\d+$/.test(id)).map(([id, fields]) => {
1192
- const path = fields[14] ?? "";
1316
+ const connections = Object.entries(records["Connection Manager"] ?? {}).filter(([id]) => isConnection(id)).map(([id, fields]) => {
1317
+ const path = fields[connectionFields.path] ?? "";
1193
1318
  const points = logicalPath(path, params).points;
1194
- const outputSize = size(fields[3]);
1195
- const inputSize = size(fields[6]);
1319
+ const outputSize = size(fields[connectionFields.outputSize]);
1320
+ const inputSize = size(fields[connectionFields.inputSize]);
1196
1321
  const assembly = (reference, point, payload) => {
1197
1322
  if (!reference) {
1198
1323
  if (!payload || payload.value <= 0 || point === undefined) {
@@ -1205,7 +1330,7 @@ function parseEds(text, file = "device.eds") {
1205
1330
  if (!/^Assem\d+$/.test(reference) || !record) {
1206
1331
  throw new Error(`${file}: unknown connection assembly ${reference}.`);
1207
1332
  }
1208
- const instance = point ?? logicalPath(record[1] ?? "", params).instance;
1333
+ const instance = point ?? logicalPath(record[assemblyFields.path] ?? "", params).instance;
1209
1334
  if (instance === undefined) {
1210
1335
  throw new Error(`${file}: no runtime instance for ${reference}.`);
1211
1336
  }
@@ -1218,11 +1343,11 @@ function parseEds(text, file = "device.eds") {
1218
1343
  };
1219
1344
  return {
1220
1345
  id,
1221
- name: fields[12] || id,
1222
- 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,
1223
1348
  path,
1224
- outputAssembly: assembly(fields[4], points.at(-2), outputSize),
1225
- inputAssembly: assembly(fields[7], points.at(-1), inputSize),
1349
+ outputAssembly: assembly(fields[connectionFields.outputFormat], points.at(-2), outputSize),
1350
+ inputAssembly: assembly(fields[connectionFields.inputFormat], points.at(-1), inputSize),
1226
1351
  outputSize,
1227
1352
  inputSize
1228
1353
  };
@@ -1230,7 +1355,7 @@ function parseEds(text, file = "device.eds") {
1230
1355
  const assemblies = Object.entries(records.Assembly ?? {}).filter(([id]) => /^Assem\d+$/.test(id)).map(([id, fields]) => {
1231
1356
  const members = [];
1232
1357
  let offsetBits = 0;
1233
- for (let index = 6;index < fields.length; index += 2) {
1358
+ for (let index = assemblyFields.firstMember;index < fields.length; index += 2) {
1234
1359
  if (!fields[index] && !fields[index + 1]) {
1235
1360
  continue;
1236
1361
  }
@@ -1253,12 +1378,19 @@ function parseEds(text, file = "device.eds") {
1253
1378
  });
1254
1379
  offsetBits += bits;
1255
1380
  }
1256
- 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);
1257
1383
  if (offsetBits > size * 8) {
1258
1384
  throw new Error(`${file}: ${id} members exceed its ${size} byte payload.`);
1259
1385
  }
1260
- const instance = logicalPath(fields[1] ?? "", params).instance ?? instances.get(id);
1261
- 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
+ };
1262
1394
  });
1263
1395
  for (const [instance, payloadSize] of recordless) {
1264
1396
  if (!assemblies.some((assembly) => assembly.instance === instance)) {
@@ -1289,21 +1421,35 @@ function placeModbusRegisters(device, registers, place) {
1289
1421
  if (!entries.length) {
1290
1422
  return [];
1291
1423
  }
1292
- const outputBase = byteOffset(place({ id: device, region: "Q", size: entries.length * registerBytes.Q }));
1293
- 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
+ });
1294
1434
  return entries.map(([name, offset], index) => {
1295
- const channel = (field, direction, offsetBits, bits, type, description) => ({
1296
- device,
1297
- id: `modbus.${name}.${field}`,
1298
- name: `${name} ${field}`,
1299
- direction,
1300
- offsetBits,
1301
- bits,
1302
- type,
1303
- address: directAddress(direction === "input" ? "I" : "Q", direction === "input" ? inputBase + index * registerBytes.I : outputBase + index * registerBytes.Q, offsetBits, bits),
1304
- unit: "",
1305
- description
1306
- });
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
+ };
1307
1453
  const value = channel("value", "output", 0, 16, "WORD", "Value to write");
1308
1454
  const write = channel("write", "output", 16, 1, "BOOL", "Writes the value when it rises");
1309
1455
  const status = channel("status", "input", 0, 8, "BYTE", "The last answer: 0 accepted, otherwise the exception code");
@@ -1342,6 +1488,14 @@ function selectConnection(id, settings, descriptor) {
1342
1488
  const choices = compatible.map((item) => `${item.id} "${item.name}" (in ${item.inputAssembly ?? "-"}, out ${item.outputAssembly ?? "-"})`).join(", ");
1343
1489
  throw new Error(`${id}: select connection; ${settings.file} offers ${choices}.`);
1344
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
+ }
1345
1499
  function selectAssemblies(id, settings, descriptor, connection) {
1346
1500
  return ["input", "output"].flatMap((direction) => {
1347
1501
  const selection = direction === "input" ? settings.inputs : settings.outputs;
@@ -1356,10 +1510,8 @@ function selectAssemblies(id, settings, descriptor, connection) {
1356
1510
  if (!assembly) {
1357
1511
  throw new Error(`${id}: assembly ${instance} is not present in ${settings.file}.`);
1358
1512
  }
1359
- const region = direction === "input" ? "I" : "Q";
1360
- if (selection?.address && !selection.address.startsWith(`%${region}B`)) {
1361
- throw new Error(`${id}: ${direction} assembly needs a %${region}B address.`);
1362
- }
1513
+ const region = regionOf(direction);
1514
+ const offset = selection?.address === undefined ? undefined : configuredByte(id, direction, selection.address);
1363
1515
  const declaredSize = direction === "input" ? connection?.inputSize : connection?.outputSize;
1364
1516
  const payloadSize = selection?.size ?? declaredSize?.value ?? assembly.size;
1365
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) {
@@ -1373,29 +1525,51 @@ function selectAssemblies(id, settings, descriptor, connection) {
1373
1525
  instance,
1374
1526
  assembly,
1375
1527
  size: payloadSize,
1376
- address: selection?.address
1528
+ offset
1377
1529
  }
1378
1530
  ];
1379
1531
  });
1380
1532
  }
1381
1533
 
1382
1534
  // packages/typegen/src/hardware.ts
1383
- import { ioScalarBits as ioScalarBits3 } from "@tsplc/iec";
1535
+ import { ioScalarBits as ioScalarBits2 } from "@tsplc/iec";
1384
1536
 
1537
+ // packages/typegen/src/device-tree.ts
1538
+ import { iecName } from "@tsplc/config/build";
1385
1539
  // packages/typegen/src/hardware/mapping-types.ts
1386
- 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 }`;
1387
1546
  var directBinding = (layout) => {
1388
- const scalar = layout.replace(/^\d+x/, "");
1389
- const integer = /^INT(\d+)$/.exec(scalar);
1390
- const bits = integer ? Number(integer[1]) : ioScalarBits2(scalar);
1547
+ const bits = layoutBits(layout);
1391
1548
  const size = bits === undefined ? undefined : addressSize(bits);
1392
1549
  if (!size) {
1393
1550
  return;
1394
1551
  }
1395
- 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}\``);
1396
1553
  };
1397
- function generateHardwareTypes(catalog, targets, publication, ioTypes = true) {
1398
- const selectors = publication?.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
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
+ };
1566
+ };
1567
+ function generateHardwareTypes(catalog, {
1568
+ root,
1569
+ targets,
1570
+ ioTypes
1571
+ }) {
1572
+ const selectors = targets?.publication.map((selector) => JSON.stringify(selector)).join(" | ") ?? "string";
1399
1573
  const publicationTypes = `// Generated by tsPLC. Run tsplc typegen after changing EDS files, device selections or PLC storage.
1400
1574
  export type PublicationSelector = ${selectors || "never"};
1401
1575
  export type PlcPublication = { readonly production: readonly PublicationSelector[]; readonly development: readonly PublicationSelector[] };
@@ -1408,11 +1582,11 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1408
1582
  binding: channel(device.id, item.id, item.direction === "input" && item.type === "BOOL" ? "; inverted?: boolean; shared?: boolean" : ""),
1409
1583
  layout: ioLayout(item.type)
1410
1584
  })));
1411
- 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}`);
1412
1586
  const anyBinding = [...channels.map((item) => item.binding), direct].join(`
1413
1587
  | `);
1414
- const mapping = targets ? [...new Set(targets.map((target) => target.layout))].sort().map((layout) => {
1415
- 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}\``);
1416
1590
  const bindings = [
1417
1591
  ...channels.filter((item) => item.layout === layout).map((item) => item.binding),
1418
1592
  directBinding(layout)
@@ -1423,45 +1597,37 @@ export type PlcPublication = { readonly production: readonly PublicationSelector
1423
1597
  }).join(" & ") || "Readonly<Record<string, never>>" : "Readonly<Record<string, HardwareIoBinding>>";
1424
1598
  return `${publicationTypes}export type HardwareIoBinding = ${anyBinding};
1425
1599
  export type HardwareIoMapping = ${mapping};
1426
- export const hardware = ${JSON.stringify(catalog, null, 2)} as const;
1600
+ export const hardware = ${JSON.stringify(portableCatalog(catalog, root), null, 2)} as const;
1427
1601
  `;
1428
1602
  }
1429
1603
 
1430
1604
  // packages/typegen/src/hardware.ts
1431
- async function edsFiles(directory) {
1432
- const entries = await readdir2(directory, { withFileTypes: true }).catch((cause) => {
1433
- if (cause && typeof cause === "object" && "code" in cause && cause.code === "ENOENT") {
1434
- return [];
1435
- }
1436
- throw cause;
1437
- });
1438
- const files = [];
1439
- for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
1440
- const path = resolve(directory, entry.name);
1441
- if (entry.isDirectory()) {
1442
- files.push(...await edsFiles(path));
1443
- } else if (entry.isFile() && /\.eds$/i.test(entry.name)) {
1444
- files.push(path);
1445
- }
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 [];
1446
1609
  }
1447
- return files;
1448
- }
1610
+ throw error;
1611
+ });
1449
1612
  async function readDescriptors(config, root) {
1450
1613
  const files = new Set;
1451
1614
  for (const directory of [config.eds].flat()) {
1452
- for (const file of await edsFiles(resolve(root, directory))) {
1615
+ for (const file of await edsFiles(config, resolve(root, directory))) {
1453
1616
  files.add(file);
1454
1617
  }
1455
1618
  }
1456
1619
  for (const device of Object.values(config.devices)) {
1457
1620
  files.add(resolve(root, device.file));
1458
1621
  }
1459
- 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)])));
1460
1623
  }
1461
1624
  async function loadHardware(config, root) {
1462
1625
  const descriptors = await readDescriptors(config, root);
1463
1626
  const selected = Object.entries(config.devices).map(([id, settings]) => {
1464
- 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
+ }
1465
1631
  const connection = selectConnection(id, settings, descriptor);
1466
1632
  const selections = selectAssemblies(id, settings, descriptor, connection);
1467
1633
  return { id, settings, descriptor, connection, selections };
@@ -1469,10 +1635,14 @@ async function loadHardware(config, root) {
1469
1635
  const place = regionPlacer(selected.flatMap((device) => device.selections), { generatedTree: config.codesys?.deviceTree !== undefined });
1470
1636
  const placed = selected.map((device) => ({
1471
1637
  ...device,
1472
- assemblies: device.selections.map((selection) => ({
1473
- ...selection,
1474
- address: place(selection)
1475
- }))
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
+ })
1476
1646
  }));
1477
1647
  const devices = placed.map(({ id, settings, descriptor, connection, assemblies }) => {
1478
1648
  const registers = placeModbusRegisters(id, settings.modbus?.registers ?? {}, place);
@@ -1494,12 +1664,12 @@ async function loadHardware(config, root) {
1494
1664
  })),
1495
1665
  channels: [
1496
1666
  ...registers.flatMap((register) => register.channels),
1497
- ...assemblies.flatMap(({ direction, instance, assembly, size, address }) => assemblyChannels({
1667
+ ...assemblies.flatMap(({ direction, instance, assembly, size, offset }) => assemblyChannels({
1498
1668
  device: id,
1499
1669
  direction,
1500
1670
  instance,
1501
1671
  members: assembly.members,
1502
- base: byteOffset(address),
1672
+ base: offset,
1503
1673
  payloadSize: size
1504
1674
  }))
1505
1675
  ],
@@ -1512,18 +1682,14 @@ async function loadHardware(config, root) {
1512
1682
  }
1513
1683
  };
1514
1684
  });
1515
- return { descriptors, devices };
1685
+ return { descriptors: [...descriptors.values()], devices };
1516
1686
  }
1517
1687
  function resolveIo(config, catalog) {
1518
1688
  return Object.fromEntries(Object.entries(config.io).map(([symbol, binding]) => {
1519
1689
  if ("address" in binding) {
1520
1690
  return [symbol, binding];
1521
1691
  }
1522
- const device = catalog.devices.find((d) => d.id === binding.device);
1523
- const channel = device?.channels.find((c) => c.id === binding.channel);
1524
- if (!channel?.address) {
1525
- throw new Error(`${symbol}: unknown or unaddressable channel ${binding.device}.${binding.channel}.`);
1526
- }
1692
+ const channel = boundChannel(catalog, symbol, binding);
1527
1693
  return [
1528
1694
  symbol,
1529
1695
  {
@@ -1537,22 +1703,24 @@ function resolveIo(config, catalog) {
1537
1703
  }
1538
1704
 
1539
1705
  // packages/typegen/src/project.ts
1540
- var formatTypeScript = (source) => format(source, { parser: "typescript" });
1541
- 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
+ };
1542
1715
  var generatedFiles = {
1543
1716
  hardware: "hardware.ts",
1544
1717
  contract: "plc.ts",
1545
1718
  machines: "machines.ts"
1546
1719
  };
1547
1720
  async function readIoSymbols(root) {
1548
- const file = resolve2(root, emittedStDirectory, emittedFiles.ioSymbols);
1549
- const text = await readFile4(file, "utf8").catch((error) => {
1550
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1551
- return "{}";
1552
- }
1553
- throw error;
1554
- });
1555
- 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 ?? "{}"));
1556
1724
  if (!symbols.success) {
1557
1725
  throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
1558
1726
  }
@@ -1563,6 +1731,7 @@ async function contractSources(config, root, settings) {
1563
1731
  const types = directories(settings.types);
1564
1732
  const globals = directories(settings.globals);
1565
1733
  if (types.length || globals.length) {
1734
+ const filesIn = async (directories) => (await Promise.all(directories.map(stFiles))).flat();
1566
1735
  const sources = {
1567
1736
  types: await filesIn(types),
1568
1737
  globals: await filesIn(globals),
@@ -1573,56 +1742,32 @@ async function contractSources(config, root, settings) {
1573
1742
  }
1574
1743
  return sources;
1575
1744
  }
1576
- const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
1745
+ const source = stRoot(config);
1577
1746
  if (!source) {
1578
- if (config.typegen) {
1579
- throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1580
- }
1581
- return;
1747
+ throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
1582
1748
  }
1583
1749
  const sourceRoot = resolve2(root, source);
1584
- 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
+ });
1585
1756
  if (!files.length) {
1586
1757
  throw new Error(`no .st declarations found in ${sourceRoot}`);
1587
1758
  }
1588
1759
  return { ...await declarationFiles(files), explicit: false };
1589
1760
  }
1590
- async function filesIn(directories) {
1591
- const files = [];
1592
- for (const directory of directories) {
1593
- files.push(...await stFiles(directory));
1594
- }
1595
- return files;
1596
- }
1597
1761
  function checkHmiTargets(controls, published) {
1598
1762
  for (const { target } of controls) {
1599
- if (!published.some((symbol) => target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`))) {
1763
+ if (!published.some((symbol) => isWithin(symbol, target))) {
1600
1764
  throw new Error(`HMI control ${target} is not in the production publication.`);
1601
1765
  }
1602
1766
  }
1603
1767
  }
1604
- async function writeOutputs(outputs) {
1605
- for (const output of outputs) {
1606
- await mkdir(dirname(output.path), { recursive: true });
1607
- const temp = `${output.path}.${process.pid}.tmp`;
1608
- await writeFile(temp, output.content);
1609
- await rename(temp, output.path);
1610
- }
1611
- }
1612
- async function checkOutputs(outputs) {
1613
- for (const output of outputs) {
1614
- const actual = await readFile4(output.path, "utf8").catch(() => {
1615
- return;
1616
- });
1617
- const normalized = actual !== undefined && /\.ts$/i.test(output.path) ? await formatTypeScript(actual) : actual;
1618
- if (normalized !== output.content) {
1619
- throw new Error(`Generated file is missing or stale: ${output.path}`);
1620
- }
1621
- }
1622
- }
1623
- async function generateProject(file = "tsplc.config.ts", options = {}) {
1624
- const { config, root, configFile } = options.loaded ?? await loadTsplcConfig(file);
1625
- 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);
1626
1771
  const catalog = await loadHardware(config, root);
1627
1772
  const io = resolveIo(config, catalog);
1628
1773
  const project = {
@@ -1634,44 +1779,53 @@ async function generateProject(file = "tsplc.config.ts", options = {}) {
1634
1779
  const outputs = [
1635
1780
  {
1636
1781
  path: resolve2(root, settings.dir, generatedFiles.hardware),
1637
- 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
+ }))
1638
1787
  },
1639
- {
1640
- path: resolve2(root, projectSnapshotFile),
1641
- content: `${JSON.stringify(project, null, 2)}
1788
+ ...options.check ? [] : [
1789
+ {
1790
+ path: resolve2(root, projectSnapshotFile),
1791
+ content: `${JSON.stringify(project, null, 2)}
1642
1792
  `
1643
- }
1793
+ }
1794
+ ]
1644
1795
  ];
1645
- const sources = options.hardwareOnly ? undefined : await contractSources(config, root, settings);
1646
- if (sources) {
1647
- const inferred = !!config.compiler && !sources.explicit;
1648
- outputs.push({
1649
- path: resolve2(root, settings.dir, generatedFiles.contract),
1650
- content: await formatTypeScript(await generateTypes({
1651
- types: sources.types,
1652
- globals: sources.globals,
1653
- publishedGlobalsOnly: inferred,
1654
- declarations: settings.declarations,
1655
- publication: inferred ? await readPublication(root) : undefined
1656
- }))
1657
- });
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);
1658
1811
  }
1659
- if (config.hmi && config.publish && config.compiler && !options.hardwareOnly) {
1660
- checkHmiTargets(config.hmi.controls, (await readPublication(root)).production);
1812
+ if (hmi && publication) {
1813
+ checkHmiTargets(hmi.controls, publication.production);
1661
1814
  }
1662
- if (config.compiler && !options.hardwareOnly) {
1663
- const machine = await readFile4(resolve2(root, emittedStDirectory, emittedFiles.machines), "utf8").catch(() => {
1664
- 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)
1665
1820
  });
1666
- if (machine) {
1667
- outputs.push({
1668
- path: resolve2(root, settings.dir, generatedFiles.machines),
1669
- content: await formatTypeScript(machine)
1670
- });
1671
- }
1672
1821
  }
1673
1822
  await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
1674
- 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
+ };
1675
1829
  }
1676
1830
 
1677
1831
  // packages/typegen/src/cli.ts
@@ -1687,17 +1841,23 @@ async function main() {
1687
1841
  }
1688
1842
  });
1689
1843
  if (values.help) {
1690
- 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]
1691
1846
 
1692
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.
1693
1849
  --check exits unsuccessfully if the output is missing or stale, without writing files.`);
1694
1850
  return;
1695
1851
  }
1696
1852
  if (!values.types && !values.out) {
1697
- const result = await generateProject(values.config, {
1698
- check: values.check
1853
+ const loaded = await loadTsplcConfig(values.config ?? configFileName, {
1854
+ env: process.env,
1855
+ target: undefined,
1856
+ forAgent: false
1699
1857
  });
1700
- 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}`);
1701
1861
  return;
1702
1862
  }
1703
1863
  if (!values.types || !values.out) {
@@ -1707,31 +1867,21 @@ Generate TypeScript types and runtime field metadata from CODESYS ST declaration
1707
1867
  if (!/\.ts$/i.test(out) || /\.d\.ts$/i.test(out)) {
1708
1868
  throw new Error("--out must be a .ts file (the generated file contains runtime metadata)");
1709
1869
  }
1710
- const result = await generateTypes({
1711
- types: resolve3(values.types),
1712
- globals: values.globals ? resolve3(values.globals) : undefined
1713
- });
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
+ };
1714
1879
  if (values.check) {
1715
- const existing = await readFile5(out, "utf8").catch((error) => {
1716
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
1717
- return;
1718
- }
1719
- throw error;
1720
- });
1721
- if (existing !== result) {
1722
- throw new Error(`${out} is missing or stale; rerun tsplc-typegen without --check`);
1723
- }
1880
+ await checkOutputs([contract]);
1724
1881
  console.log(`Up to date: ${out}`);
1725
1882
  return;
1726
1883
  }
1727
- await mkdir2(dirname2(out), { recursive: true });
1728
- const temporary = `${out}.${process.pid}.tmp`;
1729
- try {
1730
- await writeFile2(temporary, result, { flag: "wx" });
1731
- await rename2(temporary, out);
1732
- } finally {
1733
- await rm(temporary, { force: true });
1734
- }
1884
+ await writeOutputs([contract]);
1735
1885
  console.log(`Generated ${out}`);
1736
1886
  }
1737
1887
  main().catch((error) => {
@@ -1739,5 +1889,5 @@ main().catch((error) => {
1739
1889
  process.exitCode = 1;
1740
1890
  });
1741
1891
 
1742
- //# debugId=437A61781AEE599464756E2164756E21
1892
+ //# debugId=D17F9A6BF987DBC364756E2164756E21
1743
1893
  //# sourceMappingURL=cli.js.map