commandagi 0.6.10

The CommandAGI SDK for Rust: the platform client (agent threads, live sessions on a simulated world) and CommandAGI documents (a schematic, a 3D part …) declared as code. No dependencies.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
//! 2D DOCUMENTS IN RUST — a drawing, a paint document, a photo and a nest, declared as the nodes the CommandAGI 2D
//! editors draw and edit. The same nodes, node for node, as the TypeScript SDK's JSX (`twod.ts`) and the Python SDK's
//! `commandagi.design.twod`:
//!
//! ```
//! use commandagi::design::twod::*;
//!
//! fn document() -> El {
//!     drawing([layer([
//!         rect().x(40).y(40).w(200).h(120).fill("#3b82f6"),
//!         group([
//!             ellipse().cx(500).cy(300).rx(60).ry(60).fill("#f59e0b"),
//!             path().d("M 440 300 L 560 300").stroke_color("#111111").stroke_width(2),
//!         ])
//!         .name("Badge"),
//!     ])
//!     .name("Layer 1")])
//!     .name("Poster")
//!     .width(800)
//!     .height(600)
//!     .background("#ffffff")
//! }
//! # commandagi::design::declare(document()).unwrap();
//! ```
//!
//! The root names the document: `drawing` (layers of shapes, `.draw.rs`), `painting` (a layer stack of brush strokes,
//! `.paint.rs`), `photo` (pixel layers, adjustments, filters, `.img.rs`) and `nest` (flat parts nested on a sheet,
//! `.nest.rs`).
//!
//! ONE RULE FOR EVERY TAG: an element is one node, its attributes are the node's inputs (`.stroke_width(2)` is
//! `strokeWidth`), and its children are the nodes it takes, in order. `.id(…)`, `.label(…)` and `.disabled(true)` set
//! the node's own fields. The encodings are the TypeScript SDK's: a drawing is its first artboard, and each
//! `artboard([layer([…])])` after its layers is another; a top-level group of a drawing is a `layer`; a path's
//! `d` (absolute M L H V C Q Z); a drawn brush stroke's `[x, y]` points; a paint stroke's `[x, y, pressure, t]` points;
//! a modifier (`blur`, `transform`, `fill` …) wraps the one node it takes; `compound([…]).op("minus")` holds its shapes
//! (a live Pathfinder: `unite`, `minus`, `intersect` or `exclude`); `clip` takes its content, then its mask;
//! `link().src("parts/Badge.draw.rs").x(40).y(60)` shows another drawing's first artboard as that file draws it now
//! (`src`: a path from this file's folder, or an address; `.inputs(json(r#"{"size": 40}"#))` gives values to the
//! parameters that drawing declares); a painting's filter (`gaussian_blur([]).radius(3)`, the photo's filters) chains
//! among a layer's strokes and changes what is under it; in a
//! painting or a photo a `mask` child of a layer, a stroke or a filter holds the one layer that masks it, and
//! `mask([]).of("Shadow")` names a layer the stack shows, by its `name`; a painting's
//! `text_layer` is a type layer; a painting layer's `fx` holds its styles (`drop_shadow`, `inner_shadow`, `outer_glow`,
//! `inner_glow`, `bevel_emboss`, `satin`, `stroke`, `color_overlay`, `gradient_overlay`, `pattern_overlay`); a
//! constrained sketch is a leaf whose geometry is its own data:
//! `sketch().sketch(json(r#"{"points": {…}}"#)).x(40).y(60).unit("mm")` (the object a 3D document's sketch holds; its
//! stored positions are the last solve), and it may be written straight on the drawing (it is then its own layer). A value that
//! is an object is JSON text: `.brush(json(r#"{"kind": "round", "size": 4}"#))`. PIXELS ARE NOT CODE: a pixel layer
//! names its image file by relative path (`.src("scan.png")`). Each node carries its element's call in `meta.source`; a
//! `mask` is not a node, so a masked node carries the mask's call in `meta.sources.mask`. A tag the vocabulary does not
//! have is refused by name.
//!
//! A filter and a link are checked against their schema ([`twod_schema`], generated from the types the editors run); a
//! wrong one is refused with every issue: `gaussian_blur(): radius: must be at most 250 (got 300)`.
//!
//! A root without `.name(…)` declares the document named after its file, as TypeScript does ("Drawing" with no file).

use super::element::{attributes, elements, rust_name};
use super::ir::{channels, slug, wire, Scope};
use super::read::{call, tag};
use super::schema::{describe_issue, validate, with_defaults};
use super::source::meta;
use super::{Declared, Family};
use std::sync::OnceLock;
pub use super::{fragment, json, El, Json, Value};

