@aestheticfunction/dspack-emit 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/README.md +16 -6
  2. package/dist/cli.js +56 -0
  3. package/dist/index.d.ts +4 -1
  4. package/dist/index.js +3 -1
  5. package/dist/targets/a2ui/diagnostics.d.ts +110 -0
  6. package/dist/targets/a2ui/diagnostics.js +94 -0
  7. package/dist/targets/a2ui/surface.d.ts +28 -9
  8. package/dist/targets/a2ui/surface.js +566 -224
  9. package/dist/transform/desugar.d.ts +32 -0
  10. package/dist/transform/desugar.js +156 -0
  11. package/dist/transform/emit.js +59 -0
  12. package/dist/transform/index.js +4 -0
  13. package/dist/transform/mapping.d.ts +0 -6
  14. package/dist/transform/mapping.js +50 -0
  15. package/dist/transform/model.d.ts +275 -0
  16. package/dist/transform/model.js +148 -0
  17. package/dist/transform/parse-v2.d.ts +78 -0
  18. package/dist/transform/parse-v2.js +305 -0
  19. package/dist/transform/profile-load.d.ts +7 -6
  20. package/dist/transform/profile-load.js +99 -20
  21. package/dist/transform/profile-schema-v2.d.ts +9 -0
  22. package/dist/transform/profile-schema-v2.js +430 -0
  23. package/dist/transform/profiles.d.ts +31 -1
  24. package/dist/transform/scaffold.d.ts +29 -12
  25. package/dist/transform/scaffold.js +91 -31
  26. package/dist/transform/shadcn-v2-respelling.d.ts +12 -0
  27. package/dist/transform/shadcn-v2-respelling.js +49 -0
  28. package/dist/transform/validate-v2.d.ts +36 -0
  29. package/dist/transform/validate-v2.js +100 -0
  30. package/dist/types.d.ts +19 -0
  31. package/dist/validate/ajv.js +96 -25
  32. package/package.json +2 -2
  33. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  34. package/src/byte-neutral.test.ts +246 -0
  35. package/src/cli.ts +60 -0
  36. package/src/dangling-ref.test.ts +118 -0
  37. package/src/desugar.test.ts +162 -0
  38. package/src/engine-boundary.test.ts +248 -0
  39. package/src/eval-fixture.test.ts +89 -0
  40. package/src/functions.test.ts +182 -0
  41. package/src/index.ts +4 -1
  42. package/src/profile-load.test.ts +99 -1
  43. package/src/profile-v2.test.ts +363 -0
  44. package/src/review-findings.test.ts +292 -0
  45. package/src/schema-mirrors.test.ts +5 -0
  46. package/src/surface-fidelity.test.ts +213 -0
  47. package/src/targets/a2ui/diagnostics.ts +136 -0
  48. package/src/targets/a2ui/surface.ts +920 -242
  49. package/src/transform/desugar.ts +194 -0
  50. package/src/transform/emit.ts +65 -0
  51. package/src/transform/index.ts +5 -0
  52. package/src/transform/mapping.ts +42 -0
  53. package/src/transform/model.ts +325 -0
  54. package/src/transform/parse-v2.ts +397 -0
  55. package/src/transform/profile-load.ts +104 -22
  56. package/src/transform/profile-schema-v2.ts +430 -0
  57. package/src/transform/profile.v2.schema.json +422 -0
  58. package/src/transform/profiles.ts +32 -1
  59. package/src/transform/scaffold.ts +124 -47
  60. package/src/transform/shadcn-v2-respelling.ts +61 -0
  61. package/src/transform/validate-v2.ts +138 -0
  62. package/src/types.ts +20 -0
  63. package/src/validate/ajv.ts +89 -26
  64. package/src/validate-v2.test.ts +173 -0
