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