elements! {
    /// A drawing: its layers, then its other artboards (the drawing is the first).
    drawing: children;
    /// Another artboard of a drawing: its layers, `artboard([layer([…])]).name("Back").width(400).height(300)`.
    artboard: children;
    /// A paint document: its layer stack, bottom first.
    painting: children;
    /// A photo: its layer stack, bottom first.
    photo: children;
    /// A nest: its sheet, stock, options, parts and engraves.
    nest: children;
    /// A drawing's layer (its shapes), or a paint document's pixel layer (its strokes and mask).
    layer: children;
    /// A group: of shapes in a drawing, of layers in a paint document or a photo.
    group: children;
    /// A rectangle: `rect().x(…).y(…).w(…).h(…)`.
    rect: leaf;
    /// An ellipse: `ellipse().cx(…).cy(…).rx(…).ry(…)`.
    ellipse: leaf;
    /// A regular polygon.
    polygon: leaf;
    /// A path: `path().d("M 0 0 L 10 0")`.
    path: leaf;
    /// A text: `text().text("Open studio").x(…).y(…).size(…)`.
    text: leaf;
    /// A drawn brush stroke: `[x, y]` points.
    brush_stroke = "brush-stroke": leaf;
    /// A placed image: `image().src("photo.png")`.
    image: leaf;
    /// A raster layer of a drawing: `raster_layer().src("scan.png")`.
    raster_layer = "raster-layer": leaf;
    /// A drawing's link to another drawing: `link().src("parts/Badge.draw.rs").x(40).y(60)`.
    link: leaf;
    /// A constrained sketch: graphics' `Sketch` as JSON text, placed on the page:
    /// `sketch().sketch(json(r#"{"points": {…}}"#)).x(40).y(60).unit("mm")`.
    sketch: leaf;
    /// A drawing's modifier: the one node it changes.
    transform: children;
    /// A drawing's modifier: the one node it changes.
    offset: children;
    /// A drawing's modifier: the one node it changes.
    array: children;
    /// A drawing's modifier: the one node it changes.
    mirror: children;
    /// A drawing's modifier (the one node it changes), or a paint stroke (its mask).
    stroke: children;
    /// A drawing's modifier (the one node it changes), or a stack's colour layer.
    fill: children;
    /// A drawing's modifier: the one node it changes.
    blur: children;
    /// A drawing's modifier (the one node it changes), or a photo's adjustment.
    levels: children;
    /// A drawing's modifier (the one node it changes), or a photo's adjustment.
    threshold: children;
    /// A drawing's modifier: the one node it changes.
    adjust: children;
    /// A drawing's modifier: the one node it changes.
    crop: children;
    /// A drawing's modifier: the one node it changes.
    bucket_fill = "bucket-fill": children;
    /// A drawing's compound shape: the shapes it holds, combined live (`.op("unite" | "minus" | "intersect" |
    /// "exclude")`).
    compound: children;
    /// A drawing's clip: its content, then its mask.
    clip: children;
    /// A photo's pixel layer: `raster([filters]).src("photo.png")`.
    raster: children;
    /// A photo's gradient layer.
    gradient: children;
    /// The one layer that masks a layer, a stroke or a filter (`.enabled(false)`: turned off); `mask([]).of("Shadow")`
    /// names a layer the stack shows, by its name.
    mask: children;
    /// A painting's line layer: `line().from(json("[0, 0]")).to(json("[40, 30]"))`.
    line: leaf;
    /// A painting's Paint Bucket on a layer: `bucket().x(…).y(…).tolerance(32).color(…)`.
    bucket: leaf;
    /// A painting's Gradient on a layer.
    gradient_fill = "gradientFill": leaf;
    /// A painting's Move of a layer's pixels (or its selected pixels).
    move_ = "move": leaf;
    /// A painting's Eraser on a layer (or its selected pixels): `erase().selection(…)`.
    erase: leaf;
    /// A painting's Free Transform of a layer's pixels about a pivot: `free_transform().cx(…).cy(…).scale_x(1.5)`.
    free_transform = "freeTransform": leaf;
    /// A painting's type layer: `text_layer([]).text("Title").x(…).y(…).size(96)`.
    text_layer = "textLayer": children;
    /// A painting layer's styles: `fx([drop_shadow().distance(8), stroke([]).size(3)])`.
    fx: children;
    /// A layer style: a shadow under the layer.
    drop_shadow = "dropShadow": leaf;
    /// A layer style: a shadow inside the layer's edge.
    inner_shadow = "innerShadow": leaf;
    /// A layer style: a glow around the layer.
    outer_glow = "outerGlow": leaf;
    /// A layer style: a glow inside the layer's edge (or from its centre).
    inner_glow = "innerGlow": leaf;
    /// A layer style: a lit and shaded bevel of the layer's edge.
    bevel_emboss = "bevelEmboss": leaf;
    /// A layer style: a shading of the layer's interior.
    satin: leaf;
    /// A layer style: the layer's colour replaced.
    color_overlay = "colorOverlay": leaf;
    /// A layer style: a gradient over the layer.
    gradient_overlay = "gradientOverlay": leaf;
    /// A layer style: a built-in pattern over the layer.
    pattern_overlay = "patternOverlay": leaf;
    /// A photo's adjustment.
    exposure: children;
    /// A photo's adjustment.
    curves: children;
    /// A photo's adjustment.
    hsl: children;
    /// A photo's adjustment.
    vibrance: children;
    /// A photo's adjustment.
    color_balance = "colorBalance": children;
    /// A photo's adjustment.
    black_white = "blackWhite": children;
    /// A photo's adjustment.
    invert: children;
    /// A photo's adjustment.
    posterize: children;
    /// A photo's adjustment: the develop (light, colour, effects) in one tag.
    develop: children;
    /// A filter on a photo's raster or among a painting layer's strokes (its child: its mask).
    gaussian_blur = "gaussianBlur": children;
    /// A filter on a photo's raster or among a painting layer's strokes (its child: its mask).
    unsharp_mask = "unsharpMask": children;
    /// A filter on a photo's raster or among a painting layer's strokes (its child: its mask).
    sharpen: children;
    /// A filter on a photo's raster or among a painting layer's strokes (its child: its mask).
    noise: children;
    /// A nest's sheet.
    sheet: leaf;
    /// A nest's stock.
    stock: leaf;
    /// A nest's options.
    options: leaf;
    /// A nest's part: `part().id("tab").quantity(2).outline([[0, 0], [10, 0], [10, 5]])`.
    part: leaf;
    /// An image burned on a nest's first sheet:
    /// `engrave().id("logo").src("logo.png").x_mm(20).y_mm(20).width_mm(60).height_mm(30).dpi(254).dither("ordered")`.
    engrave: leaf;
}

