@tsplc/typegen 0.2.17 → 0.2.19

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/src/index.ts CHANGED
@@ -1,5 +1,29 @@
1
1
  export { generateTypes } from "./codegen/generate.ts";
2
- export * from "./hardware.ts";
2
+ export {
3
+ type HardwareCatalog,
4
+ type SelectedAssembly,
5
+ loadHardware,
6
+ resolveIo,
7
+ } from "./hardware.ts";
8
+ export {
9
+ type EdsAssembly,
10
+ type EdsConnection,
11
+ type EdsMember,
12
+ type EdsParameter,
13
+ type EdsSize,
14
+ type HardwareDescriptor,
15
+ parseEds,
16
+ readEdsRecords,
17
+ } from "./hardware/eds.ts";
18
+ export type { IoChannel } from "./hardware/channels.ts";
19
+ export type { ModbusRegister } from "./hardware/modbus.ts";
20
+ export { ioScalarBits } from "@tsplc/iec";
21
+ export { ioLayout } from "./hardware/process-image.ts";
22
+ export {
23
+ type IoTarget,
24
+ type ProjectTargets,
25
+ generateHardwareTypes,
26
+ } from "./hardware/mapping-types.ts";
3
27
  export { deviceTree, normalizeEds } from "./device-tree.ts";
4
28
 
5
29
  export { generateProject } from "./project.ts";
package/src/project.ts CHANGED
@@ -2,167 +2,262 @@ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { format } from "prettier";
4
4
  import {
5
- loadTsplcConfig,
6
- publicationSchema,
7
- typegenSchema,
8
- type ResolvedTsplcConfig,
5
+ loadTsplcConfig,
6
+ publicationSchema,
7
+ typegenSchema,
8
+ type ResolvedTsplcConfig,
9
9
  } from "@tsplc/config";
10
+ import { blockCommentEnd, lineCommentEnd } from "@tsplc/iec/st";
10
11
  import { generateTypes, stFiles } from "./codegen/generate.ts";
11
- import { generateHardwareTypes, type ProjectTargets, loadHardware, resolveIo } from "./hardware.ts";
12
+ import {
13
+ generateHardwareTypes,
14
+ type ProjectTargets,
15
+ loadHardware,
16
+ resolveIo,
17
+ } from "./hardware.ts";
18
+
19
+ /** Where the compiler emits ST, with its IO symbol paths, publication and machine interfaces. */
20
+ const emittedSt = ".tsplc/artifacts/st";
21
+
22
+ // Prettier's format() never reads a Prettier config, so generated files keep Prettier's
23
+ // defaults in whichever repository typegen runs.
24
+ const formatTypeScript = (source: string) =>
25
+ format(source, { parser: "typescript" });
26
+
27
+ const readPublication = async (root: string) =>
28
+ publicationSchema.parse(
29
+ JSON.parse(
30
+ await readFile(resolve(root, emittedSt, "publication.json"), "utf8"),
31
+ ),
32
+ );
33
+
34
+ interface ContractSources {
35
+ types: string[];
36
+ globals: string[];
37
+ /** Taken from typegen directories rather than inferred from emitted or build sources. */
38
+ explicit: boolean;
39
+ }
12
40
 
13
41
  /**
14
42
  * Explicit typegen directories take every .st file. Otherwise TYPE and VAR_GLOBAL files are
15
43
  * picked from the compiler's emitted ST or the raw build sources.
16
44
  */
