@rulecad/cad 0.7.97 → 0.9.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 +26 -10
- package/CHANGELOG.md +442 -2
- package/EXAMPLES.md +48 -42
- package/README.md +226 -73
- package/TUTORIAL.md +2 -2
- package/bin/cad.mjs +2253 -514
- package/lib/animate.mjs +173 -49
- package/lib/assembly.mjs +1854 -437
- package/lib/beams.mjs +256 -52
- package/lib/belts.mjs +66 -15
- package/lib/board-work.mjs +12 -0
- package/lib/bought.mjs +309 -53
- package/lib/buildpage.mjs +179 -29
- package/lib/carried.mjs +201 -0
- package/lib/clone.mjs +194 -42
- package/lib/design.mjs +734 -113
- package/lib/drive.mjs +187 -63
- package/lib/edit.mjs +900 -191
- package/lib/errors.mjs +16 -3
- package/lib/explain.mjs +62 -13
- package/lib/fasten.mjs +2710 -502
- package/lib/fittings.mjs +715 -121
- package/lib/fixings.mjs +21 -9
- package/lib/framebuild.mjs +792 -176
- package/lib/framecheck.mjs +1901 -368
- package/lib/framegen.mjs +100 -22
- package/lib/frameheat.mjs +225 -42
- package/lib/frameprint.mjs +513 -108
- package/lib/frames.mjs +81 -17
- package/lib/framesize.mjs +792 -120
- package/lib/frametip.mjs +235 -0
- package/lib/gait.mjs +135 -23
- package/lib/grip.mjs +62 -13
- package/lib/guides.mjs +1403 -230
- package/lib/host.mjs +149 -18
- package/lib/inplace.mjs +171 -36
- package/lib/jigs.mjs +360 -78
- package/lib/joins.mjs +697 -118
- package/lib/jsonedit.mjs +88 -26
- package/lib/kept.mjs +84 -0
- package/lib/kit.mjs +438 -68
- package/lib/layout.mjs +3 -1
- package/lib/links.mjs +149 -42
- package/lib/list.mjs +326 -64
- package/lib/live-guard.mjs +68 -0
- package/lib/live-shape.mjs +96 -24
- package/lib/live.mjs +189 -59
- package/lib/loads.mjs +579 -130
- package/lib/machine.mjs +372 -74
- package/lib/magnets.mjs +162 -44
- package/lib/measured.mjs +417 -94
- package/lib/mesh.mjs +526 -119
- package/lib/meshcmd.mjs +215 -60
- package/lib/motors.mjs +1022 -212
- package/lib/motorsvg.mjs +114 -32
- package/lib/names.mjs +41 -0
- package/lib/optimise.mjs +979 -283
- package/lib/order.mjs +519 -112
- package/lib/panels.mjs +482 -94
- package/lib/parts.mjs +78 -23
- package/lib/pins.mjs +163 -44
- package/lib/plates.mjs +224 -36
- package/lib/player.mjs +37 -9
- package/lib/power.mjs +64 -13
- package/lib/preview.mjs +83 -16
- package/lib/profilemeasure.mjs +572 -129
- package/lib/rules.mjs +38 -4
- package/lib/sandbox-hooks.mjs +154 -12
- package/lib/sandbox-preload.mjs +2 -2
- package/lib/sandbox-run.mjs +127 -12
- package/lib/sandbox.mjs +632 -35
- package/lib/schema.mjs +43 -11
- package/lib/seats.mjs +227 -49
- package/lib/services.mjs +261 -52
- package/lib/sheet.mjs +851 -178
- package/lib/slotnuts.mjs +213 -34
- package/lib/targets/gist.mjs +4 -1
- package/lib/targets.mjs +42 -6
- package/lib/task.mjs +376 -79
- package/lib/versions.mjs +113 -28
- package/lib/wires.mjs +228 -45
- package/lib/workspace.mjs +216 -17
- package/package.json +19 -19
- package/schemas/assembly.schema.json +2 -2
- package/schemas/object.schema.json +1 -1
- package/schemas/project.schema.json +1 -1
package/lib/design.mjs
CHANGED
|
@@ -12,14 +12,17 @@
|
|
|
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
|
-
// stages apart in .cache/stages
|
|
18
|
+
// stages apart in .cache/stages/<design>/, a folder for each design (see stageStore).
|
|
18
19
|
import { spawnSync } from 'node:child_process';
|
|
19
20
|
import { located, lineOf } from './errors.mjs';
|
|
20
|
-
import { host, readJson } from './host.mjs';
|
|
21
|
+
import { host, readJson, cached } from './host.mjs';
|
|
21
22
|
import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
|
|
22
|
-
import {
|
|
23
|
+
import { sandboxed, canSandbox, stageFile, ROUTE_KEY, designLimits } from './sandbox.mjs';
|
|
24
|
+
import { roomFor, STAGES_HELD, ROUTES_HELD } from './kept.mjs';
|
|
25
|
+
import { Worker } from 'node:worker_threads';
|
|
23
26
|
export { polygons };
|
|
24
27
|
import fs from 'node:fs';
|
|
25
28
|
import path from 'node:path';
|
|
@@ -27,9 +30,9 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
|
27
30
|
import { createRequire } from 'node:module';
|
|
28
31
|
import crypto from 'node:crypto';
|
|
29
32
|
import { resolve, loadRuleSet } from './rules.mjs';
|
|
30
|
-
import { WS, paths, printerOf, RULE_DIRS } from './workspace.mjs';
|
|
33
|
+
import { WS, paths, printerOf, RULE_DIRS, readOwnText, noLinksOut } from './workspace.mjs';
|
|
31
34
|
import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
|
|
32
|
-
import { optimised, forDesign } from './optimise.mjs';
|
|
35
|
+
import { optimised, forDesign, ownResults } from './optimise.mjs';
|
|
33
36
|
import * as shapes from '@rulecad/shapes';
|
|
34
37
|
import * as flexures from '@rulecad/flexures';
|
|
35
38
|
import * as gears from '@rulecad/gears';
|
|
@@ -38,6 +41,7 @@ import { designFrames, framesContext } from './frames.mjs';
|
|
|
38
41
|
import { resolve as resolveWith } from '@rulecad/variables';
|
|
39
42
|
import { engineId, packageVersion, materialise } from './versions.mjs';
|
|
40
43
|
import { satisfies } from '@rulecad/versions';
|
|
44
|
+
import { plainName, isObjectRefName } from './names.mjs';
|
|
41
45
|
|
|
42
46
|
const require = createRequire(import.meta.url);
|
|
43
47
|
const jscad = require('@jscad/modeling');
|
|
@@ -51,11 +55,32 @@ export function locate(ref) {
|
|
|
51
55
|
if (!base.includes(path.sep) || !host.exists(`${base}.json`)) {
|
|
52
56
|
const [project, name] = ref.split('/');
|
|
53
57
|
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);
|
|
58
|
+
base = path.join(paths.project(project), 'objects', plainName(name, 'object name'));
|
|
55
59
|
}
|
|
56
|
-
|
|
60
|
+
return designAt(base, variant);
|
|
61
|
+
}
|
|
62
|
+
const designAt = (base, variant) => {
|
|
63
|
+
if (!host.exists(`${base}.json`) || !host.exists(`${base}.js`))
|
|
64
|
+
throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
|
|
57
65
|
const dir = path.dirname(path.dirname(base));
|
|
58
|
-
return {
|
|
66
|
+
return {
|
|
67
|
+
project: path.basename(dir),
|
|
68
|
+
name: path.basename(base),
|
|
69
|
+
js: `${base}.js`,
|
|
70
|
+
json: `${base}.json`,
|
|
71
|
+
dir,
|
|
72
|
+
...(variant ? { variant } : {}),
|
|
73
|
+
};
|
|
74
|
+
};
|
|
75
|
+
/**
|
|
76
|
+
* A design named in a workspace's own file (an assembly's item, a project's "objects", a problem's): `name` is an
|
|
77
|
+
* object of `project`, optionally with :<variant>, and only ever a plain name. Never a path, as locate() also takes
|
|
78
|
+
* from the command line: "../../elsewhere/x" in a file would otherwise read a design outside the workspace.
|
|
79
|
+
* @param {string} project @param {string} name @param {string} [where] the file and field it was read from
|
|
80
|
+
*/
|
|
81
|
+
export function locateIn(project, name, where) {
|
|
82
|
+
const [plain, variant] = String(name).split(':');
|
|
83
|
+
return designAt(path.join(paths.project(project), 'objects', plainName(plain, 'object name', where)), variant);
|
|
59
84
|
}
|
|
60
85
|
|
|
61
86
|
// ---------- objects that read each other ----------
|
|
@@ -65,55 +90,102 @@ export function locate(ref) {
|
|
|
65
90
|
// its version; "macropad/pcb@0.2.0" reads that release instead of the working copy.
|
|
66
91
|
export const isObjectRef = (u) => String(u).includes('/');
|
|
67
92
|
const building = new Set();
|
|
68
|
-
export async function objectSets(d, object) {
|
|
69
|
-
const refs = (object.uses || []).filter(isObjectRef),
|
|
93
|
+
export async function objectSets(d, object, { trusted = false } = {}) {
|
|
94
|
+
const refs = (object.uses || []).filter(isObjectRef),
|
|
95
|
+
sets = {},
|
|
96
|
+
extra = {};
|
|
97
|
+
// Its rule sets (the entries without a slash) become paths, rules/<name>.json: plain names only, said with the file they're in
|
|
98
|
+
for (const u of object.uses || [])
|
|
99
|
+
if (!isObjectRef(u)) plainName(u, 'rule set name', `${path.relative(WS, d.json)}, in its "uses"`);
|
|
70
100
|
if (!refs.length) return { sets, extra };
|
|
71
101
|
const self = `${d.project}/${d.name}`;
|
|
72
102
|
building.add(self);
|
|
73
103
|
try {
|
|
74
104
|
for (const u of refs) {
|
|
75
|
-
|
|
76
|
-
if (
|
|
77
|
-
|
|
78
|
-
|
|
105
|
+
// (from the object's file: a design reference, never a path that locate() would also take)
|
|
106
|
+
if (!isObjectRefName(u))
|
|
107
|
+
throw new Error(
|
|
108
|
+
`${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`,
|
|
109
|
+
);
|
|
110
|
+
const [ref, want] = u.split('@'),
|
|
111
|
+
exact = /^\d+\.\d+\.\d+$/.test(want || '');
|
|
112
|
+
if (building.has(ref))
|
|
113
|
+
throw new Error(
|
|
114
|
+
`${self} and ${ref} read each other's numbers: one of them has to give its numbers to the other, not both`,
|
|
115
|
+
);
|
|
116
|
+
const base = locateIn(...ref.split('/')),
|
|
117
|
+
b = await build(exact ? materialise(base, want) : base, {}, { trusted }),
|
|
118
|
+
version = b.object.version;
|
|
119
|
+
if (want && !exact && !satisfies(version, want))
|
|
120
|
+
throw new Error(
|
|
121
|
+
`${self} uses ${ref} ${want}, but ${ref} is ${version}: change the range, or the design to suit ${version}`,
|
|
122
|
+
);
|
|
79
123
|
const units = Object.fromEntries(Object.entries(b.object.variables || {}).map(([k, x]) => [k, x.unit]));
|
|
80
124
|
const rules = {};
|
|
81
|
-
for (const [k, v] of Object.entries(b.values))
|
|
82
|
-
|
|
83
|
-
|
|
125
|
+
for (const [k, v] of Object.entries(b.values))
|
|
126
|
+
if (typeof v === 'number' && Number.isFinite(v)) {
|
|
127
|
+
rules[k] = {
|
|
128
|
+
value: v,
|
|
129
|
+
...(units[k] ? { unit: units[k] } : {}),
|
|
130
|
+
rule: `${ref}'s ${k}`,
|
|
131
|
+
kind: 'design',
|
|
132
|
+
source: `${ref}@${version}`,
|
|
133
|
+
}; // no unit: a count (turns, segments), not a length
|
|
134
|
+
}
|
|
84
135
|
sets[u] = { name: base.name, rules };
|
|
85
|
-
if (b.circuit) {
|
|
136
|
+
if (b.circuit) {
|
|
137
|
+
const e = await pcbEngine(),
|
|
138
|
+
board = b.circuit.find((x) => x.type === 'pcb_board');
|
|
139
|
+
extra[base.name] = {
|
|
140
|
+
board_holes: e.holes(b.circuit),
|
|
141
|
+
board_parts: e.parts ? e.parts(b.circuit) : {},
|
|
142
|
+
...(board.outline ? { board_outline: board.outline } : {}),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
86
145
|
}
|
|
87
|
-
} finally {
|
|
146
|
+
} finally {
|
|
147
|
+
building.delete(self);
|
|
148
|
+
}
|
|
88
149
|
return { sets, extra };
|
|
89
150
|
}
|
|
90
151
|
|
|
91
152
|
// The layouts an object can pick, by name, from its layout variables' choices (built-ins like grid have no file)
|
|
92
153
|
export function layoutsOf(d, object) {
|
|
93
154
|
const out = {};
|
|
94
|
-
for (const v of Object.values(object.variables || {}))
|
|
95
|
-
|
|
96
|
-
|
|
155
|
+
for (const v of Object.values(object.variables || {}))
|
|
156
|
+
if (v.type === 'layout') {
|
|
157
|
+
for (const n of v.choice || [v.value])
|
|
158
|
+
if (hasLayout(d.project, n, d.layoutsDir)) out[n] = readLayout(d.project, n, d.layoutsDir);
|
|
159
|
+
}
|
|
97
160
|
return out;
|
|
98
161
|
}
|
|
99
162
|
|
|
100
163
|
// The optimised layouts an object's problem variables pick, by name, for v.problems
|
|
101
164
|
export async function problemsOf(d, object, values) {
|
|
102
165
|
const out = {};
|
|
103
|
-
for (const [name, v] of Object.entries(object.variables || {}))
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
166
|
+
for (const [name, v] of Object.entries(object.variables || {}))
|
|
167
|
+
if (v.type === 'problem') {
|
|
168
|
+
const ref = values[name];
|
|
169
|
+
if (!ref || ref === 'none') continue; // a variant that draws without the optimiser (a test rig, or the regions a problem reads)
|
|
170
|
+
if (!out[ref]) {
|
|
171
|
+
// Optimising here can take an hour on a big solid: say so, why, and (on a terminal) how far it's got
|
|
172
|
+
const live = process.stderr.isTTY;
|
|
173
|
+
ownResults();
|
|
174
|
+
const r = await optimised(d.project, ref, {
|
|
175
|
+
onRun: (why) =>
|
|
176
|
+
console.error(`optimising ${ref} (${why}; the result is kept until the problem or the solver changes)…`),
|
|
177
|
+
onStep: (s) => {
|
|
178
|
+
if (live)
|
|
179
|
+
process.stderr.write(
|
|
180
|
+
`\r\x1b[Koptimising ${ref}: step ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm`,
|
|
181
|
+
);
|
|
182
|
+
if (s.step === s.steps && live) process.stderr.write('\r\x1b[K');
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
if (live) process.stderr.write('\r\x1b[K');
|
|
186
|
+
out[ref] = forDesign(r);
|
|
187
|
+
}
|
|
115
188
|
}
|
|
116
|
-
}
|
|
117
189
|
return out;
|
|
118
190
|
}
|
|
119
191
|
|
|
@@ -121,37 +193,210 @@ export async function problemsOf(d, object, values) {
|
|
|
121
193
|
export function variantSet(d, object, set = {}) {
|
|
122
194
|
if (!d.variant) return set;
|
|
123
195
|
const v = (object.variants || {})[d.variant];
|
|
124
|
-
if (!v)
|
|
196
|
+
if (!v)
|
|
197
|
+
throw new Error(
|
|
198
|
+
`${d.name} has no variant "${d.variant}" (variants: ${Object.keys(object.variants || {}).join(', ') || 'none'})`,
|
|
199
|
+
);
|
|
125
200
|
return { ...v, ...set };
|
|
126
201
|
}
|
|
127
202
|
|
|
128
|
-
const CACHE = paths.cache('builds'),
|
|
203
|
+
const CACHE = paths.cache('builds'),
|
|
204
|
+
CACHE_VERSION = 3;
|
|
129
205
|
// The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
|
|
130
206
|
// but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
|
|
131
207
|
if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
|
|
132
208
|
const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
|
|
133
209
|
// What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
|
|
134
210
|
// boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
|
|
135
|
-
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))),
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
211
|
+
const shapesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/shapes'))),
|
|
212
|
+
flexuresDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/flexures'))),
|
|
213
|
+
gearsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/gears'))),
|
|
214
|
+
motorsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/motors'))),
|
|
215
|
+
framesDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/frames'))),
|
|
216
|
+
fixingsDir = path.dirname(fileURLToPath(import.meta.resolve('@rulecad/fixings')));
|
|
217
|
+
// (every module of a helper package but its tests: they change nothing a design builds; nor a dot-file, which is a
|
|
218
|
+
// package's tests writing a scratch module beside its sources, there for a moment and gone mid-read)
|
|
219
|
+
const helperSources = (dir) =>
|
|
220
|
+
fs
|
|
221
|
+
.readdirSync(dir)
|
|
222
|
+
.filter((f) => f.endsWith('.mjs') && f !== 'test.mjs' && !f.startsWith('.'))
|
|
223
|
+
.sort()
|
|
224
|
+
.map((f) => source(pathToFileURL(path.join(dir, f)).href))
|
|
225
|
+
.join('');
|
|
226
|
+
const feaDir = path.dirname(
|
|
227
|
+
createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea'),
|
|
228
|
+
); // (flexures' own, wherever npm put it)
|
|
139
229
|
// (as one digest, so each build's key hashes a line and not a megabyte of source)
|
|
140
|
-
const own = crypto
|
|
230
|
+
const own = crypto
|
|
231
|
+
.createHash('sha256')
|
|
232
|
+
.update(
|
|
233
|
+
source(import.meta.url) +
|
|
234
|
+
source('./fixings.mjs') +
|
|
235
|
+
source('./frames.mjs') +
|
|
236
|
+
helperSources(framesDir) +
|
|
237
|
+
helperSources(shapesDir) +
|
|
238
|
+
helperSources(flexuresDir) +
|
|
239
|
+
helperSources(gearsDir) +
|
|
240
|
+
helperSources(motorsDir) +
|
|
241
|
+
helperSources(fixingsDir) +
|
|
242
|
+
helperSources(feaDir) +
|
|
243
|
+
packageVersion('@jscad/modeling'),
|
|
244
|
+
)
|
|
245
|
+
.digest('hex'); // every shapes module, not just its entry
|
|
141
246
|
// A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
|
|
142
247
|
// 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
|
-
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
248
|
+
// at once: .cache/stages/. A design in the sandbox can't write them, so the sandbox hands them back and the tool writes
|
|
249
|
+
// them. Each design has a folder of its own there (designFolder), the only one it reads: a stage's key is a hash of its
|
|
250
|
+
// name, its inputs and the library's code, which anyone can work out, so a design that came with a cloned workspace
|
|
251
|
+
// could otherwise hand back a false result under the key another design (the user's own) reads, and pass a mechanism
|
|
252
|
+
// that would fail.
|
|
253
|
+
const STAGES = paths.cache('stages'),
|
|
254
|
+
stageSalt = crypto
|
|
255
|
+
.createHash('sha256')
|
|
256
|
+
.update(helperSources(flexuresDir) + helperSources(feaDir))
|
|
257
|
+
.digest('hex');
|
|
258
|
+
// A workspace cloned from elsewhere may hold links of its own in .cache/: a cache file that is a link to a file outside
|
|
259
|
+
// (the trust list, say) would have the tool write what a sandboxed design handed back through it, and a cache folder
|
|
260
|
+
// that is a link would have cache files written, and pruned, somewhere else. So a cache file is written only when it
|
|
261
|
+
// and every folder between it and the workspace are a plain file and plain folders, or not there yet.
|
|
262
|
+
function ownCacheFile(file, root = WS) {
|
|
263
|
+
if (host.name === 'memory') return true; // (held in memory: nothing on disk to follow)
|
|
264
|
+
const top = path.resolve(root);
|
|
265
|
+
let p = path.resolve(file);
|
|
266
|
+
if (!p.startsWith(top + path.sep)) return false;
|
|
267
|
+
for (let first = true; p !== top; p = path.dirname(p), first = false) {
|
|
268
|
+
let st;
|
|
269
|
+
try {
|
|
270
|
+
st = fs.lstatSync(p);
|
|
271
|
+
} catch (e) {
|
|
272
|
+
if (e.code === 'ENOENT') continue;
|
|
273
|
+
return false;
|
|
274
|
+
}
|
|
275
|
+
if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
|
|
276
|
+
}
|
|
277
|
+
return true;
|
|
278
|
+
}
|
|
279
|
+
// A design's own folder of a cache: named by a hash of its file's path in the workspace, so it stays the same when the
|
|
280
|
+
// workspace moves, and one design's results are never read by another
|
|
281
|
+
const designFolder = (dir, d) =>
|
|
282
|
+
path.join(
|
|
283
|
+
dir,
|
|
284
|
+
crypto
|
|
285
|
+
.createHash('sha256')
|
|
286
|
+
.update(path.relative(WS, path.resolve(d.js)).split(path.sep).join('/'))
|
|
287
|
+
.digest('hex')
|
|
288
|
+
.slice(0, 16),
|
|
289
|
+
);
|
|
290
|
+
// Stages kept before each design had its own folder, directly in .cache/stages/: read by no one now, so cleared once a
|
|
291
|
+
// run (only plain files of the workspace's own folder: never through a link)
|
|
292
|
+
let oldStagesCleared = false;
|
|
293
|
+
function clearOldStages() {
|
|
294
|
+
if (oldStagesCleared) return;
|
|
295
|
+
oldStagesCleared = true;
|
|
296
|
+
for (const f of host.list(STAGES))
|
|
297
|
+
if (f.endsWith('.json') && ownCacheFile(path.join(STAGES, f)))
|
|
298
|
+
try {
|
|
299
|
+
host.remove(path.join(STAGES, f));
|
|
300
|
+
} catch {
|
|
301
|
+
// (left for another run)
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
// Room for a file of n bytes in a design's own folder (dir) of a cache written from replies (top: .cache/stages or
|
|
305
|
+
// .cache/routes), within what that folder and every design's folder there may hold (kept.mjs STAGES_HELD): the files
|
|
306
|
+
// that would take it past go first (roomFor). False when there is none. Only the design folders' own plain files are
|
|
307
|
+
// counted and removed, never through a link (a flat file of .cache/routes is the tool's own route cache: not one of these).
|
|
308
|
+
function makeRoom(top, dir, n, held) {
|
|
309
|
+
const plain = (p, folder) => {
|
|
310
|
+
if (host.name === 'memory') return true;
|
|
311
|
+
try {
|
|
312
|
+
const st = fs.lstatSync(p);
|
|
313
|
+
return folder ? st.isDirectory() : st.isFile() && st.nlink === 1;
|
|
314
|
+
} catch {
|
|
315
|
+
return false;
|
|
316
|
+
}
|
|
317
|
+
};
|
|
318
|
+
const files = [];
|
|
319
|
+
for (const sub of host.list(top)) {
|
|
320
|
+
const folder = path.join(top, sub);
|
|
321
|
+
if (!plain(folder, true)) continue;
|
|
322
|
+
for (const f of host.list(folder)) {
|
|
323
|
+
const p = path.join(folder, f);
|
|
324
|
+
if (!plain(p, false)) continue;
|
|
325
|
+
try {
|
|
326
|
+
files.push({ p, own: folder === dir, t: host.mtime(p), size: host.size(p) });
|
|
327
|
+
} catch {
|
|
328
|
+
// (gone meanwhile)
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
const gone = roomFor(files, n, held);
|
|
333
|
+
if (!gone) return false;
|
|
334
|
+
for (const p of gone) host.remove(p);
|
|
335
|
+
return true;
|
|
336
|
+
}
|
|
337
|
+
function stageStore(d) {
|
|
338
|
+
const dir = designFolder(STAGES, d);
|
|
339
|
+
return {
|
|
340
|
+
dir,
|
|
341
|
+
salt: stageSalt,
|
|
342
|
+
// (stageFile: a key that would put its file anywhere but directly in the design's folder has none, a second guard
|
|
343
|
+
// after the sandbox's own check of the keys a design hands back)
|
|
344
|
+
get: (k) => {
|
|
345
|
+
const f = stageFile(dir, k);
|
|
346
|
+
if (!f || process.env.CAD_NO_CACHE || !cached(f)) return undefined;
|
|
347
|
+
try {
|
|
348
|
+
host.touch(f);
|
|
349
|
+
} catch {
|
|
350
|
+
// (a cache file that can't be marked as used may be pruned sooner: only slower)
|
|
351
|
+
}
|
|
352
|
+
return host.readText(f);
|
|
353
|
+
}, // (CAD_NO_CACHE: computed afresh, and kept)
|
|
354
|
+
put: (k, text) => {
|
|
355
|
+
const f = stageFile(dir, k);
|
|
356
|
+
if (!f || !ownCacheFile(f)) return;
|
|
357
|
+
try {
|
|
358
|
+
clearOldStages();
|
|
359
|
+
prune(dir, STAGES_KEEP);
|
|
360
|
+
if (makeRoom(STAGES, dir, Buffer.byteLength(text, 'utf8'), STAGES_HELD)) host.writeText(f, text);
|
|
361
|
+
} catch {
|
|
362
|
+
// (a cache that can't be written is only slower)
|
|
363
|
+
}
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
const STAGES_KEEP = 60, // (a launcher's physics is 5 MB, its probe 9; a reply may hand back no more than sandbox.mjs STAGES_MOST)
|
|
368
|
+
ROUTES_KEEP = 60;
|
|
369
|
+
// The autorouter's results, for a board built in the sandbox: the child reads them from the design's own folder of the
|
|
370
|
+
// workspace's route cache (.cache/routes/<design>/), then from the route cache the tool's own process writes
|
|
371
|
+
// (RULECAD_ROUTE_CACHE: .cache/routes/, or a folder the user shares between workspaces). What it routes comes back to
|
|
372
|
+
// be written in the design's own folder only, under a key of the route cache's form (ROUTE_KEY), never through a link
|
|
373
|
+
// (ownCacheFile): the tool can't tell which keys the design really looked up, so a route it hands back is read by
|
|
374
|
+
// that design alone, never by another board or another workspace. None with CAD_NO_CACHE.
|
|
375
|
+
const routeStore = (d) => {
|
|
376
|
+
const shared = process.env.RULECAD_ROUTE_CACHE;
|
|
377
|
+
if (!shared) return null;
|
|
378
|
+
const dir = designFolder(paths.cache('routes'), d);
|
|
379
|
+
return {
|
|
380
|
+
dir,
|
|
381
|
+
shared,
|
|
382
|
+
put: (k, text) => {
|
|
383
|
+
const f = ROUTE_KEY.test(k) && stageFile(dir, k);
|
|
384
|
+
if (!f || !ownCacheFile(f)) return;
|
|
385
|
+
try {
|
|
386
|
+
prune(dir, ROUTES_KEEP);
|
|
387
|
+
if (makeRoom(paths.cache('routes'), dir, Buffer.byteLength(text, 'utf8'), ROUTES_HELD)) host.writeText(f, text);
|
|
388
|
+
} catch {
|
|
389
|
+
// (a cache that can't be written is only slower)
|
|
390
|
+
}
|
|
391
|
+
},
|
|
392
|
+
};
|
|
393
|
+
};
|
|
394
|
+
export const pcbEngine = () =>
|
|
395
|
+
import('@rulecad/pcb').catch((e) => {
|
|
396
|
+
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@rulecad\/pcb/.test(e.message))
|
|
397
|
+
throw new Error('boards need the board engine: npm install @rulecad/pcb');
|
|
398
|
+
throw e;
|
|
399
|
+
});
|
|
155
400
|
|
|
156
401
|
// What v.fixings is bound to (lib/fixings.mjs): the workspace's own rule sets by name (a release's own, where it is one:
|
|
157
402
|
// its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
|
|
@@ -159,27 +404,87 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
|
|
|
159
404
|
// made from these too, so its cache holds only while they stand.
|
|
160
405
|
let kitRules = null;
|
|
161
406
|
export function fixingsContext(d) {
|
|
162
|
-
const dir = d.rulesDir || RULE_DIRS[0],
|
|
163
|
-
|
|
164
|
-
|
|
407
|
+
const dir = d.rulesDir || RULE_DIRS[0],
|
|
408
|
+
sets = {},
|
|
409
|
+
text = [];
|
|
410
|
+
for (const f of host
|
|
411
|
+
.list(dir)
|
|
412
|
+
.filter((x) => x.endsWith('.json'))
|
|
413
|
+
.sort()) {
|
|
414
|
+
try {
|
|
415
|
+
const raw = readOwnText(path.join(dir, f)), // (a set linked in from outside the workspace is not read)
|
|
416
|
+
s = JSON.parse(raw);
|
|
417
|
+
if (s && s.rules && typeof s.rules === 'object') {
|
|
418
|
+
sets[s.name ?? f.slice(0, -5)] = s;
|
|
419
|
+
text.push(raw);
|
|
420
|
+
}
|
|
421
|
+
} catch {
|
|
422
|
+
// (a broken set is cad check's to name, where a design uses it)
|
|
423
|
+
}
|
|
165
424
|
}
|
|
166
|
-
const name = printerOf(d.project),
|
|
425
|
+
const name = printerOf(d.project),
|
|
426
|
+
peek = (n) => {
|
|
427
|
+
plainName(n, 'rule set name');
|
|
428
|
+
const f = [dir, ...RULE_DIRS].map((x) => path.join(x, `${n}.json`)).find((x) => host.exists(x));
|
|
429
|
+
if (!f) throw new Error(`no rule set "${n}" (rules/${n}.json)`);
|
|
430
|
+
return readJson(f);
|
|
431
|
+
};
|
|
167
432
|
let printer = null;
|
|
168
|
-
try {
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
433
|
+
try {
|
|
434
|
+
// (a printer with no rule set is said where a print is checked; fixings then draws for the kit's)
|
|
435
|
+
const set = peek(name),
|
|
436
|
+
values = resolveWith({ uses: [name] }, { load: peek }).values[name];
|
|
437
|
+
printer = {
|
|
438
|
+
name: set.name ?? name,
|
|
439
|
+
rules: Object.fromEntries(
|
|
440
|
+
Object.entries(set.rules).map(([k, r]) => [k, typeof values[k] === 'number' ? { ...r, value: values[k] } : r]),
|
|
441
|
+
),
|
|
442
|
+
};
|
|
443
|
+
} catch {
|
|
444
|
+
// (no printer rule set, or one that doesn't resolve: no printer here, and a print check says so)
|
|
445
|
+
}
|
|
172
446
|
let material = null;
|
|
173
|
-
try {
|
|
174
|
-
|
|
447
|
+
try {
|
|
448
|
+
const f = path.join(d.dir, 'project.json');
|
|
449
|
+
if (host.exists(f))
|
|
450
|
+
material =
|
|
451
|
+
String(readJson(f).material || '')
|
|
452
|
+
.trim()
|
|
453
|
+
.toLowerCase()
|
|
454
|
+
.split(/\s/)[0] || null;
|
|
455
|
+
} catch {
|
|
456
|
+
// (a project.json that can't be read is cad check's to name: no material here)
|
|
457
|
+
}
|
|
458
|
+
kitRules ||= (() => {
|
|
459
|
+
const k = RULE_DIRS.at(-1);
|
|
460
|
+
return crypto
|
|
461
|
+
.createHash('sha256')
|
|
462
|
+
.update(
|
|
463
|
+
fs
|
|
464
|
+
.readdirSync(k)
|
|
465
|
+
.filter((f) => f.endsWith('.json'))
|
|
466
|
+
.sort()
|
|
467
|
+
.map((f) => fs.readFileSync(path.join(k, f), 'utf8'))
|
|
468
|
+
.join(''),
|
|
469
|
+
)
|
|
470
|
+
.digest('hex');
|
|
471
|
+
})();
|
|
175
472
|
const context = { sets, printer, material };
|
|
176
|
-
return {
|
|
473
|
+
return {
|
|
474
|
+
context,
|
|
475
|
+
hash: crypto
|
|
476
|
+
.createHash('sha256')
|
|
477
|
+
.update(JSON.stringify([text, printer, material, kitRules]))
|
|
478
|
+
.digest('hex')
|
|
479
|
+
.slice(0, 24),
|
|
480
|
+
};
|
|
177
481
|
}
|
|
178
482
|
|
|
179
483
|
// An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
|
|
180
484
|
// Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
|
|
181
485
|
// Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
|
|
182
|
-
export const booleans = (object) =>
|
|
486
|
+
export const booleans = (object) =>
|
|
487
|
+
object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad';
|
|
183
488
|
|
|
184
489
|
export const readObject = (d) => {
|
|
185
490
|
const o = readJson(d.json);
|
|
@@ -194,26 +499,198 @@ function syntaxAt(e, d) {
|
|
|
194
499
|
if (e?.name !== 'SyntaxError' || e.line || host.name !== 'node') return e;
|
|
195
500
|
const r = spawnSync(process.execPath, ['--check', d.js], { encoding: 'utf8' });
|
|
196
501
|
const m = r.status ? String(r.stderr).match(/^(?:file:\/\/)?.*?:(\d+)\r?\n(.*)\r?\n/) : null;
|
|
197
|
-
if (m) {
|
|
502
|
+
if (m) {
|
|
503
|
+
e.line = Number(m[1]);
|
|
504
|
+
e.message = `${e.message}: ${m[2].trim()}`;
|
|
505
|
+
}
|
|
198
506
|
return e;
|
|
199
507
|
}
|
|
200
508
|
|
|
201
|
-
//
|
|
509
|
+
// Who may run a design in the tool's own process, outside the sandbox. On Node's file system (the CLI) every design,
|
|
510
|
+
// a board's too, runs in the sandbox unless the workspace trusts its designs (sandbox.mjs's sandboxed: "sandbox": false
|
|
511
|
+
// and cad trust, or CAD_TRUST=1), and is run here only then. A host of another kind (memoryHost: a workspace in memory,
|
|
512
|
+
// for tests and later a browser or editor's server) has no trust list of its own: its designs run in the sandbox
|
|
513
|
+
// through its runDesign hook (host.mjs), and here only when the caller says it trusts them:
|
|
514
|
+
// build(d, set, { trusted: true }).
|
|
515
|
+
function runsHere(trusted) {
|
|
516
|
+
if (host.name === 'node') return !sandboxed();
|
|
517
|
+
return trusted === true || !(host.runDesign && canSandbox()); // (only true itself: not a string or number a caller passed on)
|
|
518
|
+
}
|
|
519
|
+
// A workspace's trust names its folder, so it covers the designs in that folder: one elsewhere (a path to another
|
|
520
|
+
// workspace's file, or a link out of it) is refused here, to be run from its own workspace once that is trusted.
|
|
521
|
+
function mayRunHere(d, trusted) {
|
|
522
|
+
if (host.name === 'node') {
|
|
523
|
+
const real = (f) => {
|
|
524
|
+
try {
|
|
525
|
+
return fs.realpathSync(f);
|
|
526
|
+
} catch {
|
|
527
|
+
return path.resolve(f);
|
|
528
|
+
}
|
|
529
|
+
}; // (one folder by any spelling: a link, /var and /private/var)
|
|
530
|
+
const outside = (f) => {
|
|
531
|
+
const where = path.relative(real(WS), real(f));
|
|
532
|
+
return where === '..' || where.startsWith(`..${path.sep}`) || path.isAbsolute(where);
|
|
533
|
+
};
|
|
534
|
+
const away = [d.json, d.js].find(outside); // (the .js is the code that runs: a link to one elsewhere is elsewhere)
|
|
535
|
+
if (away && process.env.CAD_TRUST !== '1') {
|
|
536
|
+
throw Object.assign(
|
|
537
|
+
new Error(
|
|
538
|
+
`${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`,
|
|
539
|
+
),
|
|
540
|
+
{ code: 'workspace.untrusted' },
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
if (trusted === true) return;
|
|
546
|
+
throw Object.assign(
|
|
547
|
+
new Error(
|
|
548
|
+
`${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`,
|
|
549
|
+
),
|
|
550
|
+
{ code: 'workspace.untrusted' },
|
|
551
|
+
);
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// A board's build from its Circuit JSON, wherever the design ran: what it tells the parts around it (outline, holes,
|
|
555
|
+
// the module's place) goes into its values, and its solid is made here, with its parts' 3D models (meshes cad clone
|
|
556
|
+
// fetched into the workspace's models/: a design never reads files; cad does). The circuit may be a sandboxed design's
|
|
557
|
+
// reply, so a model is read only from a plain relative .json path inside the workspace, and only where it really is
|
|
558
|
+
// inside it: a link in the workspace (models/part.json leading to a file of the user's elsewhere) is not followed out.
|
|
559
|
+
// For a sandboxed design (until: when its time limit ends, as Date.now()), the solid is made in a thread of its own,
|
|
560
|
+
// under the design's limits (boardWork): drilling a board takes far longer the more holes it has, and the circuit
|
|
561
|
+
// is the design's to say.
|
|
562
|
+
async function boardBuild(pcb, board, values, object, d, until = null) {
|
|
563
|
+
Object.assign(values, pcb.outputs(board.circuit, board.matrix));
|
|
564
|
+
const meshes = {};
|
|
565
|
+
const inWs = (file) => {
|
|
566
|
+
// (on Node's file system, by real paths: /var and /private/var are one folder, a link out is out)
|
|
567
|
+
if (host.name !== 'node') return true;
|
|
568
|
+
try {
|
|
569
|
+
const rel = path.relative(fs.realpathSync(WS), fs.realpathSync(file));
|
|
570
|
+
return !!rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..');
|
|
571
|
+
} catch {
|
|
572
|
+
return false;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
for (const c of board.circuit.filter((e) => e.type === 'cad_component' && e.rulecad_model?.mesh)) {
|
|
576
|
+
const f = c.rulecad_model.mesh;
|
|
577
|
+
if (typeof f !== 'string' || f in meshes) continue;
|
|
578
|
+
const file = path.resolve(WS, f),
|
|
579
|
+
rel = path.relative(WS, file);
|
|
580
|
+
const plainPath =
|
|
581
|
+
f.endsWith('.json') && !path.isAbsolute(f) && rel && !path.isAbsolute(rel) && !rel.split(/[\\/]/).includes('..');
|
|
582
|
+
meshes[f] = plainPath && host.exists(file) && inWs(file) ? JSON.parse(host.readText(file)).triangles : null;
|
|
583
|
+
}
|
|
584
|
+
const options = { thickness: values.thickness, smooth: values.smooth, models: meshes };
|
|
585
|
+
const made =
|
|
586
|
+
until == null ? pcb.solids(board.circuit, options) : await boardWork('solids', [board.circuit, options], d, until);
|
|
587
|
+
try {
|
|
588
|
+
return named(made, object.parts || {});
|
|
589
|
+
} catch (e) {
|
|
590
|
+
throw located(e, d.js, 'design.run');
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// The tool's own work on a sandboxed board design's circuit (job: pcb's solids or checks, with its args), in a thread
|
|
595
|
+
// (board-work.mjs) that is stopped once the design's time limit ends (until, as Date.now()), with design.time, and may
|
|
596
|
+
// hold no more memory than the design may, or design.memory
|
|
597
|
+
function boardWork(job, args, d, until) {
|
|
598
|
+
const limits = designLimits(),
|
|
599
|
+
doing =
|
|
600
|
+
job === 'solids'
|
|
601
|
+
? "the tool was drilling the board's solid with the holes it gave back"
|
|
602
|
+
: 'the tool was checking the circuit it gave back';
|
|
603
|
+
return new Promise((done, reject) => {
|
|
604
|
+
const worker = new Worker(new URL('./board-work.mjs', import.meta.url), {
|
|
605
|
+
workerData: { job, args },
|
|
606
|
+
execArgv: [], // (none of this process's own flags: --input-type, say, stops a thread starting)
|
|
607
|
+
resourceLimits: { maxOldGenerationSizeMb: limits.memory },
|
|
608
|
+
});
|
|
609
|
+
let over = null;
|
|
610
|
+
const timer = setTimeout(
|
|
611
|
+
() => {
|
|
612
|
+
over = 'time';
|
|
613
|
+
worker.terminate();
|
|
614
|
+
},
|
|
615
|
+
Math.max(0, Math.min(until - Date.now(), 2 ** 31 - 1)),
|
|
616
|
+
);
|
|
617
|
+
const stopped = (e) => {
|
|
618
|
+
clearTimeout(timer);
|
|
619
|
+
if (over === 'time' || e?.code === 'ERR_WORKER_OUT_OF_MEMORY')
|
|
620
|
+
reject(
|
|
621
|
+
located(
|
|
622
|
+
new Error(
|
|
623
|
+
over === 'time'
|
|
624
|
+
? `the design ran for longer than ${limits.timeout} s, so it was stopped while ${doing}. If it is only slow, raise the limit: "designTimeout" (seconds) in cad.config.json, or CAD_DESIGN_TIMEOUT`
|
|
625
|
+
: `the design used more than the ${limits.memory} MB of memory it may, so it was stopped while ${doing}. If it needs more, raise the limit: "designMemory" (megabytes) in cad.config.json, or CAD_DESIGN_MEMORY`,
|
|
626
|
+
),
|
|
627
|
+
d.js,
|
|
628
|
+
over === 'time' ? 'design.time' : 'design.memory',
|
|
629
|
+
),
|
|
630
|
+
);
|
|
631
|
+
else reject(e || located(new Error(`${doing}, and its thread stopped before it was done`), d.js, 'design.run'));
|
|
632
|
+
};
|
|
633
|
+
worker.once('message', (made) => {
|
|
634
|
+
clearTimeout(timer);
|
|
635
|
+
done(made);
|
|
636
|
+
worker.terminate();
|
|
637
|
+
});
|
|
638
|
+
worker.once('error', stopped);
|
|
639
|
+
worker.once('exit', () => stopped(null));
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* A built board's checks (pcb checks), in a thread under the design's limits wherever its designs run sandboxed:
|
|
645
|
+
* the circuit is a sandboxed design's reply, or the cache's copy of one, and checking it takes far longer the more
|
|
646
|
+
* it holds. A trusted workspace's are checked here, as its designs run here.
|
|
647
|
+
* @param {{ circuit: object[], values: object, matrix?: object, source?: object }} b the build
|
|
648
|
+
* @param {{ js: string }} d the design
|
|
649
|
+
* @returns {Promise<object[]>} the findings
|
|
650
|
+
*/
|
|
651
|
+
export async function boardChecks(b, d) {
|
|
652
|
+
const args = [b.circuit, b.values, b.matrix, b.source];
|
|
653
|
+
if (!sandboxed()) return (await pcbEngine()).checks(...args);
|
|
654
|
+
let until;
|
|
655
|
+
try {
|
|
656
|
+
until = Date.now() + designLimits().timeout * 1000;
|
|
657
|
+
} catch (e) {
|
|
658
|
+
throw located(e, d.js, 'design.limit');
|
|
659
|
+
}
|
|
660
|
+
return boardWork('checks', args, d, until);
|
|
661
|
+
}
|
|
662
|
+
|
|
663
|
+
// build(design, set, { mirror, trusted }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
|
|
664
|
+
// 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
665
|
// 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
666
|
// parts: [{ name, role, label, geometry, polygons, triangles }]; polygons and triangles: every part together
|
|
204
|
-
export async function build(d, set = {}, { mirror = false } = {}) {
|
|
667
|
+
export async function build(d, set = {}, { mirror = false, trusted = false } = {}) {
|
|
205
668
|
const object = readObject(d);
|
|
206
669
|
set = variantSet(d, object, set);
|
|
207
|
-
const refs = await objectSets(d, object); // other objects' numbers, when it reads them
|
|
208
|
-
const sets = {
|
|
670
|
+
const refs = await objectSets(d, object, { trusted }); // other objects' numbers, when it reads them
|
|
671
|
+
const sets = {
|
|
672
|
+
...(d.rulesDir
|
|
673
|
+
? Object.fromEntries(
|
|
674
|
+
(object.uses || []).filter((u) => !isObjectRef(u)).map((u) => [u, loadRuleSet(u, d.rulesDir)]),
|
|
675
|
+
)
|
|
676
|
+
: {}),
|
|
677
|
+
...refs.sets,
|
|
678
|
+
}; // a release's own rules
|
|
209
679
|
const display = mirror ? object.mirror || {} : {};
|
|
210
680
|
let resolved;
|
|
211
|
-
try {
|
|
681
|
+
try {
|
|
682
|
+
resolved = resolve(object, { set, sets, display });
|
|
683
|
+
} catch (e) {
|
|
684
|
+
throw located(e, d.json, 'var');
|
|
685
|
+
} // mirror: lighter for the display
|
|
212
686
|
const { values, entries, deps, units } = resolved;
|
|
213
687
|
for (const [n, x] of Object.entries(refs.extra)) Object.assign(values[n], x);
|
|
214
688
|
const files = layoutsOf(d, object);
|
|
215
689
|
if (object.layouts) values.layouts = object.layouts; // older designs kept layouts in their .json
|
|
216
|
-
if (Object.keys(files).length)
|
|
690
|
+
if (Object.keys(files).length)
|
|
691
|
+
values.layouts = Object.fromEntries(
|
|
692
|
+
Object.entries(files).map(([n, l]) => [n, { ...l, keys: keys(l), width: width(l), depth: depth(l) }]),
|
|
693
|
+
);
|
|
217
694
|
// Optimised layouts: a "type": "problem" variable picks a problem in the project's problems/; the design gets the
|
|
218
695
|
// one it picked as v.problems[name] (lib/optimise.mjs), optimised the first time and cached after
|
|
219
696
|
const problems = await problemsOf(d, object, values);
|
|
@@ -222,94 +699,238 @@ export async function build(d, set = {}, { mirror = false } = {}) {
|
|
|
222
699
|
// The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether.
|
|
223
700
|
// What the design reads of its .json is its values, resolved, and its parts' names and roles: a rule's words, a
|
|
224
701
|
// label, a note or the version change nothing it builds, so they aren't in the key
|
|
225
|
-
const ruleText = [
|
|
702
|
+
const ruleText = [
|
|
703
|
+
...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))),
|
|
704
|
+
JSON.stringify(refs.extra),
|
|
705
|
+
];
|
|
226
706
|
const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
|
|
227
707
|
// (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
|
|
228
708
|
const framed = framesContext(RULE_DIRS[0]);
|
|
229
|
-
const key = crypto
|
|
709
|
+
const key = crypto
|
|
710
|
+
.createHash('sha256')
|
|
711
|
+
.update(
|
|
712
|
+
JSON.stringify([
|
|
713
|
+
CACHE_VERSION,
|
|
714
|
+
own,
|
|
715
|
+
framed.hash,
|
|
716
|
+
object.engine === 'pcb' ? engineId() : booleans(object),
|
|
717
|
+
readOwnText(d.js),
|
|
718
|
+
reads,
|
|
719
|
+
ruleText,
|
|
720
|
+
files,
|
|
721
|
+
Object.values(problems).map((p) => p.hash),
|
|
722
|
+
set,
|
|
723
|
+
display,
|
|
724
|
+
]),
|
|
725
|
+
)
|
|
726
|
+
.digest('hex');
|
|
230
727
|
const hit = path.join(CACHE, `${key}.json`);
|
|
231
728
|
// (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
|
|
232
729
|
// while those stand, and is known by them too, so what is kept by a build's hash, an overlap, follows a changed pilot)
|
|
233
|
-
let fx = null;
|
|
234
|
-
const
|
|
730
|
+
let fx = null;
|
|
731
|
+
const fixed = () => (fx ||= fixingsContext(d)),
|
|
732
|
+
known = (f) =>
|
|
733
|
+
f
|
|
734
|
+
? crypto
|
|
735
|
+
.createHash('sha256')
|
|
736
|
+
.update(key + f)
|
|
737
|
+
.digest('hex')
|
|
738
|
+
: key;
|
|
739
|
+
const kept = !process.env.CAD_NO_CACHE && cached(hit) ? JSON.parse(host.readText(hit)) : null;
|
|
235
740
|
if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
|
|
236
741
|
const c = kept;
|
|
237
|
-
try {
|
|
742
|
+
try {
|
|
743
|
+
host.touch(hit);
|
|
744
|
+
} catch {
|
|
745
|
+
// (marked as recently used, so kept when the cache is pruned: only slower if it can't be)
|
|
746
|
+
}
|
|
238
747
|
for (const e of entries) if (c.used.includes(e.name)) e.used = true;
|
|
239
748
|
const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
|
|
240
749
|
if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
|
|
241
|
-
return {
|
|
750
|
+
return {
|
|
751
|
+
object,
|
|
752
|
+
values,
|
|
753
|
+
entries,
|
|
754
|
+
deps,
|
|
755
|
+
units,
|
|
756
|
+
parts,
|
|
757
|
+
polygons: parts.flatMap((p) => p.polygons),
|
|
758
|
+
triangles: parts.flatMap((p) => p.triangles),
|
|
759
|
+
cached: true,
|
|
760
|
+
hash: known(c.fixed),
|
|
761
|
+
...(c.fixings ? { fixings: c.fixings } : {}),
|
|
762
|
+
...(c.mechanism ? { mechanism: c.mechanism } : {}),
|
|
763
|
+
...(c.circuit ? { circuit: c.circuit, matrix: c.matrix, ...(c.source ? { source: c.source } : {}) } : {}),
|
|
764
|
+
};
|
|
242
765
|
}
|
|
243
766
|
|
|
244
|
-
// A
|
|
245
|
-
//
|
|
767
|
+
// A design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach the
|
|
768
|
+
// network), a board design with the board engine there, unless the workspace trusts its designs (runsHere, above)
|
|
246
769
|
const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
|
|
247
|
-
let parts,
|
|
770
|
+
let parts,
|
|
771
|
+
board = null,
|
|
772
|
+
read,
|
|
773
|
+
mechanism = null,
|
|
774
|
+
fixings = null,
|
|
775
|
+
mounted = false;
|
|
248
776
|
const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
|
|
249
|
-
const stages = stageStore();
|
|
250
|
-
if (!
|
|
251
|
-
|
|
777
|
+
const stages = stageStore(d);
|
|
778
|
+
if (!runsHere(trusted)) {
|
|
779
|
+
// The sandbox may read the whole workspace, and follows a link out of it: so the folders this design may read (its
|
|
780
|
+
// project, the rule sets) are looked through first, once a run, and a link that leads out is refused by its name
|
|
781
|
+
noLinksOut([d.dir, path.dirname(path.dirname(d.js)), RULE_DIRS[0], d.rulesDir]);
|
|
782
|
+
let until; // (the design's time limit, here as in its sandbox, where a limit that isn't a number is refused)
|
|
783
|
+
try {
|
|
784
|
+
until = Date.now() + designLimits().timeout * 1000;
|
|
785
|
+
} catch (e) {
|
|
786
|
+
throw located(e, d.js, 'design.limit');
|
|
787
|
+
}
|
|
788
|
+
const r = await host
|
|
789
|
+
.runDesign({
|
|
790
|
+
d,
|
|
791
|
+
values,
|
|
792
|
+
meta: object.parts || {},
|
|
793
|
+
engine: booleans(object),
|
|
794
|
+
optional,
|
|
795
|
+
stages,
|
|
796
|
+
bound: { frames: framed, fixings: fixed().context },
|
|
797
|
+
board: pcb ? { routes: routeStore(d) } : null,
|
|
798
|
+
})
|
|
799
|
+
.catch((e) => {
|
|
800
|
+
throw syntaxAt(e, d);
|
|
801
|
+
});
|
|
802
|
+
({ parts, read, mechanism, fixings } = r);
|
|
803
|
+
if (pcb) {
|
|
804
|
+
board = r.board;
|
|
805
|
+
mounted = r.mounted;
|
|
806
|
+
parts = await boardBuild(pcb, board, values, object, d, until);
|
|
807
|
+
}
|
|
808
|
+
} else {
|
|
809
|
+
mayRunHere(d, trusted);
|
|
252
810
|
flexures.laminaCache(stages);
|
|
253
|
-
const mod = await host.loadModule(d.js).catch((e) => {
|
|
811
|
+
const mod = await host.loadModule(d.js).catch((e) => {
|
|
812
|
+
// a fresh copy after each edit
|
|
254
813
|
// Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
|
|
255
|
-
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@jscad\/modeling/.test(e.message))
|
|
256
|
-
|
|
814
|
+
if (e.code === 'ERR_MODULE_NOT_FOUND' && /@jscad\/modeling/.test(e.message))
|
|
815
|
+
throw new Error(`designs need JSCAD in the workspace: npm install @jscad/modeling (in ${WS})`);
|
|
816
|
+
if (/import statement outside a module/.test(e.message))
|
|
817
|
+
throw new Error(`designs are ES modules: set "type": "module" in ${path.join(WS, 'package.json')}`);
|
|
257
818
|
throw syntaxAt(located(e, d.js, 'design.run'), d);
|
|
258
819
|
});
|
|
259
820
|
if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
|
|
260
|
-
const ops = await shapes.ops(booleans(object)),
|
|
821
|
+
const ops = await shapes.ops(booleans(object)),
|
|
822
|
+
df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
|
|
261
823
|
// v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
|
|
262
|
-
const engine = pcb
|
|
263
|
-
|
|
824
|
+
const engine = pcb
|
|
825
|
+
? {
|
|
826
|
+
...pcb,
|
|
827
|
+
mount: (thread, x, y, o = {}) => {
|
|
828
|
+
mounted = true;
|
|
829
|
+
return pcb.mount(thread, x, y, { sets: fixed().context.sets, ...o });
|
|
830
|
+
},
|
|
831
|
+
}
|
|
832
|
+
: null;
|
|
833
|
+
const w = watch(
|
|
834
|
+
values,
|
|
835
|
+
{
|
|
836
|
+
shapes,
|
|
837
|
+
flexures,
|
|
838
|
+
gears,
|
|
839
|
+
motors,
|
|
840
|
+
frames: designFrames(framed),
|
|
841
|
+
fixings: df.fixings,
|
|
842
|
+
ops,
|
|
843
|
+
...(engine ? { pcb: engine } : {}),
|
|
844
|
+
},
|
|
845
|
+
optional,
|
|
846
|
+
);
|
|
264
847
|
read = w.read;
|
|
265
848
|
let made;
|
|
266
|
-
try {
|
|
267
|
-
|
|
849
|
+
try {
|
|
850
|
+
({ shapes: made, mechanism } = unpack(await mod.main(w.v)));
|
|
851
|
+
} catch (e) {
|
|
852
|
+
throw Object.assign(located(e, d.js, 'design.run'), { line: lineOf(e, pathToFileURL(d.js).href) || undefined });
|
|
853
|
+
}
|
|
854
|
+
if (pcb) {
|
|
855
|
+
// a circuit board: tscircuit builds it, and the bare board is its one part
|
|
268
856
|
const { board: b, matrix, clone } = made && made.board ? made : { board: made }; // clone: a cloned board's { circuit, arranged }, for its checks
|
|
269
857
|
board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}), ...(clone ? { source: clone } : {}) };
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
858
|
+
parts = await boardBuild(pcb, board, values, object, d);
|
|
859
|
+
} else
|
|
860
|
+
try {
|
|
861
|
+
parts = named(made, object.parts || {});
|
|
862
|
+
} catch (e) {
|
|
863
|
+
throw located(e, d.js, 'design.run');
|
|
276
864
|
}
|
|
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'); }
|
|
280
865
|
if (df.used()) fixings = df.found();
|
|
281
866
|
}
|
|
282
867
|
for (const e of entries) if (read.has(e.name)) e.used = true;
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
868
|
+
if (ownCacheFile(hit))
|
|
869
|
+
try {
|
|
870
|
+
prune();
|
|
871
|
+
host.writeText(
|
|
872
|
+
hit,
|
|
873
|
+
JSON.stringify({
|
|
874
|
+
used: entries.filter((e) => e.used).map((e) => e.name),
|
|
875
|
+
parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })),
|
|
876
|
+
...(board || {}),
|
|
877
|
+
...(mechanism ? { mechanism } : {}),
|
|
878
|
+
...(fixings || mounted ? { fixed: fixed().hash } : {}),
|
|
879
|
+
...(fixings ? { fixings } : {}),
|
|
880
|
+
}),
|
|
881
|
+
);
|
|
882
|
+
} catch {
|
|
883
|
+
// (a cache that can't be written is only slower)
|
|
884
|
+
}
|
|
885
|
+
return {
|
|
886
|
+
object,
|
|
887
|
+
values,
|
|
888
|
+
entries,
|
|
889
|
+
deps,
|
|
890
|
+
units,
|
|
891
|
+
parts,
|
|
892
|
+
polygons: parts.flatMap((p) => p.polygons),
|
|
893
|
+
triangles: parts.flatMap((p) => p.triangles),
|
|
894
|
+
hash: known(fixings || mounted ? fixed().hash : null),
|
|
895
|
+
...(fixings ? { fixings } : {}),
|
|
896
|
+
...(board || {}),
|
|
897
|
+
...(mechanism ? { mechanism } : {}),
|
|
898
|
+
};
|
|
288
899
|
}
|
|
289
900
|
|
|
290
901
|
// A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
|
|
291
902
|
const CACHE_KEEP = 800;
|
|
292
903
|
function prune(dir = CACHE, keep = CACHE_KEEP) {
|
|
293
904
|
if (Math.random() > 0.05) return; // now and then is enough
|
|
294
|
-
const files = host
|
|
905
|
+
const files = host
|
|
906
|
+
.list(dir)
|
|
907
|
+
.map((f) => {
|
|
908
|
+
const p = path.join(dir, f);
|
|
909
|
+
return { p, t: host.mtime(p) };
|
|
910
|
+
})
|
|
911
|
+
.sort((a, b) => b.t - a.t);
|
|
295
912
|
for (const { p } of files.slice(keep)) host.remove(p);
|
|
296
913
|
}
|
|
297
914
|
|
|
298
915
|
// The rules of the printer a build is checked against (the project's, else the workspace's), resolved
|
|
299
|
-
export const printer = (b, d) => {
|
|
916
|
+
export const printer = (b, d) => {
|
|
917
|
+
const n = printerOf(d.project);
|
|
918
|
+
return b.values[n] || resolve({ uses: [n] }).values[n];
|
|
919
|
+
};
|
|
300
920
|
|
|
301
921
|
// Only some parts: --part cap (by name), the real parts without supports, or what the mirror shows (no supports, and
|
|
302
922
|
// no parts marked mirror: false).
|
|
303
923
|
export function pick(b, { part, noSupports = false, forMirror = false } = {}) {
|
|
304
924
|
let parts = b.parts;
|
|
305
|
-
if (part) {
|
|
925
|
+
if (part) {
|
|
926
|
+
parts = parts.filter((p) => p.name === part);
|
|
927
|
+
if (!parts.length) throw new Error(`no part "${part}" (parts: ${b.parts.map((p) => p.name).join(', ')})`);
|
|
928
|
+
}
|
|
306
929
|
if (noSupports || forMirror) parts = parts.filter((p) => p.role !== 'support');
|
|
307
930
|
if (forMirror) parts = parts.filter((p) => p.mirror !== false);
|
|
308
931
|
return { ...b, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
|
|
309
932
|
}
|
|
310
933
|
|
|
311
|
-
|
|
312
|
-
|
|
313
934
|
export { lint } from '@rulecad/variables'; // number literals that should be variables
|
|
314
935
|
|
|
315
936
|
export { jscad };
|