@rulecad/cad 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (102) hide show
  1. package/AGENTS.md +45 -16
  2. package/CHANGELOG.md +724 -0
  3. package/EXAMPLES.md +61 -54
  4. package/README.md +376 -98
  5. package/TUTORIAL.md +2 -2
  6. package/bin/cad.mjs +2664 -541
  7. package/lib/animate.mjs +173 -49
  8. package/lib/assembly.mjs +1883 -435
  9. package/lib/beams.mjs +256 -52
  10. package/lib/belts.mjs +66 -15
  11. package/lib/board-work.mjs +12 -0
  12. package/lib/bought.mjs +309 -53
  13. package/lib/buildpage.mjs +179 -29
  14. package/lib/cache-file.mjs +105 -0
  15. package/lib/carried.mjs +201 -0
  16. package/lib/clone.mjs +194 -42
  17. package/lib/code-text.mjs +28 -0
  18. package/lib/design-imports.mjs +127 -0
  19. package/lib/design.mjs +871 -147
  20. package/lib/designshapes.mjs +142 -0
  21. package/lib/drive.mjs +187 -63
  22. package/lib/edit.mjs +922 -192
  23. package/lib/errors.mjs +16 -3
  24. package/lib/estimates.mjs +51 -0
  25. package/lib/explain.mjs +62 -13
  26. package/lib/fasten.mjs +2708 -507
  27. package/lib/fe-key.mjs +29 -0
  28. package/lib/fittings.mjs +721 -122
  29. package/lib/fixings.mjs +38 -13
  30. package/lib/framebuild.mjs +790 -175
  31. package/lib/framecheck.mjs +1901 -368
  32. package/lib/framegen.mjs +108 -22
  33. package/lib/frameheat.mjs +225 -42
  34. package/lib/frameprint.mjs +513 -108
  35. package/lib/frames.mjs +86 -18
  36. package/lib/framesize.mjs +719 -120
  37. package/lib/frametip.mjs +235 -0
  38. package/lib/gait.mjs +135 -23
  39. package/lib/grip.mjs +62 -13
  40. package/lib/guides.mjs +1403 -230
  41. package/lib/host.mjs +129 -23
  42. package/lib/inplace.mjs +171 -36
  43. package/lib/jigs.mjs +360 -78
  44. package/lib/joins.mjs +697 -118
  45. package/lib/jsonedit.mjs +88 -26
  46. package/lib/kept.mjs +84 -0
  47. package/lib/kit.mjs +439 -69
  48. package/lib/layout.mjs +2 -1
  49. package/lib/links.mjs +149 -42
  50. package/lib/list.mjs +334 -64
  51. package/lib/live-guard.mjs +68 -0
  52. package/lib/live-shape.mjs +96 -24
  53. package/lib/live.mjs +189 -59
  54. package/lib/loads.mjs +597 -136
  55. package/lib/machine.mjs +372 -74
  56. package/lib/magnets.mjs +162 -44
  57. package/lib/measured.mjs +1080 -117
  58. package/lib/mesh.mjs +526 -119
  59. package/lib/meshcmd.mjs +215 -60
  60. package/lib/motors.mjs +1002 -214
  61. package/lib/motorsvg.mjs +114 -32
  62. package/lib/names.mjs +18 -1
  63. package/lib/optimise.mjs +991 -287
  64. package/lib/order.mjs +515 -114
  65. package/lib/panels.mjs +482 -94
  66. package/lib/parts.mjs +81 -23
  67. package/lib/pins.mjs +163 -44
  68. package/lib/plates.mjs +223 -35
  69. package/lib/player.mjs +37 -9
  70. package/lib/power.mjs +64 -13
  71. package/lib/preview.mjs +83 -16
  72. package/lib/profilemeasure.mjs +572 -129
  73. package/lib/rules.mjs +17 -6
  74. package/lib/sandbox-hooks.mjs +179 -27
  75. package/lib/sandbox-lock.mjs +225 -0
  76. package/lib/sandbox-preload.mjs +2 -2
  77. package/lib/sandbox-run.mjs +122 -25
  78. package/lib/sandbox.mjs +667 -75
  79. package/lib/schema.mjs +42 -11
  80. package/lib/seats.mjs +227 -49
  81. package/lib/services.mjs +261 -52
  82. package/lib/sheet.mjs +963 -179
  83. package/lib/slotnuts.mjs +213 -34
  84. package/lib/targets/gist.mjs +4 -1
  85. package/lib/targets.mjs +22 -4
  86. package/lib/task.mjs +376 -79
  87. package/lib/versions.mjs +285 -39
  88. package/lib/wires.mjs +228 -45
  89. package/lib/workspace.mjs +200 -14
  90. package/package.json +19 -19
  91. package/schemas/assembly.schema.json +2 -2
  92. package/schemas/project.schema.json +6 -0
  93. package/templates/coupons/MEASURE.md +109 -0
  94. package/templates/coupons/assemblies/fixings-test.json +20 -0
  95. package/templates/coupons/assemblies/slot-test.json +11 -0
  96. package/templates/coupons/objects/fixings-coupon.js +88 -0
  97. package/templates/coupons/objects/fixings-coupon.json +26 -0
  98. package/templates/coupons/objects/holds-coupon.js +130 -0
  99. package/templates/coupons/objects/holds-coupon.json +42 -0
  100. package/templates/coupons/objects/slot-coupon.js +89 -0
  101. package/templates/coupons/objects/slot-coupon.json +29 -0
  102. package/templates/coupons/project.json +10 -0
package/bin/cad.mjs CHANGED
@@ -4,41 +4,111 @@ import fs from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import { execFileSync } from 'node:child_process';
6
6
  import { fmt, loadRuleSet, insideWorkspace } from '../lib/rules.mjs';
7
- import { WS, TOOL, paths, config, configError, printerOf, asks, trust, trusted } from '../lib/workspace.mjs';
7
+ import { estimatesFinding } from '../lib/estimates.mjs';
8
+ import { WS, TOOL, paths, configError, printerOf, asks, trust } from '../lib/workspace.mjs';
8
9
  import { isPlainName, plainName } from '../lib/names.mjs';
9
10
  import { fromKLE } from '@rulecad/keyboard-layout';
10
11
  import { target, hasTarget } from '../lib/targets.mjs';
11
- import { locate, locateIn, build, pick, lint, readObject, printer, pcbEngine, objectSets } from '../lib/design.mjs';
12
- import { git, tags, bump, bigger, newer, compare, snapshot, materialise, files, prints, printsFile, engineId } from '../lib/versions.mjs';
12
+ import {
13
+ locate,
14
+ locateIn,
15
+ build,
16
+ pick,
17
+ lint,
18
+ readObject,
19
+ printer,
20
+ pcbEngine,
21
+ objectSets,
22
+ boardChecks,
23
+ readTexts,
24
+ } from '../lib/design.mjs';
25
+ import {
26
+ git,
27
+ tags,
28
+ bump,
29
+ bigger,
30
+ newer,
31
+ compare,
32
+ snapshot,
33
+ materialise,
34
+ files,
35
+ readsLine,
36
+ prints,
37
+ printsFile,
38
+ engineId,
39
+ } from '../lib/versions.mjs';
13
40
  import { check } from '@rulecad/printcheck';
14
41
  import { preview } from '../lib/preview.mjs';
15
42
  import { measure, match } from '../lib/meshcmd.mjs';
16
43
  import { cloneBoard } from '../lib/clone.mjs';
17
- import { isAssembly, buildAssembly, checkAssembly, shapes, sweep, motionData, wireTubesOf } from '../lib/assembly.mjs';
44
+ import {
45
+ isAssembly,
46
+ buildAssembly,
47
+ assemblyOverrides,
48
+ checkAssembly,
49
+ shapes,
50
+ sweep,
51
+ wireTubesOf,
52
+ } from '../lib/assembly.mjs';
18
53
  import { valuesOf, why } from '../lib/explain.mjs';
19
- import { errorData, near } from '../lib/errors.mjs';
54
+ import { CadError, errorData, near } from '../lib/errors.mjs';
20
55
  import { schemaFindings } from '../lib/schema.mjs';
21
- import { readJson } from '../lib/host.mjs';
22
- import { optimised, readProblem, analysePart, picture, problemFile, densitiesKey } from '../lib/optimise.mjs';
56
+ import { readJson, readOwnText, cached } from '../lib/host.mjs';
57
+ import { writeCacheFile, readCacheJson } from '../lib/cache-file.mjs';
58
+ import {
59
+ optimised,
60
+ ownResults,
61
+ readProblem,
62
+ analysePart,
63
+ picture,
64
+ problemFile,
65
+ densitiesKey,
66
+ settledFinding,
67
+ } from '../lib/optimise.mjs';
23
68
  import { evaluate } from '../lib/rules.mjs';
24
- import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, newObject, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
69
+ import {
70
+ setVariables,
71
+ addToAssembly,
72
+ fastenFromFitsEdit,
73
+ parseValue,
74
+ valueFor,
75
+ parseSetting,
76
+ newProject,
77
+ setProject,
78
+ newAssembly,
79
+ newObject,
80
+ setInAssembly,
81
+ removeFromAssembly,
82
+ moveInAssembly,
83
+ } from '../lib/edit.mjs';
25
84
  import { setAt } from '../lib/jsonedit.mjs';
26
85
  import { threemf, slotOf } from '../lib/threemf.mjs';
27
86
  import { liveView, recorder, endOnly } from '../lib/live.mjs';
28
- import { checkSets, drawSet, draftSet, draftPart, draftParts } from '../lib/sheet.mjs';
29
- import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW } from '../lib/links.mjs';
87
+ import { checkSets, drawSet, draftSet, draftPart, draftParts, updateSet } from '../lib/sheet.mjs';
88
+ import { filaments, slots, linkTo, objectModel, assemblyModel, VIEW, viewNote } from '../lib/links.mjs';
30
89
 
31
90
  // What the print file asks of the AMS: which filament each kind of part prints in
32
91
  function filamentNotes(parts, fil) {
33
92
  const used = [...new Set(parts.map((p) => p.filament || 'base'))];
34
93
  const missing = used.filter((f) => f !== 'base' && !fil[f]);
35
- if (missing.length) return [{ level: 'fail', text: `parts print in ${missing.join(', ')}, which project.json's filaments don't list` }];
36
- return [{ level: 'pass', text: used.length > 1 ? `${used.length} filaments: ${used.map((f) => `${f} in AMS slot ${slotOf(fil, f)}${fil[f]?.name ? ` (${fil[f].name})` : ''}`).join(', ')}` : 'one filament' }];
94
+ if (missing.length)
95
+ return [{ level: 'fail', text: `parts print in ${missing.join(', ')}, which project.json's filaments don't list` }];
96
+ return [
97
+ {
98
+ level: 'pass',
99
+ text:
100
+ used.length > 1
101
+ ? `${used.length} filaments: ${used.map((f) => `${f} in AMS slot ${slotOf(fil, f)}${fil[f]?.name ? ` (${fil[f].name})` : ''}`).join(', ')}`
102
+ : 'one filament',
103
+ },
104
+ ];
37
105
  }
38
106
 
39
107
  // --open: the 3MF in Bambu Studio (macOS), else whatever opens .3mf files
40
- const openInSlicer = (f) => (process.platform === 'darwin' ? execFileSync('open', ['-a', 'Bambu Studio', f])
41
- : execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]));
108
+ const openInSlicer = (f) =>
109
+ process.platform === 'darwin'
110
+ ? execFileSync('open', ['-a', 'Bambu Studio', f])
111
+ : execFileSync(process.platform === 'win32' ? 'explorer' : 'xdg-open', [f]);
42
112
 
43
113
  const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
44
114
 
@@ -46,14 +116,19 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
46
116
  cad new <project> a project: its project.json [--title …] [--description …] [--material PLA] [--printer x1c]
47
117
  cad new <project>/<assembly> --assembly an empty assembly that checks [--title …] (makes the project if needed); with
48
118
  --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set>
49
- [--join blind] [--fitting printed] [--feet levelling] [--caps false]: a generated frame
119
+ [--join blind] [--fitting printed] [--estimate] [--feet levelling] [--caps false]: a generated frame
120
+ cad coupons the kit's test prints as projects/coupons: the fixings, holds and slot coupons, and
121
+ MEASURE.md, which says how to read each and the cad measured command that writes it back
50
122
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
51
123
  cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
52
124
  cad agents AGENTS.md: how an AI agent should design in this workspace
53
125
  cad trust allow what this workspace's cad.config.json asks (no sandbox, its own targets)
54
126
  cad rules <project>/<object> every variable: value, the rule behind it, its source
55
127
  cad rules check [set …] rule sets held to what makes them traceable (exit 1 on a failure) [--json]; notes,
56
- never failures: an alias in "interface", and what the kit's set has that your copy lacks
128
+ never failures: an alias in "interface", what the kit's set has that your copy lacks or
129
+ has newer, and a copy that is the kit's word for word
130
+ cad rules update <set> your copy in rules/ brought up to the kit's: its newer figures and new rules, keeping
131
+ your measured figures, those you checked since, and rules of your own [--dry-run] [--json]
57
132
  cad rules draw <set> a dimension drawing of what a set says a part mounts by, <set>.svg, to compare with its datasheet [--out file]
58
133
  cad rules draft <name> --from <file.pdf> the figures in a datasheet's text, into rules/<name>.json for you to name and check (all kind estimate)
59
134
  cad rules draft profile|slot|slot_nut <name> every field a beam's profile, a slot family or a slot nut has, to fill from its sheet
@@ -88,10 +163,11 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
88
163
  assembly with a motor or gears: the drive turning them, cut across the shafts [--turns n]
89
164
  cad optimise <project>/<problem> the stiffest layout for a problem in the project's problems/ (name:variant for a
90
165
  variant): a picture in .preview/, the result kept for designs [--fresh] [--json]
91
- [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button];
166
+ [--watch [port]: a live view of it at http://127.0.0.1:8090/, with a stop button]
167
+ [--allow-host <name>: open the live view by that name too, a Tailscale name say];
92
168
  each run is kept to watch again: <problem>-run.html in .preview/
93
169
  cad preview <project>/problems/<problem> a problem's result and its run, step by step, as a page that needs no
94
- server (or the run live, with --watch [port])
170
+ server (or the run live, with --watch [port], and --allow-host as for cad optimise)
95
171
  cad export <project>/<object> a 3MF for Bambu Studio in exports/ [--open: open it in Bambu Studio]
96
172
  cad show <project>/<object> the model on display through your show target, with its rules [--ttl 10m]
97
173
  cad link <project>/<object> links to open the model in a browser, and to download its STL or 3MF
@@ -107,7 +183,8 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
107
183
  cad release <project>/<object> -m "what changed" [--bump major|minor|patch] [--dry-run] [--push]
108
184
  check it, compare with the last release, suggest the bump, then commit, tag and log it in CHANGELOG.md
109
185
  cad release <project> -m "…" a project release: records the version of each object
110
- cad history <project>[/<object>] releases, with what changed and what was printed
186
+ cad history <project>[/<object>] releases, with what changed and what was printed (cad history alone: the figures
187
+ written with no assembly)
111
188
  cad diff <project>/<object> <from> [<to>] what changed between two releases (or a release and now)
112
189
  cad printed <project>/<object> --result ok|failed [--note "…"] [--material PETG] [--version 0.1.0]
113
190
  cad release <project> --all -m "…" release every object that changed (each with this message), then the project
@@ -132,7 +209,17 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
132
209
  cad measured <project>/<assembly> <name>=<value> … a measurement, where the estimate was: a rule (x1c.press=0.08) or a
133
210
  check's prediction (task.accuracy=0.8): says what moved, and keeps a ledger of predicted
134
211
  against measured, shown by cad history [--unit mm] [--source "how"] [--rule "what it is"]
135
- [--table: what the assembly still assumes, as Markdown; --out MEASURE.md: kept in that file]
212
+ [--force: a figure of the other sign, or under half or over twice the one it replaces (a tenth
213
+ to ten times, an estimate's), refused as a slip without it]
214
+ [--table: every estimate, community figure and default the assembly still rests on, the coupon
215
+ that measures each, and its predictions, as Markdown; --json: as data; --out MEASURE.md: kept there]
216
+ [--strike <date> <name>[=<figure>]: a row taken out of the ledger; the rule set it went into is
217
+ left as it is, and the command says what it still holds]
218
+ cad measured <name>=<value> … the same with no assembly: a rule measured on a coupon (x1c.pilot_m3=2.9), written to
219
+ your copy of its set and kept in the workspace's ledger, shown by cad history alone
220
+ (--strike <date> <name> takes a row out of it)
221
+ cad measured --export every figure measured here that the kit lacks, as a diff of the kit's rule sets
222
+ (packages/rules/<set>.json), to send to the kit [--json]
136
223
  The fixings coupon's rules need no --rule: x1c.pilot_m4, x1c.insert_m3 (and _petg for one
137
224
  plastic), x1c.nut_fit, x1c.nut_slip, x1c.thread_gap, x1c.thread_flank (45 or 60)
138
225
  The slot coupon's need no --rule: x1c.slot_fit, x1c.printed_slot_fit; a slot measured by
@@ -159,36 +246,228 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
159
246
 
160
247
  <project>/<object>@<version> any command but release works on a release: cad export keyboard/keycap@0.1.0
161
248
  --set name=value,name=value change variables that have a tweak range (any command)
249
+ --set item.name=value on an assembly: that item's variable (check, preview, export, show, link, list)
162
250
  --part <name> only that part (check, preview, export, link): e.g. --part cap
163
251
  --explode preview: parts moved apart, so each can be seen
164
252
  --trailer "Co-Authored-By: …" added to release commits (for agents)
165
253
  cad --version this tool's version`;
166
254
 
167
255
  // Every command and option there is: a misspelt one is refused by name, not passed over
168
- const COMMANDS = ['new', 'remove', 'move', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
169
- 'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'frame', 'wires', 'machine', 'plot', 'plates', 'order', 'kit', 'match', 'variants', 'compare', 'help'];
170
- const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-steps', 'all', 'along', 'at', 'bump', 'depth', 'dry-run', 'explode', 'force', 'fresh', 'json', 'licence', 'license', 'long', 'm', 'material', 'md', 'name', 'new',
171
- 'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
172
- 'sweep', 'tol', 'trailer', 'ttl', 'version', 'watch', 'line',
173
- 'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', 'cycles', 'period', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit, cad plot
174
- 'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
175
- 'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
176
- 'kind', 'fitting', // cad add join
177
- 'title', 'description', 'printer', 'frame', 'inside', 'outside', 'join', 'feet', 'caps', 'with-refs', 'mass', 'joint']; // cad new, cad remove, cad add load
256
+ const COMMANDS = [
257
+ 'new',
258
+ 'coupons',
259
+ 'remove',
260
+ 'move',
261
+ 'import-kle',
262
+ 'clone',
263
+ 'agents',
264
+ 'trust',
265
+ 'rules',
266
+ 'values',
267
+ 'set',
268
+ 'add',
269
+ 'why',
270
+ 'check',
271
+ 'preview',
272
+ 'animate',
273
+ 'optimise',
274
+ 'optimize',
275
+ 'export',
276
+ 'show',
277
+ 'link',
278
+ 'status',
279
+ 'release',
280
+ 'history',
281
+ 'diff',
282
+ 'printed',
283
+ 'measure',
284
+ 'measured',
285
+ 'list',
286
+ 'beams',
287
+ 'frame',
288
+ 'wires',
289
+ 'machine',
290
+ 'plot',
291
+ 'plates',
292
+ 'order',
293
+ 'kit',
294
+ 'match',
295
+ 'variants',
296
+ 'compare',
297
+ 'help',
298
+ ];
299
+ const OPTIONS = [
300
+ 'table',
301
+ 'export',
302
+ 'strike',
303
+ 'calibrate',
304
+ 'check',
305
+ 'turns',
306
+ 'preview',
307
+ 'gap',
308
+ 'no-steps',
309
+ 'all',
310
+ 'along',
311
+ 'at',
312
+ 'bump',
313
+ 'depth',
314
+ 'dry-run',
315
+ 'explode',
316
+ 'force',
317
+ 'fresh',
318
+ 'json',
319
+ 'licence',
320
+ 'license',
321
+ 'long',
322
+ 'm',
323
+ 'material',
324
+ 'md',
325
+ 'name',
326
+ 'new',
327
+ 'no-models',
328
+ 'no-pictures',
329
+ 'no-rules',
330
+ 'note',
331
+ 'open',
332
+ 'part',
333
+ 'place',
334
+ 'pose',
335
+ 'profile',
336
+ 'progress',
337
+ 'push',
338
+ 'result',
339
+ 'rules',
340
+ 'samples',
341
+ 'set',
342
+ 'short',
343
+ 'source',
344
+ 'steps',
345
+ 'sweep',
346
+ 'tol',
347
+ 'trailer',
348
+ 'ttl',
349
+ 'version',
350
+ 'watch',
351
+ 'allow-host',
352
+ 'line',
353
+ 'unit',
354
+ 'rule',
355
+ 'label',
356
+ 'from',
357
+ 'out',
358
+ 'jigs',
359
+ 'no-jigs',
360
+ 'expand',
361
+ 'size',
362
+ 'write',
363
+ 'pictures',
364
+ 'cycles',
365
+ 'period', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit, cad plot
366
+ 'a',
367
+ 'b',
368
+ 'min',
369
+ 'max',
370
+ 'poses',
371
+ 'id',
372
+ 'type',
373
+ 'parent',
374
+ 'child',
375
+ 'follow',
376
+ 'value',
377
+ 'ratio',
378
+ 'object',
379
+ 'assembly',
380
+ 'variant',
381
+ 'rotate',
382
+ 'to',
383
+ 'roll', // cad add
384
+ 'screw',
385
+ 'through',
386
+ 'into',
387
+ 'holes',
388
+ 'nut',
389
+ 'washer',
390
+ 'length',
391
+ 'torque',
392
+ 'from-fits', // cad add fasten
393
+ 'kind',
394
+ 'fitting', // cad add join
395
+ 'title',
396
+ 'description',
397
+ 'printer',
398
+ 'frame',
399
+ 'inside',
400
+ 'outside',
401
+ 'join',
402
+ 'estimate',
403
+ 'feet',
404
+ 'caps',
405
+ 'with-refs',
406
+ 'mass',
407
+ 'joint',
408
+ ]; // cad new, cad remove, cad add load
178
409
  // The commands that take --dry-run (each checks its edit and writes nothing); any other is refused with it, as a flag
179
410
  // it passed over would let the command write
180
- const takesDryRun = (cmd) => ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) || (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
181
- const DRY_RUNS = 'the commands that take one are cad new, set, add, remove, move, release, frame --expand and frame --size --write';
411
+ const takesDryRun = (cmd) =>
412
+ ['new', 'set', 'add', 'remove', 'move', 'release'].includes(cmd) ||
413
+ (cmd === 'rules' && positional()[1] === 'update') ||
414
+ (cmd === 'frame' && (opt('expand') || (opt('size') && opt('write'))));
415
+ const DRY_RUNS =
416
+ 'the commands that take one are cad new, set, add, remove, move, release, rules update, frame --expand and frame --size --write';
182
417
  // What a command takes, where that isn't <project>/<object>
183
- const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …, <project>/<assembly> <address>=<value> …, or <project> field=value …',
184
- remove: '<project>/<assembly> <id | list.n | id.field> [--with-refs] [--dry-run]', move: '<project>/<assembly> <id> --at x,y,z | --to <address> [--rotate x,y,z] [--dry-run]',
185
- optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
186
- diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
418
+ const USAGE = {
419
+ add: 'fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
420
+ why: '<project>/<object>.<variable>',
421
+ set: '<project>/<object> name=value …, <project>/<assembly> <address>=<value> …, or <project> field=value …',
422
+ remove: '<project>/<assembly> <id | list.n | id.field> [--with-refs] [--dry-run]',
423
+ move: '<project>/<assembly> <id> --at x,y,z | --to <address> [--rotate x,y,z] [--dry-run]',
424
+ optimise: '<project>/<problem>',
425
+ optimize: '<project>/<problem>',
426
+ history: '<project>[/<object>]',
427
+ release: '<project>[/<object>] -m "what changed"',
428
+ diff: '<project>/<object> <from> [<to>]',
429
+ compare: '<project>/<object> <a> <b>',
430
+ match: '<project>/<object> <model.stl|model.3mf>',
431
+ clone: '<board.kicad_pcb | GitHub link> <name>',
432
+ };
187
433
 
188
434
  const args = process.argv.slice(2);
189
435
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
190
436
  // (--sweep, --watch and --nut take one or not).
191
- const FLAGS = ['with-refs', 'table', 'calibrate', 'check', 'preview', 'no-steps', 'all', 'dry-run', 'explode', 'force', 'fresh', 'json', 'long', 'md', 'new', 'no-models', 'no-pictures', 'no-rules', 'open', 'progress', 'push', 'short', 'washer', 'from-fits', 'jigs', 'no-jigs', 'pictures', 'expand', 'size', 'write'];
437
+ const FLAGS = [
438
+ 'with-refs',
439
+ 'table',
440
+ 'export',
441
+ 'calibrate',
442
+ 'check',
443
+ 'preview',
444
+ 'no-steps',
445
+ 'all',
446
+ 'dry-run',
447
+ 'explode',
448
+ 'force',
449
+ 'fresh',
450
+ 'json',
451
+ 'long',
452
+ 'md',
453
+ 'new',
454
+ 'no-models',
455
+ 'no-pictures',
456
+ 'no-rules',
457
+ 'open',
458
+ 'progress',
459
+ 'push',
460
+ 'short',
461
+ 'washer',
462
+ 'from-fits',
463
+ 'jigs',
464
+ 'no-jigs',
465
+ 'pictures',
466
+ 'expand',
467
+ 'size',
468
+ 'write',
469
+ 'estimate',
470
+ ];
192
471
  // The options whose value may be left out; a field=value after one is a field to set, not its value (cad new
193
472
  // frame/box --assembly title=Box)
194
473
  const OPTIONAL = ['sweep', 'watch', 'nut', 'assembly'];
@@ -196,75 +475,167 @@ const opt = (k) => {
196
475
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
197
476
  if (i < 0) return undefined;
198
477
  if (FLAGS.includes(k)) return true;
199
- if (args[i + 1] && !args[i + 1].startsWith('--') && !(OPTIONAL.includes(k) && args[i + 1].includes('='))) return args[i + 1];
478
+ if (args[i + 1] && !args[i + 1].startsWith('--') && !(OPTIONAL.includes(k) && args[i + 1].includes('=')))
479
+ return args[i + 1];
200
480
  if (OPTIONAL.includes(k)) return true;
201
481
  throw new Error(`${args[i]} needs a value after it`);
202
482
  };
203
483
  // The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
204
- const takesValue = (a, next) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)) && !(OPTIONAL.includes(a.slice(2)) && String(next).includes('=')));
205
- const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1], a)));
484
+ const takesValue = (a, next) =>
485
+ a === '-m' ||
486
+ (a.startsWith('--') && !FLAGS.includes(a.slice(2)) && !(OPTIONAL.includes(a.slice(2)) && String(next).includes('=')));
487
+ const positional = () =>
488
+ args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1], a)));
489
+ // --allow-host name[,name …], as often as wanted: the names a live view (--watch) answers to beside this computer's own
490
+ // (lib/live-guard.mjs), such as a Tailscale name. A name only: a scheme, a path or a port is refused, as a typo.
491
+ const allowedHosts = () => {
492
+ const names = args
493
+ .flatMap((a, i) => (a === '--allow-host' ? [args[i + 1]] : []))
494
+ .flatMap((v) => (v === undefined || v.startsWith('--') ? [undefined] : v.split(',').map((n) => n.trim())));
495
+ if (names.length && !opt('watch'))
496
+ throw new Error('--allow-host goes with --watch: it names the live view by another name, so watch the run too');
497
+ for (const n of names)
498
+ if (!n || !/^[\w.-]+$/.test(n))
499
+ throw new Error(
500
+ `--allow-host takes a computer's name, such as my-laptop or my-laptop.tail0000.ts.net (got "${n ?? ''}")`,
501
+ );
502
+ return names;
503
+ };
206
504
  // --set name=value,name=value (a value may hold an = of its own)
207
- const sets = () => Object.fromEntries(String(opt('set') || '').split(',').filter(Boolean).map((p) => { const i = p.indexOf('='); return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()]; }));
208
- const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('').replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
505
+ const sets = () =>
506
+ Object.fromEntries(
507
+ String(opt('set') || '')
508
+ .split(',')
509
+ .filter(Boolean)
510
+ .map((p) => {
511
+ const i = p.indexOf('=');
512
+ return i < 0 ? [p.trim(), undefined] : [p.slice(0, i).trim(), p.slice(i + 1).trim()];
513
+ }),
514
+ );
515
+ const suffix = (set) =>
516
+ Object.entries(set)
517
+ .map(([k, v]) => `-${k}=${v}`)
518
+ .join('')
519
+ .replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
209
520
 
210
521
  // --progress: what a long build or sweep is doing, on one line of stderr
211
522
  const showProgress = (e) => {
212
523
  if (!opt('progress')) return;
213
- process.stderr.write(`\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`);
524
+ process.stderr.write(
525
+ `\r\x1b[K${e.stage === 'sweep' ? `sweeping ${e.joint} ${e.step}/${e.steps}` : `building ${e.item} (${e.done})`}`,
526
+ );
214
527
  };
215
528
  // Findings: as text (a mark and the words), or with --json as data: { ...about, findings: [{ level, text, code, values, refs, at }] }
216
529
  // Every measurement says why it is what it is, and every object its name: a variable with a value and no rule (or an
217
530
  // object with no name) is a warning, not a failure, so an older design still builds
218
531
  function unruled(object, file) {
219
- const out = [], none = Object.entries(object.variables || {}).filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule).map(([n]) => n);
220
- if (none.length) out.push({ level: 'warn', text: `${none.length === 1 ? 'a variable has' : `${none.length} variables have`} no rule saying why ${none.length === 1 ? 'it is' : 'they are'} what ${none.length === 1 ? 'it is' : 'they are'}: ${none.slice(0, 6).join(', ')}${none.length > 6 ? ', …' : ''}`, code: 'var.no-rule', refs: { file, variables: none } });
221
- if (!object.name) out.push({ level: 'warn', text: 'the object has no "name": give it the file\'s name, so links and releases say what it is', code: 'object.no-name', refs: { file } });
532
+ const out = [],
533
+ none = Object.entries(object.variables || {})
534
+ .filter(([, v]) => v && v.value !== undefined && !v.type && !v.rule)
535
+ .map(([n]) => n);
536
+ if (none.length)
537
+ out.push({
538
+ level: 'warn',
539
+ text: `${none.length === 1 ? 'a variable has' : `${none.length} variables have`} no rule saying why ${none.length === 1 ? 'it is' : 'they are'} what ${none.length === 1 ? 'it is' : 'they are'}: ${none.slice(0, 6).join(', ')}${none.length > 6 ? ', …' : ''}`,
540
+ code: 'var.no-rule',
541
+ refs: { file, variables: none },
542
+ });
543
+ if (!object.name)
544
+ out.push({
545
+ level: 'warn',
546
+ text: 'the object has no "name": give it the file\'s name, so links and releases say what it is',
547
+ code: 'object.no-name',
548
+ refs: { file },
549
+ });
222
550
  return out;
223
551
  }
224
552
 
