@typesol/cli 0.44.1 → 0.45.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,442 @@
1
+ // `build --docker` and `verify --docker`: programs built inside the pinned image of docker/Dockerfile, so that anyone
2
+ // can rebuild a deployed program from its source in the same environment and compare the bytes. The image is built on
3
+ // the user's machine from the Dockerfile's pinned inputs (base images by digest, release files by sha256, the TypeSOL
4
+ // tarball by its release record); no image is pulled except the pinned base images, and none is pushed anywhere.
5
+ //
6
+ // One platform, linux/amd64, so that the whole environment is one recipe. From 0.45.0 on a program builds to the same
7
+ // bytes on macOS arm64, Linux arm64 and Linux x86_64 as well (measured over 76 programs for SBPF v0 and 14 for v1 and
8
+ // v2, docs/stability.md); TypeSOL 0.44.1 and earlier linked platform-tools' compiler-builtins, whose layout differed by
9
+ // host package, so for those versions the container's platform decides the bytes of programs with 128-bit or signed
10
+ // division.
11
+ import { spawnSync } from "node:child_process";
12
+ import { createHash } from "node:crypto";
13
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
14
+ import os from "node:os";
15
+ import path from "node:path";
16
+ import { fileURLToPath } from "node:url";
17
+ export const DOCKER_PLATFORM = "linux/amd64";
18
+ const PACKAGE_ROOT = fileURLToPath(new URL("../../", import.meta.url));
19
+ export const DOCKERFILE = path.join(PACKAGE_ROOT, "docker/Dockerfile");
20
+ /** The release records the package ships (releases/<version>.json): the TypeSOL versions an image can install. */
21
+ export const RELEASES_DIR = path.join(PACKAGE_ROOT, "releases");
22
+ /**
23
+ * The dependency locks the package ships (docker/deps/<version>.lock.json): for each TypeSOL version, the npm lockfile
24
+ * of its runtime dependencies, which the image installs with `npm ci` (every package checked against its integrity).
25
+ * The lock of version N ships in package N (it does not contain N's own tarball); a version newer than the package
26
+ * carries its own, checked with the rest of its tarball against the release record.
27
+ */
28
+ export const DEPS_DIR = path.join(PACKAGE_ROOT, "docker/deps");
29
+ const IMAGE = "typesol-build";
30
+ const VERSION = /^\d+\.\d+\.\d+(-[\w.]+)?$/;
31
+ /** Docker is missing or failed: the message says what to do. Never answered by building locally instead. */
32
+ export class DockerError extends Error {
33
+ }
34
+ const sha256 = (data) => createHash("sha256").update(data).digest("hex");
35
+ const firstLine = (s) => (s ?? "").trim().split("\n")[0] ?? "";
36
+ /** Whether `docker` is there and its daemon answers. */
37
+ export function dockerStatus() {
38
+ const r = spawnSync("docker", ["version", "--format", "{{.Server.Version}} {{.Server.Os}}/{{.Server.Arch}}"], { encoding: "utf8", timeout: 20_000 });
39
+ if (r.error?.code === "ENOENT")
40
+ return { ok: false, reason: "docker is not installed (not on PATH)", fix: "install Docker: https://docs.docker.com/get-started/get-docker/" };
41
+ const out = r.stdout?.trim() ?? "";
42
+ if (r.error || r.status !== 0 || !/^\S+ \S+\/\S+$/.test(out))
43
+ return {
44
+ ok: false,
45
+ reason: `the Docker daemon is not running or not reachable${r.error ? ` (${r.error.message})` : firstLine(r.stderr) ? ` (${firstLine(r.stderr)})` : ""}`,
46
+ fix: "start Docker Desktop, or the docker service (sudo systemctl start docker)",
47
+ };
48
+ const [version, platform] = out.split(" ");
49
+ return { ok: true, version, platform };
50
+ }
51
+ /** Throws a DockerError with the fix when Docker cannot run builds. */
52
+ export function needDocker() {
53
+ const s = dockerStatus();
54
+ if (!s.ok)
55
+ throw new DockerError(`--docker needs Docker: ${s.reason}. ${s.fix}. Nothing was built.`);
56
+ }
57
+ /** The pinned inputs a Dockerfile names: its base images (FROM …@sha256:…) and its checksummed downloads (ADD --checksum). */
58
+ export function dockerfileInputs(text) {
59
+ const base = [...new Set([...text.matchAll(/^FROM\s+(\S+@sha256:[0-9a-f]{64})/gm)].map((m) => m[1]))];
60
+ const downloads = [...text.matchAll(/^ADD\s+--checksum=sha256:([0-9a-f]{64})\s+(?:\\\n\s*)?(https:\/\/\S+)/gm)].map((m) => ({ url: m[2], sha256: m[1] }));
61
+ return { base, downloads };
62
+ }
63
+ /** The versions whose records ship with this package, oldest first. */
64
+ export function recordedVersions(dir = RELEASES_DIR) {
65
+ let names;
66
+ try {
67
+ names = readdirSync(dir);
68
+ }
69
+ catch {
70
+ return [];
71
+ }
72
+ const parts = (v) => v.split(/[.-]/).map((p) => (/^\d+$/.test(p) ? Number(p) : p));
73
+ return names
74
+ .flatMap((f) => /^(\d+\.\d+\.\d+(?:-[\w.]+)?)\.json$/.exec(f)?.[1] ?? [])
75
+ .sort((a, b) => {
76
+ const [x, y] = [parts(a), parts(b)];
77
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
78
+ if (x[i] !== y[i])
79
+ return (x[i] ?? -1) < (y[i] ?? -1) ? -1 : 1;
80
+ return 0;
81
+ });
82
+ }
83
+ /**
84
+ * Where a release's record is fetched from when this package does not ship it: the repository's main branch, where it
85
+ * is committed after the release is published (the package of version N cannot contain releases/N.json).
86
+ */
87
+ export const RELEASES_URL = "https://raw.githubusercontent.com/typesol-lang/typesol/main/releases";
88
+ function parseRecord(text, version, where) {
89
+ let r;
90
+ try {
91
+ r = JSON.parse(text);
92
+ }
93
+ catch (e) {
94
+ throw new DockerError(`${where}: not valid JSON (${e.message})`);
95
+ }
96
+ if (r?.version !== version ||
97
+ typeof r.commit !== "string" ||
98
+ !r.commit ||
99
+ typeof r.tarball?.shasum !== "string" ||
100
+ typeof r.tarball.integrity !== "string" ||
101
+ !Array.isArray(r.files))
102
+ throw new DockerError(`${where} is not the release record of TypeSOL ${version} (version, commit, tarball.shasum, tarball.integrity and files are required)`);
103
+ return r;
104
+ }
105
+ /** Whether `version` comes before 0.43.0, the first release with a record. */
106
+ function beforeRecords(version) {
107
+ const [major, minor] = version.split(".").map(Number);
108
+ return major === 0 && minor < 43;
109
+ }
110
+ /**
111
+ * The release record of `version`: `file` (`--release-record`, e.g. releases/<version>.json from the repository), or
112
+ * the one this package ships. A version without one is refused: its tarball could not be checked. (findReleaseRecord
113
+ * also fetches a newer release's record from the repository.)
114
+ */
115
+ export function releaseRecord(version, file, dir = RELEASES_DIR) {
116
+ const at = file ?? path.join(dir, `${version}.json`);
117
+ if (!existsSync(at)) {
118
+ const known = recordedVersions(dir);
119
+ throw new DockerError(file
120
+ ? `--release-record ${file} does not exist`
121
+ : `no release record for TypeSOL ${version}: --docker installs only versions whose npm tarball is recorded in releases/<version>.json, ` +
122
+ `so that the image's compiler is checked against it. This package has the records of ${known.join(", ") || "no version"}. ` +
123
+ `A release's record is committed after it is published (releases/${version}.json on the repository's main branch, from 0.43.0 on): ` +
124
+ `pass it with --release-record <file>, use a later @typesol/cli, which ships it, or pick a recorded version with --typesol-version. ` +
125
+ `Versions before 0.43.0 have no record and cannot be built in the container.`);
126
+ }
127
+ const bytes = readFileSync(at);
128
+ const text = bytes.toString("utf8");
129
+ const record = parseRecord(text, version, at);
130
+ return {
131
+ record,
132
+ bytes,
133
+ source: file ? { kind: "file", location: file, sha256: sha256(bytes) } : { kind: "package", location: `releases/${version}.json`, sha256: sha256(bytes) },
134
+ };
135
+ }
136
+ /**
137
+ * The release record of `version` for a container build: `file` when given, else the package's, else (a release newer
138
+ * than this package, whose record was committed after the package was published) releases/<version>.json fetched from
139
+ * the repository's main branch over HTTPS. The check then rests on two independent sources agreeing: the tarball npm
140
+ * serves and the record the repository holds. Offline, or when the repository has no record for the version, it is an
141
+ * error that names --release-record. Where the record came from goes to `log` and into the build's manifest.
142
+ */
143
+ export async function findReleaseRecord(version, opts = {}) {
144
+ const dir = opts.dir ?? RELEASES_DIR;
145
+ if (!VERSION.test(version))
146
+ throw new DockerError(`"${version}" is not a TypeSOL version (e.g. 0.44.0)`);
147
+ if (opts.file || existsSync(path.join(dir, `${version}.json`)) || beforeRecords(version))
148
+ return releaseRecord(version, opts.file, dir);
149
+ const url = `${RELEASES_URL}/${version}.json`;
150
+ const fetchText = opts.fetch ?? globalThis.fetch;
151
+ const instead = `pass the record with --release-record <file> (releases/${version}.json from the repository), ` +
152
+ `or build a version this package records (${recordedVersions(dir).join(", ") || "none"}) with --typesol-version`;
153
+ let bytes;
154
+ try {
155
+ const res = await fetchText(url, { signal: AbortSignal.timeout(opts.timeoutMs ?? 20_000) });
156
+ if (res.status === 404)
157
+ throw new DockerError(`no release record for TypeSOL ${version}: this package does not ship one, and the repository's main branch has none (${url}: HTTP 404). ` +
158
+ `Is ${version} a released version? Otherwise ${instead}.`);
159
+ if (!res.ok)
160
+ throw new DockerError(`could not fetch the release record of TypeSOL ${version} from ${url} (HTTP ${res.status}): ${instead}.`);
161
+ bytes = Buffer.from(await res.arrayBuffer());
162
+ }
163
+ catch (e) {
164
+ if (e instanceof DockerError)
165
+ throw e;
166
+ throw new DockerError(`could not fetch the release record of TypeSOL ${version} from ${url} (${e.message}; offline?). This package does not ship it: ${instead}.`);
167
+ }
168
+ const text = bytes.toString("utf8");
169
+ const record = parseRecord(text, version, url);
170
+ const digest = sha256(bytes);
171
+ (opts.log ?? ((s) => console.error(s)))(` record releases/${version}.json from ${url} (sha256 ${digest}): this package was published before it`);
172
+ return { record, bytes, source: { kind: "repository", location: url, sha256: digest } };
173
+ }
174
+ /**
175
+ * The TypeSOL version a container build uses: `--typesol-version`, else the version of the deployed build's manifest
176
+ * (verify), else this CLI's. A project that installs another typesol than the CLI that runs is an error rather than a
177
+ * guess: the project's own (`npx --no-install typesol`) is the one its builds were made with.
178
+ */
179
+ export function chooseTypesolVersion(opts) {
180
+ if (opts.given !== undefined) {
181
+ if (!VERSION.test(opts.given))
182
+ throw new DockerError(`--typesol-version "${opts.given}" is not a version (e.g. 0.44.0)`);
183
+ return { version: opts.given, why: "--typesol-version" };
184
+ }
185
+ if (opts.deployed)
186
+ return { version: opts.deployed.version, why: `the deployed build's manifest, ${opts.deployed.from}` };
187
+ const installed = opts.projectRoot ? path.join(opts.projectRoot, "node_modules/typesol/package.json") : undefined;
188
+ if (installed && existsSync(installed)) {
189
+ let version;
190
+ try {
191
+ version = JSON.parse(readFileSync(installed, "utf8")).version;
192
+ }
193
+ catch {
194
+ /* unreadable: the CLI's own version below */
195
+ }
196
+ if (typeof version === "string" && version !== opts.cliVersion)
197
+ throw new DockerError(`this project installs typesol ${version} (node_modules/typesol), but this is typesol ${opts.cliVersion}: ` +
198
+ `run the project's own (npx --no-install typesol …), or name the version to build with, --typesol-version ${version}`);
199
+ }
200
+ return { version: opts.cliVersion, why: "this typesol" };
201
+ }
202
+ /**
203
+ * The dependency lock of `version`'s image: this package's docker/deps/<version>.lock.json, else the one in that
204
+ * version's own tarball, whose sha256 the release record lists (the image takes it from the checked tarball). Neither:
205
+ * a DockerError, as the image would have to resolve the dependencies unpinned.
206
+ */
207
+ export function dependencyLock(record, dir = DEPS_DIR) {
208
+ const rel = `docker/deps/${record.version}.lock.json`;
209
+ const at = path.join(dir, `${record.version}.lock.json`);
210
+ if (existsSync(at)) {
211
+ const bytes = readFileSync(at);
212
+ return { bytes, lock: { path: rel, sha256: sha256(bytes), source: "package" } };
213
+ }
214
+ const inTarball = record.files.find((f) => f.path === rel);
215
+ if (inTarball)
216
+ return { lock: { path: rel, sha256: inTarball.sha256, source: "tarball" } };
217
+ throw new DockerError(`no dependency lock for TypeSOL ${record.version}: neither this package (${rel}) nor that version's tarball has one, ` +
218
+ `so its npm dependencies could not be installed pinned. Use a later @typesol/cli, or a version this package locks (${lockedVersions(dir).join(", ") || "none"}).`);
219
+ }
220
+ /** The versions whose dependency locks ship with this package. */
221
+ export function lockedVersions(dir = DEPS_DIR) {
222
+ try {
223
+ return readdirSync(dir).flatMap((f) => /^(\d+\.\d+\.\d+(?:-[\w.]+)?)\.lock\.json$/.exec(f)?.[1] ?? []);
224
+ }
225
+ catch {
226
+ return [];
227
+ }
228
+ }
229
+ /** sha256 of a record's file list (path and sha256 of each, in order): one label for "every file as recorded". */
230
+ export function filesDigest(record) {
231
+ return sha256(record.files.map((f) => `${f.path}\0${f.sha256}\n`).join(""));
232
+ }
233
+ /**
234
+ * The labels an image is built with: everything the image build checked. A cached image is used only when all of
235
+ * them are this record's and this lock's.
236
+ */
237
+ export function imageLabels(dockerfileSha, record, lockSha) {
238
+ return {
239
+ "org.typesol.dockerfile.sha256": dockerfileSha,
240
+ "org.typesol.release.integrity": record.tarball.integrity,
241
+ "org.typesol.release.shasum": record.tarball.shasum,
242
+ "org.typesol.release.commit": record.commit,
243
+ "org.typesol.release.files": filesDigest(record),
244
+ "org.typesol.deps.sha256": lockSha,
245
+ };
246
+ }
247
+ /**
248
+ * The image for `version`, built first when this machine has none (`typesol-build:<version>-<Dockerfile sha256>`).
249
+ * Progress goes to stderr. Building needs the network (base images, release files, npm); running it does not.
250
+ */
251
+ export function ensureImage(version, found, log = (s) => console.error(s)) {
252
+ needDocker();
253
+ const { record, bytes, source } = found ?? releaseRecord(version);
254
+ if (record.version !== version)
255
+ throw new DockerError(`the release record is of TypeSOL ${record.version}, not ${version}`);
256
+ const deps = dependencyLock(record);
257
+ const dockerfile = readFileSync(DOCKERFILE, "utf8");
258
+ const dockerfileSha = sha256(dockerfile);
259
+ const tag = `${IMAGE}:${version}-${dockerfileSha.slice(0, 12)}`;
260
+ const labels = imageLabels(dockerfileSha, record, deps.lock.sha256);
261
+ let id = imageId(tag, labels);
262
+ if (!id) {
263
+ const shown = path.relative(process.cwd(), DOCKERFILE);
264
+ log(` image building ${tag} (${DOCKER_PLATFORM}) from ${shown.startsWith("..") ? DOCKERFILE : shown}`);
265
+ log(` once per TypeSOL version: about 750 MB of downloads, then the toolchain is checked and unpacked (minutes)`);
266
+ const ctx = mkdtempSync(path.join(os.tmpdir(), "typesol-image-"));
267
+ try {
268
+ copyFileSync(DOCKERFILE, path.join(ctx, "Dockerfile"));
269
+ writeFileSync(path.join(ctx, "release.json"), bytes);
270
+ // Empty when the lock is the one in the version's own tarball: the image takes it from there, once checked.
271
+ writeFileSync(path.join(ctx, "deps.lock.json"), deps.bytes ?? "");
272
+ const r = spawnSync("docker", [
273
+ "build",
274
+ "--platform",
275
+ DOCKER_PLATFORM,
276
+ "--build-arg",
277
+ `TYPESOL_VERSION=${version}`,
278
+ ...Object.entries(labels).flatMap(([k, v]) => ["--label", `${k}=${v}`]),
279
+ "-t",
280
+ tag,
281
+ ctx,
282
+ ],
283
+ // docker's progress on stderr: stdout stays the command's own report.
284
+ { stdio: ["ignore", 2, 2] });
285
+ if (r.error || r.status !== 0)
286
+ throw new DockerError(`docker build of ${tag} failed (${r.error?.message ?? `exit ${r.status}`}; its output is above). Nothing was built: --docker never falls back to the local toolchain.`);
287
+ }
288
+ finally {
289
+ rmSync(ctx, { recursive: true, force: true });
290
+ }
291
+ id = imageId(tag, labels);
292
+ if (!id)
293
+ throw new DockerError(`docker build reported success, but ${tag} is not there`);
294
+ }
295
+ const { base, downloads } = dockerfileInputs(dockerfile);
296
+ return {
297
+ tag,
298
+ identity: {
299
+ platform: DOCKER_PLATFORM,
300
+ dockerfile: dockerfileSha,
301
+ image: id,
302
+ base,
303
+ downloads,
304
+ typesol: { version, shasum: record.tarball.shasum, integrity: record.tarball.integrity, commit: record.commit, record: source },
305
+ deps: deps.lock,
306
+ },
307
+ };
308
+ }
309
+ /**
310
+ * The local image id of `tag` when it is there, for this platform, with these labels; undefined when there is none.
311
+ * An image of the tag built from another record or lock (a label differs) is an error, not a silent rebuild: two
312
+ * records of one version disagree, and one of them is wrong.
313
+ */
314
+ function imageId(tag, labels) {
315
+ const r = spawnSync("docker", ["image", "inspect", "--format", "{{.Id}} {{.Os}}/{{.Architecture}} {{json .Config.Labels}}", tag], { encoding: "utf8" });
316
+ if (r.status !== 0)
317
+ return undefined;
318
+ const [id, platform, ...rest] = r.stdout.trim().split(" ");
319
+ if (platform !== DOCKER_PLATFORM)
320
+ return undefined;
321
+ let found = {};
322
+ try {
323
+ found = JSON.parse(rest.join(" ")) ?? {};
324
+ }
325
+ catch {
326
+ /* no labels */
327
+ }
328
+ const differ = Object.entries(labels).filter(([k, v]) => found[k] !== v);
329
+ if (!differ.length)
330
+ return id;
331
+ throw new DockerError(`the local image ${tag} was not built from this release record and dependency lock (${differ
332
+ .map(([k, v]) => `${k}: the image has ${found[k] ?? "none"}, this record ${v}`)
333
+ .join("; ")}). If this record is the right one, remove the image (docker image rm ${tag}) and run again: it is then built from this record.`);
334
+ }
335
+ /**
336
+ * Build `jobs` in the image: `root` mounted read-only (the only sources the container sees), each output directory
337
+ * writable, no network, a read-only root file system, no capabilities, the caller's uid and gid (containerUser). The files are
338
+ * the ones `build` writes; each manifest gets the container's identity.
339
+ */
340
+ export function containerBuild(image, root, jobs) {
341
+ const src = path.resolve(root);
342
+ const mounts = ["--mount", `type=bind,src=${src},dst=/src,readonly`];
343
+ const inside = jobs.map((j, i) => {
344
+ const rel = path.relative(src, path.resolve(j.entry));
345
+ if (rel.startsWith("..") || path.isAbsolute(rel))
346
+ throw new DockerError(`${j.entry} is outside ${src}, the directory the container sees`);
347
+ mkdirSync(j.outDir, { recursive: true });
348
+ mounts.push("--mount", `type=bind,src=${path.resolve(j.outDir)},dst=/out/${i}`);
349
+ return { entry: path.posix.join("/src", ...rel.split(path.sep)), out: `/out/${i}`, address: j.address, sbpf: j.sbpf, profile: !!j.profile };
350
+ });
351
+ const r = spawnSync("docker", [
352
+ "run",
353
+ "--rm",
354
+ "--pull",
355
+ "never",
356
+ "--platform",
357
+ DOCKER_PLATFORM,
358
+ "--network",
359
+ "none",
360
+ "--read-only",
361
+ "--tmpfs",
362
+ "/tmp",
363
+ "--cap-drop",
364
+ "ALL",
365
+ "--security-opt",
366
+ "no-new-privileges",
367
+ "--user",
368
+ containerUser(),
369
+ ...limits(),
370
+ ...mounts,
371
+ image.tag,
372
+ "node",
373
+ "/opt/typesol/container-build.mjs",
374
+ JSON.stringify(inside),
375
+ ], { encoding: "utf8", stdio: ["ignore", "pipe", "inherit"], maxBuffer: 64 * 1024 * 1024 });
376
+ const line = r.stdout?.split("\n").find((l) => l.startsWith("TYPESOL_RESULT "));
377
+ if (r.error || r.status !== 0 || !line)
378
+ throw new DockerError(`the container build failed (${r.error?.message ?? `exit ${r.status}`}; the compiler's output is above). ` +
379
+ `The container sees only ${src} (read-only at /src): an import from outside it is not there.`);
380
+ const built = JSON.parse(line.slice("TYPESOL_RESULT ".length));
381
+ return built.map((b, i) => {
382
+ const job = jobs[i];
383
+ const manifestPath = path.join(job.outDir, `${b.name}.build.json`);
384
+ const manifest = { ...JSON.parse(readFileSync(manifestPath, "utf8")), container: image.identity };
385
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
386
+ return { name: b.name, soPath: path.join(job.outDir, `${b.name}.so`), manifestPath, manifest };
387
+ });
388
+ }
389
+ /**
390
+ * The user the container runs as: the caller's uid:gid, so that it can write the output directories the caller made
391
+ * and the outputs are the caller's. That is root (0:0) for a root caller, still without capabilities, with
392
+ * no-new-privileges and a read-only root file system. Where there is no uid (Windows), the image's `node` user.
393
+ */
394
+ export function containerUser(ids = { uid: process.getuid?.(), gid: process.getgid?.() }) {
395
+ return ids.uid !== undefined && ids.gid !== undefined ? `${ids.uid}:${ids.gid}` : "1000:1000";
396
+ }
397
+ /** TYPESOL_DOCKER_CPUS / TYPESOL_DOCKER_MEMORY: limits for the build container on a shared machine. */
398
+ export function limits() {
399
+ const out = [];
400
+ const cpus = process.env.TYPESOL_DOCKER_CPUS;
401
+ const memory = process.env.TYPESOL_DOCKER_MEMORY;
402
+ if (cpus) {
403
+ if (!/^\d+(\.\d+)?$/.test(cpus))
404
+ throw new DockerError(`TYPESOL_DOCKER_CPUS=${cpus}: expected a number of CPUs (e.g. 2)`);
405
+ out.push("--cpus", cpus);
406
+ }
407
+ if (memory) {
408
+ if (!/^\d+[kmg]?$/i.test(memory))
409
+ throw new DockerError(`TYPESOL_DOCKER_MEMORY=${memory}: expected a size such as 4g`);
410
+ out.push("--memory", memory);
411
+ }
412
+ return out;
413
+ }
414
+ /** The git commit of a source directory and whether its files differ from it, when it is in a checkout. */
415
+ export function sourceRevision(dir) {
416
+ const head = spawnSync("git", ["-C", dir, "rev-parse", "HEAD"], { encoding: "utf8" });
417
+ if (head.status !== 0)
418
+ return undefined;
419
+ const status = spawnSync("git", ["-C", dir, "status", "--porcelain", "--", "."], { encoding: "utf8" });
420
+ return { commit: head.stdout.trim(), clean: status.status === 0 && status.stdout.trim() === "" };
421
+ }
422
+ /** The `typesol verify` command that repeats a container verify: the arguments and every option that changes the result. */
423
+ export function repeatCommand(args, v, version) {
424
+ const opt = (name) => (typeof v[name] === "string" ? [`--${name}`, shellQuote(v[name])] : []);
425
+ return [
426
+ "typesol verify",
427
+ ...args.map(shellQuote),
428
+ ...opt("address"),
429
+ ...opt("url"),
430
+ ...opt("config"),
431
+ ...opt("sbpf"),
432
+ ...opt("manifest"),
433
+ "--docker",
434
+ "--typesol-version",
435
+ version,
436
+ ...opt("release-record"),
437
+ ].join(" ");
438
+ }
439
+ /** Quote a command-line word for a POSIX shell when it needs it. */
440
+ export function shellQuote(s) {
441
+ return /^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`;
442
+ }
@@ -1,4 +1,5 @@
1
1
  import type { Rpc, SolanaRpcApi } from "@solana/kit";
2
+ import { type DockerStatus } from "./docker.js";
2
3
  /** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
3
4
  export declare const INSTALL_AGAVE: "sh -c \"$(curl -sSfL https://release.anza.xyz/v3.1.10/install)\"";
4
5
  export interface Check {
@@ -16,6 +17,8 @@ export declare function toolchainCheck(): Check;
16
17
  * under TYPESOL_TOOLCHAIN=strict (as it is for a build then). Undefined when there are no platform-tools at all.
17
18
  */
18
19
  export declare function testedToolchainCheck(): Check | undefined;
20
+ /** Docker for `build --docker` / `verify --docker`: optional, a row either way. */
21
+ export declare function dockerCheck(status?: DockerStatus): Check;
19
22
  /** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
20
23
  export declare function solanaConfig(file?: string): {
21
24
  url?: string;
@@ -7,6 +7,7 @@ import os from "node:os";
7
7
  import path from "node:path";
8
8
  import { findToolchain, INSTALL_TESTED_TOOLCHAIN, shortClang, TESTED_TOOLCHAIN, toolchainInfo, toolchainStrict } from "../compiler/toolchain.js";
9
9
  import { base58, readKeypair } from "../keys.js";
10
+ import { DOCKER_PLATFORM, dockerStatus } from "./docker.js";
10
11
  import { findWorkspace } from "../workspace.js";
11
12
  /** The Agave CLI release TypeSOL is tested with (its platform-tools are the tested ones). */
12
13
  export const INSTALL_AGAVE = INSTALL_TESTED_TOOLCHAIN[0];
@@ -65,6 +66,16 @@ export function testedToolchainCheck() {
65
66
  fix: [`${INSTALL_TESTED_TOOLCHAIN[1]} # the tested platform-tools`],
66
67
  };
