@aestheticfunction/dspack-emit 0.5.0 → 0.7.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 (39) hide show
  1. package/README.md +5 -3
  2. package/dist/targets/a2ui/surface.js +580 -36
  3. package/dist/transform/mapping.js +21 -7
  4. package/dist/transform/model.d.ts +94 -1
  5. package/dist/transform/model.js +25 -4
  6. package/dist/transform/parse-v2.d.ts +55 -24
  7. package/dist/transform/parse-v2.js +176 -2
  8. package/dist/transform/profile-schema-v2.js +224 -46
  9. package/dist/transform/shadcn-v2-respelling.d.ts +65 -0
  10. package/dist/transform/shadcn-v2-respelling.js +407 -0
  11. package/dist/transform/validate-v2.js +39 -3
  12. package/dist/types.d.ts +5 -1
  13. package/dist/validate/ajv.d.ts +19 -0
  14. package/dist/validate/ajv.js +78 -13
  15. package/package.json +6 -2
  16. package/src/a0.test.ts +235 -0
  17. package/src/engine-boundary.test.ts +10 -0
  18. package/src/eval-fixture.test.ts +27 -14
  19. package/src/instance-diagnostics.test.ts +194 -0
  20. package/src/layered-dissolution.test.ts +139 -0
  21. package/src/profile-v2.test.ts +9 -3
  22. package/src/review-findings.test.ts +4 -1
  23. package/src/surface-emit.test.ts +43 -11
  24. package/src/surface-fidelity.test.ts +12 -0
  25. package/src/t1.test.ts +370 -0
  26. package/src/t2.test.ts +222 -0
  27. package/src/t3.test.ts +304 -0
  28. package/src/t4.test.ts +278 -0
  29. package/src/targets/a2ui/surface.ts +747 -72
  30. package/src/transform/mapping.ts +22 -6
  31. package/src/transform/model.ts +107 -5
  32. package/src/transform/parse-v2.ts +228 -17
  33. package/src/transform/profile-schema-v2.ts +224 -46
  34. package/src/transform/profile.v2.schema.json +224 -46
  35. package/src/transform/shadcn-v2-respelling.ts +414 -0
  36. package/src/transform/validate-v2.ts +39 -3
  37. package/src/types.ts +13 -1
  38. package/src/validate/ajv.ts +96 -12
  39. package/src/validate-v2.test.ts +1 -1