225
553
  function report(findings, about = {}) {
226
554
  if (opt('json')) console.log(JSON.stringify({ ...about, findings }, null, 2));
227
- else { const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' }; for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`); }
555
+ else {
556
+ const mark = { pass: '✓', warn: '!', fail: '✗', info: '·' };
557
+ for (const r of findings) console.log(` ${mark[r.level]} ${r.text}`);
558
+ }
228
559
  return findings.some((r) => r.level === 'fail');
229
560
  }
230
- const say = (...a) => { if (!opt('json')) console.log(...a); }; // text output that --json leaves out
561
+ const say = (...a) => {
562
+ if (!opt('json')) console.log(...a);
563
+ }; // text output that --json leaves out
231
564
 
232
565
  const sig = (n) => (Number.isFinite(n) ? String(Number(n.toPrecision(3))) : String(n)); // three significant figures
233
566
  // A case's stiffness, and in words: a twist turns (degrees under N·m, N·m a degree), anything else moves along its load
234
567
  const stiffOf = (c) => (c.moment ? c.torsion : c.stiffness);
235
- const howFar = (c) => (c.moment ? `turns ${sig(c.angle * 180 / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(c.torsion / 1000 * Math.PI / 180)} N·m a degree` : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`);
568
+ const howFar = (c) =>
569
+ c.moment
570
+ ? `turns ${sig((c.angle * 180) / Math.PI)}° under ${sig(c.moment / 1000)} N·m, ${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m a degree`
571
+ : `moves ${sig(c.deflection)} mm along its load, ${sig(c.stiffness)} N/mm`;
236
572
  // cad optimise: run a problem (with a progress line), then report it and draw it: a 2D layout as an SVG of its
237
573
  // densities, a 3D one as the preview's views of its surface
238
574
  async function optimiseProblem(ref, { preview: previewing = false } = {}) {
239
575
  const [project, name] = String(ref).split('/');
240
576
  if (!project || !name) throw new Error('usage: cad optimise <project>/<problem>[:variant]');
577
+ const allowHosts = allowedHosts();
241
578
  const file = problemFile(project, name.split(':')[0]);
242
579
  if (fs.existsSync(file)) {
243
- const bad = schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'problem', path.relative(WS, file));
244
- if (bad.length) { report(bad); process.exitCode = 1; return; }
580
+ const bad = schemaFindings(readJson(file), 'problem', path.relative(WS, file));
581
+ if (bad.length) {
582
+ report(bad);
583
+ process.exitCode = 1;
584
+ return;
585
+ }
245
586
  }
246
587
  const live = !opt('json') && process.stderr.isTTY;
247
588
  // --watch [port]: the live view, served while it runs (a watched run is always run afresh, so there is something to watch)
248
589
  const watch = opt('watch');
249
- if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536)) throw new Error(`--watch takes a port number (got "${watch}")`);
250
- const view = watch ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}` }) : null;
590
+ if (watch && watch !== true && !(Number(watch) > 0 && Number(watch) < 65536))
591
+ throw new Error(`--watch takes a port number (got "${watch}")`);
592
+ const view = watch
593
+ ? await liveView({ port: watch === true ? 8090 : Number(watch), title: `cad optimise ${ref}`, allowHosts })
594
+ : null;
251
595
  if (view) say(`watching at ${view.url}`);
252
596
  let r;
253
597
  const rec = recorder(); // each step kept, so the run can be watched again (cad preview <project>/problems/<name>)
254
598
  try {
255
- r = await optimised(project, name, { fresh: !!opt('fresh') || !!view, onStep: (s) => {
256
- rec.step(s);
257
- if (live) process.stderr.write(`\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`);
258
- if (view) { view.step(s); if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`); }
259
- } });
260
- } catch (e) { await view?.close(e.message); throw e; } finally { if (live) process.stderr.write('\r\x1b[K'); }
599
+ ownResults();
600
+ r = await optimised(project, name, {
601
+ fresh: !!opt('fresh') || !!view,
602
+ onStep: (s) => {
603
+ rec.step(s);
604
+ if (live)
605
+ process.stderr.write(
606
+ `\r\x1b[Kstep ${s.step}/${s.steps} compliance ${s.compliance.toPrecision(5)} N·mm change ${s.change.toFixed(3)} sharpness ${s.beta}`,
607
+ );
608
+ if (view) {
609
+ view.step(s);
610
+ if (view.stopped()) throw new Error(`stopped from the live view at step ${s.step}`);
611
+ }
612
+ },
613
+ });
614
+ } catch (e) {
615
+ await view?.close(e.message);
616
+ throw e;
617
+ } finally {
618
+ if (live) process.stderr.write('\r\x1b[K');
619
+ }
261
620
  // The page keeps showing the end for ten minutes (the process waits for it), so a finished run isn't a dead link
262
- if (view) { view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 }); say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`); }
263
- const p = await readProblem(project, name), cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
264
- const lines = [`${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => c.moment ? `${c.name} ${sig(c.angle * 180 / Math.PI)}° (${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`).join(', ')}`,
621
+ if (view) {
622
+ view.close(`finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, { hold: 10 * 60e3 });
623
+ say(`the live view shows the result for ten more minutes (Ctrl-C to stop it)`);
624
+ }
625
+ const p = await readProblem(project, name),
626
+ cells = r.dim === 3 ? `${r.grid.nx} × ${r.grid.ny} × ${r.grid.nz}` : `${r.grid.nx} × ${r.grid.ny}`;
627
+ const lines = [
628
+ `${p.material.name}${r.dim === 2 ? `, ${fmt(r.thickness)} mm thick` : ''}: ${r.cases.map((c) => (c.moment ? `${c.name} ${sig((c.angle * 180) / Math.PI)}° (${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m/°)` : `${c.name} ${sig(c.deflection)} mm (${sig(c.stiffness)} N/mm)`)).join(', ')}`,
265
629
  `${fmt(r.volume * 100)}% of the space, ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? '' : ' (stopped: not settled)'}${r.overhang ? `, printable built ${r.overhang}` : ''}${r.stress ? `, peak stress ${sig(r.stress.peak)} MPa (limit ${sig(r.stress.limit)})` : ''}${r.dropped ? `; ${r.dropped.length} loose ${r.dropped.length === 1 ? 'piece' : 'pieces'} dropped (${sig(r.dropped.reduce((t, v) => t + v, 0))} mm³)` : ''}${r.emptied ? `; ${r.emptied} ${r.emptied === 1 ? 'cell' : 'cells'} that wouldn't print emptied` : ''}${r.cleared ? `; sliced as the printer will, ${r.cleared} ${r.cleared === 1 ? 'cell' : 'cells'} under islands emptied` : ''}`,
266
- ...(r.unsupported > 0.01 ? [`${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? 'the printer\'s overhang limit' : '45°'} or less): give the part more material to stand them on, or keep less`] : []),
267
- ...(r.process ? [processLine(r)] : []), ...(r.feature ? [featureLine(r)] : []), ...(r.voids?.length ? [voidsLine(r)] : [])];
630
+ ...(r.unsupported > 0.01
631
+ ? [
632
+ `${fmt(r.unsupported * 100)}% of the kept regions has nothing holding it up (at ${r.overhang ? "the printer's overhang limit" : '45°'} or less): give the part more material to stand them on, or keep less`,
633
+ ]
634
+ : []),
635
+ ...(r.process ? [processLine(r)] : []),
636
+ ...(r.feature ? [featureLine(r)] : []),
637
+ ...(r.voids?.length ? [voidsLine(r)] : []),
638
+ ];
268
639
  let out;
269
640
  if (r.dim === 3) {
270
641
  out = paths.preview(project, `${name.replace(':', '-')}-optimised.png`);
@@ -276,46 +647,112 @@ async function optimiseProblem(ref, { preview: previewing = false } = {}) {
276
647
  fs.writeFileSync(out, picture(r, { title: r.title, lines }));
277
648
  }
278
649
  // The run, to watch again: kept by the densities' key when it was recorded here, else its end alone
279
- const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`, kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
280
- if (rec.steps()) { fs.mkdirSync(path.dirname(kept), { recursive: true }); fs.writeFileSync(kept, rec.page(`cad optimise ${ref}`, done)); }
281
- const run = paths.preview(project, `${name.replace(':', '-')}-run.html`), recorded = fs.existsSync(kept);
650
+ const done = `finished: ${r.steps} steps${r.converged ? '' : ', not settled'}`,
651
+ kept = paths.cache('runs', `${densitiesKey(p.problem)}.html`);
652
+ if (rec.steps()) writeCacheFile(kept, rec.page(`cad optimise ${ref}`, done));
653
+ const run = paths.preview(project, `${name.replace(':', '-')}-run.html`),
654
+ recorded = cached(kept);
282
655
  fs.mkdirSync(path.dirname(run), { recursive: true });
283
- fs.writeFileSync(run, recorded ? fs.readFileSync(kept, 'utf8') : endOnly(`cad optimise ${ref}`, r, `${done} (its steps weren't recorded: run it again with --fresh to watch them)`));
656
+ fs.writeFileSync(
657
+ run,
658
+ recorded
659
+ ? fs.readFileSync(kept, 'utf8')
660
+ : endOnly(
661
+ `cad optimise ${ref}`,
662
+ r,
663
+ `${done} (its steps weren't recorded: run it again with --fresh to watch them)`,
664
+ ),
665
+ );
284
666
  if (opt('json')) return console.log(JSON.stringify((({ density, history, mesh, ...x }) => x)(r), null, 2));
285
667
  console.log(`${r.title}${r.cached ? ' (cached)' : ` (${fmt(r.seconds)} s)`}`);
286
668
  for (const c of r.cases) console.log(` ${c.name}: ${howFar(c)}`);
287
- if (r.mechanism) console.log(` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`);
288
- if (r.stress && r.mechanism) console.log(` peak stress ${sig(r.stress.peak)} MPa at its input force${r.stress.strain != null ? ` (strain ${sig(r.stress.strain * 100)}%)` : ''}, the limit ${sig(r.stress.limit)} MPa${r.stress.strainLimit != null ? ` (${sig(r.stress.strainLimit * 100)}%)` : ''}: it reaches the limit at ${sig(r.stress.force)} N of push, its output then ${sig(r.stress.travel)} mm along`);
289
- else if (r.stress) console.log(` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`);
290
- if (r.stress?.copies) console.log(` made a little thin, peak stress ${sig(r.stress.copies.eroded)} MPa; a little thick, ${sig(r.stress.copies.dilated)} MPa${Math.max(r.stress.copies.eroded, r.stress.copies.dilated) > r.stress.limit * 1.02 ? ` (over the limit: ${p.problem?.robust ? 'a smaller cell or a looser limit' : 'give the problem robust: true'})` : ''}`);
291
- if (r.mechanism?.copies) console.log(` made a little thin, its output moves ${sig(r.mechanism.copies.eroded)} mm; a little thick, ${sig(r.mechanism.copies.dilated)} mm`);
292
- if (r.dim === 3) console.log(` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt(r.solid / 1000 * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`);
293
- else console.log(` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt(r.area * r.thickness / 1000)} cm³ before bosses and holes are made exact)`);
294
- if (r.reduced) console.log(` ${r.reduced.before} triangles reduced to ${r.reduced.after} (${fmt(r.reduced.after / r.reduced.before * 100)}%), the surface kept within ${fmt(r.reduced.tolerance)} mm`);
295
- console.log(` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`);
669
+ if (r.mechanism)
670
+ console.log(
671
+ ` the output moves ${sig(r.mechanism.travel)} mm its way for ${sig(r.mechanism.input)} mm of push: an advantage of ${sig(r.mechanism.advantage)}`,
672
+ );
673
+ if (r.stress && r.mechanism)
674
+ console.log(
675
+ ` peak stress ${sig(r.stress.peak)} MPa at its input force${r.stress.strain != null ? ` (strain ${sig(r.stress.strain * 100)}%)` : ''}, the limit ${sig(r.stress.limit)} MPa${r.stress.strainLimit != null ? ` (${sig(r.stress.strainLimit * 100)}%)` : ''}: it reaches the limit at ${sig(r.stress.force)} N of push, its output then ${sig(r.stress.travel)} mm along`,
676
+ );
677
+ else if (r.stress)
678
+ console.log(
679
+ ` peak stress ${sig(r.stress.peak)} MPa, the limit ${sig(r.stress.limit)} MPa${r.stress.peak > r.stress.limit * 1.02 ? ': over it (raise the volume, ease the limit, or use a smaller cell)' : ''}`,
680
+ );
681
+ if (r.stress?.copies)
682
+ console.log(
683
+ ` made a little thin, peak stress ${sig(r.stress.copies.eroded)} MPa; a little thick, ${sig(r.stress.copies.dilated)} MPa${Math.max(r.stress.copies.eroded, r.stress.copies.dilated) > r.stress.limit * 1.02 ? ` (over the limit: ${p.problem?.robust ? 'a smaller cell or a looser limit' : 'give the problem robust: true'})` : ''}`,
684
+ );
685
+ if (r.mechanism?.copies)
686
+ console.log(
687
+ ` made a little thin, its output moves ${sig(r.mechanism.copies.eroded)} mm; a little thick, ${sig(r.mechanism.copies.dilated)} mm`,
688
+ );
689
+ if (r.dim === 3)
690
+ console.log(
691
+ ` ${fmt(r.volume * 100)}% of the space filled: ${fmt(r.solid / 1000)} cm³ (${fmt((r.solid / 1000) * (p.material.density || 0))} g of ${p.material.name})${r.overhang ? `, printable built ${r.overhang}` : ''}`,
692
+ );
693
+ else
694
+ console.log(
695
+ ` ${fmt(r.volume * 100)}% of the space filled, outline ${fmt(r.area)} mm² (${fmt((r.area * r.thickness) / 1000)} cm³ before bosses and holes are made exact)`,
696
+ );
697
+ if (r.reduced)
698
+ console.log(
699
+ ` ${r.reduced.before} triangles reduced to ${r.reduced.after} (${fmt((r.reduced.after / r.reduced.before) * 100)}%), the surface kept within ${fmt(r.reduced.tolerance)} mm`,
700
+ );
701
+ console.log(
702
+ ` ${cells} cells of ${fmt(r.grid.h)} mm, ${r.steps} steps${r.converged ? ', settled' : ': stopped before it settled (raise steps)'}`,
703
+ );
296
704
  if (r.process) console.log(` ${processLine(r)}`);
297
- if (r.symmetry || r.extrude) console.log(` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`);
705
+ if (r.symmetry || r.extrude)
706
+ console.log(
707
+ ` ${[r.symmetry?.mirror ? `mirrored across ${[...r.symmetry.mirror].join(' and ')}` : '', r.symmetry?.turns ? `the same each ${r.symmetry.turns === 4 ? 'quarter' : 'half'} turn about ${r.symmetry.axis || 'z'}` : '', r.extrude ? `one section along ${r.extrude}` : ''].filter(Boolean).join(', ')}`,
708
+ );
298
709
  if (r.feature) console.log(` ${r.feature.thin ? 'warning: ' : ''}${featureLine(r)}`);
299
710
  if (r.grey > 0.1) console.log(` warning: ${greyLine(r)}`);
300
- if (r.voids?.length) { console.log(` error: ${voidsLine(r)}`); process.exitCode = 1; } else if (r.vented) console.log(' voids prevented: none enclosed, every empty pocket open to the outside');
711
+ if (r.voids?.length) {
712
+ console.log(` error: ${voidsLine(r)}`);
713
+ process.exitCode = 1;
714
+ } else if (r.vented) console.log(' voids prevented: none enclosed, every empty pocket open to the outside');
301
715
  console.log(out);
302
- if (previewing) console.log(`${run}\n ${recorded ? `the run, step by step: open it to watch it again (${r.steps} steps)` : 'the run\'s end only: its steps weren\'t recorded (cad preview --fresh runs it again and records them)'}`);
716
+ if (previewing)
717
+ console.log(
718
+ `${run}\n ${recorded ? `the run, step by step: open it to watch it again (${r.steps} steps)` : "the run's end only: its steps weren't recorded (cad preview --fresh runs it again and records them)"}`,
719
+ );
303
720
  }
304
721
  // How a milled or cast result is made, and its undercuts (none, unless an avoid region or the space's own shape sits
305
722
  // behind material: the optimiser keeps every cell as solid as those on its way out, but can't fill a cell it mustn't)
306
723
  function processLine(r) {
307
- const p = r.process, sides = [p.mill].flat(), tool = p.tool ? ` by a tool of ${fmt(p.tool)} mm radius` : '';
724
+ const p = r.process,
725
+ sides = [p.mill].flat(),
726
+ tool = p.tool ? ` by a tool of ${fmt(p.tool)} mm radius` : '';
308
727
  const draft = p.draft ? ` with a ${fmt(p.draft)}° draft (a step out every ${p.every} layers: ${fmt(p.made)}°)` : '';
309
- const how = p.mill ? `milled from ${sides.length > 1 ? `${sides.slice(0, -1).join(', ')} and ${sides.at(-1)}` : sides[0]}${tool}` : typeof p.cast === 'string' ? `cast, drawn off ${p.cast}${draft}` : `cast in two halves drawn off along ${p.cast.draw} from ${fmt(p.cast.parting)} mm${draft}`;
310
- const n = r.narrow, narrow = !n ? '' : [n.design ? `${n.design} ${n.design === 1 ? 'cell' : 'cells'} of the design too narrow for the tool` : '', n.avoided ? `${n.avoided} ${n.avoided === 1 ? 'cell' : 'cells'} of avoid regions narrower than the tool: drill those holes, or give a smaller tool` : ''].filter(Boolean).join('; ');
728
+ const how = p.mill
729
+ ? `milled from ${sides.length > 1 ? `${sides.slice(0, -1).join(', ')} and ${sides.at(-1)}` : sides[0]}${tool}`
730
+ : typeof p.cast === 'string'
731
+ ? `cast, drawn off ${p.cast}${draft}`
732
+ : `cast in two halves drawn off along ${p.cast.draw} from ${fmt(p.cast.parting)} mm${draft}`;
733
+ const n = r.narrow,
734
+ narrow = !n
735
+ ? ''
736
+ : [
737
+ n.design ? `${n.design} ${n.design === 1 ? 'cell' : 'cells'} of the design too narrow for the tool` : '',
738
+ n.avoided
739
+ ? `${n.avoided} ${n.avoided === 1 ? 'cell' : 'cells'} of avoid regions narrower than the tool: drill those holes, or give a smaller tool`
740
+ : '',
741
+ ]
742
+ .filter(Boolean)
743
+ .join('; ');
311
744
  const tail = narrow ? `; ${narrow}` : n ? ', and nothing narrower than the tool' : '';
312
- return r.undercuts ? `${how}: ${r.undercuts} ${r.undercuts === 1 ? 'cell is' : 'cells are'} undercut (an avoid region, or the edge of the space, with material between it and the ${p.mill ? 'tool' : 'draw'}: move it, or make it from that side)${tail}` : `${how}: no undercuts${tail}`;
745
+ return r.undercuts
746
+ ? `${how}: ${r.undercuts} ${r.undercuts === 1 ? 'cell is' : 'cells are'} undercut (an avoid region, or the edge of the space, with material between it and the ${p.mill ? 'tool' : 'draw'}: move it, or make it from that side)${tail}`
747
+ : `${how}: no undercuts${tail}`;
313
748
  }
314
749
  // The thinnest member asked (a printer's two lines): met by the grid itself, or held to three cells, with any cells left
315
750
  // in members narrower
316
751
  function featureLine(r) {
317
- const f = r.feature, h = f.holds / (2 * f.cells + 1);
318
- if (!f.cells) return `thinnest member ${fmt(f.asked)} mm: every member is at least a cell (${fmt(h)} mm), so the grid holds it`;
752
+ const f = r.feature,
753
+ h = f.holds / (2 * f.cells + 1);
754
+ if (!f.cells)
755
+ return `thinnest member ${fmt(f.asked)} mm: every member is at least a cell (${fmt(h)} mm), so the grid holds it`;
319
756
  return `thinnest member ${fmt(f.asked)} mm: held to three cells (${fmt(f.holds)} mm)${f.thin ? `, and ${f.thin} solid ${f.thin === 1 ? 'cell is' : 'cells are'} still in a narrower member or a square outside corner: give a bigger filter radius` : ', none narrower'}`;
320
757
  }
321
758
  // A grey result (warned of above a tenth): its design cells between a tenth and nine tenths solid. A clear design has
@@ -331,217 +768,586 @@ function voidsLine(r) {
331
768
 
332
769
  // An object's analyses for cad check: each problem's load cases on the part, and its volume against a target
333
770
  function place(triangles, [rx, ry, rz], move) {
334
- const [cx, sx, cy, sy, cz, sz] = [rx, ry, rz].flatMap((deg) => [Math.cos((deg * Math.PI) / 180), Math.sin((deg * Math.PI) / 180)]);
335
- return triangles.map((t) => t.map((p) => {
336
- let [x, y, z = 0] = p;
337
- [y, z] = [y * cx - z * sx, y * sx + z * cx];
338
- [x, z] = [x * cy + z * sy, -x * sy + z * cy];
339
- [x, y] = [x * cz - y * sz, x * sz + y * cz];
340
- return [x + move[0], y + move[1], z + (move[2] || 0)].slice(0, p.length);
341
- }));
771
+ const [cx, sx, cy, sy, cz, sz] = [rx, ry, rz].flatMap((deg) => [
772
+ Math.cos((deg * Math.PI) / 180),
773
+ Math.sin((deg * Math.PI) / 180),
774
+ ]);
775
+ return triangles.map((t) =>
776
+ t.map((p) => {
777
+ let [x, y, z = 0] = p;
778
+ [y, z] = [y * cx - z * sx, y * sx + z * cx];
779
+ [x, z] = [x * cy + z * sy, -x * sy + z * cy];
780
+ [x, y] = [x * cz - y * sz, x * sz + y * cz];
781
+ return [x + move[0], y + move[1], z + (move[2] || 0)].slice(0, p.length);
782
+ }),
783
+ );
342
784
  }
343
785
 
344
786
  // A part's analysis report, in Markdown: what was analysed, how, each load case's numbers and where, and what it
345
787
  // doesn't cover
346
- function reportText({ turn, object, title, version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }) {
788
+ function reportText({
789
+ turn,
790
+ object,
791
+ title,
792
+ version,
793
+ a,
794
+ r,
795
+ m,
796
+ strength,
797
+ weaker,
798
+ grid,
799
+ limit,
800
+ minSafety,
801
+ records,
802
+ found,
803
+ }) {
347
804
  const at = (p) => `(${p.map(fmt).join(', ')})`;
348
805
  const pct = (x) => `${x >= 0 ? '+' : ''}${fmt(x * 100)}%`;
349
- const rows = r.cases.map((c) => `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig(c.angle * 180 / Math.PI)}° | ${sig(c.torsion / 1000 * Math.PI / 180)} N·m/°` : `${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}`}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`);
806
+ const rows = r.cases.map(
807
+ (c) =>
808
+ `| ${c.name} | ${c.moment ? `${sig(c.moment / 1000)} N·m | ${sig((c.angle * 180) / Math.PI)}° | ${sig(((c.torsion / 1000) * Math.PI) / 180)} N·m/°` : `${fmt(c.force)} | ${sig(c.deflection)} | ${sig(c.stiffness)}`}${c.change ? ` (${pct(c.change.stiffness)})` : ''} | ${sig(c.stress)}${c.change ? ` (${pct(c.change.stress)})` : ''} at ${at(c.stressAt)} | ${strength ? `${sig(strength / c.stress)}×` : '–'}${m.fatigue ? ` (fatigue ${sig(m.fatigue / c.stress)}×)` : ''} | ${sig(c.movement)} at ${at(c.movementAt)} |`,
809
+ );
350
810
  return [
351
- `# ${title}: analysed under ${a.problem}`, '',
352
- `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled; peak stress at a sharp inside corner keeps rising as cells shrink, so read it with its change.` : ' On the problem\'s own cells: a quick check. Give the analysis a smaller cell to verify it.'}`, '',
811
+ `# ${title}: analysed under ${a.problem}`,
812
+ '',
813
+ `${object} ${version || ''}. Analysed on ${grid}, ${m.name} (modulus ${fmt(m.modulus)} MPa${strength ? `, strength ${fmt(strength)} MPa${weaker ? ' across its layers' : ''}` : ''}${m.fatigue ? `, fatigue strength ${fmt(m.fatigue)} MPa` : ''}). Positions are in mm, in the problem's frame${turn ? ' (the part turned back from how it prints)' : ''}.${r.cases[0]?.change ? ` In brackets: the change from ${fmt(r.cases[0].change.cell)} mm cells. Stiffness that changes by 5% or less has settled${minSafety != null ? ', and with a least safety factor asked, the peak stress must too' : ''}; peak stress at a sharp inside corner, or beside a support or load held at a few points, keeps rising as cells shrink, so read it with its change.` : " On the problem's own cells: a quick check. Give the analysis a smaller cell to verify it."}`,
814
+ '',
353
815
  '| Load case | Force (N) | Moves its load (mm) | Stiffness (N/mm) | Peak stress (MPa) | Safety factor | Largest movement (mm) |',
354
- '|---|---|---|---|---|---|---|', ...rows, '',
355
- `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`, '',
356
- '## Findings', '', ...found.map((f) => `- ${f.level}: ${f.text}`), '',
357
- '## Verification', '',
358
- ...(records.length ? records.map((v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`) : [r.critical ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.' : 'None recorded.']), '',
359
- '## What this doesn\'t cover', '',
816
+ '|---|---|---|---|---|---|---|',
817
+ ...rows,
818
+ '',
819
+ `Volume ${fmt(r.volume)} mm³.${limit != null ? ` Limit on movement: ${fmt(limit)} mm.` : ''}${minSafety != null ? ` Least safety factor: ${fmt(minSafety)}×.` : ''}`,
820
+ '',
821
+ '## Findings',
822
+ '',
823
+ ...found.map((f) => `- ${f.level}: ${f.text}`),
824
+ '',
825
+ '## Verification',
826
+ '',
827
+ ...(records.length
828
+ ? records.map(
829
+ (v) => `- ${v.kind}, ${v.date}${v.by ? `, by ${v.by}` : ''}: ${v.summary}${v.source ? ` (${v.source})` : ''}`,
830
+ )
831
+ : [
832
+ r.critical
833
+ ? '**Unverified.** This part is safety-critical: do not rely on it until a test or an independent analysis is recorded.'
834
+ : 'None recorded.',
835
+ ]),
836
+ '',
837
+ "## What this doesn't cover",
838
+ '',
360
839
  '- The analysis is linear and static, on cubes: a design aid, not engineering sign-off. Stress at sharp inside corners, and where supports and loads are applied, depends on the cell size; compare a finer cell before trusting a peak.',
361
840
  '- Material values are data-sheet figures. Printed parts vary with the printer, settings and spool, and are weaker across their layers; measure your own.',
362
- '- Buckling, impact, creep, heat and wear are not checked.', '',
841
+ '- Buckling, impact, creep, heat and wear are not checked.',
842
+ '',
363
843
  ].join('\n');
364
844
  }
365
845
 
366
846
  async function analyses(b, d, tag) {
367
- const lookup = (n) => { const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values); if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`); return v; };
847
+ const lookup = (n) => {
848
+ const v = n.split('.').reduce((o, k) => (o == null ? o : o[k]), b.values);
849
+ if (typeof v !== 'number') throw new Error(`analysis: "${n}" isn't a number`);
850
+ return v;
851
+ };
368
852
  const all = [];
369
- for (const a of b.object.analysis || []) all.push(...await (async () => {
370
- const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
371
- if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
372
- // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
373
- // then z, as JSCAD's rotate), then moved
374
- const turn = (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) || (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
375
- const turned = turn ? place(part.triangles, (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)), (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup))) : part.triangles;
376
- const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
377
- const r = await analysePart(turned, d.project, a.problem, { cell }), m = r.material;
378
- // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
379
- // number changes says whether the cells are small enough. Peak stress at a sharp inside corner never settles (in
380
- // theory it's endless there), so it's reported, not judged.
381
- if (cell) {
382
- const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
383
- r.cases.forEach((c, n) => { const o = coarser.cases[n]; c.change = { stiffness: stiffOf(c) / stiffOf(o) - 1, stress: c.stress / o.stress - 1, cell: coarser.grid.h }; });
384
- }
385
- const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
386
- const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
387
- let out = null;
388
- if (r.dim !== 3) { // a flat part's picture: its cells as analysed, with the supports and loads
389
- out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
390
- fs.mkdirSync(path.dirname(out), { recursive: true });
391
- fs.writeFileSync(out, picture({ ...r, ...(await readProblem(d.project, a.problem)).problem }, { title: `${b.object.title || d.name}: ${a.problem}`, lines: r.cases.map((c) => `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`) }));
392
- }
393
- // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
394
- // its fatigue strength where it has one
395
- const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null, weaker = m.strength_z != null && m.strength_z < m.strength;
396
- const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
397
- const at = (p) => `(${p.map(fmt).join(', ')})`;
398
- const found = r.cases.flatMap((c) => {
399
- const safety = strength ? strength / c.stress : null, fatigue = m.fatigue ? m.fatigue / c.stress : null;
400
- const text = c.moment ? `${a.problem} ${c.name}: ${howFar(c)}` : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
401
- const values = { ...(c.moment ? { angle: c.angle, moment: c.moment, torsion: c.torsion } : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }), stress: c.stress, ...(limit != null ? { limit } : {}) };
402
- const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
403
- const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
404
- const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
405
- const settled = c.change ? [{ level: Math.abs(c.change.stiffness) <= 0.05 ? 'pass' : 'warn', code: 'fea.settled', values: c.change,
406
- text: `${a.problem} ${c.name}: stiffness ${c.change.stiffness >= 0 ? '+' : ''}${fmt(c.change.stiffness * 100)}% from ${fmt(c.change.cell)} mm cells${Math.abs(c.change.stiffness) <= 0.05 ? ', settled (within 5%)' : ': not settled, use a smaller cell'}` }] : [];
407
- return [
408
- { level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail', text: limit == null ? text : `${text} (at most ${fmt(limit)})`, code: 'fea.deflection', values, refs }, ...settled,
409
- { level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail', text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`, code: 'fea.strength',
410
- values: { stress: c.stress, at: c.stressAt, ...(safety != null ? { safety } : {}), ...(fatigue != null ? { fatigue } : {}), ...(minSafety != null ? { min: minSafety } : {}) }, refs },
411
- ];
412
- });
413
- // Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
414
- if (r.thin && r.thin.share > 0.05) found.push({ level: 'warn', code: 'fea.coarse', values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h }, refs: { problem: a.problem, part: part.name },
415
- text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles` });
416
- const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
417
- if (a.volume != null) {
418
- const want = evaluate(a.volume, lookup), tol = a.tolerance ?? 0.01, off = (r.volume - want) / want;
419
- found.push({ level: Math.abs(off) <= tol ? 'pass' : 'fail', text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`, code: 'fea.volume', values: { volume: r.volume, target: want, off } });
420
- } else found.push({ level: 'info', text: `volume ${fmt(r.volume)} mm³${grams}`, code: 'fea.volume', values: { volume: r.volume } });
421
- // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
422
- const records = b.object.verification || [];
423
- if (r.critical) found.push(records.length
424
- ? { level: 'pass', text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`, code: 'fea.verified', values: { records } }
425
- : { level: 'warn', text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`, code: 'fea.unverified' });
426
- // The report: everything above, with where, written next to the previews
427
- const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
428
- fs.mkdirSync(path.dirname(report), { recursive: true });
429
- fs.writeFileSync(report, reportText({ turn, object: `${d.project}/${d.name}${tag}`, title: b.object.title || d.name, version: b.object.version, a, r, m, strength, weaker, grid, limit, minSafety, records, found }));
430
- fs.writeFileSync(report.replace(/\.md$/, '.json'), JSON.stringify({ object: `${d.project}/${d.name}${tag}`, version: b.object.version, problem: a.problem, critical: r.critical, verification: records, material: { name: m.name, modulus: m.modulus, strength: m.strength, ...(m.strength_z != null ? { strength_z: m.strength_z } : {}), ...(m.fatigue != null ? { fatigue: m.fatigue } : {}) }, grid: r.grid, volume: r.volume, cases: r.cases, findings: found.map(({ level, code, text }) => ({ level, code, text })) }, null, 2) + '\n');
431
- found.push({ level: 'info', text: `report (${grid}): ${path.relative(WS, report)}`, code: 'fea.report', refs: { report: path.relative(WS, report) } });
432
- return found;
433
- })());
853
+ for (const a of b.object.analysis || [])
854
+ all.push(
855
+ ...(await (async () => {
856
+ const part = a.part ? b.parts.find((p) => p.name === a.part) : b.parts.find((p) => p.role !== 'support');
857
+ if (!part) return [{ level: 'fail', text: `analysis: no part "${a.part}"`, code: 'fea.part' }];
858
+ // A part drawn in its print orientation, turned back into the problem's frame: rotated (degrees about x, then y,
859
+ // then z, as JSCAD's rotate), then moved
860
+ const turn =
861
+ (a.rotate || []).map((x) => evaluate(x, lookup)).some(Boolean) ||
862
+ (a.move || []).map((x) => evaluate(x, lookup)).some(Boolean);
863
+ const turned = turn
864
+ ? place(
865
+ part.triangles,
866
+ (a.rotate || [0, 0, 0]).map((x) => evaluate(x, lookup)),
867
+ (a.move || [0, 0, 0]).map((x) => evaluate(x, lookup)),
868
+ )
869
+ : part.triangles;
870
+ const cell = a.cell != null ? evaluate(a.cell, lookup) : undefined;
871
+ const r = await analysePart(turned, d.project, a.problem, { cell }),
872
+ m = r.material;
873
+ // A check of the check: with a cell given, the part is analysed again on cells a quarter bigger, and how much each
874
+ // number changes says whether the cells are small enough (settledFinding). The peak stress is judged only where
875
+ // the part is held to a safety factor (min_safety): at a sharp inside corner it never settles (in theory it's
876
+ // endless there), so elsewhere it's reported, not judged.
877
+ if (cell) {
878
+ const coarser = await analysePart(turned, d.project, a.problem, { cell: cell * 1.25 });
879
+ r.cases.forEach((c, n) => {
880
+ const o = coarser.cases[n];
881
+ c.change = {
882
+ stiffness: stiffOf(c) / stiffOf(o) - 1,
883
+ stress: c.stress / o.stress - 1,
884
+ cell: coarser.grid.h,
885
+ };
886
+ });
887
+ }
888
+ const limit = a.max_deflection != null ? evaluate(a.max_deflection, lookup) : null;
889
+ const minSafety = a.min_safety != null ? evaluate(a.min_safety, lookup) : null;
890
+ let out = null;
891
+ if (r.dim !== 3) {
892
+ // a flat part's picture: its cells as analysed, with the supports and loads
893
+ out = paths.preview(d.project, `${d.name}${tag}-analysis-${a.problem.replace(':', '-')}.svg`);
894
+ fs.mkdirSync(path.dirname(out), { recursive: true });
895
+ fs.writeFileSync(
896
+ out,
897
+ picture(
898
+ { ...r, ...(await readProblem(d.project, a.problem)).problem },
899
+ {
900
+ title: `${b.object.title || d.name}: ${a.problem}`,
901
+ lines: r.cases.map(
902
+ (c) =>
903
+ `${c.name}: ${sig(c.deflection)} mm, ${sig(c.stiffness)} N/mm, peak stress ${sig(c.stress)} MPa`,
904
+ ),
905
+ },
906
+ ),
907
+ );
908
+ }
909
+ // Safety factors: against the material's strength (its weaker one across a print's layers, where it has one), and
910
+ // its fatigue strength where it has one
911
+ const strength = m.strength ? Math.min(m.strength, m.strength_z ?? Infinity) : null,
912
+ weaker = m.strength_z != null && m.strength_z < m.strength;
913
+ const grid = `${[r.grid.nx, r.grid.ny, r.grid.nz].filter(Boolean).join(' × ')} cells of ${fmt(r.grid.h)} mm`;
914
+ const at = (p) => `(${p.map(fmt).join(', ')})`;
915
+ const found = r.cases.flatMap((c) => {
916
+ const safety = strength ? strength / c.stress : null,
917
+ fatigue = m.fatigue ? m.fatigue / c.stress : null;
918
+ const text = c.moment
919
+ ? `${a.problem} ${c.name}: ${howFar(c)}`
920
+ : `${a.problem} ${c.name}: moves ${sig(c.deflection)} mm under ${fmt(c.force)} N, ${sig(c.stiffness)} N/mm`;
921
+ const values = {
922
+ ...(c.moment
923
+ ? { angle: c.angle, moment: c.moment, torsion: c.torsion }
924
+ : { deflection: c.deflection, force: c.force, stiffness: c.stiffness }),
925
+ stress: c.stress,
926
+ ...(limit != null ? { limit } : {}),
927
+ };
928
+ const refs = { problem: a.problem, part: part.name, ...(out ? { picture: path.relative(WS, out) } : {}) };
929
+ const strong = `peak stress ${sig(c.stress)} MPa at ${at(c.stressAt)}${safety != null ? `: ${sig(safety)}× under ${m.name}'s ${weaker ? 'strength across its layers' : 'strength'}${fatigue != null ? `, ${sig(fatigue)}× under its fatigue strength` : ''}` : ''}`;
930
+ const least = Math.min(safety ?? Infinity, fatigue ?? Infinity);
931
+ const settled = c.change ? [settledFinding(a.problem, c.name, c.change, minSafety != null)] : [];
932
+ return [
933
+ {
934
+ level: limit == null || c.moment ? 'info' : c.deflection <= limit ? 'pass' : 'fail',
935
+ text: limit == null ? text : `${text} (at most ${fmt(limit)})`,
936
+ code: 'fea.deflection',
937
+ values,
938
+ refs,
939
+ },
940
+ ...settled,
941
+ {
942
+ level: minSafety == null ? 'info' : least >= minSafety ? 'pass' : 'fail',
943
+ text: `${a.problem} ${c.name}: ${strong}${minSafety != null ? ` (at least ${fmt(minSafety)}×)` : ''}`,
944
+ code: 'fea.strength',
945
+ values: {
946
+ stress: c.stress,
947
+ at: c.stressAt,
948
+ ...(safety != null ? { safety } : {}),
949
+ ...(fatigue != null ? { fatigue } : {}),
950
+ ...(minSafety != null ? { min: minSafety } : {}),
951
+ },
952
+ refs,
953
+ },
954
+ ];
955
+ });
956
+ // Members the grid is too coarse for: under four cells thick, a cell's stiffness is a rough figure
957
+ if (r.thin && r.thin.share > 0.05)
958
+ found.push({
959
+ level: 'warn',
960
+ code: 'fea.coarse',
961
+ values: { share: r.thin.share, cells: r.thin.cells, cell: r.grid.h },
962
+ refs: { problem: a.problem, part: part.name },
963
+ text: `${a.problem}: ${fmt(r.thin.share * 100)}% of the part is in members under ${r.thin.cells} cells (${fmt(r.thin.cells * r.grid.h)} mm) thick, where the stiffness is rough: use a smaller cell (${fmt(r.grid.h / 2)} mm) and see that it settles`,
964
+ });
965
+ const grams = m.density ? ` (${fmt((r.volume / 1000) * m.density)} g of ${m.name})` : '';
966
+ if (a.volume != null) {
967
+ const want = evaluate(a.volume, lookup),
968
+ tol = a.tolerance ?? 0.01,
969
+ off = (r.volume - want) / want;
970
+ found.push({
971
+ level: Math.abs(off) <= tol ? 'pass' : 'fail',
972
+ text: `volume ${fmt(r.volume)} mm³${grams}: ${off >= 0 ? '+' : ''}${fmt(off * 100)}% from ${fmt(want)} (within ${fmt(tol * 100)}%)`,
973
+ code: 'fea.volume',
974
+ values: { volume: r.volume, target: want, off },
975
+ });
976
+ } else
977
+ found.push({
978
+ level: 'info',
979
+ text: `volume ${fmt(r.volume)} mm³${grams}`,
980
+ code: 'fea.volume',
981
+ values: { volume: r.volume },
982
+ });
983
+ // A safety-critical part stays unverified until a test or an independent analysis is recorded against it
984
+ const records = b.object.verification || [];
985
+ if (r.critical)
986
+ found.push(
987
+ records.length
988
+ ? {
989
+ level: 'pass',
990
+ text: `${a.problem} is safety-critical: verified by ${records.map((v) => `${v.kind} (${v.date})`).join(', ')}`,
991
+ code: 'fea.verified',
992
+ values: { records },
993
+ }
994
+ : {
995
+ level: 'warn',
996
+ text: `${a.problem} is safety-critical and unverified: rulecad's analysis is a design aid. Test it, or have it analysed independently, and record that under "verification"`,
997
+ code: 'fea.unverified',
998
+ },
999
+ );
1000
+ // The report: everything above, with where, written next to the previews
1001
+ const report = paths.preview(d.project, `${d.name}${tag}-report-${a.problem.replace(':', '-')}.md`);
1002
+ fs.mkdirSync(path.dirname(report), { recursive: true });
1003
+ fs.writeFileSync(
1004
+ report,
1005
+ reportText({
1006
+ turn,
1007
+ object: `${d.project}/${d.name}${tag}`,
1008
+ title: b.object.title || d.name,
1009
+ version: b.object.version,
1010
+ a,
1011
+ r,
1012
+ m,
1013
+ strength,
1014
+ weaker,
1015
+ grid,
1016
+ limit,
1017
+ minSafety,
1018
+ records,
1019
+ found,
1020
+ }),
1021
+ );
1022
+ fs.writeFileSync(
1023
+ report.replace(/\.md$/, '.json'),
1024
+ JSON.stringify(
1025
+ {
1026
+ object: `${d.project}/${d.name}${tag}`,
1027
+ version: b.object.version,
1028
+ problem: a.problem,
1029
+ critical: r.critical,
1030
+ verification: records,
1031
+ material: {
1032
+ name: m.name,
1033
+ modulus: m.modulus,
1034
+ strength: m.strength,
1035
+ ...(m.strength_z != null ? { strength_z: m.strength_z } : {}),
1036
+ ...(m.fatigue != null ? { fatigue: m.fatigue } : {}),
1037
+ },
1038
+ grid: r.grid,
1039
+ volume: r.volume,
1040
+ cases: r.cases,
1041
+ findings: found.map(({ level, code, text }) => ({ level, code, text })),
1042
+ },
1043
+ null,
1044
+ 2,
1045
+ ) + '\n',
1046
+ );
1047
+ found.push({
1048
+ level: 'info',
1049
+ text: `report (${grid}): ${path.relative(WS, report)}`,
1050
+ code: 'fea.report',
1051
+ refs: { report: path.relative(WS, report) },
1052
+ });
1053
+ return found;
1054
+ })()),
1055
+ );
434
1056
  return all;
435
1057
  }
436
1058
 
1059
+ // cad rules update <set>: the workspace's copy of a kit set given the kit's newer figures and new rules (sheet.mjs
1060
+ // kitDifference says which are the kit's to take), keeping the measured, the newer and the copy's own, and saying each
1061
+ function updateRules(name) {
1062
+ plainName(name, 'rule set name');
1063
+ const u = updateSet(name),
1064
+ rel = `rules/${name}.json`;
1065
+ if (!u.copy) {
1066
+ const text = `no ${rel} in this workspace: the first design to use ${name} copies in the kit's as it is then`;
1067
+ return console.log(opt('json') ? JSON.stringify({ set: name, file: null, updated: false, text }, null, 2) : text);
1068
+ }
1069
+ const d = u.difference,
1070
+ taken = d.changed.length + d.refreshed.length + d.added.length + u.fields.length > 0,
1071
+ dry = !!opt('dry-run'),
1072
+ said = (v) => (typeof v === 'number' || typeof v === 'string' ? String(v) : JSON.stringify(v)),
1073
+ was = (k) => `${said(u.copy.rules[k]?.value)} here, ${said(u.kit.rules[k]?.value)} in the kit's`;
1074
+ if (taken && !dry) {
1075
+ insideWorkspace(u.file); // (never written through a link out of rules/)
1076
+ fs.writeFileSync(u.file, JSON.stringify(u.set, null, 2) + '\n');
1077
+ }
1078
+ if (opt('json'))
1079
+ return console.log(
1080
+ JSON.stringify(
1081
+ {
1082
+ set: name,
1083
+ file: rel,
1084
+ updated: taken && !dry,
1085
+ ...(dry ? { dryRun: true } : {}),
1086
+ changed: d.changed.map((k) => ({ rule: k, from: u.copy.rules[k]?.value, to: u.kit.rules[k]?.value })),
1087
+ added: d.added,
1088
+ refreshed: d.refreshed,
1089
+ fields: u.fields,
1090
+ kept: { measured: d.measured, newer: d.newer, own: d.own },
1091
+ },
1092
+ null,
1093
+ 2,
1094
+ ),
1095
+ );
1096
+ const lines = [
1097
+ ...d.changed.map(
1098
+ (k) =>
1099
+ ` ${k}: ${said(u.copy.rules[k]?.value)} → ${said(u.kit.rules[k]?.value)} (the kit's, ${u.kit.rules[k].kind ?? 'no kind'}, checked ${u.kit.rules[k].checked})`,
1100
+ ),
1101
+ ...(d.added.length ? [` added from the kit's: ${d.added.join(', ')}`] : []),
1102
+ ...(d.refreshed.length
1103
+ ? [
1104
+ ` the same figure, with what the kit's adds or has newer (its source, words, date or range): ${d.refreshed.join(', ')}`,
1105
+ ]
1106
+ : []),
1107
+ ...(u.fields.length ? [` the set's own fields, as the kit's: ${u.fields.join(', ')}`] : []),
1108
+ ...(d.measured.length ? [` kept as measured: ${d.measured.map((k) => `${k} (${was(k)})`).join(', ')}`] : []),
1109
+ ...(d.newer.length
1110
+ ? [` kept as yours, checked on or after the kit's date: ${d.newer.map((k) => `${k} (${was(k)})`).join(', ')}`]
1111
+ : []),
1112
+ ...(d.own.length ? [` kept, the kit has none: ${d.own.join(', ')}`] : []),
1113
+ ];
1114
+ console.log(
1115
+ taken
1116
+ ? `${dry ? 'would update' : 'updated'} ${rel} from the kit's ${name}${dry ? ' (--dry-run: nothing written)' : ''}:`
1117
+ : `${rel} is up to date with the kit's ${name}${lines.length ? ':' : ''}`,
1118
+ );
1119
+ for (const l of lines) console.log(l);
1120
+ }
1121
+
437
1122
  // cad rules check / draw / draft: rule sets themselves, not a design's use of them
438
1123
  function ruleSheets(what, names) {
439
1124
  if (what === 'check') {
440
1125
  // a set fails on a finding of level fail; a warning or a note is said and the set still passes
441
- const results = checkSets(names), fails = (r) => r.findings.filter((x) => x.level === 'fail').length, bad = results.filter(fails), noted = results.filter((r) => r.findings.length && !fails(r));
442
- if (opt('json')) console.log(JSON.stringify(results.map((r) => ({ name: r.name, findings: r.findings, ...(r.notes ? { notes: r.notes } : {}) })), null, 2));
1126
+ const results = checkSets(names),
1127
+ fails = (r) => r.findings.filter((x) => x.level === 'fail').length,
1128
+ bad = results.filter(fails),
1129
+ noted = results.filter((r) => r.findings.length && !fails(r));
1130
+ if (opt('json'))
1131
+ console.log(
1132
+ JSON.stringify(
1133
+ results.map((r) => ({ name: r.name, findings: r.findings, ...(r.notes ? { notes: r.notes } : {}) })),
1134
+ null,
1135
+ 2,
1136
+ ),
1137
+ );
443
1138
  else {
444
- for (const r of results.filter((x) => x.findings.length)) { console.log(`${r.name}: ${fails(r) ? `${fails(r)} to fix` : `passes, ${r.findings.length} to know`}`); for (const x of r.findings) console.log(` ${{ fail: 'FAIL', warn: 'WARN', info: 'NOTE' }[x.level] ?? 'FAIL'} ${x.text} (${x.code})`); }
1139
+ for (const r of results.filter((x) => x.findings.length)) {
1140
+ console.log(`${r.name}: ${fails(r) ? `${fails(r)} to fix` : `passes, ${r.findings.length} to know`}`);
1141
+ for (const x of r.findings)
1142
+ console.log(` ${{ fail: 'FAIL', warn: 'WARN', info: 'NOTE' }[x.level] ?? 'FAIL'} ${x.text} (${x.code})`);
1143
+ }
445
1144
  // notes never fail: an alias names one line per set, what a copy lacks of the kit's set says it whole
446
1145
  for (const r of results.filter((x) => x.notes)) {
447
- const alias = r.notes.filter((x) => x.code === 'rules.alias'), rest = r.notes.filter((x) => x.code !== 'rules.alias');
448
- if (alias.length) console.log(`${r.name}: NOTE ${alias.map((x) => `${x.rule} is also read as ${x.values.alias}`).join(', ')} (rules.alias)`);
1146
+ const alias = r.notes.filter((x) => x.code === 'rules.alias'),
1147
+ rest = r.notes.filter((x) => x.code !== 'rules.alias');
1148
+ if (alias.length)
1149
+ console.log(
1150
+ `${r.name}: NOTE ${alias.map((x) => `${x.rule} is also read as ${x.values.alias}`).join(', ')} (rules.alias)`,
1151
+ );
449
1152
  for (const x of rest) console.log(`${r.name}: NOTE ${x.text} (${x.code})`);
450
1153
  }
451
- console.log(`${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`);
1154
+ console.log(
1155
+ `${results.length - bad.length} of ${results.length} rule sets pass${noted.length ? ` (${noted.length} with something to know)` : ''}`,
1156
+ );
452
1157
  }
453
1158
  process.exitCode = bad.length ? 1 : 0;
454
1159
  return;
455
1160
  }
456
1161
  const name = names[0];
457
- if (!name) throw new Error(`usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`);
458
- if (what === 'draw') { const to = opt('out') || `${name}.svg`; fs.writeFileSync(to, drawSet(name)); return console.log(`drew ${to}: compare it with the datasheet`); }
1162
+ if (!name)
1163
+ throw new Error(
1164
+ `usage: cad rules ${what} <set>${what === 'draft' ? ` --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>` : ''}`,
1165
+ );
1166
+ if (what === 'update') return updateRules(name);
1167
+ if (what === 'draw') {
1168
+ const to = opt('out') || `${name}.svg`;
1169
+ fs.writeFileSync(to, drawSet(name));
1170
+ return console.log(`drew ${to}: compare it with the datasheet`);
1171
+ }
459
1172
  const save = (as, set) => {
460
- const to = insideWorkspace(path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${plainName(as, 'rule set name')}.json`)); // (from the command line: never ../, nor through a link out of rules/)
461
- if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
462
- fs.mkdirSync(path.dirname(to), { recursive: true }); fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
1173
+ const to = insideWorkspace(
1174
+ path.join(paths.rules ? paths.rules() : path.join(WS, 'rules'), `${plainName(as, 'rule set name')}.json`),
1175
+ ); // (from the command line: never ../, nor through a link out of rules/)
1176
+ if (fs.existsSync(to) && !opt('force'))
1177
+ throw new Error(`${path.relative(WS, to)} already exists (--force replaces it)`);
1178
+ fs.mkdirSync(path.dirname(to), { recursive: true });
1179
+ fs.writeFileSync(to, JSON.stringify(set, null, 2) + '\n');
463
1180
  return to;
464
1181
  };
465
1182
  // cad rules draft profile <name>: every field of the vocabulary for that part, to fill from a sheet
466
1183
  if (draftParts().includes(name) && !opt('from')) {
467
- const part = name, as = names[1];
1184
+ const part = name,
1185
+ as = names[1];
468
1186
  if (!as) throw new Error(`usage: cad rules draft ${part} <name>`);
469
1187
  const to = save(as, draftPart(part, as));
470
- return console.log(`a draft ${part.replace('_', ' ')} in ${path.relative(WS, to)}, every figure an estimate: fill it from the maker's sheet (source, page, date), then cad rules check ${as} and cad rules draw ${as}`);
1188
+ return console.log(
1189
+ `a draft ${part.replace('_', ' ')} in ${path.relative(WS, to)}, every figure an estimate: fill it from the maker's sheet (source, page, date), then cad rules check ${as} and cad rules draw ${as}`,
1190
+ );
471
1191
  }
472
- if (!opt('from')) throw new Error(`usage: cad rules draft <name> --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>`);
1192
+ if (!opt('from'))
1193
+ throw new Error(
1194
+ `usage: cad rules draft <name> --from <file.pdf>, or cad rules draft ${draftParts().join('|')} <name>`,
1195
+ );
473
1196
  const { set, found } = draftSet(name, opt('from'));
474
- if (!found) return console.log(`no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`);
1197
+ if (!found)
1198
+ return console.log(
1199
+ `no figures in ${opt('from')}'s text: it's probably a picture of a drawing, so read it by eye and write rules/${name}.json by hand`,
1200
+ );
475
1201
  const to = save(name, set);
476
- return console.log(`${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`);
1202
+ return console.log(
1203
+ `${found} figures in ${path.relative(WS, to)}, every one an estimate: name them from the vocabulary, check them against the datasheet, then cad rules check ${name}`,
1204
+ );
477
1205
  }
478
1206
 
479
1207
  async function main() {
480
- const first = args[0], pos = positional(), [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
1208
+ const first = args[0],
1209
+ pos = positional(),
1210
+ [cmd = first, ref] = pos; // names first or options first: cad check --json keyboard/case
481
1211
  if (!first || ['help', '--help', '-h'].includes(first)) return console.log(HELP);
482
- if (['--version', '-v', 'version'].includes(first)) return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
483
- if (!COMMANDS.includes(cmd)) { const guess = near(cmd, COMMANDS); throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`); }
1212
+ if (['--version', '-v', 'version'].includes(first))
1213
+ return console.log(JSON.parse(fs.readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version);
1214
+ if (!COMMANDS.includes(cmd)) {
1215
+ const guess = near(cmd, COMMANDS);
1216
+ throw new Error(`no command "${cmd}"${guess ? ` (did you mean "${guess}"?)` : ''}: cad help lists them`);
1217
+ }
484
1218
  const odd = args.find((a) => a.startsWith('--') && !OPTIONS.includes(a.slice(2)));
485
- if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
1219
+ if (odd) {
1220
+ const guess = near(odd.slice(2), OPTIONS);
1221
+ throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`);
1222
+ }
486
1223
  if (configError) throw configError;
487
- if (opt('dry-run') && !takesDryRun(cmd)) throw new Error(`cad ${cmd}${opt('size') ? ' --size' : ''} takes no --dry-run, so nothing is run: ${DRY_RUNS}`);
488
-
489
- if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/'))) return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
490
- if (cmd === 'new') { // an object, from the template; --dry-run and --json as the other edits
491
- const r = newObject(ref, { dryRun: !!opt('dry-run') }), [project, name] = String(ref).split('/');
1224
+ if (opt('dry-run') && !takesDryRun(cmd))
1225
+ throw new Error(`cad ${cmd}${opt('size') ? ' --size' : ''} takes no --dry-run, so nothing is run: ${DRY_RUNS}`);
1226
+
1227
+ if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/')))
1228
+ return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
1229
+ if (cmd === 'new') {
1230
+ // an object, from the template; --dry-run and --json as the other edits
1231
+ const r = newObject(ref, { dryRun: !!opt('dry-run') }),
1232
+ [project, name] = String(ref).split('/');
492
1233
  return edited(r, 'new', {}, `${r.dryRun ? 'would make' : 'made'} projects/${project}/objects/${name}.{js,json}`);
493
1234
  }
494
1235
 
495
- if (cmd === 'rules' && ['check', 'draw', 'draft'].includes(ref)) return ruleSheets(ref, pos.slice(2));
1236
+ if (cmd === 'rules' && ['check', 'draw', 'draft', 'update'].includes(ref)) return ruleSheets(ref, pos.slice(2));
496
1237
 
497
- if (cmd === 'trust') { // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
1238
+ if (cmd === 'trust') {
1239
+ // this workspace may do what its cad.config.json asks (designs outside the sandbox, its own targets)
498
1240
  const what = asks();
499
1241
  if (!what.length) return console.log('this workspace asks for nothing outside the sandbox: nothing to trust');
500
1242
  trust();
501
- return console.log(`trusted ${WS} for ${what.join(' and ')} (kept in your own list; a workspace that asks for more is asked again)`);
1243
+ return console.log(
1244
+ `trusted ${WS} for ${what.join(' and ')} (kept in your own list; a workspace that asks for more is asked again)`,
1245
+ );
502
1246
  }
503
1247
 
504
- if (cmd === 'agents') { // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
505
- const to = path.join(WS, 'AGENTS.md'), ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'), record = paths.cache('agents.md');
1248
+ if (cmd === 'agents') {
1249
+ // the notes for AI agents, into this workspace (AGENTS.md, and CLAUDE.md pointing at it)
1250
+ const to = path.join(WS, 'AGENTS.md'),
1251
+ ours = fs.readFileSync(path.join(TOOL, 'AGENTS.md'), 'utf8'),
1252
+ record = paths.cache('agents.md');
506
1253
  // An AGENTS.md as cad agents last wrote it (or, with no record of that, one that is an earlier copy of ours) is
507
1254
  // brought up to date; one edited here is kept, unless --force
508
- const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null, last = fs.existsSync(record) ? fs.readFileSync(record, 'utf8') : null;
509
- const ourCopy = mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
510
- if (!ourCopy && !opt('force')) throw new Error('AGENTS.md here has been edited (or isn\'t rulecad\'s): it is kept as it is (cad agents --force replaces it)');
511
- fs.writeFileSync(to, ours); fs.mkdirSync(path.dirname(record), { recursive: true }); fs.writeFileSync(record, ours);
1255
+ const mine = fs.existsSync(to) ? fs.readFileSync(to, 'utf8') : null,
1256
+ last = cached(record) ? fs.readFileSync(record, 'utf8') : null; // (never read through a link out)
1257
+ const ourCopy =
1258
+ mine === null || mine === ours || (last !== null ? mine === last : mine.startsWith(ours.split('\n')[0]));
1259
+ if (!ourCopy && !opt('force'))
1260
+ throw new Error(
1261
+ "AGENTS.md here has been edited (or isn't rulecad's): it is kept as it is (cad agents --force replaces it)",
1262
+ );
1263
+ fs.writeFileSync(to, ours);
1264
+ writeCacheFile(record, ours);
512
1265
  const claude = path.join(WS, 'CLAUDE.md');
513
1266
  if (!fs.existsSync(claude)) fs.writeFileSync(claude, '@AGENTS.md\n');
514
1267
  else if (!fs.readFileSync(claude, 'utf8').includes('@AGENTS.md')) fs.appendFileSync(claude, '\n@AGENTS.md\n');
515
- return console.log(`wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`);
1268
+ return console.log(
1269
+ `wrote ${path.relative(process.cwd(), to) || 'AGENTS.md'}: how an AI agent should design here (CLAUDE.md includes it)`,
1270
+ );
516
1271
  }
517
- if (cmd === 'import-kle') { // a layout from keyboard-layout-editor.com into a project's layouts/
1272
+ if (cmd === 'import-kle') {
1273
+ // a layout from keyboard-layout-editor.com into a project's layouts/
518
1274
  const [project, name] = String(pos[2] || '').split('/');
519
- if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || '')) throw new Error('usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)');
1275
+ if (!ref || !fs.existsSync(ref) || !project || !/^[a-z][a-z0-9-]*$/.test(name || ''))
1276
+ throw new Error(
1277
+ 'usage: cad import-kle <layout.json> <project>/<name> (the JSON download, or a file with its Raw data)',
1278
+ );
520
1279
  const { layout, notes } = fromKLE(fs.readFileSync(ref, 'utf8'));
521
1280
  const to = path.join(paths.project(project), 'layouts', `${name}.json`);
522
- if (fs.existsSync(to) && !opt('force')) throw new Error(`${path.relative(WS, to)} already exists (--force to replace it)`);
1281
+ if (fs.existsSync(to) && !opt('force'))
1282
+ throw new Error(`${path.relative(WS, to)} already exists (--force to replace it)`);
523
1283
  fs.mkdirSync(path.dirname(to), { recursive: true });
524
1284
  fs.writeFileSync(to, `${JSON.stringify({ title: layout.title || name, ...layout }, null, 1)}\n`);
525
- console.log(`made ${path.relative(WS, to)}: ${layout.rows.length} rows, ${layout.rows.flat().filter((k) => !k.gap).length} keys`);
1285
+ console.log(
1286
+ `made ${path.relative(WS, to)}: ${layout.rows.length} rows, ${layout.rows.flat().filter((k) => !k.gap).length} keys`,
1287
+ );
526
1288
  for (const n of notes) console.log(` note: ${n}`);
527
1289
  return;
528
1290
  }
529
- if (cmd === 'clone') return cloneBoard(ref, pos[2], { source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), noModels: !!opt('no-models') });
1291
+ if (cmd === 'clone')
1292
+ return cloneBoard(ref, pos[2], {
1293
+ source: opt('source'),
1294
+ licence: opt('licence') || opt('license'),
1295
+ force: !!opt('force'),
1296
+ noModels: !!opt('no-models'),
1297
+ });
530
1298
  if (cmd === 'status') return status(ref);
531
1299
  if (cmd === 'measure') {
532
- if (!ref) throw new Error('usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>], or cad measure <beam.stl|3mf|section.dxf> --profile <name>');
1300
+ if (!ref)
1301
+ throw new Error(
1302
+ 'usage: cad measure <model.stl|model.3mf> [--along x] [--at 10,50] [--line 0.6,2.5] [--rules <name>], or cad measure <beam.stl|3mf|section.dxf> --profile <name>',
1303
+ );
533
1304
  if (opt('profile')) {
534
1305
  const { measureProfile } = await import('../lib/profilemeasure.mjs');
535
- return measureProfile(ref, { profile: opt('profile'), along: opt('along'), tol: opt('tol') && opt('tol') !== true ? opt('tol') : undefined, source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
1306
+ return measureProfile(ref, {
1307
+ profile: opt('profile'),
1308
+ along: opt('along'),
1309
+ tol: opt('tol') && opt('tol') !== true ? opt('tol') : undefined,
1310
+ source: opt('source'),
1311
+ licence: opt('licence') || opt('license'),
1312
+ force: !!opt('force'),
1313
+ pictures: !opt('no-pictures'),
1314
+ });
536
1315
  }
537
- if (/\.dxf$/i.test(ref)) throw new Error('a DXF is a drawing of a section, not a model: cad measure <section.dxf> --profile <name> reads a beam\'s profile from it');
538
- const list = (k) => (opt(k) && opt(k) !== true ? String(opt(k)).split(k === 'line' ? ';' : ',').filter(Boolean) : []);
539
- return measure(ref, { along: opt('along'), at: list('at'), line: list('line'), rules: opt('rules'), source: opt('source'), licence: opt('licence') || opt('license'), force: !!opt('force'), pictures: !opt('no-pictures') });
1316
+ if (/\.dxf$/i.test(ref))
1317
+ throw new Error(
1318
+ "a DXF is a drawing of a section, not a model: cad measure <section.dxf> --profile <name> reads a beam's profile from it",
1319
+ );
1320
+ const list = (k) =>
1321
+ opt(k) && opt(k) !== true
1322
+ ? String(opt(k))
1323
+ .split(k === 'line' ? ';' : ',')
1324
+ .filter(Boolean)
1325
+ : [];
1326
+ return measure(ref, {
1327
+ along: opt('along'),
1328
+ at: list('at'),
1329
+ line: list('line'),
1330
+ rules: opt('rules'),
1331
+ source: opt('source'),
1332
+ licence: opt('licence') || opt('license'),
1333
+ force: !!opt('force'),
1334
+ pictures: !opt('no-pictures'),
1335
+ });
540
1336
  }
1337
+ if (cmd === 'coupons') return couponsCommand();
1338
+ // (cad measured with no assembly: --export, or a figure written as it is; cad history alone: those figures)
1339
+ if (cmd === 'measured' && !ref) return measuredCommand(null);
1340
+ if (cmd === 'history' && !ref) return history(null);
541
1341
  if (!ref || (cmd === 'add' && !pos[2])) throw new Error(`usage: cad ${cmd} ${USAGE[cmd] || '<project>/<object>'}`);
542
- if (cmd === 'release') return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
1342
+ if (cmd === 'release')
1343
+ return ref.includes('/') ? releaseObject(locate(ref)) : opt('all') ? releaseAll(ref) : releaseProject(ref);
543
1344
  if (cmd === 'variants') return variants(locate(ref));
544
1345
  if (cmd === 'compare') return compareVariants(locate(ref), pos[2], pos[3]);
1346
+ // These build an assembly as its file says: a --set would be passed over, so it is refused by name
1347
+ if (opt('set') !== undefined && ['measured', 'frame', 'machine', 'plot', 'plates', 'order', 'kit'].includes(cmd))
1348
+ throw new Error(
1349
+ `cad ${cmd} builds ${ref} as its file says and takes no --set: try the value with cad check ${ref} --set <item>.<variable>=<value>, then write it into the file with cad set`,
1350
+ );
545
1351
  if (cmd === 'measured') return measuredCommand(ref);
546
1352
  if (cmd === 'list' || cmd === 'wires' || cmd === 'beams') return listCommand(cmd, ref);
547
1353
  if (cmd === 'frame') return frameCommand(ref);
@@ -552,32 +1358,50 @@ async function main() {
552
1358
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
553
1359
  if (cmd === 'printed') return printed(locate(ref));
554
1360
  if (cmd === 'why') return explainValue(ref);
555
- if (cmd === 'set') return isAssembly(ref) ? editFields(ref) : !ref.includes('/') ? editProject(ref) : editVariables(ref);
1361
+ if (cmd === 'set')
1362
+ return isAssembly(ref) ? editFields(ref) : !ref.includes('/') ? editProject(ref) : editVariables(ref);
556
1363
  if (cmd === 'add') return editAssembly(pos[1], pos[2]);
557
1364
  if (cmd === 'remove' || cmd === 'move') return removeOrMove(cmd, ref, pos[2]);
558
1365
  if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
559
1366
  // A problem file's preview: its result drawn, and its run to watch again (or live, with --watch)
560
1367
  const problemRef = /^(?:projects[\\/])?([^\\/]+)[\\/]problems[\\/]([^\\/:]+?)(?:\.json)?(:[^\\/]+)?$/.exec(ref || '');
561
- if (cmd === 'preview' && problemRef) return await optimiseProblem(`${problemRef[1]}/${problemRef[2]}${problemRef[3] || ''}`, { preview: true });
1368
+ if (cmd === 'preview' && problemRef)
1369
+ return await optimiseProblem(`${problemRef[1]}/${problemRef[2]}${problemRef[3] || ''}`, { preview: true });
562
1370
  if (isAssembly(ref)) return assembly(cmd, ref);
563
1371
  const [base, at] = ref.split('@');
564
- const d = at ? materialise(locate(base), at) : locate(ref), set = sets();
1372
+ const d = at ? materialise(locate(base), at) : locate(ref),
1373
+ set = sets();
565
1374
  // A check reads the files against their schemas first: a broken .json is said as that, before a build fails on it
566
1375
  if (cmd === 'check' && !at && fs.existsSync(d.json)) {
567
1376
  const bad = schemaFindings(readJson(d.json), 'object', path.relative(WS, d.json)).filter((f) => f.level === 'fail'); // (readJson: broken JSON is named with its file)
568
- if (bad.length) { say(`${d.project}/${d.name}`); report(bad, { object: `${d.project}/${d.name}` }); process.exitCode = 1; return; }
1377
+ if (bad.length) {
1378
+ say(`${d.project}/${d.name}`);
1379
+ report(bad, { object: `${d.project}/${d.name}` });
1380
+ process.exitCode = 1;
1381
+ return;
1382
+ }
569
1383
  }
570
1384
  const b = opt('part') ? pick(await build(d, set), { part: opt('part') }) : await build(d, set);
571
1385
  const tag = `${d.variant ? `-${d.variant}` : ''}${suffix(set)}${opt('part') ? `-${opt('part')}` : ''}`; // in file names
572
- const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version = b.object.version || '0.0.0';
1386
+ const title = `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`,
1387
+ version = b.object.version || '0.0.0';
573
1388
 
574
1389
  if (b.circuit && ['check', 'preview', 'export'].includes(cmd)) return board(cmd, d, b, { title, version, tag });
575
1390
 
576
1391
  if (cmd === 'match') {
577
1392
  const file = pos[2];
578
- if (!file || file.startsWith('--')) throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
579
- const tol = opt('tol') ? Number(opt('tol')) : printer(b, d).fit ?? 0.2;
580
- const ok = await match(b, d, file, { place: opt('place'), tol, samples: Number(opt('samples')) || 20000, at: opt('at') ? String(opt('at')).split(',') : [], title: `${title} ${version}`, tag, pictures: !opt('no-pictures') });
1393
+ if (!file || file.startsWith('--'))
1394
+ throw new Error(`usage: cad match ${ref} <model.stl|model.3mf> [--tol 0.2] [--place "rz90 t1,2,3"]`);
1395
+ const tol = opt('tol') ? Number(opt('tol')) : (printer(b, d).fit ?? 0.2);
1396
+ const ok = await match(b, d, file, {
1397
+ place: opt('place'),
1398
+ tol,
1399
+ samples: Number(opt('samples')) || 20000,
1400
+ at: opt('at') ? String(opt('at')).split(',') : [],
1401
+ title: `${title} ${version}`,
1402
+ tag,
1403
+ pictures: !opt('no-pictures'),
1404
+ });
581
1405
  process.exitCode = ok ? 0 : 1;
582
1406
  return;
583
1407
  }
@@ -585,60 +1409,157 @@ async function main() {
585
1409
  if (cmd === 'values') {
586
1410
  const list = valuesOf(b, positional().slice(2));
587
1411
  if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, values: list }, null, 2));
588
- for (const v of list) console.log(`${v.name.padEnd(18)} ${`${fmt(v.value)} ${v.unit}`.padEnd(14)} ${v.expr ? `= ${v.expr}` : ''}`);
1412
+ for (const v of list)
1413
+ console.log(`${v.name.padEnd(18)} ${`${fmt(v.value)} ${v.unit}`.padEnd(14)} ${v.expr ? `= ${v.expr}` : ''}`);
589
1414
  return;
590
1415
  }
591
1416
 
592
1417
  if (cmd === 'rules') {
593
- if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variables: b.entries.map((e) => ({ name: e.name, value: e.value, unit: e.unit || null, expr: e.expr || null, rule: e.rule || null, ...(e.source ? { source: e.source, kind: e.kind || null } : {}) })) }, null, 2));
594
- for (const e of b.entries) console.log(`${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`);
1418
+ if (opt('json'))
1419
+ return console.log(
1420
+ JSON.stringify(
1421
+ {
1422
+ object: `${d.project}/${d.name}`,
1423
+ variables: b.entries.map((e) => ({
1424
+ name: e.name,
1425
+ value: e.value,
1426
+ unit: e.unit || null,
1427
+ expr: e.expr || null,
1428
+ rule: e.rule || null,
1429
+ ...(e.source ? { source: e.source, kind: e.kind || null } : {}),
1430
+ })),
1431
+ },
1432
+ null,
1433
+ 2,
1434
+ ),
1435
+ );
1436
+ for (const e of b.entries)
1437
+ console.log(
1438
+ `${e.name.padEnd(18)} ${`${fmt(e.value)} ${e.unit || ''}`.padEnd(14)} ${e.expr ? `= ${e.expr} ` : ''}${e.rule || ''}${e.source ? ` [${e.kind ? `${e.kind}: ` : ''}${e.source}]` : ''}${e.set ? ' (set)' : ''}`,
1439
+ );
595
1440
  return;
596
1441
  }
597
1442
 
598
1443
  if (cmd === 'check') {
599
1444
  say(`${title} ${version}${Object.keys(set).length ? ` (${suffix(set).slice(1)})` : ''}`);
600
- const raw = lint(fs.readFileSync(d.js, 'utf8')), file = path.relative(WS, d.js);
1445
+ const raw = lint(readOwnText(d.js)),
1446
+ file = path.relative(WS, d.js);
601
1447
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
602
- const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
603
- const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
604
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
605
- ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
606
- const failed = report([
607
- ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
608
- ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
609
- ...unruled(b.object, own(d.json)),
610
- raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`, code: 'lint.numbers', refs: { file, numbers: raw } }
611
- : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
612
- ...(b.object.role === 'reference'
613
- ? [{ level: 'pass', text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`, code: 'print.reference' }]
614
- : await printChecks(b, d)),
615
- ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
616
- ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
617
- ...(await analyses(b, d, tag)),
618
- ], { object: `${d.project}/${d.name}`, title, version, ...(Object.keys(set).length ? { set } : {}), orientation: b.object.orientation, parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })) });
1448
+ const own = (f) => path.relative(WS, f),
1449
+ ruleFiles = (b.object.uses || [])
1450
+ .filter((u) => !u.includes('/'))
1451
+ .map((u) => path.join(WS, 'rules', `${u}.json`))
1452
+ .filter((f) => fs.existsSync(f));
1453
+ const problemFiles = [
1454
+ ...new Set(
1455
+ [
1456
+ ...Object.values(b.object.variables || {})
1457
+ .filter((v) => v.type === 'problem')
1458
+ .flatMap((v) => v.choice || [v.value]),
1459
+ ...(b.object.analysis || []).map((a) => a.problem),
1460
+ ].map((n) => problemFile(d.project, String(n).split(':')[0])),
1461
+ ),
1462
+ ].filter((f) => fs.existsSync(f));
1463
+ const schemaProblems = [
1464
+ ...schemaFindings(readJson(d.json), 'object', own(d.json)),
1465
+ ...ruleFiles.flatMap((f) => schemaFindings(readJson(f), 'rules', own(f))),
1466
+ ...problemFiles.flatMap((f) => schemaFindings(readJson(f), 'problem', own(f))),
1467
+ ];
1468
+ const failed = report(
1469
+ [
1470
+ ...(schemaProblems.length
1471
+ ? schemaProblems
1472
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
1473
+ ...(b.units || []).map((u) => ({
1474
+ level: 'warn',
1475
+ text: `units: ${u.message}`,
1476
+ code: 'units',
1477
+ refs: { file: own(d.json), path: u.path, variable: u.name },
1478
+ })),
1479
+ ...unruled(b.object, own(d.json)),
1480
+ raw.length
1481
+ ? {
1482
+ level: 'fail',
1483
+ text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`,
1484
+ code: 'lint.numbers',
1485
+ refs: { file, numbers: raw },
1486
+ }
1487
+ : { level: 'pass', text: 'every measurement is a variable', code: 'lint.numbers', refs: { file } },
1488
+ ...(b.object.role === 'reference'
1489
+ ? [
1490
+ {
1491
+ level: 'pass',
1492
+ text: `a reference (${(await import('@rulecad/printcheck')).bounds(b.triangles).size.map(fmt).join(' × ')} mm), not printed: no print checks`,
1493
+ code: 'print.reference',
1494
+ },
1495
+ ]
1496
+ : await printChecks(b, d)),
1497
+ ...(b.mechanism?.findings || []), // a lamina mechanism's own: it prints free, stops, holds, clears in every state
1498
+ ...(b.fixings || []), // what v.fixings drew: each hole and seat, what it was drawn to and the rule it rests on
1499
+ ...(b.seats || []), // what v.shapes' seat helpers drew (a shaft's bore, a bearing's pocket), as v.fixings's
1500
+ ...(await analyses(b, d, tag)),
1501
+ // what rests on estimates, as an assembly's check says it (an object's check is where one looks first)
1502
+ ...[estimatesFinding([b], { ref: `${d.project}/${d.name}` })]
1503
+ .filter(Boolean)
1504
+ .map(({ short, ...x }) => ({ ...x, card: short })),
1505
+ ],
1506
+ {
1507
+ object: `${d.project}/${d.name}`,
1508
+ title,
1509
+ version,
1510
+ ...(Object.keys(set).length ? { set } : {}),
1511
+ orientation: b.object.orientation,
1512
+ parts: b.parts.map((p) => ({ name: p.name, role: p.role || 'part' })),
1513
+ },
1514
+ );
619
1515
  if (b.object.orientation) say(` orientation: ${b.object.orientation}`);
620
- if (b.parts.length > 1) say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
1516
+ if (b.parts.length > 1)
1517
+ say(` parts: ${b.parts.map((p) => `${p.name}${p.role === 'support' ? ' (support)' : ''}`).join(', ')}`);
621
1518
  process.exitCode = failed ? 1 : 0;
622
1519
  return;
623
1520
  }
624
1521
 
625
1522
  if (cmd === 'animate') {
626
- if (!b.mechanism) throw new Error(`${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`);
1523
+ if (!b.mechanism)
1524
+ throw new Error(
1525
+ `${d.project}/${d.name} isn't a lamina mechanism: cad animate plays the sequence of one made with flexures.lamina()`,
1526
+ );
627
1527
  const out = paths.preview(d.project, `${d.name}${tag}-sequence.svg`);
628
1528
  fs.mkdirSync(path.dirname(out), { recursive: true });
629
- fs.writeFileSync(out, (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, { title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}` }));
1529
+ fs.writeFileSync(
1530
+ out,
1531
+ (await import('../lib/animate.mjs')).sequenceSvg(b.mechanism, {
1532
+ title: `${title} ${version}: ${(b.mechanism.sequence || []).join(', ')}`,
1533
+ }),
1534
+ );
630
1535
  // and the sequence as data (shapes, forces, energies, strains each frame), with a page that plays it
631
- const { playerData, playerHtml } = await import('../lib/player.mjs'), data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
632
- const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`), html = paths.preview(d.project, `${d.name}${tag}-player.html`);
633
- fs.writeFileSync(json, JSON.stringify(data)); fs.writeFileSync(html, playerHtml(data));
634
- console.log(out); console.log(json); return console.log(html);
1536
+ const { playerData, playerHtml } = await import('../lib/player.mjs'),
1537
+ data = playerData(b.mechanism, { title, version, object: `${d.project}/${d.name}` });
1538
+ const json = paths.preview(d.project, `${d.name}${tag}-sequence.json`),
1539
+ html = paths.preview(d.project, `${d.name}${tag}-player.html`);
1540
+ fs.writeFileSync(json, JSON.stringify(data));
1541
+ fs.writeFileSync(html, playerHtml(data));
1542
+ console.log(out);
1543
+ console.log(json);
1544
+ return console.log(html);
635
1545
  }
636
1546
 
637
1547
  if (cmd === 'preview') {
638
1548
  const out = paths.preview(d.project, `${d.name}${tag}${opt('explode') ? '-exploded' : ''}.png`);
639
- const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
640
- const parts = b.parts.length > 1 ? ` · ${b.parts.map((p) => (p.role === 'support' ? `${p.label} (faint)` : p.label)).join(', ')}` : '';
641
- await preview(b.parts, { title: `${title} ${version}${opt('part') ? `: ${b.parts[0].label}` : ''}`, meta: [`${size} mm`, b.object.material].filter(Boolean).join(' · ') + parts, out, explode: !!opt('explode') });
1549
+ const size = (await import('@rulecad/printcheck'))
1550
+ .bounds(b.triangles)
1551
+ .size.map((n) => fmt(n))
1552
+ .join(' × ');
1553
+ const parts =
1554
+ b.parts.length > 1
1555
+ ? ` · ${b.parts.map((p) => (p.role === 'support' ? `${p.label} (faint)` : p.label)).join(', ')}`
1556
+ : '';
1557
+ await preview(b.parts, {
1558
+ title: `${title} ${version}${opt('part') ? `: ${b.parts[0].label}` : ''}`,
1559
+ meta: [`${size} mm`, b.object.material].filter(Boolean).join(' · ') + parts,
1560
+ out,
1561
+ explode: !!opt('explode'),
1562
+ });
642
1563
  return console.log(out);
643
1564
  }
644
1565
 
@@ -646,10 +1567,28 @@ async function main() {
646
1567
  const out = paths.exports(d.project, `${d.name}@${version}${tag}.3mf`);
647
1568
  fs.mkdirSync(path.dirname(out), { recursive: true });
648
1569
  const fil = filaments(d.project); // one object, a part per part, each in its filament
649
- fs.writeFileSync(out, await threemf([{ name: `${d.name}${d.variant ? ` ${d.variant}` : ''}`, parts: b.parts.map((p) => ({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) })) }], { filaments: slots(fil) }));
1570
+ fs.writeFileSync(
1571
+ out,
1572
+ await threemf(
1573
+ [
1574
+ {
1575
+ name: `${d.name}${d.variant ? ` ${d.variant}` : ''}`,
1576
+ parts: b.parts.map((p) => ({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) })),
1577
+ },
1578
+ ],
1579
+ { filaments: slots(fil) },
1580
+ ),
1581
+ );
650
1582
  const notes = filamentNotes(b.parts, fil);
651
1583
  if (opt('open')) openInSlicer(out);
652
- if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, file: path.relative(WS, out), findings: notes }, null, 2)); // (one object: the file is in it, not a line after)
1584
+ if (opt('json'))
1585
+ return console.log(
1586
+ JSON.stringify(
1587
+ { object: `${d.project}/${d.name}`, version, file: path.relative(WS, out), findings: notes },
1588
+ null,
1589
+ 2,
1590
+ ),
1591
+ ); // (one object: the file is in it, not a line after)
653
1592
  report(notes);
654
1593
  return console.log(out);
655
1594
  }
@@ -660,8 +1599,18 @@ async function main() {
660
1599
  const light = b.object.mirror && !opt('part') ? await build(d, set, { mirror: true }) : b; // the object's mirror settings
661
1600
  const shown = pick(light, { forMirror: true }); // the design itself, not what holds it up while printing, nor fine detail
662
1601
  // The rules card: the variables marked show, one line each
663
- const items = b.entries.filter((e) => e.show).slice(0, 6).map((e) => `${e.label || e.name} ${fmt(e.value)} ${e.unit || ''}${e.set ? ' (set)' : ''}`.trim());
664
- await (await target('show'))({ title: `${title} ${version}`, ttl: opt('ttl') || '10m', mesh: { polygons: shown.polygons }, card: { title: `${title} rules`, items } });
1602
+ const items = b.entries
1603
+ .filter((e) => e.show)
1604
+ .slice(0, 6)
1605
+ .map((e) => `${e.label || e.name} ${fmt(e.value)} ${e.unit || ''}${e.set ? ' (set)' : ''}`.trim());
1606
+ await (
1607
+ await target('show')
1608
+ )({
1609
+ title: `${title} ${version}`,
1610
+ ttl: opt('ttl') || '10m',
1611
+ mesh: { polygons: shown.polygons },
1612
+ card: { title: `${title} rules`, items },
1613
+ });
665
1614
  return await printLinks(await links(d, b, set));
666
1615
  }
667
1616
 
@@ -676,97 +1625,316 @@ async function main() {
676
1625
  // keeping the file's layout; refused if the variables wouldn't resolve
677
1626
  async function editVariables(ref) {
678
1627
  const pairs = positional().slice(2);
679
- if (!ref || !pairs.length || pairs.some((p) => !p.includes('='))) throw new Error('usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]');
680
- const extra = Object.fromEntries(['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]));
681
- if (pairs.length > 1 && (extra.rule || extra.label)) throw new Error(`--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`);
682
- const changes = Object.fromEntries(pairs.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), { value: parseValue(p.slice(i + 1).trim()), ...extra }]; }));
1628
+ if (!ref || !pairs.length || pairs.some((p) => !p.includes('=')))
1629
+ throw new Error(
1630
+ 'usage: cad set <project>/<object> name=value [name=value …] [--unit mm] [--rule "why"] [--label "Label"] [--new]',
1631
+ );
1632
+ const extra = Object.fromEntries(
1633
+ ['unit', 'rule', 'label'].filter((k) => typeof opt(k) === 'string').map((k) => [k, opt(k)]),
1634
+ );
1635
+ if (pairs.length > 1 && (extra.rule || extra.label))
1636
+ throw new Error(
1637
+ `--${extra.rule ? 'rule' : 'label'} describes one variable: set ${pairs.map((p) => p.split('=')[0]).join(' and ')} one at a time`,
1638
+ );
1639
+ // each value read by its variable's kind: text stays as typed (a legend 007), a number where the variable is one
1640
+ const vars = readObject(locate(ref)).variables || {};
1641
+ const changes = Object.fromEntries(
1642
+ pairs.map((p) => {
1643
+ const i = p.indexOf('='),
1644
+ name = p.slice(0, i).trim();
1645
+ return [
1646
+ name,
1647
+ { value: valueFor(Object.hasOwn(vars, name) ? vars[name] : undefined, p.slice(i + 1).trim()), ...extra },
1648
+ ];
1649
+ }),
1650
+ );
683
1651
  const r = await setVariables(ref, changes, { create: !!opt('new'), dryRun: !!opt('dry-run') });
684
1652
  if (opt('json')) return console.log(JSON.stringify(r));
685
1653
  console.log(`${r.dryRun ? `dry run, nothing written: would set` : 'set'} ${r.changed.join(', ')} in ${rel(r.file)}`);
686
1654
  }