67
68
  }
69
+ /** Docker for `build --docker` / `verify --docker`: optional, a row either way. */
70
+ export function dockerCheck(status = dockerStatus()) {
71
+ if (!status.ok)
72
+ return { ok: false, optional: true, what: "docker", detail: `${status.reason}; needed only for --docker builds`, fix: [status.fix] };
73
+ return {
74
+ ok: true,
75
+ what: "docker",
76
+ detail: `${status.version} (${status.platform}): --docker builds run in ${DOCKER_PLATFORM}${status.platform === DOCKER_PLATFORM ? "" : ", emulated here"}`,
77
+ };
78
+ }
68
79
  /** json_rpc_url / keypair_path from a Solana CLI config (the given file, or the CLI's default one). */
69
80
  export function solanaConfig(file) {
70
81
  const configPath = file ?? path.join(os.homedir(), ".config/solana/cli/config.yml");
@@ -216,6 +227,7 @@ export async function doctorChecks(opts) {
216
227
  checks.push(solanaVersion
217
228
  ? { ok: true, what: "Solana CLI", detail: solanaVersion }
218
229
  : { ok: false, optional: true, what: "Solana CLI", detail: "not on PATH (needed to deploy, not to build or test)", fix: [INSTALL_AGAVE] });
230
+ checks.push(dockerCheck());
219
231
  const cfg = solanaConfig(opts.config);
220
232
  const keypair = cfg.keypair ?? path.join(os.homedir(), ".config/solana/id.json");
221
233
  if (existsSync(keypair)) {
@@ -63,7 +63,8 @@ export interface BuiltProgram {
63
63
  }
64
64
  /**
65
65
  * The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
66
- * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
66
+ * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records;
67
+ * for a `build --docker` build, the same sources, SBPF version and address and the .so it records, on any host),
67
68
  * else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
68
69
  */
69
70
  export declare function buildForTest(ws: Workspace, name: string): BuiltProgram;
package/dist/workspace.js CHANGED
@@ -121,7 +121,8 @@ export function buildWorkspace(ws, names = Object.keys(ws.programs), opts = {})
121
121
  }
122
122
  /**
123
123
  * The program built for a test: the existing build when it is up to date (same sources, runtime header, TypeSOL,
124
- * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records),
124
+ * TypeScript, clang and platform-tools versions, host, SBPF version and address, not a --profile build, and the .so the manifest records;
125
+ * for a `build --docker` build, the same sources, SBPF version and address and the .so it records, on any host),
125
126
  * else a fresh one. Concurrent callers (parallel test workers) wait for each other instead of building over each other.
126
127
  */
127
128
  export function buildForTest(ws, name) {
@@ -131,12 +132,26 @@ export function buildForTest(ws, name) {
131
132
  const current = upToDateBuild(paths, address, ws.sbpf);
132
133
  if (current)
133
134
  return { ...current, rebuilt: false };
135
+ // A container build whose sources changed is out of date: the test builds locally over it, and says so.
136
+ if (hasContainerBuild(paths))
137
+ console.error(`note: ${path.relative(process.cwd(), paths.outDir) || "."} held a --docker build that is out of date (its sources, SBPF version or address changed); ` +
138
+ `the test builds it with the local toolchain: run \`typesol build --docker\` again before deploying`);
134
139
  const result = build(paths.entry, paths.outDir, address, { sbpf: ws.sbpf });
135
140
  writeClient(result.idl, path.join(paths.outDir, `${result.model.name}.client.ts`));
136
141
  return { address, soPath: result.soPath, idl: result.idl, rebuilt: true };
137
142
  });
138
143
  }
139
144
  const sha256 = (data) => createHash("sha256").update(data).digest("hex");
145
+ /** Whether the program's build manifest records a container (`build --docker`). */
146
+ function hasContainerBuild(paths) {
147
+ try {
148
+ const file = path.join(paths.outDir, `${path.basename(paths.entry).replace(/\.ts$/, "")}.build.json`);
149
+ return !!JSON.parse(readFileSync(file, "utf8")).container;
150
+ }
151
+ catch {
152
+ return false;
153
+ }
154
+ }
140
155
  /** The existing build of a program if building it again would give the same files, else undefined. */
141
156
  function upToDateBuild(paths, address, sbpf) {
142
157
  // The compiler names a program's files after its entry file (programs/counter.ts → counter.so).
@@ -153,21 +168,33 @@ function upToDateBuild(paths, address, sbpf) {
153
168
  catch {
154
169
  return undefined;
155
170
  }
156
- if (manifest.compiler !== COMPILER_VERSION || manifest.typescript !== ts.version || manifest.sbpf !== sbpf || manifest.profile)
171
+ if (manifest.sbpf !== sbpf || manifest.profile)
157
172
  return undefined;
158
173
  if (idl.address !== address || !manifest.sources || typeof manifest.sources !== "object")
159
174
  return undefined;
160
175
  if (sha256(readFileSync(files.so)) !== manifest.binary)
161
176
  return undefined;
177
+ // A `build --docker` build was made by the container's TypeSOL, TypeScript and toolchain, on its linux/x64: none of
178
+ // those is this machine's, so they are not compared. It is up to date while the program's sources are the ones it
179
+ // records (and its binary the one it records, above); a test never replaces it with a local build because of the
180
+ // host. Its runtime files are the container's TypeSOL version's: compared only when that is this version.
181
+ const container = !!manifest.container;
182
+ if (!container && (manifest.compiler !== COMPILER_VERSION || manifest.typescript !== ts.version))
183
+ return undefined;
162
184
  const root = path.dirname(paths.entry);
163
185
  for (const [rel, hash] of Object.entries(manifest.sources)) {
164
- const file = rel === "<runtime>/typesol_rt.h" ? path.join(RUNTIME_DIR, "typesol_rt.h") : path.resolve(root, rel);
186
+ const runtime = rel.startsWith("<runtime>/");
187
+ if (runtime && container && manifest.compiler !== COMPILER_VERSION)
188
+ continue;
189
+ const file = runtime ? path.join(RUNTIME_DIR, rel.slice("<runtime>/".length)) : path.resolve(root, rel);
165
190
  if (!existsSync(file) || sha256(readFileSync(file)) !== hash)
166
191
  return undefined;
167
192
  }
168
- // A new import changes the importing file, so every source of the current program is in the list; the runtime and
169
- // the entry must be there too (a manifest from another layout).
170
- if (!manifest.sources["<runtime>/typesol_rt.h"] || !manifest.sources[path.basename(paths.entry)])
193
+ if (container)
194
+ return manifest.sources[path.basename(paths.entry)] ? { address, soPath: files.so, idl } : undefined;
195
+ // A new import changes the importing file, so every source of the current program is in the list; the runtime (its
196
+ // header and its builtins) and the entry must be there too (a manifest from another layout or an older release).
197
+ if (!manifest.sources["<runtime>/typesol_rt.h"] || !manifest.sources["<runtime>/typesol_builtins.c"] || !manifest.sources[path.basename(paths.entry)])
171
198
  return undefined;
172
199
  // A manifest from before 0.44.0 has no host: rebuild once to record the toolchain in full.
173
200
  if (!manifest.host || manifest.host.os !== process.platform || manifest.host.arch !== process.arch)