@rulecad/cad 0.9.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 (53) hide show
  1. package/AGENTS.md +21 -6
  2. package/CHANGELOG.md +320 -0
  3. package/EXAMPLES.md +22 -17
  4. package/README.md +192 -40
  5. package/bin/cad.mjs +465 -80
  6. package/lib/assembly.mjs +68 -33
  7. package/lib/cache-file.mjs +105 -0
  8. package/lib/code-text.mjs +28 -0
  9. package/lib/design-imports.mjs +127 -0
  10. package/lib/design.mjs +251 -55
  11. package/lib/designshapes.mjs +142 -0
  12. package/lib/edit.mjs +24 -2
  13. package/lib/estimates.mjs +51 -0
  14. package/lib/fasten.mjs +11 -5
  15. package/lib/fe-key.mjs +29 -0
  16. package/lib/fittings.mjs +20 -15
  17. package/lib/fixings.mjs +17 -4
  18. package/lib/framebuild.mjs +1 -1
  19. package/lib/framegen.mjs +9 -1
  20. package/lib/frames.mjs +6 -2
  21. package/lib/framesize.mjs +8 -81
  22. package/lib/host.mjs +7 -3
  23. package/lib/kit.mjs +5 -5
  24. package/lib/list.mjs +29 -21
  25. package/lib/loads.mjs +35 -23
  26. package/lib/measured.mjs +738 -98
  27. package/lib/motors.mjs +9 -29
  28. package/lib/names.mjs +15 -0
  29. package/lib/optimise.mjs +34 -25
  30. package/lib/order.mjs +4 -10
  31. package/lib/parts.mjs +3 -0
  32. package/lib/rules.mjs +2 -1
  33. package/lib/sandbox-hooks.mjs +109 -15
  34. package/lib/sandbox-lock.mjs +225 -0
  35. package/lib/sandbox-preload.mjs +2 -2
  36. package/lib/sandbox-run.mjs +22 -24
  37. package/lib/sandbox.mjs +173 -30
  38. package/lib/sheet.mjs +114 -3
  39. package/lib/versions.mjs +195 -32
  40. package/lib/workspace.mjs +3 -2
  41. package/package.json +11 -11
  42. package/schemas/assembly.schema.json +1 -1
  43. package/schemas/project.schema.json +6 -0
  44. package/templates/coupons/MEASURE.md +109 -0
  45. package/templates/coupons/assemblies/fixings-test.json +20 -0
  46. package/templates/coupons/assemblies/slot-test.json +11 -0
  47. package/templates/coupons/objects/fixings-coupon.js +88 -0
  48. package/templates/coupons/objects/fixings-coupon.json +26 -0
  49. package/templates/coupons/objects/holds-coupon.js +130 -0
  50. package/templates/coupons/objects/holds-coupon.json +42 -0
  51. package/templates/coupons/objects/slot-coupon.js +89 -0
  52. package/templates/coupons/objects/slot-coupon.json +29 -0
  53. package/templates/coupons/project.json +10 -0
package/lib/host.mjs CHANGED
@@ -4,7 +4,9 @@
4
4
  // packages, the published rule sets) from disk.
5
5
  // host.exists(file) host.readText(file) host.writeText(file, text) host.list(dir) host.mtime(file) host.size(file)
6
6
  // host.remove(file) host.touch(file) host.loadModule(file): a design's module (its main), for a design run in the
7
- // tool's own process (a trusted one)
7
+ // tool's own process (a trusted one), loaded afresh when it or a file it imports has changed (design-imports.mjs)
8
+ // host.importsOf(file): a promise of the files of its own (not a package's) the design has imported since its last
9
+ // loadModule, as absolute paths, asked after its main has run, for the build's cache to follow
8
10
  // host.runDesign(request): run a design in the sandbox, another process that can't write files, start programs or
9
11
  // reach the network (sandbox.mjs's runSandboxed, whose request this is). build() uses it for every design it doesn't
10
12
  // run in its own process, a board's too, so a host for a browser or an editor's server never runs a design's code in
