@rulecad/cad 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/assembly.mjs CHANGED
@@ -16,6 +16,7 @@
16
16
  // { "holes": "pcb.board", "into": "case.body", "depth": "m2.insert_length", "label": "Screws find their inserts" }
17
17
  // The path must be clear for depth mm (it lands in a hole) and solid within "ring" mm of it (default: the hole's
18
18
  // diameter) half way down, so the screw has something to grip. "direction": "up" for screws from below.
19
+ import { host } from './host.mjs';
19
20
  import fs from 'node:fs';
20
21
  import crypto from 'node:crypto';
21
22
  import path from 'node:path';
@@ -25,12 +26,12 @@ import { locate, build, readObject, jscad } from './design.mjs';
25
26
  import { materialise } from './versions.mjs';
26
27
  import { satisfies } from '@rulecad/versions';
27
28
  import { bounds } from '@rulecad/printcheck';
28
- import { closest, inside } from '@rulecad/fit';
29
+ import { closest, closestAt, inside, distanceToFace } from '@rulecad/fit';
29
30
  import { keys as keyCentres, readLayout, hasLayout } from './layout.mjs';
30
31
  import { DOFS, frame, turn, mul, pathLength, jointValues, placeItems, jointMatrix } from '@rulecad/model-link';
31
32
 
32
33
  export const assemblyPath = (ref) => { const [project, name] = String(ref).split('/'); return path.join(paths.project(project || ''), 'assemblies', `${name || ''}.json`); };
33
- export const isAssembly = (ref) => String(ref).includes('/') && fs.existsSync(assemblyPath(ref.split('@')[0]));
34
+ export const isAssembly = (ref) => String(ref).includes('/') && host.exists(assemblyPath(ref.split('@')[0]));
34
35
 
35
36
  export { satisfies }; // from @rulecad/versions
36
37
 
@@ -57,7 +58,7 @@ export { satisfies }; // from @rulecad/versions
57
58
  export async function buildAssembly(ref, stack = [], overrides = {}, opts = {}) {
58
59
  const [project, name] = ref.split('/');
59
60
  if (stack.includes(ref)) throw new Error(`assembly ${ref} contains itself (${[...stack, ref].join(' → ')})`);
60
- const a = JSON.parse(fs.readFileSync(assemblyPath(ref), 'utf8'));
61
+ const a = JSON.parse(host.readText(assemblyPath(ref)));
61
62
  const printer = printerOf(project);
62
63
  if (a.kind === 'plate' && !(a.uses || []).includes(printer)) a.uses = [...(a.uses || []), printer]; // a plate is checked as a print
63
64
  const values = Object.fromEntries((a.uses || []).map((u) => { const s = loadRuleSet(u); return [u, Object.fromEntries(Object.entries(s.rules).map(([k, r]) => [k, r.value]))]; }));
@@ -102,6 +103,7 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
102
103
  return built.get(key);
103
104
  };
104
105
  const placing = [];
106
+ let builtCount = 0;
105
107
  for (const it of a.items || []) {
106
108
  if (!/^[a-z][\w-]*$/.test(it.id || '')) throw new Error(`each item needs an id (letters, digits, - or _): got ${JSON.stringify(it.id)}`);
107
109
  if (!it.object === !it.assembly) throw new Error(`item ${it.id}: give either "object" or "assembly"`);
@@ -140,7 +142,10 @@ export async function buildAssembly(ref, stack = [], overrides = {}, opts = {})
140
142
  }
141
143
  const first = await source(it, copies[0].extra);
142
144
  values[it.id] = first.sub ? first.sub.values : first.b.values; // a repeated item's own name works too: cap.base, not only cap-0-0
143
- for (const c of copies) { c.src = await source(it, c.extra); values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values; }
145
+ for (const c of copies) {
146
+ c.src = await source(it, c.extra); values[c.id] = c.src.sub ? c.src.sub.values : c.src.b.values;
147
+ opts.progress?.({ stage: 'build', assembly: ref, item: c.id, done: ++builtCount }); // progress: for a caller to show (cad --progress)
148
+ }
144
149
  placing.push([it, copies]);
145
150
  }
146
151
  // Then place them: every item is built by now, so a position can refer to any item, before or after it (a board
@@ -323,7 +328,17 @@ function motionOf(a, placed, num, ref) {
323
328
  if (a.pose && !poses[a.pose]) throw new Error(`pose "${a.pose}" isn't one of the poses (${Object.keys(poses).join(', ') || 'none'})`);
324
329
  const loops = (a.loops || []).map((l, i) => ({ label: l.label || `${typeof l.a === 'string' ? l.a : 'anchor'} meets ${typeof l.b === 'string' ? l.b : 'anchor'}`,
325
330
  a: anchor(l.a, `loop ${i + 1}`), b: anchor(l.b, `loop ${i + 1}`), tolerance: l.tolerance != null ? num(l.tolerance) : 0.01 }));
326
- return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref };
331
+ // Every object item's anchors, to say where things are: a finding near one names it (keyboard@pivot)
332
+ const marks = placed.flatMap(([, c], k) => Object.entries(c.src?.b?.object.anchors || {}).map(([name, spec]) => {
333
+ try { return { item: k, id: c.id, name, frame: frameOf(spec, evalIn(c.src.b.values, `${c.src.objName} anchor ${name}`)) }; } catch { return null; }
334
+ })).filter(Boolean);
335
+ return { items, joints, poses, pose: a.pose || Object.keys(poses)[0], loops, ref, marks };
336
+ }
337
+
338
+ // Where each item's anchors are in a pose: [{ id: 'keyboard@pivot', item, at: [x, y, z] }]
339
+ export function anchorsAt(s, values = s.jointValues) {
340
+ const worlds = placeItems(s.motion, values);
341
+ return (s.motion.marks || []).map((m) => { const w = mul(worlds[m.item], m.frame); return { id: `${m.id}@${m.name}`, item: m.id, at: [w[3], w[7], w[11]] }; });
327
342
  }
328
343
 
329
344
  // keyCentres(layout): each key's centre, from lib/layout.mjs (kept under this name for older callers)
@@ -344,7 +359,7 @@ const OVERLAPS = paths.cache('overlaps.json');
344
359
  let remembered = null, fresh = 0;
