@rulecad/cad 0.7.60 → 0.7.62

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENTS.md CHANGED
@@ -40,8 +40,14 @@ variable says which rule it comes from. Follow these steps; they're what makes a
40
40
  1. `npx cad history <project>/<object>` first: read the print log. A failed print is the reason for most changes:
41
41
  fix the rule or variable it points at (a measured fit beats a community rule).
42
42
  2. Change, then check, preview and look, as for a new part. Change values with `npx cad set <project>/<object>
43
- name=value` and assemblies with `npx cad add fit|joint|item|pose|fasten …`: they keep the file's layout and refuse an edit
44
- that breaks it. `npx cad values` lists an object's numbers; `npx cad why <project>/<object>.<name>` shows what a
43
+ name=value` and assemblies with `npx cad add fit|joint|item|beam|pose|fasten|join|guide|load …`, `npx cad set
44
+ <project>/<assembly> x1.at=… joins.0.kind=…`, `npx cad move` and `npx cad remove`: they keep the file's layout and
45
+ refuse an edit that breaks it, naming why and writing nothing. Make a project with `npx cad new <project>` and an
46
+ assembly with `npx cad new <project>/<assembly> --assembly` (`--frame box --inside … --profile …` for a frame), and
47
+ change a project's own fields with `npx cad set <project> material=PETG`. Write project and assembly files with
48
+ these commands, not by hand: each checks its edit first, `--dry-run` shows it, and `--json` gives what changed and
49
+ the checks. `cad remove` refuses to take out what other entries name and lists them; add `--with-refs` only once
50
+ the person agrees those go too. `npx cad values` lists an object's numbers; `npx cad why <project>/<object>.<name>` shows what a
45
51
  value depends on, down to the rules (estimates marked). `--json` on check, values and why gives data to act on:
46
52
  each finding has a code, its numbers and where it is.
47
53
  3. `npx cad release <project>/<object> -m "what changed, for the person" --dry-run` shows the bump and why. If it's
@@ -142,8 +148,10 @@ variable says which rule it comes from. Follow these steps; they're what makes a
142
148
  - **A frame for a size starts from a generator**: `"frame": { "kind": "box", "inside": [w, d, h], "profile",
143
149
  "join": "blind" }` (also portal, table, gantry, shelf) expands into beams, joins, feet and caps before anything is
144
150
  checked. Ask by `inside` for what it must enclose, `outside` for what it must fit in; never work the lengths out by
145
- hand. Read `frame.generated` for what it made, and `npx cad frame <project>/<assembly> --expand` to write it out
146
- when it needs changes a generator cannot make, then edit the beams and joins as a hand-drawn frame.
151
+ hand. Make it with `npx cad new <project>/<assembly> --assembly --frame box --inside 300,300,350 --profile …
152
+ --join blind`, which says what it expands into before it writes. Read `frame.generated` for what it made, and
153
+ `npx cad frame <project>/<assembly> --expand` to write it out when it needs changes a generator cannot make, then
154
+ change the beams and joins with `cad set`, `cad move`, `cad add` and `cad remove` as a hand-drawn frame's.
147
155
  - **Beams are cut and drilled by hand from their sheets and jigs**: `npx cad beams <project>/<assembly>` writes a
148
156
  cut-and-drill sheet per mark, and `--jigs` writes the jigs as a plate in `exports/` (a drill guide per distinct
149
157
  hole across a beam, a tap guide per tapped end, a cut-length stop per length, a squaring corner of the hand each square join takes),
@@ -161,7 +169,8 @@ variable says which rule it comes from. Follow these steps; they're what makes a
161
169
  wire along a beam is a run in its `via`, `{ "along": "rail.front", "from": 300, "to": 60 }`: report its length and
162
170
  its clips from `wire.length` and `wire.run`.
163
171
  - **Linear motion on a beam is a guide**: `"guides": [{ "kind": "rail", "rail": "rail-mgn12", "carriage": "MGN12H",
164
- "on": "x1.top", "from": 50, "length": 300 }]`. Never draw a rail or carriage yourself, nor type its screws: the
172
+ "on": "x1.top", "from": 50, "length": 300 }]`, written by `npx cad add guide <project>/<assembly> --kind rail
173
+ rail=rail-mgn12 carriage=MGN12H on=x1.top from=50 length=300`. Never draw a rail or carriage yourself, nor type its screws: the
165
174
  guide places the rail, its screws into the slot at its pitch and each carriage on a sliding joint with its true
166
175
  travel. Fix a table on a carriage with a fixed joint at `g1-carriage-1.top`. Run `cad check --sweep`, and report
167
176
  `guide.fit`, the travel and each carriage's `joint.moment` margin; a fail there means a longer carriage
@@ -175,6 +184,14 @@ variable says which rule it comes from. Follow these steps; they're what makes a
175
184
  Never draw the holders, motor plate, coupler or carriage yourself: the guides place them by addresses and give the
176
185
  motor its lead screw. Report the travel, `motor.torque`'s margin, `guide.coupler`, the bearings' `joint.moment`, the
177
186
  endstop's home, and each printed part's grams and margin; if the endstop is refused, use the address it names.
187
+ A belt drives a rail's carriage: `{ "kind": "belt", "guide": "g1", "motor": { "model": "nema17" }, "accel": 3000 }`
188
+ (`npx cad add guide <project>/<assembly> --kind belt guide=g1 motor.model=nema17 accel=3000`). Never draw the
189
+ pulley, idler, belt, plate or clamp yourself: the guide places them by addresses. Report `belt.length` (cut and
190
+ buy), `belt.tension`, `motor.torque`'s margin and the travel a turn, `belt.tensioner`'s room, and each printed part's
191
+ grams and margin; say the tension and the belt's thickness are estimates. A `belt.rub` or `belt.line` fail means the
192
+ idler or the part it names moves, never the belt's figures; where the part is on the carriage, raise the belt with
193
+ the `"height"` it names instead or move the part; a `belt.tensioner` fail means cutting the belt to the length it
194
+ names.
178
195
  - **A part screwed onto a beam is a `fasten` into a slot**: `"into": "x1.top"` (or `x1.top.2`, or `x1.top@120`, the
179
196
  middle of its screws), the
180
197
  part's holes drawn with `v.fixings` at the slot's spacing, `"nut"` the slot nut's kind. `fasten.slot` fails a hole off