attributes! {
    /// The 2D documents' attributes: each is the node input of its TypeScript name.
    pub trait TwodAttrs {
        /// The node's id (a nest's part: the name its placements use).
        id;
        /// The node's label.
        label;
        /// The node is disabled.
        disabled;
        /// A layer's or a document's name.
        name;
        /// Shown.
        visible;
        /// Opacity, 0 to 1.
        opacity;
        /// A layer's blend mode.
        blend;
        /// A layer clips to the layer below.
        clip;
        /// A layer is locked.
        locked;
        /// A group is collapsed.
        collapsed;
        /// Wide (a document, a layer).
        width;
        /// High (a document, a layer).
        height;
        /// A document's background.
        background;
        /// A document's dots per inch.
        dpi;
        /// Across.
        x;
        /// Down.
        y;
        /// Wide (a shape).
        w;
        /// High (a shape).
        h;
        /// A corner radius, or a radius across.
        rx;
        /// A radius down.
        ry;
        /// A centre across.
        cx;
        /// A centre down.
        cy;
        /// Rotation, in degrees.
        rotation;
        /// A polygon's sides.
        sides;
        /// A radius.
        radius;
        /// A path's SVG data (absolute M L H V C Q Z).
        d;
        /// A path's subpaths (written as `d`).
        subpaths;
        /// A stroke's points.
        points;
        /// A text's text.
        text;
        /// A text's font family.
        family;
        /// A type layer's face.
        font;
        /// A text's size.
        size;
        /// A text's weight.
        weight;
        /// A text's alignment.
        align;
        /// A text's letter spacing.
        letter_spacing;
        /// A text's line height.
        line_height;
        /// A fill.
        fill;
        /// A stroke.
        stroke;
        /// A stroke's colour.
        stroke_color;
        /// A stroke's width.
        stroke_width;
        /// A stroke's start cap.
        start_cap;
        /// A stroke's end cap.
        end_cap;
        /// The image file, by its path relative to this file; a link's drawing, by that path or by an address.
        src;
        /// A link's values for the parameters the linked drawing declares: `json(r#"{"size": 40}"#)`.
        inputs;
        /// A transform.
        transform;
        /// A pattern overlay's cell size (document pixels).
        scale;
        /// A scale across.
        scale_x;
        /// A scale down.
        scale_y;
        /// A move across.
        dx;
        /// A move down.
        dy;
        /// An offset's distance.
        delta;
        /// An array's count.
        count;
        /// An array's count across.
        count_x;
        /// An array's count down.
        count_y;
        /// An array's sweep.
        sweep;
        /// A mirror's axis.
        axis;
        /// A compound shape's operation.
        op;
        /// A kind.
        kind;
        /// A brush stroke erases.
        erase;
        /// A brush's texture.
        texture;
        /// A bucket fill's tolerance.
        tolerance;
        /// A bucket fill or a magic wand reaches only the like pixels joined to the seed.
        contiguous;
        /// The region an operation of a painting changed: `json(r#"[{"rect": [10, 10, 40, 30], "feather": 4}]"#)`.
        selection;
        /// A colour.
        color;
        /// Brightness.
        brightness;
        /// Contrast.
        contrast;
        /// Exposure.
        exposure;
        /// Gamma.
        gamma;
        /// Hue.
        hue;
        /// Saturation.
        saturation;
        /// Lightness.
        lightness;
        /// Temperature.
        temperature;
        /// Vibrance.
        vibrance;
        /// Levels: the input black.
        in_black;
        /// Levels: the input white.
        in_white;
        /// Levels: the output black.
        out_black;
        /// Levels: the output white.
        out_white;
        /// A threshold's level.
        level;
        /// A posterize's levels.
        levels;
        /// Spacing.
        spacing;
        /// An asset.
        asset;
        /// Annotations.
        annotations;
        /// Where.
        at;
        /// A drawing's scale.
        drawing_scale;
        /// A connector's end.
        from_end;
        /// A connector's end.
        to_end;
        /// A connector's routing.
        routing;
        /// A reference.
        ref_;
        /// A sketch.
        sketch;
        /// A unit.
        unit;
        /// A paint stroke's brush: `json(r#"{"kind": "round", "size": 4}"#)`.
        brush;
        /// A paint stroke's symmetry.
        mirror;
        /// A gradient's shape: "linear" or "radial".
        shape;
        /// A gradient's start.
        from;
        /// A gradient's end.
        to;
        /// A gradient's stops.
        stops;
        /// Exposure in stops.
        ev;
        /// An exposure's offset.
        offset;
        /// A levels' channel.
        channel;
        /// A curve of all channels.
        rgb;
        /// A curve of red.
        r;
        /// A curve of green.
        g;
        /// A curve of blue.
        b;
        /// A colour balance's shadows.
        shadows;
        /// A colour balance's midtones.
        midtones;
        /// A colour balance's highlights.
        highlights;
        /// A colour balance keeps the luminosity.
        preserve_luminosity;
        /// Black and white: red.
        red;
        /// Black and white: yellow.
        yellow;
        /// Black and white: green.
        green;
        /// Black and white: cyan.
        cyan;
        /// Black and white: blue.
        blue;
        /// Black and white: magenta.
        magenta;
        /// A filter's amount.
        amount;
        /// A filter's threshold.
        threshold;
        /// Noise is monochrome.
        monochrome;
        /// Noise's seed.
        seed;
        /// A develop's tint.
        tint;
        /// A develop's whites.
        whites;
        /// A develop's blacks.
        blacks;
        /// A develop's dehaze.
        dehaze;
        /// A develop's vignette.
        vignette;
        /// A develop's grain.
        grain;
        /// A develop's clarity (local contrast).
        clarity;
        /// A develop's tone curve.
        curve;
        /// A develop's sections turned off: `["light", "color", "effects"]`.
        off;
        /// A mask is on.
        enabled;
        /// A mask's layer: the name of a layer the stack shows.
        of;
        /// A style's angle, in degrees.
        angle;
        /// A shadow's distance.
        distance;
        /// A shadow's or a glow's spread.
        spread;
        /// An inner shadow's choke.
        choke;
        /// A stroke style's position: "outside", "inside" or "center".
        position;
        /// A bevel's lit side colour.
        highlight;
        /// A bevel's shaded side colour.
        shadow;
        /// The blend mode a bevel's lit side is laid with.
        highlight_blend;
        /// The blend mode a bevel's shaded side is laid with.
        shadow_blend;
        /// A bevel's light altitude, in degrees.
        altitude;
        /// A bevel's contrast.
        depth;
        /// A bevel's softness.
        soften;
        /// A bevel's direction: "up" or "down".
        direction;
        /// A pattern overlay's built-in pattern: "checks", "stripes", "dots" or "grid".
        pattern;
        /// A satin shades the other side.
        invert;
        /// A nest's safe height (mm).
        safe_z_mm;
        /// A nest's overrides.
        overrides;
        /// A sheet's width (mm).
        width_mm;
        /// A sheet's height (mm).
        height_mm;
        /// A sheet's margin (mm).
        margin_mm;
        /// A stock's material.
        material_id;
        /// A stock's thickness (mm).
        thickness_mm;
        /// A stock's machine: `json(r#"{"powerW": 40}"#)`.
        machine;
        /// The nest's resolution (mm).
        resolution_mm;
        /// The kerf (mm).
        kerf_mm;
        /// The spacing between parts (mm).
        spacing_mm;
        /// The rotations a part may take (degrees).
        rotations;
        /// The most sheets.
        max_sheets;
        /// How many of a part.
        quantity;
        /// A part's outline: `[x, y]` points.
        outline;
        /// A part's holes: lists of `[x, y]` points.
        holes;
        /// The file a nest's part was imported from: `json(r#"{"file": "disc.svg"}"#)`.
        source;
        /// An engrave's left edge on the sheet (mm).
        x_mm;
        /// An engrave's lower edge on the sheet (mm).
        y_mm;
        /// An engrave's dither: "none", "ordered" or "floyd-steinberg".
        dither;
        /// An engrave's power for the darkest pixel (%).
        power_pct;
        /// An engrave's lasing threshold (%).
        min_power_pct;
        /// An engrave's feed (mm/min).
        feed_mm_min;
        /// How many times an engrave is burned.
        passes;
    }
}

pub(crate) const FAMILY: Family = Family { module: "twod", roots: &["drawing", "painting", "photo", "nest"], declare };

/// A painting layer's styles: the tags of its `fx`.
pub const LAYER_STYLES: &[&str] = &["dropShadow", "innerShadow", "outerGlow", "innerGlow", "bevelEmboss", "satin", "stroke", "colorOverlay", "gradientOverlay", "patternOverlay"];

/// A photo's adjustments: each a layer whose attributes are the adjustment.
pub const PHOTO_ADJUSTMENTS: &[&str] = &["exposure", "levels", "curves", "hsl", "vibrance", "colorBalance", "blackWhite", "invert", "threshold", "posterize", "develop"];
/// The filters: each on a photo's raster, or among a painting layer's strokes.
pub const PHOTO_FILTERS: &[&str] = &["gaussianBlur", "unsharpMask", "sharpen", "noise"];

/// The name of a document whose root names none: the file's, as TypeScript names it ("Drawing" with no file).
fn unnamed() -> String {
    super::source::stem().unwrap_or_else(|| "Drawing".into())
}

fn declare(root: El) -> Result<Declared, String> {
    let mut d = Doc::default();
    let graph = match root.tag {
        "drawing" => d.drawing(&root)?,
        "painting" => d.stack_document(&PAINT, &root)?,
        "photo" => d.stack_document(&PHOTO, &root)?,
        _ => d.nest(&root)?,
    };
    Ok(Declared::Graph(graph))
}

fn place(el: &El) -> String {
    call(el, &["name"])
}

/// The schema of the 2D elements that are checked when read (`roots`: tag → definition, `$defs`): the filters and the
/// link, generated from the types the editors run.
pub fn twod_schema() -> &'static Json {
    static SCHEMA: OnceLock<Json> = OnceLock::new();
    SCHEMA.get_or_init(|| Json::parse(include_str!("twod_schema.json")).expect("twod_schema.json is JSON"))
}

/// `el` with `fields`, checked against its tag's schema: the element as the editors hold it (`{ type, …fields }`), with
/// each required field it leaves out at its declared default ([`with_defaults`]).
fn checked(el: &El, fields: &Json) -> Result<Json, String> {
    let schema = twod_schema();
    let def = schema.get("roots").and_then(|r| r.get(el.tag)).and_then(Json::as_str).expect("a tag of the schema");
    let defs = schema.get("$defs").cloned().unwrap_or_else(Json::obj);
    let root = Json::obj().with("$ref", format!("#/$defs/{def}"));
    let value = with_defaults(&root, &spread(Json::obj().with("type", el.tag), entries(fields).to_vec()), &defs)?;
    let issues = validate(&root, &value, &defs, "")?;
    if issues.is_empty() {
        return Ok(value);
    }
    Err(format!("{}: {}", place(el), issues.iter().map(describe_issue).collect::<Vec<_>>().join("; ")))
}

/// A value is plain data with finite numbers.
fn plain(v: &Json, what: &str) -> Result<(), String> {
    match v {
        Json::Num(n) if !n.is_finite() => Err(format!("{what}: {n} is not a finite number")),
        Json::Arr(items) => items.iter().enumerate().try_for_each(|(i, x)| plain(x, &format!("{what}[{i}]"))),
        Json::Obj(entries) => entries.iter().try_for_each(|(k, x)| plain(x, &format!("{what}.{k}"))),
        _ => Ok(()),
    }
}