345
360
  function pairOverlap(pa, pb) {
346
361
  if (!pa.hash || !pb.hash) return overlap(pa.geometry, pb.geometry);
347
- remembered ||= (() => { try { return JSON.parse(fs.readFileSync(OVERLAPS, 'utf8')); } catch { return {}; } })();
362
+ remembered ||= (() => { try { return JSON.parse(host.readText(OVERLAPS)); } catch { return {}; } })();
348
363
  const at = (p) => `${p.hash}@${Array.from(p.m || []).map((x) => Math.round(x * 1e6) / 1e6).join(',')}`;
349
364
  const [x, y] = [at(pa), at(pb)].sort(), k = crypto.createHash('sha1').update(`${x}|${y}`).digest('hex');
350
365
  if (!(k in remembered)) { remembered[k] = overlap(pa.geometry, pb.geometry); fresh++; }
@@ -352,21 +367,21 @@ function pairOverlap(pa, pb) {
352
367
  }
353
368
  function saveOverlaps() {
354
369
  if (!fresh) return;
355
- try { fs.mkdirSync(path.dirname(OVERLAPS), { recursive: true }); fs.writeFileSync(OVERLAPS, JSON.stringify(remembered)); fresh = 0; } catch {} // only slower without it
370
+ try { host.writeText(OVERLAPS, JSON.stringify(remembered)); fresh = 0; } catch {} // only slower without it
356
371
  }
357
372
 
358
373
  // checkAssembly(built) -> findings, as @rulecad/printcheck: { level, text, card? } (card: a short line for the mirror)
359
374
  export function checkAssembly(s) {
360
- const out = [], f = (level, text, card) => out.push({ level, text, ...(card && { card }) }), mm = (n) => `${Number(n.toFixed(3))}`;
375
+ const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(3))}`;
361
376
  // Versions: every pin, from this assembly and its components, against every copy of that object
362
377
  const pins = new Map();
363
378
  for (const r of s.requires) pins.set(`${r.object} ${r.range}`, r);
364
379
  for (const { object, range } of pins.values()) {
365
380
  const copies = s.objects.filter((o) => o.objName === object);
366
- if (!copies.length) { f('fail', `requires ${object} ${range}, but nothing uses it`); continue; }
381
+ if (!copies.length) { f('fail', `requires ${object} ${range}, but nothing uses it`, null, { code: 'requires.unused', refs: { object, range } }); continue; }
367
382
  const bad = copies.filter((o) => !satisfies(o.version, range));
368
383
  f(bad.length ? 'fail' : 'pass', bad.length ? `${object} ${bad[0].version} doesn't meet ${range} (${bad.map((o) => o.id).join(', ')})`
369
- : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`);
384
+ : `${object} ${copies[0].version} meets ${range}${copies.length > 1 ? ` (${copies.length} copies)` : ''}`, null, { code: 'requires.version', refs: { object, range, items: bad.map((o) => o.id) } });
370
385
  }
371
386
  // Overlaps between object instances, inside components too. Bounding boxes first: most pairs can't touch.
372
387
  const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`);
@@ -378,38 +393,60 @@ export function checkAssembly(s) {
378
393
  const pa = s.parts[i], pb = s.parts[j];
379
394
  if (pa.leaf === pb.leaf || !touch(pa, pb) || allowed(pa, pb)) continue;
380
395
  const v = pairOverlap(pa, pb);
381
- if (v > 0.01) clashes.push(`${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`);
396
+ if (v > 0.01) clashes.push({ text: `${pa.name} and ${pb.name} overlap by ${mm(v)} mm³`, a: pa.name, b: pb.name, volume: v });
382
397
  }
383
- if (clashes.length) f('fail', clashes.slice(0, 5).join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''), `${clashes.length} overlaps`);
384
- else f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap');
398
+ if (clashes.length) f('fail', clashes.slice(0, 5).map((c) => c.text).join('; ') + (clashes.length > 5 ? `; and ${clashes.length - 5} more` : ''), `${clashes.length} overlaps`,
399
+ { code: 'overlap', values: { count: clashes.length }, refs: { overlaps: clashes.map(({ a, b, volume }) => ({ a, b, volume })) } });
400
+ else f('pass', `no parts overlap (${new Set(s.parts.map((p) => p.leaf)).size} object instances)`, 'No parts overlap', { code: 'overlap', values: { count: 0 } });
385
401
  // Fits: the closest gap between two named things, against a range. Copies of one fit are reported together, worst first.
386
- const pick = (n) => (Array.isArray(n) ? n.flatMap(pick) : s.parts.filter((p) => named(p, n)));
402
+ // A fit names parts (keyboard, key-0-0.cap), or the faces of an item near one of its anchors (keyboard@pivot, within
403
+ // "within" mm, 10 by default): the pocket round a pivot, not the whole case
404
+ const marks = anchorsAt(s), within = (x) => (x.within != null ? x.num(x.within) : 10);
405
+ const near = (p, mark, r) => ({ ...p, polygons: p.polygons.filter((f) => distanceToFace(mark.at, f) <= r) });
406
+ const pickIn = (n, x) => {
407
+ if (Array.isArray(n)) return n.flatMap((m) => pickIn(m, x));
408
+ if (!n.includes('@')) return s.parts.filter((p) => named(p, n));
409
+ const mark = marks.find((m) => m.id === n);
410
+ if (!mark) return [];
411
+ return s.parts.filter((p) => named(p, mark.item)).map((p) => near(p, mark, within(x))).filter((p) => p.polygons.length);
412
+ };
413
+ const pick = (n) => pickIn(n, {});
387
414
  const groups = new Map();
