@rulecad/cad 0.9.0 → 0.11.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 (68) hide show
  1. package/AGENTS.md +29 -10
  2. package/CHANGELOG.md +604 -0
  3. package/EXAMPLES.md +122 -105
  4. package/README.md +292 -63
  5. package/bin/cad.mjs +500 -87
  6. package/lib/assembly.mjs +486 -134
  7. package/lib/bays.mjs +124 -0
  8. package/lib/cache-file.mjs +148 -0
  9. package/lib/clone.mjs +93 -11
  10. package/lib/code-text.mjs +28 -0
  11. package/lib/design-imports.mjs +127 -0
  12. package/lib/design.mjs +291 -59
  13. package/lib/designshapes.mjs +142 -0
  14. package/lib/edit.mjs +29 -5
  15. package/lib/estimates.mjs +51 -0
  16. package/lib/fasten.mjs +11 -5
  17. package/lib/fe-key.mjs +29 -0
  18. package/lib/fittings.mjs +20 -15
  19. package/lib/fixings.mjs +17 -4
  20. package/lib/framebuild.mjs +73 -92
  21. package/lib/framecheck.mjs +154 -77
  22. package/lib/framegen.mjs +9 -1
  23. package/lib/frames.mjs +6 -2
  24. package/lib/framesize.mjs +45 -82
  25. package/lib/gait.mjs +17 -7
  26. package/lib/guides.mjs +84 -50
  27. package/lib/host.mjs +7 -3
  28. package/lib/kit.mjs +5 -5
  29. package/lib/list.mjs +29 -21
  30. package/lib/live-guard.mjs +18 -8
  31. package/lib/loads.mjs +35 -23
  32. package/lib/measured.mjs +740 -99
  33. package/lib/mesh.mjs +156 -56
  34. package/lib/motors.mjs +26 -33
  35. package/lib/names.mjs +15 -0
  36. package/lib/node-version.mjs +52 -0
  37. package/lib/optimise.mjs +34 -25
  38. package/lib/order.mjs +5 -12
  39. package/lib/parts.mjs +3 -0
  40. package/lib/picture-servers.mjs +66 -0
  41. package/lib/power.mjs +14 -7
  42. package/lib/preview.mjs +12 -25
  43. package/lib/programs.mjs +113 -0
  44. package/lib/rules.mjs +2 -1
  45. package/lib/sandbox-guard.mjs +43 -0
  46. package/lib/sandbox-hooks.mjs +109 -15
  47. package/lib/sandbox-lock.mjs +225 -0
  48. package/lib/sandbox-preload.mjs +2 -2
  49. package/lib/sandbox-run.mjs +22 -24
  50. package/lib/sandbox.mjs +345 -42
  51. package/lib/sheet.mjs +114 -3
  52. package/lib/targets/gist.mjs +9 -6
  53. package/lib/versions.mjs +294 -35
  54. package/lib/workspace.mjs +6 -3
  55. package/package.json +14 -14
  56. package/schemas/assembly.schema.json +6 -5
  57. package/schemas/object.schema.json +1 -1
  58. package/schemas/project.schema.json +6 -0
  59. package/templates/coupons/MEASURE.md +109 -0
  60. package/templates/coupons/assemblies/fixings-test.json +20 -0
  61. package/templates/coupons/assemblies/slot-test.json +11 -0
  62. package/templates/coupons/objects/fixings-coupon.js +88 -0
  63. package/templates/coupons/objects/fixings-coupon.json +26 -0
  64. package/templates/coupons/objects/holds-coupon.js +130 -0
  65. package/templates/coupons/objects/holds-coupon.json +42 -0
  66. package/templates/coupons/objects/slot-coupon.js +89 -0
  67. package/templates/coupons/objects/slot-coupon.json +29 -0
  68. package/templates/coupons/project.json +10 -0
package/lib/mesh.mjs CHANGED
@@ -7,7 +7,9 @@
7
7
  // align(moving, fixed) -> the turn and shift that best lays moving over fixed
8
8
  // deviation(from, to) -> how far points on one surface are from the other, signed (+ outside, - inside)
9
9
  import fs from 'node:fs';
10
+ import path from 'node:path';
10
11
  import zlib from 'node:zlib';
12
+ import { constants as bufferLimits } from 'node:buffer';
11
13
 
12
14
  export const AXES = ['x', 'y', 'z'];