@@ -0,0 +1,194 @@
1
+ /**
2
+ * v1 surface-plan directives -> the internal transformation model.
3
+ *
4
+ * Every authored directive is surface syntax for one or more Identity / Route /
5
+ * Collect facts. This module is the whole of that translation, and it is the
6
+ * only place in the package that knows the v1 directive names: past here, the
7
+ * engine sees primitives.
8
+ *
9
+ * The translation must be EXACT, not approximate — v1 profiles keep emitting
10
+ * byte-identically (src/byte-neutral.test.ts is the gate), so every quirk of
11
+ * the original directives is reproduced here deliberately, with the quirk named:
12
+ *
13
+ * - `subText` visits the node itself, not only its descendants;
14
+ * - `subButtonText` accepts only label-bearing components, then falls back to
15
+ * an audited lift of the first direct text under the sub;
16
+ * - `textProp`/`textChildProp` overwrite, while everything else is first-wins;
17
+ * - `subTable` accepts a header-cell wherever a cell is expected, concatenates
18
+ * multiple header rows into one flat column list, and takes the first caption;
19
+ * - `structuralPassthrough` wins over any consumed value.
20
+ *
21
+ * Reading this file top to bottom is also the v1 -> internal mapping table.
22
+ */
23
+ import type { ComponentPlan, SurfacePlanDirectives } from "./profiles.js";
24
+ import { parseSurfaceV2 } from "./parse-v2.js";
25
+ import { emptySurfaceModel, WriteOrder, type Collect, type Route, type SurfaceModel } from "./model.js";
26
+
27
+ /** Cache: a plan's model is derived once, not per emitted node. */
28
+ const cache = new WeakMap<ComponentPlan, SurfaceModel>();
29
+
30
+ /**
31
+ * The internal model for a plan, whichever language it is written in: a v2
32
+ * `surface` block parses directly; v1 directives desugar. Both languages meet
33
+ * the engine only as this model — the engine cannot tell them apart, which is
34
+ * the compatibility guarantee.
35
+ */
36
+ export function surfaceModelOf(plan: ComponentPlan): SurfaceModel {
37
+ const hit = cache.get(plan);
38
+ if (hit) return hit;
39
+ const model = plan.surface ? parseSurfaceV2(plan.surface, plan, "/surface") : desugar(plan.surfacePlan ?? {});
40
+ cache.set(plan, model);
41
+ return model;
42
+ }
43
+
44
+ export function desugar(sp: SurfacePlanDirectives): SurfaceModel {
45
+ const model = emptySurfaceModel();
46
+ const route = (r: Route) => model.routes.push(r);
47
+
48
+ // structuralPassthrough: CSR props copied verbatim into same-named slots.
49
+ // Listed first because it wins over consumed values, and the engine applies
50
+ // routes in order with first-write-wins.
51
+ for (const key of sp.structuralPassthrough ?? []) {
52
+ route({
53
+ order: WriteOrder.Verbatim,
54
+ from: [{ kind: "self-prop", prop: key }],
55
+ to: { kind: "prop", name: key },
56
+ origin: "structuralPassthrough",
57
+ });
58
+ }
59
+
60
+ // subText: descendant text -> a named prop. One route per target prop; the
61
+ // selector names every sub that feeds it, which is also how two sub ids
62
+ // sharing one destination stay a single first-wins decision.
63
+ const bySubTextTarget = new Map<string, string[]>();
64
+ for (const [sub, prop] of Object.entries(sp.subText ?? {})) {
65
+ bySubTextTarget.set(prop, [...(bySubTextTarget.get(prop) ?? []), sub]);
66
+ }
67
+ for (const [prop, subs] of bySubTextTarget) {
68
+ route({ order: WriteOrder.Consume, from: [{ kind: "sub-text", subs }], to: { kind: "prop", name: prop }, origin: "subText" });
69
+ }
70
+
71
+ // subButtonText: the label of a label-bearing component inside the sub, else
72
+ // an audited lift of the first direct text under it. One route, two ordered
73
+ // selectors — the fallback that motivated Selector[].
74
+ for (const [sub, prop] of Object.entries(sp.subButtonText ?? {})) {
75
+ route({
76
+ order: WriteOrder.Consume,
77
+ from: [
78
+ { kind: "sub-label", subs: [sub] },
79
+ { kind: "sub-text-lift", subs: [sub] },
80
+ ],
81
+ to: { kind: "prop", name: prop },
82
+ origin: "subButtonText",
83
+ });
84
+ }
85
+
86
+ // subTable: three nested collects plus a caption route. Nothing here is
87
+ // table-shaped except the sub ids the profile names — the depth is nesting,
88
+ // the record key is an item field name, and the drops are ordinary drops.
89
+ if (sp.subTable) {
90
+ const t = sp.subTable;
91
+ route({
92
+ order: WriteOrder.CollectLead,
93
+ from: [{ kind: "subtree-text", subs: [t.caption] }],
94
+ to: { kind: "prop", name: t.targetCaption },
95
+ origin: "subTable.caption",
96
+ });
97
+
98
+ /** A row's cells: one flat scalar list. A header-cell counts as a cell. */
99
+ const cells = (origin: string): Collect => ({
100
+ order: WriteOrder.Collect,
101
+ flatten: false,
102
+ of: [t.row],
103
+ as: { kind: "inline" },
104
+ scalar: {
105
+ order: WriteOrder.Collect,
106
+ from: [{ kind: "subtree-text", subs: [t.cell, t.headerCell] }],
107
+ to: { kind: "prop", name: "cells" },
108
+ origin,
109
+ },
110
+ origin,
111
+ });
112
+
113
+ // Header: every header row's cells concatenate into ONE flat column list —
114
+ // v1 passes the same array to each header row, so two header rows append.
115
+ model.collects.push({
116
+ order: WriteOrder.Collect,
117
+ flatten: true,
118
+ of: [t.header],
119
+ as: { kind: "prop", name: t.targetColumns },
120
+ item: { cells: cells("subTable.header") },
121
+ origin: "subTable.header",
122
+ });
123
+
124
+ // Body: one record per row, its cells under the `cells` field. That field
125
+ // name was a literal in the v1 emitter; here it is data.
126
+ model.collects.push({
127
+ order: WriteOrder.Collect,
128
+ flatten: false,
129
+ of: [t.body],
130
+ as: { kind: "prop", name: t.targetRows },
131
+ item: { cells: cells("subTable.body") },
132
+ origin: "subTable.body",
133
+ });
134
+
135
+ Object.assign(model.drops, t.drops);
136
+ }
137
+
138
+ // textProp / textChildProp: the node's own text. Both OVERWRITE, unlike every
139
+ // consuming directive — v1's one asymmetry, kept explicit.
140
+ if (sp.textProp) {
141
+ route({
142
+ order: WriteOrder.SelfText,
143
+ from: [{ kind: "self-text" }],
144
+ to: { kind: "prop", name: sp.textProp },
145
+ overwrite: true,
146
+ origin: "textProp",
147
+ });
148
+ }
149
+ if (sp.textChildProp) {
150
+ route({
151
+ order: WriteOrder.SelfTextChild,
152
+ from: [{ kind: "self-text" }],
153
+ to: { kind: "text-child", name: sp.textChildProp },
154
+ overwrite: true,
155
+ origin: "textChildProp",
156
+ });
157
+ }
158
+
159
+ // actionProp: no source in the subtree; the event name is a deterministic
160
+ // slug the engine derives. Ordered after the text routes because v1 reads a
161
+ // prop those routes may have written when naming the event.
162
+ if (sp.actionProp) {
163
+ route({
164
+ order: WriteOrder.Action,
165
+ from: [{ kind: "synthesized-action" }],
166
+ to: { kind: "action", name: sp.actionProp },
167
+ origin: "actionProp",
168
+ });
169
+ }
170
+
171
+ // subFlatten: the two halves are Identity decisions about named subs —
172
+ // dissolve, or become the synthesized text primitive with a variant.
173
+ for (const sub of sp.subFlatten?.transparent ?? []) {
174
+ model.subIdentity[sub] = { kind: "transparent" };
175
+ }
176
+ for (const [sub, variant] of Object.entries(sp.subFlatten?.asText ?? {})) {
177
+ model.subIdentity[sub] = { kind: "as-text", variant };
178
+ }
179
+
180
+ // childProp / childrenProp: children as instance references.
181
+ if (sp.childrenProp) {
182
+ route({ order: WriteOrder.Children, from: [{ kind: "children" }], to: { kind: "slots", name: sp.childrenProp }, origin: "childrenProp" });
183
+ } else if (sp.childProp) {
184
+ route({ order: WriteOrder.Children, from: [{ kind: "children" }], to: { kind: "slot", name: sp.childProp }, origin: "childProp" });
185
+ }
186
+
187
+ // Derived, never authored: a plan that absorbs its subtree into props does
188
+ // not also emit that subtree as children. v1 computed this from the presence
189
+ // of subText/subButtonText/subTable — the same three, now expressed as the
190
+ // routes and collects that consume descendants.
191
+ model.consumesSubtree = Boolean(sp.subText || sp.subButtonText || sp.subTable);
192
+
193
+ return model;
194
+ }
@@ -14,6 +14,48 @@ import { INLINED_DEFS } from "./inline-defs.js";
14
14
  import type { MappingResult } from "./mapping.js";