package/CHANGELOG.md CHANGED
@@ -5,6 +5,66 @@ print (a hole's diameter, a seat's depth, a part's outline). Each release lists
5
5
  its reason. A **fasten** is an entry in an assembly's `"fasten"` list: one screwed joint, naming the screw by thread
6
6
  and head, the parts it passes through and the part it ends in.
7
7
 
8
+ ## 0.7.62: commands that write projects and assemblies, and belt guides (Frames 4)
9
+
10
+ ### Added
11
+
12
+ - Commands that write a workspace's projects and assemblies, so neither file need be written by hand: `cad new
13
+ <project>` (its `project.json`), `cad set <project> field=value` (title, description, material, printer,
14
+ `filaments.<name>.slot`), `cad new <project>/<assembly> --assembly` (empty, or a generated frame with `--frame box
15
+ --inside 300,300,350 --profile … --join … --feet …`, and any field as `field=value`), `cad set <project>/<assembly>
16
+ <address>=<value>` (an entry's field by its id or its place, `x1.at`, `joins.3.kind`, or the assembly's own,
17
+ `frame.join.fitting`), `cad move <project>/<assembly> <id> --at | --to [--rotate]` and `cad remove
18
+ <project>/<assembly> <id | list.n | id.field> [--with-refs]`. `cad add` also takes `guide`, `load` and `wire`, and any
19
+ field as `field=value`. Each keeps the file's layout, checks the edit against the schema and what it could break (a
20
+ generated frame must still expand, the names an entry gives must be there, and every other entry's names that were
21
+ there before must still be: a beam renamed or removed, a frame changed or removed, a joint's parent and child, a
22
+ pose's joints, a wire's ends and route, a loop's anchors, a load's joint, a mount's beam) before it writes, refuses a bad one by name with nothing written (`project.exists`,
23
+ `assembly.exists`, `project.printer`, `project.material`, `edit.kind`, `frame.refused`, `edit.address`,
24
+ `edit.ambiguous`, `edit.generated`, `edit.referenced`, `edit.dangling`, `edit.renumber`, `edit.move`), takes
25
+ `--dry-run`, and with `--json` says what changed and the checks. `cad remove` of a beam a join uses is refused,
26
+ naming the join; so is `cad remove frame` where a join uses the frame's beams, and the removal of any guide before
27
+ one with no id of its own, which is named by place. `cad new <project>/<assembly> --assembly --material PETG
28
+ --printer x1c` makes the project with them where it is not there, passes them where the project already has them, and
29
+ refuses by name one that differs. The change paths in `--json` are from the workspace (`projects/<p>/project.json`,
30
+ `projects/<p>/assemblies/<a>.json`). A name the build makes (a repeated item's copy, a mount, a guide's part) counts
31
+ as there only by the exact pattern its maker uses, so `rail-3` is refused where `rail` makes no copies.
32
+ - `schemas/project.schema.json`: the project file's fields.
33
+ - Belt guides (`"kind": "belt"`, FR4.2): a GT2 belt drives a rail guide's one carriage from a motor under a printed
34
+ plate past the beam's end a, round a toothed idler on a printed block past the rail's end (the tensioner: it slides
35
+ along the beam's slot), its ends in a printed clamp on the carriage. The motor reads the belt's ratio (40 mm a turn
36
+ for a 20 tooth GT2 pulley) and is held to the push of the carriage at its acceleration; the belt goes on `cad list`
37
+ by the metre; `belt.length`, `belt.tension`, `belt.rub` (swept through the travel), `belt.line`, `belt.tensioner`
38
+ and `belt.stretch` (a term of the error budget). The schema has the guide's keys and the fittings `belt-plate`,
39
+ `belt-clamp` and `belt-idler`. The example is `examples/bench` `axes/x-belt`, written by the edit commands.
40
+ A belt's push adds to the weight on an upright or sloping axis (in `motor.torque`, `belt.tension` and the stretch),
41
+ the clamp's screws go a layer past steel's least engagement, `belt.rub` holds what the carriage carries, and the
42
+ guide's `height` raises the belt over it.
43
+
44
+ ### Changed
45
+
46
+ - `motor.axis` passes a motor driving a belt with its shaft square to the slide (a belt's pulley), as well as one on
47
+ the slide's axis as before. `motor.holds` leaves out a belt's push at its acceleration, which is not there at rest.
48
+ - A rail's carriage carries its tapped holes as its mount: a `fasten` into a carriage ends in its own thread, held to
49
+ the depth HIWIN gives (`carriage_thread_depth`), as a motor's or a supply's mounting holes are.
50
+ - A belt guide is no longer refused as "not built yet"; a screw on a rail is refused saying a rail is driven by a belt.
51
+ - `cad add join`, `cad add fasten` and `cad add fit` accept a generated frame's beams (they were refused as not in the
52
+ assembly), and `cad add item` and `cad add load` refuse an address on an item the assembly does not have.
53
+ - `cad add` prints the place it added at (`added a join to … (joins.3)`), and its `--json` is `{ command, file,
54
+ written, changes, findings, added }`; the `file` is relative to the workspace.
55
+ - No printed size or figure moves.
56
+
57
+ ## 0.7.61: a board rebuilt when its finish changes
58
+
59
+ ### Fixed
60
+
61
+ - A board's cached build now misses when @rulecad/smooth changes, not only @rulecad/pcb: its build runs smooth's
62
+ smoothing and finish, so a change there could leave a board built by the old code (the engine id hashes both).
63
+
64
+ ### Printed sizes that moved
65
+
66
+ None. Boards build again once (their cache key changed); what they build is the same unless @rulecad/smooth changed.
67
+
8
68
  ## 0.7.60: pins, magnets and printed bolts in assemblies, and the holds coupon (Fixings 4)
9
69
 
10
70
  ### Added
@@ -54,6 +114,7 @@ they are found, checked and counted.
54
114
  ### Printed sizes that moved
55
115
 
56
116
  None.
117
+
57
118
  ## 0.7.58: frame checks (Frames 3)
58
119
 
59
120
  ### Added
package/EXAMPLES.md CHANGED
@@ -6417,19 +6417,18 @@ carriage, driven by a lead screw from a NEMA 17. A printed plate for a board is
6417
6417
  cut, drilled and printed from what the check worked out: the cut list, a sheet for each beam, the jigs, one plate of
6418
6418
  printed parts and the order to build it in. Two mistakes follow, each caught by name.
6419
6419
 
6420
- ```json projects/frame/project.json
6421
- {
6422
- "name": "frame",
6423
- "title": "A frame with a moving axis",
6424
- "printer": "x1c",
6425
- "material": "PLA",
6426
- "objects": ["plate"]
6427
- }
6420
+ The project, and the one object in it, are made by commands: `cad new frame` writes `projects/frame/project.json`
6421
+ (its title, the printer its parts are checked against, PLA), and `cad new frame/plate` starts the plate from the
6422
+ template and lists it in the project.
6423
+
6424
+ ```sh
6425
+ npx cad new frame --title "A frame with a moving axis" --printer x1c --material PLA
6426
+ npx cad new frame/plate
6428
6427
  ```
6429
6428
 
6430
6429
  ### The plate
6431
6430
 
6432
- The board plate is the one part drawn by hand. It lies on a beam's slotted face, two M4 holes from `v.fixings` along
6431
+ The board plate is the one part drawn by hand: its two files replace the template's. It lies on a beam's slotted face, two M4 holes from `v.fixings` along
6433
6432
  its middle, so both screws go into one slot's nuts. Its thickness is chosen with its screws: 3 mm of plate and the
6434
6433
  slot's 2 mm lip leave an M4x8 a hex nut's height of thread in a slot nut without reaching the slot's floor.
6435
6434
 
@@ -6691,28 +6690,23 @@ joins to 0.68 N m (what the PLA under each head takes).
6691
6690
  ### Two mistakes, caught
6692
6691
 
6693
6692
  A trapped nut. The board plate on its rail between two posts, its nuts `slide-in`, which go into a slot only from an
6694
- open end:
6693
+ open end. This one is built by commands, each checked as it is written: an empty assembly, three beams placed by
6694
+ their ends, the plate at the middle of x1's top face, the two joins and the fasten.
6695
6695
 
6696
- ```json projects/frame/assemblies/trapped.json
6697
- {
6698
- "$schema": "https://jonibach.github.io/rulecad/schemas/assembly.schema.json",
6699
- "title": "The board plate on slide-in nuts",
6700
- "kind": "fit",
6701
- "items": [
6702
- { "id": "p1", "beam": { "profile": "2020-misumi-hfs5" }, "from": [10, 10, 0], "to": [10, 10, 200] },
6703
- { "id": "p2", "beam": { "profile": "2020-misumi-hfs5" }, "from": [290, 10, 0], "to": [290, 10, 200] },
6704
- { "id": "x1", "beam": { "profile": "2020-misumi-hfs5" }, "from": [20, 10, 30], "to": [280, 10, 30] },
6705
- { "id": "plate", "object": "plate", "at": "x1.top@50%" }
6706
- ],
6707
- "joins": [
6708
- { "kind": "blind", "a": "x1.a", "b": "p1.back@30" }, { "kind": "blind", "a": "x1.b", "b": "p2.front@30" }
6709
- ],
6710
- "fasten": [
6711
- { "screw": "M4 button", "through": ["plate"], "into": "x1.top", "holes": "plate.body", "nut": "slide-in", "note": "The board plate" }
6712
- ]
6713
- }
6696
+ ```sh
6697
+ npx cad new frame/trapped --assembly --title "The board plate on slide-in nuts"
6698
+ npx cad add beam frame/trapped --id p1 --profile 2020-misumi-hfs5 --from 10,10,0 --to 10,10,200
6699
+ npx cad add beam frame/trapped --id p2 --profile 2020-misumi-hfs5 --from 290,10,0 --to 290,10,200
6700
+ npx cad add beam frame/trapped --id x1 --profile 2020-misumi-hfs5 --from 20,10,30 --to 280,10,30
6701
+ npx cad add item frame/trapped --id plate --object plate --at x1.top@50%
6702
+ npx cad add join frame/trapped --kind blind --a x1.a --b p1.back@30
6703
+ npx cad add join frame/trapped --kind blind --a x1.b --b p2.front@30
6704
+ npx cad add fasten frame/trapped --screw "M4 button" --through plate --into x1.top --holes plate.body --nut slide-in --note "The board plate"
6714
6705
  ```
6715
6706
 
6707
+ `projects/frame/assemblies/trapped.json` is then the file a person would have written: the four items, the two joins
6708
+ and the fasten.
6709
+
6716
6710
  `npx cad check frame/trapped` fails on `frame.nut`, and names the nut that would do:
6717
6711
 
6718
6712
  ```text
@@ -6728,19 +6722,11 @@ frame/trapped: x1's top slot: 2 slide-in nuts (slot-nut-6-misumi-m4-slide-in) fo
6728
6722
  A plate drawn for the wrong slot spacing. The same plate turned across a wider rail, a 2040 whose top face has two
6729
6723
  slots 20 mm apart, with its holes drawn 30 mm apart, as a 30 series beam's slots are:
6730
6724
 
6731
- ```json projects/frame/assemblies/spacing.json
6732
- {
6733
- "$schema": "https://jonibach.github.io/rulecad/schemas/assembly.schema.json",
6734
- "title": "A plate drawn for 30 mm slots on a 2040",
6735
- "kind": "fit",
6736
- "items": [
6737
- { "id": "x1", "beam": { "profile": "2040-misumi-hfs5" }, "from": [0, 0, 10], "to": [260, 0, 10] },
6738
- { "id": "plate", "object": "plate", "at": [130, 0, 20], "rotate": [0, 0, 90], "set": { "pitch": 30, "long": 44 } }
6739
- ],
6740
- "fasten": [
6741
- { "screw": "M4 button", "through": ["plate"], "into": "x1.top", "holes": "plate.body", "nut": "drop-in", "note": "The board plate" }
6742
- ]
6743
- }
6725
+ ```sh
6726
+ npx cad new frame/spacing --assembly --title "A plate drawn for 30 mm slots on a 2040"
6727
+ npx cad add beam frame/spacing --id x1 --profile 2040-misumi-hfs5 --from 0,0,10 --to 260,0,10
6728
+ npx cad add item frame/spacing --id plate --object plate --at 130,0,20 --rotate 0,0,90 --set pitch=30,long=44
6729
+ npx cad add fasten frame/spacing --screw "M4 button" --through plate --into x1.top --holes plate.body --nut drop-in --note "The board plate"
6744
6730
  ```
6745
6731
 
6746
6732
  `npx cad check frame/spacing` fails on `fasten.slot`, for each screw:
@@ -6784,14 +6770,8 @@ fan mount all come from the kit's fittings. The frame's sag under the board is r
6784
6770
  longer than the printer's bed is spliced, a foot drawn for the aluminium post is caught, and the whole case is written
6785
6771
  out as a kit: one plate to print and a page to build it from.
6786
6772
 
6787
- ```json projects/case/project.json
6788
- {
6789
- "name": "case",
6790
- "title": "A printed case for a small computer board",
6791
- "printer": "x1c",
6792
- "material": "PETG",
6793
- "objects": []
6794
- }
6773
+ ```sh
6774
+ npx cad new case --title "A printed case for a small computer board" --printer x1c --material PETG
6795
6775
  ```
6796
6776
 
6797
6777
  PETG rather than PLA: a board in a closed case runs warm, and PETG softens later.
package/README.md CHANGED
@@ -25,7 +25,8 @@ measured into rules, an optimised arm, a board, and a mechanism printed flat, ea
25
25
  rules/ shared facts, one file per set: x1c.json (printer), mx.json (Cherry MX). A set from
26
26
  @rulecad/rules is copied here the first time a design uses it: yours to keep and correct
27
27
  projects/<project>/
28
- project.json name, description, default material, printer, objects, filaments (AMS slots)
28
+ project.json name, title, description, default material, printer, objects, filaments (AMS slots)
29
+ (schemas/project.schema.json; written by cad new <project>, changed by cad set <project>)
29
30
  objects/<object>.json variables (value, unit, rule, source, label, show, interface, tweak), variants, parts
30
31
  objects/<object>.js main(v): the shape, from variables only
31
32
  layouts/<name>.json where the keys go, with each key's own properties (@rulecad/keyboard-layout)
@@ -67,6 +68,65 @@ schema, or variables that no longer resolve. Options go before or after the name
67
68
  refused by name. `cad --version` says which cad this is. Two switches for the tool itself: `CAD_NO_CACHE=1` builds
68
69
  afresh, and `CAD_TRUST=1` runs designs in the tool's own process (see Sandbox).
69
70
 
71
+ ### Projects and assemblies, by command
72
+
73
+ Every edit to a project's or an assembly's file has a command that makes it and checks it, so neither file need be
74
+ written by hand, and a program (or a graphical front end) can drive the same edits:
75
+
76
+ ```sh
77
+ npx cad new bench --title "A bench rig" --material PETG --printer x1c # projects/bench/project.json
78
+ npx cad set bench material=PLA "filaments.legend.slot=2" # its own fields
79
+ npx cad new bench/rig --assembly --title "The rig" # an empty assembly that checks
80
+ npx cad new bench/box --assembly --frame box --inside 300,300,350 --profile 2020-misumi-hfs5 --join blind --feet levelling
81
+ npx cad add beam bench/rig --id x1 --profile 2020-misumi-hfs5 --from 0,10,10 --to 300,10,10
82
+ npx cad add guide bench/box --kind rail rail=rail-mgn12 carriage=MGN12H on=x3.top from=25 length=250
83
+ npx cad add load bench/box --mass 5 --at x3.top@50%
84
+ npx cad set bench/box frame.join.fitting=printed "frame.inside=[300,300,400]" loads.0.mass=8
85
+ npx cad move bench/rig x1 --at 0,10,40 # a beam by its ends: both move
86
+ npx cad remove bench/rig x1 --with-refs # and the joins that name it
87
+ ```
88
+
89
+ | Command | What it writes |
90
+ |---|---|
91
+ | `cad new <project> [--title] [--description] [--material] [--printer]` | `project.json`, PLA unless told; refused if it is there, or the printer has no rule set |
92
+ | `cad set <project> field=value …` | A project's title, description, material, printer or `filaments.<name>.slot`; its objects are kept by `cad new <project>/<object>` |
93
+ | `cad new <project>/<assembly> --assembly [--title] [--frame <kind> --inside x,y,z --profile <set> --join … --fitting … --feet … --caps …] [field=value …]` | An assembly, empty or a generated frame, expanded and checked before it is written; its project too, where there is none. A kind other than fit is refused (a mechanism is a fit with joints, a plate is written by `cad plates`) |
94
+ | `cad add fit\|joint\|item\|beam\|loop\|pose\|fasten\|join\|guide\|load\|wire <project>/<assembly> --option … [field=value …]` | An entry, any field as `field=value` (`motor.model=nema17` nests); every name it gives checked against the assembly's items, a generated frame's beams included |
95
+ | `cad set <project>/<assembly> <address>=<value> …` | A field. An address is an entry's id and a field (`x1.at`, `hinge.max`), an entry by its place (`joins.3.kind`, `fits.0.min`), or a field of the assembly's own (`title`, `frame.join`, `task.speed`); a key with a dot in it goes in brackets and quotes (`frame.supports["z1.a"]`) |
96
+ | `cad move <project>/<assembly> <id> --at x,y,z \| --to <address> [--rotate x,y,z]` | An item to a point or an address (a beam placed by its ends moves both ends, as one), or a guide to another face (`--to x4.top`) or along its own (`--at 40`) |
97
+ | `cad remove <project>/<assembly> <id \| list.n \| id.field> [--with-refs]` | An entry or a field; refused while other entries name it, listing them, unless `--with-refs` removes them too |
98
+
99
+ A value is JSON where it is JSON (`8`, `true`, `[300, 300, 400]`, `{"kind": "bracket"}`), a list in brackets
100
+ without quotes (`[1515-openbeam, 2020-misumi-hfs5]`), and otherwise text; quote one with brackets or spaces for the
101
+ shell. A text standing where an object is asked for is its kind: `"join": "blind"` is `{ "kind": "blind" }`, so
102
+ `frame.join.fitting=printed` keeps the blind.
103
+
104
+ Each command keeps the file's layout, checks the edit against the schema and against what it could break (a
105
+ generated frame must still expand; a join's beams, a fit's parts, a fasten's items, a guide's beam, a joint's parent
106
+ and child, a pose's joints, a wire's ends and route (its anchors, path joints and runs along a beam's slot), a loop's
107
+ anchors, a load's joint and anchor, and a placed or mounted item's address must be there, in the entry changed and in every other entry
108
+ that had them before), and refuses a bad one by name with nothing written: `--json` gives the refusal as `{ "error": {
109
+ "code", "message", "file", "path", "refs" } }`. `--dry-run` does it all and writes nothing. Done, it prints each change
110
+ (`set frame.feet: "levelling" → "foot"`) and the checks; `--json` gives `{ "command", "file", "written", "dryRun",
111
+ "changes": [{ "op", "path", "before", "after" }], "findings" }`, the findings in the kit's one shape. A generated
112
+ frame's beams are not in the file, so `cad set` and `cad move` refuse them by name (`edit.generated`): change the
113
+ frame's own fields, or write it out with `cad frame <ref> --expand` first.
114
+
115
+ | Refusal | When |
116
+ |---|---|
117
+ | `project.exists`, `assembly.exists` | `cad new` of one that is there, or a field given to `cad new <project>` or `--material` or `--printer` given to `cad new <project>/<assembly> --assembly` that differs from the project's own (they are the project's: `cad set <project> material=PETG`, as the refusal names). Fields that match it change nothing and pass, so a step can run twice. Where the project is not there, the assembly makes it with them, each checked as `cad new <project>` checks it |
118
+ | `project.printer` | A printer with no rule set |
119
+ | `project.material` | A material printed fittings cannot be sized from: anything but PLA, PETG or a rule set in `rules/` giving strength, modulus and density. Every frame command reads the project's material as it builds the joins, guides and panels, so one it cannot read would stop them all |
120
+ | `edit.kind` | An assembly kind other than `fit` |
121
+ | `frame.refused` | A generated frame the generator refuses (a portal with nothing holding its feet, an end-tap join its profile cannot take) |
122
+ | `edit.address`, `edit.ambiguous`, `edit.generated` | An address nothing has, an id two lists share, a generated frame's part |
123
+ | `edit.part`, `edit.incomplete`, `edit.duplicate` | A name that is not in the assembly, an entry missing what it needs, an id already taken. A name the build makes counts as there only where an entry makes it, by its exact pattern: a repeated item's copies (`key-0`, `key-0-3`), a mounted item's mount (`psu-mount`), a panel's clips, hinges, leaves, handle and catch, a levelling foot's pad, a join's fitting (`y1-x1-bracket`), a wire's clips, a guide's parts (`g1-carriage-1`) and joints (`g1-1`, `door-hinge`). So `rail-3` is no name where `rail` is one beam |
124
+ | `edit.referenced` | `cad remove` of what other entries name (each listed in `refs`) |
125
+ | `edit.renumber` | `cad remove` of a guide while guides after it have no id of their own: they are named g1, g2 .. by place, so they would be renamed |
126
+ | `edit.dangling` | An edit that leaves another entry naming what is no longer there: a beam renamed or removed that a join, a load, a wire or a mount names, a frame changed or removed whose beams a join or a guide uses (each listed in `refs`). A name that was already missing before the edit is left to `cad check` |
127
+ | `edit.move` | A move its entry cannot take (a beam placed by its ends sent to an address) |
128
+ | `schema` | The edit leaves the file outside its schema |
129
+
70
130
  ## The workspace