388
415
  for (const x of s.fits) {
389
416
  if (x.poses && !x.poses.includes(s.pose)) continue; // a fit for some poses only: the folded screen over the keys
390
417
  if (x.holes) { holesFit(x); continue; }
391
- const A = pick(x.a), key = x.note || `${x.a} / ${x.b}`;
418
+ const A = pickIn(x.a, x), key = x.note || `${x.a} / ${x.b}`;
392
419
  const lo = x.min != null ? x.num(x.min) : -Infinity, hi = x.max != null ? x.num(x.max) : Infinity;
393
420
  const reach = Math.max(2, ...[lo, hi].filter(Number.isFinite)) + 1; // look past the range, so a gap near it is measured
394
- let B = pick(x.b);
421
+ let B = pickIn(x.b, x);
395
422
  if (Array.isArray(x.b) && A.length) { // against many others: only those within reach
396
423
  const lo3 = [0, 1, 2].map((k) => Math.min(...A.map((p) => bx(p).lo[k]))), hi3 = [0, 1, 2].map((k) => Math.max(...A.map((p) => bx(p).hi[k])));
397
424
  B = B.filter((p) => [0, 1, 2].every((k) => bx(p).lo[k] <= hi3[k] + reach && lo3[k] <= bx(p).hi[k] + reach));
398
425
  }
399
- if (!A.length || (!B.length && !Array.isArray(x.b))) { f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`); continue; }
426
+ if (!A.length || (!B.length && !Array.isArray(x.b))) { f('fail', `fit ${x.a} / ${x.b}: no such ${A.length ? x.b : x.a}`, null, { code: 'fit.missing', refs: { a: x.a, b: x.b, missing: A.length ? x.b : x.a } }); continue; }
400
427
  const vol = A.reduce((t, pa) => t + B.reduce((u, pb) => u + (touch(pa, pb) ? pairOverlap(pa, pb) : 0), 0), 0);
401
- const gap = !B.length ? Infinity : vol > 0.01 ? -vol : closest(A.flatMap((p) => p.polygons), B.flatMap((p) => p.polygons), reach); // negative: overlap, mm³
428
+ const near = !B.length || vol > 0.01 ? null : closestAt(A.flatMap((p) => p.polygons), B.flatMap((p) => p.polygons), reach);
429
+ const gap = !B.length ? Infinity : vol > 0.01 ? -vol : near.gap; // negative: overlap, mm³
402
430
  const ok = vol > 0.01 ? lo < 0 : gap >= lo && gap <= hi;
403
431
  if (!groups.has(key)) groups.set(key, { x, lo, hi, results: [] });
404
- groups.get(key).results.push({ ok, gap, id: x.a });
432
+ groups.get(key).results.push({ ok, gap, id: x.a, at: near?.at || null });
405
433
  }
434
+ // The anchor nearest a point, if one is within 20 mm: where to look
435
+ const nearest = (pt) => {
436
+ if (!pt || !marks.length) return {};
437
+ const m = marks.map((k) => ({ k, d: Math.hypot(k.at[0] - pt[0], k.at[1] - pt[1], k.at[2] - pt[2]) })).sort((a, b) => a.d - b.d)[0];
438
+ return m.d <= 20 ? { near: m.k.id, distance: Number(m.d.toFixed(2)) } : {};
439
+ };
406
440
  for (const [key, { x, lo, hi, results }] of groups) {
407
441
  const worst = results.reduce((w, r) => (!r.ok && w.ok ? r : r.ok === w.ok && r.gap < w.gap ? r : w), results[0]);
408
442
  const say = (g) => (g < 0 ? `press fit, ${mm(-g)} mm³ overlap` : g === Infinity ? 'not near each other' : `closest gap ${mm(g)} mm`);
409
443
  const n = results.length > 1 ? ` (${results.filter((r) => r.ok).length} of ${results.length} in range)` : '';
410
444
  const label = (x.label || x.a).replace(/ \(.*\)$/, '');
411
- f(worst.ok ? 'pass' : 'warn', `${key}: ${say(worst.gap)}${n}${worst.ok ? '' : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results.filter((r) => !r.ok).map((r) => r.id).join(', ')})`}`,
412
- `${label}: ${worst.gap < 0 ? `press fit ${mm(-worst.gap)} mm³` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`);
445
+ const where = nearest(worst.at);
446
+ f(worst.ok ? 'pass' : 'warn', `${key}: ${say(worst.gap)}${n}${worst.ok ? '' : `, wanted ${lo === -Infinity ? '' : `${mm(lo)} `}to ${hi === Infinity ? 'any' : mm(hi)} mm (${results.filter((r) => !r.ok).map((r) => r.id).join(', ')})${where.near ? `, ${where.distance} mm from ${where.near}` : ''}`}`,
447
+ `${label}: ${worst.gap < 0 ? `press fit ${mm(-worst.gap)} mm³` : worst.gap === Infinity ? 'apart' : `gap ${Number(worst.gap.toFixed(2))} mm`}${worst.ok ? '' : ' (out of range)'}`,
448
+ { code: 'fit', values: { ...(worst.gap < 0 ? { overlap: -worst.gap } : { gap: worst.gap }), min: lo, max: hi, inRange: results.filter((r) => r.ok).length, copies: results.length },
449
+ refs: { a: x.a, b: x.b, label: x.label, ...(s.pose ? { pose: s.pose } : {}), outOfRange: results.filter((r) => !r.ok).map((r) => r.id), ...where }, ...(worst.at ? { at: { lo: worst.at, hi: worst.at } } : {}) });
413
450
  }
414
451
  // Holes fits: each mounting hole's screw path, clear into a hole, with material round it
415
452
  function holesFit(x) {
@@ -430,7 +467,8 @@ export function checkAssembly(s) {
430
467
  if (round.length) misses.push(`${where}: no material ${mm(ring)} mm from the screw on ${round.length} of ${steps} sides`);
431
468
  }
432
469
  f(misses.length ? 'fail' : 'pass', misses.length ? `${label}: ${misses.join('; ')}` : `${label}: ${holes.length} of ${holes.length} holes clear for ${mm(depth)} mm, with material around each`,
433
- `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`);
470
+ `${label}: ${misses.length ? `${misses.length} of ${holes.length} miss` : `${holes.length} of ${holes.length} line up`}`,
471
+ { code: 'fit.holes', values: { holes: holes.length, missed: misses.length }, refs: { a: x.a, b: x.b, misses } });
434
472
  }
435
473
  // Joints: every value in its range (a ball's tip within its cone), and every loop closed
436
474
  if (s.motion?.joints.length) {
@@ -440,19 +478,19 @@ export function checkAssembly(s) {
440
478
  j.dofs.forEach(([lo, hi], i) => { if (v[i] < lo - 1e-9 || v[i] > hi + 1e-9) outside.push(`${j.id} ${mm(v[i])} (${mm(lo)} to ${mm(hi)})`); });
441
479
  if (j.cone != null) { const tip = Math.acos(Math.min(1, jointMatrix(j, v)[10])) / (Math.PI / 180); if (tip > j.cone + 1e-9) outside.push(`${j.id} tips ${mm(tip)}° (cone ${mm(j.cone)}°)`); }
442
480
  }
443
- if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`);
444
- for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`);
481
+ if (outside.length) f('fail', `joints out of range: ${outside.join(', ')}`, `${outside.length} joints out of range`, { code: 'joint.range', refs: { joints: outside } });
482
+ for (const l of loopGaps(s)) f(l.ok ? 'pass' : 'fail', `${l.label}: ${l.ok ? 'closed' : 'apart'} (${mm(l.gap)} mm, axes ${mm(l.angle)}° apart)`, `${l.label}: ${l.ok ? 'closed' : 'apart'}`, { code: 'loop', values: { gap: l.gap, angle: l.angle }, refs: { label: l.label } });
445
483
  }