15
15
  import type { Profile } from "./profiles.js";
16
16
 
17
+ /**
18
+ * The catalog's function surface, from the profile's declared FunctionPlans:
19
+ * a documentation section, the name enum for FunctionCall.call, and the
20
+ * per-function anyFunction branches that validate each call's args shape.
21
+ * Definitions are declarative schemas — implementations live in renderers,
22
+ * exactly as A2UI intends; nothing executable exists here.
23
+ */
24
+ function buildFunctions(profile: Profile): {
25
+ section: Record<string, Json>;
26
+ names: string[];
27
+ anyFunction: Json;
28
+ } | null {
29
+ const declared = profile.functions;
30
+ if (!declared || Object.keys(declared).length === 0) return null;
31
+ const names = Object.keys(declared).sort();
32
+ const section: Record<string, Json> = {};
33
+ const branches: Json[] = [];
34
+ for (const name of names) {
35
+ const fn = declared[name];
36
+ section[name] = {
37
+ description: fn.description,
38
+ returnType: fn.returns,
39
+ ...(fn.args ? { args: fn.args as Json } : {}),
40
+ } as Json;
41
+ const requiredArgs =
42
+ fn.args && Array.isArray((fn.args as { required?: unknown }).required) &&
43
+ ((fn.args as { required: unknown[] }).required.length > 0);
44
+ branches.push({
45
+ type: "object",
46
+ properties: {
47
+ call: { const: name },
48
+ ...(fn.args ? { args: fn.args as Json } : { args: { type: "object", maxProperties: 0 } }),
49
+ returnType: { const: fn.returns },
50
+ },
51
+ // A function whose declared args carry required params cannot be called
52
+ // without them — the args object itself becomes required.
53
+ required: requiredArgs ? ["call", "args"] : ["call"],
54
+ } as Json);
55
+ }
56
+ return { section, names, anyFunction: { oneOf: branches } as Json };
57
+ }
58
+
17
59
  const VER_SEGMENT: Record<A2uiVersion, string> = {
18
60
  "0.9.1": "v0_9_1",
19
61
  "1.0": "v1_0",
@@ -37,6 +79,27 @@ export function emitCatalog(
37
79
  anyComponent,
38
80
  };
39
81
 
82
+ // Declared functions: the profile's function vocabulary becomes the
83
+ // catalog's `functions` section, and — the fail-closed half — FunctionCall
84
+ // regains the upstream anyFunction constraint our inlined copy dropped
85
+ // (inline-defs.ts) back when no catalog declared any functions to call.
86
+ // With the constraint restored, an instance calling an UNDECLARED function
87
+ // fails gate A3 instead of passing silently. Profiles that declare no
88
+ // functions (every v1 profile) emit byte-identically to before.
89
+ const functions = buildFunctions(profile);
90
+ if (functions) {
91
+ $defs.anyFunction = functions.anyFunction;
92
+ const fc = $defs.FunctionCall as { properties: { call: Json }; oneOf?: Json[] };
93
+ fc.properties.call = {
94
+ type: "string",
95
+ description: "The name of the function to call. Must be declared in this catalog's functions section.",
96
+ enum: functions.names,
97
+ } as Json;
98
+ // The upstream shape our inline copy dropped: the whole call object must
99
+ // match one declared function's branch (name AND args shape together).
100
+ fc.oneOf = [{ $ref: "#/$defs/anyFunction" } as Json];
101
+ }
102
+
40
103
  if (version === "0.9.1") {
41
104
  $defs.theme = themeDef(result);
42
105
  } else {
@@ -50,6 +113,7 @@ export function emitCatalog(
50
113
  description: profile.catalogDescription,
51
114
  catalogId: id,
52
115
  components: result.components,
116
+ ...(functions ? { functions: functions.section } : {}),
53
117
  $defs,
54
118
  };
55
119
 
@@ -63,6 +127,7 @@ export function emitCatalog(
63
127
  instructions: profile.instructions,
64
128
  catalogId: catalog.catalogId,
65
129
  components: catalog.components,
130
+ ...(catalog.functions ? { functions: catalog.functions } : {}),
66
131
  $defs: catalog.$defs,
67
132
  };
68
133
  }
@@ -4,6 +4,7 @@
4
4
  import type { A2uiCatalog, A2uiVersion, DspackDoc } from "../types.js";
5
5
  import { shadcnProfile, type Profile } from "./profiles.js";
6
6
  import { mapDspack, type MappingResult } from "./mapping.js";
7
+ import { validateProfileAgainstContract } from "./validate-v2.js";
7
8
  import { emitCatalog } from "./emit.js";
8
9
  import { buildReport, type ReportBundle } from "./report.js";
9
10
  import { validateCatalog, type ValidationReport } from "../validate/ajv.js";
@@ -27,6 +28,10 @@ export function transform(
27
28
  throw new Error(`Unsupported dspack major version '${doc.dspack}'. This PoC targets dspack 0.x.`);
28
29
  }
29
30
 
31
+ // v2 profiles fail closed against the contract before anything emits;
32
+ // v1 behaviour is frozen (report + --strict-coverage instead).
33
+ validateProfileAgainstContract(profile, doc);
34
+
30
35
  const mapping = mapDspack(doc, profile);
31
36
  const catalog = emitCatalog(mapping, version, profile);
32
37
  const validation = validateCatalog(catalog, version, surface);
@@ -4,6 +4,8 @@
4
4
  * for unsupported constructs, and the design-token projection. It reads only the
5
5
  * dspack JSON and the profile — never framework code.
6
6
  */
7
+ import { surfaceModelOf } from "./desugar.js";
8
+ import { deriveSubCoverage } from "./model.js";
7
9
  import type {
8
10
  CoverageEntry,
9
11
  DspackComponent,
@@ -145,6 +147,46 @@ function computeCoverage(
145
147
  });
146
148
  }