71
131
 
72
132
  The workspace is `$CAD_WORKSPACE`, else the nearest folder at or above the current one with a `cad.config.json`,
@@ -587,6 +647,8 @@ walks one from a spec sheet to a checked box; this section is the reference. In
587
647
  | `cad measure <beam.stl> --profile <name>` (or a DXF) | A profile from the maker's model or a DXF of its section |
588
648
  | `cad add beam <project>/<assembly> --id x1 --profile 2020-misumi-hfs5 --from 0,0,0 --to 300,0,0` | A beam placed by its ends |
589
649
  | `cad add join <project>/<assembly> --kind blind --a y1.a --b x1.back@120` | Two beams joined (Joins, below) |
650
+ | `cad new <project>/<assembly> --assembly --frame box --inside 300,300,350 --profile 2020-misumi-hfs5` | A generated frame, expanded and checked as it is made (A frame from a size, below) |
651
+ | `cad set`, `cad move`, `cad remove` | A frame's fields, a beam moved by its ends, a beam taken out (refused, naming them, while joins use it) (Projects and assemblies, by command, above) |
590
652
  | `cad frame <project>/<assembly>` | A generated frame's beams and joins (`--expand` writes them out; `--size` chooses the lightest profiles) |
591
653
  | `cad check <project>/<assembly>` | The joins, screws and nuts, then the frame solved: `frame.deflection`, `frame.stress`, `frame.buckling`, `frame.rack`, `frame.frequency`, `frame.square`, `frame.heat`, `beam.printable`; `--sweep` slides each guide through its travel |
