@aestheticfunction/dspack-emit 0.4.1 → 0.6.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 (72) 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 +1004 -222
  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 +66 -2
  15. package/dist/transform/model.d.ts +368 -0
  16. package/dist/transform/model.js +169 -0
  17. package/dist/transform/parse-v2.d.ts +109 -0
  18. package/dist/transform/parse-v2.js +479 -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 +608 -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 +77 -0
  27. package/dist/transform/shadcn-v2-respelling.js +456 -0
  28. package/dist/transform/validate-v2.d.ts +36 -0
  29. package/dist/transform/validate-v2.js +136 -0
  30. package/dist/types.d.ts +23 -0
  31. package/dist/validate/ajv.js +96 -25
  32. package/dist/validate/meta/a2ui-catalog.meta.0_9_1.json +39 -0
  33. package/dist/validate/meta/a2ui-catalog.meta.1_0.json +34 -0
  34. package/package.json +2 -2
  35. package/src/__snapshots__/byte-neutral.test.ts.snap +66 -0
  36. package/src/a0.test.ts +235 -0
  37. package/src/byte-neutral.test.ts +246 -0
  38. package/src/cli.ts +60 -0
  39. package/src/dangling-ref.test.ts +118 -0
  40. package/src/desugar.test.ts +162 -0
  41. package/src/engine-boundary.test.ts +248 -0
  42. package/src/eval-fixture.test.ts +102 -0
  43. package/src/functions.test.ts +182 -0
  44. package/src/index.ts +4 -1
  45. package/src/layered-dissolution.test.ts +139 -0
  46. package/src/profile-load.test.ts +99 -1
  47. package/src/profile-v2.test.ts +369 -0
  48. package/src/review-findings.test.ts +292 -0
  49. package/src/schema-mirrors.test.ts +5 -0
  50. package/src/surface-fidelity.test.ts +213 -0
  51. package/src/t1.test.ts +369 -0
  52. package/src/t2.test.ts +222 -0
  53. package/src/t3.test.ts +304 -0
  54. package/src/t4.test.ts +278 -0
  55. package/src/targets/a2ui/diagnostics.ts +136 -0
  56. package/src/targets/a2ui/surface.ts +1468 -235
  57. package/src/transform/desugar.ts +194 -0
  58. package/src/transform/emit.ts +65 -0
  59. package/src/transform/index.ts +5 -0
  60. package/src/transform/mapping.ts +60 -2
  61. package/src/transform/model.ts +427 -0
  62. package/src/transform/parse-v2.ts +608 -0
  63. package/src/transform/profile-load.ts +104 -22
  64. package/src/transform/profile-schema-v2.ts +608 -0
  65. package/src/transform/profile.v2.schema.json +600 -0
  66. package/src/transform/profiles.ts +32 -1
  67. package/src/transform/scaffold.ts +124 -47
  68. package/src/transform/shadcn-v2-respelling.ts +475 -0
  69. package/src/transform/validate-v2.ts +174 -0
  70. package/src/types.ts +32 -0
  71. package/src/validate/ajv.ts +89 -26
  72. package/src/validate-v2.test.ts +173 -0
package/src/types.ts CHANGED
@@ -109,6 +109,38 @@ 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:
128
+ | "projected"
129
+ | "moved"
130
+ | "lifted"
131
+ | "flattened"
132
+ | "synthesized"
133
+ | "wrapped"
134
+ | "dropped"
135
+ | "deduplicated"
136
+ /** T1: a value harvested in a dissolving boundary, written onto its single eligible control. */
137
+ | "donated"
138
+ /** T3: a counterpart's data merged into a collected record via a declared key join. */
139
+ | "joined";
140
+ class: FidelityClass;
141
+ note?: string;
142
+ }
143
+
112
144
  export type FidelityClass =
113
145
  | "maps-cleanly"
114
146
  | "synthesis-defaults"
@@ -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).
@@ -49,6 +51,55 @@ function externalRefs(node: unknown, acc: string[] = []): string[] {
49
51
  return acc;
50
52
  }
51
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
+
52
103
  /** Pull every component instance (object with string `component` + `id`) from a surface. */