package/src/a0.test.ts ADDED
@@ -0,0 +1,235 @@
1
+ /**
2
+ * A0: the zero-new-capability authoring milestone — production-v3 profile
3
+ * judgment expressed entirely in the shipped Identity/Routing/Repetition
4
+ * vocabulary (T1 transparency + donation, routes, drops-with-record). No
5
+ * new primitive; every decision grounded in measured usage and recorded
6
+ * with fidelity.
7
+ *
8
+ * Fail-first: before this overlay the six compound families sat in the
9
+ * 67-unresolved ledger (alert 3, avatar 5, scroll-area 2, field 5,
10
+ * field-set 1, field-group 1 — eval-fixture.test.ts pins the 67), and the
11
+ * touched examples refused end-to-end (ex.order-detail-summary on
12
+ * 'avatar', ex.delete-project-confirmation on 'alert', …).
13
+ *
14
+ * The two honest losses, dropped WITH RECORD, never approximated:
15
+ * - alert-action holds component children; routing a sub's children to a
16
+ * slot is T4's mechanism — one production instance affected;
17
+ * - avatar-image is an EMPTY node (the contract declares no src/alt —
18
+ * the dspack#39 contract-gap class, named on the drop).
19
+ */
20
+ import { readFileSync } from "node:fs";
21
+ import { fileURLToPath } from "node:url";
22
+ import { describe, expect, it } from "vitest";
23
+ import { transformFromJson } from "./transform/index.js";
24
+ import { emitSurface } from "./targets/a2ui/surface.js";
25
+ import { loadProfile } from "./transform/profile-load.js";
26
+ import { SHADCN_V3_A0_PLANS, SHADCN_V3_A0_LABEL_ADDITIONS } from "./transform/shadcn-v2-respelling.js";
27
+ import type { DspackDoc, DspackSurface } from "./types.js";
28
+
29
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
30
+ const contract = JSON.parse(readFileSync(repo("eval/shadcn-v3.dspack.json"), "utf8")) as DspackDoc & {
31
+ examples: Array<{ id: string; surface: DspackSurface }>;
32
+ };
33
+ const fixture = JSON.parse(readFileSync(repo("eval/shadcn-v3.eval.profile.json"), "utf8"));
34
+
35
+ /** The builder's A0 merge, hermetically: keep a family set, apply the overlay. */
36
+ const a0Profile = (keep: string[]) => {
37
+ const base = structuredClone(fixture) as Record<string, unknown> & {
38
+ components: Array<Record<string, unknown> & { dspackId: string; structural?: Record<string, unknown> }>;
39
+ };
40
+ base.components = base.components.map((plan) => {
41
+ const a0 = SHADCN_V3_A0_PLANS[plan.dspackId];
42
+ return a0 ? (structuredClone(a0) as typeof plan) : plan;
43
+ });
44
+ for (const [id, note] of Object.entries(SHADCN_V3_A0_LABEL_ADDITIONS)) {
45
+ const plan = base.components.find((c) => c.dspackId === id);
46
+ if (plan && !(plan.structural ?? {}).label) {
47
+ plan.structural = { ...(plan.structural ?? {}), label: { schema: { type: "string" }, description: note.description, synthNote: note.synthNote } };
48
+ }
49
+ }
50
+ const keepSet = new Set(keep);
51
+ base.intentionallyOmitted = base.components.filter((c) => !keepSet.has(c.dspackId)).map((c) => c.dspackId).sort();
52
+ base.components = base.components.filter((c) => keepSet.has(c.dspackId));
53
+ delete (base as Record<string, unknown>)["x-scaffold"];
54
+ return loadProfile(base);
55
+ };
56
+
57
+ const surfaceOf = (root: unknown, intent = "record-detail"): DspackSurface =>
58
+ ({ dspackSurface: "0.1", system: contract.name as string, intent, root }) as DspackSurface;
59
+
60
+ /** Find the first subtree of a component in a worked example, verbatim. */
61
+ const fromExample = (exampleId: string, component: string): Record<string, unknown> => {
62
+ const ex = contract.examples.find((e) => e.id === exampleId)!;
63
+ let hit: Record<string, unknown> | undefined;
64
+ const walk = (n: Record<string, unknown>): void => {
65
+ if (hit) return;
66
+ if (n.component === component) { hit = n; return; }
67
+ for (const c of (n.children as Record<string, unknown>[] | undefined) ?? []) walk(c);
68
+ };
69
+ walk(ex.surface.root as unknown as Record<string, unknown>);
70
+ expect(hit, `${component} in ${exampleId}`).toBeDefined();
71
+ return structuredClone(hit!);
72
+ };
73
+
74
+ const firstInstance = (messages: unknown[], component: string): Record<string, unknown> => {
75
+ const comps = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } }).updateComponents.components;
76
+ const inst = comps.find((c) => c.component === component);
77
+ expect(inst, `an emitted ${component}`).toBeDefined();
78
+ return inst!;
79
+ };
80
+
81
+ describe("A0 — alert (routes over the shipped vocabulary)", () => {
82
+ it("the production delete-project alert emits {title, description}", () => {
83
+ const profile = a0Profile(["card", "alert", "badge", "button"]);
84
+ const { messages } = emitSurface(surfaceOf(fromExample("ex.delete-project-confirmation", "alert")), contract, { profile });
85
+ const alert = firstInstance(messages, "Alert");
86
+ expect(typeof alert.title).toBe("string");
87
+ expect((alert.title as string).length).toBeGreaterThan(0);
88
+ expect(typeof alert.description).toBe("string");
89
+ const check = transformFromJson(contract, { profile, surface: { messages } });
90
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
91
+ });
92
+
93
+ it("alert-action's loss is recorded, never silent: the flatten ledger marks it lossy and the coverage detail names T4", () => {
94
+ const profile = a0Profile(["card", "alert", "badge", "button"]);
95
+ const { messages, warnings, fidelity } = emitSurface(
96
+ surfaceOf(fromExample("ex.import-run-status", "alert")), contract, { profile });
97
+ firstInstance(messages, "Alert");
98
+ // Runtime record: the consumed subtree is ledgered lossy (the engine's
99
+ // consumesSubtree record — the action button is inside it).
100
+ expect(warnings.some((w) => w.code === "surface-composition-flattened")).toBe(true);
101
+ expect(fidelity.some((f) => f.kind === "flattened" && f.class === "lossy" && f.source.includes("alert"))).toBe(true);
102
+ // Documented judgment: the coverage ledger carries the drop reason,
103
+ // naming T4 as the mechanism the slot waits for.
104
+ const out = transformFromJson(contract, { profile });
105
+ const row = out.mapping.coverage.find((c) => c.id === "alert.alert-action");
106
+ expect(row?.disposition).toBe("mapped");
107
+ expect(row?.detail).toContain("T4");
108
+ });
109
+ });
110
+
111
+ describe("A0 — avatar", () => {
112
+ it("the production order-detail avatar emits {size, fallback}; the empty avatar-image drop names the contract gap", () => {
113
+ const profile = a0Profile(["card", "avatar", "badge"]);
114
+ const { messages, fidelity } = emitSurface(surfaceOf(fromExample("ex.order-detail-summary", "avatar")), contract, { profile });
115
+ const avatar = firstInstance(messages, "Avatar");
116
+ expect(avatar.fallback).toBe("AO");
117
+ expect(avatar.size).toBe("lg");
118
+ // The consumed subtree (with the empty avatar-image inside) is ledgered
119
+ // lossy; the drop's dspack#39 rationale lives on the coverage row.
120
+ expect(fidelity.some((f) => f.kind === "flattened" && f.class === "lossy")).toBe(true);
121
+ const out = transformFromJson(contract, { profile });
122
+ expect(out.mapping.coverage.find((c) => c.id === "avatar.avatar-image")?.detail).toContain("dspack#39");
123
+ const check = transformFromJson(contract, { profile, surface: { messages } });
124
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
125
+ });
126
+ });
127
+
128
+ describe("A0 — scroll-area dissolves (T1 vocabulary, no instance)", () => {
129
+ it("children rise; scrollbar chrome drops with record", () => {
130
+ const profile = a0Profile(["card", "scroll-area", "badge"]);
131
+ const { messages } = emitSurface(
132
+ surfaceOf({
133
+ component: "card",
134
+ children: [{ component: "scroll-area", children: [{ component: "badge", text: "42 open" }] }],
135
+ }),
136
+ contract,
137
+ { profile },
138
+ );
139
+ const comps = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } }).updateComponents.components;
140
+ expect(comps.some((c) => c.component === "ScrollArea")).toBe(false);
141
+ expect(comps.some((c) => c.component === "Badge")).toBe(true);
142
+ });
143
+ });
144
+
145
+ describe("A0 — the corrected field family (dspack#40) emits end-to-end", () => {
146
+ it("the production notification-preferences field-set subtree: legend becomes text, groups dissolve, labels donate onto switches", () => {
147
+ const profile = a0Profile(["card", "field", "field-set", "field-group", "switch", "radio-group", "separator", "badge", "button"]);
148
+ const subtree = fromExample("ex.notification-preferences", "field-set");
149
+ const { messages, fidelity } = emitSurface(surfaceOf(subtree, "preference-settings"), contract, { profile });
150
+ const comps = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } }).updateComponents.components;
151
+ // No wrapper survives.
152
+ for (const gone of ["FieldSet", "FieldGroup", "Field"]) {
153
+ expect(comps.some((c) => c.component === gone), `${gone} must not emit`).toBe(false);
154
+ }
155
+ // The legend text survives as a Text instance.
156
+ expect(comps.some((c) => c.component === "Text")).toBe(true);
157
+ // Every switch carries its donated label.
158
+ const switches = comps.filter((c) => c.component === "Switch");
159
+ expect(switches.length).toBeGreaterThan(0);
160
+ for (const sw of switches) expect(typeof sw.label).toBe("string");
161
+ // Donation provenance is ledgered.
162
+ expect(fidelity.some((f) => f.note?.includes("donated by 'field-label'"))).toBe(true);
163
+ const check = transformFromJson(contract, { profile, surface: { messages } });
164
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
165
+ });
166
+
167
+ it("a field's textarea and select receive the donated label (the invite-teammates shapes)", () => {
168
+ const profile = a0Profile(["card", "field", "field-set", "field-group", "textarea", "select", "badge"]);
169
+ const t = emitSurface(
170
+ surfaceOf({ component: "field", children: [{ component: "field-label", text: "Personal note" }, { component: "textarea", props: { rows: 3 } }] }),
171
+ contract, { profile });
172
+ expect(firstInstance(t.messages, "Textarea").label).toBe("Personal note");
173
+
174
+ const s = emitSurface(
175
+ surfaceOf({
176
+ component: "field",
177
+ children: [
178
+ { component: "field-label", text: "Workspace role" },
179
+ { component: "select", children: [{ component: "select-content", children: [{ component: "select-item", text: "Editor" }] }] },
180
+ ],
181
+ }),
182
+ contract, { profile });
183
+ const sel = firstInstance(s.messages, "Select");
184
+ expect(sel.label).toBe("Workspace role");
185
+ expect(sel.options).toEqual([{ label: "Editor" }]);
186
+ });
187
+ });
188
+
189
+ describe("A0 — shipped primitives compose: transparency inside a joined panel", () => {
190
+ it("a transparent scroll-area inside tabs-content dissolves instead of refusing (the ex.project-workspace-panels shape)", () => {
191
+ // Discovered by the A0 re-measurement: the T3 joined-children path fed
192
+ // raw children to emitNode, skipping the parent-style rewrite that
193
+ // dissolves transparent children — a composition bug between shipped
194
+ // primitives, fixed by mirroring the transparent-root host pattern.
195
+ const profile = a0Profile(["card", "tabs", "scroll-area", "badge"]);
196
+ const { messages } = emitSurface(
197
+ surfaceOf({
198
+ component: "tabs",
199
+ children: [
200
+ { component: "tabs-list", children: [{ component: "tabs-trigger", id: "t1", text: "Overview" }] },
201
+ { component: "tabs-content", id: "t1", children: [{ component: "scroll-area", children: [{ component: "badge", text: "42 open" }] }] },
202
+ ],
203
+ }),
204
+ contract, { profile });
205
+ const comps = (messages[1] as { updateComponents: { components: Array<Record<string, unknown>> } }).updateComponents.components;
206
+ expect(comps.some((c) => c.component === "ScrollArea")).toBe(false);
207
+ const tabs = comps.find((c) => c.component === "Tabs")!;
208
+ const sections = tabs.sections as Array<{ child: string }>;
209
+ expect(sections).toHaveLength(1);
210
+ const badge = comps.find((c) => c.component === "Badge")!;
211
+ expect(sections[0].child).toBe(badge.id);
212
+ const check = transformFromJson(contract, { profile, surface: { messages } });
213
+ expect(check.validation.gates.find((g) => g.name === "instance")?.pass).toBe(true);
214
+ });
215
+ });
216
+
217
+ describe("A0 — ledger and determinism", () => {
218
+ it("the six authored families derive zero unresolved subs", () => {
219
+ const profile = a0Profile(["card", "alert", "avatar", "scroll-area", "field", "field-set", "field-group", "switch", "badge", "button"]);
220
+ const out = transformFromJson(contract, { profile });
221
+ const unresolved = out.mapping.coverage.filter(
222
+ (c) => c.disposition === "unclassified" &&
223
+ ["alert.", "avatar.", "scroll-area.", "field.", "field-set.", "field-group."].some((p) => c.id.startsWith(p)),
224
+ );
225
+ expect(unresolved).toEqual([]);
226
+ });
227
+
228
+ it("emission is deterministic across runs", () => {
229
+ const profile = a0Profile(["card", "field", "field-set", "field-group", "switch", "badge"]);
230
+ const subtree = fromExample("ex.notification-preferences", "field-set");
231
+ const a = emitSurface(surfaceOf(subtree, "preference-settings"), contract, { profile });
232
+ const b = emitSurface(surfaceOf(subtree, "preference-settings"), contract, { profile });
233
+ expect(JSON.stringify([a.messages, a.warnings, a.fidelity])).toBe(JSON.stringify([b.messages, b.warnings, b.fidelity]));
234
+ });
235
+ });
@@ -143,10 +143,14 @@ describe("transformations keep their meaning", () => {
143
143
  });