/// An element's attributes as the node's inputs, without the node's own fields (`id`, `label`, `disabled`).
/// A compound's operations, the draw graph's: its refusal comes here, at declaration, in its words.
const COMPOUND_OPS: [&str; 4] = ["unite", "minus", "intersect", "exclude"];

fn attrs(el: &El, skip: &[&str]) -> Result<Json, String> {
    let mut out = Json::obj();
    for (k, v) in &el.attrs {
        if ["id", "label", "disabled"].contains(&k.as_str()) || skip.contains(&k.as_str()) {
            continue;
        }
        plain(v, &format!("{} {}", place(el), rust_name(k)))?;
        out.set(k, v.clone());
    }
    Ok(out)
}

fn entries(j: &Json) -> &[(String, Json)] {
    match j {
        Json::Obj(e) => e,
        _ => &[],
    }
}

/// `inputs` with `more` written over it, as JavaScript's spread writes one object over another.
fn spread(mut inputs: Json, more: impl IntoIterator<Item = (String, Json)>) -> Json {
    for (k, v) in more {
        inputs.set(&k, v);
    }
    inputs
}

fn wires(set: &str, ids: &[String]) -> Vec<(String, Json)> {
    channels(set, ids.iter().map(|id| wire(id, "out")).collect())
}

// ── Drawing ─────────────────────────────────────────────────────────────────────────────────────────────────────

const DRAW_SOURCES: &[&str] = &["rect", "ellipse", "polygon", "path", "text", "brush-stroke"];
/// Modifiers: the one node each takes is its child, on port `in`.
const DRAW_MODIFIERS: &[&str] = &["transform", "offset", "array", "mirror", "stroke", "fill", "blur", "levels", "threshold", "adjust", "crop", "bucket-fill"];
/// Pixels a drawing places: each names its image file (`src`).
const DRAW_PIXELS: &[&str] = &["image", "raster-layer"];
/// Drawables written with their own data: a constrained sketch (one `Sketch` object).
const DRAW_DATA: &[&str] = &["sketch"];
const DRAW_LATER: &[&str] = &["connector"];

/// An address (`cloud://…`, `https://…`, a path from the site's root); anything else is a path from the file's folder.
fn is_address(src: &str) -> bool {
    if src.starts_with('/') {
        return true;
    }
    match src.find("://") {
        Some(i) if i > 0 => {
            let scheme = src[..i].as_bytes();
            scheme[0].is_ascii_alphabetic() && scheme.iter().all(|b| b.is_ascii_alphanumeric() || b"+.-".contains(b))
        }
        _ => false,
    }
}

/// The tokens of an SVG path's `d`: its command letters and its numbers (`-?(\d+\.?\d*|\.\d+)(e[-+]?\d+)?`).
fn path_tokens(d: &str) -> Vec<String> {
    let s: Vec<char> = d.chars().collect();
    let digit = |i: usize| s.get(i).is_some_and(|c| c.is_ascii_digit());
    let mut out = Vec::new();
    let mut i = 0;
    while i < s.len() {
        if "MLHVCQZmlhvcqz".contains(s[i]) {
            out.push(s[i].to_string());
            i += 1;
            continue;
        }
        let start = i;
        let mut j = if s[i] == '-' { i + 1 } else { i };
        let number = if digit(j) {
            while digit(j) {
                j += 1;
            }
            if s.get(j) == Some(&'.') {
                j += 1;
                while digit(j) {
                    j += 1;
                }
            }
            true
        } else if s.get(j) == Some(&'.') && digit(j + 1) {
            j += 1;
            while digit(j) {
                j += 1;
            }
            true
        } else {
            false
        };
        if !number {
            i += 1;
            continue;
        }
        if s.get(j) == Some(&'e') {
            let k = if matches!(s.get(j + 1), Some('-' | '+')) { j + 2 } else { j + 1 };
            if digit(k) {
                j = k;
                while digit(j) {
                    j += 1;
                }
            }
        }
        out.push(s[start..j].iter().collect());
        i = j;
    }
    out
}

/// An SVG path's `d` (absolute M L H V C Q Z) as the editor's subpaths.
pub fn subpaths_of(d: &str, what: &str) -> Result<Json, String> {
    let tokens = path_tokens(d);
    let is_cmd = |t: &str| t.chars().all(|c| c.is_ascii_alphabetic());
    let pt = |x: f64, y: f64| Json::obj().with("x", x).with("y", y);
    let mut out: Vec<Json> = Vec::new();
    let mut i = 0;
    let mut cmd = String::new();
    let (mut cx, mut cy) = (0.0, 0.0);
    let n = |i: &mut usize| -> Result<f64, String> {
        match tokens.get(*i) {
            Some(t) if !is_cmd(t) => {
                *i += 1;
                t.parse::<f64>().map_err(|_| format!("{what}: {t} is not a number"))
            }
            _ => Err(format!("{what}: d ends where a number is needed")),
        }
    };
    let segs = |out: &mut Vec<Json>| -> Result<(), String> {
        if out.is_empty() {
            Err(format!("{what}: d starts with M"))
        } else {
            Ok(())
        }
    };
    let push = |out: &mut Vec<Json>, seg: Json| {
        if let Some(Json::Arr(s)) = out.last_mut().and_then(|sp| match sp {
            Json::Obj(e) => e.iter_mut().find(|(k, _)| k == "segs").map(|(_, v)| v),
            _ => None,
        }) {
            s.push(seg);
        }
    };
    while i < tokens.len() {
        if is_cmd(&tokens[i]) {
            cmd = tokens[i].clone();
            i += 1;
        }
        if cmd != cmd.to_uppercase() {
            return Err(format!("{what}: d is written in absolute commands (M L H V C Q Z), not {cmd}"));
        }
        match cmd.as_str() {
            "M" => {
                (cx, cy) = (n(&mut i)?, n(&mut i)?);
                out.push(Json::obj().with("start", pt(cx, cy)).with("segs", Json::Arr(Vec::new())));
                cmd = "L".into();
            }
            "L" => {
                (cx, cy) = (n(&mut i)?, n(&mut i)?);
                segs(&mut out)?;
                push(&mut out, Json::obj().with("to", pt(cx, cy)));
            }
            "H" => {
                cx = n(&mut i)?;
                segs(&mut out)?;
                push(&mut out, Json::obj().with("to", pt(cx, cy)));
            }
            "V" => {
                cy = n(&mut i)?;
                segs(&mut out)?;
                push(&mut out, Json::obj().with("to", pt(cx, cy)));
            }
            "C" => {
                let c1 = pt(n(&mut i)?, n(&mut i)?);
                let c2 = pt(n(&mut i)?, n(&mut i)?);
                (cx, cy) = (n(&mut i)?, n(&mut i)?);
                segs(&mut out)?;
                push(&mut out, Json::obj().with("c1", c1).with("c2", c2).with("to", pt(cx, cy)));
            }
            "Q" => {
                let c1 = pt(n(&mut i)?, n(&mut i)?);
                (cx, cy) = (n(&mut i)?, n(&mut i)?);
                segs(&mut out)?;
                push(&mut out, Json::obj().with("c1", c1).with("to", pt(cx, cy)));
            }
            // A Z closes the subpath once: a number after it names no command (TypeScript would loop on it).
            "Z" if i >= tokens.len() || is_cmd(&tokens[i]) => {
                segs(&mut out)?;
                let last = out.last_mut().expect("a subpath");
                last.set("closed", true);
                let start = last.get("start").cloned().unwrap_or(Json::Null);
                cx = start.get("x").and_then(Json::as_f64).unwrap_or(0.0);
                cy = start.get("y").and_then(Json::as_f64).unwrap_or(0.0);
            }
            _ => return Err(format!("{what}: d has no command before {}", tokens[i])),
        }
    }
    Ok(Json::Arr(out))
}

