@rulecad/cad 0.8.0 → 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.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/design.mjs CHANGED
@@ -15,12 +15,14 @@
15
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
16
  // it hands back its circuit as data, and the tool makes the board's solid from it (boardBuild).
17
17
  // Builds are cached in .cache/builds/, by everything they're made from (CAD_NO_CACHE=1 to skip), and a lamina's slow
18
- // stages apart in .cache/stages/ (see stageStore).
18
+ // stages apart in .cache/stages/<design>/, a folder for each design (see stageStore).
19
19
  import { spawnSync } from 'node:child_process';
20
20
  import { located, lineOf } from './errors.mjs';
21
- import { host, readJson } from './host.mjs';
21
+ import { host, readJson, cached } from './host.mjs';
22
22
  import { named, faces, fromFaces, polygons, unpack, watch } from './parts.mjs';
23
- import { sandboxed, canSandbox, stageFile, ROUTE_KEY } from './sandbox.mjs';
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';
24
26
  export { polygons };
25
27
  import fs from 'node:fs';
26
28
  import path from 'node:path';
@@ -28,9 +30,9 @@ import { pathToFileURL, fileURLToPath } from 'node:url';
28
30
  import { createRequire } from 'node:module';
29
31
  import crypto from 'node:crypto';
30
32
  import { resolve, loadRuleSet } from './rules.mjs';
31
- import { WS, paths, printerOf, RULE_DIRS } from './workspace.mjs';
33
+ import { WS, paths, printerOf, RULE_DIRS, readOwnText, noLinksOut } from './workspace.mjs';
32
34
  import { readLayout, hasLayout, keys, width, depth } from './layout.mjs';
33
- import { optimised, forDesign } from './optimise.mjs';
35
+ import { optimised, forDesign, ownResults } from './optimise.mjs';
34
36
  import * as shapes from '@rulecad/shapes';
35
37
  import * as flexures from '@rulecad/flexures';
36
38
  import * as gears from '@rulecad/gears';
@@ -58,9 +60,17 @@ export function locate(ref) {
58
60
  return designAt(base, variant);
59
61
  }
60
62
  const designAt = (base, variant) => {
61
- if (!host.exists(`${base}.json`) || !host.exists(`${base}.js`)) throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
63
+ if (!host.exists(`${base}.json`) || !host.exists(`${base}.js`))
64
+ throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
62
65
  const dir = path.dirname(path.dirname(base));
63
- return { project: path.basename(dir), name: path.basename(base), js: `${base}.js`, json: `${base}.json`, dir, ...(variant ? { variant } : {}) };
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
+ };
64
74
  };