687
1655
 
1656
+ // cad add item --object tray --set legend=007: each value read by the object's variable's kind, as cad set reads it
1657
+ // (text stays as typed); an object that can't be read yet leaves the values as parseValue reads them
1658
+ function itemSet(ref) {
1659
+ let vars = {};
1660
+ try {
1661
+ if (typeof opt('object') === 'string')
1662
+ vars = readObject(locateIn(ref.split('/')[0], String(opt('object')).split(/[:@]/)[0])).variables || {};
1663
+ } catch {
1664
+ // (no such object: cad add names it when it checks the item)
1665
+ }
1666
+ return Object.fromEntries(
1667
+ Object.entries(sets()).map(([k, v]) => [k, valueFor(Object.hasOwn(vars, k) ? vars[k] : undefined, v)]),
1668
+ );
1669
+ }
1670
+
688
1671
  // cad add fit|joint|item|loop|pose|fasten|join <project>/<assembly> --key value …: add to an assembly, keeping its layout
689
1672
  async function editAssembly(what, ref) {
690
- const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
691
- const pick = (keys) => Object.fromEntries(keys.map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined]).filter(([, v]) => v !== undefined));
692
- const text = (keys) => Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
1673
+ const list = (k) =>
1674
+ typeof opt(k) === 'string'
1675
+ ? opt(k)
1676
+ .split(',')
1677
+ .map((x) => parseValue(x.trim()))
1678
+ : undefined;
1679
+ const pick = (keys) =>
1680
+ Object.fromEntries(
1681
+ keys
1682
+ .map((k) => [k, typeof opt(k) === 'string' ? parseValue(opt(k)) : undefined])
1683
+ .filter(([, v]) => v !== undefined),
1684
+ );
1685
+ const text = (keys) =>
1686
+ Object.fromEntries(keys.filter((k) => typeof opt(k) === 'string').map((k) => [k, String(opt(k))]));
693
1687
  // (an item's at is a point, 1,2,3, or an address on a beam: --at x1.top@50%)