fn pairs(v: &Json, what: &str) -> Result<Json, String> {
    let Json::Arr(points) = v else { return Err(format!("{what} is a list of [x, y] points")) };
    let out = points.iter().enumerate().map(|(i, p)| match p {
        Json::Arr(c) if c.len() == 2 && c.iter().all(|x| matches!(x, Json::Num(_))) => Ok(Json::obj().with("x", c[0].clone()).with("y", c[1].clone())),
        _ => Err(format!("{what}[{i}] is [x, y]")),
    });
    Ok(Json::Arr(out.collect::<Result<_, _>>()?))
}

const MIME: &[(&str, &str)] = &[("png", "image/png"), ("jpg", "image/jpeg"), ("jpeg", "image/jpeg"), ("webp", "image/webp"), ("gif", "image/gif"), ("bmp", "image/bmp")];

/// A pixel layer's `src`: the image file it names, as the document's own file names it.
fn asset(src: Option<&Json>, el: &El) -> Result<Json, String> {
    let src = match src {
        Some(Json::Str(s)) if !s.is_empty() && !s.starts_with("data:") => s,
        _ => return Err(format!("{}: src names an image file by relative path (\"scan.png\"); pixels are not written in code", place(el))),
    };
    let scheme = src.find(':').is_some_and(|i| i > 0 && src[..i].bytes().all(|b| b.is_ascii_alphabetic()));
    if src.starts_with('/') || scheme {
        return Err(format!("{}: src is a path relative to this file, not {src}", place(el)));
    }
    let ext = src.rsplit('.').next().unwrap_or("").to_lowercase();
    let mut a = Json::obj().with("kind", "file").with("$file", src.as_str());
    if let Some((_, mime)) = MIME.iter().find(|(e, _)| *e == ext) {
        a.set("mime", *mime);
    }
    Ok(a)
}

/// A paint stroke's point tuples as the editor's points.
fn stroke_points(v: &Json, what: &str) -> Result<Json, String> {
    let Json::Arr(points) = v else { return Err(format!("{what} is a list of [x, y, pressure, t] points")) };
    let out = points.iter().enumerate().map(|(i, p)| match p {
        Json::Arr(c) if (c.len() == 4 || c.len() == 6) && c.iter().all(|x| matches!(x, Json::Num(_))) => {
            let mut q = Json::obj().with("x", c[0].clone()).with("y", c[1].clone()).with("pressure", c[2].clone()).with("t", c[3].clone());
            if c.len() == 6 {
                q = q.with("tiltX", c[4].clone()).with("tiltY", c[5].clone());
            }
            Ok(q)
        }
        _ => Err(format!("{what}[{i}] is [x, y, pressure, t] or [x, y, pressure, t, tiltX, tiltY]")),
    });
    Ok(Json::Arr(out.collect::<Result<_, _>>()?))
}

// ── Paint and photo: a layer stack ─────────────────────────────────────────────────────────────────────────────

/// The fields every layer of a stack carries (a chain's top stands in for its layer in the stack).
const COMMON: &[&str] = &["name", "visible", "opacity", "blend", "clip", "locked"];

struct StackKind {
    root: &'static str,
    prefix: &'static str,
    /// A chain member's node type.
    chain_type: fn(&El) -> String,
    /// A layer's tag → its node type and inputs; none when the tag is not a layer.
    layer: fn(&El) -> Result<Option<(String, Json)>, String>,
    /// Whether a tag is a chain member's (a stroke, a bucket fill, a filter).
    chains: fn(&El) -> bool,
    /// A chain member's own inputs.
    chain: fn(&El) -> Result<Json, String>,
}

fn pixel_layer(el: &El, kind: &str) -> Result<Option<(String, Json)>, String> {
    let mut a = attrs(el, &["src"])?;
    if el.attr_of("src").is_some() {
        a.set("__asset", asset(el.attr_of("src"), el)?);
    }
    Ok(Some((kind.to_string(), a)))
}

fn common_refused(el: &El, a: &Json, why: &str) -> Result<(), String> {
    match COMMON.iter().find(|k| a.get(k).is_some()) {
        Some(k) => Err(format!("{}: {k} is the layer's ({why})", place(el))),
        None => Ok(()),
    }
}

/// An adjustment tag as a layer: the layer's own fields, and the rest as its `adjustment`.
fn adjustment_layer(el: &El, node_type: &str) -> Result<Option<(String, Json)>, String> {
    let mut common = Json::obj();
    let mut adjustment = Json::obj().with("type", el.tag);
    for (k, v) in entries(&attrs(el, &[])?) {
        if COMMON.contains(&k.as_str()) { &mut common } else { &mut adjustment }.set(k, v.clone());
    }
    Ok(Some((node_type.into(), common.with("adjustment", adjustment))))
}

/// A filter element as a chain member's inputs: its fields are its node's `filter`.
fn filter_member(el: &El) -> Result<Json, String> {
    let a = attrs(el, &[])?;
    common_refused(el, &a, "write it on the layer it filters")?;
    Ok(Json::obj().with("filter", checked(el, &a)?))
}

/// What is painted on a painting's pixel layer: strokes, the Paint Bucket, the Gradient, the Move tool. A filter
/// ([`PHOTO_FILTERS`]) chains among them.
pub const PAINT_CHAIN: &[&str] = &["stroke", "bucket", "gradientFill", "move", "erase", "freeTransform"];
/// A painting's shape layers.
pub const PAINT_SHAPES: &[&str] = &["rect", "ellipse", "polygon", "line"];

const PAINT: StackKind = StackKind {
    root: "painting",
    prefix: "paint",
    chain_type: |el| if PHOTO_FILTERS.contains(&el.tag) { "paint.filter".into() } else { format!("paint.{}", el.tag) },
    layer: |el| match el.tag {
        "layer" => pixel_layer(el, "paint.layer"),
        "fill" | "group" => Ok(Some((format!("paint.{}", el.tag), attrs(el, &[])?))),
        "textLayer" => {
            let a = attrs(el, &[])?;
            if a.get("text").and_then(Json::as_str).is_none() {
                return Err(format!("{}: text is the layer's words (.text(\"Title\"))", place(el)));
            }
            Ok(Some(("paint.text".into(), a)))
        }
        t if PHOTO_ADJUSTMENTS.contains(&t) => adjustment_layer(el, "paint.adjust"),
        t if PAINT_SHAPES.contains(&t) => Ok(Some(("paint.shape".into(), attrs(el, &[])?.with("shape", el.tag)))),
        _ => Ok(None),
    },
    chains: |el| PHOTO_FILTERS.contains(&el.tag) || PAINT_CHAIN.contains(&el.tag),
    chain: |el| {
        if PHOTO_FILTERS.contains(&el.tag) {
            return filter_member(el);
        }
        let mut a = attrs(el, &[])?;
        common_refused(el, &a, "write it on the layer it is painted on")?;
        if let (true, Some(points)) = (el.tag == "stroke", a.get("points")) {
            let points = stroke_points(points, &format!("{} points", place(el)))?;
            a.set("points", points);
        }
        Ok(a)
    },
};

const PHOTO: StackKind = StackKind {
    root: "photo",
    prefix: "photo",
    chain_type: |_| "photo.filter".into(),
    layer: |el| match el.tag {
        "raster" => pixel_layer(el, "photo.raster"),
        "fill" | "gradient" | "group" => Ok(Some((format!("photo.{}", el.tag), attrs(el, &[])?))),
        t if PHOTO_ADJUSTMENTS.contains(&t) => adjustment_layer(el, "photo.adjust"),
        _ => Ok(None),
    },
    chains: |el| PHOTO_FILTERS.contains(&el.tag),
    chain: filter_member,
};

