@aestheticfunction/dspack-emit 0.6.0 → 0.8.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 (41) hide show
  1. package/README.md +23 -15
  2. package/dist/cli.js +4 -2
  3. package/dist/index.d.ts +1 -1
  4. package/dist/index.js +1 -1
  5. package/dist/targets/a2ui/surface.js +108 -4
  6. package/dist/transform/emit-v1_0.d.ts +45 -0
  7. package/dist/transform/emit-v1_0.js +190 -0
  8. package/dist/transform/emit.d.ts +6 -9
  9. package/dist/transform/emit.js +5 -44
  10. package/dist/transform/index.js +3 -1
  11. package/dist/types.d.ts +4 -0
  12. package/dist/validate/ajv.d.ts +26 -0
  13. package/dist/validate/ajv.js +150 -23
  14. package/dist/validate/meta/a2ui-v1_0.d.ts +9 -0
  15. package/dist/validate/meta/a2ui-v1_0.js +811 -0
  16. package/dist/validate/meta/catalog-meta.js +34 -21
  17. package/package.json +6 -2
  18. package/src/byte-neutral.test.ts +6 -3
  19. package/src/cli.ts +5 -2
  20. package/src/engine-boundary.test.ts +10 -0
  21. package/src/functions.test.ts +48 -1
  22. package/src/index.ts +1 -1
  23. package/src/instance-diagnostics.test.ts +194 -0
  24. package/src/profile-v2.test.ts +1 -1
  25. package/src/review-findings.test.ts +4 -1
  26. package/src/surface-emit.test.ts +43 -11
  27. package/src/surface-fidelity.test.ts +12 -0
  28. package/src/t1.test.ts +9 -8
  29. package/src/targets/a2ui/surface.ts +124 -4
  30. package/src/transform/emit-v1_0.ts +215 -0
  31. package/src/transform/emit.ts +10 -54
  32. package/src/transform/index.ts +3 -1
  33. package/src/transform.test.ts +33 -1
  34. package/src/types.ts +4 -0
  35. package/src/v1_0-catalog.test.ts +267 -0
  36. package/src/validate/ajv.ts +169 -22
  37. package/src/validate/meta/a2ui-catalog.meta.1_0.json +67 -13
  38. package/src/validate/meta/a2ui-v1_0.ts +820 -0
  39. package/src/validate/meta/catalog-meta.ts +34 -21
  40. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +0 -39
  41. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +0 -34
