@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/src/project.ts CHANGED
@@ -1,45 +1,53 @@
1
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
- import { dirname, resolve } from "node:path";
1
+ import { resolve } from "node:path";
3
2
  import {
4
3
  ioSymbolsSchema,
5
4
  type LoadedConfig,
6
- loadTsplcConfig,
7
5
  publicationSchema,
8
6
  type ResolvedTsplcConfig,
9
- typegenSchema,
7
+ typegenSettings,
10
8
  } from "@tsplc/config";
11
9
  import {
12
10
  emittedFiles,
13
11
  emittedStDirectory,
14
12
  projectSnapshotFile,
13
+ stRoot,
15
14
  } from "@tsplc/config/project-files";
16
- import { format } from "prettier";
15
+ import { isWithin } from "@tsplc/iec/st";
17
16
  import type { z } from "zod";
18
17
  import { declarationFiles } from "./codegen/declarations";
19
- import { generateTypes, stFiles } from "./codegen/generate";
18
+ import { generateTypes } from "./codegen/generate";
19
+ import { isMissingFile, readIfPresent, stFiles } from "./files";
20
20
  import {
21
21
  generateHardwareTypes,
22
22
  loadHardware,
23
23
  type ProjectTargets,
24
24
  resolveIo,
25
25
  } from "./hardware";
26
+ import {
27
+ checkOutputs,
28
+ formatTypeScript,
29
+ type Output,
30
+ writeOutputs,
31
+ } from "./outputs";
26
32
  import type { projectSnapshotSchema } from "./project-snapshot";
27
33
 
28
- // Prettier's format() never reads a Prettier config, so generated files keep Prettier's
29
- // defaults in whichever repository typegen runs.
30
- const formatTypeScript = (source: string) =>
31
- format(source, { parser: "typescript" });
34
+ const emittedPath = (root: string, file: string) =>
35
+ resolve(root, emittedStDirectory, file);
32
36
 
