@tsplc/typegen 0.2.21 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,46 @@
1
+ // packages/typegen/src/project-snapshot.ts
2
+ import { readFile } from "node:fs/promises";
3
+ import { dirname, resolve } from "node:path";
4
+ import { projectSnapshotFile } from "@tsplc/config/project-files";
5
+ import { ioSymbolsSchema, tsplcConfigSchema } from "@tsplc/config/schema";
6
+ import { z } from "zod";
7
+ var projectSnapshotSchema = z.object({
8
+ version: z.literal(1),
9
+ configFile: z.string().nonempty(),
10
+ config: tsplcConfigSchema,
11
+ symbols: ioSymbolsSchema
12
+ });
13
+ var missing = (error) => error instanceof Error && ("code" in error) && error.code === "ENOENT";
14
+ var parseJson = (text) => {
15
+ try {
16
+ return { json: JSON.parse(text) };
17
+ } catch (error) {
18
+ return { error };
19
+ }
20
+ };
21
+ async function readProjectSnapshot(configFile) {
22
+ const file = resolve(dirname(configFile), projectSnapshotFile);
23
+ const read = await readFile(file, "utf8").then((text) => ({ text }), (error) => ({ error }));
24
+ if ("error" in read) {
25
+ return missing(read.error) ? { kind: "absent" } : { kind: "invalid", reason: `${file}: ${String(read.error)}` };
26
+ }
27
+ const decoded = parseJson(read.text);
28
+ if ("error" in decoded) {
29
+ return { kind: "invalid", reason: `${file}: ${String(decoded.error)}` };
30
+ }
31
+ const parsed = projectSnapshotSchema.safeParse(decoded.json);
32
+ if (!parsed.success) {
33
+ return {
34
+ kind: "invalid",
35
+ reason: `${file}: ${z.prettifyError(parsed.error)}`
36
+ };
37
+ }
38
+ return parsed.data.configFile === configFile ? { kind: "valid", snapshot: parsed.data } : { kind: "stale" };
39
+ }
40
+ export {
41
+ projectSnapshotSchema,
42
+ readProjectSnapshot
43
+ };
44
+
45
+ //# debugId=FA7CACDC419D733464756E2164756E21
46
+ //# sourceMappingURL=project-snapshot.js.map
@@ -0,0 +1,10 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/project-snapshot.ts"],
4
+ "sourcesContent": [
5
+ "import { readFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\nimport { projectSnapshotFile } from \"@tsplc/config/project-files\";\nimport { ioSymbolsSchema, tsplcConfigSchema } from \"@tsplc/config/schema\";\nimport { z } from \"zod\";\n\n/** What `tsplc typegen` materializes at `projectSnapshotFile` for readers that never execute the config. */\nexport const projectSnapshotSchema = z.object({\n\tversion: z.literal(1),\n\tconfigFile: z.string().nonempty(),\n\tconfig: tsplcConfigSchema,\n\tsymbols: ioSymbolsSchema,\n});\nexport type ProjectSnapshot = z.output<typeof projectSnapshotSchema>;\n\n/**\n * A config's snapshot: `absent` before the first type generation, `stale` when it was generated\n * for another config file, `invalid` when it cannot be read or does not match the schema.\n */\nexport type SnapshotRead =\n\t| { kind: \"valid\"; snapshot: ProjectSnapshot }\n\t| { kind: \"absent\" | \"stale\" }\n\t| { kind: \"invalid\"; reason: string };\n\nconst missing = (error: unknown) =>\n\terror instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n\nconst parseJson = (text: string): { json: unknown } | { error: unknown } => {\n\ttry {\n\t\treturn { json: JSON.parse(text) };\n\t} catch (error) {\n\t\treturn { error };\n\t}\n};\n\nexport async function readProjectSnapshot(\n\tconfigFile: string,\n): Promise<SnapshotRead> {\n\tconst file = resolve(dirname(configFile), projectSnapshotFile);\n\tconst read = await readFile(file, \"utf8\").then(\n\t\t(text) => ({ text }),\n\t\t(error: unknown) => ({ error }),\n\t);\n\tif (\"error\" in read) {\n\t\treturn missing(read.error)\n\t\t\t? { kind: \"absent\" }\n\t\t\t: { kind: \"invalid\", reason: `${file}: ${String(read.error)}` };\n\t}\n\tconst decoded = parseJson(read.text);\n\tif (\"error\" in decoded) {\n\t\treturn { kind: \"invalid\", reason: `${file}: ${String(decoded.error)}` };\n\t}\n\tconst parsed = projectSnapshotSchema.safeParse(decoded.json);\n\tif (!parsed.success) {\n\t\treturn {\n\t\t\tkind: \"invalid\",\n\t\t\treason: `${file}: ${z.prettifyError(parsed.error)}`,\n\t\t};\n\t}\n\treturn parsed.data.configFile === configFile\n\t\t? { kind: \"valid\", snapshot: parsed.data }\n\t\t: { kind: \"stale\" };\n}\n"
6
+ ],
7
+ "mappings": ";AAAA;AACA;AACA;AACA;AACA;AAGO,IAAM,wBAAwB,EAAE,OAAO;AAAA,EAC7C,SAAS,EAAE,QAAQ,CAAC;AAAA,EACpB,YAAY,EAAE,OAAO,EAAE,SAAS;AAAA,EAChC,QAAQ;AAAA,EACR,SAAS;AACV,CAAC;AAYD,IAAM,UAAU,CAAC,UAChB,iBAAiB,UAAS,UAAU,UAAS,MAAM,SAAS;AAE7D,IAAM,YAAY,CAAC,SAAyD;AAAA,EAC3E,IAAI;AAAA,IACH,OAAO,EAAE,MAAM,KAAK,MAAM,IAAI,EAAE;AAAA,IAC/B,OAAO,OAAO;AAAA,IACf,OAAO,EAAE,MAAM;AAAA;AAAA;AAIV,eAAe,mBAAmB,CACxC,YACwB;AAAA,EACxB,MAAM,OAAO,QAAQ,QAAQ,UAAU,GAAG,mBAAmB;AAAA,EAC7D,MAAM,OAAO,MAAM,SAAS,MAAM,MAAM,EAAE,KACzC,CAAC,UAAU,EAAE,KAAK,IAClB,CAAC,WAAoB,EAAE,MAAM,EAC9B;AAAA,EACA,IAAI,WAAW,MAAM;AAAA,IACpB,OAAO,QAAQ,KAAK,KAAK,IACtB,EAAE,MAAM,SAAS,IACjB,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,OAAO,KAAK,KAAK,IAAI;AAAA,EAChE;AAAA,EACA,MAAM,UAAU,UAAU,KAAK,IAAI;AAAA,EACnC,IAAI,WAAW,SAAS;AAAA,IACvB,OAAO,EAAE,MAAM,WAAW,QAAQ,GAAG,SAAS,OAAO,QAAQ,KAAK,IAAI;AAAA,EACvE;AAAA,EACA,MAAM,SAAS,sBAAsB,UAAU,QAAQ,IAAI;AAAA,EAC3D,IAAI,CAAC,OAAO,SAAS;AAAA,IACpB,OAAO;AAAA,MACN,MAAM;AAAA,MACN,QAAQ,GAAG,SAAS,EAAE,cAAc,OAAO,KAAK;AAAA,IACjD;AAAA,EACD;AAAA,EACA,OAAO,OAAO,KAAK,eAAe,aAC/B,EAAE,MAAM,SAAS,UAAU,OAAO,KAAK,IACvC,EAAE,MAAM,QAAQ;AAAA;",
8
+ "debugId": "FA7CACDC419D733464756E2164756E21",
9
+ "names": []
10
+ }
package/package.json CHANGED
@@ -16,7 +16,7 @@
16
16
  "url": "git+https://github.com/rip-technologies/tsplc.git",