592
654
  | `cad list`, `cad beams` (`--jigs`), `cad order`, `cad plates`, `cad kit` | The cut list and what to buy, a sheet per beam and the jigs, the build from bars to a square frame, the printed parts on plates, and all of it in one folder (Building it, below) |
@@ -1320,7 +1382,7 @@ it, the switch's mount where its address says:
1320
1382
  `nut`. The motor drives the carriage's joint with `leadscrew` from the screw's set (its lead and diameter) and
1321
1383
  `friction` (default the set's, an estimate), so `motor.torque`, `motor.speed` and `motor.holds` read the drive's
1322
1384
  ratio as they do any lead screw. `guide.drive` and `guide.coupler` (how far the shaft reaches into the coupler) say
1323
- what was placed. A belt is not built yet; a screw on a rail or wheels is refused.
1385
+ what was placed. A screw on a rail or wheels is refused: a rail's carriage is driven by a belt.
1324
1386
  - An endstop's printed mount (`endstop-mount`) goes at a side face's address (`endstop.at`), the switch (`switch`,
1325
1387
  default `endstop-10t85`) on it; a flag on the carriage's far end meets its lever. Where that happens is the joint's
1326
1388
  lower end and its `home` (`guide.endstop`). A switch the flag cannot reach, or a mount over a holder's leg, is
@@ -1328,6 +1390,46 @@ it, the switch's mount where its address says:
1328
1390
  - Each carriage's loads are shared between its bearings at every pose (`joint.moment`) against their static rating;
1329
1391
  a moment on one bush is taken as a couple along it, an estimate, said as one.
1330
1392
 
1393
+ A timing belt drives a rail's one carriage: a pulley on a motor at the beam's end a, a toothed idler past the rail's
1394
+ end, both belt ends in a printed clamp on the carriage. The belt guide names the rail guide and the motor, and places
1395
+ the rest by addresses (`examples/bench` `axes/x-belt` is one, written by the edit commands):
1396
+
1397
+ ```json
1398
+ "guides": [{ "kind": "rail", "rail": "rail-mgn12", "carriage": "MGN12H", "on": "x1.top", "from": 30, "length": 300 },
1399
+ { "kind": "belt", "guide": "g1", "motor": { "model": "nema17", "microsteps": 16, "current": 1.2 }, "accel": 3000 }]
1400
+ ```
1401
+
1402
+ - It adds a printed motor plate (`belt-plate`, `<id>-plate`) at `<beam>.<face>@0`, its tab screwed into the face's slot
1403
+ and the motor (`<id>-motor`) hanging under it past the beam's end; the pulley (`pulley`, default `pulley-gt2-20`;
1404
+ `<id>-pulley`) on the motor's shaft; a printed clamp (`belt-clamp`, `<id>-clamp`) at the carriage's `top`, screwed
1405
+ into the carriage's own tapped holes; and the idler (`idler`, default `idler-gt2-toothed-20`; `<id>-idler`) on a
1406
+ printed block (`belt-idler`, `<id>-idler-block`) past the rail's end, which is the tensioner: its two screws go into
1407
+ slot nuts in the beam's slot, so loosened it slides along it. `idlerAt` places the block (default room short of the
1408
+ beam's end b), `across` moves the idler's axle off the belt's square line, `tension` sets each span (default 25 N, an
1409
+ estimate), `cut` says the length the belt is cut to, `height` raises the belt's middle over the face (the pulley
1410
+ further up its shaft), `belt` its set (default `gt2-belt-6`). The rail starts after
1411
+ the plate's tab and ends before the block, or the guide is refused naming where to put it.
1412
+ - The motor drives the carriage's joint with `belt` from the sets (the pulley's teeth, the belt's pitch, stiffness and
1413
+ width), so `motor.torque`, `motor.speed` and the step's term in the error budget read 20 × 2 = 40 mm a turn. Its
1414
+ load is what the belt pushes: everything the carriage carries at `accel` (the guide's, else the task's, else 1000
1415
+ mm/s²), a load on the joint that `motor.holds` leaves out (it is not there at rest). The push goes either way along
1416
+ the travel, so on an upright or sloping axis it adds to the weight: 1.04 kg on an upright 2020 at 5000 mm/s² needs
1417
+ 10.18 + 5.19 = 15.37 N. Its shaft turns square to the travel (`motor.axis`).
1418
+ - `belt.length` gives the path by the belt's pitch line, the length to cut it (whole teeth that stretch to the path at
1419
+ the tension) and to buy, rounded up to whole metres (`cad list` shows `gt2-belt-6 x 1000 mm`). `belt.tension` holds
1420
+ each span, with the push and the weight along the travel, between the belt's least static tension and its rated
1421
+ tension. `belt.rub` fails a run that rubs the beam, the rail, the carriage, the clamp or anything else on the
1422
+ carriage (by its box) anywhere through the travel, naming the run, the part and where; for a part on the carriage it
1423
+ gives the `height` that clears it by 1 mm. Its pass says how far the return run passes over the carriage's top
1424
+ (3.4 mm for an MGN12H on a 2020), the room a part on the carriage's free holes has under it.
1425
+ `belt.line` fails an idler off the pulley's line past 0.25° (an estimate). `belt.tensioner` says where the block
1426
+ must slide along its slot to tension the belt as cut, and fails when the slot has no room left there, saying how
1427
+ much shorter or longer to cut it. `belt.stretch` gives the belt's stretch under the push, the term `belt stretch` in
1428
+ a task's error budget.
1429
+ - The belt is drawn where the carriage starts its travel and left out of the overlap check: its runs move with the
1430
+ carriage, so `belt.rub` holds them through the whole travel. The plate, the clamp and the block each report their
1431
+ grams, their margin and how they print, and pass printcheck as drawn.
1432
+
1331
1433
  ## Optimised parts
