@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
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Browser-safety boundary gate (mirrors dspack-gen's core-boundary test):
3
+ * the library surface — src/transform, src/validate, src/targets — must be
4
+ * bundleable for the browser, because the dspack-studio composer runs
5
+ * `transformFromJson`, `validateCatalog`, and `loadProfile` in-page for live
6
+ * fidelity feedback. No module in these directories may import a Node
7
+ * built-in (`node:*` or bare-specifier form); schema documents reach the
8
+ * runtime through committed TS mirrors, not readFileSync.
9
+ *
10
+ * src/cli.ts is deliberately out of scope: it is the Node CLI and owns all
11
+ * filesystem I/O. Tests may use node:fs freely (they run under vitest).
12
+ */
13
+ import { readFileSync, readdirSync } from "node:fs";
14
+ import { join } from "node:path";
15
+ import { describe, expect, it } from "vitest";
16
+
17
+ const BOUNDARY_DIRS = ["src/transform", "src/validate", "src/targets"];
18
+
19
+ // Bare-specifier built-ins that would slip past a `node:` prefix check.
20
+ const BARE_BUILTINS = new Set([
21
+ "fs", "path", "url", "os", "crypto", "util", "stream", "buffer",
22
+ "http", "https", "net", "tls", "child_process", "worker_threads",
23
+ ]);
24
+
25
+ const files = BOUNDARY_DIRS.flatMap((dir) =>
26
+ readdirSync(dir, { recursive: true })
27
+ .map(String)
28
+ .filter((f) => f.endsWith(".ts") && !f.endsWith(".test.ts"))
29
+ .map((f) => join(dir, f)),
30
+ );
31
+
32
+ describe("browser boundary", () => {
33
+ it("covers the library modules", () => {
34
+ expect(files.length).toBeGreaterThanOrEqual(10);
35
+ });
36
+
37
+ it.each(files)("%s imports no Node built-ins", (file) => {
38
+ const source = readFileSync(file, "utf8");
39
+ const imports = [...source.matchAll(/from\s+"([^"]+)"|import\s*\(\s*"([^"]+)"\s*\)|require\s*\(\s*"([^"]+)"\s*\)/g)].map(
40
+ (m) => m[1] ?? m[2] ?? m[3],
41
+ );
42
+ for (const specifier of imports) {
43
+ expect(specifier.startsWith("node:"), `${file} imports ${specifier}`).toBe(false);
44
+ expect(BARE_BUILTINS.has(specifier), `${file} imports Node built-in ${specifier}`).toBe(false);
45
+ }
46
+ });
47
+ });
@@ -0,0 +1,246 @@
1
+ /**
2
+ * Byte-neutrality gate for the internal transformation model.
3
+ *
4
+ * The emitter is being rewritten onto a smaller internal representation
5
+ * (Identity / Route / Collect) with the v1 surface-plan directives desugaring
6
+ * into it. That refactor is only legitimate if it is INVISIBLE: same contract
7
+ * + same profile => the same bytes, for every profile this package can reach
8
+ * and both supported A2UI versions.
9
+ *
10
+ * So this suite hashes real emitted artifacts and pins the digests. It is a
11
+ * tripwire, not a description: a failure here means output moved, and the only
12
+ * two acceptable responses are to fix the regression, or — when a digest is
13
+ * MEANT to move — to change it in the same commit that explains why.
14
+ *
15
+ * Deliberately hashes the *artifact*, not a summary of it. A shape assertion
16
+ * ("the catalog has 8 components") passes while every description silently
17
+ * changes; a digest does not.
18
+ */
19
+ import { createHash } from "node:crypto";
20
+ import { readFileSync } from "node:fs";
21
+ import { fileURLToPath } from "node:url";
22
+ import { describe, expect, it } from "vitest";
23
+ import { transformFromJson } from "./transform/index.js";
24
+ import { emitSurface } from "./targets/a2ui/surface.js";
25
+ import { loadProfile } from "./transform/profile-load.js";
26
+ import { scaffoldProfile } from "./transform/scaffold.js";
27
+ import { shadcnProfile } from "./transform/profiles.js";
28
+ import type { A2uiVersion, DspackDoc, DspackSurface } from "./types.js";
29
+
30
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
31
+ const load = (p: string) => JSON.parse(readFileSync(repo(p), "utf8"));
32
+
33
+ const shadcnDoc = load("input/shadcn-ui.dspack.json") as DspackDoc;
34
+ const astryxDoc = load("input/astryx.dspack.json") as DspackDoc;
35
+ const settingsCard = load("surface/settings-card.surface.json");
36
+
37
+ /** Stable digest of any emitted artifact. */
38
+ const digest = (value: unknown): string =>
39
+ createHash("sha256").update(JSON.stringify(value)).digest("hex").slice(0, 16);
40
+
41
+ /** The TS profile round-tripped through JSON exactly as a user file would be. */
42
+ const shadcnProfileJson = () => ({ profileVersion: "1", ...structuredClone(shadcnProfile) });
43
+
44
+ const VERSIONS: A2uiVersion[] = ["0.9.1", "1.0"];
45
+
46
+ /**
47
+ * Pinned digests. Every entry was produced by the pre-refactor engine and is
48
+ * the contract the refactor must honour.
49
+ */
50
+ const CATALOGS: Record<string, string> = {
51
+ // The TS and JSON spellings share a digest by design — profile-as-data is
52
+ // only credible if authoring a profile as a file changes nothing.
53
+ "shadcn/ts/0.9.1": "7c1b72dfd83dde14",
54
+ "shadcn/json/0.9.1": "7c1b72dfd83dde14",
55
+ "shadcn/ts/1.0": "2dde439bbf643834",
56
+ "shadcn/json/1.0": "2dde439bbf643834",
57
+ // INTENTIONAL MOVE (scaffold rewrite): the scaffold now emits the v2
58
+ // primitive language and derives children/text routes from the contract's
59
+ // worked examples, so scaffolded catalogs carry the slots the old scaffold
60
+ // omitted. The old digests described a scaffold that was surface-unusable
61
+ // for props-based contracts; these describe one that emits.
62
+ "astryx-scaffold/0.9.1": "ffb8fd24891bedfc",
63
+ "astryx-scaffold/1.0": "60f82244302ad1fd",
64
+ };
65
+
66
+ const SURFACES: Record<string, string> = {
67
+ "settings-card": "789f1b148b4ae935",
68
+ };
69
+
70
+ describe("catalog emission is byte-stable", () => {
71
+ for (const version of VERSIONS) {
72
+ it(`shadcn / TypeScript profile / a2ui ${version}`, () => {
73
+ const out = transformFromJson(shadcnDoc, { profile: shadcnProfile, a2uiVersion: version });
74
+ expect(digest(out.catalog)).toBe(CATALOGS[`shadcn/ts/${version}`]);
75
+ });
76
+
77
+ it(`shadcn / JSON profile / a2ui ${version} — and identical to the TS profile`, () => {
78
+ const fromJson = transformFromJson(shadcnDoc, {
79
+ profile: loadProfile(shadcnProfileJson()),
80
+ a2uiVersion: version,
81
+ });
82
+ const fromTs = transformFromJson(shadcnDoc, { profile: shadcnProfile, a2uiVersion: version });
83
+ expect(digest(fromJson.catalog)).toBe(CATALOGS[`shadcn/json/${version}`]);
84
+ // Profile-as-data is only credible if the two spellings are the same run.
85
+ expect(digest(fromJson.catalog)).toBe(digest(fromTs.catalog));
86
+ });
87
+
88
+ it(`astryx / scaffolded profile / a2ui ${version}`, () => {
89
+ const { profile } = scaffoldProfile(astryxDoc, {
90
+ catalogIdBase: "https://example.test/catalogs/astryx-scaffold",
91
+ });
92
+ const out = transformFromJson(astryxDoc, { profile: loadProfile(profile), a2uiVersion: version });
93
+ expect(digest(out.catalog)).toBe(CATALOGS[`astryx-scaffold/${version}`]);
94
+ });
95
+
96
+ it(`shadcn / scaffolded profile / a2ui ${version} — refuses until every sub is decided`, () => {
97
+ // INTENTIONAL MOVE (scaffold rewrite): the old scaffold auto-classified
98
+ // every sub transparent-or-asText — the exact guess that is wrong for a
99
+ // repeated item — and its digest pinned that invention. The scaffold's
100
+ // pinned behaviour for a compound contract is now the REFUSAL: it loads,
101
+ // and transform refuses per undecided sub until the author decides.
102
+ const { profile } = scaffoldProfile(shadcnDoc, {
103
+ catalogIdBase: "https://example.test/catalogs/shadcn-scaffold",
104
+ });
105
+ const loaded = loadProfile(profile); // loadProfile-valid stays true
106
+ try {
107
+ transformFromJson(shadcnDoc, { profile: loaded, a2uiVersion: version });
108
+ expect.unreachable("a scaffold with undecided subs must refuse to transform");
109
+ } catch (e) {
110
+ const issues = (e as { issues: Array<{ message: string }> }).issues;
111
+ expect(issues.length).toBeGreaterThanOrEqual(5); // card + alert-dialog + table sub-families at minimum
112
+ expect(issues.every((i) => i.message.includes("unresolved"))).toBe(true);
113
+ expect(issues.some((i) => i.message.includes("'card-header' of 'card'"))).toBe(true);
114
+ }
115
+ });
116
+ }
117
+ });
118
+
119
+ describe("surface emission is byte-stable", () => {
120
+ it("the hand-authored settings-card surface", () => {
121
+ expect(digest(settingsCard)).toBe(SURFACES["settings-card"]);
122
+ });
123
+
124
+ /**
125
+ * The contract's own worked examples are the corpus that defines
126
+ * "expressible". Messages AND warnings are hashed: a refactor that silently
127
+ * stopped warning about a flattened compound would otherwise pass.
128
+ */
129
+ const examples = (shadcnDoc as unknown as { examples?: Array<{ id: string; surface: DspackSurface }> }).examples ?? [];
130
+ it("the contract carries worked examples to hash", () => {
131
+ expect(examples.length).toBeGreaterThan(0);
132
+ });
133
+
134
+ it.each(examples.map((e) => [e.id] as const))("%s — messages and warnings", (id) => {
135
+ const example = examples.find((e) => e.id === id)!;
136
+ const { messages, warnings } = emitSurface(example.surface, shadcnDoc, { profile: shadcnProfile });
137
+ expect({ id, messages: digest(messages), warnings: digest(warnings) }).toMatchSnapshot();
138
+ });
139
+ });
140
+
141
+ /**
142
+ * The directive-exercising surfaces. The worked examples in the pinned v2.3.0
143
+ * contract do not reach every v1 directive, so these pin the rest by hand —
144
+ * each one is the smallest surface that reaches the named strategy.
145
+ */
146
+ describe("every v1 surface-plan directive is byte-pinned", () => {
147
+ const surface = (root: unknown, intent = "record-collection"): DspackSurface =>
148
+ ({ dspackSurface: "0.1", system: shadcnDoc.name as string, intent, root }) as DspackSurface;
149
+
150
+ const cases: Array<[string, DspackSurface]> = [
151
+ [
152
+ "textChildProp + actionProp (button)",
153
+ surface({ component: "button", text: "Save changes", props: { variant: "default" } }),
154
+ ],
155
+ [
156
+ "textProp (input, badge)",
157
+ surface({
158
+ component: "card",
159
+ children: [
160
+ { component: "input", text: "Email" },
161
+ { component: "badge", text: "New", props: { variant: "secondary" } },
162
+ ],
163
+ }),
164
+ ],
165
+ [
166
+ "subFlatten.transparent + asText (card sub-family)",
167
+ surface({
168
+ component: "card",
169
+ children: [
170
+ {
171
+ component: "card-header",
172
+ children: [
173
+ { component: "card-title", text: "Members" },
174
+ { component: "card-description", text: "Everyone with access." },
175
+ ],
176
+ },
177
+ { component: "card-content", text: "Three people." },
178
+ ],
179
+ }),
180
+ ],
181
+ [
182
+ "subTable (table sub-family, header + body + caption)",
183
+ surface({
184
+ component: "table",
185
+ children: [
186
+ { component: "table-caption", text: "Recent orders" },
187
+ {
188
+ component: "table-header",
189
+ children: [{ component: "table-row", children: [{ component: "table-head", text: "Order" }, { component: "table-head", text: "Status" }] }],
190
+ },
191
+ {
192
+ component: "table-body",
193
+ children: [
194
+ { component: "table-row", children: [{ component: "table-cell", text: "#1001" }, { component: "table-cell", text: "Shipped" }] },
195
+ { component: "table-row", children: [{ component: "table-cell", text: "#1002" }, { component: "table-cell", text: "Pending" }] },
196
+ ],
197
+ },
198
+ ],
199
+ }),
200
+ ],
201
+ [
202
+ "subText + subButtonText + actionProp (alert-dialog)",
203
+ surface(
204
+ {
205
+ component: "alert-dialog",
206
+ children: [
207
+ { component: "alert-dialog-trigger", children: [{ component: "button", text: "Delete" }] },
208
+ {
209
+ component: "alert-dialog-content",
210
+ children: [
211
+ { component: "alert-dialog-title", text: "Delete project?" },
212
+ { component: "alert-dialog-description", text: "This cannot be undone." },
213
+ ],
214
+ },
215
+ ],
216
+ },
217
+ "destructive-action",
218
+ ),
219
+ ],
220
+ [
221
+ "childProp with >1 children (synthesized Column wrap)",
222
+ surface({
223
+ component: "card",
224
+ children: [
225
+ { component: "badge", text: "One" },
226
+ { component: "badge", text: "Two" },
227
+ ],
228
+ }),
229
+ ],
230
+ [
231
+ "id deduplication (two nodes claiming one id)",
232
+ surface({
233
+ component: "card",
234
+ children: [
235
+ { component: "badge", id: "tag", text: "One" },
236
+ { component: "badge", id: "tag", text: "Two" },
237
+ ],
238
+ }),
239
+ ],
240
+ ];
241
+
242
+ it.each(cases)("%s", (_name, s) => {
243
+ const { messages, warnings } = emitSurface(s, shadcnDoc, { profile: shadcnProfile });
244
+ expect({ messages: digest(messages), warnings: digest(warnings) }).toMatchSnapshot();
245
+ });
246
+ });
package/src/cli.ts CHANGED
@@ -47,11 +47,21 @@ interface Args {
47
47
  profile?: string;
48
48
  emitSurface?: string;
49
49
  strictCoverage: boolean;
50
+ /** Fidelity classes that fail an emitted surface; undefined = not strict. */
51
+ strictSurface?: string[];
50
52
  }