694
- const at = () => (typeof opt('at') !== 'string' ? {} : /^[a-z][\w-]*\./i.test(opt('at')) ? { at: String(opt('at')) } : { at: list('at') });
1688
+ const at = () =>
1689
+ typeof opt('at') !== 'string'
1690
+ ? {}
1691
+ : /^[a-z][\w-]*\./i.test(opt('at'))
1692
+ ? { at: String(opt('at')) }
1693
+ : { at: list('at') };
695
1694
  let entry;
696
- if (what === 'fit') entry = { ...text(['a', 'b']), ...pick(['min', 'max']), ...(list('poses') ? { poses: list('poses').map(String) } : {}), ...text(['note', 'label']) };
697
- else if (what === 'joint') entry = { ...text(['id', 'type', 'parent', 'child', 'label', 'follow']), ...pick(['min', 'max', 'value', 'ratio']) };
1695
+ if (what === 'fit')
1696
+ entry = {
1697
+ ...text(['a', 'b']),
1698
+ ...pick(['min', 'max']),
1699
+ ...(list('poses') ? { poses: list('poses').map(String) } : {}),
1700
+ ...text(['note', 'label']),
1701
+ };
1702
+ else if (what === 'joint')
1703
+ entry = {
1704
+ ...text(['id', 'type', 'parent', 'child', 'label', 'follow']),
1705
+ ...pick(['min', 'max', 'value', 'ratio']),
1706
+ };
698
1707
  else if (what === 'beam') {
699
- if (typeof opt('profile') !== 'string') throw new Error('usage: cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90] [--length 300] [--material al6063-t5], or --length 300 --at 0,0,0 --rotate 0,90,0');
700
- entry = { ...text(['id']), beam: { profile: String(opt('profile')), ...pick(['length']), ...text(['material']) }, ...(list('from') ? { from: list('from') } : {}), ...(list('to') ? { to: list('to') } : {}), ...pick(['roll']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}) };
701
- } else if (what === 'item') entry = { ...text(['id', 'object', 'assembly', 'variant']), ...at(), ...(list('rotate') ? { rotate: list('rotate') } : {}),
702
- ...(typeof opt('set') === 'string' ? { set: Object.fromEntries(sets() && Object.entries(sets()).map(([k, v]) => [k, parseValue(v)])) } : {}) };
1708
+ if (typeof opt('profile') !== 'string')
1709
+ throw new Error(
1710
+ 'usage: cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0 [--roll 90] [--length 300] [--material al6063-t5], or --length 300 --at 0,0,0 --rotate 0,90,0',
1711
+ );
1712
+ entry = {
1713
+ ...text(['id']),
1714
+ beam: { profile: String(opt('profile')), ...pick(['length']), ...text(['material']) },
1715
+ ...(list('from') ? { from: list('from') } : {}),
1716
+ ...(list('to') ? { to: list('to') } : {}),
1717
+ ...pick(['roll']),
1718
+ ...at(),
1719
+ ...(list('rotate') ? { rotate: list('rotate') } : {}),
1720
+ };
1721
+ } else if (what === 'item')
1722
+ entry = {
1723
+ ...text(['id', 'object', 'assembly', 'variant']),
1724
+ ...at(),
1725
+ ...(list('rotate') ? { rotate: list('rotate') } : {}),
1726
+ ...(typeof opt('set') === 'string' ? { set: itemSet(ref) } : {}),
1727
+ };
703
1728
  else if (what === 'loop') entry = text(['a', 'b', 'label']);
704
- else if (what === 'fasten' && opt('from-fits')) { // a holes fit and a fit that fastens, put as one fasten
705
- const s = await buildAssembly(ref), { fastenFromFits } = await import('../lib/fasten.mjs');
706
- const r = fastenFromFitsEdit(ref, fastenFromFits(s), { screw: typeof opt('screw') === 'string' ? opt('screw') : undefined, dryRun: !!opt('dry-run') });
1729
+ else if (what === 'fasten' && opt('from-fits')) {
1730
+ // a holes fit and a fit that fastens, put as one fasten
1731
+ const s = await buildAssembly(ref),
1732
+ { fastenFromFits } = await import('../lib/fasten.mjs');
1733
+ const r = fastenFromFitsEdit(ref, fastenFromFits(s), {
1734
+ screw: typeof opt('screw') === 'string' ? opt('screw') : undefined,
1735
+ dryRun: !!opt('dry-run'),
1736
+ });
707
1737
  if (opt('json')) return console.log(JSON.stringify(r));
708
1738
  if (r.dryRun) console.log('dry run, nothing written:');
709
- for (const x of r.added) console.log(`${r.dryRun ? 'would add' : 'added'} a fasten to ${rel(r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`);
1739
+ for (const x of r.added)
1740
+ console.log(
1741
+ `${r.dryRun ? 'would add' : 'added'} a fasten to ${rel(r.file)} in place of its holes fit and its fit that fastens: ${JSON.stringify(x)}`,
1742
+ );
710
1743
  return console.log(`check its screws: cad check ${ref}`);
711
- }
712
- else if (what === 'fasten') { // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
713
- const names = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => x.trim()).filter(Boolean) : undefined);
714
- entry = { ...text(['screw']), through: names('through') ?? [], ...text(['into']), ...(names('at') ? { at: names('at') } : {}), ...text(['holes']), ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}), ...(opt('washer') ? { washer: true } : {}), ...pick(['length', 'torque']), ...text(['note']) };
715
- }
716
- else if (what === 'join') entry = text(['kind', 'a', 'b', 'fitting', 'screw', 'note']);
1744
+ } else if (what === 'fasten') {
1745
+ // --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2 | --holes bracket.body [--nut [hex] --washer --length 12 --torque 0.5 --note …]
1746
+ const names = (k) =>
1747
+ typeof opt(k) === 'string'
1748
+ ? opt(k)
1749
+ .split(',')
1750
+ .map((x) => x.trim())
1751
+ .filter(Boolean)
1752
+ : undefined;
1753
+ entry = {
1754
+ ...text(['screw']),
1755
+ through: names('through') ?? [],
1756
+ ...text(['into']),
1757
+ ...(names('at') ? { at: names('at') } : {}),
1758
+ ...text(['holes']),
1759
+ ...(opt('nut') ? { nut: opt('nut') === true ? true : String(opt('nut')) } : {}),
1760
+ ...(opt('washer') ? { washer: true } : {}),
1761
+ ...pick(['length', 'torque']),
1762
+ ...text(['note']),
1763
+ };
1764
+ } else if (what === 'join') entry = text(['kind', 'a', 'b', 'fitting', 'screw', 'note']);
717
1765
  else if (what === 'pose') {
718
1766
  const pairs = positional().slice(3);
719
- if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
720
- entry = { name: opt('name'), values: Object.fromEntries(pairs.map((p) => { const [k, v] = p.split('='); return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)]; })) };
1767
+ if (typeof opt('name') !== 'string' || !pairs.length)
1768
+ throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
1769
+ entry = {
1770
+ name: opt('name'),
1771
+ values: Object.fromEntries(
1772
+ pairs.map((p) => {
1773
+ const [k, v] = p.split('=');
1774
+ return [k.trim(), v.includes(',') ? v.split(',').map(parseValue) : parseValue(v)];
1775
+ }),
1776
+ ),
1777
+ };
721
1778
  } else if (what === 'load') entry = { ...text(['joint']), ...pick(['mass', 'torque']), ...at(), ...text(['note']) };
722
1779
  else if (what === 'guide' || what === 'wire') entry = { ...text(['id', 'kind', 'note']) };
723
- else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]');
1780
+ else
1781
+ throw new Error(
1782
+ 'usage: cad add fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]',
1783
+ );
724
1784
  // field=value pairs, for any field (nested by dots: motor.model=nema17), over the options
725
- if (what !== 'pose') for (const [k, v] of pairsOf(positional().slice(3), 'cad add')) { const keys = k.split('.'); let o = entry; for (const x of keys.slice(0, -1)) o = (o[x] ??= {}); o[keys.at(-1)] = v; }
1785
+ if (what !== 'pose')
1786
+ for (const [k, v] of pairsOf(positional().slice(3), 'cad add')) {
1787
+ const keys = k.split('.');
1788
+ let o = entry;
1789
+ for (const x of keys.slice(0, -1)) o = o[x] ??= {};
1790
+ o[keys.at(-1)] = v;
1791
+ }
726
1792
  const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry, { dryRun: !!opt('dry-run') });
727
- edited(r, 'add', { added: entry }, `${opt('dry-run') ? 'would add' : 'added'} ${/^[aeiou]/.test(what) ? 'an' : 'a'} ${what} to ${rel(r.file)} (${r.changes[0].path})`);
1793
+ edited(
1794
+ r,
1795
+ 'add',
1796
+ { added: entry },
1797
+ `${opt('dry-run') ? 'would add' : 'added'} ${/^[aeiou]/.test(what) ? 'an' : 'a'} ${what} to ${rel(r.file)} (${r.changes[0].path})`,
1798
+ );
728
1799
  }
729
1800
 
730
1801
  // name=value pairs from the command line, each value as cad set takes it; refused by name where one has no =