446
484
  // Plates print everything: no references
447
485
  if (s.a.kind === 'plate') {
448
486
  const refs = s.objects.filter((o) => o.role === 'reference' && !o.unplaced); // an unplaced item only lends its numbers
449
- if (refs.length) f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`);
487
+ if (refs.length) f('fail', `a plate can't print references: ${refs.map((o) => o.id).join(', ')}`, null, { code: 'plate.reference', refs: { items: refs.map((o) => o.id) } });
450
488
  }
451
489
  // Rules that are only estimates, anywhere in the assembly or its components
452
490
  const est = new Set();
453
491
  for (const o of s.objects) for (const e of o.built.entries) if (e.kind === 'estimate' && (e.used || !e.name.includes('.'))) est.add(e.name);
454
492
  for (const n of s.seen) { const [u, k] = n.split('.'); if (loadRuleSet(u).rules[k]?.kind === 'estimate') est.add(n); }
455
- if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure them and record kind: measured`, `Estimate: ${[...est].join(', ')}`);
493
+ if (est.size) f('warn', `uses estimates, not measurements: ${[...est].join(', ')}. Measure them and record kind: measured`, `Estimate: ${[...est].join(', ')}`, { code: 'rules.estimate', refs: { rules: [...est] } });
456
494
  saveOverlaps();
457
495
  return out;
458
496
  }
@@ -484,8 +522,8 @@ const isNamed = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name
484
522
 
485
523
  // sweep(s, { joint, steps }) -> findings: each free joint (or the one named) moved through its range, the others held
486
524
  // at the assembly's pose, looking for parts that collide and loops that come apart on the way
487
- export function sweep(s, { joint, steps = 24 } = {}) {
488
- const out = [], f = (level, text, card) => out.push({ level, text, ...(card && { card }) }), mm = (n) => `${Number(n.toFixed(2))}`;
525
+ export function sweep(s, { joint, steps = 24, progress } = {}) {
526
+ const out = [], f = (level, text, card, extra) => out.push({ level, text, ...(card && { card }), ...extra }), mm = (n) => `${Number(n.toFixed(2))}`;
489
527
  const free = s.motion.joints.filter((j) => !j.follow && j.dofs.length && (!joint || j.id === joint));
490
528
  if (joint && !free.length) throw new Error(`no joint "${joint}" to sweep (${s.motion.joints.filter((j) => !j.follow && j.dofs.length).map((j) => j.id).join(', ') || 'none'})`);
491
529
  const base = s.jointValues;
@@ -497,13 +535,15 @@ export function sweep(s, { joint, steps = 24 } = {}) {
497
535
  const t = s.at(Object.fromEntries(Object.entries(set).filter(([id]) => !s.motion.joints.find((x) => x.id === id).follow)));
498
536
  const what = [...clashesOf(t, isNamed).map(([a, b]) => `${a} hits ${b}`), ...loopGaps(t).filter((l) => !l.ok).map((l) => `${l.label} apart by ${mm(l.gap)} mm`)];
499
537
  if (what.length) bad.push([v, what]);
538
+ progress?.({ stage: 'sweep', joint: j.id, step: i, steps });
500
539
  }
501
540
  const ranges = []; // runs of steps in a row that collide
502
541
  for (const [v, what] of bad) { const r = ranges[ranges.length - 1]; if (r && Math.abs(v - r.to - (hi - lo) / steps) < 1e-9) { r.to = v; r.what = [...new Set([...r.what, ...what])]; } else ranges.push({ from: v, to: v, what }); }
503
542
  const span = `${mm(lo)} to ${mm(hi)}${unit}`;
504
- if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`);
543
+ if (!ranges.length) f('pass', `sweep ${name}, ${span} in ${steps} steps: nothing collides`, `${name}: clear ${span}`, { code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: [] } });
505
544
  else f('fail', `sweep ${name}, ${span} in ${steps} steps: ${ranges.map((r) => `${r.from === r.to ? `at ${mm(r.from)}` : `${mm(r.from)} to ${mm(r.to)}`}${unit.trim()}: ${r.what.slice(0, 3).join('; ')}${r.what.length > 3 ? `; and ${r.what.length - 3} more` : ''}`).join(' | ')}`,
506
- `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`);
545
+ `${name}: collides ${ranges.map((r) => (r.from === r.to ? mm(r.from) : `${mm(r.from)}-${mm(r.to)}`)).join(', ')}${unit.trim()}`,
546
+ { code: 'sweep', values: { from: lo, to: hi, steps }, refs: { joint: name, collisions: ranges.map((r) => ({ from: r.from, to: r.to, what: r.what })) } });
507
547
  });
508
548
  saveOverlaps();
509
549
  return out;
@@ -520,3 +560,28 @@ export function shapes(parts) {
520
560
  }
521
561
  return { shapes: list, place };
522
562
  }