144
144
 
145
145
  it("first-write-wins: the first matching sub claims the destination", () => {
146
+ // The trigger keeps the AlertDialog instance catalog-valid
147
+ // (`triggerLabel` is required; emitSurface now refuses invalid
148
+ // instances) — the behaviour under test is the duplicated title.
146
149
  const [dialog] = instances(
147
150
  {
148
151
  component: "alert-dialog",
149
152
  children: [
153
+ { component: "alert-dialog-trigger", children: [{ component: "button", text: "Open" }] },
150
154
  { component: "alert-dialog-content", children: [
151
155
  { component: "alert-dialog-title", text: "First" },
152
156
  { component: "alert-dialog-title", text: "Second" },
@@ -173,6 +177,9 @@ describe("transformations keep their meaning", () => {
173
177
  });
174
178
 
175
179
  it("collection: two header rows concatenate into one column list (v1 behaviour)", () => {
180
+ // A body row keeps the Table instance catalog-valid (`rows` is required;
181
+ // emitSurface now refuses invalid instances) — the behaviour under test
182
+ // is the header concatenation, which is unaffected.
176
183
  const [table] = instances({
177
184
  component: "table",
178
185
  children: [
@@ -180,6 +187,9 @@ describe("transformations keep their meaning", () => {
180
187
  { component: "table-row", children: [{ component: "table-head", text: "A" }] },
181
188
  { component: "table-row", children: [{ component: "table-head", text: "B" }] },
182
189
  ] },
190
+ { component: "table-body", children: [
191
+ { component: "table-row", children: [{ component: "table-cell", text: "1" }] },
192
+ ] },
183
193
  ],
184
194
  });
185
195
  expect(table.columns).toEqual(["A", "B"]);
@@ -5,14 +5,27 @@
5
5
  * Supersedes the /tmp-only measurement recorded in 2aac076 ("29 subs under 6
6
6
  * compounds, 1 unresolved"): that profile's nine extra compound plans carried
7
7
  * judgment that did not survive the reboot. This fixture transplants only
8
- * COMMITTED mapping evidence (the six shipped plans, in their byte-proven v2
9
- * re-spelling) onto a mechanical scaffold of the pinned v3 contract, declares
10
- * zero casualties, and lets every open representation decision show as open:
8
+ * COMMITTED mapping evidence — the six shipped plans in their byte-proven v2
9
+ * re-spelling, the T1 transparent-identity resolutions (src/t1.test.ts),
10
+ * the T2 item-mode collection plans (src/t2.test.ts), and the T3
11
+ * declared-join plans (src/t3.test.ts) — onto a mechanical
12
+ * scaffold of the pinned v3 contract, declares zero casualties, and lets
13
+ * every open decision show as open:
11
14
  *
12
- * 106 sub-components under 19 mapped compounds
13
- * 20 resolved — exactly the transplanted families (card 5, table 7,
14
- * alert-dialog 8)
15
- * 86 unresolved — real, deliberate, and the measure of the T1–T5 work
15
+ * 104 sub-components under 21 mapped compounds (contract 3.2.0: the
16
+ * dspack#40 correction moved the field wrapper trio right-side-up —
17
+ * field keeps 5 inner parts; field-set and field-group are compounds
18
+ * of their own with 1 sub each, so the denominator moved 106 → 104)
19
+ * 86 resolved — the transplanted families (card 5, table 7,
20
+ * alert-dialog 8), T1's form family (6), T2's
21
+ * radio-group (1) and select (7), T3's tabs (3),
22
+ * the A0 authoring pass (alert 3, avatar 5,
23
+ * scroll-area 2, field 5, field-set 1, field-group 1),
24
+ * and T4 (dialog 7, sheet 7, popover 6,
25
+ * dropdown-menu 12 — the last measured as data-shaped)
26
+ * 18 unresolved — real, deliberate: accordion (3), breadcrumb (6),
27
+ * pagination (6), tooltip (3) — the T6/upstream and
28
+ * deferred-shape tail
16
29
  *
17
30
  * The v2 contract gate refusing this fixture against the v3 contract is not a
18
31
  * failure; it is the fatal coverage gate doing on the production corpus
@@ -49,19 +62,19 @@ describe("the production-v3 evaluation fixture", () => {
49
62
  expect(profile.casualtyComponents).toEqual([]);
50
63
  });
51
64
 
52
- it("the fatal coverage gate refuses it against the v3 contract: 86 unresolved decisions, each pathed", () => {
65
+ it("the fatal coverage gate refuses it against the v3 contract: 18 unresolved decisions, each pathed", () => {
53
66
  try {
54
67
  transformFromJson(contract, { profile: loadProfile(structuredClone(fixtureJson)) });
55
- expect.unreachable("86 open representation decisions must refuse, not emit");
68
+ expect.unreachable("18 open representation decisions must refuse, not emit");
56
69
  } catch (e) {
57
70
  expect(e).toBeInstanceOf(ProfileContractError);
58
71
  const issues = (e as ProfileContractError).issues;
59
- expect(issues).toHaveLength(86);
72
+ expect(issues).toHaveLength(18);
60
73
  expect(issues.every((i) => i.message.includes("unresolved"))).toBe(true);
61
74
  }
62
75
  });
63
76
 
64
- it("derived coverage: 106 subs, 20 resolved by the transplanted families, 86 open", () => {
77
+ it("derived coverage: 104 subs, 86 resolved (transplants + T1-T4 + A0), 18 open", () => {
65
78
  const profile = loadProfile(structuredClone(fixtureJson));
66
79
  const byId = new Map(profile.components.map((p: ComponentPlan) => [p.dspackId, p]));
67
80
  let resolved = 0;
@@ -82,8 +95,8 @@ describe("the production-v3 evaluation fixture", () => {
82
95
  }
83
96
  }
84
97
  }
85
- expect(resolved + unresolved).toBe(106);
86
- expect(unresolved).toBe(86);
87
- expect(Object.fromEntries(resolvedByCompound)).toEqual({ card: 5, table: 7, "alert-dialog": 8 });
98
+ expect(resolved + unresolved).toBe(104);
99
+ expect(unresolved).toBe(18);
100
+ expect(Object.fromEntries(resolvedByCompound)).toEqual({ card: 5, table: 7, "alert-dialog": 8, form: 6, "radio-group": 1, select: 7, tabs: 3, alert: 3, avatar: 5, "scroll-area": 2, field: 5, "field-set": 1, "field-group": 1, dialog: 7, sheet: 7, popover: 6, "dropdown-menu": 12 });
88
101
  });
89
102
  });
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Instance diagnostics — two ratified fixes, proven fail-first:
3
+ *
4
+ * Fix 1 (gate A3, src/validate/ajv.ts): gate 3 used to validate every
5
+ * instance against `#/$defs/anyComponent` — a flat oneOf over ALL catalog
6
+ * components — with allErrors, so ONE missing prop yielded an error per
7
+ * OTHER branch (their const/required/unevaluatedProperties failures), all
8
+ * prefixed with the instance's own component#id. Branch-aware validation
9
+ * reports only the instance's own branch (semantically equivalent: every
10
+ * branch pins `component: {const: <name>}`), enriches messages from ajv
11
+ * params (enum/const/unevaluated), and carries a structured `errorDetails`
12
+ * channel preserving keyword/params for downstream UIs.
13
+ *
14
+ * Fix 2 (emitSurface, src/targets/a2ui/surface.ts): the emitter could
15
+ * produce instances that cannot validate against the very catalog they
16
+ * name — a required prop silently dropped at projection (authored
17
+ * `props.title` with no propMap), or an enum value passed through verbatim
18
+ * when no valueMap exists. emitSurface now refuses with one aggregated,
19
+ * causal message instead of emitting a catalog-invalid surface. Full-schema
20
+ * rigor stays gate A3's job (defense in depth); this guard covers
21
+ * required-presence and enum-membership, the observed defect class.
22
+ *
23
+ * The fixture is a minimal inline contract + v2 profile with three mapped
24
+ * components carrying DISTINCT required props (label / title / caption) and
25
+ * one enum prop (tone) — so cross-branch noise, if any, is detectable by
26
+ * name.
27
+ */
28
+ import { describe, expect, it } from "vitest";
29
+ import { transformFromJson } from "./transform/index.js";
30
+ import { loadProfile } from "./transform/profile-load.js";
31
+ import { emitSurface, EmitSurfaceError } from "./targets/a2ui/surface.js";
32
+ import type { DspackDoc, DspackSurface } from "./types.js";
33
+
34
+ const contract: DspackDoc = {
35
+ dspack: "0.4",
36
+ name: "mini-kit",
37
+ description: "Minimal inline contract for instance diagnostics.",
38
+ tokens: { color: { values: { primary: { value: "#3366ff", type: "color" } } } },
39
+ components: {
40
+ "text-field": { name: "TextField", description: "Single-line text input." },
41
+ alert: {
42
+ name: "Alert",
43
+ description: "Callout whose title comes from its alert-title sub-component.",
44
+ composition: { subComponents: [{ id: "alert-title" }] },
45
+ },
46
+ chip: {
47
+ name: "Chip",
48
+ description: "Small status marker with a tone.",
49
+ props: { tone: { type: "enum", values: ["info", "warning"], description: "Visual tone." } },
50
+ },
51
+ },
52
+ };
53
+
54
+ /** A v2 profile document mapping all three components. */
55
+ const profileDoc = (): Record<string, unknown> => ({
56
+ profileVersion: "2",
57
+ catalogTitle: "mini-kit — A2UI catalog",
58
+ catalogDescription: "Minimal catalog exercising branch-aware instance diagnostics.",
59
+ catalogIdBase: "https://example.test/catalogs/mini-kit",
60
+ instructions: "",
61
+ primaryColorToken: { category: "color", name: "primary" },
62
+ surfaceSynthesis: { textComponent: "Text", textProp: "text", wrapComponent: "Column", wrapChildrenProp: "children" },
63
+ synthesized: [],
64
+ casualtyComponents: [],
65
+ components: [
66
+ {
67
+ a2ui: "TextField",
68
+ dspackId: "text-field",
69
+ commons: ["ComponentCommon"],
70
+ structural: {
71
+ label: { schema: { type: "string" }, description: "The field label.", synthNote: "synthesized from node text" },
72
+ },
73
+ required: ["label"],
74
+ surface: { routes: [{ from: ["self.text"], to: "prop:label" }] },
75
+ },
76
+ {
77
+ a2ui: "Alert",
78
+ dspackId: "alert",
79
+ commons: ["ComponentCommon"],
80
+ structural: {
81
+ title: { schema: { type: "string" }, description: "The alert title.", synthNote: "from the alert-title sub-component" },
82
+ },
83
+ required: ["title"],
84
+ surface: { routes: [{ from: ["sub(alert-title).text"], to: "prop:title" }] },
85
+ },
86
+ {
87
+ a2ui: "Chip",
88
+ dspackId: "chip",
89
+ commons: ["ComponentCommon"],
90
+ structural: {
91
+ caption: { schema: { type: "string" }, description: "The chip caption.", synthNote: "synthesized from node text" },
92
+ },
93
+ // Deliberately NO valueMap: an authored tone passes through verbatim today.
94
+ propMap: { tone: { a2ui: "tone", kind: "enum", targetEnum: ["info", "warning"], description: "Visual tone." } },
95
+ required: ["caption"],
96
+ surface: { routes: [{ from: ["self.text"], to: "prop:caption" }] },
97
+ },
98
+ ],
99
+ });
100
+
101
+ const profile = () => loadProfile(profileDoc());
102
+
103
+ const surfaceOf = (root: unknown, intent = "diagnostics"): DspackSurface =>
104
+ ({ dspackSurface: "0.1", system: "mini-kit", intent, root }) as DspackSurface;
105
+
106
+ const messagesWith = (...instances: Array<Record<string, unknown>>) => ({
107
+ messages: [{ version: "v0.9", updateComponents: { surfaceId: "s", components: instances } }],
108
+ });
109
+
110
+ const instanceGate = (surface: unknown) => {
111
+ const out = transformFromJson(contract, { profile: profile(), surface });
112
+ return out.validation.gates.find((g) => g.name === "instance")!;
113
+ };
114
+
115
+ describe("gate A3 reports branch-scoped errors (fix 1)", () => {
116
+ it("an instance missing its ONE required prop gets own-branch errors only, not every other branch's noise", () => {
117
+ const gate = instanceGate(messagesWith({ id: "x", component: "TextField" }));
118
+ expect(gate.pass).toBe(false);
119
+ const errors = gate.errors ?? [];
120
+ // Branch-scoped: a handful of errors, not one per unrelated branch.
121
+ expect(errors.length).toBeGreaterThan(0);
122
+ expect(errors.length).toBeLessThanOrEqual(4);
123
+ for (const e of errors) {
124
+ // Every error names the instance itself…
125
+ expect(e).toContain("TextField#x");
126
+ // …and NONE leak the other components' branches: their names or their
127
+ // required props must not appear in a report about a TextField.
128
+ expect(e).not.toMatch(/\bAlert\b|\bChip\b|'title'|'caption'|"title"|"caption"/);
129
+ }
130
+ // The genuine error is reported: label is missing.
131
+ expect(errors.join("\n")).toMatch(/label/);
132
+ // Structured evidence rides alongside, preserving ajv keyword/params.
133
+ expect(gate.errorDetails).toBeDefined();
134
+ const detail = gate.errorDetails!.find((d) => d.instance === "TextField#x")!;
135
+ expect(detail).toBeDefined();
136
+ expect(detail.component).toBe("TextField");
137
+ expect(detail.id).toBe("x");
138
+ const required = detail.errors.find((e) => e.keyword === "required");
139
+ expect(required).toBeDefined();
140
+ expect((required!.params as { missingProperty?: string }).missingProperty).toBe("label");
141
+ });
142
+
143
+ it("an unknown component yields exactly ONE error naming it and the admitted count", () => {
144
+ const gate = instanceGate(messagesWith({ id: "z", component: "Zorp" }));
145
+ expect(gate.pass).toBe(false);
146
+ expect(gate.errors).toHaveLength(1);
147
+ expect(gate.errors![0]).toBe("Zorp#z: component 'Zorp' is not in this catalog (3 components admitted)");
148
+ });
149
+
150
+ it("an enum violation names the allowed values (enriched from ajv params)", () => {
151
+ const gate = instanceGate(
152
+ messagesWith({ id: "c", component: "Chip", caption: "Beta", tone: "loud" }),
153
+ );
154
+ expect(gate.pass).toBe(false);
155
+ const joined = (gate.errors ?? []).join("\n");
156
+ expect(joined).toMatch(/allowed: info, warning/);
157
+ });
158
+ });
159
+
160
+ describe("emitSurface refuses catalog-invalid instances (fix 2)", () => {
161
+ it("a required prop left unset by a dropped authored prop refuses — with the cause", () => {
162
+ // Authored `props.title` has no propMap on 'alert' (title comes from the
163
+ // alert-title sub-component), so today the prop drops with a warning and
164
+ // the emitted Alert instance is missing its required `title`.
165
+ const s = surfaceOf({ component: "alert", props: { title: "Heads up" } });
166
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(EmitSurfaceError);
167
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(/required prop 'title'/);
168
+ // The refusal explains the cause: the authored prop had no projection,
169
+ // and the value was expected from the sub-component.
170
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(/props\.title/);
171
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(/alert-title/);
172
+ });
173
+
174
+ it("an enum value outside the targetEnum refuses, naming the allowed values", () => {
175
+ // No valueMap on tone: the raw value would land verbatim on the instance
176
+ // and fail gate A3 downstream. Refuse at emission instead.
177
+ const s = surfaceOf({ component: "chip", text: "Beta", props: { tone: "loud" } });
178
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(EmitSurfaceError);
179
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(/tone/);
180
+ expect(() => emitSurface(s, contract, { profile: profile() })).toThrowError(/allowed: info, warning/);
181
+ });
182
+
183
+ it("fixture sanity: valid surfaces emit and pass every gate (true before and after the fixes)", () => {
184
+ for (const root of [
185
+ { component: "text-field", text: "Email" },
186
+ { component: "alert", children: [{ component: "alert-title", text: "Heads up" }] },
187
+ { component: "chip", text: "Beta", props: { tone: "info" } },
188
+ ]) {
189
+ const { messages } = emitSurface(surfaceOf(root), contract, { profile: profile() });
190
+ const out = transformFromJson(contract, { profile: profile(), surface: { messages } });
191
+ expect(out.validation.pass, `gates for ${root.component}`).toBe(true);
192
+ }
193
+ });
194
+ });