51
53
 
52
54
  /** Flags that take no value; their presence means `true`. */
53
55
  const BOOLEAN_FLAGS = new Set(["strict-coverage"]);
54
56
 
57
+ /**
58
+ * Flags whose value is optional: bare `--strict-surface` means the default
59
+ * class set; `--strict-surface=lossy,synthesis-defaults` configures it.
60
+ */
61
+ const OPTIONAL_VALUE_FLAGS = new Set(["strict-surface"]);
62
+ const STRICT_SURFACE_DEFAULT = ["lossy", "cannot-represent"];
63
+ const FIDELITY_CLASSES = new Set(["maps-cleanly", "synthesis-defaults", "lossy", "cannot-represent"]);
64
+
55
65
  function parseArgs(argv: string[]): Args {
56
66
  // Supports `--key value`, `--key=value`, and valueless boolean flags; fails fast
57
67
  // on a malformed flag or a value-taking `--key` missing its value.
@@ -64,6 +74,14 @@ function parseArgs(argv: string[]): Args {
64
74
  m.set(tok.slice(2, eq), tok.slice(eq + 1));
65
75
  } else if (BOOLEAN_FLAGS.has(tok.slice(2))) {
66
76
  m.set(tok.slice(2), "true");
77
+ } else if (OPTIONAL_VALUE_FLAGS.has(tok.slice(2))) {
78
+ const next = argv[i + 1];
79
+ if (next !== undefined && !next.startsWith("--")) {
80
+ m.set(tok.slice(2), next);
81
+ i++;
82
+ } else {
83
+ m.set(tok.slice(2), "");
84
+ }
67
85
  } else {
68
86
  const value = argv[++i];
69
87
  if (value === undefined) fail(`flag '${tok}' is missing a value`);
@@ -95,9 +113,50 @@ function parseArgs(argv: string[]): Args {
95
113
  profile,
96
114
  emitSurface: m.get("emit-surface"),
97
115
  strictCoverage: m.get("strict-coverage") === "true",
116
+ strictSurface: parseStrictSurface(m),
98
117
  };
99
118
  }
100
119
 
120
+ function parseStrictSurface(m: Map<string, string>): string[] | undefined {
121
+ if (!m.has("strict-surface")) return undefined;
122
+ const raw = m.get("strict-surface")!;
123
+ const classes = raw === "" ? STRICT_SURFACE_DEFAULT : raw.split(",").map((c) => c.trim());
124
+ for (const c of classes) {
125
+ if (!FIDELITY_CLASSES.has(c)) {
126
+ fail(`--strict-surface: unknown fidelity class '${c}' (known: ${[...FIDELITY_CLASSES].join(", ")})`);
127
+ }
128
+ }
129
+ return classes;
130
+ }
131
+
132
+ /**
133
+ * The strict-surface gate: print the emitted surface's fidelity ledger, then
134
+ * fail (exit 5) when any entry's class is in the configured set. Loss is
135
+ * never invisible — without the flag the ledger still prints; the flag makes
136
+ * the configured classes FATAL rather than informational.
137
+ */
138
+ function gateSurfaceFidelity(
139
+ tag: string,
140
+ fidelity: Array<{ source: string; destination: string; origin: string; kind: string; class: string; note?: string }>,
141
+ strict: string[] | undefined,
142
+ ): void {
143
+ const counts = new Map<string, number>();
144
+ for (const f of fidelity) counts.set(f.class, (counts.get(f.class) ?? 0) + 1);
145
+ const summary = [...counts.entries()].map(([c, n]) => `${c}=${n}`).join(" ") || "none";
146
+ console.log(`${tag} fidelity ${fidelity.length} transformation(s): ${summary}`);
147
+ if (!strict) return;
148
+ const failing = fidelity.filter((f) => strict.includes(f.class));
149
+ if (failing.length === 0) {
150
+ console.log(`${tag} PASS strict-surface (no ${strict.join("/")} transformations)`);
151
+ return;
152
+ }
153
+ console.error(`${tag} STRICT-SURFACE: ${failing.length} transformation(s) in failing class(es) ${strict.join(", ")}:`);
154
+ for (const f of failing) {
155
+ console.error(`${tag} [${f.class}] ${f.kind} ${f.source} -> ${f.destination} (${f.origin})${f.note ? ` — ${f.note}` : ""}`);
156
+ }
157
+ process.exit(5);
158
+ }
159
+
101
160
  function fail(msg: string): never {
102
161
  console.error(`error: ${msg}`);
103
162
  process.exit(2);
@@ -207,6 +266,7 @@ function main(): void {
207
266
  const outPath = join(base, `${name}.surface.json`);
208
267
  writeFileSync(outPath, JSON.stringify({ messages: emitted.messages }, null, 2) + "\n");
209
268
  for (const w of emitted.warnings) console.log(`${tag} note ${w.code}: ${w.message}`);
269
+ gateSurfaceFidelity(tag, emitted.fidelity, args.strictSurface);
210
270
  // Gate A3 over the emitted surface: its instances must validate against the
211
271
  // catalog generated in this same run.
212
272
  const check = transform(doc, args.version, { messages: emitted.messages }, profile);
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Internal $ref discipline — one boundary, every authored-schema channel.
3
+ *
4
+ * Gate 1's documented guarantee ("compilation fails on any unresolved $ref,
5
+ * proving the catalog is a valid, fully self-contained schema") was FALSE:
6
+ * ajv defers ref resolution past compile(), so a structural slot schema
7
+ * carrying `{$ref: "#/$defs/DoesNotExist"}` produced either all-gates-PASS
8
+ * (no surface supplied) or a raw MissingRefError thrown out of gate 3's
9
+ * un-guarded getSchema (the main transform path) — pass-or-crash, never a
10
+ * finding. The functions channel was closed at load (profile-load refuses
11
+ * $ref in args outright); structural schemas legitimately ref the catalog's
12
+ * own $defs, so their discipline lives where the catalog exists: gate 1 now
13
+ * RESOLVES every internal ref and fails with the ref and its JSON path, and
14
+ * gate 3 is crash-proofed so no path ever escapes as a raw ajv error.
15
+ */
16
+ import { readFileSync } from "node:fs";
17
+ import { fileURLToPath } from "node:url";
18
+ import { describe, expect, it } from "vitest";
19
+ import { transformFromJson } from "./transform/index.js";
20
+ import { validateCatalog } from "./validate/ajv.js";
21
+ import { loadProfile } from "./transform/profile-load.js";
22
+ import { shadcnProfile } from "./transform/profiles.js";
23
+ import type { A2uiCatalog, DspackDoc } from "./types.js";
24
+
25
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
26
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
27
+
28
+ /** The shipped profile with ONE structural slot schema pointing at nothing. */
29
+ const withDanglingStructural = () => {
30
+ const profile = structuredClone(shadcnProfile);
31
+ profile.components = profile.components.map((p) =>
32
+ p.dspackId === "badge"
33
+ ? {
34
+ ...p,
35
+ structural: {
36
+ ...p.structural,
37
+ label: { ...p.structural.label, schema: { $ref: "#/$defs/DoesNotExist" } },
38
+ },
39
+ }
40
+ : p,
41
+ );
42
+ return profile;
43
+ };
44
+
45
+ describe("a dangling internal $ref is a finding, never a pass and never a crash", () => {
46
+ it("gate 1 fails with the ref and its location — no surface supplied (the silent-pass path)", () => {
47
+ const out = transformFromJson(doc, { profile: withDanglingStructural(), surface: undefined });
48
+ const gate = out.validation.gates.find((g) => g.name === "schema-compile + no-external-ref");
49
+ expect(gate?.pass).toBe(false);
50
+ expect(gate?.errors?.join("\n")).toContain("#/$defs/DoesNotExist");
51
+ expect(gate?.errors?.join("\n")).toContain("components/Badge");
52
+ expect(out.validation.pass).toBe(false);
53
+ });
54
+
55
+ it("the main transform path reports the same finding instead of throwing raw (the crash path)", () => {
56
+ // Pre-fix: this exact call escaped as an uncaught ajv MissingRefError.
57
+ const out = transformFromJson(doc, { profile: withDanglingStructural() });
58
+ expect(out.validation.pass).toBe(false);
59
+ const gate1 = out.validation.gates.find((g) => g.name === "schema-compile + no-external-ref");
60
+ expect(gate1?.pass).toBe(false);
61
+ const gate3 = out.validation.gates.find((g) => g.name === "instance");
62
+ expect(gate3?.pass).toBe(false); // skipped-as-failed, with a reason — not a crash
63
+ expect(gate3?.detail).toContain("self-contained");
64
+ });
65
+
66
+ it("a dangling ref in a v2 document's structural schema is caught by the same boundary", () => {
67
+ const v2 = {
68
+ profileVersion: "2",
69
+ catalogTitle: "t",
70
+ catalogDescription: "d",
71
+ catalogIdBase: "https://example.test/catalogs/x",
72
+ instructions: "",
73
+ primaryColorToken: { category: "color", name: "primary" },
74
+ surfaceSynthesis: { textComponent: "Text", textProp: "text", wrapComponent: "Column", wrapChildrenProp: "children" },
75
+ synthesized: [
76
+ {
77
+ a2ui: "Text",
78
+ commons: ["ComponentCommon"],
79
+ structural: { text: { schema: { $ref: "#/$defs/Nope" }, description: "d", synthNote: "s" } },
80
+ required: ["text"],
81
+ },
82
+ ],
83
+ casualtyComponents: [],
84
+ components: [],
85
+ };
86
+ const out = transformFromJson(doc, { profile: loadProfile(v2), surface: undefined });
87
+ const gate = out.validation.gates.find((g) => g.name === "schema-compile + no-external-ref");
88
+ expect(gate?.pass).toBe(false);
89
+ expect(gate?.errors?.join("\n")).toContain("#/$defs/Nope");
90
+ });
91
+
92
+ it("validateCatalog as a public API reports rather than passes on a hand-built broken catalog", () => {
93
+ const broken = {
94
+ $schema: "https://json-schema.org/draft/2020-12/schema",
95
+ $id: "https://example.test/broken/catalog.json",
96
+ title: "t",
97
+ description: "d",
98
+ catalogId: "https://example.test/broken/catalog.json",
99
+ components: { Widget: { type: "object", properties: { part: { $ref: "#/$defs/Missing" } } } },
100
+ $defs: { anyComponent: { oneOf: [{ $ref: "#/components/Widget" }] } },
101
+ } as unknown as A2uiCatalog;
102
+ const report = validateCatalog(broken, "0.9.1");
103
+ const gate = report.gates.find((g) => g.name === "schema-compile + no-external-ref");
104
+ expect(gate?.pass).toBe(false);
105
+ expect(gate?.errors?.join("\n")).toContain("#/$defs/Missing");
106
+ });
107
+
108
+ it("every legitimate ref shape the shipped profiles use keeps passing", () => {
109
+ // The shipped v1 profile refs ComponentId, Action, DynamicString,
110
+ // ChildList, CheckRule via structural schemas — all must still resolve.
111
+ const out = transformFromJson(doc, { profile: shadcnProfile });
112
+ expect(out.validation.pass).toBe(true);
113
+ // And a valid ref into a NESTED pointer (components/<Name>) resolves too:
114
+ // the catalog's own anyComponent does exactly this.
115
+ const gate = out.validation.gates.find((g) => g.name === "schema-compile + no-external-ref");
116
+ expect(gate?.pass).toBe(true);
117
+ });
118
+ });
@@ -0,0 +1,162 @@
1
+ /**
2
+ * v1 desugaring is TOTAL.
3
+ *
4
+ * The danger of a desugaring layer is not that it translates something wrongly
5
+ * — byte-neutral.test.ts catches that. It is that it translates something into
6
+ * NOTHING: a directive quietly falling through the desugarer still type-checks,
7
+ * still loads, and simply stops taking effect. So this suite asserts coverage
8
+ * directly: every directive the v1 type declares must be reachable, and every
9
+ * directive actually authored in a shipped profile must produce model facts.
10
+ */
11
+ import { describe, expect, it } from "vitest";
12
+ import { desugar, surfaceModelOf } from "./transform/desugar.js";
13
+ import { deriveSubCoverage, destinationsOf, unclassifiedSubs, type SurfaceModel } from "./transform/model.js";
14
+ import { shadcnProfile, type SurfacePlanDirectives } from "./transform/profiles.js";
15
+
16
+ /** Every key the v1 directive type declares. Update deliberately, never to go green. */
17
+ const V1_DIRECTIVES: Array<keyof SurfacePlanDirectives> = [
18
+ "subText",
19
+ "subButtonText",
20
+ "actionProp",
21
+ "textChildProp",
22
+ "textProp",
23
+ "childProp",
24
+ "childrenProp",
25
+ "structuralPassthrough",
26
+ "subTable",
27
+ "subFlatten",
28
+ ];
29
+
30
+ /** Did desugaring record anything at all? */
31
+ const isEmpty = (m: SurfaceModel): boolean =>
32
+ m.routes.length === 0 &&
33
+ m.collects.length === 0 &&
34
+ Object.keys(m.subIdentity).length === 0 &&
35
+ Object.keys(m.drops).length === 0;
36
+
37
+ /** A minimal authored value for each directive, enough to exercise its branch. */
38
+ const SAMPLE: { [K in keyof SurfacePlanDirectives]-?: SurfacePlanDirectives[K] } = {
39
+ subText: { "x-title": "title" },
40
+ subButtonText: { "x-trigger": "triggerLabel" },
41
+ actionProp: "onConfirm",
42
+ textChildProp: "child",
43
+ textProp: "label",
44
+ childProp: "child",
45
+ childrenProp: "children",
46
+ structuralPassthrough: ["columns"],
47
+ subTable: {
48
+ caption: "t-caption",
49
+ header: "t-header",
50
+ headerCell: "t-head",
51
+ body: "t-body",
52
+ row: "t-row",
53
+ cell: "t-cell",
54
+ targetCaption: "caption",
55
+ targetColumns: "columns",
56
+ targetRows: "rows",
57
+ drops: { "t-footer": "no slot in the synthesized shape" },
58
+ },
59
+ subFlatten: { transparent: ["x-header"], asText: { "x-title": "h3" } },
60
+ };
61
+
62
+ describe("every v1 directive desugars into model facts", () => {
63
+ it.each(V1_DIRECTIVES.map((d) => [d] as const))("%s produces a non-empty model", (directive) => {
64
+ const model = desugar({ [directive]: SAMPLE[directive] } as SurfacePlanDirectives);
65
+ expect(isEmpty(model)).toBe(false);
66
+ });
67
+
68
+ it("an empty surface plan produces an empty model (no invented facts)", () => {
69
+ expect(isEmpty(desugar({}))).toBe(true);
70
+ expect(desugar({}).consumesSubtree).toBe(false);
71
+ });
72
+
73
+ it("the sample set covers every declared directive — no directive is untested", () => {
74
+ expect(Object.keys(SAMPLE).sort()).toEqual([...V1_DIRECTIVES].sort());
75
+ });
76
+ });
77
+
78
+ describe("directives keep their v1 meaning", () => {
79
+ it("only the consuming three absorb the subtree", () => {
80
+ for (const d of ["subText", "subButtonText", "subTable"] as const) {
81
+ expect(desugar({ [d]: SAMPLE[d] } as SurfacePlanDirectives).consumesSubtree).toBe(true);
82
+ }
83
+ // subFlatten rewrites the child list but does NOT consume the subtree.
84
+ for (const d of ["subFlatten", "textProp", "childProp", "childrenProp", "actionProp"] as const) {
85
+ expect(desugar({ [d]: SAMPLE[d] } as SurfacePlanDirectives).consumesSubtree).toBe(false);
86
+ }
87
+ });
88
+
89
+ it("textProp and textChildProp overwrite; consuming routes are first-wins", () => {
90
+ expect(desugar({ textProp: "label" }).routes[0].overwrite).toBe(true);
91
+ expect(desugar({ textChildProp: "child" }).routes[0].overwrite).toBe(true);
92
+ expect(desugar({ subText: { a: "title" } }).routes[0].overwrite).toBeUndefined();
93
+ });
94
+
95
+ it("structuralPassthrough is ordered before consumed values so it wins", () => {
96
+ const model = desugar({ structuralPassthrough: ["columns"], subTable: SAMPLE.subTable });
97
+ expect(model.routes[0].origin).toBe("structuralPassthrough");
98
+ });
99
+
100
+ it("subButtonText carries the lift as an ordered fallback, not a special case", () => {
101
+ const [route] = desugar({ subButtonText: { "x-trigger": "triggerLabel" } }).routes;
102
+ expect(route.from.map((s) => s.kind)).toEqual(["sub-label", "sub-text-lift"]);
103
+ });
104
+
105
+ it("childrenProp wins over childProp when a plan declares both (v1 order)", () => {
106
+ const model = desugar({ childProp: "child", childrenProp: "children" });
107
+ expect(model.routes).toHaveLength(1);
108
+ expect(model.routes[0].to).toEqual({ kind: "slots", name: "children" });
109
+ });
110
+
111
+ it("subTable becomes nested collects, not a grammar", () => {
112
+ const model = desugar({ subTable: SAMPLE.subTable });
113
+ expect(model.collects).toHaveLength(2);
114
+ // The row-record key was a literal in the v1 emitter; here it is data.
115
+ expect(Object.keys(model.collects[1].item!)).toEqual(["cells"]);
116
+ // A header-cell is accepted wherever a cell is — the set-valued selector.
117
+ const scalar = (model.collects[1].item!.cells as { scalar: { from: Array<{ subs?: string[] }> } }).scalar;
118
+ expect(scalar.from[0].subs).toEqual(["t-cell", "t-head"]);
119
+ // Drops are ordinary drops with their authored reason, not a table concept.
120
+ expect(model.drops["t-footer"]).toContain("no slot");
121
+ });
122
+ });
123
+
124
+ describe("the shipped profile desugars completely", () => {
125
+ const authored = shadcnProfile.components.filter((p) => p.surfacePlan);
126
+
127
+ it("every plan with directives produces model facts", () => {
128
+ expect(authored.length).toBeGreaterThan(0);
129
+ for (const plan of authored) {
130
+ expect(`${plan.dspackId}: ${isEmpty(surfaceModelOf(plan)) ? "EMPTY" : "ok"}`).not.toContain("EMPTY");
131
+ }
132
+ });
133
+
134
+ it("every destination the model writes names a literal property", () => {
135
+ for (const plan of shadcnProfile.components) {
136
+ for (const dest of destinationsOf(surfaceModelOf(plan))) {
137
+ expect(dest.name).toBeTruthy();
138
+ expect(typeof dest.name).toBe("string");
139
+ }
140
+ }
141
+ });
142
+
143
+ it("derived sub coverage accounts for every sub the authored subCoverage lists", () => {
144
+ for (const plan of shadcnProfile.components) {
145
+ const authoredSubs = Object.keys(plan.subCoverage ?? {});
146
+ if (authoredSubs.length === 0) continue;
147
+ // Derivation reproduces the authored prose without being told it — the
148
+ // precondition for retiring `subCoverage` as hand-maintained documentation.
149
+ const derived = deriveSubCoverage(surfaceModelOf(plan), authoredSubs);
150
+ for (const sub of authoredSubs) {
151
+ expect(`${plan.dspackId} -> ${sub}: ${derived.get(sub) ?? "MISSING"}`).not.toContain("MISSING");
152
+ }
153
+ expect(unclassifiedSubs(surfaceModelOf(plan), authoredSubs)).toEqual([]);
154
+ }
155
+ });
156
+
157
+ it("a sub the model cannot account for is unclassified, not quietly covered", () => {
158
+ // `badge` has no consuming directive, so an invented sub has nowhere to go.
159
+ const badge = shadcnProfile.components.find((p) => p.dspackId === "badge")!;
160
+ expect(unclassifiedSubs(surfaceModelOf(badge), ["badge-icon"])).toEqual(["badge-icon"]);
161
+ });
162
+ });