@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,213 @@
1
+ /**
2
+ * The surface transformation ledger, and the strict gate over it.
3
+ *
4
+ * Every route, collect, projection, and synthesis reports what it DID —
5
+ * source, destination, originating profile rule, kind, fidelity class. The
6
+ * ledger is additive: messages and warnings stay byte-frozen (the byte gate
7
+ * proves that separately); this file proves the ledger itself is complete,
8
+ * ordered, and honest for each transformation the engine performs.
9
+ */
10
+ import { readFileSync } from "node:fs";
11
+ import { execFileSync } from "node:child_process";
12
+ import { fileURLToPath } from "node:url";
13
+ import { describe, expect, it } from "vitest";
14
+ import { emitSurface } from "./targets/a2ui/surface.js";
15
+ import { shadcnProfile } from "./transform/profiles.js";
16
+ import type { DspackDoc, DspackSurface, SurfaceFidelityEntry } from "./types.js";
17
+
18
+ const repo = (p: string) => fileURLToPath(new URL(`../${p}`, import.meta.url));
19
+ const doc = JSON.parse(readFileSync(repo("input/shadcn-ui.dspack.json"), "utf8")) as DspackDoc;
20
+
21
+ const surface = (root: unknown, intent = "record-collection"): DspackSurface =>
22
+ ({ dspackSurface: "0.1", system: doc.name as string, intent, root }) as DspackSurface;
23
+
24
+ const fidelityOf = (root: unknown, intent?: string): SurfaceFidelityEntry[] =>
25
+ emitSurface(surface(root, intent), doc, { profile: shadcnProfile }).fidelity;
26
+
27
+ describe("every transformation reports itself", () => {
28
+ it("propMap projection: clean, default-substituted, and dropped are distinguished", () => {
29
+ const entries = fidelityOf({ component: "button", text: "Save", props: { variant: "default" } });
30
+ // 'default' -> 'primary' is a valueMap HIT: projected, maps-cleanly.
31
+ const projected = entries.find((e) => e.origin === "propMap.variant");
32
+ expect(projected).toMatchObject({ kind: "projected", class: "maps-cleanly", destination: "variant" });
33
+
34
+ const dropped = fidelityOf({ component: "button", text: "Save", props: { hovercolor: "red" } });
35
+ expect(dropped.find((e) => e.source.includes("hovercolor"))).toMatchObject({
36
+ kind: "dropped",
37
+ class: "lossy",
38
+ destination: "(discarded)",
39
+ });
40
+ });
41
+
42
+ it("synthesized action and synthesized text child carry synthesis-defaults and their origin rule", () => {
43
+ const entries = fidelityOf({ component: "button", text: "Save changes" });
44
+ const action = entries.find((e) => e.kind === "synthesized" && e.destination === "action");
45
+ expect(action).toMatchObject({ class: "synthesis-defaults", origin: "actionProp" });
46
+ expect(action!.source).toContain("no source");
47
+ const text = entries.find((e) => e.kind === "synthesized" && e.destination.includes("Text"));
48
+ expect(text).toMatchObject({ class: "synthesis-defaults", origin: "surfaceSynthesis.textComponent" });
49
+ });
50
+
51
+ it("consuming a compound records each moved harvest, the lift, and one lossy flatten", () => {
52
+ const entries = fidelityOf(
53
+ {
54
+ component: "alert-dialog",
55
+ children: [
56
+ { component: "alert-dialog-trigger", text: "Remove" },
57
+ {
58
+ component: "alert-dialog-content",
59
+ children: [
60
+ { component: "alert-dialog-title", text: "Sure?" },
61
+ { component: "alert-dialog-description", text: "Gone forever." },
62
+ ],
63
+ },
64
+ ],
65
+ },
66
+ "destructive-action",
67
+ );
68
+ const moved = entries.filter((e) => e.kind === "moved");
69
+ expect(moved.map((e) => e.destination)).toEqual(expect.arrayContaining(["title", "description"]));
70
+ // Source paths locate the harvested node, not just the compound.
71
+ expect(moved.find((e) => e.destination === "title")!.source).toContain("alert-dialog-title");
72
+ const lift = entries.find((e) => e.kind === "lifted");
73
+ expect(lift).toMatchObject({ destination: "triggerLabel", class: "maps-cleanly" });
74
+ expect(lift!.note).toContain("audited");
75
+ const flatten = entries.filter((e) => e.kind === "flattened" && e.class === "lossy");
76
+ expect(flatten).toHaveLength(1);
77
+ expect(flatten[0].origin).toContain("subText");
78
+ });
79
+
80
+ it("collection records the gathered rows, per-cell flattening losses, and drops", () => {
81
+ const entries = fidelityOf({
82
+ component: "table",
83
+ children: [
84
+ { component: "table-caption", text: "Orders" },
85
+ {
86
+ component: "table-body",
87
+ children: [
88
+ {
89
+ component: "table-row",
90
+ children: [
91
+ { component: "table-cell", children: [{ component: "badge", text: "Paid" }] },
92
+ { component: "table-cell", text: "#1" },
93
+ ],
94
+ },
95
+ ],
96
+ },
97
+ { component: "table-footer", text: "1 order" },
98
+ ],
99
+ });
100
+ expect(entries.find((e) => e.destination === "rows")).toMatchObject({ kind: "moved", class: "maps-cleanly" });
101
+ const cellFlatten = entries.find((e) => e.kind === "flattened" && e.source.includes("badge"));
102
+ expect(cellFlatten).toMatchObject({ class: "lossy" });
103
+ const footerDrop = entries.find((e) => e.kind === "dropped" && e.source.includes("table-footer"));
104
+ expect(footerDrop).toMatchObject({ class: "lossy", origin: "drops.table-footer" });
105
+ expect(footerDrop!.note).toContain("summary rows");
106
+ });
107
+
108
+ it("transparent grouping and the wrap both report; dedup reports as clean", () => {
109
+ const entries = fidelityOf({
110
+ component: "card",
111
+ children: [
112
+ { component: "card-header", children: [{ component: "card-title", text: "T" }] },
113
+ { component: "badge", id: "b", text: "One" },
114
+ { component: "badge", id: "b", text: "Two" },
115
+ ],
116
+ });
117
+ expect(entries.find((e) => e.kind === "flattened" && e.source.includes("card-header"))).toMatchObject({
118
+ class: "lossy",
119
+ origin: "subs.card-header",
120
+ });
121
+ expect(entries.find((e) => e.kind === "wrapped")).toMatchObject({ class: "synthesis-defaults" });
122
+ expect(entries.find((e) => e.kind === "deduplicated")).toMatchObject({ class: "maps-cleanly" });
123
+ });
124
+
125
+ it("the ledger is deterministic and ordered like the warnings", () => {
126
+ const run = () =>
127
+ fidelityOf({
128
+ component: "card",
129
+ children: [
130
+ { component: "card-header", children: [{ component: "card-title", text: "T" }] },
131
+ { component: "button", text: "Go" },
132
+ { component: "badge", text: "New" },
133
+ ],
134
+ });
135
+ expect(JSON.stringify(run())).toBe(JSON.stringify(run()));
136
+ const entries = run();
137
+ // The wrap (after children) is last, exactly like its warning.
138
+ expect(entries[entries.length - 1].kind).toBe("wrapped");
139
+ });
140
+
141
+ it("a clean emission reports maps-cleanly entries and nothing lossy", () => {
142
+ const entries = fidelityOf({ component: "input", text: "Email" });
143
+ expect(entries.length).toBeGreaterThan(0);
144
+ expect(entries.every((e) => e.class === "maps-cleanly" || e.class === "synthesis-defaults")).toBe(true);
145
+ });
146
+ });
147
+
148
+ describe("--strict-surface", () => {
149
+ const cli = (args: string[]): { status: number; output: string } => {
150
+ try {
151
+ const out = execFileSync("npx", ["tsx", "src/cli.ts", ...args], {
152
+ cwd: repo(""),
153
+ encoding: "utf8",
154
+ stdio: ["ignore", "pipe", "pipe"],
155
+ });
156
+ return { status: 0, output: out };
157
+ } catch (e) {
158
+ const err = e as { status: number; stdout?: string; stderr?: string };
159
+ return { status: err.status, output: `${err.stdout ?? ""}${err.stderr ?? ""}` };
160
+ }
161
+ };
162
+
163
+ // A surface whose emission is lossy: a card whose transparent header dissolves.
164
+ const SCRATCH = repo("node_modules/.zz-fidelity-scratch");
165
+ const LOSSY = `${SCRATCH}/zz-lossy.dsurface.json`;
166
+ const CLEAN = `${SCRATCH}/zz-clean.dsurface.json`;
167
+
168
+ it("fails on configured classes with exit 5, naming each failing transformation", () => {
169
+ const fs = require("node:fs") as typeof import("node:fs");
170
+ fs.mkdirSync(SCRATCH, { recursive: true });
171
+ fs.writeFileSync(
172
+ LOSSY,
173
+ JSON.stringify(
174
+ surface({
175
+ component: "card",
176
+ children: [{ component: "card-header", children: [{ component: "card-title", text: "T" }] }],
177
+ }),
178
+ ),
179
+ );
180
+ const strict = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-lossy.dsurface.json", "--strict-surface"]);
181
+ expect(strict.status).toBe(5);
182
+ expect(strict.output).toContain("STRICT-SURFACE");
183
+ expect(strict.output).toContain("[lossy]");
184
+ expect(strict.output).toContain("subs.card-header");
185
+
186
+ // Without the flag the same emission succeeds — loss is visible, not fatal.
187
+ const loose = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-lossy.dsurface.json"]);
188
+ expect(loose.status).toBe(0);
189
+ expect(loose.output).toContain("fidelity");
190
+ });
191
+
192
+ it("passes a clean surface, and the class set is configurable", () => {
193
+ const fs = require("node:fs") as typeof import("node:fs");
194
+ fs.writeFileSync(CLEAN, JSON.stringify(surface({ component: "input", text: "Email" })));
195
+ const strict = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-clean.dsurface.json", "--strict-surface"]);
196
+ expect(strict.status).toBe(0);
197
+ expect(strict.output).toContain("PASS strict-surface");
198
+
199
+ // synthesis-defaults included -> a button's synthesized Text child and
200
+ // action now fail it (input stays clean even then: textProp is a plain
201
+ // move, which is exactly why the class set is worth configuring).
202
+ const fs2 = require("node:fs") as typeof import("node:fs");
203
+ fs2.writeFileSync(`${SCRATCH}/zz-synth.dsurface.json`, JSON.stringify(surface({ component: "button", text: "Go" })));
204
+ const strictest = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-synth.dsurface.json", "--strict-surface=lossy,synthesis-defaults"]);
205
+ expect(strictest.status).toBe(5);
206
+ expect(strictest.output).toContain("[synthesis-defaults]");
207
+
208
+ // An unknown class is a usage error, not a silent no-op.
209
+ const bad = cli(["--in", "input/shadcn-ui.dspack.json", "--a2ui-version", "0.9.1", "--out", "node_modules/.zz-fidelity-scratch", "--emit-surface", "node_modules/.zz-fidelity-scratch/zz-clean.dsurface.json", "--strict-surface=vibes"]);
210
+ expect(bad.status).toBe(2);
211
+ expect(bad.output).toContain("unknown fidelity class");
212
+ });
213
+ });
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Ordered surface diagnostics.
3
+ *
4
+ * The v1 engine emitted warnings by pushing them onto an array wherever it
5
+ * happened to be. That made the emitted order an ACCIDENT of method order and
6
+ * traversal — invisible while one implementation existed, and load-bearing the
7
+ * moment a second one appeared, because the byte gate hashes warnings.
8
+ *
9
+ * An engine driven by routes and collects resolves work in declaration order,
10
+ * which is NOT v1's method order. Left implicit, the rewrite would emit the
11
+ * same warnings in a different sequence and fail the gate for a reason that has
12
+ * nothing to do with correctness — and the temptation would be to "fix" it by
13
+ * re-baselining the hashes, which would silently discard the guarantee.
14
+ *
15
+ * So order becomes explicit data. Every diagnostic carries a sort key; the
16
+ * engine collects them in whatever order it likes and sorts once at the end.
17
+ * The key reproduces v1 exactly, and — because it is declared rather than
18
+ * emergent — keeps reproducing it under later refactors.
19
+ *
20
+ * The phases below are DERIVED from the v1 engine, not designed: each is the
21
+ * point in `emitNode` where that warning was pushed. They are numbered in that
22
+ * method's execution order, and the numbering is the compatibility contract.
23
+ */
24
+ import type { SurfaceFidelityEntry, Warning } from "../../types.js";
25
+
26
+ /**
27
+ * Legacy emission phases, in v1 `emitNode` execution order.
28
+ *
29
+ * Read alongside the pre-rewrite `emitNode`: id allocation happened first, then
30
+ * prop projection, then the two consuming strategies (each ending with its own
31
+ * composition warning), then text-child synthesis, then the synthesized action,
32
+ * then the child-list rewrite — and only after every child had emitted did the
33
+ * single-slot wrap run.
34
+ */
35
+ export enum Phase {
36
+ /** `allocateId` for this node — v1 allocated before any projection. */
37
+ IdAllocation = 0,
38
+ /** `applyPropMap`: dropped props and unprojectable values. */
39
+ PropMap = 1,
40
+ /** `applySubContent`'s audited label lift. */
41
+ LabelLift = 2,
42
+ /** `applySubContent`'s closing composition-flattened warning. */
43
+ SubContentFlatten = 3,
44
+ /** `applySubTable`'s per-cell flattening and per-sub drops. */
45
+ TableBody = 4,
46
+ /** `applySubTable`'s closing composition-flattened warning. */
47
+ TableFlatten = 5,
48
+ /** `emitTextPrimitive` invoked by the text-child route. */
49
+ TextChild = 6,
50
+ /** The synthesized declarative action. */
51
+ Action = 7,
52
+ /** `flattenSubs` rewriting the child list before children emit. */
53
+ ChildRewrite = 8,
54
+ /** `wrapInColumn` — runs AFTER every child has emitted. */
55
+ Wrap = 9,
56
+ }
57
+
58
+ /**
59
+ * Where a diagnostic sits relative to this node's children. v1's array order is
60
+ * a pre-order walk in which a parent's pre-child warnings precede all of its
61
+ * descendants' warnings, and its post-child warnings follow all of them — so a
62
+ * flat `(node, phase)` sort would wrongly hoist the wrap warning above the
63
+ * children it wraps.
64
+ */
65
+ export enum Band {
66
+ BeforeChildren = 0,
67
+ Children = 1,
68
+ AfterChildren = 2,
69
+ }
70
+
71
+ export interface Diagnostic {
72
+ warning: Warning;
73
+ /**
74
+ * Lexicographically ordered key. Shape, per tree level:
75
+ * [...ancestorPath, Band.Children, childIndex] repeated to reach the node,
76
+ * then [band, phase, rule, seq].
77
+ * Nesting bands this way is what makes a parent's post-child diagnostics sort
78
+ * after its whole subtree without any special case.
79
+ */
80
+ key: number[];
81
+ }
82
+
83
+ /** Compares two diagnostic keys lexicographically; shorter sorts first on a tie. */
84
+ export function compareKeys(a: number[], b: number[]): number {
85
+ const n = Math.min(a.length, b.length);
86
+ for (let i = 0; i < n; i++) {
87
+ if (a[i] !== b[i]) return a[i] - b[i];
88
+ }
89
+ return a.length - b.length;
90
+ }
91
+
92
+ /**
93
+ * Collects diagnostics with explicit ordering and returns them in legacy order.
94
+ *
95
+ * `seq` is a monotonic counter used only as the final tie-breaker, so two
96
+ * diagnostics identical in every declared dimension still order deterministically
97
+ * — by the order the engine produced them, which is itself deterministic.
98
+ */
99
+ export class Diagnostics {
100
+ private readonly items: Diagnostic[] = [];
101
+ private readonly fidelityItems: Array<{ entry: SurfaceFidelityEntry; key: number[] }> = [];
102
+ private seq = 0;
103
+
104
+ /**
105
+ * @param path the node's tree path (alternating Band.Children / child index)
106
+ * @param band where this sits relative to the node's children
107
+ * @param phase the legacy emission phase
108
+ * @param rule index of the desugared rule that produced it, for stable order
109
+ * among several routes writing in the same phase
110
+ */
111
+ push(warning: Warning, path: readonly number[], band: Band, phase: Phase, rule = 0): void {
112
+ this.items.push({ warning, key: [...path, band, phase, rule, this.seq++] });
113
+ }
114
+
115
+ /** Legacy-ordered warnings. Sorting once at the end is the whole point. */
116
+ ordered(): Warning[] {
117
+ return [...this.items].sort((a, b) => compareKeys(a.key, b.key)).map((d) => d.warning);
118
+ }
119
+
120
+ /**
121
+ * The fidelity ledger rides the same ordering discipline as the warnings —
122
+ * an entry's position is declared by (path, band, phase, rule), never by
123
+ * when the engine happened to record it.
124
+ */
125
+ pushFidelity(entry: SurfaceFidelityEntry, path: readonly number[], band: Band, phase: Phase, rule = 0): void {
126
+ this.fidelityItems.push({ entry, key: [...path, band, phase, rule, this.seq++] });
127
+ }
128
+
129
+ orderedFidelity(): SurfaceFidelityEntry[] {
130
+ return [...this.fidelityItems].sort((a, b) => compareKeys(a.key, b.key)).map((d) => d.entry);
131
+ }
132
+
133
+ get length(): number {
134
+ return this.items.length;
135
+ }
136
+ }