@tsplc/config 0.5.14 → 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/dist/index.js CHANGED
@@ -1,10 +1,11 @@
1
1
  // packages/config/src/compiler.ts
2
+ import { nanosecondsPerMillisecond } from "@tsplc/iec";
2
3
  import { z } from "zod";
3
- var nanosecondsPattern = /^[1-9][0-9]*$/;
4
- var durationSchema = z.object({
4
+ var nanosecondsSchema = z.string().regex(/^[1-9][0-9]*$/, { abort: true });
5
+ var durationSchema = z.strictObject({
5
6
  kind: z.literal("duration"),
6
- nanoseconds: z.string().regex(nanosecondsPattern)
7
- }).strict();
7
+ nanoseconds: nanosecondsSchema
8
+ });
8
9
  function duration(value, scale) {
9
10
  if (!Number.isFinite(value) || value <= 0) {
10
11
  throw new Error("Task duration must be finite and positive.");
@@ -16,9 +17,12 @@ function duration(value, scale) {
16
17
  return { kind: "duration", nanoseconds: String(nanoseconds) };
17
18
  }
18
19
  var ns = (value) => duration(value, 1);
19
- var ms = (value) => duration(value, 1e6);
20
- var seconds = (value) => duration(value, 1e9);
21
- var sourceExportSchema = z.object({ module: z.string().min(1), export: z.string().min(1) }).strict();
20
+ var ms = (value) => duration(value, Number(nanosecondsPerMillisecond));
21
+ var seconds = (value) => duration(value, Number(nanosecondsPerMillisecond) * 1000);
22
+ var sourceExportSchema = z.strictObject({
23
+ module: z.string().nonempty(),
24
+ export: z.string().nonempty()
25
+ });
22
26
  var taskSchema = z.strictObject({
23
27
  name: z.string().nonempty(),
24
28
  schedule: z.strictObject({
@@ -28,23 +32,46 @@ var taskSchema = z.strictObject({
28
32
  priority: z.number().int().nonnegative(),
29
33
  programs: z.array(z.string().nonempty()).nonempty()
30
34
  });
31
- var targetSchema = z.object({
32
- kind: z.string().min(1),
35
+ var scheduleRepeats = (tasks) => {
36
+ const names = new Set;
37
+ const programs = new Set;
38
+ const repeats = [];
39
+ tasks.forEach((task, index) => {
40
+ const name = task.name.toUpperCase();
41
+ if (names.has(name)) {
42
+ repeats.push({ task: index, position: null });
43
+ }
44
+ names.add(name);
45
+ task.programs.forEach((program, position) => {
46
+ const scheduled = program.toUpperCase();
47
+ if (programs.has(scheduled)) {
48
+ repeats.push({ task: index, position });
49
+ }
50
+ programs.add(scheduled);
51
+ });
52
+ });
53
+ return repeats;
54
+ };
55
+ var targetSchema = z.strictObject({
56
+ kind: z.string().nonempty(),
33
57
  options: z.unknown().refine((value) => value !== undefined, {
34
58
  message: "Target options are required."
35
59
  })
36
- }).strict();
60
+ });
37
61
  var common = {
38
- name: z.string().min(1),
39
- tsconfig: z.string().min(1),
40
- tasks: z.array(taskSchema).min(1),
62
+ name: z.string().nonempty(),
63
+ tsconfig: z.string().nonempty(),
64
+ tasks: z.array(taskSchema).nonempty(),
41
65
  target: targetSchema
42
66
  };
43
- var entryConfigSchema = z.object({ ...common, entry: sourceExportSchema }).strict();
44
- var programsConfigSchema = z.object({
67
+ var entryConfigSchema = z.strictObject({
45
68
  ...common,
46
- programs: z.record(z.string().min(1), sourceExportSchema)
47
- }).strict();
69
+ entry: sourceExportSchema
70
+ });
71
+ var programsConfigSchema = z.strictObject({
72
+ ...common,
73
+ programs: z.record(z.string().nonempty(), sourceExportSchema)
74
+ });
48
75
  function definePlcConfig(config) {
49
76
  return config;
50
77
  }
@@ -75,25 +102,24 @@ function validateConfig(value) {
75
102
  if (Object.keys(programs).length === 0) {
76
103
  report("At least one program is required.");
77
104
  }
78
- const taskNames = new Set;
79
- const assigned = new Set;
80
- for (const task of data.tasks) {
81
- if (taskNames.has(task.name)) {
105
+ const repeats = scheduleRepeats(data.tasks);
106
+ const repeated = (task, position) => repeats.some((repeat) => repeat.task === task && repeat.position === position);
107
+ data.tasks.forEach((task, index) => {
108
+ if (repeated(index, null)) {
82
109
  report(`Duplicate task name: ${task.name}.`);
83
110
  }
84
- taskNames.add(task.name);
85
- for (const program of task.programs) {
111
+ task.programs.forEach((program, position) => {
86
112
  if (!Object.hasOwn(programs, program)) {
87
113
  report(`Task ${task.name} references unknown program ${program}.`);
88
114
  }
89
- if (assigned.has(program)) {
115
+ if (repeated(index, position)) {
90
116
  report(`Program ${program} must belong to exactly one task.`);
91
117
  }
92
- assigned.add(program);
93
- }
94
- }
118
+ });
119
+ });
120
+ const scheduled = new Set(data.tasks.flatMap((task) => task.programs));
95
121
  for (const program of Object.keys(programs)) {
96
- if (!assigned.has(program)) {
122
+ if (!scheduled.has(program)) {
97
123
  report(`Program ${program} is not assigned to a task.`);
98
124
  }
99
125
  }
@@ -112,74 +138,13 @@ function validateConfig(value) {
112
138
  };
113
139
  }
114
140
  // packages/config/src/environment.ts
115
- import { z as z2 } from "zod";
116
- var secretLength = 512;
117
- var secretValue = z2.string().nonempty("is empty").max(secretLength, `is longer than ${secretLength} characters`).regex(/^[^\r\n\0]*$/, "holds a line break or NUL");
118
- var secretPlaceholder = (name) => `${`{{tsplc-secret:${name}:`.padEnd(secretLength - 2, "-")}}}`;
119
- var selectedTarget = (config, { target, forAgent }) => {
120
- const names = Object.keys(config.targets);
121
- if (target !== undefined) {
122
- const selected = config.targets[target];
123
- if (!selected) {
124
- throw new Error(`The config has no target ${target}; its targets are: ${names.join(", ") || "none"}.`);
125
- }
126
- return selected;
127
- }
128
- const targets = Object.values(config.targets);
129
- if (targets.length <= 1) {
130
- return targets[0];
131
- }
132
- if (!forAgent) {
133
- return;
134
- }
135
- const withAgent = targets.filter(({ agent }) => agent);
136
- if (withAgent.length === 1) {
137
- return withAgent[0];
138
- }
139
- throw new Error(`Choose the target to deploy to with --target: ${names.join(", ")}.`);
140
- };
141
- var targetValues = (config, options) => selectedTarget(config, options)?.values ?? {};
142
- var projectEnvironment = (config, options) => {
143
- const target = selectedTarget(config, options);
144
- return {
145
- ...options.env,
146
- ...target?.agent && { TSPLC_AGENT_URL: target.agent.url },
147
- ...target?.values,
148
- ...options.forAgent && Object.fromEntries((config.secrets?.names ?? []).map((name) => [
149
- name,
150
- secretPlaceholder(name)
151
- ]))
152
- };
153
- };
154
- var releaseEnvironment = (config, loaded, plant) => {
155
- const names = [
156
- ...new Set([...config.secrets?.names ?? [], ...plant.secrets])
157
- ].filter((name) => !Object.hasOwn(plant.values, name));
158
- const [first, ...rest] = names;
159
- return {
160
- env: {
161
- ...loaded.env,
162
- ...plant.values,
163
- ...Object.fromEntries(names.map((name) => [name, secretPlaceholder(name)]))
164
- },
165
- values: { ...loaded.values, ...plant.values },
166
- secrets: first === undefined ? undefined : {
167
- service: plant.service,
168
- names: [first, ...rest]
169
- }
170
- };
171
- };
172
- // packages/config/src/loader.ts
173
- import { readFile } from "node:fs/promises";
174
- import { dirname, resolve } from "node:path";
175
- import { createJiti } from "jiti";
176
-
177
- // packages/config/src/schema.ts
178
- import { z as z4 } from "zod";
141
+ import { z as z3 } from "zod";
179
142
 
180
143
  // packages/config/src/build-schema.ts
181
- import { z as z3 } from "zod";
182
- var commandArgumentSchema = z3.string().refine((value) => value.trim().length > 0, "Command arguments must not be empty").refine((value) => !/["\r\n\0]/.test(value), "Command arguments must not contain quotes, line breaks, or null bytes");
144
+ import { latestTimeNanoseconds, nanosecondsPerMillisecond as nanosecondsPerMillisecond2 } from "@tsplc/iec";
145
+ import { generatedNamePattern } from "@tsplc/iec/st";
146
+ import { z as z2 } from "zod";
147
+ var commandArgumentSchema = z2.string().refine((value) => value.trim().length > 0, "Command arguments must not be empty").refine((value) => !/["\r\n\0]/.test(value), "Command arguments must not contain quotes, line breaks, or null bytes");
183
148
  var codesysTimeouts = {
184
149
  build: 20 * 60 * 1000,
185
150
  hostCommand: 15000,
@@ -189,171 +154,161 @@ var codesysTimeouts = {
189
154
  terminate: 5000,
190
155
  transfer: 30 * 60 * 1000
191
156
  };
192
- var positiveMilliseconds = z3.number().int().positive();
193
- var pathSchema = z3.string().trim().nonempty();
194
- var tcpPort = z3.number().int().min(1).max(65535);
195
- var sha256Digest = z3.string().regex(/^[a-f0-9]{64}$/);
196
- var envName = z3.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
197
- var wineSchema = z3.strictObject({
157
+ var positiveMilliseconds = z2.number().int().positive();
158
+ var pathSchema = z2.string().trim().nonempty();
159
+ var tcpPort = z2.number().int().min(1).max(65535);
160
+ var runtimePort = 11740;
161
+ var gatewayPort = 1217;
162
+ var sha256Digest = z2.string().regex(/^[a-f0-9]{64}$/);
163
+ var envName = z2.string().regex(/^[A-Za-z_][A-Za-z0-9_]*$/);
164
+ var wineSchema = z2.strictObject({
198
165
  prefix: pathSchema,
199
166
  binary: pathSchema.default("wine"),
200
167
  pathBinary: pathSchema.default("winepath"),
201
- debug: z3.string().default("-all"),
202
- nativeExit: z3.boolean().default(false)
168
+ debug: z2.string().default("-all"),
169
+ nativeExit: z2.boolean().default(false)
203
170
  });
204
- var localCodesysSchema = z3.strictObject({
171
+ var localCodesysSchema = z2.strictObject({
205
172
  executable: commandArgumentSchema,
206
173
  profile: commandArgumentSchema,
207
174
  wine: wineSchema.optional(),
208
175
  commandProcessor: pathSchema.default("cmd.exe")
209
176
  });
210
- var iecName = z3.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/);
211
- var taskPriority = z3.number().int().min(0).max(31);
212
- var cyclicTasksSchema = z3.array(z3.strictObject({
177
+ var iecName = z2.string().regex(generatedNamePattern);
178
+ var taskPriority = z2.number().int().min(0).max(31);
179
+ var cyclicTasksSchema = z2.array(z2.strictObject({
213
180
  name: iecName,
214
- intervalNanoseconds: z3.string().regex(nanosecondsPattern).refine((value) => {
215
- if (!nanosecondsPattern.test(value)) {
216
- return false;
217
- }
181
+ intervalNanoseconds: nanosecondsSchema.refine((value) => {
218
182
  const ns = BigInt(value);
219
- return ns % 1000000n === 0n && ns <= 4294967295000000n;
183
+ return ns % nanosecondsPerMillisecond2 === 0n && ns <= latestTimeNanoseconds;
220
184
  }, "Cyclic tasks require an exact positive TIME interval in milliseconds"),
221
185
  priority: taskPriority,
222
- programs: z3.array(iecName).nonempty()
186
+ programs: z2.array(iecName).nonempty()
223
187
  })).nonempty().superRefine((tasks, context) => {
224
- const names = new Set;
225
- const programs = new Set;
226
- tasks.forEach((task, index) => {
227
- if (names.has(task.name.toLowerCase())) {
228
- context.addIssue({
229
- code: "custom",
230
- path: [index, "name"],
231
- message: "Task names must be unique"
232
- });
233
- }
234
- names.add(task.name.toLowerCase());
235
- task.programs.forEach((program, position) => {
236
- if (programs.has(program.toLowerCase())) {
237
- context.addIssue({
238
- code: "custom",
239
- path: [index, "programs", position],
240
- message: "A program can be scheduled only once"
241
- });
242
- }
243
- programs.add(program.toLowerCase());
188
+ for (const { task, position } of scheduleRepeats(tasks)) {
189
+ context.addIssue(position === null ? {
190
+ code: "custom",
191
+ path: [task, "name"],
192
+ message: "Task names must be unique"
193
+ } : {
194
+ code: "custom",
195
+ path: [task, "programs", position],
196
+ message: "A program can be scheduled only once"
244
197
  });
245
- });
198
+ }
246
199
  });
247
200
  var ioBindingOptions = {
248
- inverted: z3.boolean().optional(),
249
- shared: z3.boolean().optional()
201
+ inverted: z2.boolean().optional(),
202
+ shared: z2.boolean().optional()
250
203
  };
251
- var directIoBindingSchema = z3.strictObject({
252
- address: z3.string().regex(/^%[IQ](?:X\d+\.[0-7]|[BWD]\d+)$/),
253
- type: z3.string().optional(),
204
+ var directIoBindingSchema = z2.strictObject({
205
+ address: z2.string().regex(/^%[IQ](?:X\d+\.[0-7]|[BWD]\d+)$/),
206
+ type: z2.string().optional(),
254
207
  ...ioBindingOptions
255
208
  });
256
- var ethernetSchema = z3.strictObject({
257
- interface: z3.string().nonempty().optional(),
258
- address: z3.ipv4().optional(),
259
- subnet: z3.ipv4().optional(),
260
- gateway: z3.ipv4().optional()
209
+ var ethernetSchema = z2.strictObject({
210
+ interface: z2.string().nonempty().optional(),
211
+ address: z2.ipv4().optional(),
212
+ subnet: z2.ipv4().optional(),
213
+ gateway: z2.ipv4().optional()
261
214
  });
262
- var assemblyAddress = z3.string().regex(/^%[IQ]B\d+$/);
263
- var processImageSchema = z3.strictObject({
215
+ var assemblyAddress = z2.string().regex(/^%[IQ]B\d+$/);
216
+ var processImageSchema = z2.strictObject({
264
217
  address: assemblyAddress,
265
- size: z3.number().int().positive()
218
+ size: z2.number().int().positive()
266
219
  });
267
- var channelAddress = z3.string().regex(/^%[IQ](?:X\d+\.[0-7]|B\d+)$/);
268
- var deviceTreeSchema = z3.strictObject({
220
+ var channelAddress = z2.string().regex(/^%[IQ](?:X\d+\.[0-7]|B\d+)$/);
221
+ var deviceTreeSchema = z2.strictObject({
269
222
  ethernet: ethernetSchema.default({}),
270
- devices: z3.array(z3.strictObject({
223
+ devices: z2.array(z2.strictObject({
271
224
  name: iecName,
272
- eds: z3.string().nonempty(),
273
- address: z3.ipv4().optional(),
274
- rpiMicroseconds: z3.number().int().positive().optional(),
225
+ eds: z2.string().nonempty(),
226
+ address: z2.ipv4().optional(),
227
+ rpiMicroseconds: z2.number().int().positive().optional(),
275
228
  inputs: processImageSchema.optional(),
276
229
  outputs: processImageSchema.optional(),
277
- modbus: z3.strictObject({
230
+ modbus: z2.strictObject({
278
231
  port: tcpPort,
279
- registers: z3.array(z3.strictObject({
232
+ registers: z2.array(z2.strictObject({
280
233
  name: iecName,
281
- offset: z3.number().int().nonnegative(),
282
- value: z3.string().regex(/^%QW\d+$/),
283
- write: z3.string().regex(/^%QX\d+\.[0-7]$/),
284
- status: z3.string().regex(/^%IB\d+$/),
285
- requests: z3.string().regex(/^%ID\d+$/)
234
+ offset: z2.number().int().nonnegative(),
235
+ value: z2.string().regex(/^%QW\d+$/),
236
+ write: z2.string().regex(/^%QX\d+\.[0-7]$/),
237
+ status: z2.string().regex(/^%IB\d+$/),
238
+ requests: z2.string().regex(/^%ID\d+$/)
286
239
  }))
287
240
  }).optional(),
288
- comments: z3.array(z3.strictObject({
241
+ comments: z2.array(z2.strictObject({
289
242
  address: channelAddress,
290
- text: z3.string().nonempty()
243
+ text: z2.string().nonempty()
291
244
  })).default([])
292
245
  })).nonempty(),
293
- mappings: z3.array(z3.strictObject({
246
+ mappings: z2.array(z2.strictObject({
294
247
  address: channelAddress,
295
- variable: z3.string().nonempty()
248
+ variable: z2.string().nonempty()
296
249
  })).default([])
297
250
  });
298
- var fourPartVersion = z3.string().regex(/^\d+\.\d+\.\d+\.\d+$/);
299
- var controllerSchema = z3.strictObject({
300
- type: z3.number().int().positive(),
301
- id: z3.string().regex(/^[0-9A-F]{4} [0-9A-F]{4}$/),
251
+ var fourPartVersion = z2.string().regex(/^\d+\.\d+\.\d+\.\d+$/);
252
+ var controllerSchema = z2.strictObject({
253
+ type: z2.number().int().positive(),
254
+ id: z2.string().regex(/^[0-9A-F]{4} [0-9A-F]{4}$/),
302
255
  version: fourPartVersion
303
256
  });
304
257
  var controllerTargetSchema = controllerSchema.pick({ version: true }).extend({
305
- target: z3.enum(["linux-sl", "virtual-linux-arm64-sl"])
258
+ target: z2.enum(["linux-sl", "virtual-linux-arm64-sl"])
306
259
  });
307
- var controllerDevices = {
308
- "linux-sl": { type: 4102, id: "0000 0005" },
309
- "virtual-linux-arm64-sl": { type: 4096, id: "0000 1008" }
310
- };
311
- var controllerDeviceNames = {
312
- "linux-sl": "CODESYS Control for Linux SL",
313
- "virtual-linux-arm64-sl": "CODESYS Virtual Control for Linux ARM64 SL"
260
+ var controllerTargets = {
261
+ "linux-sl": {
262
+ device: { type: 4102, id: "0000 0005" },
263
+ deviceName: "CODESYS Control for Linux SL"
264
+ },
265
+ "virtual-linux-arm64-sl": {
266
+ device: { type: 4096, id: "0000 1008" },
267
+ deviceName: "CODESYS Virtual Control for Linux ARM64 SL"
268
+ }
314
269
  };
315
- var configSchema = z3.strictObject({
316
- io: z3.record(z3.string(), directIoBindingSchema).optional(),
270
+ var configSchema = z2.strictObject({
271
+ io: z2.record(z2.string(), directIoBindingSchema).optional(),
317
272
  deviceTree: deviceTreeSchema.optional(),
318
273
  controller: controllerSchema.optional(),
319
- libraryReferences: z3.array(z3.string().nonempty()).default([]),
320
- libraries: z3.array(z3.strictObject({
321
- title: z3.string(),
322
- company: z3.string().optional(),
323
- version: z3.string().optional(),
324
- namespace: z3.string().optional(),
274
+ libraryReferences: z2.array(z2.string().nonempty()).default([]),
275
+ libraries: z2.array(z2.strictObject({
276
+ title: z2.string(),
277
+ company: z2.string().optional(),
278
+ version: z2.string().optional(),
279
+ namespace: z2.string().optional(),
325
280
  path: pathSchema,
326
281
  sha256: sha256Digest,
327
- url: z3.string().optional()
282
+ url: z2.string().optional()
328
283
  })).optional(),
329
- docker: z3.strictObject({
330
- cpuSet: z3.string().regex(/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/).optional()
284
+ docker: z2.strictObject({
285
+ cpuSet: z2.string().regex(/^\d+(?:-\d+)?(?:,\d+(?:-\d+)?)*$/).optional()
331
286
  }).optional(),
332
287
  template: pathSchema.optional(),
333
288
  sourceDir: pathSchema.default("src"),
334
289
  entry: pathSchema.default("src/Main.st"),
335
290
  outDir: pathSchema.default("build"),
336
- task: z3.string().nonempty().default("MainTask"),
291
+ task: z2.string().nonempty().default("MainTask"),
337
292
  tasks: cyclicTasksSchema.optional(),
338
- removeObjects: z3.array(z3.string().nonempty()).default([]),
339
- symbols: z3.boolean().default(false),
340
- bulkImport: z3.boolean().optional(),
341
- online: z3.strictObject({
293
+ removeObjects: z2.array(z2.string().nonempty()).default([]),
294
+ symbols: z2.boolean().default(false),
295
+ bulkImport: z2.boolean().optional(),
296
+ online: z2.strictObject({
342
297
  network: pathSchema.default("bridge"),
343
- gateway: z3.strictObject({
298
+ gateway: z2.strictObject({
344
299
  host: pathSchema,
345
- port: tcpPort.default(1217)
300
+ port: tcpPort.default(gatewayPort)
346
301
  }),
347
- device: z3.strictObject({
302
+ device: z2.strictObject({
348
303
  host: pathSchema,
349
- port: tcpPort.default(11740)
304
+ port: tcpPort.default(runtimePort)
350
305
  }),
351
- credentials: z3.strictObject({
306
+ credentials: z2.strictObject({
352
307
  usernameEnv: envName,
353
308
  passwordEnv: envName
354
309
  }).optional()
355
310
  }).optional(),
356
- timeouts: z3.strictObject({
311
+ timeouts: z2.strictObject({
357
312
  startup: positiveMilliseconds.default(codesysTimeouts.startup),
358
313
  build: positiveMilliseconds.default(codesysTimeouts.build),
359
314
  stop: positiveMilliseconds.default(codesysTimeouts.stop),
@@ -370,87 +325,179 @@ var releaseConfigSchema = configSchema.omit({
370
325
  online: true,
371
326
  bulkImport: true
372
327
  });
373
- var engineeringBuildSchema = configSchema.omit({
328
+ var compilerDecided = {
374
329
  sourceDir: true,
375
330
  entry: true,
376
331
  outDir: true,
377
332
  task: true,
378
333
  tasks: true
379
- });
380
- function engineeringBuildOptions(build) {
381
- const {
382
- sourceDir: _source,
383
- entry: _entry,
384
- outDir: _out,
385
- task: _task,
386
- tasks: _tasks,
387
- ...settings
388
- } = build;
334
+ };
335
+ var isCompilerDecided = (key) => Object.hasOwn(compilerDecided, key);
336
+ var engineeringBuildSchema = configSchema.omit(compilerDecided);
337
+ var engineeringBuildOptions = (build) => {
338
+ const settings = { ...build };
339
+ for (const key of Object.keys(settings)) {
340
+ if (isCompilerDecided(key)) {
341
+ delete settings[key];
342
+ }
343
+ }
389
344
  return settings;
390
- }
345
+ };
346
+
347
+ // packages/config/src/environment.ts
348
+ var secretLength = 512;
349
+ var secretValue = z3.string().nonempty("is empty").max(secretLength, `is longer than ${secretLength} characters`).regex(/^[^\r\n\0]*$/, "holds a line break or NUL");
350
+ var plainValue = z3.string().nonempty("is empty").regex(/^[^\0]*$/, "holds a NUL");
351
+ var secretPlaceholder = (name) => `${`{{tsplc-secret:${name}:`.padEnd(secretLength - 2, "-")}}}`;
352
+ var agentUrlEnv = "TSPLC_AGENT_URL";
353
+ var agentTokenEnv = "TSPLC_AGENT_TOKEN";
354
+ var selectedTarget = (config, { target, forAgent }) => {
355
+ const names = Object.keys(config.targets);
356
+ if (target !== undefined) {
357
+ const selected = config.targets[target];
358
+ if (!selected) {
359
+ throw new Error(`The config has no target ${target}; its targets are: ${names.join(", ") || "none"}.`);
360
+ }
361
+ return selected;
362
+ }
363
+ const targets = Object.values(config.targets);
364
+ if (targets.length <= 1) {
365
+ return targets[0];
366
+ }
367
+ if (!forAgent) {
368
+ return;
369
+ }
370
+ const withAgent = targets.filter(({ agent }) => agent);
371
+ if (withAgent.length === 1) {
372
+ return withAgent[0];
373
+ }
374
+ throw new Error(`Choose the target to deploy to with --target: ${names.join(", ")}.`);
375
+ };
376
+ var targetEnvironment = (config, options) => {
377
+ const target = selectedTarget(config, options);
378
+ return {
379
+ env: {
380
+ ...options.env,
381
+ ...target?.agent && { [agentUrlEnv]: target.agent.url },
382
+ ...target?.values,
383
+ ...options.forAgent && Object.fromEntries((config.secrets?.names ?? []).map((name) => [
384
+ name,
385
+ secretPlaceholder(name)
386
+ ]))
387
+ },
388
+ values: target?.values ?? {}
389
+ };
390
+ };
391
+ var projectEnvironment = (config, options) => targetEnvironment(config, options).env;
392
+ var plantVariablesSchema = z3.strictObject({
393
+ service: z3.string().nonempty(),
394
+ values: z3.record(envName, z3.string()),
395
+ secrets: z3.array(envName)
396
+ });
397
+ var isNonEmpty = (items) => items.length > 0;
398
+ var releaseEnvironment = (config, loaded, plant) => {
399
+ const names = [
400
+ ...new Set([...config.secrets?.names ?? [], ...plant.secrets])
401
+ ].filter((name) => !Object.hasOwn(plant.values, name));
402
+ return {
403
+ env: {
404
+ ...loaded.env,
405
+ ...plant.values,
406
+ ...Object.fromEntries(names.map((name) => [name, secretPlaceholder(name)]))
407
+ },
408
+ values: { ...loaded.values, ...plant.values },
409
+ secrets: isNonEmpty(names) ? { service: plant.service, names } : undefined
410
+ };
411
+ };
412
+ // packages/config/src/loader.ts
413
+ import { access } from "node:fs/promises";
414
+ import { dirname, resolve } from "node:path";
415
+ import { createJiti } from "jiti";
416
+
417
+ // packages/config/src/config-module.ts
418
+ import { z as z4 } from "zod";
419
+ var configModuleSchema = z4.object({
420
+ default: z4.unknown(),
421
+ config: z4.unknown()
422
+ });
423
+ var configExport = (module, path) => {
424
+ const exports = configModuleSchema.parse(module);
425
+ if (exports.default === undefined && exports.config === undefined) {
426
+ throw new Error(`${path} must export a default config`);
427
+ }
428
+ return exports.default ?? exports.config;
429
+ };
430
+
431
+ // packages/config/src/schema.ts
432
+ import { z as z6 } from "zod";
391
433
 
392
434
  // packages/config/src/project-files.ts
435
+ import { z as z5 } from "zod";
393
436
  var generatedDirectory = ".tsplc";
394
437
  var emittedStDirectory = `${generatedDirectory}/artifacts/st`;
438
+ var ioSymbolsSchema = z5.record(z5.string(), z5.string());
395
439
  var projectSnapshotFile = `${generatedDirectory}/project.json`;
396
440
 
397
441
  // packages/config/src/schema.ts
398
- var httpOptionsSchema = z4.strictObject({
399
- timeoutMs: z4.number().int().positive().max(60000).default(2000),
400
- credentials: z4.array(z4.strictObject({
442
+ var httpOptionsSchema = z6.strictObject({
443
+ timeoutMs: z6.number().int().positive().max(60000).default(2000),
444
+ credentials: z6.array(z6.strictObject({
401
445
  originEnv: envName,
402
446
  bearerTokenEnv: envName
403
447
  })).default([])
404
448
  }).prefault({});
405
- var ioBindingSchema = z4.union([
449
+ var ioBindingSchema = z6.union([
406
450
  directIoBindingSchema,
407
- z4.strictObject({
408
- device: z4.string().min(1),
409
- channel: z4.string().min(1),
451
+ z6.strictObject({
452
+ device: z6.string().nonempty(),
453
+ channel: z6.string().nonempty(),
410
454
  ...ioBindingOptions
411
455
  })
412
456
  ]);
413
- var assemblySchema = z4.strictObject({
414
- assembly: z4.number().int().nonnegative().optional(),
415
- size: z4.number().int().positive().optional(),
457
+ var assemblySchema = z6.strictObject({
458
+ assembly: z6.number().int().nonnegative().optional(),
459
+ size: z6.number().int().positive().optional(),
416
460
  address: assemblyAddress.optional()
417
461
  });
418
- var hardwareDeviceSchema = z4.strictObject({
419
- file: z4.string().min(1),
420
- connection: z4.string().min(1).optional(),
462
+ var hardwareDeviceSchema = z6.strictObject({
463
+ file: z6.string().nonempty(),
464
+ connection: z6.string().nonempty().optional(),
421
465
  inputs: assemblySchema.optional(),
422
466
  outputs: assemblySchema.optional(),
423
- modbus: z4.strictObject({
467
+ modbus: z6.strictObject({
424
468
  port: tcpPort.default(502),
425
- registers: z4.record(iecName, z4.number().int().min(0).max(65535))
469
+ registers: z6.record(iecName, z6.number().int().min(0).max(65535))
426
470
  }).optional(),
427
- statusSymbols: z4.record(z4.string(), z4.string()).optional(),
428
- network: z4.strictObject({
429
- address: z4.ipv4().optional(),
471
+ statusSymbols: z6.record(z6.string(), z6.string()).optional(),
472
+ network: z6.strictObject({
473
+ address: z6.ipv4().optional(),
430
474
  rpi: durationSchema.refine((rpi) => BigInt(rpi.nanoseconds) % 1000n === 0n, "An RPI must be a whole number of microseconds.").optional()
431
475
  }).optional()
432
476
  });
433
- var dependencySchema = z4.union([
477
+ var dependencySchema = z6.union([
434
478
  fourPartVersion,
435
- z4.strictObject({
479
+ z6.strictObject({
436
480
  version: fourPartVersion,
437
- company: z4.string().optional(),
438
- namespace: z4.string().optional()
481
+ company: z6.string().optional(),
482
+ namespace: z6.string().optional()
439
483
  }),
440
- z4.strictObject({ path: z4.string().min(1), namespace: z4.string().optional() })
484
+ z6.strictObject({
485
+ path: z6.string().nonempty(),
486
+ namespace: z6.string().optional()
487
+ })
441
488
  ]);
442
489
  var codesysTaskSchema = taskSchema.extend({
443
490
  name: iecName,
444
491
  priority: taskPriority
445
492
  });
446
- var monitorSchema = z4.strictObject({
447
- endpoint: z4.string().url(),
448
- namespaceUri: z4.string().optional(),
449
- symbols: z4.array(z4.string().min(1)).optional(),
450
- securityMode: z4.enum(["None", "Sign", "SignAndEncrypt"]).default("SignAndEncrypt"),
451
- securityPolicy: z4.enum(["None", "Basic256Sha256"]).optional(),
452
- certificateDirectory: z4.string().min(1).default(`${generatedDirectory}/opcua-pki`),
453
- username: z4.string().min(1).optional(),
493
+ var monitorSchema = z6.strictObject({
494
+ endpoint: z6.string().url(),
495
+ namespaceUri: z6.string().optional(),
496
+ symbols: z6.array(z6.string().nonempty()).optional(),
497
+ securityMode: z6.enum(["None", "Sign", "SignAndEncrypt"]).default("SignAndEncrypt"),
498
+ securityPolicy: z6.enum(["None", "Basic256Sha256"]).optional(),
499
+ certificateDirectory: z6.string().nonempty().default(`${generatedDirectory}/opcua-pki`),
500
+ username: z6.string().nonempty().optional(),
454
501
  passwordEnv: envName.optional()
455
502
  }).superRefine((monitor, context) => {
456
503
  if (monitor.securityPolicy && monitor.securityMode === "None" !== (monitor.securityPolicy === "None")) {
@@ -478,71 +525,70 @@ var monitorSchema = z4.strictObject({
478
525
  ...monitor,
479
526
  securityPolicy: monitor.securityPolicy ?? (monitor.securityMode === "None" ? "None" : "Basic256Sha256")
480
527
  }));
481
- var telemetrySchema = z4.strictObject({
482
- capacity: z4.number().int().min(4).max(4096).default(64),
483
- recordBytes: z4.number().int().min(128).max(1024).default(512)
528
+ var telemetrySchema = z6.strictObject({
529
+ capacity: z6.number().int().min(4).max(4096).default(64),
530
+ recordBytes: z6.number().int().min(128).max(1024).default(512)
484
531
  });
485
- var debugSchema = z4.strictObject({
486
- trace: z4.union([
487
- z4.literal(false),
488
- z4.strictObject({
489
- capacity: z4.number().int().min(16).max(4096).default(256),
490
- operands: z4.number().int().min(0).max(8).default(4)
532
+ var debugSchema = z6.strictObject({
533
+ trace: z6.union([
534
+ z6.literal(false),
535
+ z6.strictObject({
536
+ capacity: z6.number().int().min(16).max(4096).default(256),
537
+ operands: z6.number().int().min(0).max(8).default(4)
491
538
  })
492
539
  ]).default(false),
493
- writers: z4.union([
494
- z4.boolean(),
495
- z4.strictObject({ paths: z4.array(z4.string().nonempty()).nonempty() })
540
+ writers: z6.union([
541
+ z6.boolean(),
542
+ z6.strictObject({ paths: z6.array(z6.string().nonempty()).nonempty() })
496
543
  ]).default(true),
497
- jobs: z4.boolean().default(true),
498
- watch: z4.record(z4.string(), z4.array(z4.string().min(1))).default({}),
499
- requests: z4.strictObject({
500
- capacity: z4.number().int().min(1).max(1e5).default(1000),
501
- bodies: z4.boolean().default(false)
544
+ jobs: z6.boolean().default(true),
545
+ watch: z6.record(z6.string(), z6.array(z6.string().nonempty())).default({}),
546
+ requests: z6.strictObject({
547
+ capacity: z6.number().int().min(1).max(1e5).default(1000),
548
+ bodies: z6.boolean().default(false)
502
549
  }).prefault({})
503
550
  });
504
- var typegenSchema = z4.strictObject({
505
- types: z4.union([z4.string(), z4.array(z4.string())]).optional(),
506
- globals: z4.union([z4.string(), z4.array(z4.string())]).optional(),
507
- dir: z4.string().default("generated"),
508
- declarations: z4.boolean().default(true),
509
- ioTypes: z4.boolean().default(true)
551
+ var typegenSchema = z6.strictObject({
552
+ types: z6.union([z6.string(), z6.array(z6.string())]).optional(),
553
+ globals: z6.union([z6.string(), z6.array(z6.string())]).optional(),
554
+ dir: z6.string().default("generated"),
555
+ declarations: z6.boolean().default(true),
556
+ ioTypes: z6.boolean().default(true)
510
557
  });
511
- var buildTargetSchema = z4.enum(["production", "development"]);
512
- var publicationSchema = z4.strictObject({
513
- production: z4.array(z4.string().nonempty()),
514
- development: z4.array(z4.string().nonempty())
558
+ var buildTargetSchema = z6.enum(["production", "development"]);
559
+ var publicationSchema = z6.strictObject({
560
+ production: z6.array(z6.string().nonempty()),
561
+ development: z6.array(z6.string().nonempty())
515
562
  });
516
- var ioSymbolsSchema = z4.record(z4.string(), z4.string());
517
- var hmiTarget = z4.string().regex(/^\w+(\.\w+|\[\d+\])+$/);
518
- var hmiControlId = z4.string().nonempty();
519
- var hmiControlSchema = z4.discriminatedUnion("kind", [
520
- z4.strictObject({
521
- kind: z4.literal("button"),
563
+ var hmiTarget = z6.string().regex(/^\w+(\.\w+|\[\d+\])+$/);
564
+ var hmiControlId = z6.string().nonempty();
565
+ var hmiControlSchema = z6.discriminatedUnion("kind", [
566
+ z6.strictObject({
567
+ kind: z6.literal("button"),
522
568
  id: hmiControlId,
523
- label: z4.string().nonempty(),
569
+ label: z6.string().nonempty(),
524
570
  target: hmiTarget,
525
- tone: z4.enum(["start", "stop"]).optional(),
526
- confirm: z4.boolean().optional()
571
+ tone: z6.enum(["start", "stop"]).optional(),
572
+ confirm: z6.boolean().optional()
527
573
  }),
528
- z4.strictObject({
529
- kind: z4.literal("toggle"),
574
+ z6.strictObject({
575
+ kind: z6.literal("toggle"),
530
576
  id: hmiControlId,
531
- label: z4.string().nonempty(),
577
+ label: z6.string().nonempty(),
532
578
  target: hmiTarget
533
579
  }),
534
- z4.strictObject({
535
- kind: z4.literal("slider"),
580
+ z6.strictObject({
581
+ kind: z6.literal("slider"),
536
582
  id: hmiControlId,
537
- label: z4.string().nonempty(),
583
+ label: z6.string().nonempty(),
538
584
  target: hmiTarget,
539
- min: z4.number().int(),
540
- max: z4.number().int()
585
+ min: z6.number().int(),
586
+ max: z6.number().int()
541
587
  })
542
588
  ]);
543
- var hmiSchema = z4.strictObject({
544
- title: z4.string().nonempty(),
545
- controls: z4.array(hmiControlSchema).default([]).superRefine((controls, context) => {
589
+ var hmiSchema = z6.strictObject({
590
+ title: z6.string().nonempty(),
591
+ controls: z6.array(hmiControlSchema).default([]).superRefine((controls, context) => {
546
592
  const seen = new Set;
547
593
  controls.forEach((control, index) => {
548
594
  if (seen.has(control.id)) {
@@ -555,22 +601,22 @@ var hmiSchema = z4.strictObject({
555
601
  seen.add(control.id);
556
602
  });
557
603
  }),
558
- conveyors: z4.array(z4.strictObject({
559
- label: z4.string().nonempty(),
560
- positions: z4.number().int().positive(),
561
- diverters: z4.array(z4.number().int().nonnegative()).default([])
604
+ conveyors: z6.array(z6.strictObject({
605
+ label: z6.string().nonempty(),
606
+ positions: z6.number().int().positive(),
607
+ diverters: z6.array(z6.number().int().nonnegative()).default([])
562
608
  })).default([])
563
609
  });
564
- var tsplcConfigSchema = z4.strictObject({
565
- name: z4.string().default("Application"),
566
- backend: z4.literal("codesys"),
610
+ var tsplcConfigSchema = z6.strictObject({
611
+ name: z6.string().default("Application"),
612
+ backend: z6.literal("codesys"),
567
613
  publish: publicationSchema.optional(),
568
- server: z4.strictObject({
569
- baseUrlEnv: z4.string().optional(),
570
- transport: z4.enum(["http", "opcua"]).default("http"),
571
- runtime: z4.strictObject({
572
- entry: z4.string(),
573
- target: z4.enum([
614
+ server: z6.strictObject({
615
+ baseUrlEnv: envName.optional(),
616
+ transport: z6.enum(["http", "opcua"]).default("http"),
617
+ runtime: z6.strictObject({
618
+ entry: z6.string(),
619
+ target: z6.enum([
574
620
  "bun-linux-x64",
575
621
  "bun-linux-arm64",
576
622
  "bun-darwin-x64",
@@ -579,49 +625,63 @@ var tsplcConfigSchema = z4.strictObject({
579
625
  ]).optional()
580
626
  }).optional()
581
627
  }).optional(),
582
- compiler: z4.strictObject({
583
- tsconfig: z4.string().default("tsconfig.json"),
584
- programs: z4.record(z4.string(), z4.strictObject({ module: z4.string(), export: z4.string() }))
628
+ compiler: z6.strictObject({
629
+ tsconfig: z6.string().default("tsconfig.json"),
630
+ programs: z6.record(z6.string(), sourceExportSchema)
585
631
  }).optional(),
586
- tasks: z4.array(codesysTaskSchema).nonempty().optional(),
632
+ tasks: z6.array(codesysTaskSchema).nonempty().optional(),
587
633
  build: configSchema.extend({ task: configSchema.shape.task.unwrap().optional() }).optional(),
588
- codesys: z4.strictObject({
634
+ codesys: z6.strictObject({
589
635
  http: httpOptionsSchema.optional(),
590
- programNames: z4.record(z4.string(), z4.string()).optional(),
591
- deviceTree: z4.strictObject({ ethernet: ethernetSchema.optional() }).optional(),
592
- controllers: z4.strictObject({
636
+ programNames: z6.record(z6.string(), z6.string()).optional(),
637
+ deviceTree: z6.strictObject({ ethernet: ethernetSchema.optional() }).optional(),
638
+ controllers: z6.strictObject({
593
639
  production: controllerTargetSchema.optional(),
594
640
  development: controllerTargetSchema.optional()
595
641
  }).optional()
596
642
  }).optional(),
597
- eds: z4.union([z4.string(), z4.array(z4.string())]).default("eds"),
598
- devices: z4.record(z4.string(), hardwareDeviceSchema).default({}),
599
- io: z4.record(z4.string(), ioBindingSchema).default({}),
600
- dependencies: z4.record(z4.string(), dependencySchema).default({}),
643
+ eds: z6.union([z6.string(), z6.array(z6.string())]).default("eds"),
644
+ devices: z6.record(z6.string(), hardwareDeviceSchema).default({}),
645
+ io: z6.record(z6.string(), ioBindingSchema).default({}),
646
+ dependencies: z6.record(z6.string(), dependencySchema).default({}),
601
647
  typegen: typegenSchema.optional(),
602
648
  monitor: monitorSchema.optional(),
603
649
  hmi: hmiSchema.optional(),
604
650
  telemetry: telemetrySchema.optional(),
605
651
  debug: debugSchema.optional(),
606
- targets: z4.record(z4.string().nonempty(), z4.strictObject({
607
- values: z4.record(envName, z4.string()).default({}),
608
- agent: z4.strictObject({ url: z4.url() }).optional()
652
+ targets: z6.record(z6.string().nonempty(), z6.strictObject({
653
+ values: z6.record(envName, z6.string()).default({}),
654
+ agent: z6.strictObject({ url: z6.url() }).optional()
609
655
  })).default({}),
610
- secrets: z4.strictObject({
611
- service: z4.string().nonempty(),
612
- names: z4.array(envName).nonempty()
656
+ secrets: z6.strictObject({
657
+ service: z6.string().nonempty(),
658
+ names: z6.array(envName).nonempty()
613
659
  }).optional()
660
+ }).superRefine((config, context) => {
661
+ if (config.compiler && !config.tasks) {
662
+ context.addIssue({
663
+ code: "custom",
664
+ path: ["tasks"],
665
+ message: "TypeScript programs require a tasks configuration."
666
+ });
667
+ }
614
668
  });
615
669
  var buildTargetFor = (command) => ["run", "download", "online-change", "inspect"].includes(command) ? "development" : "production";
616
670
  var controllerFor = (config, command) => {
617
671
  const controller = config.codesys?.controllers?.[buildTargetFor(command)];
618
672
  return controller && {
619
- ...controllerDevices[controller.target],
673
+ ...controllerTargets[controller.target].device,
620
674
  version: controller.version
621
675
  };
622
676
  };
623
- var controllerDeviceName = (config, command) => controllerDeviceNames[config.codesys?.controllers?.[buildTargetFor(command)]?.target ?? "linux-sl"];
677
+ var controllerDeviceName = (config, command) => controllerTargets[config.codesys?.controllers?.[buildTargetFor(command)]?.target ?? "linux-sl"].deviceName;
624
678
  var serverTokenEnv = (config) => config.codesys?.http?.credentials.find(({ originEnv }) => originEnv === config.server?.baseUrlEnv)?.bearerTokenEnv;
679
+ var serverBaseUrl = (config, env) => config.server?.baseUrlEnv === undefined ? undefined : env[config.server.baseUrlEnv];
680
+ var typegenSettings = (config) => config.typegen ?? typegenSchema.parse({});
681
+ var projectSlugs = {
682
+ kebab: (name) => name.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, "$1$3-$2$4").replace(/[^A-Za-z0-9]+/g, "-").replace(/^-|-$/g, "").toLowerCase(),
683
+ runtime: (name) => name.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase().replace(/[^a-z0-9_-]+/g, "-")
684
+ };
625
685
  var simulationConfig = (config) => ({
626
686
  ...config,
627
687
  eds: [],
@@ -652,14 +712,15 @@ function rawBuildConfig(config) {
652
712
  }
653
713
  return {
654
714
  ...config.build,
655
- tasks: cyclicTasksSchema.parse(config.tasks.map((task) => ({
656
- name: task.name,
657
- intervalNanoseconds: task.schedule.interval.nanoseconds,
658
- priority: task.priority,
659
- programs: task.programs
660
- })))
715
+ tasks: cyclicTasksSchema.parse(taskPlan(config.tasks))
661
716
  };
662
717
  }
718
+ var taskPlan = (tasks) => tasks.map((task) => ({
719
+ name: task.name,
720
+ intervalNanoseconds: task.schedule.interval.nanoseconds,
721
+ priority: task.priority,
722
+ programs: task.programs
723
+ }));
663
724
  function compilerConfig(config, io, buildTarget = "production") {
664
725
  if (!config.compiler || !config.tasks) {
665
726
  throw new Error("This project uses raw Structured Text; no TypeScript compiler is configured.");
@@ -704,37 +765,30 @@ function compilerConfig(config, io, buildTarget = "production") {
704
765
  }
705
766
  function mappedChannel(config, name, binding) {
706
767
  const source = config.io[name];
707
- return config.codesys?.deviceTree !== undefined && source !== undefined && "device" in source && !binding.inverted && !binding.shared && /^%[IQ][XB]/.test(binding.address) && !/^ARRAY/i.test(binding.type ?? "");
768
+ return config.codesys?.deviceTree !== undefined && source !== undefined && "device" in source && !binding.inverted && !binding.shared && channelAddress.safeParse(binding.address).success && !/^ARRAY/i.test(binding.type ?? "");
708
769
  }
709
770
 
710
771
  // packages/config/src/loader.ts
711
- async function loadTsplcConfig(file = "tsplc.config.ts", environment = {
712
- env: process.env,
713
- target: undefined,
714
- forAgent: false
715
- }) {
772
+ async function loadTsplcConfig(file, environment) {
716
773
  const configFile = resolve(file);
717
- await readFile(configFile);
774
+ await access(configFile);
718
775
  const jiti = createJiti(import.meta.url, {
719
776
  moduleCache: false,
720
777
  fsCache: false,
721
778
  interopDefault: false,
722
779
  tryNative: false
723
780
  });
724
- const module = await jiti.import(configFile);
725
- const config = tsplcConfigSchema.parse(module.default ?? module.config);
726
- if (config.compiler && !config.tasks) {
727
- throw new Error("TypeScript programs require a tasks configuration.");
728
- }
781
+ const config = tsplcConfigSchema.parse(configExport(await jiti.import(configFile), configFile));
729
782
  return {
730
783
  configFile,
731
784
  root: dirname(configFile),
732
785
  config,
733
- env: projectEnvironment(config, environment),
734
- values: targetValues(config, environment)
786
+ ...targetEnvironment(config, environment)
735
787
  };
736
788
  }
737
789
  export {
790
+ agentTokenEnv,
791
+ agentUrlEnv,
738
792
  buildTargetFor,
739
793
  buildTargetSchema,
740
794
  compilerConfig,
@@ -748,20 +802,26 @@ export {
748
802
  loadTsplcConfig,
749
803
  ms,
750
804
  ns,
805
+ plainValue,
806
+ plantVariablesSchema,
751
807
  projectEnvironment,
808
+ projectSlugs,
752
809
  publicationSchema,
753
810
  rawBuildConfig,
754
811
  releaseEnvironment,
755
812
  seconds,
756
813
  secretPlaceholder,
757
814
  secretValue,
815
+ serverBaseUrl,
758
816
  serverTokenEnv,
759
817
  simulationConfig,
818
+ taskPlan,
760
819
  telemetrySchema,
761
820
  tsplcConfigSchema,
762
821
  typegenSchema,
822
+ typegenSettings,
763
823
  validateConfig
764
824
  };
765
825
 
766
- //# debugId=34F0A86B085AEEAF64756E2164756E21
826
+ //# debugId=476DC5A9333B317564756E2164756E21
767
827
  //# sourceMappingURL=index.js.map