17
17
  "directory": "packages/typegen"
18
18
  },
19
- "version": "0.2.21",
19
+ "version": "0.3.0",
20
20
  "type": "module",
21
21
  "exports": {
22
22
  ".": {
@@ -29,6 +29,11 @@
29
29
  "bun": "./src/codegen/generate.ts",
30
30
  "default": "./dist/codegen.js"
31
31
  },
32
+ "./project-snapshot": {
33
+ "types": "./src/project-snapshot.ts",
34
+ "bun": "./src/project-snapshot.ts",
35
+ "default": "./dist/project-snapshot.js"
36
+ },
32
37
  "./hardware": {
33
38
  "types": "./src/hardware.ts",
34
39
  "bun": "./src/hardware.ts",
@@ -38,19 +43,30 @@
38
43
  "files": [
39
44
  "dist",
40
45
  "src",
41
- "!**/*.test.ts"
46
+ "!**/*.test.ts",
47
+ "!**/*.fixtures.ts",
48
+ "!**/test_*.py",
49
+ "!**/__pycache__/**",
50
+ "!**/*.pyc",
51
+ "!**/tests/**"
42
52
  ],
43
53
  "engines": {
44
54
  "bun": ">=1.4.3"
45
55
  },
46
56
  "dependencies": {
47
- "@tsplc/config": "0.2.21",
57
+ "@tsplc/config": "0.3.0",
48
58
  "prettier": "3.9.10",
49
- "@tsplc/iec": "0.2.21"
59
+ "zod": "4.3.6",
60
+ "@tsplc/iec": "0.3.0"
50
61
  },
51
62
  "bin": {
52
63
  "tsplc-typegen": "./dist/cli.js"
53
64
  },
65
+ "buildEntries": {
66
+ "./dist/cli.js": {
67
+ "source": "./src/cli.ts"
68
+ }
69
+ },
54
70
  "publishConfig": {
55
71
  "access": "public"
56
72
  }
package/src/cli.ts CHANGED
@@ -2,8 +2,8 @@
2
2
  import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
3
3
  import { dirname, resolve } from "node:path";
4
4
  import { parseArgs } from "node:util";
5
- import { generateProject } from "./project.ts";
6
5
  import { generateTypes } from "./codegen/generate";
6
+ import { generateProject } from "./project.ts";
7
7
 
8
8
  async function main(): Promise<void> {
9
9
  const { values } = parseArgs({
@@ -1,20 +1,20 @@
1
1
  import { readdir, readFile } from "node:fs/promises";
2
2
  import { basename, join } from "node:path";
3
+ import type { Publication } from "@tsplc/config";
4
+ import { type ElementaryType, elementaryTypesByName } from "@tsplc/iec";
5
+ import { identifierPattern } from "@tsplc/iec/st";
3
6
  import {
4
7
  constantResolver,
5
8
  integerExpression,
6
9
  isNumberInteger,
7
10
  } from "./constants";
8
- import type { Publication } from "@tsplc/config";
9
- import { type ElementaryType, elementaryTypesByName } from "@tsplc/iec";
10
- import { identifierPattern } from "@tsplc/iec/st";
11
11
  import {
12
12
  type Declaration,
13
13
  type GlobalList,
14
- type Source,
15
- type TypeReference,
16
14
  parseDeclarations,
17
15
  parseGlobals,
16
+ type Source,
17
+ type TypeReference,
18
18
  } from "./parser";
19
19
 
20
20
  export interface GenerateOptions {
@@ -275,7 +275,8 @@ function emit(
275
275
  const visited = new Set<string>();
276
276
  function visitReference(type: TypeReference): void {
277
277
  if (type.kind === "array") {
278
- return visitReference(type.element);
278
+ visitReference(type.element);
279
+ return;
279
280
  }
280
281
  if (type.kind === "named" && !scalars[type.name.toUpperCase()]) {
281
282
  visit(declaration(type.name));
@@ -292,7 +293,9 @@ function emit(
292
293
  }
293
294
  visiting.add(type.name);
294
295
  if (type.kind === "struct") {
295
- type.members.forEach((member) => visitReference(member.type));
296
+ type.members.forEach((member) => {
297
+ visitReference(member.type);
298
+ });
296
299
  }
297
300
  if (type.kind === "alias") {
298
301
  visitReference(type.type);
@@ -1,9 +1,10 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import { readFile } from "node:fs/promises";
2
3
  import type { DeviceTree, ResolvedTsplcConfig } from "@tsplc/config";
3
4
  import { iecName } from "@tsplc/config/build";
4
- import type { HardwareCatalog } from "./hardware.ts";
5
5
  import { edsSections } from "./hardware/eds.ts";
6
6
  import { byteOffset } from "./hardware/process-image.ts";
7
+ import type { HardwareCatalog } from "./hardware.ts";
7
8
 
8
9
  const quoted = (value: string) => `"${value.replaceAll('"', '""')}"`;
9
10
 
@@ -1,5 +1,5 @@
1
- import type { EdsMember } from "./eds.ts";
2
1
  import { ioScalarBits } from "@tsplc/iec";
2
+ import type { EdsMember } from "./eds.ts";
3
3
  import { directAddress } from "./process-image.ts";
4
4
 
5
5
  export interface IoChannel {
@@ -1,3 +1,4 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  export interface EdsParameter {
2
3
  id: string;
3
4
  name: string;
@@ -53,21 +54,21 @@ export interface HardwareDescriptor {
53
54
  }
54
55
 
55
56
  const cipTypes: Record<number, string> = {
56
- 0xc1: "BOOL",
57
- 0xc2: "SINT",
58
- 0xc3: "INT",
59
- 0xc4: "DINT",
60
- 0xc5: "LINT",
61
- 0xc6: "USINT",
62
- 0xc7: "UINT",
63
- 0xc8: "UDINT",
64
- 0xc9: "ULINT",
65
- 0xca: "REAL",
66
- 0xcb: "LREAL",
67
- 0xd1: "BYTE",
68
- 0xd2: "WORD",
69
- 0xd3: "DWORD",
70
- 0xd4: "LWORD",
57
+ 193: "BOOL",
58
+ 194: "SINT",
59
+ 195: "INT",
60
+ 196: "DINT",
61
+ 197: "LINT",
62
+ 198: "USINT",
63
+ 199: "UINT",
64
+ 200: "UDINT",
65
+ 201: "ULINT",
66
+ 202: "REAL",
67
+ 203: "LREAL",
68
+ 209: "BYTE",
69
+ 210: "WORD",
70
+ 211: "DWORD",
71
+ 212: "LWORD",
71
72
  };
72
73
 
73
74
  /** A record's fields, and where the record (key through semicolon) sits in the EDS text. */
@@ -276,17 +277,19 @@ export function parseEds(
276
277
  }
277
278
  const parameters = Object.entries(records.Params ?? {})
278
279
  .filter(([id]) => /^Param\d+$/.test(id))
279
- .map(([id, fields]): EdsParameter => ({
280
- id,
281
- name: fields[6] || id,
282
- type: cipTypes[Number(fields[4])] ?? "opaque",
283
- size: integer(fields[5], `${id} data size`, { minimum: 1 }),
284
- unit: fields[7] ?? "",
285
- description: fields[8] ?? "",
286
- minimum: optionalNumber(fields[9]),
287
- maximum: optionalNumber(fields[10]),
288
- default: optionalNumber(fields[11]),
289
- }));
280
+ .map(
281
+ ([id, fields]): EdsParameter => ({
282
+ id,
283
+ name: fields[6] || id,
284
+ type: cipTypes[Number(fields[4])] ?? "opaque",
285
+ size: integer(fields[5], `${id} data size`, { minimum: 1 }),
286
+ unit: fields[7] ?? "",
287
+ description: fields[8] ?? "",
288
+ minimum: optionalNumber(fields[9]),
289
+ maximum: optionalNumber(fields[10]),
290
+ default: optionalNumber(fields[11]),
291
+ }),
292
+ );
290
293
  const params = new Map(
291
294
  parameters.map((parameter) => [parameter.id, parameter]),
292
295
  );
@@ -1,5 +1,6 @@
1
- import type { HardwareCatalog } from "../hardware.ts";
1
+ // biome-ignore-all lint/suspicious/noTemplateCurlyInString: These strings describe Docker or generated TypeScript interpolation, not JavaScript interpolation here.
2
2
  import { ioScalarBits } from "@tsplc/iec";
3
+ import type { HardwareCatalog } from "../hardware.ts";
3
4
  import { addressSize, ioLayout } from "./process-image.ts";
4
5
 
5
6
  /** A bindable `io` key with its layout; array indexes appear as the literal `${number}`. */
@@ -1,8 +1,9 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import type { IoChannel } from "./channels.ts";
2
3
  import {
3
- type ProcessImageRegion,
4
4
  byteOffset,
5
5
  directAddress,
6
+ type ProcessImageRegion,
6
7
  } from "./process-image.ts";
7
8
 
8
9
  export interface ModbusRegister {
package/src/hardware.ts CHANGED
@@ -1,12 +1,13 @@
1
+ // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
1
2
  import { readdir, readFile } from "node:fs/promises";
2
3
  import { resolve } from "node:path";
3
4
  import type { ResolvedTsplcConfig } from "@tsplc/config";
5
+ import { assemblyChannels, type IoChannel } from "./hardware/channels.ts";
4
6
  import {
5
7
  type EdsConnection,
6
8
  type HardwareDescriptor,
7
9
  parseEds,
8
10
  } from "./hardware/eds.ts";
9
- import { type IoChannel, assemblyChannels } from "./hardware/channels.ts";
10
11
  import {
11
12
  type ModbusRegister,
12
13
  placeModbusRegisters,
@@ -14,6 +15,8 @@ import {
14
15
  import { byteOffset, regionPlacer } from "./hardware/process-image.ts";
15
16
  import { selectAssemblies, selectConnection } from "./hardware/selection.ts";
16
17
 
18
+ export { ioScalarBits } from "@tsplc/iec";
19
+ export type { IoChannel } from "./hardware/channels.ts";
17
20
  export {
18
21
  type EdsAssembly,
19
22
  type EdsConnection,
@@ -24,15 +27,13 @@ export {
24
27
  parseEds,
25
28
  readEdsRecords,
26
29
  } from "./hardware/eds.ts";
27
- export type { IoChannel } from "./hardware/channels.ts";
28
- export type { ModbusRegister } from "./hardware/modbus.ts";
29
- export { ioScalarBits } from "@tsplc/iec";
30
- export { ioLayout } from "./hardware/process-image.ts";
31
30
  export {
31
+ generateHardwareTypes,
32
32
  type IoTarget,
33
33
  type ProjectTargets,
34
- generateHardwareTypes,
35
34
  } from "./hardware/mapping-types.ts";
35
+ export type { ModbusRegister } from "./hardware/modbus.ts";
36
+ export { ioLayout } from "./hardware/process-image.ts";
36
37
 
37
38
  export interface SelectedAssembly {
38
39
  direction: "input" | "output";
package/src/index.ts CHANGED
@@ -1,10 +1,7 @@
1
+ export { ioScalarBits } from "@tsplc/iec";
1
2
  export { generateTypes } from "./codegen/generate.ts";
2
- export {
3
- type HardwareCatalog,
4
- type SelectedAssembly,
5
- loadHardware,
6
- resolveIo,
7
- } from "./hardware.ts";
3
+ export { deviceTree, normalizeEds } from "./device-tree.ts";
4
+ export type { IoChannel } from "./hardware/channels.ts";
8
5
  export {
9
6
  type EdsAssembly,
10
7
  type EdsConnection,
@@ -15,15 +12,18 @@ export {
15
12
  parseEds,
16
13
  readEdsRecords,
17
14
  } 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
15
  export {
16
+ generateHardwareTypes,
23
17
  type IoTarget,
24
18
  type ProjectTargets,
25
- generateHardwareTypes,
26
19
  } from "./hardware/mapping-types.ts";
27
- export { deviceTree, normalizeEds } from "./device-tree.ts";
20
+ export type { ModbusRegister } from "./hardware/modbus.ts";
21
+ export { ioLayout } from "./hardware/process-image.ts";
22
+ export {
23
+ type HardwareCatalog,
24
+ loadHardware,
25
+ resolveIo,
26
+ type SelectedAssembly,
27
+ } from "./hardware.ts";
28
28
 
29
- export { generateProject } from "./project.ts";
29
+ export { generatedFiles, generateProject } from "./project.ts";
@@ -0,0 +1,63 @@
1
+ import { readFile } from "node:fs/promises";
2
+ import { dirname, resolve } from "node:path";
3
+ import { projectSnapshotFile } from "@tsplc/config/project-files";
4
+ import { ioSymbolsSchema, tsplcConfigSchema } from "@tsplc/config/schema";
5
+ import { z } from "zod";
6
+
7
+ /** What `tsplc typegen` materializes at `projectSnapshotFile` for readers that never execute the config. */
8
+ export const projectSnapshotSchema = z.object({
9
+ version: z.literal(1),
10
+ configFile: z.string().nonempty(),
11
+ config: tsplcConfigSchema,
12
+ symbols: ioSymbolsSchema,
13
+ });
14
+ export type ProjectSnapshot = z.output<typeof projectSnapshotSchema>;
15
+
16
+ /**
17
+ * A config's snapshot: `absent` before the first type generation, `stale` when it was generated
18
+ * for another config file, `invalid` when it cannot be read or does not match the schema.
19
+ */
20
+ export type SnapshotRead =
21
+ | { kind: "valid"; snapshot: ProjectSnapshot }
22
+ | { kind: "absent" | "stale" }
23
+ | { kind: "invalid"; reason: string };
24
+
25
+ const missing = (error: unknown) =>
26
+ error instanceof Error && "code" in error && error.code === "ENOENT";
27
+
28
+ const parseJson = (text: string): { json: unknown } | { error: unknown } => {
29
+ try {
30
+ return { json: JSON.parse(text) };
31
+ } catch (error) {
32
+ return { error };
33
+ }
34
+ };
35
+
36
+ export async function readProjectSnapshot(
37
+ configFile: string,
38
+ ): Promise<SnapshotRead> {
39
+ const file = resolve(dirname(configFile), projectSnapshotFile);
40
+ const read = await readFile(file, "utf8").then(
41
+ (text) => ({ text }),
42
+ (error: unknown) => ({ error }),
43
+ );
44
+ if ("error" in read) {
45
+ return missing(read.error)
46
+ ? { kind: "absent" }
47
+ : { kind: "invalid", reason: `${file}: ${String(read.error)}` };
48
+ }
49
+ const decoded = parseJson(read.text);
50
+ if ("error" in decoded) {
51
+ return { kind: "invalid", reason: `${file}: ${String(decoded.error)}` };
52
+ }
53
+ const parsed = projectSnapshotSchema.safeParse(decoded.json);
54
+ if (!parsed.success) {
55
+ return {
56
+ kind: "invalid",
57
+ reason: `${file}: ${z.prettifyError(parsed.error)}`,
58
+ };
59
+ }
60
+ return parsed.data.configFile === configFile
61
+ ? { kind: "valid", snapshot: parsed.data }
62
+ : { kind: "stale" };
63
+ }
package/src/project.ts CHANGED
@@ -1,23 +1,29 @@
1
1
  import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
- import { format } from "prettier";
4
3
  import {
4
+ ioSymbolsSchema,
5
+ type LoadedConfig,
5
6
  loadTsplcConfig,
6
7
  publicationSchema,
7
- typegenSchema,
8
8
  type ResolvedTsplcConfig,
9
+ typegenSchema,
9
10
  } from "@tsplc/config";
11
+ import {
12
+ emittedFiles,
13
+ emittedStDirectory,
14
+ projectSnapshotFile,
15
+ } from "@tsplc/config/project-files";
10
16
  import { blockCommentEnd, lineCommentEnd } from "@tsplc/iec/st";
17
+ import { format } from "prettier";
18
+ import type { z } from "zod";
11
19
  import { generateTypes, stFiles } from "./codegen/generate.ts";
12
20
  import {
13
21
  generateHardwareTypes,
14
- type ProjectTargets,
15
22
  loadHardware,
23
+ type ProjectTargets,
16
24
  resolveIo,
17
25
  } 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";
26
+ import type { projectSnapshotSchema } from "./project-snapshot.ts";
21
27
 
22
28
  // Prettier's format() never reads a Prettier config, so generated files keep Prettier's
23
29
  // defaults in whichever repository typegen runs.
@@ -27,10 +33,36 @@ const formatTypeScript = (source: string) =>
27
33
  const readPublication = async (root: string) =>
28
34
  publicationSchema.parse(
29
35
  JSON.parse(
30
- await readFile(resolve(root, emittedSt, "publication.json"), "utf8"),
36
+ await readFile(
37
+ resolve(root, emittedStDirectory, emittedFiles.publication),
38
+ "utf8",
39
+ ),
31
40
  ),
32
41
  );
33
42
 
43
+ /** The files typegen writes into the config's `typegen.dir`. */
44
+ export const generatedFiles = {
45
+ hardware: "hardware.ts",
46
+ contract: "plc.ts",
47
+ machines: "machines.ts",
48
+ } as const;
49
+
50
+ /** The compiler's IO symbol paths, or none before the project's first build. */
51
+ 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
+ if (!symbols.success) {
61
+ throw new Error(`Invalid IO symbols in ${file}`, { cause: symbols.error });
62
+ }
63
+ return symbols.data;
64
+ }
65
+
34
66
  interface ContractSources {
35
67
  types: string[];
36
68
  globals: string[];
@@ -64,7 +96,7 @@ async function contractSources(
64
96
  }
65
97
  return sources;
66
98
  }
67
- const source = config.compiler ? emittedSt : config.build?.sourceDir;
99
+ const source = config.compiler ? emittedStDirectory : config.build?.sourceDir;
68
100
  if (!source) {
69
101
  if (config.typegen) {
70
102
  throw new Error(
@@ -175,7 +207,7 @@ export async function generateProject(
175
207
  hardwareOnly?: boolean;
176
208
  /** Source-derived I/O keys and publication selectors, independent of the active target. */
177
209
  targets?: ProjectTargets;
178
- loaded?: Awaited<ReturnType<typeof loadTsplcConfig>>;
210
+ loaded?: LoadedConfig;
179
211
  } = {},
180
212
  ) {
181
213
  const { config, root, configFile } =
@@ -183,17 +215,12 @@ export async function generateProject(
183
215
  const settings = typegenSchema.parse(config.typegen ?? {});
184
216
  const catalog = await loadHardware(config, root);
185
217
  const io = resolveIo(config, catalog);
186
- const project = {
218
+ const project: z.input<typeof projectSnapshotSchema> = {
187
219
  version: 1,
188
220
  configFile,
189
221
  config,
190
222
  symbols: config.compiler
191
- ? JSON.parse(
192
- await readFile(
193
- resolve(root, emittedSt, "io-symbols.json"),
194
- "utf8",
195
- ).catch(() => "{}"),
196
- )
223
+ ? await readIoSymbols(root)
197
224
  : Object.fromEntries(
198
225
  Object.keys(io)
199
226
  .filter((symbol) => symbol.includes("."))
@@ -202,7 +229,7 @@ export async function generateProject(
202
229
  };
203
230
  const outputs: Output[] = [
204
231
  {
205
- path: resolve(root, settings.dir, "hardware.ts"),
232
+ path: resolve(root, settings.dir, generatedFiles.hardware),
206
233
  content: await formatTypeScript(
207
234
  generateHardwareTypes(
208
235
  catalog,
@@ -213,8 +240,8 @@ export async function generateProject(
213
240
  ),
214
241
  },
215
242
  {
216
- path: resolve(root, ".tsplc/project.json"),
217
- content: JSON.stringify(project, null, 2) + "\n",
243
+ path: resolve(root, projectSnapshotFile),
244
+ content: `${JSON.stringify(project, null, 2)}\n`,
218
245
  },
219
246
  ];
220
247
  const sources = options.hardwareOnly
@@ -223,7 +250,7 @@ export async function generateProject(
223
250
  if (sources) {
224
251
  const inferred = !!config.compiler && !sources.explicit;
225
252
  outputs.push({
226
- path: resolve(root, settings.dir, "plc.ts"),
253
+ path: resolve(root, settings.dir, generatedFiles.contract),
227
254
  content: await formatTypeScript(
228
255
  await generateTypes({
229
256
  types: sources.types,
@@ -248,12 +275,12 @@ export async function generateProject(
248
275
  }
249
276
  if (config.compiler && !options.hardwareOnly) {
250
277
  const machine = await readFile(
251
- resolve(root, emittedSt, "machines.ts"),
278
+ resolve(root, emittedStDirectory, emittedFiles.machines),
252
279
  "utf8",
253
280
  ).catch(() => undefined);
254
281
  if (machine) {
255
282
  outputs.push({
256
- path: resolve(root, settings.dir, "machines.ts"),
283
+ path: resolve(root, settings.dir, generatedFiles.machines),
257
284
  content: await formatTypeScript(machine),
258
285
  });
259
286
  }