147
149
  }
150
+
151
+ // Sub-component coverage, DERIVED from each mapped compound's transformation
152
+ // model rather than authored prose (the old `subCoverage` field is v1
153
+ // documentation the engine never read; the model is what actually happens).
154
+ // An unresolved sub is an unclassified coverage entry: for v1 profiles this
155
+ // reports (and fails under --strict-coverage); v2 profiles never get here —
156
+ // validateProfileAgainstContract refuses them at entry. Measured before
157
+ // enforcement: pinned shadcn v2.3.0, astryx and acme all derive zero
158
+ // unresolved subs, so no shipped artifact changes.
159
+ const byId = new Map<string, ComponentPlan>();
160
+ for (const p of [...profile.components, ...profile.synthesized]) {
161
+ if (p.dspackId) byId.set(p.dspackId, p);
162
+ }
163
+ for (const [id, component] of Object.entries(doc.components ?? {})) {
164
+ const subs =
165
+ (component as { composition?: { subComponents?: Array<{ id: string }> } }).composition?.subComponents ?? [];
166
+ if (subs.length === 0) continue;
167
+ const plan = byId.get(id);
168
+ if (!plan) continue; // unmapped/casualty parents: the parent entry above carries the family
169
+ const model = surfaceModelOf(plan);
170
+ const derived = deriveSubCoverage(model, subs.map((s) => s.id));
171
+ for (const sub of subs) {
172
+ const how = derived.get(sub.id);
173
+ if (how) {
174
+ coverage.push({ id: `${id}.${sub.id}`, disposition: "mapped", detail: how });
175
+ } else {
176
+ coverage.push({ id: `${id}.${sub.id}`, disposition: "unclassified" });
177
+ warnings.push({
178
+ code: `unresolved-sub:${id}.${sub.id}`,
179
+ message: `sub-component '${sub.id}' of mapped compound '${id}' is unresolved: no route consumes it, no collect gathers it, no disposition dissolves or drops it.`,
180
+ });
181
+ fidelity.push({
182
+ source: `components.${id}.composition.${sub.id}`,
183
+ target: "(silently dropped)",
184
+ class: "cannot-represent",
185
+ note: "Unresolved by the compound's transformation model. This is a coverage gap, not a deliberate casualty.",
186
+ });
187
+ }
188
+ }
189
+ }
148
190
  return coverage;