563
+
564
+ // An assembly's joints, for the page's sliders: each part moves with its item (motion in @rulecad/model-link)
565
+ export function motionData(s) {
566
+ const mo = s.motion;
567
+ if (!mo.joints.length) return {};
568
+ const r = (x) => Number(x.toFixed(6)), names = mo.items.map((x) => x[0]);
569
+ const named = (p, n) => p.name === n || p.leaf === n || p.item === n || p.name.startsWith(`${n}.`), allow = [];
570
+ const loose = s.fits.filter((x) => x.min != null && x.num(x.min) < 0);
571
+ s.parts.forEach((pa, i) => s.parts.forEach((pb, j) => {
572
+ if (j > i && pa.item !== pb.item && loose.some((x) => (named(pa, x.a) && named(pb, x.b)) || (named(pa, x.b) && named(pb, x.a)))) allow.push([i, j]);
573
+ }));
574
+ return { motion: {
575
+ items: mo.items.map(([n, ...m]) => [n, ...m.map(r)]),
576
+ joints: mo.joints.map(({ id, type, parent, child, a, b, dofs, label, follow, path, cone }) => ({ id, type, parent, child, a: a.map(r), b: b.map(r), dofs: dofs.map((d) => d.map(r)),
577
+ ...(label ? { label } : {}), ...(follow ? { follow } : {}), ...(path ? { path: path.map((p) => p.map(r)) } : {}), ...(cone != null ? { cone } : {}) })),
578
+ poses: mo.poses, ...(s.pose ? { pose: s.pose } : {}),
579
+ part: s.parts.map((p) => names.indexOf(p.item)),
580
+ ...(allow.length ? { allow } : {}),
581
+ } };
582
+ }
583
+
584
+ // ---------- links ----------
585
+ // The rules sheet a link carries, for the page's Rules panel: a row for each of an object's own values, then each rule
586
+ // they use, as [group, name, value, unit, rule, expr, kind, source, checked] (group: the object, or the rule's set).
587
+ // A rule set marked "private" stays out, and --no-rules leaves the sheet out altogether.
package/lib/design.mjs CHANGED
@@ -14,6 +14,11 @@
14
14
  // @rulecad/pcb describes); the build then carries its Circuit JSON (circuit) and matrix, and one part: the bare board
15
15
  // (its copper is in the 2D views).
16
16
  // Builds are cached in .cache/builds/, by everything they're made from (CAD_NO_CACHE=1 to skip).
17
+ import { located } from './errors.mjs';
18
+ import { host } from './host.mjs';
19
+ import { named, faces, fromFaces, polygons } from './parts.mjs';
20
+ import { runSandboxed, sandboxed } from './sandbox.mjs';
21
+ export { polygons };
17
22
  import fs from 'node:fs';
18
23
  import path from 'node:path';
19
24
  import { pathToFileURL } from 'node:url';
@@ -35,12 +40,12 @@ export function locate(ref) {
35
40
  const [plain, variant] = String(ref).split(':');
36
41
  ref = plain;
37
42
  let base = ref.replace(/\.(js|json)$/, '');
38
- if (!base.includes(path.sep) || !fs.existsSync(`${base}.json`)) {
43
+ if (!base.includes(path.sep) || !host.exists(`${base}.json`)) {
39
44
  const [project, name] = ref.split('/');
40
45
  if (!project || !name) throw new Error(`name a design as <project>/<object>, e.g. keyboard/keycap (got "${ref}")`);
41
46
  base = path.join(paths.project(project), 'objects', name);
42
47
  }
43
- if (!fs.existsSync(`${base}.json`) || !fs.existsSync(`${base}.js`)) throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
48
+ if (!host.exists(`${base}.json`) || !host.exists(`${base}.js`)) throw new Error(`no design at ${path.relative(WS, base)}.{js,json}`);
44
49
  const dir = path.dirname(path.dirname(base));
45
50
  return { project: path.basename(dir), name: path.basename(base), js: `${base}.js`, json: `${base}.json`, dir, ...(variant ? { variant } : {}) };
46
51
  }
@@ -104,8 +109,11 @@ export const pcbEngine = () => import('@rulecad/pcb').catch((e) => {
104
109
 
105
110
  // An object's on-screen settings are "display" ({ "smooth": 24 }), and a part left off screen is "display": false.
106
111
  // Their first name, "mirror", still works: read here, the rest of the tool sees it as mirror either way.
112
+ // Which engine a design's v.ops booleans use: the object's "engine": "manifold", or CAD_ENGINE=manifold for every design
113
+ export const booleans = (object) => (object.engine === 'manifold' ? 'manifold' : object.engine === 'pcb' ? 'jscad' : process.env.CAD_ENGINE || 'jscad');
114
+
107
115
  export const readObject = (d) => {
108
- const o = JSON.parse(fs.readFileSync(d.json, 'utf8'));
116
+ const o = JSON.parse(host.readText(d.json));
109
117
  if (o.display && !o.mirror) o.mirror = o.display;
110
118
  for (const p of Object.values(o.parts || {})) if (p.display === false) p.mirror = false;
111
119
  return o;
@@ -119,7 +127,9 @@ export async function build(d, set = {}, { mirror = false } = {}) {
119
127
  const refs = await objectSets(d, object); // other objects' numbers, when it reads them
120
128
  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
121
129
  const display = mirror ? object.mirror || {} : {};
122
- const { values, entries } = resolve(object, { set, sets, display }); // mirror: lighter for the display
130
+ let resolved;
131
+ try { resolved = resolve(object, { set, sets, display }); } catch (e) { throw located(e, d.json, 'var'); } // mirror: lighter for the display
132
+ const { values, entries, deps, units } = resolved;
123
133
  for (const [n, x] of Object.entries(refs.extra)) Object.assign(values[n], x);
124
134
  const files = layoutsOf(d, object);
125
135
  if (object.layouts) values.layouts = object.layouts; // older designs kept layouts in their .json
@@ -127,77 +137,61 @@ export async function build(d, set = {}, { mirror = false } = {}) {
127
137
 
128
138
  // The cache: everything the build is made from. A hit skips running the design (and its booleans) altogether
129
139
  const ruleText = [...(object.uses || []).map((u) => JSON.stringify(sets[u] || loadRuleSet(u))), JSON.stringify(refs.extra)];
130
- const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : '', fs.readFileSync(d.js, 'utf8'), JSON.stringify(object), ruleText, files, set, display])).digest('hex');
140
+ const key = crypto.createHash('sha256').update(JSON.stringify([CACHE_VERSION, own, object.engine === 'pcb' ? engineId() : booleans(object), host.readText(d.js), JSON.stringify(object), ruleText, files, set, display])).digest('hex');
131
141
  const hit = path.join(CACHE, `${key}.json`);
132
- if (!process.env.CAD_NO_CACHE && fs.existsSync(hit)) {
133
- const c = JSON.parse(fs.readFileSync(hit, 'utf8'));
134
- try { const now = new Date(); fs.utimesSync(hit, now, now); } catch {} // recently used: kept when the cache is pruned
142
+ if (!process.env.CAD_NO_CACHE && host.exists(hit)) {
143
+ const c = JSON.parse(host.readText(hit));
144
+ try { host.touch(hit); } catch {} // recently used: kept when the cache is pruned
135
145
  for (const e of entries) if (c.used.includes(e.name)) e.used = true;
136
146
  const parts = c.parts.map(({ solid: f, ...p }) => ({ ...p, geometry: fromFaces(f) }));
137
147
  if (c.circuit) Object.assign(values, (await pcbEngine()).outputs(c.circuit, c.matrix));
138
- return { object, values, entries, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix } : {}) };
148
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), cached: true, hash: key, ...(c.circuit ? { circuit: c.circuit, matrix: c.matrix } : {}) };
139
149
  }