@@ -35,7 +37,8 @@ export const nodeHost = {
35
37
  const now = new Date();
36
38
  fs.utimesSync(f, now, now);
37
39
  },
38
- loadModule: (f) => import(`${pathToFileURL(f).href}?t=${fs.statSync(f).mtimeMs}`), // a fresh copy after each edit
40
+ loadModule: async (f) => (await import('./design-imports.mjs')).loadDesign(path.resolve(f)), // (its import hook is set up only when a design is first run here)
41
+ importsOf: async (f) => (await import('./design-imports.mjs')).importsOf(path.resolve(f)),
39
42
  runDesign: (request) => import('./sandbox.mjs').then((s) => s.runSandboxed(request)), // (loaded when first used: sandbox.mjs reads the workspace, which reads through this host)
40
43
  };
41
44
 
@@ -74,7 +77,7 @@ export const readOwnText = (f) => host.readText(guard(f));
74
77
  * Whether a cache file is there to be read: a file of the workspace's .cache/ only where it really is inside the
75
78
  * workspace. A cloned workspace may hold a .cache/ of its own, and a kept build or stage there that is a link to a file
76
79
  * elsewhere would be read as the tool's own and shown, or handed to a design: such a file is a miss, made afresh (and
77
- * not written through the link: design.mjs ownCacheFile).
80
+ * not written through the link: cache-file.mjs writeCacheFile).
78
81
  * @param {string} f
79
82
  */
