@rulecad/cad 0.8.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/AGENTS.md +24 -10
  2. package/CHANGELOG.md +404 -0
  3. package/EXAMPLES.md +40 -38
  4. package/README.md +193 -67
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2250 -512
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1847 -434
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/carried.mjs +201 -0
  15. package/lib/clone.mjs +194 -42
  16. package/lib/design.mjs +649 -121
  17. package/lib/drive.mjs +187 -63
  18. package/lib/edit.mjs +899 -191
  19. package/lib/errors.mjs +16 -3
  20. package/lib/explain.mjs +62 -13
  21. package/lib/fasten.mjs +2702 -507
  22. package/lib/fittings.mjs +715 -121
  23. package/lib/fixings.mjs +21 -9
  24. package/lib/framebuild.mjs +790 -175
  25. package/lib/framecheck.mjs +1901 -368
  26. package/lib/framegen.mjs +100 -22
  27. package/lib/frameheat.mjs +225 -42
  28. package/lib/frameprint.mjs +513 -108
  29. package/lib/frames.mjs +81 -17
  30. package/lib/framesize.mjs +792 -120
  31. package/lib/frametip.mjs +235 -0
  32. package/lib/gait.mjs +135 -23
  33. package/lib/grip.mjs +62 -13
  34. package/lib/guides.mjs +1403 -230
  35. package/lib/host.mjs +123 -21
  36. package/lib/inplace.mjs +171 -36
  37. package/lib/jigs.mjs +360 -78
  38. package/lib/joins.mjs +697 -118
  39. package/lib/jsonedit.mjs +88 -26
  40. package/lib/kept.mjs +84 -0
  41. package/lib/kit.mjs +438 -68
  42. package/lib/layout.mjs +2 -1
  43. package/lib/links.mjs +149 -42
  44. package/lib/list.mjs +326 -64
  45. package/lib/live-guard.mjs +68 -0
  46. package/lib/live-shape.mjs +96 -24
  47. package/lib/live.mjs +189 -59
  48. package/lib/loads.mjs +579 -130
  49. package/lib/machine.mjs +372 -74
  50. package/lib/magnets.mjs +162 -44
  51. package/lib/measured.mjs +417 -94
  52. package/lib/mesh.mjs +526 -119
  53. package/lib/meshcmd.mjs +215 -60
  54. package/lib/motors.mjs +1021 -213
  55. package/lib/motorsvg.mjs +114 -32
  56. package/lib/names.mjs +3 -1
  57. package/lib/optimise.mjs +978 -283
  58. package/lib/order.mjs +519 -112
  59. package/lib/panels.mjs +482 -94
  60. package/lib/parts.mjs +78 -23
  61. package/lib/pins.mjs +163 -44
  62. package/lib/plates.mjs +223 -35
  63. package/lib/player.mjs +37 -9
  64. package/lib/power.mjs +64 -13
  65. package/lib/preview.mjs +83 -16
  66. package/lib/profilemeasure.mjs +572 -129
  67. package/lib/rules.mjs +15 -5
  68. package/lib/sandbox-hooks.mjs +77 -19
  69. package/lib/sandbox-run.mjs +117 -18
  70. package/lib/sandbox.mjs +509 -60
  71. package/lib/schema.mjs +42 -11
  72. package/lib/seats.mjs +227 -49
  73. package/lib/services.mjs +261 -52
  74. package/lib/sheet.mjs +851 -178
  75. package/lib/slotnuts.mjs +213 -34
  76. package/lib/targets/gist.mjs +4 -1
  77. package/lib/targets.mjs +22 -4
  78. package/lib/task.mjs +376 -79
  79. package/lib/versions.mjs +111 -28
  80. package/lib/wires.mjs +228 -45
  81. package/lib/workspace.mjs +197 -12
  82. package/package.json +19 -19
  83. package/schemas/assembly.schema.json +2 -2
package/lib/measured.mjs CHANGED
@@ -16,16 +16,27 @@ import path from 'node:path';
16
16
  import { setAt } from './jsonedit.mjs';
17
17
  import { CadError } from './errors.mjs';
18
18
  import { paths, WS, RULE_DIRS, printerOf } from './workspace.mjs';
19
- import { loadRuleSet, peekRuleSet } from './rules.mjs';
19
+ import { loadRuleSet, peekRuleSet, insideWorkspace } from './rules.mjs';
20
+ import { readOwnText } from './host.mjs';
20
21
  import { buildAssembly, checkAssembly, assemblyPath } from './assembly.mjs';
21
22
  import { slotModel, JOIN_SET, joinRuleSet } from '@rulecad/frames';
22
23
  import { fixingsContext } from './design.mjs';
23
24
  import { fixingsFor, threads } from '@rulecad/fixings';
24
25
  import { couponFigure } from './frameprint.mjs';
26
+ import { springFor } from './joins.mjs';
25
27
 
26
- const today = () => new Date().toISOString().slice(0, 10), n = (x) => String(Number(Number(x).toFixed(4)));
28
+ const today = () => new Date().toISOString().slice(0, 10),
29
+ n = (x) => String(Number(Number(x).toFixed(4)));
27
30
  export const ledgerFile = (project) => path.join(paths.project(project), 'ledger.jsonl');
28
- export const readLedger = (project) => { const f = ledgerFile(project); return fs.existsSync(f) ? fs.readFileSync(f, 'utf8').split('\n').filter(Boolean).map((l) => JSON.parse(l)) : []; };
31
+ export const readLedger = (project) => {
32
+ const f = ledgerFile(project);
33
+ return fs.existsSync(f)
34
+ ? readOwnText(f)
35
+ .split('\n')
36
+ .filter(Boolean)
37
+ .map((l) => JSON.parse(l))
38
+ : [];
39
+ };
29
40
 
30
41
  const findingsOf = async (ref) => checkAssembly(await buildAssembly(ref));
31
42
  const keyOf = (x) => `${x.code}|${JSON.stringify(x.refs ?? {})}`;
@@ -36,13 +47,36 @@ export const predictionsOf = (findings) => findings.filter((x) => x.predict);
36
47
  // set @rulecad/frames' estimates), so nothing is written until every value has been checked
