@rulecad/cad 0.10.0 → 0.11.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.
- package/AGENTS.md +8 -4
- package/CHANGELOG.md +285 -1
- package/EXAMPLES.md +101 -89
- package/README.md +104 -27
- package/bin/cad.mjs +41 -13
- package/lib/assembly.mjs +418 -101
- package/lib/bays.mjs +124 -0
- package/lib/cache-file.mjs +66 -23
- package/lib/clone.mjs +93 -11
- package/lib/design.mjs +40 -4
- package/lib/edit.mjs +5 -3
- package/lib/framebuild.mjs +72 -91
- package/lib/framecheck.mjs +154 -77
- package/lib/framesize.mjs +37 -1
- package/lib/gait.mjs +17 -7
- package/lib/guides.mjs +84 -50
- package/lib/live-guard.mjs +18 -8
- package/lib/measured.mjs +2 -1
- package/lib/mesh.mjs +156 -56
- package/lib/motors.mjs +17 -4
- package/lib/node-version.mjs +52 -0
- package/lib/order.mjs +1 -2
- package/lib/picture-servers.mjs +66 -0
- package/lib/power.mjs +14 -7
- package/lib/preview.mjs +12 -25
- package/lib/programs.mjs +113 -0
- package/lib/sandbox-guard.mjs +43 -0
- package/lib/sandbox.mjs +172 -12
- package/lib/targets/gist.mjs +9 -6
- package/lib/versions.mjs +106 -10
- package/lib/workspace.mjs +3 -1
- package/package.json +13 -13
- package/schemas/assembly.schema.json +5 -4
- package/schemas/object.schema.json +1 -1
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
// The lowest Node the cad command runs on, checked before anything else of it loads: the command's first import
|
|
2
|
+
// (bin/cad.mjs), so that on an older Node it says so in one plain line rather than failing part way with Node's own
|
|
3
|
+
// error. The lowest is the one package.json's "engines" states (CONTRIBUTING.md says why it is 22.13: below it the
|
|
4
|
+
// sandbox designs run in can't start); npm only warns of it on install, in a line that is easily missed.
|
|
5
|
+
// This module imports nothing that an older Node lacks.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
|
|
8
|
+
/** The lowest Node version package.json's "engines" states, as `[major, minor, patch]`. */
|
|
9
|
+
export function nodeFloor() {
|
|
10
|
+
const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
11
|
+
const m = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(pkg.engines?.node ?? '');
|
|
12
|
+
return m ? [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)] : [0, 0, 0];
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* What cad says on a Node older than it runs on, or null on one it runs on.
|
|
17
|
+
* @param {string} [version] Node's version, as process.versions.node gives it ('22.12.0')
|
|
18
|
+
* @param {number[]} [floor] the lowest version, as nodeFloor gives it
|
|
19
|
+
* @returns {string | null}
|
|
20
|
+
*/
|
|
21
|
+
export function nodeTooOld(version = process.versions.node, floor = nodeFloor()) {
|
|
22
|
+
const v = String(version)
|
|
23
|
+
.replace(/^v/, '')
|
|
24
|
+
.split('.')
|
|
25
|
+
.map((n) => Number.parseInt(n, 10) || 0);
|
|
26
|
+
for (let i = 0; i < 3; i++) {
|
|
27
|
+
if ((v[i] ?? 0) > floor[i]) return null;
|
|
28
|
+
if ((v[i] ?? 0) < floor[i]) {
|
|
29
|
+
const want = floor[2] ? floor.join('.') : `${floor[0]}.${floor[1]}`;
|
|
30
|
+
return `cad needs Node ${want} or later; this is Node ${String(version).replace(/^v/, '')}. Install a newer Node (nodejs.org) and run the command again.`;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Stop the command, with that line on stderr and exit status 1, on a Node older than cad runs on; on any other, do
|
|
38
|
+
* nothing.
|
|
39
|
+
* @param {string} [version] Node's version, as process.versions.node gives it
|
|
40
|
+
*/
|
|
41
|
+
export function checkNode(version = process.versions.node) {
|
|
42
|
+
const said = nodeTooOld(version);
|
|
43
|
+
if (!said) return;
|
|
44
|
+
try {
|
|
45
|
+
fs.writeSync(2, `${said}\n`); // (written at once: a pipe's stream may not have sent it before the exit)
|
|
46
|
+
} catch {
|
|
47
|
+
process.stderr.write(`${said}\n`);
|
|
48
|
+
}
|
|
49
|
+
process.exit(1);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
checkNode();
|
package/lib/order.mjs
CHANGED
|
@@ -131,8 +131,7 @@ const allowedPair = (s, a, b) =>
|
|
|
131
131
|
together(s, a, b) ||
|
|
132
132
|
s.fits.some(
|
|
133
133
|
(x) =>
|
|
134
|
-
x.min != null &&
|
|
135
|
-
x.num(x.min) < 0 &&
|
|
134
|
+
(x.overlap === 'allowed' || (x.min != null && x.num(x.min) < 0)) &&
|
|
136
135
|
((names(x.a).includes(a.id) && names(x.b).includes(b.id)) ||
|
|
137
136
|
(names(x.a).includes(b.id) && names(x.b).includes(a.id))),
|
|
138
137
|
);
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// The two small web servers cad takes its pictures from. preview.mjs starts one, and a headless Chrome to open it, for
|
|
2
|
+
// the few seconds a picture takes: partsServer(data) serves the page that draws a part's six views
|
|
3
|
+
// (lib/preview/page.html), the part itself (/data.json) and three's build files; pageServer(html) serves one page (an
|
|
4
|
+
// SVG drawing, a report) whatever is asked for.
|
|
5
|
+
// Both answer only to this computer's own names and addresses, as the live views do (live-guard.mjs, which says why):
|
|
6
|
+
// any web page open in the browser can send requests to a server on this computer, and one whose own name is pointed
|
|
7
|
+
// at 127.0.0.1 (DNS rebinding) could otherwise read the part or the page while its picture is taken. preview.mjs sends
|
|
8
|
+
// Chrome to http://127.0.0.1:<port>/, so Chrome's own requests always name this computer.
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import http from 'node:http';
|
|
12
|
+
import { createRequire } from 'node:module';
|
|
13
|
+
import { TOOL } from './workspace.mjs';
|
|
14
|
+
import { liveGuard } from './live-guard.mjs';
|
|
15
|
+
|
|
16
|
+
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
|
|
17
|
+
|
|
18
|
+
// The check both servers run on each request. What a refused request is told is their own: there is no name to ask
|
|
19
|
+
// for with --allow-host here, and no run to stop
|
|
20
|
+
const allowed = liveGuard({
|
|
21
|
+
host: '127.0.0.1',
|
|
22
|
+
says: {
|
|
23
|
+
host: (given) =>
|
|
24
|
+
'cad serves this page for a few seconds, to make a picture of it, and only to this computer: ' +
|
|
25
|
+
`it does not answer to "${given}".\n`,
|
|
26
|
+
post: 'cad serves this page only to make a picture of it: it takes nothing sent from another page.\n',
|
|
27
|
+
},
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* The server a part's six views are drawn from: the page, the part and three's build files, and nothing else. It
|
|
32
|
+
* answers only to this computer's own names and addresses.
|
|
33
|
+
* @param {string} data the part as the page reads it (JSON: title, meta, parts with their triangles)
|
|
34
|
+
* @returns {import('node:http').Server} not yet listening
|
|
35
|
+
*/
|
|
36
|
+
export function partsServer(data) {
|
|
37
|
+
return http.createServer((req, res) => {
|
|
38
|
+
if (!allowed(req, res)) return;
|
|
39
|
+
// An address that can't be read (//) is not found: read with new URL() it threw, and ended the command
|
|
40
|
+
const u = URL.parse(req.url ?? '', 'http://x')?.pathname ?? '';
|
|
41
|
+
const send = (type, body) => {
|
|
42
|
+
res.writeHead(200, { 'Content-Type': type });
|
|
43
|
+
res.end(body);
|
|
44
|
+
};
|
|
45
|
+
if (u === '/') return send('text/html', fs.readFileSync(path.join(TOOL, 'lib/preview/page.html')));
|
|
46
|
+
if (u === '/data.json') return send('application/json', data);
|
|
47
|
+
const f = path.join(THREE, path.basename(u)); // only three's build files
|
|
48
|
+
if (u.startsWith('/three/') && fs.existsSync(f)) return send('text/javascript', fs.readFileSync(f));
|
|
49
|
+
res.writeHead(404);
|
|
50
|
+
res.end();
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The server any page's picture is taken from: it answers every request with the page, and only to this computer's
|
|
56
|
+
* own names and addresses.
|
|
57
|
+
* @param {string} html the page
|
|
58
|
+
* @returns {import('node:http').Server} not yet listening
|
|
59
|
+
*/
|
|
60
|
+
export function pageServer(html) {
|
|
61
|
+
return http.createServer((req, res) => {
|
|
62
|
+
if (!allowed(req, res)) return;
|
|
63
|
+
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
64
|
+
res.end(html);
|
|
65
|
+
});
|
|
66
|
+
}
|
package/lib/power.mjs
CHANGED
|
@@ -18,6 +18,9 @@ export function powerChecks(s, f) {
|
|
|
18
18
|
const m = d.model,
|
|
19
19
|
refs = { item: d.id, ...(d.joint ? { joint: d.joint } : {}) };
|
|
20
20
|
if (m.type === 'stepper') {
|
|
21
|
+
// A stepper sheet's rated current is per phase, what each coil carries with both on at a full step. It is taken
|
|
22
|
+
// as the peak a driver lets through each coil, as Pololu advises (the cautious reading: a microstepping sine at
|
|
23
|
+
// that peak never puts more through a coil than the sheet allows), and so is a drive's own "current"
|
|
21
24
|
const rated = m.figures.rated_current?.value,
|
|
22
25
|
current = d.spec.current ?? rated,
|
|
23
26
|
R = m.figures.resistance?.value;
|
|
@@ -41,19 +44,23 @@ export function powerChecks(s, f) {
|
|
|
41
44
|
continue;
|
|
42
45
|
}
|
|
43
46
|
const model = driverModel(o.bought.set, { variant: o.bought.variant ?? undefined }),
|
|
44
|
-
{ vref, findings } = setting(
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
47
|
+
{ vref, findings, rms } = setting(
|
|
48
|
+
model,
|
|
49
|
+
{ peak: current },
|
|
50
|
+
{
|
|
51
|
+
cooled: !!d.spec.cooled,
|
|
52
|
+
supply: voltage,
|
|
53
|
+
microsteps: d.spec.microsteps,
|
|
54
|
+
},
|
|
55
|
+
);
|
|
49
56
|
for (const x of findings)
|
|
50
57
|
f(x.level, `${d.id}: ${x.text}`, `${d.id}: driver`, { code: x.code, values: x.values, refs });
|
|
51
58
|
if (!findings.some((x) => x.level === 'fail'))
|
|
52
59
|
f(
|
|
53
60
|
'pass',
|
|
54
|
-
`${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A per coil (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`,
|
|
61
|
+
`${d.id} on ${model.name}: set the trimmer to ${n3(vref, 3)} V for ${n3(current, 2)} A peak per coil${model.measure === 'rms' ? ` (${n3(rms, 2)} A RMS)` : ''} (${model.formula}${model.uart ? `, or set it over UART` : ''}), ${model.sense} ohm sense resistors: read yours before trusting this`,
|
|
55
62
|
null,
|
|
56
|
-
{ code: 'motor.driver', refs, values: { vref, current, sense: model.sense } },
|
|
63
|
+
{ code: 'motor.driver', refs, values: { vref, current, peak: current, rms, sense: model.sense } },
|
|
57
64
|
);
|
|
58
65
|
} else if (m.type === 'servo') {
|
|
59
66
|
draws.push({ name: d.id, current: 0.7, voltage: m.figures.rated_voltage?.value ?? 5, duty: d.spec.duty ?? 0.2 });
|
package/lib/preview.mjs
CHANGED
|
@@ -3,14 +3,13 @@
|
|
|
3
3
|
// solid with built (an assembly with show: built); explode drops
|
|
4
4
|
// supports below and, in an assembly, lifts each kind of object above the one before (plate, switches, keycaps); a part
|
|
5
5
|
// with `lift` (a screw, a nut: lib/fasten.mjs) goes with the part it sits in (`with`) and then out along its own axis.
|
|
6
|
-
// rendered by headless Chrome from lib/preview/page.html, served on this
|
|
6
|
+
// rendered by headless Chrome from lib/preview/page.html, served on this computer only for the few seconds it takes,
|
|
7
|
+
// by a server that answers only to this computer's own names (picture-servers.mjs).
|
|
7
8
|
import fs from 'node:fs';
|
|
8
9
|
import os from 'node:os';
|
|
9
10
|
import path from 'node:path';
|
|
10
|
-
import http from 'node:http';
|
|
11
11
|
import { spawn } from 'node:child_process';
|
|
12
|
-
import {
|
|
13
|
-
import { TOOL } from './workspace.mjs';
|
|
12
|
+
import { pageServer, partsServer } from './picture-servers.mjs';
|
|
14
13
|
|
|
15
14
|
// Any Chrome or Chromium: $CAD_CHROME, else the usual places on macOS, Linux and Windows
|
|
16
15
|
const CHROME =
|
|
@@ -25,7 +24,6 @@ const CHROME =
|
|
|
25
24
|
'/opt/pw-browsers/chromium',
|
|
26
25
|
'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
|
|
27
26
|
].find((f) => fs.existsSync(f));
|
|
28
|
-
const THREE = path.dirname(createRequire(import.meta.url).resolve('three')); // wherever npm put it
|
|
29
27
|
|
|
30
28
|
export async function preview(parts, { title = '', meta = '', out, explode = false, marks = null, built = false }) {
|
|
31
29
|
const flat = (tris) => {
|
|
@@ -47,31 +45,16 @@ export async function preview(parts, { title = '', meta = '', out, explode = fal
|
|
|
47
45
|
positions: flat(p.triangles),
|
|
48
46
|
})),
|
|
49
47
|
});
|
|
50
|
-
|
|
51
|
-
const u = new URL(req.url, 'http://x').pathname;
|
|
52
|
-
const send = (type, body) => {
|
|
53
|
-
res.writeHead(200, { 'Content-Type': type });
|
|
54
|
-
res.end(body);
|
|
55
|
-
};
|
|
56
|
-
if (u === '/') return send('text/html', fs.readFileSync(path.join(TOOL, 'lib/preview/page.html')));
|
|
57
|
-
if (u === '/data.json') return send('application/json', data);
|
|
58
|
-
const f = path.join(THREE, path.basename(u)); // only three's build files
|
|
59
|
-
if (u.startsWith('/three/') && fs.existsSync(f)) return send('text/javascript', fs.readFileSync(f));
|
|
60
|
-
res.writeHead(404);
|
|
61
|
-
res.end();
|
|
62
|
-
});
|
|
63
|
-
return shoot(server, out);
|
|
48
|
+
return shoot(partsServer(data), out);
|
|
64
49
|
}
|
|
65
50
|
|
|
66
|
-
// Any page as an image: html served on this
|
|
51
|
+
// Any page as an image: html served on this computer for the few seconds Chrome takes (an SVG drawing, a report)
|
|
67
52
|
export async function picture(html, out, { width = 1800, height = 1200 } = {}) {
|
|
68
|
-
|
|
69
|
-
res.writeHead(200, { 'Content-Type': 'text/html' });
|
|
70
|
-
res.end(html);
|
|
71
|
-
});
|
|
72
|
-
return shoot(server, out, { width, height });
|
|
53
|
+
return shoot(pageServer(html), out, { width, height });
|
|
73
54
|
}
|
|
74
55
|
|
|
56
|
+
// Chrome is sent to the server by this computer's address, the one name the server is sure to answer to
|
|
57
|
+
// (picture-servers.mjs refuses a request that names any other computer)
|
|
75
58
|
async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
|
|
76
59
|
await new Promise((r) => server.listen(0, '127.0.0.1', r));
|
|
77
60
|
const profile = fs.mkdtempSync(path.join(os.tmpdir(), 'cad-preview-'));
|
|
@@ -119,7 +102,11 @@ async function shoot(server, out, { width = 1800, height = 1200 } = {}) {
|
|
|
119
102
|
});
|
|
120
103
|
});
|
|
121
104
|
} finally {
|
|
105
|
+
// The picture is made, or Chrome has failed: nobody has anything left to ask, so every connection goes with the
|
|
106
|
+
// server. close() alone waits for each one still open, and nothing ever ends one that has asked nothing or
|
|
107
|
+
// stopped half-way through asking: a web page's early connection to the port kept the cad command from ending
|
|
122
108
|
server.close();
|
|
109
|
+
server.closeAllConnections();
|
|
123
110
|
// Chrome's helpers can still be writing to its profile as it exits (macOS: "Directory not empty"): try a few
|
|
124
111
|
// times, and leave it in the temporary folder rather than fail a picture that was made
|
|
125
112
|
try {
|
package/lib/programs.mjs
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
// The programs cad starts that are not its own (git, gh, the file browser), found once each by cad itself.
|
|
2
|
+
//
|
|
3
|
+
// A program named without its folder is looked for by the system, and not only in PATH's folders: on Windows, Node
|
|
4
|
+
// looks first in the folder the program is started in, and on every system a PATH with an empty entry or "." in it
|
|
5
|
+
// looks in the current folder. cad starts git with the workspace as its folder, and the user's current folder is
|
|
6
|
+
// usually inside the workspace, and a workspace can come from anyone: a git.exe in one would run with the user's full
|
|
7
|
+
// rights, outside the design sandbox. So cad finds each program itself, by walking PATH: only entries that are full
|
|
8
|
+
// paths, none inside the workspace (npm puts the workspace's node_modules/.bin on PATH, and a stranger's package can put
|
|
9
|
+
// a "git" there), and on Windows only the kinds of file Windows starts without a shell (.com and .exe; a .bat or .cmd
|
|
10
|
+
// needs one, and cad never starts a program through a shell). The program is then started by the full path found.
|
|
11
|
+
import fs from 'node:fs';
|
|
12
|
+
import path from 'node:path';
|
|
13
|
+
import { execFileSync } from 'node:child_process';
|
|
14
|
+
import { WS } from './workspace.mjs';
|
|
15
|
+
|
|
16
|
+
// The real path of a folder or file (every link followed), or the path as it is where it is not there
|
|
17
|
+
const real = (p) => {
|
|
18
|
+
try {
|
|
19
|
+
return fs.realpathSync.native(p);
|
|
20
|
+
} catch {
|
|
21
|
+
return path.resolve(p);
|
|
22
|
+
}
|
|
23
|
+
};
|
|
24
|
+
|
|
25
|
+
// Whether a path lies in a folder, or is it (on Windows and macOS, letters compared without their case)
|
|
26
|
+
const inside = (p, folder, platform) => {
|
|
27
|
+
const fold = platform === 'linux' ? (s) => s : (s) => s.toLowerCase(),
|
|
28
|
+
r = path.relative(fold(folder), fold(p));
|
|
29
|
+
return r === '' || (!r.startsWith('..') && !path.isAbsolute(r));
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// A file that can be run: on Windows, a file (its extension says it runs); elsewhere, a file with leave to run
|
|
33
|
+
function runnable(f, platform) {
|
|
34
|
+
try {
|
|
35
|
+
if (!fs.statSync(f).isFile()) return false;
|
|
36
|
+
if (platform !== 'win32') fs.accessSync(f, fs.constants.X_OK);
|
|
37
|
+
return true;
|
|
38
|
+
} catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Where a program is, looked for in PATH's folders only: a full path, or null when it is in none of them. Entries that
|
|
45
|
+
* are empty, relative ("." among them) or inside one of the folders in `avoid` (the workspace, unless told otherwise)
|
|
46
|
+
* are passed over, and so is a program found by a link that leads back inside one. On Windows the name is tried with
|
|
47
|
+
* each extension in PATHEXT that Windows starts without a shell (.com, .exe).
|
|
48
|
+
* @param {string} name the program's name alone, as "git"
|
|
49
|
+
* @param {{ env?: NodeJS.ProcessEnv, platform?: NodeJS.Platform, avoid?: string[] }} [options]
|
|
50
|
+
* @returns {string | null}
|
|
51
|
+
*/
|
|
52
|
+
export function findProgram(name, { env = process.env, platform = process.platform, avoid = [WS] } = {}) {
|
|
53
|
+
if (!/^[\w.-]+$/.test(name) || name.startsWith('.')) throw new Error(`not a program's name: ${name}`);
|
|
54
|
+
const p = platform === 'win32' ? path.win32 : path.posix,
|
|
55
|
+
// (Windows keeps its variables' names in any case: Path, PATH)
|
|
56
|
+
get = (k) => (platform === 'win32' ? Object.entries(env).find(([n]) => n.toUpperCase() === k)?.[1] : env[k]),
|
|
57
|
+
away = avoid.map(real);
|
|
58
|
+
const exts =
|
|
59
|
+
platform !== 'win32'
|
|
60
|
+
? ['']
|
|
61
|
+
: path.win32.extname(name)
|
|
62
|
+
? ['']
|
|
63
|
+
: (get('PATHEXT') || '.COM;.EXE')
|
|
64
|
+
.split(';')
|
|
65
|
+
.map((e) => e.trim().toLowerCase())
|
|
66
|
+
.filter((e) => e === '.com' || e === '.exe');
|
|
67
|
+
for (const entry of (get('PATH') || '').split(platform === 'win32' ? ';' : ':')) {
|
|
68
|
+
const dir = entry.trim().replace(/^"(.*)"$/, '$1'); // (Windows allows a quoted entry)
|
|
69
|
+
if (!dir || !p.isAbsolute(dir) || (platform === 'win32' && !/^([a-z]:[\\/]|\\\\)/i.test(dir))) continue;
|
|
70
|
+
if (away.some((w) => inside(real(dir), w, platform))) continue;
|
|
71
|
+
for (const ext of exts) {
|
|
72
|
+
const f = p.join(dir, name + ext);
|
|
73
|
+
if (runnable(f, platform) && !away.some((w) => inside(real(f), w, platform))) return f;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const found = new Map();
|
|
80
|
+
/**
|
|
81
|
+
* findProgram for the workspace, looked for once a run: a full path, or null.
|
|
82
|
+
* @param {string} name @returns {string | null}
|
|
83
|
+
*/
|
|
84
|
+
export function whereIs(name) {
|
|
85
|
+
if (!found.has(name)) found.set(name, findProgram(name));
|
|
86
|
+
return found.get(name);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* The full path of a program cad starts, found once a run (findProgram), or an Error whose code is ENOENT, in plain
|
|
91
|
+
* words, when it is not on PATH outside the workspace.
|
|
92
|
+
* @param {string} name @param {string} what what the program is for, said when it is missing ("git, which keeps releases")
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
export function program(name, what = name) {
|
|
96
|
+
const f = whereIs(name);
|
|
97
|
+
if (f) return f;
|
|
98
|
+
const e = /** @type {Error & { code: string }} */ (
|
|
99
|
+
new Error(
|
|
100
|
+
`${what} is not installed on this computer, or is not in any folder on its PATH. (cad looks for ${name} only in PATH's own folders, never in the workspace, so a program of that name in the workspace is not used.) Install it, or add its folder to PATH, then run the command again`,
|
|
101
|
+
)
|
|
102
|
+
);
|
|
103
|
+
e.code = 'ENOENT';
|
|
104
|
+
throw e;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Run a program cad starts (program()) by its full path, never through a shell: execFileSync's own options.
|
|
109
|
+
* @param {string} name @param {string[]} args @param {import('node:child_process').ExecFileSyncOptions} [options]
|
|
110
|
+
* @param {string} [what] what the program is for, said when it is missing
|
|
111
|
+
*/
|
|
112
|
+
export const runProgram = (name, args, options = {}, what = name) =>
|
|
113
|
+
execFileSync(program(name, what), args, { ...options, shell: false });
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// The sandbox's guard: a small process of its own that ends a design's sandboxed process when the cad command that
|
|
2
|
+
// started it ends, however it ends. Started by sandbox.mjs (guardChild), once a command, with a pipe from the command
|
|
3
|
+
// as its input. The command writes `+<pid>` when it starts a sandboxed process and `-<pid>` when that process has
|
|
4
|
+
// ended. When the pipe closes (the command finished, was killed from outside, its terminal was closed, a test or CI
|
|
5
|
+
// job that ran it was stopped), the guard stops every process still listed and exits.
|
|
6
|
+
// The check can't be in the sandboxed process itself: a design that loops for ever holds that process's only thread,
|
|
7
|
+
// so no timer of its own would ever run, and a thread of its own would need the sandbox to allow workers. Nor can the
|
|
8
|
+
// command's own time limit do it, as a timer in the command dies with the command.
|
|
9
|
+
// It runs no design and reads nothing but its input. It ignores the signals a terminal sends to all its processes
|
|
10
|
+
// (Ctrl-C, a closed window), so it is the closing of the pipe that ends it, after the command, never before.
|
|
11
|
+
const listed = new Set();
|
|
12
|
+
for (const s of ['SIGINT', 'SIGHUP', 'SIGTERM', 'SIGBREAK']) {
|
|
13
|
+
try {
|
|
14
|
+
process.on(s, () => {}); // (the command's end closes the pipe, which is what this waits for)
|
|
15
|
+
} catch {
|
|
16
|
+
// (a signal this system doesn't have: nothing to ignore)
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
let rest = '';
|
|
20
|
+
process.stdin.setEncoding('utf8');
|
|
21
|
+
process.stdin.on('data', (text) => {
|
|
22
|
+
const lines = (rest + text).split('\n');
|
|
23
|
+
rest = lines.pop();
|
|
24
|
+
for (const line of lines) {
|
|
25
|
+
const m = /^([+-])(\d+)$/.exec(line.trim());
|
|
26
|
+
if (!m) continue;
|
|
27
|
+
if (m[1] === '+') listed.add(Number(m[2]));
|
|
28
|
+
else listed.delete(Number(m[2]));
|
|
29
|
+
}
|
|
30
|
+
});
|
|
31
|
+
const end = () => {
|
|
32
|
+
for (const pid of listed) {
|
|
33
|
+
try {
|
|
34
|
+
process.kill(pid, 'SIGKILL');
|
|
35
|
+
} catch {
|
|
36
|
+
// (it has ended already)
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
process.exit(0);
|
|
40
|
+
};
|
|
41
|
+
process.stdin.on('end', end);
|
|
42
|
+
process.stdin.on('close', end);
|
|
43
|
+
process.stdin.on('error', end);
|