@aestheticfunction/dspack-emit 0.4.0 → 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 (74) 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 +8 -7
  20. package/dist/transform/profile-load.js +101 -24
  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/profile-schema.d.ts +8 -0
  24. package/dist/transform/profile-schema.js +382 -0
  25. package/dist/transform/profiles.d.ts +31 -1
  26. package/dist/transform/scaffold.d.ts +29 -12
  27. package/dist/transform/scaffold.js +91 -31
  28. package/dist/transform/shadcn-v2-respelling.d.ts +12 -0
  29. package/dist/transform/shadcn-v2-respelling.js +49 -0
  30. package/dist/transform/validate-v2.d.ts +36 -0
  31. package/dist/transform/validate-v2.js +100 -0
  32. package/dist/types.d.ts +19 -0
  33. package/dist/validate/ajv.js +98 -29
  34. package/dist/validate/meta/catalog-meta.d.ts +10 -0
  35. package/dist/validate/meta/catalog-meta.js +157 -0
  36. package/package.json +3 -3
  37. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  38. package/src/browser-boundary.test.ts +47 -0
  39. package/src/byte-neutral.test.ts +246 -0
  40. package/src/cli.ts +60 -0
  41. package/src/dangling-ref.test.ts +118 -0
  42. package/src/desugar.test.ts +162 -0
  43. package/src/engine-boundary.test.ts +248 -0
  44. package/src/eval-fixture.test.ts +89 -0
  45. package/src/functions.test.ts +182 -0
  46. package/src/index.ts +4 -1
  47. package/src/profile-load.test.ts +99 -1
  48. package/src/profile-v2.test.ts +363 -0
  49. package/src/review-findings.test.ts +292 -0
  50. package/src/schema-mirrors.test.ts +35 -0
  51. package/src/surface-fidelity.test.ts +213 -0
  52. package/src/targets/a2ui/diagnostics.ts +136 -0
  53. package/src/targets/a2ui/surface.ts +920 -242
  54. package/src/transform/desugar.ts +194 -0
  55. package/src/transform/emit.ts +65 -0
  56. package/src/transform/index.ts +5 -0
  57. package/src/transform/mapping.ts +42 -0
  58. package/src/transform/model.ts +325 -0
  59. package/src/transform/parse-v2.ts +397 -0
  60. package/src/transform/profile-load.ts +107 -28
  61. package/src/transform/profile-schema-v2.ts +430 -0
  62. package/src/transform/profile-schema.ts +382 -0
  63. package/src/transform/profile.v2.schema.json +422 -0
  64. package/src/transform/profiles.ts +32 -1
  65. package/src/transform/scaffold.ts +124 -47
  66. package/src/transform/shadcn-v2-respelling.ts +61 -0
  67. package/src/transform/validate-v2.ts +138 -0
  68. package/src/types.ts +20 -0
  69. package/src/validate/ajv.ts +91 -32
  70. package/src/validate/meta/catalog-meta.ts +167 -0
  71. package/src/validate-v2.test.ts +173 -0
  72. package/dist/transform/profile.v1.schema.json +0 -153
  73. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +0 -39
  74. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +0 -34
@@ -1,17 +1,34 @@
1
1
  /**
2
- * scaffoldProfile: a mechanical 1:1 draft Profile from a dspack contract.
2
+ * scaffoldProfile: a mechanical draft Profile from a dspack contract — in the
3
+ * v2 primitive language, honest about what it cannot decide.
3
4
  *
4
- * Seeded from the json-render CatalogModel (the judgment-free 1:1 IR): every
5
- * top-level contract component becomes a ComponentPlan with verbatim prop
6
- * projections; compound sub-components get subFlatten directives derived from
7
- * their *declared* `acceptsChildren` (text → asText, otherwise transparent).
5
+ * The old scaffold had two measured failures. For props-based contracts it
6
+ * emitted no surface plan at all, so any surface with children hit a hard
7
+ * throw — catalog-valid, surface-unusable, for exactly the idiom the docs
8
+ * call typical. And for compounds it INVENTED the judgment it should have
9
+ * surfaced: every sub auto-classified transparent-or-asText from
10
+ * `acceptsChildren`, which is precisely the guess that is wrong for a
11
+ * repeated item like `radio-group-item` (the measured T2 gap).
8
12
  *
9
- * The scaffold invents no judgment: no valueMaps, no casualties, no lossy
10
- * projections. Everything a human must review is returned as `notes` — the
11
- * scaffold's analog of dspack-export's `awaitingAuthorship`. The result is a
12
- * valid v1 profile document (loadProfile accepts it) whose transform passes
13
- * gates A1/A2 with full coverage; whether each mapping is *right* is the
14
- * author's call.
13
+ * This scaffold derives instead of guessing:
14
+ *
15
+ * - identity and verbatim prop projections, as before — provable 1:1;
16
+ * - a `children` route where the contract OBSERVABLY supports children:
17
+ * the component appears with child nodes in a worked example, or declares
18
+ * sub-components. Provenance lands in the synthNote;
19
+ * - a `text` route where a worked example shows the component carrying text;
20
+ * - sub-components are NOT decided. Each one is an explicit unresolved
21
+ * decision: listed in `notes`, recorded under `x-scaffold.unresolved`, and
22
+ * absent from the surface block — which the v2 contract gate then refuses
23
+ * to transform, per sub, until the author decides (route, collect,
24
+ * transparent, asText, or drop with a reason). A scaffold that transforms
25
+ * before those decisions exist would be inventing them.
26
+ *
27
+ * The result loads (loadProfile accepts it). For a contract with no compound
28
+ * sub-families it transforms immediately; for one with compounds, transform
29
+ * refuses with the exact per-sub checklist. That refusal is the deliverable:
30
+ * the scaffold's job is to make the remaining judgment explicit, not to
31
+ * pretend it has been exercised.
15
32
  */