// ── The declaration ────────────────────────────────────────────────────────────────────────────────────────────

/// What a `<mask>` is: the one layer it holds, or a layer the stack shows, named by `of`.
enum MaskOf<'a> {
    /// `<mask>`: the held layer's node, whether the mask is on, and the element.
    Held(String, bool, &'a El),
    /// `<mask of="Name" />`: the layer's name, whether the mask is on, and the element.
    Named(String, bool, &'a El),
}

impl<'a> MaskOf<'a> {
    fn el(&self) -> &'a El {
        match self {
            MaskOf::Held(_, _, m) | MaskOf::Named(_, _, m) => m,
        }
    }
}

/// One 2D graph being declared: the scope, and what is written on its nodes after they are added.
#[derive(Default)]
struct Doc {
    s: Option<Scope>,
    /// Nodes that are disabled.
    disabled: Vec<String>,
    /// What a node holds that is not a node (its mask element, its styles): its `meta.sources`.
    sources: Vec<(String, Json)>,
    /// Each slot's top node, by the name its layer element wrote (a `mask(of="…")` names one).
    layers: Vec<(String, String)>,
    /// Masks that name a layer, wired once every layer is declared: (node, name, on, where it was written).
    masks: Vec<(String, String, bool, String)>,
}

impl Doc {
    fn scope(&mut self) -> &mut Scope {
        self.s.as_mut().expect("a scope")
    }

    /// Declare `el` as one node of `kind`.
    fn add(&mut self, el: &El, kind: &str, inputs: Json) -> Result<String, String> {
        let id = match el.attr_of("id") {
            None => None,
            Some(Json::Str(s)) => Some(s.as_str()).filter(|s| !s.is_empty()),
            Some(_) => return Err(format!("{}: id is a string", place(el))),
        };
        let label = el.attr_of("label").and_then(Json::as_str);
        let Json::Obj(inputs) = inputs else { unreachable!("inputs are an object") };
        let nid = self.scope().add(kind, inputs, id, label, meta(el))?;
        if el.attr_of("disabled") == Some(&Json::Bool(true)) {
            self.disabled.push(nid.clone());
        }
        Ok(nid)
    }

    /// The graph: `{id, nodes, outputs, meta}`, with the fields written after each node was added.
    fn build(&mut self, output: &str) -> Json {
        self.build_all(&[output.to_string()])
    }

    fn build_all(&mut self, outputs: &[String]) -> Json {
        let g = self.s.take().expect("a scope").build();
        let mut nodes = g.get("nodes").cloned().unwrap_or(Json::obj());
        if let Json::Obj(entries) = &mut nodes {
            for (id, node) in entries.iter_mut() {
                if self.disabled.contains(id) {
                    node.set("disabled", true);
                }
                if let Some((_, at)) = self.sources.iter().find(|(m, _)| m == id) {
                    let m = node.remove("meta").unwrap_or(Json::obj()).with("sources", at.clone());
                    node.set("meta", m);
                }
            }
        }
        Json::obj()
            .with("id", g.get("id").cloned().unwrap_or(Json::Null))
            .with("nodes", nodes)
            .with("outputs", Json::Arr(outputs.iter().map(|o| o.as_str().into()).collect()))
            .with("meta", g.get("meta").cloned().unwrap_or(Json::obj()))
    }

    fn drawn(&mut self, el: &El, top: bool) -> Result<String, String> {
        let t = el.tag;
        let kids: Vec<&El> = el.child_elements().collect();
        if t == "layer" && !top {
            return Err(format!("{}: a layer() is a child of the drawing(); inside it, group with group()", place(el)));
        }
        if t == "layer" || t == "group" {
            let children = kids.iter().map(|c| self.drawn(c, false)).collect::<Result<Vec<_>, _>>()?;
            return self.add(el, "group", spread(attrs(el, &[])?, wires("children", &children)));
        }
        if DRAW_SOURCES.contains(&t) {
            if !kids.is_empty() {
                return Err(format!("{} takes no children", place(el)));
            }
            let mut a = attrs(el, &[])?;
            if t == "path" {
                if a.get("subpaths").is_some() {
                    return Err(format!("{}: a path is written with d (an SVG path), not subpaths", place(el)));
                }
                if let Some(d) = a.remove("d") {
                    let Json::Str(d) = d else { return Err(format!("{}: d is an SVG path string", place(el))) };
                    a.set("subpaths", subpaths_of(&d, &place(el))?);
                }
            }
            if t == "brush-stroke" {
                if let Some(points) = a.get("points") {
                    let points = pairs(points, &format!("{} points", place(el)))?;
                    a.set("points", points);
                }
            }
            return self.add(el, t, a);
        }
        if DRAW_DATA.contains(&t) {
            if !kids.is_empty() {
                return Err(format!("{} takes no children", place(el)));
            }
            let a = attrs(el, &[])?;
            if !matches!(a.get("sketch"), Some(Json::Obj(_))) {
                return Err(format!("{}: sketch is its geometry, as the editor holds it ({{ points, segments, constraints, … }})", place(el)));
            }
            return self.add(el, t, a);
        }
        if DRAW_PIXELS.contains(&t) {
            if !kids.is_empty() {
                return Err(format!("{} takes no children", place(el)));
            }
            if el.attr_of("src").is_none() {
                return Err(format!("{}: src names its image file by relative path (\"photo.png\")", place(el)));
            }
            let a = attrs(el, &["src"])?.with("__asset", asset(el.attr_of("src"), el)?);
            return self.add(el, t, a);
        }
        if t == "link" {
            let mut placed = checked(el, &attrs(el, &[])?)?;
            placed.remove("type");
            let Some(Json::Str(src)) = placed.remove("src") else { unreachable!("the schema requires src") };
            if src.trim().is_empty() || src.starts_with("data:") {
                return Err(format!("{}: src names a drawing by its path from this file's folder (\"parts/Badge.draw.rs\") or by an address", place(el)));
            }
            let reference = Json::obj().with(if is_address(&src) { "assetPath" } else { "path" }, src.as_str());
            return self.add(el, "draw.instance", spread(Json::obj().with("__instance", reference), entries(&placed).to_vec()));
        }
        if DRAW_MODIFIERS.contains(&t) {
            if kids.len() != 1 {
                return Err(format!("{} wraps the one node it changes", place(el)));
            }
            let a = attrs(el, &[])?;
            let input = self.drawn(kids[0], false)?;
            return self.add(el, t, a.with("in", wire(&input, "out")));
        }
        if t == "compound" {
            if let Some(op) = el.attr_of("op") {
                if !op.as_str().is_some_and(|o| COMPOUND_OPS.contains(&o)) {
                    return Err(format!("compound.op is unite, minus, intersect or exclude, not {}", op.text()));
                }
            }
            let a = attrs(el, &[])?;
            let shapes = kids.iter().map(|c| self.drawn(c, false)).collect::<Result<Vec<_>, _>>()?;
            return self.add(el, t, spread(a, wires("children", &shapes)));
        }
        if t == "clip" {
            if kids.len() != 2 {
                return Err(format!("{} takes its content, then its mask", place(el)));
            }
            let a = attrs(el, &[])?;
            let content = self.drawn(kids[0], false)?;
            let mask = self.drawn(kids[1], false)?;
            return self.add(el, t, a.with("content", wire(&content, "out")).with("mask", wire(&mask, "out")));
        }
        if DRAW_LATER.contains(&t) {
            return Err(format!("{} is not declared in code yet (a drawing in code holds shapes, images, sketches, links, groups and modifiers)", tag(t)));
        }
        Err(format!("{} is not read in a drawing (see commandagi::design::twod)", tag(t)))
    }