37
48
  function ruleFile(name) {
38
49
  const dot = name.indexOf('.');
39
- if (dot < 1) throw new CadError('measured.name', `"${name}": name a rule as <set>.<rule> (x1c.press), or a prediction by its check's code (task.accuracy)`);
40
- const set = name.slice(0, dot), rule = name.slice(dot + 1);
41
- const file = path.join(WS, 'rules', `${set}.json`), from = RULE_DIRS.map((d) => path.join(d, `${set}.json`)).find((f) => fs.existsSync(f));
50
+ if (dot < 1)
51
+ throw new CadError(
52
+ 'measured.name',
53
+ `"${name}": name a rule as <set>.<rule> (x1c.press), or a prediction by its check's code (task.accuracy)`,
54
+ );
55
+ const set = name.slice(0, dot),
56
+ rule = name.slice(dot + 1);
57
+ const file = path.join(WS, 'rules', `${set}.json`),
58
+ from = RULE_DIRS.map((d) => path.join(d, `${set}.json`)).find((f) => fs.existsSync(f));
42
59
  // the joins set has no file in the kit: the workspace's copy starts from @rulecad/frames' estimates
43
- if (set === JOIN_SET && !from) { const text = JSON.stringify(joinRuleSet(), null, 2) + '\n'; return { set, rule, data: JSON.parse(text), file, text, copied: `started rules/${set}.json from @rulecad/frames' estimates: yours to keep and edit` }; }
60
+ if (set === JOIN_SET && !from) {
61
+ const text = JSON.stringify(joinRuleSet(), null, 2) + '\n';
62
+ return {
63
+ set,
64
+ rule,
65
+ data: JSON.parse(text),
66
+ file,
67
+ text,
68
+ copied: `started rules/${set}.json from @rulecad/frames' estimates: yours to keep and edit`,
69
+ };
70
+ }
44
71
  const data = peekRuleSet(set); // (the measurement goes in your copy: the tool's set is copied there when it is written)
45
- return { set, rule, data, file, text: fs.readFileSync(from, 'utf8'), copied: from === file ? null : `copied the ${set} rule set into rules/${set}.json: yours to keep and edit` };
72
+ return {
73
+ set,
74
+ rule,
75
+ data,
76
+ file,
77
+ text: readOwnText(from),
78
+ copied: from === file ? null : `copied the ${set} rule set into rules/${set}.json: yours to keep and edit`,
79
+ };
46
80
  }
47
81
 
48
82
  // The slot coupon (examples/bench/projects/benchmarks/MEASURE.md, rows 29 to 33): the two fits it measures, which a