17
45
  async function contractSources(
18
- config: ResolvedTsplcConfig,
19
- root: string,
20
- settings: { types?: string | string[]; globals?: string | string[] },
21
- ): Promise<{ types: string[]; globals: string[]; explicit: boolean } | undefined> {
22
- const directories = (setting: string | string[] | undefined) =>
23
- setting ? [setting].flat().map((path) => resolve(root, path)) : [];
24
- const types = directories(settings.types),
25
- globals = directories(settings.globals);
26
- if (types.length || globals.length) {
27
- const sources = { types: [] as string[], globals: [] as string[], explicit: true };
28
- for (const directory of types) sources.types.push(...(await stFiles(directory)));
29
- for (const directory of globals) sources.globals.push(...(await stFiles(directory)));
30
- if (!sources.types.length && !sources.globals.length)
31
- throw new Error("no .st declarations found in the configured typegen directories");
32
- return sources;
33
- }
34
- const source = config.compiler ? ".tsplc/artifacts/st" : config.build?.sourceDir;
35
- if (!source) {
36
- if (config.typegen)
37
- throw new Error("Configure build.sourceDir or typegen.types/globals to generate PLC types.");
38
- return undefined;
39
- }
40
- const sourceRoot = resolve(root, source);
41
- const files = await stFiles(sourceRoot);
42
- if (!files.length) throw new Error(`no .st declarations found in ${sourceRoot}`);
43
- const sources = { types: [] as string[], globals: [] as string[], explicit: false };
44
- for (const file of files) {
45
- const body = (await readFile(file, "utf8"))
46
- .replace(/\(\*[\s\S]*?\*\)|\/\/[^\r\n]*|\{[^}]*\}/g, "")
47
- .trimStart();
48
- if (/^TYPE\b/i.test(body)) sources.types.push(file);
49
- else if (/^VAR_GLOBAL\b/i.test(body)) sources.globals.push(file);
50
- }
51
- return sources;
46
+ config: ResolvedTsplcConfig,
47
+ root: string,
48
+ settings: { types?: string | string[]; globals?: string | string[] },
49
+ ): Promise<ContractSources | undefined> {
50
+ const directories = (setting: string | string[] | undefined) =>
51
+ setting ? [setting].flat().map((path) => resolve(root, path)) : [];
52
+ const types = directories(settings.types);
53
+ const globals = directories(settings.globals);
54
+ if (types.length || globals.length) {
55
+ const sources = {
56
+ types: await filesIn(types),
57
+ globals: await filesIn(globals),
58
+ explicit: true,
59
+ };
60
+ if (!sources.types.length && !sources.globals.length) {
61
+ throw new Error(
62
+ "no .st declarations found in the configured typegen directories",
63
+ );
64
+ }
65
+ return sources;
66
+ }
67
+ const source = config.compiler ? emittedSt : config.build?.sourceDir;
68
+ if (!source) {
69
+ if (config.typegen) {
70
+ throw new Error(
71
+ "Configure build.sourceDir or typegen.types/globals to generate PLC types.",
72
+ );
73
+ }
74
+ return undefined;
75
+ }
76
+ const sourceRoot = resolve(root, source);
77
+ const files = await stFiles(sourceRoot);
78
+ if (!files.length) {
79
+ throw new Error(`no .st declarations found in ${sourceRoot}`);
80
+ }
81
+ const sources: ContractSources = { types: [], globals: [], explicit: false };
82
+ for (const file of files) {
83
+ const text = await readFile(file, "utf8");
84
+ const code = text.slice(codeStart(text, 0));
85
+ if (/^TYPE\b/i.test(code)) {
86
+ sources.types.push(file);
87
+ } else if (/^VAR_GLOBAL\b/i.test(code)) {
88
+ sources.globals.push(file);
89
+ }
90
+ }
91
+ return sources;
92
+ }
93
+
94
+ /** Where ST code begins at or after `offset`: past whitespace, comments and pragmas. */
95
+ function codeStart(text: string, offset: number): number {
96
+ const start = offset + text.slice(offset).search(/\S|$/);
97
+ if (text.startsWith("(*", start)) {
98
+ const end = blockCommentEnd(text, start);
99
+ return end === null ? start : codeStart(text, end);
100
+ }
101
+ if (text.startsWith("//", start)) {
102
+ return codeStart(text, lineCommentEnd(text, start));
103
+ }
104
+ if (text.startsWith("{", start)) {
105
+ const end = text.indexOf("}", start);
106
+ return end < 0 ? start : codeStart(text, end + 1);
107
+ }
108
+ return start;
109
+ }
110
+
111
+ /** Every .st file under each directory, in directory order. */
112
+ async function filesIn(directories: string[]): Promise<string[]> {
113
+ const files: string[] = [];
114
+ for (const directory of directories) {
115
+ files.push(...(await stFiles(directory)));
116
+ }
117
+ return files;
118
+ }
119
+
120
+ /** An HMI control may target only a published symbol or a field or element under one. */
121
+ function checkHmiTargets(
122
+ controls: readonly { target: string }[],
123
+ published: readonly string[],
124
+ ) {
125
+ for (const { target } of controls) {
126
+ if (
127
+ !published.some(
128
+ (symbol) =>
129
+ target === symbol ||
130
+ target.startsWith(`${symbol}.`) ||
131
+ target.startsWith(`${symbol}[`),
132
+ )
133
+ ) {
134
+ throw new Error(
135
+ `HMI control ${target} is not in the production publication.`,
136
+ );
137
+ }
138
+ }
139
+ }
140
+
141
+ interface Output {
142
+ path: string;
143
+ content: string;
144
+ }
145
+
146
+ /** Writes each output through a temporary file, so a reader never sees half of one. */
147
+ async function writeOutputs(outputs: Output[]) {
148
+ for (const output of outputs) {
149
+ await mkdir(dirname(output.path), { recursive: true });
150
+ const temp = `${output.path}.${process.pid}.tmp`;
151
+ await writeFile(temp, output.content);
152
+ await rename(temp, output.path);
153
+ }
154
+ }
155
+
156
+ async function checkOutputs(outputs: Output[]) {
157
+ for (const output of outputs) {
158
+ const actual = await readFile(output.path, "utf8").catch(() => undefined);
159
+ // Consumers may format generated TS with their own formatter. Compare the
160
+ // same normalized syntax while preserving changes to values and comments.
161
+ const normalized =
162
+ actual !== undefined && /\.ts$/i.test(output.path)
163
+ ? await formatTypeScript(actual)
164
+ : actual;
165
+ if (normalized !== output.content) {
166
+ throw new Error(`Generated file is missing or stale: ${output.path}`);
167
+ }
168
+ }
52
169
  }