140
150
 
141
- const mod = await import(`${pathToFileURL(d.js).href}?t=${fs.statSync(d.js).mtimeMs}`).catch((e) => { // a fresh copy after each edit
142
- // Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
143
- 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})`);
144
- 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')}`);
145
- throw e;
146
- });
147
- if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
148
- // Rules the code reads directly (v.mx.housing_top) count as used too, so estimates it relies on get flagged
149
- const read = new Set(), watched = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v && typeof v === 'object'
150
- ? new Proxy(v, { get: (t, r) => { if (typeof r === 'string' && r in t) read.add(`${k}.${r}`); return t[r]; } }) : v]));
151
+ // A JSCAD design runs in a sandbox (sandbox.mjs: another process that can't write files, start programs or reach
152
+ // the network) unless the workspace trusts its designs; a board design runs here, with the board engine
151
153
  const pcb = object.engine === 'pcb' ? await pcbEngine() : null;
152
- watched.shapes = shapes; if (pcb) watched.pcb = pcb;
153
- let made = await mod.main(watched), board = null;
154
- if (object.engine === 'pcb') { // a circuit board: tscircuit builds it, and the bare board is its one part
155
- const { board: b, matrix } = made && made.board ? made : { board: made };
156
- board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}) };
157
- Object.assign(values, pcb.outputs(board.circuit, matrix)); // what it tells the parts around it: outline, Pico
158
- made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth });
154
+ let parts, board = null, read;
155
+ if (!pcb && sandboxed() && host.name === 'node') ({ parts, read } = await runSandboxed(d, values, object.parts || {}, booleans(object)));
156
+ else {
157
+ const mod = await host.loadModule(d.js).catch((e) => { // a fresh copy after each edit
158
+ // Designs import JSCAD themselves, so it has to be installed where they are (it's the workspace's dependency)
159
+ 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})`);
160
+ 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')}`);
161
+ throw e;
162
+ });
163
+ if (typeof mod.main !== 'function') throw new Error(`${path.relative(WS, d.js)} has no exported main(v)`);
164
+ // Rules the code reads directly (v.mx.housing_top) count as used too, so estimates it relies on get flagged
165
+ read = new Set();
166
+ const watched = Object.fromEntries(Object.entries(values).map(([k, v]) => [k, v && typeof v === 'object'
167
+ ? new Proxy(v, { get: (t, r) => { if (typeof r === 'string' && r in t) read.add(`${k}.${r}`); return t[r]; } }) : v]));
168
+ watched.shapes = shapes; watched.ops = await shapes.ops(booleans(object)); if (pcb) watched.pcb = pcb;
169
+ let made;
170
+ try { made = await mod.main(watched); } catch (e) { throw located(e, d.js, 'design.run'); }
171
+ if (object.engine === 'pcb') { // a circuit board: tscircuit builds it, and the bare board is its one part
172
+ const { board: b, matrix } = made && made.board ? made : { board: made };
173
+ board = { circuit: await pcb.render(b), ...(matrix ? { matrix } : {}) };
174
+ Object.assign(values, pcb.outputs(board.circuit, matrix)); // what it tells the parts around it: outline, Pico
175
+ made = pcb.solids(board.circuit, { thickness: values.thickness, smooth: values.smooth });
176
+ }
177
+ parts = named(made, object.parts || {});
159
178
  }
160
- const parts = named(made, object.parts || {});
161
179
  for (const e of entries) if (read.has(e.name)) e.used = true;
162
180
  try {
163
- fs.mkdirSync(CACHE, { recursive: true });
164
181
  prune();
165
- fs.writeFileSync(hit, JSON.stringify({ used: entries.filter((e) => e.used).map((e) => e.name), parts: parts.map(({ geometry, ...p }) => ({ ...p, solid: faces(geometry) })), ...(board || {}) }));
182
+ 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 || {}) }));
166
183
  } catch {} // a cache that can't be written is only slower
167
- return { object, values, entries, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}) };
184
+ return { object, values, entries, deps, units, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles), hash: key, ...(board || {}) };
168
185
  }
169
186
 
170
187
  // The cache keeps its most recently used builds, about CACHE_KEEP of them (an old version's builds go first)
171
188
  const CACHE_KEEP = 800;
172
189
  function prune() {
173
190
  if (Math.random() > 0.05) return; // now and then is enough
174
- const files = fs.readdirSync(CACHE).map((f) => { const p = path.join(CACHE, f); return { p, t: fs.statSync(p).mtimeMs }; }).sort((a, b) => b.t - a.t);
175
- for (const { p } of files.slice(CACHE_KEEP)) fs.rmSync(p, { force: true });
191
+ const files = host.list(CACHE).map((f) => { const p = path.join(CACHE, f); return { p, t: host.mtime(p) }; }).sort((a, b) => b.t - a.t);
192
+ for (const { p } of files.slice(CACHE_KEEP)) host.remove(p);
176
193
  }
177
194
 
178
- // A design's result as parts: named ({ cap, pillar }) or one unnamed shape ("body").
179
- function named(result, meta) {
180
- const isShape = (r) => Array.isArray(r) || jscad.geometries.geom3.isA(r) || jscad.geometries.geom2.isA(r);
181
- const entries = isShape(result) ? [['body', result]] : Object.entries(result || {});
182
- const empty = (g) => g == null || (Array.isArray(g) && !g.length);
183
- for (const k of Object.keys(meta)) if (!meta[k].optional && !entries.some(([n, g]) => n === k && !empty(g))) throw new Error(`parts in the .json lists "${k}", but main() returns no such part`);
184
- return entries.filter(([name, g]) => !(empty(g) && meta[name]?.optional)).map(([name, g]) => {
185
- const m = meta[name] || {};
186
- if (m.role && !['part', 'support'].includes(m.role)) throw new Error(`part ${name}: role is part or support`);
187
- // The solid for booleans (fit checks) is JSCAD's own, exactly; a cached build restores the very same faces
188
- const geometry = solid(g);
189
- return { name, role: m.role || 'part', label: m.label || name, ...(m.filament ? { filament: m.filament } : {}), ...(m.mirror === false ? { mirror: false } : {}),
190
- geometry, polygons: polygons(g), triangles: polygons(g, { triangulate: true }) };
191
- });
192
- }
193
-
194
- // A part's result as one JSCAD solid with its transforms applied (several solids become one set of faces), and back from
195
- // the exact faces a cache keeps: the same numbers, so booleans on a cached build agree with a fresh one.
196
- const { geom3, poly3 } = jscad.geometries;
197
- const solid = (g) => geom3.create([g].flat(Infinity).filter((x) => geom3.isA(x)).flatMap((x) => geom3.toPolygons(x)));
198
- const faces = (g) => geom3.toPolygons(g).map((p) => p.vertices.map((v) => [v[0], v[1], v[2]]));
199
- const fromFaces = (list) => geom3.create(list.map((vs) => poly3.create(vs)));
200
-
201
195
  // The rules of the printer a build is checked against (the project's, else the workspace's), resolved