80
83
  export function cached(f) {
@@ -162,6 +165,7 @@ export function memoryHost(files = {}, { root = path.resolve('/rulecad-memory')
162
165
  );
163
166
  return import(`data:text/javascript;base64,${Buffer.from(src).toString('base64')}`);
164
167
  },
168
+ importsOf: async () => [], // (a module loaded from its text can't import a file of its project)
165
169
  runDesign: async (request) => {
166
170
  const { d } = request,
167
171
  project = path.resolve(path.dirname(path.dirname(d.js)));
package/lib/kit.mjs CHANGED
@@ -12,7 +12,7 @@ import path from 'node:path';
12
12
  import { paths, WS } from './workspace.mjs';
13
13
  import { CadError } from './errors.mjs';
14
14
  import { buildAssembly } from './assembly.mjs';
15
- import { shoppingList } from './list.mjs';
15
+ import { shoppingList, flowText } from './list.mjs';
16
16
  import { platesOf, checkPlate } from './plates.mjs';
17
17
  import { cutListOf, writeBeamSheets } from './beams.mjs';
18
18
  import { writeJigs } from './jigs.mjs';
@@ -224,7 +224,7 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
224
224
  rows.push([
225
225
  'bar',
226
226
  b.count,
227
- `${st.profile} x ${mm(b.length)} mm`,
227
+ `${st.label ?? st.profile} x ${mm(b.length)} mm`,
228
228
  `${b.count} x ${mm(b.length)} mm`,
229
229
  `the cut list's marks ${[...new Set(st.bars.flatMap((x) => x.cuts.map((c) => c.mark)))].join(', ')}`,
230
230
  ]);
@@ -320,7 +320,7 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
320
320
  ...table(
321
321
  ['Profile', 'Buy', 'Left over, mm'],
322
322
  list.cut.stock.map((st) => [
323
- st.profile,
323
+ st.label ?? st.profile,
324
324
  st.buy.map((b) => `${b.count} x ${mm(b.length)} mm`).join(', '),
325
325
  mm(st.offcut ?? 0),
326
326
  ]),
@@ -404,7 +404,7 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
404
404
  '',
405
405
  );
406
406
  out.push(
407
- `About ${mm(list.totals.printedGrams)} g of ${list.totals.material.toUpperCase()} and ${list.totals.minutes} min of printing (an estimate from each part's volume and the printer's flow).`,
407
+ `About ${mm(list.totals.printedGrams)} g of ${list.totals.material.toUpperCase()} and ${list.totals.minutes} min of printing (an estimate from each part's volume and ${flowText(list.totals)}).`,
408
408
  '',
409
409
  );
410
410
  }
@@ -448,7 +448,7 @@ export async function writeKit(s, findings, { pictures = false, preview = null }
448
448
  '',
449
449
  );
450
450
  for (const st of list.cut.stock) {
451
- out.push(`${st.profile}, the cuts on each bar in order:`, '');
451
+ out.push(`${st.label ?? st.profile}, the cuts on each bar in order:`, '');
452
452
  st.bars.forEach((b, i) =>
453
453
  out.push(
454
454
  `${i + 1}. A ${mm(b.length)} mm bar: ${b.cuts.map((c) => `${c.mark} ${mm(c.length)} (${c.item})`).join(', ')}; ${mm(b.offcut)} mm left`,
package/lib/list.mjs CHANGED
@@ -7,7 +7,7 @@ import { placeItems, jointValues } from '@rulecad/model-link';
7
7
  import { screwModel, pinModel, magnetModel } from '@rulecad/fixings';
8
8
  import { peekRuleSet as loadRuleSet } from './rules.mjs';
9
9
  import { motorScrews } from './motors.mjs';
10
- import { paths } from './workspace.mjs';
10
+ import { paths, printerOf } from './workspace.mjs';
11
11
  import { readJson } from './host.mjs';
12
12
  import path from 'node:path';
13
13
  import { volume } from './mesh.mjs';
@@ -35,15 +35,25 @@ export function materialOf(project) {
35
35
  }
36
36
  }
37
37
 
38
- // Every printed thing in the assembly, once for each copy: its volume, grams and minutes
39
- export function printedParts(s) {
40
- const mat = materialOf(s.project);
41
- let flow = 12;
38
+ // How fast the project's printer lays plastic, for the minutes: its rule set's print_flow (mm³/s), the printer named by
39
+ // project.json or cad.config.json (workspace.mjs printerOf), as cad check reads it. Where that rule set gives none (or
40
+ // cannot be read), 12 mm³/s, a usual print flow, marked assumed so the list says so.
41
+ export function flowOf(project) {
42
+ let printer = null;
42
43
  try {
43
- flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
44
+ printer = printerOf(project);
45
+ const f = loadRuleSet(printer).rules.print_flow?.value;
46
+ if (typeof f === 'number' && f > 0) return { printer, flow: f };
44
47
  } catch {
45
- // (no x1c rule set: 12 mm³/s, a usual print flow)
48
+ // (no printer named, or its rule set unreadable: the usual flow, said to be assumed)
46
49
  }
50
+ return { printer, flow: 12, assumed: true };
51
+ }
52
+
53
+ // Every printed thing in the assembly, once for each copy: its volume, grams and minutes
54
+ export function printedParts(s) {
55
+ const mat = materialOf(s.project);
56
+ const { flow } = flowOf(s.project);
47
57
  const by = new Map();
48
58
  for (const p of s.parts) {
49
59
  if (p.role !== 'part' && p.role != null) continue;
@@ -72,12 +82,7 @@ function inPlaceRow(s, printed) {
72
82
  members = printed.filter((p) => ids.includes(p.id));
73
83
  if (members.length < 2) return printed;
74
84
  const mat = materialOf(s.project);
75
- let flow = 12;
76
- try {
77
- flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
78
- } catch {
79
- // (no x1c rule set: 12 mm³/s, a usual print flow)
80
- }
85
+ const { flow } = flowOf(s.project);
81
86
  const volume = members.reduce((t, p) => t + p.volume, 0),
82
87
  row = {
83
88
  id: members.map((p) => p.id).join(', '),
@@ -140,12 +145,8 @@ export function shoppingList(s) {
140
145
  if (!b.from.includes(h.from)) b.from.push(h.from);
141
146
  bolts.set(h.name, b);
142
147
  }
143
- let flow = 12;
144
- try {
145
- flow = loadRuleSet('x1c').rules.print_flow?.value ?? flow;
146
- } catch {
147
- // (no x1c rule set: 12 mm³/s, a usual print flow)
148
- }
148
+ const printer = flowOf(s.project),
149
+ { flow } = printer;
149
150
  for (const b of bolts.values()) {
150
151
  const mm3 = (b.grams / mat.density) * 1000;
151
152
  printed.push({
@@ -311,12 +312,19 @@ export function shoppingList(s) {
311
312
  0,
312
313
  ),
313
314
  material: mat.name,
314
- ...(mat.assumed ? { densityAssumed: true } : {}),
315
+ ...(mat.assumed ? { densityAssumed: true, density: mat.density } : {}),
316
+ printer: printer.printer,
317
+ flow,
318
+ ...(printer.assumed ? { flowAssumed: true } : {}),
315
319
  ...(unknown.length ? { noMassFor: unknown } : {}),
316
320
  },
317
321
  };
318
322
  }
319
323
 
324
+ /** Whose flow a list's minutes are from, and what was assumed (a printer without a print_flow, a material without a density). @param {object} t a list's totals @returns {string} */
325
+ export const flowText = (t) =>
326
+ `${t.flowAssumed ? `the usual flow (${t.printer ? `${t.printer} gives no print_flow` : 'no printer named'}: ${t.flow} mm³/s assumed)` : `${t.printer ?? 'the printer'}'s flow, ${t.flow} mm³/s`}${t.densityAssumed ? `; no density known for ${t.material}: ${t.density} g/cm³ assumed for the grams` : ''}`;
327
+
320
328
  export function listText(ref, l) {
321
329
  const out = [`${ref}: what it takes to build`];
322
330
  const row = (a) => out.push(a.join(' '));
@@ -378,7 +386,7 @@ export function listText(ref, l) {
378
386
  }
379
387
  out.push(
380
388
  '',
381
- `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and the printer's flow), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`,
389
+ `Total: ${l.totals.printedGrams} g printed, about ${l.totals.minutes} min of printing (an estimate from volume and ${flowText(l.totals)}), ${l.totals.fixingsGrams ? `${l.totals.fixingsGrams} g of fixings, ` : ''}${l.totals.machineGrams} g as a machine${l.totals.noMassFor ? ` (no mass given for ${l.totals.noMassFor.join(', ')})` : ''}`,
382
390
  );
383
391
  if (l.cost) {
384
392
  const c = l.cost,
package/lib/loads.mjs CHANGED
@@ -1,11 +1,11 @@
1
1
  // What the machine's own weight and its payload do to it: the force and tipping moment each joint's bearing or printed
2
2
  // location takes, how far the links bend, how fast the arm rings, and what acceleration the motors can give it. Masses come
3
3
  // from the parts as drawn (volume and density) and the bought parts' rules. Findings in the assembly's shape.
4
- import crypto from 'node:crypto';
5
4
  import { grid as makeGrid, analyse, positions } from '@rulecad/fea';
6
5
  import { jacobian } from '@rulecad/robots';
7
6
  import { performance } from '@rulecad/motors';
8
- import { host, cached } from './host.mjs';
7
+ import { writeCacheFile, readCacheJson } from './cache-file.mjs';
8
+ import { feKey } from './fe-key.mjs';
9
9
  import { paths } from './workspace.mjs';
10
10
  import { peekRuleSet } from './rules.mjs';
11
11
  import { solidFill } from './optimise.mjs';
@@ -117,15 +117,20 @@ function bearingMargin(rows, loads) {
117
117
  return { P0, C0: first.C0, margin: first.C0 / P0, span };
118
118
  }
119
119
 
120
- // A printed location's weakest clip, from FE on the part as drawn: fixed at its foot, the load at its head
121
- function clipStress(tris, force, modulus, nu, cell) {
122
- const key = crypto
123
- .createHash('sha256')
124
- .update(JSON.stringify(['surface', tris.length, tris[0], force, modulus, cell]))
125
- .digest('hex')
126
- .slice(0, 20),
127
- file = paths.cache('clip', key);
128
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
120
+ /**
121
+ * A printed location's weakest clip, from FE on the part as drawn: fixed at its foot, the load at its head. Kept in
122
+ * .cache under a hash of every triangle and the material (fe-key.mjs). Exported for its tests.
123
+ * @param {number[][][]} tris the clip's triangles, in mm
124
+ * @param {number[]} force the load at its head, N
125
+ * @param {number} modulus its material's stiffness, MPa
126
+ * @param {number} nu its material's Poisson's ratio
127
+ * @param {number} cell the FE cells' size, mm
128
+ * @returns {{ stress: number, deflection?: number, thin?: boolean }}
129
+ */
130
+ export function clipStress(tris, force, modulus, nu, cell) {
131
+ const file = paths.cache('clip', feKey('clip', [tris, force, modulus, nu, cell])),
132
+ kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
133
+ if (kept) return kept;
129
134
  const { lo, hi } = extent(tris),
130
135
  n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
131
136
  const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell },
@@ -154,7 +159,7 @@ function clipStress(tris, force, modulus, nu, cell) {
154
159
  let most = 0;
155
160
  for (let e = 0; e < density.length; e++) if (density[e] >= 0.5 && a.surface[0][e] > most) most = a.surface[0][e];
156
161
  const out = { stress: most, deflection: a.deflection[0].most };
157
- host.writeText(file, JSON.stringify(out));
162
+ writeCacheFile(file, JSON.stringify(out));
158
163
  return out;
159
164
  }
160
165
 
@@ -255,16 +260,23 @@ export function momentChecks(s, f, helpers, masses, payload) {
255
260
  return out;
256
261
  }
257
262
 
258
- // A link bent: held at its parent joint, the carried weight at its far end. δ from the FE, the tilt from a cantilever's
259
- // relation (1.5 δ / L), carried on to the tool. Kept in .cache, as this is the slow part.
260
- function linkFE(tris, O, far, force, E, nu, cell) {
261
- const key = crypto
262
- .createHash('sha256')
263
- .update(JSON.stringify(['surface', tris.length, tris.slice(0, 4), O, far, force, E, cell]))
264
- .digest('hex')
265
- .slice(0, 20),
266
- file = paths.cache('link', key);
267
- if (!process.env.CAD_NO_CACHE && cached(file)) return JSON.parse(host.readText(file));
263
+ /**
264
+ * A link bent: held at its parent joint, the carried weight at its far end. δ from the FE, the tilt from a cantilever's
265
+ * relation (1.5 δ / L), carried on to the tool. Kept in .cache, as this is the slow part, under a hash of every
266
+ * triangle and the material (fe-key.mjs). Exported for its tests.
267
+ * @param {number[][][]} tris the link's triangles, in mm
268
+ * @param {number[]} O where it is held (its parent joint), mm
269
+ * @param {number[]} far where the load is put on it, mm
270
+ * @param {number[]} force the load, N
271
+ * @param {number} E its material's stiffness, MPa
272
+ * @param {number} nu its material's Poisson's ratio
273
+ * @param {number} cell the FE cells' size, mm
274
+ * @returns {{ deflection: number, stress?: number, cell: number, missing?: boolean }}
275
+ */
276
+ export function linkFE(tris, O, far, force, E, nu, cell) {
277
+ const file = paths.cache('link', feKey('link', [tris, O, far, force, E, nu, cell])),
278
+ kept = !process.env.CAD_NO_CACHE && readCacheJson(file);
279
+ if (kept) return kept;
268
280
  const { lo, hi } = extent(tris),
269
281
  n = hi.map((h, k) => Math.max(1, Math.ceil((h - lo[k]) / cell)));
270
282
  const gr = { nx: n[0], ny: n[1], nz: n[2], h: cell },
@@ -297,7 +309,7 @@ function linkFE(tris, O, far, force, E, nu, cell) {
297
309
  stress: Array.from(a.surface[0]).reduce((m, x, e) => (density[e] >= 0.5 && x > m ? x : m), 0),
298
310
  cell,
299
311
  };
300
- host.writeText(file, JSON.stringify(out));
312
+ writeCacheFile(file, JSON.stringify(out));
301
313
  return out;
302
314
  }
303
315