@tsplc/config 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/compiler.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
1
2
  import { z } from "zod";
2
3
 
3
4
  interface Diagnostic {
@@ -7,13 +8,13 @@ interface Diagnostic {
7
8
  message: string;
8
9
  }
9
10
 
10
- export const nanosecondsPattern = /^[1-9][0-9]*$/;
11
- export const durationSchema = z
12
- .object({
13
- kind: z.literal("duration"),
14
- nanoseconds: z.string().regex(nanosecondsPattern),
15
- })
16
- .strict();
11
+ export const nanosecondsSchema = z
12
+ .string()
13
+ .regex(/^[1-9][0-9]*$/, { abort: true });
14
+ export const durationSchema = z.strictObject({
15
+ kind: z.literal("duration"),
16
+ nanoseconds: nanosecondsSchema,
17
+ });
17
18
 
18
19
  export type Duration = z.infer<typeof durationSchema>;
19
20
 
@@ -21,7 +22,6 @@ function duration(value: number, scale: number): Duration {
21
22
  if (!Number.isFinite(value) || value <= 0) {
22
23
  throw new Error("Task duration must be finite and positive.");
23
24
  }
24
- // Keep task periods exact before serializing them for the compiler/backend.
25
25
  const nanoseconds = value * scale;
26
26
  if (!Number.isSafeInteger(nanoseconds)) {
27
27
  throw new Error(
@@ -32,16 +32,18 @@ function duration(value: number, scale: number): Duration {
32
32
  }
33
33
 
34
34
  export const ns = (value: number): Duration => duration(value, 1);
35
- export const ms = (value: number): Duration => duration(value, 1_000_000);
35
+ export const ms = (value: number): Duration =>
36
+ duration(value, Number(nanosecondsPerMillisecond));
36
37
  export const seconds = (value: number): Duration =>
37
- duration(value, 1_000_000_000);
38
+ duration(value, Number(nanosecondsPerMillisecond) * 1000);
38
39
 
39
40
  /** The helpers a config calls to write a duration, by the name it calls them. */
40
41
  export const durationHelpers = { ns, ms, seconds };
41
42
 
42
- const sourceExportSchema = z
43
- .object({ module: z.string().min(1), export: z.string().min(1) })
44
- .strict();
43
+ export const sourceExportSchema = z.strictObject({
44
+ module: z.string().nonempty(),
45
+ export: z.string().nonempty(),
46
+ });
45
47
  // Names and priorities are only bounded here; a backend narrows them to what its scheduler accepts.
46
48
  export const taskSchema = z.strictObject({
47
49
  name: z.string().nonempty(),
@@ -53,41 +55,67 @@ export const taskSchema = z.strictObject({
53
55
  programs: z.array(z.string().nonempty()).nonempty(),
54
56
  });
55
57
 
58
+ /**
59
+ * Where a schedule repeats itself, in the order it reads: each task named as an earlier one
60
+ * (`position` null), and each program a task schedules that an earlier position already does.
61
+ * IEC names ignore case, so two that differ only in case repeat each other.
62
+ */
63
+ export const scheduleRepeats = (
64
+ tasks: readonly { name: string; programs: readonly string[] }[],
65
+ ) => {
66
+ const names = new Set<string>();
67
+ const programs = new Set<string>();
68
+ const repeats: { task: number; position: number | null }[] = [];
69
+ tasks.forEach((task, index) => {
70
+ const name = task.name.toUpperCase();
71
+ if (names.has(name)) {
72
+ repeats.push({ task: index, position: null });
73
+ }
74
+ names.add(name);
75
+ task.programs.forEach((program, position) => {
76
+ const scheduled = program.toUpperCase();
77
+ if (programs.has(scheduled)) {
78
+ repeats.push({ task: index, position });
79
+ }
80
+ programs.add(scheduled);
81
+ });
82
+ });
83
+ return repeats;
84
+ };
85
+
56
86
  // Shared configuration validates the target envelope. Each backend owns its
57
87
  // options schema and hardware-specific scheduling/addressing constraints.
58
- const targetSchema = z
59
- .object({
60
- kind: z.string().min(1),
61
- options: z.unknown().refine((value) => value !== undefined, {
62
- message: "Target options are required.",
63
- }),
64
- })
65
- .strict();
88
+ const targetSchema = z.strictObject({
89
+ kind: z.string().nonempty(),
90
+ options: z.unknown().refine((value) => value !== undefined, {
91
+ message: "Target options are required.",
92
+ }),
93
+ });
66
94
  const common = {
67
- name: z.string().min(1),
68
- tsconfig: z.string().min(1),
69
- tasks: z.array(taskSchema).min(1),
95
+ name: z.string().nonempty(),
96
+ tsconfig: z.string().nonempty(),
97
+ tasks: z.array(taskSchema).nonempty(),
70
98
  target: targetSchema,
71
99
  };
72
- const entryConfigSchema = z
73
- .object({ ...common, entry: sourceExportSchema })
74
- .strict();
75
- const programsConfigSchema = z
76
- .object({
77
- ...common,
78
- programs: z.record(z.string().min(1), sourceExportSchema),
79
- })
80
- .strict();
81
-
82
- export interface TargetDescriptor<Options = unknown> {
83
- kind: string;
84
- options: Options;
85
- }
100
+ const entryConfigSchema = z.strictObject({
101
+ ...common,
102
+ entry: sourceExportSchema,
103
+ });
104
+ const programsConfigSchema = z.strictObject({
105
+ ...common,
106
+ programs: z.record(z.string().nonempty(), sourceExportSchema),
107
+ });
108
+
109
+ export type TargetDescriptor<Options = unknown> = Omit<
110
+ z.infer<typeof targetSchema>,
111
+ "options"
112
+ > & { options: Options };
86
113
  export type SourceExport = z.infer<typeof sourceExportSchema>;
87
114
  export type TaskConfig = Omit<z.infer<typeof taskSchema>, "programs"> & {
88
115
  programs: readonly string[];
89
116
  };
90
117
 
118
+ // Readonly lists, unlike the schemas' output, so a config written `as const` is accepted.
91
119
  export type PlcConfig<Target extends TargetDescriptor = TargetDescriptor> = {
92
120
  name: string;
93
121
  tsconfig: string;
@@ -98,13 +126,7 @@ export type PlcConfig<Target extends TargetDescriptor = TargetDescriptor> = {
98
126
  | { programs: Readonly<Record<string, SourceExport>>; entry?: never }
99
127
  );
100
128
 
101
- export interface NormalizedConfig {
102
- name: string;
103
- tsconfig: string;
104
- programs: Readonly<Record<string, SourceExport>>;
105
- tasks: readonly TaskConfig[];
106
- target: TargetDescriptor;
107
- }
129
+ export type NormalizedConfig = z.output<typeof programsConfigSchema>;
108
130
 
109
131
  export function definePlcConfig<const C extends PlcConfig>(config: C): C {
110
132
  return config;
@@ -148,27 +170,27 @@ export function validateConfig(value: unknown): {
148
170
  report("At least one program is required.");
149
171
  }
150
172
 
151
- // A program has one scan owner. Preserve task call order while rejecting
152
- // unknown, duplicated, or unassigned program keys.
153
- const taskNames = new Set<string>();
154
- const assigned = new Set<string>();
155
- for (const task of data.tasks) {
156
- if (taskNames.has(task.name)) {
173
+ const repeats = scheduleRepeats(data.tasks);
174
+ const repeated = (task: number, position: number | null) =>
175
+ repeats.some(
176
+ (repeat) => repeat.task === task && repeat.position === position,
177
+ );
178
+ data.tasks.forEach((task, index) => {
179
+ if (repeated(index, null)) {
157
180
  report(`Duplicate task name: ${task.name}.`);
158
181
  }
159
- taskNames.add(task.name);
160
- for (const program of task.programs) {
182
+ task.programs.forEach((program, position) => {
161
183
  if (!Object.hasOwn(programs, program)) {
162
184
  report(`Task ${task.name} references unknown program ${program}.`);
163
185
  }
164
- if (assigned.has(program)) {
186
+ if (repeated(index, position)) {
165
187
  report(`Program ${program} must belong to exactly one task.`);
166
188
  }
167
- assigned.add(program);
168
- }
169
- }
189
+ });
190
+ });
191
+ const scheduled = new Set(data.tasks.flatMap((task) => task.programs));
170
192
  for (const program of Object.keys(programs)) {
171
- if (!assigned.has(program)) {
193
+ if (!scheduled.has(program)) {
172
194
  report(`Program ${program} is not assigned to a task.`);
173
195
  }
174
196
  }
@@ -0,0 +1,15 @@
1
+ import { z } from "zod";
2
+
3
+ const configModuleSchema = z.object({
4
+ default: z.unknown(),
5
+ config: z.unknown(),
6
+ });
7
+
8
+ /** The config a config module exports: its default export, else its `config` export. */
9
+ export const configExport = (module: unknown, path: string) => {
10
+ const exports = configModuleSchema.parse(module);
11
+ if (exports.default === undefined && exports.config === undefined) {
12
+ throw new Error(`${path} must export a default config`);
13
+ }
14
+ return exports.default ?? exports.config;
15
+ };
@@ -1,4 +1,5 @@
1
1
  import { z } from "zod";
2
+ import { envName } from "./build-schema";
2
3
  import type { ResolvedTsplcConfig } from "./schema";
3
4
 
4
5
  /** Environment variables by name, as `process.env` holds them. */
@@ -14,6 +15,12 @@ export const secretValue = z
14
15
  .max(secretLength, `is longer than ${secretLength} characters`)
15
16
  .regex(/^[^\r\n\0]*$/, "holds a line break or NUL");
16
17
 
18
+ /** A plain variable's value, which the PLC's program may read through `env()`: no NUL. */
19
+ export const plainValue = z
20
+ .string()
21
+ .nonempty("is empty")
22
+ .regex(/^[^\0]*$/, "holds a NUL");
23
+
17
24
  /**
18
25
  * What a release for the plant agent carries in its ST instead of secret `name`; the agent puts
19
26
  * the value in its place. It is as long as the longest value, so whatever holds it fits the value.
@@ -21,6 +28,10 @@ export const secretValue = z
21
28
  export const secretPlaceholder = (name: string) =>
22
29
  `${`{{tsplc-secret:${name}:`.padEnd(secretLength - 2, "-")}}}`;
23
30
 
31
+ /** The plant agent `tsplc` commands reach, and the token they reach it with. */
32
+ export const agentUrlEnv = "TSPLC_AGENT_URL";
33
+ export const agentTokenEnv = "TSPLC_AGENT_TOKEN";
34
+
24
35
  export interface EnvironmentOptions {
25
36
  env: Environment;
26
37
  /** The config's target to take values from; with one target configured, that one. */
@@ -61,48 +72,55 @@ const selectedTarget = (
61
72
  };
62
73
 
63
74
  /**
64
- * The selected target's values. A release for the plant agent carries them, and the agent starts
65
- * its server with them, so the PLC and the server read the same ones.
75
+ * `projectEnvironment` with the selected target's values alone. A release for the plant agent
76
+ * carries them, and the agent starts its server with them, so the PLC and the server read the
77
+ * same ones.
66
78
  */
67
- export const targetValues = (
79
+ export const targetEnvironment = (
68
80
  config: ResolvedTsplcConfig,
69
81
  options: EnvironmentOptions,
70
- ): Readonly<Record<string, string>> =>
71
- selectedTarget(config, options)?.values ?? {};
82
+ ): { env: Environment; values: Readonly<Record<string, string>> } => {
83
+ const target = selectedTarget(config, options);
84
+ return {
85
+ env: {
86
+ ...options.env,
87
+ ...(target?.agent && { [agentUrlEnv]: target.agent.url }),
88
+ ...target?.values,
89
+ ...(options.forAgent &&
90
+ Object.fromEntries(
91
+ (config.secrets?.names ?? []).map((name) => [
92
+ name,
93
+ secretPlaceholder(name),
94
+ ]),
95
+ )),
96
+ },
97
+ values: target?.values ?? {},
98
+ };
99
+ };
72
100
 
73
101
  /**
74
102
  * The environment the build reads the config's variables from, such as `server.baseUrlEnv`, the
75
103
  * HTTP credentials and the program's `env()` calls, and the plant commands their agent from:
76
- * `env`, with the target's agent as TSPLC_AGENT_URL and its values over it.
104
+ * `env`, with the target's agent as `agentUrlEnv` and its values over it.
77
105
  */
78
106
  export const projectEnvironment = (
79
107
  config: ResolvedTsplcConfig,
80
108
  options: EnvironmentOptions,
81
- ): Environment => {
82
- const target = selectedTarget(config, options);
83
- return {
84
- ...options.env,
85
- ...(target?.agent && { TSPLC_AGENT_URL: target.agent.url }),
86
- ...target?.values,
87
- ...(options.forAgent &&
88
- Object.fromEntries(
89
- (config.secrets?.names ?? []).map((name) => [
90
- name,
91
- secretPlaceholder(name),
92
- ]),
93
- )),
94
- };
95
- };
109
+ ): Environment => targetEnvironment(config, options).env;
96
110
 
97
111
  /**
98
112
  * What a plant agent holds for a release: its plain variables' values, and the names of the
99
113
  * secrets it holds in `service`, the config's `secrets.service` or the agent's own.
100
114
  */
101
- export interface PlantVariables {
102
- service: string;
103
- values: Readonly<Record<string, string>>;
104
- secrets: readonly string[];
105
- }
115
+ export const plantVariablesSchema = z.strictObject({
116
+ service: z.string().nonempty(),
117
+ values: z.record(envName, z.string()),
118
+ secrets: z.array(envName),
119
+ });
120
+ export type PlantVariables = z.infer<typeof plantVariablesSchema>;
121
+
122
+ const isNonEmpty = <Item>(items: Item[]): items is [Item, ...Item[]] =>
123
+ items.length > 0;
106
124
 
107
125
  /**
108
126
  * What a release for the plant agent is built with: the loaded config's environment with the
@@ -118,7 +136,6 @@ export const releaseEnvironment = (
118
136
  const names = [
119
137
  ...new Set([...(config.secrets?.names ?? []), ...plant.secrets]),
120
138
  ].filter((name) => !Object.hasOwn(plant.values, name));
121
- const [first, ...rest] = names;
122
139
  return {
123
140
  env: {
124
141
  ...loaded.env,
@@ -128,12 +145,6 @@ export const releaseEnvironment = (
128
145
  ),
129
146
  },
130
147
  values: { ...loaded.values, ...plant.values },
131
- secrets:
132
- first === undefined
133
- ? undefined
134
- : {
135
- service: plant.service,
136
- names: [first, ...rest] satisfies [string, ...string[]],
137
- },
148
+ secrets: isNonEmpty(names) ? { service: plant.service, names } : undefined,
138
149
  };
139
150
  };
package/src/index.ts CHANGED
@@ -17,15 +17,20 @@ export {
17
17
  validateConfig,
18
18
  } from "./compiler";
19
19
  export {
20
+ agentTokenEnv,
21
+ agentUrlEnv,
20
22
  type Environment,
21
23
  type EnvironmentOptions,
22
24
  type PlantVariables,
25
+ plainValue,
26
+ plantVariablesSchema,
23
27
  projectEnvironment,
24
28
  releaseEnvironment,
25
29
  secretPlaceholder,
26
30
  secretValue,
27
31
  } from "./environment";
28
32
  export { type LoadedConfig, loadTsplcConfig } from "./loader";
33
+ export { ioSymbolsSchema } from "./project-files";
29
34
  export {
30
35
  type BuildTarget,
31
36
  buildTargetFor,
@@ -39,19 +44,23 @@ export {
39
44
  type HttpOptions,
40
45
  hmiSchema,
41
46
  httpOptionsSchema,
42
- ioSymbolsSchema,
43
47
  type LibraryDependency,
44
48
  type Publication,
49
+ projectSlugs,
45
50
  publicationSchema,
46
51
  type ResolvedDebugConfig,
47
52
  type ResolvedHmiConfig,
48
53
  type ResolvedTelemetryConfig,
49
54
  type ResolvedTsplcConfig,
50
55
  rawBuildConfig,
56
+ type ServerConfig,
57
+ serverBaseUrl,
51
58
  serverTokenEnv,
52
59
  simulationConfig,
53
60
  type TsplcConfig,
61
+ taskPlan,
54
62
  telemetrySchema,
55
63
  tsplcConfigSchema,
56
64
  typegenSchema,
65
+ typegenSettings,
57
66
  } from "./schema";
package/src/loader.ts CHANGED
@@ -1,24 +1,17 @@
1
- import { readFile } from "node:fs/promises";
1
+ import { access } from "node:fs/promises";
2
2
  import { dirname, resolve } from "node:path";
3
3
  import { createJiti } from "jiti";
4
- import {
5
- type EnvironmentOptions,
6
- projectEnvironment,
7
- targetValues,
8
- } from "./environment";
4
+ import { configExport } from "./config-module";
5
+ import { type EnvironmentOptions, targetEnvironment } from "./environment";
9
6
  import { tsplcConfigSchema } from "./schema";
10
7
 
11
- /** The config, the target's values, and the environment its variables resolve in: `process.env` and the only target, unless `environment` says otherwise. */
8
+ /** The config, the target's values, and the environment its variables resolve in. */
12
9
  export async function loadTsplcConfig(
13
- file = "tsplc.config.ts",
14
- environment: EnvironmentOptions = {
15
- env: process.env,
16
- target: undefined,
17
- forAgent: false,
18
- },
10
+ file: string,
11
+ environment: EnvironmentOptions,
19
12
  ) {
20
13
  const configFile = resolve(file);
21
- await readFile(configFile);
14
+ await access(configFile);
22
15
  const jiti = createJiti(import.meta.url, {
23
16
  moduleCache: false,
24
17
  fsCache: false,
@@ -26,20 +19,14 @@ export async function loadTsplcConfig(
26
19
  // Bun can import TS natively, but its module cache would hide config edits.
27
20
  tryNative: false,
28
21
  });
29
- const module = await jiti.import<{ default?: unknown; config?: unknown }>(
30
- configFile,
22
+ const config = tsplcConfigSchema.parse(
23
+ configExport(await jiti.import(configFile), configFile),
31
24
  );
32
- const config = tsplcConfigSchema.parse(module.default ?? module.config);
33
- if (config.compiler && !config.tasks) {
34
- throw new Error("TypeScript programs require a tasks configuration.");
35
- }
36
25
  return {
37
26
  configFile,
38
27
  root: dirname(configFile),
39
28
  config,
40
- env: projectEnvironment(config, environment),
41
- /** The selected target's values alone, which a release carries to the plant agent's server. */
42
- values: targetValues(config, environment),
29
+ ...targetEnvironment(config, environment),
43
30
  };
44
31
  }
45
32
 
@@ -1,3 +1,9 @@
1
+ import { z } from "zod";
2
+ import type { ResolvedTsplcConfig } from "./schema";
3
+
4
+ /** The file in a project's directory that holds its config. */
5
+ export const configFileName = "tsplc.config.ts";
6
+
1
7
  /** Generated project state, relative to the directory that holds a project's config. */
2
8
  export const generatedDirectory = ".tsplc";
3
9
 
@@ -11,5 +17,13 @@ export const emittedFiles = {
11
17
  machines: "machines.ts",
12
18
  } as const;
13
19
 
20
+ /** `emittedFiles.ioSymbols`: each IO binding's name with the published symbol path the compiler gave it. */
21
+ export const ioSymbolsSchema = z.record(z.string(), z.string());
22
+
14
23
  /** Typegen's materialized config and symbols, which the editor reads instead of executing the config. */
15
24
  export const projectSnapshotFile = `${generatedDirectory}/project.json`;
25
+
26
+ /** A project's ST, relative to its config: the emitted ST of a TypeScript project, else its build sources. */
27
+ export const stRoot = (
28
+ config: Pick<ResolvedTsplcConfig, "compiler" | "build">,
29
+ ) => (config.compiler ? emittedStDirectory : config.build?.sourceDir);