149
191
  }
150
192
 
@@ -0,0 +1,325 @@
1
+ /**
2
+ * The internal surface transformation model.
3
+ *
4
+ * Ten authored surface-plan directives accumulated one at a time, each named
5
+ * after the collision that produced it (`subText`, `subButtonText`, `subTable`,
6
+ * `subFlatten`, …). Measured against two design systems and a second emit
7
+ * target, that vocabulary does not generalize: only four directives are used by
8
+ * both shipped profiles, the second target reuses none of them, and the
9
+ * scaffolder can reach two. They are not a vocabulary for projecting design
10
+ * systems onto protocols — they are point-fixes for one collision, shadcn's
11
+ * compound sub-component composition meeting A2UI's fixed catalog vocabulary.
12
+ *
13
+ * Underneath, every one of them answers exactly one of three questions:
14
+ *
15
+ * Identity does this node become an instance, and as which component?
16
+ * Routing for each piece of this node's subtree, where does it land?
17
+ * Repetition when a sub-structure repeats, how does it become an array?
18
+ *
19
+ * This module is that answer as types. The authored directives become surface
20
+ * syntax that desugars here (see desugar.ts); the engine reads only this.
21
+ *
22
+ * THREE THINGS IMPLEMENTATION CONTACT ADDED, and why they are refinements of
23
+ * the model rather than escapes from it:
24
+ *
25
+ * 1. `Selector[]`, not `Selector`. The audited label lift — "take the sub's
26
+ * label, else the first direct text under it" — is a fallback chain, not a
27
+ * special case. Ordered selectors express it, and express nothing else.
28
+ * 2. `subs: string[]`, not `sub: string`. A table body accepts both a cell and
29
+ * a header-cell in the same row. One selector naming a set is honest; two
30
+ * collects racing for one destination is not.
31
+ * 3. First-write-wins as a uniform WRITE DISCIPLINE rather than per-directive
32
+ * `??=` scattered through the emitter. Every v1 directive already behaved
33
+ * this way; only `textProp`/`textChildProp` overwrote, and that asymmetry
34
+ * is preserved explicitly (see `Route.overwrite`) rather than silently.
35
+ *
36
+ * What is deliberately NOT here, and must not arrive later: JSON paths,
37
+ * expression evaluation, predicates, computed destination names, and writes to
38
+ * arbitrary other instances. Those would each buy generality at the cost of the
39
+ * property that makes emission auditable — that a plan can be checked against
40
+ * its contract before it runs.
41
+ */
42
+ import type { Json } from "../types.js";
43
+
44
+ /**
45
+ * Whether a dspack node becomes an emitted instance, and under which catalog
46
+ * identity. `transparent` and `as-text` are v1's `subFlatten` halves: today
47
+ * they are declared by a compound about its own sub-family (subs have no plans
48
+ * of their own), which is why they live in `Plan.subIdentity` rather than on
49
+ * the node's plan. When plans gain identities of their own, that field becomes
50
+ * the narrower spelling of this same idea.
51
+ */
52
+ export type Identity =
53
+ /** Emits one instance of the named A2UI component. */
54
+ | { kind: "mapped"; a2ui: string }
55
+ /** Emits nothing; its children rise to the destination its parent would use. */
56
+ | { kind: "transparent" }
57
+ /** Emits as the profile's synthesized text primitive, carrying its subtree text. */
58
+ | { kind: "as-text"; variant: string };
59
+
60
+ /**
61
+ * Where information comes from. A closed enumeration: every selector is
62
+ * statically checkable against the contract before emission runs.
63
+ */
64
+ export type Selector =
65
+ /** This node's own `text`. */
66
+ | { kind: "self-text" }
67
+ /** One declared prop on this node, verbatim. */
68
+ | { kind: "self-prop"; prop: string }
69
+ /** `text` of any descendant whose component is one of `subs`. */
70
+ | { kind: "sub-text"; subs: string[] }
71
+ /**
72
+ * The label of a descendant inside one of `subs` — a component whose own plan
73
+ * projects text as a child label. Incidental text elsewhere never qualifies.
74
+ */
75
+ | { kind: "sub-label"; subs: string[] }
76
+ /**
77
+ * First direct text under one of `subs`, document order, the sub's own text
78
+ * included. This is a LIFT: relocation of text that exists, never synthesis.
79
+ * Only ever reached as a fallback, and always recorded.
80
+ */
81
+ | { kind: "sub-text-lift"; subs: string[] }
82
+ /** All text in a descendant's subtree, document order, space-joined. */
83
+ | { kind: "subtree-text"; subs: string[] }
84
+ /** This node's ordered children, emitted as instances. */
85
+ | { kind: "children" }
86
+ /** No source: a declarative A2UI action synthesized from a deterministic slug. */
87
+ | { kind: "synthesized-action" };
88
+
89
+ /**
90
+ * Where information lands on the emitted instance. Names are literal — never
91
+ * computed — so a plan's destinations can be validated against its own
92
+ * `propMap`/`structural` at load time. This matters more than it looks: gate A3
93
+ * validates emitted messages against the catalog and so catches an OMITTED
94
+ * property, but an INVENTED one would pass. Load-time checking is the only
95
+ * place that asymmetry can be closed.
96
+ */
97
+ export type Destination =
98
+ /** A scalar property. */
99
+ | { kind: "prop"; name: string }
100
+ /** A ComponentId property referencing a synthesized text primitive. */
101
+ | { kind: "text-child"; name: string }
102
+ /** A single ComponentId property (>1 child is wrapped in the profile's wrap component). */
103
+ | { kind: "slot"; name: string }
104
+ /** A ChildList property. */
105
+ | { kind: "slots"; name: string }
106
+ /** An Action property. */
107
+ | { kind: "action"; name: string };
108
+
109
+ /**
110
+ * Legacy write order. The engine applies routes and collects sorted by this,
111
+ * never by declaration index or traversal happenstance — the same discipline
112
+ * the diagnostics use, applied to output. Object key order is observable
113
+ * (artifacts are hashed), so "when a route writes" is part of the contract and
114
+ * belongs in data rather than in the shape of a method.
115
+ */
116
+ export enum WriteOrder {
117
+ /** Props copied verbatim into same-named destinations; wins over consumption. */
118
+ Verbatim = 10,
119
+ /** Sub-scoped consumption. Resolved by ONE document-order walk (see below). */
120
+ Consume = 20,
121
+ /** Repetition, and the caption-style routes that belong to the same strategy. */
122
+ CollectLead = 30,
123
+ Collect = 31,
124
+ /** The node's own text. */
125
+ SelfText = 40,
126
+ SelfTextChild = 41,
127
+ /** Synthesis with no source in the subtree. */
128
+ Action = 50,
129
+ /** Children as instance references, once every value destination is settled. */
130
+ Children = 60,
131
+ }
132
+
133
+ /** Moves one piece of information from a source to a destination. */
134
+ export interface Route {
135
+ /** When this route writes, relative to every other route and collect. */
136
+ order: WriteOrder;
137
+ /** Tried in order; the first that yields a value wins. */
138
+ from: Selector[];
139
+ to: Destination;
140
+ /**
141
+ * v1 asymmetry, preserved deliberately: `textProp`/`textChildProp` overwrite
142
+ * whatever is already there, while every consuming directive is first-wins.
143
+ * Making it a field rather than a code path keeps the difference reviewable.
144
+ */
145
+ overwrite?: boolean;
146
+ /** Which authored directive produced this route — provenance for fidelity. */
147
+ origin: string;
148
+ }
149
+
150
+ /**
151
+ * Collects a repeated sub-structure into an array-valued destination. Item
152
+ * fields are themselves routes or nested collects, which is why a paired group
153
+ * (an options array whose value is a child reference) needs no separate
154
+ * primitive — and why `subTable`'s three-level shape is nesting rather than a
155
+ * grammar.
156
+ */
157
+ export interface Collect {
158
+ /** When this collect writes, relative to every other route and collect. */
159
+ order: WriteOrder;
160
+ /**
161
+ * True when every repetition's cells concatenate into ONE flat list (v1's
162
+ * header semantics: two header rows append into a single column list);
163
+ * false when each repetition becomes its own record. Declared data — the
164
+ * engine must never infer this from names or origins.
165
+ */
166
+ flatten: boolean;
167
+ /** Descendant components that open one repetition. */
168
+ of: string[];
169
+ /** Array-valued destination, or `inline` when nested into a parent's field. */
170
+ as: Destination | { kind: "inline" };
171
+ /**
172
+ * Per-item fields. A collect whose item is a single unnamed scalar (a table
173
+ * row's cells) uses `scalar` instead.
174
+ */
175
+ item?: Record<string, Route | Collect>;
176
+ /** The item IS one scalar, produced by this route. Mutually exclusive with `item`. */
177
+ scalar?: Route;
178
+ /** Declared join key for paired collections. Never inferred. Reserved for T3. */
179
+ joinOn?: string;
180
+ origin: string;
181
+ }
182
+
183
+ /**
184
+ * Sub-components this plan explicitly discards, with the authored reason. v1
185
+ * spelled this inside `subTable.drops`; it is not a table concept.
186
+ */
187
+ export type Drops = Record<string, string>;
188
+
189
+ /** The whole of how a plan projects a surface node. Replaces SurfacePlanDirectives. */
190
+ export interface SurfaceModel {
191
+ routes: Route[];
192
+ collects: Collect[];
193
+ /** Identity assigned to named sub-components met inside this node's subtree. */
194
+ subIdentity: Record<string, Identity>;
195
+ drops: Drops;
196
+ /**
197
+ * True when this plan absorbs its whole subtree into props, so children are
198
+ * not emitted as instances. Derived during desugaring from the presence of
199
+ * consuming routes/collects — never authored.
200
+ */
201
+ consumesSubtree: boolean;
202
+ }
203
+
204
+ export const emptySurfaceModel = (): SurfaceModel => ({
205
+ routes: [],
206
+ collects: [],
207
+ subIdentity: {},
208
+ drops: {},
209
+ consumesSubtree: false,
210
+ });
211
+
212
+ /** Narrowing helper: a collect's field may be either shape. */
213
+ export const isCollect = (field: Route | Collect): field is Collect =>
214
+ (field as Collect).of !== undefined;
215
+
216
+ /** Human-readable selector, for warnings and fidelity provenance. */
217
+ export function describeSelector(s: Selector): string {
218
+ switch (s.kind) {
219
+ case "self-text":
220
+ return "self.text";
221
+ case "self-prop":
222
+ return `self.props.${s.prop}`;
223
+ case "sub-text":
224
+ return `sub(${s.subs.join("|")}).text`;
225
+ case "sub-label":
226
+ return `sub(${s.subs.join("|")}).label`;
227
+ case "sub-text-lift":
228
+ return `sub(${s.subs.join("|")}).firstText`;
229
+ case "subtree-text":
230
+ return `sub(${s.subs.join("|")}).subtreeText`;
231
+ case "children":
232
+ return "children";
233
+ case "synthesized-action":
234
+ return "synthesized.action";
235
+ }
236
+ }
237
+
238
+ /** Human-readable destination, for warnings and fidelity provenance. */
239
+ export const describeDestination = (d: Destination | { kind: "inline" }): string =>
240
+ d.kind === "inline" ? "inline" : `${d.kind}:${d.name}`;
241
+
242
+ /** Every destination a model writes, for load-time validation against the plan. */
243
+ export function destinationsOf(model: SurfaceModel): Destination[] {
244
+ const out: Destination[] = model.routes.map((r) => r.to);
245
+ const walk = (c: Collect): void => {
246
+ if (c.as.kind !== "inline") out.push(c.as);
247
+ for (const field of Object.values(c.item ?? {})) {
248
+ if (isCollect(field)) walk(field);
249
+ else out.push(field.to);
250
+ }
251
+ if (c.scalar) out.push(c.scalar.to);
252
+ };
253
+ for (const c of model.collects) walk(c);
254
+ return out;
255
+ }
256
+
257
+ /**
258
+ * Every sub-component id this model accounts for, and how. This is what makes
259
+ * `subCoverage` derivable instead of authored: a sub is covered when the model
260
+ * consumes it, dissolves it, re-identifies it, or drops it with a reason —
261
+ * and anything else is an unclassified sub, which must fail closed.
262
+ */
263
+ export function referencedSubs(model: SurfaceModel): Map<string, string> {
264
+ const subs = new Map<string, string>();
265
+ const note = (id: string, how: string) => {
266
+ if (!subs.has(id)) subs.set(id, how);
267
+ };
268
+
269
+ const fromSelector = (s: Selector, how: string): void => {
270
+ if (s.kind === "sub-text" || s.kind === "sub-label" || s.kind === "sub-text-lift" || s.kind === "subtree-text") {
271
+ for (const id of s.subs) note(id, how);
272
+ }
273
+ };
274
+
275
+ for (const r of model.routes) {
276
+ for (const s of r.from) fromSelector(s, `consumed into ${describeDestination(r.to)}`);
277
+ }
278
+
279
+ const walk = (c: Collect): void => {
280
+ for (const id of c.of) note(id, `collected into ${describeDestination(c.as)}`);
281
+ for (const field of Object.values(c.item ?? {})) {
282
+ if (isCollect(field)) walk(field);
283
+ else for (const s of field.from) fromSelector(s, `collected into ${describeDestination(field.to)}`);
284
+ }
285
+ if (c.scalar) for (const s of c.scalar.from) fromSelector(s, `collected as a scalar item`);
286
+ };
287
+ for (const c of model.collects) walk(c);
288
+
289
+ for (const [id, identity] of Object.entries(model.subIdentity)) {
290
+ note(id, identity.kind === "as-text" ? `re-identified as text (${identity.variant})` : "transparent grouping");
291
+ }
292
+ for (const [id, reason] of Object.entries(model.drops)) note(id, `dropped: ${reason}`);
293
+
294
+ return subs;
295
+ }
296
+
297
+ /**
298
+ * Derived sub-component coverage: the honest replacement for the authored
299
+ * `subCoverage` prose, which the engine never reads and which only a test in
300
+ * another repo enforces.
301
+ *
302
+ * A sub is covered when the model NAMES it, or — when the plan absorbs its
303
+ * whole subtree — when it is merely walked through on the way to a named one.
304
+ * That second case is not slack: `alert-dialog-content`, `-header` and
305
+ * `-footer` are real, and a derivation that only counted named subs would
306
+ * report them missing while the emitter handles them correctly.
307
+ *
308
+ * Anything else is unclassified, and must fail closed.
309
+ */
310
+ export function deriveSubCoverage(model: SurfaceModel, contractSubs: string[]): Map<string, string> {
311
+ const covered = referencedSubs(model);
312
+ for (const sub of contractSubs) {
313
+ if (covered.has(sub)) continue;
314
+ if (model.consumesSubtree) covered.set(sub, "transparent grouping, traversed by the subtree consumer");
315
+ }
316
+ return covered;
317
+ }
318
+
319
+ /** Subs the contract declares that the model cannot account for at all. */
320
+ export const unclassifiedSubs = (model: SurfaceModel, contractSubs: string[]): string[] => {
321
+ const covered = deriveSubCoverage(model, contractSubs);
322
+ return contractSubs.filter((s) => !covered.has(s));
323
+ };
324
+
325
+ export type { Json };