33
- const readPublication = async (root: string) =>
34
- publicationSchema.parse(
35
- JSON.parse(
36
- await readFile(
37
- resolve(root, emittedStDirectory, emittedFiles.publication),
38
- "utf8",
39
- ),
40
- ),
37
+ /** Why typegen can't read a TypeScript program's contract: the program isn't emitted. */
38
+ const missingEmission = (root: string) =>
39
+ new Error(
40
+ `No emitted Structured Text in ${resolve(root, emittedStDirectory)}: emit the program with tsplc build --emit-only, or check with tsplc typegen --check, which emits it first.`,
41
41
  );
42
42
 
43
+ const readPublication = async (root: string) => {
44
+ const text = await readIfPresent(emittedPath(root, emittedFiles.publication));
45
+ if (text === null) {
46
+ throw missingEmission(root);
47
+ }
48
+ return publicationSchema.parse(JSON.parse(text));
49
+ };
50
+
43
51
  /** The files typegen writes into the config's `typegen.dir`. */
44
52
  export const generatedFiles = {
45
53
  hardware: "hardware.ts",
@@ -49,14 +57,9 @@ export const generatedFiles = {
49
57
 
50
58
  /** The compiler's IO symbol paths, or none before the project's first build. */
51
59
  async function readIoSymbols(root: string) {
52
- const file = resolve(root, emittedStDirectory, emittedFiles.ioSymbols);
53
- const text = await readFile(file, "utf8").catch((error: unknown) => {
54
- if (error instanceof Error && "code" in error && error.code === "ENOENT") {
55
- return "{}";
56
- }
57
- throw error;
58
- });
59
- const symbols = ioSymbolsSchema.safeParse(JSON.parse(text));
60
+ const file = emittedPath(root, emittedFiles.ioSymbols);
61
+ const text = await readIfPresent(file);
62
+ const symbols = ioSymbolsSchema.safeParse(JSON.parse(text ?? "{}"));
60
63
  if (!symbols.success) {
61
64
  throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
62
65
  }
@@ -77,13 +80,15 @@ interface ContractSources {
77
80
  async function contractSources(
78
81
  config: ResolvedTsplcConfig,
79
82
  root: string,
80
- settings: { types?: string | string[]; globals?: string | string[] },
81
- ): Promise<ContractSources | undefined> {
83
+ settings: ReturnType<typeof typegenSettings>,
84
+ ): Promise<ContractSources> {
82
85
  const directories = (setting: string | string[] | undefined) =>
83
86
  setting ? [setting].flat().map((path) => resolve(root, path)) : [];
84
87
  const types = directories(settings.types);
85
88
  const globals = directories(settings.globals);
86
89
  if (types.length || globals.length) {
90
+ const filesIn = async (directories: string[]) =>
91
+ (await Promise.all(directories.map(stFiles))).flat();
87
92
  const sources = {
88
93
  types: await filesIn(types),
89
94
  globals: await filesIn(globals),
@@ -96,46 +101,34 @@ async function contractSources(
96
101
  }
97
102
  return sources;
98
103
  }
99
- const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
104
+ const source = stRoot(config);
100
105
  if (!source) {
101
- if (config.typegen) {
102
- throw new Error(
103
- "Configure build.sourceDir or typegen.types/globals to generate PLC types.",
104
- );
105
- }
106
- return undefined;
106
+ throw new Error(
107
+ "Configure build.sourceDir or typegen.types/globals to generate PLC types.",
108
+ );
107
109
  }
108
110
  const sourceRoot = resolve(root, source);
109
- const files = await stFiles(sourceRoot);
111
+ const files = await stFiles(sourceRoot).catch((cause: unknown) => {
112
+ if (!isMissingFile(cause)) {
113
+ throw cause;
114
+ }
115
+ throw config.compiler
116
+ ? missingEmission(root)
117
+ : new Error(`build.sourceDir ${sourceRoot} doesn't exist.`);
118
+ });
110
119
  if (!files.length) {
111
120
  throw new Error(`no .st declarations found in ${sourceRoot}`);
112
121
  }
113
122
  return { ...(await declarationFiles(files)), explicit: false };
114
123
  }
115
124
 
116
- /** Every .st file under each directory, in directory order. */
117
- async function filesIn(directories: string[]): Promise<string[]> {
118
- const files: string[] = [];
119
- for (const directory of directories) {
120
- files.push(...(await stFiles(directory)));
121
- }
122
- return files;
123
- }
124
-
125
125
  /** An HMI control may target only a published symbol or a field or element under one. */
126
126
  function checkHmiTargets(
127
127
  controls: readonly { target: string }[],
128
128
  published: readonly string[],
129
129
  ) {
130
130
  for (const { target } of controls) {
131
- if (
132
- !published.some(
133
- (symbol) =>
134
- target === symbol ||
135
- target.startsWith(`${symbol}.`) ||
136
- target.startsWith(`${symbol}[`),
137
- )
138
- ) {
131
+ if (!published.some((symbol) => isWithin(symbol, target))) {
139
132
  throw new Error(
140
133
  `HMI control ${target} is not in the production publication.`,
141
134
  );
@@ -143,49 +136,25 @@ function checkHmiTargets(
143
136
  }
144
137
  }
145
138
 
146
- interface Output {
147
- path: string;
148
- content: string;
149
- }
150
-
151
- /** Writes each output through a temporary file, so a reader never sees half of one. */
152
- async function writeOutputs(outputs: Output[]) {
153
- for (const output of outputs) {
154
- await mkdir(dirname(output.path), { recursive: true });
155
- const temp = `${output.path}.${process.pid}.tmp`;
156
- await writeFile(temp, output.content);
157
- await rename(temp, output.path);
158
- }
159
- }
160
-
161
- async function checkOutputs(outputs: Output[]) {
162
- for (const output of outputs) {
163
- const actual = await readFile(output.path, "utf8").catch(() => undefined);
164
- // Consumers may format generated TS with their own formatter. Compare the
165
- // same normalized syntax while preserving changes to values and comments.
166
- const normalized =
167
- actual !== undefined && /\.ts$/i.test(output.path)
168
- ? await formatTypeScript(actual)
169
- : actual;
170
- if (normalized !== output.content) {
171
- throw new Error(`Generated file is missing or stale: ${output.path}`);
172
- }
173
- }
174
- }
175
-
139
+ /**
140
+ * Writes the hardware types, the project snapshot and, for a TypeScript
141
+ * program or a raw Structured Text project with a `typegen` section, the PLC contract, whose path
142
+ * it returns as `contract`. With `check` it compares them instead, all but the snapshot, which
143
+ * belongs to the checkout rather than the source.
144
+ */
176
145
  export async function generateProject(
177
- file = "tsplc.config.ts",
146
+ { config, root, configFile }: LoadedConfig,
178
147
  options: {
179
148
  check?: boolean;
149
+ /** Only the hardware types and snapshot, which a TypeScript program imports before its first emission. */
180
150
  hardwareOnly?: boolean;
181
151
  /** Source-derived I/O keys and publication selectors, independent of the active target. */
182
152
  targets?: ProjectTargets;
183
- loaded?: LoadedConfig;
184
153
  } = {},
185
154
  ) {
186
- const { config, root, configFile } =
187
- options.loaded ?? (await loadTsplcConfig(file));
188
- const settings = typegenSchema.parse(config.typegen ?? {});
155
+ const hardwareOnly =
156
+ options.hardwareOnly || (!config.compiler && !config.typegen);
157
+ const settings = typegenSettings(config);
189
158
  const catalog = await loadHardware(config, root);
190
159
  const io = resolveIo(config, catalog);
191
160
  const project: z.input<typeof projectSnapshotSchema> = {
@@ -204,60 +173,63 @@ export async function generateProject(
204
173
  {
205
174
  path: resolve(root, settings.dir, generatedFiles.hardware),
206
175
  content: await formatTypeScript(
207
- generateHardwareTypes(
208
- catalog,
209
- options.targets?.io,
210
- options.targets?.publication,
211
- settings.ioTypes,
212
- ),
176
+ generateHardwareTypes(catalog, {
177
+ root,
178
+ targets: options.targets ?? null,
179
+ ioTypes: settings.ioTypes,
180
+ }),
213
181
  ),
214
182
  },
215
- {
216
- path: resolve(root, projectSnapshotFile),
217
- content: `${JSON.stringify(project, null, 2)}\n`,
218
- },
183
+ // The snapshot is this checkout's state, with its absolute config path, and isn't committed.
184
+ ...(options.check
185
+ ? []
186
+ : [
187
+ {
188
+ path: resolve(root, projectSnapshotFile),
189
+ content: `${JSON.stringify(project, null, 2)}\n`,
190
+ },
191
+ ]),
219
192
  ];
220
- const sources = options.hardwareOnly
221
- ? undefined
193
+ const sources = hardwareOnly
194
+ ? null
222
195
  : await contractSources(config, root, settings);
223
- if (sources) {
224
- const inferred = !!config.compiler && !sources.explicit;
225
- outputs.push({
226
- path: resolve(root, settings.dir, generatedFiles.contract),
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
- });
196
+ const inferred = sources !== null && !!config.compiler && !sources.explicit;
197
+ const hmi =
198
+ config.compiler && config.publish && !hardwareOnly ? config.hmi : undefined;
199
+ const publication = inferred || hmi ? await readPublication(root) : null;
200
+ const contract = sources && {
201
+ path: resolve(root, settings.dir, generatedFiles.contract),
202
+ content: await formatTypeScript(
203
+ await generateTypes({
204
+ types: sources.types,
205
+ globals: sources.globals,
206
+ publication: inferred ? publication : null,
207
+ declarations: settings.declarations,
208
+ }),
209
+ ),
210
+ };
211
+ if (contract) {
212
+ outputs.push(contract);
237
213
  }
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
- );
214
+ if (hmi && publication) {
215
+ checkHmiTargets(hmi.controls, publication.production);
248
216
  }
249
- if (config.compiler && !options.hardwareOnly) {
250
- const machine = await readFile(
251
- resolve(root, emittedStDirectory, emittedFiles.machines),
252
- "utf8",
253
- ).catch(() => undefined);
254
- if (machine) {
255
- outputs.push({
256
- path: resolve(root, settings.dir, generatedFiles.machines),
257
- content: await formatTypeScript(machine),
258
- });
259
- }
217
+ if (config.compiler && !hardwareOnly) {
218
+ const machines = await readIfPresent(
219
+ emittedPath(root, emittedFiles.machines),
220
+ );
221
+ outputs.push({
222
+ path: resolve(root, settings.dir, generatedFiles.machines),
223
+ content: machines === null ? null : await formatTypeScript(machines),
224
+ });
260
225
  }
261
226
  await (options.check ? checkOutputs(outputs) : writeOutputs(outputs));
262
- return { catalog, io, files: outputs.map((output) => output.path) };
227
+ return {
228
+ catalog,
229
+ io,
230
+ files: outputs.flatMap((output) =>
231
+ output.content === null ? [] : [output.path],
232
+ ),
233
+ contract: contract?.path ?? null,
234
+ };
263
235
  }