1332
1434
 
1333
1435
  `cad optimise` finds the stiffest layout of a flat part: where to put a fixed amount of material so the part bends
package/bin/cad.mjs CHANGED
@@ -20,7 +20,7 @@ import { schemaFindings } from '../lib/schema.mjs';
20
20
  import { readJson } from '../lib/host.mjs';
21
21
  import { optimised, readProblem, analysePart, picture, problemFile } from '../lib/optimise.mjs';
22
22
  import { evaluate } from '../lib/rules.mjs';
23
- import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue } from '../lib/edit.mjs';
23
+ import { setVariables, addToAssembly, fastenFromFitsEdit, parseValue, parseSetting, newProject, setProject, newAssembly, setInAssembly, removeFromAssembly, moveInAssembly } from '../lib/edit.mjs';
24
24
  import { setAt } from '../lib/jsonedit.mjs';
25
25
  import { threemf, slotOf } from '../lib/threemf.mjs';
26
26
  import { liveView } from '../lib/live.mjs';
@@ -42,6 +42,10 @@ const openInSlicer = (f) => (process.platform === 'darwin' ? execFileSync('open'
42
42
  const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
43
43
 
44
44
  cad new <project>/<object> start a design from the template (makes the project if needed)
45
+ cad new <project> a project: its project.json [--title …] [--description …] [--material PLA] [--printer x1c]
46
+ cad new <project>/<assembly> --assembly an empty assembly that checks [--title …] (makes the project if needed); with
47
+ --frame box|portal|table|gantry|shelf --inside 300,300,350 (or --outside) --profile <set>
48
+ [--join blind] [--fitting printed] [--feet levelling] [--caps false]: a generated frame
45
49
  cad import-kle <file> <project>/<name> a keyboard layout from keyboard-layout-editor.com, into layouts/
46
50
  cad clone <board.kicad_pcb | GitHub link> <name> a published circuit board into rules/<name>.json, to redraw by rules [--source, --licence]
47
51
  cad agents AGENTS.md: how an AI agent should design in this workspace
@@ -54,7 +58,18 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
54
58
  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
55
59
  cad values <project>/<object> [names…] the object's variables, resolved [--json]
56
60
  cad set <project>/<object> name=value … change variables, keeping the file's layout [--unit, --rule, --label, --new to add one]
57
- cad add fit|joint|item|beam|loop|pose <project>/<assembly> --a … --b … --min … add to an assembly, keeping its layout
61
+ cad set <project>/<assembly> <address>=<value> … change an assembly's fields: an entry's by its id or place (x1.at=[0,0,20],
62
+ joins.3.kind=bracket), or its own (title=…, frame.join.fitting=printed, frame.inside=[300,300,400]);
63
+ a value is JSON, a [list, of, names] or text
64
+ cad set <project> field=value … change a project's own fields: title, description, material, printer, filaments.<name>.slot
65
+ cad add fit|joint|item|beam|loop|pose|guide|load|wire <project>/<assembly> --a … --b … --min … [field=value …]
66
+ add to an assembly, keeping its layout; any field as field=value (motor.model=nema17)
67
+ cad move <project>/<assembly> <id> --at x,y,z | --to x1.top@50% [--rotate 0,0,90] move an item (a beam by its ends
68
+ moves both) or a guide (--to x3.top, --at 100 along it)
69
+ cad remove <project>/<assembly> <id | list.n | id.field> take an entry or a field out; refused, naming them, while other
70
+ entries name it, unless --with-refs takes them out too
71
+ Every edit (new, set, add, move, remove): checked against the schema and what it could break before it is written,
72
+ refused by name with nothing written; --dry-run shows it without writing; --json says what changed, and the checks
58
73
  cad add fasten <project>/<assembly> --screw "M3 cap" --through bracket --into base --at bracket.h1,bracket.h2
59
74
  a screwed joint (or --holes bracket.body for the part's own holes) [--nut [hex|square|lock]]
60
75
  [--washer] [--length 12] [--torque 0.5] [--note …]
@@ -143,7 +158,7 @@ const HELP = `cad: JSCAD designs you can trace, check, share and print (rulecad)
143
158
  cad --version this tool's version`;
144
159
 
145
160
  // Every command and option there is: a misspelt one is refused by name, not passed over
146
- const COMMANDS = ['new', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
161
+ const COMMANDS = ['new', 'remove', 'move', 'import-kle', 'clone', 'agents', 'trust', 'rules', 'values', 'set', 'add', 'why', 'check', 'preview', 'animate', 'optimise', 'optimize', 'export',
147
162
  'show', 'link', 'status', 'release', 'history', 'diff', 'printed', 'measure', 'measured', 'list', 'beams', 'frame', 'wires', 'machine', 'plot', 'plates', 'order', 'kit', 'match', 'variants', 'compare', 'help'];
148
163
  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',
149
164
  'no-models', 'no-pictures', 'no-rules', 'note', 'open', 'part', 'place', 'pose', 'profile', 'progress', 'push', 'result', 'rules', 'samples', 'set', 'short', 'source', 'steps',
@@ -151,27 +166,32 @@ const OPTIONS = ['table', 'calibrate', 'check', 'turns', 'preview', 'gap', 'no-s
151
166
  'unit', 'rule', 'label', 'from', 'out', 'jigs', 'no-jigs', 'expand', 'size', 'write', 'pictures', // cad set, cad rules, cad beams, cad frame, cad plates, cad kit
152
167
  'a', 'b', 'min', 'max', 'poses', 'id', 'type', 'parent', 'child', 'follow', 'value', 'ratio', 'object', 'assembly', 'variant', 'rotate', 'to', 'roll', // cad add
153
168
  'screw', 'through', 'into', 'holes', 'nut', 'washer', 'length', 'torque', 'from-fits', // cad add fasten
154
- 'kind', 'fitting']; // cad add join
169
+ 'kind', 'fitting', // cad add join
170
+ 'title', 'description', 'printer', 'frame', 'inside', 'outside', 'join', 'feet', 'caps', 'with-refs', 'mass', 'joint']; // cad new, cad remove, cad add load
155
171
  // What a command takes, where that isn't <project>/<object>
156
- const USAGE = { add: 'fit|joint|item|beam|loop|pose|fasten|join <project>/<assembly> --key value …', why: '<project>/<object>.<variable>', set: '<project>/<object> name=value …',
172
+ 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 …',
173
+ 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]',
157
174
  optimise: '<project>/<problem>', optimize: '<project>/<problem>', history: '<project>[/<object>]', release: '<project>[/<object>] -m "what changed"',
158
175
  diff: '<project>/<object> <from> [<to>]', compare: '<project>/<object> <a> <b>', match: '<project>/<object> <model.stl|model.3mf>', clone: '<board.kicad_pcb | GitHub link> <name>' };
159
176
 
160
177
  const args = process.argv.slice(2);
161
178
  // Options that stand alone. Every other takes the value after it: --name value, or -m for one-letter names
162
179
  // (--sweep, --watch and --nut take one or not).
163
- const FLAGS = ['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'];
180
+ 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'];
181
+ // The options whose value may be left out; a field=value after one is a field to set, not its value (cad new
182
+ // frame/box --assembly title=Box)
183
+ const OPTIONAL = ['sweep', 'watch', 'nut', 'assembly'];
164
184
  const opt = (k) => {
165
185
  const i = args.findIndex((a) => a === `--${k}` || (k.length === 1 && a === `-${k}`));
166
186
  if (i < 0) return undefined;
167
187
  if (FLAGS.includes(k)) return true;
168
- if (args[i + 1] && !args[i + 1].startsWith('--')) return args[i + 1];
169
- if (['sweep', 'watch', 'nut'].includes(k)) return true;
188
+ if (args[i + 1] && !args[i + 1].startsWith('--') && !(OPTIONAL.includes(k) && args[i + 1].includes('='))) return args[i + 1];
189
+ if (OPTIONAL.includes(k)) return true;
170
190
  throw new Error(`${args[i]} needs a value after it`);
171
191
  };
172
192
  // The arguments that aren't options or an option's value: cad values keyboard/case depth width --json
173
- const takesValue = (a) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)));
174
- const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1])));
193
+ const takesValue = (a, next) => a === '-m' || (a.startsWith('--') && !FLAGS.includes(a.slice(2)) && !(OPTIONAL.includes(a.slice(2)) && String(next).includes('=')));
194
+ const positional = () => args.filter((a, i) => !a.startsWith('--') && a !== '-m' && !(i > 0 && takesValue(args[i - 1], a)));
175
195
  // --set name=value,name=value (a value may hold an = of its own)