731
1802
  function pairsOf(list, what) {
732
1803
  const bad = list.find((p) => !p.includes('='));
733
1804
  if (bad) throw new Error(`${what}: "${bad}" isn't field=value`);
734
- return list.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), parseSetting(p.slice(i + 1))]; });
1805
+ return list.map((p) => {
1806
+ const i = p.indexOf('=');
1807
+ return [p.slice(0, i).trim(), parseSetting(p.slice(i + 1))];
1808
+ });
735
1809
  }
736
1810
  const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
737
- const shownValue = (v) => (v === undefined ? 'nothing' : JSON.stringify(v).length > 70 ? `${JSON.stringify(v).slice(0, 67)}...` : JSON.stringify(v));
1811
+ const shownValue = (v) =>
1812
+ v === undefined
1813
+ ? 'nothing'
1814
+ : JSON.stringify(v).length > 70
1815
+ ? `${JSON.stringify(v).slice(0, 67)}...`
1816
+ : JSON.stringify(v);
738
1817
  // What an edit did, as words or as data (--json): its changes, then its checks
739
1818
  function edited(r, command, extra = {}, head = null) {
740
- if (opt('json')) return console.log(JSON.stringify({ command, file: rel(r.file), written: r.written, ...(r.dryRun ? { dryRun: true } : {}), ...(r.made ? { made: r.made.map(rel) } : {}), ...extra, changes: r.changes, findings: r.findings }, null, 2));
741
- const verb = { set: 'set', add: 'added', remove: 'removed', make: 'made' }, would = r.dryRun ? 'would be ' : '';
742
- console.log(`${r.dryRun ? 'dry run, nothing written: ' : ''}${head ?? `${rel(r.file)}${r.dryRun || r.written ? '' : ' (no change)'}`}`);
743
- if (!head) for (const c of r.changes) console.log(` ${would}${verb[c.op]} ${c.path}${c.op === 'set' ? `: ${shownValue(c.before)} → ${shownValue(c.after)}` : c.op === 'add' ? `: ${shownValue(c.after)}` : c.because ? ` (it ${c.because})` : ''}`);
1819
+ if (opt('json'))
1820
+ return console.log(
1821
+ JSON.stringify(
1822
+ {
1823
+ command,
1824
+ file: rel(r.file),
1825
+ written: r.written,
1826
+ ...(r.dryRun ? { dryRun: true } : {}),
1827
+ ...(r.made ? { made: r.made.map(rel) } : {}),
1828
+ ...extra,
1829
+ changes: r.changes,
1830
+ findings: r.findings,
1831
+ },
1832
+ null,
1833
+ 2,
1834
+ ),
1835
+ );
1836
+ const verb = { set: 'set', add: 'added', remove: 'removed', make: 'made' },
1837
+ would = r.dryRun ? 'would be ' : '';
1838
+ console.log(
1839
+ `${r.dryRun ? 'dry run, nothing written: ' : ''}${head ?? `${rel(r.file)}${r.dryRun || r.written ? '' : ' (no change)'}`}`,
1840
+ );
1841
+ if (!head)
1842
+ for (const c of r.changes)
1843
+ console.log(
1844
+ ` ${would}${verb[c.op]} ${c.path}${c.op === 'set' ? `: ${shownValue(c.before)} → ${shownValue(c.after)}` : c.op === 'add' ? `: ${shownValue(c.after)}` : c.because ? ` (it ${c.because})` : ''}`,
1845
+ );
744
1846
  report(r.findings);
745
1847
  }
746
1848
 
747
1849
  // cad new <project> [--title --description --material --printer], cad new <project>/<assembly> --assembly [--frame ...]
748
1850
  async function newCommand(ref) {
749
- const dryRun = !!opt('dry-run'), str = (k) => (typeof opt(k) === 'string' ? opt(k) : undefined);
750
- if (!ref) throw new Error('usage: cad new <project>/<object>, cad new <project>, or cad new <project>/<assembly> --assembly');
751
- if (!ref.includes('/')) return edited(newProject(ref, { title: str('title'), description: str('description'), material: str('material'), printer: str('printer'), dryRun }), 'new');
1851
+ const dryRun = !!opt('dry-run'),
1852
+ str = (k) => (typeof opt(k) === 'string' ? opt(k) : undefined);
1853
+ if (!ref)
1854
+ throw new Error('usage: cad new <project>/<object>, cad new <project>, or cad new <project>/<assembly> --assembly');
1855
+ if (!ref.includes('/'))
1856
+ return edited(
1857
+ newProject(ref, {
1858
+ title: str('title'),
1859
+ description: str('description'),
1860
+ material: str('material'),
1861
+ printer: str('printer'),
1862
+ dryRun,
1863
+ }),
1864
+ 'new',
1865
+ );
752
1866
  let frame;
753
1867
  // the frame's options go with --frame, and a join's fitting and screw with --join: none is dropped unsaid
754
- const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'feet', 'caps'], loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
755
- if (!opt('frame') && loose.length) throw new Error(`--${loose.join(', --')} ${loose.length === 1 ? 'is a frame option' : 'are frame options'}: give --frame box|portal|table|gantry|shelf with ${loose.length === 1 ? 'it' : 'them'}, or set the fields after with cad set ${ref} frame.<field>=…`);
756
- if (opt('frame') && !str('join') && (str('fitting') || str('screw'))) throw new Error(`--${['fitting', 'screw'].filter((k) => str(k)).join(' and --')} ${str('fitting') && str('screw') ? 'say' : 'says'} how the join is made: give the join's kind with ${str('fitting') && str('screw') ? 'them' : 'it'}, as --join blind`);
1868
+ const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'estimate', 'feet', 'caps'],
1869
+ loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
1870
+ if (!opt('frame') && loose.length)
1871
+ throw new Error(
1872
+ `--${loose.join(', --')} ${loose.length === 1 ? 'is a frame option' : 'are frame options'}: give --frame box|portal|table|gantry|shelf with ${loose.length === 1 ? 'it' : 'them'}, or set the fields after with cad set ${ref} frame.<field>=…`,
1873
+ );
1874
+ const how = ['fitting', 'screw', 'estimate'].filter((k) => opt(k) !== undefined);
1875
+ if (opt('frame') && !str('join') && how.length)
1876
+ throw new Error(
1877
+ `--${how.join(' and --')} ${how.length > 1 ? 'say' : 'says'} how the join is made: give the join's kind with ${how.length > 1 ? 'them' : 'it'}, as --join blind`,
1878
+ );
757
1879
  if (opt('frame')) {
758
- const nums = (k) => (str(k) ? str(k).split(',').map((x) => parseValue(x.trim())) : undefined);
759
- const join = str('join') && (str('fitting') || str('screw')) ? { kind: str('join'), ...(str('fitting') ? { fitting: str('fitting') } : {}), ...(str('screw') ? { screw: str('screw') } : {}) } : str('join');
760
- frame = Object.fromEntries(Object.entries({ kind: str('frame'), inside: nums('inside'), outside: nums('outside'), profile: str('profile'), join, feet: str('feet'), caps: str('caps') != null ? parseSetting(str('caps')) : undefined }).filter(([, v]) => v !== undefined));
761
- if (opt('frame') === true || !frame.profile || (!frame.inside && !frame.outside)) throw new Error('usage: cad new <project>/<assembly> --assembly --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set> [--join blind] [--feet levelling]');
1880
+ // a size is numbers in mm, one for each of the frame's sides, as 300,300,350
1881
+ const nums = (k) => {
1882
+ if (opt(k) === undefined) return undefined;
1883
+ const v = str(k)
1884
+ ?.split(',')
1885
+ .map((x) => parseValue(x.trim()));
1886
+ if (!v?.length || !v.every((x) => typeof x === 'number' && Number.isFinite(x)))
1887
+ throw new Error(
1888
+ `--${k} is numbers in mm, the frame's width, depth and height, as --${k} 300,300,350 (a portal's width and height, as 500,400) (got ${JSON.stringify(opt(k))})`,
1889
+ );
1890
+ return v;
1891
+ };
1892
+ const join =
1893
+ str('join') && how.length
1894
+ ? {
1895
+ kind: str('join'),
1896
+ ...(str('fitting') ? { fitting: str('fitting') } : {}),
1897
+ ...(str('screw') ? { screw: str('screw') } : {}),
1898
+ ...(opt('estimate') ? { estimate: true } : {}),
1899
+ }
1900
+ : str('join');
1901
+ frame = Object.fromEntries(
1902
+ Object.entries({
1903
+ kind: str('frame'),
1904
+ inside: nums('inside'),
1905
+ outside: nums('outside'),
1906
+ profile: str('profile'),
1907
+ join,
1908
+ feet: str('feet'),
1909
+ caps: str('caps') != null ? parseSetting(str('caps')) : undefined,
1910
+ }).filter(([, v]) => v !== undefined),
1911
+ );
1912
+ if (opt('frame') === true || !frame.profile || (!frame.inside && !frame.outside))
1913
+ throw new Error(
1914
+ 'usage: cad new <project>/<assembly> --assembly --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set> [--join blind] [--feet levelling]',
1915
+ );
762
1916
  }
763
- edited(newAssembly(ref, { title: str('title'), kind: str('kind'), description: str('description'), frame, fields: Object.fromEntries(pairsOf(positional().slice(2), 'cad new')), project: { material: str('material'), printer: str('printer') }, dryRun }), 'new');
1917
+ edited(
1918
+ newAssembly(ref, {
1919
+ title: str('title'),
1920
+ kind: str('kind'),
1921
+ description: str('description'),
1922
+ frame,
1923
+ fields: Object.fromEntries(pairsOf(positional().slice(2), 'cad new')),
1924
+ project: { material: str('material'), printer: str('printer') },
1925
+ dryRun,
1926
+ }),
1927
+ 'new',
1928
+ );
764
1929
  }
765
1930
 
766
1931
  // cad set <project>/<assembly> <address>=<value> …
767
1932
  function editFields(ref) {
768
1933
  const pairs = pairsOf(positional().slice(2), 'cad set');
769
- if (!pairs.length) throw new Error(`usage: cad set ${ref} <address>=<value> … (x1.at=[0,0,20], joins.0.kind=bracket, frame.join.fitting=printed)`);
1934
+ if (!pairs.length)
1935
+ throw new Error(
1936
+ `usage: cad set ${ref} <address>=<value> … (x1.at=[0,0,20], joins.0.kind=bracket, frame.join.fitting=printed)`,
1937
+ );
770
1938
  edited(setInAssembly(ref, Object.fromEntries(pairs), { dryRun: !!opt('dry-run') }), 'set');
771
1939
  }
772
1940
  // cad set <project> field=value …
@@ -777,34 +1945,89 @@ function editProject(project) {
777
1945
  }
778
1946
  // cad remove <project>/<assembly> <address> [--with-refs], cad move <project>/<assembly> <id> --at | --to [--rotate]
779
1947
  function removeOrMove(cmd, ref, what) {
780
- if (!what || !isAssembly(ref)) throw new Error(`usage: cad ${cmd} ${USAGE[cmd]}${ref && !isAssembly(ref) ? ` (there is no assembly ${ref})` : ''}`);
781
- if (cmd === 'remove') return edited(removeFromAssembly(ref, what, { withRefs: !!opt('with-refs'), dryRun: !!opt('dry-run') }), 'remove');
782
- const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
1948
+ if (!what || !isAssembly(ref))
1949
+ throw new Error(
1950
+ `usage: cad ${cmd} ${USAGE[cmd]}${ref && !isAssembly(ref) ? ` (there is no assembly ${ref})` : ''}`,
1951
+ );
1952
+ if (cmd === 'remove')
1953
+ return edited(removeFromAssembly(ref, what, { withRefs: !!opt('with-refs'), dryRun: !!opt('dry-run') }), 'remove');
1954
+ const list = (k) =>
1955
+ typeof opt(k) === 'string'
1956
+ ? opt(k)
1957
+ .split(',')
1958
+ .map((x) => parseValue(x.trim()))
1959
+ : undefined;
783
1960
  const at = typeof opt('at') !== 'string' ? undefined : opt('at').includes(',') ? list('at') : parseValue(opt('at'));
784
- edited(moveInAssembly(ref, what, { at, to: typeof opt('to') === 'string' ? opt('to') : undefined, rotate: list('rotate'), dryRun: !!opt('dry-run') }), 'move');
1961
+ edited(
1962
+ moveInAssembly(ref, what, {
1963
+ at,
1964
+ to: typeof opt('to') === 'string' ? opt('to') : undefined,
1965
+ rotate: list('rotate'),
1966
+ dryRun: !!opt('dry-run'),
1967
+ }),
1968
+ 'move',
1969
+ );
785
1970
  }
786
1971
 
787
1972
  // cad why <project>/<object>.<name>: the value, and what it reads, down to the rules (estimates marked)
788
1973
  async function explainValue(ref) {
789
1974
  const m = /^([^/]+\/[^.]+)\.(.+)$/.exec(ref || '');
790
- if (!m) throw new Error('usage: cad why <project>/<object>.<variable> (or .<set>.<rule>), e.g. cad why keyboard/case.depth');
1975
+ if (!m)
1976
+ throw new Error(
1977
+ 'usage: cad why <project>/<object>.<variable> (or .<set>.<rule>), e.g. cad why keyboard/case.depth',
1978
+ );
791
1979
  const tree = await why(m[1], m[2], { depth: Number(opt('depth')) || 12 });
792
1980
  if (opt('json')) return console.log(JSON.stringify(tree, null, 2));
793
1981
  const line = (n, pad) => {
794
1982
  const about = n.kind ? ` [${n.kind === 'estimate' ? 'ESTIMATE' : n.kind}${n.source ? `: ${n.source}` : ''}]` : '';
795
1983
  const where = n.via ? ` (${n.object})` : '';
796
- console.log(`${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`);
1984
+ console.log(
1985
+ `${pad}${n.name} = ${fmt(n.value)}${n.unit ? ` ${n.unit}` : ''}${n.expr ? ` = ${n.expr}` : ''}${where}${n.seen ? ' (above)' : ''}${about}`,
1986
+ );
797
1987
  if (!n.seen && n.rule && !pad) console.log(` ${n.rule}`);
798
- if (n.problem) { // the result a problem variable picks, and what it is made from
799
- const q = n.problem, vals = Object.entries(q.variables);
800
- console.log(`${pad} optimised from ${q.file}: ${q.title}, ${q.material}${q.set ? `, with ${Object.entries(q.set).map(([k, v]) => `${k} = ${v}`).join(', ')}` : ''}`);
1988
+ if (n.problem) {
1989
+ // the result a problem variable picks, and what it is made from
1990
+ const q = n.problem,
1991
+ vals = Object.entries(q.variables);
1992
+ console.log(
1993
+ `${pad} optimised from ${q.file}: ${q.title}, ${q.material}${
1994
+ q.set
1995
+ ? `, with ${Object.entries(q.set)
1996
+ .map(([k, v]) => `${k} = ${v}`)
1997
+ .join(', ')}`
1998
+ : ''
1999
+ }`,
2000
+ );
801
2001
  console.log(`${pad} rule sets: ${q.uses.join(', ')}`);
802
- if (vals.length) console.log(`${pad} its values: ${vals.map(([k, v]) => `${k} = ${typeof v === 'number' ? fmt(v) : v}`).join(', ')}`);
2002
+ if (vals.length)
2003
+ console.log(
2004
+ `${pad} its values: ${vals.map(([k, v]) => `${k} = ${typeof v === 'number' ? fmt(v) : v}`).join(', ')}`,
2005
+ );
803
2006
  if (q.parts.length) console.log(`${pad} parts read: ${q.parts.join(', ')}`);
804
- if (q.assembly) { const A = q.assembly, bits = [...(A.joints.length ? [`joints read: ${A.joints.map((j) => `${j.joint} at (${j.at.map(fmt).join(', ')})`).join(', ')}`] : []), ...(A.sweeps.length ? [`swept: ${A.sweeps.map((w) => `${w.sweep} through ${w.through}, ${fmt(w.from)} to ${fmt(w.to)} in ${w.steps} steps`).join(', ')}`] : [])]; console.log(`${pad} in the assembly ${A.name}, item ${A.item}${A.pose ? `, pose ${A.pose}` : ''}${bits.length ? `: ${bits.join('; ')}` : ''}`); }
805
- if (q.anchors.length) console.log(`${pad} anchors read: ${q.anchors.map((a) => `${a.anchor} at (${a.at.map(fmt).join(', ')})`).join(', ')}`);
2007
+ if (q.assembly) {
2008
+ const A = q.assembly,
2009
+ bits = [
2010
+ ...(A.joints.length
2011
+ ? [`joints read: ${A.joints.map((j) => `${j.joint} at (${j.at.map(fmt).join(', ')})`).join(', ')}`]
2012
+ : []),
2013
+ ...(A.sweeps.length
2014
+ ? [
2015
+ `swept: ${A.sweeps.map((w) => `${w.sweep} through ${w.through}, ${fmt(w.from)} to ${fmt(w.to)} in ${w.steps} steps`).join(', ')}`,
2016
+ ]
2017
+ : []),
2018
+ ];
2019
+ console.log(
2020
+ `${pad} in the assembly ${A.name}, item ${A.item}${A.pose ? `, pose ${A.pose}` : ''}${bits.length ? `: ${bits.join('; ')}` : ''}`,
2021
+ );
2022
+ }
2023
+ if (q.anchors.length)
2024
+ console.log(
2025
+ `${pad} anchors read: ${q.anchors.map((a) => `${a.anchor} at (${a.at.map(fmt).join(', ')})`).join(', ')}`,
2026
+ );
806
2027
  console.log(`${pad} filter ${fmt(q.filter.value)} mm: ${q.filter.from}`);
807
- console.log(`${pad} ${q.made ? `kept in ${q.densities}` : `not made yet (cad optimise ${n.object.split('/')[0]}/${q.problem}); it will be kept in ${q.densities}`}: made again only when one of these, or the solver, changes`);
2028
+ console.log(
2029
+ `${pad} ${q.made ? `kept in ${q.densities}` : `not made yet (cad optimise ${n.object.split('/')[0]}/${q.problem}); it will be kept in ${q.densities}`}: made again only when one of these, or the solver, changes`,
2030
+ );
808
2031
  }
809
2032
  for (const c of n.reads || []) line(c, `${pad} `);
810
2033
  };
@@ -812,21 +2035,53 @@ async function explainValue(ref) {
812
2035
  }
813
2036
 
814
2037
  async function board(cmd, d, b, { title, version, tag }) {
815
- const pcb = await pcbEngine(), name = `${d.name}@${version}${tag}`;
2038
+ const pcb = await pcbEngine(),
2039
+ name = `${d.name}@${version}${tag}`;
816
2040
  if (cmd === 'check') {
817
2041
  say(`${title} ${version}`);
818
- const raw = lint(fs.readFileSync(d.js, 'utf8'));
2042
+ const raw = lint(readOwnText(d.js));
819
2043
  // The files first: the object's JSON, and the workspace's own rule sets it uses, against their schemas
820
- const own = (f) => path.relative(WS, f), ruleFiles = (b.object.uses || []).filter((u) => !u.includes('/')).map((u) => path.join(WS, 'rules', `${u}.json`)).filter((f) => fs.existsSync(f));
821
- const problemFiles = [...new Set([...Object.values(b.object.variables || {}).filter((v) => v.type === 'problem').flatMap((v) => v.choice || [v.value]), ...(b.object.analysis || []).map((a) => a.problem)].map((n) => problemFile(d.project, String(n).split(':')[0])))].filter((f) => fs.existsSync(f));
822
- const schemaProblems = [...schemaFindings(JSON.parse(fs.readFileSync(d.json, 'utf8')), 'object', own(d.json)), ...ruleFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'rules', own(f))),
823
- ...problemFiles.flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'problem', own(f)))];
824
- const failed = report([
825
- ...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
826
- ...(b.units || []).map((u) => ({ level: 'warn', text: `units: ${u.message}`, code: 'units', refs: { file: own(d.json), path: u.path, variable: u.name } })),
827
- raw.length ? { level: 'fail', text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}` } : { level: 'pass', text: 'every measurement is a variable' },
828
- ...(await pcb.checks(b.circuit, b.values, b.matrix, b.source)),
829
- ], { object: `${d.project}/${d.name}`, title, version });
2044
+ const own = (f) => path.relative(WS, f),
2045
+ ruleFiles = (b.object.uses || [])
2046
+ .filter((u) => !u.includes('/'))
2047
+ .map((u) => path.join(WS, 'rules', `${u}.json`))
2048
+ .filter((f) => fs.existsSync(f));
2049
+ const problemFiles = [
2050
+ ...new Set(
2051
+ [
2052
+ ...Object.values(b.object.variables || {})
2053
+ .filter((v) => v.type === 'problem')
2054
+ .flatMap((v) => v.choice || [v.value]),
2055
+ ...(b.object.analysis || []).map((a) => a.problem),
2056
+ ].map((n) => problemFile(d.project, String(n).split(':')[0])),
2057
+ ),
2058
+ ].filter((f) => fs.existsSync(f));
2059
+ const schemaProblems = [
2060
+ ...schemaFindings(readJson(d.json), 'object', own(d.json)),
2061
+ ...ruleFiles.flatMap((f) => schemaFindings(readJson(f), 'rules', own(f))),
2062
+ ...problemFiles.flatMap((f) => schemaFindings(readJson(f), 'problem', own(f))),
2063
+ ];
2064
+ const failed = report(
2065
+ [
2066
+ ...(schemaProblems.length
2067
+ ? schemaProblems
2068
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
2069
+ ...(b.units || []).map((u) => ({
2070
+ level: 'warn',
2071
+ text: `units: ${u.message}`,
2072
+ code: 'units',
2073
+ refs: { file: own(d.json), path: u.path, variable: u.name },
2074
+ })),
2075
+ raw.length
2076
+ ? {
2077
+ level: 'fail',
2078
+ text: `numbers in ${path.basename(d.js)} that should be variables: ${raw.map((r) => `line ${r.line}: ${r.text}`).join(', ')}`,
2079
+ }
2080
+ : { level: 'pass', text: 'every measurement is a variable' },
2081
+ ...(await boardChecks(b, d)),
2082
+ ],
2083
+ { object: `${d.project}/${d.name}`, title, version },
2084
+ );
830
2085
  if (b.object.orientation) say(` ${b.object.orientation}`);
831
2086
  process.exitCode = failed ? 1 : 0;
832
2087
  return;
@@ -834,22 +2089,46 @@ async function board(cmd, d, b, { title, version, tag }) {
834
2089
  if (cmd === 'preview') {
835
2090
  const top = await pcb.png(b.circuit, paths.preview(d.project, `${d.name}${tag}-pcb.png`));
836
2091
  const sch = await pcb.schematicPng(b.circuit, paths.preview(d.project, `${d.name}${tag}-schematic.png`));
837
- const size = (await import('@rulecad/printcheck')).bounds(b.triangles).size.map((n) => fmt(n)).join(' × ');
2092
+ const size = (await import('@rulecad/printcheck'))
2093
+ .bounds(b.triangles)
2094
+ .size.map((n) => fmt(n))
2095
+ .join(' × ');
838
2096
  const out = paths.preview(d.project, `${d.name}${tag}.png`);
839
2097
  await preview(b.parts, { title: `${title} ${version}`, meta: `${size} mm · a circuit board`, out, explode: false });
840
2098
  return console.log(`${top}\n${sch}\n${out}`);
841
2099
  }
842
2100
  // export: exports/<project>/<name>-fab.zip (Gerbers, drills, BOM, placement: upload it to JLCPCB as it is), KiCad's
843
2101
  // board and schematic beside it, and the matrix for firmware
844
- const dir = paths.exports(d.project), { zip: zipOf } = await import('@rulecad/model-link');
2102
+ const dir = paths.exports(d.project),
2103
+ { zip: zipOf } = await import('@rulecad/model-link');
845
2104
  fs.mkdirSync(dir, { recursive: true });
846
- const fab = await pcb.fabFiles(b.circuit, d.name, { source: b.source }), zip = path.join(dir, `${name}-fab.zip`);
2105
+ const fab = await pcb.fabFiles(b.circuit, d.name, { source: b.source }),
2106
+ zip = path.join(dir, `${name}-fab.zip`);
847
2107
  fs.writeFileSync(zip, await zipOf(Object.entries(fab)));
848
2108
  const written = [zip];
849
- for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name, { source: b.source }))) { fs.writeFileSync(path.join(dir, f), t); written.push(path.join(dir, f)); }
850
- if (b.matrix) { const f = path.join(dir, `${name}-matrix.json`); fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n'); written.push(f); }
851
- const done = [{ level: 'pass', text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)` }];
852
- if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, version, files: written.map((f) => path.relative(WS, f)), findings: done }, null, 2));
2109
+ for (const [f, t] of Object.entries(await pcb.kicadFiles(b.circuit, name, { source: b.source }))) {
2110
+ fs.writeFileSync(path.join(dir, f), t);
2111
+ written.push(path.join(dir, f));
2112
+ }
2113
+ if (b.matrix) {
2114
+ const f = path.join(dir, `${name}-matrix.json`);
2115
+ fs.writeFileSync(f, JSON.stringify(b.matrix, null, 2) + '\n');
2116
+ written.push(f);
2117
+ }
2118
+ const done = [
2119
+ {
2120
+ level: 'pass',
2121
+ text: `fab zip: ${Object.keys(fab).length} files (${Object.keys(fab).filter((f) => !/\.(csv|DRL)$/.test(f)).length} Gerber layers, 2 drill files, BOM, placement)`,
2122
+ },
2123
+ ];
2124
+ if (opt('json'))
2125
+ return console.log(
2126
+ JSON.stringify(
2127
+ { object: `${d.project}/${d.name}`, version, files: written.map((f) => path.relative(WS, f)), findings: done },
2128
+ null,
2129
+ 2,
2130
+ ),
2131
+ );
853
2132
  report(done);
854
2133
  for (const f of written) console.log(f);
855
2134
  }
@@ -857,7 +2136,13 @@ async function board(cmd, d, b, { title, version, tag }) {
857
2136
  // ---------- assemblies ----------
858
2137
  async function assembly(cmd, ref) {
859
2138
  const pose = typeof opt('pose') === 'string' ? opt('pose') : undefined;
860
- const s = await buildAssembly(ref, [], {}, { pose, progress: showProgress }), a = s.a, title = `${a.title || s.name}${pose ? ` (${pose})` : ''}`;
2139
+ // --set item.variable=value: that item built at the value (an unknown item or variable is refused by name)
2140
+ const set = sets(),
2141
+ overrides = assemblyOverrides(ref, set),
2142
+ setTag = suffix(set); // (in file names, as an object's)
2143
+ const s = await buildAssembly(ref, [], overrides, { pose, progress: showProgress }),
2144
+ a = s.a,
2145
+ title = `${a.title || s.name}${pose ? ` (${pose})` : ''}${setTag ? ` (${setTag.slice(1)})` : ''}`;
861
2146
  const versions = [...new Map(s.objects.map((o) => [o.objName, `${o.objName} ${o.version}`])).values()].join(', ');
862
2147
  const rules = (ns) => Object.fromEntries(Object.keys(loadRuleSet(ns).rules).map((k) => [k, s.num(`${ns}.${k}`)]));
863
2148
  const printed = s.parts.filter((p) => p.role !== 'reference');
@@ -866,78 +2151,174 @@ async function assembly(cmd, ref) {
866
2151
  say(`${title} (${a.kind || 'fit'}: ${versions})`);
867
2152
  // Each pose (or the one asked for): what's the same in every pose is said once, the rest under the pose's name
868
2153
  const findings = assemblyFindings(s, a, pose);
869
- if (opt('sweep')) findings.push(...sweep(s, { joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined, steps: Number(opt('steps')) || 24, progress: showProgress }));
870
- if (a.kind === 'plate') findings.push(...check(printed.flatMap((p) => p.triangles), rules(printerOf(s.project)), { parts: printed }));
871
- process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) }) ? 1 : 0;
2154
+ if (opt('sweep'))
2155
+ findings.push(
2156
+ ...sweep(s, {
2157
+ joint: typeof opt('sweep') === 'string' ? opt('sweep') : undefined,
2158
+ steps: Number(opt('steps')) || 24,
2159
+ progress: showProgress,
2160
+ }),
2161
+ );
2162
+ if (a.kind === 'plate')
2163
+ findings.push(
2164
+ ...check(
2165
+ printed.flatMap((p) => p.triangles),
2166
+ rules(printerOf(s.project)),
2167
+ { parts: printed },
2168
+ ),
2169
+ );
2170
+ process.exitCode = report(findings, { assembly: ref, title, kind: a.kind || 'fit', ...(pose ? { pose } : {}) })
2171
+ ? 1
2172
+ : 0;
872
2173
  return;
873
2174
  }