13
15
  export const axisOf = (a) => {
@@ -21,22 +23,66 @@ export const planeAxes = (axis) => (axis === 2 ? [0, 1] : axis === 1 ? [0, 2] :
21
23
  // ---- reading ----
22
24
 
23
25
  export function readMesh(file) {
24
- const buf = fs.readFileSync(file);
25
- if (/\.3mf$/i.test(file)) return read3mf(buf);
26
- if (/\.stl$/i.test(file)) return readStl(buf);
26
+ let buf;
27
+ try {
28
+ buf = fs.readFileSync(file);
29
+ } catch (e) {
30
+ // (what Node can't read at once is said as what it is: its own words name neither the file nor a way on)
31
+ const why =
32
+ e.code === 'ERR_FS_FILE_TOO_LARGE'
33
+ ? 'more than 2 GB, the most cad reads of a file'
34
+ : e.code === 'EISDIR'
35
+ ? 'a folder, not an STL or 3MF file'
36
+ : null;
37
+ if (!why) throw e;
38
+ throw new Error(`${path.basename(file)}: ${why}`, { cause: e });
39
+ }
40
+ // (what is wrong with the file is said with its name, as `cad measure a.3mf b.stl` reads two)
41
+ const named = (read) => {
42
+ try {
43
+ return read(buf);
44
+ } catch (e) {
45
+ throw new Error(`${path.basename(file)}: ${e.message}`, { cause: e });
46
+ }
47
+ };
48
+ if (/\.3mf$/i.test(file)) return named(read3mf);
49
+ if (/\.stl$/i.test(file)) return named(readStl);
27
50
  throw new Error(`${file}: an STL or 3MF, please (export STEP files from a CAD program as STL first)`);
28
51
  }
29
52
 
30
53
  // What cad reads from a file it did not make (an STL or 3MF from the internet): past these, the file is refused with
31
54
  // the limit named, rather than left to fill memory. Two million triangles is about 660 MB as cad holds them, and more
32
55
  // than a detailed print-ready model has; a 3MF that places its objects more than a hundred thousand times is made to
33
- // hurt, not to print; 512 MB is what its zip may unpack to.
34
- export const MESH_LIMITS = { triangles: 2_000_000, places: 100_000, unzipped: 512 * 1024 * 1024 };
56
+ // hurt, not to print; 512 MB is what its zip may unpack to; 16 is how deep a 3MF's objects may sit inside each other
57
+ // (a deeper one, or one that holds itself, is refused rather than read with its deeper parts left out); 64 MB is the
58
+ // most `cad clone` downloads or reads for a board or one of its parts' models (KiCad's largest are a few MB); text is
59
+ // the longest text Node holds (a little under 512 MB of characters): a 3MF's model file or a text STL past it is
60
+ // refused in cad's words, since Node's own ("Cannot create a string longer than 0x1fffffe8 characters") name nothing.
61
+ export const MESH_LIMITS = {
62
+ triangles: 2_000_000,
63
+ places: 100_000,
64
+ unzipped: 512 * 1024 * 1024,
65
+ depth: 16,
66
+ download: 64 * 1024 * 1024,
67
+ text: bufferLimits.MAX_STRING_LENGTH,
68
+ };
69
+ // A file's bytes as text, refused if they are more than Node holds as one text (what: the file, for the message)
70
+ function asText(buf, what, longest = MESH_LIMITS.text) {
71
+ if (buf.length > longest)
72
+ throw new Error(`${what} is more than ${Math.floor(longest / (1024 * 1024))} MB of text, the most cad reads`);
73
+ return buf.toString('utf8');
74
+ }
35
75
  const grouped = (n) => n.toLocaleString('en-GB');
76
+ // A name out of a file from elsewhere, fit to say in a message: a damaged or hostile file can hold anything there, so
77
+ // a character that is not print (one that could move a terminal's cursor, say) is shown as "?", and a long name is cut.
78
+ const sayable = (name) => {
79
+ const s = String(name).replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, '?');
80
+ return s.length > 80 ? `${s.slice(0, 80)}...` : s;
81
+ };
36
82
  const finite = (v) => v.length === 3 && v.every(Number.isFinite);
37
83
 
38
- // readStl(buf, { triangles }) -> triangles; refuses a corner that is not three numbers, and a file past the limit
39
- export function readStl(buf, { triangles: most = MESH_LIMITS.triangles } = {}) {
84
+ // readStl(buf, { triangles, text }) -> triangles; refuses a corner that is not three numbers, and a file past a limit
85
+ export function readStl(buf, { triangles: most = MESH_LIMITS.triangles, text: longest = MESH_LIMITS.text } = {}) {
40
86
  const n = buf.length >= 84 ? buf.readUInt32LE(80) : -1;
41
87
  if (n >= 0 && 84 + n * 50 === buf.length) {
42
88
  // binary
@@ -53,7 +99,7 @@ export function readStl(buf, { triangles: most = MESH_LIMITS.triangles } = {}) {
53
99
  return tris;
54
100
  }
55
101
  const pts = [];
56
- for (const m of buf.toString('utf8').matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)) {
102
+ for (const m of asText(buf, 'the STL', longest).matchAll(/vertex\s+(\S+)\s+(\S+)\s+(\S+)/g)) {
57
103
  const p = [+m[1], +m[2], +m[3]];
58
104
  if (!finite(p)) {
59
105
  const k = pts.length;
@@ -70,49 +116,16 @@ export function readStl(buf, { triangles: most = MESH_LIMITS.triangles } = {}) {
70
116
  }
71
117
 
72
118
  // A zip's files by name (stored or deflated), from its central directory. What it unpacks, all entries together, may
73
- // come to `max` bytes (512 MB): a zip made to unpack far past its size is refused, not unpacked into memory.
119
+ // come to `max` bytes (512 MB): a zip made to unpack far past its size is refused, not unpacked into memory. Every
120
+ // place and size the file gives is held against its length before it is read: one that points past the end is a
121
+ // damaged zip file, said with the entry, not Node's own "out of range".
74
122
  export function unzip(buf, { max = MESH_LIMITS.unzipped } = {}) {
75
- let e = buf.length - 22;
76
- while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
77
- if (e < 0) throw new Error('not a zip file');
78
- let count = buf.readUInt16LE(e + 10),
79
- p = buf.readUInt32LE(e + 16);
80
- if (p === 0xffffffff && e >= 20 && buf.readUInt32LE(e - 20) === 0x07064b50) {
81
- // Zip64: the real numbers are in its own record
82
- const z = Number(buf.readBigUInt64LE(e - 12));
83
- count = Number(buf.readBigUInt64LE(z + 32));
84
- p = Number(buf.readBigUInt64LE(z + 48));
85
- }
86
123
  const files = {},
87
124
  tooBig = () => new Error(`the zip unpacks to more than ${max / (1024 * 1024)} MB, the most cad reads`);
88
- let left = max;
125
+ let [count, p] = zipList(buf),
126
+ left = max;
89
127
  for (let i = 0; i < count; i++) {
90
- if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('a damaged zip file');
91
- const method = buf.readUInt16LE(p + 10),
92
- nameLen = buf.readUInt16LE(p + 28);
93
- const extraLen = buf.readUInt16LE(p + 30),
94
- noteLen = buf.readUInt16LE(p + 32);
95
- let local = buf.readUInt32LE(p + 42),
96
- csize = buf.readUInt32LE(p + 20);
97
- const name = buf.toString('utf8', p + 46, p + 46 + nameLen);
98
- // Zip64: sizes and offset in the extra field when the 32-bit ones are 0xffffffff
99
- const ext = buf.subarray(p + 46 + nameLen, p + 46 + nameLen + extraLen);
100
- for (let q = 0; q + 4 <= ext.length;) {
101
- const id = ext.readUInt16LE(q),
102
- len = ext.readUInt16LE(q + 2);
103
- if (id === 1) {
104
- let r = q + 4;
105
- if (buf.readUInt32LE(p + 24) === 0xffffffff) r += 8; // uncompressed size
106
- if (buf.readUInt32LE(p + 20) === 0xffffffff) {
107
- csize = Number(ext.readBigUInt64LE(r));
108
- r += 8;
109
- }
110
- if (local === 0xffffffff) local = Number(ext.readBigUInt64LE(r));
111
- }
112
- q += 4 + len;
113
- }
114
- const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
115
- const data = buf.subarray(start, start + csize);
128
+ const { name, entry, method, data, next } = zipEntry(buf, p, i);
116
129
  let file = null;
117
130
  if (method === 8)
118
131
  try {
@@ -120,26 +133,103 @@ export function unzip(buf, { max = MESH_LIMITS.unzipped } = {}) {
120
133
  file = zlib.inflateRawSync(data, { maxOutputLength: left + 1 });
121
134
  } catch (err) {
122
135
  if (err.code === 'ERR_BUFFER_TOO_LARGE') throw tooBig();
136
+ if (/^Z_/.test(err.code || '')) throw damagedZip(`${entry} doesn't unpack (${err.message})`);
123
137
  throw err;
124
138
  }
125
139
  else if (method === 0) file = data;
126
140
  if (file && (left -= file.length) < 0) throw tooBig();
127
141
  files[name] = file;
128
- p += 46 + nameLen + extraLen + noteLen;
142
+ p = next;
129
143
  }
130
144
  return files;
131
145
  }
146
+ const damagedZip = (what) => new Error(`a damaged zip file: ${what}`);
147
+ // Whether the `len` bytes at `at` are all in the file (a place past what a number holds exactly is not)
148
+ const inZip = (buf, at, len) => Number.isSafeInteger(at) && at >= 0 && at + len <= buf.length;
149
+
150
+ // How many files a zip lists and where its list (the central directory) starts: [count, place], from the record at
151
+ // the zip's end, or from the Zip64 record before it when the file is written with 64-bit numbers
152
+ function zipList(buf) {
153
+ let e = buf.length - 22;
154
+ while (e >= 0 && buf.readUInt32LE(e) !== 0x06054b50) e--;
155
+ if (e < 0) throw new Error('not a zip file');
156
+ let count = buf.readUInt16LE(e + 10),
157
+ p = buf.readUInt32LE(e + 16);
158
+ if (p === 0xffffffff && e >= 20 && buf.readUInt32LE(e - 20) === 0x07064b50) {
159
+ // Zip64: the real numbers are in its own record
160
+ const z = Number(buf.readBigUInt64LE(e - 12));
161
+ if (!inZip(buf, z, 56)) throw damagedZip('its record of large sizes is past its end');
162
+ count = Number(buf.readBigUInt64LE(z + 32));
163
+ p = Number(buf.readBigUInt64LE(z + 48));
164
+ }
165
+ if (count && !inZip(buf, p, 46)) throw damagedZip('its list of files starts past its end');
166
+ return [count, p];
167
+ }
168
+
169
+ // Entry i of a zip's list of files, at p: { name, entry (as a message names it), method (0 stored, 8 deflated), data
170
+ // (its bytes as packed), next (where the list's next entry is) }, each place and size checked before it is read
171
+ function zipEntry(buf, p, i) {
172
+ if (!inZip(buf, p, 46)) throw damagedZip(`its list of files runs past its end at entry ${i + 1}`);
173
+ if (buf.readUInt32LE(p) !== 0x02014b50) throw damagedZip(`entry ${i + 1} of its list of files is not an entry`);
174
+ const nameLen = buf.readUInt16LE(p + 28),
175
+ extraLen = buf.readUInt16LE(p + 30),
176
+ noteLen = buf.readUInt16LE(p + 32);
177
+ if (!inZip(buf, p + 46, nameLen + extraLen + noteLen))
178
+ throw damagedZip(`its list of files runs past its end at entry ${i + 1}`);
179
+ const name = buf.toString('utf8', p + 46, p + 46 + nameLen),
180
+ entry = `entry ${i + 1} (${sayable(name)})`;
181
+ let local = buf.readUInt32LE(p + 42),
182
+ csize = buf.readUInt32LE(p + 20);
183
+ // Zip64: sizes and offset in the extra field when the 32-bit ones are 0xffffffff
184
+ const ext = buf.subarray(p + 46 + nameLen, p + 46 + nameLen + extraLen);
185
+ for (let q = 0; q + 4 <= ext.length;) {
186
+ const id = ext.readUInt16LE(q),
187
+ len = ext.readUInt16LE(q + 2);
188
+ if (id === 1) {
189
+ let r = q + 4;
190
+ const big = () => {
191
+ if (r + 8 > Math.min(ext.length, q + 4 + len))
192
+ throw damagedZip(`${entry} lacks the large sizes it says it has`);
193
+ return Number(ext.readBigUInt64LE(r));
194
+ };
195
+ if (buf.readUInt32LE(p + 24) === 0xffffffff) r += 8; // uncompressed size
196
+ if (buf.readUInt32LE(p + 20) === 0xffffffff) {
197
+ csize = big();
198
+ r += 8;
199
+ }
200
+ if (local === 0xffffffff) local = big();
201
+ }
202
+ q += 4 + len;
203
+ }
204
+ if (!inZip(buf, local, 30)) throw damagedZip(`${entry} starts past the end of the file`);
205
+ if (buf.readUInt32LE(local) !== 0x04034b50) throw damagedZip(`${entry} is not where its list of files says`);
206
+ const start = local + 30 + buf.readUInt16LE(local + 26) + buf.readUInt16LE(local + 28);
207
+ if (!inZip(buf, start, csize)) throw damagedZip(`${entry} runs past the end of the file`);
208
+ return {
209
+ name,
210
+ entry,
211
+ method: buf.readUInt16LE(p + 10),
212
+ data: buf.subarray(start, start + csize),
213
+ next: p + 46 + nameLen + extraLen + noteLen,
214
+ };
215
+ }
132
216
 
133
217
  // A 3MF: every build item, with its transform, and the components it is made of (in this model file or another).
134
- // limits: { triangles, places, max } (MESH_LIMITS): what it places is counted first, and a file past a limit is refused
135
- // before anything is placed, as is a corner that is not three numbers or a triangle naming a corner its object hasn't.
218
+ // limits: { triangles, places, depth, max } (MESH_LIMITS): what it places is counted first, and a file past a limit is
219
+ // refused before anything is placed, as is a corner that is not three numbers, a triangle naming a corner its object
220
+ // hasn't, an object more than `depth` (16) levels deep inside others, and an object that holds itself.
136
221
  export function read3mf(buf, limits = {}) {
137
- const { triangles: most = MESH_LIMITS.triangles, places: follows = MESH_LIMITS.places } = limits;
222
+ const {
223
+ triangles: most = MESH_LIMITS.triangles,
224
+ places: follows = MESH_LIMITS.places,
225
+ depth: deepest = MESH_LIMITS.depth,
226
+ text: longest = MESH_LIMITS.text,
227
+ } = limits;
138
228
  const files = unzip(buf, limits);
139
229
  const models = Object.fromEntries(
140
230
  Object.entries(files)
141
231
  .filter(([n, d]) => d && /\.model$/i.test(n))
142
- .map(([n, d]) => ['/' + n.replace(/^\//, ''), d.toString('utf8')]),
232
+ .map(([n, d]) => ['/' + n.replace(/^\//, ''), asText(d, `the 3MF's model file ${sayable(n)}`, longest)]),
143
233
  );
144
234
  const root = Object.keys(models).find((n) => /^\/3D\/3dmodel\.model$/i.test(n)) || Object.keys(models)[0];
145
235
  if (!root) throw new Error('no 3D model in the 3MF');
@@ -158,19 +248,29 @@ export function read3mf(buf, limits = {}) {
158
248
  : Object.keys(objects)
159
249
  .filter((k) => k.startsWith(root))
160
250
  .map((ref) => ({ ref }));
161
- // How many triangles and placings each object brings, with all it holds (by depth, as placing stops at 16)
162
- const memo = new Map();
251
+ // How many triangles and placings each object brings, with all it holds (by depth). An object deeper than cad follows
252
+ // is refused, not left out: the model would look whole and not be; so is one that holds itself.
253
+ const memo = new Map(),
254
+ holding = new Set(),
255
+ named = (key) => `object ${sayable(key.split('#')[1])} (${sayable(key.split('#')[0].replace(/^\//, ''))})`;
163
256
  const tally = (key, depth) => {
164
257
  const o = objects[key];
165
- if (!o || depth > 16) return [0, 0];
258
+ if (!o) return [0, 0];
259
+ if (holding.has(key)) throw new Error(`the 3MF's ${named(key)} holds itself, so it has no end`);
260
+ if (depth > deepest)
261
+ throw new Error(
262
+ `the 3MF holds ${named(key)} more than ${deepest} levels deep inside others, the most cad follows`,
263
+ );
166
264
  const k = `${key}@${depth}`;
167
265
  if (!memo.has(k)) {
168
266
  const sum = [o.tris.length, 1];
267
+ holding.add(key);
169
268
  for (const c of o.components) {
170
269
  const [t, n] = tally(c.ref, depth + 1);
171
270
  sum[0] += t;
172
271
  sum[1] += n;
173
272
  }
273
+ holding.delete(key);
174
274
  memo.set(k, sum);
175
275
  }
176
276
  return memo.get(k);
@@ -187,7 +287,7 @@ export function read3mf(buf, limits = {}) {
187
287
  const out = [];
188
288
  const place = (key, M, depth = 0) => {
189
289
  const o = objects[key];
190
- if (!o || depth > 16) return;
290
+ if (!o || depth > deepest) return; // (refused above)
191
291
  for (const t of o.tris) {
192
292
  const placed = t.map((v) => apply3mf(M, v));
193
293
  // (finite corners and finite transforms can still multiply past what a number holds: 1e200 placed at 1e200)
package/lib/motors.mjs CHANGED
@@ -8,10 +8,10 @@ import { stageEfficiency } from '@rulecad/gears';
8
8
  import { screwGroup } from '@rulecad/fixings';
9
9
  import { named } from './parts.mjs';
10
10
  import { referenceBuilt } from './bought.mjs';
11
- import crypto from 'node:crypto';
12
11
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
13
12
  import { threadsBackend } from '@rulecad/fea/threads';
14
- import { host, cached } from './host.mjs';
13
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
14
+ import { feKey } from './fe-key.mjs';
15
15
  import { paths, printerOf } from './workspace.mjs';
16
16
  import { peekRuleSet } from './rules.mjs';
17
17
  import { isPlainName } from './names.mjs';
@@ -172,7 +172,12 @@ function slideDrive(spec, what, j, num) {
172
172
  export const shaftFits = (drives, joints, ids) =>
173
173
  drives
174
174
  .filter((d) => d.joint && d.model.shaft.length)
175
- .map((d) => ({ a: `${d.id}.shaft`, b: ids[joints.find((j) => j.id === d.joint).child], min: -1000, silent: true }));
175
+ .map((d) => ({
176
+ a: `${d.id}.shaft`,
177
+ b: ids[joints.find((j) => j.id === d.joint).child],
178
+ overlap: 'allowed',
179
+ silent: true,
180
+ }));
176
181
 
177
182
  // "loads": [{ "joint": "elbow", "torque": 0.5 }, { "joint": "slide", "force": 12 }, { "mass": 0.2, "at": "forearm.tip" }]
178
183
  export function loadsOf(a, anchor, num, joints) {
@@ -291,14 +296,19 @@ export const mountTorque = (d) =>
291
296
  );
292
297
 
293
298
  // A motor's speed if the assembly doesn't say: its corner speed, its rated speed, or half its free speed (a stepper's
294
- // at its driver's supply, volts: the assembly's, else the package's default)
299
+ // at its driver's supply, volts: the assembly's, else the package's default). A geared stepper works at the step rate
300
+ // its pull-in torque is measured at, where that torque is its own (past it @rulecad/motors lets the torque fall)
295
301
  export function workingSpeed(model, spec, supply) {
296
302
  if (spec.speed != null) return spec.speed;
297
303
  const p = performance(model, { supply });
304
+ const tested = model.figures.pull_in_rate?.value,
305
+ starts = model.figures.step_rate?.value;
298
306
  return model.type === 'dc'
299
307
  ? p.limit / 2
300
308
  : model.figures.pull_in_torque
301
- ? p.limit
309
+ ? tested && starts && tested < starts
310
+ ? (p.limit * tested) / starts
311
+ : p.limit
302
312
  : model.type === 'servo'
303
313
  ? p.limit
304
314
  : model.type === 'brushless'
@@ -751,7 +761,10 @@ function mountCheck(s, d, f, W, avail, materialName, frame) {
751
761
  each = Math.max(...screwGroup(m.mount.holes, { moment: [0, 0, avail] }).screws.map((x) => x.shear)),
752
762
  bearing = each / (hd * t),
753
763
  margin = mat.strength / bearing;
754
- for (const x of here.findings)
764
+ // mount.printable is left out: it is about the solid mount() cuts for a pose, and neither is known here (the part
765
+ // may be drawn for the other pose, or by hand), so it would say what is not true of this part. How the part prints
766
+ // is read from its own mesh, by the print checks
767
+ for (const x of here.findings.filter((y) => y.code !== 'mount.printable'))
755
768
  f(x.level, `${d.id} on ${other}: ${x.text}`, x.level === 'pass' ? null : `${d.id}: ${x.code.split('.')[1]}`, {
756
769
  code: 'motor.mount',
757
770
  ...(x.values ? { values: x.values } : {}),
@@ -828,32 +841,12 @@ export function mountFE({
828
841
  nu,
829
842
  budget = 9000,
830
843
  }) {
831
- const key = crypto
832
- .createHash('sha256')
833
- .update(
834
- JSON.stringify([
835
- 4,
836
- tris,
837
- holes,
838
- hole,
839
- plate,
840
- side,
841
- held,
842
- down,
843
- weight,
844
- centre,
845
- torque,
846
- tip,
847
- ref,
848
- E,
849
- nu,
850
- budget,
851
- ]),
852
- )
853
- .digest('hex')
854
- .slice(0, 24),
855
- file = paths.cache('mount', `${key}.json`);
856
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
844
+ const file = paths.cache(
845
+ 'mount',
846
+ `${feKey('mount', [tris, holes, hole, plate, side, held, down, weight, centre, torque, tip, ref, E, nu, budget])}.json`,
847
+ );
848
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
849
+ if (kept) return kept;
857
850
  const { lo, hi } = box3(tris.flat()),
858
851
  span = sub3(hi, lo);
859
852
  let cell = Math.max(0.4, plate / 2);
@@ -988,7 +981,7 @@ export function mountFE({
988
981
  atHoles = holes.some(([x, y]) => Math.hypot(p[0] - x, p[1] - y) <= grip + cell);
989
982
  }
990
983
  const out = { deflection, relative: !!base, stress, atHoles, cell, across, held: heldBy, cells: g.cells };
991
- host.writeText(file, JSON.stringify(out));
984
+ writeCacheFile(file, JSON.stringify(out));
992
985
  return out;
993
986
  }
994
987
 
package/lib/names.mjs CHANGED
@@ -39,3 +39,18 @@ export function isObjectRefName(ref) {
39
39
  const m = typeof ref === 'string' && OBJECT_REF.exec(ref);
40
40
  return !!m && isPlainName(m[1]) && isPlainName(m[2]);
41
41
  }
42
+
43
+ /**
44
+ * Whether `f` is a path to a file inside a workspace as the tool writes one down (a build's imports, a release's
45
+ * list of what it read): relative, with forward slashes, never climbing out (..), never absolute or with a drive
46
+ * letter, and never into a node_modules folder. Such lists can come from a workspace's own .cache/ or a release's tag,
47
+ * which a cloned workspace brings, so a path that is not like this is never read.
48
+ * @param {unknown} f
49
+ * @returns {boolean}
50
+ */
51
+ export const isWorkspacePath = (f) =>
52
+ typeof f === 'string' &&
53
+ f !== '' &&
54
+ !f.startsWith('/') &&
55
+ !/^[a-zA-Z]:|\\/.test(f) &&
56
+ f.split('/').every((s) => s !== '' && s !== '.' && s !== '..' && s.toLowerCase() !== 'node_modules');
@@ -0,0 +1,52 @@
1
+ // The lowest Node the cad command runs on, checked before anything else of it loads: the command's first import
2
+ // (bin/cad.mjs), so that on an older Node it says so in one plain line rather than failing part way with Node's own
3
+ // error. The lowest is the one package.json's "engines" states (CONTRIBUTING.md says why it is 22.13: below it the
4
+ // sandbox designs run in can't start); npm only warns of it on install, in a line that is easily missed.
5
+ // This module imports nothing that an older Node lacks.
6
+ import fs from 'node:fs';
7
+
8
+ /** The lowest Node version package.json's "engines" states, as `[major, minor, patch]`. */
9
+ export function nodeFloor() {
10
+ const pkg = JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
11
+ const m = /(\d+)(?:\.(\d+))?(?:\.(\d+))?/.exec(pkg.engines?.node ?? '');
12
+ return m ? [Number(m[1]), Number(m[2] ?? 0), Number(m[3] ?? 0)] : [0, 0, 0];
13
+ }
14
+
15
+ /**
16
+ * What cad says on a Node older than it runs on, or null on one it runs on.
17
+ * @param {string} [version] Node's version, as process.versions.node gives it ('22.12.0')
18
+ * @param {number[]} [floor] the lowest version, as nodeFloor gives it
19
+ * @returns {string | null}
20
+ */
21
+ export function nodeTooOld(version = process.versions.node, floor = nodeFloor()) {
22
+ const v = String(version)
23
+ .replace(/^v/, '')
24
+ .split('.')
25
+ .map((n) => Number.parseInt(n, 10) || 0);
26
+ for (let i = 0; i < 3; i++) {
27
+ if ((v[i] ?? 0) > floor[i]) return null;
28
+ if ((v[i] ?? 0) < floor[i]) {
29
+ const want = floor[2] ? floor.join('.') : `${floor[0]}.${floor[1]}`;
30
+ return `cad needs Node ${want} or later; this is Node ${String(version).replace(/^v/, '')}. Install a newer Node (nodejs.org) and run the command again.`;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+
36
+ /**
37
+ * Stop the command, with that line on stderr and exit status 1, on a Node older than cad runs on; on any other, do
38
+ * nothing.
39
+ * @param {string} [version] Node's version, as process.versions.node gives it
40
+ */
41
+ export function checkNode(version = process.versions.node) {
42
+ const said = nodeTooOld(version);
43
+ if (!said) return;
44
+ try {
45
+ fs.writeSync(2, `${said}\n`); // (written at once: a pipe's stream may not have sent it before the exit)
46
+ } catch {
47
+ process.stderr.write(`${said}\n`);
48
+ }
49
+ process.exit(1);
50
+ }
51
+
52
+ checkNode();
package/lib/optimise.mjs CHANGED
@@ -8,7 +8,8 @@ import fs from 'node:fs';
8
8
  import path from 'node:path';
9
9
  import crypto from 'node:crypto';
10
10
  import { AsyncLocalStorage } from 'node:async_hooks';
11
- import { host, readJson, cached } from './host.mjs';
11
+ import { host, readJson } from './host.mjs';
12
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
12
13
  import { paths, printerOf, noLinksOut } from './workspace.mjs';
13
14
  import { plainName } from './names.mjs';
14
15
  import { resolve, evaluate, fmt } from './rules.mjs';
@@ -35,6 +36,7 @@ import {
35
36
  import { islands } from '@rulecad/printcheck';
36
37
  import { turn, mul, inv, placeItems, jointValues } from '@rulecad/model-link';
37
38
  import { section, loops, slabLevels } from './mesh.mjs';
39
+ import { codeOnly } from './code-text.mjs';
38
40
  import { threadsBackend } from '@rulecad/fea/threads'; // the solver's products shared over the machine's cores
39
41
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
40
42
 
@@ -688,24 +690,30 @@ function made(r, spec, density) {
688
690
  return out;
689
691
  }
690
692
  const digest = (x) => crypto.createHash('sha256').update(JSON.stringify(x)).digest('hex');
691
- /**
692
- * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
693
- * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
694
- * that readies the problem for the solver (holdEmpty). Drawing a shape from the densities is not in it.
695
- * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
696
- */
697
693
  /**
698
694
  * Throws (code workspace.outside, naming the link) where the kept results optimised() reads (.cache/optimise,
699
695
  * .cache/densities) hold a link out of the workspace: a cloned workspace may carry a .cache/ of its own. Called before
700
696
  * optimised(), as its own text is part of the densities key (densityCode).
701
697
  */
702
698
  export const ownResults = () => noLinksOut([paths.cache('optimise'), paths.cache('densities')]);
703
- export const densityCode = () => ({
699
+ // The solver's share of topopt's file: the code above this line, which decides the densities (all model() calls, the
700
+ // virtual temperature among them: cache-salts.test.mjs holds it so); below it, only how a shape is drawn from them
701
+ const SHAPES_FROM_RESULTS = '// ---------- shapes from results ----------';
702
+ /**
703
+ * The code an optimisation's densities are made by, each piece by name: this file's VERSION, topopt's solver (its file
704
+ * up to its shapes from results), the FE's code and its threads backend (the solver's products), and cad's own code
705
+ * that readies the problem for the solver (holdEmpty, and optimised, which calls it). Drawing a shape from the
706
+ * densities is not in it. Each is the code without its comment lines and blank lines (codeOnly), so rewording a
707
+ * comment keeps the densities, and any change to the code optimises again.
708
+ * @param {(module: string) => string} [read] reads a module's text by its name (tests read an edited copy)
709
+ * @returns {{ version: number, solver: string, fea: string, threads: string, cad: string }}
710
+ */
711
+ export const densityCode = (read = source) => ({
704
712
  version: VERSION,
705
- solver: source('@rulecad/topopt').split('// ---------- shapes from results ----------')[0],
706
- fea: source('@rulecad/fea'),
707
- threads: source('@rulecad/fea/threads'),
708
- cad: `${holdEmpty.toString()}\n${optimised.toString()}`,
713
+ solver: codeOnly(read('@rulecad/topopt').split(SHAPES_FROM_RESULTS)[0]),
714
+ fea: codeOnly(read('@rulecad/fea')),
715
+ threads: codeOnly(read('@rulecad/fea/threads')),
716
+ cad: codeOnly(`${holdEmpty.toString()}\n${optimised.toString()}`),
709
717
  });
710
718
  /**
711
719
  * The key an optimisation's densities are kept by (.cache/densities/<key>.json): the problem and every piece of
@@ -732,21 +740,21 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
732
740
  fs.readFileSync(new URL(import.meta.url), 'utf8'),
733
741
  ]),
734
742
  file = paths.cache('optimise', `${hash}.json`);
735
- if (!fresh && !process.env.CAD_NO_CACHE && host.exists(file))
736
- return { ...JSON.parse(host.readText(file)), cached: true };
743
+ const shapeKept = !fresh && !process.env.CAD_NO_CACHE && readCacheJson(file); // (one cut short or spoiled: a miss)
744
+ if (shapeKept) return { ...shapeKept, cached: true };
737
745
  const spec = holdEmpty(discretise(r.problem)),
738
746
  densities = paths.cache('densities', `${densitiesKey(r.problem)}.json`);
739
747
  // A mark that this problem has been optimised before (by any solver), so a run can say whether it's the solver that changed
740
748
  const seen = paths.cache('densities', `${digest([VERSION, r.problem])}.seen`);
741
- if (!fresh && !process.env.CAD_NO_CACHE && !host.exists(densities))
749
+ const densitiesKept = !fresh && !process.env.CAD_NO_CACHE ? readCacheJson(densities) : undefined;
750
+ if (!fresh && !process.env.CAD_NO_CACHE && !densitiesKept)
742
751
  onRun?.(host.exists(seen) ? 'the solver has changed since its last result' : 'no result yet');
743
752
  else if (fresh) onRun?.('asked to run afresh');
744
- const o =
745
- !fresh && !process.env.CAD_NO_CACHE && host.exists(densities)
746
- ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(JSON.parse(host.readText(densities)))
747
- : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
748
- if (!host.exists(densities)) host.writeText(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
749
- if (!host.exists(seen)) host.writeText(seen, '');
753
+ const o = densitiesKept
754
+ ? (({ density, ...x }) => ({ ...x, density: Float64Array.from(density) }))(densitiesKept)
755
+ : optimise(spec, { backend: threadsBackend, onStep: onStep && ((st) => onStep({ ...st, grid: spec.grid })) });
756
+ if (!host.exists(densities)) writeCacheFile(densities, JSON.stringify({ ...o, density: Array.from(o.density) }));
757
+ if (!host.exists(seen)) writeCacheFile(seen, '');
750
758
  // Regions as data: a part's triangles are named, not copied
751
759
  const named = (list) => list.map(({ triangles, ...x }) => x);
752
760
  const shape =
@@ -920,7 +928,7 @@ export async function optimised(project, ref, { onStep, onRun, fresh = false } =
920
928
  supports: named(r.problem.supports),
921
929
  loads: named(r.problem.loads),
922
930
  };
923
- host.writeText(file, JSON.stringify(result));
931
+ writeCacheFile(file, JSON.stringify(result));
924
932
  return result;
925
933
  }
926
934
 
@@ -980,12 +988,13 @@ export async function analysePart(triangles, project, ref, { cell } = {}) {
980
988
  )
981
989
  .digest('hex')}.json`,
982
990
  );
983
- if (!process.env.CAD_NO_CACHE && cached(file)) {
984
- const { density, ...x } = JSON.parse(host.readText(file));
991
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
992
+ if (kept) {
993
+ const { density, ...x } = kept;
985
994
  return { ...x, density: Float64Array.from(density) };
986
995
  }
987
996
  const out = analyseSolid(triangles, r, h);
988
- host.writeText(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
997
+ writeCacheFile(file, JSON.stringify({ ...out, density: Array.from(out.density) }));
989
998
  return out;
990
999
  }
991
1000
  // The grid covers the part and the problem's space
package/lib/order.mjs CHANGED
@@ -6,10 +6,8 @@
6
6
  // tool comes from (its anchor's z points out along the screw): whatever stands on that line must go on after it.
7
7
  // Works on the assembly's top-level items; a component (an assembly used as an item) is one step.
8
8
  import crypto from 'node:crypto';
9
- import path from 'node:path';
10
- import fs from 'node:fs';
11
9
  import { placeItems, jointValues, mul } from '@rulecad/model-link';
12
- import { host, cached } from './host.mjs';
10
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
13
11
  import { paths } from './workspace.mjs';
14
12
  import { motorScrews } from './motors.mjs';
15
13
  import jscad from '@jscad/modeling';
@@ -133,8 +131,7 @@ const allowedPair = (s, a, b) =>
133
131
  together(s, a, b) ||
134
132
  s.fits.some(
135
133
  (x) =>
136
- x.min != null &&
137
- x.num(x.min) < 0 &&
134
+ (x.overlap === 'allowed' || (x.min != null && x.num(x.min) < 0)) &&
138
135
  ((names(x.a).includes(a.id) && names(x.b).includes(b.id)) ||
139
136
  (names(x.a).includes(b.id) && names(x.b).includes(a.id))),
140
137
  );
@@ -605,14 +602,10 @@ function orderFile(s) {
605
602
  export function orderOf(s) {
606
603
  if (s.orderSteps) return s.orderSteps;
607
604
  const file = orderFile(s);
608
- if (!process.env.CAD_NO_CACHE && cached(file)) return (s.orderSteps = JSON.parse(host.readText(file)));
605
+ const kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
606
+ if (kept) return (s.orderSteps = kept);
609
607
  const r = assemblyOrder(s);
610
- try {
611
- fs.mkdirSync(path.dirname(file), { recursive: true });
612
- host.writeText(file, JSON.stringify(r));
613
- } catch {
614
- // (a cache that can't be written is only slower)
615
- }
608
+ writeCacheFile(file, JSON.stringify(r)); // (one that can't be written is only slower)
616
609
  return (s.orderSteps = r);
617
610
  }
618
611
 
package/lib/parts.mjs CHANGED
@@ -29,6 +29,8 @@ export function unpack(made) {
29
29
  // (v.mx.housing_top) are noted in `read`, so estimates a design relies on get flagged. A name that isn't there is
30
30
  // refused: a misspelt v.widht would otherwise come through as undefined, and quietly draw another shape. `optional`
31
31
  // names may be absent: the display's own inputs, and what only some designs get (layouts, problems, the board engine).
32
+ // A helper the design reached for is noted as `:<name>` (':frames'): no rule's name holds a colon. A release records
33
+ // the rule sets v.frames reads only for a design that used it.
32
34
  export function watch(values, extras = {}, optional = []) {
33
35
  const read = new Set(),
34
36
  may = new Set([...optional, 'layouts', 'problems', 'pcb', 'then', 'toJSON']);
@@ -50,6 +52,7 @@ export function watch(values, extras = {}, optional = []) {
50
52
  };
51
53
  const v = new Proxy(given, {
52
54
  get: (t, r) => {
55
+ if (typeof r === 'string' && Object.hasOwn(extras, r)) read.add(`:${r}`);
53
56
  if (typeof r !== 'string' || r in t || may.has(r)) return t[r];
54
57
  const guess = near(r, Object.keys(t));
55
58
  throw new CadError(