@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
@@ -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 } from "../types.js";
17
34
  export interface ScaffoldOptions {
@@ -32,7 +49,7 @@ export interface ScaffoldNote {
32
49
  note: string;
33
50
  }
34
51
  export interface ScaffoldResult {
35
- /** A v1 profile *document* (includes profileVersion; loadProfile accepts it). */
52
+ /** A v2 profile *document* (includes profileVersion; loadProfile accepts it). */
36
53
  profile: Record<string, unknown>;
37
54
  /** Everything that needs human judgment before the profile is trustworthy. */
38
55
  notes: ScaffoldNote[];
@@ -1,7 +1,6 @@
1
1
  import { buildCatalogModel } from "../targets/json-render/model.js";
2
2
  const DYN_STRING = { $ref: "#/$defs/DynamicString" };
3
3
  const CHILD_LIST = { $ref: "#/$defs/ChildList" };
4
- const COMP_ID = { $ref: "#/$defs/ComponentId" };
5
4
  const TEXT_PLAN = {
6
5
  a2ui: "Text",
7
6
  commons: ["ComponentCommon"],
@@ -48,13 +47,44 @@ function subsOf(doc, id) {
48
47
  }
49
48
  return out;
50
49
  }
50
+ /**
51
+ * What the contract's own worked examples show each component doing. The
52
+ * example corpus is the contract's definition of "expressible", which makes
53
+ * this measurement, not judgment: a component observed with children needs a
54
+ * children story; one observed with text needs a text story.
55
+ */
56
+ function observeExamples(doc) {
57
+ const seen = new Map();
58
+ const examples = doc.examples ?? [];
59
+ const visit = (node, exampleId) => {
60
+ if (!node || typeof node !== "object")
61
+ return;
62
+ const n = node;
63
+ if (typeof n.component === "string") {
64
+ const entry = seen.get(n.component) ?? {};
65
+ const childNodes = [...(n.children ?? []), ...Object.values(n.slots ?? {}).flat()];
66
+ if (childNodes.length > 0 && entry.children === undefined)
67
+ entry.children = exampleId;
68
+ if (typeof n.text === "string" && entry.text === undefined)
69
+ entry.text = exampleId;
70
+ seen.set(n.component, entry);
71
+ for (const child of childNodes)
72
+ visit(child, exampleId);
73
+ }
74
+ };
75
+ for (const ex of examples)
76
+ visit(ex.surface?.root, ex.id ?? "(unnamed example)");
77
+ return seen;
78
+ }
51
79
  export function scaffoldProfile(doc, options) {
52
80
  const notes = [];
53
81
  const model = buildCatalogModel(doc, {});
54
82
  const byId = new Map(model.components.map((c) => [c.dspackId, c]));
55
83
  const topLevelIds = Object.keys(doc.components ?? {});
56
84
  const name = (id) => byId.get(id)?.name ?? id;
85
+ const observed = observeExamples(doc);
57
86
  const usedNames = new Set(topLevelIds.map((id) => name(id)));
87
+ const unresolvedByComponent = {};
58
88
  const components = topLevelIds.map((id) => {
59
89
  const entry = byId.get(id);
60
90
  const contractProps = (doc.components?.[id]?.props ?? {});
@@ -82,43 +112,65 @@ export function scaffoldProfile(doc, options) {
82
112
  .filter(([, p]) => p.required === true)
83
113
  .map(([propName]) => propName)
84
114
  .filter((propName) => propName in propMap);
115
+ const structural = {};
116
+ const routes = [];
117
+ const subs = subsOf(doc, id);
118
+ const seen = observed.get(id) ?? {};
119
+ // Children: only where the contract observably supports them — a worked
120
+ // example shows child nodes, or the component declares sub-components
121
+ // (whose instances arrive as its children in every surface).
122
+ const childrenBecause = seen.children
123
+ ? `observed with child nodes in worked example '${seen.children}'`
124
+ : subs.length > 0
125
+ ? `declares ${subs.length} sub-component(s), which arrive as its children in surfaces`
126
+ : undefined;
127
+ if (childrenBecause) {
128
+ structural.children = {
129
+ schema: CHILD_LIST,
130
+ description: "Child component IDs, in order.",
131
+ synthNote: `Scaffolded: ${childrenBecause}.`,
132
+ };
133
+ required.push("children");
134
+ routes.push({ from: ["children"], to: "slots:children" });
135
+ }
136
+ // Text: only where a worked example shows the component carrying it.
137
+ if (seen.text) {
138
+ structural.text = {
139
+ schema: DYN_STRING,
140
+ description: "The component's text content.",
141
+ synthNote: `Scaffolded: observed carrying text in worked example '${seen.text}'.`,
142
+ };
143
+ routes.push({ from: ["self.text"], to: "prop:text" });
144
+ }
145
+ if (!childrenBecause && !seen.text && Object.keys(propMap).length === 0) {
146
+ notes.push({
147
+ target: id,
148
+ 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.",
149
+ });
150
+ }
85
151
  const plan = {
86
152
  a2ui: entry.name,
87
153
  dspackId: id,
88
154
  commons: ["ComponentCommon"],
89
- structural: {},
155
+ structural,
90
156
  required,
91
157
  };
92
158
  if (Object.keys(propMap).length > 0)
93
159
  plan.propMap = propMap;
94
- else
95
- notes.push({
96
- target: id,
97
- note: "no declarative props were scaffolded; the contract likely needs prop enrichment before this mapping is useful.",
98
- });
99
- const subs = subsOf(doc, id);
160
+ if (routes.length > 0)
161
+ plan.surface = { routes };
162
+ // Sub-components: explicit unresolved decisions, never guesses. The v2
163
+ // contract gate refuses to transform until each is decided — that refusal,
164
+ // with its per-sub checklist, is the scaffold handing judgment to its
165
+ // owner rather than exercising it.
100
166
  if (subs.length > 0) {
101
- const transparent = subs.filter((s) => s.acceptsChildren !== "text").map((s) => s.id);
102
- const asText = Object.fromEntries(subs.filter((s) => s.acceptsChildren === "text").map((s) => [s.id, "body"]));
103
- plan.structural = {
104
- child: {
105
- schema: COMP_ID,
106
- description: "The ID of the single child component. Wrap multiple elements in a Column and pass its ID.",
107
- synthNote: "Scaffolded: the compound's sub-components flatten (subFlatten) and collapse to a single, possibly Column-wrapped, child slot.",
108
- },
109
- };
110
- plan.required.push("child");
111
- plan.surfacePlan = { childProp: "child", subFlatten: { transparent, asText } };
112
- plan.subCoverage = Object.fromEntries(subs.map((s) => [
113
- s.id,
114
- s.acceptsChildren === "text"
115
- ? "text -> synthesized Text (variant body) [scaffolded from acceptsChildren: text — review]"
116
- : "transparent grouping: children splice inline, in order [scaffolded — review]",
117
- ]));
118
- notes.push({
119
- target: id,
120
- 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.`,
121
- });
167
+ unresolvedByComponent[id] = subs.map((s) => s.id);
168
+ for (const sub of subs) {
169
+ notes.push({
170
+ target: `${id}.${sub.id}`,
171
+ 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.",
172
+ });
173
+ }
122
174
  }
123
175
  return plan;
124
176
  });
@@ -146,10 +198,10 @@ export function scaffoldProfile(doc, options) {
146
198
  });
147
199
  }
148
200
  const profile = {
149
- profileVersion: "1",
201
+ profileVersion: "2",
150
202
  catalogTitle: options.catalogTitle ?? `${doc.name} — A2UI catalog (compiled from dspack)`,
151
203
  catalogDescription: options.catalogDescription ??
152
- `A2UI catalog compiled from the ${doc.name} dspack contract by scaffoldProfile. Mechanical 1:1 draft: review the scaffold notes before trusting any mapping.`,
204
+ `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.`,
153
205
  catalogIdBase: options.catalogIdBase,
154
206
  instructions: options.instructions ?? "For layout, use the Column component to organize other components.",
155
207
  primaryColorToken,
@@ -162,6 +214,14 @@ export function scaffoldProfile(doc, options) {
162
214
  wrapComponent: "Column",
163
215
  wrapChildrenProp: "children",
164
216
  },
217
+ ...(Object.keys(unresolvedByComponent).length > 0
218
+ ? {
219
+ "x-scaffold": {
220
+ unresolved: unresolvedByComponent,
221
+ 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.",
222
+ },
223
+ }
224
+ : {}),
165
225
  };
166
226
  notes.push({
167
227
  target: "casualtyComponents",
@@ -0,0 +1,12 @@
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
+ export declare const SHADCN_V2_SURFACES: Record<string, SurfaceV2>;
@@ -0,0 +1,49 @@
1
+ export const SHADCN_V2_SURFACES = {
2
+ button: {
3
+ routes: [
4
+ { from: ["self.text"], to: "textChild:child", overwrite: true },
5
+ { from: ["synthesized.action"], to: "action:action" },
6
+ ],
7
+ },
8
+ card: {
9
+ routes: [{ from: ["children"], to: "slot:child" }],
10
+ subs: {
11
+ "card-header": "transparent",
12
+ "card-content": "transparent",
13
+ "card-footer": "transparent",
14
+ "card-title": { asText: "h3" },
15
+ "card-description": { asText: "caption" },
16
+ },
17
+ },
18
+ input: {
19
+ routes: [{ from: ["self.text"], to: "prop:label", overwrite: true }],
20
+ },
21
+ badge: {
22
+ routes: [{ from: ["self.text"], to: "prop:label", overwrite: true }],
23
+ },
24
+ table: {
25
+ routes: [
26
+ { from: ["self.props.caption"], to: "prop:caption" },
27
+ { from: ["self.props.columns"], to: "prop:columns" },
28
+ { from: ["self.props.rows"], to: "prop:rows" },
29
+ { from: ["sub(table-caption).subtreeText"], to: "prop:caption" },
30
+ ],
31
+ collects: [
32
+ { of: ["table-header"], into: "prop:columns", shape: "flat", row: ["table-row"], cells: ["table-cell", "table-head"] },
33
+ { of: ["table-body"], into: "prop:rows", shape: "records", field: "cells", row: ["table-row"], cells: ["table-cell", "table-head"] },
34
+ ],
35
+ subs: {
36
+ "table-footer": { drop: "summary rows have no slot in the synthesized caption/columns/rows shape" },
37
+ },
38
+ },
39
+ "alert-dialog": {
40
+ routes: [
41
+ { from: ["sub(alert-dialog-title).text"], to: "prop:title" },
42
+ { from: ["sub(alert-dialog-description).text"], to: "prop:description" },
43
+ { from: ["sub(alert-dialog-cancel).text"], to: "prop:cancelLabel" },
44
+ { from: ["sub(alert-dialog-action).text"], to: "prop:confirmLabel" },
45
+ { from: ["sub(alert-dialog-trigger).label", "sub(alert-dialog-trigger).firstText"], to: "prop:triggerLabel" },
46
+ { from: ["synthesized.action"], to: "action:action" },
47
+ ],
48
+ },
49
+ };
@@ -0,0 +1,36 @@
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
+ export interface ProfileContractIssue {
25
+ path: string;
26
+ message: string;
27
+ }
28
+ export declare class ProfileContractError extends Error {
29
+ readonly issues: ProfileContractIssue[];
30
+ constructor(issues: ProfileContractIssue[]);
31
+ }
32
+ /**
33
+ * Validate a v2 profile against the contract it is about to project. A no-op
34
+ * for v1 profiles (language undefined): their behaviour is frozen.
35
+ */
36
+ export declare function validateProfileAgainstContract(profile: Profile, doc: DspackDoc): void;
@@ -0,0 +1,100 @@
1
+ import { surfaceModelOf } from "./desugar.js";
2
+ import { referencedSubs, unclassifiedSubs } from "./model.js";
3
+ export class ProfileContractError extends Error {
4
+ issues;
5
+ constructor(issues) {
6
+ super(`profile does not fit this contract (${issues.length} issue${issues.length === 1 ? "" : "s"}): ` +
7
+ issues
8
+ .slice(0, 3)
9
+ .map((i) => `${i.path || "$"}: ${i.message}`)
10
+ .join("; ") +
11
+ (issues.length > 3 ? "; …" : ""));
12
+ this.issues = issues;
13
+ this.name = "ProfileContractError";
14
+ }
15
+ }
16
+ /** Every sub-component id a model's selectors, collects, and subs name. */
17
+ function namedSubs(model) {
18
+ const out = new Set(referencedSubs(model).keys());
19
+ return out;
20
+ }
21
+ /** Every `self.props.X` a model reads, with the destination reading it. */
22
+ function namedSelfProps(model) {
23
+ const out = [];
24
+ for (const r of model.routes) {
25
+ for (const s of r.from)
26
+ if (s.kind === "self-prop")
27
+ out.push({ prop: s.prop, to: r.to.name });
28
+ }
29
+ return out;
30
+ }
31
+ /**
32
+ * Validate a v2 profile against the contract it is about to project. A no-op
33
+ * for v1 profiles (language undefined): their behaviour is frozen.
34
+ */
35
+ export function validateProfileAgainstContract(profile, doc) {
36
+ if (profile.language !== "v2")
37
+ return;
38
+ const issues = [];
39
+ const components = (doc.components ?? {});
40
+ // Both collections: mapping.ts counts any synthesized plan with a dspackId
41
+ // as mapped, so the gate must see exactly what the mapper sees. And a plan
42
+ // with NO surface block validates against the empty model — for a compound,
43
+ // that means every declared sub is unresolved and refuses, identically to
44
+ // `surface: {}`. Presence of an empty key must never flip the gate.
45
+ const collections = [
46
+ ["components", profile.components],
47
+ ["synthesized", profile.synthesized],
48
+ ];
49
+ for (const [collection, plans] of collections) {
50
+ for (const [i, plan] of plans.entries()) {
51
+ if (!plan.dspackId)
52
+ continue;
53
+ const at = `/${collection}/${i}/surface`;
54
+ const component = components[plan.dspackId];
55
+ if (!component)
56
+ continue; // mapping.ts already warns on unknown dspackIds
57
+ const declaredSubs = (component.composition?.subComponents ?? []).map((s) => s.id);
58
+ const declaredProps = new Set(Object.keys(component.props ?? {}));
59
+ const model = surfaceModelOf(plan);
60
+ for (const sub of namedSubs(model)) {
61
+ if (!declaredSubs.includes(sub)) {
62
+ issues.push({
63
+ path: at,
64
+ message: `'${sub}' is not a declared sub-component of '${plan.dspackId}' in this contract (declared: ${declaredSubs.length ? declaredSubs.join(", ") : "none"})`,
65
+ });
66
+ }
67
+ }
68
+ // A self-prop read is declared either by the CONTRACT (an ordinary prop)
69
+ // or by the PLAN's own structural block when source and destination share
70
+ // its name — the passthrough shape, where an A2UI structural slot may be
71
+ // authored directly on the surface node (v1's structuralPassthrough, and
72
+ // the reason the Table's caption/columns/rows are legal without the
73
+ // contract declaring them). Reading an undeclared prop into a
74
+ // DIFFERENTLY-named destination declares nothing anywhere, and refuses.
75
+ for (const { prop, to } of namedSelfProps(model)) {
76
+ const contractDeclared = declaredProps.has(prop);
77
+ const passthroughShaped = to === prop && prop in (plan.structural ?? {});
78
+ if (!contractDeclared && !passthroughShaped) {
79
+ issues.push({
80
+ path: at,
81
+ message: `self.props.${prop} reads a prop '${plan.dspackId}' does not declare in this contract, and it is not a same-named structural passthrough`,
82
+ });
83
+ }
84
+ }
85
+ // Derived coverage, enforced. The measured gates behind making this fatal:
86
+ // pinned shadcn v2.3.0, astryx and acme all derive zero-unresolved, and
87
+ // the production v3 pair's single finding (radio-group -> radio-group-item)
88
+ // is the known T2 gap — see scripts/sub-coverage-report.mjs and the
89
+ // 2aac076 measurement record.
90
+ for (const sub of unclassifiedSubs(model, declaredSubs)) {
91
+ issues.push({
92
+ path: at,
93
+ 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.`,
94
+ });
95
+ }
96
+ }
97
+ }
98
+ if (issues.length > 0)
99
+ throw new ProfileContractError(issues);
100
+ }
package/dist/types.d.ts CHANGED
@@ -84,6 +84,25 @@ export interface A2uiCatalog extends Json {
84
84
  $defs: Record<string, Json>;
85
85
  }
86
86
  export type A2uiVersion = "0.9.1" | "1.0";
87
+ /**
88
+ * What one surface transformation DID — the per-emission ledger, distinct
89
+ * from the catalog-level FidelityEntry below (which describes what a profile
90
+ * can carry in principle; this describes what one surface actually lost or
91
+ * gained). Additive channel: messages and warnings are byte-frozen for v1,
92
+ * so fidelity rides alongside them on EmitSurfaceResult, never inside them.
93
+ */
94
+ export interface SurfaceFidelityEntry {
95
+ /** Where in the surface the content came from (JSON path, plus selector). */
96
+ source: string;
97
+ /** Where on the emitted instance it landed, or "(discarded)". */
98
+ destination: string;
99
+ /** The profile rule that caused it (route/collect origin, propMap key, or synthesis). */
100
+ origin: string;
101
+ /** What happened to the content. */
102
+ kind: "projected" | "moved" | "lifted" | "flattened" | "synthesized" | "wrapped" | "dropped" | "deduplicated";
103
+ class: FidelityClass;
104
+ note?: string;
105
+ }
87
106
  export type FidelityClass = "maps-cleanly" | "synthesis-defaults" | "lossy" | "cannot-represent";
88
107
  export interface FidelityEntry {
89
108
  source: string;
@@ -3,9 +3,11 @@
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).
@@ -36,6 +38,61 @@ function externalRefs(node, acc = []) {
36
38
  }
37
39
  return acc;
38
40
  }
41
+ /**
42
+ * Collect every INTERNAL `$ref` that does not resolve inside the catalog
43
+ * document, with the JSON path of the offending `$ref` keyword.
44
+ *
45
+ * This is what makes gate 1's documented guarantee true. ajv defers ref
46
+ * resolution past `compile()`, so a structural slot schema (or any other
47
+ * authored-schema channel) carrying `{$ref: "#/$defs/DoesNotExist"}` used to
48
+ * produce either all-gates-PASS (no instances checked) or a raw
49
+ * MissingRefError thrown out of gate 3 — pass-or-crash, never a finding.
50
+ * Resolving the pointers ourselves turns the whole class into a pathed gate
51
+ * failure at one boundary, for every channel at once.
52
+ */
53
+ function danglingInternalRefs(root) {
54
+ const bad = [];
55
+ const resolves = (pointer) => {
56
+ if (pointer === "#" || pointer === "#/")
57
+ return true;
58
+ if (!pointer.startsWith("#/"))
59
+ return false; // #foo anchors are not used in our catalogs
60
+ let node = root;
61
+ for (const raw of pointer.slice(2).split("/")) {
62
+ const key = decodeURIComponent(raw).replaceAll("~1", "/").replaceAll("~0", "~");
63
+ if (Array.isArray(node)) {
64
+ const i = Number(key);
65
+ if (!Number.isInteger(i) || i < 0 || i >= node.length)
66
+ return false;
67
+ node = node[i];
68
+ }
69
+ else if (node && typeof node === "object" && key in node) {
70
+ node = node[key];
71
+ }
72
+ else {
73
+ return false;
74
+ }
75
+ }
76
+ return true;
77
+ };
78
+ const walk = (node, at) => {
79
+ if (Array.isArray(node)) {
80
+ node.forEach((n, i) => walk(n, `${at}/${i}`));
81
+ }
82
+ else if (node && typeof node === "object") {
83
+ for (const [k, v] of Object.entries(node)) {
84
+ if (k === "$ref" && typeof v === "string" && v.startsWith("#") && !resolves(v)) {
85
+ bad.push(`${at}/$ref: '${v}' does not resolve inside this catalog`);
86
+ }
87
+ else {
88
+ walk(v, `${at}/${k}`);
89
+ }
90
+ }
91
+ }
92
+ };
93
+ walk(root, "");
94
+ return bad;
95
+ }
39
96
  /** Pull every component instance (object with string `component` + `id`) from a surface. */
40
97
  export function extractInstances(surface, acc = []) {
41
98
  if (Array.isArray(surface)) {
@@ -53,8 +110,9 @@ export function extractInstances(surface, acc = []) {
53
110
  }
54
111
  export function validateCatalog(catalog, version, surface) {
55
112
  const gates = [];
56
- // Gate 1 — schema compile + no external $ref.
113
+ // Gate 1 — schema compile + no external $ref + every internal $ref resolves.
57
114
  const exts = externalRefs(catalog);
115
+ const dangling = danglingInternalRefs(catalog);
58
116
  let compiled = false;
59
117
  let compileErr = "";
60
118
  try {
@@ -64,15 +122,18 @@ export function validateCatalog(catalog, version, surface) {
64
122
  catch (e) {
65
123
  compileErr = e instanceof Error ? e.message : String(e);
66
124
  }
125
+ const selfContained = compiled && exts.length === 0 && dangling.length === 0;
67
126
  gates.push({
68
127
  name: "schema-compile + no-external-ref",
69
- pass: compiled && exts.length === 0,
70
- detail: compiled && exts.length === 0
71
- ? "Catalog compiles as a draft-2020-12 JSON Schema with only internal $refs."
128
+ pass: selfContained,
129
+ detail: selfContained
130
+ ? "Catalog compiles as a draft-2020-12 JSON Schema; every $ref is internal and resolves."
72
131
  : !compiled
73
132
  ? `ajv failed to compile the catalog as a schema: ${compileErr}`
74
- : `Catalog contains external $refs: ${[...new Set(exts)].join(", ")}`,
75
- errors: exts.length ? [...new Set(exts)] : undefined,
133
+ : exts.length
134
+ ? `Catalog contains external $refs: ${[...new Set(exts)].join(", ")}`
135
+ : `Catalog is not self-contained: ${dangling.length} internal $ref(s) do not resolve.`,
136
+ errors: exts.length ? [...new Set(exts)] : dangling.length ? dangling : undefined,
76
137
  });
77
138
  // Gate 2 — catalog shape.
78
139
  const meta = catalogMetaSchemas[version];
@@ -86,33 +147,43 @@ export function validateCatalog(catalog, version, surface) {
86
147
  : `Catalog violates the v${version} catalog-shape meta-schema.`,
87
148
  errors: shapeOk ? undefined : (validateShape.errors ?? []).map(fmtErr),
88
149
  });
89
- // Gate 3 — instances (only if compilable and a surface was supplied).
150
+ // Gate 3 — instances (only if the catalog is usable and a surface was supplied).
90
151
  if (surface !== undefined) {
91
- if (!compiled) {
152
+ if (!compiled || dangling.length > 0) {
92
153
  gates.push({
93
154
  name: "instance",
94
155
  pass: false,
95
- detail: "Skipped: catalog did not compile, so instances cannot be checked.",
156
+ detail: !compiled
157
+ ? "Skipped: catalog did not compile, so instances cannot be checked."
158
+ : "Skipped: catalog is not self-contained (gate 1 lists the dangling $refs), so instances cannot be checked.",
96
159
  });
97
160
  }
98
161
  else {
99
- const ajv = newAjv();
100
- ajv.addSchema(catalog, catalog.$id);
101
- const validateAny = ajv.getSchema(`${catalog.$id}#/$defs/anyComponent`);
102
- const instances = extractInstances(surface);
162
+ // Belt and braces: gate 1 has already proven every ref resolves, but a
163
+ // raw ajv throw must never escape this function regardless.
103
164
  const failures = [];
104
- if (!validateAny) {
105
- failures.push("Could not resolve #/$defs/anyComponent from the catalog.");
106
- }
107
- else {
108
- for (const inst of instances) {
109
- if (!validateAny(inst)) {
110
- const where = `${inst.component}#${inst.id}`;
111
- for (const e of validateAny.errors ?? [])
112
- failures.push(`${where}: ${fmtErr(e)}`);
165
+ let instances = [];
166
+ try {
167
+ const ajv = newAjv();
168
+ ajv.addSchema(catalog, catalog.$id);
169
+ const validateAny = ajv.getSchema(`${catalog.$id}#/$defs/anyComponent`);
170
+ instances = extractInstances(surface);
171
+ if (!validateAny) {
172
+ failures.push("Could not resolve #/$defs/anyComponent from the catalog.");
173
+ }
174
+ else {
175
+ for (const inst of instances) {
176
+ if (!validateAny(inst)) {
177
+ const where = `${inst.component}#${inst.id}`;
178
+ for (const e of validateAny.errors ?? [])
179
+ failures.push(`${where}: ${fmtErr(e)}`);
180
+ }
113
181
  }
114
182
  }
115
183
  }
184
+ catch (e) {
185
+ failures.push(`instance validation could not run: ${e instanceof Error ? e.message : String(e)}`);
186
+ }
116
187
  gates.push({
117
188
  name: "instance",
118
189
  pass: failures.length === 0,
package/package.json CHANGED
@@ -1,8 +1,8 @@
1
1
  {
2
2
  "name": "@aestheticfunction/dspack-emit",
3
- "version": "0.4.1",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
- "description": "dspack emitters: compile a dspack design-system contract and dspack surfaces into protocol targets — an A2UI catalog + surface messages (gates A1-A3) and json-render catalog/registry modules + specs (gates J1-J3).",
5
+ "description": "dspack emitters: compile a dspack design-system contract and dspack surfaces into protocol targets \u2014 an A2UI catalog + surface messages (gates A1-A3) and json-render catalog/registry modules + specs (gates J1-J3).",
6
6
  "license": "Apache-2.0",
7
7
  "exports": {
8
8
  ".": {