65
75
  /**
66
76
  * A design named in a workspace's own file (an assembly's item, a project's "objects", a problem's): `name` is an
@@ -81,58 +91,101 @@ export function locateIn(project, name, where) {
81
91
  export const isObjectRef = (u) => String(u).includes('/');
82
92
  const building = new Set();
83
93
  export async function objectSets(d, object, { trusted = false } = {}) {
84
- const refs = (object.uses || []).filter(isObjectRef), sets = {}, extra = {};
94
+ const refs = (object.uses || []).filter(isObjectRef),
95
+ sets = {},
96
+ extra = {};
85
97
  // 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"`);
98
+ for (const u of object.uses || [])
99
+ if (!isObjectRef(u)) plainName(u, 'rule set name', `${path.relative(WS, d.json)}, in its "uses"`);
87
100
  if (!refs.length) return { sets, extra };
88
101
  const self = `${d.project}/${d.name}`;
89
102
  building.add(self);
90
103
  try {
91
104
  for (const u of refs) {
92
105
  // (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`);
94
- const [ref, want] = u.split('@'), exact = /^\d+\.\d+\.\d+$/.test(want || '');
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`);
96
- const base = locateIn(...ref.split('/')), b = await build(exact ? materialise(base, want) : base, {}, { trusted }), version = b.object.version;
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}`);
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
+ );
98
123
  const units = Object.fromEntries(Object.entries(b.object.variables || {}).map(([k, x]) => [k, x.unit]));
99
124
  const rules = {};
100
- for (const [k, v] of Object.entries(b.values)) if (typeof v === 'number' && Number.isFinite(v)) {
101
- rules[k] = { value: v, ...(units[k] ? { unit: units[k] } : {}), rule: `${ref}'s ${k}`, kind: 'design', source: `${ref}@${version}` }; // no unit: a count (turns, segments), not a length
102
- }
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
+ }
103
135
  sets[u] = { name: base.name, rules };
104
- if (b.circuit) { const e = await pcbEngine(), board = b.circuit.find((x) => x.type === 'pcb_board'); extra[base.name] = { board_holes: e.holes(b.circuit), board_parts: e.parts ? e.parts(b.circuit) : {}, ...(board.outline ? { board_outline: board.outline } : {}) }; }
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
+ }
105
145
  }
106
- } finally { building.delete(self); }
146
+ } finally {
147
+ building.delete(self);
148
+ }
107
149
  return { sets, extra };
108
150
  }
109
151
 
110
152
  // The layouts an object can pick, by name, from its layout variables' choices (built-ins like grid have no file)
111
153
  export function layoutsOf(d, object) {
112
154
  const out = {};
113
- for (const v of Object.values(object.variables || {})) if (v.type === 'layout') {
114
- for (const n of v.choice || [v.value]) if (hasLayout(d.project, n, d.layoutsDir)) out[n] = readLayout(d.project, n, d.layoutsDir);
115
- }
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
+ }
116
160
  return out;
117
161
  }
118
162
 
119
163
  // The optimised layouts an object's problem variables pick, by name, for v.problems
120
164
  export async function problemsOf(d, object, values) {
121
165
  const out = {};
122
- for (const [name, v] of Object.entries(object.variables || {})) if (v.type === 'problem') {
123
- const ref = values[name];
124
- if (!ref || ref === 'none') continue; // a variant that draws without the optimiser (a test rig, or the regions a problem reads)
125
- if (!out[ref]) {
126
- // Optimising here can take an hour on a big solid: say so, why, and (on a terminal) how far it's got
127
- const live = process.stderr.isTTY;
128
- const r = await optimised(d.project, ref, {
129
- onRun: (why) => console.error(`optimising ${ref} (${why}; the result is kept until the problem or the solver changes)…`),
130
- onStep: (s) => { if (live) process.stderr.write(`\r\x1b[Koptimising ${ref}: step ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm`); if (s.step === s.steps && live) process.stderr.write('\r\x1b[K'); },
131
- });
132
- if (live) process.stderr.write('\r\x1b[K');
133
- out[ref] = forDesign(r);
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
+ }
134
188
  }
135
- }
136
189
  return out;
137
190
  }
138
191
 
@@ -140,28 +193,68 @@ export async function problemsOf(d, object, values) {
140
193
  export function variantSet(d, object, set = {}) {
141
194
  if (!d.variant) return set;
142
195
  const v = (object.variants || {})[d.variant];
143
- if (!v) throw new Error(`${d.name} has no variant "${d.variant}" (variants: ${Object.keys(object.variants || {}).join(', ') || 'none'})`);
196
+ if (!v)
197
+ throw new Error(
198
+ `${d.name} has no variant "${d.variant}" (variants: ${Object.keys(object.variants || {}).join(', ') || 'none'})`,
199
+ );
144
200
  return { ...v, ...set };
145
201
  }
146
202
 
147
- const CACHE = paths.cache('builds'), CACHE_VERSION = 3;
203
+ const CACHE = paths.cache('builds'),
204
+ CACHE_VERSION = 3;
148
205
  // The autorouter's results too, by its exact input (@rulecad/pcb reads RULECAD_ROUTE_CACHE): a board rebuilt for anything
149
206
  // but its routing (a change to the library, its finish, its checks) reuses its route instead of searching again
150
207
  if (!process.env.CAD_NO_CACHE) process.env.RULECAD_ROUTE_CACHE ||= paths.cache('routes');
151
208
  const source = (f) => fs.readFileSync(new URL(f, import.meta.url), 'utf8');
152
209
  // What every build is made with: this code, the shape helpers and JSCAD's version (an upgrade rebuilds everything);
153
210
  // boards also with the board engine (engineId: its code and tscircuit's version), loaded only for boards
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')));
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')));
155
217
  // (every module of a helper package but its tests: they change nothing a design builds; nor a dot-file, which is a
156
218
  // 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('');
158
- const feaDir = path.dirname(createRequire(pathToFileURL(path.join(flexuresDir, 'package.json')).href).resolve('@rulecad/fea')); // (flexures' own, wherever npm put it)
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)
159
229
  // (as one digest, so each build's key hashes a line and not a megabyte of source)
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
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
161
246
  // A lamina's slow stages (the physics, the flood's probe) are kept apart from the builds, keyed by the library's code
162
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
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
164
- const STAGES = paths.cache('stages'), stageSalt = crypto.createHash('sha256').update(helperSources(flexuresDir) + helperSources(feaDir)).digest('hex');
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');
165
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
166
259
  // (the trust list, say) would have the tool write what a sandboxed design handed back through it, and a cache folder
167
260
  // that is a link would have cache files written, and pruned, somewhere else. So a cache file is written only when it
@@ -173,32 +266,137 @@ function ownCacheFile(file, root = WS) {
173
266
  if (!p.startsWith(top + path.sep)) return false;
174
267
  for (let first = true; p !== top; p = path.dirname(p), first = false) {
175
268
  let st;
176
- try { st = fs.lstatSync(p); } catch (e) { if (e.code === 'ENOENT') continue; return false; }
269
+ try {
270
+ st = fs.lstatSync(p);
271
+ } catch (e) {
272
+ if (e.code === 'ENOENT') continue;
273
+ return false;
274
+ }
177
275
  if (first ? !(st.isFile() && st.nlink === 1) : !st.isDirectory()) return false;
178
276
  }
179
277
  return true;
180
278
  }
181
- const stageStore = () => ({
182
- salt: stageSalt,
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)
187
- });
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)
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
+ };
197
393
  };
198
- export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
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');
200
- throw e;
201
- });
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
+ });
202
400
 
203
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:
204
402
  // its threads and materials are used before the kit's), the project's printer as a rule set with its values worked
@@ -206,27 +404,87 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
206
404
  // made from these too, so its cache holds only while they stand.
207
405
  let kitRules = null;
208
406
  export function fixingsContext(d) {
209
- const dir = d.rulesDir || RULE_DIRS[0], sets = {}, text = [];
210
- for (const f of host.list(dir).filter((x) => x.endsWith('.json')).sort()) {
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)
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
+ }
212
424
  }
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); };
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
+ };
214
432
  let printer = null;
215
- try { // (a printer with no rule set is said where a print is checked; fixings then draws for the kit's)
216
- const set = peek(name), values = resolveWith({ uses: [name] }, { load: peek }).values[name];
217
- printer = { name: set.name ?? name, rules: Object.fromEntries(Object.entries(set.rules).map(([k, r]) => [k, typeof values[k] === 'number' ? { ...r, value: values[k] } : r])) };
218
- } catch {}
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
+ }
219
446
  let material = null;
220
- try { const f = path.join(d.dir, 'project.json'); if (host.exists(f)) material = String(readJson(f).material || '').trim().toLowerCase().split(/\s/)[0] || null; } catch {}
221
- kitRules ||= (() => { const k = RULE_DIRS.at(-1); return crypto.createHash('sha256').update(fs.readdirSync(k).filter((f) => f.endsWith('.json')).sort().map((f) => fs.readFileSync(path.join(k, f), 'utf8')).join('')).digest('hex'); })();
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
+ })();
222
472
  const context = { sets, printer, material };
223
- return { context, hash: crypto.createHash('sha256').update(JSON.stringify([text, printer, material, kitRules])).digest('hex').slice(0, 24) };
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
+ };
224
481
  }
225
482
 
226
483
  // An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
227
484
  // Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
228
485
  // Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
229
- export const booleans = (object) => (object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad');
486
+ export const booleans = (object) =>
487
+ object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad';
230
488
 
231
489
  export const readObject = (d) => {
232
490
  const o = readJson(d.json);
@@ -241,7 +499,10 @@ function syntaxAt(e, d) {
241
499
  if (e?.name !== 'SyntaxError' || e.line || host.name !== 'node') return e;
242
500
  const r = spawnSync(process.execPath, ['--check', d.js], { encoding: 'utf8' });
243
501
  const m = r.status ? String(r.stderr).match(/^(?:file:\/\/)?.*?:(\d+)\r?\n(.*)\r?\n/) : null;
244
- if (m) { e.line = Number(m[1]); e.message = `${e.message}: ${m[2].trim()}`; }
502
+ if (m) {
503
+ e.line = Number(m[1]);
504
+ e.message = `${e.message}: ${m[2].trim()}`;
505
+ }
245
506
  return e;
246
507
  }
247
508
 
@@ -259,16 +520,35 @@ function runsHere(trusted) {
259
520
  // workspace's file, or a link out of it) is refused here, to be run from its own workspace once that is trusted.
260
521
  function mayRunHere(d, trusted) {
261
522
  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); };
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
+ };
264
534
  const away = [d.json, d.js].find(outside); // (the .js is the code that runs: a link to one elsewhere is elsewhere)
265
535
  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' });
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
+ );
267
542
  }
268
543
  return;
269
544
  }
270
545
  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' });
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
+ );
272
552
  }
273
553
 
274
554
  // A board's build from its Circuit JSON, wherever the design ran: what it tells the parts around it (outline, holes,
@@ -276,22 +556,108 @@ function mayRunHere(d, trusted) {
276
556
  // fetched into the workspace's models/: a design never reads files; cad does). The circuit may be a sandboxed design's
277
557
  // reply, so a model is read only from a plain relative .json path inside the workspace, and only where it really is
278
558
  // 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) {
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) {
280
563
  Object.assign(values, pcb.outputs(board.circuit, board.matrix));
281
564
  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)
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)
283
567
  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; }
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
+ }
285
574
  };
286
575
  for (const c of board.circuit.filter((e) => e.type === 'cad_component' && e.rulecad_model?.mesh)) {
287
576
  const f = c.rulecad_model.mesh;
288
577
  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('..');
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('..');
291
582
  meshes[f] = plainPath && host.exists(file) && inWs(file) ? JSON.parse(host.readText(file)).triangles : null;
292
583
  }
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'); }
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);
295
661
  }
296
662
 
297
663
  // build(design, set, { mirror, trusted }) -> { object, values, entries, parts, polygons (for the mirror), triangles (for checks and export), fixings? }
@@ -302,15 +668,29 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
302
668
  const object = readObject(d);
303
669
  set = variantSet(d, object, set);
304
670
  const refs = await objectSets(d, object, { trusted }); // other objects' numbers, when it reads them
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
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
306
679
  const display = mirror ? object.mirror || {} : {};
307
680
  let resolved;
308
- try { resolved = resolve(object, { set, sets, display }); } catch (e) { throw located(e, d.json, 'var'); } // mirror: lighter for the display
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
309
686
  const { values, entries, deps, units } = resolved;
310
687
  for (const [n, x] of Object.entries(refs.extra)) Object.assign(values[n], x);
311
688
  const files = layoutsOf(d, object);
312
689
  if (object.layouts) values.layouts = object.layouts; // older designs kept layouts in their .json
313
- if (Object.keys(files).length) values.layouts = Object.fromEntries(Object.entries(files).map(([n, l]) => [n, { ...l, keys: keys(l), width: width(l), depth: depth(l) }]));
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
+ );
314
694
  // Optimised layouts: a "type": "problem" variable picks a problem in the project's problems/; the design gets the
315
695
  // one it picked as v.problems[name] (lib/optimise.mjs), optimised the first time and cached after
316
696
  const problems = await problemsOf(d, object, values);
@@ -319,90 +699,238 @@ export async function build(d, set = {}, { mirror = false, trusted = false } = {
319
699
  // The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether.
320
700
  // What the design reads of its .json is its values, resolved, and its parts' names and roles: a rule's words, a
321
701
  // label, a note or the version change nothing it builds, so they aren't in the key
322
- const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
702
+ const ruleText = [
703
+ ...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))),
704
+ JSON.stringify(refs.extra),
705
+ ];
323
706
  const reads = { values, parts: object.parts, engine: object.engine, mirror: object.mirror };
324
707
  // (v.frames reads the workspace's own profile sets: a build is made from them too, lib/frames.mjs)
325
708
  const framed = framesContext(RULE_DIRS[0]);
326
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, framed.hash, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), reads, ruleText, files, Object.values(problems).map((p) => p.hash), set, display])).digest('hex');
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');
327
727
  const hit = path.join(CACHE, `${key}.json`);
328
728
  // (a build that called v.fixings is also made from the workspace's thread sets, its printer and material: it holds
329
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)
330
- let fx = null; const fixed = () => (fx ||= fixingsContext(d)), known = (f) => (f ? crypto.createHash('sha256').update(key + f).digest('hex') : key);
331
- const kept = !process.env.CAD_NO_CACHE && host.exists(hit) ? JSON.parse(host.readText(hit)) : null;
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;
332
740
  if (kept && (!kept.fixed || kept.fixed === fixed().hash)) {
333
741
  const c = kept;
334
- try { host.touch(hit); } catch {} // recently used: kept when the cache is pruned
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
+ }
335
747
  for (const e of entries) if (c.used.includes(e.name)) e.used = true;
336
748
  const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
337
749
  if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
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 } : {}) } : {}) };
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
+ };
339
765
  }
340
766
 
341
767
  // A design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach the
342
768
  // network), a board design with the board engine there, unless the workspace trusts its designs (runsHere, above)
343
769
  const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
344
- let parts, board = null, read, mechanism = null, fixings = null, mounted = false;
770
+ let parts,
771
+ board = null,
772
+ read,
773
+ mechanism = null,
774
+ fixings = null,
775
+ mounted = false;
345
776
  const optional = Object.keys(object.mirror || {}); // inputs only the on-screen copy has: main may ask for them when they aren't there
346
- const stages = stageStore();
777
+ const stages = stageStore(d);
347
778
  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); });
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
+ });
349
802
  ({ parts, read, mechanism, fixings } = r);
350
- if (pcb) { board = r.board; mounted = r.mounted; parts = boardBuild(pcb, board, values, object, d); }
803
+ if (pcb) {
804
+ board = r.board;
805
+ mounted = r.mounted;
806
+ parts = await boardBuild(pcb, board, values, object, d, until);
807
+ }
351
808
  } else {
352
809
  mayRunHere(d, trusted);
353
810
  flexures.laminaCache(stages);
354
- const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
811
+ const mod = await host.loadModule(d.js).catch((e) => {
812
+ // a fresh copy after each edit
355
813
  // Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
356
- if (e.code === 'ERR_MODULE_NOT_FOUND' && /@jscad\/modeling/.test(e.message)) throw new Error(`designs need JSCAD in the workspace: npm install @jscad/modeling (in ${WS})`);
357
- if (/import statement outside a module/.test(e.message)) throw new Error(`designs are ES modules: set "type": "module" in ${path.join(WS, 'package.json')}`);
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')}`);
358
818
  throw syntaxAt(located(e, d.js, 'design.run'), d);
359
819
  });
360
820
  if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
361
- const ops = await shapes.ops(booleans(object)), df = (await import('./fixings.mjs')).designFixings({ ...fixed().context, ops }); // (loaded when a design is run here: the sandbox's runner has its own)
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)
362
823
  // v.pcb.mount('M2', ...) reads the workspace's thread sets, as v.fixings does: such a build is known by them too
363
- const engine = pcb ? { ...pcb, mount: (thread, x, y, o = {}) => { mounted = true; return pcb.mount(thread, x, y, { sets: fixed().context.sets, ...o }); } } : null;
364
- const w = watch(values, { shapes, flexures, gears, motors, frames: designFrames(framed), fixings: df.fixings, ops, ...(engine ? { pcb: engine } : {}) }, optional);
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
+ );
365
847
  read = w.read;
366
848
  let made;
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 }); }
368
- if (pcb) { // a circuit board: tscircuit builds it, and the bare board is its one part
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
369
856
  const { board: b, matrix, clone } = made && made.board ? made : { board: made }; // clone: a cloned board's { circuit, arranged }, for its checks
370
857
  board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}), ...(clone ? { source: clone } : {}) };
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'); }
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');
864
+ }
373
865
  if (df.used()) fixings = df.found();
374
866
  }
375
867
  for (const e of entries) if (read.has(e.name)) e.used = true;
376
- if (ownCacheFile(hit)) try {
377
- prune();
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 } : {}) }));
379
- } catch {} // a cache that can't be written is only slower
380
- return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: known(fixings || mounted ? fixed().hash : null), ...(fixings ? { fixings } : {}), ...(board || {}), ...(mechanism ? { mechanism } : {}) };
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
+ };
381
899
  }
382
900
 
383
901
  // A cache keeps its most recently used files, about `keep` of them (an old version's builds go first)
384
902
  const CACHE_KEEP = 800;
385
903
  function prune(dir = CACHE, keep = CACHE_KEEP) {
386
904
  if (Math.random() > 0.05) return; // now and then is enough
387
- const files = host.list(dir).map((f) => { const p = path.join(dir, f); return { p, t: host.mtime(p) }; }).sort((a, b) => b.t - a.t);
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);
388
912
  for (const { p } of files.slice(keep)) host.remove(p);
389
913
  }
390
914
 
391
915
  // The rules of the printer a build is checked against (the project's, else the workspace's), resolved
392
- export const printer = (b, d) => { const n = printerOf(d.project); return b.values[n] || resolve({ uses: [n] }).values[n]; };
916
+ export const printer = (b, d) => {
917
+ const n = printerOf(d.project);
918
+ return b.values[n] || resolve({ uses: [n] }).values[n];
919
+ };
393
920
 
394
921
  // Only some parts: --part cap (by name), the real parts without supports, or what the mirror shows (no supports, and
395
922
  // no parts marked mirror: false).
396
923
  export function pick(b, { part, noSupports = false, forMirror = false } = {}) {
397
924
  let parts = b.parts;
398
- if (part) { parts = parts.filter((p) => p.name === part); if (!parts.length) throw new Error(`no part "${part}" (parts: ${b.parts.map((p) => p.name).join(', ')})`); }
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
+ }
399
929
  if (noSupports || forMirror) parts = parts.filter((p) => p.role !== 'support');
400
930
  if (forMirror) parts = parts.filter((p) => p.mirror !== false);
401
931
  return { ...b, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
402
932
  }
403
933
 
404
-
405
-
406
934
  export { lint } from '@rulecad/variables'; // number literals that should be variables
407
935
 
408
936
  export { jscad };