@@ -51,33 +85,68 @@ function ruleFile(name) {
51
85
  const SLOT_COUPON = 'the slot coupon (examples/bench/projects/benchmarks/MEASURE.md)';
52
86
  function slotRule(project, set, key, data) {
53
87
  if (set === printerOf(project) && ['slot_fit', 'printed_slot_fit'].includes(key)) {
54
- const fit = data.rules?.fit, was = typeof fit?.value === 'number' ? fit.value : null;
55
- return { unit: 'mm', predicted: was, was: `${set}.fit, ${fit?.kind ?? 'none'}`, source: SLOT_COUPON,
56
- rule: key === 'slot_fit' ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${SLOT_COUPON} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
57
- : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${SLOT_COUPON} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`, kind: 'measured' };
88
+ const fit = data.rules?.fit,
89
+ was = typeof fit?.value === 'number' ? fit.value : null;
90
+ return {
91
+ unit: 'mm',
92
+ predicted: was,
93
+ was: `${set}.fit, ${fit?.kind ?? 'none'}`,
94
+ source: SLOT_COUPON,
95
+ rule:
96
+ key === 'slot_fit'
97
+ ? `Clearance each side between a printed part and a bought beam's slot it slides in (a tongue in the opening, a carrier in the cavity): the tightest on ${SLOT_COUPON} that slid the beam's length by hand without rattling. Printed carriers are drawn with it (@rulecad/frames carrierModel) before the general fit`
98
+ : `Clearance each side a slot printed in a part is opened by, so a bought slot nut slides in it: the tightest printed slot on ${SLOT_COUPON} a slide-in nut ran the length of by hand without catching. For printed beams and plates with slots`,
99
+ kind: 'measured',
100
+ };
58
101
  }
59
- if (data.part === 'slot' && data.rules?.[key]) return { source: `calipers on your own beam (${SLOT_COUPON}, row 32)` };
102
+ if (data.part === 'slot' && data.rules?.[key])
103
+ return { source: `calipers on your own beam (${SLOT_COUPON}, row 32)` };
60
104
  return null;
61
105
  }
62
106
 
63
107
  // The joint rig (examples/bench/projects/benchmarks/MEASURE.md, rows 34 to 37): a join's bending spring, written to the
64
108
  // joins set or a bought fitting's set, and a slot nut's hold along its slot, which no maker publishes, so a nut's set
65
109
  // has no rule for it until it is measured
66
- const RIG = 'the joint rig (examples/bench/projects/benchmarks/MEASURE.md)';
67
- function rigRule(set, key, data) {
68
- if (data.part === 'slot_nut' && key === 'hold_along') return { unit: 'N', predicted: null, was: 'no figure: no maker publishes it', source: `${RIG}, a luggage scale`,
69
- rule: `The pull along its slot at which this nut slips, its screw tightened as its maker says (or firmly by hand with a hex key where it says nothing): the reading on ${RIG}'s luggage scale as the nut moved` };
110
+ const RIG_SAID = 'the joint rig (examples/bench/projects/benchmarks/MEASURE.md)';
111
+ function rigRule(set, key, data, frame = null) {
112
+ if (data.part === 'slot_nut' && key === 'hold_along')
113
+ return {
114
+ unit: 'N',
115
+ predicted: null,
116
+ was: 'no figure: no maker publishes it',
117
+ source: `${RIG_SAID}, a luggage scale`,
118
+ rule: `The pull along its slot at which this nut slips, its screw tightened as its maker says (or firmly by hand with a hex key where it says nothing): the reading on ${RIG_SAID}'s luggage scale as the nut moved`,
119
+ };
70
120
  // what a spring measured on the rig is, in place of the estimate's sentence ("a working guess ... until the joint rig
71
121
  // measures it"); the drop it came from goes in its source
72
- const how = `measured on ${RIG}: a beam held out by the join, the drop of its end under a hung mass less the beam's own bending (F L² / that)`;
73
- const turn = (who) => ({ bending: `How stiffly ${who} holds the end of a beam against turning across its axis`, twist: `How stiffly ${who} holds the end of a beam against twisting about its own axis` });
122
+ // (or on a frame of the maker's own: the spring that gives the drop read in that frame's solve)
123
+ const RIG = frame ? `the frame ${frame}, a dial on a beam held out by the join` : RIG_SAID,
124
+ how = frame
125
+ ? `measured on the frame ${frame}: a beam held out by the join, the drop of its end under a hung mass, and the spring that gives that drop in the frame's own solve`
126
+ : `measured on ${RIG}: a beam held out by the join, the drop of its end under a hung mass less the beam's own bending (F L² / that)`;
127
+ const turn = (who) => ({
128
+ bending: `How stiffly ${who} holds the end of a beam against turning across its axis`,
129
+ twist: `How stiffly ${who} holds the end of a beam against twisting about its own axis`,
130
+ });
74
131
  if (set === JOIN_SET) {
75
- const j = key.match(/^(.+)_(bending|twist|printed_share)$/), kind = j?.[1].replace(/_/g, '-');
132
+ const j = key.match(/^(.+)_(bending|twist|printed_share)$/),
133
+ kind = j?.[1].replace(/_/g, '-');
76
134
  if (!j) return { source: RIG };
77
- return { source: RIG, measuredRule: j[2] === 'printed_share' ? `A ${kind} join with a printed fitting, as a share of the fitting's own bending stiffness by finite elements: the join's spring ${how}, over the fitting's figure`
78
- : `${turn(`a ${kind} join`)[j[2]]}, for a 20 mm series profile: ${how}` };
135
+ return {
136
+ source: RIG,
137
+ measuredRule:
138
+ j[2] === 'printed_share'
139
+ ? `A ${kind} join with a printed fitting, as a share of the fitting's own bending stiffness by finite elements: the join's spring ${how}, over the fitting's figure`
140
+ : `${turn(`a ${kind} join`)[j[2]]}, for a 20 mm series profile: ${how}`,
141
+ };
142
+ }
143
+ if (data.part === 'fitting' && /_stiffness$/.test(key)) {
144
+ const k = key.replace(/_stiffness$/, '');
145
+ return {
146
+ source: RIG,
147
+ ...(turn('this fitting')[k] ? { measuredRule: `${turn('this fitting')[k]}, its screws tight: ${how}` } : {}),
148
+ };
79
149
  }
80
- if (data.part === 'fitting' && /_stiffness$/.test(key)) { const k = key.replace(/_stiffness$/, ''); return { source: RIG, ...(turn('this fitting')[k] ? { measuredRule: `${turn('this fitting')[k]}, its screws tight: ${how}` } : {}) }; }
81
150
  return null;
82
151
  }
83
152
 
@@ -89,9 +158,16 @@ function couponRule(set, key, data) {
89
158
  const m = key.match(/^beam_(modulus|strength)(_z)?$/);
90
159
  if (!m || data.rules?.density == null) return null;
91
160
  const how = m[2] ? 'printed standing up, bent across its layers' : 'printed lying down, its layers along it';
92
- return { unit: 'MPa', source: BEAM_COUPON, predicted: data.rules?.[m[2] && data.rules[`${m[1]}_z`] ? `${m[1]}_z` : m[1]]?.value ?? null, was: `${set}.${m[1]}${m[2] && data.rules[`${m[1]}_z`] ? '_z' : ''}, the data sheet's`,
93
- measuredRule: m[1] === 'modulus' ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${BEAM_COUPON} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
94
- : `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${BEAM_COUPON} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it` };
161
+ return {
162
+ unit: 'MPa',
163
+ source: BEAM_COUPON,
164
+ predicted: data.rules?.[m[2] && data.rules[`${m[1]}_z`] ? `${m[1]}_z` : m[1]]?.value ?? null,
165
+ was: `${set}.${m[1]}${m[2] && data.rules[`${m[1]}_z`] ? '_z' : ''}, the data sheet's`,
166
+ measuredRule:
167
+ m[1] === 'modulus'
168
+ ? `The modulus a printed beam of ${set.toUpperCase()} bends at, ${how}, with its section counted from its walls and infill (@rulecad/frames printedSection): the sag of ${BEAM_COUPON} under a hung mass, measured with a dial, and the solve's sag scaled to it. A printed beam takes it before the plastic's own modulus`
169
+ : `The stress a printed beam of ${set.toUpperCase()} breaks at in bending, ${how}, its section counted from its walls and infill: the mass ${BEAM_COUPON} broke at, as the stress the solve gives under it. A printed beam takes it before the plastic's own strength, and its creep limit follows it`,
170
+ };
95
171
  }
96
172
 
97
173
  // The printer's rules the fixings read that a printer's set may not hold yet, each measured on the fixings coupon
@@ -101,25 +177,53 @@ function couponRule(set, key, data) {
101
177
  const COUPON = 'the fixings coupon (examples/bench/projects/benchmarks/MEASURE.md)';
102
178
  function fixingsRule(project, set, key) {
103
179
  if (set !== printerName(project)) return null;
104
- let fx; const f = () => (fx ||= (() => { const { context } = fixingsContext({ project, dir: paths.project(project) }); return { ...fixingsFor({ sets: context.sets, printer: context.printer }), material: context.material }; })());
105
- const plastic = (p) => (p ?? f().material ?? 'the project\'s plastic').toUpperCase();
180
+ let fx;
181
+ const f = () =>
182
+ (fx ||= (() => {
183
+ const { context } = fixingsContext({ project, dir: paths.project(project) });
184
+ return { ...fixingsFor({ sets: context.sets, printer: context.printer }), material: context.material };
185
+ })());
186
+ const plastic = (p) => (p ?? f().material ?? "the project's plastic").toUpperCase();
106
187
  const hole = key.match(/^(pilot|insert)_(.+)$/);
107
188
  if (hole) {
108
189
  const bySet = new Map(threads().map((t) => [fixingsFor().fixingModel(t).set, t]));
109
- const [setName, thread] = [...bySet].filter(([k]) => hole[2] === k || hole[2].startsWith(`${k}_`)).sort((a, b) => b[0].length - a[0].length)[0] ?? [];
190
+ const [setName, thread] =
191
+ [...bySet]
192
+ .filter(([k]) => hole[2] === k || hole[2].startsWith(`${k}_`))
193
+ .sort((a, b) => b[0].length - a[0].length)[0] ?? [];
110
194
  if (!thread) return null;
111
195
  const own = hole[2].slice(setName.length + 1) || null;
112
196
  if (own && !/^[a-z][a-z0-9]*$/.test(own)) return null;
113
197
  const h = f().holeModel(thread, { kind: hole[1], ...(own ? { material: own } : {}) });
114
- return { unit: 'mm', predicted: h.nominal, was: `${h.basis.rule}, ${h.basis.kind}`,
115
- rule: hole[1] === 'pilot' ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${COUPON} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
116
- : `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${COUPON} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
117
- source: COUPON };
198
+ return {
199
+ unit: 'mm',
200
+ predicted: h.nominal,
201
+ was: `${h.basis.rule}, ${h.basis.kind}`,
202
+ rule:
203
+ hole[1] === 'pilot'
204
+ ? `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} screw to form its own thread in ${plastic(own)}, standing upright: the one on ${COUPON} the screw went into straight and held in, turned by hand. Drawn as it is: no hole compensation`
205
+ : `Hole to draw for ${/^(M|8|11|18)/.test(thread) ? 'an' : 'a'} ${thread} heat-set insert in ${plastic(own)}: the one on ${COUPON} the insert went into straight and flush, and held when a screw was tightened in it. Drawn as it is: no hole compensation`,
206
+ source: COUPON,
207
+ };
208
+ }
209
+ if (key === 'nut_fit')
210
+ return {
211
+ unit: 'mm',
212
+ predicted: f().nutPocketModel('M3').clearance,
213
+ was: 'snug, no clearance',
214
+ source: COUPON,
215
+ rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit`,
216
+ };
217
+ if (key === 'nut_slip') {
218
+ const t = f().nutTrapModel('M3', { depth: 1 });
219
+ return {
220
+ unit: 'mm',
221
+ predicted: t.clearance,
222
+ was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip',
223
+ source: COUPON,
224
+ rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit`,
225
+ };
118
226
  }
119
- if (key === 'nut_fit') return { unit: 'mm', predicted: f().nutPocketModel('M3').clearance, was: 'snug, no clearance', source: COUPON,
120
- rule: `Clearance across the flats of a nut pocket let in from a face, on top of hole_comp: the tightest on ${COUPON} a hex nut dropped into by hand and did not turn in as its screw was tightened. A nut pocket's snug fit` };
121
- if (key === 'nut_slip') { const t = f().nutTrapModel('M3', { depth: 1 }); return { unit: 'mm', predicted: t.clearance, was: t.rests.find((r) => /slip$/.test(r.name))?.name ?? 'slip', source: COUPON,
122
- rule: `Clearance across the flats of a nut slot a nut slides into from the side, on top of hole_comp: the tightest on ${COUPON} a hex nut slid into by hand, stayed in turned over, and did not turn as its screw was tightened. A nut slot's slip fit` }; }
123
227
  // The holds coupon's fits (rows 40 to 45): each the printer's rule a pin, a snap pin's socket or a magnet's pocket is
124
228
  // drawn from, read through the model that draws it, so the ledger's prediction is what the kit drew; and the snap
125
229
  // pins' barb, a record as the flank form is. Each is held to what a fit of its kind can be, so a slip of the pen
@@ -127,45 +231,117 @@ function fixingsRule(project, set, key) {
127
231
  const fit = HOLDS[key];
128
232
  if (fit) {
129
233
  const r = fit.model(f()).rests.find((x) => x.name.endsWith(`.${key}`) || x.name.endsWith(`'s ${key}`));
130
- return { unit: 'mm', predicted: r?.value ?? fit.kit, was: r ? `${r.name}, ${r.kind}` : fit.was, source: HOLDS_COUPON, measuredRule: fit.rule,
131
- check: (x) => (x < fit.range[0] || x > fit.range[1] || (fit.above && x === 0) ? `is ${fit.above ? 'above' : 'from'} ${fit.range[0]}${fit.above ? ' and up' : ''} to ${fit.range[1]} mm: ${fit.why}` : null) };
234
+ return {
235
+ unit: 'mm',
236
+ predicted: r?.value ?? fit.kit,
237
+ was: r ? `${r.name}, ${r.kind}` : fit.was,
238
+ source: HOLDS_COUPON,
239
+ measuredRule: fit.rule,
240
+ check: (x) =>
241
+ x < fit.range[0] || x > fit.range[1] || (fit.above && x === 0)
242
+ ? `is ${fit.above ? 'above' : 'from'} ${fit.range[0]}${fit.above ? ' and up' : ''} to ${fit.range[1]} mm: ${fit.why}`
243
+ : null,
244
+ };
245
+ }
246
+ if (key === 'thread_flank') {
247
+ const t = f().threadModel('M8', { length: f().holeModel('M8', { kind: 'thread' }).depth, internal: true });
248
+ return {
249
+ unit: '°',
250
+ predicted: t.overhang.drawn,
251
+ was: 'flanks: printed, the default',
252
+ source: COUPON,
253
+ allowed: [t.overhang.drawn, t.overhang.standard],
254
+ rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise`,
255
+ };
132
256
  }
133
- if (key === 'thread_flank') { const t = f().threadModel('M8', { length: f().holeModel('M8', { kind: 'thread' }).depth, internal: true }); return { unit: '°', predicted: t.overhang.drawn, was: 'flanks: printed, the default', source: COUPON, allowed: [t.overhang.drawn, t.overhang.standard],
134
- rule: `The down-facing flank of a printed thread standing upright, as an overhang from upright: ${t.overhang.drawn} is the form laid back to the printer's overhang (flanks: 'printed', the kit's default), ${t.overhang.standard} the standard's own form (flanks: 'standard'). The one on ${COUPON} that held, turned smoothly and printed clean. A record for choosing the default: designs still draw flanks: 'printed' unless they say otherwise` }; }
135
257
  return null;
136
258
  }
137
259
  // The holds coupon's fits: the rule each writes once measured, what bounds it, and the model that draws from it
138
260
  const HOLDS_COUPON = 'the holds coupon (examples/bench/projects/benchmarks/MEASURE.md)';
139
261
  const HOLDS = {
140
- snap_clearance: { range: [0, 0.5], above: true, model: (f) => f.pinModel('snap pin 4x6'), why: 'its gap is drawn with no hole compensation, so at 0 the printed socket comes out smaller than the peg and pinches it: a press, not a snap. Past half a millimetre a pin rocks; the coupon prints 0.1 to 0.3, and never a socket at 0',
141
- rule: `Gap round a printed snap pin's peg in its socket, each side, as drawn (no hole compensation): the socket on ${HOLDS_COUPON} a snap pin clicked through by hand and then held without rocking` },
142
- pin_press: { range: [0, 0.3], model: (f) => f.pinModel('dowel 3x12', { fit: 'press' }), why: 'how much smaller a hole is drawn than the pin it grips, past hole_comp, and more than 0.3 mm splits a printed boss; the coupon prints 0 to 0.1',
143
- rule: `How much smaller across a printed hole is drawn than a plain pin pressed into it, past hole_comp: the hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) pressed into by hand or in a vice, stood straight, and could not be pulled out by hand` },
144
- pin_slip: { range: [0, 0.6], model: (f) => f.pinModel('dowel 3x12', { fit: 'slip' }), why: 'how much larger a hole is drawn than the pin that turns in it, past hole_comp, and past 0.6 mm it is a loose hole. At 0 the hole is the pin and hole_comp, the pin\'s own size once printed: a close slip; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1',
145
- rule: `How much larger across a printed hole is drawn than a plain pin that turns in it, past hole_comp: the tightest hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) slid into by hand and turned freely in` },
146
- magnet_press: { range: [0, 0.4], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'press' }), why: 'how much smaller a pocket is drawn than the magnet it grips, past hole_comp, and more than 0.4 mm splits its wall; the coupon prints 0 to 0.2',
147
- rule: `How much smaller across a printed pocket is drawn than a disc magnet pressed into it, past hole_comp: the pocket on ${HOLDS_COUPON} a 6x3 and an 8x3 magnet went into with a thumb or a vice, flush, without splitting the wall, and stayed in when the plate was turned over and tapped` },
148
- magnet_glue: { range: [0, 0.6], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'glue' }), why: 'room for a film of glue across the pocket, past hole_comp, and past 0.6 mm the magnet sits off centre; the coupon\'s press row shows where a magnet drops in',
149
- rule: `How much larger across a printed pocket is drawn than a magnet glued into it, past hole_comp: the least on ${HOLDS_COUPON} a magnet dropped into freely, which leaves room for glue` },
150
- magnet_crush: { range: [0, 0.6], model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'ribs' }), why: 'how far inside the magnet the crush ribs\' tips stand, past hole_comp, and past 0.6 mm a rib no longer crushes but splits. At 0 the ribs\' tips stand at the magnet and hole_comp, a light crush once printed; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1',
151
- rule: `With crush ribs, how much smaller across the ribs' tips stand than the magnet, past hole_comp: the ribbed pocket on ${HOLDS_COUPON} an 8x3 magnet pressed into by hand, flush, and held when the plate was turned over and tapped` },
152
- snap_barb: { range: [0, 1], above: true, kit: 0.4, was: 'barb 0.4, the default', model: () => ({ rests: [] }), why: 'a snap pin\'s barb past its peg, and past a millimetre the halves cannot close enough to let it through; the coupon prints 0.3 to 0.5',
153
- rule: `A snap pin's barb past its peg: the one on ${HOLDS_COUPON} that clicked through its socket by hand and held when pulled. A record for choosing the default: pins are still drawn with a 0.4 mm barb unless their name says barb N` }
262
+ snap_clearance: {
263
+ range: [0, 0.5],
264
+ above: true,
265
+ model: (f) => f.pinModel('snap pin 4x6'),
266
+ why: 'its gap is drawn with no hole compensation, so at 0 the printed socket comes out smaller than the peg and pinches it: a press, not a snap. Past half a millimetre a pin rocks; the coupon prints 0.1 to 0.3, and never a socket at 0',
267
+ rule: `Gap round a printed snap pin's peg in its socket, each side, as drawn (no hole compensation): the socket on ${HOLDS_COUPON} a snap pin clicked through by hand and then held without rocking`,
268
+ },
269
+ pin_press: {
270
+ range: [0, 0.3],
271
+ model: (f) => f.pinModel('dowel 3x12', { fit: 'press' }),
272
+ why: 'how much smaller a hole is drawn than the pin it grips, past hole_comp, and more than 0.3 mm splits a printed boss; the coupon prints 0 to 0.1',
273
+ rule: `How much smaller across a printed hole is drawn than a plain pin pressed into it, past hole_comp: the hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) pressed into by hand or in a vice, stood straight, and could not be pulled out by hand`,
274
+ },
275
+ pin_slip: {
276
+ range: [0, 0.6],
277
+ model: (f) => f.pinModel('dowel 3x12', { fit: 'slip' }),
278
+ why: "how much larger a hole is drawn than the pin that turns in it, past hole_comp, and past 0.6 mm it is a loose hole. At 0 the hole is the pin and hole_comp, the pin's own size once printed: a close slip; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1",
279
+ rule: `How much larger across a printed hole is drawn than a plain pin that turns in it, past hole_comp: the tightest hole on ${HOLDS_COUPON} a 3 mm dowel (or 1.75 mm filament) slid into by hand and turned freely in`,
280
+ },
281
+ magnet_press: {
282
+ range: [0, 0.4],
283
+ model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'press' }),
284
+ why: 'how much smaller a pocket is drawn than the magnet it grips, past hole_comp, and more than 0.4 mm splits its wall; the coupon prints 0 to 0.2',
285
+ rule: `How much smaller across a printed pocket is drawn than a disc magnet pressed into it, past hole_comp: the pocket on ${HOLDS_COUPON} a 6x3 and an 8x3 magnet went into with a thumb or a vice, flush, without splitting the wall, and stayed in when the plate was turned over and tapped`,
286
+ },
287
+ magnet_glue: {
288
+ range: [0, 0.6],
289
+ model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'glue' }),
290
+ why: "room for a film of glue across the pocket, past hole_comp, and past 0.6 mm the magnet sits off centre; the coupon's press row shows where a magnet drops in",
291
+ rule: `How much larger across a printed pocket is drawn than a magnet glued into it, past hole_comp: the least on ${HOLDS_COUPON} a magnet dropped into freely, which leaves room for glue`,
292
+ },
293
+ magnet_crush: {
294
+ range: [0, 0.6],
295
+ model: (f) => f.magnetSeatModel('disc magnet 8x3', { fit: 'ribs' }),
296
+ why: "how far inside the magnet the crush ribs' tips stand, past hole_comp, and past 0.6 mm a rib no longer crushes but splits. At 0 the ribs' tips stand at the magnet and hole_comp, a light crush once printed; the coupon prints 0.1 to 0.3, and 0 once it is centred on 0.1",
297
+ rule: `With crush ribs, how much smaller across the ribs' tips stand than the magnet, past hole_comp: the ribbed pocket on ${HOLDS_COUPON} an 8x3 magnet pressed into by hand, flush, and held when the plate was turned over and tapped`,
298
+ },
299
+ snap_barb: {
300
+ range: [0, 1],
301
+ above: true,
302
+ kit: 0.4,
303
+ was: 'barb 0.4, the default',
304
+ model: () => ({ rests: [] }),
305
+ why: "a snap pin's barb past its peg, and past a millimetre the halves cannot close enough to let it through; the coupon prints 0.3 to 0.5",
306
+ rule: `A snap pin's barb past its peg: the one on ${HOLDS_COUPON} that clicked through its socket by hand and held when pulled. A record for choosing the default: pins are still drawn with a 0.4 mm barb unless their name says barb N`,
307
+ },
154
308
  };