@@ -118,6 +118,12 @@ export function emitSurface(
118
118
  ? emitter.emitTransparentRoot(surface.root, "$.root")
119
119
  : emitter.emitNode(surface.root, "$.root");
120
120
 
121
+ // Every instance is assembled; refuse the whole emission if any of them
122
+ // could not validate against the catalog this surface names (required
123
+ // presence + enum membership — the observed defect class; gate A3 keeps
124
+ // full-schema rigor downstream).
125
+ emitter.refuseCatalogInvalid();
126
+
121
127
  const surfaceId = options.surfaceId ?? slug(surface.intent);
122
128
  const theme: Json = { agentDisplayName: `${doc.name} via dspack` };
123
129
  const primaryHex = primaryColor(doc, profile);
@@ -177,6 +183,17 @@ class SurfaceEmitter {
177
183
  readonly components: Json[] = [];
178
184
  readonly diagnostics = new Diagnostics();
179
185
  private readonly usedIds = new Set<string>();
186
+ /**
187
+ * Evidence channel for the final catalog-validity guard: authored props
188
+ * dropped per EMITTED instance — either the prop had no A2UI projection at
189
+ * all, or its value had no projection and no default. Keyed by instance
190
+ * object so a later missing-required refusal can cite its cause. This is
191
+ * bookkeeping alongside the (byte-frozen) warnings, never a new warning.
192
+ */
193
+ private readonly droppedProps = new Map<
194
+ Json,
195
+ Array<{ prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" }>
196
+ >();
180
197
 
181
198
  constructor(
182
199
  private readonly profile: Profile,
@@ -591,8 +608,9 @@ class SurfaceEmitter {
591
608
 
592
609
  case "sub-text-lift": {
593
610
  // Audited lift: relocation of text that exists, never synthesis. If
594
- // nothing exists to lift the destination stays missing and gate A3
595
- // refuses the instance, exactly as before.
611
+ // nothing exists to lift the destination stays missing — refused at
612
+ // emission by the final catalog-validity guard when it is required,
613
+ // arbitrated by gate A3 otherwise. Either way, no fabrication.
596
614
  const lift = (n: SurfaceNode, inside: boolean): { text: string; component: string } | undefined => {
597
615
  const here = inside || selector.subs.includes(n.component);
598
616
  if (here && n.text !== undefined && n.text !== "") return { text: n.text, component: n.component };
@@ -656,6 +674,7 @@ class SurfaceEmitter {
656
674
  if (routedVerbatim.has(prop)) continue;
657
675
  const pp = plan.propMap?.[prop];
658
676
  if (!pp) {
677
+ this.recordDrop(instance, { prop, raw, component: node.component, path, reason: "no-projection" });
659
678
  this.diagnostics.push(
660
679
  {
661
680
  code: "surface-prop-dropped",
@@ -676,6 +695,7 @@ class SurfaceEmitter {
676
695
  const mapped = pp.valueMap ? pp.valueMap[String(raw)] : undefined;
677
696
  const value = pp.valueMap ? (mapped ?? pp.default) : raw;
678
697
  if (value === undefined) {
698
+ this.recordDrop(instance, { prop, dest: pp.a2ui, raw, component: node.component, path, reason: "no-value" });
679
699
  this.diagnostics.push(
680
700
  {
681
701
  code: "surface-prop-value-dropped",
@@ -710,6 +730,104 @@ class SurfaceEmitter {
710
730
  }
711
731
  }
712
732
 
733
+ private recordDrop(
734
+ instance: Json,
735
+ entry: { prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" },
736
+ ): void {
737
+ const list = this.droppedProps.get(instance);
738
+ if (list) list.push(entry);
739
+ else this.droppedProps.set(instance, [entry]);
740
+ }
741
+
742
+ /**
743
+ * Final guard (ratified 2026-08-10): never return a surface whose instances
744
+ * the emitted catalog itself refuses. Two checks per instance, against its
745
+ * own ComponentPlan:
746
+ *
747
+ * - every catalog-required prop carries a value (`plan.required` — the
748
+ * same list mapping.ts emits as `required: ["component", ...]`);
749
+ * - every propMap-projected prop with a `targetEnum` carries a member of
750
+ * that enum (without a valueMap the authored value passes through
751
+ * verbatim, so an off-vocabulary value used to land silently).
752
+ *
753
+ * On any violation the whole emission refuses with ONE aggregated message
754
+ * citing each violation and — where the node's recorded drop diagnostics
755
+ * recover it — the cause. This covers the observed defect class
756
+ * (required-presence + enum-membership); full-schema rigor stays gate A3's
757
+ * job, downstream, as defense in depth. Warnings and fidelity recording are
758
+ * untouched: a surface that emits, emits byte-identically to before.
759
+ */
760
+ refuseCatalogInvalid(): void {
761
+ const byA2ui = new Map<string, ComponentPlan>();
762
+ for (const plan of [...this.profile.components, ...this.profile.synthesized]) {
763
+ // Transparent plans dissolve at emission — no instance ever carries them.
764
+ if (!surfaceModelOf(plan).transparent) byA2ui.set(plan.a2ui, plan);
765
+ }
766
+
767
+ const violations: string[] = [];
768
+ for (const inst of this.components) {
769
+ const plan = byA2ui.get(String(inst.component));
770
+ if (!plan) continue; // no plan to check against: gate A3 arbitrates downstream
771
+ const where = `${inst.component}#${inst.id}`;
772
+ const drops = this.droppedProps.get(inst) ?? [];
773
+
774
+ for (const req of plan.required) {
775
+ if (inst[req] !== undefined) continue;
776
+ violations.push(`${where}: required prop '${req}' has no value after emission${this.missingCause(plan, req, drops)}`);
777
+ }
778
+
779
+ for (const [src, pp] of Object.entries(plan.propMap ?? {})) {
780
+ if (!pp.targetEnum) continue;
781
+ const value = inst[pp.a2ui];
782
+ if (value === undefined) continue;
783
+ if (typeof value === "string" && pp.targetEnum.includes(value)) continue;
784
+ const cause = pp.valueMap ? "" : ` — authored 'props.${src}' passed through verbatim (this propMap declares no valueMap)`;
785
+ violations.push(
786
+ `${where}: prop '${pp.a2ui}' value ${JSON.stringify(value)} is outside the catalog's enum (allowed: ${pp.targetEnum.join(", ")})${cause}`,
787
+ );
788
+ }
789
+ }
790
+
791
+ if (violations.length > 0) {
792
+ throw new EmitSurfaceError(
793
+ `refusing to emit: ${violations.length} instance value(s) would not validate against the emitted catalog ` +
794
+ `(gate A3 would refuse this surface downstream):\n` +
795
+ violations.map((v) => ` - ${v}`).join("\n"),
796
+ "$",
797
+ );
798
+ }
799
+ }
800
+
801
+ /**
802
+ * The recoverable cause for a required prop with no value: the authored
803
+ * prop this node DID carry that was dropped (recorded at PropMap time),
804
+ * and/or where the plan's own routes expect the value to come from.
805
+ */
806
+ private missingCause(
807
+ plan: ComponentPlan,
808
+ req: string,
809
+ drops: Array<{ prop: string; dest?: string; raw: unknown; component: string; path: string; reason: "no-projection" | "no-value" }>,
810
+ ): string {
811
+ const model = surfaceModelOf(plan);
812
+ const feeders = model.routes.filter((r) => r.to.name === req);
813
+ const subs = [
814
+ ...new Set(feeders.flatMap((r) => r.from.flatMap((s) => ("subs" in s ? [...(s.subs as string[])] : [])))),
815
+ ];
816
+ const source =
817
+ subs.length > 0
818
+ ? ` (${req} comes from the ${subs.map((s) => `'${s}'`).join(" / ")} sub-component${subs.length > 1 ? "s" : ""})`
819
+ : feeders.length > 0
820
+ ? ` (${req} is fed by ${feeders.map((r) => r.from.map(describeSelector).join(" | ")).join(", ")})`
821
+ : "";
822
+ const drop = drops.find((d) => d.prop === req || d.dest === req);
823
+ if (!drop) return source;
824
+ const why =
825
+ drop.reason === "no-projection"
826
+ ? `authored 'props.${drop.prop}' on '${drop.component}' has no A2UI projection`
827
+ : `authored 'props.${drop.prop}'=${JSON.stringify(drop.raw)} on '${drop.component}' has no projection for that value and no default`;
828
+ return ` — ${why}${source}`;
829
+ }
830
+
713
831
  /**
714
832
  * Refuse when a consumed subtree contains a component the profile declared a
715
833
  * casualty. Consumption is how compounds fold their parts into props; it is
@@ -1546,8 +1664,10 @@ class SurfaceEmitter {
1546
1664
  if (value !== undefined) {
1547
1665
  pending.push({ prop: d.to.name, value, origin: d.origin, donorPath: `${path}${suffix}`, donorComponent });
1548
1666
  }
1549
- // Nothing to donate is not an error: the destination stays absent and
1550
- // gate A3 arbitrates — relocation, never synthesis (the lift rule).
1667
+ // Nothing to donate is not an error: the destination stays absent —
1668
+ // refused at emission by the final catalog-validity guard when it is
1669
+ // required, arbitrated by gate A3 otherwise. Relocation, never
1670
+ // synthesis (the lift rule).
1551
1671
  }
1552
1672
 
1553
1673
  // The boundary's own text rises as body text unless a self.text
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The A2UI 1.0 catalog, built from the same mapping result as 0.9.1. Only the differences the 1.0 specification
3
+ * requires live here, each against the pinned upstream (fixtures/a2ui/PIN.md; specification/v1_0/docs/a2ui_protocol.md,
4
+ * "Catalog Schema Rules and Conventions"):
5
+ *
6
+ * - `protocolVersion: "1.0"` (required for catalogs targeting 1.0 and beyond).
7
+ * - Standard types are referenced as `common_types.json#/$defs/<Type>`, never copied into the catalog, and only the
8
+ * types the specification lists may be referenced (rule 3). The 0.9.1 catalog inlines its own copies; 1.0 must not.
9
+ * - Components are flat. `ComponentCommon` is composed by the envelope (agent_to_renderer.json `Component`), so it is
10
+ * not wrapped in per component, and the envelope, not the component, is where `unevaluatedProperties: false` holds
11
+ * (rule 5). A trait such as `Checkable` stays, as in upstream's basic catalog.
12
+ * - `$defs` holds `anyComponent`, `anyFunction` and leaf definitions only (rules 1 and 2). With no functions declared,
13
+ * `anyFunction` is `{"not": {}}`, which matches no call: the form upstream's own function-less 1.0 catalog uses
14
+ * (catalogs/vegachart/v1/catalog.json).
15
+ * - Functions are call-validation schemas: `properties["@call"].const`, optional `args`, `returnType` (rule 6). As with
16
+ * components, the envelope (`FunctionCall`, composing `FunctionCommon`) closes the object, not the function schema.
17
+ * - There is no `surfaceProperties`. Design tokens are catalog-level metadata, `metadata.extensions.dspack_tokens`
18
+ * (rule 7; extension names are UAX #31 identifiers with a product prefix).
19
+ * - Every component, function and property name is a UAX #31 identifier. A design-system property whose name is an
20
+ * ARIA attribute maps onto the envelope's `@accessibility` instead of being renamed, so the catalog never declares a
21
+ * second channel for the same accessible name ("Catalog-Agnostic Accessibility Requirements").
22
+ *
23
+ * Anything this module cannot represent faithfully is refused with a stated reason rather than emitted approximately.
24
+ */
25
+ import type { A2uiCatalog, FidelityEntry, Json } from "../types.js";
26
+ import type { MappingResult } from "./mapping.js";
27
+ import type { Profile } from "./profiles.js";
28
+
29
+ /** The standard types a 1.0 catalog may reference in common_types.json (rule 3), in the specification's order. */
30
+ export const COMMON_TYPES_V1_0 = [
31
+ "ComponentId",
32
+ "Child",
33
+ "ChildList",
34
+ "DynamicString",
35
+ "DynamicNumber",
36
+ "DynamicBoolean",
37
+ "DynamicStringList",
38
+ "DynamicValue",
39
+ "AccessibilityAttributes",
40
+ "CheckRule",
41
+ "Checkable",
42
+ "Action",
43
+ "DataBinding",
44
+ "FunctionCall",
45
+ ] as const;
46
+ const COMMON = new Set<string>(COMMON_TYPES_V1_0);
47
+
48
+ /**
49
+ * Design-system properties named after an ARIA attribute, and the `@accessibility` attribute that carries the same
50
+ * meaning on a 1.0 component instance (common_types.json AccessibilityAttributes: label, description, live, hidden).
51
+ */
52
+ export const ARIA_TO_ACCESSIBILITY: Readonly<Record<string, "label" | "description" | "live" | "hidden">> = {
53
+ "aria-label": "label",
54
+ "aria-description": "description",
55
+ "aria-live": "live",
56
+ "aria-hidden": "hidden",
57
+ };
58
+
59
+ /** The catalog-level extension that carries the design tokens (a product-prefixed UAX #31 name). */
60
+ export const TOKEN_EXTENSION = "dspack_tokens";
61
+ /**
62
+ * The component-level extension that records which design-system properties the envelope now carries:
63
+ * `{ properties: { "<aria-name>": { carriedBy: "@accessibility.<attribute>", schema: <the property's own schema> } } }`.
64
+ */
65
+ export const ACCESSIBILITY_EXTENSION = "dspack_accessibility";
66
+
67
+ /** UAX #31 (`^[\p{XID_Start}_][\p{XID_Continue}]*$`), the rule for every catalog entity name in 1.0. */
68
+ const IDENTIFIER = /^[\p{XID_Start}_][\p{XID_Continue}]*$/u;
69
+
70
+ class V1Refusal extends Error {}
71
+
72
+ /** Re-target a schema's standard-type references at common_types.json; refuse any other #/$defs reference. */
73
+ function retarget(node: Json, at: string): Json {
74
+ if (Array.isArray(node)) return node.map((n, i) => retarget(n as Json, `${at}/${i}`)) as unknown as Json;
75
+ if (!node || typeof node !== "object") return node;
76
+ const out: Json = {};
77
+ for (const [k, v] of Object.entries(node)) {
78
+ if (k === "$ref" && typeof v === "string" && v.startsWith("#/$defs/")) {
79
+ const type = v.slice("#/$defs/".length);
80
+ if (!COMMON.has(type)) {
81
+ throw new V1Refusal(`${at}: '${v}' has no A2UI 1.0 counterpart in common_types.json (allowed: ${COMMON_TYPES_V1_0.join(", ")})`);
82
+ }
83
+ out[k] = `common_types.json#/$defs/${type}`;
84
+ } else {
85
+ out[k] = retarget(v as Json, `${at}/${k}`);
86
+ }
87
+ }
88
+ return out;
89
+ }
90
+
91
+ function component(name: string, emitted: Json): Json {
92
+ const parts = (emitted.allOf ?? []) as Json[];
93
+ const own = parts.find((p) => !("$ref" in p));
94
+ if (!own) throw new V1Refusal(`components.${name}: no component schema to emit`);
95
+ const traits = parts
96
+ .filter((p) => "$ref" in p)
97
+ .map((p) => String(p.$ref).slice("#/$defs/".length))
98
+ .filter((t) => t !== "ComponentCommon"); // composed by the envelope (rule 5)
99
+
100
+ const schema = retarget(own, `components.${name}`);
101
+ const properties = (schema.properties ?? {}) as Record<string, Json>;
102
+ const required = ((schema.required ?? []) as string[]).slice();
103
+ const carried: Record<string, Json> = {};
104
+ for (const prop of Object.keys(properties)) {
105
+ const attribute = ARIA_TO_ACCESSIBILITY[prop];
106
+ if (attribute) {
107
+ if (required.includes(prop)) {
108
+ throw new V1Refusal(`components.${name}.${prop}: a required ARIA property cannot move to the optional @accessibility.${attribute}`);
109
+ }
110
+ // The design system's own guidance for the property (its description, a default such as "Loading", its source)
111
+ // stays in the catalog beside the mapping, so an agent reading the 1.0 catalog still learns when and how to set it.
112
+ carried[prop] = { carriedBy: `@accessibility.${attribute}`, schema: properties[prop]! };
113
+ delete properties[prop];
114
+ } else if (!IDENTIFIER.test(prop)) {
115
+ throw new V1Refusal(`components.${name}.${prop}: not a UAX #31 identifier, and no 1.0 mapping is defined for it`);
116
+ }
117
+ }
118
+ const flat: Json = { ...schema, properties };
119
+ if (Object.keys(carried).length > 0) {
120
+ flat.metadata = { extensions: { [ACCESSIBILITY_EXTENSION]: { properties: carried } } };
121
+ }
122
+ if (traits.length === 0) return flat;
123
+ // A trait keeps upstream's basic-catalog form: { type, allOf: [trait, component] }.
124
+ const { metadata, ...body } = flat;
125
+ return {
126
+ type: "object",
127
+ allOf: [...traits.map((t) => ({ $ref: retarget({ $ref: `#/$defs/${t}` } as Json, `components.${name}`).$ref })), body],
128
+ ...(metadata ? { metadata } : {}),
129
+ } as Json;
130
+ }
131
+
132
+ function functions(profile: Profile): { section?: Record<string, Json>; anyFunction: Json } {
133
+ const declared = profile.functions;
134
+ const names = declared ? Object.keys(declared).sort() : [];
135
+ if (names.length === 0) return { anyFunction: { not: {} } };
136
+ const section: Record<string, Json> = {};
137
+ for (const name of names) {
138
+ if (!IDENTIFIER.test(name)) throw new V1Refusal(`functions.${name}: not a UAX #31 identifier`);
139
+ const fn = declared![name];
140
+ const args = fn.args ? retarget(fn.args as Json, `functions.${name}.args`) : undefined;
141
+ const requiresArgs = Array.isArray((fn.args as { required?: unknown } | undefined)?.required) && ((fn.args as { required: unknown[] }).required.length > 0);
142
+ section[name] = {
143
+ type: "object",
144
+ description: fn.description,
145
+ returnType: fn.returns,
146
+ properties: { "@call": { const: name }, ...(args ? { args } : {}) },
147
+ required: requiresArgs ? ["@call", "args"] : ["@call"],
148
+ // No unevaluatedProperties here: the FunctionCall envelope (common_types.json) composes FunctionCommon with this
149
+ // schema and closes the object itself, as upstream's basic catalog relies on.
150
+ } as Json;
151
+ }
152
+ return { section, anyFunction: { oneOf: names.map((n) => ({ $ref: `#/functions/${n}` })) } as Json };
153
+ }
154
+
155
+ /** The 1.0 catalog. Throws, with the reason, when the mapping holds something 1.0 cannot represent. */
156
+ export function emitCatalogV1_0(result: MappingResult, profile: Profile, id: string): A2uiCatalog {
157
+ try {
158
+ const components: Record<string, Json> = {};
159
+ for (const name of result.componentOrder) {
160
+ if (!IDENTIFIER.test(name)) throw new V1Refusal(`components.${name}: not a UAX #31 identifier`);
161
+ if (name === "Surface") throw new V1Refusal("components.Surface: the name is reserved by the protocol");
162
+ components[name] = component(name, result.components[name] as Json);
163
+ }
164
+ const fns = functions(profile);
165
+ const tokens: Json = {
166
+ ...(result.primaryColorHex ? { primaryColor: { value: result.primaryColorHex, source: result.primaryColorSource } } : {}),
167
+ palette: (result.tokenExtension as Json)["x-dspack-tokens"] ?? {},
168
+ };
169
+ return {
170
+ $schema: "https://json-schema.org/draft/2020-12/schema",
171
+ $id: id,
172
+ protocolVersion: "1.0",
173
+ title: profile.catalogTitle,
174
+ description: profile.catalogDescription,
175
+ catalogId: id,
176
+ ...(profile.instructions !== undefined ? { instructions: profile.instructions } : {}),
177
+ metadata: { extensions: { [TOKEN_EXTENSION]: tokens } },
178
+ components,
179
+ ...(fns.section ? { functions: fns.section } : {}),
180
+ $defs: {
181
+ anyComponent: {
182
+ oneOf: result.componentOrder.map((n) => ({ $ref: `#/components/${n}` })),
183
+ discriminator: { propertyName: "component" },
184
+ },
185
+ anyFunction: fns.anyFunction,
186
+ },
187
+ } as unknown as A2uiCatalog;
188
+ } catch (e) {
189
+ if (e instanceof V1Refusal) throw new Error(`A2UI 1.0 catalog refused: ${e.message}`);
190
+ throw e;
191
+ }
192
+ }
193
+
194
+ /** The mapping's fidelity entries as they read for the 1.0 catalog: where tokens and ARIA properties actually go. */
195
+ export function fidelityV1_0(result: MappingResult): FidelityEntry[] {
196
+ const out: FidelityEntry[] = [];
197
+ for (const f of result.fidelity) {
198
+ if (/theme|surfaceProperties/.test(f.target)) {
199
+ out.push({ ...f, target: `metadata.extensions.${TOKEN_EXTENSION}`, note: f.note.replace(/theme\.primaryColor's #rrggbb pattern/, "the token extension's primaryColor").replace("(additionalProperties allows it)", "(a catalog-level metadata extension)") });
200
+ continue;
201
+ }
202
+ const aria = /^components\.([^.]+)\.properties\.(.+)$/.exec(f.target);
203
+ if (aria && ARIA_TO_ACCESSIBILITY[aria[2]!]) {
204
+ out.push({
205
+ ...f,
206
+ target: `components.${aria[1]} instance @accessibility.${ARIA_TO_ACCESSIBILITY[aria[2]!]}`,
207
+ class: "synthesis-defaults",
208
+ note: `In A2UI 1.0 the envelope's @accessibility.${ARIA_TO_ACCESSIBILITY[aria[2]!]} carries '${aria[2]}' (an ARIA attribute name is not a UAX #31 identifier). The catalog keeps the mapping and the property's own guidance in metadata.extensions.${ACCESSIBILITY_EXTENSION}.`,
209
+ });
210
+ continue;
211
+ }
212
+ out.push(f);
213
+ }
214
+ return out;
215
+ }
@@ -1,18 +1,16 @@
1
1
  /**
2
- * Versioned catalog emitter. The two supported A2UI versions differ only in:
3
- * - v0.9.1: a `$defs.theme` object (carries `primaryColor`, #rrggbb).
4
- * - v1.0: a `$defs.surfaceProperties` object + a top-level `instructions`.
5
- * Everything else (components, inlined `$defs`, `anyComponent`) is identical.
6
- *
7
- * The theme / surfaceProperties shapes are copied from the checked-in fixtures
8
- * (fixtures/a2ui/basic-catalog.{v0_9_1,v1_0}.json) and confirmed in pre-flight.
9
- * We additionally carry the resolved design tokens as a documented extension
10
- * (`additionalProperties: true` on both shapes permits it).
2
+ * Versioned catalog emitter. This module writes the A2UI 0.9.1 catalog, whose
3
+ * `$defs.theme` shape is copied from the checked-in fixture
4
+ * (fixtures/a2ui/basic-catalog.v0_9_1.json); the resolved design tokens ride
5
+ * along as a documented extension (`additionalProperties: true` permits it).
6
+ * The A2UI 1.0 catalog follows different rules and is built from the same
7
+ * mapping result by emit-v1_0.ts.
11
8
  */
12
9
  import type { A2uiCatalog, A2uiVersion, Json } from "../types.js";
13
10
  import { INLINED_DEFS } from "./inline-defs.js";
14
11
  import type { MappingResult } from "./mapping.js";
15
12
  import type { Profile } from "./profiles.js";
13
+ import { emitCatalogV1_0 } from "./emit-v1_0.js";
16
14
 
17
15
  /**
18
16
  * The catalog's function surface, from the profile's declared FunctionPlans:
@@ -68,6 +66,8 @@ export function emitCatalog(
68
66
  ): A2uiCatalog {
69
67
  const seg = VER_SEGMENT[version];
70
68
  const id = `${profile.catalogIdBase}/${seg}/catalog.json`;
69
+ // A2UI 1.0 has its own catalog rules (emit-v1_0.ts); everything below is the 0.9.1 catalog, unchanged.
70
+ if (version === "1.0") return emitCatalogV1_0(result, profile, id);
71
71
 
72
72
  const anyComponent: Json = {
73
73
  oneOf: result.componentOrder.map((n) => ({ $ref: `#/components/${n}` })),
@@ -100,11 +100,7 @@ export function emitCatalog(
100
100
  fc.oneOf = [{ $ref: "#/$defs/anyFunction" } as Json];
101
101
  }
102
102
 
103
- if (version === "0.9.1") {
104
- $defs.theme = themeDef(result);
105
- } else {
106
- $defs.surfaceProperties = surfacePropertiesDef(result);
107
- }
103
+ $defs.theme = themeDef(result);
108
104
 
109
105
  const catalog: A2uiCatalog = {
110
106
  $schema: "https://json-schema.org/draft/2020-12/schema",
@@ -117,21 +113,6 @@ export function emitCatalog(
117
113
  $defs,
118
114
  };
119
115
 
120
- if (version === "1.0") {
121
- // Insert `instructions` right after description, mirroring the v1.0 fixture order.
122
- return {
123
- $schema: catalog.$schema,
124
- $id: catalog.$id,
125
- title: catalog.title,
126
- description: catalog.description,
127
- instructions: profile.instructions,
128
- catalogId: catalog.catalogId,
129
- components: catalog.components,
130
- ...(catalog.functions ? { functions: catalog.functions } : {}),
131
- $defs: catalog.$defs,
132
- };
133
- }
134
-
135
116
  return catalog;
136
117
  }
137
118
 
@@ -166,28 +147,3 @@ function themeDef(result: MappingResult): Json {
166
147
  ...result.tokenExtension,
167
148
  };
168
149
  }
169
-
170
- /** v1.0 — shape from fixtures/a2ui/basic-catalog.v1_0.json#/$defs/surfaceProperties. */
171
- function surfacePropertiesDef(result: MappingResult): Json {
172
- const def: Json = {
173
- type: "object",
174
- properties: {
175
- iconUrl: {
176
- type: "string",
177
- format: "uri",
178
- description: "A URL for an image that identifies the agent or tool associated with the surface.",
179
- },
180
- agentDisplayName: {
181
- type: "string",
182
- description: "Text displayed next to the surface to identify the agent or tool that created it.",
183
- },
184
- },
185
- additionalProperties: true,
186
- ...result.tokenExtension,
187
- };
188
- // v1.0 basic surfaceProperties has no primaryColor field; carry it as an extension.
189
- if (result.primaryColorHex) {
190
- def["x-dspack-primaryColor"] = { value: result.primaryColorHex, source: result.primaryColorSource };
191
- }
192
- return def;
193
- }
@@ -6,6 +6,7 @@ import { shadcnProfile, type Profile } from "./profiles.js";
6
6
  import { mapDspack, type MappingResult } from "./mapping.js";
7
7
  import { validateProfileAgainstContract } from "./validate-v2.js";
8
8
  import { emitCatalog } from "./emit.js";
9
+ import { fidelityV1_0 } from "./emit-v1_0.js";
9
10
  import { buildReport, type ReportBundle } from "./report.js";
10
11
  import { validateCatalog, type ValidationReport } from "../validate/ajv.js";
11
12
 
@@ -35,7 +36,8 @@ export function transform(
35
36
  const mapping = mapDspack(doc, profile);
36
37
  const catalog = emitCatalog(mapping, version, profile);
37
38
  const validation = validateCatalog(catalog, version, surface);
38
- const report = buildReport(version, mapping, validation);
39
+ // The 1.0 report says where tokens and ARIA properties go in a 1.0 catalog; the 0.9.1 report is unchanged.
40
+ const report = buildReport(version, version === "1.0" ? { ...mapping, fidelity: fidelityV1_0(mapping) } : mapping, validation);
39
41
 
40
42
  return { catalog, mapping, validation, report };
41
43
  }
@@ -70,10 +70,25 @@ describe("profile mapping", () => {
70
70
  });
71
71
  });
72
72
 
73
+ /**
74
+ * The same hand-authored surface with its bindings in the A2UI 1.0 spelling (`{"@path": …}`; a plain `{path}` is a
75
+ * literal object in 1.0). Only the instances' data bindings differ between the versions in this surface. Emitting 1.0
76
+ * messages is P1b; this fixture only lets the 1.0 catalog be checked against genuine 1.0 instances.
77
+ */
78
+ function asV1_0Instances(node: unknown): unknown {
79
+ if (Array.isArray(node)) return node.map(asV1_0Instances);
80
+ if (node && typeof node === "object") {
81
+ const o = node as Record<string, unknown>;
82
+ if (Object.keys(o).length === 1 && typeof o.path === "string") return { "@path": o.path };
83
+ return Object.fromEntries(Object.entries(o).map(([k, v]) => [k, asV1_0Instances(v)]));
84
+ }
85
+ return node;
86
+ }
87
+
73
88
  describe("validation gates", () => {
74
89
  it("passes all three gates for both emitted versions", () => {
75
90
  for (const v of ["0.9.1", "1.0"] as const) {
76
- const { validation } = transform(doc, v, surface);
91
+ const { validation } = transform(doc, v, v === "1.0" ? asV1_0Instances(surface) : surface);
77
92
  expect(validation.pass, `v${v} should pass`).toBe(true);
78
93
  expect(validation.gates.map((g) => g.name)).toEqual([
79
94
  "schema-compile + no-external-ref",
@@ -83,6 +98,23 @@ describe("validation gates", () => {
83
98
  }
84
99
  });
85
100
 
101
+ it("catalog conformance is not message conformance: a 0.9-spelled binding is not a valid 1.0 instance", () => {
102
+ const { validation } = transform(doc, "1.0", surface);
103
+ const instance = validation.gates.find((g) => g.name === "instance")!;
104
+ expect(validation.gates.find((g) => g.name === "catalog-shape")!.pass).toBe(true);
105
+ expect(instance.pass).toBe(false);
106
+ expect(instance.errors?.join("\n")).toMatch(/required property '@path'/);
107
+ });
108
+
109
+ it("the 1.0 instance gate closes the component the way the envelope does: an unknown property is refused", () => {
110
+ const v1 = asV1_0Instances(surface) as { messages: Array<{ updateComponents?: { components: Array<Record<string, unknown>> } }> };
111
+ const update = v1.messages.find((m) => m.updateComponents)!;
112
+ update.updateComponents!.components[0]!.notAProperty = true;
113
+ const instance = transform(doc, "1.0", v1).validation.gates.find((g) => g.name === "instance")!;
114
+ expect(instance.pass).toBe(false);
115
+ expect(instance.errors?.join("\n")).toMatch(/unevaluated properties \('notAProperty'\)|notAProperty/);
116
+ });
117
+
86
118
  it("the instance gate is not vacuous: rejects an invalid Button instance", () => {
87
119
  const { catalog } = transform(doc, "0.9.1", surface);
88
120
  const bad = {
package/src/types.ts CHANGED
@@ -97,7 +97,11 @@ export interface A2uiCatalog extends Json {
97
97
  title: string;
98
98
  description: string;
99
99
  catalogId: string;
100
+ /** A2UI 1.0 only: the specification version the catalog targets. Never written for 0.9.1. */
101
+ protocolVersion?: string;
100
102
  instructions?: string;
103
+ /** A2UI 1.0 only: catalog-level metadata (`metadata.extensions`). Never written for 0.9.1. */
104
+ metadata?: Json;
101
105
  components: Record<string, Json>;
102
106
  functions?: Record<string, Json>;
103
107
  $defs: Record<string, Json>;