@aestheticfunction/dspack-emit 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -4,7 +4,7 @@ import { collectChildren } from "../csr.js";
4
4
  import { Band, Diagnostics, Phase } from "./diagnostics.js";
5
5
  import { surfaceModelOf } from "../../transform/desugar.js";
6
6
  import { validateProfileAgainstContract } from "../../transform/validate-v2.js";
7
- import { describeSelector, isCollect, WriteOrder } from "../../transform/model.js";
7
+ import { describeSelector, emptySurfaceModel, isCollect, WriteOrder } from "../../transform/model.js";
8
8
  export class EmitSurfaceError extends Error {
9
9
  path;
10
10
  constructor(message, path) {
@@ -30,8 +30,17 @@ export function emitSurface(surface, doc, options = {}) {
30
30
  if (plan.dspackId)
31
31
  byDspackId.set(plan.dspackId, plan);
32
32
  }
33
+ // T1: a transparent ROOT still needs an instance renderers can start from
34
+ // (components[0], id "root"). The established arity discipline answers it:
35
+ // the root dissolves and its risen children wrap in the profile's
36
+ // synthesized wrap component, which becomes the root — synthesis, recorded,
37
+ // never silent. (ex.expense-report-form roots at `form` directly; refusing
38
+ // transparent roots would refuse the exact failure T1 exists to fix.)
33
39
  const emitter = new SurfaceEmitter(profile, byDspackId);
34
- const rootId = emitter.emitNode(surface.root, "$.root");
40
+ const rootPlan = byDspackId.get(surface.root.component);
41
+ const rootId = rootPlan && surfaceModelOf(rootPlan).transparent
42
+ ? emitter.emitTransparentRoot(surface.root, "$.root")
43
+ : emitter.emitNode(surface.root, "$.root");
35
44
  const surfaceId = options.surfaceId ?? slug(surface.intent);
36
45
  const theme = { agentDisplayName: `${doc.name} via dspack` };
37
46
  const primaryHex = primaryColor(doc, profile);
@@ -83,7 +92,7 @@ class SurfaceEmitter {
83
92
  * desugar.ts; if any of them appears below, the compatibility boundary has
84
93
  * leaked (src/engine-boundary.test.ts fails on exactly that).
85
94
  */
86
- emitNode(node, path, treePath = []) {
95
+ emitNode(node, path, treePath = [], donations = []) {
87
96
  const plan = this.byDspackId.get(node.component);
88
97
  if (!plan) {
89
98
  // A declared casualty refuses with its authored reason — the refusal is
@@ -120,6 +129,23 @@ class SurfaceEmitter {
120
129
  // (except where a route declares `overwrite`); ordering of DIAGNOSTICS is
121
130
  // the explicit phase model, never this loop's order.
122
131
  this.applyOperations(node, model, instance, id, path, treePath);
132
+ // T1 donations: contextual values a dissolved wrapper handed to this
133
+ // control, applied AFTER the control's own writes, first-wins — inherited
134
+ // context fills what the control left absent and never beats its own
135
+ // authored content. The ledger records exactly what happened either way.
136
+ for (const d of donations) {
137
+ const landed = this.write(instance, d.prop, d.value);
138
+ this.diagnostics.pushFidelity({
139
+ source: `${d.donorPath} (${d.donorComponent}.text)`,
140
+ destination: `${d.prop} @ ${path} (${node.component})`,
141
+ origin: d.origin,
142
+ kind: landed ? "donated" : "dropped",
143
+ class: landed ? "maps-cleanly" : "lossy",
144
+ note: landed
145
+ ? `donated by '${d.donorComponent}' to '${node.component}' — the dissolving boundary's single eligible control`
146
+ : `'${d.prop}' already written on '${node.component}'; the donated value did not land`,
147
+ }, treePath, Band.BeforeChildren, Phase.PropMap);
148
+ }
123
149
  if (!model.consumesSubtree) {
124
150
  this.emitChildren(node, model, instance, id, path, treePath);
125
151
  }
@@ -161,6 +187,10 @@ class SurfaceEmitter {
161
187
  for (const { route, rule } of model.routes.map((route, rule) => ({ route, rule }))) {
162
188
  if (route.order === WriteOrder.Consume || route.order === WriteOrder.Children)
163
189
  continue;
190
+ if (route.order === WriteOrder.Slot) {
191
+ steps.push({ order: route.order, run: () => this.applySlotRoute(node, model, route, rule, instance, path, treePath) });
192
+ continue;
193
+ }
164
194
  steps.push({ order: route.order, run: () => this.applyRoute(node, route, rule, instance, id, path, treePath) });
165
195
  }
166
196
  for (const [rule, collect] of model.collects.entries()) {
@@ -174,6 +204,9 @@ class SurfaceEmitter {
174
204
  if (model.collects.some((c) => c.as.kind !== "inline")) {
175
205
  steps.push({ order: WriteOrder.Collect + 1, run: () => this.closeCollects(node, model, path, treePath) });
176
206
  }
207
+ if (model.routes.some((r) => r.order === WriteOrder.Slot)) {
208
+ steps.push({ order: WriteOrder.Slot + 1, run: () => this.closeSlots(node, model, path, treePath) });
209
+ }
177
210
  steps.sort((a, b) => a.order - b.order);
178
211
  for (const step of steps)
179
212
  step.run();
@@ -476,6 +509,128 @@ class SurfaceEmitter {
476
509
  void model;
477
510
  if (collect.as.kind === "inline")
478
511
  return;
512
+ // T2 item-mode: each descendant matching `of` (document order) becomes
513
+ // one record whose fields resolve against THAT item's own node. Absent
514
+ // sources omit the field — gate A3 arbitrates required record shapes,
515
+ // never synthesis. Sibling content the collect does not claim follows
516
+ // the ordinary consumed-subtree accounting (closeCollects).
517
+ if (collect.fields) {
518
+ const itemLocal = (n, sel) => sel.kind === "self-text" ? n.text : sel.kind === "self-id" ? n.id : sel.kind === "self-prop" ? n.props?.[sel.prop] : undefined;
519
+ // Gather left items and (when a join is declared) joined counterparts,
520
+ // both in document order.
521
+ const lefts = [];
522
+ const rights = [];
523
+ const gather = (n, nPath) => {
524
+ if (collect.of.includes(n.component)) {
525
+ lefts.push({ n, nPath });
526
+ return; // an item's subtree is the item's; nested items do not re-match
527
+ }
528
+ if (collect.join?.with.includes(n.component)) {
529
+ rights.push({ n, nPath });
530
+ return;
531
+ }
532
+ collectChildren(n).forEach((c, i) => gather(c.node, `${nPath}${c.suffix}[${i}]`));
533
+ };
534
+ collectChildren(node).forEach((c, i) => gather(c.node, `${path}${c.suffix}[${i}]`));
535
+ // T3: the declared key join. Every edge refuses — the profile names
536
+ // the relation, the emitter never infers one.
537
+ const counterparts = new Map();
538
+ if (collect.join) {
539
+ const j = collect.join;
540
+ const seenLeft = new Map();
541
+ for (const item of lefts) {
542
+ const key = itemLocal(item.n, j.leftKey);
543
+ if (typeof key !== "string" || key === "") {
544
+ throw new EmitSurfaceError(`join '${j.origin}': item '${item.n.component}' carries no key (${describeSelector(j.leftKey)}); a keyless item cannot participate in a declared join`, item.nPath);
545
+ }
546
+ const prior = seenLeft.get(key);
547
+ if (prior !== undefined) {
548
+ throw new EmitSurfaceError(`join '${j.origin}': duplicate left key '${key}' (also at ${prior}); join keys must be unique on each side`, item.nPath);
549
+ }
550
+ seenLeft.set(key, item.nPath);
551
+ }
552
+ for (const cp of rights) {
553
+ const key = itemLocal(cp.n, j.rightKey);
554
+ if (typeof key !== "string" || key === "") {
555
+ throw new EmitSurfaceError(`join '${j.origin}': counterpart '${cp.n.component}' carries no key (${describeSelector(j.rightKey)})`, cp.nPath);
556
+ }
557
+ if (counterparts.has(key)) {
558
+ throw new EmitSurfaceError(`join '${j.origin}': duplicate right key '${key}'; join keys must be unique on each side`, cp.nPath);
559
+ }
560
+ if (!seenLeft.has(key)) {
561
+ throw new EmitSurfaceError(`join '${j.origin}': counterpart '${cp.n.component}' key '${key}' matches no item; a dangling counterpart is a contradiction, not surplus`, cp.nPath);
562
+ }
563
+ counterparts.set(key, cp);
564
+ }
565
+ }
566
+ const records = [];
567
+ for (const item of lefts) {
568
+ const record = {};
569
+ for (const [fieldName, sel] of Object.entries(collect.fields)) {
570
+ const value = itemLocal(item.n, sel);
571
+ if (value !== undefined)
572
+ record[fieldName] = value;
573
+ }
574
+ this.diagnostics.pushFidelity({
575
+ source: `${item.nPath} (${item.n.component})`,
576
+ destination: collect.as.name,
577
+ origin: collect.origin,
578
+ kind: "moved",
579
+ class: "maps-cleanly",
580
+ note: `item record { ${Object.keys(record).join(", ")} } collected`,
581
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
582
+ if (collect.join) {
583
+ const j = collect.join;
584
+ const key = itemLocal(item.n, j.leftKey);
585
+ const cp = counterparts.get(key);
586
+ if (!cp && !j.optional) {
587
+ throw new EmitSurfaceError(`join '${j.origin}': item '${item.n.component}' key '${key}' has no counterpart among [${j.with.join(", ")}]; exactly one is required (declare optional to relax to 0..1)`, item.nPath);
588
+ }
589
+ if (cp) {
590
+ for (const [fieldName, jSel] of Object.entries(j.fields)) {
591
+ if ("kind" in jSel && jSel.kind === "joined-children") {
592
+ // The slot-valued field: the counterpart's children emit as
593
+ // instances; the record carries the reference. Repetition's
594
+ // ratified slot form — not T4 multi-slot routing. The child
595
+ // list goes through the SAME rewriting as any parent's
596
+ // (mirroring the transparent-root host pattern), so a
597
+ // transparent top-level child inside a joined panel
598
+ // dissolves instead of refusing as an unroutable instance.
599
+ const spliced = this.rewriteChildren(cp.n, emptySurfaceModel(), cp.nPath, treePath);
600
+ if (spliced.length === 0)
601
+ continue;
602
+ const ids = spliced.map((k, ki) => "textVariant" in k
603
+ ? this.emitTextPrimitive(k.text, `${slug(key)}_${slug(k.textVariant)}`, cp.nPath, [...treePath, Band.Children, records.length, ki], Phase.TextChild, 0, k.textVariant)
604
+ : this.emitNode(k.node, `${cp.nPath}${k.suffix}[${ki}]`, [...treePath, Band.Children, records.length], k.donations ?? []));
605
+ record[fieldName] =
606
+ ids.length === 1 ? ids[0] : this.wrapInColumn(ids, `${slug(key)}`, cp.nPath, treePath);
607
+ }
608
+ else {
609
+ const value = itemLocal(cp.n, jSel);
610
+ if (value !== undefined)
611
+ record[fieldName] = value;
612
+ }
613
+ }
614
+ this.diagnostics.pushFidelity({
615
+ source: `${cp.nPath} (${cp.n.component})`,
616
+ destination: `${collect.as.name} @ item '${key}'`,
617
+ origin: j.origin,
618
+ kind: "joined",
619
+ class: "maps-cleanly",
620
+ note: `counterpart joined on key '${key}' -> fields { ${Object.keys(j.fields).join(", ")} }`,
621
+ }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
622
+ }
623
+ }
624
+ records.push(record);
625
+ }
626
+ if (records.length > 0) {
627
+ const landed = this.write(instance, collect.as.name, records);
628
+ if (!landed) {
629
+ this.diagnostics.pushFidelity({ source: `${path} (${collect.of.join("|")} items)`, destination: "(discarded)", origin: collect.origin, kind: "dropped", class: "lossy", note: `'${collect.as.name}' was already written by an earlier phase; the collected records did not land` }, treePath, Band.BeforeChildren, Phase.TableBody, rule);
630
+ }
631
+ }
632
+ return;
633
+ }
479
634
  const out = [];
480
635
  const flat = [];
481
636
  const scalarField = Object.values(collect.item ?? {}).find((f) => isCollect(f) && f.scalar);
@@ -529,19 +684,116 @@ class SurfaceEmitter {
529
684
  * is either an explicit drop or an unrecognized sub — both warned, never
530
685
  * silently ignored — followed by the composition casualty for the compound.
531
686
  */
687
+ /**
688
+ * T4: one slot route — the ordered children of exactly one descendant
689
+ * instance of the named sub become instances, and the slot carries the
690
+ * reference (multi wraps in the profile's wrap component, exactly like
691
+ * T3's joined-children). The region's child list goes through the SAME
692
+ * rewriting as any parent's (this plan's dispositions apply to nested
693
+ * subs), with subs claimed by sibling routes skipped — their consumption
694
+ * is their own route's ledger entry. Zero regions leave the destination
695
+ * absent (gate A3 arbitrates); several refuse: a slot names one region.
696
+ */
697
+ applySlotRoute(node, model, route, rule, instance, path, treePath) {
698
+ const sel = route.from[0];
699
+ if (sel.kind !== "sub-children")
700
+ return;
701
+ const region = sel.subs[0];
702
+ const found = [];
703
+ const locate = (n, nPath) => {
704
+ for (const c of collectChildren(n)) {
705
+ if (c.node.component === region)
706
+ found.push({ n: c.node, nPath: `${nPath}${c.suffix}` });
707
+ locate(c.node, `${nPath}${c.suffix}`);
708
+ }
709
+ };
710
+ locate(node, path);
711
+ if (found.length === 0)
712
+ return; // absent region: the destination stays absent and A3 arbitrates
713
+ if (found.length > 1) {
714
+ throw new EmitSurfaceError(`slot route '${route.origin}': ${found.length} instances of '${region}' in this '${node.component}'; ` +
715
+ `a slot names ONE region — exactly one may appear`, path);
716
+ }
717
+ const claimed = new Set();
718
+ for (const r of model.routes) {
719
+ if (r === route)
720
+ continue;
721
+ for (const s of r.from)
722
+ if ("subs" in s)
723
+ for (const id of s.subs)
724
+ claimed.add(id);
725
+ }
726
+ for (const c of model.collects)
727
+ for (const id of [...c.of, ...(c.join?.with ?? [])])
728
+ claimed.add(id);
729
+ const src = found[0];
730
+ const spliced = this.rewriteChildren(src.n, model, src.nPath, treePath, claimed);
731
+ if (spliced.length === 0)
732
+ return; // an empty region carries nothing; absent, A3 arbitrates
733
+ const ids = spliced.map((k, ki) => "textVariant" in k
734
+ ? this.emitTextPrimitive(k.text, `${slug(region)}_${slug(k.textVariant)}`, src.nPath, [...treePath, Band.BeforeChildren, rule, ki], Phase.SubContentFlatten, rule, k.textVariant)
735
+ : this.emitNode(k.node, `${src.nPath}${k.suffix}[${ki}]`, [...treePath, Band.BeforeChildren, rule, ki], k.donations ?? []));
736
+ const ref = ids.length === 1 ? ids[0] : this.wrapInColumn(ids, slug(region), src.nPath, treePath);
737
+ const landed = this.write(instance, route.to.name, ref);
738
+ this.diagnostics.pushFidelity({
739
+ source: `${src.nPath} (${region} children)`,
740
+ destination: `${route.to.name} @ ${path} (${node.component})`,
741
+ origin: route.origin,
742
+ kind: landed ? "moved" : "dropped",
743
+ class: landed ? "maps-cleanly" : "lossy",
744
+ note: landed
745
+ ? `region '${region}' emitted as instances; the slot carries the reference`
746
+ : `'${route.to.name}' already written; the region's reference did not land`,
747
+ }, treePath, Band.BeforeChildren, Phase.SubContentFlatten, rule);
748
+ }
749
+ /**
750
+ * Fail-closed closure for a slot-routed compound: every DIRECT child must
751
+ * be a claimed region, a route-consumed sub, a collected family, or carry
752
+ * a disposition — an unclaimed child is structural content with no
753
+ * destination, and approximating it silently is exactly what this engine
754
+ * refuses to do.
755
+ */
756
+ closeSlots(node, model, path, treePath) {
757
+ const claimed = new Set();
758
+ for (const r of model.routes)
759
+ for (const s of r.from)
760
+ if ("subs" in s)
761
+ for (const id of s.subs)
762
+ claimed.add(id);
763
+ for (const c of model.collects)
764
+ for (const id of [...c.of, ...(c.join?.with ?? [])])
765
+ claimed.add(id);
766
+ for (const child of collectChildren(node)) {
767
+ const c = child.node.component;
768
+ if (claimed.has(c) || c in model.subIdentity)
769
+ continue;
770
+ const reason = model.drops[c];
771
+ if (reason !== undefined) {
772
+ const childPath = `${path}${child.suffix}`;
773
+ this.diagnostics.push({ code: "surface-sub-dropped", message: `${childPath}: '${c}' dropped: ${reason}.` }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
774
+ this.diagnostics.pushFidelity({ source: `${childPath} (${c})`, destination: "(discarded)", origin: `drops.${c}`, kind: "dropped", class: "lossy", note: reason }, treePath, Band.BeforeChildren, Phase.SubContentFlatten);
775
+ continue;
776
+ }
777
+ throw new EmitSurfaceError(`'${c}' is a direct child of slot-routed compound '${node.component}' with no destination — ` +
778
+ `every region must be claimed by a route, collected, or carry a disposition`, `${path}${child.suffix}`);
779
+ }
780
+ }
532
781
  closeCollects(node, model, path, treePath) {
533
- const claimedByCollect = new Set(model.collects.flatMap((c) => c.of));
782
+ const claimedByCollect = new Set(model.collects.flatMap((c) => [...c.of, ...(c.join?.with ?? [])]));
534
783
  for (const child of collectChildren(node)) {
535
784
  const c = child.node.component;
536
785
  if (claimedByCollect.has(c) || this.claimedByRoute(model, c))
537
786
  continue;
538
787
  const childPath = `${path}${child.suffix}`;
539
788
  const reason = model.drops[c];
789
+ const itemMode = model.collects.some((col) => col.fields);
540
790
  this.diagnostics.push({
541
791
  code: "surface-sub-dropped",
542
792
  message: reason
543
793
  ? `${childPath}: '${c}' dropped: ${reason}.`
544
- : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
794
+ : itemMode
795
+ ? `${childPath}: '${c}' is not a collected item and has no disposition; dropped (sibling pairing is T3's declared join).`
796
+ : `${childPath}: '${c}' has no slot in the synthesized table shape; dropped.`,
545
797
  }, treePath, Band.BeforeChildren, Phase.TableBody);
546
798
  this.diagnostics.pushFidelity({
547
799
  source: `${childPath} (${c})`,
@@ -552,9 +804,12 @@ class SurfaceEmitter {
552
804
  note: reason ?? "no slot in the collected shape",
553
805
  }, treePath, Band.BeforeChildren, Phase.TableBody);
554
806
  }
807
+ const itemsOnly = model.collects.every((col) => col.fields);
555
808
  this.diagnostics.push({
556
809
  code: "surface-composition-flattened",
557
- message: `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
810
+ message: itemsOnly
811
+ ? `${path}: compound '${node.component}' subtree consumed into collected item records (uncollected content is not carried).`
812
+ : `${path}: compound '${node.component}' subtree consumed into the synthesized table shape (documented casualty; cell content beyond text is not carried).`,
558
813
  }, treePath, Band.BeforeChildren, Phase.TableFlatten);
559
814
  this.diagnostics.pushFidelity({
560
815
  source: `${path} (${node.component} subtree)`,
@@ -608,14 +863,19 @@ class SurfaceEmitter {
608
863
  /** Children as instance references, after any sub-identity rewriting. */
609
864
  emitChildren(node, model, instance, id, path, treePath) {
610
865
  const childRoute = model.routes.find((r) => r.from.some((s) => s.kind === "children"));
611
- const childNodes = Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0
866
+ const raw = collectChildren(node);
867
+ const anyTransparentChild = raw.some((c) => {
868
+ const plan = this.byDspackId.get(c.node.component);
869
+ return plan !== undefined && surfaceModelOf(plan).transparent;
870
+ });
871
+ const childNodes = Object.keys(model.subIdentity).length > 0 || Object.keys(model.drops).length > 0 || anyTransparentChild
612
872
  ? this.rewriteChildren(node, model, path, treePath)
613
- : collectChildren(node).map((c) => ({ node: c.node, suffix: c.suffix }));
873
+ : raw.map((c) => ({ node: c.node, suffix: c.suffix }));
614
874
  if (childNodes.length === 0)
615
875
  return;
616
876
  const childIds = childNodes.map((child, i) => "textVariant" in child
617
877
  ? this.emitTextPrimitive(child.text, `${id}_${slug(child.textVariant)}`, path, [...treePath, Band.Children, i], Phase.TextChild, 0, child.textVariant)
618
- : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i]));
878
+ : this.emitNode(child.node, `${path}${child.suffix}[${i}]`, [...treePath, Band.Children, i], child.donations ?? []));
619
879
  if (!childRoute) {
620
880
  throw new EmitSurfaceError(`component '${node.component}' has children but its surface plan declares no child slot`, path);
621
881
  }
@@ -628,33 +888,136 @@ class SurfaceEmitter {
628
888
  }
629
889
  }
630
890
  /**
631
- * Identity applied to named sub-components met in this node's child list:
632
- * `transparent` dissolves (its children rise in document order, recursively),
633
- * `as-text` becomes the profile's text primitive carrying its subtree text.
891
+ * T1, the general root-transparency rule (ratified): a transparent node is
892
+ * a semantic statement that the dspack node has no emitted identity — valid
893
+ * at the root too. The root dissolves through the ORDINARY machinery
894
+ * (presented as a child of a synthetic host, so boundary donations, sub
895
+ * dispositions, and every refusal apply), then:
896
+ *
897
+ * - exactly one surviving descendant -> it IS the root (id "root",
898
+ * components[0]) — the existing root invariant, preserved
899
+ * deterministically;
900
+ * - several survivors -> they wrap in the synthesized
901
+ * wrap component, which is structural TRANSPORT, not a replacement
902
+ * identity for the transparent component;
903
+ * - nothing survives -> refuse. Fabricating content for
904
+ * an empty root would be synthesis of meaning, not structure.
905
+ *
906
+ * No component is special-cased by name.
634
907
  */
635
- rewriteChildren(node, model, path, treePath) {
636
- const out = [];
637
- const visit = (n, suffix) => {
638
- // An authored drop is warn-and-discard, exactly like the collect path:
639
- // the sub is skipped with its reason on record, never emitted and never
640
- // crashed into the unknown-component refusal.
641
- const dropReason = model.drops[n.component];
908
+ emitTransparentRoot(root, path) {
909
+ const { wrapComponent, wrapChildrenProp } = this.profile.surfaceSynthesis;
910
+ // Present the root AS A CHILD of a synthetic host, so the ordinary
911
+ // rewriting machinery performs the whole dissolution — the plan-transparent
912
+ // ledger entry, the boundary's own donations (transparentDonate), sub
913
+ // dispositions, and every refusal — with no root-only special case.
914
+ const host = { component: "__root_host__", children: [root] };
915
+ const spliced = this.rewriteChildren(host, emptySurfaceModel(), path, []);
916
+ if (spliced.length === 0) {
917
+ throw new EmitSurfaceError(`transparent root '${root.component}' dissolved to nothing — no descendant survives to become the root, and fabricating one is refused`, path);
918
+ }
919
+ if (spliced.length === 1) {
920
+ const only = spliced[0];
921
+ this.diagnostics.pushFidelity({
922
+ source: `${path} (${root.component})`,
923
+ destination: "root",
924
+ origin: `plan.${root.component}`,
925
+ kind: "moved",
926
+ class: "maps-cleanly",
927
+ note: "transparent root: its single surviving descendant is preserved as the root instance",
928
+ }, [], Band.BeforeChildren, Phase.ChildRewrite);
929
+ return "textVariant" in only
930
+ ? this.emitTextPrimitive(only.text, "root", path, [Band.Children, 0], Phase.TextChild, 0, only.textVariant)
931
+ : this.emitNode(only.node, path, [Band.Children, 0], only.donations ?? []);
932
+ }
933
+ const id = this.allocateId("root", path, { treePath: [], band: Band.BeforeChildren, phase: Phase.IdAllocation, rule: 0 });
934
+ const index = this.components.length;
935
+ this.components.push({});
936
+ const childIds = spliced.map((child, i) => "textVariant" in child
937
+ ? this.emitTextPrimitive(child.text, `root_${slug(child.textVariant)}`, path, [Band.Children, i], Phase.TextChild, 0, child.textVariant)
938
+ : this.emitNode(child.node, `${path}.children[${i}]`, [Band.Children, i], child.donations ?? []));
939
+ this.components[index] = { id, component: wrapComponent, [wrapChildrenProp]: childIds };
940
+ this.diagnostics.push({
941
+ code: "surface-synthesized-wrap",
942
+ message: `${path}: transparent root '${root.component}' dissolved; ${childIds.length} risen child(ren) wrapped in a synthesized ${wrapComponent} ('root').`,
943
+ }, [], Band.AfterChildren, Phase.Wrap);
944
+ this.diagnostics.pushFidelity({ source: `${path} (${childIds.length} risen children)`, destination: `synthesized ${wrapComponent} 'root'`, origin: "surfaceSynthesis.wrapComponent", kind: "wrapped", class: "synthesis-defaults", note: "structural transport for several risen children — not a replacement identity for the transparent root" }, [], Band.AfterChildren, Phase.Wrap);
945
+ return id;
946
+ }
947
+ /**
948
+ * Identity applied to the child list: sub dispositions from the surrounding
949
+ * model, T1 plan-level transparency for child COMPONENTS (dissolved under
950
+ * their own model — the `ctx` switch), and donation boundaries. A
951
+ * dissolving boundary that carries donations harvests them from its own
952
+ * subtree, consumes the donor subs, and attaches the pending writes to its
953
+ * single eligible control — refusing on zero or several candidates. The
954
+ * pending writes ride the returned child list explicitly and apply inside
955
+ * the control's own construction: no committed instance is ever mutated.
956
+ */
957
+ rewriteChildren(node, model, path, treePath,
958
+ /**
959
+ * T4: subs claimed by SIBLING routes of the enclosing compound (text
960
+ * harvests, other slot sources). A claimed sub is skipped silently at any
961
+ * dissolution depth — its consumption is ledgered by its own route, and
962
+ * recording it twice would say it was dropped when it was moved.
963
+ */
964
+ claimedSubs = new Set()) {
965
+ const push = (w) => this.diagnostics.push(w, treePath, Band.BeforeChildren, Phase.ChildRewrite);
966
+ const ledger = (f) => this.diagnostics.pushFidelity(f, treePath, Band.BeforeChildren, Phase.ChildRewrite);
967
+ // Layered dissolution contexts (emit#37, ratified 2026-08-07). A
968
+ // dissolving boundary shadows the enclosing compound contexts where they
969
+ // overlap, but does not erase them: a component's disposition is resolved
970
+ // against the stack of enclosing models, innermost first, so an outer
971
+ // compound's sub (e.g. `card-footer`) keeps its disposition when it
972
+ // appears inside a dissolved inner boundary (e.g. a transparent `field`).
973
+ // A single-frame stack resolves identically to the pre-amendment single
974
+ // `ctx` — the byte pins prove it.
975
+ const resolve = (stack, pick) => {
976
+ for (const m of stack) {
977
+ const v = pick(m);
978
+ if (v !== undefined)
979
+ return v;
980
+ }
981
+ return undefined;
982
+ };
983
+ const visit = (n, suffix, stack, out) => {
984
+ if (claimedSubs.has(n.component))
985
+ return;
986
+ // An authored drop is warn-and-discard, exactly like the collect path —
987
+ // resolved through the ancestor chain (inner shadows outer).
988
+ const dropReason = resolve(stack, (m) => m.drops[n.component]);
642
989
  if (dropReason !== undefined) {
643
- this.diagnostics.push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
644
- this.diagnostics.pushFidelity({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
990
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' dropped: ${dropReason}.` });
991
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `drops.${n.component}`, kind: "dropped", class: "lossy", note: dropReason });
645
992
  return;
646
993
  }
647
- const identity = model.subIdentity[n.component];
994
+ // T1: a child COMPONENT whose plan is transparent dissolves here — its
995
+ // subtree governed by ITS OWN model PUSHED ONTO the enclosing stack, so
996
+ // the boundary shadows but does not erase the outer contexts.
997
+ const childPlan = this.byDspackId.get(n.component);
998
+ const childModel = childPlan ? surfaceModelOf(childPlan) : undefined;
999
+ if (childModel?.transparent) {
1000
+ ledger({
1001
+ source: `${path} (${n.component})`,
1002
+ destination: "(children rise in place)",
1003
+ origin: `plan.${n.component}`,
1004
+ kind: "flattened",
1005
+ class: "lossy",
1006
+ note: "transparent identity: the component dissolves; its own structure is not carried",
1007
+ });
1008
+ dissolve(n, suffix, [childModel, ...stack], childModel.transparentDonate, `plan.${n.component}`, out);
1009
+ return;
1010
+ }
1011
+ const identity = resolve(stack, (m) => m.subIdentity[n.component]);
648
1012
  if (identity?.kind === "transparent") {
649
- this.diagnostics.push({
1013
+ push({
650
1014
  code: "surface-sub-flattened",
651
1015
  message: `${path}: grouping sub-component '${n.component}' spliced inline (subFlatten strategy); its own structure is not carried.`,
652
- }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
653
- this.diagnostics.pushFidelity({ source: `${path} (${n.component})`, destination: "(children rise in place)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "transparent grouping dissolved; its own structure is not carried" }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
654
- if (n.text !== undefined && n.text !== "")
655
- out.push({ text: n.text, textVariant: "body" });
656
- for (const child of collectChildren(n))
657
- visit(child.node, child.suffix);
1016
+ });
1017
+ ledger({ source: `${path} (${n.component})`, destination: "(children rise in place)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "transparent grouping dissolved; its own structure is not carried" });
1018
+ // A grouping sub has no model of its own; its children continue under
1019
+ // the same enclosing stack that resolved it.
1020
+ dissolve(n, suffix, stack, identity.donate ?? [], `subs.${n.component}`, out);
658
1021
  return;
659
1022
  }
660
1023
  if (identity?.kind === "as-text") {
@@ -664,22 +1027,99 @@ class SurfaceEmitter {
664
1027
  // Structure destroyed, text preserved — the same loss the cell
665
1028
  // flatten records, and it must class the same way.
666
1029
  const names = nested.map((c) => `'${c.node.component}'`).join(", ");
667
- this.diagnostics.pushFidelity({ source: `${path} (${n.component} containing ${names})`, destination: "(subtree text)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "re-identified as text; nested component structure and props are not carried" }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1030
+ ledger({ source: `${path} (${n.component} containing ${names})`, destination: "(subtree text)", origin: `subs.${n.component}`, kind: "flattened", class: "lossy", note: "re-identified as text; nested component structure and props are not carried" });
668
1031
  }
669
1032
  if (text !== "") {
670
1033
  out.push({ text, textVariant: identity.variant });
671
1034
  }
672
1035
  else {
673
- this.diagnostics.push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
674
- this.diagnostics.pushFidelity({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" }, treePath, Band.BeforeChildren, Phase.ChildRewrite);
1036
+ push({ code: "surface-sub-dropped", message: `${path}: '${n.component}' carried no text to synthesize; dropped.` });
1037
+ ledger({ source: `${path} (${n.component})`, destination: "(discarded)", origin: `subs.${n.component}`, kind: "dropped", class: "lossy", note: "re-identified as text but carried none" });
675
1038
  }
676
1039
  return;
677
1040
  }
678
1041
  out.push({ node: n, suffix });
679
1042
  };
1043
+ /**
1044
+ * Dissolves one boundary node under `innerCtx`. When the boundary carries
1045
+ * donations: harvest first-wins per donation, consume every donor sub,
1046
+ * splice the rest, then bind the pending writes to the single eligible
1047
+ * control among the spliced replacements — zero or several refuse.
1048
+ * Eligibility is declared, never guessed: a control's plan must declare
1049
+ * every donated destination.
1050
+ */
1051
+ const dissolve = (n, suffix, innerStack, donations, originLabel, out) => {
1052
+ const consumedDonorSubs = new Set();
1053
+ const pending = [];
1054
+ for (const d of donations) {
1055
+ let value;
1056
+ let donorComponent = n.component;
1057
+ if (d.from.kind === "self-text") {
1058
+ value = n.text;
1059
+ }
1060
+ else if (d.from.kind === "sub-text") {
1061
+ for (const sub of d.from.subs)
1062
+ consumedDonorSubs.add(sub);
1063
+ const walk = (m) => {
1064
+ if (value === undefined && d.from.kind === "sub-text" && d.from.subs.includes(m.component) && m.text !== undefined) {
1065
+ value = m.text;
1066
+ donorComponent = m.component;
1067
+ }
1068
+ for (const c of collectChildren(m))
1069
+ walk(c.node);
1070
+ };
1071
+ walk(n);
1072
+ }
1073
+ if (value !== undefined) {
1074
+ pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
1075
+ }
1076
+ // Nothing to donate is not an error: the destination stays absent and
1077
+ // gate A3 arbitrates — relocation, never synthesis (the lift rule).
1078
+ }
1079
+ // The boundary's own text rises as body text unless a self.text
1080
+ // donation claimed it (the plain transparent-sub behaviour otherwise).
1081
+ const selfDonated = donations.some((d) => d.from.kind === "self-text");
1082
+ const spliced = [];
1083
+ if (!selfDonated && n.text !== undefined && n.text !== "")
1084
+ spliced.push({ text: n.text, textVariant: "body" });
1085
+ for (const child of collectChildren(n)) {
1086
+ if (consumedDonorSubs.has(child.node.component)) {
1087
+ const supplied = pending.some((q) => q.donorComponent === child.node.component && q.value === child.node.text);
1088
+ if (!supplied) {
1089
+ push({ code: "surface-sub-dropped", message: `${path}: '${child.node.component}' dropped: its text was not the donated value (first donor wins).` });
1090
+ ledger({ source: `${path}${child.suffix} (${child.node.component})`, destination: "(discarded)", origin: originLabel, kind: "dropped", class: "lossy", note: "surplus donor: the donation was already supplied (first donor wins)" });
1091
+ }
1092
+ continue;
1093
+ }
1094
+ visit(child.node, child.suffix, innerStack, spliced);
1095
+ }
1096
+ if (pending.length > 0) {
1097
+ const controls = spliced.filter((entry) => {
1098
+ if (!("node" in entry))
1099
+ return false;
1100
+ const plan = this.byDspackId.get(entry.node.component);
1101
+ if (!plan || surfaceModelOf(plan).transparent)
1102
+ return false;
1103
+ const declared = new Set([
1104
+ ...Object.keys(plan.structural ?? {}),
1105
+ ...Object.values(plan.propMap ?? {}).map((pp) => pp.a2ui),
1106
+ ]);
1107
+ return pending.every((q) => declared.has(q.prop));
1108
+ });
1109
+ if (controls.length !== 1) {
1110
+ const names = controls.map((c) => `'${c.node.component}'`).join(", ");
1111
+ throw new EmitSurfaceError(`donation boundary '${n.component}' (${originLabel}) requires exactly one eligible control declaring ` +
1112
+ `[${pending.map((q) => q.prop).join(", ")}]; found ${controls.length}${controls.length ? ` (${names})` : ""} — ` +
1113
+ `a donation relocates onto one control, never broadcasts`, `${path}${suffix}`);
1114
+ }
1115
+ controls[0].donations = [...(controls[0].donations ?? []), ...pending];
1116
+ }
1117
+ out.push(...spliced);
1118
+ };
1119
+ const rootOut = [];
680
1120
  for (const child of collectChildren(node))
681
- visit(child.node, child.suffix);
682
- return out;
1121
+ visit(child.node, child.suffix, [model], rootOut);
1122
+ return rootOut;
683
1123
  }
684
1124
  emitTextPrimitive(text, preferredId, path, treePath, phase, rule, variant) {
685
1125
  const { textComponent, textProp } = this.profile.surfaceSynthesis;