155
309
 
156
310
  // The pull bolt on the holds coupon (row 46): an M8 printed bolt whose waist breaks across its layers, so it measures
157
311
  // how strongly a plastic holds across its layers, which PLA's data sheet does not give. It goes in the plastic's set
158
312
  // as strength_z, which a printed bolt standing on its head, and every part pulled across its layers, then reads
159
313
  function boltRule(set, key, data) {
160
- if (key !== 'strength_z' || data.rules?.density == null || typeof data.rules?.strength?.value !== 'number') return null;
161
- const along = data.rules.strength.value, z = data.rules.strength_z;
162
- return { unit: 'MPa', predicted: z?.value ?? along, was: z ? `${set}.strength_z, ${z.kind}` : `${set}.strength, along the layers: no figure across them`, source: `${HOLDS_COUPON}, the pull bolt broken on a luggage scale`,
314
+ if (key !== 'strength_z' || data.rules?.density == null || typeof data.rules?.strength?.value !== 'number')
315
+ return null;
316
+ const along = data.rules.strength.value,
317
+ z = data.rules.strength_z;
318
+ return {
319
+ unit: 'MPa',
320
+ predicted: z?.value ?? along,
321
+ was: z ? `${set}.strength_z, ${z.kind}` : `${set}.strength, along the layers: no figure across them`,
322
+ source: `${HOLDS_COUPON}, the pull bolt broken on a luggage scale`,
163
323
  measuredRule: `Tensile strength of ${set.toUpperCase()} across its printed layers: the pull bolt on ${HOLDS_COUPON}, printed standing, broken on a luggage scale at its 3.5 mm waist (the kilograms × 9.81 over 9.62 mm²). A printed bolt standing on its head, and any part pulled across its layers, takes it before the along-layer strength`,
164
- check: (x) => (!(x > 0) || x > along ? `is above 0 and no more than ${set}.strength, ${along} MPa: a print holds less across its layers than along them, so read the scale's peak again, and work it as kilograms × 9.81 over the waist's 9.62 mm²` : null) };
324
+ check: (x) =>
325
+ !(x > 0) || x > along
326
+ ? `is above 0 and no more than ${set}.strength, ${along} MPa: a print holds less across its layers than along them, so read the scale's peak again, and work it as kilograms × 9.81 over the waist's 9.62 mm²`
327
+ : null,
328
+ };
165
329
  }