    fn drawing(&mut self, root: &El) -> Result<Json, String> {
        let a = attrs(root, &["name", "width", "height", "background"])?;
        if let Some((k, _)) = entries(&a).first() {
            return Err(format!("drawing(): {} is not read (a drawing has name, width, height, background)", rust_name(k)));
        }
        // A drawing with no name of its own declares none; the file's name only names the graph.
        let own = root.attr_of("name").and_then(Json::as_str);
        let mut m = Json::obj();
        if let Some(own) = own {
            m.set("name", own);
        }
        for k in ["width", "height", "background"] {
            if let Some(v) = root.attr_of(k) {
                plain(v, &format!("drawing() {k}"))?;
                m.set(k, v.clone());
            }
        }
        self.s = Some(Scope::new(&format!("draw:{}", slug(&own.map(str::to_string).unwrap_or_else(unnamed))), m.clone()));
        // The drawing is its first artboard: its layers are its own; each artboard() after them is another.
        let children: Vec<&El> = root.child_elements().collect();
        if let Some(first) = children.iter().position(|c| c.tag == "artboard") {
            if children[first..].iter().any(|c| c.tag != "artboard") {
                return Err("drawing(): its layers come before its artboard()s (the drawing is the first artboard)".into());
            }
        }
        let layers = children.iter().filter(|c| c.tag != "artboard").map(|c| self.drawn(c, true)).collect::<Result<Vec<_>, _>>()?;
        let mut inputs = Vec::new();
        if let Some(bg) = m.get("background") {
            inputs.push(("background".to_string(), bg.clone()));
        }
        inputs.extend(wires("layers", &layers));
        let comp = self.scope().add("composite", inputs, Some("composite"), Some("Output"), meta(root))?;
        let boards: Vec<&El> = children.iter().copied().filter(|c| c.tag == "artboard").collect();
        if boards.is_empty() {
            return Ok(self.build(&comp));
        }
        let fields = |from: &Json| {
            let mut f = Vec::new();
            for k in ["width", "height", "background"] {
                if let Some(v) = from.get(k) {
                    f.push((k.to_string(), v.clone()));
                }
            }
            f
        };
        let page = |id: &str, name: &str, f: Vec<(String, Json)>| {
            let mut p = Json::obj().with("id", id).with("name", name);
            for (k, v) in f {
                p.set(&k, v);
            }
            p.with("compositeId", id)
        };
        let mut pages = vec![page("composite", own.unwrap_or("Artboard 1"), fields(&m))];
        let mut outputs = vec![comp];
        for (i, b) in boards.iter().enumerate() {
            let a = attrs(b, &["name", "width", "height", "background"])?;
            if let Some((k, _)) = entries(&a).first() {
                return Err(format!("{}: {} is not read (an artboard has name, width, height, background)", place(b), rust_name(k)));
            }
            let name = b.attr_of("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(|| format!("Artboard {}", i + 2));
            let mut own_fields = Json::obj();
            for k in ["width", "height", "background"] {
                if let Some(v) = b.attr_of(k) {
                    plain(v, &format!("{} {k}", place(b)))?;
                    own_fields.set(k, v.clone());
                }
            }
            let mut board_layers = Vec::new();
            for c in b.child_elements() {
                if c.tag == "artboard" {
                    return Err(format!("{}: an artboard() is a child of the drawing(), not of another artboard", place(b)));
                }
                board_layers.push(self.drawn(c, true)?);
            }
            let id = match b.attr_of("id") {
                None => None,
                Some(Json::Str(s)) => Some(s.clone()).filter(|s| !s.is_empty()),
                Some(_) => return Err(format!("{}: id is a string", place(b))),
            };
            let mut inputs = Vec::new();
            if let Some(bg) = own_fields.get("background") {
                inputs.push(("background".to_string(), bg.clone()));
            }
            inputs.extend(wires("layers", &board_layers));
            let nid = self.scope().add("composite", inputs, id.as_deref(), Some(&name), meta(b))?;
            pages.push(page(&nid, &name, fields(&own_fields)));
            outputs.push(nid);
        }
        self.scope().meta.set("pages", Json::Arr(pages));
        Ok(self.build_all(&outputs))
    }

    /// A layer's (or a stroke's, or a filter's) `mask`: the one stack layer it holds, declared outside the stack and
    /// wired to the node's `mask` port. The `mask` element is not a node: its call is the masked node's
    /// `meta.sources.mask`.
    fn mask_of<'a>(&mut self, kind: &StackKind, el: &'a El) -> Result<Option<MaskOf<'a>>, String> {
        let masks: Vec<&El> = el.child_elements().filter(|c| c.tag == "mask").collect();
        let Some(m) = masks.first() else { return Ok(None) };
        if masks.len() > 1 {
            return Err(format!("{} has one mask()", place(el)));
        }
        let a = attrs(m, &[])?;
        for (k, v) in entries(&a) {
            if (k != "enabled" && k != "of") || (k == "enabled" && !matches!(v, Json::Bool(_))) || (k == "of" && !matches!(v, Json::Str(_))) {
                return Err(format!("mask() in {} has enabled and of (write the rest on the layer it holds or names)", place(el)));
            }
        }
        let on = a.get("enabled") != Some(&Json::Bool(false));
        if let Some(Json::Str(of)) = a.get("of") {
            let of = of.as_str().to_string();
            if m.child_elements().next().is_some() {
                return Err(format!("mask(of=\"{of}\") in {} holds no layer: it names a layer of the stack", place(el)));
            }
            return Ok(Some(MaskOf::Named(of, on, m)));
        }
        let held: Vec<&El> = m.child_elements().collect();
        if held.len() != 1 {
            return Err(format!("mask() in {} holds one layer", place(el)));
        }
        let ids = self.stack(kind, &held, false)?;
        Ok(Some(MaskOf::Held(ids[0].clone(), on, m)))
    }

    /// Wire every `mask(of="…")` to the layer it names: a name must match exactly one layer of the stack.
    fn resolve_masks(&mut self) -> Result<(), String> {
        for (id, of, on, what) in std::mem::take(&mut self.masks) {
            let hits: Vec<String> = self.layers.iter().filter(|(n, _)| *n == of).map(|(_, id)| id.clone()).collect();
            if hits.is_empty() {
                return Err(format!("{what} is masked by \"{of}\", and no layer is named that"));
            }
            if hits.len() > 1 {
                return Err(format!("{what} is masked by \"{of}\", and {} layers are named that", hits.len()));
            }
            self.scope().set_input(&id, "mask", wire(&hits[0], "out"));
            if !on {
                self.scope().set_input(&id, "maskEnabled", Json::Bool(false));
            }
        }
        Ok(())
    }

    /// A painting layer's `fx`: its styles in order (the layer's `fx`), and where each was written.
    fn styles_of(kind: &StackKind, el: &El) -> Result<Option<(Json, Json)>, String> {
        let blocks: Vec<&El> = el.child_elements().filter(|c| c.tag == "fx").collect();
        let Some(block) = blocks.first() else { return Ok(None) };
        if kind.prefix != "paint" {
            return Err(format!("{}: fx() (layer styles) is a painting's", place(el)));
        }
        if blocks.len() > 1 {
            return Err(format!("{} has one fx()", place(el)));
        }
        if !entries(&attrs(block, &[])?).is_empty() {
            return Err(format!("fx() in {} has no attributes (write them on its styles)", place(el)));
        }
        let mut sources = Json::obj();
        if let Some(at) = block.source_json() {
            sources.set("fx", at);
        }
        let mut fx = Vec::new();
        for (i, c) in block.child_elements().enumerate() {
            if !LAYER_STYLES.contains(&c.tag) {
                return Err(format!("{} is not a layer style ({})", tag(c.tag), LAYER_STYLES.join(", ")));
            }
            if c.child_elements().next().is_some() {
                return Err(format!("{} in fx() takes no children", place(c)));
            }
            if let Some(at) = c.source_json() {
                sources.set(&format!("fx.{i}"), at);
            }
            fx.push(spread(Json::obj().with("type", c.tag), entries(&attrs(c, &[])?).to_vec()));
        }
        Ok(Some((Json::Arr(fx), sources)))
    }

    /// Declare `el` as one node of `kind`, masked by its `mask` when it has one, with its `fx` when it has them.
    fn add_masked(&mut self, kind: &StackKind, el: &El, node_type: &str, inputs: Json) -> Result<String, String> {
        let mask = self.mask_of(kind, el)?;
        let styles = Self::styles_of(kind, el)?;
        let mut inputs = match &mask {
            Some(MaskOf::Held(id, on, _)) => {
                let i = inputs.with("mask", wire(id, "out"));
                if *on { i } else { i.with("maskEnabled", false) }
            }
            _ => inputs,
        };
        let mut sources = Json::obj();
        if let Some((fx, at)) = styles {
            inputs.set("fx", fx);
            sources = at;
        }
        let id = self.add(el, node_type, inputs)?;
        if let Some(MaskOf::Named(of, on, _)) = &mask {
            self.masks.push((id.clone(), of.clone(), *on, format!("{}'s mask()", place(el))));
        }
        if let Some(at) = mask.as_ref().and_then(|m| m.el().source_json()) {
            sources.set("mask", at);
        }
        if !entries(&sources).is_empty() {
            self.sources.push((id.clone(), sources));
        }
        Ok(id)
    }

    /// `in_stack`: these children are slots of the stack (a mask's own held layer is not one a `mask(of=…)` may name).
    fn stack(&mut self, kind: &StackKind, children: &[&El], in_stack: bool) -> Result<Vec<String>, String> {
        let mut slots = Vec::new();
        for &el in children {
            let Some((layer_type, inputs)) = (kind.layer)(el)? else {
                if (kind.chains)(el) {
                    return Err(format!("{} is painted on a layer: write it inside one", place(el)));
                }
                return Err(format!("{} is not read in a {} (see commandagi::design::twod)", tag(el.tag), tag(kind.root)));
            };
            let (mut stack, mut chain) = (Vec::new(), Vec::new());
            for c in el.child_elements().filter(|c| c.tag != "mask" && c.tag != "fx") {
                if (kind.chains)(c) { &mut chain } else { &mut stack }.push(c);
            }
            let group = format!("{}.group", kind.prefix);
            if !stack.is_empty() && layer_type != group {
                return Err(format!("{}: only a group() holds layers", place(el)));
            }
            let inner = if layer_type == group { self.stack(kind, &stack, in_stack)? } else { Vec::new() };
            let mut top = self.add_masked(kind, el, &layer_type, spread(inputs.clone(), wires("layers", &inner)))?;
            // Each chain member carries the layer's fields: the stack reads them off whichever member is on top.
            let mut carried = Json::obj().with("name", "Layer").with("visible", true).with("opacity", 1i64).with("blend", "normal");
            for k in COMMON {
                if let Some(v) = inputs.get(k) {
                    carried.set(k, v.clone());
                }
            }
            for c in chain {
                let own = (kind.chain)(c)?;
                let inputs = spread(carried.clone(), entries(&own).to_vec()).with("src", wire(&top, "out"));
                top = self.add_masked(kind, c, &(kind.chain_type)(c), inputs)?;
            }
            if in_stack {
                if let Some(Json::Str(name)) = inputs.get("name") {
                    self.layers.push((name.as_str().to_string(), top.clone()));
                }
            }
            slots.push(top);
        }
        Ok(slots)
    }

    fn stack_document(&mut self, kind: &StackKind, root: &El) -> Result<Json, String> {
        let a = attrs(root, &[])?;
        if let Some((k, _)) = entries(&a).iter().find(|(k, _)| !["name", "width", "height", "background", "dpi"].contains(&k.as_str())) {
            return Err(format!("{}: {} is not read (it has name, width, height, background, dpi)", tag(kind.root), rust_name(k)));
        }
        let title = a.get("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(unnamed);
        self.s = Some(Scope::new(&format!("{}:{}", kind.prefix, slug(&title)), Json::obj().with("domain", kind.prefix).with("name", title)));
        let kids: Vec<&El> = root.child_elements().collect();
        let layers = self.stack(kind, &kids, true)?;
        self.resolve_masks()?;
        let Json::Obj(inputs) = spread(a, wires("layers", &layers)) else { unreachable!() };
        let doc = self.scope().add(&format!("{}.doc", kind.prefix), inputs, Some("doc"), None, meta(root))?;
        Ok(self.build(&doc))
    }

    // ── Nest ───────────────────────────────────────────────────────────────────────────────────────────────────

    fn nest(&mut self, root: &El) -> Result<Json, String> {
        const ONE: &[&str] = &["sheet", "stock", "options"];
        let a = attrs(root, &["name"])?;
        if let Some((k, _)) = entries(&a).iter().find(|(k, _)| !["safeZMm", "overrides"].contains(&k.as_str())) {
            return Err(format!("nest(): {} is not read (it has safe_z_mm, overrides)", rust_name(k)));
        }
        let title = root.attr_of("name").and_then(Json::as_str).map(str::to_string).unwrap_or_else(unnamed);
        self.s = Some(Scope::new(&format!("nest:{}", slug(&title)), Json::obj().with("domain", "nest").with("name", title)));
        let mut one: Vec<(String, Json)> = Vec::new();
        let mut parts = Vec::new();
        let mut engraves = Vec::new();
        for el in root.child_elements() {
            if ONE.contains(&el.tag) {
                if one.iter().any(|(k, _)| k == el.tag) {
                    return Err(format!("a nest has one {}", tag(el.tag)));
                }
                let id = self.add(el, &format!("nest.{}", el.tag), attrs(el, &[])?)?;
                one.push((el.tag.to_string(), wire(&id, "out")));
            } else if el.tag == "part" {
                if el.attr_of("id").and_then(Json::as_str).is_none() {
                    return Err(format!("{}: a part has an id (the name its placements and overrides use)", place(el)));
                }
                parts.push(self.add(el, "nest.part", attrs(el, &[])?)?);
            } else if el.tag == "engrave" {
                if el.attr_of("id").and_then(Json::as_str).is_none() {
                    return Err(format!("{}: an engrave has an id (the name the nest's code uses)", place(el)));
                }
                engraves.push(self.add(el, "nest.engrave", attrs(el, &[])?)?);
            } else {
                return Err(format!("{} is not read in a nest (it has sheet(), stock(), options(), part(), engrave())", tag(el.tag)));
            }
        }
        if let Some(k) = ONE.iter().find(|k| !one.iter().any(|(t, _)| t == *k)) {
            return Err(format!("a nest needs its {}", tag(k)));
        }
        let Json::Obj(inputs) = spread(spread(spread(a, one), wires("parts", &parts)), wires("engraves", &engraves)) else { unreachable!() };
        let doc = self.scope().add("nest.doc", inputs, Some("nest"), None, meta(root))?;
        Ok(self.build(&doc))
    }
}