53
170
 
54
171
  export async function generateProject(
55
- file = "tsplc.config.ts",
56
- options: {
57
- check?: boolean;
58
- hardwareOnly?: boolean;
59
- /** Source-derived I/O keys and publication selectors, independent of the active target. */
60
- targets?: ProjectTargets;
61
- loaded?: Awaited<ReturnType<typeof loadTsplcConfig>>;
62
- } = {},
172
+ file = "tsplc.config.ts",
173
+ options: {
174
+ check?: boolean;
175
+ hardwareOnly?: boolean;
176
+ /** Source-derived I/O keys and publication selectors, independent of the active target. */
177
+ targets?: ProjectTargets;
178
+ loaded?: Awaited<ReturnType<typeof loadTsplcConfig>>;
179
+ } = {},
63
180
  ) {
64
- const { config, root, configFile } = options.loaded ?? (await loadTsplcConfig(file));
65
- const settings = typegenSchema.parse(config.typegen ?? {});
66
- const catalog = await loadHardware(config, root),
67
- io = resolveIo(config, catalog);
68
- const project = {
69
- version: 1,
70
- configFile,
71
- config,
72
- symbols: config.compiler
73
- ? JSON.parse(
74
- await readFile(resolve(root, ".tsplc/artifacts/st/io-symbols.json"), "utf8").catch(
75
- () => "{}",
76
- ),
77
- )
78
- : Object.fromEntries(
79
- Object.keys(io)
80
- .filter((symbol) => symbol.includes("."))
81
- .map((symbol) => [symbol, symbol]),
82
- ),
83
- };
84
- const outputs = [
85
- {
86
- path: resolve(root, settings.dir, "hardware.ts"),
87
- content: await format(
88
- generateHardwareTypes(
89
- catalog,
90
- options.targets?.io,
91
- options.targets?.publication,
92
- settings.ioTypes,
93
- ),
94
- {
95
- parser: "typescript",
96
- },
97
- ),
98
- },
99
- {
100
- path: resolve(root, ".tsplc/project.json"),
101
- content: JSON.stringify(project, null, 2) + "\n",
102
- },
103
- ];
104
- const sources = options.hardwareOnly ? undefined : await contractSources(config, root, settings);
105
- if (sources)
106
- outputs.push({
107
- path: resolve(root, settings.dir, "plc.ts"),
108
- content: await format(
109
- await generateTypes({
110
- types: sources.types,
111
- globals: sources.globals,
112
- publishedGlobalsOnly: !!config.compiler && !sources.explicit,
113
- declarations: settings.declarations,
114
- publication:
115
- config.compiler && !sources.explicit
116
- ? publicationSchema.parse(
117
- JSON.parse(
118
- await readFile(resolve(root, ".tsplc/artifacts/st/publication.json"), "utf8"),
119
- ),
120
- )
121
- : undefined,
122
- }),
123
- { parser: "typescript" },
124
- ),
125
- });
126
- if (config.hmi && config.publish && config.compiler && !options.hardwareOnly) {
127
- const published = publicationSchema.parse(
128
- JSON.parse(await readFile(resolve(root, ".tsplc/artifacts/st/publication.json"), "utf8")),
129
- ).production;
130
- for (const { target } of config.hmi.controls)
131
- if (
132
- !published.some(
133
- (symbol) =>
134
- target === symbol || target.startsWith(`${symbol}.`) || target.startsWith(`${symbol}[`),
135
- )
136
- )
137
- throw new Error(`HMI control ${target} is not in the production publication.`);
138
- }
139
- if (config.compiler && !options.hardwareOnly) {
140
- const machine = await readFile(resolve(root, ".tsplc/artifacts/st/machines.ts"), "utf8").catch(
141
- () => undefined,
142
- );
143
- if (machine)
144
- outputs.push({
145
- path: resolve(root, settings.dir, "machines.ts"),
146
- content: await format(machine, { parser: "typescript" }),
147
- });
148
- }
149
- for (const output of outputs) {
150
- if (options.check) {
151
- const actual = await readFile(output.path, "utf8").catch(() => undefined);
152
- // Consumers may format generated TS with their own formatter. Compare the
153
- // same normalized syntax while preserving changes to values and comments.
154
- const normalized =
155
- actual !== undefined && /\.ts$/i.test(output.path)
156
- ? await format(actual, { parser: "typescript" })
157
- : actual;
158
- if (normalized !== output.content)
159
- throw new Error(`Generated file is missing or stale: ${output.path}`);
160
- } else {
161
- await mkdir(dirname(output.path), { recursive: true });
162
- const temp = `${output.path}.${process.pid}.tmp`;
163
- await writeFile(temp, output.content);
164
- await rename(temp, output.path);
165
- }
166
- }
167
- return { catalog, io, files: outputs.map((o) => o.path) };
181
+ const { config, root, configFile } =
182
+ options.loaded ?? (await loadTsplcConfig(file));
183
+ const settings = typegenSchema.parse(config.typegen ?? {});
184
+ const catalog = await loadHardware(config, root);
185
+ const io = resolveIo(config, catalog);
186
+ const project = {
187
+ version: 1,
188
+ configFile,
189
+ config,
190
+ symbols: config.compiler
191
+ ? JSON.parse(
192
+ await readFile(
193
+ resolve(root, emittedSt, "io-symbols.json"),
194
+ "utf8",
195
+ ).catch(() => "{}"),
196
+ )
197
+ : Object.fromEntries(
198
+ Object.keys(io)
199
+ .filter((symbol) => symbol.includes("."))
200
+ .map((symbol) => [symbol, symbol]),
201
+ ),
202
+ };
203
+ const outputs: Output[] = [
204
+ {
205
+ path: resolve(root, settings.dir, "hardware.ts"),
206
+ content: await formatTypeScript(
207
+ generateHardwareTypes(
208
+ catalog,
209
+ options.targets?.io,
210
+ options.targets?.publication,
211
+ settings.ioTypes,
212
+ ),
213
+ ),
214
+ },
215
+ {
216
+ path: resolve(root, ".tsplc/project.json"),
217
+ content: JSON.stringify(project, null, 2) + "\n",
218
+ },
219
+ ];
220
+ const sources = options.hardwareOnly
221
+ ? undefined
222
+ : await contractSources(config, root, settings);
223
+ if (sources) {
224
+ const inferred = !!config.compiler && !sources.explicit;
225
+ outputs.push({
226
+ path: resolve(root, settings.dir, "plc.ts"),
227
+ content: await formatTypeScript(
228
+ await generateTypes({
229
+ types: sources.types,
230
+ globals: sources.globals,
231
+ publishedGlobalsOnly: inferred,
232
+ declarations: settings.declarations,
233
+ publication: inferred ? await readPublication(root) : undefined,
234
+ }),
235
+ ),
236
+ });
237
+ }
238
+ if (
239
+ config.hmi &&
240
+ config.publish &&
241
+ config.compiler &&
242
+ !options.hardwareOnly
243
+ ) {
244
+ checkHmiTargets(
245
+ config.hmi.controls,
246
+ (await readPublication(root)).production,
247
+ );
248
+ }
249
+ if (config.compiler && !options.hardwareOnly) {
250
+ const machine = await readFile(
251
+ resolve(root, emittedSt, "machines.ts"),
252
+ "utf8",
253
+ ).catch(() => undefined);
254
+ if (machine) {
255
+ outputs.push({
256
+ path: resolve(root, settings.dir, "machines.ts"),
257
+ content: await formatTypeScript(machine),
258
+ });
259
+ }
260
+ }
261
+ await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
262
+ return { catalog, io, files: outputs.map((output) => output.path) };
168
263
  }