202
196
  export const printer = (b, d) => { const n = printerOf(d.project); return b.values[n] || resolve({ uses: [n] }).values[n]; };
203
197
 
@@ -211,20 +205,7 @@ export function pick(b, { part, noSupports = false, forMirror = false } = {}) {
211
205
  return { ...b, parts, polygons: parts.flatMap((p) => p.polygons), triangles: parts.flatMap((p) => p.triangles) };
212
206
  }
213
207
 
214
- // Any JSCAD result -> polygons (corner lists), transforms applied. triangulate: also split faces at T-junctions (a
215
- // corner of one face in the middle of a neighbour's edge, left by booleans) so every edge pairs up, as slicers want.
216
- export function polygons(result, { triangulate = false } = {}) {
217
- const { geom3, geom2 } = jscad.geometries;
218
- const out = [];
219
- for (const g of [result].flat(Infinity)) {
220
- if (geom2.isA(g)) throw new Error("2D shapes can't be printed or shown: extrude them first");
221
- if (!geom3.isA(g)) continue;
222
- const fixed = jscad.modifiers.generalize({ snap: true, triangulate }, g);
223
- for (const p of geom3.toPolygons(fixed)) out.push(p.vertices.map((v) => [v[0], v[1], v[2]]));
224
- }
225
- if (!out.length) throw new Error('the design has no 3D shapes');
226
- return out;
227
- }
208
+
228
209
 
229
210
  export { lint } from '@rulecad/variables'; // number literals that should be variables
230
211
 