166
- const printerName = (project) => { try { return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c'; } catch { return 'x1c'; } };
330
+ const printerName = (project) => {
331
+ try {
332
+ return fixingsContext({ project, dir: paths.project(project) }).context.printer?.name ?? 'x1c';
333
+ } catch {
334
+ return 'x1c';
335
+ }
336
+ };
167
337
  // A rule the workspace's copy lacks and the kit's own set of that name holds (a set copied before the rule was added)
168
- function kitRule(set, key) { try { return JSON.parse(fs.readFileSync(path.join(RULE_DIRS.at(-1), `${set}.json`), 'utf8')).rules?.[key] ?? null; } catch { return null; } }
338
+ function kitRule(set, key) {
339
+ try {
340
+ return JSON.parse(fs.readFileSync(path.join(RULE_DIRS.at(-1), `${set}.json`), 'utf8')).rules?.[key] ?? null;
341
+ } catch {
342
+ return null;
343
+ }
344
+ }
169
345
 
170
346
  /**
171
347
  * Write measurements back.
@@ -176,85 +352,232 @@ function kitRule(set, key) { try { return JSON.parse(fs.readFileSync(path.join(R
176
352
  */
177
353
  export async function recordMeasured(ref, values, { unit, source, rule, date = today() } = {}) {
178
354
  const [project, name] = String(ref).split('/');
179
- if (!project || !name || !fs.existsSync(assemblyPath(ref))) throw new CadError('measured.assembly', `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`);
180
- if (!Object.keys(values).length) throw new CadError('measured.usage', 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]');
181
- const before = await findingsOf(ref), entries = [], predictions = predictionsOf(before);
182
- const writes = [], slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
355
+ if (!project || !name || !fs.existsSync(assemblyPath(ref)))
356
+ throw new CadError(
357
+ 'measured.assembly',
358
+ `no assembly "${ref}": give <project>/<assembly>, the one whose predictions it moves`,
359
+ );
360
+ if (!Object.keys(values).length)
361
+ throw new CadError(
362
+ 'measured.usage',
363
+ 'usage: cad measured <project>/<assembly> <name>=<value> … [--unit mm] [--source "how it was measured"]',
364
+ );
365
+ const before = await findingsOf(ref),
366
+ entries = [],
367
+ predictions = predictionsOf(before);
368
+ const writes = [],
369
+ slots = new Map(); // (every value is checked before any is written, so a refusal leaves the rule sets as they were)
183
370
  // a rule's new value, checked before anything is written (a refusal leaves the rule sets as they were)
184
- const writeRule = (k, value, { from = null, unit: u = unit } = {}) => {
371
+ const writeRule = (k, value, { from = null, unit: u = unit, frame = null } = {}) => {
185
372
  const { set, rule: key, data, file, text, copied } = ruleFile(k);
186
- const old = data.rules?.[key], known = slotRule(project, set, key, data) ?? rigRule(set, key, data) ?? couponRule(set, key, data) ?? boltRule(set, key, data) ?? fixingsRule(project, set, key) ?? (old ? null : kitRule(set, key));
187
- if (known?.allowed && !known.allowed.includes(value)) throw new CadError('measured.value', `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`);
373
+ const old = data.rules?.[key],
374
+ known =
375
+ slotRule(project, set, key, data) ??
376
+ rigRule(set, key, data, frame) ??
377
+ couponRule(set, key, data) ??
378
+ boltRule(set, key, data) ??
379
+ fixingsRule(project, set, key) ??
380
+ (old ? null : kitRule(set, key));
381
+ if (known?.allowed && !known.allowed.includes(value))
382
+ throw new CadError(
383
+ 'measured.value',
384
+ `${k} is ${known.allowed.join(' or ')}: the flank forms the coupon prints (got ${value})`,
385
+ );
188
386
  const wrong = known?.check?.(value);
189
387
  if (wrong) throw new CadError('measured.value', `${k} ${wrong} (got ${value})`);
190
- if (!old && !rule && !known) throw new CadError('measured.rule', `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`);
191
- const had = old ?? known, prior = typeof had?.value === 'number' ? had.value : known?.predicted ?? null;
192
- if (u && had?.unit && u !== had.unit) throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${u}: give it in ${had.unit}`);
388
+ if (!old && !rule && !known)
389
+ throw new CadError(
390
+ 'measured.rule',
391
+ `${set} has no rule "${key}" (and no check here predicts "${k}"): --rule "what it is" to add it (checks: ${[...new Set(predictions.map((x) => x.code))].join(', ') || 'none'})`,
392
+ );
393
+ const had = old ?? known,
394
+ prior = typeof had?.value === 'number' ? had.value : (known?.predicted ?? null);
395
+ if (u && had?.unit && u !== had.unit)
396
+ throw new CadError('measured.unit', `${k} is in ${had.unit}, and this is in ${u}: give it in ${had.unit}`);
193
397
  // its sentence: what was measured, never the estimate's "until it is measured": the one given, else the rig's, else the rule's own
194
- const entry = { value, unit: u ?? had?.unit ?? '', rule: (from ? null : rule) ?? known?.measuredRule ?? had.rule, kind: 'measured', source: [source || known?.source || 'measured on the bench', from].filter(Boolean).join(': '), checked: date };
398
+ const entry = {
399
+ value,
400
+ unit: u ?? had?.unit ?? '',
401
+ rule: (from ? null : rule) ?? known?.measuredRule ?? had.rule,
402
+ kind: 'measured',
403
+ source: [source || known?.source || 'measured on the bench', from].filter(Boolean).join(': '),
404
+ checked: date,
405
+ };
195
406
  if (data.part === 'slot') slots.set(set, { data, change: { ...slots.get(set)?.change, [key]: value } });
196
407
  writes.push({ file, key, entry, text, copied, set });
197
- entries.push({ date, assembly: name, name: k, figure: entry.rule, unit: entry.unit, predicted: prior, was: old ? old.kind : known?.was ?? known?.kind ?? null, measured: value, ratio: prior ? value / prior : null, ...(source ? { source } : {}) });
408
+ entries.push({
409
+ date,
410
+ assembly: name,
411
+ name: k,
412
+ figure: entry.rule,
413
+ unit: entry.unit,
414
+ predicted: prior,
415
+ was: old ? old.kind : (known?.was ?? known?.kind ?? null),
416
+ measured: value,
417
+ ratio: prior ? value / prior : null,
418
+ ...(source ? { source } : {}),
419
+ });
198
420
  };
199
421
  for (const [k, value] of Object.entries(values)) {
200
422
  if (!Number.isFinite(value)) throw new CadError('measured.value', `${k}: a measurement is a number (got ${value})`);
201
423
  const named = predictions.filter((x) => x.code === k || x.predict.name === k);
202
424
  if (named.length) {
203
425
  const p = named[0].predict;
204
- entries.push({ date, assembly: name, name: k, code: named[0].code, figure: p.figure, unit: p.unit, predicted: p.value, measured: value, ratio: p.value ? value / p.value : null, ...(source ? { source } : {}) });
426
+ entries.push({
427
+ date,
428
+ assembly: name,
429
+ name: k,
430
+ code: named[0].code,
431
+ figure: p.figure,
432
+ unit: p.unit,
433
+ predicted: p.value,
434
+ measured: value,
435
+ ratio: p.value ? value / p.value : null,
436
+ ...(source ? { source } : {}),
437
+ });
205
438
  // a drop on the joint rig: what the beam bends of it is the beam's own; the rest is the join turning, so its spring
206
439
  if (p.rig) {
207
- const r = p.rig, n = (x) => String(Number(Number(x).toFixed(3)));
208
- if (!(value > r.beam)) throw new CadError('measured.value', `${k}: ${n(value)} mm is no more than the ${n(r.beam)} mm the beam bends by itself under ${n(r.force)} N at ${n(r.arm)} mm, so the join would be stiffer than solid metal: read the drop again, from the dial's reading with the mass hung less its reading without`);
209
- const spring = (r.force * r.arm * r.arm) / (value - r.beam), figure = Number((spring * r.per).toPrecision(4));
210
- writeRule(r.rule, figure, { unit: r.unit, from: `${n(value)} mm drop of ${k.replace(/\.drop$/, '')} under ${n(r.force)} N at ${n(r.arm)} mm (${r.join}), less the beam's own ${n(r.beam)} mm, is a spring of ${(spring / 1e6).toFixed(3)} N·m/mrad` });
440
+ const r = p.rig,
441
+ n = (x) => String(Number(Number(x).toFixed(3)));
442
+ const frame = r.from === 'frame',
443
+ rigidSaid = frame
444
+ ? `the ${n(r.rigid)} mm the frame gives under ${n(r.force)} N at ${n(r.arm)} mm with the join${r.others ? ` and the ${r.others} other${r.others > 1 ? 's' : ''} on the same rule` : ''} held rigid`
445
+ : `the ${n(r.rigid)} mm the beam bends by itself under ${n(r.force)} N at ${n(r.arm)} mm`;
446
+ // the spring that gives the drop read, from the same model the prediction came from: the frame solved again at
447
+ // each step of a bounded search, or the rig's closed form
448
+ const found = typeof r.dropAt === 'function' ? springFor(r, value) : { refused: 'unsolved' };
449
+ if (found.refused === 'stiff')
450
+ throw new CadError(
451
+ 'measured.value',
452
+ `${k}: ${n(value)} mm is no more than ${rigidSaid}, so the join would be stiffer than solid metal: read the drop again, from the dial's reading with the mass hung less its reading without`,
453
+ );
454
+ if (found.refused === 'soft')
455
+ throw new CadError(
456
+ 'measured.value',
457
+ `${k}: ${n(value)} mm is more than the join can give: even a million times softer than its ${(r.spring / 1e6).toFixed(3)} N·m/mrad it drops ${n(found.most)} mm, so something else gives (a support or another join loose, the dial's arm moving): look at what holds the frame and the dial, and read the drop again`,
458
+ );
459
+ if (found.refused)
460
+ throw new CadError(
461
+ 'measured.value',
462
+ `${k}: no join spring was found that gives ${n(value)} mm${frame ? " in the frame's solve" : ''}, so nothing is written: read the drop again, and check the frame's supports`,
463
+ );
464
+ const spring = found.spring,
465
+ figure = Number((spring * r.per).toPrecision(4));
466
+ writeRule(r.rule, figure, {
467
+ unit: r.unit,
468
+ frame: frame ? `${project}/${name}` : null,
469
+ from: frame
470
+ ? `${n(value)} mm drop of ${k.replace(/\.drop$/, '')} under ${n(r.force)} N at ${n(r.arm)} mm (${r.join}), in the frame's solve where ${n(r.rigid)} mm of it is the frame with the join${r.others ? ` and the ${r.others} other${r.others > 1 ? 's' : ''} on the same rule` : ''} held rigid, is a spring of ${(spring / 1e6).toFixed(3)} N·m/mrad`
471
+ : `${n(value)} mm drop of ${k.replace(/\.drop$/, '')} under ${n(r.force)} N at ${n(r.arm)} mm (${r.join}), less the beam's own ${n(r.beam)} mm, is a spring of ${(spring / 1e6).toFixed(3)} N·m/mrad`,
472
+ });
211
473
  }
212
474
  // the beam coupon: the modulus from its sag, the strength from the mass it broke at
213
475
  if (p.coupon) {
214
- const c = p.coupon, figure = couponFigure(c, p.value, value);
215
- if (!(value > 0)) throw new CadError('measured.value', `${k}: a ${c.kind === 'modulus' ? 'sag' : 'mass'} is above 0 (got ${value})`);
216
- writeRule(c.rule, figure, { unit: c.unit, from: c.kind === 'modulus' ? `${n(value)} mm sag of ${k.replace(/\.sag$/, '')} under ${c.what}, against ${n(p.value)} mm at ${n(c.base)} MPa` : `broke at ${n(value)} kg ${c.what}, ${n(c.perKg)} MPa a kilogram on its own weight's ${n(c.self)} MPa` });
476
+ const c = p.coupon,
477
+ figure = couponFigure(c, p.value, value);
478
+ if (!(value > 0))
479
+ throw new CadError(
480
+ 'measured.value',
481
+ `${k}: a ${c.kind === 'modulus' ? 'sag' : 'mass'} is above 0 (got ${value})`,
482
+ );
483
+ writeRule(c.rule, figure, {
484
+ unit: c.unit,
485
+ from:
486
+ c.kind === 'modulus'
487
+ ? `${n(value)} mm sag of ${k.replace(/\.sag$/, '')} under ${c.what}, against ${n(p.value)} mm at ${n(c.base)} MPa`
488
+ : `broke at ${n(value)} kg ${c.what}, ${n(c.perKg)} MPa a kilogram on its own weight's ${n(c.self)} MPa`,
489
+ });
217
490
  }
218
491
  continue;
219
492
  }
220
493
  writeRule(k, value);
221
494
  }
222
495
  // a slot's figures together still make a slot (an opening narrower than its cavity, lips thinner than it is deep)
223
- for (const [set, { data, change }] of slots) { try { slotModel(data, change); } catch (e) { throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`); } }
496
+ for (const [set, { data, change }] of slots) {
497
+ try {
498
+ slotModel(data, change);
499
+ } catch (e) {
500
+ throw new CadError('measured.value', `${set}: ${e.message.replace(/^slotModel: /, '')}`);
501
+ }
502
+ }
224
503
  // every value checked: now each set is written, the workspace's copy made from where it started where there is none
225
504
  const texts = new Map();
226
- for (const w of writes) texts.set(w.file, { ...w, text: setAt(texts.get(w.file)?.text ?? w.text, ['rules', w.key], w.entry) });
505
+ for (const w of writes)
506
+ texts.set(w.file, { ...w, text: setAt(texts.get(w.file)?.text ?? w.text, ['rules', w.key], w.entry) });
227
507
  for (const [file, w] of texts) {
228
- fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, w.text);
508
+ fs.mkdirSync(path.dirname(file), { recursive: true });
509
+ fs.writeFileSync(file, w.text);
229
510
  if (w.copied) console.error(w.copied);
230
511
  }
231
- const after = await findingsOf(ref), was = new Map(before.map((x) => [keyOf(x), x])), moved = [];
512
+ const after = await findingsOf(ref),
513
+ was = new Map(before.map((x) => [keyOf(x), x])),
514
+ moved = [];
232
515
  for (const x of after) {
233
516
  const y = was.get(keyOf(x));
234
- if (x.predict && y?.predict && Math.abs(x.predict.value - y.predict.value) > 1e-9) moved.push({ code: x.code, figure: x.predict.figure, unit: x.predict.unit, from: y.predict.value, to: x.predict.value });
517
+ if (x.predict && y?.predict && Math.abs(x.predict.value - y.predict.value) > 1e-9)
518
+ moved.push({
519
+ code: x.code,
520
+ figure: x.predict.figure,
521
+ unit: x.predict.unit,
522
+ from: y.predict.value,
523
+ to: x.predict.value,
524
+ });
235
525
  else if (y && y.text !== x.text && !x.predict) moved.push({ code: x.code, text: x.text, was: y.text });
236
526
  }
237
- fs.appendFileSync(ledgerFile(project), entries.map((e) => JSON.stringify({ ...e, moved: moved.filter((m) => m.figure) })).join('\n') + '\n');
527
+ fs.appendFileSync(
528
+ insideWorkspace(ledgerFile(project)), // (never through a link: rules.mjs)
529
+ entries.map((e) => JSON.stringify({ ...e, moved: moved.filter((m) => m.figure) })).join('\n') + '\n',
530
+ );
238
531
  return { entries, moved, findings: after };
239
532
  }
240
533
 
241
534
  // What the kit assumes, as a Markdown table: each rule used that is only an estimate, what measures it, and what it feeds
242
535
  export async function assumptionsTable(ref) {
243
- const findings = await findingsOf(ref), estimates = findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? [], preds = predictionsOf(findings);
536
+ const findings = await findingsOf(ref),
537
+ estimates = findings.find((x) => x.code === 'rules.estimate')?.refs?.rules ?? [],
538
+ preds = predictionsOf(findings);
244
539
  const rows = estimates.map((name) => {
245
- let rule = ''; try { const [u, k] = name.split('.'); rule = loadRuleSet(u).rules[k]?.rule ?? ''; } catch {}
540
+ let rule = '';
541
+ try {
542
+ const [u, k] = name.split('.');
543
+ rule = loadRuleSet(u).rules[k]?.rule ?? '';
544
+ } catch {
545
+ // (no such rule set or rule: the table leaves its rule blank)
546
+ }
246
547
  return `| \`${name}\` | ${rule} | estimate | \`cad measured ${ref} ${name}=<value>\` |`;
247
548
  });
248
- const out = ['| What the kit assumes | What it is | Trust | How to settle it |', '|---|---|---|---|', ...rows,
249
- ...preds.map((x) => `| ${x.predict.figure} | ${n(x.predict.value)} ${x.predict.unit}, predicted by \`${x.code}\` | prediction | \`cad measured ${ref} ${x.predict.name ?? x.code}=<value>\` |`)];
549
+ const out = [
550
+ '| What the kit assumes | What it is | Trust | How to settle it |',
551
+ '|---|---|---|---|',
552
+ ...rows,
553
+ ...preds.map(
554
+ (x) =>
555
+ `| ${x.predict.figure} | ${n(x.predict.value)} ${x.predict.unit}, predicted by \`${x.code}\` | prediction | \`cad measured ${ref} ${x.predict.name ?? x.code}=<value>\` |`,
556
+ ),
557
+ ];
250
558
  return out.join('\n');
251
559
  }
252
560
  // A table kept in a file, between two markers: the rest of the file stays as written
253
561
  export const MARK = ['<!-- cad measured: start -->', '<!-- cad measured: end -->'];
254
562
  export function writeTable(file, table) {
255
- const text = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '', a = text.indexOf(MARK[0]), b = text.indexOf(MARK[1]);
563
+ const text = fs.existsSync(file) ? readOwnText(file) : '',
564
+ a = text.indexOf(MARK[0]),
565
+ b = text.indexOf(MARK[1]);
256
566
  const block = `${MARK[0]}\n${table}\n${MARK[1]}`;
257
- fs.writeFileSync(file, a >= 0 && b > a ? text.slice(0, a) + block + text.slice(b + MARK[1].length) : `${text}${text && !text.endsWith('\n') ? '\n' : ''}\n${block}\n`);
567
+ fs.writeFileSync(
568
+ file,
569
+ a >= 0 && b > a
570
+ ? text.slice(0, a) + block + text.slice(b + MARK[1].length)
571
+ : `${text}${text && !text.endsWith('\n') ? '\n' : ''}\n${block}\n`,
572
+ );
258
573
  }
259
574
 
260
- export const ledgerLines = (entries) => entries.map((e) => `${e.date} ${e.assembly} ${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() + (e.predicted != null ? `, predicted ${n(e.predicted)}${e.was ? ` (${e.was})` : ''}${e.ratio != null ? `, ratio ${n(e.ratio)}` : ''}` : '') + (e.source ? ` [${e.source}]` : ''));
575
+ export const ledgerLines = (entries) =>
576
+ entries.map(
577
+ (e) =>
578
+ `${e.date} ${e.assembly} ${e.name}: measured ${n(e.measured)} ${e.unit || ''}`.trimEnd() +
579
+ (e.predicted != null
580
+ ? `, predicted ${n(e.predicted)}${e.was ? ` (${e.was})` : ''}${e.ratio != null ? `, ratio ${n(e.ratio)}` : ''}`
581
+ : '') +
582
+ (e.source ? ` [${e.source}]` : ''),
583
+ );