@rulecad/cad 0.7.92 → 0.8.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 +4 -0
- package/CHANGELOG.md +76 -1
- package/EXAMPLES.md +8 -4
- package/README.md +64 -16
- package/bin/cad.mjs +28 -13
- package/lib/assembly.mjs +15 -11
- package/lib/design.mjs +122 -29
- package/lib/edit.mjs +4 -3
- package/lib/fasten.mjs +19 -6
- package/lib/fittings.mjs +8 -3
- package/lib/framebuild.mjs +5 -4
- package/lib/host.mjs +31 -2
- package/lib/layout.mjs +2 -1
- package/lib/motors.mjs +3 -1
- package/lib/names.mjs +39 -0
- package/lib/optimise.mjs +38 -11
- package/lib/order.mjs +1 -1
- package/lib/plates.mjs +2 -2
- package/lib/rules.mjs +25 -1
- package/lib/sandbox-hooks.mjs +92 -8
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +20 -4
- package/lib/sandbox.mjs +162 -14
- package/lib/schema.mjs +2 -1
- package/lib/targets.mjs +25 -7
- package/lib/versions.mjs +5 -3
- package/lib/workspace.mjs +21 -7
- package/package.json +11 -11
- package/schemas/object.schema.json +1 -1
- package/schemas/problem.schema.json +25 -7
- package/schemas/project.schema.json +1 -1
package/lib/optimise.mjs
CHANGED
|
@@ -10,9 +10,10 @@ import crypto from 'node:crypto';
|
|
|
10
10
|
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
11
11
|
import { host, readJson } from './host.mjs';
|
|
12
12
|
import { paths, printerOf } from './workspace.mjs';
|
|
13
|
+
import { plainName } from './names.mjs';
|
|
13
14
|
import { resolve, evaluate } from './rules.mjs';
|
|
14
15
|
import { located } from './errors.mjs';
|
|
15
|
-
import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey } from '@rulecad/topopt';
|
|
16
|
+
import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey, featureCells, thin } from '@rulecad/topopt';
|
|
16
17
|
import { islands } from '@rulecad/printcheck';
|
|
17
18
|
import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
|
|
18
19
|
import { section, loops, slabLevels } from './mesh.mjs';
|
|
@@ -20,7 +21,7 @@ import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products
|
|
|
20
21
|
import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
|
|
21
22
|
|
|
22
23
|
const VERSION = 2, source = (m) => fs.readFileSync(new URL(import.meta.resolve(m)), 'utf8'); // the solver's code: a change remakes results
|
|
23
|
-
export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${name}.json`);
|
|
24
|
+
export const problemFile = (project, name) => path.join(paths.project(project), 'problems', `${plainName(name, 'problem name')}.json`); // (a name from a design's file: never ../)
|
|
24
25
|
export const hasProblem = (project, ref) => host.exists(problemFile(project, String(ref).split(':')[0]));
|
|
25
26
|
|
|
26
27
|
/**
|
|
@@ -64,7 +65,7 @@ async function readOne(project, ref, link) {
|
|
|
64
65
|
const designs = new Map();
|
|
65
66
|
const design = (object, what) => { // (the build kept as it starts: regions are read side by side)
|
|
66
67
|
if (!designs.has(object)) designs.set(object, (async () => {
|
|
67
|
-
const { build,
|
|
68
|
+
const { build, locateIn, readObject } = await import('./design.mjs'), d = locateIn(project, object, `${path.basename(file)}: ${what}`);
|
|
68
69
|
const own = Object.entries(readObject(d).variables || {}).find(([, v]) => v.type === 'problem' && String(v.value).split(':')[0] === name);
|
|
69
70
|
if (own) throw new Error(`${path.basename(file)}: ${what} is on ${object}, which is built from this problem (its variable ${own[0]}): name a part or anchor of what it is fixed to instead`);
|
|
70
71
|
const chain = reading.getStore(); // this problem's place on the chain names the design it reads
|
|
@@ -112,12 +113,12 @@ async function readOne(project, ref, link) {
|
|
|
112
113
|
const inAssembly = (what) => {
|
|
113
114
|
if (!p.in) throw new Error(`${fileName}: ${what} needs the problem placed in an assembly: "in": { "assembly": "<name>", "item": "<the item it is drawn in>" }`);
|
|
114
115
|
return (placing ||= (async () => {
|
|
115
|
-
const { buildAssembly, assemblyPath } = await import('./assembly.mjs'), {
|
|
116
|
+
const { buildAssembly, assemblyPath } = await import('./assembly.mjs'), { locateIn, readObject } = await import('./design.mjs');
|
|
116
117
|
const ref = `${project}/${p.in.assembly}`, overrides = {};
|
|
117
118
|
if (!host.exists(assemblyPath(ref))) throw new Error(`${fileName}: no assembly "${p.in.assembly}" to place the problem in (projects/${project}/assemblies/${p.in.assembly}.json)`);
|
|
118
119
|
for (const it of readJson(assemblyPath(ref)).items || []) if (typeof it.object === 'string') {
|
|
119
120
|
let vars = {};
|
|
120
|
-
try { vars = readObject(
|
|
121
|
+
try { vars = readObject(locateIn(project, it.object.split(/[:@]/)[0])).variables || {}; } catch { continue; }
|
|
121
122
|
for (const [k, v] of Object.entries(vars)) if (v.type === 'problem' && (it.id === p.in.item || String(it.set?.[k] ?? v.value).split(':')[0] === name)) (overrides[it.id] ||= {})[k] = 'none';
|
|
122
123
|
}
|
|
123
124
|
const chain = reading.getStore();
|
|
@@ -212,6 +213,11 @@ async function readOne(project, ref, link) {
|
|
|
212
213
|
};
|
|
213
214
|
// The build direction: a direction ('+z'), or a variable holding one
|
|
214
215
|
const overhang = p.overhang ? (typeof values[p.overhang] === 'string' ? values[p.overhang] : p.overhang) : null;
|
|
216
|
+
// The sides it is milled from, and a one-way mould's draw, likewise: or a variable holding them ('+z', '+z +x', or
|
|
217
|
+
// 'none': not milled, not cast), so a variant can switch the process
|
|
218
|
+
const named = (v) => (typeof v === 'string' && typeof values[v] === 'string' ? values[v] : v);
|
|
219
|
+
const millSides = (() => { const v = named(p.mill); if (typeof v !== 'string') return v; const list = v.trim().split(/[\s,]+/).filter(Boolean); return v === 'none' ? null : list.length > 1 ? list : v; })();
|
|
220
|
+
const castWay = (() => { const v = named(p.cast); return v === 'none' ? null : v; })();
|
|
215
221
|
// A teardrop's point: a direction, or up or down the build direction (+z, as drawn, when it's free)
|
|
216
222
|
const point = (t) => { const up = overhang && overhang !== 'none' ? overhang : '+z'; return t === 'up' ? up : t === 'down' ? (up[0] === '-' ? '+' : '-') + up[1] : t; };
|
|
217
223
|
const region = async (r) => {
|
|
@@ -247,12 +253,16 @@ async function readOne(project, ref, link) {
|
|
|
247
253
|
supports: await Promise.all(p.supports.map(async (s) => ({ ...(await region(s)), fix: s.fix || 'xyz'.slice(0, dim) }))),
|
|
248
254
|
loads: await Promise.all(p.loads.map(async (l) => ({ ...(await region(l)), force: pt(l.force), case: l.case || 'load' }))),
|
|
249
255
|
cases: Object.fromEntries(Object.entries(p.cases || {}).map(([k, w]) => [k, ev(w)])),
|
|
250
|
-
material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}),
|
|
256
|
+
material: { E: m.modulus, nu: m.poisson }, ...(dim === 2 ? { thickness: ev(p.thickness) } : {}), cell: ev(p.cell), ...(p.volume != null ? { volume: ev(p.volume) } : {}), ...(p.stress != null ? { stress: ev(p.stress) } : {}), ...(p.strain != null ? { strain: ev(p.strain) } : {}), ...(p.robust ? { robust: true } : {}),
|
|
251
257
|
...(p.filter != null ? { filter: ev(p.filter) } : lines > ev(p.cell) * 1.5 ? { filter: lines } : {}), ...(p.penal != null ? { penal: ev(p.penal) } : {}),
|
|
252
258
|
...(p.projection != null ? { projection: p.projection } : {}), ...(p.steps != null ? { steps: p.steps } : {}),
|
|
253
259
|
...(overhang && overhang !== 'none' ? { overhang } : {}),
|
|
254
260
|
// How it's made other than printed: milled from a side, cast in a mould; symmetric, extruded (topopt's filters)
|
|
255
|
-
...(
|
|
261
|
+
...(millSides ? { mill: millSides } : {}), ...(castWay ? { cast: typeof castWay === 'string' ? castWay : { draw: castWay.draw, ...(castWay.parting != null ? { parting: ev(castWay.parting) } : {}) } } : {}),
|
|
262
|
+
// (a tool or draft with the process switched off by its variable is left out with it; one with no such process
|
|
263
|
+
// at all goes on, for topopt to refuse by name)
|
|
264
|
+
...(p.tool != null && (millSides || !p.mill) ? { tool: ev(p.tool) } : {}), ...(p.draft != null && (castWay || !p.cast) ? { draft: ev(p.draft) } : {}), ...(p.voids === 'prevented' ? { voids: 'prevented' } : {}),
|
|
265
|
+
...(p.feature != null ? { feature: ev(p.feature) } : {}),
|
|
256
266
|
...(p.symmetry ? { symmetry: p.symmetry } : {}), ...(p.extrude ? { extrude: p.extrude } : {}),
|
|
257
267
|
// A mechanism: where the output should move, along one axis, against a spring; a spring the input pushes against
|
|
258
268
|
...(p.output ? { output: { ...(await region(p.output)), direction: pt(p.output.direction), ...(p.output.spring != null ? { spring: ev(p.output.spring) } : {}) } } : {}),
|
|
@@ -289,19 +299,36 @@ function holdEmpty(spec) {
|
|
|
289
299
|
}
|
|
290
300
|
// How a result is made, and what that process can't make in it: for a milled or cast part, the cells a tool or mould
|
|
291
301
|
// half could not reach (undercuts, none by construction unless an avoid region or the space's own shape leaves material between a cell and its side), how grey it is; where enclosed voids are
|
|
292
|
-
// refused (a powder bed print, a trapped core), each void with its volume (mm³, or mm² in 2D) and
|
|
302
|
+
// refused or prevented (a powder bed print, a trapped core), each void left with its volume (mm³, or mm² in 2D) and
|
|
303
|
+
// where it is, and with prevented that they were
|
|
293
304
|
function made(r, spec, density) {
|
|
294
305
|
const p = r.problem, out = {};
|
|
295
306
|
if (p.mill || p.cast) {
|
|
296
|
-
const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw),
|
|
297
|
-
|
|
307
|
+
const c = spec.cast, from = p.mill || (typeof c === 'string' ? c : c.draw), tool = p.tool ? p.tool / spec.grid.h : undefined;
|
|
308
|
+
const u = undercuts(spec.grid, density, { from, ...(c && typeof c === 'object' ? { parting: c.parting } : {}), ...(p.draft ? { draft: p.draft } : {}) });
|
|
309
|
+
// With a tool's size: the cells it can't get its end into besides, in the design (none, by construction) and in
|
|
310
|
+
// avoid regions (a hole narrower than the tool: drilled, or a smaller tool)
|
|
311
|
+
if (tool) {
|
|
312
|
+
const hidden = new Set(u.cells), narrow = undercuts(spec.grid, density, { from, tool }).cells.filter((e) => !hidden.has(e));
|
|
313
|
+
out.narrow = { design: narrow.filter((e) => spec.passive[e] === 0).length, avoided: narrow.filter((e) => spec.passive[e] === -1).length };
|
|
314
|
+
}
|
|
315
|
+
// (a draft at the grid: a step out every whole number of layers in 1 / tan, so the angle made is atan of one over it)
|
|
316
|
+
const every = p.draft ? Math.max(1, Math.floor(1 / Math.tan((p.draft * Math.PI) / 180) + 1e-9)) : 0;
|
|
317
|
+
out.process = p.mill ? { mill: p.mill, ...(p.tool ? { tool: p.tool } : {}) } : { cast: typeof c === 'string' ? c : { draw: c.draw, parting: round(c.at, 3) }, ...(every ? { draft: p.draft, every, made: round((Math.atan(1 / every) * 180) / Math.PI, 2) } : {}) };
|
|
298
318
|
out.undercuts = u.count;
|
|
299
319
|
}
|
|
300
320
|
if (p.symmetry) out.symmetry = p.symmetry;
|
|
301
321
|
if (p.extrude) out.extrude = p.extrude;
|
|
302
322
|
// How grey it came out: a process or a tie can leave no clear part (a 2D section milled from its side)
|
|
303
323
|
if (p.mill || p.cast || p.symmetry || p.extrude) out.grey = round(grey(density, spec.passive), 3);
|
|
304
|
-
if (r.voids === 'refused') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
|
|
324
|
+
if (r.voids === 'refused' || r.voids === 'prevented') out.voids = voids(spec.grid, density, { origin: spec.origin }).map((v) => ({ volume: round(v.volume, 3), at: v.at.map((x) => round(x, 3)) }));
|
|
325
|
+
if (r.voids === 'prevented') out.vented = true;
|
|
326
|
+
// The thinnest member asked: the ball's radius on the grid, the width it holds members to (a cell, where the grid
|
|
327
|
+
// already does), and the solid cells left in members narrower (or on a square outside corner)
|
|
328
|
+
if (p.feature != null) {
|
|
329
|
+
const h = spec.grid.h, cells = featureCells(p.feature, h);
|
|
330
|
+
out.feature = { asked: p.feature, cells, holds: round((2 * cells + 1) * h, 3), thin: cells ? thin(spec.grid, density, { radius: cells }).count : 0 };
|
|
331
|
+
}
|
|
305
332
|
return out;
|
|
306
333
|
}
|
|
307
334
|
const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
|
package/lib/order.mjs
CHANGED
|
@@ -238,7 +238,7 @@ export function assemblyOrder(s) {
|
|
|
238
238
|
}
|
|
239
239
|
|
|
240
240
|
/** One fastening of a step as the order and the build page say it: the fit, its screws by count and name, the key and how tight. */
|
|
241
|
-
export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.hand ? `to ${f.tighten.torque} N m and no further (a printed bolt, turned by hand, not tightened)` : f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
|
|
241
|
+
export const fastenerText = (f) => `${f.fit}${f.fastener ? ` (${f.count != null ? `${f.count} × ` : ''}${f.fastener})` : ''}${f.key ? ` with ${/^[aeiou8]/i.test(f.key) ? 'an' : 'a'} ${f.key}` : ''}${f.tighten ? `, ${f.tighten.hand ? `to ${f.tighten.torque} N m and no further (a printed bolt, turned by hand, not tightened)` : f.tighten.given ? `to ${f.tighten.torque} N m` : f.tighten.load ? `to ${f.tighten.torque} N m (what the joint's load leaves the thread)` : f.tighten.thread ? `to ${f.tighten.torque} N m at most (half what the thread strips at)` : `to ${f.tighten.torque} N m at most (what the seat takes)`}` : ''}`;
|
|
242
242
|
|
|
243
243
|
// Cached by what the parts are and where they are, with everything else that changes the answer (a motor's screw
|
|
244
244
|
// names the tool its step gives)
|
package/lib/plates.mjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import fs from 'node:fs';
|
|
5
5
|
import path from 'node:path';
|
|
6
6
|
import { bounds, check as printCheck } from '@rulecad/printcheck';
|
|
7
|
-
import {
|
|
7
|
+
import { locateIn, build } from './design.mjs';
|
|
8
8
|
import { paths, printerOf } from './workspace.mjs';
|
|
9
9
|
import { peekRuleSet } from './rules.mjs';
|
|
10
10
|
import { CadError } from './errors.mjs';
|
|
@@ -39,7 +39,7 @@ async function plateParts(s) {
|
|
|
39
39
|
const it = o.fitting ? items.get(o.id) : null;
|
|
40
40
|
if (o.fitting && !it?.fitting) continue;
|
|
41
41
|
const fitting = it ? { ...it.fitting, pose: 'print' } : null;
|
|
42
|
-
const b = fitting ? (await fittingBuilt({ ...it, fitting }, o.id, framesContext(), plasticOf(s.project))).b : await build({ ...
|
|
42
|
+
const b = fitting ? (await fittingBuilt({ ...it, fitting }, o.id, framesContext(), plasticOf(s.project))).b : await build({ ...locateIn(s.project, o.objName), ...(o.variant ? { variant: o.variant } : {}) }, o.set || {});
|
|
43
43
|
const tris = b.parts.flatMap((p) => p.triangles), { lo, hi } = bounds(tris);
|
|
44
44
|
const fil = [...new Set(b.parts.filter((p) => p.role !== 'support').map((p) => p.filament || 'base'))].sort().join('+') || 'base';
|
|
45
45
|
out.push({ id: o.id.replace(/\./g, '_'), source: o.id, object: o.objName, ...(fitting ? { fitting } : {}), variant: o.variant, set: o.set || {}, filament: fil, material: own, hash: b.hash, lo, size: [hi[0] - lo[0], hi[1] - lo[1]], height: hi[2] - lo[2] });
|
package/lib/rules.mjs
CHANGED
|
@@ -1,27 +1,51 @@
|
|
|
1
1
|
// Rules from files: the variables and expressions of @rulecad/variables, with rule sets read from the workspace's rules/
|
|
2
2
|
// (then the tool's) by name. Everything but loading is in @rulecad/variables, which needs no files and runs anywhere.
|
|
3
|
+
import fs from 'node:fs';
|
|
3
4
|
import path from 'node:path';
|
|
4
5
|
import { host, readJson } from './host.mjs';
|
|
5
6
|
import { RULE_DIRS, WS } from './workspace.mjs';
|
|
7
|
+
import { plainName } from './names.mjs';
|
|
6
8
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
7
9
|
|
|
8
10
|
export { ANCHORS, isName, options, checkName, evaluate, fmt } from '@rulecad/variables';
|
|
9
11
|
|
|
10
12
|
// dir: one folder (a release's own rules), else the workspace's rules, then the tool's. A rule set the tool provides
|
|
11
13
|
// is copied into the workspace the first time it's used: the workspace keeps every rule its designs depend on (so a
|
|
12
|
-
// release can record them in git), and your own measurements are edits to your copy.
|
|
14
|
+
// release can record them in git), and your own measurements are edits to your copy. The name is joined into both
|
|
15
|
+
// paths, so it must be plain (lib/names.mjs): a name with ../ would read a file from elsewhere and write its copy
|
|
16
|
+
// outside the workspace.
|
|
13
17
|
export function loadRuleSet(name, dir) {
|
|
18
|
+
plainName(name, 'rule set name');
|
|
14
19
|
const file = (dir ? [dir] : RULE_DIRS).map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
|
|
15
20
|
if (!file) throw new Error(`no rule set "${name}" (rules/${name}.json)`);
|
|
16
21
|
const own = path.join(WS, 'rules', `${name}.json`);
|
|
17
22
|
if (!dir && file !== own) {
|
|
23
|
+
insideWorkspace(own);
|
|
18
24
|
host.writeText(own, host.readText(file));
|
|
19
25
|
console.error(`copied the ${name} rule set into rules/${name}.json: yours to keep and edit`);
|
|
20
26
|
}
|
|
21
27
|
return readJson(own);
|
|
22
28
|
}
|
|
29
|
+
/**
|
|
30
|
+
* `file` (a rule set about to be written into the workspace's rules/) if no folder or file on its way down from the
|
|
31
|
+
* workspace is a link, else an error naming the link. A workspace can come from anyone, and git can carry a link: a
|
|
32
|
+
* rules/ folder that links to a folder elsewhere, or a rules/<name>.json that links to a file not yet made, would have
|
|
33
|
+
* the copy written outside the workspace.
|
|
34
|
+
* @param {string} file
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function insideWorkspace(file) {
|
|
38
|
+
if (host.name !== 'node') return file; // (a workspace in memory has no links)
|
|
39
|
+
const top = path.resolve(WS); // (the workspace's own folder may be reached by a link: only what is inside it counts)
|
|
40
|
+
for (let p = path.resolve(file); p.startsWith(top + path.sep); p = path.dirname(p)) {
|
|
41
|
+
let link = false; try { link = fs.lstatSync(p).isSymbolicLink(); } catch {} // (not there yet: nothing to follow)
|
|
42
|
+
if (link) throw new Error(`${path.relative(WS, p)} is a link to somewhere else, so nothing was written to ${path.relative(WS, file)}: it could land outside the workspace. Make ${path.relative(WS, p)} a folder or file of the workspace's own`);
|
|
43
|
+
}
|
|
44
|
+
return file;
|
|
45
|
+
}
|
|
23
46
|
// A rule set read as it is, the workspace's if it has one: for figures a check only reads, leaving the workspace alone
|
|
24
47
|
export function peekRuleSet(name) {
|
|
48
|
+
plainName(name, 'rule set name');
|
|
25
49
|
const file = RULE_DIRS.map((d) => path.join(d, `${name}.json`)).find((f) => host.exists(f));
|
|
26
50
|
if (!file) throw new Error(`no rule set "${name}" (rules/${name}.json)`);
|
|
27
51
|
return readJson(file);
|
package/lib/sandbox-hooks.mjs
CHANGED
|
@@ -1,35 +1,119 @@
|
|
|
1
1
|
// The sandbox's import hook: code in the design's project may import @jscad/modeling, @rulecad/shapes, @rulecad/flexures, @rulecad/gears, @rulecad/motors, @rulecad/frames, @rulecad/fixings and files of
|
|
2
2
|
// its own project, nothing else (no node: modules: no files, network or processes). The tool's own modules are free.
|
|
3
|
+
// An allowed package is named plainly and must lead inside that package: '@jscad/modeling/../../graceful-fs' would
|
|
4
|
+
// otherwise climb out of it to any file of the workspace, and a file outside the project isn't held to these rules.
|
|
5
|
+
import fs from 'node:fs';
|
|
6
|
+
import path from 'node:path';
|
|
3
7
|
import { builtinModules } from 'node:module';
|
|
8
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
9
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
10
|
+
// (Not @rulecad/pcb: a board design reaches the board engine as v.pcb, which the runner loads as the tool's own
|
|
11
|
+
// module. The engine imports Node's modules, which a package a design may import may not, and the permission model
|
|
12
|
+
// holds it to reads only.)
|
|
8
13
|
const ALLOWED = ['@jscad/modeling', '@rulecad/shapes', '@rulecad/flexures', '@rulecad/gears', '@rulecad/motors', '@rulecad/frames', '@rulecad/fixings'];
|
|
14
|
+
|
|
15
|
+
// Each allowed package's real folder, as the tool itself finds it (from its entry up to the package.json of that
|
|
16
|
+
// name: exports may hide that file), found once; null where the tool can't find the package
|
|
17
|
+
function home(name) {
|
|
18
|
+
try {
|
|
19
|
+
for (let d = path.dirname(fileURLToPath(import.meta.resolve(name))); path.dirname(d) !== d; d = path.dirname(d)) {
|
|
20
|
+
const pj = path.join(d, 'package.json');
|
|
21
|
+
if (fs.existsSync(pj) && JSON.parse(fs.readFileSync(pj, 'utf8')).name === name) return pathToFileURL(fs.realpathSync(d) + path.sep).href;
|
|
22
|
+
}
|
|
23
|
+
} catch { /* not where the tool can find it */ }
|
|
24
|
+
return null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// What a file of each package may import by name: the allowed packages and what its package.json says it depends on
|
|
28
|
+
function needs(url) {
|
|
29
|
+
try {
|
|
30
|
+
const j = JSON.parse(fs.readFileSync(new URL('package.json', url), 'utf8'));
|
|
31
|
+
return [...ALLOWED, ...['dependencies', 'peerDependencies', 'optionalDependencies'].flatMap((k) => Object.keys(j[k] || {}))];
|
|
32
|
+
} catch { return ALLOWED; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Each allowed package's real folder (a file: URL ending in a slash), or null where the tool can't find it. Found in
|
|
37
|
+
* the tool's own thread: older Node runs these hooks in a worker, where import.meta.resolve can't find packages, so
|
|
38
|
+
* the preload works them out and hands them over.
|
|
39
|
+
* @returns {Record<string, string | null>}
|
|
40
|
+
*/
|
|
41
|
+
export const homesOf = () => Object.fromEntries(ALLOWED.map((a) => [a, home(a)]));
|
|
42
|
+
|
|
43
|
+
let project = '', homes = {}, deps = {};
|
|
44
|
+
/**
|
|
45
|
+
* Set the hooks up: the design's project (a file: URL ending in a slash) and, from the preload, the packages' folders.
|
|
46
|
+
* @param {{ project?: string, homes?: Record<string, string | null> }} [data]
|
|
47
|
+
*/
|
|
48
|
+
export async function initialize(data) {
|
|
49
|
+
project = data?.project || '';
|
|
50
|
+
homes = data?.homes || homesOf();
|
|
51
|
+
deps = Object.fromEntries(ALLOWED.filter((a) => homes[a]).map((a) => [a, needs(homes[a])]));
|
|
52
|
+
}
|
|
53
|
+
|
|
9
54
|
const deny = (spec, why) => Object.assign(new Error(`designs can't import "${spec}": ${why}`), { code: 'design.sandbox' });
|
|
10
55
|
|
|
11
56
|
// The same check, for in-thread hooks (synchronous) and worker hooks (async)
|
|
12
57
|
export function resolveHook(spec, context, next) {
|
|
13
58
|
const fromDesign = check(spec, context), r = next(spec, context);
|
|
14
|
-
return fromDesign ? after(spec, r) : r;
|
|
59
|
+
return fromDesign ? after(spec, r) : inPackage(spec, context, r);
|
|
15
60
|
}
|
|
16
61
|
export async function resolve(spec, context, next) {
|
|
17
62
|
const fromDesign = check(spec, context), r = await next(spec, context);
|
|
18
|
-
return fromDesign ? after(spec, r) : r;
|
|
63
|
+
return fromDesign ? after(spec, r) : inPackage(spec, context, r);
|
|
64
|
+
}
|
|
65
|
+
// A design may reach any file of an allowed package, and such a file isn't the design's, so it is free of the rules
|
|
66
|
+
// above: one that imports something the package doesn't depend on would hand that to the design. @jscad/modeling's
|
|
67
|
+
// own tests require('ava'), and an "ava" the workspace installs (a file: dependency, say) may do anything. So a file
|
|
68
|
+
// of an allowed package (not of a package kept in its node_modules) may import only the allowed packages, what its
|
|
69
|
+
// package.json depends on, and its own files.
|
|
70
|
+
const packageAt = (url) => ALLOWED.find((a) => homes[a] && url?.startsWith(homes[a]) && !url.slice(homes[a].length).split('/').some((s) => s.toLowerCase() === 'node_modules'));
|
|
71
|
+
// (before Node looks for a name, and after it finds a relative file)
|
|
72
|
+
function packageCheck(spec, context) {
|
|
73
|
+
const name = packageAt(context.parentURL);
|
|
74
|
+
if (name && !isRelative(spec) && (spec.startsWith('node:') || builtinModules.includes(spec) || !deps[name].some((d) => spec === d || spec.startsWith(`${d}/`)))) {
|
|
75
|
+
throw deny(spec, `${fileURLToPath(context.parentURL)} would import it, and its package ${name} doesn't depend on it (a design may use a package's own files, not the tools its tests use)`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
function inPackage(spec, context, r) {
|
|
79
|
+
const name = isRelative(spec) && packageAt(context.parentURL);
|
|
80
|
+
if (name && !r.url.startsWith(homes[name])) throw deny(spec, `${fileURLToPath(context.parentURL)} would reach outside its package, ${name}`);
|
|
81
|
+
return r;
|
|
19
82
|
}
|
|
20
83
|
const isRelative = (spec) => spec.startsWith('./') || spec.startsWith('../');
|
|
84
|
+
const packageOf = (spec) => ALLOWED.find((a) => spec === a || spec.startsWith(`${a}/`));
|
|
21
85
|
// A design's own files are its project's. A path that leaves it is refused wherever it leads: into the workspace's
|
|
22
|
-
// node_modules, say, where any package may be.
|
|
86
|
+
// node_modules, say, where any package may be. An allowed package must lead into its own folder, the one the tool
|
|
87
|
+
// uses, or a copy in the project: not through a link out of the project to some other folder of the same name.
|
|
23
88
|
const after = (spec, r) => {
|
|
24
|
-
if (isRelative(spec)
|
|
89
|
+
if (isRelative(spec)) {
|
|
90
|
+
if (!r.url.startsWith(project)) throw deny(spec, 'it is outside the project');
|
|
91
|
+
return r;
|
|
92
|
+
}
|
|
93
|
+
const name = packageOf(spec), inside = homes[name];
|
|
94
|
+
if (!r.url.startsWith(project) && !(inside && r.url.startsWith(inside))) {
|
|
95
|
+
const to = r.url.startsWith('file:') ? fileURLToPath(r.url) : r.url;
|
|
96
|
+
const own = inside ? ` (${fileURLToPath(inside)})` : '';
|
|
97
|
+
throw deny(spec, `it leads outside the package ${name}, to ${to}. A design may use only the copy rulecad itself uses${own} or one inside its project: if the workspace installs another copy, give it the version rulecad uses (npm ls ${name} lists the copies)`);
|
|
98
|
+
}
|
|
25
99
|
return r;
|
|
26
100
|
};
|
|
101
|
+
// A file inside a package is named plainly: no '.' or '..' among the folders, no backslash, no %-encoded letters, and
|
|
102
|
+
// never in the package's own node_modules (another package, which may read files: a nested graceful-fs, say). Windows
|
|
103
|
+
// drops a name's trailing dots and spaces and knows NODE_M~1 for node_modules, so those spellings are refused too.
|
|
104
|
+
const odd = (s) => { const t = s.replace(/[. ]+$/, '').toLowerCase(); return t === '' || t === 'node_modules' || s.includes('~'); };
|
|
105
|
+
const climbs = (spec, name) => /[\\%]/.test(spec) || (spec !== name && spec.slice(name.length + 1).split('/').some(odd));
|
|
27
106
|
// Everything under the project is the design's code, a node_modules folder there included
|
|
28
107
|
function check(spec, context) {
|
|
29
108
|
const fromDesign = project && context.parentURL?.startsWith(project);
|
|
109
|
+
if (!fromDesign) packageCheck(spec, context);
|
|
30
110
|
if (fromDesign) {
|
|
31
111
|
if (spec.startsWith('node:') || builtinModules.includes(spec)) throw deny(spec, 'a design only makes shapes (no files, network or programs)');
|
|
32
|
-
if (!isRelative(spec)
|
|
112
|
+
if (!isRelative(spec)) {
|
|
113
|
+
const name = packageOf(spec);
|
|
114
|
+
if (!name) throw deny(spec, `only ${ALLOWED.join(', ')} and files in its project`);
|
|
115
|
+
if (climbs(spec, name)) throw deny(spec, `a file of ${name} is named by its path inside the package, with no "." or ".." folders, node_modules, backslashes, "%" or "~", and no folder whose name ends in a dot or a space`);
|
|
116
|
+
}
|
|
33
117
|
}
|
|
34
118
|
return fromDesign;
|
|
35
119
|
}
|
package/lib/sandbox-preload.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Loaded first in the sandbox (node --import): the import hook that keeps designs to their own imports. In-thread
|
|
2
2
|
// (module.registerHooks) where Node has it; older Node runs hooks in a worker, which the sandbox then allows.
|
|
3
3
|
import * as mod from 'node:module';
|
|
4
|
-
import { resolveHook, initialize } from './sandbox-hooks.mjs';
|
|
4
|
+
import { resolveHook, initialize, homesOf } from './sandbox-hooks.mjs';
|
|
5
5
|
|
|
6
6
|
const project = process.env.CAD_SANDBOX_PROJECT;
|
|
7
7
|
if (mod.registerHooks) {
|
|
8
8
|
initialize({ project });
|
|
9
9
|
mod.registerHooks({ resolve: resolveHook });
|
|
10
|
-
} else mod.register('./sandbox-hooks.mjs', import.meta.url, { data: { project } });
|
|
10
|
+
} else mod.register('./sandbox-hooks.mjs', import.meta.url, { data: { project, homes: homesOf() } });
|
package/lib/sandbox-run.mjs
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
// The sandbox's runner: reads { js, values, meta } on stdin, runs the design's main(values), and writes its parts'
|
|
2
2
|
// faces (and the rules it read) as JSON on stdout. Started by sandbox.mjs, under Node's permission model.
|
|
3
|
+
// A board design (board set) gets v.pcb, the board engine, and what it hands back is built into Circuit JSON here:
|
|
4
|
+
// the reply carries that circuit (and the matrix, and a cloned board's source) in place of parts, and the tool makes
|
|
5
|
+
// the board's solid from it. Routes the autorouter found are read from the tool's route cache and handed back.
|
|
3
6
|
import fs from 'node:fs';
|
|
4
7
|
import path from 'node:path';
|
|
5
8
|
import * as shapes from '@rulecad/shapes';
|
|
@@ -20,11 +23,20 @@ for (const k of ['getBuiltinModule', 'binding', '_linkedBinding', 'dlopen', 'kil
|
|
|
20
23
|
}
|
|
21
24
|
const chunks = [];
|
|
22
25
|
for await (const c of process.stdin) chunks.push(c);
|
|
23
|
-
const { js, values, meta, engine, optional, stages, bound } = JSON.parse(Buffer.concat(chunks).toString('utf8')), context = bound?.fixings;
|
|
26
|
+
const { js, values, meta, engine, optional, stages, bound, board } = JSON.parse(Buffer.concat(chunks).toString('utf8')), context = bound?.fixings;
|
|
24
27
|
// A lamina's slow stages: read from the tool's cache (the workspace is readable), and what this run makes handed back
|
|
25
28
|
// with the parts for the tool to write (this process can't)
|
|
26
29
|
const kept = {}; // (what this run made of them)
|
|
27
30
|
if (stages) flexures.laminaCache({ salt: stages.salt, get: (k) => { try { return fs.readFileSync(path.join(stages.dir, `${k}.json`), 'utf8'); } catch { return undefined; } }, put: (k, text) => { kept[k] = text; } });
|
|
31
|
+
// A board's engine: @rulecad/pcb, loaded only for a board design, its mount bound to the workspace's thread sets (as
|
|
32
|
+
// data, like v.fixings), and its routes kept as the stages are
|
|
33
|
+
const routes = {};
|
|
34
|
+
let pcb = null, mounted = false;
|
|
35
|
+
if (board) {
|
|
36
|
+
pcb = await import('@rulecad/pcb');
|
|
37
|
+
if (pcb.routeStore) pcb.routeStore({ get: (k) => { if (!board.routes) return undefined; try { return fs.readFileSync(path.join(board.routes, `${k}.json`), 'utf8'); } catch { return undefined; } }, put: (k, text) => { routes[k] = text; } });
|
|
38
|
+
}
|
|
39
|
+
const engineFor = () => ({ ...pcb, mount: (thread, x, y, o = {}) => { mounted = true; return pcb.mount(thread, x, y, { sets: context?.sets, ...o }); } });
|
|
28
40
|
const stdout = process.stdout, done = (o) => stdout.write(JSON.stringify(o), () => exit(0));
|
|
29
41
|
// stdout carries the result, so what a design prints (console.log, to see a value) goes to stderr, which the tool passes on
|
|
30
42
|
console.log = console.info = console.debug = (...a) => console.error(...a);
|
|
@@ -32,10 +44,14 @@ try {
|
|
|
32
44
|
const mod = await import(js);
|
|
33
45
|
if (typeof mod.main !== 'function') throw Object.assign(new Error('the design has no exported main(v)'), { code: 'design.main' });
|
|
34
46
|
const ops = await shapes.ops(engine || 'jscad'), df = designFixings({ ...(context || {}), ops }); // (v.fixings: bound to the project, as the build's own is)
|
|
35
|
-
const { v, read } = watch(values, { shapes, flexures, gears, motors, frames: designFrames(bound?.frames), fixings: df.fixings, ops }, optional);
|
|
47
|
+
const { v, read } = watch(values, { shapes, flexures, gears, motors, frames: designFrames(bound?.frames), fixings: df.fixings, ops, ...(pcb ? { pcb: engineFor() } : {}) }, optional);
|
|
36
48
|
const { shapes: made, mechanism } = unpack(await mod.main(v));
|
|
37
|
-
const
|
|
38
|
-
|
|
49
|
+
const found = { read: [...read], ...(mechanism ? { mechanism } : {}), ...(df.used() ? { fixings: df.found() } : {}), ...(Object.keys(kept).length ? { stages: kept } : {}) };
|
|
50
|
+
if (pcb) { // a circuit board: its Circuit JSON, for the tool to make the board's solid and files from
|
|
51
|
+
const { board: b, matrix, clone } = made && made.board ? made : { board: made };
|
|
52
|
+
const circuit = await pcb.render(b);
|
|
53
|
+
done({ parts: [], ...found, board: { circuit, ...(matrix ? { matrix } : {}), ...(clone ? { source: clone } : {}) }, ...(mounted ? { mounted } : {}), ...(Object.keys(routes).length ? { routes } : {}) });
|
|
54
|
+
} else done({ parts: named(made, meta).map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...found });
|
|
39
55
|
} catch (e) {
|
|
40
56
|
const line = lineOf(e, js);
|
|
41
57
|
done({ error: { message: e?.message || String(e), ...(line ? { line } : {}), ...(e?.name === 'SyntaxError' ? { syntax: true } : {}), code: e?.code && typeof e.code === 'string' && !/^ERR_/.test(e.code) ? e.code : e?.code === 'ERR_ACCESS_DENIED' ? 'design.sandbox' : 'design.run', ...(e?.code === 'ERR_ACCESS_DENIED' && e.resource ? { resource: e.resource } : {}) } });
|