874
2175
  if (cmd === 'animate') {
875
- if (!s.gait) { // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
876
- const { driveSvg } = await import('../lib/drive.mjs'), out = paths.preview(s.project, `${s.name}-drive.svg`);
2176
+ if (!s.gait) {
2177
+ // a motor turning what it drives: the gears cut across their shafts, the load's part turning with them
2178
+ const { driveSvg } = await import('../lib/drive.mjs'),
2179
+ out = paths.preview(s.project, `${s.name}${setTag}-drive.svg`);
877
2180
  fs.mkdirSync(path.dirname(out), { recursive: true });
878
2181
  fs.writeFileSync(out, driveSvg(s, { title, ...(opt('turns') ? { turns: Number(opt('turns')) } : {}) }));
879
2182
  return console.log(out);
880
2183
  }
881
- const { gaitSvg, gaitData } = await import('../lib/animate.mjs'), { framesOf } = await import('../lib/gait.mjs'), r = framesOf(s);
882
- if (!r.frames.length) throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
883
- const svg = paths.preview(s.project, `${s.name}-gait.svg`), json = paths.preview(s.project, `${s.name}-gait.json`);
2184
+ const { gaitSvg, gaitData } = await import('../lib/animate.mjs'),
2185
+ { framesOf } = await import('../lib/gait.mjs'),
2186
+ r = framesOf(s);
2187
+ if (!r.frames.length)
2188
+ throw new Error(`${ref}'s gait has nothing to play: ${r.findings.map((x) => x.text).join('; ')}`);
2189
+ const svg = paths.preview(s.project, `${s.name}${setTag}-gait.svg`),
2190
+ json = paths.preview(s.project, `${s.name}${setTag}-gait.json`);
884
2191
  fs.mkdirSync(path.dirname(svg), { recursive: true });
885
- fs.writeFileSync(svg, gaitSvg(s, r, { title: `${title}: ${typeof a.gait.pattern === 'string' ? a.gait.pattern : 'a gait'}` })); fs.writeFileSync(json, JSON.stringify(gaitData(s, r)));
886
- console.log(svg); return console.log(json);
2192
+ fs.writeFileSync(
2193
+ svg,
2194
+ gaitSvg(s, r, { title: `${title}: ${typeof a.gait.pattern === 'string' ? a.gait.pattern : 'a gait'}` }),
2195
+ );
2196
+ fs.writeFileSync(json, JSON.stringify(gaitData(s, r)));
2197
+ console.log(svg);
2198
+ return console.log(json);
887
2199
  }
888
2200
  if (cmd === 'preview') {
889
2201
  const check = !!opt('check'); // the check view: each motor's torque labelled at its joints, never on the rest view
890
- const out = paths.preview(s.project, `${s.name}${pose ? `-${pose}` : ''}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`);
2202
+ const out = paths.preview(
2203
+ s.project,
2204
+ `${s.name}${pose ? `-${pose}` : ''}${setTag}${opt('explode') ? '-exploded' : ''}${check ? '-check' : ''}.png`,
2205
+ );
891
2206
  let marks = null;
892
2207
  if (check) {
893
- if (!s.motion?.drives?.length) throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
2208
+ if (!s.motion?.drives?.length)
2209
+ throw new Error(`${ref} has no motor: cad preview --check labels the torque a motor sends through its joints`);
894
2210
  marks = (await import('../lib/motorsvg.mjs')).workMarks(s);
895
2211
  }
896
- const size = (await import('@rulecad/printcheck')).bounds(s.triangles).size.map((n) => fmt(n)).join(' × ');
897
- const built = s.a.show === 'built' // (show: built: references drawn solid, as the thing built)
898
- const faint = [...new Set(s.parts.filter((p) => p.role !== 'part' && !(built && p.role === 'reference')).map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`))]; // each kind once
899
- await preview([...s.parts, ...wireTubesOf(s)], { title: check ? `${title}: the motor at work` : title, meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`, out, explode: !!opt('explode'), marks, built });
2212
+ const size = (await import('@rulecad/printcheck'))
2213
+ .bounds(s.triangles)
2214
+ .size.map((n) => fmt(n))
2215
+ .join(' × ');
2216
+ const built = s.a.show === 'built'; // (show: built: references drawn solid, as the thing built)
2217
+ const faint = [
2218
+ ...new Set(
2219
+ s.parts
2220
+ .filter((p) => p.role !== 'part' && !(built && p.role === 'reference'))
2221
+ .map((p) => `${p.object || p.item}${p.role === 'support' ? ' supports' : ''}`),
2222
+ ),
2223
+ ]; // each kind once
2224
+ await preview([...s.parts, ...wireTubesOf(s)], {
2225
+ title: check ? `${title}: the motor at work` : title,
2226
+ meta: `${size} mm · ${versions}${faint.length ? ` · faint: ${faint.join(', ')}` : ''}`,
2227
+ out,
2228
+ explode: !!opt('explode'),
2229
+ marks,
2230
+ built,
2231
+ });
900
2232
  // each motor at work beside it: its curve with the working point, and the torque through its train (said before
901
2233
  // the picture, which stays the last line, for whatever reads it)
902
2234
  if (s.motion?.drives?.length && !pose && !opt('explode') && !check) {
903
2235
  const { motorWork, workCurve, trainSvg } = await import('../lib/motorsvg.mjs');
904
2236
  for (const w of motorWork(s)) {
905
- for (const [kind, svg] of [['curve', workCurve(w)], ['train', trainSvg(w)]]) {
2237
+ for (const [kind, svg] of [
2238
+ ['curve', workCurve(w)],
2239
+ ['train', trainSvg(w)],
2240
+ ]) {
906
2241
  const file = paths.preview(s.project, `${s.name}-${w.id}-${kind}.svg`);
907
- fs.writeFileSync(file, svg); console.log(file);
2242
+ fs.writeFileSync(file, svg);
2243
+ console.log(file);
908
2244
  }
909
2245
  }
910
2246
  }
911
2247
  return console.log(out);
912
2248
  }
913
2249
  if (cmd === 'export') {
914
- if (a.kind !== 'plate') throw new Error(`${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`);
915
- const out = paths.exports(s.project, `${s.name}.3mf`);
2250
+ if (a.kind !== 'plate')
2251
+ throw new Error(
2252
+ `${ref} is a fit assembly, for checking: export its objects, or make a plate (kind: plate) to print them together`,
2253
+ );
2254
+ const out = paths.exports(s.project, `${s.name}${setTag}.3mf`);
916
2255
  fs.mkdirSync(path.dirname(out), { recursive: true });
917
2256
  // One object per printed thing (a keycap with its legend and supports), a part per part, each in its filament
918
- const fil = filaments(s.project), things = new Map();
919
- for (const p of printed) { if (!things.has(p.leaf)) things.set(p.leaf, []); things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) }); }
920
- fs.writeFileSync(out, await threemf([...things].map(([name, parts]) => ({ name, parts })), { filaments: slots(fil) }));
2257
+ const fil = filaments(s.project),
2258
+ things = new Map();
2259
+ for (const p of printed) {
2260
+ if (!things.has(p.leaf)) things.set(p.leaf, []);
2261
+ things.get(p.leaf).push({ name: p.label, triangles: p.triangles, slot: slotOf(fil, p.filament) });
2262
+ }
2263
+ fs.writeFileSync(
2264
+ out,
2265
+ await threemf(
2266
+ [...things].map(([name, parts]) => ({ name, parts })),
2267
+ { filaments: slots(fil) },
2268
+ ),
2269
+ );
921
2270
  report(filamentNotes(printed, fil));
922
2271
  if (opt('open')) openInSlicer(out);
923
2272
  return console.log(out);
924
2273
  }
925
2274
  const link = async () => {
926
- const model = await assemblyModel(s, { title, versions, filaments: filaments(s.project), noRules: !!opt('no-rules'), steps: opt('no-steps') ? false : opt('steps') });
927
- if (model.steps) say(`carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`);
2275
+ const model = await assemblyModel(s, {
2276
+ title,
2277
+ versions,
2278
+ filaments: filaments(s.project),
2279
+ noRules: !!opt('no-rules'),
2280
+ steps: opt('no-steps') ? false : opt('steps'),
2281
+ });
2282
+ // built with --set: the link says so, as an object's does (a.width=80,b.depth=20), and its downloads are named with it
2283
+ if (Object.keys(set).length)
2284
+ model.set = Object.entries(set)
2285
+ .map(([k, v]) => `${k}=${v}`)
2286
+ .join(',')
2287
+ .replace(/[^\w.=+,-]/g, '_');
2288
+ if (model.steps)
2289
+ say(
2290
+ `carries the drawing ${model.steps.name ?? '(unnamed)'} (${model.steps.b.length} blocks; --no-steps to leave it out)`,
2291
+ );
928
2292
  const url = await linkTo(model);
929
- return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src: model.src, size: url.length, title, version: '' };
2293
+ return {
2294
+ view: url,
2295
+ stl: `${url}&get=stl`,
2296
+ '3mf': `${url}&get=3mf`,
2297
+ src: model.src,
2298
+ size: url.length,
2299
+ title,
2300
+ version: '',
2301
+ };
930
2302
  };
931
2303
  if (cmd === 'link') return await printLinks(await link());
932
2304
  if (cmd === 'show') {
933
2305
  // Each shape once, placed for every copy: nine keys cost one keycap in the mirror's link. Built with each object's
934
2306
  // mirror settings (fewer segments), so the display gets a lighter mesh; checks and links use the real one
935
- const m = await buildAssembly(ref, [], {}, { mirror: true, pose });
2307
+ const m = await buildAssembly(ref, [], overrides, { mirror: true, pose });
936
2308
  const placed = shapes(m.parts.filter((p) => p.role !== 'support' && p.mirror !== false));
937
2309
  // The card: what the checks found, one short line each
938
- const items = checkAssembly(s).filter((x) => x.card).slice(0, 6).map((x) => x.card);
939
- await (await target('show'))({ title, ttl: opt('ttl') || '10m', mesh: { shapes: placed.shapes.map((x) => x.polygons), place: placed.place },
940
- card: { title: a.kind === 'plate' ? `${title}: ${versions}` : `${title}: checks`, items } });
2310
+ const items = checkAssembly(s)
2311
+ .filter((x) => x.card)
2312
+ .slice(0, 6)
2313
+ .map((x) => x.card);
2314
+ await (
2315
+ await target('show')
2316
+ )({
2317
+ title,
2318
+ ttl: opt('ttl') || '10m',
2319
+ mesh: { shapes: placed.shapes.map((x) => x.polygons), place: placed.place },
2320
+ card: { title: a.kind === 'plate' ? `${title}: ${versions}` : `${title}: checks`, items },
2321
+ });
941
2322
  return await printLinks(await link());
942
2323
  }
943
2324
  throw new Error(`cad ${cmd} doesn't work on an assembly (check, preview, export, show, link do)`);
