@rulecad/cad 0.7.97 → 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 +2 -0
- package/CHANGELOG.md +38 -2
- package/EXAMPLES.md +8 -4
- package/README.md +41 -14
- package/bin/cad.mjs +9 -8
- 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/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 +5 -4
- 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/project.schema.json +1 -1
package/lib/design.mjs
CHANGED
|
@@ -12,14 +12,15 @@
|
|
|
12
12
|
// as v.layouts[name] = { …the file, keys (each key's centre and properties), width, depth } (lib/layout.mjs).
|
|
13
13
|
// Boards: "engine": "pcb" in the .json makes main(v) return a tscircuit board ({ board, matrix, clone }, built with v.pcb, as
|
|
14
14
|
// @rulecad/pcb describes); the build then carries its Circuit JSON (circuit) and matrix, and one part: the bare board
|
|
15
|
-
// (its copper is in the 2D views).
|
|
15
|
+
// (its copper is in the 2D views). A board design runs in the sandbox as any design does, with the board engine there:
|
|
16
|
+
// it hands back its circuit as data, and the tool makes the board's solid from it (boardBuild).
|
|
16
17
|
// Builds are cached in .cache/builds/, by everything they're made from (CAD_NO_CACHE=1 to skip), and a lamina's slow
|
|
17
18
|
// stages apart in .cache/stages/ (see stageStore).
|
|
18
19
|
import { spawnSync } from 'node:child_process';
|
|
19
20
|
import { located, lineOf } from './errors.mjs';
|
|
20
21
|
import { host, readJson } from './host.mjs';
|
|
21
22
|
import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
|
|
22
|
-
import {
|
|
23
|
+
import { sandboxed, canSandbox, stageFile, ROUTE_KEY } from './sandbox.mjs';
|
|
23
24
|
export { polygons };
|
|
24
25
|
import fs from 'node:fs';
|
|
25
26
|
import path from 'node:path';
|
|
@@ -38,6 +39,7 @@ import { designFrames, framesContext } from './frames.mjs';
|
|
|
38
39
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
39
40
|
import { engineId, packageVersion, materialise } from './versions.mjs';
|
|
40
41
|
import { satisfies } from '@rulecad/versions';
|
|
42
|
+
import { plainName, isObjectRefName } from './names.mjs';
|
|
41
43
|
|
|
42
44
|
const require = createRequire(import.meta.url);
|
|
43
45
|
const jscad = require('@jscad/modeling');
|
|
@@ -51,11 +53,24 @@ export function locate(ref) {
|
|
|
51
53
|
if (!base.includes(path.sep) || !host.exists(`${base}.json`)) {
|
|
52
54
|
const [project, name] = ref.split('/');
|
|
53
55
|
if (!project || !name) throw new Error(`name a design as <project>/<object>, e.g. keyboard/keycap (got "${ref}")`);
|
|
54
|
-
base = path.join(paths.project(project), 'objects', name);
|
|
56
|
+
base = path.join(paths.project(project), 'objects', plainName(name, 'object name'));
|
|
55
57
|
}
|
|
58
|
+
return designAt(base, variant);
|
|
59
|
+
}
|
|
60
|
+
const designAt = (base, variant) => {
|
|
56
61
|
if (!host.exists(`${base}.json`) || !host.exists(`${base}.js`)) throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
|
|
57
62
|
const dir = path.dirname(path.dirname(base));
|
|
58
63
|
return { project: path.basename(dir), name: path.basename(base), js: `${base}.js`, json: `${base}.json`, dir, ...(variant ? { variant } : {}) };
|
|
64
|
+
};
|
|
65
|
+
/**
|
|
66
|
+
* A design named in a workspace's own file (an assembly's item, a project's "objects", a problem's): `name` is an
|
|
67
|
+
* object of `project`, optionally with :<variant>, and only ever a plain name. Never a path, as locate() also takes
|
|
68
|
+
* from the command line: "../../elsewhere/x" in a file would otherwise read a design outside the workspace.
|
|
69
|
+
* @param {string} project @param {string} name @param {string} [where] the file and field it was read from
|
|
70
|
+
*/
|
|
71
|
+
export function locateIn(project, name, where) {
|
|
72
|
+
const [plain, variant] = String(name).split(':');
|
|
73
|
+
return designAt(path.join(paths.project(project), 'objects', plainName(plain, 'object name', where)), variant);
|
|
59
74
|
}
|
|
60
75
|
|
|
61
76
|
// ---------- objects that read each other ----------
|
|
@@ -65,16 +80,20 @@ export function locate(ref) {
|
|
|
65
80
|
// its version; "macropad/pcb@0.2.0" reads that release instead of the working copy.
|
|
66
81
|
export const isObjectRef = (u) => String(u).includes('/');
|
|
67
82
|
const building = new Set();
|
|
68
|
-
export async function objectSets(d, object) {
|
|
83
|
+
export async function objectSets(d, object, { trusted = false } = {}) {
|
|
69
84
|
const refs = (object.uses || []).filter(isObjectRef), sets = {}, extra = {};
|
|
85
|
+
// Its rule sets (the entries without a slash) become paths, rules/<name>.json: plain names only, said with the file they're in
|
|
86
|
+
for (const u of object.uses || []) if (!isObjectRef(u)) plainName(u, 'rule set name', `${path.relative(WS, d.json)}, in its "uses"`);
|
|
70
87
|
if (!refs.length) return { sets, extra };
|
|
71
88
|
const self = `${d.project}/${d.name}`;
|
|
72
89
|
building.add(self);
|
|
73
90
|
try {
|
|
74
91
|
for (const u of refs) {
|
|
92
|
+
// (from the object's file: a design reference, never a path that locate() would also take)
|
|
93
|
+
if (!isObjectRefName(u)) throw new Error(`${path.relative(WS, d.json)}: "${u}" in its "uses" is not a design reference. Name another object as <project>/<object>, both plain names (letters, digits, - and _), optionally with :<variant> and @<version>, as keyboard/keycap@^1.0.0`);
|
|
75
94
|
const [ref, want] = u.split('@'), exact = /^\d+\.\d+\.\d+$/.test(want || '');
|
|
76
95
|
if (building.has(ref)) throw new Error(`${self} and ${ref} read each other's numbers: one of them has to give its numbers to the other, not both`);
|
|
77
|
-
const base =
|
|
96
|
+
const base = locateIn(...ref.split('/')), b = await build(exact ? materialise(base, want) : base, {}, { trusted }), version = b.object.version;
|
|
78
97
|
if (want && !exact && !satisfies(version, want)) throw new Error(`${self} uses ${ref} ${want}, but ${ref} is ${version}: change the range, or the design to suit ${version}`);
|
|
79
98
|
const units = Object.fromEntries(Object.entries(b.object.variables || {}).map(([k, x]) => [k, x.unit]));
|
|
80
99
|
const rules = {};
|
|
@@ -133,8 +152,9 @@ const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
|
133
152
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
134
153
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
|
135
154
|
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))), flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))), gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))), motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))), framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))), fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
|
|
136
|
-
// (every module of a helper package but its tests: they change nothing a design builds
|
|
137
|
-
|
|
155
|
+
// (every module of a helper package but its tests: they change nothing a design builds; nor a dot-file, which is a
|
|
156
|
+
// package's tests writing a scratch module beside its sources, there for a moment and gone mid-read)
|
|
157
|
+
const helperSources = (dir) => fs.readdirSync(dir).filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.')).sort().map((f) => source(pathToFileURL(path.join(dir, f)).href)).join('');
|
|
138
158
|
const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
|
|
139
159
|
// (as one digest, so each build's key hashes a line and not a megabyte of source)
|
|
140
160
|
const own = crypto.createHash('sha256').update(source(import.meta.url) + source('./fixings.mjs') + source('./frames.mjs') + helperSources(framesDir) + helperSources(shapesDir) + helperSources(flexuresDir) + helperSources(gearsDir) + helperSources(motorsDir) + helperSources(fixingsDir) + helperSources(feaDir) + packageVersion('@jscad/modeling')).digest('hex'); // every shapes module, not just its entry
|
|
@@ -142,12 +162,39 @@ const own = crypto.createHash('sha256').update(source(import.meta.url) + source(
|
|
|
142
162
|
// and their own inputs, so a build that changes only what comes after them (a strap, a check, a rule's words) has them
|
|
143
163
|
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes them
|
|
144
164
|
const STAGES = paths.cache('stages'), stageSalt = crypto.createHash('sha256').update(helperSources(flexuresDir) + helperSources(feaDir)).digest('hex');
|
|
165
|
+
// A workspace cloned from elsewhere may hold links of its own in .cache/: a cache file that is a link to a file outside
|
|
166
|
+
// (the trust list, say) would have the tool write what a sandboxed design handed back through it, and a cache folder
|
|
167
|
+
// that is a link would have cache files written, and pruned, somewhere else. So a cache file is written only when it
|
|
168
|
+
// and every folder between it and the workspace are a plain file and plain folders, or not there yet.
|
|
169
|
+
function ownCacheFile(file, root = WS) {
|
|
170
|
+
if (host.name === 'memory') return true; // (held in memory: nothing on disk to follow)
|
|
171
|
+
const top = path.resolve(root);
|
|
172
|
+
let p = path.resolve(file);
|
|
173
|
+
if (!p.startsWith(top + path.sep)) return false;
|
|
174
|
+
for (let first = true; p !== top; p = path.dirname(p), first = false) {
|
|
175
|
+
let st;
|
|
176
|
+
try { st = fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') continue; return false; }
|
|
177
|
+
if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
|
|
178
|
+
}
|
|
179
|
+
return true;
|
|
180
|
+
}
|
|
145
181
|
const stageStore = () => ({
|
|
146
182
|
salt: stageSalt,
|
|
147
|
-
|
|
148
|
-
|
|
183
|
+
// (stageFile: a key that would put its file anywhere but directly in .cache/stages/ has none, a second guard after the
|
|
184
|
+
// sandbox's own check of the keys a design hands back)
|
|
185
|
+
get: (k) => { const f = stageFile(STAGES, k); if (!f || process.env.CAD_NO_CACHE || !host.exists(f)) return undefined; try { host.touch(f); } catch {} return host.readText(f); }, // (CAD_NO_CACHE: computed afresh, and kept)
|
|
186
|
+
put: (k, text) => { const f = stageFile(STAGES, k); if (!f || !ownCacheFile(f)) return; try { prune(STAGES, STAGES_KEEP); host.writeText(f, text); } catch {} }, // (a cache that can't be written is only slower)
|
|
149
187
|
});
|
|
150
188
|
const STAGES_KEEP = 60; // (a launcher's physics is 5 MB, its probe 9)
|
|
189
|
+
// The autorouter's results, for a board built in the sandbox: the child reads them from the route cache's folder, and
|
|
190
|
+
// what it routes comes back to be written here, under a key of the route cache's form only (ROUTE_KEY), directly in
|
|
191
|
+
// the folder, never through a link (ownCacheFile). None with CAD_NO_CACHE.
|
|
192
|
+
const routeStore = () => {
|
|
193
|
+
const dir = process.env.RULECAD_ROUTE_CACHE;
|
|
194
|
+
if (!dir) return null;
|
|
195
|
+
const within = path.relative(WS, path.resolve(dir)), root = !path.isAbsolute(within) && !within.startsWith('..') ? WS : dir; // (a folder of the user's own choosing elsewhere: its files, not what leads to it)
|
|
196
|
+
return { dir, put: (k, text) => { const f = ROUTE_KEY.test(k) && stageFile(dir, k); if (!f || !ownCacheFile(f, root)) return; try { host.writeText(f, text); } catch {} } }; // (a cache that can't be written is only slower; kept as @rulecad/pcb keeps its own, unpruned)
|
|
197
|
+
};
|
|
151
198
|
export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
|
|
152
199
|
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@rulecad\/pcb/.test(e.message)) throw new Error('boards need the board engine: npm install @rulecad/pcb');
|
|
153
200
|
throw e;
|
|
@@ -163,7 +210,7 @@ export function fixingsContext(d) {
|
|
|
163
210
|
for (const f of host.list(dir).filter((x) => x.endsWith('.json')).sort()) {
|
|
164
211
|
try { const raw = host.readText(path.join(dir, f)), s = JSON.parse(raw); if (s && s.rules && typeof s.rules === 'object') { sets[s.name ?? f.slice(0, -5)] = s; text.push(raw); } } catch {} // (a broken set is cad check's to name, where a design uses it)
|
|
165
212
|
}
|
|
166
|
-
const name = printerOf(d.project), peek = (n) => { const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x)); if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`); return readJson(f); };
|
|
213
|
+
const name = printerOf(d.project), peek = (n) => { plainName(n, 'rule set name'); const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x)); if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`); return readJson(f); };
|
|
167
214
|
let printer = null;
|
|
168
215
|
try { // (a printer with no rule set is said where a print is checked; fixings then draws for the kit's)
|
|
169
216
|
const set = peek(name), values = resolveWith({ uses: [name] }, { load: peek }).values[name];
|
|
@@ -198,13 +245,63 @@ function syntaxAt(e, d) {
|
|
|
198
245
|
return e;
|
|
199
246
|
}
|
|
200
247
|
|
|
201
|
-
//
|
|
248
|
+
// Who may run a design in the tool's own process, outside the sandbox. On Node's file system (the CLI) every design,
|
|
249
|
+
// a board's too, runs in the sandbox unless the workspace trusts its designs (sandbox.mjs's sandboxed: "sandbox": false
|
|
250
|
+
// and cad trust, or CAD_TRUST=1), and is run here only then. A host of another kind (memoryHost: a workspace in memory,
|
|
251
|
+
// for tests and later a browser or editor's server) has no trust list of its own: its designs run in the sandbox
|
|
252
|
+
// through its runDesign hook (host.mjs), and here only when the caller says it trusts them:
|
|
253
|
+
// build(d, set, { trusted: true }).
|
|
254
|
+
function runsHere(trusted) {
|
|
255
|
+
if (host.name === 'node') return !sandboxed();
|
|
256
|
+
return trusted === true || !(host.runDesign && canSandbox()); // (only true itself: not a string or number a caller passed on)
|
|
257
|
+
}
|
|
258
|
+
// A workspace's trust names its folder, so it covers the designs in that folder: one elsewhere (a path to another
|
|
259
|
+
// workspace's file, or a link out of it) is refused here, to be run from its own workspace once that is trusted.
|
|
260
|
+
function mayRunHere(d, trusted) {
|
|
261
|
+
if (host.name === 'node') {
|
|
262
|
+
const real = (f) => { try { return fs.realpathSync(f); } catch { return path.resolve(f); } }; // (one folder by any spelling: a link, /var and /private/var)
|
|
263
|
+
const outside = (f) => { const where = path.relative(real(WS), real(f)); return where === '..' || where.startsWith(`..${path.sep}`) || path.isAbsolute(where); };
|
|
264
|
+
const away = [d.json, d.js].find(outside); // (the .js is the code that runs: a link to one elsewhere is elsewhere)
|
|
265
|
+
if (away && process.env.CAD_TRUST !== '1') {
|
|
266
|
+
throw Object.assign(new Error(`${real(away)} is a design outside this workspace (${WS}): this workspace's trust covers only its own designs. Run it from its own workspace (cd there, read its designs, and run cad trust there if you trust them); until then, it isn't run`), { code: 'workspace.untrusted' });
|
|
267
|
+
}
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (trusted === true) return;
|
|
271
|
+
throw Object.assign(new Error(`${path.relative(WS, d.json).split(path.sep).join('/')} would run in the tool's own process, without the sandbox: this workspace is held ${host.name === 'memory' ? 'in memory' : `by the ${host.name} host`}, where designs can't be sandboxed${host.runDesign ? ' (this Node has no permission model)' : ''}. Build it with { trusted: true } only if you trust its designs; until then, it isn't run`), { code: 'workspace.untrusted' });
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// A board's build from its Circuit JSON, wherever the design ran: what it tells the parts around it (outline, holes,
|
|
275
|
+
// the module's place) goes into its values, and its solid is made here, with its parts' 3D models (meshes cad clone
|
|
276
|
+
// fetched into the workspace's models/: a design never reads files; cad does). The circuit may be a sandboxed design's
|
|
277
|
+
// reply, so a model is read only from a plain relative .json path inside the workspace, and only where it really is
|
|
278
|
+
// inside it: a link in the workspace (models/part.json leading to a file of the user's elsewhere) is not followed out.
|
|
279
|
+
function boardBuild(pcb, board, values, object, d) {
|
|
280
|
+
Object.assign(values, pcb.outputs(board.circuit, board.matrix));
|
|
281
|
+
const meshes = {};
|
|
282
|
+
const inWs = (file) => { // (on Node's file system, by real paths: /var and /private/var are one folder, a link out is out)
|
|
283
|
+
if (host.name !== 'node') return true;
|
|
284
|
+
try { const rel = path.relative(fs.realpathSync(WS), fs.realpathSync(file)); return !!rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..'); } catch { return false; }
|
|
285
|
+
};
|
|
286
|
+
for (const c of board.circuit.filter((e) => e.type === 'cad_component' && e.rulecad_model?.mesh)) {
|
|
287
|
+
const f = c.rulecad_model.mesh;
|
|
288
|
+
if (typeof f !== 'string' || f in meshes) continue;
|
|
289
|
+
const file = path.resolve(WS, f), rel = path.relative(WS, file);
|
|
290
|
+
const plainPath = f.endsWith('.json') && !path.isAbsolute(f) && rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..');
|
|
291
|
+
meshes[f] = plainPath && host.exists(file) && inWs(file) ? JSON.parse(host.readText(file)).triangles : null;
|
|
292
|
+
}
|
|
293
|
+
const made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth, models: meshes });
|
|
294
|
+
try { return named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// build(design, set, { mirror, trusted }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
|
|
298
|
+
// trusted: the caller trusts the design, for a host other than Node's file system (memoryHost): run it in this process, not the sandbox (runsHere)
|
|
202
299
|
// fixings: what the design's calls to v.fixings found (each hole and seat, what it was drawn to and rests on), as findings
|
|
203
300
|
// parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
|
|
204
|
-
export async function build(d, set = {}, { mirror = false } = {}) {
|
|
301
|
+
export async function build(d, set = {}, { mirror = false, trusted = false } = {}) {
|
|
205
302
|
const object = readObject(d);
|
|
206
303
|
set = variantSet(d, object, set);
|
|
207
|
-
const refs = await objectSets(d, object); // other objects' numbers, when it reads them
|
|
304
|
+
const refs = await objectSets(d, object, { trusted }); // other objects' numbers, when it reads them
|
|
208
305
|
const sets = { ...(d.rulesDir ? Object.fromEntries((object.uses || []).filter((u) => !isObjectRef(u)).map((u) => [u, loadRuleSet(u, d.rulesDir)])) : {}), ...refs.sets }; // a release's own rules
|
|
209
306
|
const display = mirror ? object.mirror || {} : {};
|
|
210
307
|
let resolved;
|
|
@@ -241,14 +338,18 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
241
338
|
return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: known(c.fixed), ...(c.fixings ? { fixings: c.fixings } : {}), ...(c.mechanism ? { mechanism: c.mechanism } : {}), ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}) };
|
|
242
339
|
}
|
|
243
340
|
|
|
244
|
-
// A
|
|
245
|
-
//
|
|
341
|
+
// A design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach the
|
|
342
|
+
// network), a board design with the board engine there, unless the workspace trusts its designs (runsHere, above)
|
|
246
343
|
const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
|
|
247
344
|
let parts, board = null, read, mechanism = null, fixings = null, mounted = false;
|
|
248
345
|
const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
|
|
249
346
|
const stages = stageStore();
|
|
250
|
-
if (!
|
|
251
|
-
|
|
347
|
+
if (!runsHere(trusted)) {
|
|
348
|
+
const r = await host.runDesign({ d, values, meta: object.parts || {}, engine: booleans(object), optional, stages, bound: { frames: framed, fixings: fixed().context }, board: pcb ? { routes: routeStore() } : null }).catch((e) => { throw syntaxAt(e, d); });
|
|
349
|
+
({ parts, read, mechanism, fixings } = r);
|
|
350
|
+
if (pcb) { board = r.board; mounted = r.mounted; parts = boardBuild(pcb, board, values, object, d); }
|
|
351
|
+
} else {
|
|
352
|
+
mayRunHere(d, trusted);
|
|
252
353
|
flexures.laminaCache(stages);
|
|
253
354
|
const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
|
|
254
355
|
// Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
|
|
@@ -264,23 +365,15 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
264
365
|
read = w.read;
|
|
265
366
|
let made;
|
|
266
367
|
try { ({ shapes: made, mechanism } = unpack(await mod.main(w.v))); } catch (e) { throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined }); }
|
|
267
|
-
if (
|
|
368
|
+
if (pcb) { // a circuit board: tscircuit builds it, and the bare board is its one part
|
|
268
369
|
const { board: b, matrix, clone } = made && made.board ? made : { board: made }; // clone: a cloned board's { circuit, arranged }, for its checks
|
|
269
370
|
board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}), ...(clone ? { source: clone } : {}) };
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
const meshes = {};
|
|
273
|
-
for (const c of board.circuit.filter((e) => e.type === 'cad_component' && e.rulecad_model?.mesh)) {
|
|
274
|
-
const f = c.rulecad_model.mesh;
|
|
275
|
-
if (!(f in meshes)) meshes[f] = host.exists(path.join(WS, f)) ? JSON.parse(host.readText(path.join(WS, f))).triangles : null;
|
|
276
|
-
}
|
|
277
|
-
made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth, models: meshes });
|
|
278
|
-
}
|
|
279
|
-
try { parts = named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
|
|
371
|
+
parts = boardBuild(pcb, board, values, object, d);
|
|
372
|
+
} else try { parts = named(made, object.parts || {}); } catch (e) { throw located(e, d.js, 'design.run'); }
|
|
280
373
|
if (df.used()) fixings = df.found();
|
|
281
374
|
}
|
|
282
375
|
for (const e of entries) if (read.has(e.name)) e.used = true;
|
|
283
|
-
try {
|
|
376
|
+
if (ownCacheFile(hit)) try {
|
|
284
377
|
prune();
|
|
285
378
|
host.writeText(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}), ...(mechanism ? { mechanism } : {}), ...(fixings || mounted ? { fixed: fixed().hash } : {}), ...(fixings ? { fixings } : {}) }));
|
|
286
379
|
} catch {} // a cache that can't be written is only slower
|
package/lib/edit.mjs
CHANGED
|
@@ -7,6 +7,7 @@ import { setAt, appendAt, getAt, removeAt } from './jsonedit.mjs';
|
|
|
7
7
|
import { validate, schema } from './schema.mjs';
|
|
8
8
|
import { CadError } from './errors.mjs';
|
|
9
9
|
import { paths } from './workspace.mjs';
|
|
10
|
+
import { plainName, isPlainName } from './names.mjs';
|
|
10
11
|
import { locate, readObject, objectSets } from './design.mjs';
|
|
11
12
|
import { resolve, evaluate, peekRuleSet } from './rules.mjs';
|
|
12
13
|
import { expandFrame, frameText } from './framegen.mjs';
|
|
@@ -58,7 +59,7 @@ export async function setVariables(ref, changes, { create = false, dryRun = fals
|
|
|
58
59
|
}
|
|
59
60
|
|
|
60
61
|
const assemblyFile = (ref) => {
|
|
61
|
-
const [project, name] = ref.split('/'), file = path.join(paths.project(project), 'assemblies', `${name}.json`);
|
|
62
|
+
const [project, name] = ref.split('/'), file = path.join(paths.project(project), 'assemblies', `${plainName(name, 'assembly name')}.json`); // (from the command line: never ../, nor ..\ on Windows)
|
|
62
63
|
if (!fs.existsSync(file)) throw new CadError('assembly.missing', `no assembly at ${path.relative(paths.project(project), file)}`, { file });
|
|
63
64
|
return file;
|
|
64
65
|
};
|
|
@@ -197,8 +198,8 @@ function entryProblems(what, entry, { ref, file, known, self }) {
|
|
|
197
198
|
if (!it && made(item)) continue; // a guide's part or a repeated item's copy (key-0-3)
|
|
198
199
|
if (!it) throw new CadError('edit.part', `fit ${side}: no item "${item}" in ${ref} (items: ${list(ids)})`, { file });
|
|
199
200
|
if (it.object) {
|
|
200
|
-
const [project] = ref.split('/'), obj = path.join(paths.project(project), 'objects', `${
|
|
201
|
-
const parts = fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
|
|
201
|
+
const [project] = ref.split('/'), own = String(it.object).split(/[@:]/)[0], obj = isPlainName(own) && path.join(paths.project(project), 'objects', `${own}.json`); // (a name from the assembly's file: read only where it is plain)
|
|
202
|
+
const parts = obj && fs.existsSync(obj) ? Object.keys(JSON.parse(fs.readFileSync(obj, 'utf8')).parts || { body: {} }) : null;
|
|
202
203
|
if (parts && !parts.includes(part)) throw new CadError('edit.part', `fit ${side}: ${it.object} has no part "${part}" (parts: ${parts.join(', ')})`, { file });
|
|
203
204
|
}
|
|
204
205
|
}
|
package/lib/fasten.mjs
CHANGED
|
@@ -801,6 +801,14 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
801
801
|
const inEnd = L - grip, zTip = zHead + L, inThread = end.slot ? zTip - end.zThr : inEnd; // (a slot nut's thread starts in its tongue, in the opening)
|
|
802
802
|
sc.dir = D; sc.engaged = end.kind ? r3(Math.max(0, Math.min(inThread, avail))) : 0; sc.endKind = end.kind ?? null; sc.intoMaterial = intoMat.known ? intoMat.name : null; sc.bear = (washer ? washer.diameter : head?.across ?? fx.major * 2) / 2;
|
|
803
803
|
sc.length = L; sc.model = model; sc.between = [at(zHead), at(zTip)]; sc.end = end.kind ?? null;
|
|
804
|
+
// a screw into a thread in plastic (a pilot, a tapped or a printed thread): the most torque to tighten it to keeps its
|
|
805
|
+
// preload to the thread's stripping load over fixings.load_margin, as screwLoad does. A stripping load is an estimate
|
|
806
|
+
// and a torque's clamp scatters by a quarter to a third, so the seat alone may ask more than the thread takes
|
|
807
|
+
let threadMost = null; // { torque, strip }: rounded down to the hundredth, as screwLoad's
|
|
808
|
+
if (!fx.printed && ['pilot', 'tap', 'thread'].includes(sc.endKind) && sc.intoMaterial && sc.engaged > 0) {
|
|
809
|
+
try { const strip = F.stripping(fx, { depth: sc.engaged, material: sc.intoMaterial }).strip; threadMost = { strip, torque: Math.floor(((DEFAULTS.nut_factor.value * fx.major * strip) / DEFAULTS.load_margin.value / 1000) * 100 + 1e-9) / 100 }; } catch { threadMost = null; }
|
|
810
|
+
}
|
|
811
|
+
const threadSays = (t) => (threadMost && threadMost.torque < t ? `; its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate, so tighten to ${mm(threadMost.torque)} N m at most, half that` : ''); // (where the thread holds a screw to less than the seat)
|
|
804
812
|
const lenValues = { length: L, grip: r3(grip), into: r3(inEnd) }, under = `${mm2(grip)} mm under its head${washer ? ' (its washer with it)' : ''}`;
|
|
805
813
|
const wouldDo = pick && pick.length !== L ? `${pick.name} would do` : null;
|
|
806
814
|
if (given == null) {
|
|
@@ -849,7 +857,7 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
849
857
|
// the tightening is the least of that and a screw tightened fully (three quarters of its proof load)
|
|
850
858
|
const bt = lipsTake(F, s, x.lips.item, fx, across, lips.opening), v2 = bt ? { ...values, area: bt.area, limit: bt.limit, force: bt.force, torque: bt.torque } : values;
|
|
851
859
|
if (bt) { sc.most = bt.torque; sc.seatForce = bt.force; }
|
|
852
|
-
say('fasten.seat', 'pass', `the head, ${mm(across)} mm across, bears on the lips of ${of} ${lips.inside ? `from inside, in its ${mm(lips.cavityWidth)} mm cavity (${mm(head.height)} mm of the ${mm(lips.room)} mm under the lips)` : 'from outside'}, on each side of its ${mm(lips.opening)} mm opening${bt ? `; ${bt.text}` : ''}`, v2);
|
|
860
|
+
say('fasten.seat', 'pass', `the head, ${mm(across)} mm across, bears on the lips of ${of} ${lips.inside ? `from inside, in its ${mm(lips.cavityWidth)} mm cavity (${mm(head.height)} mm of the ${mm(lips.room)} mm under the lips)` : 'from outside'}, on each side of its ${mm(lips.opening)} mm opening${bt ? `; ${bt.text}${threadSays(bt.torque)}` : ''}`, v2);
|
|
853
861
|
}
|
|
854
862
|
} else if (A) {
|
|
855
863
|
const seatPart = A.segs[bore0], near = seatPart.of.near, zLocal = (z) => (flip ? -z : z), bearR = (washer ? washer.diameter : head.across) / 2, boreR = seatPart.a.free, seatMat = matOf(A); // (boreR: the hole's mouth at the seat, a lead-in with it)
|
|
@@ -878,7 +886,7 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
878
886
|
const takes = st.limit * mine, K = DEFAULTS.nut_factor.value, torqueOf = (N) => (K * fx.major * N) / 1000, v2 = { ...values, area: +mine.toFixed(2), limit: st.limit, force: +takes.toFixed(1), ...(fx.printed ? {} : { torque: +torqueOf(takes).toFixed(3) }) }; // (a printed bolt: no tightening torque)
|
|
879
887
|
if (!fx.printed) { sc.most = +torqueOf(takes).toFixed(2); sc.seatForce = takes; } // (a printed bolt is done up by hand: no torque to tighten to)
|
|
880
888
|
if (torque == null && fx.printed) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N. A printed bolt is done up by hand, with no torque to tighten to`, v2);
|
|
881
|
-
else if (torque == null) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m${!washer && onWasher && sunk <= 0.01 ? `: the ${fx.thread} washer would raise that to ${mm(+(st.limit * onWasher).toFixed(0))} N (${mm(+torqueOf(st.limit * onWasher).toFixed(2))} N m)` : ''}`, v2);
|
|
889
|
+
else if (torque == null) say('fasten.seat', 'pass', `${where}; on ${st.material} (${mm(st.limit)} MPa) its ${mm(+mine.toFixed(1))} mm² takes ${mm(+takes.toFixed(0))} N, a tightening of ${mm(+torqueOf(takes).toFixed(2))} N m${!washer && onWasher && sunk <= 0.01 && !(threadMost && threadMost.torque <= +torqueOf(takes).toFixed(2)) ? `: the ${fx.thread} washer would raise that to ${mm(+(st.limit * onWasher).toFixed(0))} N (${mm(+torqueOf(st.limit * onWasher).toFixed(2))} N m)` : ''}${threadSays(+torqueOf(takes).toFixed(2))}`, v2);
|
|
882
890
|
else {
|
|
883
891
|
const p = st.force / mine, within = p <= st.limit + 1e-9, pw = onWasher ? st.force / onWasher : null;
|
|
884
892
|
// A printed bolt turned to a torque by hand: the clamp is T = K d F with steel's nut factor, an estimate for a
|
|
@@ -890,12 +898,14 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
890
898
|
{ torque, force: st.force, breaking: bolt.breaking, margin: +(bolt.breaking / st.force).toFixed(2), most: safe });
|
|
891
899
|
}
|
|
892
900
|
if (within) say('fasten.seat', 'pass', `${where}; ${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}, ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa`, { ...v2, pressure: +p.toFixed(1) });
|
|
893
|
-
else say('fasten.seat', 'fail', `${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}: ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa. ${!washer && pw != null && pw <= st.limit && sunk <= 0.01 ? `The ${fx.thread} washer, ${mm(st.washer.diameter)} mm across, brings it to ${mm(+pw.toFixed(1))} MPa, within: give "washer": true` : `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m): ${fx.printed ? 'turn it no further than that' : 'tighten to that'}, or spread the load wider`}`, { ...v2, pressure: +p.toFixed(1), ...(pw != null ? { washer: +pw.toFixed(1) } : {}) });
|
|
901
|
+
else say('fasten.seat', 'fail', `${turned ?? `at ${mm(torque)} N m the screw clamps with ${mm(st.force)} N`}: ${mm(+p.toFixed(1))} MPa under the ${washer ? 'washer' : 'head'} on ${st.material}, whose strength is ${mm(st.limit)} MPa. ${!washer && pw != null && pw <= st.limit && sunk <= 0.01 && !(threadMost && threadMost.torque < torque) ? `The ${fx.thread} washer, ${mm(st.washer.diameter)} mm across, brings it to ${mm(+pw.toFixed(1))} MPa, within: give "washer": true` : threadMost && threadMost.torque < +torqueOf(takes).toFixed(2) ? `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m), and its thread in ${sc.intoMaterial} strips at about ${mm(+threadMost.strip.toFixed(0))} N, an estimate: tighten to ${mm(threadMost.torque)} N m at most, half that` : `The seat takes ${mm(+takes.toFixed(0))} N (${mm(+torqueOf(takes).toFixed(2))} N m): ${fx.printed ? 'turn it no further than that' : 'tighten to that'}, or spread the load wider`}`, { ...v2, pressure: +p.toFixed(1), ...(pw != null ? { washer: +pw.toFixed(1) } : {}) });
|
|
894
902
|
}
|
|
895
903
|
}
|
|
896
904
|
}
|
|
897
905
|
}
|
|
898
906
|
}
|
|
907
|
+
// the torque to tighten to: the seat's take, held to half what a thread in plastic strips at
|
|
908
|
+
if (sc.most != null && threadMost && threadMost.torque < sc.most) { sc.most = threadMost.torque; sc.mostBy = 'thread'; }
|
|
899
909
|
|
|
900
910
|
// The hardware, each piece where it sits: its own frame, the item it moves with, the way it comes out, what it may overlap
|
|
901
911
|
const host = (r) => r.parts[0], up = D.map((c) => -c), piece = (kind, m, o, P, Z, r, lift, allow, X) => sc.hardware.push({ kind, shape: shapeOf(F, kind, m, o), M: standing(P, Z, X), host: host(r), lift, allow });
|
|
@@ -932,9 +942,11 @@ export function fastenOf(s, worlds, opts = {}) {
|
|
|
932
942
|
}
|
|
933
943
|
const names = new Map();
|
|
934
944
|
for (const h of hardware.filter((o) => o.fasten === k)) names.set(h.name, (names.get(h.name) ?? 0) + 1);
|
|
935
|
-
// the screws' lines carry the key that turns them and how tight: the torque given, or the most the seat under the head
|
|
945
|
+
// the screws' lines carry the key that turns them and how tight: the torque given, or the most the seat under the head
|
|
946
|
+
// takes, held to half what a thread in plastic strips at
|
|
936
947
|
const keys = [...new Set(rel.screws.map((sc) => sc.tool).filter(Boolean))], most = rel.screws.map((sc) => sc.most).filter((t) => t != null);
|
|
937
|
-
const
|
|
948
|
+
const least = most.length ? Math.min(...most) : null, byThread = least != null && rel.screws.some((sc) => sc.most === least && sc.mostBy === 'thread'); // (the least of the seats' and the threads' takes)
|
|
949
|
+
const tighten = torque != null ? { torque, given: true, ...(fx.printed ? { hand: true } : {}) } : least != null ? { torque: least, given: false, ...(byThread ? { thread: true } : {}) } : null;
|
|
938
950
|
const lines = [...names].map(([fastener, n]) => ({ fastener, count: n, ...(rel.screws.some((sc) => sc.model?.name === fastener) ? { ...(keys.length ? { key: keys.join(' or ') } : {}), ...(tighten ? { tighten } : {}) } : {}) }));
|
|
939
951
|
through.forEach((t, j) => fits.push({ a: t, b: slotAt ? slotAt.item : x.into, fastens: true, silent: true, fasten: k, note: x.note || `${t} fastened to ${x.into}`, ...(j === 0 && lines[0] ? lines[0] : {}) }));
|
|
940
952
|
if (!through.length && lines[0]) fits.push({ a: x.into, b: x.into, silent: true, fasten: k, note: label, ...lines[0] });
|
|
@@ -1003,7 +1015,8 @@ function loadOf(s, worlds, rel, list, { F, fx, ids, material }) {
|
|
|
1003
1015
|
return { sc, tension: pick.tension, shear: pick.shear, r };
|
|
1004
1016
|
});
|
|
1005
1017
|
const share = torques.length ? Math.max(...screwGroup(places, { moment: [0, 0, torques.reduce((t, q) => t + q.about, 0)] }).screws.map((x) => x.shear)) : null;
|
|
1006
|
-
|
|
1018
|
+
// (worst: at the same margin, the screw pulled harder, since a thread's margin counts its preload and an unloaded screw can tie)
|
|
1019
|
+
const worst = screws.reduce((a, b) => (b.r.margin < a.r.margin || (b.r.margin === a.r.margin && b.tension > a.tension) ? b : a)), slip = screws.filter((x) => x.r.margins.slip != null).reduce((a, b) => (!a || b.r.margins.slip < a.r.margins.slip ? b : a), null);
|
|
1007
1020
|
const tighten = rel.torque == null && !fx.printed ? Math.min(...screws.map((x) => x.r.preload.torque)) : null; // (a printed bolt is done up by hand)
|
|
1008
1021
|
const rests = [...new Map(screws.flatMap((x) => x.r.rests).filter((q) => q.kind === 'estimate' || q.kind === 'community').map((q) => [q.name, q])).values()].map((q) => q.name);
|
|
1009
1022
|
return { beyond: [...beyond].filter((k) => k >= 0).map((k) => ids[k]), kg, hung: hung.length, force: Fw, torques, share, screws, worst, slip, tighten, rests, line: cases[0].line, turns: cases.map((gp) => gp.turns).find((t) => t != null) ?? null };
|
package/lib/framebuild.mjs
CHANGED
|
@@ -302,16 +302,17 @@ function buildFrame(s) {
|
|
|
302
302
|
});
|
|
303
303
|
// a join made before its bay is squared is left snug, and tightened at that square step, which says so too
|
|
304
304
|
steps.forEach((x, i) => { if (x.kind !== 'join' || !x.joins?.length) return; const sq = steps.slice(i + 1).find((y) => y.kind === 'square'); if (sq) x.lines = [...(x.lines ?? []), `Snug for now: tightened to its torque at step ${sq.n}, once square`]; });
|
|
305
|
-
// the tightening of each kind of join: the least its screws' seats take, or the torque given
|
|
305
|
+
// the tightening of each kind of join: the least its screws' seats take, or the torque given (thread: where that
|
|
306
|
+
// least is half what a thread in plastic strips at)
|
|
306
307
|
const byKind = new Map();
|
|
307
308
|
for (const j of joins) for (const f of s.fits.filter((q) => j.fasten.includes(q.fasten) && q.tighten)) {
|
|
308
|
-
const k = byKind.get(j.kind) ?? { kind: j.kind, joins: 0, fasteners: new Set(), keys: new Set(), torque: Infinity, given: false, load: false };
|
|
309
|
-
k.torque = Math.min(k.torque, f.tighten.torque); k.given ||= !!f.tighten.given; k.load ||= !!f.tighten.load; if (f.fastener) k.fasteners.add(f.fastener); if (f.key) k.keys.add(f.key);
|
|
309
|
+
const k = byKind.get(j.kind) ?? { kind: j.kind, joins: 0, fasteners: new Set(), keys: new Set(), torque: Infinity, given: false, load: false, thread: false };
|
|
310
|
+
k.thread = f.tighten.torque < k.torque ? !!f.tighten.thread : k.thread || (f.tighten.torque === k.torque && !!f.tighten.thread); k.torque = Math.min(k.torque, f.tighten.torque); k.given ||= !!f.tighten.given; k.load ||= !!f.tighten.load; if (f.fastener) k.fasteners.add(f.fastener); if (f.key) k.keys.add(f.key);
|
|
310
311
|
byKind.set(j.kind, k);
|
|
311
312
|
}
|
|
312
313
|
for (const j of joins) if (byKind.has(j.kind)) byKind.get(j.kind).joins++;
|
|
313
314
|
const torques = [...byKind.values()].map((k) => ({ kind: k.kind, joins: k.joins, fasteners: [...k.fasteners], key: [...k.keys].join(' or '), torque: k.torque,
|
|
314
|
-
why: k.given ? 'as given' : k.load ? 'what the joint\'s load leaves the thread' : 'at most: what the seat under the head takes (a slot\'s lips under a blind join\'s head, an estimate), or the screw tightened fully, the less' }));
|
|
315
|
+
why: k.given ? 'as given' : k.load ? 'what the joint\'s load leaves the thread' : k.thread ? 'at most: half what the thread in plastic is estimated to strip at, less than the seat under the head takes' : 'at most: what the seat under the head takes (a slot\'s lips under a blind join\'s head, an estimate), or the screw tightened fully, the less' }));
|
|
315
316
|
return { steps, torques };
|
|
316
317
|
}
|
|
317
318
|
}
|
package/lib/host.mjs
CHANGED
|
@@ -3,8 +3,16 @@
|
|
|
3
3
|
// another with useHost: memoryHost(files) keeps a workspace in memory, reading anything outside it (the tool's
|
|
4
4
|
// packages, the published rule sets) from disk.
|
|
5
5
|
// host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file)
|
|
6
|
-
// host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main)
|
|
6
|
+
// host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main), for a design run in the
|
|
7
|
+
// tool's own process (a trusted one)
|
|
8
|
+
// host.runDesign(request): run a design in the sandbox, another process that can't write files, start programs or
|
|
9
|
+
// reach the network (sandbox.mjs's runSandboxed, whose request this is). build() uses it for every design it doesn't
|
|
10
|
+
// run in its own process, a board's too, so a host for a browser or an editor's server never runs a design's code in
|
|
11
|
+
// the server itself. Node's host runs the design where it is; memoryHost copies the design's project from memory into
|
|
12
|
+
// a temporary folder for the sandbox to read, and removes it after. A host without runDesign runs a design only when
|
|
13
|
+
// the caller trusts it (build's { trusted: true }).
|
|
7
14
|
import fs from 'node:fs';
|
|
15
|
+
import os from 'node:os';
|
|
8
16
|
import path from 'node:path';
|
|
9
17
|
import { createRequire } from 'node:module';
|
|
10
18
|
import { pathToFileURL } from 'node:url';
|
|
@@ -21,6 +29,7 @@ export const nodeHost = {
|
|
|
21
29
|
remove: (f) => fs.rmSync(f, { force: true }),
|
|
22
30
|
touch: (f) => { const now = new Date(); fs.utimesSync(f, now, now); },
|
|
23
31
|
loadModule: (f) => import(`${pathToFileURL(f).href}?t=${fs.statSync(f).mtimeMs}`), // a fresh copy after each edit
|
|
32
|
+
runDesign: (request) => import('./sandbox.mjs').then((s) => s.runSandboxed(request)), // (loaded when first used: sandbox.mjs reads the workspace, which reads through this host)
|
|
24
33
|
};
|
|
25
34
|
|
|
26
35
|
let current = nodeHost;
|
|
@@ -35,10 +44,17 @@ export function readJson(f) {
|
|
|
35
44
|
try { return JSON.parse(text); } catch (e) { throw new CadError('json', `not valid JSON: ${e.message}`, { file: f, cause: e }); }
|
|
36
45
|
}
|
|
37
46
|
|
|
47
|
+
// The folder of node_modules the tool finds JSCAD in: a copy of a project in memory reaches its packages through it
|
|
48
|
+
function toolModules() {
|
|
49
|
+
for (let d = path.dirname(createRequire(import.meta.url).resolve('@jscad/modeling')); path.dirname(d) !== d; d = path.dirname(d)) if (path.basename(d) === 'node_modules') return d;
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
38
53
|
/**
|
|
39
54
|
* A workspace in memory: { [path]: text } under root. Reads outside root come from disk (the tool, its rule sets);
|
|
40
55
|
* writes stay in memory. A design module is loaded from its text, its imports of @jscad/modeling and @rulecad/shapes
|
|
41
|
-
* pointed at the installed packages
|
|
56
|
+
* pointed at the installed packages, when it runs in the tool's process (trusted); otherwise runDesign copies its
|
|
57
|
+
* project's files into a temporary folder, with a link to the tool's packages, and runs it in the sandbox from there.
|
|
42
58
|
* @param {Record<string, string>} files paths relative to root @param {{ root?: string }} [options]
|
|
43
59
|
*/
|
|
44
60
|
export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory') } = {}) {
|
|
@@ -61,5 +77,18 @@ export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory')
|
|
|
61
77
|
.replace(/from\s+'(@jscad\/modeling|@rulecad\/shapes)'/g, (_, s) => `from '${bare(s)}'`);
|
|
62
78
|
return import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
|
|
63
79
|
},
|
|
80
|
+
runDesign: async (request) => {
|
|
81
|
+
const { d } = request, project = path.resolve(path.dirname(path.dirname(d.js)));
|
|
82
|
+
if (!inside(d.js)) return nodeHost.runDesign(request); // (a design on disk runs where it is)
|
|
83
|
+
const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'rulecad-memory-design-')));
|
|
84
|
+
try {
|
|
85
|
+
const copy = path.join(tmp, 'projects', path.basename(project));
|
|
86
|
+
for (const [f, text] of mem) if (f.startsWith(project + path.sep)) { const to = path.join(copy, path.relative(project, f)); fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, text); }
|
|
87
|
+
fs.writeFileSync(path.join(tmp, 'package.json'), JSON.stringify({ type: 'module' }));
|
|
88
|
+
const modules = toolModules();
|
|
89
|
+
if (modules) fs.symlinkSync(modules, path.join(tmp, 'node_modules'), 'junction');
|
|
90
|
+
return await nodeHost.runDesign({ ...request, d: { ...d, js: path.join(copy, path.relative(project, path.resolve(d.js))) }, read: [...(request.read || []), tmp] });
|
|
91
|
+
} finally { try { fs.unlinkSync(path.join(tmp, 'node_modules')); } catch {} fs.rmSync(tmp, { recursive: true, force: true }); } // (the link first, on its own: never a walk into the tool's packages)
|
|
92
|
+
},
|
|
64
93
|
};
|
|
65
94
|
}
|
package/lib/layout.mjs
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
import path from 'node:path';
|
|
3
3
|
import { host, readJson } from './host.mjs';
|
|
4
4
|
import { WS, paths } from './workspace.mjs';
|
|
5
|
+
import { plainName } from './names.mjs';
|
|
5
6
|
|
|
6
|
-
export const layoutPath = (project, name, dir) => path.join(dir || path.join(paths.project(project), 'layouts'), `${name}.json`);
|
|
7
|
+
export const layoutPath = (project, name, dir) => path.join(dir || path.join(paths.project(project), 'layouts'), `${plainName(name, 'layout name')}.json`); // (a name from a design's file: never ../)
|
|
7
8
|
export const hasLayout = (project, name, dir) => host.exists(layoutPath(project, name, dir));
|
|
8
9
|
export function readLayout(project, name, dir) {
|
|
9
10
|
const f = layoutPath(project, name, dir);
|
package/lib/motors.mjs
CHANGED
|
@@ -14,6 +14,7 @@ import { threadsBackend } from '@rulecad/fea/threads';
|
|
|
14
14
|
import { host } from './host.mjs';
|
|
15
15
|
import { paths, printerOf } from './workspace.mjs';
|
|
16
16
|
import { peekRuleSet } from './rules.mjs';
|
|
17
|
+
import { isPlainName } from './names.mjs';
|
|
17
18
|
import { solidFill } from './optimise.mjs';
|
|
18
19
|
|
|
19
20
|
const require = createRequire(import.meta.url);
|
|
@@ -164,7 +165,8 @@ export function workingSpeed(model, spec, supply) {
|
|
|
164
165
|
return model.type === 'dc' ? p.limit / 2 : model.figures.pull_in_torque ? p.limit : model.type === 'servo' ? p.limit : model.type === 'brushless' ? p.limit / 4 : p.limit / 5;
|
|
165
166
|
}
|
|
166
167
|
|
|
167
|
-
const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0];
|
|
168
|
+
const material = (name) => { const n = String(name || 'pla').toLowerCase().split(/\s/)[0]; if (!isPlainName(n)) return null; try { // (a name from project.json: never a path out of the kit's rules)
|
|
169
|
+
return { name: n, ...Object.fromEntries(Object.entries(require(`@rulecad/rules/${n}.json`).rules).map(([k, r]) => [k, r.value])) }; } catch { return null; } };
|
|
168
170
|
|
|
169
171
|
// The findings: f(level, text, card, extra), as the assembly's check makes them
|
|
170
172
|
export function motorChecks(s, f, helpers, materialName) {
|
package/lib/names.mjs
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Names that become parts of file paths: rule sets (rules/<name>.json, and the kit's), projects (projects/<name>/),
|
|
2
|
+
// objects (objects/<name>.js), layouts and problems. They are read from a workspace's own files (project.json's
|
|
3
|
+
// "printer", an object's "uses", cad.config.json) and from the command line, and a workspace can come from anyone, so a
|
|
4
|
+
// name is used only if it is plain: letters, digits, - and _, starting with a letter or digit. A name with a slash, a
|
|
5
|
+
// backslash or a dot could climb out of its folder (issue #342: "printer": "../../../A/B" made cad check copy a file
|
|
6
|
+
// to a new place outside the workspace), so it is refused, with the file and field it came from.
|
|
7
|
+
|
|
8
|
+
/** The characters a rule-set, project, object, layout or problem name may hold. */
|
|
9
|
+
export const PLAIN_NAME = /^[a-z0-9][a-z0-9_-]*$/i;
|
|
10
|
+
|
|
11
|
+
/** Whether `name` is a plain name (PLAIN_NAME), safe to join into a path. */
|
|
12
|
+
export const isPlainName = (name) => typeof name === 'string' && PLAIN_NAME.test(name);
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* `name` if it is plain, else an error saying so: which kind of name it is (`what`, as "rule set name") and, where it
|
|
16
|
+
* was read from a file, which file and field (`where`, as 'projects/p/project.json, its "printer"').
|
|
17
|
+
* @param {unknown} name
|
|
18
|
+
* @param {string} what
|
|
19
|
+
* @param {string} [where]
|
|
20
|
+
* @returns {string}
|
|
21
|
+
*/
|
|
22
|
+
export function plainName(name, what, where) {
|
|
23
|
+
if (isPlainName(name)) return /** @type {string} */ (name);
|
|
24
|
+
const shown = typeof name === 'string' ? `"${name}"` : String(name);
|
|
25
|
+
throw new Error(`${where ? `${where}: ` : ''}the ${what} ${shown} is not a plain name. Use only letters, digits, - and _, starting with a letter or digit (no spaces, dots, slashes or backslashes), as x1c or keycap-2`);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// An object named in another object's "uses": <project>/<object>, then optionally :<variant> and @<version or range>
|
|
29
|
+
const OBJECT_REF = /^([^/:@]+)\/([^/:@]+)(?::([^/@]+))?(?:@([^/]+))?$/;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether an entry of "uses" naming another object (it holds a slash) has the form <project>/<object>, optionally
|
|
33
|
+
* with :<variant> and @<version>, both names plain. A path to a file is not accepted there.
|
|
34
|
+
* @param {unknown} ref
|
|
35
|
+
*/
|
|
36
|
+
export function isObjectRefName(ref) {
|
|
37
|
+
const m = typeof ref === 'string' && OBJECT_REF.exec(ref);
|
|
38
|
+
return !!m && isPlainName(m[1]) && isPlainName(m[2]);
|
|
39
|
+
}
|
package/lib/optimise.mjs
CHANGED
|
@@ -10,6 +10,7 @@ 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
16
|
import { discretise, optimise, outlines, surface, area, bounds, resultant, printable, refine, despike, reduce, undercuts, voids, grey, featureCells, thin } from '@rulecad/topopt';
|
|
@@ -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();
|
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)
|