@tsplc/build 0.4.3 → 0.5.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.
@@ -1,7 +1,17 @@
1
- import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
1
+ import { createHash } from "node:crypto";
2
+ import {
3
+ cp,
4
+ mkdir,
5
+ mkdtemp,
6
+ readdir,
7
+ readFile,
8
+ rm,
9
+ stat,
10
+ writeFile,
11
+ } from "node:fs/promises";
2
12
  import { createRequire } from "node:module";
3
13
  import { tmpdir } from "node:os";
4
- import { basename, dirname, resolve } from "node:path";
14
+ import { basename, dirname, posix, relative, resolve, sep } from "node:path";
5
15
  import { z } from "zod";
6
16
  import { packageDirectory } from "./package-path.ts";
7
17
 
@@ -9,6 +19,7 @@ const includeSource = (source: string) => {
9
19
  const name = basename(source);
10
20
  return (
11
21
  name !== "__pycache__" &&
22
+ name !== ".DS_Store" &&
12
23
  !name.endsWith(".pyc") &&
13
24
  !name.endsWith(".test.ts") &&
14
25
  !name.endsWith(".fixtures.ts") &&
@@ -16,20 +27,121 @@ const includeSource = (source: string) => {
16
27
  );
17
28
  };
18
29
 
19
- /** The workspace packages container code imports, each copied with the files Bun runs it from. */
30
+ /**
31
+ * The workspace packages container code imports, each copied with the files Bun runs it from,
32
+ * to `directory` in the context and `image` in the image.
33
+ */
20
34
  const containerPackages = [
21
35
  {
22
36
  entry: "@tsplc/config/build",
23
37
  directory: "shared-config",
38
+ image: "/opt/tsplc-config",
24
39
  files: ["src", "templates", "package.json"],
25
40
  },
26
41
  {
27
42
  entry: "@tsplc/iec",
28
43
  directory: "shared-iec",
44
+ image: "/opt/tsplc-iec",
29
45
  files: ["src", "package.json"],
30
46
  },
31
47
  ];
32
48
 
49
+ /** Where the image keeps this package. */
50
+ const imagePackage = "/opt/codesys-build";
51
+ /**
52
+ * This package's files that the image runs and a container may take from the installed package
53
+ * instead: everything the runner imports and the CODESYS scripts. The entrypoint stays the image's.
54
+ */
55
+ const packageCode = ["src", "python", "docker/runner.ts", "docker/config.ts"];
56
+
57
+ const packageRoot = (entry: string) =>
58
+ resolve(dirname(createRequire(import.meta.url).resolve(entry)), "..");
59
+
60
+ /** A host file or directory and the path in the image it replaces. */
61
+ export interface ContainerMount {
62
+ source: string;
63
+ target: string;
64
+ }
65
+
66
+ /**
67
+ * The code a builder container runs, as this installation has it, and where the image keeps its
68
+ * own copy. Mounted over the image's, it makes a container run this installation's tsPLC whatever
69
+ * tsPLC built the image, so only a change of the image's recipe needs a new image.
70
+ */
71
+ export const containerCode = (): ContainerMount[] => [
72
+ ...packageCode.map((path) => ({
73
+ source: resolve(packageDirectory, path),
74
+ target: posix.join(imagePackage, path),
75
+ })),
76
+ ...containerPackages.flatMap(({ entry, image, files }) =>
77
+ files.map((file) => ({
78
+ source: resolve(packageRoot(entry), file),
79
+ target: posix.join(image, file),
80
+ })),
81
+ ),
82
+ ];
83
+
84
+ /** Every file under `path`, or `path` itself, that `include` keeps, by its path relative to `root`. */
85
+ const listFiles = async (
86
+ root: string,
87
+ path: string,
88
+ include: (relativePath: string) => boolean,
89
+ ): Promise<string[]> => {
90
+ const name = relative(root, path).split(sep).join("/");
91
+ if (!include(name)) {
92
+ return [];
93
+ }
94
+ if (!(await stat(path)).isDirectory()) {
95
+ return [name];
96
+ }
97
+ const entries = await readdir(path);
98
+ return (
99
+ await Promise.all(
100
+ entries.map((entry) => listFiles(root, resolve(path, entry), include)),
101
+ )
102
+ ).flat();
103
+ };
104
+
105
+ /** A digest of named texts and files, which changes when a name or a file's content does. */
106
+ const digestFiles = async (
107
+ files: { name: string; path: string }[],
108
+ texts: Record<string, string>,
109
+ ) => {
110
+ const hash = createHash("sha256");
111
+ for (const [name, text] of Object.entries(texts)) {
112
+ hash.update(`${name}\0${text}\0`);
113
+ }
114
+ for (const file of [...files].sort((a, b) => a.name.localeCompare(b.name))) {
115
+ hash.update(`${file.name}\0`);
116
+ hash.update(await readFile(file.path));
117
+ hash.update("\0");
118
+ }
119
+ return hash.digest("hex");
120
+ };
121
+
122
+ /**
123
+ * A digest of the code `containerCode` mounts, which a long-running container is labelled with so
124
+ * that one running other code is replaced.
125
+ */
126
+ export const containerCodeDigest = async () =>
127
+ digestFiles(
128
+ (
129
+ await Promise.all(
130
+ containerCode().map(async ({ source, target }) =>
131
+ (
132
+ await listFiles(dirname(source), source, (path) =>
133
+ includeSource(basename(path)),
134
+ )
135
+ ).map((name) => ({
136
+ name: posix.join(posix.dirname(target), name),
137
+ path: resolve(dirname(source), name),
138
+ })),
139
+ ),
140
+ )
141
+ ).flat(),
142
+ {},
143
+ );
144
+
33
145
  const manifestDependencies = z.object({
34
146
  name: z.string(),
35
147
  dependencies: z.record(z.string(), z.string()).default({}),
@@ -67,6 +179,47 @@ const readManifest = async (directory: string) =>
67
179
  JSON.parse(await readFile(resolve(directory, "package.json"), "utf8")),
68
180
  );
69
181
 
182
+ /** The manifest of the third-party packages the image installs, as its recipe writes it. */
183
+ export const containerManifest = async () => {
184
+ const manifests = [await readManifest(packageDirectory)];
185
+ for (const { entry } of containerPackages) {
186
+ manifests.push(await readManifest(packageRoot(entry)));
187
+ }
188
+ return { type: "module", dependencies: containerDependencies(manifests) };
189
+ };
190
+
191
+ /**
192
+ * The files of the image's recipe that its containers can't take from the installed package: the
193
+ * Dockerfile, the entrypoint and the installation's scripts and data. Tests and checks of the
194
+ * installation's own tools stay out, as the published package leaves them out.
195
+ */
196
+ const recipeFile = (path: string) =>
197
+ path === "docker" ||
198
+ path === "docker/Dockerfile" ||
199
+ path === "docker/entrypoint.sh" ||
200
+ ((path === "docker/install" || path.startsWith("docker/install/")) &&
201
+ includeSource(basename(path)) &&
202
+ !path.split("/").includes("tests") &&
203
+ path !== "docker/install/wine-signal/check.sh");
204
+
205
+ /**
206
+ * The builder image's recipe: what it installs and how. An image built from another recipe has
207
+ * another vendor installation or other third-party packages, so its containers can't run this
208
+ * installation's code, while one built from this recipe runs any tsPLC with this recipe.
209
+ */
210
+ export const builderRecipe = async () =>
211
+ digestFiles(
212
+ (await recipeFiles()).map((name) => ({
213
+ name,
214
+ path: resolve(packageDirectory, name),
215
+ })),
216
+ { manifest: JSON.stringify(await containerManifest()) },
217
+ );
218
+
219
+ /** The package's files `builderRecipe` covers, beside the third-party manifest. */
220
+ export const recipeFiles = () =>
221
+ listFiles(packageDirectory, resolve(packageDirectory, "docker"), recipeFile);
222
+
70
223
  export async function prepareDockerContext() {
71
224
  const context = await mkdtemp(resolve(tmpdir(), "tsplc-docker-"));
72
225
  try {
@@ -80,13 +233,8 @@ export async function prepareDockerContext() {
80
233
  },
81
234
  );
82
235
  }
83
- const manifests = [await readManifest(packageDirectory)];
84
236
  for (const { entry, directory, files } of containerPackages) {
85
- const root = resolve(
86
- dirname(createRequire(import.meta.url).resolve(entry)),
87
- "..",
88
- );
89
- manifests.push(await readManifest(root));
237
+ const root = packageRoot(entry);
90
238
  await mkdir(resolve(context, directory));
91
239
  for (const file of files) {
92
240
  await cp(resolve(root, file), resolve(context, directory, file), {
@@ -97,10 +245,7 @@ export async function prepareDockerContext() {
97
245
  }
98
246
  await writeFile(
99
247
  resolve(context, "package.json"),
100
- JSON.stringify({
101
- type: "module",
102
- dependencies: containerDependencies(manifests),
103
- }),
248
+ JSON.stringify(await containerManifest()),
104
249
  );
105
250
  return context;
106
251
  } catch (cause) {
package/src/docker-run.ts CHANGED
@@ -4,6 +4,7 @@ import { copyFile, cp, mkdir, readFile, writeFile } from "node:fs/promises";
4
4
  import { basename, posix, relative, resolve, sep } from "node:path";
5
5
  import { promisify } from "node:util";
6
6
  import type { ResolvedConfig } from "@tsplc/config/build";
7
+ import { containerCode } from "./docker-context.ts";
7
8
 
8
9
  const execute = promisify(execFile);
9
10
 
@@ -184,7 +185,8 @@ export const writeOperationRequest = async (
184
185
  * Write the builder container's request and return the `docker run` options that precede
185
186
  * the image; the caller chooses `--rm` or `--detach`. The request names only container paths;
186
187
  * host paths enter through these mounts, and host-only Docker, CODESYS and runtime settings
187
- * stay outside.
188
+ * stay outside. The container runs this installation's code and CODESYS scripts, mounted over
189
+ * the image's copy, so a tsPLC update needs no new image unless the image's recipe changed.
188
190
  */
189
191
  export const prepareContainerRun = async (
190
192
  config: ResolvedConfig,
@@ -221,5 +223,9 @@ export const prepareContainerRun = async (
221
223
  bindMount(config.template, "/template.project", true),
222
224
  "--mount",
223
225
  bindMount(config.outDir, "/output"),
226
+ ...containerCode().flatMap(({ source, target }) => [
227
+ "--mount",
228
+ bindMount(source, target, true),
229
+ ]),
224
230
  ];
225
231
  };
package/src/images.ts CHANGED
@@ -2,7 +2,7 @@ import { copyFile, cp, mkdir, mkdtemp, rm } from "node:fs/promises";
2
2
  import { tmpdir } from "node:os";
3
3
  import { resolve } from "node:path";
4
4
  import { dockerImage } from "@tsplc/config/build";
5
- import { prepareDockerContext } from "./docker-context.ts";
5
+ import { builderRecipe, prepareDockerContext } from "./docker-context.ts";
6
6
  import { packageDirectory } from "./package-path.ts";
7
7
 
8
8
  export const builderImage = dockerImage;
@@ -30,8 +30,11 @@ export const setupPlatformFor = (server: string): SetupPlatform | null => {
30
30
  return null;
31
31
  };
32
32
 
33
+ /** The label an image built by `buildBuilderImage` carries its `builderRecipe` in. */
34
+ export const recipeLabel = "tsplc.recipe";
35
+
33
36
  /**
34
- * Builds the builder image from the full recipe. `installer` is a local CODESYS installer,
37
+ * Builds the builder image from the full recipe, labelled with it. `installer` is a local CODESYS installer,
35
38
  * or null to download the official one; `winetricksCache` seeds the prerequisite downloads.
36
39
  * `docker` runs one Docker client command, so each caller keeps its own terminal handling.
37
40
  */
@@ -71,6 +74,8 @@ export async function buildBuilderImage(options: {
71
74
  `SETUP_PLATFORM=${options.setupPlatform}`,
72
75
  "--build-arg",
73
76
  `INSTALLER_SOURCE=${options.installer ? "installer-local" : "installer-download"}`,
77
+ "--label",
78
+ `${recipeLabel}=${await builderRecipe()}`,
74
79
  "--progress",
75
80
  "plain",
76
81
  "--build-context",
@@ -89,6 +94,22 @@ export async function buildBuilderImage(options: {
89
94
  }
90
95
  }
91
96
 
97
+ /** Builds the local CODESYS Control for Linux SL runtime, the device a production build targets. */
98
+ export const buildRuntimeImage = (options: {
99
+ tag: string;
100
+ docker: (args: string[]) => Promise<void>;
101
+ }) =>
102
+ options.docker([
103
+ "build",
104
+ "--platform",
105
+ "linux/amd64",
106
+ "--progress",
107
+ "plain",
108
+ "-t",
109
+ options.tag,
110
+ resolve(packageDirectory, "docker/control-linux-sl"),
111
+ ]);
112
+
92
113
  export const buildGatewayImage = (options: {
93
114
  tag: string;
94
115
  docker: (args: string[]) => Promise<void>;
package/src/index.ts CHANGED
@@ -9,6 +9,11 @@ export {
9
9
  } from "@tsplc/config/build";
10
10
  export { readBuild } from "./artifacts.ts";
11
11
  export { buildProject } from "./build";
12
+ export {
13
+ type BuilderImageStatus,
14
+ builderImageStatus,
15
+ setupReason,
16
+ } from "./builder-image.ts";
12
17
  export {
13
18
  type ControllerLogin,
14
19
  findControllerLogin,