176
196
  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()]; }));
177
197
  const suffix = (set) => Object.entries(set).map(([k, v]) => `-${k}=${v}`).join('').replace(/[^\w.=+-]/g, '_'); // in file names: nothing that could name another folder
@@ -408,6 +428,7 @@ async function main() {
408
428
  if (odd) { const guess = near(odd.slice(2), OPTIONS); throw new Error(`no option ${odd}${guess ? ` (did you mean --${guess}?)` : ''}: cad help lists them`); }
409
429
  if (configError) throw configError;
410
430
 
431
+ if (cmd === 'new' && (opt('assembly') || !String(ref || '').includes('/'))) return newCommand(ref ?? (typeof opt('assembly') === 'string' ? opt('assembly') : undefined));
411
432
  if (cmd === 'new') {
412
433
  const [project, name] = String(ref || '').split('/');
413
434
  if (!/^[a-z][a-z0-9-]*$/.test(project || '') || !/^[a-z][a-z0-9-]*$/.test(name || '')) throw new Error('usage: cad new <project>/<object>, lower-case names with dashes');
@@ -485,8 +506,9 @@ async function main() {
485
506
  if (cmd === 'diff') return diff(locate(ref), pos[2], pos[3] || null);
486
507
  if (cmd === 'printed') return printed(locate(ref));
487
508
  if (cmd === 'why') return explainValue(ref);
488
- if (cmd === 'set') return editVariables(ref);
509
+ if (cmd === 'set') return isAssembly(ref) ? editFields(ref) : !ref.includes('/') ? editProject(ref) : editVariables(ref);
489
510
  if (cmd === 'add') return editAssembly(pos[1], pos[2]);
511
+ if (cmd === 'remove' || cmd === 'move') return removeOrMove(cmd, ref, pos[2]);
490
512
  if (cmd === 'optimise' || cmd === 'optimize') return await optimiseProblem(ref);
491
513
  if (isAssembly(ref)) return assembly(cmd, ref);
492
514
  const [base, at] = ref.split('@');
@@ -646,10 +668,70 @@ async function editAssembly(what, ref) {
646
668
  const pairs = positional().slice(3);
647
669
  if (typeof opt('name') !== 'string' || !pairs.length) throw new Error('usage: cad add pose <project>/<assembly> --name open hinge=90 [joint=value …]');
648
670
  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)]; })) };