@@ -945,24 +2326,46 @@ async function assembly(cmd, ref) {
945
2326
 
946
2327
  // The model as a link: full print precision (triangles), the rules card, and exactly which version it is.
947
2328
  async function links(d, b, set) {
948
- const s = d.tag ? { kind: null } : await since(d), fil = filaments(d.project);
2329
+ const s = d.tag ? { kind: null } : await since(d),
2330
+ fil = filaments(d.project);
949
2331
  const version = d.version || b.object.version || '0.0.0';
950
2332
  const src = `${d.project}/${d.name}${d.variant ? `:${d.variant}` : ''}@${version}${s.kind && s.kind !== 'first' ? '+changes' : s.kind === 'first' ? '+unreleased' : ''}`;
951
- const model = await objectModel(b, { title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`, version, src, set: Object.keys(set).length ? suffix(set).slice(1).replace(/-(?=\w+=)/g, ',') : null, filaments: fil, noRules: !!opt('no-rules') });
2333
+ const model = await objectModel(b, {
2334
+ title: `${b.object.title || b.object.name}${d.variant ? ` (${d.variant})` : ''}`,
2335
+ version,
2336
+ src,
2337
+ set: Object.keys(set).length
2338
+ ? suffix(set)
2339
+ .slice(1)
2340
+ .replace(/-(?=\w+=)/g, ',')
2341
+ : null,
2342
+ filaments: fil,
2343
+ noRules: !!opt('no-rules'),
2344
+ });
952
2345
  const url = await linkTo(model);
953
- return { view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, src, size: url.length, title: model.title, version };
2346
+ return {
2347
+ view: url,
2348
+ stl: `${url}&get=stl`,
2349
+ '3mf': `${url}&get=3mf`,
2350
+ src,
2351
+ size: url.length,
2352
+ title: model.title,
2353
+ version,
2354
+ };
954
2355
  }
955
2356
 
956
2357
  // Short links: the model's data stored by the shorten target (a secret Gist), and a link that carries only its ID. The
957
2358
  // same model reuses its ID (.cache/links.json, by the data's hash). Without a shorten target, links stay long.
958
2359
  async function shorten(l) {
959
2360
  if (!hasTarget('shorten')) return l;
960
- const token = l.view.split('#m=')[1], hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
961
- const file = paths.cache('links.json'), cache = fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {};
2361
+ const token = l.view.split('#m=')[1],
2362
+ hash = (await import('node:crypto')).createHash('sha256').update(token).digest('hex').slice(0, 16);
2363
+ const file = paths.cache('links.json'),
2364
+ kept = readCacheJson(file),
2365
+ cache = kept && typeof kept === 'object' && !Array.isArray(kept) ? kept : {};
962
2366
  if (!cache[hash]) {
963
2367
  cache[hash] = await (await target('shorten'))(token, { desc: `model: ${l.src}` });
964
- fs.mkdirSync(path.dirname(file), { recursive: true });
965
- fs.writeFileSync(file, JSON.stringify(cache, null, 2));
2368
+ writeCacheFile(file, JSON.stringify(cache, null, 2));
966
2369
  }
967
2370
  const url = `${VIEW}#s=${cache[hash]}`;
968
2371
  return { ...l, view: url, stl: `${url}&get=stl`, '3mf': `${url}&get=3mf`, short: true };
@@ -973,18 +2376,33 @@ async function shorten(l) {
973
2376
  const TOO_LONG = 8000; // characters: past this, chat apps and email cut a link short or refuse it
974
2377
  async function printLinks(l) {
975
2378
  if ((opt('md') && !opt('long')) || opt('short')) l = await shorten(l);
976
- if (!l.short && l.view.length > TOO_LONG) console.error(`this link is ${(l.view.length / 1024).toFixed(0)} KB, too long for chat or email. ${hasTarget('shorten')
977
- ? 'Leave out --long for a short one.' : 'For short links, add "shorten": "gist" to "targets" in cad.config.json: each model you share is then stored in a secret GitHub Gist (needs the gh command, signed in).'}`);
2379
+ // (on stderr, so that --md still prints one line to paste)
2380
+ if (viewNote()) console.error(viewNote());
2381
+ if (!l.short && l.view.length > TOO_LONG)
2382
+ console.error(
2383
+ `this link is ${(l.view.length / 1024).toFixed(0)} KB, too long for chat or email. ${
2384
+ hasTarget('shorten')
2385
+ ? 'Leave out --long for a short one.'
2386
+ : 'For short links, add "shorten": "gist" to "targets" in cad.config.json: each model you share is then stored in a secret GitHub Gist (needs the gh command, signed in).'
2387
+ }`,
2388
+ );
978
2389
  // One link: the page picks which parts go in a download (all of them, one key, only the case)
979
- if (opt('md')) return console.log(`**${[l.title, l.version].filter(Boolean).join(' ')}**${l.src.includes('+') ? ' (not a release)' : ''}: [View and download](${l.view})`);
980
- console.log(`${l.src}, ${l.short ? 'short links (data in a secret Gist)' : `${(l.size / 1024).toFixed(1)} KB links`}${l.src.includes('+') ? ' (not a release: the link shows it)' : ''}`);
2390
+ if (opt('md'))
2391
+ return console.log(
2392
+ `**${[l.title, l.version].filter(Boolean).join(' ')}**${l.src.includes('+') ? ' (not a release)' : ''}: [View and download](${l.view})`,
2393
+ );
2394
+ console.log(
2395
+ `${l.src}, ${l.short ? 'short links (data in a secret Gist)' : `${(l.size / 1024).toFixed(1)} KB links`}${l.src.includes('+') ? ' (not a release: the link shows it)' : ''}`,
2396
+ );
981
2397
  // A long link is the whole model: printed only when asked for (--long), else written to a file (a link of a
982
2398
  // keyboard is megabytes: in a terminal or an agent's context it's only noise)
983
2399
  if (!l.short && !opt('long')) {
984
2400
  const f = paths.cache('links', `${l.src.replace(/[^\w@.+-]+/g, '-')}.txt`);
985
- fs.mkdirSync(path.dirname(f), { recursive: true });
986
- fs.writeFileSync(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`);
987
- return console.log(` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`);
2401
+ // (where .cache/links can't be written, a link in a cloned workspace's .cache, the links are printed instead)
2402
+ if (writeCacheFile(f, `view ${l.view}\nstl ${l.stl}\n3mf ${l['3mf']}\n`))
2403
+ return console.log(
2404
+ ` links in ${path.relative(WS, f)} (--md: one ${hasTarget('shorten') ? 'short ' : ''}link for chat; --long: print them)`,
2405
+ );
988
2406
  }
989
2407
  console.log(` view ${l.view}`);
990
2408
  console.log(` stl ${l.stl}`);
@@ -996,58 +2414,202 @@ const KINDS = ['patch', 'minor', 'major'];
996
2414
  const today = () => new Date().toISOString().slice(0, 10);
997
2415
 
998
2416
  // Unreleased changes: compare with the last release. -> { last, kind, reasons } (kind null: nothing changed)
999
- // A design that reads other objects is resolved with their numbers (each side with the objects it named then).
1000
- const snap = async (d) => snapshot(d, (await objectSets(d, readObject(d))).sets);
2417
+ // A design that reads other objects is resolved with their numbers (each side with the objects it named then: a
2418
+ // release with them as its tag holds them). And the files it read besides its own (`reads`, as the release recorded
2419
+ // them: its helpers, and the rule sets v.fixings and v.frames read) are compared file by file, the design now with
2420
+ // the same files as the release, so an edited helper or thread set counts as a change.
2421
+ const snap = async (d, reads) =>
2422
+ snapshot(d, (await objectSets(d, readObject(d))).sets, reads ? readTexts(d, reads) : null);
1001
2423
  async function since(d) {
1002
2424
  const last = tags(d.project, d.name).at(-1);
1003
2425
  if (!last) return { last: null, kind: 'first', reasons: [] };
1004
- return { last, ...compare(await snap(materialise(d, last.version)), await snap(d)) };
2426
+ const was = materialise(d, last.version);
2427
+ return { last, ...compare(await snap(was, was.reads), await snap(d, was.reads)) };
1005
2428
  }
1006
2429
 
1007
2430
  // Only the design's own files (and its project's changelog and print log) may have uncommitted changes.
1008
2431
  // A release commits only its own files, so other work in progress can stay as it is (another object, an assembly, the
1009
2432
  // docs). What it can't release past is uncommitted shared code (lib/, bin/) or a rule or layout it uses: those would
1010
2433
  // be in the build but not in the release.
2434
+ // git names the files from the repository's root, which may be above the workspace (a workspace in a folder of a larger
2435
+ // repository): only the workspace's own files are asked for (-- .), and named from the workspace.
1011
2436
  function onlyChanged(allowed) {
1012
- const dirty = git('status', '--porcelain', '--untracked-files=all').split('\n').filter(Boolean).map((l) => l.slice(3).replace(/^"|"$/g, ''));
2437
+ let porcelain, prefix;
2438
+ try {
2439
+ porcelain = git('status', '--porcelain', '--untracked-files=all', '--', '.');
2440
+ prefix = git('rev-parse', '--show-prefix');
2441
+ } catch (e) {
2442
+ if (/not a git repository/.test(e.stderr || e.message)) return; // (a dry run outside git: a release is refused first)
2443
+ throw e;
2444
+ }
2445
+ const dirty = porcelain
2446
+ .split('\n')
2447
+ .filter(Boolean)
2448
+ .map((l) => l.slice(3).replace(/^"|"$/g, ''))
2449
+ .map((f) => (f.startsWith(prefix) ? f.slice(prefix.length) : f));
1013
2450
  const shared = dirty.filter((f) => !allowed.includes(f) && /^(lib|bin)\//.test(f));
1014
- if (shared.length) throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
2451
+ if (shared.length)
2452
+ throw new Error(`commit shared code first (the release would build with it): ${shared.join(', ')}`);
1015
2453
  }
1016
2454
 
1017
- function commitAndTag(paths, subject, tag, message) {
1018
- git('add', '--', ...paths);
1019
- git('commit', '-q', '-m', subject, ...(opt('trailer') ? ['--trailer', opt('trailer')] : []), '--', ...paths); // only these, whatever else is staged
1020
- git('tag', '-a', tag, '-m', message);
1021
- if (opt('push')) { git('push', '-q', 'origin', 'HEAD'); git('push', '-q', 'origin', tag); }
2455
+ // A release is a git commit and a tag, so before anything is written: git is there, the workspace is in a repository,
2456
+ // and git has a name and email address to put on the commit. Each missing one is said in plain words, with what to run.
2457
+ function releasable() {
2458
+ try {
2459
+ git('rev-parse', '--is-inside-work-tree');
2460
+ } catch (e) {
2461
+ if (e.code === 'ENOENT')
2462
+ throw new Error(
2463
+ 'not released: a release is kept in git (a commit and a tag), and git is not installed on this computer. Install it (https://git-scm.com), then release again',
2464
+ );
2465
+ throw new Error(
2466
+ `not released: a release is kept in git (a commit and a tag), and ${WS} is not a git repository yet. Make it one and commit your designs (git init, then git add -A and git commit -m "My designs"), then release again`,
2467
+ );
2468
+ }
2469
+ try {
2470
+ git('var', 'GIT_AUTHOR_IDENT');
2471
+ git('var', 'GIT_COMMITTER_IDENT');
2472
+ } catch {
2473
+ throw new Error(
2474
+ 'not released: git has no name and email address to put on the release. Run git config user.name "Your Name" and git config user.email "you@example.com" (add --global to use them in every repository), then release again',
2475
+ );
2476
+ }
2477
+ }
2478
+
2479
+ // What git said when it refused, without its hints: the hook's own words, or git's reason
2480
+ const gitSaid = (e) =>
2481
+ String(e.stderr || e.stdout || e.message)
2482
+ .split('\n')
2483
+ .map((l) => l.trim().replace(/^(fatal|error): /, ''))
2484
+ .filter((l) => l && !/^hint:/.test(l) && !/^Command failed/.test(l))
2485
+ .join('; ')
2486
+ .replace(/\.$/, '') || 'no reason given';
2487
+
2488
+ // The files a release is about to change, as they are now (null: not there yet), to put back if git refuses it
2489
+ const keep = (list) => new Map(list.map((f) => [f, fs.existsSync(f) ? readOwnText(f) : null]));
2490
+
2491
+ // Commit the release's files and tag the commit. If git refuses either (a hook that fails, a tag that can't be
2492
+ // signed), everything is put back as it was before the release: the commit (if it was made), what was staged, and the
2493
+ // files in kept (its version and changelog), so that the release can simply be run again.
2494
+ function commitAndTag(paths, subject, tag, message, kept) {
2495
+ const head = (() => {
2496
+ try {
2497
+ return git('rev-parse', '--verify', '-q', 'HEAD');
2498
+ } catch {
2499
+ return null; // (a repository with no commit yet)
2500
+ }
2501
+ })();
2502
+ let index = null;
2503
+ try {
2504
+ index = git('write-tree'); // what is staged now, to stage again
2505
+ } catch {
2506
+ // (an index git can't write as a tree: the release's files are unstaged instead)
2507
+ }
2508
+ let step = 'commit';
2509
+ try {
2510
+ git('add', '--', ...paths);
2511
+ git('commit', '-q', '-m', subject, ...(opt('trailer') ? ['--trailer', opt('trailer')] : []), '--', ...paths); // only these, whatever else is staged
2512
+ step = 'tag';
2513
+ git('tag', '-a', tag, '-m', message);
2514
+ } catch (e) {
2515
+ let undone = true;
2516
+ try {
2517
+ if (step === 'tag') head ? git('reset', '-q', '--soft', head) : git('update-ref', '-d', 'HEAD');
2518
+ if (index) git('read-tree', index);
2519
+ else if (head) git('reset', '-q', '--', ...paths);
2520
+ else git('rm', '-q', '--cached', '--ignore-unmatch', '--', ...paths);
2521
+ } catch {
2522
+ undone = false;
2523
+ }
2524
+ for (const [f, text] of kept) text == null ? fs.rmSync(f, { force: true }) : fs.writeFileSync(f, text);
2525
+ throw new Error(
2526
+ `not released: git refused the release's ${step} (${gitSaid(e)}). ${
2527
+ undone
2528
+ ? 'Your files are as they were before the release'
2529
+ : `Your files are as they were before the release, but git's own record may not be: see git status${step === 'tag' ? ' and git log' : ''}`
2530
+ }. Put that right, then release again`,
2531
+ );
2532
+ }
2533
+ if (opt('push'))
2534
+ try {
2535
+ git('push', '-q', 'origin', 'HEAD');
2536
+ git('push', '-q', 'origin', tag);
2537
+ } catch (e) {
2538
+ throw new Error(
2539
+ `released and tagged ${tag} here, but not pushed: git said ${gitSaid(e)}. Push it when you can: git push --follow-tags`,
2540
+ );
2541
+ }
1022
2542
  }
1023
2543
 
2544
+ // Add a release's entry at the top of its project's changelog. An entry for the same name and version that was never
2545
+ // committed (left by a release that went wrong part way) is replaced, never repeated. One that was committed is a real
2546
+ // release and stays: an object named as its project (lamp/lamp) has entries headed as the project's own (lamp 0.1.0).
1024
2547
  function changelog(dir, heading, message, reasons) {
1025
2548
  const f = path.join(dir, 'CHANGELOG.md');
1026
- const old = fs.existsSync(f) ? fs.readFileSync(f, 'utf8').replace(/^# .*\n+/, '') : '';
2549
+ const same = `## ${heading.slice(0, heading.indexOf(' ('))} (`,
2550
+ logFile = path.relative(WS, f).split(path.sep).join('/');
2551
+ const entries = (text) => text.replace(/^# .*\n+/, '').split(/^(?=## )/m);
2552
+ const committed = new Map(); // heading -> how many committed entries have it
2553
+ try {
2554
+ for (const e of entries(git('show', `HEAD:./${logFile}`)))
2555
+ if (e.startsWith(same)) committed.set(e.split('\n')[0], (committed.get(e.split('\n')[0]) || 0) + 1);
2556
+ } catch {
2557
+ // (no commit yet, or the changelog was never committed: every entry for this release is a leftover)
2558
+ }
2559
+ const old = fs.existsSync(insideWorkspace(f))
2560
+ ? entries(readOwnText(f))
2561
+ .filter((e) => {
2562
+ if (!e.startsWith(same)) return true;
2563
+ const h = e.split('\n')[0],
2564
+ n = committed.get(h) || 0;
2565
+ committed.set(h, n - 1);
2566
+ return n > 0;
2567
+ })
2568
+ .join('')
2569
+ : '';
1027
2570
  const entry = `## ${heading}\n\n${message}\n${reasons.length ? `\n${reasons.map((r) => `- ${r.text} (${r.kind})`).join('\n')}\n` : ''}`;
1028
2571
  fs.writeFileSync(f, `# ${path.basename(dir)} changelog\n\n${entry}\n${old}`);
1029
- return path.relative(WS, f).split(path.sep).join('/'); // (git's terms: forward slashes)
2572
+ return logFile; // (git's terms: forward slashes)
1030
2573
  }
1031
2574
 
1032
2575
  // An object's print checks: printcheck's, and for parts printed in place, theirs (lib/inplace.mjs)
1033
2576
  async function printChecks(b, d) {
1034
- const pr = printer(b, d), printed = check(b.triangles, pr, { parts: b.parts });
1035
- return b.object.printInPlace ? [...printed, ...(await (await import('../lib/inplace.mjs')).inPlaceChecks(b, pr, printed))] : printed;
2577
+ const pr = printer(b, d),
2578
+ printed = check(b.triangles, pr, { parts: b.parts });
2579
+ return b.object.printInPlace
2580
+ ? [...printed, ...(await (await import('../lib/inplace.mjs')).inPlaceChecks(b, pr, printed))]
2581
+ : printed;
1036
2582
  }
1037
2583
 
1038
2584
  async function releaseObject(d, { batch = false } = {}) {
1039
2585
  const message = opt('m');
1040
2586
  if (!message || message === true) throw new Error('say what changed: -m "Wider slot for a looser fit"');
1041
- const object = readObject(d), b = await build(d);
1042
- const raw = lint(fs.readFileSync(d.js, 'utf8')), fails = (b.circuit ? await (await pcbEngine()).checks(b.circuit, b.values, b.matrix, b.source) // boards: the board's checks
1043
- : b.object.role === 'reference' ? [] : [...(await printChecks(b, d)), ...(b.mechanism?.findings || [])]).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
1044
- if (raw.length || fails.length) throw new Error(`fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`);
2587
+ const object = readObject(d),
2588
+ b = await build(d);
2589
+ const raw = lint(readOwnText(d.js)),
2590
+ fails = (
2591
+ b.circuit
2592
+ ? await boardChecks(b, d) // boards: the board's checks (under the design's limits, where it is sandboxed)
2593
+ : b.object.role === 'reference'
2594
+ ? []
2595
+ : [...(await printChecks(b, d)), ...(b.mechanism?.findings || [])]
2596
+ ).filter((r) => r.level === 'fail'); // references aren't printed; a mechanism's own checks count
2597
+ if (raw.length || fails.length)
2598
+ throw new Error(
2599
+ `fix the check first: ${[...raw.map((r) => `raw number ${r.text} on line ${r.line}`), ...fails.map((f) => f.text)].join('; ')}`,
2600
+ );
1045
2601
  let { last, kind, reasons } = await since(d);
1046
2602
  if (!kind) throw new Error(`nothing has changed since ${last.version}`);
1047
2603
  const asked = opt('bump');
1048
2604
  if (asked && last) {
1049
2605
  if (!KINDS.includes(asked)) throw new Error('--bump is major, minor or patch');
1050
- if (bigger(asked, kind) !== asked && !opt('force')) throw new Error(`the changes need at least a ${kind} release (${reasons.filter((r) => r.kind === kind).map((r) => r.text).join('; ')}); --force to override`);
2606
+ if (bigger(asked, kind) !== asked && !opt('force'))
2607
+ throw new Error(
2608
+ `the changes need at least a ${kind} release (${reasons
2609
+ .filter((r) => r.kind === kind)
2610
+ .map((r) => r.text)
2611
+ .join('; ')}); --force to override`,
2612
+ );
1051
2613
  kind = asked;
1052
2614
  }
1053
2615
  const version = last ? bump(last.version, kind) : object.version || '0.1.0';
@@ -1055,67 +2617,132 @@ async function releaseObject(d, { batch = false } = {}) {
1055
2617
  console.log(`${tag} (${kind}${last ? `, from ${last.version}` : ''})`);
1056
2618
  for (const r of reasons) console.log(` ${r.kind.padEnd(5)} ${r.text}`);
1057
2619
  if (opt('dry-run')) return;
1058
- const allowed = [...files(d, object), `projects/${d.project}/CHANGELOG.md`, path.relative(WS, printsFile(d)).split(path.sep).join('/')];
1059
- if (!batch) onlyChanged(allowed); // releaseAll checked the whole tree first
1060
- fs.writeFileSync(d.json, setAt(fs.readFileSync(d.json, 'utf8'), ['version'], version)); // the object's own version (added, if it had none), nothing else
2620
+ const allowed = [
2621
+ ...files(d, object, b),
2622
+ `projects/${d.project}/CHANGELOG.md`,
2623
+ path.relative(WS, printsFile(d)).split(path.sep).join('/'),
2624
+ ];
2625
+ if (!batch) {
2626
+ releasable(); // releaseAll checked these first
2627
+ onlyChanged(allowed);
2628
+ }
2629
+ const kept = keep([d.json, path.join(d.dir, 'CHANGELOG.md')]);
2630
+ fs.writeFileSync(d.json, setAt(readOwnText(d.json), ['version'], version)); // the object's own version (added, if it had none), nothing else
1061
2631
  const log = changelog(d.dir, `${d.name} ${version} (${kind}), ${today()}`, message, reasons);
1062
- commitAndTag([...files(d, object), log].filter((f) => fs.existsSync(path.join(WS, f))), `${tag}: ${message}`, tag, `${kind}: ${message}${b.circuit ? `\n\nengine: ${engineId()}` : ''}`);
2632
+ // (the tag records what the build read besides the design's own files: lib/versions.mjs readsLine)
2633
+ const notes = [b.circuit ? `engine: ${engineId()}` : '', readsLine(b)].filter(Boolean);
2634
+ commitAndTag(
2635
+ [...files(d, object, b), log].filter((f) => fs.existsSync(path.join(WS, f))),
2636
+ `${tag}: ${message}`,
2637
+ tag,
2638
+ `${kind}: ${message}${notes.length ? `\n\n${notes.join('\n')}` : ''}`,
2639
+ kept,
2640
+ );
1063
2641
  console.log(`tagged ${tag}${opt('push') ? ' and pushed' : ' (not pushed: --push, or git push --follow-tags)'}`);
1064
2642
  }
1065
2643
 
1066
2644
  // A project's project.json, or a plain word that there's no such project (and which there are)
1067
2645
  function projectFile(project) {
1068
2646
  const pj = path.join(paths.project(project), 'project.json');
1069
- if (!fs.existsSync(pj)) { const have = projects(); throw new Error(`no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`); }
2647
+ if (!fs.existsSync(pj)) {
2648
+ const have = projects();
2649
+ throw new Error(
2650
+ `no project "${project}"${have.length ? ` (projects: ${have.join(', ')})` : ': cad new <project>/<object> starts one'}`,
2651
+ );
2652
+ }
1070
2653
  return pj;
1071
2654
  }
1072
2655
  // The workspace's projects: the folders under projects/ that hold a project.json (not a stray file, such as .DS_Store)
1073
- const projects = () => (fs.existsSync(paths.projects) ? fs.readdirSync(paths.projects).filter((p) => isPlainName(p) && fs.existsSync(path.join(paths.project(p), 'project.json'))).sort() : []); // (a folder whose name isn't plain is not a project the tool can name)
2656
+ const projects = () =>
2657
+ fs.existsSync(paths.projects)
2658
+ ? fs
2659
+ .readdirSync(paths.projects)
2660
+ .filter((p) => isPlainName(p) && fs.existsSync(path.join(paths.project(p), 'project.json')))
2661
+ .sort()
2662
+ : []; // (a folder whose name isn't plain is not a project the tool can name)
1074
2663
 
1075
2664
  async function releaseProject(project) {
1076
2665
  const message = opt('m');
1077
2666
  if (!message || message === true) throw new Error('say what this release is: -m "First full set"');
1078
- const dir = paths.project(project), pj = projectFile(project);
1079
- const p = JSON.parse(fs.readFileSync(pj, 'utf8')), manifest = {};
2667
+ const dir = paths.project(project),
2668
+ pj = projectFile(project);
2669
+ const p = readJson(pj),
2670
+ manifest = {};
1080
2671
  for (const name of p.objects) {
1081
- const d = locateIn(project, name, `projects/${project}/project.json, its "objects"`), s = await since(d);
2672
+ const d = locateIn(project, name, `projects/${project}/project.json, its "objects"`),
2673
+ s = await since(d);
1082
2674
  if (!s.last) throw new Error(`${name} has no release yet: cad release ${project}/${name} -m "…"`);
1083
2675
  if (s.kind) throw new Error(`${name} has changes since ${s.last.version}: release it first`);
1084
2676
  manifest[name] = s.last.version;
1085
2677
  }
1086
2678
  const last = tags(project).at(-1);
1087
- let kind = 'first', reasons = [];
2679
+ let kind = 'first',
2680
+ reasons = [];
1088
2681
  if (last) {
1089
- const before = JSON.parse(git('cat-file', '-p', `refs/tags/${last.tag}`).split('\n\n').slice(1).join('\n\n').split('\n').find((l) => l.startsWith('{')) || '{}');
2682
+ const before = JSON.parse(
2683
+ git('cat-file', '-p', `refs/tags/${last.tag}`)
2684
+ .split('\n\n')
2685
+ .slice(1)
2686
+ .join('\n\n')
2687
+ .split('\n')
2688
+ .find((l) => l.startsWith('{')) || '{}',
2689
+ );
1090
2690
  for (const [name, v] of Object.entries(manifest)) {
1091
2691
  if (!before[name]) reasons.push({ kind: 'minor', text: `${name} ${v} added` });
1092
2692
  else if (before[name] !== v) {
1093
- const k = tags(project, name).filter((t) => newer(t.version, before[name]) && !newer(t.version, v)).reduce((m, t) => bigger(m, t.kind === 'first' ? 'patch' : t.kind || 'patch'), 'patch');
2693
+ const k = tags(project, name)
2694
+ .filter((t) => newer(t.version, before[name]) && !newer(t.version, v))
2695
+ .reduce((m, t) => bigger(m, t.kind === 'first' ? 'patch' : t.kind || 'patch'), 'patch');
1094
2696
  reasons.push({ kind: k, text: `${name} ${before[name]} → ${v}` });
1095
2697
  }
1096
2698
  }
1097
- for (const name of Object.keys(before)) if (!manifest[name]) reasons.push({ kind: 'major', text: `${name} removed` });
2699
+ for (const name of Object.keys(before))
2700
+ if (!manifest[name]) reasons.push({ kind: 'major', text: `${name} removed` });
1098
2701
  if (!reasons.length) throw new Error(`nothing has changed since ${project}@${last.version}`);
1099
2702
  kind = reasons.reduce((k, r) => bigger(k, r.kind), 'patch');
1100
2703
  }
1101
2704
  const version = last ? bump(last.version, kind) : p.version || '0.1.0';
1102
- console.log(`${project}@${version} (${kind}): ${Object.entries(manifest).map(([n, v]) => `${n}@${v}`).join(', ')}`);
2705
+ console.log(
2706
+ `${project}@${version} (${kind}): ${Object.entries(manifest)
2707
+ .map(([n, v]) => `${n}@${v}`)
2708
+ .join(', ')}`,
2709
+ );
1103
2710
  if (opt('dry-run')) return;
1104
- onlyChanged([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`]);
1105
- p.version = version; p.release = manifest;
1106
- fs.writeFileSync(pj, JSON.stringify(p, null, 2) + '\n');
2711
+ releasable();
2712
+ onlyChanged([
2713
+ `projects/${project}/project.json`,
2714
+ `projects/${project}/CHANGELOG.md`,
2715
+ `projects/${project}/prints.jsonl`,
2716
+ ]);
2717
+ const kept = keep([pj, path.join(dir, 'CHANGELOG.md')]);
2718
+ // The release's version and the versions of its objects (fields of the project schema), the rest of the file as it was
2719
+ fs.writeFileSync(pj, setAt(setAt(readOwnText(pj), ['version'], version), ['release'], manifest));
1107
2720
  const log = changelog(dir, `${project} ${version} (${kind}), ${today()}`, message, reasons);
1108
- commitAndTag([`projects/${project}/project.json`, log], `${project}@${version}: ${message}`, `${project}@${version}`, `${kind}: ${message}\n\n${JSON.stringify(manifest)}`);
2721
+ commitAndTag(
2722
+ [`projects/${project}/project.json`, log],
2723
+ `${project}@${version}: ${message}`,
2724
+ `${project}@${version}`,
2725
+ `${kind}: ${message}\n\n${JSON.stringify(manifest)}`,
2726
+ kept,
2727
+ );
1109
2728
  console.log(`tagged ${project}@${version}`);
1110
2729
  }
1111
2730
 
1112
2731
  // Release every object in a project that changed, then the project: the tree may hold changes only to their files.
1113
2732
  async function releaseAll(project) {
1114
- const pj = JSON.parse(fs.readFileSync(projectFile(project), 'utf8'));
2733
+ const pj = readJson(projectFile(project));
1115
2734
  const changed = [];
1116
- for (const n of pj.objects) { const d = locateIn(project, n, `projects/${project}/project.json, its "objects"`); if ((await since(d)).kind) changed.push(d); }
1117
- const allowed = new Set([`projects/${project}/project.json`, `projects/${project}/CHANGELOG.md`, `projects/${project}/prints.jsonl`,
1118
- ...changed.flatMap((d) => files(d, readObject(d)))]);
2735
+ for (const n of pj.objects) {
2736
+ const d = locateIn(project, n, `projects/${project}/project.json, its "objects"`);
2737
+ if ((await since(d)).kind) changed.push(d);
2738
+ }
2739
+ const allowed = new Set([
2740
+ `projects/${project}/project.json`,
2741
+ `projects/${project}/CHANGELOG.md`,
2742
+ `projects/${project}/prints.jsonl`,
2743
+ ]);
2744
+ for (const d of changed) for (const f of files(d, readObject(d), await build(d))) allowed.add(f);
2745
+ if (!opt('dry-run')) releasable(); // (before any object is released)
1119
2746
  onlyChanged([...allowed]);
1120
2747
  for (const d of changed) await releaseObject(d, { batch: true });
1121
2748
  if (!opt('dry-run')) await releaseProject(project);
@@ -1125,8 +2752,14 @@ async function releaseAll(project) {
1125
2752
  function variants(d) {
1126
2753
  const v = readObject(d).variants || {};
1127
2754
  if (opt('json')) return console.log(JSON.stringify({ object: `${d.project}/${d.name}`, variants: v }, null, 2));
1128
- if (!Object.keys(v).length) return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
1129
- for (const [n, set] of Object.entries(v)) console.log(`${`${d.project}/${d.name}:${n}`.padEnd(32)} ${Object.entries(set).map(([k, x]) => `${k}=${x}`).join(', ')}`);
2755
+ if (!Object.keys(v).length)
2756
+ return console.log(`${d.name} has no variants: add "variants": { "name": { …inputs } } to its .json`);
2757
+ for (const [n, set] of Object.entries(v))
2758
+ console.log(
2759
+ `${`${d.project}/${d.name}:${n}`.padEnd(32)} ${Object.entries(set)
2760
+ .map(([k, x]) => `${k}=${x}`)
2761
+ .join(', ')}`,
2762
+ );
1130
2763
  }
1131
2764
 
1132
2765
  // Two variants or releases side by side in one preview, the second to the right of the first
@@ -1135,89 +2768,231 @@ async function compareVariants(d, a, b) {
1135
2768
  const one = async (x) => build(/^\d+\.\d+\.\d+$/.test(x) ? materialise(d, x) : { ...d, variant: x }, sets());
1136
2769
  const [A, B] = [await one(a), await one(b)];
1137
2770
  const { bounds } = await import('@rulecad/printcheck');
1138
- const gap = (bounds(A.triangles).size[0] + bounds(B.triangles).size[0]) / 4, dx = bounds(A.triangles).hi[0] - bounds(B.triangles).lo[0] + gap;
2771
+ const gap = (bounds(A.triangles).size[0] + bounds(B.triangles).size[0]) / 4,
2772
+ dx = bounds(A.triangles).hi[0] - bounds(B.triangles).lo[0] + gap;
1139
2773
  const moved = (p) => ({ ...p, triangles: p.triangles.map((t) => t.map(([x, y, z]) => [x + dx, y, z])) });
1140
- const parts = [...A.parts.map((p) => ({ ...p, item: a, label: `${a}: ${p.label}` })), ...B.parts.map((p) => moved({ ...p, item: b, label: `${b}: ${p.label}` }))];
2774
+ const parts = [
2775
+ ...A.parts.map((p) => ({ ...p, item: a, label: `${a}: ${p.label}` })),
2776
+ ...B.parts.map((p) => moved({ ...p, item: b, label: `${b}: ${p.label}` })),
2777
+ ];
1141
2778
  const out = paths.preview(d.project, `${d.name}-${a}-vs-${b}.png`);
1142
- await preview(parts, { title: `${A.object.title || d.name}: ${a} and ${b}`, meta: `${a} on the left, ${b} on the right`, out, explode: false });
2779
+ await preview(parts, {
2780
+ title: `${A.object.title || d.name}: ${a} and ${b}`,
2781
+ meta: `${a} on the left, ${b} on the right`,
2782
+ out,
2783
+ explode: false,
2784
+ });
1143
2785
  console.log(out);
1144
2786
  }
1145
2787
 
1146
2788
  async function status(project) {
1147
- if (!project && !projects().length) return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
2789
+ if (!project && !projects().length)
2790
+ return console.log(`no projects in ${WS} yet: cad new <project>/<object> starts one`);
1148
2791
  for (const p of project ? [project] : projects()) {
1149
- const pj = JSON.parse(fs.readFileSync(projectFile(p), 'utf8'));
2792
+ const pj = readJson(projectFile(p));
1150
2793
  console.log(`${p}${pj.version ? `@${pj.version}` : ''}`);
1151
2794
  for (const name of pj.objects) {
1152
2795
  const s = await since(locateIn(p, name, `projects/${p}/project.json, its "objects"`));
1153
- console.log(` ${name.padEnd(16)} ${s.last ? s.last.version.padEnd(8) : 'unreleased'} ${s.kind === 'first' ? '' : s.kind ? `changed since: needs a ${s.kind} release` : 'up to date'}`);
2796
+ console.log(
2797
+ ` ${name.padEnd(16)} ${s.last ? s.last.version.padEnd(8) : 'unreleased'} ${s.kind === 'first' ? '' : s.kind ? `changed since: needs a ${s.kind} release` : 'up to date'}`,
2798
+ );
1154
2799
  }
1155
2800
  }
1156
2801
  }
1157
2802
 
1158
2803
  async function machineCommand(what, ref) {
1159
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1160
- const m = await import('../lib/machine.mjs'), s = await buildAssembly(ref);
1161
- if (what === 'machine') { const out = m.machineOf(s), file = m.writeMachine(s, out); (await import('../lib/buildpage.mjs')).writeWiring(s); return console.log(opt('json') ? JSON.stringify(out, null, 2) : file); }
1162
- const source = positional()[2], tol = opt('tol') != null ? Number(opt('tol')) : undefined;
2804
+ if (!isAssembly(ref))
2805
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2806
+ const m = await import('../lib/machine.mjs'),
2807
+ s = await buildAssembly(ref);
2808
+ if (what === 'machine') {
2809
+ const out = m.machineOf(s),
2810
+ file = m.writeMachine(s, out);
2811
+ (await import('../lib/buildpage.mjs')).writeWiring(s);
2812
+ return console.log(opt('json') ? JSON.stringify(out, null, 2) : file);
2813
+ }
2814
+ const source = positional()[2],
2815
+ tol = opt('tol') != null ? Number(opt('tol')) : undefined;
1163
2816
  if (!source && !opt('calibrate') && s.gait && !s.task?.sheet) return gaitPlot(m, s, ref);
1164
- if (!source && !opt('calibrate')) throw new Error('usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate], or cad plot <project>/<assembly> on an assembly with a gait');
1165
- const { sheetFrame } = await import('@rulecad/robots'), f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
1166
- const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'), base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
2817
+ if (!source && !opt('calibrate'))
2818
+ throw new Error(
2819
+ 'usage: cad plot <project>/<assembly> <drawing.svg> [--calibrate], or cad plot <project>/<assembly> on an assembly with a gait',
2820
+ );
2821
+ const { sheetFrame } = await import('@rulecad/robots'),
2822
+ f = s.task?.sheet ? sheetFrame(s.task.sheet) : null;
2823
+ const svg = opt('calibrate') ? m.CALIBRATION(f?.width ?? 148, f?.height ?? 210) : fs.readFileSync(source, 'utf8'),
2824
+ base = `${s.name}-${opt('calibrate') ? 'calibration' : path.basename(source, path.extname(source))}`;
1167
2825
  const r = m.plot(s, svg, { tolerance: tol, name: base });
1168
2826
  const failed = !r.ok;
1169
- if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, ...(r.time ? { time: r.time } : {}), ...(r.ok ? { file: m.writePlot(s, r, base).file } : {}) }, null, 2)); process.exitCode = failed ? 1 : 0; return; }
2827
+ if (opt('json')) {
2828
+ console.log(
2829
+ JSON.stringify(
2830
+ {
2831
+ ok: r.ok,
2832
+ findings: r.findings,
2833
+ ...(r.time ? { time: r.time } : {}),
2834
+ ...(r.ok ? { file: m.writePlot(s, r, base).file } : {}),
2835
+ },
2836
+ null,
2837
+ 2,
2838
+ ),
2839
+ );
2840
+ process.exitCode = failed ? 1 : 0;
2841
+ return;
2842
+ }
1170
2843
  report(r.findings, { assembly: ref, title: `${ref}: ${base}` });
1171
- if (r.ok) { const w = m.writePlot(s, r, base); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
2844
+ if (r.ok) {
2845
+ const w = m.writePlot(s, r, base);
2846
+ console.log(path.relative(WS, w.file));
2847
+ console.log(path.relative(WS, w.preview));
2848
+ }
1172
2849
  process.exitCode = failed ? 1 : 0;
1173
2850
  }
1174
2851
 
1175
2852
  // A gait as a step file: --cycles (3), --period (s a cycle; default the gait's), --pose (where it starts and ends; default the one shown)
1176
2853
  async function gaitPlot(m, s, ref) {
1177
- const cycles = opt('cycles') != null ? Number(opt('cycles')) : 3, period = opt('period') != null ? Number(opt('period')) : undefined;
1178
- if (!Number.isInteger(cycles) || cycles < 1) throw new Error(`--cycles is a whole number, 1 or more (got ${opt('cycles')})`);
1179
- if (period != null && !(period > 0)) throw new Error(`--period is the seconds of one cycle, above 0 (got ${opt('period')})`);
2854
+ const cycles = opt('cycles') != null ? Number(opt('cycles')) : 3,
2855
+ period = opt('period') != null ? Number(opt('period')) : undefined;
2856
+ if (!Number.isInteger(cycles) || cycles < 1)
2857
+ throw new Error(`--cycles is a whole number, 1 or more (got ${opt('cycles')})`);
2858
+ if (period != null && !(period > 0))
2859
+ throw new Error(`--period is the seconds of one cycle, above 0 (got ${opt('period')})`);
1180
2860
  const r = m.plotGait(s, { cycles, period, from: opt('pose') });
1181
- if (opt('json')) { console.log(JSON.stringify({ ok: r.ok, findings: r.findings, time: r.time, ...(r.ok ? { file: m.writeGait(s, r).file } : {}) }, null, 2)); process.exitCode = r.ok ? 0 : 1; return; }
2861
+ if (opt('json')) {
2862
+ console.log(
2863
+ JSON.stringify(
2864
+ { ok: r.ok, findings: r.findings, time: r.time, ...(r.ok ? { file: m.writeGait(s, r).file } : {}) },
2865
+ null,
2866
+ 2,
2867
+ ),
2868
+ );
2869
+ process.exitCode = r.ok ? 0 : 1;
2870
+ return;
2871
+ }
1182
2872
  report(r.findings, { assembly: ref, title: `${ref}: its gait` });
1183
- if (r.ok) { const w = m.writeGait(s, r); console.log(path.relative(WS, w.file)); console.log(path.relative(WS, w.preview)); }
2873
+ if (r.ok) {
2874
+ const w = m.writeGait(s, r);
2875
+ console.log(path.relative(WS, w.file));
2876
+ console.log(path.relative(WS, w.preview));
2877
+ }
1184
2878
  process.exitCode = r.ok ? 0 : 1;
1185
2879
  }
1186
2880
 
1187
2881
  async function platesCommand(what, ref) {
1188
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
2882
+ if (!isAssembly(ref))
2883
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1189
2884
  const s = await buildAssembly(ref);
1190
2885
  if (what === 'order') {
1191
- const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'), { withPreload } = await import('../lib/slotnuts.mjs'), r = withPreload(s, orderOf(s));
2886
+ const { orderOf, orderText, stepPictures } = await import('../lib/order.mjs'),
2887
+ { withPreload } = await import('../lib/slotnuts.mjs'),
2888
+ r = withPreload(s, orderOf(s));
1192
2889
  // a frame (beams with joins): from bars to a square frame, its sides built flat, nuts loaded before the join that would shut them in
1193
- const frame = s.joins?.length ? (await import('../lib/framebuild.mjs')) : null, fb = frame ? frame.frameBuild(s) : null;
1194
- if (opt('json')) { console.log(JSON.stringify(fb ? { ...r, frame: fb } : r, null, 2)); if (r.stuck || fb?.stuck) process.exitCode = 1; return; }
2890
+ const frame = s.joins?.length ? await import('../lib/framebuild.mjs') : null,
2891
+ fb = frame ? frame.frameBuild(s) : null;
2892
+ if (opt('json')) {
2893
+ console.log(JSON.stringify(fb ? { ...r, frame: fb } : r, null, 2));
2894
+ if (r.stuck || fb?.stuck) process.exitCode = 1;
2895
+ return;
2896
+ }
1195
2897
  console.log(fb ? frame.frameBuildText(ref, fb) : orderText(ref, r));
1196
- if (r.stuck || fb?.stuck) { process.exitCode = 1; return; }
1197
- if (opt('preview') && fb) { for (const { n, parts } of frame.frameStepPictures(s, fb)) { const st = fb.steps[n - 1], out = paths.preview(s.project, `${s.name}-step-${String(n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${fb.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } return; } // (numbered as the frame's build is)
1198
- if (opt('preview')) { const pics = stepPictures(s, r); for (const [i, parts] of pics.entries()) { const st = r.steps[i], out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`); await preview(parts, { title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`, meta: st.text, out }); console.log(path.relative(WS, out)); } }
2898
+ if (r.stuck || fb?.stuck) {
2899
+ process.exitCode = 1;
2900
+ return;
2901
+ }
2902
+ if (opt('preview') && fb) {
2903
+ for (const { n, parts } of frame.frameStepPictures(s, fb)) {
2904
+ const st = fb.steps[n - 1],
2905
+ out = paths.preview(s.project, `${s.name}-step-${String(n).padStart(2, '0')}.png`);
2906
+ await preview(parts, { title: `${s.a.title || s.name}: step ${n} of ${fb.steps.length}`, meta: st.text, out });
2907
+ console.log(path.relative(WS, out));
2908
+ }
2909
+ return;
2910
+ } // (numbered as the frame's build is)
2911
+ if (opt('preview')) {
2912
+ const pics = stepPictures(s, r);
2913
+ for (const [i, parts] of pics.entries()) {
2914
+ const st = r.steps[i],
2915
+ out = paths.preview(s.project, `${s.name}-step-${String(st.n).padStart(2, '0')}.png`);
2916
+ await preview(parts, {
2917
+ title: `${s.a.title || s.name}: step ${st.n} of ${r.steps.length}`,
2918
+ meta: st.text,
2919
+ out,
2920
+ });
2921
+ console.log(path.relative(WS, out));
2922
+ }
2923
+ }
1199
2924
  return;
1200
2925
  }
1201
- const { platesOf, checkPlate } = await import('../lib/plates.mjs'), gap = opt('gap') != null ? Number(opt('gap')) : undefined;
2926
+ const { platesOf, checkPlate } = await import('../lib/plates.mjs'),
2927
+ gap = opt('gap') != null ? Number(opt('gap')) : undefined;
1202
2928
  if (gap != null && !(gap > 0)) throw new Error(`--gap is a distance in mm, above 0 (got ${opt('gap')})`);
1203
2929
  // a frame's jigs (its beams' drill and tap guides, length stops and squaring corners) on beds of their own, in the
1204
2930
  // project's plastic: exports/<project>/<assembly>.jigs.3mf, as cad beams --jigs writes them (--no-jigs leaves them)
1205
- const { cutListOf } = await import('../lib/beams.mjs'), jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
2931
+ const { cutListOf } = await import('../lib/beams.mjs'),
2932
+ jigs = !opt('no-jigs') && cutListOf(s) ? await (await import('../lib/jigs.mjs')).writeJigs(s) : null;
1206
2933
  let r;
1207
- try { r = await platesOf(s, { write: true, gap }); } catch (e) { if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e; r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] }; } // (bought fittings only: the jigs are what it prints)
2934
+ try {
2935
+ r = await platesOf(s, { write: true, gap });
2936
+ } catch (e) {
2937
+ if (e.code !== 'plates.empty' || !jigs?.jigs.length) throw e;
2938
+ r = { bed: null, gap: null, plates: [], touched: [], removed: [], findings: [] };
2939
+ } // (bought fittings only: the jigs are what it prints)
1208
2940
  const results = [];
1209
- for (const p of r.plates.filter((x) => !x.stood)) results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
1210
- const jigRows = jigs ? { plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })), count: jigs.jigs.length, grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1), findings: jigs.findings } : null;
1211
- const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some((x) => x.level === 'fail');
1212
- if (opt('json')) { console.log(JSON.stringify({ assembly: ref, bed: r.bed, gap: r.gap, plates: r.plates, repacked: r.touched, removed: r.removed, findings: r.findings, checks: results, ...(jigRows ? { jigs: jigRows } : {}) }, null, 2)); process.exitCode = fails ? 1 : 0; return; }
2941
+ for (const p of r.plates.filter((x) => !x.stood))
2942
+ results.push({ name: p.name, findings: await checkPlate(`${s.project}/${p.name}`) });
2943
+ const jigRows = jigs
2944
+ ? {
2945
+ plates: jigs.plates.map((p) => ({ ...p, file: path.relative(WS, p.file) })),
2946
+ count: jigs.jigs.length,
2947
+ grams: +jigs.jigs.reduce((t, x) => t + x.grams, 0).toFixed(1),
2948
+ findings: jigs.findings,
2949
+ }
2950
+ : null;
2951
+ const fails = [...r.findings, ...results.flatMap((x) => x.findings), ...(jigs?.findings ?? [])].some(
2952
+ (x) => x.level === 'fail',
2953
+ );
2954
+ if (opt('json')) {
2955
+ console.log(
2956
+ JSON.stringify(
2957
+ {
2958
+ assembly: ref,
2959
+ bed: r.bed,
2960
+ gap: r.gap,
2961
+ plates: r.plates,
2962
+ repacked: r.touched,
2963
+ removed: r.removed,
2964
+ findings: r.findings,
2965
+ checks: results,
2966
+ ...(jigRows ? { jigs: jigRows } : {}),
2967
+ },
2968
+ null,
2969
+ 2,
2970
+ ),
2971
+ );
2972
+ process.exitCode = fails ? 1 : 0;
2973
+ return;
2974
+ }
1213
2975
  report(r.findings);
1214
- if (r.plates.length) say(`${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`);
1215
- for (const p of r.plates) say(` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`);
2976
+ if (r.plates.length)
2977
+ say(
2978
+ `${ref}: ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}, parts ${r.gap} mm apart (the first layer's rule)`,
2979
+ );
2980
+ for (const p of r.plates)
2981
+ say(
2982
+ ` ${p.name}${p.stood ? ' (unchanged)' : ''}: ${p.material}, ${p.filament}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min: ${p.parts.map((x) => x.id).join(', ')}`,
2983
+ );
1216
2984
  if (r.removed.length) say(` removed ${r.removed.join(', ')} (nothing is on them now)`);
1217
- for (const x of results) { const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate'); say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`); for (const y of bad) say(` [${y.level}] ${y.text}`); }
2985
+ for (const x of results) {
2986
+ const bad = x.findings.filter((y) => (y.level === 'fail' || y.level === 'warn') && y.code !== 'rules.estimate');
2987
+ say(` ${x.name}: ${bad.length ? `${bad.length} to look at` : 'prints clean'}`);
2988
+ for (const y of bad) say(` [${y.level}] ${y.text}`);
2989
+ }
1218
2990
  if (jigRows?.count) {
1219
- say(`${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`);
1220
- for (const p of jigRows.plates) say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
2991
+ say(
2992
+ `${ref}: ${jigRows.count} jig${jigRows.count === 1 ? '' : 's'} for its beams, ${jigRows.grams} g, on ${jigRows.plates.length} plate${jigRows.plates.length === 1 ? '' : 's'} of their own (cad beams ${ref} --jigs says what each is for)`,
2993
+ );
2994
+ for (const p of jigRows.plates)
2995
+ say(` ${p.file}: ${p.material}, ${p.parts.length} part${p.parts.length === 1 ? '' : 's'}`);
1221
2996
  for (const f of jigRows.findings) say(` [${f.level}] ${f.text}`);
1222
2997
  }
1223
2998
  process.exitCode = fails ? 1 : 0;
@@ -1225,97 +3000,240 @@ async function platesCommand(what, ref) {
1225
3000
 
1226
3001
  // An assembly's findings as cad check gives them: each pose (or the one asked for), what is the same in every pose
1227
3002
  // said once and the rest under the pose's name, after its files' schema check. cad kit counts the same list
1228
- function assemblyFindings(s, a, pose) {
3003
+ // (raw: the assembly as it would be written, checked in place of its file's)
3004
+ function assemblyFindings(s, a, pose, raw) {
1229
3005
  const poses = pose ? [pose] : Object.keys(s.motion.poses);
1230
- const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`), layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => isPlainName(l))); // (object/name is a layout kept in an object; a name that is not plain is refused where the layout is read)
1231
- const schemaProblems = [...(fs.existsSync(file) ? schemaFindings(JSON.parse(fs.readFileSync(file, 'utf8')), 'assembly', path.relative(WS, file)) : []),
1232
- ...[...layouts].map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`)).filter((f) => fs.existsSync(f)).flatMap((f) => schemaFindings(JSON.parse(fs.readFileSync(f, 'utf8')), 'layout', path.relative(WS, f)))];
3006
+ const file = path.join(paths.project(s.project), 'assemblies', `${s.name}.json`),
3007
+ layouts = new Set((a.items || []).map((i) => i.repeat?.layout).filter((l) => isPlainName(l))); // (object/name is a layout kept in an object; a name that is not plain is refused where the layout is read)
3008
+ const schemaProblems = [
3009
+ ...(raw || fs.existsSync(file) ? schemaFindings(raw ?? readJson(file), 'assembly', path.relative(WS, file)) : []),
3010
+ ...[...layouts]
3011
+ .map((l) => path.join(paths.project(s.project), 'layouts', `${l}.json`))
3012
+ .filter((f) => fs.existsSync(f))
3013
+ .flatMap((f) => schemaFindings(readJson(f), 'layout', path.relative(WS, f))),
3014
+ ];
1233
3015
  let findings = checkAssembly(s);
1234
3016
  if (poses.length > 1) {
1235
- const each = poses.map((p) => [p, checkAssembly(s.at(p))]), same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
1236
- findings = [{ level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } }, ...each[0][1].filter(same),
1237
- ...each.flatMap(([p, list]) => list.filter((x) => !same(x)).map((x) => ({ ...x, text: `${p}: ${x.text}`, ...(x.card ? { card: `${p}: ${x.card}` } : {}), refs: { ...x.refs, pose: p } })))];
3017
+ const each = poses.map((p) => [p, checkAssembly(s.at(p))]),
3018
+ same = (x) => each.every(([, list]) => list.some((y) => y.text === x.text && y.level === x.level));
3019
+ findings = [
3020
+ { level: 'pass', text: `${poses.length} poses checked: ${poses.join(', ')}`, code: 'poses', refs: { poses } },
3021
+ ...each[0][1].filter(same),
3022
+ ...each.flatMap(([p, list]) =>
3023
+ list
3024
+ .filter((x) => !same(x))
3025
+ .map((x) => ({
3026
+ ...x,
3027
+ text: `${p}: ${x.text}`,
3028
+ ...(x.card ? { card: `${p}: ${x.card}` } : {}),
3029
+ refs: { ...x.refs, pose: p },
3030
+ })),
3031
+ ),
3032
+ ];
1238
3033
  }
1239
- findings.unshift(...(schemaProblems.length ? schemaProblems : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]));
3034
+ findings.unshift(
3035
+ ...(schemaProblems.length
3036
+ ? schemaProblems
3037
+ : [{ level: 'pass', text: 'files match their schemas', code: 'schema' }]),
3038
+ );
1240
3039
  return findings;
1241
3040
  }
1242
3041
 
1243
3042
  // cad kit: the folder to build an assembly from, without the model (lib/kit.mjs)
1244
3043
  async function kitCommand(ref) {
1245
- if (!isAssembly(ref)) throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
3044
+ if (!isAssembly(ref))
3045
+ throw new Error(`cad kit works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1246
3046
  // (laying out its plates reads the printer's rule set: a fresh workspace gets its own copy in rules/, as cad plates
1247
3047
  // gives it, and the kit says which it copied)
1248
- const rulesDir = path.join(WS, 'rules'), had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
1249
- const s = await buildAssembly(ref), { writeKit } = await import('../lib/kit.mjs');
3048
+ const rulesDir = path.join(WS, 'rules'),
3049
+ had = new Set(fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []);
3050
+ const s = await buildAssembly(ref),
3051
+ { writeKit } = await import('../lib/kit.mjs');
1250
3052
  const r = await writeKit(s, assemblyFindings(s, s.a, undefined), { pictures: !!opt('pictures'), preview });
1251
- const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : []).filter((f) => f.endsWith('.json') && !had.has(f)).map((f) => `rules/${f}`);
1252
- const shown = { assembly: ref, dir: path.relative(WS, r.dir), files: r.files, copied, plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({ name, material, filament, parts: parts.length, grams, minutes, file, issues })), jigs: r.jigs, sheets: r.sheets, steps: r.steps, warnings: r.findings.map((f) => f.text) };
3053
+ const copied = (fs.existsSync(rulesDir) ? fs.readdirSync(rulesDir) : [])
3054
+ .filter((f) => f.endsWith('.json') && !had.has(f))
3055
+ .map((f) => `rules/${f}`);
3056
+ const shown = {
3057
+ assembly: ref,
3058
+ dir: path.relative(WS, r.dir),
3059
+ files: r.files,
3060
+ copied,
3061
+ plates: r.plates.map(({ name, material, filament, parts, grams, minutes, file, issues }) => ({
3062
+ name,
3063
+ material,
3064
+ filament,
3065
+ parts: parts.length,
3066
+ grams,
3067
+ minutes,
3068
+ file,
3069
+ issues,
3070
+ })),
3071
+ jigs: r.jigs,
3072
+ sheets: r.sheets,
3073
+ steps: r.steps,
3074
+ warnings: r.findings.map((f) => f.text),
3075
+ };
1253
3076
  if (opt('json')) return console.log(JSON.stringify(shown, null, 2));
1254
3077
  say(`${ref}: the kit to build it from, in ${shown.dir}${path.sep}`);
1255
- say(` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`);
3078
+ say(
3079
+ ` README.md: what the checks say, what to buy, what to print${r.sheets.length ? ', the cut list, the drilling and tapping' : ''}${r.steps ? `, and the build in ${r.steps} steps` : ''}`,
3080
+ );
1256
3081
  say(' buy.csv: the shopping list');
1257
- for (const p of shown.plates) say(` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`);
3082
+ for (const p of shown.plates)
3083
+ say(
3084
+ ` ${p.file}: ${p.material}, ${p.parts} part${p.parts === 1 ? '' : 's'}, ${p.grams} g, about ${p.minutes} min${p.issues.length ? ` (${p.issues.length} to look at)` : ''}`,
3085
+ );
1258
3086
  for (const p of r.jigs?.plates ?? []) say(` ${p.file}: ${r.jigs.count} jigs for the beams, ${p.parts} parts`);
1259
3087
  for (const x of r.sheets) say(` ${x.file}: mark ${x.mark} (${x.items.join(', ')})`);
1260
3088
  const pics = r.files.filter((f) => f.startsWith('pictures/'));
1261
3089
  if (pics.length) say(` pictures/: ${pics.length} pictures (the whole, and the steps of the build)`);
1262
3090
  for (const w of shown.warnings) say(` warning: ${w}`);
1263
- for (const f of copied) say(`and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`);
3091
+ for (const f of copied)
3092
+ say(
3093
+ `and copied ${f} into this workspace: the rule set its plates were laid out by, yours to keep and edit (the next kit reads your copy)`,
3094
+ );
3095
+ }
3096
+
3097
+ // cad frame --size --write: the design it would write, built and checked as cad check checks it; refused, naming the
3098
+ // failing checks (each code and how many, the first three in full), where any check would fail
3099
+ async function refuseFailing(ref, next) {
3100
+ const n = await buildAssembly(ref, [], {}, { assembly: next }),
3101
+ failing = assemblyFindings(n, n.a, undefined, next).filter((x) => x.level === 'fail');
3102
+ if (!failing.length) return;
3103
+ const count = new Map();
3104
+ for (const x of failing) count.set(x.code ?? 'check', (count.get(x.code ?? 'check') ?? 0) + 1);
3105
+ const codes = [...count].map(([c, k]) => (k > 1 ? `${c} x${k}` : c)).join(', '),
3106
+ first = failing
3107
+ .slice(0, 3)
3108
+ .map((x) => x.text)
3109
+ .join('; ');
3110
+ throw new Error(
3111
+ `${ref}: with the sized profiles written in, cad check would fail ${failing.length} check${failing.length > 1 ? 's' : ''} (${codes}), so nothing is written. The first: ${first}. Fix what they name in the design, or leave the profile that breaks them out of frame.size.profiles, then size again`,
3112
+ );
1264
3113
  }
1265
3114
 
1266
3115
  // cad frame: a generated frame as it expands, and --expand writes the expansion into the assembly, to edit by hand
1267
3116
  async function frameCommand(ref) {
1268
- if (!isAssembly(ref)) throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1269
- const { expandFrame, frameText } = await import('../lib/framegen.mjs'), { assemblyPath } = await import('../lib/assembly.mjs');
1270
- const file = assemblyPath(ref), raw = readJson(file);
3117
+ if (!isAssembly(ref))
3118
+ throw new Error(`cad frame works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
3119
+ const { expandFrame, frameText } = await import('../lib/framegen.mjs'),
3120
+ { assemblyPath } = await import('../lib/assembly.mjs');
3121
+ const file = assemblyPath(ref),
3122
+ raw = readJson(file);
1271
3123
  if (opt('size')) {
1272
- const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'), { placeItems, jointValues, mul } = await import('@rulecad/model-link');
1273
- const s = await buildAssembly(ref), r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
1274
- if (!r) throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
1275
- const rows = r.rows, out = { assembly: ref, ok: r.ok, total: r.total, drawn: r.drawn, tried: r.tried, search: r.search, groups: rows, limits: r.limits };
3124
+ const { frameSizing, sizingText, writeSizing, sizeOption } = await import('../lib/framesize.mjs'),
3125
+ { placeItems, jointValues, mul } = await import('@rulecad/model-link');
3126
+ const s = await buildAssembly(ref),
3127
+ r = frameSizing(s, { placeItems, jointValues, mul }, sizeOption(s) ?? undefined);
3128
+ if (!r)
3129
+ throw new Error(`${ref} has no frame to size: its beams need joins between them, or "frame": { "supports" }`);
3130
+ const rows = r.rows,
3131
+ out = {
3132
+ assembly: ref,
3133
+ ok: r.ok,
3134
+ total: r.total,
3135
+ drawn: r.drawn,
3136
+ tried: r.tried,
3137
+ search: r.search,
3138
+ groups: rows,
3139
+ limits: r.limits,
3140
+ unchecked: r.unchecked,
3141
+ };
1276
3142
  if (opt('write')) {
1277
- if (!r.ok) throw new Error(`${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`);
1278
- if (opt('dry-run')) { // the sizing and the check above, nothing written
1279
- if (opt('json')) return console.log(JSON.stringify({ ...out, file: rel(file), written: false, dryRun: true }, null, 2));
3143
+ if (!r.ok)
3144
+ throw new Error(
3145
+ `${ref}: no profile in the list meets every limit, so nothing is written (cad frame ${ref} --size says how near it comes)`,
3146
+ );
3147
+ // the profiles drawn are already the ones chosen: nothing to write, and a generated frame stays generated
3148
+ if (rows.every((x) => !x.roll && x.drawn.length === 1 && x.drawn[0] === x.profile.replace(/^profile-/, ''))) {
3149
+ if (opt('json'))
3150
+ return console.log(JSON.stringify({ ...out, file: rel(file), written: false, unchanged: true }, null, 2));
1280
3151
  console.log(sizingText(r).join('\n'));
1281
- return console.log(`dry run, nothing written: would write ${rel(file)}`);
3152
+ return console.log(
3153
+ `nothing written: every beam already has the profile chosen for it, so ${rel(file)} stays as it is`,
3154
+ );
1282
3155
  }
1283
- fs.writeFileSync(file, `${JSON.stringify(writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r), null, 2)}\n`);
3156
+ const next = writeSizing(raw, raw.frame?.kind != null ? expandFrame(raw, s.num).a : raw, r);
3157
+ await refuseFailing(ref, next);
3158
+ if (opt('dry-run')) {
3159
+ // the sizing and the checks above, nothing written
3160
+ if (opt('json'))
3161
+ return console.log(JSON.stringify({ ...out, file: rel(file), written: false, dryRun: true }, null, 2));
3162
+ console.log(sizingText(r).join('\n'));
3163
+ return console.log(`dry run, nothing written: would write ${rel(file)}, which cad check passes`);
3164
+ }
3165
+ fs.writeFileSync(file, `${JSON.stringify(next, null, 2)}\n`);
1284
3166
  if (opt('json')) return console.log(JSON.stringify({ ...out, file: path.relative(WS, file) }, null, 2));
1285
3167
  console.log(sizingText(r).join('\n'));
1286
- return console.log(`wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`);
3168
+ return console.log(
3169
+ `wrote ${path.relative(WS, file)}: ${rows.reduce((t, x) => t + x.beams.length, 0)} beams given their profiles${raw.frame?.kind != null ? ' (the generated frame written out expanded, as --expand does, as a generator takes one profile)' : ''}; their lines are kept (a deeper beam that would stand past the end of the one it meets moves along it), so check the joins and ends of any beam that changed size`,
3170
+ );
1287
3171
  }
1288
3172
  if (opt('json')) return console.log(JSON.stringify(out, null, 2));
1289
- return console.log(`${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`);
3173
+ return console.log(
3174
+ `${ref}: ${sizingText(r).join('\n')}\n(cad frame ${ref} --size --write writes these profiles into the assembly)`,
3175
+ );
1290
3176
  }
1291
- if (raw.frame?.kind == null) throw new Error(`${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`);
1292
- const s = await buildAssembly(ref), m = s.generated, out = expandFrame(raw, s.num).a;
3177
+ if (raw.frame?.kind == null)
3178
+ throw new Error(
3179
+ `${ref} asks for no generated frame: give it "frame": { "kind": "box", "inside": [300, 300, 350], "profile": "2020-misumi-hfs5", "join": "blind" }`,
3180
+ );
3181
+ const s = await buildAssembly(ref),
3182
+ m = s.generated,
3183
+ out = expandFrame(raw, s.num).a;
1293
3184
  if (opt('expand') && opt('dry-run')) {
1294
- if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: rel(file), written: false, dryRun: true, frame: m, expanded: out }, null, 2));
1295
- return console.log(`dry run, nothing written: would write ${rel(file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings`);
3185
+ if (opt('json'))
3186
+ return console.log(
3187
+ JSON.stringify(
3188
+ { assembly: ref, file: rel(file), written: false, dryRun: true, frame: m, expanded: out },
3189
+ null,
3190
+ 2,
3191
+ ),
3192
+ );
3193
+ return console.log(
3194
+ `dry run, nothing written: would write ${rel(file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings`,
3195
+ );
1296
3196
  }
1297
3197
  if (opt('expand')) {
1298
3198
  fs.writeFileSync(file, `${JSON.stringify(out, null, 2)}\n`);
1299
- if (opt('json')) return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
1300
- return console.log(`wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`);
3199
+ if (opt('json'))
3200
+ return console.log(JSON.stringify({ assembly: ref, file: path.relative(WS, file), frame: m }, null, 2));
3201
+ return console.log(
3202
+ `wrote ${path.relative(WS, file)}: the ${m.kind} as ${m.beams.length + (m.moving ? 1 : 0)} beams, ${m.joins.length} joins and ${m.ends.length + m.panels.length} fittings, to edit by hand (its "frame" keeps only how it is solved)`,
3203
+ );
1301
3204
  }
1302
3205
  if (opt('json')) return console.log(JSON.stringify({ assembly: ref, frame: m, expanded: out }, null, 2));
1303
- console.log(`${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`);
3206
+ console.log(
3207
+ `${ref}: ${frameText(m).join('\n')}\n(cad frame ${ref} --expand writes these into the assembly, to edit by hand)`,
3208
+ );
1304
3209
  }