16
33
  import type { DspackDoc, DspackProp } from "../types.js";
17
34
  import { buildCatalogModel, type CatalogComponent } from "../targets/json-render/model.js";
@@ -33,7 +50,7 @@ export interface ScaffoldNote {
33
50
  }
34
51
 
35
52
  export interface ScaffoldResult {
36
- /** A v1 profile *document* (includes profileVersion; loadProfile accepts it). */
53
+ /** A v2 profile *document* (includes profileVersion; loadProfile accepts it). */
37
54
  profile: Record<string, unknown>;
38
55
  /** Everything that needs human judgment before the profile is trustworthy. */
39
56
  notes: ScaffoldNote[];
@@ -41,7 +58,6 @@ export interface ScaffoldResult {
41
58
 
42
59
  const DYN_STRING = { $ref: "#/$defs/DynamicString" };
43
60
  const CHILD_LIST = { $ref: "#/$defs/ChildList" };
44
- const COMP_ID = { $ref: "#/$defs/ComponentId" };
45
61
 
46
62
  const TEXT_PLAN = {
47
63
  a2ui: "Text",
@@ -83,7 +99,6 @@ const COLUMN_PLAN = {
83
99
 
84
100
  interface SubDecl {
85
101
  id: string;
86
- acceptsChildren?: string;
87
102
  }
88
103
 
89
104
  function subsOf(doc: DspackDoc, id: string): SubDecl[] {
@@ -96,14 +111,46 @@ function subsOf(doc: DspackDoc, id: string): SubDecl[] {
96
111
  return out;
97
112
  }
98
113
 
114
+ interface Observation {
115
+ children?: string; // example id where the component was seen with child nodes
116
+ text?: string; // example id where it was seen carrying text
117
+ }
118
+
119
+ /**
120
+ * What the contract's own worked examples show each component doing. The
121
+ * example corpus is the contract's definition of "expressible", which makes
122
+ * this measurement, not judgment: a component observed with children needs a
123
+ * children story; one observed with text needs a text story.
124
+ */
125
+ function observeExamples(doc: DspackDoc): Map<string, Observation> {
126
+ const seen = new Map<string, Observation>();
127
+ const examples = (doc as { examples?: Array<{ id?: string; surface?: { root?: unknown } }> }).examples ?? [];
128
+ const visit = (node: unknown, exampleId: string): void => {
129
+ if (!node || typeof node !== "object") return;
130
+ const n = node as { component?: string; text?: unknown; children?: unknown[]; slots?: Record<string, unknown[]> };
131
+ if (typeof n.component === "string") {
132
+ const entry = seen.get(n.component) ?? {};
133
+ const childNodes = [...(n.children ?? []), ...Object.values(n.slots ?? {}).flat()];
134
+ if (childNodes.length > 0 && entry.children === undefined) entry.children = exampleId;
135
+ if (typeof n.text === "string" && entry.text === undefined) entry.text = exampleId;
136
+ seen.set(n.component, entry);
137
+ for (const child of childNodes) visit(child, exampleId);
138
+ }
139
+ };
140
+ for (const ex of examples) visit(ex.surface?.root, ex.id ?? "(unnamed example)");
141
+ return seen;
142
+ }
143
+
99
144
  export function scaffoldProfile(doc: DspackDoc, options: ScaffoldOptions): ScaffoldResult {
100
145
  const notes: ScaffoldNote[] = [];
101
146
  const model = buildCatalogModel(doc, {});
102
147
  const byId = new Map<string, CatalogComponent>(model.components.map((c) => [c.dspackId, c]));
103
148
  const topLevelIds = Object.keys(doc.components ?? {});
104
149
  const name = (id: string) => byId.get(id)?.name ?? id;
150
+ const observed = observeExamples(doc);
105
151
 
106
152
  const usedNames = new Set(topLevelIds.map((id) => name(id)));
153
+ const unresolvedByComponent: Record<string, string[]> = {};
107
154
 
108
155
  const components = topLevelIds.map((id) => {
109
156
  const entry = byId.get(id)!;
@@ -131,46 +178,68 @@ export function scaffoldProfile(doc: DspackDoc, options: ScaffoldOptions): Scaff
131
178
  .map(([propName]) => propName)
132
179
  .filter((propName) => propName in propMap);
133
180
 
181
+ const structural: Record<string, unknown> = {};
182
+ const routes: Array<Record<string, unknown>> = [];
183
+ const subs = subsOf(doc, id);
184
+ const seen = observed.get(id) ?? {};
185
+
186
+ // Children: only where the contract observably supports them — a worked
187
+ // example shows child nodes, or the component declares sub-components
188
+ // (whose instances arrive as its children in every surface).
189
+ const childrenBecause = seen.children
190
+ ? `observed with child nodes in worked example '${seen.children}'`
191
+ : subs.length > 0
192
+ ? `declares ${subs.length} sub-component(s), which arrive as its children in surfaces`
193
+ : undefined;
194
+ if (childrenBecause) {
195
+ structural.children = {
196
+ schema: CHILD_LIST,
197
+ description: "Child component IDs, in order.",
198
+ synthNote: `Scaffolded: ${childrenBecause}.`,
199
+ };
200
+ required.push("children");
201
+ routes.push({ from: ["children"], to: "slots:children" });
202
+ }
203
+
204
+ // Text: only where a worked example shows the component carrying it.
205
+ if (seen.text) {
206
+ structural.text = {
207
+ schema: DYN_STRING,
208
+ description: "The component's text content.",
209
+ synthNote: `Scaffolded: observed carrying text in worked example '${seen.text}'.`,
210
+ };
211
+ routes.push({ from: ["self.text"], to: "prop:text" });
212
+ }
213
+
214
+ if (!childrenBecause && !seen.text && Object.keys(propMap).length === 0) {
215
+ notes.push({
216
+ target: id,
217
+ note: "no declarative props, and never observed with children or text in a worked example; the contract likely needs enrichment before this mapping is useful.",
218
+ });
219
+ }
220
+
134
221
  const plan: Record<string, unknown> = {
135
222
  a2ui: entry.name,
136
223
  dspackId: id,
137
224
  commons: ["ComponentCommon"],
138
- structural: {},
225
+ structural,
139
226
  required,
140
227
  };
141
228
  if (Object.keys(propMap).length > 0) plan.propMap = propMap;
142
- else
143
- notes.push({
144
- target: id,
145
- note: "no declarative props were scaffolded; the contract likely needs prop enrichment before this mapping is useful.",
146
- });
229
+ if (routes.length > 0) plan.surface = { routes };
147
230
 
148
- const subs = subsOf(doc, id);
231
+ // Sub-components: explicit unresolved decisions, never guesses. The v2
232
+ // contract gate refuses to transform until each is decided — that refusal,
233
+ // with its per-sub checklist, is the scaffold handing judgment to its
234
+ // owner rather than exercising it.
149
235
  if (subs.length > 0) {
150
- const transparent = subs.filter((s) => s.acceptsChildren !== "text").map((s) => s.id);
151
- const asText = Object.fromEntries(subs.filter((s) => s.acceptsChildren === "text").map((s) => [s.id, "body"]));
152
- plan.structural = {
153
- child: {
154
- schema: COMP_ID,
155
- description: "The ID of the single child component. Wrap multiple elements in a Column and pass its ID.",
156
- synthNote:
157
- "Scaffolded: the compound's sub-components flatten (subFlatten) and collapse to a single, possibly Column-wrapped, child slot.",
158
- },
159
- };
160
- (plan.required as string[]).push("child");
161
- plan.surfacePlan = { childProp: "child", subFlatten: { transparent, asText } };
162
- plan.subCoverage = Object.fromEntries(
163
- subs.map((s) => [
164
- s.id,
165
- s.acceptsChildren === "text"
166
- ? "text -> synthesized Text (variant body) [scaffolded from acceptsChildren: text — review]"
167
- : "transparent grouping: children splice inline, in order [scaffolded — review]",
168
- ]),
169
- );
170
- notes.push({
171
- target: id,
172
- note: `compound scaffolded from declared acceptsChildren (${subs.length} sub-components: ${transparent.length} transparent, ${Object.keys(asText).length} asText); review each subCoverage line and pick text variants.`,
173
- });
236
+ unresolvedByComponent[id] = subs.map((s) => s.id);
237
+ for (const sub of subs) {
238
+ notes.push({
239
+ target: `${id}.${sub.id}`,
240
+ note: "unresolved sub-component: decide route (consume its text/label), collect (repeated items), transparent (dissolve), asText (re-identify), or drop (with a reason). transform() refuses until this is decided.",
241
+ });
242
+ }
174
243
  }
175
244
 
176
245
  return plan;
@@ -201,11 +270,11 @@ export function scaffoldProfile(doc: DspackDoc, options: ScaffoldOptions): Scaff
201
270
  }
202
271
 
203
272
  const profile: Record<string, unknown> = {
204
- profileVersion: "1",
273
+ profileVersion: "2",
205
274
  catalogTitle: options.catalogTitle ?? `${doc.name} — A2UI catalog (compiled from dspack)`,
206
275
  catalogDescription:
207
276
  options.catalogDescription ??
208
- `A2UI catalog compiled from the ${doc.name} dspack contract by scaffoldProfile. Mechanical 1:1 draft: review the scaffold notes before trusting any mapping.`,
277
+ `A2UI catalog compiled from the ${doc.name} dspack contract by scaffoldProfile. Mechanical draft in the v2 primitive language: review the scaffold notes, and resolve every listed sub-component decision, before trusting any mapping.`,
209
278
  catalogIdBase: options.catalogIdBase,
210
279
  instructions: options.instructions ?? "For layout, use the Column component to organize other components.",
211
280
  primaryColorToken,
@@ -218,6 +287,14 @@ export function scaffoldProfile(doc: DspackDoc, options: ScaffoldOptions): Scaff
218
287
  wrapComponent: "Column",
219
288
  wrapChildrenProp: "children",
220
289
  },
290
+ ...(Object.keys(unresolvedByComponent).length > 0
291
+ ? {
292
+ "x-scaffold": {
293
+ unresolved: unresolvedByComponent,
294
+ note: "Every listed sub-component is an authoring decision the scaffold deliberately did not make. transform() refuses until each is resolved in the owning plan's surface block.",
295
+ },
296
+ }
297
+ : {}),
221
298
  };
222
299
 
223
300
  notes.push({
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The shadcn plans' v2 re-spelling — the six shipped v1 surface plans written
3
+ * in the primitive language. Byte-proven equivalent: src/profile-v2.test.ts
4
+ * emits every pinned artifact identically through these blocks.
5
+ *
6
+ * Shared by the keystone test and by eval/build-eval-profile.mjs, which
7
+ * transplants them onto a scaffold of the production v3 contract to build the
8
+ * reproducible coverage-evaluation fixture. One source, two consumers — the
9
+ * respelling is committed mapping evidence, not per-file copies.
10
+ */
11
+ import type { SurfaceV2 } from "./parse-v2.js";
12
+
13
+ export const SHADCN_V2_SURFACES: Record<string, SurfaceV2> = {
14
+ button: {
15
+ routes: [
16
+ { from: ["self.text"], to: "textChild:child", overwrite: true },
17
+ { from: ["synthesized.action"], to: "action:action" },
18
+ ],
19
+ },
20
+ card: {
21
+ routes: [{ from: ["children"], to: "slot:child" }],
22
+ subs: {
23
+ "card-header": "transparent",
24
+ "card-content": "transparent",
25
+ "card-footer": "transparent",
26
+ "card-title": { asText: "h3" },
27
+ "card-description": { asText: "caption" },
28
+ },
29
+ },
30
+ input: {
31
+ routes: [{ from: ["self.text"], to: "prop:label", overwrite: true }],
32
+ },
33
+ badge: {
34
+ routes: [{ from: ["self.text"], to: "prop:label", overwrite: true }],
35
+ },
36
+ table: {
37
+ routes: [
38
+ { from: ["self.props.caption"], to: "prop:caption" },
39
+ { from: ["self.props.columns"], to: "prop:columns" },
40
+ { from: ["self.props.rows"], to: "prop:rows" },
41
+ { from: ["sub(table-caption).subtreeText"], to: "prop:caption" },
42
+ ],
43
+ collects: [
44
+ { of: ["table-header"], into: "prop:columns", shape: "flat", row: ["table-row"], cells: ["table-cell", "table-head"] },
45
+ { of: ["table-body"], into: "prop:rows", shape: "records", field: "cells", row: ["table-row"], cells: ["table-cell", "table-head"] },
46
+ ],
47
+ subs: {
48
+ "table-footer": { drop: "summary rows have no slot in the synthesized caption/columns/rows shape" },
49
+ },
50
+ },
51
+ "alert-dialog": {
52
+ routes: [
53
+ { from: ["sub(alert-dialog-title).text"], to: "prop:title" },
54
+ { from: ["sub(alert-dialog-description).text"], to: "prop:description" },
55
+ { from: ["sub(alert-dialog-cancel).text"], to: "prop:cancelLabel" },
56
+ { from: ["sub(alert-dialog-action).text"], to: "prop:confirmLabel" },
57
+ { from: ["sub(alert-dialog-trigger).label", "sub(alert-dialog-trigger).firstText"], to: "prop:triggerLabel" },
58
+ { from: ["synthesized.action"], to: "action:action" },
59
+ ],
60
+ },
61
+ };
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Contract-facing validation for v2 profiles.
3
+ *
4
+ * parse-v2.ts checks everything a plan can be wrong about ON ITS OWN — grammar
5
+ * closure, declared destinations, write conflicts. This module checks what a
6
+ * plan can only be wrong about AGAINST A CONTRACT, and it runs at every entry
7
+ * that has one in hand (transform, emitSurface), before any emission:
8
+ *
9
+ * - every `sub(x)` a route, collect, or disposition names must be a declared
10
+ * sub-component of the plan's contract component;
11
+ * - every `self.props.X` must be declared — by the contract as an ordinary
12
+ * prop, or by the plan's own structural block as a same-named passthrough;
13
+ * - derived sub-component coverage must be COMPLETE: every declared sub is
14
+ * routed, collected, absorbed, transparent, re-identified, or explicitly
15
+ * dropped — anything else is an unresolved authoring decision, and v2
16
+ * fails closed on it with a finding per sub.
17
+ *
18
+ * v1 is deliberately not gated here: its behaviour is frozen, and its
19
+ * coverage story stays report-plus-`--strict-coverage`. The split is the
20
+ * compatibility policy in one sentence — v2 refuses what v1 merely reports.
21
+ */
22
+ import type { DspackDoc } from "../types.js";
23
+ import type { Profile } from "./profiles.js";
24
+ import { surfaceModelOf } from "./desugar.js";
25
+ import { referencedSubs, unclassifiedSubs, type SurfaceModel } from "./model.js";
26
+
27
+ export interface ProfileContractIssue {
28
+ path: string;
29
+ message: string;
30
+ }
31
+
32
+ export class ProfileContractError extends Error {
33
+ constructor(readonly issues: ProfileContractIssue[]) {
34
+ super(
35
+ `profile does not fit this contract (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
36
+ issues
37
+ .slice(0, 3)
38
+ .map((i) => `${i.path || "$"}: ${i.message}`)
39
+ .join("; ") +
40
+ (issues.length > 3 ? "; …" : ""),
41
+ );
42
+ this.name = "ProfileContractError";
43
+ }
44
+ }
45
+
46
+ interface ContractComponent {
47
+ props?: Record<string, unknown>;
48
+ composition?: { subComponents?: Array<{ id: string }> };
49
+ }
50
+
51
+ /** Every sub-component id a model's selectors, collects, and subs name. */
52
+ function namedSubs(model: SurfaceModel): Set<string> {
53
+ const out = new Set<string>(referencedSubs(model).keys());
54
+ return out;
55
+ }
56
+
57
+ /** Every `self.props.X` a model reads, with the destination reading it. */
58
+ function namedSelfProps(model: SurfaceModel): Array<{ prop: string; to: string }> {
59
+ const out: Array<{ prop: string; to: string }> = [];
60
+ for (const r of model.routes) {
61
+ for (const s of r.from) if (s.kind === "self-prop") out.push({ prop: s.prop, to: r.to.name });
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /**
67
+ * Validate a v2 profile against the contract it is about to project. A no-op
68
+ * for v1 profiles (language undefined): their behaviour is frozen.
69
+ */
70
+ export function validateProfileAgainstContract(profile: Profile, doc: DspackDoc): void {
71
+ if (profile.language !== "v2") return;
72
+
73
+ const issues: ProfileContractIssue[] = [];
74
+ const components = (doc.components ?? {}) as Record<string, ContractComponent>;
75
+
76
+ // Both collections: mapping.ts counts any synthesized plan with a dspackId
77
+ // as mapped, so the gate must see exactly what the mapper sees. And a plan
78
+ // with NO surface block validates against the empty model — for a compound,
79
+ // that means every declared sub is unresolved and refuses, identically to
80
+ // `surface: {}`. Presence of an empty key must never flip the gate.
81
+ const collections: Array<["components" | "synthesized", typeof profile.components]> = [
82
+ ["components", profile.components],
83
+ ["synthesized", profile.synthesized],
84
+ ];
85
+ for (const [collection, plans] of collections) {
86
+ for (const [i, plan] of plans.entries()) {
87
+ if (!plan.dspackId) continue;
88
+ const at = `/${collection}/${i}/surface`;
89
+ const component = components[plan.dspackId];
90
+ if (!component) continue; // mapping.ts already warns on unknown dspackIds
91
+
92
+ const declaredSubs = (component.composition?.subComponents ?? []).map((s) => s.id);
93
+ const declaredProps = new Set(Object.keys(component.props ?? {}));
94
+ const model = surfaceModelOf(plan);
95
+
96
+ for (const sub of namedSubs(model)) {
97
+ if (!declaredSubs.includes(sub)) {
98
+ issues.push({
99
+ path: at,
100
+ message: `'${sub}' is not a declared sub-component of '${plan.dspackId}' in this contract (declared: ${declaredSubs.length ? declaredSubs.join(", ") : "none"})`,
101
+ });
102
+ }
103
+ }
104
+
105
+ // A self-prop read is declared either by the CONTRACT (an ordinary prop)
106
+ // or by the PLAN's own structural block when source and destination share
107
+ // its name — the passthrough shape, where an A2UI structural slot may be
108
+ // authored directly on the surface node (v1's structuralPassthrough, and
109
+ // the reason the Table's caption/columns/rows are legal without the
110
+ // contract declaring them). Reading an undeclared prop into a
111
+ // DIFFERENTLY-named destination declares nothing anywhere, and refuses.
112
+ for (const { prop, to } of namedSelfProps(model)) {
113
+ const contractDeclared = declaredProps.has(prop);
114
+ const passthroughShaped = to === prop && prop in (plan.structural ?? {});
115
+ if (!contractDeclared && !passthroughShaped) {
116
+ issues.push({
117
+ path: at,
118
+ message: `self.props.${prop} reads a prop '${plan.dspackId}' does not declare in this contract, and it is not a same-named structural passthrough`,
119
+ });
120
+ }
121
+ }
122
+
123
+ // Derived coverage, enforced. The measured gates behind making this fatal:
124
+ // pinned shadcn v2.3.0, astryx and acme all derive zero-unresolved, and
125
+ // the production v3 pair's single finding (radio-group -> radio-group-item)
126
+ // is the known T2 gap — see scripts/sub-coverage-report.mjs and the
127
+ // 2aac076 measurement record.
128
+ for (const sub of unclassifiedSubs(model, declaredSubs)) {
129
+ issues.push({
130
+ path: at,
131
+ message: `sub-component '${sub}' of '${plan.dspackId}' is unresolved: no route consumes it, no collect gathers it, no disposition dissolves or drops it. Decide it — route, collect, transparent, asText, or drop with a reason.`,
132
+ });
133
+ }
134
+ }
135
+ }
136
+
137
+ if (issues.length > 0) throw new ProfileContractError(issues);
138
+ }
package/src/types.ts CHANGED
@@ -109,6 +109,26 @@ export type A2uiVersion = "0.9.1" | "1.0";
109
109
  // Fidelity reporting
110
110
  // ---------------------------------------------------------------------------
111
111
 
112
+ /**
113
+ * What one surface transformation DID — the per-emission ledger, distinct
114
+ * from the catalog-level FidelityEntry below (which describes what a profile
115
+ * can carry in principle; this describes what one surface actually lost or
116
+ * gained). Additive channel: messages and warnings are byte-frozen for v1,
117
+ * so fidelity rides alongside them on EmitSurfaceResult, never inside them.
118
+ */
119
+ export interface SurfaceFidelityEntry {
120
+ /** Where in the surface the content came from (JSON path, plus selector). */
121
+ source: string;
122
+ /** Where on the emitted instance it landed, or "(discarded)". */
123
+ destination: string;
124
+ /** The profile rule that caused it (route/collect origin, propMap key, or synthesis). */
125
+ origin: string;
126
+ /** What happened to the content. */
127
+ kind: "projected" | "moved" | "lifted" | "flattened" | "synthesized" | "wrapped" | "dropped" | "deduplicated";
128
+ class: FidelityClass;
129
+ note?: string;
130
+ }
131
+
112
132
  export type FidelityClass =
113
133
  | "maps-cleanly"
114
134
  | "synthesis-defaults"
@@ -3,19 +3,20 @@
3
3
  * approach A2UI uses in specification/scripts/validate.py
4
4
  * (draft 2020-12, strict:false, ajv-formats):
5
5
  *
6
- * 1. schema-compile + no-external-ref: ajv compiles the catalog AS a JSON Schema.
7
- * Compilation fails on any unresolved `$ref`, proving the catalog is a valid,
8
- * fully self-contained schema with zero external references.
6
+ * 1. schema-compile + no-external-ref: ajv compiles the catalog AS a JSON
7
+ * Schema, no `$ref` points outside it, and — because ajv defers ref
8
+ * resolution past compile() — every internal `$ref` is resolved by this
9
+ * gate itself, so a dangling pointer is a pathed finding here rather than
10
+ * a silent pass or a raw MissingRefError out of gate 3.
9
11
  * 2. catalog-shape: the catalog validates against the version-specific
10
12
  * a2ui-catalog.meta.<ver>.json (the literal "catalog schema" check; this is what
11
13
  * makes v0.9.1 vs v1.0 conformance distinct — theme vs surfaceProperties).
12
14
  * 3. instance: every component instance in the hand-authored surface validates
13
15
  * against the catalog's own #/$defs/anyComponent.
14
16
  */
15
- import { readFileSync } from "node:fs";
16
- import { fileURLToPath } from "node:url";
17
17
  import Ajv2020 from "ajv/dist/2020.js";
18
18
  import addFormats from "ajv-formats";
19
+ import { catalogMetaSchemas } from "./meta/catalog-meta.js";
19
20
  import type { A2uiCatalog, A2uiVersion, Json } from "../types.js";
20
21
 
21
22
  export interface GateResult {
@@ -31,9 +32,6 @@ export interface ValidationReport {
31
32
  gates: GateResult[];
32
33
  }
33
34
 
34
- const metaPath = (ver: A2uiVersion): string =>
35
- fileURLToPath(new URL(`./meta/a2ui-catalog.meta.${ver === "0.9.1" ? "0_9_1" : "1_0"}.json`, import.meta.url));
36
-
37
35
  function newAjv(): Ajv2020 {
38
36
  const ajv = new Ajv2020({ strict: false, allErrors: true, validateFormats: true });
39
37
  addFormats(ajv);
@@ -53,6 +51,55 @@ function externalRefs(node: unknown, acc: string[] = []): string[] {
53
51
  return acc;
54
52
  }
55
53
 
54
+ /**
55
+ * Collect every INTERNAL `$ref` that does not resolve inside the catalog
56
+ * document, with the JSON path of the offending `$ref` keyword.
57
+ *
58
+ * This is what makes gate 1's documented guarantee true. ajv defers ref
59
+ * resolution past `compile()`, so a structural slot schema (or any other
60
+ * authored-schema channel) carrying `{$ref: "#/$defs/DoesNotExist"}` used to
61
+ * produce either all-gates-PASS (no instances checked) or a raw
62
+ * MissingRefError thrown out of gate 3 — pass-or-crash, never a finding.
63
+ * Resolving the pointers ourselves turns the whole class into a pathed gate
64
+ * failure at one boundary, for every channel at once.
65
+ */
66
+ function danglingInternalRefs(root: unknown): string[] {
67
+ const bad: string[] = [];
68
+ const resolves = (pointer: string): boolean => {
69
+ if (pointer === "#" || pointer === "#/") return true;
70
+ if (!pointer.startsWith("#/")) return false; // #foo anchors are not used in our catalogs
71
+ let node: unknown = root;
72
+ for (const raw of pointer.slice(2).split("/")) {
73
+ const key = decodeURIComponent(raw).replaceAll("~1", "/").replaceAll("~0", "~");
74
+ if (Array.isArray(node)) {
75
+ const i = Number(key);
76
+ if (!Number.isInteger(i) || i < 0 || i >= node.length) return false;
77
+ node = node[i];
78
+ } else if (node && typeof node === "object" && key in (node as Record<string, unknown>)) {
79
+ node = (node as Record<string, unknown>)[key];
80
+ } else {
81
+ return false;
82
+ }
83
+ }
84
+ return true;
85
+ };
86
+ const walk = (node: unknown, at: string): void => {
87
+ if (Array.isArray(node)) {
88
+ node.forEach((n, i) => walk(n, `${at}/${i}`));
89
+ } else if (node && typeof node === "object") {
90
+ for (const [k, v] of Object.entries(node)) {
91
+ if (k === "$ref" && typeof v === "string" && v.startsWith("#") && !resolves(v)) {
92
+ bad.push(`${at}/$ref: '${v}' does not resolve inside this catalog`);
93
+ } else {
94
+ walk(v, `${at}/${k}`);
95
+ }
96
+ }
97
+ }
98
+ };
99
+ walk(root, "");
100
+ return bad;
101
+ }
102
+
56
103
  /** Pull every component instance (object with string `component` + `id`) from a surface. */
57
104
  export function extractInstances(surface: unknown, acc: Json[] = []): Json[] {
58
105
  if (Array.isArray(surface)) {
@@ -72,8 +119,9 @@ export function validateCatalog(
72
119
  ): ValidationReport {
73
120
  const gates: GateResult[] = [];
74
121
 
75
- // Gate 1 — schema compile + no external $ref.
122
+ // Gate 1 — schema compile + no external $ref + every internal $ref resolves.
76
123
  const exts = externalRefs(catalog);
124
+ const dangling = danglingInternalRefs(catalog);
77
125
  let compiled = false;
78
126
  let compileErr = "";
79
127
  try {
@@ -82,20 +130,22 @@ export function validateCatalog(
82
130
  } catch (e) {
83
131
  compileErr = e instanceof Error ? e.message : String(e);
84
132
  }
133
+ const selfContained = compiled && exts.length === 0 && dangling.length === 0;
85
134
  gates.push({
86
135
  name: "schema-compile + no-external-ref",
87
- pass: compiled && exts.length === 0,
88
- detail:
89
- compiled && exts.length === 0
90
- ? "Catalog compiles as a draft-2020-12 JSON Schema with only internal $refs."
91
- : !compiled
92
- ? `ajv failed to compile the catalog as a schema: ${compileErr}`
93
- : `Catalog contains external $refs: ${[...new Set(exts)].join(", ")}`,
94
- errors: exts.length ? [...new Set(exts)] : undefined,
136
+ pass: selfContained,
137
+ detail: selfContained
138
+ ? "Catalog compiles as a draft-2020-12 JSON Schema; every $ref is internal and resolves."
139
+ : !compiled
140
+ ? `ajv failed to compile the catalog as a schema: ${compileErr}`
141
+ : exts.length
142
+ ? `Catalog contains external $refs: ${[...new Set(exts)].join(", ")}`
143
+ : `Catalog is not self-contained: ${dangling.length} internal $ref(s) do not resolve.`,
144
+ errors: exts.length ? [...new Set(exts)] : dangling.length ? dangling : undefined,
95
145
  });
96
146
 
97
147
  // Gate 2 — catalog shape.
98
- const meta = JSON.parse(readFileSync(metaPath(version), "utf8")) as Json;
148
+ const meta = catalogMetaSchemas[version];
99
149
  const validateShape = newAjv().compile(meta);
100
150
  const shapeOk = validateShape(catalog) as boolean;
101
151
  gates.push({
@@ -107,29 +157,38 @@ export function validateCatalog(
107
157
  errors: shapeOk ? undefined : (validateShape.errors ?? []).map(fmtErr),
108
158
  });
109
159
 
110
- // Gate 3 — instances (only if compilable and a surface was supplied).
160
+ // Gate 3 — instances (only if the catalog is usable and a surface was supplied).
111
161
  if (surface !== undefined) {
112
- if (!compiled) {
162
+ if (!compiled || dangling.length > 0) {
113
163
  gates.push({
114
164
  name: "instance",
115
165
  pass: false,
116
- detail: "Skipped: catalog did not compile, so instances cannot be checked.",
166
+ detail: !compiled
167
+ ? "Skipped: catalog did not compile, so instances cannot be checked."
168
+ : "Skipped: catalog is not self-contained (gate 1 lists the dangling $refs), so instances cannot be checked.",
117
169
  });
118
170
  } else {
119
- const ajv = newAjv();
120
- ajv.addSchema(catalog as unknown as Json, catalog.$id);
121
- const validateAny = ajv.getSchema(`${catalog.$id}#/$defs/anyComponent`);
122
- const instances = extractInstances(surface);
171
+ // Belt and braces: gate 1 has already proven every ref resolves, but a
172
+ // raw ajv throw must never escape this function regardless.
123
173
  const failures: string[] = [];
124
- if (!validateAny) {
125
- failures.push("Could not resolve #/$defs/anyComponent from the catalog.");
126
- } else {
127
- for (const inst of instances) {
128
- if (!validateAny(inst)) {
129
- const where = `${inst.component}#${inst.id}`;
130
- for (const e of validateAny.errors ?? []) failures.push(`${where}: ${fmtErr(e)}`);
174
+ let instances: Json[] = [];
175
+ try {
176
+ const ajv = newAjv();
177
+ ajv.addSchema(catalog as unknown as Json, catalog.$id);
178
+ const validateAny = ajv.getSchema(`${catalog.$id}#/$defs/anyComponent`);
179
+ instances = extractInstances(surface);
180
+ if (!validateAny) {
181
+ failures.push("Could not resolve #/$defs/anyComponent from the catalog.");
182
+ } else {
183
+ for (const inst of instances) {
184
+ if (!validateAny(inst)) {
185
+ const where = `${inst.component}#${inst.id}`;
186
+ for (const e of validateAny.errors ?? []) failures.push(`${where}: ${fmtErr(e)}`);
187
+ }
131
188
  }
132
189
  }
190
+ } catch (e) {
191
+ failures.push(`instance validation could not run: ${e instanceof Error ? e.message : String(e)}`);
133
192
  }
134
193
  gates.push({
135
194
  name: "instance",