649
- } else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten|join <project>/<assembly> --key value …');
650
- const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry);
651
- if (opt('json')) return console.log(JSON.stringify({ ...r, added: entry }));
652
- console.log(`added ${/^[aeiou]/.test(what) ? "an" : "a"} ${what} to ${path.relative(WS, r.file)}`);
671
+ } else if (what === 'load') entry = { ...text(['joint']), ...pick(['mass', 'torque']), ...at(), ...text(['note']) };
672
+ else if (what === 'guide' || what === 'wire') entry = { ...text(['id', 'kind', 'note']) };
673
+ else throw new Error('usage: cad add fit|joint|item|beam|loop|pose|fasten|join|guide|load|wire <project>/<assembly> --key value … [field=value …]');
674
+ // field=value pairs, for any field (nested by dots: motor.model=nema17), over the options
675
+ 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; }
676
+ const r = addToAssembly(ref, what === 'beam' ? 'item' : what, entry, { dryRun: !!opt('dry-run') });
677
+ 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})`);
678
+ }
679
+
680
+ // name=value pairs from the command line, each value as cad set takes it; refused by name where one has no =
681
+ function pairsOf(list, what) {
682
+ const bad = list.find((p) => !p.includes('='));
683
+ if (bad) throw new Error(`${what}: "${bad}" isn't field=value`);
684
+ return list.map((p) => { const i = p.indexOf('='); return [p.slice(0, i).trim(), parseSetting(p.slice(i + 1))]; });
685
+ }
686
+ const rel = (f) => path.relative(WS, f).split(path.sep).join('/');
687
+ const shownValue = (v) => (v === undefined ? 'nothing' : JSON.stringify(v).length > 70 ? `${JSON.stringify(v).slice(0, 67)}...` : JSON.stringify(v));
688
+ // What an edit did, as words or as data (--json): its changes, then its checks
689
+ function edited(r, command, extra = {}, head = null) {
690
+ 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));
691
+ const verb = { set: 'set', add: 'added', remove: 'removed', make: 'made' }, would = r.dryRun ? 'would be ' : '';
692
+ console.log(`${r.dryRun ? 'dry run, nothing written: ' : ''}${head ?? `${rel(r.file)}${r.dryRun || r.written ? '' : ' (no change)'}`}`);
693
+ 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})` : ''}`);
694
+ report(r.findings);
695
+ }
696
+
697
+ // cad new <project> [--title --description --material --printer], cad new <project>/<assembly> --assembly [--frame ...]
698
+ async function newCommand(ref) {
699
+ const dryRun = !!opt('dry-run'), str = (k) => (typeof opt(k) === 'string' ? opt(k) : undefined);
700
+ if (!ref) throw new Error('usage: cad new <project>/<object>, cad new <project>, or cad new <project>/<assembly> --assembly');
701
+ if (!ref.includes('/')) return edited(newProject(ref, { title: str('title'), description: str('description'), material: str('material'), printer: str('printer'), dryRun }), 'new');
702
+ let frame;
703
+ // the frame's options go with --frame, and a join's fitting and screw with --join: none is dropped unsaid
704
+ const FRAME_OPTS = ['inside', 'outside', 'profile', 'join', 'fitting', 'screw', 'feet', 'caps'], loose = FRAME_OPTS.filter((k) => opt(k) !== undefined);
705
+ 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>=…`);
706
+ 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`);
707
+ if (opt('frame')) {
708
+ const nums = (k) => (str(k) ? str(k).split(',').map((x) => parseValue(x.trim())) : undefined);
709
+ const join = str('join') && (str('fitting') || str('screw')) ? { kind: str('join'), ...(str('fitting') ? { fitting: str('fitting') } : {}), ...(str('screw') ? { screw: str('screw') } : {}) } : str('join');
710
+ 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));
711
+ 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]');
712
+ }
713
+ 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');
714
+ }
715
+
716
+ // cad set <project>/<assembly> <address>=<value> …
717
+ function editFields(ref) {
718
+ const pairs = pairsOf(positional().slice(2), 'cad set');
719
+ 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)`);
720
+ edited(setInAssembly(ref, Object.fromEntries(pairs), { dryRun: !!opt('dry-run') }), 'set');
721
+ }
722
+ // cad set <project> field=value …
723
+ function editProject(project) {
724
+ const pairs = pairsOf(positional().slice(2), 'cad set');
725
+ if (!pairs.length) throw new Error(`usage: cad set ${project} material=PETG printer=x1c title="…"`);
726
+ edited(setProject(project, Object.fromEntries(pairs), { dryRun: !!opt('dry-run') }), 'set');
727
+ }
728
+ // cad remove <project>/<assembly> <address> [--with-refs], cad move <project>/<assembly> <id> --at | --to [--rotate]
729
+ function removeOrMove(cmd, ref, what) {
730
+ if (!what || !isAssembly(ref)) throw new Error(`usage: cad ${cmd} ${USAGE[cmd]}${ref && !isAssembly(ref) ? ` (there is no assembly ${ref})` : ''}`);
731
+ if (cmd === 'remove') return edited(removeFromAssembly(ref, what, { withRefs: !!opt('with-refs'), dryRun: !!opt('dry-run') }), 'remove');
732
+ const list = (k) => (typeof opt(k) === 'string' ? opt(k).split(',').map((x) => parseValue(x.trim())) : undefined);
733
+ const at = typeof opt('at') !== 'string' ? undefined : opt('at').includes(',') ? list('at') : parseValue(opt('at'));
734
+ edited(moveInAssembly(ref, what, { at, to: typeof opt('to') === 'string' ? opt('to') : undefined, rotate: list('rotate'), dryRun: !!opt('dry-run') }), 'move');
653
735
  }
654
736
 
655
737
  // cad why <project>/<object>.<name>: the value, and what it reads, down to the rules (estimates marked)