53
104
  export function extractInstances(surface: unknown, acc: Json[] = []): Json[] {
54
105
  if (Array.isArray(surface)) {
@@ -68,8 +119,9 @@ export function validateCatalog(
68
119
  ): ValidationReport {
69
120
  const gates: GateResult[] = [];
70
121
 
71
- // Gate 1 — schema compile + no external $ref.
122
+ // Gate 1 — schema compile + no external $ref + every internal $ref resolves.
72
123
  const exts = externalRefs(catalog);
124
+ const dangling = danglingInternalRefs(catalog);
73
125
  let compiled = false;
74
126
  let compileErr = "";
75
127
  try {
@@ -78,16 +130,18 @@ export function validateCatalog(
78
130
  } catch (e) {
79
131
  compileErr = e instanceof Error ? e.message : String(e);
80
132
  }
133
+ const selfContained = compiled && exts.length === 0 && dangling.length === 0;
81
134
  gates.push({
82
135
  name: "schema-compile + no-external-ref",
83
- pass: compiled && exts.length === 0,
84
- detail:
85
- compiled && exts.length === 0
86
- ? "Catalog compiles as a draft-2020-12 JSON Schema with only internal $refs."
87
- : !compiled
88
- ? `ajv failed to compile the catalog as a schema: ${compileErr}`
89
- : `Catalog contains external $refs: ${[...new Set(exts)].join(", ")}`,
90
- 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,
91
145
  });
92
146
 
93
147
  // Gate 2 — catalog shape.
@@ -103,29 +157,38 @@ export function validateCatalog(
103
157
  errors: shapeOk ? undefined : (validateShape.errors ?? []).map(fmtErr),
104
158
  });
105
159
 
106
- // 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).
107
161
  if (surface !== undefined) {
108
- if (!compiled) {
162
+ if (!compiled || dangling.length > 0) {
109
163
  gates.push({
110
164
  name: "instance",
111
165
  pass: false,
112
- 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.",
113
169
  });
114
170
  } else {
115
- const ajv = newAjv();
116
- ajv.addSchema(catalog as unknown as Json, catalog.$id);
117
- const validateAny = ajv.getSchema(`${catalog.$id}#/$defs/anyComponent`);
118
- 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.
119
173
  const failures: string[] = [];
120
- if (!validateAny) {
121
- failures.push("Could not resolve #/$defs/anyComponent from the catalog.");
122
- } else {
123
- for (const inst of instances) {
124
- if (!validateAny(inst)) {
125
- const where = `${inst.component}#${inst.id}`;
126
- 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
+ }
127
188
  }
128
189
  }
190
+ } catch (e) {
191
+ failures.push(`instance validation could not run: ${e instanceof Error ? e.message : String(e)}`);
129
192
  }
130
193
  gates.push({
131
194
  name: "instance",
@@ -0,0 +1,173 @@
1
+ /**
2
+ * Contract-facing validation: what a profile can only be wrong about against
3
+ * a contract, proven to refuse (v2) and proven NOT to change behaviour (v1).
4
+ *
5
+ * The enforcement decision this file records: derived sub-component coverage
6
+ * is fatal for v2 profiles at every entry, and report-plus-`--strict-coverage`
7
+ * for v1. Measured before enforcement (scripts/sub-coverage-report.mjs, the
8
+ * 2aac076 record): pinned shadcn v2.3.0, astryx and acme all derive zero
9
+ * unresolved subs — so the fatal gate refuses no shipped artifact, only
10
+ * future profiles with genuine gaps, which is the point.
11
+ */
12
+ import { readFileSync } from "node:fs";
13
+ import { fileURLToPath } from "node:url";
14
+ import { describe, expect, it } from "vitest";
15
+ import { transformFromJson } from "./transform/index.js";
16
+ import { emitSurface } from "./targets/a2ui/surface.js";
17
+ import { loadProfile } from "./transform/profile-load.js";
18
+ import { ProfileContractError } from "./transform/validate-v2.js";
19
+ import { shadcnProfile } from "./transform/profiles.js";
20
+ import type { DspackDoc, DspackSurface } from "./types.js";
21
+
22
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
23
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
24
+
25
+ /** A minimal v2 document whose one plan maps the contract's `card` compound. */
26
+ const v2Doc = (surface: unknown): Record<string, unknown> => ({
27
+ profileVersion: "2",
28
+ catalogTitle: "t",
29
+ catalogDescription: "d",
30
+ catalogIdBase: "https://example.test/catalogs/x",
31
+ instructions: "",
32
+ primaryColorToken: { category: "color", name: "primary" },
33
+ surfaceSynthesis: { textComponent: "Text", textProp: "text", wrapComponent: "Column", wrapChildrenProp: "children" },
34
+ synthesized: [
35
+ {
36
+ a2ui: "Text",
37
+ commons: ["ComponentCommon"],
38
+ structural: { text: { schema: { type: "string" }, description: "d", synthNote: "s" } },
39
+ propMap: { variant: { a2ui: "variant", kind: "enum", targetEnum: ["body", "h3", "caption"] } },
40
+ required: ["text"],
41
+ },
42
+ {
43
+ a2ui: "Column",
44
+ commons: ["ComponentCommon"],
45
+ structural: { children: { schema: { type: "array" }, description: "d", synthNote: "s" } },
46
+ required: ["children"],
47
+ },
48
+ ],
49
+ casualtyComponents: [],
50
+ components: [
51
+ {
52
+ a2ui: "Card",
53
+ dspackId: "card",
54
+ commons: ["ComponentCommon"],
55
+ structural: {
56
+ child: { schema: { type: "string" }, description: "d", synthNote: "s" },
57
+ label: { schema: { type: "string" }, description: "d", synthNote: "s" },
58
+ },
59
+ required: ["child"],
60
+ surface,
61
+ },
62
+ ],
63
+ });
64
+
65
+ /** The full card sub-family, resolved — the baseline that passes the gate. */
66
+ const RESOLVED = {
67
+ routes: [{ from: ["children"], to: "slot:child" }],
68
+ subs: {
69
+ "card-header": "transparent",
70
+ "card-content": "transparent",
71
+ "card-footer": "transparent",
72
+ "card-title": { asText: "h3" },
73
+ "card-description": { asText: "caption" },
74
+ },
75
+ };
76
+
77
+ const refusal = (surface: unknown): string => {
78
+ try {
79
+ transformFromJson(doc, { profile: loadProfile(v2Doc(surface)) });
80
+ return "PASSED";
81
+ } catch (e) {
82
+ if (e instanceof ProfileContractError) return e.issues.map((i) => `${i.path}: ${i.message}`).join("\n");
83
+ throw e;
84
+ }
85
+ };
86
+
87
+ describe("v2 contract validation refuses before emission", () => {
88
+ it("a fully resolved plan passes the gate", () => {
89
+ expect(refusal(RESOLVED)).toBe("PASSED");
90
+ });
91
+
92
+ it("an unresolved sub-component refuses, naming the sub and the decision to make", () => {
93
+ const { subs } = structuredClone(RESOLVED) as { subs: Record<string, unknown> };
94
+ delete subs["card-footer"];
95
+ const out = refusal({ ...RESOLVED, subs });
96
+ expect(out).toContain("'card-footer' of 'card' is unresolved");
97
+ expect(out).toContain("route, collect, transparent, asText, or drop");
98
+ });
99
+
100
+ it("a sub the contract does not declare refuses", () => {
101
+ const out = refusal({
102
+ ...RESOLVED,
103
+ subs: { ...RESOLVED.subs, "card-sidebar": "transparent" },
104
+ });
105
+ expect(out).toContain("'card-sidebar' is neither a declared sub-component of 'card' nor a component");
106
+ });
107
+
108
+ it("reading an undeclared prop into a renamed destination refuses; the passthrough shape passes", () => {
109
+ const renamed = refusal({
110
+ ...RESOLVED,
111
+ routes: [...RESOLVED.routes, { from: ["self.props.badge"], to: "prop:label" }],
112
+ });
113
+ expect(renamed).toContain("self.props.badge");
114
+ expect(renamed).toContain("not a same-named structural passthrough");
115
+
116
+ const passthrough = refusal({
117
+ ...RESOLVED,
118
+ routes: [...RESOLVED.routes, { from: ["self.props.label"], to: "prop:label" }],
119
+ });
120
+ expect(passthrough).toBe("PASSED");
121
+ });
122
+
123
+ it("emitSurface runs the same gate as transform", () => {
124
+ const { subs } = structuredClone(RESOLVED) as { subs: Record<string, unknown> };
125
+ delete subs["card-footer"];
126
+ const surface: DspackSurface = {
127
+ dspackSurface: "0.1",
128
+ system: doc.name as string,
129
+ intent: "record-collection",
130
+ root: { component: "card", children: [] },
131
+ } as unknown as DspackSurface;
132
+ expect(() => emitSurface(surface, doc, { profile: loadProfile(v2Doc({ ...RESOLVED, subs })) })).toThrowError(
133
+ ProfileContractError,
134
+ );
135
+ });
136
+ });
137
+
138
+ describe("v1 behaviour is frozen: report, not refusal", () => {
139
+ it("a v1 profile with an unresolved sub still transforms — the gap lands in coverage", () => {
140
+ // The shipped card plan, its subFlatten stripped: card's five subs become
141
+ // unresolved. v1 must keep transforming (byte-frozen behaviour) while the
142
+ // coverage report says exactly what is missing.
143
+ const gappy = {
144
+ ...structuredClone(shadcnProfile),
145
+ components: shadcnProfile.components.map((p) =>
146
+ p.dspackId === "card" ? { ...p, surfacePlan: { childProp: "child" } } : p,
147
+ ),
148
+ };
149
+ const out = transformFromJson(doc, { profile: gappy });
150
+ const unresolved = out.mapping.coverage.filter(
151
+ (c) => c.disposition === "unclassified" && c.id.startsWith("card."),
152
+ );
153
+ expect(unresolved.map((c) => c.id).sort()).toEqual([
154
+ "card.card-content",
155
+ "card.card-description",
156
+ "card.card-footer",
157
+ "card.card-header",
158
+ "card.card-title",
159
+ ]);
160
+ // And the strict-coverage contract: these are exactly what exit 3 keys on.
161
+ expect(out.mapping.warnings.some((w) => w.code === "unresolved-sub:card.card-title")).toBe(true);
162
+ });
163
+
164
+ it("the shipped profiles derive zero unresolved subs — the measured gate behind enforcement", () => {
165
+ const out = transformFromJson(doc, { profile: shadcnProfile });
166
+ const unresolved = out.mapping.coverage.filter((c) => c.disposition === "unclassified");
167
+ expect(unresolved).toEqual([]);
168
+ // Derived sub rows exist and carry their classification.
169
+ const subRows = out.mapping.coverage.filter((c) => c.id.includes("."));
170
+ expect(subRows.length).toBeGreaterThanOrEqual(20);
171
+ expect(subRows.every((c) => c.disposition === "mapped" && c.detail)).toBe(true);
172
+ });
173
+ });