1305
3210
 
1306
3211
  async function listCommand(what, ref) {
1307
- if (!isAssembly(ref)) throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
1308
- const s = await buildAssembly(ref);
3212
+ if (!isAssembly(ref))
3213
+ throw new Error(`cad ${what} works on an assembly (<project>/<assembly>), and there is no "${ref}"`);
3214
+ const s = await buildAssembly(ref, [], assemblyOverrides(ref, sets())); // (--set item.variable=value, as cad check)
1309
3215
  if (what === 'list') {
1310
- const { shoppingList, listText } = await import('../lib/list.mjs'), l = shoppingList(s);
3216
+ const { shoppingList, listText } = await import('../lib/list.mjs'),
3217
+ l = shoppingList(s);
1311
3218
  return console.log(opt('json') ? JSON.stringify(l, null, 2) : listText(ref, l));
1312
3219
  }
1313
3220
  if (what === 'beams' && opt('jigs')) {
1314
- const { writeJigs, jigsText } = await import('../lib/jigs.mjs'), r = await writeJigs(s), rel = (f) => path.relative(WS, f);
3221
+ const { writeJigs, jigsText } = await import('../lib/jigs.mjs'),
3222
+ r = await writeJigs(s),
3223
+ rel = (f) => path.relative(WS, f);
1315
3224
  const shown = { ...r, plates: r.plates.map((p) => ({ ...p, file: rel(p.file) })) };
1316
3225
  if (opt('preview') && r.parts.length) {
1317
3226
  const out = paths.preview(s.project, `${s.name}-jigs.png`);
1318
- await preview(r.parts.flatMap((o) => o.parts.map((p) => ({ name: p.name, label: p.name, role: 'part', triangles: p.triangles }))), { title: `${s.a.title || s.name}: jigs`, meta: `${r.jigs.length} jigs on ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}`, out });
3227
+ await preview(
3228
+ r.parts.flatMap((o) =>
3229
+ o.parts.map((p) => ({ name: p.name, label: p.name, role: 'part', triangles: p.triangles })),
3230
+ ),
3231
+ {
3232
+ title: `${s.a.title || s.name}: jigs`,
3233
+ meta: `${r.jigs.length} jigs on ${r.plates.length} plate${r.plates.length === 1 ? '' : 's'}`,
3234
+ out,
3235
+ },
3236
+ );
1319
3237
  shown.preview = rel(out);
1320
3238
  }
1321
3239
  delete shown.parts;
@@ -1326,90 +3244,295 @@ async function listCommand(what, ref) {
1326
3244
  return;
1327
3245
  }
1328
3246
  if (what === 'beams') {
1329
- const { writeBeamSheets } = await import('../lib/beams.mjs'), sheets = writeBeamSheets(s);
1330
- if (opt('json')) return console.log(JSON.stringify(sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })), null, 2));
3247
+ const { writeBeamSheets } = await import('../lib/beams.mjs'),
3248
+ sheets = writeBeamSheets(s);
3249
+ if (opt('json'))
3250
+ return console.log(
3251
+ JSON.stringify(
3252
+ sheets.map((x) => ({ ...x, file: path.relative(WS, x.file) })),
3253
+ null,
3254
+ 2,
3255
+ ),
3256
+ );
1331
3257
  if (!sheets.length) return console.log(`${ref} has no beams`);
1332
3258
  for (const x of sheets) say(` mark ${x.mark} (${x.items.join(', ')}), 1:${x.scale}: ${path.relative(WS, x.file)}`);
1333
- const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'), sag = writeFrameShape(s), mode = writeFrameMode(s);
1334
- if (sag) say(` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`);
1335
- if (mode) say(` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`);
3259
+ const { writeFrameShape, writeFrameMode } = await import('../lib/framecheck.mjs'),
3260
+ sag = writeFrameShape(s),
3261
+ mode = writeFrameMode(s);
3262
+ if (sag)
3263
+ say(
3264
+ ` the frame's sag, drawn ${+sag.scale.toPrecision(3)} times its size (a check view): ${path.relative(WS, sag.file)}`,
3265
+ );
3266
+ if (mode)
3267
+ say(
3268
+ ` the frame's lowest mode, ${+mode.Hz.toPrecision(3)} Hz, animated (a check view): ${path.relative(WS, mode.file)}`,
3269
+ );
1336
3270
  return;
1337
3271
  }
1338
- const { wiresFor } = await import('../lib/assembly.mjs'), { wiringSheet } = await import('../lib/wires.mjs'), rows = wiresFor(s);
1339
- if (opt('json')) return console.log(JSON.stringify(rows.map(({ route, ...r }) => r), null, 2));
3272
+ const { wiresFor } = await import('../lib/assembly.mjs'),
3273
+ { wiringSheet } = await import('../lib/wires.mjs'),
3274
+ rows = wiresFor(s);
3275
+ if (opt('json'))
3276
+ return console.log(
3277
+ JSON.stringify(
3278
+ rows.map(({ route, ...r }) => r),
3279
+ null,
3280
+ 2,
3281
+ ),
3282
+ );
1340
3283
  if (!rows.length) return console.log(`${ref} has no "wires"`);
1341
- if (opt('out')) { fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n'); return console.log(`wrote ${opt('out')}`); }
1342
- const { writeWiring } = await import('../lib/buildpage.mjs'), file = writeWiring(s);
1343
- console.log(wiringSheet(rows)); say(path.relative(WS, file));
3284
+ if (opt('out')) {
3285
+ fs.writeFileSync(path.resolve(opt('out')), wiringSheet(rows) + '\n');
3286
+ return console.log(`wrote ${opt('out')}`);
3287
+ }
3288
+ const { writeWiring } = await import('../lib/buildpage.mjs'),
3289
+ file = writeWiring(s);
3290
+ console.log(wiringSheet(rows));
3291
+ say(path.relative(WS, file));
3292
+ }
3293
+
3294
+ // cad coupons: the kit's coupons as a project of this workspace's own, projects/coupons, with the MEASURE.md that says
3295
+ // how to read each and the cad measured command that writes it back. Copied, never linked: the maker prints and keeps
3296
+ // them as they are, and a workspace that has the project already keeps it (a newer kit's comes in under another name)
3297
+ function couponsCommand() {
3298
+ const to = paths.project('coupons'),
3299
+ from = path.join(TOOL, 'templates', 'coupons');
3300
+ if (fs.existsSync(to))
3301
+ throw new CadError(
3302
+ 'coupons.exists',
3303
+ "projects/coupons is here already, and is kept as it is: to get the kit's newest, rename yours first (projects/coupons-old) and run cad coupons again",
3304
+ );
3305
+ fs.cpSync(from, to, { recursive: true });
3306
+ say(
3307
+ 'made projects/coupons: the fixings, holds and slot coupons, and MEASURE.md, which says how to print and read each and the command that writes it back',
3308
+ );
3309
+ say(' npx cad export coupons/fixings-coupon (and holds-coupon, slot-coupon): each as a 3MF to print');
3310
+ say(' npx cad measured x1c.pilot_m3=<figure>: a result written back, for every design here to follow');
3311
+ say(' npx cad measured --export: what you measured, as a change to send to the kit');
3312
+ const drawsFor = printerOf(null);
3313
+ if (drawsFor !== 'x1c')
3314
+ say(
3315
+ ` note: the coupons are drawn from the X1C's rules (x1c), and this workspace prints on ${drawsFor}: their figures are the X1C's until they are drawn from yours`,
3316
+ );
1344
3317
  }
1345
3318
 
3319
+ // cad measured [<project>/<assembly>] <name>=<value> …: with an assembly, its checks run either side and what moved is
3320
+ // said; without one (the first word a name=value, or no word at all for --export and --strike), a rule measured on a
3321
+ // coupon is written all the same, into the workspace's ledger
1346
3322
  async function measuredCommand(ref) {
1347
- const { recordMeasured, assumptionsTable, writeTable, ledgerLines } = await import('../lib/measured.mjs');
3323
+ const { recordMeasured, assumptions, assumptionsTable, writeTable, ledgerLines, strikeLedger, exportMeasured } =
3324
+ await import('../lib/measured.mjs');
3325
+ const onto = ref && ref.includes('/') ? ref : null;
3326
+ if (opt('export')) return exportCommand(exportMeasured);
3327
+ if (opt('table') && !onto)
3328
+ throw new CadError(
3329
+ 'measured.usage',
3330
+ 'usage: cad measured <project>/<assembly> --table: the figures that assembly rests on (a table is of one assembly)',
3331
+ );
1348
3332
  if (opt('table')) {
3333
+ if (opt('json')) return console.log(JSON.stringify(await assumptions(ref), null, 2));
1349
3334
  const table = await assumptionsTable(ref);
1350
- if (opt('out')) { writeTable(path.resolve(opt('out')), table); return console.log(`wrote the table to ${opt('out')}`); }
3335
+ if (opt('out')) {
3336
+ writeTable(path.resolve(opt('out')), table);
3337
+ return console.log(`wrote the table to ${opt('out')}`);
3338
+ }
1351
3339
  return console.log(table);
1352
3340
  }
1353
- const values = Object.fromEntries(positional().slice(2).map((x) => { const i = x.indexOf('='); if (i < 1) throw new Error(`usage: cad measured <project>/<assembly> <name>=<value> … (got "${x}")`); return [x.slice(0, i), Number(x.slice(i + 1))]; }));
1354
- const r = await recordMeasured(ref, values, { unit: opt('unit'), source: opt('source'), rule: opt('rule') });
3341
+ if (args.includes('--strike')) return strikeCommand(onto, strikeLedger);
3342
+ const values = Object.fromEntries(
3343
+ positional()
3344
+ .slice(onto ? 2 : 1)
3345
+ .map((x) => {
3346
+ const i = x.indexOf('=');
3347
+ if (i < 1)
3348
+ throw new Error(
3349
+ `usage: cad measured [<project>/<assembly>] <name>=<value> … (got "${x}"): an assembly is <project>/<assembly>`,
3350
+ );
3351
+ const v = x.slice(i + 1).trim();
3352
+ // (Number('') is 0: an empty figure would be written as 0, the most trusted kind)
3353
+ if (!v)
3354
+ throw new CadError(
3355
+ 'measured.value',
3356
+ `${x.slice(0, i)} has no figure after its "=": give the one measured (${x.slice(0, i)}=0.25)`,
3357
+ );
3358
+ return [x.slice(0, i), Number(v)];
3359
+ }),
3360
+ );
3361
+ const r = await recordMeasured(onto, values, {
3362
+ unit: opt('unit'),
3363
+ source: opt('source'),
3364
+ rule: opt('rule'),
3365
+ force: !!opt('force'),
3366
+ });
1355
3367
  if (opt('json')) return console.log(JSON.stringify({ entries: r.entries, moved: r.moved }, null, 2));
1356
3368
  for (const l of ledgerLines(r.entries)) say(l);
1357
- for (const m of r.moved) say(m.figure ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}` : ` ${m.code}: ${m.text}`);
1358
- if (!r.moved.length) say(' nothing the checks say has moved');
3369
+ for (const m of r.moved)
3370
+ say(
3371
+ m.figure
3372
+ ? ` ${m.figure}: ${Number(m.from.toFixed(4))} ${m.unit} to ${Number(m.to.toFixed(4))} ${m.unit}`
3373
+ : ` ${m.code}: ${m.text}`,
3374
+ );
3375
+ if (!onto)
3376
+ say(
3377
+ ` kept in ledger.jsonl (cad history shows it); give an assembly first to see what it moves there (cad measured <project>/<assembly> ${Object.keys(values)[0]}=…)`,
3378
+ );
3379
+ else if (!r.moved.length) say(' nothing the checks say has moved');
3380
+ }
3381
+
3382
+ // cad measured --export: what this workspace measured that the kit lacks, as a diff of the kit's rule sets to send it
3383
+ function exportCommand(exportMeasured) {
3384
+ const r = exportMeasured();
3385
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3386
+ if (!r.sets.length && !r.alone.length)
3387
+ return say(
3388
+ 'nothing measured here that the kit lacks: cad measured writes a figure from a coupon (cad coupons adds them), and this lists it once it is',
3389
+ );
3390
+ if (r.diff) process.stdout.write(r.diff);
3391
+ // (on stderr, so the diff alone goes to a file: cad measured --export > measured.diff)
3392
+ for (const a of r.alone)
3393
+ console.error(
3394
+ `${a.file} is a set the kit has no file for; send its measured figures as they are: ${a.rules.map((x) => `${x.name} = ${x.value}${x.unit ? ` ${x.unit}` : ''}`).join(', ')}`,
3395
+ );
3396
+ if (r.sets.length)
3397
+ console.error(
3398
+ `${r.sets.reduce((t, x) => t + x.rules.length, 0)} measured figure(s) the kit lacks, as a change to ${r.sets.map((x) => x.file).join(', ')}: send it to https://github.com/JoniBach/rulecad/issues with the printer and plastic you printed in`,
3399
+ );
3400
+ }
3401
+
3402
+ // cad measured <project>/<assembly> --strike <date> <name>: a row taken out of the ledger (a slip written as measured).
3403
+ // The rule set it went into is a file of its own: the command says what it still holds, and leaves it as it is
3404
+ // (with no assembly, a row written without one: the workspace's ledger)
3405
+ async function strikeCommand(ref, strikeLedger) {
3406
+ const date = opt('strike'),
3407
+ names = positional().slice(ref ? 2 : 1);
3408
+ if (names.length !== 1)
3409
+ throw new CadError(
3410
+ 'measured.usage',
3411
+ `usage: cad measured [<project>/<assembly>] --strike <date> <name>[=<figure>]: the date and the name of the row to take out, as cad history${ref ? ` ${ref}` : ''} shows them`,
3412
+ );
3413
+ const r = strikeLedger(ref, date, names[0]);
3414
+ if (opt('json')) return console.log(JSON.stringify(r, null, 2));
3415
+ say(
3416
+ `struck ${r.struck.length === 1 ? 'a row' : `${r.struck.length} rows`} from ${ref ? `projects/${ref.split('/')[0]}/` : ''}ledger.jsonl:`,
3417
+ );
3418
+ for (const l of r.lines) say(` ${l}`);
3419
+ if (r.rule) say(r.rule.said);
1359
3420
  }
1360
3421
 
1361
3422
  async function ledger(project, name) {
1362
3423
  const { readLedger, ledgerLines } = await import('../lib/measured.mjs');
1363
- const rows = readLedger(project).filter((e) => !name || e.assembly === name);
3424
+ const rows = readLedger(project).filter((e) => !name || e.assembly === name); // (project null: the workspace's)
1364
3425
  return { rows, lines: ledgerLines(rows) };
1365
3426
  }
1366
3427
 
1367
3428
  async function history(ref) {
3429
+ // cad history alone: the figures written with no assembly (cad measured x1c.pilot_m3=2.9), the workspace's ledger
3430
+ if (!ref) {
3431
+ const { rows, lines } = await ledger(null);
3432
+ if (opt('json')) return console.log(JSON.stringify({ ledger: rows }, null, 2));
3433
+ if (!lines.length)
3434
+ return say(
3435
+ "nothing measured here without an assembly yet (cad measured x1c.pilot_m3=<value>); cad history <project> shows a project's",
3436
+ );
3437
+ say('measured on coupons, predicted against measured:');
3438
+ for (const l of lines) say(` ${l}`);
3439
+ return;
3440
+ }
1368
3441
  const [project, name] = ref.split('/');
1369
3442
  if (name && isAssembly(ref)) {
1370
3443
  const { rows, lines } = await ledger(project, name);
1371
3444
  if (opt('json')) return console.log(JSON.stringify({ assembly: ref, ledger: rows }, null, 2));
1372
3445
  if (!lines.length) return say(`${ref}: nothing measured yet (cad measured ${ref} <name>=<value>)`);
1373
- say('predicted against measured:'); for (const l of lines) say(` ${l}`);
3446
+ say('predicted against measured:');
3447
+ for (const l of lines) say(` ${l}`);
1374
3448
  return;
1375
3449
  }
1376
3450
  if (!name) {
1377
3451
  const { rows, lines } = await ledger(project);
1378
- if (lines.length && !opt('json')) { console.log('predicted against measured:'); for (const l of lines) console.log(` ${l}`); }
1379
- if (opt('json')) return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
3452
+ if (lines.length && !opt('json')) {
3453
+ console.log('predicted against measured:');
3454
+ for (const l of lines) console.log(` ${l}`);
3455
+ }
3456
+ if (opt('json'))
3457
+ return console.log(JSON.stringify({ project, releases: tags(project).reverse(), ledger: rows }, null, 2));
1380
3458
  for (const t of tags(project).reverse()) console.log(`${t.tag} ${t.date} ${t.kind} ${t.message}`);
1381
3459
  return status(project);
1382
3460
  }
1383
- const d = locate(ref), done = prints(d);
3461
+ const d = locate(ref),
3462
+ done = prints(d);
1384
3463
  const s = await since(d);
1385
- if (opt('json')) return console.log(JSON.stringify({ object: ref, unreleased: s.kind && s.last ? { kind: s.kind, reasons: s.reasons.map((r) => r.text) } : null, releases: tags(d.project, d.name).reverse().map((t) => ({ ...t, prints: done.filter((x) => x.version === t.version) })) }, null, 2));
1386
- if (s.kind && s.last) { console.log(`unreleased (needs ${s.kind}):`); for (const r of s.reasons) console.log(` ${r.text}`); }
3464
+ if (opt('json'))
3465
+ return console.log(
3466
+ JSON.stringify(
3467
+ {
3468
+ object: ref,
3469
+ unreleased: s.kind && s.last ? { kind: s.kind, reasons: s.reasons.map((r) => r.text) } : null,
3470
+ releases: tags(d.project, d.name)
3471
+ .reverse()
3472
+ .map((t) => ({ ...t, prints: done.filter((x) => x.version === t.version) })),
3473
+ },
3474
+ null,
3475
+ 2,
3476
+ ),
3477
+ );
3478
+ if (s.kind && s.last) {
3479
+ console.log(`unreleased (needs ${s.kind}):`);
3480
+ for (const r of s.reasons) console.log(` ${r.text}`);
3481
+ }
1387
3482
  for (const t of tags(d.project, d.name).reverse()) {
1388
3483
  console.log(`${t.version.padEnd(8)} ${t.date} ${t.kind.padEnd(5)} ${t.message}`);
1389
- for (const p of done.filter((x) => x.version === t.version)) console.log(` printed ${p.date} in ${p.material}: ${p.result}${p.note ? `, ${p.note}` : ''}${p.set ? ` (${p.set})` : ''}`);
3484
+ for (const p of done.filter((x) => x.version === t.version))
3485
+ console.log(
3486
+ ` printed ${p.date} in ${p.material}: ${p.result}${p.note ? `, ${p.note}` : ''}${p.set ? ` (${p.set})` : ''}`,
3487
+ );
1390
3488
  }
1391
3489
  }
1392
3490
 
1393
3491
  async function diff(d, from, to) {
1394
3492
  if (!from) throw new Error('usage: cad diff <project>/<object> <from> [<to>]');
1395
- const a = await snap(materialise(d, from)), b = await snap(to ? materialise(d, to) : d);
1396
- const r = compare(a, b);
3493
+ const A = materialise(d, from),
3494
+ B = to ? materialise(d, to) : d;
3495
+ const r = compare(await snap(A, A.reads), await snap(B, B.reads || A.reads));
1397
3496
  console.log(`${d.project}/${d.name} ${from} → ${to || 'now'}: ${r.kind ? `a ${r.kind} change` : 'no changes'}`);
1398
3497
  for (const x of r.reasons) console.log(` ${x.kind.padEnd(5)} ${x.text}`);
1399
3498
  }
1400
3499
 
1401
3500
  function printed(d) {
1402
3501
  const result = opt('result');
1403
- if (!['ok', 'failed'].includes(result)) throw new Error('--result ok or --result failed (and --note "what happened")');
1404
- const object = readObject(d), released = tags(d.project, d.name).map((t) => t.version), version = opt('version') || released.at(-1) || object.version;
1405
- if (opt('version') && version !== object.version && !released.includes(version)) throw new Error(`${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`);
1406
- const entry = { date: today(), object: d.name, version, ...(opt('set') ? { set: opt('set') } : {}), material: opt('material') || object.material, result, ...(opt('note') ? { note: opt('note') } : {}) };
1407
- fs.appendFileSync(printsFile(d), JSON.stringify(entry) + '\n');
3502
+ if (!['ok', 'failed'].includes(result))
3503
+ throw new Error('--result ok or --result failed (and --note "what happened")');
3504
+ const object = readObject(d),
3505
+ released = tags(d.project, d.name).map((t) => t.version),
3506
+ version = opt('version') || released.at(-1) || object.version;
3507
+ if (opt('version') && version !== object.version && !released.includes(version))
3508
+ throw new Error(
3509
+ `${d.name} has no version ${version} (${released.length ? `releases: ${released.join(', ')}` : `unreleased, at ${object.version}`})`,
3510
+ );
3511
+ const entry = {
3512
+ date: today(),
3513
+ object: d.name,
3514
+ version,
3515
+ ...(opt('set') ? { set: opt('set') } : {}),
3516
+ material: opt('material') || object.material,
3517
+ result,
3518
+ ...(opt('note') ? { note: opt('note') } : {}),
3519
+ };
3520
+ fs.appendFileSync(insideWorkspace(printsFile(d)), JSON.stringify(entry) + '\n'); // (never through a link: rules.mjs)
1408
3521
  console.log(`logged in ${path.relative(WS, printsFile(d))}: ${d.name}@${version} ${result}`);
1409
3522
  }
1410
3523
 
1411
3524
  main().catch((e) => {
1412
- if (opt('json')) console.log(JSON.stringify({ error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) }, null, 2));
1413
- else console.error(`${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`);
3525
+ if (opt('json'))
3526
+ console.log(
3527
+ JSON.stringify(
3528
+ { error: errorData({ ...e, message: e.message, code: e.code, file: e.file && path.relative(WS, e.file) }) },
3529
+ null,
3530
+ 2,
3531
+ ),
3532
+ );
3533
+ else
3534
+ console.error(
3535
+ `${e.message}${e.file ? ` (${path.relative(WS, e.file)}${e.line ? `:${e.line}` : ''}${e.path ? `: ${e.path}` : ''})` : ''}`,
3536
+ );
1414
3537
  process.exit(1);
1415
3538
  });