package/lib/edit.mjs ADDED
@@ -0,0 +1,73 @@
1
+ // Model edits: change a design's JSON by what the change means (set a variable, add a fit, a joint, an item, a pose),
2
+ // keeping the file's layout (lib/jsonedit.mjs), and refusing an edit that leaves the file broken: it must still match
3
+ // its schema, and an object's variables must still resolve. Used by cad set and cad add; a program can call them too.
4
+ import fs from 'node:fs';
5
+ import path from 'node:path';
6
+ import { setAt, appendAt, getAt } from './jsonedit.mjs';
7
+ import { validate, schema } from './schema.mjs';
8
+ import { CadError } from './errors.mjs';
9
+ import { paths } from './workspace.mjs';
10
+ import { locate, readObject, objectSets } from './design.mjs';
11
+ import { resolve } from './rules.mjs';
12
+
13
+ // A value from the command line: a number if it is one, otherwise an expression (or a name) as text
14
+ export const parseValue = (s) => (s === undefined ? undefined : /^-?(\d+\.?\d*|\.\d+)(e-?\d+)?$/i.test(String(s).trim()) ? Number(s) : String(s));
15
+
16
+ function write(file, text, kind) {
17
+ let json;
18
+ try { json = JSON.parse(text); } catch (e) { throw new CadError('edit.broken', `the edit would break ${file}'s JSON: ${e.message}`, { file }); }
19
+ const problems = validate(json, schema(kind));
20
+ if (problems.length) throw new CadError('schema', `${path.basename(file)}: ${problems[0].path}: ${problems[0].message}`, { file, path: problems[0].path });
21
+ fs.writeFileSync(file, text);
22
+ return json;
23
+ }
24
+
25
+ /**
26
+ * Set variables of an object: { name: value }, each with optional unit, rule, label; new ones only with create.
27
+ * @param {string} ref project/object @param {Record<string, { value?: any, unit?: string, rule?: string, label?: string }>} changes
28
+ * @param {{ create?: boolean }} [options] @returns {Promise<{ file: string, changed: string[] }>}
29
+ */
30
+ export async function setVariables(ref, changes, { create = false } = {}) {
31
+ const d = locate(ref), before = fs.readFileSync(d.json, 'utf8');
32
+ let text = before;
33
+ for (const [name, c] of Object.entries(changes)) {
34
+ const exists = getAt(text, ['variables', name]) !== undefined;
35
+ if (!exists && !create) throw new CadError('var.unknown', `${ref} has no variable "${name}" (add it with --new, a unit and a rule)`, { file: d.json, path: `variables.${name}` });
36
+ if (!exists && (c.value === undefined || !c.rule)) throw new CadError('edit.incomplete', `a new variable needs a value and a rule (why the value is what it is): ${name}`, { file: d.json });
37
+ if (!exists) { text = setAt(text, ['variables', name], { value: c.value, ...(c.unit !== undefined ? { unit: c.unit } : {}), rule: c.rule, ...(c.label ? { label: c.label } : {}) }); continue; }
38
+ for (const k of ['value', 'unit', 'rule', 'label']) if (c[k] !== undefined) text = setAt(text, ['variables', name, k], c[k]);
39
+ }
40
+ const json = write(d.json, text, 'object');
41
+ try { // the variables must still resolve: an unknown name or a loop puts the file back as it was
42
+ resolve(json, { sets: (await objectSets(d, readObject(d))).sets });
43
+ } catch (e) { fs.writeFileSync(d.json, before); throw Object.assign(e, { file: d.json, message: `not changed: ${e.message}` }); }
44
+ return { file: d.json, changed: Object.keys(changes) };
45
+ }
46
+
47
+ const assemblyFile = (ref) => {
48
+ const [project, name] = ref.split('/'), file = path.join(paths.project(project), 'assemblies', `${name}.json`);
49
+ if (!fs.existsSync(file)) throw new CadError('assembly.missing', `no assembly at ${path.relative(paths.project(project), file)}`, { file });
50
+ return file;
51
+ };
52
+
53
+ /**
54
+ * Add to an assembly: a fit, a joint, an item or a loop (appended to its list), or a pose (by name).
55
+ * @param {string} ref project/assembly @param {'fit' | 'joint' | 'item' | 'loop' | 'pose'} what @param {any} entry (a pose: { name, values })
56
+ * @returns {{ file: string }}
57
+ */
58
+ export function addToAssembly(ref, what, entry) {
59
+ const file = assemblyFile(ref), before = fs.readFileSync(file, 'utf8'), list = { fit: 'fits', joint: 'joints', item: 'items', loop: 'loops' }[what];
60
+ let text = before;
61
+ if (what === 'pose') {
62
+ if (getAt(text, ['poses']) === undefined) text = setAt(text, ['poses'], {});
63
+ text = setAt(text, ['poses', entry.name], entry.values);
64
+ } else {
65
+ if (!list) throw new CadError('edit.what', `can't add a ${what} (fit, joint, item, loop or pose)`);
66
+ if (getAt(text, [list]) === undefined) text = setAt(text, [list], []);
67
+ const ids = (getAt(text, [list]) || []).map((x) => x.id).filter(Boolean);
68
+ if (entry.id && ids.includes(entry.id)) throw new CadError('edit.duplicate', `${ref} already has a ${what} "${entry.id}"`, { file });
69
+ text = appendAt(text, [list], entry);
70
+ }
71
+ write(file, text, 'assembly');
72
+ return { file };
73
+ }
package/lib/errors.mjs ADDED
@@ -0,0 +1,25 @@
1
+ // Errors that say what went wrong for programs as well as people: a code (var.unknown, design.run, schema, …), the file
2
+ // it's in and, where known, the JSON path to fix (variables.cap_h.value). `cad … --json` prints them as they are.
3
+
4
+ /** An error with a code, and the file and JSON path it's about. */
5
+ export class CadError extends Error {
6
+ /** @param {string} code @param {string} message @param {{ file?: string, path?: string, cause?: unknown }} [where] */
7
+ constructor(code, message, { file, path, cause } = {}) {
8
+ super(message, cause ? { cause } : undefined);
9
+ this.code = code;
10
+ if (file) this.file = file;
11
+ if (path) this.path = path;
12
+ }
13
+ }
14
+
15
+ /** Mark an error with the file it came from (and a code, if it has none). @param {any} e @param {string} file @param {string} [code] */
16
+ export function located(e, file, code) {
17
+ if (e && typeof e === 'object') {
18
+ if (!e.file) e.file = file;
19
+ if (!e.code || typeof e.code !== 'string' || /^ERR_/.test(e.code)) e.code = code || e.code || 'error';
20
+ }
21
+ return e;
22
+ }
23
+
24
+ /** An error as plain data: { code, message, file?, path? }. @param {any} e */
25
+ export const errorData = (e) => ({ code: e?.code || 'error', message: e?.message || String(e), ...(e?.file ? { file: e.file } : {}), ...(e?.path ? { path: e.path } : {}) });
@@ -0,0 +1,40 @@
1
+ // What an object's numbers are, and why: `cad values` and `cad why`. A value's explanation is the tree of names its
2
+ // expression reads, down to the rules (each with its kind and source), following other objects' values into their own
3
+ // designs (link.l = keyboard.link_l, explained in the keyboard).
4
+ import { locate, build, isObjectRef } from './design.mjs';
5
+
6
+ /**
7
+ * An object's own variables, resolved: name, value, unit, expression and rule (all of them, or the names given).
8
+ * @param {{ entries: any[] }} b a build @param {string[]} [names]
9
+ */
10
+ export function valuesOf(b, names = []) {
11
+ const own = b.entries.filter((e) => !e.name.includes('.'));
12
+ const pick = names.length ? names.map((n) => own.find((e) => e.name === n) || (() => { throw Object.assign(new Error(`no variable "${n}" (variables: ${own.map((e) => e.name).join(', ')})`), { code: 'var.unknown' }); })()) : own;
13
+ return pick.map((e) => ({ name: e.name, value: e.value, unit: e.unit || '', ...(e.expr ? { expr: e.expr } : {}), ...(e.rule ? { rule: e.rule } : {}), ...(e.label ? { label: e.label } : {}) }));
14
+ }
15
+
16
+ /**
17
+ * Why a value is what it is: { name, value, unit, expr?, rule?, kind?, source?, object, reads: [...] }, each name its
18
+ * expression reads explained the same way, to `depth` levels. A name met twice is explained once (later: { …, seen: true }).
19
+ * @param {string} ref project/object @param {string} name a variable, or a rule (x1c.line) @param {{ depth?: number }} [options]
20
+ */
21
+ export async function why(ref, name, { depth = 12 } = {}) {
22
+ const builds = new Map(), seen = new Set();
23
+ const get = async (r) => builds.get(r) || (builds.set(r, await build(locate(r))), builds.get(r));
24
+ const node = async (r, n, d) => {
25
+ const b = await get(r), e = b.entries.find((x) => x.name === n);
26
+ if (!e) throw Object.assign(new Error(`${r}: no variable or rule "${n}"`), { code: 'var.unknown' });
27
+ const out = { name: n, value: e.value, unit: e.unit || '', object: r, ...(e.expr ? { expr: e.expr } : {}), ...(e.rule ? { rule: e.rule } : {}),
28
+ ...(e.kind ? { kind: e.kind } : {}), ...(e.source ? { source: e.source } : {}) };
29
+ const key = `${r}:${n}`;
30
+ if (seen.has(key)) return { ...out, seen: true };
31
+ seen.add(key);
32
+ // Another object's value (keyboard.link_l in the link): explained in that object's own design
33
+ const [set, rest] = n.includes('.') ? [n.slice(0, n.indexOf('.')), n.slice(n.indexOf('.') + 1)] : [null, null];
34
+ const from = set && (b.object.uses || []).find((u) => isObjectRef(u) && u.split('/').pop().split(/[:@]/)[0] === set);
35
+ if (from && d > 0) return { ...(await node(from.split(/[:@]/)[0], rest, d - 1)), via: `${r}:${n}` };
36
+ out.reads = d > 0 ? await Promise.all((b.deps?.[n] || []).map((m) => node(r, m, d - 1))) : [];
37
+ return out;
38
+ };
39
+ return node(ref, name, depth);
40
+ }